From 14bcc13150e184f1709206147d3976a290c00dee Mon Sep 17 00:00:00 2001 From: Morro Date: Fri, 28 Jun 2024 13:03:34 +0800 Subject: [PATCH] Initiate APM32F40X MCU Support in Betaflight (#13709) * Add APM32F4 driver libraries and USB middleware * Remove all duplicated APM32 driver files and retaining only the APM32 LIB directory --- .../Include/Legacy/apm32_dal_legacy.h | 101 + .../Include/apm32_assert.h | 73 + .../Include/apm32_assert_template.h | 72 + .../Include/apm32f4xx_dal.h | 272 + .../Include/apm32f4xx_dal_adc.h | 922 + .../Include/apm32f4xx_dal_adc_ex.h | 412 + .../Include/apm32f4xx_dal_can.h | 868 + .../Include/apm32f4xx_dal_cfg_template.h | 361 + .../Include/apm32f4xx_dal_comp.h | 442 + .../Include/apm32f4xx_dal_cortex.h | 431 + .../Include/apm32f4xx_dal_crc.h | 205 + .../Include/apm32f4xx_dal_cryp.h | 708 + .../Include/apm32f4xx_dal_cryp_ex.h | 166 + .../Include/apm32f4xx_dal_dac.h | 504 + .../Include/apm32f4xx_dal_dac_ex.h | 229 + .../Include/apm32f4xx_dal_dci.h | 583 + .../Include/apm32f4xx_dal_dci_ex.h | 149 + .../Include/apm32f4xx_dal_def.h | 234 + .../Include/apm32f4xx_dal_dma.h | 826 + .../Include/apm32f4xx_dal_dma_ex.h | 126 + .../Include/apm32f4xx_dal_eint.h | 390 + .../Include/apm32f4xx_dal_eth.h | 2175 +++ .../Include/apm32f4xx_dal_flash.h | 449 + .../Include/apm32f4xx_dal_flash_ex.h | 594 + .../Include/apm32f4xx_dal_flash_ramfunc.h | 98 + .../Include/apm32f4xx_dal_gpio.h | 349 + .../Include/apm32f4xx_dal_gpio_ex.h | 681 + .../Include/apm32f4xx_dal_hash.h | 657 + .../Include/apm32f4xx_dal_hash_ex.h | 199 + .../Include/apm32f4xx_dal_hcd.h | 341 + .../Include/apm32f4xx_dal_i2c.h | 765 + .../Include/apm32f4xx_dal_i2c_ex.h | 139 + .../Include/apm32f4xx_dal_i2s.h | 616 + .../Include/apm32f4xx_dal_i2s_ex.h | 207 + .../Include/apm32f4xx_dal_irda.h | 706 + .../Include/apm32f4xx_dal_iwdt.h | 244 + .../Include/apm32f4xx_dal_log.h | 163 + .../Include/apm32f4xx_dal_mmc.h | 771 + .../Include/apm32f4xx_dal_nand.h | 407 + .../Include/apm32f4xx_dal_nor.h | 352 + .../Include/apm32f4xx_dal_pccard.h | 307 + .../Include/apm32f4xx_dal_pcd.h | 484 + .../Include/apm32f4xx_dal_pcd_ex.h | 103 + .../Include/apm32f4xx_dal_pmu.h | 452 + .../Include/apm32f4xx_dal_pmu_ex.h | 257 + .../Include/apm32f4xx_dal_qspi.h | 755 + .../Include/apm32f4xx_dal_rcm.h | 1482 ++ .../Include/apm32f4xx_dal_rcm_ex.h | 1950 ++ .../Include/apm32f4xx_dal_rng.h | 385 + .../Include/apm32f4xx_dal_rtc.h | 939 + .../Include/apm32f4xx_dal_rtc_ex.h | 1106 ++ .../Include/apm32f4xx_dal_sd.h | 782 + .../Include/apm32f4xx_dal_sdram.h | 254 + .../Include/apm32f4xx_dal_smartcard.h | 779 + .../Include/apm32f4xx_dal_smbus.h | 755 + .../Include/apm32f4xx_dal_spi.h | 753 + .../Include/apm32f4xx_dal_sram.h | 258 + .../Include/apm32f4xx_dal_tmr.h | 2171 +++ .../Include/apm32f4xx_dal_tmr_ex.h | 378 + .../Include/apm32f4xx_dal_uart.h | 908 + .../Include/apm32f4xx_dal_usart.h | 672 + .../Include/apm32f4xx_dal_wwdt.h | 322 + .../Include/apm32f4xx_ddl_adc.h | 4575 +++++ .../Include/apm32f4xx_ddl_bus.h | 1433 ++ .../Include/apm32f4xx_ddl_comp.h | 598 + .../Include/apm32f4xx_ddl_cortex.h | 628 + .../Include/apm32f4xx_ddl_crc.h | 220 + .../Include/apm32f4xx_ddl_dac.h | 1410 ++ .../Include/apm32f4xx_ddl_dma.h | 2738 +++ .../Include/apm32f4xx_ddl_dmc.h | 610 + .../Include/apm32f4xx_ddl_eint.h | 963 + .../Include/apm32f4xx_ddl_gpio.h | 982 + .../Include/apm32f4xx_ddl_i2c.h | 1786 ++ .../Include/apm32f4xx_ddl_iwdt.h | 314 + .../Include/apm32f4xx_ddl_pmu.h | 924 + .../Include/apm32f4xx_ddl_rcm.h | 2900 +++ .../Include/apm32f4xx_ddl_rng.h | 345 + .../Include/apm32f4xx_ddl_rtc.h | 3390 ++++ .../Include/apm32f4xx_ddl_sdmmc.h | 1165 ++ .../Include/apm32f4xx_ddl_smc.h | 1110 ++ .../Include/apm32f4xx_ddl_spi.h | 1930 ++ .../Include/apm32f4xx_ddl_system.h | 931 + .../Include/apm32f4xx_ddl_tmr.h | 3790 ++++ .../Include/apm32f4xx_ddl_usart.h | 2370 +++ .../Include/apm32f4xx_ddl_usb.h | 631 + .../Include/apm32f4xx_ddl_utils.h | 331 + .../Include/apm32f4xx_ddl_wwdt.h | 328 + .../Include/apm32f4xx_device_cfg_template.h | 65 + .../APM32F4xx_DAL_Driver/LICENSE.txt | 29 + .../Source/apm32f4xx_dal.c | 608 + .../Source/apm32f4xx_dal_adc.c | 2135 ++ .../Source/apm32f4xx_dal_adc_ex.c | 1146 ++ .../Source/apm32f4xx_dal_can.c | 2487 +++ .../Source/apm32f4xx_dal_comp.c | 843 + .../Source/apm32f4xx_dal_cortex.c | 527 + .../Source/apm32f4xx_dal_crc.c | 353 + .../Source/apm32f4xx_dal_cryp.c | 7157 +++++++ .../Source/apm32f4xx_dal_cryp_ex.c | 705 + .../Source/apm32f4xx_dal_dac.c | 1366 ++ .../Source/apm32f4xx_dal_dac_ex.c | 520 + .../Source/apm32f4xx_dal_dci.c | 1182 ++ .../Source/apm32f4xx_dal_dci_ex.c | 191 + .../Source/apm32f4xx_dal_dma.c | 1330 ++ .../Source/apm32f4xx_dal_dma_ex.c | 338 + .../Source/apm32f4xx_dal_eint.c | 573 + .../Source/apm32f4xx_dal_eth.c | 3137 +++ .../Source/apm32f4xx_dal_flash.c | 800 + .../Source/apm32f4xx_dal_flash_ex.c | 893 + .../Source/apm32f4xx_dal_flash_ramfunc.c | 196 + .../Source/apm32f4xx_dal_gpio.c | 553 + .../Source/apm32f4xx_dal_hash.c | 3539 ++++ .../Source/apm32f4xx_dal_hash_ex.c | 1065 + .../Source/apm32f4xx_dal_hcd.c | 1830 ++ .../Source/apm32f4xx_dal_i2c.c | 7549 ++++++++ .../Source/apm32f4xx_dal_i2c_ex.c | 207 + .../Source/apm32f4xx_dal_i2s.c | 2119 ++ .../Source/apm32f4xx_dal_i2s_ex.c | 1160 ++ .../Source/apm32f4xx_dal_irda.c | 2712 +++ .../Source/apm32f4xx_dal_iwdt.c | 287 + .../Source/apm32f4xx_dal_log.c | 97 + .../Source/apm32f4xx_dal_mmc.c | 3226 ++++ .../Source/apm32f4xx_dal_nand.c | 2289 +++ .../Source/apm32f4xx_dal_nor.c | 1568 ++ .../Source/apm32f4xx_dal_pccard.c | 971 + .../Source/apm32f4xx_dal_pcd.c | 2402 +++ .../Source/apm32f4xx_dal_pcd_ex.c | 196 + .../Source/apm32f4xx_dal_pmu.c | 591 + .../Source/apm32f4xx_dal_pmu_ex.c | 403 + .../Source/apm32f4xx_dal_qspi.c | 2557 +++ .../Source/apm32f4xx_dal_rcm.c | 1137 ++ .../Source/apm32f4xx_dal_rcm_ex.c | 685 + .../Source/apm32f4xx_dal_rng.c | 892 + .../Source/apm32f4xx_dal_rtc.c | 1921 ++ .../Source/apm32f4xx_dal_rtc_ex.c | 1891 ++ .../Source/apm32f4xx_dal_sd.c | 3302 ++++ .../Source/apm32f4xx_dal_sdram.c | 1169 ++ .../Source/apm32f4xx_dal_smartcard.c | 2385 +++ .../Source/apm32f4xx_dal_smbus.c | 2809 +++ .../Source/apm32f4xx_dal_spi.c | 3940 ++++ .../Source/apm32f4xx_dal_sram.c | 1135 ++ ...pm32f4xx_dal_timebase_rtc_alarm_template.c | 343 + ...m32f4xx_dal_timebase_rtc_wakeup_template.c | 318 + .../apm32f4xx_dal_timebase_tmr_template.c | 202 + .../Source/apm32f4xx_dal_tmr.c | 7645 ++++++++ .../Source/apm32f4xx_dal_tmr_ex.c | 2453 +++ .../Source/apm32f4xx_dal_uart.c | 3772 ++++ .../Source/apm32f4xx_dal_usart.c | 2859 +++ .../Source/apm32f4xx_dal_wwdt.c | 445 + .../Source/apm32f4xx_ddl_adc.c | 952 + .../Source/apm32f4xx_ddl_comp.c | 264 + .../Source/apm32f4xx_ddl_crc.c | 128 + .../Source/apm32f4xx_ddl_dac.c | 305 + .../Source/apm32f4xx_ddl_dma.c | 448 + .../Source/apm32f4xx_ddl_dmc.c | 419 + .../Source/apm32f4xx_ddl_eint.c | 238 + .../Source/apm32f4xx_ddl_gpio.c | 328 + .../Source/apm32f4xx_ddl_i2c.c | 276 + .../Source/apm32f4xx_ddl_pmu.c | 106 + .../Source/apm32f4xx_ddl_rcm.c | 671 + .../Source/apm32f4xx_ddl_rng.c | 136 + .../Source/apm32f4xx_ddl_rtc.c | 863 + .../Source/apm32f4xx_ddl_sdmmc.c | 1603 ++ .../Source/apm32f4xx_ddl_smc.c | 1087 ++ .../Source/apm32f4xx_ddl_spi.c | 649 + .../Source/apm32f4xx_ddl_tmr.c | 1214 ++ .../Source/apm32f4xx_ddl_usart.c | 525 + .../Source/apm32f4xx_ddl_usb.c | 2304 +++ .../Source/apm32f4xx_ddl_utils.c | 766 + .../Source/apm32f4xx_device_cfg_template.c | 188 + .../Geehy/APM32F4xx/Include/apm32f405xx.h | 14362 ++++++++++++++ .../Geehy/APM32F4xx/Include/apm32f407xx.h | 15797 +++++++++++++++ .../Geehy/APM32F4xx/Include/apm32f411xx.h | 14229 ++++++++++++++ .../Geehy/APM32F4xx/Include/apm32f417xx.h | 16078 ++++++++++++++++ .../Geehy/APM32F4xx/Include/apm32f465xx.h | 14248 ++++++++++++++ .../Geehy/APM32F4xx/Include/apm32f4xx.h | 245 + .../Device/Geehy/APM32F4xx/LICENSE.txt | 6 + .../Source/arm/startup_apm32f405xx.s | 421 + .../Source/arm/startup_apm32f407xx.s | 427 + .../Source/arm/startup_apm32f411xx.s | 410 + .../Source/arm/startup_apm32f417xx.s | 428 + .../Source/arm/startup_apm32f465xx.s | 421 + .../APM32F4xx/Source/gcc/apm32f405xe_flash.ld | 183 + .../APM32F4xx/Source/gcc/apm32f405xg_flash.ld | 183 + .../APM32F4xx/Source/gcc/apm32f407xe_flash.ld | 183 + .../APM32F4xx/Source/gcc/apm32f407xg_flash.ld | 183 + .../APM32F4xx/Source/gcc/apm32f411xc_flash.ld | 164 + .../APM32F4xx/Source/gcc/apm32f411xe_flash.ld | 164 + .../APM32F4xx/Source/gcc/apm32f417xe_flash.ld | 183 + .../APM32F4xx/Source/gcc/apm32f417xg_flash.ld | 183 + .../APM32F4xx/Source/gcc/apm32f465xe_flash.ld | 183 + .../Source/gcc/startup_apm32f405xx.S | 485 + .../Source/gcc/startup_apm32f407xx.S | 494 + .../Source/gcc/startup_apm32f411xx.S | 468 + .../Source/gcc/startup_apm32f417xx.S | 497 + .../Source/gcc/startup_apm32f465xx.S | 485 + .../APM32F4xx/Source/iar/apm32f405xG.icf | 172 + .../APM32F4xx/Source/iar/apm32f407xE.icf | 172 + .../APM32F4xx/Source/iar/apm32f407xG.icf | 172 + .../APM32F4xx/Source/iar/apm32f411xC.icf | 172 + .../APM32F4xx/Source/iar/apm32f411xE.icf | 172 + .../APM32F4xx/Source/iar/apm32f417xE.icf | 172 + .../APM32F4xx/Source/iar/apm32f417xG.icf | 172 + .../APM32F4xx/Source/iar/apm32f465xE.icf | 172 + .../Source/iar/startup_apm32f405xx.s | 608 + .../Source/iar/startup_apm32f407xx.s | 623 + .../Source/iar/startup_apm32f411xx.s | 579 + .../Source/iar/startup_apm32f417xx.s | 628 + .../Source/iar/startup_apm32f465xx.s | 608 + .../Geehy/APM32F4xx/Source/system_apm32f4xx.c | 229 + .../Device/Class/CDC/Inc/usbd_cdc.h | 173 + .../Device/Class/CDC/Src/usbd_cdc.c | 663 + .../Class/Composite/usbd_composite_template.c | 228 + .../Class/Composite/usbd_composite_template.h | 70 + .../Class/CustomHID/Inc/usbd_customhid.h | 374 + .../Class/CustomHID/Src/usbd_customhid.c | 644 + .../Device/Class/HID/Inc/usbd_hid.h | 350 + .../Device/Class/HID/Src/usbd_hid.c | 523 + .../Device/Class/HID/Src/usbd_hid_keyboard.c | 515 + .../Device/Class/MSC/Inc/usbd_msc.h | 122 + .../Device/Class/MSC/Inc/usbd_msc_bot.h | 218 + .../Device/Class/MSC/Inc/usbd_msc_scsi.h | 190 + .../Device/Class/MSC/Src/usbd_msc.c | 457 + .../Device/Class/MSC/Src/usbd_msc_bot.c | 367 + .../Device/Class/MSC/Src/usbd_msc_scsi.c | 1455 ++ .../Device/Class/WINUSB/Inc/usbd_winusb.h | 146 + .../Device/Class/WINUSB/Src/usbd_winusb.c | 769 + .../Device/Core/Inc/usbd_config.h | 389 + .../Device/Core/Inc/usbd_core.h | 109 + .../Device/Core/Inc/usbd_dataXfer.h | 57 + .../Device/Core/Inc/usbd_stdReq.h | 59 + .../Device/Core/Src/usbd_core.c | 1168 ++ .../Device/Core/Src/usbd_dataXfer.c | 173 + .../Device/Core/Src/usbd_stdReq.c | 697 + .../Host/Class/CDC/Inc/usbh_cdc.h | 200 + .../Host/Class/CDC/Src/usbh_cdc.c | 1108 ++ .../Host/Class/HID/Inc/usbh_hid.h | 180 + .../Host/Class/HID/Inc/usbh_hid_keyboard.h | 342 + .../Host/Class/HID/Inc/usbh_hid_mouse.h | 92 + .../Host/Class/HID/Src/usbh_hid.c | 952 + .../Host/Class/HID/Src/usbh_hid_keyboard.c | 192 + .../Host/Class/HID/Src/usbh_hid_mouse.c | 154 + .../Host/Class/MSC/Inc/usbh_msc.h | 167 + .../Host/Class/MSC/Inc/usbh_msc_bot.h | 203 + .../Host/Class/MSC/Inc/usbh_msc_scsi.h | 191 + .../Host/Class/MSC/Src/usbh_msc.c | 1023 + .../Host/Class/MSC/Src/usbh_msc_bot.c | 672 + .../Host/Class/MSC/Src/usbh_msc_scsi.c | 395 + .../Host/Core/Inc/usbh_channel.h | 53 + .../Host/Core/Inc/usbh_config.h | 491 + .../Host/Core/Inc/usbh_core.h | 104 + .../Host/Core/Inc/usbh_dataXfer.h | 76 + .../Host/Core/Inc/usbh_enum.h | 51 + .../Host/Core/Inc/usbh_stdReq.h | 96 + .../Host/Core/Src/usbh_channel.c | 123 + .../Host/Core/Src/usbh_core.c | 1048 + .../Host/Core/Src/usbh_dataXfer.c | 808 + .../Host/Core/Src/usbh_enum.c | 495 + .../Host/Core/Src/usbh_stdReq.c | 723 + 258 files changed, 290932 insertions(+) create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/Legacy/apm32_dal_legacy.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32_assert.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32_assert_template.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_adc.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_adc_ex.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_can.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_cfg_template.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_comp.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_cortex.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_crc.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_cryp.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_cryp_ex.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_dac.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_dac_ex.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_dci.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_dci_ex.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_def.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_dma.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_dma_ex.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_eint.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_eth.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_flash.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_flash_ex.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_flash_ramfunc.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_gpio.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_gpio_ex.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_hash.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_hash_ex.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_hcd.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_i2c.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_i2c_ex.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_i2s.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_i2s_ex.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_irda.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_iwdt.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_log.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_mmc.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_nand.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_nor.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_pccard.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_pcd.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_pcd_ex.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_pmu.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_pmu_ex.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_qspi.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_rcm.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_rcm_ex.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_rng.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_rtc.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_rtc_ex.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_sd.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_sdram.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_smartcard.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_smbus.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_spi.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_sram.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_tmr.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_tmr_ex.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_uart.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_usart.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_wwdt.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_adc.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_bus.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_comp.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_cortex.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_crc.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_dac.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_dma.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_dmc.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_eint.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_gpio.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_i2c.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_iwdt.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_pmu.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_rcm.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_rng.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_rtc.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_sdmmc.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_smc.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_spi.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_system.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_tmr.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_usart.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_usb.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_utils.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_wwdt.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_device_cfg_template.h create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/LICENSE.txt create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal.c create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_adc.c create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_adc_ex.c create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_can.c create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_comp.c create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_cortex.c create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_crc.c create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_cryp.c create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_cryp_ex.c create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_dac.c create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_dac_ex.c create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_dci.c create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_dci_ex.c create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_dma.c create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_dma_ex.c create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_eint.c create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_eth.c create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_flash.c create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_flash_ex.c create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_flash_ramfunc.c create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_gpio.c create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_hash.c create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_hash_ex.c create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_hcd.c create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_i2c.c create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_i2c_ex.c create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_i2s.c create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_i2s_ex.c create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_irda.c create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_iwdt.c create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_log.c create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_mmc.c create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_nand.c create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_nor.c create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_pccard.c create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_pcd.c create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_pcd_ex.c create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_pmu.c create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_pmu_ex.c create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_qspi.c create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_rcm.c create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_rcm_ex.c create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_rng.c create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_rtc.c create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_rtc_ex.c create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_sd.c create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_sdram.c create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_smartcard.c create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_smbus.c create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_spi.c create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_sram.c create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_timebase_rtc_alarm_template.c create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_timebase_rtc_wakeup_template.c create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_timebase_tmr_template.c create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_tmr.c create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_tmr_ex.c create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_uart.c create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_usart.c create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_wwdt.c create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_ddl_adc.c create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_ddl_comp.c create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_ddl_crc.c create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_ddl_dac.c create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_ddl_dma.c create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_ddl_dmc.c create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_ddl_eint.c create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_ddl_gpio.c create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_ddl_i2c.c create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_ddl_pmu.c create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_ddl_rcm.c create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_ddl_rng.c create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_ddl_rtc.c create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_ddl_sdmmc.c create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_ddl_smc.c create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_ddl_spi.c create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_ddl_tmr.c create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_ddl_usart.c create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_ddl_usb.c create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_ddl_utils.c create mode 100644 lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_device_cfg_template.c create mode 100644 lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Include/apm32f405xx.h create mode 100644 lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Include/apm32f407xx.h create mode 100644 lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Include/apm32f411xx.h create mode 100644 lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Include/apm32f417xx.h create mode 100644 lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Include/apm32f465xx.h create mode 100644 lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Include/apm32f4xx.h create mode 100644 lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/LICENSE.txt create mode 100644 lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/arm/startup_apm32f405xx.s create mode 100644 lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/arm/startup_apm32f407xx.s create mode 100644 lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/arm/startup_apm32f411xx.s create mode 100644 lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/arm/startup_apm32f417xx.s create mode 100644 lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/arm/startup_apm32f465xx.s create mode 100644 lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/gcc/apm32f405xe_flash.ld create mode 100644 lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/gcc/apm32f405xg_flash.ld create mode 100644 lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/gcc/apm32f407xe_flash.ld create mode 100644 lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/gcc/apm32f407xg_flash.ld create mode 100644 lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/gcc/apm32f411xc_flash.ld create mode 100644 lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/gcc/apm32f411xe_flash.ld create mode 100644 lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/gcc/apm32f417xe_flash.ld create mode 100644 lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/gcc/apm32f417xg_flash.ld create mode 100644 lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/gcc/apm32f465xe_flash.ld create mode 100644 lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/gcc/startup_apm32f405xx.S create mode 100644 lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/gcc/startup_apm32f407xx.S create mode 100644 lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/gcc/startup_apm32f411xx.S create mode 100644 lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/gcc/startup_apm32f417xx.S create mode 100644 lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/gcc/startup_apm32f465xx.S create mode 100644 lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/iar/apm32f405xG.icf create mode 100644 lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/iar/apm32f407xE.icf create mode 100644 lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/iar/apm32f407xG.icf create mode 100644 lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/iar/apm32f411xC.icf create mode 100644 lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/iar/apm32f411xE.icf create mode 100644 lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/iar/apm32f417xE.icf create mode 100644 lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/iar/apm32f417xG.icf create mode 100644 lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/iar/apm32f465xE.icf create mode 100644 lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/iar/startup_apm32f405xx.s create mode 100644 lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/iar/startup_apm32f407xx.s create mode 100644 lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/iar/startup_apm32f411xx.s create mode 100644 lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/iar/startup_apm32f417xx.s create mode 100644 lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/iar/startup_apm32f465xx.s create mode 100644 lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/system_apm32f4xx.c create mode 100644 lib/main/APM32F4/Middlewares/APM32_USB_Library/Device/Class/CDC/Inc/usbd_cdc.h create mode 100644 lib/main/APM32F4/Middlewares/APM32_USB_Library/Device/Class/CDC/Src/usbd_cdc.c create mode 100644 lib/main/APM32F4/Middlewares/APM32_USB_Library/Device/Class/Composite/usbd_composite_template.c create mode 100644 lib/main/APM32F4/Middlewares/APM32_USB_Library/Device/Class/Composite/usbd_composite_template.h create mode 100644 lib/main/APM32F4/Middlewares/APM32_USB_Library/Device/Class/CustomHID/Inc/usbd_customhid.h create mode 100644 lib/main/APM32F4/Middlewares/APM32_USB_Library/Device/Class/CustomHID/Src/usbd_customhid.c create mode 100644 lib/main/APM32F4/Middlewares/APM32_USB_Library/Device/Class/HID/Inc/usbd_hid.h create mode 100644 lib/main/APM32F4/Middlewares/APM32_USB_Library/Device/Class/HID/Src/usbd_hid.c create mode 100644 lib/main/APM32F4/Middlewares/APM32_USB_Library/Device/Class/HID/Src/usbd_hid_keyboard.c create mode 100644 lib/main/APM32F4/Middlewares/APM32_USB_Library/Device/Class/MSC/Inc/usbd_msc.h create mode 100644 lib/main/APM32F4/Middlewares/APM32_USB_Library/Device/Class/MSC/Inc/usbd_msc_bot.h create mode 100644 lib/main/APM32F4/Middlewares/APM32_USB_Library/Device/Class/MSC/Inc/usbd_msc_scsi.h create mode 100644 lib/main/APM32F4/Middlewares/APM32_USB_Library/Device/Class/MSC/Src/usbd_msc.c create mode 100644 lib/main/APM32F4/Middlewares/APM32_USB_Library/Device/Class/MSC/Src/usbd_msc_bot.c create mode 100644 lib/main/APM32F4/Middlewares/APM32_USB_Library/Device/Class/MSC/Src/usbd_msc_scsi.c create mode 100644 lib/main/APM32F4/Middlewares/APM32_USB_Library/Device/Class/WINUSB/Inc/usbd_winusb.h create mode 100644 lib/main/APM32F4/Middlewares/APM32_USB_Library/Device/Class/WINUSB/Src/usbd_winusb.c create mode 100644 lib/main/APM32F4/Middlewares/APM32_USB_Library/Device/Core/Inc/usbd_config.h create mode 100644 lib/main/APM32F4/Middlewares/APM32_USB_Library/Device/Core/Inc/usbd_core.h create mode 100644 lib/main/APM32F4/Middlewares/APM32_USB_Library/Device/Core/Inc/usbd_dataXfer.h create mode 100644 lib/main/APM32F4/Middlewares/APM32_USB_Library/Device/Core/Inc/usbd_stdReq.h create mode 100644 lib/main/APM32F4/Middlewares/APM32_USB_Library/Device/Core/Src/usbd_core.c create mode 100644 lib/main/APM32F4/Middlewares/APM32_USB_Library/Device/Core/Src/usbd_dataXfer.c create mode 100644 lib/main/APM32F4/Middlewares/APM32_USB_Library/Device/Core/Src/usbd_stdReq.c create mode 100644 lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Class/CDC/Inc/usbh_cdc.h create mode 100644 lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Class/CDC/Src/usbh_cdc.c create mode 100644 lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Class/HID/Inc/usbh_hid.h create mode 100644 lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Class/HID/Inc/usbh_hid_keyboard.h create mode 100644 lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Class/HID/Inc/usbh_hid_mouse.h create mode 100644 lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Class/HID/Src/usbh_hid.c create mode 100644 lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Class/HID/Src/usbh_hid_keyboard.c create mode 100644 lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Class/HID/Src/usbh_hid_mouse.c create mode 100644 lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Class/MSC/Inc/usbh_msc.h create mode 100644 lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Class/MSC/Inc/usbh_msc_bot.h create mode 100644 lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Class/MSC/Inc/usbh_msc_scsi.h create mode 100644 lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Class/MSC/Src/usbh_msc.c create mode 100644 lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Class/MSC/Src/usbh_msc_bot.c create mode 100644 lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Class/MSC/Src/usbh_msc_scsi.c create mode 100644 lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Core/Inc/usbh_channel.h create mode 100644 lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Core/Inc/usbh_config.h create mode 100644 lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Core/Inc/usbh_core.h create mode 100644 lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Core/Inc/usbh_dataXfer.h create mode 100644 lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Core/Inc/usbh_enum.h create mode 100644 lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Core/Inc/usbh_stdReq.h create mode 100644 lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Core/Src/usbh_channel.c create mode 100644 lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Core/Src/usbh_core.c create mode 100644 lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Core/Src/usbh_dataXfer.c create mode 100644 lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Core/Src/usbh_enum.c create mode 100644 lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Core/Src/usbh_stdReq.c diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/Legacy/apm32_dal_legacy.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/Legacy/apm32_dal_legacy.h new file mode 100644 index 0000000000..3270ce3c66 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/Legacy/apm32_dal_legacy.h @@ -0,0 +1,101 @@ +/** + * + * @file apm32_dal_legacy.h + * @brief This file contains aliases definition for the DAL constants + * macros and functions maintained for legacy purpose. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2021 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef APM32_DAL_LEGACY +#define APM32_DAL_LEGACY + +#ifdef __cplusplus +extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +/* Exported types ------------------------------------------------------------*/ +/* Exported constants --------------------------------------------------------*/ + +/** @defgroup DAL_CORTEX_Aliased_Defines DAL CORTEX Aliased Defines maintained for legacy purpose + * @{ + */ +#define __DAL_CORTEX_SYSTICKCLK_CONFIG DAL_SYSTICK_CLKSourceConfig + +/** + * @} + */ + +/** @defgroup DAL_GPIO_Aliased_Macros DAL GPIO Aliased Macros maintained for legacy purpose + * @{ + */ + +#if defined(APM32F4) +#define GPIO_SPEED_LOW GPIO_SPEED_FREQ_LOW +#define GPIO_SPEED_MEDIUM GPIO_SPEED_FREQ_MEDIUM +#define GPIO_SPEED_FAST GPIO_SPEED_FREQ_HIGH +#define GPIO_SPEED_HIGH GPIO_SPEED_FREQ_VERY_HIGH +#endif /* APM32F4 */ + +/** + * @} + */ + +/** @defgroup DAL_SD_Aliased_Macros DAL SD/MMC Aliased Macros maintained for legacy purpose + * @{ + */ +#define SDMMC_STATIC_FLAGS SDIO_STATIC_FLAGS + + /** + * @} + */ + +/** @defgroup DAL_PPP_Aliased_Macros DAL PPP Aliased Macros maintained for legacy purpose + * @{ + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* APM32_DAL_LEGACY */ diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32_assert.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32_assert.h new file mode 100644 index 0000000000..9988085ede --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32_assert.h @@ -0,0 +1,73 @@ +/** + * @file apm32_assert.h + * @brief APM32 assert template file. + * This file should be copied to the application folder and renamed + * to apm32_assert.h. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2017 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef APM32_ASSERT_H +#define APM32_ASSERT_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Exported types ------------------------------------------------------------*/ +/* Exported constants --------------------------------------------------------*/ +/* Includes ------------------------------------------------------------------*/ +/* Exported macro ------------------------------------------------------------*/ +#ifdef USE_FULL_ASSERT + + #define ASSERT_PARAM(_PARAM_) ((_PARAM_) ? (void)0U : AssertFailedHandler((uint8_t *)__FILE__, __LINE__)) + /* Declaration */ + void AssertFailedHandler(uint8_t *file, uint32_t line); + +#else + #define ASSERT_PARAM(_PARAM_) ((void)0U) +#endif /* USE_FULL_ASSERT */ + +#ifdef __cplusplus +} +#endif + +#endif /* APM32_ASSERT_H */ + + + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32_assert_template.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32_assert_template.h new file mode 100644 index 0000000000..037e8f545b --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32_assert_template.h @@ -0,0 +1,72 @@ +/** + * @file apm32_assert.h + * @brief APM32 assert template file. + * This file should be copied to the application folder and renamed + * to apm32_assert.h. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2017 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef APM32_ASSERT_H +#define APM32_ASSERT_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Exported types ------------------------------------------------------------*/ +/* Exported constants --------------------------------------------------------*/ +/* Includes ------------------------------------------------------------------*/ +/* Exported macro ------------------------------------------------------------*/ +#if (USE_FULL_ASSERT == 1U) + + #define ASSERT_PARAM(_PARAM_) ((_PARAM_) ? (void)(_PARAM_) : AssertFailedHandler((uint8_t *)__FILE__, __LINE__)) + /* Declaration */ + void AssertFailedHandler(uint8_t *file, uint32_t line); +#else + #define ASSERT_PARAM(_PARAM_) ((void)(_PARAM_)) +#endif /* USE_FULL_ASSERT */ + +#ifdef __cplusplus +} +#endif + +#endif /* APM32_ASSERT_H */ + + + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal.h new file mode 100644 index 0000000000..9d73949545 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal.h @@ -0,0 +1,272 @@ +/** + * + * @file apm32f4xx_dal.h + * @brief This file contains all the functions prototypes for the DAL + * module driver. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2017 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef APM32F4xx_DAL_H +#define APM32F4xx_DAL_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal_cfg.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @addtogroup DAL + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ +/* Exported constants --------------------------------------------------------*/ + +/** @defgroup DAL_Exported_Constants DAL Exported Constants + * @{ + */ + +/** @defgroup DAL_TICK_FREQ Tick Frequency + * @{ + */ +typedef enum +{ + DAL_TICK_FREQ_10HZ = 100U, + DAL_TICK_FREQ_100HZ = 10U, + DAL_TICK_FREQ_1KHZ = 1U, + DAL_TICK_FREQ_DEFAULT = DAL_TICK_FREQ_1KHZ +} DAL_TickFreqTypeDef; +/** + * @} + */ + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ +/** @defgroup DAL_Exported_Macros DAL Exported Macros + * @{ + */ + +/** @brief Freeze/Unfreeze Peripherals in Debug mode + */ +#define __DAL_DBGMCU_FREEZE_TMR2() (DBGMCU->APB1F |= (DBGMCU_APB1F_TMR2_STS)) +#define __DAL_DBGMCU_FREEZE_TMR3() (DBGMCU->APB1F |= (DBGMCU_APB1F_TMR3_STS)) +#define __DAL_DBGMCU_FREEZE_TMR4() (DBGMCU->APB1F |= (DBGMCU_APB1F_TMR4_STS)) +#define __DAL_DBGMCU_FREEZE_TMR5() (DBGMCU->APB1F |= (DBGMCU_APB1F_TMR5_STS)) +#define __DAL_DBGMCU_FREEZE_TMR6() (DBGMCU->APB1F |= (DBGMCU_APB1F_TMR6_STS)) +#define __DAL_DBGMCU_FREEZE_TMR7() (DBGMCU->APB1F |= (DBGMCU_APB1F_TMR7_STS)) +#define __DAL_DBGMCU_FREEZE_TMR12() (DBGMCU->APB1F |= (DBGMCU_APB1F_TMR12_STS)) +#define __DAL_DBGMCU_FREEZE_TMR13() (DBGMCU->APB1F |= (DBGMCU_APB1F_TMR13_STS)) +#define __DAL_DBGMCU_FREEZE_TMR14() (DBGMCU->APB1F |= (DBGMCU_APB1F_TMR14_STS)) +#define __DAL_DBGMCU_FREEZE_RTC() (DBGMCU->APB1F |= (DBGMCU_APB1F_RTC_STS)) +#define __DAL_DBGMCU_FREEZE_WWDT() (DBGMCU->APB1F |= (DBGMCU_APB1F_WWDT_STS)) +#define __DAL_DBGMCU_FREEZE_IWDT() (DBGMCU->APB1F |= (DBGMCU_APB1F_IWDT_STS)) +#define __DAL_DBGMCU_FREEZE_I2C1_TIMEOUT() (DBGMCU->APB1F |= (DBGMCU_APB1F_I2C1_SMBUS_TIMEOUT_STS)) +#define __DAL_DBGMCU_FREEZE_I2C2_TIMEOUT() (DBGMCU->APB1F |= (DBGMCU_APB1F_I2C2_SMBUS_TIMEOUT_STS)) +#define __DAL_DBGMCU_FREEZE_I2C3_TIMEOUT() (DBGMCU->APB1F |= (DBGMCU_APB1F_I2C3_SMBUS_TIMEOUT_STS)) +#define __DAL_DBGMCU_FREEZE_CAN1() (DBGMCU->APB1F |= (DBGMCU_APB1F_CAN1_STS)) +#define __DAL_DBGMCU_FREEZE_CAN2() (DBGMCU->APB1F |= (DBGMCU_APB1F_CAN2_STS)) +#define __DAL_DBGMCU_FREEZE_TMR1() (DBGMCU->APB2F |= (DBGMCU_APB2F_TMR1_STS)) +#define __DAL_DBGMCU_FREEZE_TMR8() (DBGMCU->APB2F |= (DBGMCU_APB2F_TMR8_STS)) +#define __DAL_DBGMCU_FREEZE_TMR9() (DBGMCU->APB2F |= (DBGMCU_APB2F_TMR9_STS)) +#define __DAL_DBGMCU_FREEZE_TMR10() (DBGMCU->APB2F |= (DBGMCU_APB2F_TMR10_STS)) +#define __DAL_DBGMCU_FREEZE_TMR11() (DBGMCU->APB2F |= (DBGMCU_APB2F_TMR11_STS)) + +#define __DAL_DBGMCU_UNFREEZE_TMR2() (DBGMCU->APB1F &= ~(DBGMCU_APB1F_TMR2_STS)) +#define __DAL_DBGMCU_UNFREEZE_TMR3() (DBGMCU->APB1F &= ~(DBGMCU_APB1F_TMR3_STS)) +#define __DAL_DBGMCU_UNFREEZE_TMR4() (DBGMCU->APB1F &= ~(DBGMCU_APB1F_TMR4_STS)) +#define __DAL_DBGMCU_UNFREEZE_TMR5() (DBGMCU->APB1F &= ~(DBGMCU_APB1F_TMR5_STS)) +#define __DAL_DBGMCU_UNFREEZE_TMR6() (DBGMCU->APB1F &= ~(DBGMCU_APB1F_TMR6_STS)) +#define __DAL_DBGMCU_UNFREEZE_TMR7() (DBGMCU->APB1F &= ~(DBGMCU_APB1F_TMR7_STS)) +#define __DAL_DBGMCU_UNFREEZE_TMR12() (DBGMCU->APB1F &= ~(DBGMCU_APB1F_TMR12_STS)) +#define __DAL_DBGMCU_UNFREEZE_TMR13() (DBGMCU->APB1F &= ~(DBGMCU_APB1F_TMR13_STS)) +#define __DAL_DBGMCU_UNFREEZE_TMR14() (DBGMCU->APB1F &= ~(DBGMCU_APB1F_TMR14_STS)) +#define __DAL_DBGMCU_UNFREEZE_RTC() (DBGMCU->APB1F &= ~(DBGMCU_APB1F_RTC_STS)) +#define __DAL_DBGMCU_UNFREEZE_WWDT() (DBGMCU->APB1F &= ~(DBGMCU_APB1F_WWDT_STS)) +#define __DAL_DBGMCU_UNFREEZE_IWDT() (DBGMCU->APB1F &= ~(DBGMCU_APB1F_IWDT_STS)) +#define __DAL_DBGMCU_UNFREEZE_I2C1_TIMEOUT() (DBGMCU->APB1F &= ~(DBGMCU_APB1F_I2C1_SMBUS_TIMEOUT_STS)) +#define __DAL_DBGMCU_UNFREEZE_I2C2_TIMEOUT() (DBGMCU->APB1F &= ~(DBGMCU_APB1F_I2C2_SMBUS_TIMEOUT_STS)) +#define __DAL_DBGMCU_UNFREEZE_I2C3_TIMEOUT() (DBGMCU->APB1F &= ~(DBGMCU_APB1F_I2C3_SMBUS_TIMEOUT_STS)) +#define __DAL_DBGMCU_UNFREEZE_CAN1() (DBGMCU->APB1F &= ~(DBGMCU_APB1F_CAN1_STS)) +#define __DAL_DBGMCU_UNFREEZE_CAN2() (DBGMCU->APB1F &= ~(DBGMCU_APB1F_CAN2_STS)) +#define __DAL_DBGMCU_UNFREEZE_TMR1() (DBGMCU->APB2F &= ~(DBGMCU_APB2F_TMR1_STS)) +#define __DAL_DBGMCU_UNFREEZE_TMR8() (DBGMCU->APB2F &= ~(DBGMCU_APB2F_TMR8_STS)) +#define __DAL_DBGMCU_UNFREEZE_TMR9() (DBGMCU->APB2F &= ~(DBGMCU_APB2F_TMR9_STS)) +#define __DAL_DBGMCU_UNFREEZE_TMR10() (DBGMCU->APB2F &= ~(DBGMCU_APB2F_TMR10_STS)) +#define __DAL_DBGMCU_UNFREEZE_TMR11() (DBGMCU->APB2F &= ~(DBGMCU_APB2F_TMR11_STS)) + +/** @brief Main Flash memory mapped at 0x00000000 + */ +#define __DAL_SYSCFG_REMAPMEMORY_FLASH() (SYSCFG->MMSEL &= ~(SYSCFG_MMSEL_MMSEL)) + +/** @brief System Flash memory mapped at 0x00000000 + */ +#define __DAL_SYSCFG_REMAPMEMORY_SYSTEMFLASH() do {SYSCFG->MMSEL &= ~(SYSCFG_MMSEL_MMSEL);\ + SYSCFG->MMSEL |= SYSCFG_MMSEL_MMSEL_0;\ + }while(0); + +/** @brief Embedded SRAM mapped at 0x00000000 + */ +#define __DAL_SYSCFG_REMAPMEMORY_SRAM() do {SYSCFG->MMSEL &= ~(SYSCFG_MMSEL_MMSEL);\ + SYSCFG->MMSEL |= (SYSCFG_MMSEL_MMSEL_0 | SYSCFG_MMSEL_MMSEL_1);\ + }while(0); + +#if defined(APM32F405xx) || defined(APM32F407xx) || defined(APM32F417xx) || defined(APM32F465xx) || defined(APM32F411xx) +/** @brief SMC Bank1 (NOR/PSRAM 1 and 2) mapped at 0x00000000 + */ +#define __DAL_SYSCFG_REMAPMEMORY_SMC() do {SYSCFG->MMSEL &= ~(SYSCFG_MMSEL_MMSEL);\ + SYSCFG->MMSEL |= (SYSCFG_MMSEL_MMSEL_1);\ + }while(0); +#endif /* APM32F405xx || APM32F407xx || APM32F417xx || APM32F465xx || APM32F411xx */ + +/** + * @} + */ + +/** @defgroup DAL_Private_Macros DAL Private Macros + * @{ + */ +#define IS_TICKFREQ(FREQ) (((FREQ) == DAL_TICK_FREQ_10HZ) || \ + ((FREQ) == DAL_TICK_FREQ_100HZ) || \ + ((FREQ) == DAL_TICK_FREQ_1KHZ)) +/** + * @} + */ + +/* Exported variables --------------------------------------------------------*/ + +/** @addtogroup DAL_Exported_Variables + * @{ + */ +extern __IO uint32_t uwTick; +extern uint32_t uwTickPrio; +extern DAL_TickFreqTypeDef uwTickFreq; +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup DAL_Exported_Functions + * @{ + */ +/** @addtogroup DAL_Exported_Functions_Group1 + * @{ + */ +/* Initialization and Configuration functions ******************************/ +DAL_StatusTypeDef DAL_Init(void); +DAL_StatusTypeDef DAL_DeInit(void); +void DAL_MspInit(void); +void DAL_MspDeInit(void); +DAL_StatusTypeDef DAL_InitTick (uint32_t TickPriority); +/** + * @} + */ + +/** @addtogroup DAL_Exported_Functions_Group2 + * @{ + */ +/* Peripheral Control functions ************************************************/ +void DAL_IncTick(void); +void DAL_Delay(uint32_t Delay); +uint32_t DAL_GetTick(void); +uint32_t DAL_GetTickPrio(void); +DAL_StatusTypeDef DAL_SetTickFreq(DAL_TickFreqTypeDef Freq); +DAL_TickFreqTypeDef DAL_GetTickFreq(void); +void DAL_SuspendTick(void); +void DAL_ResumeTick(void); +uint32_t DAL_GetHalVersion(void); +uint32_t DAL_GetREVID(void); +uint32_t DAL_GetDEVID(void); +void DAL_DBGMCU_EnableDBGSleepMode(void); +void DAL_DBGMCU_DisableDBGSleepMode(void); +void DAL_DBGMCU_EnableDBGStopMode(void); +void DAL_DBGMCU_DisableDBGStopMode(void); +void DAL_DBGMCU_EnableDBGStandbyMode(void); +void DAL_DBGMCU_DisableDBGStandbyMode(void); +void DAL_EnableCompensationCell(void); +void DAL_DisableCompensationCell(void); +uint32_t DAL_GetUIDw0(void); +uint32_t DAL_GetUIDw1(void); +uint32_t DAL_GetUIDw2(void); +/** + * @} + */ + +/** + * @} + */ +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/** @defgroup DAL_Private_Variables DAL Private Variables + * @{ + */ +/** + * @} + */ +/* Private constants ---------------------------------------------------------*/ +/** @defgroup DAL_Private_Constants DAL Private Constants + * @{ + */ +/** + * @} + */ +/* Private macros ------------------------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* APM32F4xx_DAL_H */ + + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_adc.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_adc.h new file mode 100644 index 0000000000..1c459e9761 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_adc.h @@ -0,0 +1,922 @@ +/** + * + * @file apm32f4xx_dal_adc.h + * @brief Header file containing functions prototypes of ADC DAL library. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2017 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef APM32F4xx_DAL_ADC_H +#define APM32F4xx_DAL_ADC_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal_def.h" + +/* Include low level driver */ +#include "apm32f4xx_ddl_adc.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @addtogroup ADC + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ +/** @defgroup ADC_Exported_Types ADC Exported Types + * @{ + */ + +/** + * @brief Structure definition of ADC and regular group initialization + * @note Parameters of this structure are shared within 2 scopes: + * - Scope entire ADC (affects regular and injected groups): ClockPrescaler, Resolution, ScanConvMode, DataAlign, ScanConvMode, EOCSelection, LowPowerAutoWait, LowPowerAutoPowerOff, ChannelsBank. + * - Scope regular group: ContinuousConvMode, NbrOfConversion, DiscontinuousConvMode, NbrOfDiscConversion, ExternalTrigConvEdge, ExternalTrigConv. + * @note The setting of these parameters with function DAL_ADC_Init() is conditioned to ADC state. + * ADC state can be either: + * - For all parameters: ADC disabled + * - For all parameters except 'Resolution', 'ScanConvMode', 'DiscontinuousConvMode', 'NbrOfDiscConversion' : ADC enabled without conversion on going on regular group. + * - For parameters 'ExternalTrigConv' and 'ExternalTrigConvEdge': ADC enabled, even with conversion on going. + * If ADC is not in the appropriate state to modify some parameters, these parameters setting is bypassed + * without error reporting (as it can be the expected behaviour in case of intended action to update another parameter (which fulfills the ADC state condition) on the fly). + */ +typedef struct +{ + uint32_t ClockPrescaler; /*!< Select ADC clock prescaler. The clock is common for + all the ADCs. + This parameter can be a value of @ref ADC_ClockPrescaler */ + uint32_t Resolution; /*!< Configures the ADC resolution. + This parameter can be a value of @ref ADC_Resolution */ + uint32_t DataAlign; /*!< Specifies ADC data alignment to right (MSB on register bit 11 and LSB on register bit 0) (default setting) + or to left (if regular group: MSB on register bit 15 and LSB on register bit 4, if injected group (MSB kept as signed value due to potential negative value after offset application): MSB on register bit 14 and LSB on register bit 3). + This parameter can be a value of @ref ADC_Data_align */ + uint32_t ScanConvMode; /*!< Configures the sequencer of regular and injected groups. + This parameter can be associated to parameter 'DiscontinuousConvMode' to have main sequence subdivided in successive parts. + If disabled: Conversion is performed in single mode (one channel converted, the one defined in rank 1). + Parameters 'NbrOfConversion' and 'InjectedNbrOfConversion' are discarded (equivalent to set to 1). + If enabled: Conversions are performed in sequence mode (multiple ranks defined by 'NbrOfConversion'/'InjectedNbrOfConversion' and each channel rank). + Scan direction is upward: from rank1 to rank 'n'. + This parameter can be set to ENABLE or DISABLE */ + uint32_t EOCSelection; /*!< Specifies what EOC (End Of Conversion) flag is used for conversion by polling and interruption: end of conversion of each rank or complete sequence. + This parameter can be a value of @ref ADC_EOCSelection. + Note: For injected group, end of conversion (flag&IT) is raised only at the end of the sequence. + Therefore, if end of conversion is set to end of each conversion, injected group should not be used with interruption (DAL_ADCEx_InjectedStart_IT) + or polling (DAL_ADCEx_InjectedStart and DAL_ADCEx_InjectedPollForConversion). By the way, polling is still possible since driver will use an estimated timing for end of injected conversion. + Note: If overrun feature is intended to be used, use ADC in mode 'interruption' (function DAL_ADC_Start_IT() ) with parameter EOCSelection set to end of each conversion or in mode 'transfer by DMA' (function DAL_ADC_Start_DMA()). + If overrun feature is intended to be bypassed, use ADC in mode 'polling' or 'interruption' with parameter EOCSelection must be set to end of sequence */ + FunctionalState ContinuousConvMode; /*!< Specifies whether the conversion is performed in single mode (one conversion) or continuous mode for regular group, + after the selected trigger occurred (software start or external trigger). + This parameter can be set to ENABLE or DISABLE. */ + uint32_t NbrOfConversion; /*!< Specifies the number of ranks that will be converted within the regular group sequencer. + To use regular group sequencer and convert several ranks, parameter 'ScanConvMode' must be enabled. + This parameter must be a number between Min_Data = 1 and Max_Data = 16. */ + FunctionalState DiscontinuousConvMode; /*!< Specifies whether the conversions sequence of regular group is performed in Complete-sequence/Discontinuous-sequence (main sequence subdivided in successive parts). + Discontinuous mode is used only if sequencer is enabled (parameter 'ScanConvMode'). If sequencer is disabled, this parameter is discarded. + Discontinuous mode can be enabled only if continuous mode is disabled. If continuous mode is enabled, this parameter setting is discarded. + This parameter can be set to ENABLE or DISABLE. */ + uint32_t NbrOfDiscConversion; /*!< Specifies the number of discontinuous conversions in which the main sequence of regular group (parameter NbrOfConversion) will be subdivided. + If parameter 'DiscontinuousConvMode' is disabled, this parameter is discarded. + This parameter must be a number between Min_Data = 1 and Max_Data = 8. */ + uint32_t ExternalTrigConv; /*!< Selects the external event used to trigger the conversion start of regular group. + If set to ADC_SOFTWARE_START, external triggers are disabled. + If set to external trigger source, triggering is on event rising edge by default. + This parameter can be a value of @ref ADC_External_trigger_Source_Regular */ + uint32_t ExternalTrigConvEdge; /*!< Selects the external trigger edge of regular group. + If trigger is set to ADC_SOFTWARE_START, this parameter is discarded. + This parameter can be a value of @ref ADC_External_trigger_edge_Regular */ + FunctionalState DMAContinuousRequests; /*!< Specifies whether the DMA requests are performed in one shot mode (DMA transfer stop when number of conversions is reached) + or in Continuous mode (DMA transfer unlimited, whatever number of conversions). + Note: In continuous mode, DMA must be configured in circular mode. Otherwise an overrun will be triggered when DMA buffer maximum pointer is reached. + Note: This parameter must be modified when no conversion is on going on both regular and injected groups (ADC disabled, or ADC enabled without continuous mode or external trigger that could launch a conversion). + This parameter can be set to ENABLE or DISABLE. */ +}ADC_InitTypeDef; + + + +/** + * @brief Structure definition of ADC channel for regular group + * @note The setting of these parameters with function DAL_ADC_ConfigChannel() is conditioned to ADC state. + * ADC can be either disabled or enabled without conversion on going on regular group. + */ +typedef struct +{ + uint32_t Channel; /*!< Specifies the channel to configure into ADC regular group. + This parameter can be a value of @ref ADC_channels */ + uint32_t Rank; /*!< Specifies the rank in the regular group sequencer. + This parameter must be a number between Min_Data = 1 and Max_Data = 16 */ + uint32_t SamplingTime; /*!< Sampling time value to be set for the selected channel. + Unit: ADC clock cycles + Conversion time is the addition of sampling time and processing time (12 ADC clock cycles at ADC resolution 12 bits, 11 cycles at 10 bits, 9 cycles at 8 bits, 7 cycles at 6 bits). + This parameter can be a value of @ref ADC_sampling_times + Caution: This parameter updates the parameter property of the channel, that can be used into regular and/or injected groups. + If this same channel has been previously configured in the other group (regular/injected), it will be updated to last setting. + Note: In case of usage of internal measurement channels (VrefInt/Vbat/TempSensor), + sampling time constraints must be respected (sampling time can be adjusted in function of ADC clock frequency and sampling time setting) + Refer to device datasheet for timings values, parameters TS_vrefint, TS_temp (values rough order: 4us min). */ + uint32_t Offset; /*!< Reserved for future use, can be set to 0 */ +}ADC_ChannelConfTypeDef; + +/** + * @brief ADC Configuration multi-mode structure definition + */ +typedef struct +{ + uint32_t WatchdogMode; /*!< Configures the ADC analog watchdog mode. + This parameter can be a value of @ref ADC_analog_watchdog_selection */ + uint32_t HighThreshold; /*!< Configures the ADC analog watchdog High threshold value. + This parameter must be a 12-bit value. */ + uint32_t LowThreshold; /*!< Configures the ADC analog watchdog High threshold value. + This parameter must be a 12-bit value. */ + uint32_t Channel; /*!< Configures ADC channel for the analog watchdog. + This parameter has an effect only if watchdog mode is configured on single channel + This parameter can be a value of @ref ADC_channels */ + FunctionalState ITMode; /*!< Specifies whether the analog watchdog is configured + is interrupt mode or in polling mode. + This parameter can be set to ENABLE or DISABLE */ + uint32_t WatchdogNumber; /*!< Reserved for future use, can be set to 0 */ +}ADC_AnalogWDGConfTypeDef; + +/** + * @brief DAL ADC state machine: ADC states definition (bitfields) + */ +/* States of ADC global scope */ +#define DAL_ADC_STATE_RESET 0x00000000U /*!< ADC not yet initialized or disabled */ +#define DAL_ADC_STATE_READY 0x00000001U /*!< ADC peripheral ready for use */ +#define DAL_ADC_STATE_BUSY_INTERNAL 0x00000002U /*!< ADC is busy to internal process (initialization, calibration) */ +#define DAL_ADC_STATE_TIMEOUT 0x00000004U /*!< TimeOut occurrence */ + +/* States of ADC errors */ +#define DAL_ADC_STATE_ERROR_INTERNAL 0x00000010U /*!< Internal error occurrence */ +#define DAL_ADC_STATE_ERROR_CONFIG 0x00000020U /*!< Configuration error occurrence */ +#define DAL_ADC_STATE_ERROR_DMA 0x00000040U /*!< DMA error occurrence */ + +/* States of ADC group regular */ +#define DAL_ADC_STATE_REG_BUSY 0x00000100U /*!< A conversion on group regular is ongoing or can occur (either by continuous mode, + external trigger, low power auto power-on (if feature available), multimode ADC master control (if feature available)) */ +#define DAL_ADC_STATE_REG_EOC 0x00000200U /*!< Conversion data available on group regular */ +#define DAL_ADC_STATE_REG_OVR 0x00000400U /*!< Overrun occurrence */ + +/* States of ADC group injected */ +#define DAL_ADC_STATE_INJ_BUSY 0x00001000U /*!< A conversion on group injected is ongoing or can occur (either by auto-injection mode, + external trigger, low power auto power-on (if feature available), multimode ADC master control (if feature available)) */ +#define DAL_ADC_STATE_INJ_EOC 0x00002000U /*!< Conversion data available on group injected */ + +/* States of ADC analog watchdogs */ +#define DAL_ADC_STATE_AWD1 0x00010000U /*!< Out-of-window occurrence of analog watchdog 1 */ +#define DAL_ADC_STATE_AWD2 0x00020000U /*!< Not available on APM32F4 device: Out-of-window occurrence of analog watchdog 2 */ +#define DAL_ADC_STATE_AWD3 0x00040000U /*!< Not available on APM32F4 device: Out-of-window occurrence of analog watchdog 3 */ + +/* States of ADC multi-mode */ +#define DAL_ADC_STATE_MULTIMODE_SLAVE 0x00100000U /*!< Not available on APM32F4 device: ADC in multimode slave state, controlled by another ADC master ( */ + + +/** + * @brief ADC handle Structure definition + */ +#if (USE_DAL_ADC_REGISTER_CALLBACKS == 1) +typedef struct __ADC_HandleTypeDef +#else +typedef struct +#endif +{ + ADC_TypeDef *Instance; /*!< Register base address */ + + ADC_InitTypeDef Init; /*!< ADC required parameters */ + + __IO uint32_t NbrOfCurrentConversionRank; /*!< ADC number of current conversion rank */ + + DMA_HandleTypeDef *DMA_Handle; /*!< Pointer DMA Handler */ + + DAL_LockTypeDef Lock; /*!< ADC locking object */ + + __IO uint32_t State; /*!< ADC communication state */ + + __IO uint32_t ErrorCode; /*!< ADC Error code */ +#if (USE_DAL_ADC_REGISTER_CALLBACKS == 1) + void (* ConvCpltCallback)(struct __ADC_HandleTypeDef *hadc); /*!< ADC conversion complete callback */ + void (* ConvHalfCpltCallback)(struct __ADC_HandleTypeDef *hadc); /*!< ADC conversion DMA half-transfer callback */ + void (* LevelOutOfWindowCallback)(struct __ADC_HandleTypeDef *hadc); /*!< ADC analog watchdog 1 callback */ + void (* ErrorCallback)(struct __ADC_HandleTypeDef *hadc); /*!< ADC error callback */ + void (* InjectedConvCpltCallback)(struct __ADC_HandleTypeDef *hadc); /*!< ADC group injected conversion complete callback */ + void (* MspInitCallback)(struct __ADC_HandleTypeDef *hadc); /*!< ADC Msp Init callback */ + void (* MspDeInitCallback)(struct __ADC_HandleTypeDef *hadc); /*!< ADC Msp DeInit callback */ +#endif /* USE_DAL_ADC_REGISTER_CALLBACKS */ +}ADC_HandleTypeDef; + +#if (USE_DAL_ADC_REGISTER_CALLBACKS == 1) +/** + * @brief DAL ADC Callback ID enumeration definition + */ +typedef enum +{ + DAL_ADC_CONVERSION_COMPLETE_CB_ID = 0x00U, /*!< ADC conversion complete callback ID */ + DAL_ADC_CONVERSION_HALF_CB_ID = 0x01U, /*!< ADC conversion DMA half-transfer callback ID */ + DAL_ADC_LEVEL_OUT_OF_WINDOW_1_CB_ID = 0x02U, /*!< ADC analog watchdog 1 callback ID */ + DAL_ADC_ERROR_CB_ID = 0x03U, /*!< ADC error callback ID */ + DAL_ADC_INJ_CONVERSION_COMPLETE_CB_ID = 0x04U, /*!< ADC group injected conversion complete callback ID */ + DAL_ADC_MSPINIT_CB_ID = 0x05U, /*!< ADC Msp Init callback ID */ + DAL_ADC_MSPDEINIT_CB_ID = 0x06U /*!< ADC Msp DeInit callback ID */ +} DAL_ADC_CallbackIDTypeDef; + +/** + * @brief DAL ADC Callback pointer definition + */ +typedef void (*pADC_CallbackTypeDef)(ADC_HandleTypeDef *hadc); /*!< pointer to a ADC callback function */ + +#endif /* USE_DAL_ADC_REGISTER_CALLBACKS */ + +/** + * @} + */ + +/* Exported constants --------------------------------------------------------*/ +/** @defgroup ADC_Exported_Constants ADC Exported Constants + * @{ + */ + +/** @defgroup ADC_Error_Code ADC Error Code + * @{ + */ +#define DAL_ADC_ERROR_NONE 0x00U /*!< No error */ +#define DAL_ADC_ERROR_INTERNAL 0x01U /*!< ADC IP internal error: if problem of clocking, + enable/disable, erroneous state */ +#define DAL_ADC_ERROR_OVR 0x02U /*!< Overrun error */ +#define DAL_ADC_ERROR_DMA 0x04U /*!< DMA transfer error */ +#if (USE_DAL_ADC_REGISTER_CALLBACKS == 1) +#define DAL_ADC_ERROR_INVALID_CALLBACK (0x10U) /*!< Invalid Callback error */ +#endif /* USE_DAL_ADC_REGISTER_CALLBACKS */ +/** + * @} + */ + + +/** @defgroup ADC_ClockPrescaler ADC Clock Prescaler + * @{ + */ +#define ADC_CLOCK_SYNC_PCLK_DIV2 0x00000000U +#define ADC_CLOCK_SYNC_PCLK_DIV4 ((uint32_t)ADC_CCTRL_ADCPRE_0) +#define ADC_CLOCK_SYNC_PCLK_DIV6 ((uint32_t)ADC_CCTRL_ADCPRE_1) +#define ADC_CLOCK_SYNC_PCLK_DIV8 ((uint32_t)ADC_CCTRL_ADCPRE) +/** + * @} + */ + +/** @defgroup ADC_delay_between_2_sampling_phases ADC Delay Between 2 Sampling Phases + * @{ + */ +#define ADC_TWOSAMPLINGDELAY_5CYCLES 0x00000000U +#define ADC_TWOSAMPLINGDELAY_6CYCLES ((uint32_t)ADC_CCTRL_SMPDEL2_0) +#define ADC_TWOSAMPLINGDELAY_7CYCLES ((uint32_t)ADC_CCTRL_SMPDEL2_1) +#define ADC_TWOSAMPLINGDELAY_8CYCLES ((uint32_t)(ADC_CCTRL_SMPDEL2_1 | ADC_CCTRL_SMPDEL2_0)) +#define ADC_TWOSAMPLINGDELAY_9CYCLES ((uint32_t)ADC_CCTRL_SMPDEL2_2) +#define ADC_TWOSAMPLINGDELAY_10CYCLES ((uint32_t)(ADC_CCTRL_SMPDEL2_2 | ADC_CCTRL_SMPDEL2_0)) +#define ADC_TWOSAMPLINGDELAY_11CYCLES ((uint32_t)(ADC_CCTRL_SMPDEL2_2 | ADC_CCTRL_SMPDEL2_1)) +#define ADC_TWOSAMPLINGDELAY_12CYCLES ((uint32_t)(ADC_CCTRL_SMPDEL2_2 | ADC_CCTRL_SMPDEL2_1 | ADC_CCTRL_SMPDEL2_0)) +#define ADC_TWOSAMPLINGDELAY_13CYCLES ((uint32_t)ADC_CCTRL_SMPDEL2_3) +#define ADC_TWOSAMPLINGDELAY_14CYCLES ((uint32_t)(ADC_CCTRL_SMPDEL2_3 | ADC_CCTRL_SMPDEL2_0)) +#define ADC_TWOSAMPLINGDELAY_15CYCLES ((uint32_t)(ADC_CCTRL_SMPDEL2_3 | ADC_CCTRL_SMPDEL2_1)) +#define ADC_TWOSAMPLINGDELAY_16CYCLES ((uint32_t)(ADC_CCTRL_SMPDEL2_3 | ADC_CCTRL_SMPDEL2_1 | ADC_CCTRL_SMPDEL2_0)) +#define ADC_TWOSAMPLINGDELAY_17CYCLES ((uint32_t)(ADC_CCTRL_SMPDEL2_3 | ADC_CCTRL_SMPDEL2_2)) +#define ADC_TWOSAMPLINGDELAY_18CYCLES ((uint32_t)(ADC_CCTRL_SMPDEL2_3 | ADC_CCTRL_SMPDEL2_2 | ADC_CCTRL_SMPDEL2_0)) +#define ADC_TWOSAMPLINGDELAY_19CYCLES ((uint32_t)(ADC_CCTRL_SMPDEL2_3 | ADC_CCTRL_SMPDEL2_2 | ADC_CCTRL_SMPDEL2_1)) +#define ADC_TWOSAMPLINGDELAY_20CYCLES ((uint32_t)ADC_CCTRL_SMPDEL2) +/** + * @} + */ + +/** @defgroup ADC_Resolution ADC Resolution + * @{ + */ +#define ADC_RESOLUTION_12B 0x00000000U +#define ADC_RESOLUTION_10B ((uint32_t)ADC_CTRL1_RESSEL_0) +#define ADC_RESOLUTION_8B ((uint32_t)ADC_CTRL1_RESSEL_1) +#define ADC_RESOLUTION_6B ((uint32_t)ADC_CTRL1_RESSEL) +/** + * @} + */ + +/** @defgroup ADC_External_trigger_edge_Regular ADC External Trigger Edge Regular + * @{ + */ +#define ADC_EXTERNALTRIGCONVEDGE_NONE 0x00000000U +#define ADC_EXTERNALTRIGCONVEDGE_RISING ((uint32_t)ADC_CTRL2_REGEXTTRGEN_0) +#define ADC_EXTERNALTRIGCONVEDGE_FALLING ((uint32_t)ADC_CTRL2_REGEXTTRGEN_1) +#define ADC_EXTERNALTRIGCONVEDGE_RISINGFALLING ((uint32_t)ADC_CTRL2_REGEXTTRGEN) +/** + * @} + */ + +/** @defgroup ADC_External_trigger_Source_Regular ADC External Trigger Source Regular + * @{ + */ +/* Note: Parameter ADC_SOFTWARE_START is a software parameter used for */ +/* compatibility with other APM32 devices. */ +#define ADC_EXTERNALTRIGCONV_T1_CC1 0x00000000U +#define ADC_EXTERNALTRIGCONV_T1_CC2 ((uint32_t)ADC_CTRL2_REGEXTTRGSEL_0) +#define ADC_EXTERNALTRIGCONV_T1_CC3 ((uint32_t)ADC_CTRL2_REGEXTTRGSEL_1) +#define ADC_EXTERNALTRIGCONV_T2_CC2 ((uint32_t)(ADC_CTRL2_REGEXTTRGSEL_1 | ADC_CTRL2_REGEXTTRGSEL_0)) +#define ADC_EXTERNALTRIGCONV_T2_CC3 ((uint32_t)ADC_CTRL2_REGEXTTRGSEL_2) +#define ADC_EXTERNALTRIGCONV_T2_CC4 ((uint32_t)(ADC_CTRL2_REGEXTTRGSEL_2 | ADC_CTRL2_REGEXTTRGSEL_0)) +#define ADC_EXTERNALTRIGCONV_T2_TRGO ((uint32_t)(ADC_CTRL2_REGEXTTRGSEL_2 | ADC_CTRL2_REGEXTTRGSEL_1)) +#define ADC_EXTERNALTRIGCONV_T3_CC1 ((uint32_t)(ADC_CTRL2_REGEXTTRGSEL_2 | ADC_CTRL2_REGEXTTRGSEL_1 | ADC_CTRL2_REGEXTTRGSEL_0)) +#define ADC_EXTERNALTRIGCONV_T3_TRGO ((uint32_t)ADC_CTRL2_REGEXTTRGSEL_3) +#define ADC_EXTERNALTRIGCONV_T4_CC4 ((uint32_t)(ADC_CTRL2_REGEXTTRGSEL_3 | ADC_CTRL2_REGEXTTRGSEL_0)) +#define ADC_EXTERNALTRIGCONV_T5_CC1 ((uint32_t)(ADC_CTRL2_REGEXTTRGSEL_3 | ADC_CTRL2_REGEXTTRGSEL_1)) +#define ADC_EXTERNALTRIGCONV_T5_CC2 ((uint32_t)(ADC_CTRL2_REGEXTTRGSEL_3 | ADC_CTRL2_REGEXTTRGSEL_1 | ADC_CTRL2_REGEXTTRGSEL_0)) +#define ADC_EXTERNALTRIGCONV_T5_CC3 ((uint32_t)(ADC_CTRL2_REGEXTTRGSEL_3 | ADC_CTRL2_REGEXTTRGSEL_2)) +#define ADC_EXTERNALTRIGCONV_T8_CC1 ((uint32_t)(ADC_CTRL2_REGEXTTRGSEL_3 | ADC_CTRL2_REGEXTTRGSEL_2 | ADC_CTRL2_REGEXTTRGSEL_0)) +#define ADC_EXTERNALTRIGCONV_T8_TRGO ((uint32_t)(ADC_CTRL2_REGEXTTRGSEL_3 | ADC_CTRL2_REGEXTTRGSEL_2 | ADC_CTRL2_REGEXTTRGSEL_1)) +#define ADC_EXTERNALTRIGCONV_EXT_IT11 ((uint32_t)ADC_CTRL2_REGEXTTRGSEL) +#define ADC_SOFTWARE_START ((uint32_t)ADC_CTRL2_REGEXTTRGSEL + 1U) +/** + * @} + */ + +/** @defgroup ADC_Data_align ADC Data Align + * @{ + */ +#define ADC_DATAALIGN_RIGHT 0x00000000U +#define ADC_DATAALIGN_LEFT ((uint32_t)ADC_CTRL2_DALIGNCFG) +/** + * @} + */ + +/** @defgroup ADC_channels ADC Common Channels + * @{ + */ +#define ADC_CHANNEL_0 0x00000000U +#define ADC_CHANNEL_1 ((uint32_t)ADC_CTRL1_AWDCHSEL_0) +#define ADC_CHANNEL_2 ((uint32_t)ADC_CTRL1_AWDCHSEL_1) +#define ADC_CHANNEL_3 ((uint32_t)(ADC_CTRL1_AWDCHSEL_1 | ADC_CTRL1_AWDCHSEL_0)) +#define ADC_CHANNEL_4 ((uint32_t)ADC_CTRL1_AWDCHSEL_2) +#define ADC_CHANNEL_5 ((uint32_t)(ADC_CTRL1_AWDCHSEL_2 | ADC_CTRL1_AWDCHSEL_0)) +#define ADC_CHANNEL_6 ((uint32_t)(ADC_CTRL1_AWDCHSEL_2 | ADC_CTRL1_AWDCHSEL_1)) +#define ADC_CHANNEL_7 ((uint32_t)(ADC_CTRL1_AWDCHSEL_2 | ADC_CTRL1_AWDCHSEL_1 | ADC_CTRL1_AWDCHSEL_0)) +#define ADC_CHANNEL_8 ((uint32_t)ADC_CTRL1_AWDCHSEL_3) +#define ADC_CHANNEL_9 ((uint32_t)(ADC_CTRL1_AWDCHSEL_3 | ADC_CTRL1_AWDCHSEL_0)) +#define ADC_CHANNEL_10 ((uint32_t)(ADC_CTRL1_AWDCHSEL_3 | ADC_CTRL1_AWDCHSEL_1)) +#define ADC_CHANNEL_11 ((uint32_t)(ADC_CTRL1_AWDCHSEL_3 | ADC_CTRL1_AWDCHSEL_1 | ADC_CTRL1_AWDCHSEL_0)) +#define ADC_CHANNEL_12 ((uint32_t)(ADC_CTRL1_AWDCHSEL_3 | ADC_CTRL1_AWDCHSEL_2)) +#define ADC_CHANNEL_13 ((uint32_t)(ADC_CTRL1_AWDCHSEL_3 | ADC_CTRL1_AWDCHSEL_2 | ADC_CTRL1_AWDCHSEL_0)) +#define ADC_CHANNEL_14 ((uint32_t)(ADC_CTRL1_AWDCHSEL_3 | ADC_CTRL1_AWDCHSEL_2 | ADC_CTRL1_AWDCHSEL_1)) +#define ADC_CHANNEL_15 ((uint32_t)(ADC_CTRL1_AWDCHSEL_3 | ADC_CTRL1_AWDCHSEL_2 | ADC_CTRL1_AWDCHSEL_1 | ADC_CTRL1_AWDCHSEL_0)) +#define ADC_CHANNEL_16 ((uint32_t)ADC_CTRL1_AWDCHSEL_4) +#define ADC_CHANNEL_17 ((uint32_t)(ADC_CTRL1_AWDCHSEL_4 | ADC_CTRL1_AWDCHSEL_0)) +#define ADC_CHANNEL_18 ((uint32_t)(ADC_CTRL1_AWDCHSEL_4 | ADC_CTRL1_AWDCHSEL_1)) + +#define ADC_CHANNEL_VREFINT ((uint32_t)ADC_CHANNEL_17) +#define ADC_CHANNEL_VBAT ((uint32_t)ADC_CHANNEL_18) +/** + * @} + */ + +/** @defgroup ADC_sampling_times ADC Sampling Times + * @{ + */ +#define ADC_SAMPLETIME_3CYCLES 0x00000000U +#define ADC_SAMPLETIME_15CYCLES ((uint32_t)ADC_SMPTIM1_SMPCYCCFG10_0) +#define ADC_SAMPLETIME_28CYCLES ((uint32_t)ADC_SMPTIM1_SMPCYCCFG10_1) +#define ADC_SAMPLETIME_56CYCLES ((uint32_t)(ADC_SMPTIM1_SMPCYCCFG10_1 | ADC_SMPTIM1_SMPCYCCFG10_0)) +#define ADC_SAMPLETIME_84CYCLES ((uint32_t)ADC_SMPTIM1_SMPCYCCFG10_2) +#define ADC_SAMPLETIME_112CYCLES ((uint32_t)(ADC_SMPTIM1_SMPCYCCFG10_2 | ADC_SMPTIM1_SMPCYCCFG10_0)) +#define ADC_SAMPLETIME_144CYCLES ((uint32_t)(ADC_SMPTIM1_SMPCYCCFG10_2 | ADC_SMPTIM1_SMPCYCCFG10_1)) +#define ADC_SAMPLETIME_480CYCLES ((uint32_t)ADC_SMPTIM1_SMPCYCCFG10) +/** + * @} + */ + + /** @defgroup ADC_EOCSelection ADC EOC Selection + * @{ + */ +#define ADC_EOC_SEQ_CONV 0x00000000U +#define ADC_EOC_SINGLE_CONV 0x00000001U +#define ADC_EOC_SINGLE_SEQ_CONV 0x00000002U /*!< reserved for future use */ +/** + * @} + */ + +/** @defgroup ADC_Event_type ADC Event Type + * @{ + */ +#define ADC_AWD_EVENT ((uint32_t)ADC_FLAG_AWD) +#define ADC_OVR_EVENT ((uint32_t)ADC_FLAG_OVR) +/** + * @} + */ + +/** @defgroup ADC_analog_watchdog_selection ADC Analog Watchdog Selection + * @{ + */ +#define ADC_ANALOGWATCHDOG_SINGLE_REG ((uint32_t)(ADC_CTRL1_AWDSGLEN | ADC_CTRL1_REGAWDEN)) +#define ADC_ANALOGWATCHDOG_SINGLE_INJEC ((uint32_t)(ADC_CTRL1_AWDSGLEN | ADC_CTRL1_INJAWDEN)) +#define ADC_ANALOGWATCHDOG_SINGLE_REGINJEC ((uint32_t)(ADC_CTRL1_AWDSGLEN | ADC_CTRL1_REGAWDEN | ADC_CTRL1_INJAWDEN)) +#define ADC_ANALOGWATCHDOG_ALL_REG ((uint32_t)ADC_CTRL1_REGAWDEN) +#define ADC_ANALOGWATCHDOG_ALL_INJEC ((uint32_t)ADC_CTRL1_INJAWDEN) +#define ADC_ANALOGWATCHDOG_ALL_REGINJEC ((uint32_t)(ADC_CTRL1_REGAWDEN | ADC_CTRL1_INJAWDEN)) +#define ADC_ANALOGWATCHDOG_NONE 0x00000000U +/** + * @} + */ + +/** @defgroup ADC_interrupts_definition ADC Interrupts Definition + * @{ + */ +#define ADC_IT_EOC ((uint32_t)ADC_CTRL1_EOCIEN) +#define ADC_IT_AWD ((uint32_t)ADC_CTRL1_AWDIEN) +#define ADC_IT_JEOC ((uint32_t)ADC_CTRL1_INJEOCIEN) +#define ADC_IT_OVR ((uint32_t)ADC_CTRL1_OVRIEN) +/** + * @} + */ + +/** @defgroup ADC_flags_definition ADC Flags Definition + * @{ + */ +#define ADC_FLAG_AWD ((uint32_t)ADC_STS_AWDFLG) +#define ADC_FLAG_EOC ((uint32_t)ADC_STS_EOCFLG) +#define ADC_FLAG_JEOC ((uint32_t)ADC_STS_INJEOCFLG) +#define ADC_FLAG_JSTRT ((uint32_t)ADC_STS_INJCSFLG) +#define ADC_FLAG_STRT ((uint32_t)ADC_STS_REGCSFLG) +#define ADC_FLAG_OVR ((uint32_t)ADC_STS_OVRFLG) +/** + * @} + */ + +/** @defgroup ADC_channels_type ADC Channels Type + * @{ + */ +#define ADC_ALL_CHANNELS 0x00000001U +#define ADC_REGULAR_CHANNELS 0x00000002U /*!< reserved for future use */ +#define ADC_INJECTED_CHANNELS 0x00000003U /*!< reserved for future use */ +/** + * @} + */ + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ +/** @defgroup ADC_Exported_Macros ADC Exported Macros + * @{ + */ + +/** @brief Reset ADC handle state + * @param __HANDLE__ ADC handle + * @retval None + */ +#if (USE_DAL_ADC_REGISTER_CALLBACKS == 1) +#define __DAL_ADC_RESET_HANDLE_STATE(__HANDLE__) \ + do{ \ + (__HANDLE__)->State = DAL_ADC_STATE_RESET; \ + (__HANDLE__)->MspInitCallback = NULL; \ + (__HANDLE__)->MspDeInitCallback = NULL; \ + } while(0) +#else +#define __DAL_ADC_RESET_HANDLE_STATE(__HANDLE__) \ + ((__HANDLE__)->State = DAL_ADC_STATE_RESET) +#endif + +/** + * @brief Enable the ADC peripheral. + * @param __HANDLE__ ADC handle + * @retval None + */ +#define __DAL_ADC_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CTRL2 |= ADC_CTRL2_ADCEN) + +/** + * @brief Disable the ADC peripheral. + * @param __HANDLE__ ADC handle + * @retval None + */ +#define __DAL_ADC_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CTRL2 &= ~ADC_CTRL2_ADCEN) + +/** + * @brief Enable the ADC end of conversion interrupt. + * @param __HANDLE__ specifies the ADC Handle. + * @param __INTERRUPT__ ADC Interrupt. + * @retval None + */ +#define __DAL_ADC_ENABLE_IT(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->CTRL1) |= (__INTERRUPT__)) + +/** + * @brief Disable the ADC end of conversion interrupt. + * @param __HANDLE__ specifies the ADC Handle. + * @param __INTERRUPT__ ADC interrupt. + * @retval None + */ +#define __DAL_ADC_DISABLE_IT(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->CTRL1) &= ~(__INTERRUPT__)) + +/** @brief Check if the specified ADC interrupt source is enabled or disabled. + * @param __HANDLE__ specifies the ADC Handle. + * @param __INTERRUPT__ specifies the ADC interrupt source to check. + * @retval The new state of __IT__ (TRUE or FALSE). + */ +#define __DAL_ADC_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->CTRL1 & (__INTERRUPT__)) == (__INTERRUPT__)) + +/** + * @brief Clear the ADC's pending flags. + * @param __HANDLE__ specifies the ADC Handle. + * @param __FLAG__ ADC flag. + * @retval None + */ +#define __DAL_ADC_CLEAR_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->STS) = ~(__FLAG__)) + +/** + * @brief Get the selected ADC's flag status. + * @param __HANDLE__ specifies the ADC Handle. + * @param __FLAG__ ADC flag. + * @retval None + */ +#define __DAL_ADC_GET_FLAG(__HANDLE__, __FLAG__) ((((__HANDLE__)->Instance->STS) & (__FLAG__)) == (__FLAG__)) + +/** + * @} + */ + +/* Include ADC DAL Extension module */ +#include "apm32f4xx_dal_adc_ex.h" + +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup ADC_Exported_Functions + * @{ + */ + +/** @addtogroup ADC_Exported_Functions_Group1 + * @{ + */ +/* Initialization/de-initialization functions ***********************************/ +DAL_StatusTypeDef DAL_ADC_Init(ADC_HandleTypeDef* hadc); +DAL_StatusTypeDef DAL_ADC_DeInit(ADC_HandleTypeDef *hadc); +void DAL_ADC_MspInit(ADC_HandleTypeDef* hadc); +void DAL_ADC_MspDeInit(ADC_HandleTypeDef* hadc); + +#if (USE_DAL_ADC_REGISTER_CALLBACKS == 1) +/* Callbacks Register/UnRegister functions ***********************************/ +DAL_StatusTypeDef DAL_ADC_RegisterCallback(ADC_HandleTypeDef *hadc, DAL_ADC_CallbackIDTypeDef CallbackID, pADC_CallbackTypeDef pCallback); +DAL_StatusTypeDef DAL_ADC_UnRegisterCallback(ADC_HandleTypeDef *hadc, DAL_ADC_CallbackIDTypeDef CallbackID); +#endif /* USE_DAL_ADC_REGISTER_CALLBACKS */ +/** + * @} + */ + +/** @addtogroup ADC_Exported_Functions_Group2 + * @{ + */ +/* I/O operation functions ******************************************************/ +DAL_StatusTypeDef DAL_ADC_Start(ADC_HandleTypeDef* hadc); +DAL_StatusTypeDef DAL_ADC_Stop(ADC_HandleTypeDef* hadc); +DAL_StatusTypeDef DAL_ADC_PollForConversion(ADC_HandleTypeDef* hadc, uint32_t Timeout); + +DAL_StatusTypeDef DAL_ADC_PollForEvent(ADC_HandleTypeDef* hadc, uint32_t EventType, uint32_t Timeout); + +DAL_StatusTypeDef DAL_ADC_Start_IT(ADC_HandleTypeDef* hadc); +DAL_StatusTypeDef DAL_ADC_Stop_IT(ADC_HandleTypeDef* hadc); + +void DAL_ADC_IRQHandler(ADC_HandleTypeDef* hadc); + +DAL_StatusTypeDef DAL_ADC_Start_DMA(ADC_HandleTypeDef* hadc, uint32_t* pData, uint32_t Length); +DAL_StatusTypeDef DAL_ADC_Stop_DMA(ADC_HandleTypeDef* hadc); + +uint32_t DAL_ADC_GetValue(ADC_HandleTypeDef* hadc); + +void DAL_ADC_ConvCpltCallback(ADC_HandleTypeDef* hadc); +void DAL_ADC_ConvHalfCpltCallback(ADC_HandleTypeDef* hadc); +void DAL_ADC_LevelOutOfWindowCallback(ADC_HandleTypeDef* hadc); +void DAL_ADC_ErrorCallback(ADC_HandleTypeDef *hadc); +/** + * @} + */ + +/** @addtogroup ADC_Exported_Functions_Group3 + * @{ + */ +/* Peripheral Control functions *************************************************/ +DAL_StatusTypeDef DAL_ADC_ConfigChannel(ADC_HandleTypeDef* hadc, ADC_ChannelConfTypeDef* sConfig); +DAL_StatusTypeDef DAL_ADC_AnalogWDGConfig(ADC_HandleTypeDef* hadc, ADC_AnalogWDGConfTypeDef* AnalogWDGConfig); +/** + * @} + */ + +/** @addtogroup ADC_Exported_Functions_Group4 + * @{ + */ +/* Peripheral State functions ***************************************************/ +uint32_t DAL_ADC_GetState(ADC_HandleTypeDef* hadc); +uint32_t DAL_ADC_GetError(ADC_HandleTypeDef *hadc); +/** + * @} + */ + +/** + * @} + */ +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/** @defgroup ADC_Private_Constants ADC Private Constants + * @{ + */ +/* Delay for ADC stabilization time. */ +/* Maximum delay is 1us (refer to device datasheet, parameter tSTAB). */ +/* Unit: us */ +#define ADC_STAB_DELAY_US 3U +/* Delay for temperature sensor stabilization time. */ +/* Maximum delay is 10us (refer to device datasheet, parameter tSTART). */ +/* Unit: us */ +#define ADC_TEMPSENSOR_DELAY_US 10U +/** + * @} + */ + +/* Private macro ------------------------------------------------------------*/ + +/** @defgroup ADC_Private_Macros ADC Private Macros + * @{ + */ +/* Macro reserved for internal DAL driver usage, not intended to be used in + code of final user */ + +/** + * @brief Verification of ADC state: enabled or disabled + * @param __HANDLE__ ADC handle + * @retval SET (ADC enabled) or RESET (ADC disabled) + */ +#define ADC_IS_ENABLE(__HANDLE__) \ + ((( ((__HANDLE__)->Instance->CTRL2 & ADC_CTRL2_ADCEN) == ADC_CTRL2_ADCEN ) \ + ) ? SET : RESET) + +/** + * @brief Test if conversion trigger of regular group is software start + * or external trigger. + * @param __HANDLE__ ADC handle + * @retval SET (software start) or RESET (external trigger) + */ +#define ADC_IS_SOFTWARE_START_REGULAR(__HANDLE__) \ + (((__HANDLE__)->Instance->CTRL2 & ADC_CTRL2_REGEXTTRGEN) == RESET) + +/** + * @brief Test if conversion trigger of injected group is software start + * or external trigger. + * @param __HANDLE__ ADC handle + * @retval SET (software start) or RESET (external trigger) + */ +#define ADC_IS_SOFTWARE_START_INJECTED(__HANDLE__) \ + (((__HANDLE__)->Instance->CTRL2 & ADC_CTRL2_INJEXTTRGEN) == RESET) + +/** + * @brief Simultaneously clears and sets specific bits of the handle State + * @note: ADC_STATE_CLR_SET() macro is merely aliased to generic macro MODIFY_REG(), + * the first parameter is the ADC handle State, the second parameter is the + * bit field to clear, the third and last parameter is the bit field to set. + * @retval None + */ +#define ADC_STATE_CLR_SET MODIFY_REG + +/** + * @brief Clear ADC error code (set it to error code: "no error") + * @param __HANDLE__ ADC handle + * @retval None + */ +#define ADC_CLEAR_ERRORCODE(__HANDLE__) \ + ((__HANDLE__)->ErrorCode = DAL_ADC_ERROR_NONE) + + +#define IS_ADC_CLOCKPRESCALER(ADC_CLOCK) (((ADC_CLOCK) == ADC_CLOCK_SYNC_PCLK_DIV2) || \ + ((ADC_CLOCK) == ADC_CLOCK_SYNC_PCLK_DIV4) || \ + ((ADC_CLOCK) == ADC_CLOCK_SYNC_PCLK_DIV6) || \ + ((ADC_CLOCK) == ADC_CLOCK_SYNC_PCLK_DIV8)) +#define IS_ADC_SAMPLING_DELAY(DELAY) (((DELAY) == ADC_TWOSAMPLINGDELAY_5CYCLES) || \ + ((DELAY) == ADC_TWOSAMPLINGDELAY_6CYCLES) || \ + ((DELAY) == ADC_TWOSAMPLINGDELAY_7CYCLES) || \ + ((DELAY) == ADC_TWOSAMPLINGDELAY_8CYCLES) || \ + ((DELAY) == ADC_TWOSAMPLINGDELAY_9CYCLES) || \ + ((DELAY) == ADC_TWOSAMPLINGDELAY_10CYCLES) || \ + ((DELAY) == ADC_TWOSAMPLINGDELAY_11CYCLES) || \ + ((DELAY) == ADC_TWOSAMPLINGDELAY_12CYCLES) || \ + ((DELAY) == ADC_TWOSAMPLINGDELAY_13CYCLES) || \ + ((DELAY) == ADC_TWOSAMPLINGDELAY_14CYCLES) || \ + ((DELAY) == ADC_TWOSAMPLINGDELAY_15CYCLES) || \ + ((DELAY) == ADC_TWOSAMPLINGDELAY_16CYCLES) || \ + ((DELAY) == ADC_TWOSAMPLINGDELAY_17CYCLES) || \ + ((DELAY) == ADC_TWOSAMPLINGDELAY_18CYCLES) || \ + ((DELAY) == ADC_TWOSAMPLINGDELAY_19CYCLES) || \ + ((DELAY) == ADC_TWOSAMPLINGDELAY_20CYCLES)) +#define IS_ADC_RESOLUTION(RESOLUTION) (((RESOLUTION) == ADC_RESOLUTION_12B) || \ + ((RESOLUTION) == ADC_RESOLUTION_10B) || \ + ((RESOLUTION) == ADC_RESOLUTION_8B) || \ + ((RESOLUTION) == ADC_RESOLUTION_6B)) +#define IS_ADC_EXT_TRIG_EDGE(EDGE) (((EDGE) == ADC_EXTERNALTRIGCONVEDGE_NONE) || \ + ((EDGE) == ADC_EXTERNALTRIGCONVEDGE_RISING) || \ + ((EDGE) == ADC_EXTERNALTRIGCONVEDGE_FALLING) || \ + ((EDGE) == ADC_EXTERNALTRIGCONVEDGE_RISINGFALLING)) +#define IS_ADC_EXT_TRIG(REGTRIG) (((REGTRIG) == ADC_EXTERNALTRIGCONV_T1_CC1) || \ + ((REGTRIG) == ADC_EXTERNALTRIGCONV_T1_CC2) || \ + ((REGTRIG) == ADC_EXTERNALTRIGCONV_T1_CC3) || \ + ((REGTRIG) == ADC_EXTERNALTRIGCONV_T2_CC2) || \ + ((REGTRIG) == ADC_EXTERNALTRIGCONV_T2_CC3) || \ + ((REGTRIG) == ADC_EXTERNALTRIGCONV_T2_CC4) || \ + ((REGTRIG) == ADC_EXTERNALTRIGCONV_T2_TRGO) || \ + ((REGTRIG) == ADC_EXTERNALTRIGCONV_T3_CC1) || \ + ((REGTRIG) == ADC_EXTERNALTRIGCONV_T3_TRGO) || \ + ((REGTRIG) == ADC_EXTERNALTRIGCONV_T4_CC4) || \ + ((REGTRIG) == ADC_EXTERNALTRIGCONV_T5_CC1) || \ + ((REGTRIG) == ADC_EXTERNALTRIGCONV_T5_CC2) || \ + ((REGTRIG) == ADC_EXTERNALTRIGCONV_T5_CC3) || \ + ((REGTRIG) == ADC_EXTERNALTRIGCONV_T8_CC1) || \ + ((REGTRIG) == ADC_EXTERNALTRIGCONV_T8_TRGO) || \ + ((REGTRIG) == ADC_EXTERNALTRIGCONV_EXT_IT11)|| \ + ((REGTRIG) == ADC_SOFTWARE_START)) +#define IS_ADC_DATA_ALIGN(ALIGN) (((ALIGN) == ADC_DATAALIGN_RIGHT) || \ + ((ALIGN) == ADC_DATAALIGN_LEFT)) +#define IS_ADC_SAMPLE_TIME(TIME) (((TIME) == ADC_SAMPLETIME_3CYCLES) || \ + ((TIME) == ADC_SAMPLETIME_15CYCLES) || \ + ((TIME) == ADC_SAMPLETIME_28CYCLES) || \ + ((TIME) == ADC_SAMPLETIME_56CYCLES) || \ + ((TIME) == ADC_SAMPLETIME_84CYCLES) || \ + ((TIME) == ADC_SAMPLETIME_112CYCLES) || \ + ((TIME) == ADC_SAMPLETIME_144CYCLES) || \ + ((TIME) == ADC_SAMPLETIME_480CYCLES)) +#define IS_ADC_EOCSelection(EOCSelection) (((EOCSelection) == ADC_EOC_SINGLE_CONV) || \ + ((EOCSelection) == ADC_EOC_SEQ_CONV) || \ + ((EOCSelection) == ADC_EOC_SINGLE_SEQ_CONV)) +#define IS_ADC_EVENT_TYPE(EVENT) (((EVENT) == ADC_AWD_EVENT) || \ + ((EVENT) == ADC_OVR_EVENT)) +#define IS_ADC_ANALOG_WATCHDOG(WATCHDOG) (((WATCHDOG) == ADC_ANALOGWATCHDOG_SINGLE_REG) || \ + ((WATCHDOG) == ADC_ANALOGWATCHDOG_SINGLE_INJEC) || \ + ((WATCHDOG) == ADC_ANALOGWATCHDOG_SINGLE_REGINJEC) || \ + ((WATCHDOG) == ADC_ANALOGWATCHDOG_ALL_REG) || \ + ((WATCHDOG) == ADC_ANALOGWATCHDOG_ALL_INJEC) || \ + ((WATCHDOG) == ADC_ANALOGWATCHDOG_ALL_REGINJEC) || \ + ((WATCHDOG) == ADC_ANALOGWATCHDOG_NONE)) +#define IS_ADC_CHANNELS_TYPE(CHANNEL_TYPE) (((CHANNEL_TYPE) == ADC_ALL_CHANNELS) || \ + ((CHANNEL_TYPE) == ADC_REGULAR_CHANNELS) || \ + ((CHANNEL_TYPE) == ADC_INJECTED_CHANNELS)) +#define IS_ADC_THRESHOLD(THRESHOLD) ((THRESHOLD) <= 0xFFFU) + +#define IS_ADC_REGULAR_LENGTH(LENGTH) (((LENGTH) >= 1U) && ((LENGTH) <= 16U)) +#define IS_ADC_REGULAR_RANK(RANK) (((RANK) >= 1U) && ((RANK) <= (16U))) +#define IS_ADC_REGULAR_DISC_NUMBER(NUMBER) (((NUMBER) >= 1U) && ((NUMBER) <= 8U)) +#define IS_ADC_RANGE(RESOLUTION, ADC_VALUE) \ + ((((RESOLUTION) == ADC_RESOLUTION_12B) && ((ADC_VALUE) <= 0x0FFFU)) || \ + (((RESOLUTION) == ADC_RESOLUTION_10B) && ((ADC_VALUE) <= 0x03FFU)) || \ + (((RESOLUTION) == ADC_RESOLUTION_8B) && ((ADC_VALUE) <= 0x00FFU)) || \ + (((RESOLUTION) == ADC_RESOLUTION_6B) && ((ADC_VALUE) <= 0x003FU))) + +/** + * @brief Set ADC Regular channel sequence length. + * @param _NbrOfConversion_ Regular channel sequence length. + * @retval None + */ +#define ADC_REGSEQ1(_NbrOfConversion_) (((_NbrOfConversion_) - (uint8_t)1U) << 20U) + +/** + * @brief Set the ADC's sample time for channel numbers between 10 and 18. + * @param _SAMPLETIME_ Sample time parameter. + * @param _CHANNELNB_ Channel number. + * @retval None + */ +#define ADC_SMPTIM1(_SAMPLETIME_, _CHANNELNB_) ((_SAMPLETIME_) << (3U * (((uint32_t)((uint16_t)(_CHANNELNB_))) - 10U))) + +/** + * @brief Set the ADC's sample time for channel numbers between 0 and 9. + * @param _SAMPLETIME_ Sample time parameter. + * @param _CHANNELNB_ Channel number. + * @retval None + */ +#define ADC_SMPTIM2(_SAMPLETIME_, _CHANNELNB_) ((_SAMPLETIME_) << (3U * ((uint32_t)((uint16_t)(_CHANNELNB_))))) + +/** + * @brief Set the selected regular channel rank for rank between 1 and 6. + * @param _CHANNELNB_ Channel number. + * @param _RANKNB_ Rank number. + * @retval None + */ +#define ADC_REGSEQ3_RK(_CHANNELNB_, _RANKNB_) (((uint32_t)((uint16_t)(_CHANNELNB_))) << (5U * ((_RANKNB_) - 1U))) + +/** + * @brief Set the selected regular channel rank for rank between 7 and 12. + * @param _CHANNELNB_ Channel number. + * @param _RANKNB_ Rank number. + * @retval None + */ +#define ADC_REGSEQ2_RK(_CHANNELNB_, _RANKNB_) (((uint32_t)((uint16_t)(_CHANNELNB_))) << (5U * ((_RANKNB_) - 7U))) + +/** + * @brief Set the selected regular channel rank for rank between 13 and 16. + * @param _CHANNELNB_ Channel number. + * @param _RANKNB_ Rank number. + * @retval None + */ +#define ADC_REGSEQ1_RK(_CHANNELNB_, _RANKNB_) (((uint32_t)((uint16_t)(_CHANNELNB_))) << (5U * ((_RANKNB_) - 13U))) + +/** + * @brief Enable ADC continuous conversion mode. + * @param _CONTINUOUS_MODE_ Continuous mode. + * @retval None + */ +#define ADC_CTRL2_CONTCENINUOUS(_CONTINUOUS_MODE_) ((_CONTINUOUS_MODE_) << 1U) + +/** + * @brief Configures the number of discontinuous conversions for the regular group channels. + * @param _NBR_DISCONTINUOUSCONV_ Number of discontinuous conversions. + * @retval None + */ +#define ADC_CTRL1_DISCONTINUOUS(_NBR_DISCONTINUOUSCONV_) (((_NBR_DISCONTINUOUSCONV_) - 1U) << ADC_CTRL1_DISCNUMCFG_Pos) + +/** + * @brief Enable ADC scan mode. + * @param _SCANCONV_MODE_ Scan conversion mode. + * @retval None + */ +#define ADC_CTRL1_SCANENCONV(_SCANCONV_MODE_) ((_SCANCONV_MODE_) << 8U) + +/** + * @brief Enable the ADC end of conversion selection. + * @param _EOCSelection_MODE_ End of conversion selection mode. + * @retval None + */ +#define ADC_CTRL2_EOCSELelection(_EOCSelection_MODE_) ((_EOCSelection_MODE_) << 10U) + +/** + * @brief Enable the ADC DMA continuous request. + * @param _DMAContReq_MODE_ DMA continuous request mode. + * @retval None + */ +#define ADC_CTRL2_DMAENContReq(_DMAContReq_MODE_) ((_DMAContReq_MODE_) << 9U) + +/** + * @brief Return resolution bits in CTRL1 register. + * @param __HANDLE__ ADC handle + * @retval None + */ +#define ADC_GET_RESOLUTION(__HANDLE__) (((__HANDLE__)->Instance->CTRL1) & ADC_CTRL1_RESSEL) + +/** + * @} + */ + +/* Private functions ---------------------------------------------------------*/ +/** @defgroup ADC_Private_Functions ADC Private Functions + * @{ + */ + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* APM32F4xx_DAL_ADC_H */ + + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_adc_ex.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_adc_ex.h new file mode 100644 index 0000000000..f6055f1576 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_adc_ex.h @@ -0,0 +1,412 @@ +/** + * @file apm32f4xx_dal_adc_ex.h + * @brief Header file of ADC DAL module. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2017 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef APM32F4xx_ADC_EX_H +#define APM32F4xx_ADC_EX_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal_def.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @addtogroup ADCEx + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ +/** @defgroup ADCEx_Exported_Types ADC Exported Types + * @{ + */ + +/** + * @brief ADC Configuration injected Channel structure definition + * @note Parameters of this structure are shared within 2 scopes: + * - Scope channel: InjectedChannel, InjectedRank, InjectedSamplingTime, InjectedOffset + * - Scope injected group (affects all channels of injected group): InjectedNbrOfConversion, InjectedDiscontinuousConvMode, + * AutoInjectedConv, ExternalTrigInjecConvEdge, ExternalTrigInjecConv. + * @note The setting of these parameters with function DAL_ADCEx_InjectedConfigChannel() is conditioned to ADC state. + * ADC state can be either: + * - For all parameters: ADC disabled + * - For all except parameters 'InjectedDiscontinuousConvMode' and 'AutoInjectedConv': ADC enabled without conversion on going on injected group. + * - For parameters 'ExternalTrigInjecConv' and 'ExternalTrigInjecConvEdge': ADC enabled, even with conversion on going on injected group. + */ +typedef struct +{ + uint32_t InjectedChannel; /*!< Selection of ADC channel to configure + This parameter can be a value of @ref ADC_channels + Note: Depending on devices, some channels may not be available on package pins. Refer to device datasheet for channels availability. */ + uint32_t InjectedRank; /*!< Rank in the injected group sequencer + This parameter must be a value of @ref ADCEx_injected_rank + Note: In case of need to disable a channel or change order of conversion sequencer, rank containing a previous channel setting can be overwritten by the new channel setting (or parameter number of conversions can be adjusted) */ + uint32_t InjectedSamplingTime; /*!< Sampling time value to be set for the selected channel. + Unit: ADC clock cycles + Conversion time is the addition of sampling time and processing time (12 ADC clock cycles at ADC resolution 12 bits, 11 cycles at 10 bits, 9 cycles at 8 bits, 7 cycles at 6 bits). + This parameter can be a value of @ref ADC_sampling_times + Caution: This parameter updates the parameter property of the channel, that can be used into regular and/or injected groups. + If this same channel has been previously configured in the other group (regular/injected), it will be updated to last setting. + Note: In case of usage of internal measurement channels (VrefInt/Vbat/TempSensor), + sampling time constraints must be respected (sampling time can be adjusted in function of ADC clock frequency and sampling time setting) + Refer to device datasheet for timings values, parameters TS_vrefint, TS_temp (values rough order: 4us min). */ + uint32_t InjectedOffset; /*!< Defines the offset to be subtracted from the raw converted data (for channels set on injected group only). + Offset value must be a positive number. + Depending of ADC resolution selected (12, 10, 8 or 6 bits), + this parameter must be a number between Min_Data = 0x000 and Max_Data = 0xFFF, 0x3FF, 0xFF or 0x3F respectively. */ + uint32_t InjectedNbrOfConversion; /*!< Specifies the number of ranks that will be converted within the injected group sequencer. + To use the injected group sequencer and convert several ranks, parameter 'ScanConvMode' must be enabled. + This parameter must be a number between Min_Data = 1 and Max_Data = 4. + Caution: this setting impacts the entire injected group. Therefore, call of DAL_ADCEx_InjectedConfigChannel() to + configure a channel on injected group can impact the configuration of other channels previously set. */ + FunctionalState InjectedDiscontinuousConvMode; /*!< Specifies whether the conversions sequence of injected group is performed in Complete-sequence/Discontinuous-sequence (main sequence subdivided in successive parts). + Discontinuous mode is used only if sequencer is enabled (parameter 'ScanConvMode'). If sequencer is disabled, this parameter is discarded. + Discontinuous mode can be enabled only if continuous mode is disabled. If continuous mode is enabled, this parameter setting is discarded. + This parameter can be set to ENABLE or DISABLE. + Note: For injected group, number of discontinuous ranks increment is fixed to one-by-one. + Caution: this setting impacts the entire injected group. Therefore, call of DAL_ADCEx_InjectedConfigChannel() to + configure a channel on injected group can impact the configuration of other channels previously set. */ + FunctionalState AutoInjectedConv; /*!< Enables or disables the selected ADC automatic injected group conversion after regular one + This parameter can be set to ENABLE or DISABLE. + Note: To use Automatic injected conversion, discontinuous mode must be disabled ('DiscontinuousConvMode' and 'InjectedDiscontinuousConvMode' set to DISABLE) + Note: To use Automatic injected conversion, injected group external triggers must be disabled ('ExternalTrigInjecConv' set to ADC_SOFTWARE_START) + Note: In case of DMA used with regular group: if DMA configured in normal mode (single shot) JAUTO will be stopped upon DMA transfer complete. + To maintain JAUTO always enabled, DMA must be configured in circular mode. + Caution: this setting impacts the entire injected group. Therefore, call of DAL_ADCEx_InjectedConfigChannel() to + configure a channel on injected group can impact the configuration of other channels previously set. */ + uint32_t ExternalTrigInjecConv; /*!< Selects the external event used to trigger the conversion start of injected group. + If set to ADC_INJECTED_SOFTWARE_START, external triggers are disabled. + If set to external trigger source, triggering is on event rising edge. + This parameter can be a value of @ref ADCEx_External_trigger_Source_Injected + Note: This parameter must be modified when ADC is disabled (before ADC start conversion or after ADC stop conversion). + If ADC is enabled, this parameter setting is bypassed without error reporting (as it can be the expected behaviour in case of another parameter update on the fly) + Caution: this setting impacts the entire injected group. Therefore, call of DAL_ADCEx_InjectedConfigChannel() to + configure a channel on injected group can impact the configuration of other channels previously set. */ + uint32_t ExternalTrigInjecConvEdge; /*!< Selects the external trigger edge of injected group. + This parameter can be a value of @ref ADCEx_External_trigger_edge_Injected. + If trigger is set to ADC_INJECTED_SOFTWARE_START, this parameter is discarded. + Caution: this setting impacts the entire injected group. Therefore, call of DAL_ADCEx_InjectedConfigChannel() to + configure a channel on injected group can impact the configuration of other channels previously set. */ +}ADC_InjectionConfTypeDef; + +/** + * @brief ADC Configuration multi-mode structure definition + */ +typedef struct +{ + uint32_t Mode; /*!< Configures the ADC to operate in independent or multi mode. + This parameter can be a value of @ref ADCEx_Common_mode */ + uint32_t DMAAccessMode; /*!< Configures the Direct memory access mode for multi ADC mode. + This parameter can be a value of @ref ADCEx_Direct_memory_access_mode_for_multi_mode */ + uint32_t TwoSamplingDelay; /*!< Configures the Delay between 2 sampling phases. + This parameter can be a value of @ref ADC_delay_between_2_sampling_phases */ +}ADC_MultiModeTypeDef; + +/** + * @} + */ + +/* Exported constants --------------------------------------------------------*/ +/** @defgroup ADCEx_Exported_Constants ADC Exported Constants + * @{ + */ + +/** @defgroup ADCEx_Common_mode ADC Common Mode + * @{ + */ +#define ADC_MODE_INDEPENDENT 0x00000000U +#define ADC_DUALMODE_REGSIMULT_INJECSIMULT ((uint32_t)ADC_CCTRL_ADCMSEL_0) +#define ADC_DUALMODE_REGSIMULT_ALTERTRIG ((uint32_t)ADC_CCTRL_ADCMSEL_1) +#define ADC_DUALMODE_INJECSIMULT ((uint32_t)(ADC_CCTRL_ADCMSEL_2 | ADC_CCTRL_ADCMSEL_0)) +#define ADC_DUALMODE_REGSIMULT ((uint32_t)(ADC_CCTRL_ADCMSEL_2 | ADC_CCTRL_ADCMSEL_1)) +#define ADC_DUALMODE_INTERL ((uint32_t)(ADC_CCTRL_ADCMSEL_2 | ADC_CCTRL_ADCMSEL_1 | ADC_CCTRL_ADCMSEL_0)) +#define ADC_DUALMODE_ALTERTRIG ((uint32_t)(ADC_CCTRL_ADCMSEL_3 | ADC_CCTRL_ADCMSEL_0)) +#define ADC_TRIPLEMODE_REGSIMULT_INJECSIMULT ((uint32_t)(ADC_CCTRL_ADCMSEL_4 | ADC_CCTRL_ADCMSEL_0)) +#define ADC_TRIPLEMODE_REGSIMULT_AlterTrig ((uint32_t)(ADC_CCTRL_ADCMSEL_4 | ADC_CCTRL_ADCMSEL_1)) +#define ADC_TRIPLEMODE_INJECSIMULT ((uint32_t)(ADC_CCTRL_ADCMSEL_4 | ADC_CCTRL_ADCMSEL_2 | ADC_CCTRL_ADCMSEL_0)) +#define ADC_TRIPLEMODE_REGSIMULT ((uint32_t)(ADC_CCTRL_ADCMSEL_4 | ADC_CCTRL_ADCMSEL_2 | ADC_CCTRL_ADCMSEL_1)) +#define ADC_TRIPLEMODE_INTERL ((uint32_t)(ADC_CCTRL_ADCMSEL_4 | ADC_CCTRL_ADCMSEL_2 | ADC_CCTRL_ADCMSEL_1 | ADC_CCTRL_ADCMSEL_0)) +#define ADC_TRIPLEMODE_ALTERTRIG ((uint32_t)(ADC_CCTRL_ADCMSEL_4 | ADC_CCTRL_ADCMSEL_3 | ADC_CCTRL_ADCMSEL_0)) +/** + * @} + */ + +/** @defgroup ADCEx_Direct_memory_access_mode_for_multi_mode ADC Direct Memory Access Mode For Multi Mode + * @{ + */ +#define ADC_DMAACCESSMODE_DISABLED 0x00000000U /*!< DMA mode disabled */ +#define ADC_DMAACCESSMODE_1 ((uint32_t)ADC_CCTRL_DMAMODE_0) /*!< DMA mode 1 enabled (2 / 3 half-words one by one - 1 then 2 then 3)*/ +#define ADC_DMAACCESSMODE_2 ((uint32_t)ADC_CCTRL_DMAMODE_1) /*!< DMA mode 2 enabled (2 / 3 half-words by pairs - 2&1 then 1&3 then 3&2)*/ +#define ADC_DMAACCESSMODE_3 ((uint32_t)ADC_CCTRL_DMAMODE) /*!< DMA mode 3 enabled (2 / 3 bytes by pairs - 2&1 then 1&3 then 3&2) */ +/** + * @} + */ + +/** @defgroup ADCEx_External_trigger_edge_Injected ADC External Trigger Edge Injected + * @{ + */ +#define ADC_EXTERNALTRIGINJECCONVEDGE_NONE 0x00000000U +#define ADC_EXTERNALTRIGINJECCONVEDGE_RISING ((uint32_t)ADC_CTRL2_INJEXTTRGEN_0) +#define ADC_EXTERNALTRIGINJECCONVEDGE_FALLING ((uint32_t)ADC_CTRL2_INJEXTTRGEN_1) +#define ADC_EXTERNALTRIGINJECCONVEDGE_RISINGFALLING ((uint32_t)ADC_CTRL2_INJEXTTRGEN) +/** + * @} + */ + +/** @defgroup ADCEx_External_trigger_Source_Injected ADC External Trigger Source Injected + * @{ + */ +#define ADC_EXTERNALTRIGINJECCONV_T1_CC4 0x00000000U +#define ADC_EXTERNALTRIGINJECCONV_T1_TRGO ((uint32_t)ADC_CTRL2_INJGEXTTRGSEL_0) +#define ADC_EXTERNALTRIGINJECCONV_T2_CC1 ((uint32_t)ADC_CTRL2_INJGEXTTRGSEL_1) +#define ADC_EXTERNALTRIGINJECCONV_T2_TRGO ((uint32_t)(ADC_CTRL2_INJGEXTTRGSEL_1 | ADC_CTRL2_INJGEXTTRGSEL_0)) +#define ADC_EXTERNALTRIGINJECCONV_T3_CC2 ((uint32_t)ADC_CTRL2_INJGEXTTRGSEL_2) +#define ADC_EXTERNALTRIGINJECCONV_T3_CC4 ((uint32_t)(ADC_CTRL2_INJGEXTTRGSEL_2 | ADC_CTRL2_INJGEXTTRGSEL_0)) +#define ADC_EXTERNALTRIGINJECCONV_T4_CC1 ((uint32_t)(ADC_CTRL2_INJGEXTTRGSEL_2 | ADC_CTRL2_INJGEXTTRGSEL_1)) +#define ADC_EXTERNALTRIGINJECCONV_T4_CC2 ((uint32_t)(ADC_CTRL2_INJGEXTTRGSEL_2 | ADC_CTRL2_INJGEXTTRGSEL_1 | ADC_CTRL2_INJGEXTTRGSEL_0)) +#define ADC_EXTERNALTRIGINJECCONV_T4_CC3 ((uint32_t)ADC_CTRL2_INJGEXTTRGSEL_3) +#define ADC_EXTERNALTRIGINJECCONV_T4_TRGO ((uint32_t)(ADC_CTRL2_INJGEXTTRGSEL_3 | ADC_CTRL2_INJGEXTTRGSEL_0)) +#define ADC_EXTERNALTRIGINJECCONV_T5_CC4 ((uint32_t)(ADC_CTRL2_INJGEXTTRGSEL_3 | ADC_CTRL2_INJGEXTTRGSEL_1)) +#define ADC_EXTERNALTRIGINJECCONV_T5_TRGO ((uint32_t)(ADC_CTRL2_INJGEXTTRGSEL_3 | ADC_CTRL2_INJGEXTTRGSEL_1 | ADC_CTRL2_INJGEXTTRGSEL_0)) +#define ADC_EXTERNALTRIGINJECCONV_T8_CC2 ((uint32_t)(ADC_CTRL2_INJGEXTTRGSEL_3 | ADC_CTRL2_INJGEXTTRGSEL_2)) +#define ADC_EXTERNALTRIGINJECCONV_T8_CC3 ((uint32_t)(ADC_CTRL2_INJGEXTTRGSEL_3 | ADC_CTRL2_INJGEXTTRGSEL_2 | ADC_CTRL2_INJGEXTTRGSEL_0)) +#define ADC_EXTERNALTRIGINJECCONV_T8_CC4 ((uint32_t)(ADC_CTRL2_INJGEXTTRGSEL_3 | ADC_CTRL2_INJGEXTTRGSEL_2 | ADC_CTRL2_INJGEXTTRGSEL_1)) +#define ADC_EXTERNALTRIGINJECCONV_EXT_IT15 ((uint32_t)ADC_CTRL2_INJGEXTTRGSEL) +#define ADC_INJECTED_SOFTWARE_START ((uint32_t)ADC_CTRL2_INJGEXTTRGSEL + 1U) +/** + * @} + */ + +/** @defgroup ADCEx_injected_rank ADC Injected Rank + * @{ + */ +#define ADC_INJECTED_RANK_1 0x00000001U +#define ADC_INJECTED_RANK_2 0x00000002U +#define ADC_INJECTED_RANK_3 0x00000003U +#define ADC_INJECTED_RANK_4 0x00000004U +/** + * @} + */ + +/** @defgroup ADCEx_channels ADC Specific Channels + * @{ + */ +#if defined(APM32F405xx) || defined(APM32F407xx) || defined(APM32F417xx) || defined(APM32F465xx) +#define ADC_CHANNEL_TEMPSENSOR ((uint32_t)ADC_CHANNEL_16) +#endif /* APM32F405xx || APM32F407xx || APM32F417xx || APM32F465xx */ + +#if defined(APM32F411xx) +#define ADC_CHANNEL_DIFFERENCIATION_TEMPSENSOR_VBAT 0x10000000U /* Dummy bit for driver internal usage, not used in ADC channel setting registers CTRL1 or REGSEQx */ +#define ADC_CHANNEL_TEMPSENSOR ((uint32_t)ADC_CHANNEL_18 | ADC_CHANNEL_DIFFERENCIATION_TEMPSENSOR_VBAT) +#endif /* APM32F411xx */ +/** + * @} + */ + + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ +/** @defgroup ADC_Exported_Macros ADC Exported Macros + * @{ + */ + +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup ADCEx_Exported_Functions + * @{ + */ + +/** @addtogroup ADCEx_Exported_Functions_Group1 + * @{ + */ + +/* I/O operation functions ******************************************************/ +DAL_StatusTypeDef DAL_ADCEx_InjectedStart(ADC_HandleTypeDef* hadc); +DAL_StatusTypeDef DAL_ADCEx_InjectedStop(ADC_HandleTypeDef* hadc); +DAL_StatusTypeDef DAL_ADCEx_InjectedPollForConversion(ADC_HandleTypeDef* hadc, uint32_t Timeout); +DAL_StatusTypeDef DAL_ADCEx_InjectedStart_IT(ADC_HandleTypeDef* hadc); +DAL_StatusTypeDef DAL_ADCEx_InjectedStop_IT(ADC_HandleTypeDef* hadc); +uint32_t DAL_ADCEx_InjectedGetValue(ADC_HandleTypeDef* hadc, uint32_t InjectedRank); +#if defined(ADC_MULTIMODE_SUPPORT) +DAL_StatusTypeDef DAL_ADCEx_MultiModeStart_DMA(ADC_HandleTypeDef* hadc, uint32_t* pData, uint32_t Length); +DAL_StatusTypeDef DAL_ADCEx_MultiModeStop_DMA(ADC_HandleTypeDef* hadc); +uint32_t DAL_ADCEx_MultiModeGetValue(ADC_HandleTypeDef* hadc); +#endif /* ADC_MULTIMODE_SUPPORT */ + +void DAL_ADCEx_InjectedConvCpltCallback(ADC_HandleTypeDef* hadc); + +/* Peripheral Control functions *************************************************/ +DAL_StatusTypeDef DAL_ADCEx_InjectedConfigChannel(ADC_HandleTypeDef* hadc,ADC_InjectionConfTypeDef* sConfigInjected); +#if defined(ADC_MULTIMODE_SUPPORT) +DAL_StatusTypeDef DAL_ADCEx_MultiModeConfigChannel(ADC_HandleTypeDef* hadc, ADC_MultiModeTypeDef* multimode); +#endif /* ADC_MULTIMODE_SUPPORT */ +/** + * @} + */ + +/** + * @} + */ +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/** @defgroup ADCEx_Private_Constants ADC Private Constants + * @{ + */ + +/** + * @} + */ + +/* Private macros ------------------------------------------------------------*/ +/** @defgroup ADCEx_Private_Macros ADC Private Macros + * @{ + */ +#if defined(APM32F405xx) || defined(APM32F407xx) || defined(APM32F417xx) || defined(APM32F465xx) +#define IS_ADC_CHANNEL(CHANNEL) ((CHANNEL) <= ADC_CHANNEL_18) +#endif /* APM32F405xx || APM32F407xx || APM32F417xx || APM32F465xx */ + +#if defined(APM32F411xx) +#define IS_ADC_CHANNEL(CHANNEL) (((CHANNEL) <= ADC_CHANNEL_18) || \ + ((CHANNEL) == ADC_CHANNEL_TEMPSENSOR)) +#endif /* APM32F411xx */ + +#define IS_ADC_MODE(MODE) (((MODE) == ADC_MODE_INDEPENDENT) || \ + ((MODE) == ADC_DUALMODE_REGSIMULT_INJECSIMULT) || \ + ((MODE) == ADC_DUALMODE_REGSIMULT_ALTERTRIG) || \ + ((MODE) == ADC_DUALMODE_INJECSIMULT) || \ + ((MODE) == ADC_DUALMODE_REGSIMULT) || \ + ((MODE) == ADC_DUALMODE_INTERL) || \ + ((MODE) == ADC_DUALMODE_ALTERTRIG) || \ + ((MODE) == ADC_TRIPLEMODE_REGSIMULT_INJECSIMULT) || \ + ((MODE) == ADC_TRIPLEMODE_REGSIMULT_AlterTrig) || \ + ((MODE) == ADC_TRIPLEMODE_INJECSIMULT) || \ + ((MODE) == ADC_TRIPLEMODE_REGSIMULT) || \ + ((MODE) == ADC_TRIPLEMODE_INTERL) || \ + ((MODE) == ADC_TRIPLEMODE_ALTERTRIG)) +#define IS_ADC_DMA_ACCESS_MODE(MODE) (((MODE) == ADC_DMAACCESSMODE_DISABLED) || \ + ((MODE) == ADC_DMAACCESSMODE_1) || \ + ((MODE) == ADC_DMAACCESSMODE_2) || \ + ((MODE) == ADC_DMAACCESSMODE_3)) +#define IS_ADC_EXT_INJEC_TRIG_EDGE(EDGE) (((EDGE) == ADC_EXTERNALTRIGINJECCONVEDGE_NONE) || \ + ((EDGE) == ADC_EXTERNALTRIGINJECCONVEDGE_RISING) || \ + ((EDGE) == ADC_EXTERNALTRIGINJECCONVEDGE_FALLING) || \ + ((EDGE) == ADC_EXTERNALTRIGINJECCONVEDGE_RISINGFALLING)) +#define IS_ADC_EXT_INJEC_TRIG(INJTRIG) (((INJTRIG) == ADC_EXTERNALTRIGINJECCONV_T1_CC4) || \ + ((INJTRIG) == ADC_EXTERNALTRIGINJECCONV_T1_TRGO) || \ + ((INJTRIG) == ADC_EXTERNALTRIGINJECCONV_T2_CC1) || \ + ((INJTRIG) == ADC_EXTERNALTRIGINJECCONV_T2_TRGO) || \ + ((INJTRIG) == ADC_EXTERNALTRIGINJECCONV_T3_CC2) || \ + ((INJTRIG) == ADC_EXTERNALTRIGINJECCONV_T3_CC4) || \ + ((INJTRIG) == ADC_EXTERNALTRIGINJECCONV_T4_CC1) || \ + ((INJTRIG) == ADC_EXTERNALTRIGINJECCONV_T4_CC2) || \ + ((INJTRIG) == ADC_EXTERNALTRIGINJECCONV_T4_CC3) || \ + ((INJTRIG) == ADC_EXTERNALTRIGINJECCONV_T4_TRGO) || \ + ((INJTRIG) == ADC_EXTERNALTRIGINJECCONV_T5_CC4) || \ + ((INJTRIG) == ADC_EXTERNALTRIGINJECCONV_T5_TRGO) || \ + ((INJTRIG) == ADC_EXTERNALTRIGINJECCONV_T8_CC2) || \ + ((INJTRIG) == ADC_EXTERNALTRIGINJECCONV_T8_CC3) || \ + ((INJTRIG) == ADC_EXTERNALTRIGINJECCONV_T8_CC4) || \ + ((INJTRIG) == ADC_EXTERNALTRIGINJECCONV_EXT_IT15)|| \ + ((INJTRIG) == ADC_INJECTED_SOFTWARE_START)) +#define IS_ADC_INJECTED_LENGTH(LENGTH) (((LENGTH) >= 1U) && ((LENGTH) <= 4U)) +#define IS_ADC_INJECTED_RANK(RANK) (((RANK) >= 1U) && ((RANK) <= 4U)) + +/** + * @brief Set the selected injected Channel rank. + * @param _CHANNELNB_ Channel number. + * @param _RANKNB_ Rank number. + * @param _JSQR_JL_ Sequence length. + * @retval None + */ +#define ADC_INJSEQ(_CHANNELNB_, _RANKNB_, _JSQR_JL_) (((uint32_t)((uint16_t)(_CHANNELNB_))) << (5U * (uint8_t)(((_RANKNB_) + 3U) - (_JSQR_JL_)))) + +/** + * @brief Defines if the selected ADC is within ADC common register ADC123 or ADC1 or ADC2 + * if available (ADC2, ADC3 availability depends on APM32 product) + * @param __HANDLE__ ADC handle + * @retval Common control register ADC123 or ADC12 or ADC1 + */ +#if defined(APM32F405xx) || defined(APM32F407xx) || defined(APM32F417xx) || defined(APM32F465xx) +#define ADC_COMMON_REGISTER(__HANDLE__) ADC123_COMMON +#elif defined(APM32F411xx) +#define ADC_COMMON_REGISTER(__HANDLE__) ((__HANDLE__)->Instance == ADC1 ? ADC1_COMMON : ADC2_COMMON) +#else +#define ADC_COMMON_REGISTER(__HANDLE__) ADC1_COMMON +#endif /* APM32F405xx || APM32F407xx || APM32F417xx || APM32F465xx */ +/** + * @} + */ + +/* Private functions ---------------------------------------------------------*/ +/** @defgroup ADCEx_Private_Functions ADC Private Functions + * @{ + */ + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* APM32F4xx_ADC_EX_H */ + + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_can.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_can.h new file mode 100644 index 0000000000..728641d8a3 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_can.h @@ -0,0 +1,868 @@ +/** + * + * @file apm32f4xx_dal_can.h + * @brief Header file of CAN DAL module. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef APM32F4xx_DAL_CAN_H +#define APM32F4xx_DAL_CAN_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal_def.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +#if defined (CAN1) +/** @addtogroup CAN + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ +/** @defgroup CAN_Exported_Types CAN Exported Types + * @{ + */ +/** + * @brief DAL State structures definition + */ +typedef enum +{ + DAL_CAN_STATE_RESET = 0x00U, /*!< CAN not yet initialized or disabled */ + DAL_CAN_STATE_READY = 0x01U, /*!< CAN initialized and ready for use */ + DAL_CAN_STATE_LISTENING = 0x02U, /*!< CAN receive process is ongoing */ + DAL_CAN_STATE_SLEEP_PENDING = 0x03U, /*!< CAN sleep request is pending */ + DAL_CAN_STATE_SLEEP_ACTIVE = 0x04U, /*!< CAN sleep mode is active */ + DAL_CAN_STATE_ERROR = 0x05U /*!< CAN error state */ + +} DAL_CAN_StateTypeDef; + +/** + * @brief CAN init structure definition + */ +typedef struct +{ + uint32_t Prescaler; /*!< Specifies the length of a time quantum. + This parameter must be a number between Min_Data = 1 and Max_Data = 1024. */ + + uint32_t Mode; /*!< Specifies the CAN operating mode. + This parameter can be a value of @ref CAN_operating_mode */ + + uint32_t SyncJumpWidth; /*!< Specifies the maximum number of time quanta the CAN hardware + is allowed to lengthen or shorten a bit to perform resynchronization. + This parameter can be a value of @ref CAN_synchronisation_jump_width */ + + uint32_t TimeSeg1; /*!< Specifies the number of time quanta in Bit Segment 1. + This parameter can be a value of @ref CAN_time_quantum_in_bit_segment_1 */ + + uint32_t TimeSeg2; /*!< Specifies the number of time quanta in Bit Segment 2. + This parameter can be a value of @ref CAN_time_quantum_in_bit_segment_2 */ + + FunctionalState TimeTriggeredMode; /*!< Enable or disable the time triggered communication mode. + This parameter can be set to ENABLE or DISABLE. */ + + FunctionalState AutoBusOff; /*!< Enable or disable the automatic bus-off management. + This parameter can be set to ENABLE or DISABLE. */ + + FunctionalState AutoWakeUp; /*!< Enable or disable the automatic wake-up mode. + This parameter can be set to ENABLE or DISABLE. */ + + FunctionalState AutoRetransmission; /*!< Enable or disable the non-automatic retransmission mode. + This parameter can be set to ENABLE or DISABLE. */ + + FunctionalState ReceiveFifoLocked; /*!< Enable or disable the Receive FIFO Locked mode. + This parameter can be set to ENABLE or DISABLE. */ + + FunctionalState TransmitFifoPriority;/*!< Enable or disable the transmit FIFO priority. + This parameter can be set to ENABLE or DISABLE. */ + +} CAN_InitTypeDef; + +/** + * @brief CAN filter configuration structure definition + */ +typedef struct +{ + uint32_t FilterIdHigh; /*!< Specifies the filter identification number (MSBs for a 32-bit + configuration, first one for a 16-bit configuration). + This parameter must be a number between Min_Data = 0x0000 and Max_Data = 0xFFFF. */ + + uint32_t FilterIdLow; /*!< Specifies the filter identification number (LSBs for a 32-bit + configuration, second one for a 16-bit configuration). + This parameter must be a number between Min_Data = 0x0000 and Max_Data = 0xFFFF. */ + + uint32_t FilterMaskIdHigh; /*!< Specifies the filter mask number or identification number, + according to the mode (MSBs for a 32-bit configuration, + first one for a 16-bit configuration). + This parameter must be a number between Min_Data = 0x0000 and Max_Data = 0xFFFF. */ + + uint32_t FilterMaskIdLow; /*!< Specifies the filter mask number or identification number, + according to the mode (LSBs for a 32-bit configuration, + second one for a 16-bit configuration). + This parameter must be a number between Min_Data = 0x0000 and Max_Data = 0xFFFF. */ + + uint32_t FilterFIFOAssignment; /*!< Specifies the FIFO (0 or 1U) which will be assigned to the filter. + This parameter can be a value of @ref CAN_filter_FIFO */ + + uint32_t FilterBank; /*!< Specifies the filter bank which will be initialized. + For single CAN instance(14 dedicated filter banks), + this parameter must be a number between Min_Data = 0 and Max_Data = 13. + For dual CAN instances(28 filter banks shared), + this parameter must be a number between Min_Data = 0 and Max_Data = 27. */ + + uint32_t FilterMode; /*!< Specifies the filter mode to be initialized. + This parameter can be a value of @ref CAN_filter_mode */ + + uint32_t FilterScale; /*!< Specifies the filter scale. + This parameter can be a value of @ref CAN_filter_scale */ + + uint32_t FilterActivation; /*!< Enable or disable the filter. + This parameter can be a value of @ref CAN_filter_activation */ + + uint32_t SlaveStartFilterBank; /*!< Select the start filter bank for the slave CAN instance. + For single CAN instances, this parameter is meaningless. + For dual CAN instances, all filter banks with lower index are assigned to master + CAN instance, whereas all filter banks with greater index are assigned to slave + CAN instance. + This parameter must be a number between Min_Data = 0 and Max_Data = 27. */ + +} CAN_FilterTypeDef; + +/** + * @brief CAN Tx message header structure definition + */ +typedef struct +{ + uint32_t StdId; /*!< Specifies the standard identifier. + This parameter must be a number between Min_Data = 0 and Max_Data = 0x7FF. */ + + uint32_t ExtId; /*!< Specifies the extended identifier. + This parameter must be a number between Min_Data = 0 and Max_Data = 0x1FFFFFFF. */ + + uint32_t IDE; /*!< Specifies the type of identifier for the message that will be transmitted. + This parameter can be a value of @ref CAN_identifier_type */ + + uint32_t RTR; /*!< Specifies the type of frame for the message that will be transmitted. + This parameter can be a value of @ref CAN_remote_transmission_request */ + + uint32_t DLC; /*!< Specifies the length of the frame that will be transmitted. + This parameter must be a number between Min_Data = 0 and Max_Data = 8. */ + + FunctionalState TransmitGlobalTime; /*!< Specifies whether the timestamp counter value captured on start + of frame transmission, is sent in DATA6 and DATA7 replacing pData[6] and pData[7]. + @note: Time Triggered Communication Mode must be enabled. + @note: DLC must be programmed as 8 bytes, in order these 2 bytes are sent. + This parameter can be set to ENABLE or DISABLE. */ + +} CAN_TxHeaderTypeDef; + +/** + * @brief CAN Rx message header structure definition + */ +typedef struct +{ + uint32_t StdId; /*!< Specifies the standard identifier. + This parameter must be a number between Min_Data = 0 and Max_Data = 0x7FF. */ + + uint32_t ExtId; /*!< Specifies the extended identifier. + This parameter must be a number between Min_Data = 0 and Max_Data = 0x1FFFFFFF. */ + + uint32_t IDE; /*!< Specifies the type of identifier for the message that will be transmitted. + This parameter can be a value of @ref CAN_identifier_type */ + + uint32_t RTR; /*!< Specifies the type of frame for the message that will be transmitted. + This parameter can be a value of @ref CAN_remote_transmission_request */ + + uint32_t DLC; /*!< Specifies the length of the frame that will be transmitted. + This parameter must be a number between Min_Data = 0 and Max_Data = 8. */ + + uint32_t Timestamp; /*!< Specifies the timestamp counter value captured on start of frame reception. + @note: Time Triggered Communication Mode must be enabled. + This parameter must be a number between Min_Data = 0 and Max_Data = 0xFFFF. */ + + uint32_t FilterMatchIndex; /*!< Specifies the index of matching acceptance filter element. + This parameter must be a number between Min_Data = 0 and Max_Data = 0xFF. */ + +} CAN_RxHeaderTypeDef; + +/** + * @brief CAN handle Structure definition + */ +typedef struct __CAN_HandleTypeDef +{ + CAN_TypeDef *Instance; /*!< Register base address */ + + CAN_InitTypeDef Init; /*!< CAN required parameters */ + + __IO DAL_CAN_StateTypeDef State; /*!< CAN communication state */ + + __IO uint32_t ErrorCode; /*!< CAN Error code. + This parameter can be a value of @ref CAN_Error_Code */ + +#if USE_DAL_CAN_REGISTER_CALLBACKS == 1 + void (* TxMailbox0CompleteCallback)(struct __CAN_HandleTypeDef *hcan);/*!< CAN Tx Mailbox 0 complete callback */ + void (* TxMailbox1CompleteCallback)(struct __CAN_HandleTypeDef *hcan);/*!< CAN Tx Mailbox 1 complete callback */ + void (* TxMailbox2CompleteCallback)(struct __CAN_HandleTypeDef *hcan);/*!< CAN Tx Mailbox 2 complete callback */ + void (* TxMailbox0AbortCallback)(struct __CAN_HandleTypeDef *hcan); /*!< CAN Tx Mailbox 0 abort callback */ + void (* TxMailbox1AbortCallback)(struct __CAN_HandleTypeDef *hcan); /*!< CAN Tx Mailbox 1 abort callback */ + void (* TxMailbox2AbortCallback)(struct __CAN_HandleTypeDef *hcan); /*!< CAN Tx Mailbox 2 abort callback */ + void (* RxFifo0MsgPendingCallback)(struct __CAN_HandleTypeDef *hcan); /*!< CAN Rx FIFO 0 msg pending callback */ + void (* RxFifo0FullCallback)(struct __CAN_HandleTypeDef *hcan); /*!< CAN Rx FIFO 0 full callback */ + void (* RxFifo1MsgPendingCallback)(struct __CAN_HandleTypeDef *hcan); /*!< CAN Rx FIFO 1 msg pending callback */ + void (* RxFifo1FullCallback)(struct __CAN_HandleTypeDef *hcan); /*!< CAN Rx FIFO 1 full callback */ + void (* SleepCallback)(struct __CAN_HandleTypeDef *hcan); /*!< CAN Sleep callback */ + void (* WakeUpFromRxMsgCallback)(struct __CAN_HandleTypeDef *hcan); /*!< CAN Wake Up from Rx msg callback */ + void (* ErrorCallback)(struct __CAN_HandleTypeDef *hcan); /*!< CAN Error callback */ + + void (* MspInitCallback)(struct __CAN_HandleTypeDef *hcan); /*!< CAN Msp Init callback */ + void (* MspDeInitCallback)(struct __CAN_HandleTypeDef *hcan); /*!< CAN Msp DeInit callback */ + +#endif /* (USE_DAL_CAN_REGISTER_CALLBACKS) */ +} CAN_HandleTypeDef; + +#if USE_DAL_CAN_REGISTER_CALLBACKS == 1 +/** + * @brief DAL CAN common Callback ID enumeration definition + */ +typedef enum +{ + DAL_CAN_TX_MAILBOX0_COMPLETE_CB_ID = 0x00U, /*!< CAN Tx Mailbox 0 complete callback ID */ + DAL_CAN_TX_MAILBOX1_COMPLETE_CB_ID = 0x01U, /*!< CAN Tx Mailbox 1 complete callback ID */ + DAL_CAN_TX_MAILBOX2_COMPLETE_CB_ID = 0x02U, /*!< CAN Tx Mailbox 2 complete callback ID */ + DAL_CAN_TX_MAILBOX0_ABORT_CB_ID = 0x03U, /*!< CAN Tx Mailbox 0 abort callback ID */ + DAL_CAN_TX_MAILBOX1_ABORT_CB_ID = 0x04U, /*!< CAN Tx Mailbox 1 abort callback ID */ + DAL_CAN_TX_MAILBOX2_ABORT_CB_ID = 0x05U, /*!< CAN Tx Mailbox 2 abort callback ID */ + DAL_CAN_RX_FIFO0_MSG_PENDING_CB_ID = 0x06U, /*!< CAN Rx FIFO 0 message pending callback ID */ + DAL_CAN_RX_FIFO0_FULL_CB_ID = 0x07U, /*!< CAN Rx FIFO 0 full callback ID */ + DAL_CAN_RX_FIFO1_MSG_PENDING_CB_ID = 0x08U, /*!< CAN Rx FIFO 1 message pending callback ID */ + DAL_CAN_RX_FIFO1_FULL_CB_ID = 0x09U, /*!< CAN Rx FIFO 1 full callback ID */ + DAL_CAN_SLEEP_CB_ID = 0x0AU, /*!< CAN Sleep callback ID */ + DAL_CAN_WAKEUP_FROM_RX_MSG_CB_ID = 0x0BU, /*!< CAN Wake Up from Rx msg callback ID */ + DAL_CAN_ERROR_CB_ID = 0x0CU, /*!< CAN Error callback ID */ + + DAL_CAN_MSPINIT_CB_ID = 0x0DU, /*!< CAN MspInit callback ID */ + DAL_CAN_MSPDEINIT_CB_ID = 0x0EU, /*!< CAN MspDeInit callback ID */ + +} DAL_CAN_CallbackIDTypeDef; + +/** + * @brief DAL CAN Callback pointer definition + */ +typedef void (*pCAN_CallbackTypeDef)(CAN_HandleTypeDef *hcan); /*!< pointer to a CAN callback function */ + +#endif /* USE_DAL_CAN_REGISTER_CALLBACKS */ +/** + * @} + */ + +/* Exported constants --------------------------------------------------------*/ + +/** @defgroup CAN_Exported_Constants CAN Exported Constants + * @{ + */ + +/** @defgroup CAN_Error_Code CAN Error Code + * @{ + */ +#define DAL_CAN_ERROR_NONE (0x00000000U) /*!< No error */ +#define DAL_CAN_ERROR_EWG (0x00000001U) /*!< Protocol Error Warning */ +#define DAL_CAN_ERROR_EPV (0x00000002U) /*!< Error Passive */ +#define DAL_CAN_ERROR_BOF (0x00000004U) /*!< Bus-off error */ +#define DAL_CAN_ERROR_STF (0x00000008U) /*!< Stuff error */ +#define DAL_CAN_ERROR_FOR (0x00000010U) /*!< Form error */ +#define DAL_CAN_ERROR_ACK (0x00000020U) /*!< Acknowledgment error */ +#define DAL_CAN_ERROR_BR (0x00000040U) /*!< Bit recessive error */ +#define DAL_CAN_ERROR_BD (0x00000080U) /*!< Bit dominant error */ +#define DAL_CAN_ERROR_CRC (0x00000100U) /*!< CRC error */ +#define DAL_CAN_ERROR_RX_FOV0 (0x00000200U) /*!< Rx FIFO0 overrun error */ +#define DAL_CAN_ERROR_RX_FOV1 (0x00000400U) /*!< Rx FIFO1 overrun error */ +#define DAL_CAN_ERROR_TX_ALST0 (0x00000800U) /*!< TxMailbox 0 transmit failure due to arbitration lost */ +#define DAL_CAN_ERROR_TX_TERR0 (0x00001000U) /*!< TxMailbox 0 transmit failure due to transmit error */ +#define DAL_CAN_ERROR_TX_ALST1 (0x00002000U) /*!< TxMailbox 1 transmit failure due to arbitration lost */ +#define DAL_CAN_ERROR_TX_TERR1 (0x00004000U) /*!< TxMailbox 1 transmit failure due to transmit error */ +#define DAL_CAN_ERROR_TX_ALST2 (0x00008000U) /*!< TxMailbox 2 transmit failure due to arbitration lost */ +#define DAL_CAN_ERROR_TX_TERR2 (0x00010000U) /*!< TxMailbox 2 transmit failure due to transmit error */ +#define DAL_CAN_ERROR_TIMEOUT (0x00020000U) /*!< Timeout error */ +#define DAL_CAN_ERROR_NOT_INITIALIZED (0x00040000U) /*!< Peripheral not initialized */ +#define DAL_CAN_ERROR_NOT_READY (0x00080000U) /*!< Peripheral not ready */ +#define DAL_CAN_ERROR_NOT_STARTED (0x00100000U) /*!< Peripheral not started */ +#define DAL_CAN_ERROR_PARAM (0x00200000U) /*!< Parameter error */ + +#if USE_DAL_CAN_REGISTER_CALLBACKS == 1 +#define DAL_CAN_ERROR_INVALID_CALLBACK (0x00400000U) /*!< Invalid Callback error */ +#endif /* USE_DAL_CAN_REGISTER_CALLBACKS */ +#define DAL_CAN_ERROR_INTERNAL (0x00800000U) /*!< Internal error */ + +/** + * @} + */ + +/** @defgroup CAN_InitStatus CAN InitStatus + * @{ + */ +#define CAN_INITSTATUS_FAILED (0x00000000U) /*!< CAN initialization failed */ +#define CAN_INITSTATUS_SUCCESS (0x00000001U) /*!< CAN initialization OK */ +/** + * @} + */ + +/** @defgroup CAN_operating_mode CAN Operating Mode + * @{ + */ +#define CAN_MODE_NORMAL (0x00000000U) /*!< Normal mode */ +#define CAN_MODE_LOOPBACK ((uint32_t)CAN_BITTIM_LBKMEN) /*!< Loopback mode */ +#define CAN_MODE_SILENT ((uint32_t)CAN_BITTIM_SILMEN) /*!< Silent mode */ +#define CAN_MODE_SILENT_LOOPBACK ((uint32_t)(CAN_BITTIM_LBKMEN | CAN_BITTIM_SILMEN)) /*!< Loopback combined with silent mode */ +/** + * @} + */ + + +/** @defgroup CAN_synchronisation_jump_width CAN Synchronization Jump Width + * @{ + */ +#define CAN_SJW_1TQ (0x00000000U) /*!< 1 time quantum */ +#define CAN_SJW_2TQ ((uint32_t)CAN_BITTIM_RSYNJW_0) /*!< 2 time quantum */ +#define CAN_SJW_3TQ ((uint32_t)CAN_BITTIM_RSYNJW_1) /*!< 3 time quantum */ +#define CAN_SJW_4TQ ((uint32_t)CAN_BITTIM_RSYNJW) /*!< 4 time quantum */ +/** + * @} + */ + +/** @defgroup CAN_time_quantum_in_bit_segment_1 CAN Time Quantum in Bit Segment 1 + * @{ + */ +#define CAN_BS1_1TQ (0x00000000U) /*!< 1 time quantum */ +#define CAN_BS1_2TQ ((uint32_t)CAN_BITTIM_TIMSEG1_0) /*!< 2 time quantum */ +#define CAN_BS1_3TQ ((uint32_t)CAN_BITTIM_TIMSEG1_1) /*!< 3 time quantum */ +#define CAN_BS1_4TQ ((uint32_t)(CAN_BITTIM_TIMSEG1_1 | CAN_BITTIM_TIMSEG1_0)) /*!< 4 time quantum */ +#define CAN_BS1_5TQ ((uint32_t)CAN_BITTIM_TIMSEG1_2) /*!< 5 time quantum */ +#define CAN_BS1_6TQ ((uint32_t)(CAN_BITTIM_TIMSEG1_2 | CAN_BITTIM_TIMSEG1_0)) /*!< 6 time quantum */ +#define CAN_BS1_7TQ ((uint32_t)(CAN_BITTIM_TIMSEG1_2 | CAN_BITTIM_TIMSEG1_1)) /*!< 7 time quantum */ +#define CAN_BS1_8TQ ((uint32_t)(CAN_BITTIM_TIMSEG1_2 | CAN_BITTIM_TIMSEG1_1 | CAN_BITTIM_TIMSEG1_0)) /*!< 8 time quantum */ +#define CAN_BS1_9TQ ((uint32_t)CAN_BITTIM_TIMSEG1_3) /*!< 9 time quantum */ +#define CAN_BS1_10TQ ((uint32_t)(CAN_BITTIM_TIMSEG1_3 | CAN_BITTIM_TIMSEG1_0)) /*!< 10 time quantum */ +#define CAN_BS1_11TQ ((uint32_t)(CAN_BITTIM_TIMSEG1_3 | CAN_BITTIM_TIMSEG1_1)) /*!< 11 time quantum */ +#define CAN_BS1_12TQ ((uint32_t)(CAN_BITTIM_TIMSEG1_3 | CAN_BITTIM_TIMSEG1_1 | CAN_BITTIM_TIMSEG1_0)) /*!< 12 time quantum */ +#define CAN_BS1_13TQ ((uint32_t)(CAN_BITTIM_TIMSEG1_3 | CAN_BITTIM_TIMSEG1_2)) /*!< 13 time quantum */ +#define CAN_BS1_14TQ ((uint32_t)(CAN_BITTIM_TIMSEG1_3 | CAN_BITTIM_TIMSEG1_2 | CAN_BITTIM_TIMSEG1_0)) /*!< 14 time quantum */ +#define CAN_BS1_15TQ ((uint32_t)(CAN_BITTIM_TIMSEG1_3 | CAN_BITTIM_TIMSEG1_2 | CAN_BITTIM_TIMSEG1_1)) /*!< 15 time quantum */ +#define CAN_BS1_16TQ ((uint32_t)CAN_BITTIM_TIMSEG1) /*!< 16 time quantum */ +/** + * @} + */ + +/** @defgroup CAN_time_quantum_in_bit_segment_2 CAN Time Quantum in Bit Segment 2 + * @{ + */ +#define CAN_BS2_1TQ (0x00000000U) /*!< 1 time quantum */ +#define CAN_BS2_2TQ ((uint32_t)CAN_BITTIM_TIMSEG2_0) /*!< 2 time quantum */ +#define CAN_BS2_3TQ ((uint32_t)CAN_BITTIM_TIMSEG2_1) /*!< 3 time quantum */ +#define CAN_BS2_4TQ ((uint32_t)(CAN_BITTIM_TIMSEG2_1 | CAN_BITTIM_TIMSEG2_0)) /*!< 4 time quantum */ +#define CAN_BS2_5TQ ((uint32_t)CAN_BITTIM_TIMSEG2_2) /*!< 5 time quantum */ +#define CAN_BS2_6TQ ((uint32_t)(CAN_BITTIM_TIMSEG2_2 | CAN_BITTIM_TIMSEG2_0)) /*!< 6 time quantum */ +#define CAN_BS2_7TQ ((uint32_t)(CAN_BITTIM_TIMSEG2_2 | CAN_BITTIM_TIMSEG2_1)) /*!< 7 time quantum */ +#define CAN_BS2_8TQ ((uint32_t)CAN_BITTIM_TIMSEG2) /*!< 8 time quantum */ +/** + * @} + */ + +/** @defgroup CAN_filter_mode CAN Filter Mode + * @{ + */ +#define CAN_FILTERMODE_IDMASK (0x00000000U) /*!< Identifier mask mode */ +#define CAN_FILTERMODE_IDLIST (0x00000001U) /*!< Identifier list mode */ +/** + * @} + */ + +/** @defgroup CAN_filter_scale CAN Filter Scale + * @{ + */ +#define CAN_FILTERSCALE_16BIT (0x00000000U) /*!< Two 16-bit filters */ +#define CAN_FILTERSCALE_32BIT (0x00000001U) /*!< One 32-bit filter */ +/** + * @} + */ + +/** @defgroup CAN_filter_activation CAN Filter Activation + * @{ + */ +#define CAN_FILTER_DISABLE (0x00000000U) /*!< Disable filter */ +#define CAN_FILTER_ENABLE (0x00000001U) /*!< Enable filter */ +/** + * @} + */ + +/** @defgroup CAN_filter_FIFO CAN Filter FIFO + * @{ + */ +#define CAN_FILTER_FIFO0 (0x00000000U) /*!< Filter FIFO 0 assignment for filter x */ +#define CAN_FILTER_FIFO1 (0x00000001U) /*!< Filter FIFO 1 assignment for filter x */ +/** + * @} + */ + +/** @defgroup CAN_identifier_type CAN Identifier Type + * @{ + */ +#define CAN_ID_STD (0x00000000U) /*!< Standard Id */ +#define CAN_ID_EXT (0x00000004U) /*!< Extended Id */ +/** + * @} + */ + +/** @defgroup CAN_remote_transmission_request CAN Remote Transmission Request + * @{ + */ +#define CAN_RTR_DATA (0x00000000U) /*!< Data frame */ +#define CAN_RTR_REMOTE (0x00000002U) /*!< Remote frame */ +/** + * @} + */ + +/** @defgroup CAN_receive_FIFO_number CAN Receive FIFO Number + * @{ + */ +#define CAN_RX_FIFO0 (0x00000000U) /*!< CAN receive FIFO 0 */ +#define CAN_RX_FIFO1 (0x00000001U) /*!< CAN receive FIFO 1 */ +/** + * @} + */ + +/** @defgroup CAN_Tx_Mailboxes CAN Tx Mailboxes + * @{ + */ +#define CAN_TX_MAILBOX0 (0x00000001U) /*!< Tx Mailbox 0 */ +#define CAN_TX_MAILBOX1 (0x00000002U) /*!< Tx Mailbox 1 */ +#define CAN_TX_MAILBOX2 (0x00000004U) /*!< Tx Mailbox 2 */ +/** + * @} + */ + +/** @defgroup CAN_flags CAN Flags + * @{ + */ +/* Transmit Flags */ +#define CAN_FLAG_RQCP0 (0x00000500U) /*!< Request complete MailBox 0 flag */ +#define CAN_FLAG_TXOK0 (0x00000501U) /*!< Transmission OK MailBox 0 flag */ +#define CAN_FLAG_ALST0 (0x00000502U) /*!< Arbitration Lost MailBox 0 flag */ +#define CAN_FLAG_TERR0 (0x00000503U) /*!< Transmission error MailBox 0 flag */ +#define CAN_FLAG_RQCP1 (0x00000508U) /*!< Request complete MailBox1 flag */ +#define CAN_FLAG_TXOK1 (0x00000509U) /*!< Transmission OK MailBox 1 flag */ +#define CAN_FLAG_ALST1 (0x0000050AU) /*!< Arbitration Lost MailBox 1 flag */ +#define CAN_FLAG_TERR1 (0x0000050BU) /*!< Transmission error MailBox 1 flag */ +#define CAN_FLAG_RQCP2 (0x00000510U) /*!< Request complete MailBox2 flag */ +#define CAN_FLAG_TXOK2 (0x00000511U) /*!< Transmission OK MailBox 2 flag */ +#define CAN_FLAG_ALST2 (0x00000512U) /*!< Arbitration Lost MailBox 2 flag */ +#define CAN_FLAG_TERR2 (0x00000513U) /*!< Transmission error MailBox 2 flag */ +#define CAN_FLAG_TME0 (0x0000051AU) /*!< Transmit mailbox 0 empty flag */ +#define CAN_FLAG_TME1 (0x0000051BU) /*!< Transmit mailbox 1 empty flag */ +#define CAN_FLAG_TME2 (0x0000051CU) /*!< Transmit mailbox 2 empty flag */ +#define CAN_FLAG_LOW0 (0x0000051DU) /*!< Lowest priority mailbox 0 flag */ +#define CAN_FLAG_LOW1 (0x0000051EU) /*!< Lowest priority mailbox 1 flag */ +#define CAN_FLAG_LOW2 (0x0000051FU) /*!< Lowest priority mailbox 2 flag */ + +/* Receive Flags */ +#define CAN_FLAG_FF0 (0x00000203U) /*!< RX FIFO 0 Full flag */ +#define CAN_FLAG_FOV0 (0x00000204U) /*!< RX FIFO 0 Overrun flag */ +#define CAN_FLAG_FF1 (0x00000403U) /*!< RX FIFO 1 Full flag */ +#define CAN_FLAG_FOV1 (0x00000404U) /*!< RX FIFO 1 Overrun flag */ + +/* Operating Mode Flags */ +#define CAN_FLAG_INAK (0x00000100U) /*!< Initialization acknowledge flag */ +#define CAN_FLAG_SLAK (0x00000101U) /*!< Sleep acknowledge flag */ +#define CAN_FLAG_ERRI (0x00000102U) /*!< Error flag */ +#define CAN_FLAG_WKU (0x00000103U) /*!< Wake up interrupt flag */ +#define CAN_FLAG_SLAKI (0x00000104U) /*!< Sleep acknowledge interrupt flag */ + +/* Error Flags */ +#define CAN_FLAG_EWG (0x00000300U) /*!< Error warning flag */ +#define CAN_FLAG_EPV (0x00000301U) /*!< Error passive flag */ +#define CAN_FLAG_BOF (0x00000302U) /*!< Bus-Off flag */ +/** + * @} + */ + + +/** @defgroup CAN_Interrupts CAN Interrupts + * @{ + */ +/* Transmit Interrupt */ +#define CAN_IT_TX_MAILBOX_EMPTY ((uint32_t)CAN_INTEN_TXMEIEN) /*!< Transmit mailbox empty interrupt */ + +/* Receive Interrupts */ +#define CAN_IT_RX_FIFO0_MSG_PENDING ((uint32_t)CAN_INTEN_FMIEN0) /*!< FIFO 0 message pending interrupt */ +#define CAN_IT_RX_FIFO0_FULL ((uint32_t)CAN_INTEN_FFULLIEN0) /*!< FIFO 0 full interrupt */ +#define CAN_IT_RX_FIFO0_OVERRUN ((uint32_t)CAN_INTEN_FOVRIEN0) /*!< FIFO 0 overrun interrupt */ +#define CAN_IT_RX_FIFO1_MSG_PENDING ((uint32_t)CAN_INTEN_FMIEN1) /*!< FIFO 1 message pending interrupt */ +#define CAN_IT_RX_FIFO1_FULL ((uint32_t)CAN_INTEN_FFULLIEN1) /*!< FIFO 1 full interrupt */ +#define CAN_IT_RX_FIFO1_OVERRUN ((uint32_t)CAN_INTEN_FOVRIEN1) /*!< FIFO 1 overrun interrupt */ + +/* Operating Mode Interrupts */ +#define CAN_IT_WAKEUP ((uint32_t)CAN_INTEN_WUPIEN) /*!< Wake-up interrupt */ +#define CAN_IT_SLEEP_ACK ((uint32_t)CAN_INTEN_SLEEPIEN) /*!< Sleep acknowledge interrupt */ + +/* Error Interrupts */ +#define CAN_IT_ERROR_WARNING ((uint32_t)CAN_INTEN_ERRWIEN) /*!< Error warning interrupt */ +#define CAN_IT_ERROR_PASSIVE ((uint32_t)CAN_INTEN_ERRPIEN) /*!< Error passive interrupt */ +#define CAN_IT_BUSOFF ((uint32_t)CAN_INTEN_BOFFIEN) /*!< Bus-off interrupt */ +#define CAN_IT_LAST_ERROR_CODE ((uint32_t)CAN_INTEN_LECIEN) /*!< Last error code interrupt */ +#define CAN_IT_ERROR ((uint32_t)CAN_INTEN_ERRIEN) /*!< Error Interrupt */ +/** + * @} + */ + +/** + * @} + */ + +/* Exported macros -----------------------------------------------------------*/ +/** @defgroup CAN_Exported_Macros CAN Exported Macros + * @{ + */ + +/** @brief Reset CAN handle state + * @param __HANDLE__ CAN handle. + * @retval None + */ +#if USE_DAL_CAN_REGISTER_CALLBACKS == 1 +#define __DAL_CAN_RESET_HANDLE_STATE(__HANDLE__) do{ \ + (__HANDLE__)->State = DAL_CAN_STATE_RESET; \ + (__HANDLE__)->MspInitCallback = NULL; \ + (__HANDLE__)->MspDeInitCallback = NULL; \ + } while(0) +#else +#define __DAL_CAN_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = DAL_CAN_STATE_RESET) +#endif /*USE_DAL_CAN_REGISTER_CALLBACKS */ + +/** + * @brief Enable the specified CAN interrupts. + * @param __HANDLE__ CAN handle. + * @param __INTERRUPT__ CAN Interrupt sources to enable. + * This parameter can be any combination of @arg CAN_Interrupts + * @retval None + */ +#define __DAL_CAN_ENABLE_IT(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->INTEN) |= (__INTERRUPT__)) + +/** + * @brief Disable the specified CAN interrupts. + * @param __HANDLE__ CAN handle. + * @param __INTERRUPT__ CAN Interrupt sources to disable. + * This parameter can be any combination of @arg CAN_Interrupts + * @retval None + */ +#define __DAL_CAN_DISABLE_IT(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->INTEN) &= ~(__INTERRUPT__)) + +/** @brief Check if the specified CAN interrupt source is enabled or disabled. + * @param __HANDLE__ specifies the CAN Handle. + * @param __INTERRUPT__ specifies the CAN interrupt source to check. + * This parameter can be a value of @arg CAN_Interrupts + * @retval The state of __IT__ (TRUE or FALSE). + */ +#define __DAL_CAN_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->INTEN) & (__INTERRUPT__)) + +/** @brief Check whether the specified CAN flag is set or not. + * @param __HANDLE__ specifies the CAN Handle. + * @param __FLAG__ specifies the flag to check. + * This parameter can be one of @arg CAN_flags + * @retval The state of __FLAG__ (TRUE or FALSE). + */ +#define __DAL_CAN_GET_FLAG(__HANDLE__, __FLAG__) \ + ((((__FLAG__) >> 8U) == 5U)? ((((__HANDLE__)->Instance->TXSTS) & (1U << ((__FLAG__) & CAN_FLAG_MASK))) == (1U << ((__FLAG__) & CAN_FLAG_MASK))): \ + (((__FLAG__) >> 8U) == 2U)? ((((__HANDLE__)->Instance->RXF0) & (1U << ((__FLAG__) & CAN_FLAG_MASK))) == (1U << ((__FLAG__) & CAN_FLAG_MASK))): \ + (((__FLAG__) >> 8U) == 4U)? ((((__HANDLE__)->Instance->RXF1) & (1U << ((__FLAG__) & CAN_FLAG_MASK))) == (1U << ((__FLAG__) & CAN_FLAG_MASK))): \ + (((__FLAG__) >> 8U) == 1U)? ((((__HANDLE__)->Instance->MSTS) & (1U << ((__FLAG__) & CAN_FLAG_MASK))) == (1U << ((__FLAG__) & CAN_FLAG_MASK))): \ + (((__FLAG__) >> 8U) == 3U)? ((((__HANDLE__)->Instance->ERRSTS) & (1U << ((__FLAG__) & CAN_FLAG_MASK))) == (1U << ((__FLAG__) & CAN_FLAG_MASK))): 0U) + +/** @brief Clear the specified CAN pending flag. + * @param __HANDLE__ specifies the CAN Handle. + * @param __FLAG__ specifies the flag to check. + * This parameter can be one of the following values: + * @arg CAN_FLAG_RQCP0: Request complete MailBox 0 Flag + * @arg CAN_FLAG_TXOK0: Transmission OK MailBox 0 Flag + * @arg CAN_FLAG_ALST0: Arbitration Lost MailBox 0 Flag + * @arg CAN_FLAG_TERR0: Transmission error MailBox 0 Flag + * @arg CAN_FLAG_RQCP1: Request complete MailBox 1 Flag + * @arg CAN_FLAG_TXOK1: Transmission OK MailBox 1 Flag + * @arg CAN_FLAG_ALST1: Arbitration Lost MailBox 1 Flag + * @arg CAN_FLAG_TERR1: Transmission error MailBox 1 Flag + * @arg CAN_FLAG_RQCP2: Request complete MailBox 2 Flag + * @arg CAN_FLAG_TXOK2: Transmission OK MailBox 2 Flag + * @arg CAN_FLAG_ALST2: Arbitration Lost MailBox 2 Flag + * @arg CAN_FLAG_TERR2: Transmission error MailBox 2 Flag + * @arg CAN_FLAG_FF0: RX FIFO 0 Full Flag + * @arg CAN_FLAG_FOV0: RX FIFO 0 Overrun Flag + * @arg CAN_FLAG_FF1: RX FIFO 1 Full Flag + * @arg CAN_FLAG_FOV1: RX FIFO 1 Overrun Flag + * @arg CAN_FLAG_WKUI: Wake up Interrupt Flag + * @arg CAN_FLAG_SLAKI: Sleep acknowledge Interrupt Flag + * @retval None + */ +#define __DAL_CAN_CLEAR_FLAG(__HANDLE__, __FLAG__) \ + ((((__FLAG__) >> 8U) == 5U)? (((__HANDLE__)->Instance->TXSTS) = (1U << ((__FLAG__) & CAN_FLAG_MASK))): \ + (((__FLAG__) >> 8U) == 2U)? (((__HANDLE__)->Instance->RXF0) = (1U << ((__FLAG__) & CAN_FLAG_MASK))): \ + (((__FLAG__) >> 8U) == 4U)? (((__HANDLE__)->Instance->RXF1) = (1U << ((__FLAG__) & CAN_FLAG_MASK))): \ + (((__FLAG__) >> 8U) == 1U)? (((__HANDLE__)->Instance->MSTS) = (1U << ((__FLAG__) & CAN_FLAG_MASK))): 0U) + +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup CAN_Exported_Functions CAN Exported Functions + * @{ + */ + +/** @addtogroup CAN_Exported_Functions_Group1 Initialization and de-initialization functions + * @brief Initialization and Configuration functions + * @{ + */ + +/* Initialization and de-initialization functions *****************************/ +DAL_StatusTypeDef DAL_CAN_Init(CAN_HandleTypeDef *hcan); +DAL_StatusTypeDef DAL_CAN_DeInit(CAN_HandleTypeDef *hcan); +void DAL_CAN_MspInit(CAN_HandleTypeDef *hcan); +void DAL_CAN_MspDeInit(CAN_HandleTypeDef *hcan); + +#if USE_DAL_CAN_REGISTER_CALLBACKS == 1 +/* Callbacks Register/UnRegister functions ***********************************/ +DAL_StatusTypeDef DAL_CAN_RegisterCallback(CAN_HandleTypeDef *hcan, DAL_CAN_CallbackIDTypeDef CallbackID, void (* pCallback)(CAN_HandleTypeDef *_hcan)); +DAL_StatusTypeDef DAL_CAN_UnRegisterCallback(CAN_HandleTypeDef *hcan, DAL_CAN_CallbackIDTypeDef CallbackID); + +#endif /* (USE_DAL_CAN_REGISTER_CALLBACKS) */ +/** + * @} + */ + +/** @addtogroup CAN_Exported_Functions_Group2 Configuration functions + * @brief Configuration functions + * @{ + */ + +/* Configuration functions ****************************************************/ +DAL_StatusTypeDef DAL_CAN_ConfigFilter(CAN_HandleTypeDef *hcan, CAN_FilterTypeDef *sFilterConfig); + +/** + * @} + */ + +/** @addtogroup CAN_Exported_Functions_Group3 Control functions + * @brief Control functions + * @{ + */ + +/* Control functions **********************************************************/ +DAL_StatusTypeDef DAL_CAN_Start(CAN_HandleTypeDef *hcan); +DAL_StatusTypeDef DAL_CAN_Stop(CAN_HandleTypeDef *hcan); +DAL_StatusTypeDef DAL_CAN_RequestSleep(CAN_HandleTypeDef *hcan); +DAL_StatusTypeDef DAL_CAN_WakeUp(CAN_HandleTypeDef *hcan); +uint32_t DAL_CAN_IsSleepActive(CAN_HandleTypeDef *hcan); +DAL_StatusTypeDef DAL_CAN_AddTxMessage(CAN_HandleTypeDef *hcan, CAN_TxHeaderTypeDef *pHeader, uint8_t aData[], uint32_t *pTxMailbox); +DAL_StatusTypeDef DAL_CAN_AbortTxRequest(CAN_HandleTypeDef *hcan, uint32_t TxMailboxes); +uint32_t DAL_CAN_GetTxMailboxesFreeLevel(CAN_HandleTypeDef *hcan); +uint32_t DAL_CAN_IsTxMessagePending(CAN_HandleTypeDef *hcan, uint32_t TxMailboxes); +uint32_t DAL_CAN_GetTxTimestamp(CAN_HandleTypeDef *hcan, uint32_t TxMailbox); +DAL_StatusTypeDef DAL_CAN_GetRxMessage(CAN_HandleTypeDef *hcan, uint32_t RxFifo, CAN_RxHeaderTypeDef *pHeader, uint8_t aData[]); +uint32_t DAL_CAN_GetRxFifoFillLevel(CAN_HandleTypeDef *hcan, uint32_t RxFifo); + +/** + * @} + */ + +/** @addtogroup CAN_Exported_Functions_Group4 Interrupts management + * @brief Interrupts management + * @{ + */ +/* Interrupts management ******************************************************/ +DAL_StatusTypeDef DAL_CAN_ActivateNotification(CAN_HandleTypeDef *hcan, uint32_t ActiveITs); +DAL_StatusTypeDef DAL_CAN_DeactivateNotification(CAN_HandleTypeDef *hcan, uint32_t InactiveITs); +void DAL_CAN_IRQHandler(CAN_HandleTypeDef *hcan); + +/** + * @} + */ + +/** @addtogroup CAN_Exported_Functions_Group5 Callback functions + * @brief Callback functions + * @{ + */ +/* Callbacks functions ********************************************************/ + +void DAL_CAN_TxMailbox0CompleteCallback(CAN_HandleTypeDef *hcan); +void DAL_CAN_TxMailbox1CompleteCallback(CAN_HandleTypeDef *hcan); +void DAL_CAN_TxMailbox2CompleteCallback(CAN_HandleTypeDef *hcan); +void DAL_CAN_TxMailbox0AbortCallback(CAN_HandleTypeDef *hcan); +void DAL_CAN_TxMailbox1AbortCallback(CAN_HandleTypeDef *hcan); +void DAL_CAN_TxMailbox2AbortCallback(CAN_HandleTypeDef *hcan); +void DAL_CAN_RxFifo0MsgPendingCallback(CAN_HandleTypeDef *hcan); +void DAL_CAN_RxFifo0FullCallback(CAN_HandleTypeDef *hcan); +void DAL_CAN_RxFifo1MsgPendingCallback(CAN_HandleTypeDef *hcan); +void DAL_CAN_RxFifo1FullCallback(CAN_HandleTypeDef *hcan); +void DAL_CAN_SleepCallback(CAN_HandleTypeDef *hcan); +void DAL_CAN_WakeUpFromRxMsgCallback(CAN_HandleTypeDef *hcan); +void DAL_CAN_ErrorCallback(CAN_HandleTypeDef *hcan); + +/** + * @} + */ + +/** @addtogroup CAN_Exported_Functions_Group6 Peripheral State and Error functions + * @brief CAN Peripheral State functions + * @{ + */ +/* Peripheral State and Error functions ***************************************/ +DAL_CAN_StateTypeDef DAL_CAN_GetState(CAN_HandleTypeDef *hcan); +uint32_t DAL_CAN_GetError(CAN_HandleTypeDef *hcan); +DAL_StatusTypeDef DAL_CAN_ResetError(CAN_HandleTypeDef *hcan); + +/** + * @} + */ + +/** + * @} + */ + +/* Private types -------------------------------------------------------------*/ +/** @defgroup CAN_Private_Types CAN Private Types + * @{ + */ + +/** + * @} + */ + +/* Private variables ---------------------------------------------------------*/ +/** @defgroup CAN_Private_Variables CAN Private Variables + * @{ + */ + +/** + * @} + */ + +/* Private constants ---------------------------------------------------------*/ +/** @defgroup CAN_Private_Constants CAN Private Constants + * @{ + */ +#define CAN_FLAG_MASK (0x000000FFU) +/** + * @} + */ + +/* Private Macros -----------------------------------------------------------*/ +/** @defgroup CAN_Private_Macros CAN Private Macros + * @{ + */ + +#define IS_CAN_MODE(MODE) (((MODE) == CAN_MODE_NORMAL) || \ + ((MODE) == CAN_MODE_LOOPBACK)|| \ + ((MODE) == CAN_MODE_SILENT) || \ + ((MODE) == CAN_MODE_SILENT_LOOPBACK)) +#define IS_CAN_SJW(SJW) (((SJW) == CAN_SJW_1TQ) || ((SJW) == CAN_SJW_2TQ) || \ + ((SJW) == CAN_SJW_3TQ) || ((SJW) == CAN_SJW_4TQ)) +#define IS_CAN_BS1(BS1) (((BS1) == CAN_BS1_1TQ) || ((BS1) == CAN_BS1_2TQ) || \ + ((BS1) == CAN_BS1_3TQ) || ((BS1) == CAN_BS1_4TQ) || \ + ((BS1) == CAN_BS1_5TQ) || ((BS1) == CAN_BS1_6TQ) || \ + ((BS1) == CAN_BS1_7TQ) || ((BS1) == CAN_BS1_8TQ) || \ + ((BS1) == CAN_BS1_9TQ) || ((BS1) == CAN_BS1_10TQ)|| \ + ((BS1) == CAN_BS1_11TQ)|| ((BS1) == CAN_BS1_12TQ)|| \ + ((BS1) == CAN_BS1_13TQ)|| ((BS1) == CAN_BS1_14TQ)|| \ + ((BS1) == CAN_BS1_15TQ)|| ((BS1) == CAN_BS1_16TQ)) +#define IS_CAN_BS2(BS2) (((BS2) == CAN_BS2_1TQ) || ((BS2) == CAN_BS2_2TQ) || \ + ((BS2) == CAN_BS2_3TQ) || ((BS2) == CAN_BS2_4TQ) || \ + ((BS2) == CAN_BS2_5TQ) || ((BS2) == CAN_BS2_6TQ) || \ + ((BS2) == CAN_BS2_7TQ) || ((BS2) == CAN_BS2_8TQ)) +#define IS_CAN_PRESCALER(PRESCALER) (((PRESCALER) >= 1U) && ((PRESCALER) <= 1024U)) +#define IS_CAN_FILTER_ID_HALFWORD(HALFWORD) ((HALFWORD) <= 0xFFFFU) +#define IS_CAN_FILTER_BANK_DUAL(BANK) ((BANK) <= 27U) +#define IS_CAN_FILTER_BANK_SINGLE(BANK) ((BANK) <= 13U) +#define IS_CAN_FILTER_MODE(MODE) (((MODE) == CAN_FILTERMODE_IDMASK) || \ + ((MODE) == CAN_FILTERMODE_IDLIST)) +#define IS_CAN_FILTER_SCALE(SCALE) (((SCALE) == CAN_FILTERSCALE_16BIT) || \ + ((SCALE) == CAN_FILTERSCALE_32BIT)) +#define IS_CAN_FILTER_ACTIVATION(ACTIVATION) (((ACTIVATION) == CAN_FILTER_DISABLE) || \ + ((ACTIVATION) == CAN_FILTER_ENABLE)) +#define IS_CAN_FILTER_FIFO(FIFO) (((FIFO) == CAN_FILTER_FIFO0) || \ + ((FIFO) == CAN_FILTER_FIFO1)) +#define IS_CAN_TX_MAILBOX(TRANSMITMAILBOX) (((TRANSMITMAILBOX) == CAN_TX_MAILBOX0 ) || \ + ((TRANSMITMAILBOX) == CAN_TX_MAILBOX1 ) || \ + ((TRANSMITMAILBOX) == CAN_TX_MAILBOX2 )) +#define IS_CAN_TX_MAILBOX_LIST(TRANSMITMAILBOX) ((TRANSMITMAILBOX) <= (CAN_TX_MAILBOX0 | CAN_TX_MAILBOX1 | CAN_TX_MAILBOX2)) +#define IS_CAN_STDID(STDID) ((STDID) <= 0x7FFU) +#define IS_CAN_EXTID(EXTID) ((EXTID) <= 0x1FFFFFFFU) +#define IS_CAN_DLC(DLC) ((DLC) <= 8U) +#define IS_CAN_IDTYPE(IDTYPE) (((IDTYPE) == CAN_ID_STD) || \ + ((IDTYPE) == CAN_ID_EXT)) +#define IS_CAN_RTR(RTR) (((RTR) == CAN_RTR_DATA) || ((RTR) == CAN_RTR_REMOTE)) +#define IS_CAN_RX_FIFO(FIFO) (((FIFO) == CAN_RX_FIFO0) || ((FIFO) == CAN_RX_FIFO1)) +#define IS_CAN_IT(IT) ((IT) <= (CAN_IT_TX_MAILBOX_EMPTY | CAN_IT_RX_FIFO0_MSG_PENDING | \ + CAN_IT_RX_FIFO0_FULL | CAN_IT_RX_FIFO0_OVERRUN | \ + CAN_IT_RX_FIFO1_MSG_PENDING | CAN_IT_RX_FIFO1_FULL | \ + CAN_IT_RX_FIFO1_OVERRUN | CAN_IT_WAKEUP | \ + CAN_IT_SLEEP_ACK | CAN_IT_ERROR_WARNING | \ + CAN_IT_ERROR_PASSIVE | CAN_IT_BUSOFF | \ + CAN_IT_LAST_ERROR_CODE | CAN_IT_ERROR)) + +/** + * @} + */ +/* End of private macros -----------------------------------------------------*/ + +/** + * @} + */ + + +#endif /* CAN1 */ +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* APM32F4xx_DAL_CAN_H */ diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_cfg_template.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_cfg_template.h new file mode 100644 index 0000000000..38f926365b --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_cfg_template.h @@ -0,0 +1,361 @@ +/** + * + * @file apm32f4xx_dal_cfg_template.h + * @brief DAL configuration template file. + * This file should be copied to the application folder and renamed + * to apm32f4xx_dal_cfg.h. + * + * @attention + * + * Copyright (C) 2023 Geehy Semiconductor + * + * You may not use this file except in compliance with the + * GEEHY COPYRIGHT NOTICE (GEEHY SOFTWARE PACKAGE LICENSE). + * + * The program is only for reference, which is distributed in the hope + * that it will be useful and instructional for customers to develop + * their software. Unless required by applicable law or agreed to in + * writing, the program is distributed on an "AS IS" BASIS, WITHOUT + * ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied. + * See the GEEHY SOFTWARE PACKAGE LICENSE for the governing permissions + * and limitations under the License. + * + */ + +/* Define to prevent recursive inclusion */ +#ifndef APM32F4xx_DAL_CFG_H +#define APM32F4xx_DAL_CFG_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Configuration settings for log component */ +#define USE_LOG_COMPONENT 0U +/* Include log header file */ +#include "apm32f4xx_dal_log.h" + +/* Configuration settings for assert enable */ +/* #define USE_FULL_ASSERT 1U */ + +/* DAL module configuration */ +#define DAL_MODULE_ENABLED +#define DAL_ADC_MODULE_ENABLED +#define DAL_CAN_MODULE_ENABLED +#define DAL_CRC_MODULE_ENABLED +#define DAL_CRYP_MODULE_ENABLED +#define DAL_COMP_MODULE_ENABLED +#define DAL_DAC_MODULE_ENABLED +#define DAL_DCI_MODULE_ENABLED +#define DAL_DMA_MODULE_ENABLED +#define DAL_ETH_MODULE_ENABLED +#define DAL_FLASH_MODULE_ENABLED +#define DAL_NAND_MODULE_ENABLED +#define DAL_NOR_MODULE_ENABLED +#define DAL_PCCARD_MODULE_ENABLED +#define DAL_SRAM_MODULE_ENABLED +#define DAL_SDRAM_MODULE_ENABLED +#define DAL_HASH_MODULE_ENABLED +#define DAL_GPIO_MODULE_ENABLED +#define DAL_EINT_MODULE_ENABLED +#define DAL_I2C_MODULE_ENABLED +#define DAL_SMBUS_MODULE_ENABLED +#define DAL_I2S_MODULE_ENABLED +#define DAL_IWDT_MODULE_ENABLED +#define DAL_PMU_MODULE_ENABLED +#define DAL_QSPI_MODULE_ENABLED +#define DAL_RCM_MODULE_ENABLED +#define DAL_RNG_MODULE_ENABLED +#define DAL_RTC_MODULE_ENABLED +#define DAL_SD_MODULE_ENABLED +#define DAL_SPI_MODULE_ENABLED +#define DAL_TMR_MODULE_ENABLED +#define DAL_UART_MODULE_ENABLED +#define DAL_USART_MODULE_ENABLED +#define DAL_IRDA_MODULE_ENABLED +#define DAL_SMARTCARD_MODULE_ENABLED +#define DAL_WWDT_MODULE_ENABLED +#define DAL_CORTEX_MODULE_ENABLED +#define DAL_PCD_MODULE_ENABLED +#define DAL_HCD_MODULE_ENABLED +#define DAL_MMC_MODULE_ENABLED + +/* Value of the external high speed oscillator in Hz */ +#if !defined (HSE_VALUE) + #define HSE_VALUE 8000000U +#endif /* HSE_VALUE */ + +/* Timeout for external high speed oscillator in ms */ +#if !defined (HSE_STARTUP_TIMEOUT) + #define HSE_STARTUP_TIMEOUT 100U +#endif /* HSE_STARTUP_TIMEOUT */ + +/* Value of the internal high speed oscillator in Hz */ +#if !defined (HSI_VALUE) + #define HSI_VALUE 16000000U +#endif /* HSI_VALUE */ + +/* Value of the internal low speed oscillator in Hz */ +#if !defined (LSI_VALUE) + #define LSI_VALUE 32000U +#endif /* LSI_VALUE */ + +/* Value of the external low speed oscillator in Hz */ +#if !defined (LSE_VALUE) + #define LSE_VALUE 32768U +#endif /* LSE_VALUE */ + +/* Timeout for external low speed oscillator in ms */ +#if !defined (LSE_STARTUP_TIMEOUT) + #define LSE_STARTUP_TIMEOUT 5000U +#endif /* LSE_STARTUP_TIMEOUT */ + +/* Value of the external high speed oscillator in Hz for I2S peripheral */ +#if !defined (EXTERNAL_CLOCK_VALUE) + #define EXTERNAL_CLOCK_VALUE 12288000U +#endif /* EXTERNAL_CLOCK_VALUE */ + +/* System Configuration */ +#define VDD_VALUE 3300U /*!< Value of VDD in mv */ +#define TICK_INT_PRIORITY 0x0FU /*!< tick interrupt priority */ +#define USE_RTOS 0U +#define PREFETCH_ENABLE 1U +#define INSTRUCTION_CACHE_ENABLE 1U +#define DATA_CACHE_ENABLE 1U + +/* DAL peripheral register callbacks */ +#define USE_DAL_ADC_REGISTER_CALLBACKS 0U /* ADC register callback disabled */ +#define USE_DAL_CAN_REGISTER_CALLBACKS 0U /* CAN register callback disabled */ +#define USE_DAL_COMP_REGISTER_CALLBACKS 0U /* COMP register callback disabled */ +#define USE_DAL_CRYP_REGISTER_CALLBACKS 0U /* CRYP register callback disabled */ +#define USE_DAL_DAC_REGISTER_CALLBACKS 0U /* DAC register callback disabled */ +#define USE_DAL_DCI_REGISTER_CALLBACKS 0U /* DCI register callback disabled */ +#define USE_DAL_ETH_REGISTER_CALLBACKS 0U /* ETH register callback disabled */ +#define USE_DAL_HASH_REGISTER_CALLBACKS 0U /* HASH register callback disabled */ +#define USE_DAL_HCD_REGISTER_CALLBACKS 0U /* HCD register callback disabled */ +#define USE_DAL_I2C_REGISTER_CALLBACKS 0U /* I2C register callback disabled */ +#define USE_DAL_I2S_REGISTER_CALLBACKS 0U /* I2S register callback disabled */ +#define USE_DAL_IRDA_REGISTER_CALLBACKS 0U /* IRDA register callback disabled */ +#define USE_DAL_MMC_REGISTER_CALLBACKS 0U /* MMC register callback disabled */ +#define USE_DAL_NAND_REGISTER_CALLBACKS 0U /* NAND register callback disabled */ +#define USE_DAL_NOR_REGISTER_CALLBACKS 0U /* NOR register callback disabled */ +#define USE_DAL_PCCARD_REGISTER_CALLBACKS 0U /* PCCARD register callback disabled */ +#define USE_DAL_PCD_REGISTER_CALLBACKS 0U /* PCD register callback disabled */ +#define USE_DAL_QSPI_REGISTER_CALLBACKS 0U /* QSPI register callback disabled */ +#define USE_DAL_RNG_REGISTER_CALLBACKS 0U /* RNG register callback disabled */ +#define USE_DAL_RTC_REGISTER_CALLBACKS 0U /* RTC register callback disabled */ +#define USE_DAL_SD_REGISTER_CALLBACKS 0U /* SD register callback disabled */ +#define USE_DAL_SMARTCARD_REGISTER_CALLBACKS 0U /* SMARTCARD register callback disabled */ +#define USE_DAL_SDRAM_REGISTER_CALLBACKS 0U /* SDRAM register callback disabled */ +#define USE_DAL_SRAM_REGISTER_CALLBACKS 0U /* SRAM register callback disabled */ +#define USE_DAL_SMBUS_REGISTER_CALLBACKS 0U /* SMBUS register callback disabled */ +#define USE_DAL_SPI_REGISTER_CALLBACKS 0U /* SPI register callback disabled */ +#define USE_DAL_TMR_REGISTER_CALLBACKS 0U /* TMR register callback disabled */ +#define USE_DAL_UART_REGISTER_CALLBACKS 0U /* UART register callback disabled */ +#define USE_DAL_USART_REGISTER_CALLBACKS 0U /* USART register callback disabled */ +#define USE_DAL_WWDT_REGISTER_CALLBACKS 0U /* WWDT register callback disabled */ + +/* Ethernet peripheral configuration */ +/* Addr and buffer size */ + +/* MAC ADDRESS */ +#define ETH_MAC_ADDR_0 2U +#define ETH_MAC_ADDR_1 0U +#define ETH_MAC_ADDR_2 0U +#define ETH_MAC_ADDR_3 0U +#define ETH_MAC_ADDR_4 0U +#define ETH_MAC_ADDR_5 0U + +/* Ethernet driver buffers size and number */ +#define ETH_BUFFER_SIZE_RX ETH_MAX_PACKET_SIZE /* Buffer size for receive */ +#define ETH_BUFFER_SIZE_TX ETH_MAX_PACKET_SIZE /* Buffer size for transmit */ +#define ETH_BUFFER_NUMBER_RX 4U /* 4 Rx buffers of size ETH_BUFFER_SIZE_RX */ +#define ETH_BUFFER_NUMBER_TX 4U /* 4 Tx buffers of size ETH_BUFFER_SIZE_TX */ + +/* Delay and timeout */ + +/* PHY Reset MAX Delay */ +#define EXT_PHY_RESET_MAX_DELAY 0x000000FFU +/* PHY Configuration MAX Delay */ +#define EXT_PHY_CONFIG_MAX_DELAY 0x00000FFFU + +#define EXT_PHY_READ_TIMEOUT 0x0000FFFFU +#define EXT_PHY_WRITE_TIMEOUT 0x0000FFFFU + +/* SPI peripheral configuration */ + +/* SPI CRC FEATURE */ +#define USE_SPI_CRC 1U + +/* Include module's header file */ +#ifdef DAL_RCM_MODULE_ENABLED + #include "apm32f4xx_dal_rcm.h" +#endif /* DAL_RCM_MODULE_ENABLED */ + +#ifdef DAL_GPIO_MODULE_ENABLED + #include "apm32f4xx_dal_gpio.h" +#endif /* DAL_GPIO_MODULE_ENABLED */ + +#ifdef DAL_EINT_MODULE_ENABLED + #include "apm32f4xx_dal_eint.h" +#endif /* DAL_EINT_MODULE_ENABLED */ + +#ifdef DAL_DMA_MODULE_ENABLED + #include "apm32f4xx_dal_dma.h" +#endif /* DAL_DMA_MODULE_ENABLED */ + +#ifdef DAL_CORTEX_MODULE_ENABLED + #include "apm32f4xx_dal_cortex.h" +#endif /* DAL_CORTEX_MODULE_ENABLED */ + +#ifdef DAL_ADC_MODULE_ENABLED + #include "apm32f4xx_dal_adc.h" +#endif /* DAL_ADC_MODULE_ENABLED */ + +#ifdef DAL_CAN_MODULE_ENABLED + #include "apm32f4xx_dal_can.h" +#endif /* DAL_CAN_MODULE_ENABLED */ + +#ifdef DAL_CRC_MODULE_ENABLED + #include "apm32f4xx_dal_crc.h" +#endif /* DAL_CRC_MODULE_ENABLED */ + +#ifdef DAL_CRYP_MODULE_ENABLED + #include "apm32f4xx_dal_cryp.h" +#endif /* DAL_CRYP_MODULE_ENABLED */ + +#ifdef DAL_COMP_MODULE_ENABLED + #include "apm32f4xx_dal_comp.h" +#endif /* DAL_COMP_MODULE_ENABLED */ + +#ifdef DAL_DAC_MODULE_ENABLED + #include "apm32f4xx_dal_dac.h" +#endif /* DAL_DAC_MODULE_ENABLED */ + +#ifdef DAL_DCI_MODULE_ENABLED + #include "apm32f4xx_dal_dci.h" +#endif /* DAL_DCI_MODULE_ENABLED */ + +#ifdef DAL_ETH_MODULE_ENABLED + #include "apm32f4xx_dal_eth.h" +#endif /* DAL_ETH_MODULE_ENABLED */ + +#ifdef DAL_FLASH_MODULE_ENABLED + #include "apm32f4xx_dal_flash.h" +#endif /* DAL_FLASH_MODULE_ENABLED */ + +#ifdef DAL_HASH_MODULE_ENABLED + #include "apm32f4xx_dal_hash.h" +#endif /* DAL_HASH_MODULE_ENABLED */ + +#ifdef DAL_HCD_MODULE_ENABLED + #include "apm32f4xx_dal_hcd.h" +#endif /* DAL_HCD_MODULE_ENABLED */ + +#ifdef DAL_I2C_MODULE_ENABLED + #include "apm32f4xx_dal_i2c.h" +#endif /* DAL_I2C_MODULE_ENABLED */ + +#ifdef DAL_I2S_MODULE_ENABLED + #include "apm32f4xx_dal_i2s.h" +#endif /* DAL_I2S_MODULE_ENABLED */ + +#ifdef DAL_IRDA_MODULE_ENABLED + #include "apm32f4xx_dal_irda.h" +#endif /* DAL_IRDA_MODULE_ENABLED */ + +#ifdef DAL_MMC_MODULE_ENABLED + #include "apm32f4xx_dal_mmc.h" +#endif /* DAL_MMC_MODULE_ENABLED */ + +#ifdef DAL_NAND_MODULE_ENABLED + #include "apm32f4xx_dal_nand.h" +#endif /* DAL_NAND_MODULE_ENABLED */ + +#ifdef DAL_NOR_MODULE_ENABLED + #include "apm32f4xx_dal_nor.h" +#endif /* DAL_NOR_MODULE_ENABLED */ + +#ifdef DAL_PCCARD_MODULE_ENABLED + #include "apm32f4xx_dal_pccard.h" +#endif /* DAL_PCCARD_MODULE_ENABLED */ + +#ifdef DAL_PCD_MODULE_ENABLED + #include "apm32f4xx_dal_pcd.h" +#endif /* DAL_PCD_MODULE_ENABLED */ + +#ifdef DAL_PMU_MODULE_ENABLED + #include "apm32f4xx_dal_pmu.h" +#endif /* DAL_PMU_MODULE_ENABLED */ + +#ifdef DAL_QSPI_MODULE_ENABLED + #include "apm32f4xx_dal_qspi.h" +#endif /* DAL_QSPI_MODULE_ENABLED */ + +#ifdef DAL_RNG_MODULE_ENABLED + #include "apm32f4xx_dal_rng.h" +#endif /* DAL_RNG_MODULE_ENABLED */ + +#ifdef DAL_RTC_MODULE_ENABLED + #include "apm32f4xx_dal_rtc.h" +#endif /* DAL_RTC_MODULE_ENABLED */ + +#ifdef DAL_SRAM_MODULE_ENABLED + #include "apm32f4xx_dal_sram.h" +#endif /* DAL_SRAM_MODULE_ENABLED */ + +#ifdef DAL_SDRAM_MODULE_ENABLED + #include "apm32f4xx_dal_sdram.h" +#endif /* DAL_SDRAM_MODULE_ENABLED */ + +#ifdef DAL_SMBUS_MODULE_ENABLED + #include "apm32f4xx_dal_smbus.h" +#endif /* DAL_SMBUS_MODULE_ENABLED */ + +#ifdef DAL_SD_MODULE_ENABLED + #include "apm32f4xx_dal_sd.h" +#endif /* DAL_SD_MODULE_ENABLED */ + +#ifdef DAL_SPI_MODULE_ENABLED + #include "apm32f4xx_dal_spi.h" +#endif /* DAL_SPI_MODULE_ENABLED */ + +#ifdef DAL_SMARTCARD_MODULE_ENABLED + #include "apm32f4xx_dal_smartcard.h" +#endif /* DAL_SMARTCARD_MODULE_ENABLED */ + +#ifdef DAL_TMR_MODULE_ENABLED + #include "apm32f4xx_dal_tmr.h" +#endif /* DAL_TMR_MODULE_ENABLED */ + +#ifdef DAL_UART_MODULE_ENABLED + #include "apm32f4xx_dal_uart.h" +#endif /* DAL_UART_MODULE_ENABLED */ + +#ifdef DAL_USART_MODULE_ENABLED + #include "apm32f4xx_dal_usart.h" +#endif /* DAL_USART_MODULE_ENABLED */ + +#ifdef DAL_IWDT_MODULE_ENABLED + #include "apm32f4xx_dal_iwdt.h" +#endif /* DAL_IWDT_MODULE_ENABLED */ + +#ifdef DAL_WWDT_MODULE_ENABLED + #include "apm32f4xx_dal_wwdt.h" +#endif /* DAL_WWDT_MODULE_ENABLED */ + +/* Assert Component */ +#if (USE_FULL_ASSERT == 1U) + #define ASSERT_PARAM(_PARAM_) ((_PARAM_) ? (void)(_PARAM_) : AssertFailedHandler((uint8_t *)__FILE__, __LINE__)) + /* Declaration */ + void AssertFailedHandler(uint8_t *file, uint32_t line); +#else + #define ASSERT_PARAM(_PARAM_) ((void)(_PARAM_)) +#endif /* USE_FULL_ASSERT */ + + +#ifdef __cplusplus +} +#endif + +#endif /* APM32F4xx_DAL_CFG_H */ diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_comp.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_comp.h new file mode 100644 index 0000000000..b41c75c137 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_comp.h @@ -0,0 +1,442 @@ +/** + * + * @file apm32f4xx_dal_comp.h + * @brief Header file of COMP DAL module. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2017 STMicroelectronics. + * Copyright (C) 2023-2024 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + */ +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef APM32F4xx_DAL_COMP_H +#define APM32F4xx_DAL_COMP_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal_def.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @addtogroup COMP + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ + +/** @defgroup COMP_Exported_Types COMP Exported Types + * @{ + */ + +/** + * @brief COMP Init structure definition + */ +typedef struct +{ + uint32_t WindowMode; /*!< Set window mode. + Note: Window mode is available only for COMP1. + This parameter can be a value of @ref COMP_WindowMode */ + + uint32_t Mode; /*!< Set comparator operating mode to adjust speed. + Note: Speed mode is available only for COMP2. + This parameter can be a value of @ref COMP_SpeedMode */ + + uint32_t NonInvertingInput; /*!< Set comparator input plus (non-inverting input). + Note: Non-inverting input is available only for COMP2. + This parameter can be a value of @ref COMP_NonInvertingInput */ + + uint32_t InvertingInput; /*!< Set comparator input minus (inverting input). + This parameter can be a value of @ref COMP_InvertingInput */ + + uint32_t Output; /*!< Set comparator output. + This parameter can be a value of @ref COMP_Output */ + + uint32_t OutputPol; /*!< Set comparator output polarity. + This parameter can be a value of @ref COMP_OutputPolarity */ + + +} COMP_InitTypeDef; + +/** + * @brief DAL COMP States definition + */ +#define COMP_STATE_LOCKED (uint32_t)0x10U /*!< COMP Configuration is locked */ +typedef enum +{ + DAL_COMP_STATE_RESET = 0x00U, /*!< COMP not yet initialized */ + DAL_COMP_STATE_RESET_LOCKED = (DAL_COMP_STATE_RESET | COMP_STATE_LOCKED), /*!< COMP not yet initialized and configuration is locked */ + DAL_COMP_STATE_READY = 0x01U, /*!< COMP initialized and ready for use */ + DAL_COMP_STATE_READY_LOCKED = (DAL_COMP_STATE_READY | COMP_STATE_LOCKED), /*!< COMP initialized but configuration is locked */ + DAL_COMP_STATE_BUSY = 0x02U, /*!< COMP internal process is ongoing */ + DAL_COMP_STATE_BUSY_LOCKED = (DAL_COMP_STATE_BUSY | COMP_STATE_LOCKED), /*!< COMP internal process ongoing but configuration is locked */ +} DAL_COMP_StateTypeDef; + +/** + * @brief COMP Handle Structure definition + */ +#if (USE_DAL_COMP_REGISTER_CALLBACKS == 1) +typedef struct __COMP_HandleTypeDef +#else +typedef struct +#endif /* USE_DAL_COMP_REGISTER_CALLBACKS */ +{ + COMP_TypeDef *Instance; /*!< Register base address */ + + COMP_InitTypeDef Init; /*!< COMP required parameters */ + + __IO DAL_COMP_StateTypeDef State; /*!< COMP communication state */ + + DAL_LockTypeDef Lock; /*!< Locking object */ + + __IO uint32_t ErrorCode; /*!< COMP Error code */ +#if (USE_DAL_COMP_REGISTER_CALLBACKS == 1) + void (* MspInitCallback)(struct __COMP_HandleTypeDef * hcomp); /*!< COMP Msp Init callback */ + void (* MspDeInitCallback)(struct __COMP_HandleTypeDef * hcomp); /*!< COMP Msp DeInit callback */ +#endif /* USE_DAL_COMP_REGISTER_CALLBACKS */ +} COMP_HandleTypeDef; + +#if (USE_DAL_COMP_REGISTER_CALLBACKS == 1) +/** + * @brief COMP Callbacks ID enumeration definition + */ +typedef enum +{ + DAL_COMP_MSPINIT_CB_ID = 0x00U, /*!< COMP MspInit callback ID */ + DAL_COMP_MSPDEINIT_CB_ID = 0x01U /*!< COMP MspDeInit callback ID */ +} DAL_COMP_CallbackIDTypeDef; + +/** + * @brief COMP Callback pointer definition + */ +typedef void (*pCOMP_CallbackTypeDef)(COMP_HandleTypeDef * hcomp); /*!< pointer to a COMP callback function */ +#endif /* USE_DAL_COMP_REGISTER_CALLBACKS */ + +/** + * @} + */ + +/* Exported constants --------------------------------------------------------*/ + +/** @defgroup COMP_Exported_Constants COMP Exported Constants + * @{ + */ + +/** @defgroup COMP_Error_Code COMP Error Code + * @brief COMP Error Code + * @{ + */ +#define DAL_COMP_ERROR_NONE 0x00000000U /*!< No error */ +#if (USE_DAL_COMP_REGISTER_CALLBACKS == 1) +#define DAL_COMP_ERROR_INVALID_CALLBACK 0x00000001U /*!< Invalid Callback error */ +#endif /* USE_DAL_COMP_REGISTER_CALLBACKS */ +/** + * @} + */ + +/** @defgroup COMP_WindowMode COMP Window Mode + * @{ + */ +#define COMP_WINDOWMODE_DISABLE 0x00000000U /*!< Window mode disable: Comparators instances pair COMP1 and COMP2 are independent */ +#define COMP_WINDOWMODE_ENABLE COMP_CSTS_WMODESEL /*!< Window mode enable: Comparators instances pair COMP1 and COMP2 have their non inverting inputs connected together */ +/** + * @} + */ + +/** @defgroup COMP_NonInvertingInput COMP Non Inverting Input + * @{ + */ +#define COMP_NONINVERTING_INPUT_PC2 0x00000000U /*!< PC2 available only for COMP2 */ +/** + * @} + */ + +/** @defgroup COMP_InvertingInput COMP Inverting Input + * @{ + */ +#define COMP_INVERTING_INPUT_VREFINT 0x00000000U /*!< VrefInt */ +#define COMP_INVERTING_INPUT_PC1 COMP_CSTS_INMCCFG_0 /*!< PC1 available only for COMP1 */ +#define COMP_INVERTING_INPUT_PC3 COMP_CSTS_INMCCFG_0 /*!< PC3 available only for COMP2 */ +#define COMP_INVERTING_INPUT_1_4VREFINT COMP_CSTS_INMCCFG_2 /*!< 1/4 VrefInt available only for COMP2 */ +#define COMP_INVERTING_INPUT_1_2VREFINT (COMP_CSTS_INMCCFG_2 | COMP_CSTS_INMCCFG_0) /*!< 1/2 VrefInt available only for COMP2 */ +#define COMP_INVERTING_INPUT_3_4VREFINT (COMP_CSTS_INMCCFG_2 | COMP_CSTS_INMCCFG_1) /*!< 3/4 VrefInt available only for COMP2 */ +/** + * @} + */ + +/** @defgroup COMP_SpeedMode COMP Speed Mode + * @{ + */ +#define COMP_SPEEDMODE_LOW 0x00000000U /*!< Low speed */ +#define COMP_SPEEDMODE_HIGH (COMP_CSTS_SPEEDM) /*!< High speed */ +/** + * @} + */ + +/** @defgroup COMP_Output COMP Output + * @{ + */ +#define COMP_OUTPUT_NONE 0x00000000U /*!< COMP output isn't connected to other peripherals */ +#define COMP_OUTPUT_TMR1BKIN COMP_CSTS_OUTSEL_0 /*!< COMP output connected to TMR1 Break Input (BKIN) */ +#define COMP_OUTPUT_TMR1IC1 COMP_CSTS_OUTSEL_1 /*!< COMP output connected to TMR1 Input Capture 1 */ +#define COMP_OUTPUT_TMR1ETRF (COMP_CSTS_OUTSEL_1 | COMP_CSTS_OUTSEL_0) /*!< COMP output connected to TMR1 External Trigger Input */ +#define COMP_OUTPUT_TMR8BKIN COMP_CSTS_OUTSEL_2 /*!< COMP output connected to TMR8 Break Input (BKIN) */ +#define COMP_OUTPUT_TMR8IC1 (COMP_CSTS_OUTSEL_2 | COMP_CSTS_OUTSEL_0) /*!< COMP output connected to TMR8 Input Capture 1 */ +#define COMP_OUTPUT_TMR8ETRF (COMP_CSTS_OUTSEL_2 | COMP_CSTS_OUTSEL_1) /*!< COMP output connected to TMR8 External Trigger Input */ +#define COMP_OUTPUT_TMR2IC4 (COMP_CSTS_OUTSEL_2 | COMP_CSTS_OUTSEL_1 | COMP_CSTS_OUTSEL_0) /*!< COMP output connected to TMR2 Input Capture 4 */ +#define COMP_OUTPUT_TMR2ETRF (COMP_CSTS_OUTSEL_3) /*!< COMP output connected to TMR2 External Trigger Input */ +#define COMP_OUTPUT_TMR3IC1 (COMP_CSTS_OUTSEL_3 | COMP_CSTS_OUTSEL_0) /*!< COMP output connected to TMR3 Input Capture 1 */ +#define COMP_OUTPUT_TMR3ETRF (COMP_CSTS_OUTSEL_3 | COMP_CSTS_OUTSEL_1) /*!< COMP output connected to TMR3 External Trigger Input */ +#define COMP_OUTPUT_TMR4IC1 (COMP_CSTS_OUTSEL_3 | COMP_CSTS_OUTSEL_1 | COMP_CSTS_OUTSEL_0) /*!< COMP output connected to TMR4 Input Capture 1 */ +/** + * @} + */ + +/** @defgroup COMP_OutputPolarity COMP Output Polarity + * @{ + */ +#define COMP_OUTPUTPOL_NONINVERTED 0x00000000U /*!< COMP output on GPIO isn't inverted */ +#define COMP_OUTPUTPOL_INVERTED COMP_CSTS_POLCFG /*!< COMP output on GPIO is inverted */ +/** + * @} + */ + +/** @defgroup COMP_OutputLevel COMP Output Level + * @{ + */ +#define COMP_OUTPUTLEVEL_LOW (uint32_t)0x00000000U /*!< COMP output level is low */ +#define COMP_OUTPUTLEVEL_HIGH (uint32_t)0x00000001U /*!< COMP output level is high */ +/** + * @} + */ + +/** + * @} + */ + +/* Exported macros -----------------------------------------------------------*/ +/** @defgroup COMP_Exported_Macros COMP Exported Macros + * @{ + */ +/** @defgroup COMP_Handle_Management COMP Handle Management + * @{ + */ +/** + * @brief Reset COMP handle state + * @param __HANDLE__ COMP handle. + * @retval None + */ +#if (USE_DAL_COMP_REGISTER_CALLBACKS == 1) +#define __DAL_COMP_RESET_HANDLE_STATE(__HANDLE__) do{ \ + (__HANDLE__)->State = DAL_COMP_STATE_RESET; \ + (__HANDLE__)->MspInitCallback = NULL; \ + (__HANDLE__)->MspDeInitCallback = NULL; \ + } while(0) +#else +#define __DAL_COMP_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = DAL_COMP_STATE_RESET) +#endif /* USE_DAL_COMP_REGISTER_CALLBACKS */ + +/** + * @brief Clear COMP error code (set it to no error code "DAL_COMP_ERROR_NONE"). + * @param __HANDLE__ COMP handle + * @retval None + */ +#define COMP_CLEAR_ERRORCODE(__HANDLE__) ((__HANDLE__)->ErrorCode = DAL_COMP_ERROR_NONE) + +/** + * @brief Enable the specified comparator. + * @param __HANDLE__ COMP handle + * @retval None + */ +#define __DAL_COMP_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CSTS |= COMP_CSTS_EN) + +/** + * @brief Disable the specified comparator. + * @param __HANDLE__ COMP handle + * @retval None + */ +#define __DAL_COMP_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CSTS &= ~COMP_CSTS_EN) + +/** + * @brief Lock the specified comparator configuration. + * @note Using this function implies that COMP DAL status is already locked. + * To unlock the configuration, user will have to resort to __DAL_COMP_DISABLE_LOCK() API. + * @param __HANDLE__ COMP handle + * @retval None + */ +#define __DAL_COMP_LOCK(__HANDLE__) ((__HANDLE__)->Instance->CSTS |= COMP_CSTS_LOCK) + +/** + * @brief Check whether the specified COMP is locked. + * @param __HANDLE__ COMP handle + * @retval Value 0: COMP is not locked, Value 1: COMP is locked + */ +#define __DAL_COMP_IS_LOCKED(__HANDLE__) (((__HANDLE__)->Instance->CSTS & COMP_CSTS_LOCK) == COMP_CSTS_LOCK) + +/** + * @} + */ + +/** + * @} + */ + +/* Private types -------------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/* Private macros ------------------------------------------------------------*/ +/** @defgroup COMP_Private_Macros COMP Private Macros + * @{ + */ + +/** @defgroup COMP_IS_COMP_Definitions COMP private macros to check input parameters + * @{ + */ +#define IS_COMP_WINDOWMODE(__MODE__) (((__MODE__) == COMP_WINDOWMODE_DISABLE) || \ + ((__MODE__) == COMP_WINDOWMODE_ENABLE)) + +#define IS_COMP1_INVERTINGINPUT(__INPUT__) (((__INPUT__) == COMP_INVERTING_INPUT_VREFINT) || \ + ((__INPUT__) == COMP_INVERTING_INPUT_PC1)) + +#define IS_COMP2_INVERTINGINPUT(__INPUT__) (((__INPUT__) == COMP_INVERTING_INPUT_VREFINT) || \ + ((__INPUT__) == COMP_INVERTING_INPUT_PC3) || \ + ((__INPUT__) == COMP_INVERTING_INPUT_1_4VREFINT) || \ + ((__INPUT__) == COMP_INVERTING_INPUT_1_2VREFINT) || \ + ((__INPUT__) == COMP_INVERTING_INPUT_3_4VREFINT)) + +#define IS_COMP_NONINVERTINGINPUT(__INPUT__) (((__INPUT__) == COMP_NONINVERTING_INPUT_PC2)) + +#define IS_COMP_SPEEDMODE(__MODE__) (((__MODE__) == COMP_SPEEDMODE_LOW) || \ + ((__MODE__) == COMP_SPEEDMODE_HIGH)) + +#define IS_COMP_OUTPUT(__OUTPUT__) (((__OUTPUT__) == COMP_OUTPUT_NONE) || \ + ((__OUTPUT__) == COMP_OUTPUT_TMR1BKIN) || \ + ((__OUTPUT__) == COMP_OUTPUT_TMR1IC1) || \ + ((__OUTPUT__) == COMP_OUTPUT_TMR1ETRF) || \ + ((__OUTPUT__) == COMP_OUTPUT_TMR8BKIN) || \ + ((__OUTPUT__) == COMP_OUTPUT_TMR8IC1) || \ + ((__OUTPUT__) == COMP_OUTPUT_TMR8ETRF) || \ + ((__OUTPUT__) == COMP_OUTPUT_TMR2IC4) || \ + ((__OUTPUT__) == COMP_OUTPUT_TMR2ETRF) || \ + ((__OUTPUT__) == COMP_OUTPUT_TMR3IC1) || \ + ((__OUTPUT__) == COMP_OUTPUT_TMR3ETRF) || \ + ((__OUTPUT__) == COMP_OUTPUT_TMR4IC1)) + +#define IS_COMP_OUTPUTPOL(__POLARITY__) (((__POLARITY__) == COMP_OUTPUTPOL_NONINVERTED) || \ + ((__POLARITY__) == COMP_OUTPUTPOL_INVERTED)) + +#define IS_COMP_OUTPUTLEVEL(__LEVEL__) (((__LEVEL__) == COMP_OUTPUTLEVEL_LOW) || \ + ((__LEVEL__) == COMP_OUTPUTLEVEL_HIGH)) + +/** + * @} + */ + +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup COMP_Exported_Functions + * @{ + */ + +/** @addtogroup COMP_Exported_Functions_Group1 + * @{ + */ +/* Initialization/de-initialization functions ********************************/ +DAL_StatusTypeDef DAL_COMP_Init(COMP_HandleTypeDef * hcomp); +DAL_StatusTypeDef DAL_COMP_DeInit(COMP_HandleTypeDef * hcomp); +void DAL_COMP_MspInit(COMP_HandleTypeDef * hcomp); +void DAL_COMP_MspDeInit(COMP_HandleTypeDef * hcomp); +#if (USE_DAL_COMP_REGISTER_CALLBACKS == 1) +/* Callbacks Register/UnRegister functions ***********************************/ +DAL_StatusTypeDef DAL_COMP_RegisterCallback(COMP_HandleTypeDef * hcomp, DAL_COMP_CallbackIDTypeDef CallbackID, pCOMP_CallbackTypeDef pCallback); +DAL_StatusTypeDef DAL_COMP_UnRegisterCallback(COMP_HandleTypeDef * hcomp, DAL_COMP_CallbackIDTypeDef CallbackID); +#endif /* USE_DAL_COMP_REGISTER_CALLBACKS */ +/** + * @} + */ + +/** @addtogroup COMP_Exported_Functions_Group2 + * @{ + */ +/* I/O operation functions ***************************************************/ +DAL_StatusTypeDef DAL_COMP_Start(COMP_HandleTypeDef * hcomp); +DAL_StatusTypeDef DAL_COMP_Stop(COMP_HandleTypeDef * hcomp); +/** + * @} + */ + +/** @addtogroup COMP_Exported_Functions_Group3 + * @{ + */ +/* Peripheral Control functions ************************************************/ +DAL_StatusTypeDef DAL_COMP_Lock(COMP_HandleTypeDef * hcomp); +uint32_t DAL_COMP_GetOutputLevel(COMP_HandleTypeDef * hcomp); +/** + * @} + */ + +/** @addtogroup COMP_Exported_Functions_Group4 + * @{ + */ +/* Peripheral State functions **************************************************/ +DAL_COMP_StateTypeDef DAL_COMP_GetState(COMP_HandleTypeDef * hcomp); +uint32_t DAL_COMP_GetError(COMP_HandleTypeDef * hcomp); +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* APM32F4xx_DAL_COMP_H */ + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_cortex.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_cortex.h new file mode 100644 index 0000000000..29c84c7591 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_cortex.h @@ -0,0 +1,431 @@ +/** + * + * @file apm32f4xx_dal_cortex.h + * @brief Header file of CORTEX DAL module. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2017 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file in + * the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef APM32F4xx_DAL_CORTEX_H +#define APM32F4xx_DAL_CORTEX_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal_def.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @addtogroup CORTEX + * @{ + */ +/* Exported types ------------------------------------------------------------*/ +/** @defgroup CORTEX_Exported_Types Cortex Exported Types + * @{ + */ + +#if (__MPU_PRESENT == 1U) +/** @defgroup CORTEX_MPU_Region_Initialization_Structure_definition MPU Region Initialization Structure Definition + * @brief MPU Region initialization structure + * @{ + */ +typedef struct +{ + uint8_t Enable; /*!< Specifies the status of the region. + This parameter can be a value of @ref CORTEX_MPU_Region_Enable */ + uint8_t Number; /*!< Specifies the number of the region to protect. + This parameter can be a value of @ref CORTEX_MPU_Region_Number */ + uint32_t BaseAddress; /*!< Specifies the base address of the region to protect. */ + uint8_t Size; /*!< Specifies the size of the region to protect. + This parameter can be a value of @ref CORTEX_MPU_Region_Size */ + uint8_t SubRegionDisable; /*!< Specifies the number of the subregion protection to disable. + This parameter must be a number between Min_Data = 0x00 and Max_Data = 0xFF */ + uint8_t TypeExtField; /*!< Specifies the TEX field level. + This parameter can be a value of @ref CORTEX_MPU_TEX_Levels */ + uint8_t AccessPermission; /*!< Specifies the region access permission type. + This parameter can be a value of @ref CORTEX_MPU_Region_Permission_Attributes */ + uint8_t DisableExec; /*!< Specifies the instruction access status. + This parameter can be a value of @ref CORTEX_MPU_Instruction_Access */ + uint8_t IsShareable; /*!< Specifies the shareability status of the protected region. + This parameter can be a value of @ref CORTEX_MPU_Access_Shareable */ + uint8_t IsCacheable; /*!< Specifies the cacheable status of the region protected. + This parameter can be a value of @ref CORTEX_MPU_Access_Cacheable */ + uint8_t IsBufferable; /*!< Specifies the bufferable status of the protected region. + This parameter can be a value of @ref CORTEX_MPU_Access_Bufferable */ +}MPU_Region_InitTypeDef; +/** + * @} + */ +#endif /* __MPU_PRESENT */ + +/** + * @} + */ + +/* Exported constants --------------------------------------------------------*/ + +/** @defgroup CORTEX_Exported_Constants CORTEX Exported Constants + * @{ + */ + +/** @defgroup CORTEX_Preemption_Priority_Group CORTEX Preemption Priority Group + * @{ + */ +#define NVIC_PRIORITYGROUP_0 0x00000007U /*!< 0 bits for pre-emption priority + 4 bits for subpriority */ +#define NVIC_PRIORITYGROUP_1 0x00000006U /*!< 1 bits for pre-emption priority + 3 bits for subpriority */ +#define NVIC_PRIORITYGROUP_2 0x00000005U /*!< 2 bits for pre-emption priority + 2 bits for subpriority */ +#define NVIC_PRIORITYGROUP_3 0x00000004U /*!< 3 bits for pre-emption priority + 1 bits for subpriority */ +#define NVIC_PRIORITYGROUP_4 0x00000003U /*!< 4 bits for pre-emption priority + 0 bits for subpriority */ +/** + * @} + */ + +/** @defgroup CORTEX_SysTick_clock_source CORTEX _SysTick clock source + * @{ + */ +#define SYSTICK_CLKSOURCE_HCLK_DIV8 0x00000000U +#define SYSTICK_CLKSOURCE_HCLK 0x00000004U + +/** + * @} + */ + +#if (__MPU_PRESENT == 1) +/** @defgroup CORTEX_MPU_HFNMI_PRIVDEF_Control MPU HFNMI and PRIVILEGED Access control + * @{ + */ +#define MPU_HFNMI_PRIVDEF_NONE 0x00000000U +#define MPU_HARDFAULT_NMI MPU_CTRL_HFNMIENA_Msk +#define MPU_PRIVILEGED_DEFAULT MPU_CTRL_PRIVDEFENA_Msk +#define MPU_HFNMI_PRIVDEF (MPU_CTRL_HFNMIENA_Msk | MPU_CTRL_PRIVDEFENA_Msk) + +/** + * @} + */ + +/** @defgroup CORTEX_MPU_Region_Enable CORTEX MPU Region Enable + * @{ + */ +#define MPU_REGION_ENABLE ((uint8_t)0x01) +#define MPU_REGION_DISABLE ((uint8_t)0x00) +/** + * @} + */ + +/** @defgroup CORTEX_MPU_Instruction_Access CORTEX MPU Instruction Access + * @{ + */ +#define MPU_INSTRUCTION_ACCESS_ENABLE ((uint8_t)0x00) +#define MPU_INSTRUCTION_ACCESS_DISABLE ((uint8_t)0x01) +/** + * @} + */ + +/** @defgroup CORTEX_MPU_Access_Shareable CORTEX MPU Instruction Access Shareable + * @{ + */ +#define MPU_ACCESS_SHAREABLE ((uint8_t)0x01) +#define MPU_ACCESS_NOT_SHAREABLE ((uint8_t)0x00) +/** + * @} + */ + +/** @defgroup CORTEX_MPU_Access_Cacheable CORTEX MPU Instruction Access Cacheable + * @{ + */ +#define MPU_ACCESS_CACHEABLE ((uint8_t)0x01) +#define MPU_ACCESS_NOT_CACHEABLE ((uint8_t)0x00) +/** + * @} + */ + +/** @defgroup CORTEX_MPU_Access_Bufferable CORTEX MPU Instruction Access Bufferable + * @{ + */ +#define MPU_ACCESS_BUFFERABLE ((uint8_t)0x01) +#define MPU_ACCESS_NOT_BUFFERABLE ((uint8_t)0x00) +/** + * @} + */ + +/** @defgroup CORTEX_MPU_TEX_Levels MPU TEX Levels + * @{ + */ +#define MPU_TEX_LEVEL0 ((uint8_t)0x00) +#define MPU_TEX_LEVEL1 ((uint8_t)0x01) +#define MPU_TEX_LEVEL2 ((uint8_t)0x02) +/** + * @} + */ + +/** @defgroup CORTEX_MPU_Region_Size CORTEX MPU Region Size + * @{ + */ +#define MPU_REGION_SIZE_32B ((uint8_t)0x04) +#define MPU_REGION_SIZE_64B ((uint8_t)0x05) +#define MPU_REGION_SIZE_128B ((uint8_t)0x06) +#define MPU_REGION_SIZE_256B ((uint8_t)0x07) +#define MPU_REGION_SIZE_512B ((uint8_t)0x08) +#define MPU_REGION_SIZE_1KB ((uint8_t)0x09) +#define MPU_REGION_SIZE_2KB ((uint8_t)0x0A) +#define MPU_REGION_SIZE_4KB ((uint8_t)0x0B) +#define MPU_REGION_SIZE_8KB ((uint8_t)0x0C) +#define MPU_REGION_SIZE_16KB ((uint8_t)0x0D) +#define MPU_REGION_SIZE_32KB ((uint8_t)0x0E) +#define MPU_REGION_SIZE_64KB ((uint8_t)0x0F) +#define MPU_REGION_SIZE_128KB ((uint8_t)0x10) +#define MPU_REGION_SIZE_256KB ((uint8_t)0x11) +#define MPU_REGION_SIZE_512KB ((uint8_t)0x12) +#define MPU_REGION_SIZE_1MB ((uint8_t)0x13) +#define MPU_REGION_SIZE_2MB ((uint8_t)0x14) +#define MPU_REGION_SIZE_4MB ((uint8_t)0x15) +#define MPU_REGION_SIZE_8MB ((uint8_t)0x16) +#define MPU_REGION_SIZE_16MB ((uint8_t)0x17) +#define MPU_REGION_SIZE_32MB ((uint8_t)0x18) +#define MPU_REGION_SIZE_64MB ((uint8_t)0x19) +#define MPU_REGION_SIZE_128MB ((uint8_t)0x1A) +#define MPU_REGION_SIZE_256MB ((uint8_t)0x1B) +#define MPU_REGION_SIZE_512MB ((uint8_t)0x1C) +#define MPU_REGION_SIZE_1GB ((uint8_t)0x1D) +#define MPU_REGION_SIZE_2GB ((uint8_t)0x1E) +#define MPU_REGION_SIZE_4GB ((uint8_t)0x1F) +/** + * @} + */ + +/** @defgroup CORTEX_MPU_Region_Permission_Attributes CORTEX MPU Region Permission Attributes + * @{ + */ +#define MPU_REGION_NO_ACCESS ((uint8_t)0x00) +#define MPU_REGION_PRIV_RW ((uint8_t)0x01) +#define MPU_REGION_PRIV_RW_URO ((uint8_t)0x02) +#define MPU_REGION_FULL_ACCESS ((uint8_t)0x03) +#define MPU_REGION_PRIV_RO ((uint8_t)0x05) +#define MPU_REGION_PRIV_RO_URO ((uint8_t)0x06) +/** + * @} + */ + +/** @defgroup CORTEX_MPU_Region_Number CORTEX MPU Region Number + * @{ + */ +#define MPU_REGION_NUMBER0 ((uint8_t)0x00) +#define MPU_REGION_NUMBER1 ((uint8_t)0x01) +#define MPU_REGION_NUMBER2 ((uint8_t)0x02) +#define MPU_REGION_NUMBER3 ((uint8_t)0x03) +#define MPU_REGION_NUMBER4 ((uint8_t)0x04) +#define MPU_REGION_NUMBER5 ((uint8_t)0x05) +#define MPU_REGION_NUMBER6 ((uint8_t)0x06) +#define MPU_REGION_NUMBER7 ((uint8_t)0x07) +/** + * @} + */ +#endif /* __MPU_PRESENT */ + +/** + * @} + */ + + +/* Exported Macros -----------------------------------------------------------*/ + +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup CORTEX_Exported_Functions + * @{ + */ + +/** @addtogroup CORTEX_Exported_Functions_Group1 + * @{ + */ +/* Initialization and de-initialization functions *****************************/ +void DAL_NVIC_SetPriorityGrouping(uint32_t PriorityGroup); +void DAL_NVIC_SetPriority(IRQn_Type IRQn, uint32_t PreemptPriority, uint32_t SubPriority); +void DAL_NVIC_EnableIRQ(IRQn_Type IRQn); +void DAL_NVIC_DisableIRQ(IRQn_Type IRQn); +void DAL_NVIC_SystemReset(void); +uint32_t DAL_SYSTICK_Config(uint32_t TicksNumb); +/** + * @} + */ + +/** @addtogroup CORTEX_Exported_Functions_Group2 + * @{ + */ +/* Peripheral Control functions ***********************************************/ +uint32_t DAL_NVIC_GetPriorityGrouping(void); +void DAL_NVIC_GetPriority(IRQn_Type IRQn, uint32_t PriorityGroup, uint32_t* pPreemptPriority, uint32_t* pSubPriority); +uint32_t DAL_NVIC_GetPendingIRQ(IRQn_Type IRQn); +void DAL_NVIC_SetPendingIRQ(IRQn_Type IRQn); +void DAL_NVIC_ClearPendingIRQ(IRQn_Type IRQn); +uint32_t DAL_NVIC_GetActive(IRQn_Type IRQn); +void DAL_SYSTICK_CLKSourceConfig(uint32_t CLKSource); +void DAL_SYSTICK_IRQHandler(void); +void DAL_SYSTICK_Callback(void); + +#if (__MPU_PRESENT == 1U) +void DAL_MPU_Enable(uint32_t MPU_Control); +void DAL_MPU_Disable(void); +void DAL_MPU_ConfigRegion(MPU_Region_InitTypeDef *MPU_Init); +#endif /* __MPU_PRESENT */ +/** + * @} + */ + +/** + * @} + */ + +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/* Private macros ------------------------------------------------------------*/ +/** @defgroup CORTEX_Private_Macros CORTEX Private Macros + * @{ + */ +#define IS_NVIC_PRIORITY_GROUP(GROUP) (((GROUP) == NVIC_PRIORITYGROUP_0) || \ + ((GROUP) == NVIC_PRIORITYGROUP_1) || \ + ((GROUP) == NVIC_PRIORITYGROUP_2) || \ + ((GROUP) == NVIC_PRIORITYGROUP_3) || \ + ((GROUP) == NVIC_PRIORITYGROUP_4)) + +#define IS_NVIC_PREEMPTION_PRIORITY(PRIORITY) ((PRIORITY) < 0x10U) + +#define IS_NVIC_SUB_PRIORITY(PRIORITY) ((PRIORITY) < 0x10U) + +#define IS_NVIC_DEVICE_IRQ(IRQ) ((IRQ) >= (IRQn_Type)0x00U) + +#define IS_SYSTICK_CLK_SOURCE(SOURCE) (((SOURCE) == SYSTICK_CLKSOURCE_HCLK) || \ + ((SOURCE) == SYSTICK_CLKSOURCE_HCLK_DIV8)) + +#if (__MPU_PRESENT == 1U) +#define IS_MPU_REGION_ENABLE(STATE) (((STATE) == MPU_REGION_ENABLE) || \ + ((STATE) == MPU_REGION_DISABLE)) + +#define IS_MPU_INSTRUCTION_ACCESS(STATE) (((STATE) == MPU_INSTRUCTION_ACCESS_ENABLE) || \ + ((STATE) == MPU_INSTRUCTION_ACCESS_DISABLE)) + +#define IS_MPU_ACCESS_SHAREABLE(STATE) (((STATE) == MPU_ACCESS_SHAREABLE) || \ + ((STATE) == MPU_ACCESS_NOT_SHAREABLE)) + +#define IS_MPU_ACCESS_CACHEABLE(STATE) (((STATE) == MPU_ACCESS_CACHEABLE) || \ + ((STATE) == MPU_ACCESS_NOT_CACHEABLE)) + +#define IS_MPU_ACCESS_BUFFERABLE(STATE) (((STATE) == MPU_ACCESS_BUFFERABLE) || \ + ((STATE) == MPU_ACCESS_NOT_BUFFERABLE)) + +#define IS_MPU_TEX_LEVEL(TYPE) (((TYPE) == MPU_TEX_LEVEL0) || \ + ((TYPE) == MPU_TEX_LEVEL1) || \ + ((TYPE) == MPU_TEX_LEVEL2)) + +#define IS_MPU_REGION_PERMISSION_ATTRIBUTE(TYPE) (((TYPE) == MPU_REGION_NO_ACCESS) || \ + ((TYPE) == MPU_REGION_PRIV_RW) || \ + ((TYPE) == MPU_REGION_PRIV_RW_URO) || \ + ((TYPE) == MPU_REGION_FULL_ACCESS) || \ + ((TYPE) == MPU_REGION_PRIV_RO) || \ + ((TYPE) == MPU_REGION_PRIV_RO_URO)) + +#define IS_MPU_REGION_NUMBER(NUMBER) (((NUMBER) == MPU_REGION_NUMBER0) || \ + ((NUMBER) == MPU_REGION_NUMBER1) || \ + ((NUMBER) == MPU_REGION_NUMBER2) || \ + ((NUMBER) == MPU_REGION_NUMBER3) || \ + ((NUMBER) == MPU_REGION_NUMBER4) || \ + ((NUMBER) == MPU_REGION_NUMBER5) || \ + ((NUMBER) == MPU_REGION_NUMBER6) || \ + ((NUMBER) == MPU_REGION_NUMBER7)) + +#define IS_MPU_REGION_SIZE(SIZE) (((SIZE) == MPU_REGION_SIZE_32B) || \ + ((SIZE) == MPU_REGION_SIZE_64B) || \ + ((SIZE) == MPU_REGION_SIZE_128B) || \ + ((SIZE) == MPU_REGION_SIZE_256B) || \ + ((SIZE) == MPU_REGION_SIZE_512B) || \ + ((SIZE) == MPU_REGION_SIZE_1KB) || \ + ((SIZE) == MPU_REGION_SIZE_2KB) || \ + ((SIZE) == MPU_REGION_SIZE_4KB) || \ + ((SIZE) == MPU_REGION_SIZE_8KB) || \ + ((SIZE) == MPU_REGION_SIZE_16KB) || \ + ((SIZE) == MPU_REGION_SIZE_32KB) || \ + ((SIZE) == MPU_REGION_SIZE_64KB) || \ + ((SIZE) == MPU_REGION_SIZE_128KB) || \ + ((SIZE) == MPU_REGION_SIZE_256KB) || \ + ((SIZE) == MPU_REGION_SIZE_512KB) || \ + ((SIZE) == MPU_REGION_SIZE_1MB) || \ + ((SIZE) == MPU_REGION_SIZE_2MB) || \ + ((SIZE) == MPU_REGION_SIZE_4MB) || \ + ((SIZE) == MPU_REGION_SIZE_8MB) || \ + ((SIZE) == MPU_REGION_SIZE_16MB) || \ + ((SIZE) == MPU_REGION_SIZE_32MB) || \ + ((SIZE) == MPU_REGION_SIZE_64MB) || \ + ((SIZE) == MPU_REGION_SIZE_128MB) || \ + ((SIZE) == MPU_REGION_SIZE_256MB) || \ + ((SIZE) == MPU_REGION_SIZE_512MB) || \ + ((SIZE) == MPU_REGION_SIZE_1GB) || \ + ((SIZE) == MPU_REGION_SIZE_2GB) || \ + ((SIZE) == MPU_REGION_SIZE_4GB)) + +#define IS_MPU_SUB_REGION_DISABLE(SUBREGION) ((SUBREGION) < (uint16_t)0x00FF) +#endif /* __MPU_PRESENT */ + +/** + * @} + */ + +/* Private functions ---------------------------------------------------------*/ + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* APM32F4xx_DAL_CORTEX_H */ + + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_crc.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_crc.h new file mode 100644 index 0000000000..cfaa6fa53b --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_crc.h @@ -0,0 +1,205 @@ +/** + * + * @file apm32f4xx_dal_crc.h + * @brief Header file of CRC DAL module. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef APM32F4xx_DAL_CRC_H +#define APM32F4xx_DAL_CRC_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal_def.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @addtogroup CRC + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ +/** @defgroup CRC_Exported_Types CRC Exported Types + * @{ + */ + +/** + * @brief CRC DAL State Structure definition + */ +typedef enum +{ + DAL_CRC_STATE_RESET = 0x00U, /*!< CRC not yet initialized or disabled */ + DAL_CRC_STATE_READY = 0x01U, /*!< CRC initialized and ready for use */ + DAL_CRC_STATE_BUSY = 0x02U, /*!< CRC internal process is ongoing */ + DAL_CRC_STATE_TIMEOUT = 0x03U, /*!< CRC timeout state */ + DAL_CRC_STATE_ERROR = 0x04U /*!< CRC error state */ +} DAL_CRC_StateTypeDef; + + +/** + * @brief CRC Handle Structure definition + */ +typedef struct +{ + CRC_TypeDef *Instance; /*!< Register base address */ + + DAL_LockTypeDef Lock; /*!< CRC Locking object */ + + __IO DAL_CRC_StateTypeDef State; /*!< CRC communication state */ + +} CRC_HandleTypeDef; +/** + * @} + */ + +/* Exported constants --------------------------------------------------------*/ +/** @defgroup CRC_Exported_Constants CRC Exported Constants + * @{ + */ + +/** + * @} + */ + +/* Exported macros -----------------------------------------------------------*/ +/** @defgroup CRC_Exported_Macros CRC Exported Macros + * @{ + */ + +/** @brief Reset CRC handle state. + * @param __HANDLE__ CRC handle. + * @retval None + */ +#define __DAL_CRC_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = DAL_CRC_STATE_RESET) + +/** + * @brief Reset CRC Data Register. + * @param __HANDLE__ CRC handle + * @retval None + */ +#define __DAL_CRC_DATA_RESET(__HANDLE__) ((__HANDLE__)->Instance->CTRL |= CRC_CTRL_RST) + +/** + * @brief Store data in the Independent Data (ID) register. + * @param __HANDLE__ CRC handle + * @param __VALUE__ Value to be stored in the ID register + * @note Refer to the Reference Manual to get the authorized __VALUE__ length in bits + * @retval None + */ +#define __DAL_CRC_SET_IDR(__HANDLE__, __VALUE__) (WRITE_REG((__HANDLE__)->Instance->INDATA, (__VALUE__))) + +/** + * @brief Return the data stored in the Independent Data (ID) register. + * @param __HANDLE__ CRC handle + * @note Refer to the Reference Manual to get the authorized __VALUE__ length in bits + * @retval Value of the ID register + */ +#define __DAL_CRC_GET_IDR(__HANDLE__) (((__HANDLE__)->Instance->INDATA) & CRC_INDATA_INDATA) +/** + * @} + */ + + +/* Private macros --------------------------------------------------------*/ +/** @defgroup CRC_Private_Macros CRC Private Macros + * @{ + */ + +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +/** @defgroup CRC_Exported_Functions CRC Exported Functions + * @{ + */ + +/* Initialization and de-initialization functions ****************************/ +/** @defgroup CRC_Exported_Functions_Group1 Initialization and de-initialization functions + * @{ + */ +DAL_StatusTypeDef DAL_CRC_Init(CRC_HandleTypeDef *hcrc); +DAL_StatusTypeDef DAL_CRC_DeInit(CRC_HandleTypeDef *hcrc); +void DAL_CRC_MspInit(CRC_HandleTypeDef *hcrc); +void DAL_CRC_MspDeInit(CRC_HandleTypeDef *hcrc); +/** + * @} + */ + +/* Peripheral Control functions ***********************************************/ +/** @defgroup CRC_Exported_Functions_Group2 Peripheral Control functions + * @{ + */ +uint32_t DAL_CRC_Accumulate(CRC_HandleTypeDef *hcrc, uint32_t pBuffer[], uint32_t BufferLength); +uint32_t DAL_CRC_Calculate(CRC_HandleTypeDef *hcrc, uint32_t pBuffer[], uint32_t BufferLength); +/** + * @} + */ + +/* Peripheral State and Error functions ***************************************/ +/** @defgroup CRC_Exported_Functions_Group3 Peripheral State functions + * @{ + */ +DAL_CRC_StateTypeDef DAL_CRC_GetState(CRC_HandleTypeDef *hcrc); +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* APM32F4xx_DAL_CRC_H */ diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_cryp.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_cryp.h new file mode 100644 index 0000000000..db53b0103c --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_cryp.h @@ -0,0 +1,708 @@ +/** + * + * @file apm32f4xx_dal_cryp.h + * @author MCD Application Team + * @brief Header file of CRYP DAL module. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef APM32F4xx_DAL_CRYP_H +#define APM32F4xx_DAL_CRYP_H + +#ifdef __cplusplus +extern "C" { +#endif + + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal_def.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ +#if defined (AES) || defined (CRYP) +/** @addtogroup CRYP + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ + +/** @defgroup CRYP_Exported_Types CRYP Exported Types + * @{ + */ + +/** + * @brief CRYP Init Structure definition + */ + +typedef struct +{ + uint32_t DataType; /*!< 32-bit data, 16-bit data, 8-bit data or 1-bit string. + This parameter can be a value of @ref CRYP_Data_Type */ + uint32_t KeySize; /*!< Used only in AES mode : 128, 192 or 256 bit key length in CRYP1. + 128 or 256 bit key length in TinyAES This parameter can be a value of @ref CRYP_Key_Size */ + uint32_t *pKey; /*!< The key used for encryption/decryption */ + uint32_t *pInitVect; /*!< The initialization vector used also as initialization + counter in CTR mode */ + uint32_t Algorithm; /*!< DES/ TDES Algorithm ECB/CBC + AES Algorithm ECB/CBC/CTR/GCM or CCM + This parameter can be a value of @ref CRYP_Algorithm_Mode */ + uint32_t *Header; /*!< used only in AES GCM and CCM Algorithm for authentication, + GCM : also known as Additional Authentication Data + CCM : named B1 composed of the associated data length and Associated Data. */ + uint32_t HeaderSize; /*!< The size of header buffer in word */ + uint32_t *B0; /*!< B0 is first authentication block used only in AES CCM mode */ + uint32_t DataWidthUnit; /*!< Data With Unit, this parameter can be value of @ref CRYP_Data_Width_Unit*/ + uint32_t HeaderWidthUnit; /*!< Header Width Unit, this parameter can be value of @ref CRYP_Header_Width_Unit*/ + uint32_t KeyIVConfigSkip; /*!< CRYP peripheral Key and IV configuration skip, to config Key and Initialization + Vector only once and to skip configuration for consecutive processings. + This parameter can be a value of @ref CRYP_Configuration_Skip */ + +} CRYP_ConfigTypeDef; + + +/** + * @brief CRYP State Structure definition + */ + +typedef enum +{ + DAL_CRYP_STATE_RESET = 0x00U, /*!< CRYP not yet initialized or disabled */ + DAL_CRYP_STATE_READY = 0x01U, /*!< CRYP initialized and ready for use */ + DAL_CRYP_STATE_BUSY = 0x02U /*!< CRYP BUSY, internal processing is ongoing */ +} DAL_CRYP_STATETypeDef; + + +/** + * @brief CRYP handle Structure definition + */ + +typedef struct __CRYP_HandleTypeDef +{ +#if defined (CRYP) + CRYP_TypeDef *Instance; /*!< CRYP registers base address */ +#else /* AES*/ + AES_TypeDef *Instance; /*!< AES Register base address */ +#endif /* End AES or CRYP */ + + CRYP_ConfigTypeDef Init; /*!< CRYP required parameters */ + + FunctionalState AutoKeyDerivation; /*!< Used only in TinyAES to allows to bypass or not key write-up before decryption. + This parameter can be a value of ENABLE/DISABLE */ + + uint32_t *pCrypInBuffPtr; /*!< Pointer to CRYP processing (encryption, decryption,...) buffer */ + + uint32_t *pCrypOutBuffPtr; /*!< Pointer to CRYP processing (encryption, decryption,...) buffer */ + + __IO uint16_t CrypHeaderCount; /*!< Counter of header data */ + + __IO uint16_t CrypInCount; /*!< Counter of input data */ + + __IO uint16_t CrypOutCount; /*!< Counter of output data */ + + uint16_t Size; /*!< length of input data in word */ + + uint32_t Phase; /*!< CRYP peripheral phase */ + + DMA_HandleTypeDef *hdmain; /*!< CRYP In DMA handle parameters */ + + DMA_HandleTypeDef *hdmaout; /*!< CRYP Out DMA handle parameters */ + + DAL_LockTypeDef Lock; /*!< CRYP locking object */ + + __IO DAL_CRYP_STATETypeDef State; /*!< CRYP peripheral state */ + + __IO uint32_t ErrorCode; /*!< CRYP peripheral error code */ + + uint32_t KeyIVConfig; /*!< CRYP peripheral Key and IV configuration flag, used when + configuration can be skipped */ + + uint32_t SizesSum; /*!< Sum of successive payloads lengths (in bytes), stored + for a single signature computation after several + messages processing */ + +#if (USE_DAL_CRYP_REGISTER_CALLBACKS == 1) + void (*InCpltCallback)(struct __CRYP_HandleTypeDef *hcryp); /*!< CRYP Input FIFO transfer completed callback */ + void (*OutCpltCallback)(struct __CRYP_HandleTypeDef *hcryp); /*!< CRYP Output FIFO transfer completed callback */ + void (*ErrorCallback)(struct __CRYP_HandleTypeDef *hcryp); /*!< CRYP Error callback */ + + void (* MspInitCallback)(struct __CRYP_HandleTypeDef *hcryp); /*!< CRYP Msp Init callback */ + void (* MspDeInitCallback)(struct __CRYP_HandleTypeDef *hcryp); /*!< CRYP Msp DeInit callback */ + +#endif /* (USE_DAL_CRYP_REGISTER_CALLBACKS) */ +} CRYP_HandleTypeDef; + + +/** + * @} + */ + +#if (USE_DAL_CRYP_REGISTER_CALLBACKS == 1) +/** @defgroup DAL_CRYP_Callback_ID_enumeration_definition DAL CRYP Callback ID enumeration definition + * @brief DAL CRYP Callback ID enumeration definition + * @{ + */ +typedef enum +{ + DAL_CRYP_INPUT_COMPLETE_CB_ID = 0x01U, /*!< CRYP Input FIFO transfer completed callback ID */ + DAL_CRYP_OUTPUT_COMPLETE_CB_ID = 0x02U, /*!< CRYP Output FIFO transfer completed callback ID */ + DAL_CRYP_ERROR_CB_ID = 0x03U, /*!< CRYP Error callback ID */ + + DAL_CRYP_MSPINIT_CB_ID = 0x04U, /*!< CRYP MspInit callback ID */ + DAL_CRYP_MSPDEINIT_CB_ID = 0x05U /*!< CRYP MspDeInit callback ID */ + +} DAL_CRYP_CallbackIDTypeDef; +/** + * @} + */ + +/** @defgroup DAL_CRYP_Callback_pointer_definition DAL CRYP Callback pointer definition + * @brief DAL CRYP Callback pointer definition + * @{ + */ + +typedef void (*pCRYP_CallbackTypeDef)(CRYP_HandleTypeDef *hcryp); /*!< pointer to a common CRYP callback function */ + +/** + * @} + */ + +#endif /* USE_DAL_CRYP_REGISTER_CALLBACKS */ + +/* Exported constants --------------------------------------------------------*/ +/** @defgroup CRYP_Exported_Constants CRYP Exported Constants + * @{ + */ + +/** @defgroup CRYP_Error_Definition CRYP Error Definition + * @{ + */ +#define DAL_CRYP_ERROR_NONE 0x00000000U /*!< No error */ +#define DAL_CRYP_ERROR_WRITE 0x00000001U /*!< Write error */ +#define DAL_CRYP_ERROR_READ 0x00000002U /*!< Read error */ +#define DAL_CRYP_ERROR_DMA 0x00000004U /*!< DMA error */ +#define DAL_CRYP_ERROR_BUSY 0x00000008U /*!< Busy flag error */ +#define DAL_CRYP_ERROR_TIMEOUT 0x00000010U /*!< Timeout error */ +#define DAL_CRYP_ERROR_NOT_SUPPORTED 0x00000020U /*!< Not supported mode */ +#define DAL_CRYP_ERROR_AUTH_TAG_SEQUENCE 0x00000040U /*!< Sequence are not respected only for GCM or CCM */ +#if (USE_DAL_CRYP_REGISTER_CALLBACKS == 1) +#define DAL_CRYP_ERROR_INVALID_CALLBACK ((uint32_t)0x00000080U) /*!< Invalid Callback error */ +#endif /* USE_DAL_CRYP_REGISTER_CALLBACKS */ +/** + * @} + */ + +/** @defgroup CRYP_Data_Width_Unit CRYP Data Width Unit + * @{ + */ + +#define CRYP_DATAWIDTHUNIT_WORD 0x00000000U /*!< By default, size unit is word */ +#define CRYP_DATAWIDTHUNIT_BYTE 0x00000001U /*!< By default, size unit is word */ + +/** + * @} + */ + +/** @defgroup CRYP_Header_Width_Unit CRYP Header Width Unit + * @{ + */ + +#define CRYP_HEADERWIDTHUNIT_WORD 0x00000000U /*!< By default, header size unit is word */ +#define CRYP_HEADERWIDTHUNIT_BYTE 0x00000001U /*!< By default, header size unit is byte */ + +/** + * @} + */ + +/** @defgroup CRYP_Algorithm_Mode CRYP Algorithm Mode + * @{ + */ +#if defined(CRYP) + +#define CRYP_DES_ECB CRYP_CTRL_ALGOMSEL_DES_ECB +#define CRYP_DES_CBC CRYP_CTRL_ALGOMSEL_DES_CBC +#define CRYP_TDES_ECB CRYP_CTRL_ALGOMSEL_TDES_ECB +#define CRYP_TDES_CBC CRYP_CTRL_ALGOMSEL_TDES_CBC +#define CRYP_AES_ECB CRYP_CTRL_ALGOMSEL_AES_ECB +#define CRYP_AES_CBC CRYP_CTRL_ALGOMSEL_AES_CBC +#define CRYP_AES_CTR CRYP_CTRL_ALGOMSEL_AES_CTR +#if defined (CRYP_CTRL_ALGOMSEL_AES_GCM) +#define CRYP_AES_GCM CRYP_CTRL_ALGOMSEL_AES_GCM +#define CRYP_AES_CCM CRYP_CTRL_ALGOMSEL_AES_CCM +#endif /* GCM CCM defined*/ +#else /* AES*/ +#define CRYP_AES_ECB 0x00000000U /*!< Electronic codebook chaining algorithm */ +#define CRYP_AES_CBC AES_CR_CHMOD_0 /*!< Cipher block chaining algorithm */ +#define CRYP_AES_CTR AES_CR_CHMOD_1 /*!< Counter mode chaining algorithm */ +#define CRYP_AES_GCM_GMAC (AES_CR_CHMOD_0 | AES_CR_CHMOD_1) /*!< Galois counter mode - Galois message authentication code */ +#define CRYP_AES_CCM AES_CR_CHMOD_2 /*!< Counter with Cipher Mode */ +#endif /* End AES or CRYP */ + +/** + * @} + */ + +/** @defgroup CRYP_Key_Size CRYP Key Size + * @{ + */ +#if defined(CRYP) +#define CRYP_KEYSIZE_128B 0x00000000U +#define CRYP_KEYSIZE_192B CRYP_CTRL_KSIZESEL_0 +#define CRYP_KEYSIZE_256B CRYP_CTRL_KSIZESEL_1 +#else /* AES*/ +#define CRYP_KEYSIZE_128B 0x00000000U /*!< 128-bit long key */ +#define CRYP_KEYSIZE_256B AES_CR_KEYSIZE /*!< 256-bit long key */ +#endif /* End AES or CRYP */ +/** + * @} + */ + +/** @defgroup CRYP_Data_Type CRYP Data Type + * @{ + */ +#if defined(CRYP) +#define CRYP_DATATYPE_32B 0x00000000U +#define CRYP_DATATYPE_16B CRYP_CTRL_DTSEL_0 +#define CRYP_DATATYPE_8B CRYP_CTRL_DTSEL_1 +#define CRYP_DATATYPE_1B CRYP_CTRL_DTSEL +#else /* AES*/ +#define CRYP_DATATYPE_32B 0x00000000U /*!< 32-bit data type (no swapping) */ +#define CRYP_DATATYPE_16B AES_CR_DATATYPE_0 /*!< 16-bit data type (half-word swapping) */ +#define CRYP_DATATYPE_8B AES_CR_DATATYPE_1 /*!< 8-bit data type (byte swapping) */ +#define CRYP_DATATYPE_1B AES_CR_DATATYPE /*!< 1-bit data type (bit swapping) */ +#endif /* End AES or CRYP */ + +/** + * @} + */ + +/** @defgroup CRYP_Interrupt CRYP Interrupt + * @{ + */ +#if defined (CRYP) +#define CRYP_IT_INI CRYP_INTMASK_INIMASK /*!< Input FIFO Interrupt */ +#define CRYP_IT_OUTI CRYP_INTMASK_OUTIMASK /*!< Output FIFO Interrupt */ +#else /* AES*/ +#define CRYP_IT_CCFIE AES_CR_CCFIE /*!< Computation Complete interrupt enable */ +#define CRYP_IT_ERRIE AES_CR_ERRIE /*!< Error interrupt enable */ +#define CRYP_IT_WRERR AES_SR_WRERR /*!< Write Error */ +#define CRYP_IT_RDERR AES_SR_RDERR /*!< Read Error */ +#define CRYP_IT_CCF AES_SR_CCF /*!< Computation completed */ +#endif /* End AES or CRYP */ + +/** + * @} + */ + +/** @defgroup CRYP_Flags CRYP Flags + * @{ + */ +#if defined (CRYP) +/* Flags in the SR register */ +#define CRYP_FLAG_IFEM CRYP_STS_IFEMPT /*!< Input FIFO is empty */ +#define CRYP_FLAG_IFNF CRYP_STS_IFFULL /*!< Input FIFO is not Full */ +#define CRYP_FLAG_OFNE CRYP_STS_OFEMPT /*!< Output FIFO is not empty */ +#define CRYP_FLAG_OFFU CRYP_STS_OFFULL /*!< Output FIFO is Full */ +#define CRYP_FLAG_BUSY CRYP_STS_BUSY /*!< The CRYP core is currently processing a block of data + or a key preparation (for AES decryption). */ +/* Flags in the RISR register */ +#define CRYP_FLAG_OUTRIS 0x01000002U /*!< Output FIFO service raw interrupt status */ +#define CRYP_FLAG_INRIS 0x01000001U /*!< Input FIFO service raw interrupt status*/ +#else /* AES*/ +/* status flags */ +#define CRYP_FLAG_BUSY AES_SR_BUSY /*!< GCM process suspension forbidden */ +#define CRYP_FLAG_WRERR AES_SR_WRERR /*!< Write Error */ +#define CRYP_FLAG_RDERR AES_SR_RDERR /*!< Read error */ +#define CRYP_FLAG_CCF AES_SR_CCF /*!< Computation completed */ +/* clearing flags */ +#define CRYP_CCF_CLEAR AES_CR_CCFC /*!< Computation Complete Flag Clear */ +#define CRYP_ERR_CLEAR AES_CR_ERRC /*!< Error Flag Clear */ +#endif /* End AES or CRYP */ + +/** + * @} + */ + +/** @defgroup CRYP_Configuration_Skip CRYP Key and IV Configuration Skip Mode + * @{ + */ + +#define CRYP_KEYIVCONFIG_ALWAYS 0x00000000U /*!< Peripheral Key and IV configuration to do systematically */ +#define CRYP_KEYIVCONFIG_ONCE 0x00000001U /*!< Peripheral Key and IV configuration to do only once */ + +/** + * @} + */ + + +/** + * @} + */ + +/* Exported macros -----------------------------------------------------------*/ +/** @defgroup CRYP_Exported_Macros CRYP Exported Macros + * @{ + */ + +/** @brief Reset CRYP handle state + * @param __HANDLE__ specifies the CRYP handle. + * @retval None + */ +#if (USE_DAL_CRYP_REGISTER_CALLBACKS == 1) +#define __DAL_CRYP_RESET_HANDLE_STATE(__HANDLE__) do{\ + (__HANDLE__)->State = DAL_CRYP_STATE_RESET;\ + (__HANDLE__)->MspInitCallback = NULL;\ + (__HANDLE__)->MspDeInitCallback = NULL;\ + }while(0) +#else +#define __DAL_CRYP_RESET_HANDLE_STATE(__HANDLE__) ( (__HANDLE__)->State = DAL_CRYP_STATE_RESET) +#endif /* USE_DAL_CRYP_REGISTER_CALLBACKS */ + +/** + * @brief Enable/Disable the CRYP peripheral. + * @param __HANDLE__: specifies the CRYP handle. + * @retval None + */ +#if defined(CRYP) +#define __DAL_CRYP_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CTRL |= CRYP_CTRL_CRYPEN) +#define __DAL_CRYP_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CTRL &= ~CRYP_CTRL_CRYPEN) +#else /* AES*/ +#define __DAL_CRYP_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CTRL |= AES_CR_EN) +#define __DAL_CRYP_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CTRL &= ~AES_CR_EN) +#endif /* End AES or CRYP */ + +/** @brief Check whether the specified CRYP status flag is set or not. + * @param __FLAG__: specifies the flag to check. + * This parameter can be one of the following values for TinyAES: + * @arg @ref CRYP_FLAG_BUSY GCM process suspension forbidden + * @arg @ref CRYP_IT_WRERR Write Error + * @arg @ref CRYP_IT_RDERR Read Error + * @arg @ref CRYP_IT_CCF Computation Complete + * This parameter can be one of the following values for CRYP: + * @arg CRYP_FLAG_BUSY: The CRYP core is currently processing a block of data + * or a key preparation (for AES decryption). + * @arg CRYP_FLAG_IFEM: Input FIFO is empty + * @arg CRYP_FLAG_IFNF: Input FIFO is not full + * @arg CRYP_FLAG_INRIS: Input FIFO service raw interrupt is pending + * @arg CRYP_FLAG_OFNE: Output FIFO is not empty + * @arg CRYP_FLAG_OFFU: Output FIFO is full + * @arg CRYP_FLAG_OUTRIS: Input FIFO service raw interrupt is pending + * @retval The state of __FLAG__ (TRUE or FALSE). + */ +#define CRYP_FLAG_MASK 0x0000001FU +#if defined(CRYP) +#define __DAL_CRYP_GET_FLAG(__HANDLE__, __FLAG__) ((((uint8_t)((__FLAG__) >> 24)) == 0x01U)?((((__HANDLE__)->Instance->INTSTS) & ((__FLAG__) & CRYP_FLAG_MASK)) == ((__FLAG__) & CRYP_FLAG_MASK)): \ + ((((__HANDLE__)->Instance->INTSTS) & ((__FLAG__) & CRYP_FLAG_MASK)) == ((__FLAG__) & CRYP_FLAG_MASK))) +#else /* AES*/ +#define __DAL_CRYP_GET_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->STS & (__FLAG__)) == (__FLAG__)) +#endif /* End AES or CRYP */ + +/** @brief Clear the CRYP pending status flag. + * @param __FLAG__: specifies the flag to clear. + * This parameter can be one of the following values: + * @arg @ref CRYP_ERR_CLEAR Read (RDERR) or Write Error (WRERR) Flag Clear + * @arg @ref CRYP_CCF_CLEAR Computation Complete Flag (CCF) Clear + * @param __HANDLE__: specifies the CRYP handle. + * @retval None + */ + +#if defined(AES) +#define __DAL_CRYP_CLEAR_FLAG(__HANDLE__, __FLAG__) SET_BIT((__HANDLE__)->Instance->CTRL, (__FLAG__)) + + +/** @brief Check whether the specified CRYP interrupt source is enabled or not. + * @param __INTERRUPT__: CRYP interrupt source to check + * This parameter can be one of the following values for TinyAES: + * @arg @ref CRYP_IT_ERRIE Error interrupt (used for RDERR and WRERR) + * @arg @ref CRYP_IT_CCFIE Computation Complete interrupt + * @param __HANDLE__: specifies the CRYP handle. + * @retval State of interruption (TRUE or FALSE). + */ + +#define __DAL_CRYP_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->CTRL\ + & (__INTERRUPT__)) == (__INTERRUPT__)) + +#endif /* AES */ + +/** @brief Check whether the specified CRYP interrupt is set or not. + * @param __INTERRUPT__: specifies the interrupt to check. + * This parameter can be one of the following values for TinyAES: + * @arg @ref CRYP_IT_WRERR Write Error + * @arg @ref CRYP_IT_RDERR Read Error + * @arg @ref CRYP_IT_CCF Computation Complete + * This parameter can be one of the following values for CRYP: + * @arg CRYP_IT_INI: Input FIFO service masked interrupt status + * @arg CRYP_IT_OUTI: Output FIFO service masked interrupt status + * @param __HANDLE__: specifies the CRYP handle. + * @retval The state of __INTERRUPT__ (TRUE or FALSE). + */ +#if defined(CRYP) +#define __DAL_CRYP_GET_IT(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->MINTSTS\ + & (__INTERRUPT__)) == (__INTERRUPT__)) +#else /* AES*/ +#define __DAL_CRYP_GET_IT(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->STS & (__INTERRUPT__)) == (__INTERRUPT__)) +#endif /* End AES or CRYP */ + +/** + * @brief Enable the CRYP interrupt. + * @param __INTERRUPT__: CRYP Interrupt. + * This parameter can be one of the following values for TinyAES: + * @arg @ref CRYP_IT_ERRIE Error interrupt (used for RDERR and WRERR) + * @arg @ref CRYP_IT_CCFIE Computation Complete interrupt + * This parameter can be one of the following values for CRYP: + * @ CRYP_IT_INI : Input FIFO service interrupt mask. + * @ CRYP_IT_OUTI : Output FIFO service interrupt mask.CRYP interrupt. + * @param __HANDLE__: specifies the CRYP handle. + * @retval None + */ +#if defined(CRYP) +#define __DAL_CRYP_ENABLE_IT(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->INTMASK) |= (__INTERRUPT__)) +#else /* AES*/ +#define __DAL_CRYP_ENABLE_IT(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->CTRL) |= (__INTERRUPT__)) +#endif /* End AES or CRYP */ + +/** + * @brief Disable the CRYP interrupt. + * @param __INTERRUPT__: CRYP Interrupt. + * This parameter can be one of the following values for TinyAES: + * @arg @ref CRYP_IT_ERRIE Error interrupt (used for RDERR and WRERR) + * @arg @ref CRYP_IT_CCFIE Computation Complete interrupt + * This parameter can be one of the following values for CRYP: + * @ CRYP_IT_INI : Input FIFO service interrupt mask. + * @ CRYP_IT_OUTI : Output FIFO service interrupt mask.CRYP interrupt. + * @param __HANDLE__: specifies the CRYP handle. + * @retval None + */ +#if defined(CRYP) +#define __DAL_CRYP_DISABLE_IT(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->INTMASK) &= ~(__INTERRUPT__)) +#else /* AES*/ +#define __DAL_CRYP_DISABLE_IT(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->CTRL) &= ~(__INTERRUPT__)) +#endif /* End AES or CRYP */ + +/** + * @} + */ +#if defined (CRYP_CTRL_ALGOMSEL_AES_GCM)|| defined (AES) +/* Include CRYP DAL Extended module */ +#include "apm32f4xx_dal_cryp_ex.h" +#endif /* AES or GCM CCM defined*/ +/* Exported functions --------------------------------------------------------*/ +/** @defgroup CRYP_Exported_Functions CRYP Exported Functions + * @{ + */ + +/** @addtogroup CRYP_Exported_Functions_Group1 + * @{ + */ +DAL_StatusTypeDef DAL_CRYP_Init(CRYP_HandleTypeDef *hcryp); +DAL_StatusTypeDef DAL_CRYP_DeInit(CRYP_HandleTypeDef *hcryp); +void DAL_CRYP_MspInit(CRYP_HandleTypeDef *hcryp); +void DAL_CRYP_MspDeInit(CRYP_HandleTypeDef *hcryp); +DAL_StatusTypeDef DAL_CRYP_SetConfig(CRYP_HandleTypeDef *hcryp, CRYP_ConfigTypeDef *pConf); +DAL_StatusTypeDef DAL_CRYP_GetConfig(CRYP_HandleTypeDef *hcryp, CRYP_ConfigTypeDef *pConf); +#if (USE_DAL_CRYP_REGISTER_CALLBACKS == 1) +DAL_StatusTypeDef DAL_CRYP_RegisterCallback(CRYP_HandleTypeDef *hcryp, DAL_CRYP_CallbackIDTypeDef CallbackID, + pCRYP_CallbackTypeDef pCallback); +DAL_StatusTypeDef DAL_CRYP_UnRegisterCallback(CRYP_HandleTypeDef *hcryp, DAL_CRYP_CallbackIDTypeDef CallbackID); +#endif /* USE_DAL_CRYP_REGISTER_CALLBACKS */ +/** + * @} + */ + +/** @addtogroup CRYP_Exported_Functions_Group2 + * @{ + */ + +/* encryption/decryption ***********************************/ +DAL_StatusTypeDef DAL_CRYP_Encrypt(CRYP_HandleTypeDef *hcryp, uint32_t *Input, uint16_t Size, uint32_t *Output, + uint32_t Timeout); +DAL_StatusTypeDef DAL_CRYP_Decrypt(CRYP_HandleTypeDef *hcryp, uint32_t *Input, uint16_t Size, uint32_t *Output, + uint32_t Timeout); +DAL_StatusTypeDef DAL_CRYP_Encrypt_IT(CRYP_HandleTypeDef *hcryp, uint32_t *Input, uint16_t Size, uint32_t *Output); +DAL_StatusTypeDef DAL_CRYP_Decrypt_IT(CRYP_HandleTypeDef *hcryp, uint32_t *Input, uint16_t Size, uint32_t *Output); +DAL_StatusTypeDef DAL_CRYP_Encrypt_DMA(CRYP_HandleTypeDef *hcryp, uint32_t *Input, uint16_t Size, uint32_t *Output); +DAL_StatusTypeDef DAL_CRYP_Decrypt_DMA(CRYP_HandleTypeDef *hcryp, uint32_t *Input, uint16_t Size, uint32_t *Output); + +/** + * @} + */ + + +/** @addtogroup CRYP_Exported_Functions_Group3 + * @{ + */ +/* Interrupt Handler functions **********************************************/ +void DAL_CRYP_IRQHandler(CRYP_HandleTypeDef *hcryp); +DAL_CRYP_STATETypeDef DAL_CRYP_GetState(CRYP_HandleTypeDef *hcryp); +void DAL_CRYP_InCpltCallback(CRYP_HandleTypeDef *hcryp); +void DAL_CRYP_OutCpltCallback(CRYP_HandleTypeDef *hcryp); +void DAL_CRYP_ErrorCallback(CRYP_HandleTypeDef *hcryp); +uint32_t DAL_CRYP_GetError(CRYP_HandleTypeDef *hcryp); + +/** + * @} + */ + +/** + * @} + */ + +/* Private macros --------------------------------------------------------*/ +/** @defgroup CRYP_Private_Macros CRYP Private Macros + * @{ + */ + +/** @defgroup CRYP_IS_CRYP_Definitions CRYP Private macros to check input parameters + * @{ + */ +#if defined(CRYP) +#if defined (CRYP_CTRL_ALGOMSEL_AES_GCM) +#define IS_CRYP_ALGORITHM(ALGORITHM) (((ALGORITHM) == CRYP_DES_ECB) || \ + ((ALGORITHM) == CRYP_DES_CBC) || \ + ((ALGORITHM) == CRYP_TDES_ECB) || \ + ((ALGORITHM) == CRYP_TDES_CBC) || \ + ((ALGORITHM) == CRYP_AES_ECB) || \ + ((ALGORITHM) == CRYP_AES_CBC) || \ + ((ALGORITHM) == CRYP_AES_CTR) || \ + ((ALGORITHM) == CRYP_AES_GCM) || \ + ((ALGORITHM) == CRYP_AES_CCM)) +#else /*NO GCM CCM */ +#define IS_CRYP_ALGORITHM(ALGORITHM) (((ALGORITHM) == CRYP_DES_ECB) || \ + ((ALGORITHM) == CRYP_DES_CBC) || \ + ((ALGORITHM) == CRYP_TDES_ECB) || \ + ((ALGORITHM) == CRYP_TDES_CBC) || \ + ((ALGORITHM) == CRYP_AES_ECB) || \ + ((ALGORITHM) == CRYP_AES_CBC) || \ + ((ALGORITHM) == CRYP_AES_CTR)) +#endif /* GCM CCM defined*/ +#define IS_CRYP_KEYSIZE(KEYSIZE)(((KEYSIZE) == CRYP_KEYSIZE_128B) || \ + ((KEYSIZE) == CRYP_KEYSIZE_192B) || \ + ((KEYSIZE) == CRYP_KEYSIZE_256B)) +#else /* AES*/ +#define IS_CRYP_ALGORITHM(ALGORITHM) (((ALGORITHM) == CRYP_AES_ECB) || \ + ((ALGORITHM) == CRYP_AES_CBC) || \ + ((ALGORITHM) == CRYP_AES_CTR) || \ + ((ALGORITHM) == CRYP_AES_GCM_GMAC)|| \ + ((ALGORITHM) == CRYP_AES_CCM)) + + +#define IS_CRYP_KEYSIZE(KEYSIZE)(((KEYSIZE) == CRYP_KEYSIZE_128B) || \ + ((KEYSIZE) == CRYP_KEYSIZE_256B)) +#endif /* End AES or CRYP */ + +#define IS_CRYP_DATATYPE(DATATYPE)(((DATATYPE) == CRYP_DATATYPE_32B) || \ + ((DATATYPE) == CRYP_DATATYPE_16B) || \ + ((DATATYPE) == CRYP_DATATYPE_8B) || \ + ((DATATYPE) == CRYP_DATATYPE_1B)) + +#define IS_CRYP_INIT(CONFIG)(((CONFIG) == CRYP_KEYIVCONFIG_ALWAYS) || \ + ((CONFIG) == CRYP_KEYIVCONFIG_ONCE)) +/** + * @} + */ + +/** + * @} + */ + + +/* Private constants ---------------------------------------------------------*/ +/** @defgroup CRYP_Private_Constants CRYP Private Constants + * @{ + */ + +/** + * @} + */ +/* Private defines -----------------------------------------------------------*/ +/** @defgroup CRYP_Private_Defines CRYP Private Defines + * @{ + */ + +/** + * @} + */ + +/* Private variables ---------------------------------------------------------*/ +/** @defgroup CRYP_Private_Variables CRYP Private Variables + * @{ + */ + +/** + * @} + */ +/* Private functions prototypes ----------------------------------------------*/ +/** @defgroup CRYP_Private_Functions_Prototypes CRYP Private Functions Prototypes + * @{ + */ + +/** + * @} + */ + +/* Private functions ---------------------------------------------------------*/ +/** @defgroup CRYP_Private_Functions CRYP Private Functions + * @{ + */ + +/** + * @} + */ + + +/** + * @} + */ + + +/** + * @} + */ +#endif /* TinyAES or CRYP*/ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* APM32F4xx_DAL_CRYP_H */ + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_cryp_ex.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_cryp_ex.h new file mode 100644 index 0000000000..0966db18ff --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_cryp_ex.h @@ -0,0 +1,166 @@ +/** + * + * @file apm32f4xx_dal_cryp_ex.h + * @brief Header file of CRYP DAL Extension module. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef APM32F4xx_DAL_CRYP_EX_H +#define APM32F4xx_DAL_CRYP_EX_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal_def.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @addtogroup CRYPEx + * @{ + */ +/* Exported types ------------------------------------------------------------*/ +/** @defgroup CRYPEx_Exported_Types CRYPEx Exported types + * @{ + */ + +/** + * @} + */ +/* Exported constants --------------------------------------------------------*/ +/** @defgroup CRYPEx_Exported_Constants CRYPEx Exported constants + * @{ + */ + +/** + * @} + */ + +/* Private types -------------------------------------------------------------*/ +/** @defgroup CRYPEx_Private_Types CRYPEx Private Types + * @{ + */ + +/** + * @} + */ + +/* Private variables ---------------------------------------------------------*/ +/** @defgroup CRYPEx_Private_Variables CRYPEx Private Variables + * @{ + */ + +/** + * @} + */ + +/* Private constants ---------------------------------------------------------*/ +/** @defgroup CRYPEx_Private_Constants CRYPEx Private Constants + * @{ + */ + +/** + * @} + */ + +/* Private macros ------------------------------------------------------------*/ +/** @defgroup CRYPEx_Private_Macros CRYPEx Private Macros + * @{ + */ + +/** + * @} + */ + +/* Private functions ---------------------------------------------------------*/ +/** @defgroup CRYPEx_Private_Functions CRYPEx Private Functions + * @{ + */ + +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +/** @defgroup CRYPEx_Exported_Functions CRYPEx Exported Functions + * @{ + */ +#if defined (CRYP) || defined (AES) +/** @addtogroup CRYPEx_Exported_Functions_Group1 + * @{ + */ +DAL_StatusTypeDef DAL_CRYPEx_AESGCM_GenerateAuthTAG(CRYP_HandleTypeDef *hcryp, uint32_t *AuthTag, uint32_t Timeout); +DAL_StatusTypeDef DAL_CRYPEx_AESCCM_GenerateAuthTAG(CRYP_HandleTypeDef *hcryp, uint32_t *AuthTag, uint32_t Timeout); +/** + * @} + */ +#endif /* CRYP||AES */ + +#if defined (AES) +/** @addtogroup CRYPEx_Exported_Functions_Group2 + * @{ + */ +void DAL_CRYPEx_EnableAutoKeyDerivation(CRYP_HandleTypeDef *hcryp); +void DAL_CRYPEx_DisableAutoKeyDerivation(CRYP_HandleTypeDef *hcryp); +/** + * @} + */ +#endif /* AES */ + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* APM32F4xx_DAL_CRYP_EX_H */ + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_dac.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_dac.h new file mode 100644 index 0000000000..46bf3e4b8e --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_dac.h @@ -0,0 +1,504 @@ +/** + * + * @file apm32f4xx_dal_dac.h + * @brief Header file of DAC DAL module. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef APM32F4xx_DAL_DAC_H +#define APM32F4xx_DAL_DAC_H + +#ifdef __cplusplus +extern "C" { +#endif + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal_def.h" + +#if defined(DAC) + +/** @addtogroup DAC + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ + +/** @defgroup DAC_Exported_Types DAC Exported Types + * @{ + */ + +/** + * @brief DAL State structures definition + */ +typedef enum +{ + DAL_DAC_STATE_RESET = 0x00U, /*!< DAC not yet initialized or disabled */ + DAL_DAC_STATE_READY = 0x01U, /*!< DAC initialized and ready for use */ + DAL_DAC_STATE_BUSY = 0x02U, /*!< DAC internal processing is ongoing */ + DAL_DAC_STATE_TIMEOUT = 0x03U, /*!< DAC timeout state */ + DAL_DAC_STATE_ERROR = 0x04U /*!< DAC error state */ + +} DAL_DAC_StateTypeDef; + +/** + * @brief DAC handle Structure definition + */ +#if (USE_DAL_DAC_REGISTER_CALLBACKS == 1) +typedef struct __DAC_HandleTypeDef +#else +typedef struct +#endif /* USE_DAL_DAC_REGISTER_CALLBACKS */ +{ + DAC_TypeDef *Instance; /*!< Register base address */ + + __IO DAL_DAC_StateTypeDef State; /*!< DAC communication state */ + + DAL_LockTypeDef Lock; /*!< DAC locking object */ + + DMA_HandleTypeDef *DMA_Handle1; /*!< Pointer DMA handler for channel 1 */ + + DMA_HandleTypeDef *DMA_Handle2; /*!< Pointer DMA handler for channel 2 */ + + __IO uint32_t ErrorCode; /*!< DAC Error code */ + +#if (USE_DAL_DAC_REGISTER_CALLBACKS == 1) + void (* ConvCpltCallbackCh1) (struct __DAC_HandleTypeDef *hdac); + void (* ConvHalfCpltCallbackCh1) (struct __DAC_HandleTypeDef *hdac); + void (* ErrorCallbackCh1) (struct __DAC_HandleTypeDef *hdac); + void (* DMAUnderrunCallbackCh1) (struct __DAC_HandleTypeDef *hdac); +#if defined(DAC_CHANNEL2_SUPPORT) + void (* ConvCpltCallbackCh2) (struct __DAC_HandleTypeDef *hdac); + void (* ConvHalfCpltCallbackCh2) (struct __DAC_HandleTypeDef *hdac); + void (* ErrorCallbackCh2) (struct __DAC_HandleTypeDef *hdac); + void (* DMAUnderrunCallbackCh2) (struct __DAC_HandleTypeDef *hdac); +#endif /* DAC_CHANNEL2_SUPPORT */ + + void (* MspInitCallback) (struct __DAC_HandleTypeDef *hdac); + void (* MspDeInitCallback) (struct __DAC_HandleTypeDef *hdac); +#endif /* USE_DAL_DAC_REGISTER_CALLBACKS */ + +} DAC_HandleTypeDef; + +/** + * @brief DAC Configuration regular Channel structure definition + */ +typedef struct +{ + uint32_t DAC_Trigger; /*!< Specifies the external trigger for the selected DAC channel. + This parameter can be a value of @ref DAC_trigger_selection */ + + uint32_t DAC_OutputBuffer; /*!< Specifies whether the DAC channel output buffer is enabled or disabled. + This parameter can be a value of @ref DAC_output_buffer */ + +} DAC_ChannelConfTypeDef; + +#if (USE_DAL_DAC_REGISTER_CALLBACKS == 1) +/** + * @brief DAL DAC Callback ID enumeration definition + */ +typedef enum +{ + DAL_DAC_CH1_COMPLETE_CB_ID = 0x00U, /*!< DAC CH1 Complete Callback ID */ + DAL_DAC_CH1_HALF_COMPLETE_CB_ID = 0x01U, /*!< DAC CH1 half Complete Callback ID */ + DAL_DAC_CH1_ERROR_ID = 0x02U, /*!< DAC CH1 error Callback ID */ + DAL_DAC_CH1_UNDERRUN_CB_ID = 0x03U, /*!< DAC CH1 underrun Callback ID */ +#if defined(DAC_CHANNEL2_SUPPORT) + DAL_DAC_CH2_COMPLETE_CB_ID = 0x04U, /*!< DAC CH2 Complete Callback ID */ + DAL_DAC_CH2_HALF_COMPLETE_CB_ID = 0x05U, /*!< DAC CH2 half Complete Callback ID */ + DAL_DAC_CH2_ERROR_ID = 0x06U, /*!< DAC CH2 error Callback ID */ + DAL_DAC_CH2_UNDERRUN_CB_ID = 0x07U, /*!< DAC CH2 underrun Callback ID */ +#endif /* DAC_CHANNEL2_SUPPORT */ + DAL_DAC_MSPINIT_CB_ID = 0x08U, /*!< DAC MspInit Callback ID */ + DAL_DAC_MSPDEINIT_CB_ID = 0x09U, /*!< DAC MspDeInit Callback ID */ + DAL_DAC_ALL_CB_ID = 0x0AU /*!< DAC All ID */ +} DAL_DAC_CallbackIDTypeDef; + +/** + * @brief DAL DAC Callback pointer definition + */ +typedef void (*pDAC_CallbackTypeDef)(DAC_HandleTypeDef *hdac); +#endif /* USE_DAL_DAC_REGISTER_CALLBACKS */ + +/** + * @} + */ + +/* Exported constants --------------------------------------------------------*/ + +/** @defgroup DAC_Exported_Constants DAC Exported Constants + * @{ + */ + +/** @defgroup DAC_Error_Code DAC Error Code + * @{ + */ +#define DAL_DAC_ERROR_NONE 0x00U /*!< No error */ +#define DAL_DAC_ERROR_DMAUNDERRUNCH1 0x01U /*!< DAC channel1 DMA underrun error */ +#if defined(DAC_CHANNEL2_SUPPORT) +#define DAL_DAC_ERROR_DMAUNDERRUNCH2 0x02U /*!< DAC channel2 DMA underrun error */ +#endif /* DAC_CHANNEL2_SUPPORT */ +#define DAL_DAC_ERROR_DMA 0x04U /*!< DMA error */ +#define DAL_DAC_ERROR_TIMEOUT 0x08U /*!< Timeout error */ +#if (USE_DAL_DAC_REGISTER_CALLBACKS == 1) +#define DAL_DAC_ERROR_INVALID_CALLBACK 0x10U /*!< Invalid callback error */ +#endif /* USE_DAL_DAC_REGISTER_CALLBACKS */ + +/** + * @} + */ + +/** @defgroup DAC_trigger_selection DAC trigger selection + * @{ + */ +#define DAC_TRIGGER_NONE 0x00000000UL /*!< Conversion is automatic once the DAC1_DHRxxxx register has been loaded, and not by external trigger */ +#define DAC_TRIGGER_T2_TRGO (DAC_CTRL_TRGSELCH1_2 | DAC_CTRL_TRGENCH1) /*!< TIM2 TRGO selected as external conversion trigger for DAC channel */ +#define DAC_TRIGGER_T4_TRGO (DAC_CTRL_TRGSELCH1_2 | DAC_CTRL_TRGSELCH1_0 | DAC_CTRL_TRGENCH1) /*!< TIM4 TRGO selected as external conversion trigger for DAC channel */ +#define DAC_TRIGGER_T5_TRGO ( DAC_CTRL_TRGSELCH1_1 | DAC_CTRL_TRGSELCH1_0 | DAC_CTRL_TRGENCH1) /*!< TIM3 TRGO selected as external conversion trigger for DAC channel */ +#define DAC_TRIGGER_T6_TRGO ( DAC_CTRL_TRGENCH1) /*!< Conversion started by software trigger for DAC channel */ +#define DAC_TRIGGER_T7_TRGO ( DAC_CTRL_TRGSELCH1_1 | DAC_CTRL_TRGENCH1) /*!< TIM7 TRGO selected as external conversion trigger for DAC channel */ +#define DAC_TRIGGER_T8_TRGO ( DAC_CTRL_TRGSELCH1_0 | DAC_CTRL_TRGENCH1) /*!< TIM8 TRGO selected as external conversion trigger for DAC channel */ +#define DAC_TRIGGER_EXT_IT9 (DAC_CTRL_TRGSELCH1_2 | DAC_CTRL_TRGSELCH1_1 | DAC_CTRL_TRGENCH1) /*!< EXTI Line9 event selected as external conversion trigger for DAC channel */ +#define DAC_TRIGGER_SOFTWARE (DAC_CTRL_TRGSELCH1 | DAC_CTRL_TRGENCH1) /*!< Conversion started by software trigger for DAC channel */ + +/** + * @} + */ + +/** @defgroup DAC_output_buffer DAC output buffer + * @{ + */ +#define DAC_OUTPUTBUFFER_ENABLE 0x00000000U +#define DAC_OUTPUTBUFFER_DISABLE (DAC_CTRL_BUFFDCH1) + +/** + * @} + */ + +/** @defgroup DAC_Channel_selection DAC Channel selection + * @{ + */ +#define DAC_CHANNEL_1 0x00000000U +#if defined(DAC_CHANNEL2_SUPPORT) +#define DAC_CHANNEL_2 0x00000010U +#endif /* DAC_CHANNEL2_SUPPORT */ +/** + * @} + */ + +/** @defgroup DAC_data_alignment DAC data alignment + * @{ + */ +#define DAC_ALIGN_12B_R 0x00000000U +#define DAC_ALIGN_12B_L 0x00000004U +#define DAC_ALIGN_8B_R 0x00000008U + +/** + * @} + */ + +/** @defgroup DAC_flags_definition DAC flags definition + * @{ + */ +#define DAC_FLAG_DMAUDR1 (DAC_STS_DMAUDFLG1) +#if defined(DAC_CHANNEL2_SUPPORT) +#define DAC_FLAG_DMAUDR2 (DAC_STS_DMAUDFLG2) +#endif /* DAC_CHANNEL2_SUPPORT */ + +/** + * @} + */ + +/** @defgroup DAC_IT_definition DAC IT definition + * @{ + */ +#define DAC_IT_DMAUDR1 (DAC_STS_DMAUDFLG1) +#if defined(DAC_CHANNEL2_SUPPORT) +#define DAC_IT_DMAUDR2 (DAC_STS_DMAUDFLG2) +#endif /* DAC_CHANNEL2_SUPPORT */ + +/** + * @} + */ + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ + +/** @defgroup DAC_Exported_Macros DAC Exported Macros + * @{ + */ + +/** @brief Reset DAC handle state. + * @param __HANDLE__ specifies the DAC handle. + * @retval None + */ +#if (USE_DAL_DAC_REGISTER_CALLBACKS == 1) +#define __DAL_DAC_RESET_HANDLE_STATE(__HANDLE__) do { \ + (__HANDLE__)->State = DAL_DAC_STATE_RESET; \ + (__HANDLE__)->MspInitCallback = NULL; \ + (__HANDLE__)->MspDeInitCallback = NULL; \ + } while(0) +#else +#define __DAL_DAC_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = DAL_DAC_STATE_RESET) +#endif /* USE_DAL_DAC_REGISTER_CALLBACKS */ + +/** @brief Enable the DAC channel. + * @param __HANDLE__ specifies the DAC handle. + * @param __DAC_Channel__ specifies the DAC channel + * @retval None + */ +#define __DAL_DAC_ENABLE(__HANDLE__, __DAC_Channel__) \ + ((__HANDLE__)->Instance->CTRL |= (DAC_CTRL_ENCH1 << ((__DAC_Channel__) & 0x10UL))) + +/** @brief Disable the DAC channel. + * @param __HANDLE__ specifies the DAC handle + * @param __DAC_Channel__ specifies the DAC channel. + * @retval None + */ +#define __DAL_DAC_DISABLE(__HANDLE__, __DAC_Channel__) \ + ((__HANDLE__)->Instance->CTRL &= ~(DAC_CTRL_ENCH1 << ((__DAC_Channel__) & 0x10UL))) + +/** @brief Set DHR12R1 alignment. + * @param __ALIGNMENT__ specifies the DAC alignment + * @retval None + */ +#define DAC_DH12R1_ALIGNMENT(__ALIGNMENT__) (0x00000008UL + (__ALIGNMENT__)) + +#if defined(DAC_CHANNEL2_SUPPORT) +/** @brief Set DHR12R2 alignment. + * @param __ALIGNMENT__ specifies the DAC alignment + * @retval None + */ +#define DAC_DH12R2_ALIGNMENT(__ALIGNMENT__) (0x00000014UL + (__ALIGNMENT__)) +#endif /* DAC_CHANNEL2_SUPPORT */ + +/** @brief Set DHR12RD alignment. + * @param __ALIGNMENT__ specifies the DAC alignment + * @retval None + */ +#define DAC_DH12RDUAL_ALIGNMENT(__ALIGNMENT__) (0x00000020UL + (__ALIGNMENT__)) + +/** @brief Enable the DAC interrupt. + * @param __HANDLE__ specifies the DAC handle + * @param __INTERRUPT__ specifies the DAC interrupt. + * This parameter can be any combination of the following values: + * @arg DAC_IT_DMAUDR1 DAC channel 1 DMA underrun interrupt + * @arg DAC_IT_DMAUDR2 DAC channel 2 DMA underrun interrupt + * @retval None + */ +#define __DAL_DAC_ENABLE_IT(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->CTRL) |= (__INTERRUPT__)) + +/** @brief Disable the DAC interrupt. + * @param __HANDLE__ specifies the DAC handle + * @param __INTERRUPT__ specifies the DAC interrupt. + * This parameter can be any combination of the following values: + * @arg DAC_IT_DMAUDR1 DAC channel 1 DMA underrun interrupt + * @arg DAC_IT_DMAUDR2 DAC channel 2 DMA underrun interrupt + * @retval None + */ +#define __DAL_DAC_DISABLE_IT(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->CTRL) &= ~(__INTERRUPT__)) + +/** @brief Check whether the specified DAC interrupt source is enabled or not. + * @param __HANDLE__ DAC handle + * @param __INTERRUPT__ DAC interrupt source to check + * This parameter can be any combination of the following values: + * @arg DAC_IT_DMAUDR1 DAC channel 1 DMA underrun interrupt + * @arg DAC_IT_DMAUDR2 DAC channel 2 DMA underrun interrupt + * @retval State of interruption (SET or RESET) + */ +#define __DAL_DAC_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->CTRL\ + & (__INTERRUPT__)) == (__INTERRUPT__)) + +/** @brief Get the selected DAC's flag status. + * @param __HANDLE__ specifies the DAC handle. + * @param __FLAG__ specifies the DAC flag to get. + * This parameter can be any combination of the following values: + * @arg DAC_FLAG_DMAUDR1 DAC channel 1 DMA underrun flag + * @arg DAC_FLAG_DMAUDR2 DAC channel 2 DMA underrun flag + * @retval None + */ +#define __DAL_DAC_GET_FLAG(__HANDLE__, __FLAG__) ((((__HANDLE__)->Instance->STS) & (__FLAG__)) == (__FLAG__)) + +/** @brief Clear the DAC's flag. + * @param __HANDLE__ specifies the DAC handle. + * @param __FLAG__ specifies the DAC flag to clear. + * This parameter can be any combination of the following values: + * @arg DAC_FLAG_DMAUDR1 DAC channel 1 DMA underrun flag + * @arg DAC_FLAG_DMAUDR2 DAC channel 2 DMA underrun flag + * @retval None + */ +#define __DAL_DAC_CLEAR_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->STS) = (__FLAG__)) + +/** + * @} + */ + +/* Private macro -------------------------------------------------------------*/ + +/** @defgroup DAC_Private_Macros DAC Private Macros + * @{ + */ +#define IS_DAC_OUTPUT_BUFFER_STATE(STATE) (((STATE) == DAC_OUTPUTBUFFER_ENABLE) || \ + ((STATE) == DAC_OUTPUTBUFFER_DISABLE)) + +#if defined(DAC_CHANNEL2_SUPPORT) +#define IS_DAC_CHANNEL(CHANNEL) (((CHANNEL) == DAC_CHANNEL_1) || \ + ((CHANNEL) == DAC_CHANNEL_2)) +#else +#define IS_DAC_CHANNEL(CHANNEL) ((CHANNEL) == DAC_CHANNEL_1) +#endif /* DAC_CHANNEL2_SUPPORT */ + +#define IS_DAC_ALIGN(ALIGN) (((ALIGN) == DAC_ALIGN_12B_R) || \ + ((ALIGN) == DAC_ALIGN_12B_L) || \ + ((ALIGN) == DAC_ALIGN_8B_R)) + +#define IS_DAC_DATA(DATA) ((DATA) <= 0xFFF0UL) + +/** + * @} + */ + +/* Include DAC DAL Extended module */ +#include "apm32f4xx_dal_dac_ex.h" + +/* Exported functions --------------------------------------------------------*/ + +/** @addtogroup DAC_Exported_Functions + * @{ + */ + +/** @addtogroup DAC_Exported_Functions_Group1 + * @{ + */ +/* Initialization and de-initialization functions *****************************/ +DAL_StatusTypeDef DAL_DAC_Init(DAC_HandleTypeDef *hdac); +DAL_StatusTypeDef DAL_DAC_DeInit(DAC_HandleTypeDef *hdac); +void DAL_DAC_MspInit(DAC_HandleTypeDef *hdac); +void DAL_DAC_MspDeInit(DAC_HandleTypeDef *hdac); + +/** + * @} + */ + +/** @addtogroup DAC_Exported_Functions_Group2 + * @{ + */ +/* IO operation functions *****************************************************/ +DAL_StatusTypeDef DAL_DAC_Start(DAC_HandleTypeDef *hdac, uint32_t Channel); +DAL_StatusTypeDef DAL_DAC_Stop(DAC_HandleTypeDef *hdac, uint32_t Channel); +DAL_StatusTypeDef DAL_DAC_Start_DMA(DAC_HandleTypeDef *hdac, uint32_t Channel, uint32_t *pData, uint32_t Length, + uint32_t Alignment); +DAL_StatusTypeDef DAL_DAC_Stop_DMA(DAC_HandleTypeDef *hdac, uint32_t Channel); +void DAL_DAC_IRQHandler(DAC_HandleTypeDef *hdac); +DAL_StatusTypeDef DAL_DAC_SetValue(DAC_HandleTypeDef *hdac, uint32_t Channel, uint32_t Alignment, uint32_t Data); + +void DAL_DAC_ConvCpltCallbackCh1(DAC_HandleTypeDef *hdac); +void DAL_DAC_ConvHalfCpltCallbackCh1(DAC_HandleTypeDef *hdac); +void DAL_DAC_ErrorCallbackCh1(DAC_HandleTypeDef *hdac); +void DAL_DAC_DMAUnderrunCallbackCh1(DAC_HandleTypeDef *hdac); + +#if (USE_DAL_DAC_REGISTER_CALLBACKS == 1) +/* DAC callback registering/unregistering */ +DAL_StatusTypeDef DAL_DAC_RegisterCallback(DAC_HandleTypeDef *hdac, DAL_DAC_CallbackIDTypeDef CallbackID, + pDAC_CallbackTypeDef pCallback); +DAL_StatusTypeDef DAL_DAC_UnRegisterCallback(DAC_HandleTypeDef *hdac, DAL_DAC_CallbackIDTypeDef CallbackID); +#endif /* USE_DAL_DAC_REGISTER_CALLBACKS */ + +/** + * @} + */ + +/** @addtogroup DAC_Exported_Functions_Group3 + * @{ + */ +/* Peripheral Control functions ***********************************************/ +uint32_t DAL_DAC_GetValue(DAC_HandleTypeDef *hdac, uint32_t Channel); +DAL_StatusTypeDef DAL_DAC_ConfigChannel(DAC_HandleTypeDef *hdac, DAC_ChannelConfTypeDef *sConfig, uint32_t Channel); +/** + * @} + */ + +/** @addtogroup DAC_Exported_Functions_Group4 + * @{ + */ +/* Peripheral State and Error functions ***************************************/ +DAL_DAC_StateTypeDef DAL_DAC_GetState(DAC_HandleTypeDef *hdac); +uint32_t DAL_DAC_GetError(DAC_HandleTypeDef *hdac); + +/** + * @} + */ + +/** + * @} + */ + +/** @defgroup DAC_Private_Functions DAC Private Functions + * @{ + */ +void DAC_DMAConvCpltCh1(DMA_HandleTypeDef *hdma); +void DAC_DMAErrorCh1(DMA_HandleTypeDef *hdma); +void DAC_DMAHalfConvCpltCh1(DMA_HandleTypeDef *hdma); +/** + * @} + */ + +/** + * @} + */ + +#endif /* DAC */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + + +#endif /* APM32F4xx_DAL_DAC_H */ + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_dac_ex.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_dac_ex.h new file mode 100644 index 0000000000..366f814d8f --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_dac_ex.h @@ -0,0 +1,229 @@ +/** + * + * @file apm32f4xx_dal_dac_ex.h + * @brief Header file of DAC DAL Extended module. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef APM32F4xx_DAL_DAC_EX_H +#define APM32F4xx_DAL_DAC_EX_H + +#ifdef __cplusplus +extern "C" { +#endif + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal_def.h" + +#if defined(DAC) + +/** @addtogroup DACEx + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ + +/** + * @brief DAL State structures definition + */ + +/* Exported constants --------------------------------------------------------*/ + +/** @defgroup DACEx_Exported_Constants DACEx Exported Constants + * @{ + */ + +/** @defgroup DACEx_lfsrunmask_triangleamplitude DACEx lfsrunmask triangle amplitude + * @{ + */ +#define DAC_LFSRUNMASK_BIT0 0x00000000UL /*!< Unmask DAC channel LFSR bit0 for noise wave generation */ +#define DAC_LFSRUNMASK_BITS1_0 ( DAC_CTRL_MAMPSELCH1_0) /*!< Unmask DAC channel LFSR bit[1:0] for noise wave generation */ +#define DAC_LFSRUNMASK_BITS2_0 ( DAC_CTRL_MAMPSELCH1_1 ) /*!< Unmask DAC channel LFSR bit[2:0] for noise wave generation */ +#define DAC_LFSRUNMASK_BITS3_0 ( DAC_CTRL_MAMPSELCH1_1 | DAC_CTRL_MAMPSELCH1_0) /*!< Unmask DAC channel LFSR bit[3:0] for noise wave generation */ +#define DAC_LFSRUNMASK_BITS4_0 ( DAC_CTRL_MAMPSELCH1_2 ) /*!< Unmask DAC channel LFSR bit[4:0] for noise wave generation */ +#define DAC_LFSRUNMASK_BITS5_0 ( DAC_CTRL_MAMPSELCH1_2 | DAC_CTRL_MAMPSELCH1_0) /*!< Unmask DAC channel LFSR bit[5:0] for noise wave generation */ +#define DAC_LFSRUNMASK_BITS6_0 ( DAC_CTRL_MAMPSELCH1_2 | DAC_CTRL_MAMPSELCH1_1 ) /*!< Unmask DAC channel LFSR bit[6:0] for noise wave generation */ +#define DAC_LFSRUNMASK_BITS7_0 ( DAC_CTRL_MAMPSELCH1_2 | DAC_CTRL_MAMPSELCH1_1 | DAC_CTRL_MAMPSELCH1_0) /*!< Unmask DAC channel LFSR bit[7:0] for noise wave generation */ +#define DAC_LFSRUNMASK_BITS8_0 (DAC_CTRL_MAMPSELCH1_3 ) /*!< Unmask DAC channel LFSR bit[8:0] for noise wave generation */ +#define DAC_LFSRUNMASK_BITS9_0 (DAC_CTRL_MAMPSELCH1_3 | DAC_CTRL_MAMPSELCH1_0) /*!< Unmask DAC channel LFSR bit[9:0] for noise wave generation */ +#define DAC_LFSRUNMASK_BITS10_0 (DAC_CTRL_MAMPSELCH1_3 | DAC_CTRL_MAMPSELCH1_1 ) /*!< Unmask DAC channel LFSR bit[10:0] for noise wave generation */ +#define DAC_LFSRUNMASK_BITS11_0 (DAC_CTRL_MAMPSELCH1_3 | DAC_CTRL_MAMPSELCH1_1 | DAC_CTRL_MAMPSELCH1_0) /*!< Unmask DAC channel LFSR bit[11:0] for noise wave generation */ +#define DAC_TRIANGLEAMPLITUDE_1 0x00000000UL /*!< Select max triangle amplitude of 1 */ +#define DAC_TRIANGLEAMPLITUDE_3 ( DAC_CTRL_MAMPSELCH1_0) /*!< Select max triangle amplitude of 3 */ +#define DAC_TRIANGLEAMPLITUDE_7 ( DAC_CTRL_MAMPSELCH1_1 ) /*!< Select max triangle amplitude of 7 */ +#define DAC_TRIANGLEAMPLITUDE_15 ( DAC_CTRL_MAMPSELCH1_1 | DAC_CTRL_MAMPSELCH1_0) /*!< Select max triangle amplitude of 15 */ +#define DAC_TRIANGLEAMPLITUDE_31 ( DAC_CTRL_MAMPSELCH1_2 ) /*!< Select max triangle amplitude of 31 */ +#define DAC_TRIANGLEAMPLITUDE_63 ( DAC_CTRL_MAMPSELCH1_2 | DAC_CTRL_MAMPSELCH1_0) /*!< Select max triangle amplitude of 63 */ +#define DAC_TRIANGLEAMPLITUDE_127 ( DAC_CTRL_MAMPSELCH1_2 | DAC_CTRL_MAMPSELCH1_1 ) /*!< Select max triangle amplitude of 127 */ +#define DAC_TRIANGLEAMPLITUDE_255 ( DAC_CTRL_MAMPSELCH1_2 | DAC_CTRL_MAMPSELCH1_1 | DAC_CTRL_MAMPSELCH1_0) /*!< Select max triangle amplitude of 255 */ +#define DAC_TRIANGLEAMPLITUDE_511 (DAC_CTRL_MAMPSELCH1_3 ) /*!< Select max triangle amplitude of 511 */ +#define DAC_TRIANGLEAMPLITUDE_1023 (DAC_CTRL_MAMPSELCH1_3 | DAC_CTRL_MAMPSELCH1_0) /*!< Select max triangle amplitude of 1023 */ +#define DAC_TRIANGLEAMPLITUDE_2047 (DAC_CTRL_MAMPSELCH1_3 | DAC_CTRL_MAMPSELCH1_1 ) /*!< Select max triangle amplitude of 2047 */ +#define DAC_TRIANGLEAMPLITUDE_4095 (DAC_CTRL_MAMPSELCH1_3 | DAC_CTRL_MAMPSELCH1_1 | DAC_CTRL_MAMPSELCH1_0) /*!< Select max triangle amplitude of 4095 */ + +/** + * @} + */ + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ + + +/* Private macro -------------------------------------------------------------*/ + +/** @defgroup DACEx_Private_Macros DACEx Private Macros + * @{ + */ +#define IS_DAC_TRIGGER(TRIGGER) (((TRIGGER) == DAC_TRIGGER_NONE) || \ + ((TRIGGER) == DAC_TRIGGER_T2_TRGO) || \ + ((TRIGGER) == DAC_TRIGGER_T8_TRGO) || \ + ((TRIGGER) == DAC_TRIGGER_T7_TRGO) || \ + ((TRIGGER) == DAC_TRIGGER_T5_TRGO) || \ + ((TRIGGER) == DAC_TRIGGER_T6_TRGO) || \ + ((TRIGGER) == DAC_TRIGGER_T4_TRGO) || \ + ((TRIGGER) == DAC_TRIGGER_EXT_IT9) || \ + ((TRIGGER) == DAC_TRIGGER_SOFTWARE)) + +#define IS_DAC_LFSR_UNMASK_TRIANGLE_AMPLITUDE(VALUE) (((VALUE) == DAC_LFSRUNMASK_BIT0) || \ + ((VALUE) == DAC_LFSRUNMASK_BITS1_0) || \ + ((VALUE) == DAC_LFSRUNMASK_BITS2_0) || \ + ((VALUE) == DAC_LFSRUNMASK_BITS3_0) || \ + ((VALUE) == DAC_LFSRUNMASK_BITS4_0) || \ + ((VALUE) == DAC_LFSRUNMASK_BITS5_0) || \ + ((VALUE) == DAC_LFSRUNMASK_BITS6_0) || \ + ((VALUE) == DAC_LFSRUNMASK_BITS7_0) || \ + ((VALUE) == DAC_LFSRUNMASK_BITS8_0) || \ + ((VALUE) == DAC_LFSRUNMASK_BITS9_0) || \ + ((VALUE) == DAC_LFSRUNMASK_BITS10_0) || \ + ((VALUE) == DAC_LFSRUNMASK_BITS11_0) || \ + ((VALUE) == DAC_TRIANGLEAMPLITUDE_1) || \ + ((VALUE) == DAC_TRIANGLEAMPLITUDE_3) || \ + ((VALUE) == DAC_TRIANGLEAMPLITUDE_7) || \ + ((VALUE) == DAC_TRIANGLEAMPLITUDE_15) || \ + ((VALUE) == DAC_TRIANGLEAMPLITUDE_31) || \ + ((VALUE) == DAC_TRIANGLEAMPLITUDE_63) || \ + ((VALUE) == DAC_TRIANGLEAMPLITUDE_127) || \ + ((VALUE) == DAC_TRIANGLEAMPLITUDE_255) || \ + ((VALUE) == DAC_TRIANGLEAMPLITUDE_511) || \ + ((VALUE) == DAC_TRIANGLEAMPLITUDE_1023) || \ + ((VALUE) == DAC_TRIANGLEAMPLITUDE_2047) || \ + ((VALUE) == DAC_TRIANGLEAMPLITUDE_4095)) +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +/* Extended features functions ***********************************************/ + +/** @addtogroup DACEx_Exported_Functions + * @{ + */ + +/** @addtogroup DACEx_Exported_Functions_Group2 + * @{ + */ +/* IO operation functions *****************************************************/ + +DAL_StatusTypeDef DAL_DACEx_TriangleWaveGenerate(DAC_HandleTypeDef *hdac, uint32_t Channel, uint32_t Amplitude); +DAL_StatusTypeDef DAL_DACEx_NoiseWaveGenerate(DAC_HandleTypeDef *hdac, uint32_t Channel, uint32_t Amplitude); + +#if defined(DAC_CHANNEL2_SUPPORT) +#endif +DAL_StatusTypeDef DAL_DACEx_DualStart(DAC_HandleTypeDef *hdac); +DAL_StatusTypeDef DAL_DACEx_DualStop(DAC_HandleTypeDef *hdac); +DAL_StatusTypeDef DAL_DACEx_DualSetValue(DAC_HandleTypeDef *hdac, uint32_t Alignment, uint32_t Data1, uint32_t Data2); +uint32_t DAL_DACEx_DualGetValue(DAC_HandleTypeDef *hdac); + +#if defined(DAC_CHANNEL2_SUPPORT) +#endif +void DAL_DACEx_ConvCpltCallbackCh2(DAC_HandleTypeDef *hdac); +void DAL_DACEx_ConvHalfCpltCallbackCh2(DAC_HandleTypeDef *hdac); +void DAL_DACEx_ErrorCallbackCh2(DAC_HandleTypeDef *hdac); +void DAL_DACEx_DMAUnderrunCallbackCh2(DAC_HandleTypeDef *hdac); + + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +/** @addtogroup DACEx_Private_Functions + * @{ + */ +#if defined(DAC_CHANNEL2_SUPPORT) +/* DAC_DMAConvCpltCh2 / DAC_DMAErrorCh2 / DAC_DMAHalfConvCpltCh2 */ +/* are called by DAL_DAC_Start_DMA */ +void DAC_DMAConvCpltCh2(DMA_HandleTypeDef *hdma); +void DAC_DMAErrorCh2(DMA_HandleTypeDef *hdma); +void DAC_DMAHalfConvCpltCh2(DMA_HandleTypeDef *hdma); +#endif /* DAC_CHANNEL2_SUPPORT */ +/** + * @} + */ + +/** + * @} + */ + +#endif /* DAC */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* APM32F4xx_DAL_DAC_EX_H */ + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_dci.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_dci.h new file mode 100644 index 0000000000..88c1410c17 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_dci.h @@ -0,0 +1,583 @@ +/** + * + * @file apm32f4xx_dal_dci.h + * @brief Header file of DCI DAL module. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2017 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file in + * the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef APM32F4xx_DAL_DCI_H +#define APM32F4xx_DAL_DCI_H + +#ifdef __cplusplus + extern "C" { +#endif + +#if defined(APM32F407xx) || defined(APM32F417xx) +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal_def.h" + +/* Include DCI DAL Extended module */ +/* (include on top of file since DCI structures are defined in extended file) */ +#include "apm32f4xx_dal_dci_ex.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @addtogroup DCI DCI + * @brief DCI DAL module driver + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ +/** @defgroup DCI_Exported_Types DCI Exported Types + * @{ + */ +/** + * @brief DCI Embedded Synchronisation CODE Init structure definition + */ +typedef struct +{ + uint8_t FrameStartUnmask; /*!< Specifies the frame start delimiter unmask. */ + uint8_t LineStartUnmask; /*!< Specifies the line start delimiter unmask. */ + uint8_t LineEndUnmask; /*!< Specifies the line end delimiter unmask. */ + uint8_t FrameEndUnmask; /*!< Specifies the frame end delimiter unmask. */ +}DCI_SyncUnmaskTypeDef; +/** + * @brief DAL DCI State structures definition + */ +typedef enum +{ + DAL_DCI_STATE_RESET = 0x00U, /*!< DCI not yet initialized or disabled */ + DAL_DCI_STATE_READY = 0x01U, /*!< DCI initialized and ready for use */ + DAL_DCI_STATE_BUSY = 0x02U, /*!< DCI internal processing is ongoing */ + DAL_DCI_STATE_TIMEOUT = 0x03U, /*!< DCI timeout state */ + DAL_DCI_STATE_ERROR = 0x04U, /*!< DCI error state */ + DAL_DCI_STATE_SUSPENDED = 0x05U /*!< DCI suspend state */ +}DAL_DCI_StateTypeDef; + +/** + * @brief DCI handle Structure definition + */ +typedef struct __DCI_HandleTypeDef +{ + DCI_TypeDef *Instance; /*!< DCI Register base address */ + + DCI_InitTypeDef Init; /*!< DCI parameters */ + + DAL_LockTypeDef Lock; /*!< DCI locking object */ + + __IO DAL_DCI_StateTypeDef State; /*!< DCI state */ + + __IO uint32_t XferCount; /*!< DMA transfer counter */ + + __IO uint32_t XferSize; /*!< DMA transfer size */ + + uint32_t XferTransferNumber; /*!< DMA transfer number */ + + uint32_t pBuffPtr; /*!< Pointer to DMA output buffer */ + + DMA_HandleTypeDef *DMA_Handle; /*!< Pointer to the DMA handler */ + + __IO uint32_t ErrorCode; /*!< DCI Error code */ +#if (USE_DAL_DCI_REGISTER_CALLBACKS == 1) + void (* FrameEventCallback) ( struct __DCI_HandleTypeDef *hdci); /*!< DCI Frame Event Callback */ + void (* VsyncEventCallback) ( struct __DCI_HandleTypeDef *hdci); /*!< DCI Vsync Event Callback */ + void (* LineEventCallback ) ( struct __DCI_HandleTypeDef *hdci); /*!< DCI Line Event Callback */ + void (* ErrorCallback) ( struct __DCI_HandleTypeDef *hdci); /*!< DCI Error Callback */ + void (* MspInitCallback) ( struct __DCI_HandleTypeDef *hdci); /*!< DCI Msp Init callback */ + void (* MspDeInitCallback) ( struct __DCI_HandleTypeDef *hdci); /*!< DCI Msp DeInit callback */ +#endif /* USE_DAL_DCI_REGISTER_CALLBACKS */ +}DCI_HandleTypeDef; + +#if (USE_DAL_DCI_REGISTER_CALLBACKS == 1) +typedef enum +{ + DAL_DCI_FRAME_EVENT_CB_ID = 0x00U, /*!< DCI Frame Event Callback ID */ + DAL_DCI_VSYNC_EVENT_CB_ID = 0x01U, /*!< DCI Vsync Event Callback ID */ + DAL_DCI_LINE_EVENT_CB_ID = 0x02U, /*!< DCI Line Event Callback ID */ + DAL_DCI_ERROR_CB_ID = 0x03U, /*!< DCI Error Callback ID */ + DAL_DCI_MSPINIT_CB_ID = 0x04U, /*!< DCI MspInit callback ID */ + DAL_DCI_MSPDEINIT_CB_ID = 0x05U /*!< DCI MspDeInit callback ID */ + +}DAL_DCI_CallbackIDTypeDef; + +typedef void (*pDCI_CallbackTypeDef)(DCI_HandleTypeDef *hdci); +#endif /* USE_DAL_DCI_REGISTER_CALLBACKS */ + + +/** + * @} + */ + +/* Exported constants --------------------------------------------------------*/ +/** @defgroup DCI_Exported_Constants DCI Exported Constants + * @{ + */ + +/** @defgroup DCI_Error_Code DCI Error Code + * @{ + */ +#define DAL_DCI_ERROR_NONE 0x00000000U /*!< No error */ +#define DAL_DCI_ERROR_OVR 0x00000001U /*!< Overrun error */ +#define DAL_DCI_ERROR_SYNC 0x00000002U /*!< Synchronization error */ +#define DAL_DCI_ERROR_TIMEOUT 0x00000020U /*!< Timeout error */ +#define DAL_DCI_ERROR_DMA 0x00000040U /*!< DMA error */ +#if (USE_DAL_DCI_REGISTER_CALLBACKS == 1) +#define DAL_DCI_ERROR_INVALID_CALLBACK ((uint32_t)0x00000080U) /*!< Invalid callback error */ +#endif +/** + * @} + */ + +/** @defgroup DCI_Capture_Mode DCI Capture Mode + * @{ + */ +#define DCI_MODE_CONTINUOUS 0x00000000U /*!< The received data are transferred continuously + into the destination memory through the DMA */ +#define DCI_MODE_SNAPSHOT ((uint32_t)DCI_CTRL_CMODE) /*!< Once activated, the interface waits for the start of + frame and then transfers a single frame through the DMA */ +/** + * @} + */ + +/** @defgroup DCI_Synchronization_Mode DCI Synchronization Mode + * @{ + */ +#define DCI_SYNCHRO_HARDWARE 0x00000000U /*!< Hardware synchronization data capture (frame/line start/stop) + is synchronized with the HSYNC/VSYNC signals */ +#define DCI_SYNCHRO_EMBEDDED ((uint32_t)DCI_CTRL_ESYNCSEL) /*!< Embedded synchronization data capture is synchronized with + synchronization codes embedded in the data flow */ + +/** + * @} + */ + +/** @defgroup DCI_PIXCK_Polarity DCI PIXCK Polarity + * @{ + */ +#define DCI_PCKPOLARITY_FALLING 0x00000000U /*!< Pixel clock active on Falling edge */ +#define DCI_PCKPOLARITY_RISING ((uint32_t)DCI_CTRL_PXCLKPOL) /*!< Pixel clock active on Rising edge */ + +/** + * @} + */ + +/** @defgroup DCI_VSYNC_Polarity DCI VSYNC Polarity + * @{ + */ +#define DCI_VSPOLARITY_LOW 0x00000000U /*!< Vertical synchronization active Low */ +#define DCI_VSPOLARITY_HIGH ((uint32_t)DCI_CTRL_VSYNCPOL) /*!< Vertical synchronization active High */ + +/** + * @} + */ + +/** @defgroup DCI_HSYNC_Polarity DCI HSYNC Polarity + * @{ + */ +#define DCI_HSPOLARITY_LOW 0x00000000U /*!< Horizontal synchronization active Low */ +#define DCI_HSPOLARITY_HIGH ((uint32_t)DCI_CTRL_HSYNCPOL) /*!< Horizontal synchronization active High */ + +/** + * @} + */ + +/** @defgroup DCI_MODE_JPEG DCI MODE JPEG + * @{ + */ +#define DCI_JPEG_DISABLE 0x00000000U /*!< Mode JPEG Disabled */ +#define DCI_JPEG_ENABLE ((uint32_t)DCI_CTRL_JPGFM) /*!< Mode JPEG Enabled */ + +/** + * @} + */ + +/** @defgroup DCI_Capture_Rate DCI Capture Rate + * @{ + */ +#define DCI_CR_ALL_FRAME 0x00000000U /*!< All frames are captured */ +#define DCI_CR_ALTERNATE_2_FRAME ((uint32_t)DCI_CTRL_FCRCFG_0) /*!< Every alternate frame captured */ +#define DCI_CR_ALTERNATE_4_FRAME ((uint32_t)DCI_CTRL_FCRCFG_1) /*!< One frame in 4 frames captured */ + +/** + * @} + */ + +/** @defgroup DCI_Extended_Data_Mode DCI Extended Data Mode + * @{ + */ +#define DCI_EXTEND_DATA_8B 0x00000000U /*!< Interface captures 8-bit data on every pixel clock */ +#define DCI_EXTEND_DATA_10B ((uint32_t)DCI_CTRL_EXDMOD_0) /*!< Interface captures 10-bit data on every pixel clock */ +#define DCI_EXTEND_DATA_12B ((uint32_t)DCI_CTRL_EXDMOD_1) /*!< Interface captures 12-bit data on every pixel clock */ +#define DCI_EXTEND_DATA_14B ((uint32_t)(DCI_CTRL_EXDMOD_0 | DCI_CTRL_EXDMOD_1)) /*!< Interface captures 14-bit data on every pixel clock */ + +/** + * @} + */ + +/** @defgroup DCI_Window_Coordinate DCI Window Coordinate + * @{ + */ +#define DCI_WINDOW_COORDINATE 0x3FFFU /*!< Window coordinate */ + +/** + * @} + */ + +/** @defgroup DCI_Window_Height DCI Window Height + * @{ + */ +#define DCI_WINDOW_HEIGHT 0x1FFFU /*!< Window Height */ + +/** + * @} + */ + +/** @defgroup DCI_Window_Vertical_Line DCI Window Vertical Line + * @{ + */ +#define DCI_POSITION_CWSIZE_VLINE (uint32_t)DCI_CROPWSIZE_VLINECNT_Pos /*!< Required left shift to set crop window vertical line count */ +#define DCI_POSITION_CWSTRT_VST (uint32_t)DCI_CROPWSTAT_VSLINECNT_Pos /*!< Required left shift to set crop window vertical start line count */ + +/** + * @} + */ + +/** @defgroup DCI_interrupt_sources DCI interrupt sources + * @{ + */ +#define DCI_IT_FRAME ((uint32_t)DCI_INTEN_CCINTEN) /*!< Capture complete interrupt */ +#define DCI_IT_OVR ((uint32_t)DCI_INTEN_OVRINTEN) /*!< Overrun interrupt */ +#define DCI_IT_ERR ((uint32_t)DCI_INTEN_SYNCERRINTEN) /*!< Synchronization error interrupt */ +#define DCI_IT_VSYNC ((uint32_t)DCI_INTEN_VSYNCINTEN) /*!< VSYNC interrupt */ +#define DCI_IT_LINE ((uint32_t)DCI_INTEN_LINEINTEN) /*!< Line interrupt */ +/** + * @} + */ + +/** @defgroup DCI_Flags DCI Flags + * @{ + */ + +/** + * @brief DCI SR register + */ +#define DCI_FLAG_HSYNC ((uint32_t)DCI_STS_INDEX|DCI_STS_HSYNCSTS) /*!< HSYNC pin state (active line / synchronization between lines) */ +#define DCI_FLAG_VSYNC ((uint32_t)DCI_STS_INDEX|DCI_STS_VSYNCSTS) /*!< VSYNC pin state (active frame / synchronization between frames) */ +#define DCI_FLAG_FNE ((uint32_t)DCI_STS_INDEX|DCI_STS_FIFONEMP) /*!< FIFO not empty flag */ +/** + * @brief DCI RIS register + */ +#define DCI_FLAG_FRAMERI ((uint32_t)DCI_RINTSTS_CC_RINT_RIS) /*!< Frame capture complete interrupt flag */ +#define DCI_FLAG_OVRRI ((uint32_t)DCI_RINTSTS_OVR_RINT_RIS) /*!< Overrun interrupt flag */ +#define DCI_FLAG_ERRRI ((uint32_t)DCI_RINTSTS_SYNCERR_RINT_RIS) /*!< Synchronization error interrupt flag */ +#define DCI_FLAG_VSYNCRI ((uint32_t)DCI_RINTSTS_VSYNC_RINT_RIS) /*!< VSYNC interrupt flag */ +#define DCI_FLAG_LINERI ((uint32_t)DCI_RINTSTS_LINE_RINT_RIS) /*!< Line interrupt flag */ +/** + * @brief DCI MIS register + */ +#define DCI_FLAG_FRAMEMI ((uint32_t)DCI_MIS_INDEX|DCI_MIS_FRAME_MIS) /*!< DCI Frame capture complete masked interrupt status */ +#define DCI_FLAG_OVRMI ((uint32_t)DCI_MIS_INDEX|DCI_MIS_OVR_MIS ) /*!< DCI Overrun masked interrupt status */ +#define DCI_FLAG_ERRMI ((uint32_t)DCI_MIS_INDEX|DCI_MIS_ERR_MIS ) /*!< DCI Synchronization error masked interrupt status */ +#define DCI_FLAG_VSYNCMI ((uint32_t)DCI_MIS_INDEX|DCI_MIS_VSYNC_MIS) /*!< DCI VSYNC masked interrupt status */ +#define DCI_FLAG_LINEMI ((uint32_t)DCI_MIS_INDEX|DCI_MIS_LINE_MIS ) /*!< DCI Line masked interrupt status */ +/** + * @} + */ + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ +/** @defgroup DCI_Exported_Macros DCI Exported Macros + * @{ + */ + +/** @brief Reset DCI handle state + * @param __HANDLE__ specifies the DCI handle. + * @retval None + */ +#define __DAL_DCI_RESET_HANDLE_STATE(__HANDLE__) do{ \ + (__HANDLE__)->State = DAL_DCI_STATE_RESET; \ + (__HANDLE__)->MspInitCallback = NULL; \ + (__HANDLE__)->MspDeInitCallback = NULL; \ + } while(0) + +/** + * @brief Enable the DCI. + * @param __HANDLE__ DCI handle + * @retval None + */ +#define __DAL_DCI_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CTRL |= DCI_CTRL_DCIEN) + +/** + * @brief Disable the DCI. + * @param __HANDLE__ DCI handle + * @retval None + */ +#define __DAL_DCI_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CTRL &= ~(DCI_CTRL_DCIEN)) + +/* Interrupt & Flag management */ +/** + * @brief Get the DCI pending flag. + * @param __HANDLE__ DCI handle + * @param __FLAG__ Get the specified flag. + * This parameter can be one of the following values (no combination allowed) + * @arg DCI_FLAG_HSYNC: HSYNC pin state (active line / synchronization between lines) + * @arg DCI_FLAG_VSYNC: VSYNC pin state (active frame / synchronization between frames) + * @arg DCI_FLAG_FNE: FIFO empty flag + * @arg DCI_FLAG_FRAMERI: Frame capture complete flag mask + * @arg DCI_FLAG_OVRRI: Overrun flag mask + * @arg DCI_FLAG_ERRRI: Synchronization error flag mask + * @arg DCI_FLAG_VSYNCRI: VSYNC flag mask + * @arg DCI_FLAG_LINERI: Line flag mask + * @arg DCI_FLAG_FRAMEMI: DCI Capture complete masked interrupt status + * @arg DCI_FLAG_OVRMI: DCI Overrun masked interrupt status + * @arg DCI_FLAG_ERRMI: DCI Synchronization error masked interrupt status + * @arg DCI_FLAG_VSYNCMI: DCI VSYNC masked interrupt status + * @arg DCI_FLAG_LINEMI: DCI Line masked interrupt status + * @retval The state of FLAG. + */ +#define __DAL_DCI_GET_FLAG(__HANDLE__, __FLAG__)\ +((((__FLAG__) & (DCI_STS_INDEX|DCI_MIS_INDEX)) == 0x0U)? ((__HANDLE__)->Instance->RINTSTS & (__FLAG__)) :\ + (((__FLAG__) & DCI_STS_INDEX) == 0x0U)? ((__HANDLE__)->Instance->MINTSTS & (__FLAG__)) : ((__HANDLE__)->Instance->STS & (__FLAG__))) + +/** + * @brief Clear the DCI pending flags. + * @param __HANDLE__ DCI handle + * @param __FLAG__ specifies the flag to clear. + * This parameter can be any combination of the following values: + * @arg DCI_FLAG_FRAMERI: Frame capture complete flag mask + * @arg DCI_FLAG_OVRRI: Overrun flag mask + * @arg DCI_FLAG_ERRRI: Synchronization error flag mask + * @arg DCI_FLAG_VSYNCRI: VSYNC flag mask + * @arg DCI_FLAG_LINERI: Line flag mask + * @retval None + */ +#define __DAL_DCI_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->INTCLR = (__FLAG__)) + +/** + * @brief Enable the specified DCI interrupts. + * @param __HANDLE__ DCI handle + * @param __INTERRUPT__ specifies the DCI interrupt sources to be enabled. + * This parameter can be any combination of the following values: + * @arg DCI_IT_FRAME: Frame capture complete interrupt mask + * @arg DCI_IT_OVR: Overrun interrupt mask + * @arg DCI_IT_ERR: Synchronization error interrupt mask + * @arg DCI_IT_VSYNC: VSYNC interrupt mask + * @arg DCI_IT_LINE: Line interrupt mask + * @retval None + */ +#define __DAL_DCI_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->INTEN |= (__INTERRUPT__)) + +/** + * @brief Disable the specified DCI interrupts. + * @param __HANDLE__ DCI handle + * @param __INTERRUPT__ specifies the DCI interrupt sources to be enabled. + * This parameter can be any combination of the following values: + * @arg DCI_IT_FRAME: Frame capture complete interrupt mask + * @arg DCI_IT_OVR: Overrun interrupt mask + * @arg DCI_IT_ERR: Synchronization error interrupt mask + * @arg DCI_IT_VSYNC: VSYNC interrupt mask + * @arg DCI_IT_LINE: Line interrupt mask + * @retval None + */ +#define __DAL_DCI_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->INTEN &= ~(__INTERRUPT__)) + +/** + * @brief Check whether the specified DCI interrupt has occurred or not. + * @param __HANDLE__ DCI handle + * @param __INTERRUPT__ specifies the DCI interrupt source to check. + * This parameter can be one of the following values: + * @arg DCI_IT_FRAME: Frame capture complete interrupt mask + * @arg DCI_IT_OVR: Overrun interrupt mask + * @arg DCI_IT_ERR: Synchronization error interrupt mask + * @arg DCI_IT_VSYNC: VSYNC interrupt mask + * @arg DCI_IT_LINE: Line interrupt mask + * @retval The state of INTERRUPT. + */ +#define __DAL_DCI_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->MINTSTS & (__INTERRUPT__)) + +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup DCI_Exported_Functions DCI Exported Functions + * @{ + */ + +/** @addtogroup DCI_Exported_Functions_Group1 Initialization and Configuration functions + * @{ + */ +/* Initialization and de-initialization functions *****************************/ +DAL_StatusTypeDef DAL_DCI_Init(DCI_HandleTypeDef *hdci); +DAL_StatusTypeDef DAL_DCI_DeInit(DCI_HandleTypeDef *hdci); +void DAL_DCI_MspInit(DCI_HandleTypeDef* hdci); +void DAL_DCI_MspDeInit(DCI_HandleTypeDef* hdci); + +/* Callbacks Register/UnRegister functions ***********************************/ +#if (USE_DAL_DCI_REGISTER_CALLBACKS == 1) +DAL_StatusTypeDef DAL_DCI_RegisterCallback(DCI_HandleTypeDef *hdci, DAL_DCI_CallbackIDTypeDef CallbackID, pDCI_CallbackTypeDef pCallback); +DAL_StatusTypeDef DAL_DCI_UnRegisterCallback(DCI_HandleTypeDef *hdci, DAL_DCI_CallbackIDTypeDef CallbackID); +#endif /* USE_DAL_DCI_REGISTER_CALLBACKS */ +/** + * @} + */ + +/** @addtogroup DCI_Exported_Functions_Group2 IO operation functions + * @{ + */ +/* IO operation functions *****************************************************/ +DAL_StatusTypeDef DAL_DCI_Start_DMA(DCI_HandleTypeDef* hdci, uint32_t DCI_Mode, uint32_t pData, uint32_t Length); +DAL_StatusTypeDef DAL_DCI_Stop(DCI_HandleTypeDef* hdci); +DAL_StatusTypeDef DAL_DCI_Suspend(DCI_HandleTypeDef* hdci); +DAL_StatusTypeDef DAL_DCI_Resume(DCI_HandleTypeDef* hdci); +void DAL_DCI_ErrorCallback(DCI_HandleTypeDef *hdci); +void DAL_DCI_LineEventCallback(DCI_HandleTypeDef *hdci); +void DAL_DCI_FrameEventCallback(DCI_HandleTypeDef *hdci); +void DAL_DCI_VsyncEventCallback(DCI_HandleTypeDef *hdci); +void DAL_DCI_VsyncCallback(DCI_HandleTypeDef *hdci); +void DAL_DCI_HsyncCallback(DCI_HandleTypeDef *hdci); +void DAL_DCI_IRQHandler(DCI_HandleTypeDef *hdci); +/** + * @} + */ + +/** @addtogroup DCI_Exported_Functions_Group3 Peripheral Control functions + * @{ + */ +/* Peripheral Control functions ***********************************************/ +DAL_StatusTypeDef DAL_DCI_ConfigCrop(DCI_HandleTypeDef *hdci, uint32_t X0, uint32_t Y0, uint32_t XSize, uint32_t YSize); +DAL_StatusTypeDef DAL_DCI_EnableCrop(DCI_HandleTypeDef *hdci); +DAL_StatusTypeDef DAL_DCI_DisableCrop(DCI_HandleTypeDef *hdci); +DAL_StatusTypeDef DAL_DCI_ConfigSyncUnmask(DCI_HandleTypeDef *hdci, DCI_SyncUnmaskTypeDef *SyncUnmask); +/** + * @} + */ + +/** @addtogroup DCI_Exported_Functions_Group4 Peripheral State functions + * @{ + */ +/* Peripheral State functions *************************************************/ +DAL_DCI_StateTypeDef DAL_DCI_GetState(DCI_HandleTypeDef *hdci); +uint32_t DAL_DCI_GetError(DCI_HandleTypeDef *hdci); +/** + * @} + */ + +/** + * @} + */ + +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/** @defgroup DCI_Private_Constants DCI Private Constants + * @{ + */ +#define DCI_MIS_INDEX 0x1000U /*!< DCI MIS register index */ +#define DCI_STS_INDEX 0x2000U /*!< DCI SR register index */ +/** + * @} + */ +/* Private macro -------------------------------------------------------------*/ +/** @defgroup DCI_Private_Macros DCI Private Macros + * @{ + */ +#define IS_DCI_CAPTURE_MODE(MODE)(((MODE) == DCI_MODE_CONTINUOUS) || \ + ((MODE) == DCI_MODE_SNAPSHOT)) + +#define IS_DCI_SYNCHRO(MODE)(((MODE) == DCI_SYNCHRO_HARDWARE) || \ + ((MODE) == DCI_SYNCHRO_EMBEDDED)) + +#define IS_DCI_PCKPOLARITY(POLARITY)(((POLARITY) == DCI_PCKPOLARITY_FALLING) || \ + ((POLARITY) == DCI_PCKPOLARITY_RISING)) + +#define IS_DCI_VSPOLARITY(POLARITY)(((POLARITY) == DCI_VSPOLARITY_LOW) || \ + ((POLARITY) == DCI_VSPOLARITY_HIGH)) + +#define IS_DCI_HSPOLARITY(POLARITY)(((POLARITY) == DCI_HSPOLARITY_LOW) || \ + ((POLARITY) == DCI_HSPOLARITY_HIGH)) + +#define IS_DCI_MODE_JPEG(JPEG_MODE)(((JPEG_MODE) == DCI_JPEG_DISABLE) || \ + ((JPEG_MODE) == DCI_JPEG_ENABLE)) + +#define IS_DCI_CAPTURE_RATE(RATE) (((RATE) == DCI_CR_ALL_FRAME) || \ + ((RATE) == DCI_CR_ALTERNATE_2_FRAME) || \ + ((RATE) == DCI_CR_ALTERNATE_4_FRAME)) + +#define IS_DCI_EXTENDED_DATA(DATA)(((DATA) == DCI_EXTEND_DATA_8B) || \ + ((DATA) == DCI_EXTEND_DATA_10B) || \ + ((DATA) == DCI_EXTEND_DATA_12B) || \ + ((DATA) == DCI_EXTEND_DATA_14B)) + +#define IS_DCI_WINDOW_COORDINATE(COORDINATE) ((COORDINATE) <= DCI_WINDOW_COORDINATE) + +#define IS_DCI_WINDOW_HEIGHT(HEIGHT) ((HEIGHT) <= DCI_WINDOW_HEIGHT) + +/** + * @} + */ + +/* Private functions ---------------------------------------------------------*/ +/** @addtogroup DCI_Private_Functions DCI Private Functions + * @{ + */ + +/** + * @} + */ + +#endif /* APM32F407xx || APM32F417xx */ + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* APM32F4xx_DAL_DCI_H */ diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_dci_ex.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_dci_ex.h new file mode 100644 index 0000000000..554b1590c7 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_dci_ex.h @@ -0,0 +1,149 @@ +/** + * + * @file apm32f4xx_dal_dci_ex.h + * @brief Header file of DCI Extension DAL module. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2017 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file in + * the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef APM32F4xx_DAL_DCI_EX_H +#define APM32F4xx_DAL_DCI_EX_H + +#ifdef __cplusplus + extern "C" { +#endif + +#if defined(APM32F407xx) || defined(APM32F417xx) + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal_def.h" + + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @addtogroup DCIEx + * @brief DCI DAL module driver + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ +/** @defgroup DCIEx_Exported_Types DCI Extended Exported Types + * @{ + */ +/** + * @brief DCIEx Embedded Synchronisation CODE Init structure definition + */ +typedef struct +{ + uint8_t FrameStartCode; /*!< Specifies the code of the frame start delimiter. */ + uint8_t LineStartCode; /*!< Specifies the code of the line start delimiter. */ + uint8_t LineEndCode; /*!< Specifies the code of the line end delimiter. */ + uint8_t FrameEndCode; /*!< Specifies the code of the frame end delimiter. */ +}DCI_CodesInitTypeDef; + +/** + * @brief DCI Init structure definition + */ +typedef struct +{ + uint32_t SynchroMode; /*!< Specifies the Synchronization Mode: Hardware or Embedded. + This parameter can be a value of @ref DCI_Synchronization_Mode */ + + uint32_t PCKPolarity; /*!< Specifies the Pixel clock polarity: Falling or Rising. + This parameter can be a value of @ref DCI_PIXCK_Polarity */ + + uint32_t VSPolarity; /*!< Specifies the Vertical synchronization polarity: High or Low. + This parameter can be a value of @ref DCI_VSYNC_Polarity */ + + uint32_t HSPolarity; /*!< Specifies the Horizontal synchronization polarity: High or Low. + This parameter can be a value of @ref DCI_HSYNC_Polarity */ + + uint32_t CaptureRate; /*!< Specifies the frequency of frame capture: All, 1/2 or 1/4. + This parameter can be a value of @ref DCI_Capture_Rate */ + + uint32_t ExtendedDataMode; /*!< Specifies the data width: 8-bit, 10-bit, 12-bit or 14-bit. + This parameter can be a value of @ref DCI_Extended_Data_Mode */ + + DCI_CodesInitTypeDef SyncroCode; /*!< Specifies the code of the frame start delimiter. */ + + uint32_t JPEGMode; /*!< Enable or Disable the JPEG mode + This parameter can be a value of @ref DCI_MODE_JPEG */ +}DCI_InitTypeDef; + +/** + * @} + */ + +/* Exported constants --------------------------------------------------------*/ +/* Exported macro ------------------------------------------------------------*/ +/* Exported functions --------------------------------------------------------*/ +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +#define DCI_POSITION_ESCR_LSC (uint32_t)DCI_ESYNCC_LSDC_Pos /*!< Required left shift to set line start delimiter */ +#define DCI_POSITION_ESCR_LEC (uint32_t)DCI_ESYNCC_LEDC_Pos /*!< Required left shift to set line end delimiter */ +#define DCI_POSITION_ESCR_FEC (uint32_t)DCI_ESYNCC_FEDC_Pos /*!< Required left shift to set frame end delimiter */ + +/* Private macro -------------------------------------------------------------*/ + +/** @defgroup DCIEx_Private_Macros DCI Extended Private Macros + * @{ + */ + +/** + * @} + */ + +/* Private functions ---------------------------------------------------------*/ +#endif /* APM32F407xx || APM32F417xx */ + + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* APM32F4xx_DAL_DCI_H */ diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_def.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_def.h new file mode 100644 index 0000000000..babfd3c143 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_def.h @@ -0,0 +1,234 @@ +/** + * + * @file apm32f4xx_dal_def.h + * @brief This file contains DAL common defines, enumeration, macros and + * structures definitions. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2017 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef APM32F4xx_DAL_DEF +#define APM32F4xx_DAL_DEF + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx.h" +#include "Legacy/apm32_dal_legacy.h" +#include + +/* Exported types ------------------------------------------------------------*/ + +/** + * @brief DAL Status structures definition + */ +typedef enum +{ + DAL_OK = 0x00U, + DAL_ERROR = 0x01U, + DAL_BUSY = 0x02U, + DAL_TIMEOUT = 0x03U +} DAL_StatusTypeDef; + +/** + * @brief DAL Lock structures definition + */ +typedef enum +{ + DAL_UNLOCKED = 0x00U, + DAL_LOCKED = 0x01U +} DAL_LockTypeDef; + +/* Exported macro ------------------------------------------------------------*/ + +#define UNUSED(X) (void)X /* To avoid gcc/g++ warnings */ + +#define DAL_MAX_DELAY 0xFFFFFFFFU + +#define DAL_IS_BIT_SET(REG, BIT) (((REG) & (BIT)) == (BIT)) +#define DAL_IS_BIT_CLR(REG, BIT) (((REG) & (BIT)) == 0U) + +#define __DAL_LINKDMA(__HANDLE__, __PPP_DMA_FIELD__, __DMA_HANDLE__) \ + do{ \ + (__HANDLE__)->__PPP_DMA_FIELD__ = &(__DMA_HANDLE__); \ + (__DMA_HANDLE__).Parent = (__HANDLE__); \ + } while(0U) + +/** @brief Reset the Handle's State field. + * @param __HANDLE__ specifies the Peripheral Handle. + * @note This macro can be used for the following purpose: + * - When the Handle is declared as local variable; before passing it as parameter + * to DAL_PPP_Init() for the first time, it is mandatory to use this macro + * to set to 0 the Handle's "State" field. + * Otherwise, "State" field may have any random value and the first time the function + * DAL_PPP_Init() is called, the low level hardware initialization will be missed + * (i.e. DAL_PPP_MspInit() will not be executed). + * - When there is a need to reconfigure the low level hardware: instead of calling + * DAL_PPP_DeInit() then DAL_PPP_Init(), user can make a call to this macro then DAL_PPP_Init(). + * In this later function, when the Handle's "State" field is set to 0, it will execute the function + * DAL_PPP_MspInit() which will reconfigure the low level hardware. + * @retval None + */ +#define __DAL_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = 0U) + +#if (USE_RTOS == 1U) + /* Reserved for future use */ + #error "USE_RTOS should be 0 in the current DAL release" +#else + #define __DAL_LOCK(__HANDLE__) \ + do{ \ + if((__HANDLE__)->Lock == DAL_LOCKED) \ + { \ + return DAL_BUSY; \ + } \ + else \ + { \ + (__HANDLE__)->Lock = DAL_LOCKED; \ + } \ + }while (0U) + + #define __DAL_UNLOCK(__HANDLE__) \ + do{ \ + (__HANDLE__)->Lock = DAL_UNLOCKED; \ + }while (0U) +#endif /* USE_RTOS */ + +#if defined (__ARMCC_VERSION) && (__ARMCC_VERSION >= 6010050) /* ARM Compiler V6 */ + #ifndef __weak + #define __weak __attribute__((weak)) + #endif + #ifndef __packed + #define __packed __attribute__((packed)) + #endif +#elif defined ( __GNUC__ ) && !defined (__CC_ARM) /* GNU Compiler */ + #ifndef __weak + #define __weak __attribute__((weak)) + #endif /* __weak */ + #ifndef __packed + #define __packed __attribute__((__packed__)) + #endif /* __packed */ +#endif /* __GNUC__ */ + + +/* Macro to get variable aligned on 4-bytes, for __ICCARM__ the directive "#pragma data_alignment=4" must be used instead */ +#if defined (__ARMCC_VERSION) && (__ARMCC_VERSION >= 6010050) /* ARM Compiler V6 */ + #ifndef __ALIGN_BEGIN + #define __ALIGN_BEGIN + #endif + #ifndef __ALIGN_END + #define __ALIGN_END __attribute__ ((aligned (4))) + #endif +#elif defined ( __GNUC__ ) && !defined (__CC_ARM) /* GNU Compiler */ + #ifndef __ALIGN_END +#define __ALIGN_END __attribute__ ((aligned (4))) + #endif /* __ALIGN_END */ + #ifndef __ALIGN_BEGIN + #define __ALIGN_BEGIN + #endif /* __ALIGN_BEGIN */ +#else + #ifndef __ALIGN_END + #define __ALIGN_END + #endif /* __ALIGN_END */ + #ifndef __ALIGN_BEGIN + #if defined (__CC_ARM) /* ARM Compiler V5*/ +#define __ALIGN_BEGIN __align(4) + #elif defined (__ICCARM__) /* IAR Compiler */ + #define __ALIGN_BEGIN + #endif /* __CC_ARM */ + #endif /* __ALIGN_BEGIN */ +#endif /* __GNUC__ */ + + +/** + * @brief __RAM_FUNC definition + */ +#if defined ( __CC_ARM ) || (defined (__ARMCC_VERSION) && (__ARMCC_VERSION >= 6010050)) +/* ARM Compiler V4/V5 and V6 + -------------------------- + RAM functions are defined using the toolchain options. + Functions that are executed in RAM should reside in a separate source module. + Using the 'Options for File' dialog you can simply change the 'Code / Const' + area of a module to a memory space in physical RAM. + Available memory areas are declared in the 'Target' tab of the 'Options for Target' + dialog. +*/ +#define __RAM_FUNC + +#elif defined ( __ICCARM__ ) +/* ICCARM Compiler + --------------- + RAM functions are defined using a specific toolchain keyword "__ramfunc". +*/ +#define __RAM_FUNC __ramfunc + +#elif defined ( __GNUC__ ) +/* GNU Compiler + ------------ + RAM functions are defined using a specific toolchain attribute + "__attribute__((section(".RamFunc")))". +*/ +#define __RAM_FUNC __attribute__((section(".RamFunc"))) + +#endif + +/** + * @brief __NOINLINE definition + */ +#if defined ( __CC_ARM ) || (defined (__ARMCC_VERSION) && (__ARMCC_VERSION >= 6010050)) || defined ( __GNUC__ ) +/* ARM V4/V5 and V6 & GNU Compiler + ------------------------------- +*/ +#define __NOINLINE __attribute__ ( (noinline) ) + +#elif defined ( __ICCARM__ ) +/* ICCARM Compiler + --------------- +*/ +#define __NOINLINE _Pragma("optimize = no_inline") + +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* APM32F4xx_DAL_DEF */ + + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_dma.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_dma.h new file mode 100644 index 0000000000..f3ca9f5df2 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_dma.h @@ -0,0 +1,826 @@ +/** + * + * @file apm32f4xx_dal_dma.h + * @brief Header file of DMA DAL module. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2017 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file in + * the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef APM32F4xx_DAL_DMA_H +#define APM32F4xx_DAL_DMA_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal_def.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @addtogroup DMA + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ + +/** @defgroup DMA_Exported_Types DMA Exported Types + * @brief DMA Exported Types + * @{ + */ + +/** + * @brief DMA Configuration Structure definition + */ +typedef struct +{ + uint32_t Channel; /*!< Specifies the channel used for the specified stream. + This parameter can be a value of @ref DMA_Channel_selection */ + + uint32_t Direction; /*!< Specifies if the data will be transferred from memory to peripheral, + from memory to memory or from peripheral to memory. + This parameter can be a value of @ref DMA_Data_transfer_direction */ + + uint32_t PeriphInc; /*!< Specifies whether the Peripheral address register should be incremented or not. + This parameter can be a value of @ref DMA_Peripheral_incremented_mode */ + + uint32_t MemInc; /*!< Specifies whether the memory address register should be incremented or not. + This parameter can be a value of @ref DMA_Memory_incremented_mode */ + + uint32_t PeriphDataAlignment; /*!< Specifies the Peripheral data width. + This parameter can be a value of @ref DMA_Peripheral_data_size */ + + uint32_t MemDataAlignment; /*!< Specifies the Memory data width. + This parameter can be a value of @ref DMA_Memory_data_size */ + + uint32_t Mode; /*!< Specifies the operation mode of the DMAy Streamx. + This parameter can be a value of @ref DMA_mode + @note The circular buffer mode cannot be used if the memory-to-memory + data transfer is configured on the selected Stream */ + + uint32_t Priority; /*!< Specifies the software priority for the DMAy Streamx. + This parameter can be a value of @ref DMA_Priority_level */ + + uint32_t FIFOMode; /*!< Specifies if the FIFO mode or Direct mode will be used for the specified stream. + This parameter can be a value of @ref DMA_FIFO_direct_mode + @note The Direct mode (FIFO mode disabled) cannot be used if the + memory-to-memory data transfer is configured on the selected stream */ + + uint32_t FIFOThreshold; /*!< Specifies the FIFO threshold level. + This parameter can be a value of @ref DMA_FIFO_threshold_level */ + + uint32_t MemBurst; /*!< Specifies the Burst transfer configuration for the memory transfers. + It specifies the amount of data to be transferred in a single non interruptible + transaction. + This parameter can be a value of @ref DMA_Memory_burst + @note The burst mode is possible only if the address Increment mode is enabled. */ + + uint32_t PeriphBurst; /*!< Specifies the Burst transfer configuration for the peripheral transfers. + It specifies the amount of data to be transferred in a single non interruptible + transaction. + This parameter can be a value of @ref DMA_Peripheral_burst + @note The burst mode is possible only if the address Increment mode is enabled. */ +}DMA_InitTypeDef; + + +/** + * @brief DAL DMA State structures definition + */ +typedef enum +{ + DAL_DMA_STATE_RESET = 0x00U, /*!< DMA not yet initialized or disabled */ + DAL_DMA_STATE_READY = 0x01U, /*!< DMA initialized and ready for use */ + DAL_DMA_STATE_BUSY = 0x02U, /*!< DMA process is ongoing */ + DAL_DMA_STATE_TIMEOUT = 0x03U, /*!< DMA timeout state */ + DAL_DMA_STATE_ERROR = 0x04U, /*!< DMA error state */ + DAL_DMA_STATE_ABORT = 0x05U, /*!< DMA Abort state */ +}DAL_DMA_StateTypeDef; + +/** + * @brief DAL DMA Error Code structure definition + */ +typedef enum +{ + DAL_DMA_FULL_TRANSFER = 0x00U, /*!< Full transfer */ + DAL_DMA_HALF_TRANSFER = 0x01U /*!< Half Transfer */ +}DAL_DMA_LevelCompleteTypeDef; + +/** + * @brief DAL DMA Error Code structure definition + */ +typedef enum +{ + DAL_DMA_XFER_CPLT_CB_ID = 0x00U, /*!< Full transfer */ + DAL_DMA_XFER_HALFCPLT_CB_ID = 0x01U, /*!< Half Transfer */ + DAL_DMA_XFER_M1CPLT_CB_ID = 0x02U, /*!< M1 Full Transfer */ + DAL_DMA_XFER_M1HALFCPLT_CB_ID = 0x03U, /*!< M1 Half Transfer */ + DAL_DMA_XFER_ERROR_CB_ID = 0x04U, /*!< Error */ + DAL_DMA_XFER_ABORT_CB_ID = 0x05U, /*!< Abort */ + DAL_DMA_XFER_ALL_CB_ID = 0x06U /*!< All */ +}DAL_DMA_CallbackIDTypeDef; + +/** + * @brief DMA handle Structure definition + */ +typedef struct __DMA_HandleTypeDef +{ + DMA_Stream_TypeDef *Instance; /*!< Register base address */ + + DMA_InitTypeDef Init; /*!< DMA communication parameters */ + + DAL_LockTypeDef Lock; /*!< DMA locking object */ + + __IO DAL_DMA_StateTypeDef State; /*!< DMA transfer state */ + + void *Parent; /*!< Parent object state */ + + void (* XferCpltCallback)( struct __DMA_HandleTypeDef * hdma); /*!< DMA transfer complete callback */ + + void (* XferHalfCpltCallback)( struct __DMA_HandleTypeDef * hdma); /*!< DMA Half transfer complete callback */ + + void (* XferM1CpltCallback)( struct __DMA_HandleTypeDef * hdma); /*!< DMA transfer complete Memory1 callback */ + + void (* XferM1HalfCpltCallback)( struct __DMA_HandleTypeDef * hdma); /*!< DMA transfer Half complete Memory1 callback */ + + void (* XferErrorCallback)( struct __DMA_HandleTypeDef * hdma); /*!< DMA transfer error callback */ + + void (* XferAbortCallback)( struct __DMA_HandleTypeDef * hdma); /*!< DMA transfer Abort callback */ + + __IO uint32_t ErrorCode; /*!< DMA Error code */ + + uint32_t StreamBaseAddress; /*!< DMA Stream Base Address */ + + uint32_t StreamIndex; /*!< DMA Stream Index */ + +}DMA_HandleTypeDef; + +/** + * @} + */ + +/* Exported constants --------------------------------------------------------*/ + +/** @defgroup DMA_Exported_Constants DMA Exported Constants + * @brief DMA Exported constants + * @{ + */ + +/** @defgroup DMA_Error_Code DMA Error Code + * @brief DMA Error Code + * @{ + */ +#define DAL_DMA_ERROR_NONE 0x00000000U /*!< No error */ +#define DAL_DMA_ERROR_TE 0x00000001U /*!< Transfer error */ +#define DAL_DMA_ERROR_FE 0x00000002U /*!< FIFO error */ +#define DAL_DMA_ERROR_DME 0x00000004U /*!< Direct Mode error */ +#define DAL_DMA_ERROR_TIMEOUT 0x00000020U /*!< Timeout error */ +#define DAL_DMA_ERROR_PARAM 0x00000040U /*!< Parameter error */ +#define DAL_DMA_ERROR_NO_XFER 0x00000080U /*!< Abort requested with no Xfer ongoing */ +#define DAL_DMA_ERROR_NOT_SUPPORTED 0x00000100U /*!< Not supported mode */ +/** + * @} + */ + +/** @defgroup DMA_Channel_selection DMA Channel selection + * @brief DMA channel selection + * @{ + */ +#define DMA_CHANNEL_0 0x00000000U /*!< DMA Channel 0 */ +#define DMA_CHANNEL_1 0x02000000U /*!< DMA Channel 1 */ +#define DMA_CHANNEL_2 0x04000000U /*!< DMA Channel 2 */ +#define DMA_CHANNEL_3 0x06000000U /*!< DMA Channel 3 */ +#define DMA_CHANNEL_4 0x08000000U /*!< DMA Channel 4 */ +#define DMA_CHANNEL_5 0x0A000000U /*!< DMA Channel 5 */ +#define DMA_CHANNEL_6 0x0C000000U /*!< DMA Channel 6 */ +#define DMA_CHANNEL_7 0x0E000000U /*!< DMA Channel 7 */ +#if defined (DMA_SCFGx_CHSEL_3) +#define DMA_CHANNEL_8 0x10000000U /*!< DMA Channel 8 */ +#define DMA_CHANNEL_9 0x12000000U /*!< DMA Channel 9 */ +#define DMA_CHANNEL_10 0x14000000U /*!< DMA Channel 10 */ +#define DMA_CHANNEL_11 0x16000000U /*!< DMA Channel 11 */ +#define DMA_CHANNEL_12 0x18000000U /*!< DMA Channel 12 */ +#define DMA_CHANNEL_13 0x1A000000U /*!< DMA Channel 13 */ +#define DMA_CHANNEL_14 0x1C000000U /*!< DMA Channel 14 */ +#define DMA_CHANNEL_15 0x1E000000U /*!< DMA Channel 15 */ +#endif /* DMA_SCFGx_CHSEL_3 */ +/** + * @} + */ + +/** @defgroup DMA_Data_transfer_direction DMA Data transfer direction + * @brief DMA data transfer direction + * @{ + */ +#define DMA_PERIPH_TO_MEMORY 0x00000000U /*!< Peripheral to memory direction */ +#define DMA_MEMORY_TO_PERIPH ((uint32_t)DMA_SCFGx_DIRCFG_0) /*!< Memory to peripheral direction */ +#define DMA_MEMORY_TO_MEMORY ((uint32_t)DMA_SCFGx_DIRCFG_1) /*!< Memory to memory direction */ +/** + * @} + */ + +/** @defgroup DMA_Peripheral_incremented_mode DMA Peripheral incremented mode + * @brief DMA peripheral incremented mode + * @{ + */ +#define DMA_PINC_ENABLE ((uint32_t)DMA_SCFGx_PERIM) /*!< Peripheral increment mode enable */ +#define DMA_PINC_DISABLE 0x00000000U /*!< Peripheral increment mode disable */ +/** + * @} + */ + +/** @defgroup DMA_Memory_incremented_mode DMA Memory incremented mode + * @brief DMA memory incremented mode + * @{ + */ +#define DMA_MINC_ENABLE ((uint32_t)DMA_SCFGx_MEMIM) /*!< Memory increment mode enable */ +#define DMA_MINC_DISABLE 0x00000000U /*!< Memory increment mode disable */ +/** + * @} + */ + +/** @defgroup DMA_Peripheral_data_size DMA Peripheral data size + * @brief DMA peripheral data size + * @{ + */ +#define DMA_PDATAALIGN_BYTE 0x00000000U /*!< Peripheral data alignment: Byte */ +#define DMA_PDATAALIGN_HALFWORD ((uint32_t)DMA_SCFGx_PERSIZECFG_0) /*!< Peripheral data alignment: HalfWord */ +#define DMA_PDATAALIGN_WORD ((uint32_t)DMA_SCFGx_PERSIZECFG_1) /*!< Peripheral data alignment: Word */ +/** + * @} + */ + +/** @defgroup DMA_Memory_data_size DMA Memory data size + * @brief DMA memory data size + * @{ + */ +#define DMA_MDATAALIGN_BYTE 0x00000000U /*!< Memory data alignment: Byte */ +#define DMA_MDATAALIGN_HALFWORD ((uint32_t)DMA_SCFGx_MEMSIZECFG_0) /*!< Memory data alignment: HalfWord */ +#define DMA_MDATAALIGN_WORD ((uint32_t)DMA_SCFGx_MEMSIZECFG_1) /*!< Memory data alignment: Word */ +/** + * @} + */ + +/** @defgroup DMA_mode DMA mode + * @brief DMA mode + * @{ + */ +#define DMA_NORMAL 0x00000000U /*!< Normal mode */ +#define DMA_CIRCULAR ((uint32_t)DMA_SCFGx_CIRCMEN) /*!< Circular mode */ +#define DMA_PFCTRL ((uint32_t)DMA_SCFGx_PERFC) /*!< Peripheral flow control mode */ +/** + * @} + */ + +/** @defgroup DMA_Priority_level DMA Priority level + * @brief DMA priority levels + * @{ + */ +#define DMA_PRIORITY_LOW 0x00000000U /*!< Priority level: Low */ +#define DMA_PRIORITY_MEDIUM ((uint32_t)DMA_SCFGx_PRILCFG_0) /*!< Priority level: Medium */ +#define DMA_PRIORITY_HIGH ((uint32_t)DMA_SCFGx_PRILCFG_1) /*!< Priority level: High */ +#define DMA_PRIORITY_VERY_HIGH ((uint32_t)DMA_SCFGx_PRILCFG) /*!< Priority level: Very High */ +/** + * @} + */ + +/** @defgroup DMA_FIFO_direct_mode DMA FIFO direct mode + * @brief DMA FIFO direct mode + * @{ + */ +#define DMA_FIFOMODE_DISABLE 0x00000000U /*!< FIFO mode disable */ +#define DMA_FIFOMODE_ENABLE ((uint32_t)DMA_FCTRLx_DMDEN) /*!< FIFO mode enable */ +/** + * @} + */ + +/** @defgroup DMA_FIFO_threshold_level DMA FIFO threshold level + * @brief DMA FIFO level + * @{ + */ +#define DMA_FIFO_THRESHOLD_1QUARTERFULL 0x00000000U /*!< FIFO threshold 1 quart full configuration */ +#define DMA_FIFO_THRESHOLD_HALFFULL ((uint32_t)DMA_FCTRLx_FTHSEL_0) /*!< FIFO threshold half full configuration */ +#define DMA_FIFO_THRESHOLD_3QUARTERSFULL ((uint32_t)DMA_FCTRLx_FTHSEL_1) /*!< FIFO threshold 3 quarts full configuration */ +#define DMA_FIFO_THRESHOLD_FULL ((uint32_t)DMA_FCTRLx_FTHSEL) /*!< FIFO threshold full configuration */ +/** + * @} + */ + +/** @defgroup DMA_Memory_burst DMA Memory burst + * @brief DMA memory burst + * @{ + */ +#define DMA_MBURST_SINGLE 0x00000000U +#define DMA_MBURST_INC4 ((uint32_t)DMA_SCFGx_MBCFG_0) +#define DMA_MBURST_INC8 ((uint32_t)DMA_SCFGx_MBCFG_1) +#define DMA_MBURST_INC16 ((uint32_t)DMA_SCFGx_MBCFG) +/** + * @} + */ + +/** @defgroup DMA_Peripheral_burst DMA Peripheral burst + * @brief DMA peripheral burst + * @{ + */ +#define DMA_PBURST_SINGLE 0x00000000U +#define DMA_PBURST_INC4 ((uint32_t)DMA_SCFGx_PBCFG_0) +#define DMA_PBURST_INC8 ((uint32_t)DMA_SCFGx_PBCFG_1) +#define DMA_PBURST_INC16 ((uint32_t)DMA_SCFGx_PBCFG) +/** + * @} + */ + +/** @defgroup DMA_interrupt_enable_definitions DMA interrupt enable definitions + * @brief DMA interrupts definition + * @{ + */ +#define DMA_IT_TC ((uint32_t)DMA_SCFGx_TXCIEN) +#define DMA_IT_HT ((uint32_t)DMA_SCFGx_HTXIEN) +#define DMA_IT_TE ((uint32_t)DMA_SCFGx_TXEIEN) +#define DMA_IT_DME ((uint32_t)DMA_SCFGx_DMEIEN) +#define DMA_IT_FE 0x00000080U +/** + * @} + */ + +/** @defgroup DMA_flag_definitions DMA flag definitions + * @brief DMA flag definitions + * @{ + */ +#define DMA_FLAG_FEIF0_4 0x00000001U +#define DMA_FLAG_DMEIF0_4 0x00000004U +#define DMA_FLAG_TEIF0_4 0x00000008U +#define DMA_FLAG_HTIF0_4 0x00000010U +#define DMA_FLAG_TCIF0_4 0x00000020U +#define DMA_FLAG_FEIF1_5 0x00000040U +#define DMA_FLAG_DMEIF1_5 0x00000100U +#define DMA_FLAG_TEIF1_5 0x00000200U +#define DMA_FLAG_HTIF1_5 0x00000400U +#define DMA_FLAG_TCIF1_5 0x00000800U +#define DMA_FLAG_FEIF2_6 0x00010000U +#define DMA_FLAG_DMEIF2_6 0x00040000U +#define DMA_FLAG_TEIF2_6 0x00080000U +#define DMA_FLAG_HTIF2_6 0x00100000U +#define DMA_FLAG_TCIF2_6 0x00200000U +#define DMA_FLAG_FEIF3_7 0x00400000U +#define DMA_FLAG_DMEIF3_7 0x01000000U +#define DMA_FLAG_TEIF3_7 0x02000000U +#define DMA_FLAG_HTIF3_7 0x04000000U +#define DMA_FLAG_TCIF3_7 0x08000000U +/** + * @} + */ + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ + +/** @brief Reset DMA handle state + * @param __HANDLE__ specifies the DMA handle. + * @retval None + */ +#define __DAL_DMA_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = DAL_DMA_STATE_RESET) + +/** + * @brief Return the current DMA Stream FIFO filled level. + * @param __HANDLE__ DMA handle + * @retval The FIFO filling state. + * - DMA_FIFOStatus_Less1QuarterFull: when FIFO is less than 1 quarter-full + * and not empty. + * - DMA_FIFOStatus_1QuarterFull: if more than 1 quarter-full. + * - DMA_FIFOStatus_HalfFull: if more than 1 half-full. + * - DMA_FIFOStatus_3QuartersFull: if more than 3 quarters-full. + * - DMA_FIFOStatus_Empty: when FIFO is empty + * - DMA_FIFOStatus_Full: when FIFO is full + */ +#define __DAL_DMA_GET_FS(__HANDLE__) (((__HANDLE__)->Instance->FCTRL & (DMA_FCTRLx_FSTS))) + +/** + * @brief Enable the specified DMA Stream. + * @param __HANDLE__ DMA handle + * @retval None + */ +#define __DAL_DMA_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->SCFG |= DMA_SCFGx_EN) + +/** + * @brief Disable the specified DMA Stream. + * @param __HANDLE__ DMA handle + * @retval None + */ +#define __DAL_DMA_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->SCFG &= ~DMA_SCFGx_EN) + +/* Interrupt & Flag management */ + +/** + * @brief Return the current DMA Stream transfer complete flag. + * @param __HANDLE__ DMA handle + * @retval The specified transfer complete flag index. + */ +#define __DAL_DMA_GET_TC_FLAG_INDEX(__HANDLE__) \ +(((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream0))? DMA_FLAG_TCIF0_4 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream0))? DMA_FLAG_TCIF0_4 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream4))? DMA_FLAG_TCIF0_4 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream4))? DMA_FLAG_TCIF0_4 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream1))? DMA_FLAG_TCIF1_5 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream1))? DMA_FLAG_TCIF1_5 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream5))? DMA_FLAG_TCIF1_5 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream5))? DMA_FLAG_TCIF1_5 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream2))? DMA_FLAG_TCIF2_6 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream2))? DMA_FLAG_TCIF2_6 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream6))? DMA_FLAG_TCIF2_6 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream6))? DMA_FLAG_TCIF2_6 :\ + DMA_FLAG_TCIF3_7) + +/** + * @brief Return the current DMA Stream half transfer complete flag. + * @param __HANDLE__ DMA handle + * @retval The specified half transfer complete flag index. + */ +#define __DAL_DMA_GET_HT_FLAG_INDEX(__HANDLE__)\ +(((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream0))? DMA_FLAG_HTIF0_4 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream0))? DMA_FLAG_HTIF0_4 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream4))? DMA_FLAG_HTIF0_4 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream4))? DMA_FLAG_HTIF0_4 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream1))? DMA_FLAG_HTIF1_5 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream1))? DMA_FLAG_HTIF1_5 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream5))? DMA_FLAG_HTIF1_5 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream5))? DMA_FLAG_HTIF1_5 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream2))? DMA_FLAG_HTIF2_6 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream2))? DMA_FLAG_HTIF2_6 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream6))? DMA_FLAG_HTIF2_6 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream6))? DMA_FLAG_HTIF2_6 :\ + DMA_FLAG_HTIF3_7) + +/** + * @brief Return the current DMA Stream transfer error flag. + * @param __HANDLE__ DMA handle + * @retval The specified transfer error flag index. + */ +#define __DAL_DMA_GET_TE_FLAG_INDEX(__HANDLE__)\ +(((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream0))? DMA_FLAG_TEIF0_4 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream0))? DMA_FLAG_TEIF0_4 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream4))? DMA_FLAG_TEIF0_4 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream4))? DMA_FLAG_TEIF0_4 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream1))? DMA_FLAG_TEIF1_5 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream1))? DMA_FLAG_TEIF1_5 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream5))? DMA_FLAG_TEIF1_5 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream5))? DMA_FLAG_TEIF1_5 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream2))? DMA_FLAG_TEIF2_6 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream2))? DMA_FLAG_TEIF2_6 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream6))? DMA_FLAG_TEIF2_6 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream6))? DMA_FLAG_TEIF2_6 :\ + DMA_FLAG_TEIF3_7) + +/** + * @brief Return the current DMA Stream FIFO error flag. + * @param __HANDLE__ DMA handle + * @retval The specified FIFO error flag index. + */ +#define __DAL_DMA_GET_FE_FLAG_INDEX(__HANDLE__)\ +(((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream0))? DMA_FLAG_FEIF0_4 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream0))? DMA_FLAG_FEIF0_4 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream4))? DMA_FLAG_FEIF0_4 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream4))? DMA_FLAG_FEIF0_4 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream1))? DMA_FLAG_FEIF1_5 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream1))? DMA_FLAG_FEIF1_5 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream5))? DMA_FLAG_FEIF1_5 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream5))? DMA_FLAG_FEIF1_5 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream2))? DMA_FLAG_FEIF2_6 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream2))? DMA_FLAG_FEIF2_6 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream6))? DMA_FLAG_FEIF2_6 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream6))? DMA_FLAG_FEIF2_6 :\ + DMA_FLAG_FEIF3_7) + +/** + * @brief Return the current DMA Stream direct mode error flag. + * @param __HANDLE__ DMA handle + * @retval The specified direct mode error flag index. + */ +#define __DAL_DMA_GET_DME_FLAG_INDEX(__HANDLE__)\ +(((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream0))? DMA_FLAG_DMEIF0_4 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream0))? DMA_FLAG_DMEIF0_4 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream4))? DMA_FLAG_DMEIF0_4 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream4))? DMA_FLAG_DMEIF0_4 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream1))? DMA_FLAG_DMEIF1_5 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream1))? DMA_FLAG_DMEIF1_5 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream5))? DMA_FLAG_DMEIF1_5 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream5))? DMA_FLAG_DMEIF1_5 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream2))? DMA_FLAG_DMEIF2_6 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream2))? DMA_FLAG_DMEIF2_6 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Stream6))? DMA_FLAG_DMEIF2_6 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA2_Stream6))? DMA_FLAG_DMEIF2_6 :\ + DMA_FLAG_DMEIF3_7) + +/** + * @brief Get the DMA Stream pending flags. + * @param __HANDLE__ DMA handle + * @param __FLAG__ Get the specified flag. + * This parameter can be any combination of the following values: + * @arg DMA_FLAG_TCIFx: Transfer complete flag. + * @arg DMA_FLAG_HTIFx: Half transfer complete flag. + * @arg DMA_FLAG_TEIFx: Transfer error flag. + * @arg DMA_FLAG_DMEIFx: Direct mode error flag. + * @arg DMA_FLAG_FEIFx: FIFO error flag. + * Where x can be 0_4, 1_5, 2_6 or 3_7 to select the DMA Stream flag. + * @retval The state of FLAG (SET or RESET). + */ +#define __DAL_DMA_GET_FLAG(__HANDLE__, __FLAG__)\ +(((uint32_t)((__HANDLE__)->Instance) > (uint32_t)DMA2_Stream3)? (DMA2->HINTSTS & (__FLAG__)) :\ + ((uint32_t)((__HANDLE__)->Instance) > (uint32_t)DMA1_Stream7)? (DMA2->LINTSTS & (__FLAG__)) :\ + ((uint32_t)((__HANDLE__)->Instance) > (uint32_t)DMA1_Stream3)? (DMA1->HINTSTS & (__FLAG__)) : (DMA1->LINTSTS & (__FLAG__))) + +/** + * @brief Clear the DMA Stream pending flags. + * @param __HANDLE__ DMA handle + * @param __FLAG__ specifies the flag to clear. + * This parameter can be any combination of the following values: + * @arg DMA_FLAG_TCIFx: Transfer complete flag. + * @arg DMA_FLAG_HTIFx: Half transfer complete flag. + * @arg DMA_FLAG_TEIFx: Transfer error flag. + * @arg DMA_FLAG_DMEIFx: Direct mode error flag. + * @arg DMA_FLAG_FEIFx: FIFO error flag. + * Where x can be 0_4, 1_5, 2_6 or 3_7 to select the DMA Stream flag. + * @retval None + */ +#define __DAL_DMA_CLEAR_FLAG(__HANDLE__, __FLAG__) \ +(((uint32_t)((__HANDLE__)->Instance) > (uint32_t)DMA2_Stream3)? (DMA2->HIFCLR = (__FLAG__)) :\ + ((uint32_t)((__HANDLE__)->Instance) > (uint32_t)DMA1_Stream7)? (DMA2->LIFCLR = (__FLAG__)) :\ + ((uint32_t)((__HANDLE__)->Instance) > (uint32_t)DMA1_Stream3)? (DMA1->HIFCLR = (__FLAG__)) : (DMA1->LIFCLR = (__FLAG__))) + +/** + * @brief Enable the specified DMA Stream interrupts. + * @param __HANDLE__ DMA handle + * @param __INTERRUPT__ specifies the DMA interrupt sources to be enabled or disabled. + * This parameter can be any combination of the following values: + * @arg DMA_IT_TC: Transfer complete interrupt mask. + * @arg DMA_IT_HT: Half transfer complete interrupt mask. + * @arg DMA_IT_TE: Transfer error interrupt mask. + * @arg DMA_IT_FE: FIFO error interrupt mask. + * @arg DMA_IT_DME: Direct mode error interrupt. + * @retval None + */ +#define __DAL_DMA_ENABLE_IT(__HANDLE__, __INTERRUPT__) (((__INTERRUPT__) != DMA_IT_FE)? \ +((__HANDLE__)->Instance->SCFG |= (__INTERRUPT__)) : ((__HANDLE__)->Instance->FCTRL |= (__INTERRUPT__))) + +/** + * @brief Disable the specified DMA Stream interrupts. + * @param __HANDLE__ DMA handle + * @param __INTERRUPT__ specifies the DMA interrupt sources to be enabled or disabled. + * This parameter can be any combination of the following values: + * @arg DMA_IT_TC: Transfer complete interrupt mask. + * @arg DMA_IT_HT: Half transfer complete interrupt mask. + * @arg DMA_IT_TE: Transfer error interrupt mask. + * @arg DMA_IT_FE: FIFO error interrupt mask. + * @arg DMA_IT_DME: Direct mode error interrupt. + * @retval None + */ +#define __DAL_DMA_DISABLE_IT(__HANDLE__, __INTERRUPT__) (((__INTERRUPT__) != DMA_IT_FE)? \ +((__HANDLE__)->Instance->SCFG &= ~(__INTERRUPT__)) : ((__HANDLE__)->Instance->FCTRL &= ~(__INTERRUPT__))) + +/** + * @brief Check whether the specified DMA Stream interrupt is enabled or disabled. + * @param __HANDLE__ DMA handle + * @param __INTERRUPT__ specifies the DMA interrupt source to check. + * This parameter can be one of the following values: + * @arg DMA_IT_TC: Transfer complete interrupt mask. + * @arg DMA_IT_HT: Half transfer complete interrupt mask. + * @arg DMA_IT_TE: Transfer error interrupt mask. + * @arg DMA_IT_FE: FIFO error interrupt mask. + * @arg DMA_IT_DME: Direct mode error interrupt. + * @retval The state of DMA_IT. + */ +#define __DAL_DMA_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) (((__INTERRUPT__) != DMA_IT_FE)? \ + ((__HANDLE__)->Instance->SCFG & (__INTERRUPT__)) : \ + ((__HANDLE__)->Instance->FCTRL & (__INTERRUPT__))) + +/** + * @brief Writes the number of data units to be transferred on the DMA Stream. + * @param __HANDLE__ DMA handle + * @param __COUNTER__ Number of data units to be transferred (from 0 to 65535) + * Number of data items depends only on the Peripheral data format. + * + * @note If Peripheral data format is Bytes: number of data units is equal + * to total number of bytes to be transferred. + * + * @note If Peripheral data format is Half-Word: number of data units is + * equal to total number of bytes to be transferred / 2. + * + * @note If Peripheral data format is Word: number of data units is equal + * to total number of bytes to be transferred / 4. + * + * @retval The number of remaining data units in the current DMAy Streamx transfer. + */ +#define __DAL_DMA_SET_COUNTER(__HANDLE__, __COUNTER__) ((__HANDLE__)->Instance->NDATA = (uint16_t)(__COUNTER__)) + +/** + * @brief Returns the number of remaining data units in the current DMAy Streamx transfer. + * @param __HANDLE__ DMA handle + * + * @retval The number of remaining data units in the current DMA Stream transfer. + */ +#define __DAL_DMA_GET_COUNTER(__HANDLE__) ((__HANDLE__)->Instance->NDATA) + + +/* Include DMA DAL Extension module */ +#include "apm32f4xx_dal_dma_ex.h" + +/* Exported functions --------------------------------------------------------*/ + +/** @defgroup DMA_Exported_Functions DMA Exported Functions + * @brief DMA Exported functions + * @{ + */ + +/** @defgroup DMA_Exported_Functions_Group1 Initialization and de-initialization functions + * @brief Initialization and de-initialization functions + * @{ + */ +DAL_StatusTypeDef DAL_DMA_Init(DMA_HandleTypeDef *hdma); +DAL_StatusTypeDef DAL_DMA_DeInit(DMA_HandleTypeDef *hdma); +/** + * @} + */ + +/** @defgroup DMA_Exported_Functions_Group2 I/O operation functions + * @brief I/O operation functions + * @{ + */ +DAL_StatusTypeDef DAL_DMA_Start (DMA_HandleTypeDef *hdma, uint32_t SrcAddress, uint32_t DstAddress, uint32_t DataLength); +DAL_StatusTypeDef DAL_DMA_Start_IT(DMA_HandleTypeDef *hdma, uint32_t SrcAddress, uint32_t DstAddress, uint32_t DataLength); +DAL_StatusTypeDef DAL_DMA_Abort(DMA_HandleTypeDef *hdma); +DAL_StatusTypeDef DAL_DMA_Abort_IT(DMA_HandleTypeDef *hdma); +DAL_StatusTypeDef DAL_DMA_PollForTransfer(DMA_HandleTypeDef *hdma, DAL_DMA_LevelCompleteTypeDef CompleteLevel, uint32_t Timeout); +void DAL_DMA_IRQHandler(DMA_HandleTypeDef *hdma); +DAL_StatusTypeDef DAL_DMA_CleanCallbacks(DMA_HandleTypeDef *hdma); +DAL_StatusTypeDef DAL_DMA_RegisterCallback(DMA_HandleTypeDef *hdma, DAL_DMA_CallbackIDTypeDef CallbackID, void (* pCallback)(DMA_HandleTypeDef *_hdma)); +DAL_StatusTypeDef DAL_DMA_UnRegisterCallback(DMA_HandleTypeDef *hdma, DAL_DMA_CallbackIDTypeDef CallbackID); + +/** + * @} + */ + +/** @defgroup DMA_Exported_Functions_Group3 Peripheral State functions + * @brief Peripheral State functions + * @{ + */ +DAL_DMA_StateTypeDef DAL_DMA_GetState(DMA_HandleTypeDef *hdma); +uint32_t DAL_DMA_GetError(DMA_HandleTypeDef *hdma); +/** + * @} + */ +/** + * @} + */ +/* Private Constants -------------------------------------------------------------*/ +/** @defgroup DMA_Private_Constants DMA Private Constants + * @brief DMA private defines and constants + * @{ + */ +/** + * @} + */ + +/* Private macros ------------------------------------------------------------*/ +/** @defgroup DMA_Private_Macros DMA Private Macros + * @brief DMA private macros + * @{ + */ +#if defined (DMA_SCFGx_CHSEL_3) +#define IS_DMA_CHANNEL(CHANNEL) (((CHANNEL) == DMA_CHANNEL_0) || \ + ((CHANNEL) == DMA_CHANNEL_1) || \ + ((CHANNEL) == DMA_CHANNEL_2) || \ + ((CHANNEL) == DMA_CHANNEL_3) || \ + ((CHANNEL) == DMA_CHANNEL_4) || \ + ((CHANNEL) == DMA_CHANNEL_5) || \ + ((CHANNEL) == DMA_CHANNEL_6) || \ + ((CHANNEL) == DMA_CHANNEL_7) || \ + ((CHANNEL) == DMA_CHANNEL_8) || \ + ((CHANNEL) == DMA_CHANNEL_9) || \ + ((CHANNEL) == DMA_CHANNEL_10)|| \ + ((CHANNEL) == DMA_CHANNEL_11)|| \ + ((CHANNEL) == DMA_CHANNEL_12)|| \ + ((CHANNEL) == DMA_CHANNEL_13)|| \ + ((CHANNEL) == DMA_CHANNEL_14)|| \ + ((CHANNEL) == DMA_CHANNEL_15)) +#else +#define IS_DMA_CHANNEL(CHANNEL) (((CHANNEL) == DMA_CHANNEL_0) || \ + ((CHANNEL) == DMA_CHANNEL_1) || \ + ((CHANNEL) == DMA_CHANNEL_2) || \ + ((CHANNEL) == DMA_CHANNEL_3) || \ + ((CHANNEL) == DMA_CHANNEL_4) || \ + ((CHANNEL) == DMA_CHANNEL_5) || \ + ((CHANNEL) == DMA_CHANNEL_6) || \ + ((CHANNEL) == DMA_CHANNEL_7)) +#endif /* DMA_SCFGx_CHSEL_3 */ + +#define IS_DMA_DIRECTION(DIRECTION) (((DIRECTION) == DMA_PERIPH_TO_MEMORY ) || \ + ((DIRECTION) == DMA_MEMORY_TO_PERIPH) || \ + ((DIRECTION) == DMA_MEMORY_TO_MEMORY)) + +#define IS_DMA_BUFFER_SIZE(SIZE) (((SIZE) >= 0x01U) && ((SIZE) < 0x10000U)) + +#define IS_DMA_PERIPHERAL_INC_STATE(STATE) (((STATE) == DMA_PINC_ENABLE) || \ + ((STATE) == DMA_PINC_DISABLE)) + +#define IS_DMA_MEMORY_INC_STATE(STATE) (((STATE) == DMA_MINC_ENABLE) || \ + ((STATE) == DMA_MINC_DISABLE)) + +#define IS_DMA_PERIPHERAL_DATA_SIZE(SIZE) (((SIZE) == DMA_PDATAALIGN_BYTE) || \ + ((SIZE) == DMA_PDATAALIGN_HALFWORD) || \ + ((SIZE) == DMA_PDATAALIGN_WORD)) + +#define IS_DMA_MEMORY_DATA_SIZE(SIZE) (((SIZE) == DMA_MDATAALIGN_BYTE) || \ + ((SIZE) == DMA_MDATAALIGN_HALFWORD) || \ + ((SIZE) == DMA_MDATAALIGN_WORD )) + +#define IS_DMA_MODE(MODE) (((MODE) == DMA_NORMAL ) || \ + ((MODE) == DMA_CIRCULAR) || \ + ((MODE) == DMA_PFCTRL)) + +#define IS_DMA_PRIORITY(PRIORITY) (((PRIORITY) == DMA_PRIORITY_LOW ) || \ + ((PRIORITY) == DMA_PRIORITY_MEDIUM) || \ + ((PRIORITY) == DMA_PRIORITY_HIGH) || \ + ((PRIORITY) == DMA_PRIORITY_VERY_HIGH)) + +#define IS_DMA_FIFO_MODE_STATE(STATE) (((STATE) == DMA_FIFOMODE_DISABLE ) || \ + ((STATE) == DMA_FIFOMODE_ENABLE)) + +#define IS_DMA_FIFO_THRESHOLD(THRESHOLD) (((THRESHOLD) == DMA_FIFO_THRESHOLD_1QUARTERFULL ) || \ + ((THRESHOLD) == DMA_FIFO_THRESHOLD_HALFFULL) || \ + ((THRESHOLD) == DMA_FIFO_THRESHOLD_3QUARTERSFULL) || \ + ((THRESHOLD) == DMA_FIFO_THRESHOLD_FULL)) + +#define IS_DMA_MEMORY_BURST(BURST) (((BURST) == DMA_MBURST_SINGLE) || \ + ((BURST) == DMA_MBURST_INC4) || \ + ((BURST) == DMA_MBURST_INC8) || \ + ((BURST) == DMA_MBURST_INC16)) + +#define IS_DMA_PERIPHERAL_BURST(BURST) (((BURST) == DMA_PBURST_SINGLE) || \ + ((BURST) == DMA_PBURST_INC4) || \ + ((BURST) == DMA_PBURST_INC8) || \ + ((BURST) == DMA_PBURST_INC16)) +/** + * @} + */ + +/* Private functions ---------------------------------------------------------*/ +/** @defgroup DMA_Private_Functions DMA Private Functions + * @brief DMA private functions + * @{ + */ +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* APM32F4xx_DAL_DMA_H */ + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_dma_ex.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_dma_ex.h new file mode 100644 index 0000000000..2cbb076f5b --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_dma_ex.h @@ -0,0 +1,126 @@ +/** + * + * @file apm32f4xx_dal_dma_ex.h + * @brief Header file of DMA DAL extension module. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2017 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file in + * the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef APM32F4xx_DAL_DMA_EX_H +#define APM32F4xx_DAL_DMA_EX_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal_def.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @addtogroup DMAEx + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ +/** @defgroup DMAEx_Exported_Types DMAEx Exported Types + * @brief DMAEx Exported types + * @{ + */ + +/** + * @brief DAL DMA Memory definition + */ +typedef enum +{ + MEMORY0 = 0x00U, /*!< Memory 0 */ + MEMORY1 = 0x01U /*!< Memory 1 */ +}DAL_DMA_MemoryTypeDef; + +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +/** @defgroup DMAEx_Exported_Functions DMAEx Exported Functions + * @brief DMAEx Exported functions + * @{ + */ + +/** @defgroup DMAEx_Exported_Functions_Group1 Extended features functions + * @brief Extended features functions + * @{ + */ + +/* IO operation functions *******************************************************/ +DAL_StatusTypeDef DAL_DMAEx_MultiBufferStart(DMA_HandleTypeDef *hdma, uint32_t SrcAddress, uint32_t DstAddress, uint32_t SecondMemAddress, uint32_t DataLength); +DAL_StatusTypeDef DAL_DMAEx_MultiBufferStart_IT(DMA_HandleTypeDef *hdma, uint32_t SrcAddress, uint32_t DstAddress, uint32_t SecondMemAddress, uint32_t DataLength); +DAL_StatusTypeDef DAL_DMAEx_ChangeMemory(DMA_HandleTypeDef *hdma, uint32_t Address, DAL_DMA_MemoryTypeDef memory); + +/** + * @} + */ +/** + * @} + */ + +/* Private functions ---------------------------------------------------------*/ +/** @defgroup DMAEx_Private_Functions DMAEx Private Functions + * @brief DMAEx Private functions + * @{ + */ +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* APM32F4xx_DAL_DMA_EX_H*/ + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_eint.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_eint.h new file mode 100644 index 0000000000..78445fed93 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_eint.h @@ -0,0 +1,390 @@ +/** + * + * @file apm32f4xx_dal_eint.h + * @brief Header file of EINT DAL module. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2018 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS.Clause + * + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef APM32f4xx_DAL_EINT_H +#define APM32f4xx_DAL_EINT_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal_def.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @defgroup EINT EINT + * @brief EINT DAL module driver + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ + +/** @defgroup EINT_Exported_Types EINT Exported Types + * @{ + */ +typedef enum +{ + DAL_EINT_COMMON_CB_ID = 0x00U +} EINT_CallbackIDTypeDef; + +/** + * @brief EINT Handle structure definition + */ +typedef struct +{ + uint32_t Line; /*!< Eint line number */ + void (* PendingCallback)(void); /*!< Eint pending callback */ +} EINT_HandleTypeDef; + +/** + * @brief EINT Configuration structure definition + */ +typedef struct +{ + uint32_t Line; /*!< The Eint line to be configured. This parameter + can be a value of @ref EINT_Line */ + uint32_t Mode; /*!< The Exit Mode to be configured for a core. + This parameter can be a combination of @ref EINT_Mode */ + uint32_t Trigger; /*!< The Eint Trigger to be configured. This parameter + can be a value of @ref EINT_Trigger */ + uint32_t GPIOSel; /*!< The Eint GPIO multiplexer selection to be configured. + This parameter is only possible for line 0 to 15. It + can be a value of @ref EINT_GPIOSel */ +} EINT_ConfigTypeDef; + +/** + * @} + */ + +/* Exported constants --------------------------------------------------------*/ +/** @defgroup EINT_Exported_Constants EINT Exported Constants + * @{ + */ + +/** @defgroup EINT_Line EINT Line + * @{ + */ +#define EINT_LINE_0 (EINT_GPIO | 0x00u) /*!< External interrupt line 0 */ +#define EINT_LINE_1 (EINT_GPIO | 0x01u) /*!< External interrupt line 1 */ +#define EINT_LINE_2 (EINT_GPIO | 0x02u) /*!< External interrupt line 2 */ +#define EINT_LINE_3 (EINT_GPIO | 0x03u) /*!< External interrupt line 3 */ +#define EINT_LINE_4 (EINT_GPIO | 0x04u) /*!< External interrupt line 4 */ +#define EINT_LINE_5 (EINT_GPIO | 0x05u) /*!< External interrupt line 5 */ +#define EINT_LINE_6 (EINT_GPIO | 0x06u) /*!< External interrupt line 6 */ +#define EINT_LINE_7 (EINT_GPIO | 0x07u) /*!< External interrupt line 7 */ +#define EINT_LINE_8 (EINT_GPIO | 0x08u) /*!< External interrupt line 8 */ +#define EINT_LINE_9 (EINT_GPIO | 0x09u) /*!< External interrupt line 9 */ +#define EINT_LINE_10 (EINT_GPIO | 0x0Au) /*!< External interrupt line 10 */ +#define EINT_LINE_11 (EINT_GPIO | 0x0Bu) /*!< External interrupt line 11 */ +#define EINT_LINE_12 (EINT_GPIO | 0x0Cu) /*!< External interrupt line 12 */ +#define EINT_LINE_13 (EINT_GPIO | 0x0Du) /*!< External interrupt line 13 */ +#define EINT_LINE_14 (EINT_GPIO | 0x0Eu) /*!< External interrupt line 14 */ +#define EINT_LINE_15 (EINT_GPIO | 0x0Fu) /*!< External interrupt line 15 */ +#define EINT_LINE_16 (EINT_CONFIG | 0x10u) /*!< External interrupt line 16 Connected to the PVD Output */ +#define EINT_LINE_17 (EINT_CONFIG | 0x11u) /*!< External interrupt line 17 Connected to the RTC Alarm event */ +#if defined(EINT_IMASK_IM18) +#define EINT_LINE_18 (EINT_CONFIG | 0x12u) /*!< External interrupt line 18 Connected to the USB OTG FS Wakeup from suspend event */ +#else +#define EINT_LINE_18 (EINT_RESERVED | 0x12u) /*!< No interrupt supported in this line */ +#endif /* EINT_IMASK_IM18 */ +#if defined(EINT_IMASK_IM19) +#define EINT_LINE_19 (EINT_CONFIG | 0x13u) /*!< External interrupt line 19 Connected to the Ethernet Wakeup event */ +#else +#define EINT_LINE_19 (EINT_RESERVED | 0x13u) /*!< No interrupt supported in this line */ +#endif /* EINT_IMASK_IM19 */ +#if defined(EINT_IMASK_IM20) +#define EINT_LINE_20 (EINT_CONFIG | 0x14u) /*!< External interrupt line 20 Connected to the USB OTG HS (configured in FS) Wakeup event */ +#else +#define EINT_LINE_20 (EINT_RESERVED | 0x14u) /*!< No interrupt supported in this line */ +#endif /* EINT_IMASK_IM20 */ +#define EINT_LINE_21 (EINT_CONFIG | 0x15u) /*!< External interrupt line 21 Connected to the RTC Tamper and Time Stamp events */ +#define EINT_LINE_22 (EINT_CONFIG | 0x16u) /*!< External interrupt line 22 Connected to the RTC Wakeup event */ +#if defined(EINT_IMASK_IM23) +#define EINT_LINE_23 (EINT_CONFIG | 0x17u) /*!< External interrupt line 23 Connected to the LPTIM1 asynchronous event */ +#endif /* EINT_IMASK_IM23 */ + +/** + * @} + */ + +/** @defgroup EINT_Mode EINT Mode + * @{ + */ +#define EINT_MODE_NONE 0x00000000u +#define EINT_MODE_INTERRUPT 0x00000001u +#define EINT_MODE_EVENT 0x00000002u +/** + * @} + */ + +/** @defgroup EINT_Trigger EINT Trigger + * @{ + */ + +#define EINT_TRIGGER_NONE 0x00000000u +#define EINT_TRIGGER_RISING 0x00000001u +#define EINT_TRIGGER_FALLING 0x00000002u +#define EINT_TRIGGER_RISING_FALLING (EINT_TRIGGER_RISING | EINT_TRIGGER_FALLING) +/** + * @} + */ + +/** @defgroup EINT_GPIOSel EINT GPIOSel + * @brief + * @{ + */ +#define EINT_GPIOA 0x00000000u +#define EINT_GPIOB 0x00000001u +#define EINT_GPIOC 0x00000002u +#if defined (GPIOD) +#define EINT_GPIOD 0x00000003u +#endif /* GPIOD */ +#if defined (GPIOE) +#define EINT_GPIOE 0x00000004u +#endif /* GPIOE */ +#if defined (GPIOF) +#define EINT_GPIOF 0x00000005u +#endif /* GPIOF */ +#if defined (GPIOG) +#define EINT_GPIOG 0x00000006u +#endif /* GPIOG */ +#if defined (GPIOH) +#define EINT_GPIOH 0x00000007u +#endif /* GPIOH */ +#if defined (GPIOI) +#define EINT_GPIOI 0x00000008u +#endif /* GPIOI */ +#if defined (GPIOJ) +#define EINT_GPIOJ 0x00000009u +#endif /* GPIOJ */ +#if defined (GPIOK) +#define EINT_GPIOK 0x0000000Au +#endif /* GPIOK */ + +/** + * @} + */ + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ +/** @defgroup EINT_Exported_Macros EINT Exported Macros + * @{ + */ + +/** + * @} + */ + +/* Private constants --------------------------------------------------------*/ +/** @defgroup EINT_Private_Constants EINT Private Constants + * @{ + */ +/** + * @brief EINT Line property definition + */ +#define EINT_IPENDOPERTY_SHIFT 24u +#define EINT_CONFIG (0x02uL << EINT_IPENDOPERTY_SHIFT) +#define EINT_GPIO ((0x04uL << EINT_IPENDOPERTY_SHIFT) | EINT_CONFIG) +#define EINT_RESERVED (0x08uL << EINT_IPENDOPERTY_SHIFT) +#define EINT_IPENDOPERTY_MASK (EINT_CONFIG | EINT_GPIO) + +/** + * @brief EINT bit usage + */ +#define EINT_PIN_MASK 0x0000001Fu + +/** + * @brief EINT Mask for interrupt & event mode + */ +#define EINT_MODE_MASK (EINT_MODE_EVENT | EINT_MODE_INTERRUPT) + +/** + * @brief EINT Mask for trigger possibilities + */ +#define EINT_TRIGGER_MASK (EINT_TRIGGER_RISING | EINT_TRIGGER_FALLING) + +/** + * @brief EINT Line number + */ +#if defined(EINT_IMASK_IM23) +#define EINT_LINE_NB 24UL +#else +#define EINT_LINE_NB 23UL +#endif /* EINT_IMASK_IM23 */ + +/** + * @} + */ + +/* Private macros ------------------------------------------------------------*/ +/** @defgroup EINT_Private_Macros EINT Private Macros + * @{ + */ +#define IS_EINT_LINE(__EINT_LINE__) ((((__EINT_LINE__) & ~(EINT_IPENDOPERTY_MASK | EINT_PIN_MASK)) == 0x00u) && \ + ((((__EINT_LINE__) & EINT_IPENDOPERTY_MASK) == EINT_CONFIG) || \ + (((__EINT_LINE__) & EINT_IPENDOPERTY_MASK) == EINT_GPIO)) && \ + (((__EINT_LINE__) & EINT_PIN_MASK) < EINT_LINE_NB)) + +#define IS_EINT_MODE(__EINT_LINE__) ((((__EINT_LINE__) & EINT_MODE_MASK) != 0x00u) && \ + (((__EINT_LINE__) & ~EINT_MODE_MASK) == 0x00u)) + +#define IS_EINT_TRIGGER(__EINT_LINE__) (((__EINT_LINE__) & ~EINT_TRIGGER_MASK) == 0x00u) + +#define IS_EINT_PENDING_EDGE(__EINT_LINE__) ((__EINT_LINE__) == EINT_TRIGGER_RISING_FALLING) + +#define IS_EINT_CONFIG_LINE(__EINT_LINE__) (((__EINT_LINE__) & EINT_CONFIG) != 0x00u) + +#if !defined (GPIOD) +#define IS_EINT_GPIO_PORT(__PORT__) (((__PORT__) == EINT_GPIOA) || \ + ((__PORT__) == EINT_GPIOB) || \ + ((__PORT__) == EINT_GPIOC) || \ + ((__PORT__) == EINT_GPIOH)) +#elif !defined (GPIOE) +#define IS_EINT_GPIO_PORT(__PORT__) (((__PORT__) == EINT_GPIOA) || \ + ((__PORT__) == EINT_GPIOB) || \ + ((__PORT__) == EINT_GPIOC) || \ + ((__PORT__) == EINT_GPIOD) || \ + ((__PORT__) == EINT_GPIOH)) +#elif !defined (GPIOF) +#define IS_EINT_GPIO_PORT(__PORT__) (((__PORT__) == EINT_GPIOA) || \ + ((__PORT__) == EINT_GPIOB) || \ + ((__PORT__) == EINT_GPIOC) || \ + ((__PORT__) == EINT_GPIOD) || \ + ((__PORT__) == EINT_GPIOE) || \ + ((__PORT__) == EINT_GPIOH)) +#elif !defined (GPIOI) +#define IS_EINT_GPIO_PORT(__PORT__) (((__PORT__) == EINT_GPIOA) || \ + ((__PORT__) == EINT_GPIOB) || \ + ((__PORT__) == EINT_GPIOC) || \ + ((__PORT__) == EINT_GPIOD) || \ + ((__PORT__) == EINT_GPIOE) || \ + ((__PORT__) == EINT_GPIOF) || \ + ((__PORT__) == EINT_GPIOG) || \ + ((__PORT__) == EINT_GPIOH)) +#elif !defined (GPIOJ) +#define IS_EINT_GPIO_PORT(__PORT__) (((__PORT__) == EINT_GPIOA) || \ + ((__PORT__) == EINT_GPIOB) || \ + ((__PORT__) == EINT_GPIOC) || \ + ((__PORT__) == EINT_GPIOD) || \ + ((__PORT__) == EINT_GPIOE) || \ + ((__PORT__) == EINT_GPIOF) || \ + ((__PORT__) == EINT_GPIOG) || \ + ((__PORT__) == EINT_GPIOH) || \ + ((__PORT__) == EINT_GPIOI)) +#else +#define IS_EINT_GPIO_PORT(__PORT__) (((__PORT__) == EINT_GPIOA) || \ + ((__PORT__) == EINT_GPIOB) || \ + ((__PORT__) == EINT_GPIOC) || \ + ((__PORT__) == EINT_GPIOD) || \ + ((__PORT__) == EINT_GPIOE) || \ + ((__PORT__) == EINT_GPIOF) || \ + ((__PORT__) == EINT_GPIOG) || \ + ((__PORT__) == EINT_GPIOH) || \ + ((__PORT__) == EINT_GPIOI) || \ + ((__PORT__) == EINT_GPIOJ) || \ + ((__PORT__) == EINT_GPIOK)) +#endif /* GPIOD */ + +#define IS_EINT_GPIO_PIN(__PIN__) ((__PIN__) < 16U) +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +/** @defgroup EINT_Exported_Functions EINT Exported Functions + * @brief EINT Exported Functions + * @{ + */ + +/** @defgroup EINT_Exported_Functions_Group1 Configuration functions + * @brief Configuration functions + * @{ + */ +/* Configuration functions ****************************************************/ +DAL_StatusTypeDef DAL_EINT_SetConfigLine(EINT_HandleTypeDef *heint, EINT_ConfigTypeDef *pEintConfig); +DAL_StatusTypeDef DAL_EINT_GetConfigLine(EINT_HandleTypeDef *heint, EINT_ConfigTypeDef *pEintConfig); +DAL_StatusTypeDef DAL_EINT_ClearConfigLine(EINT_HandleTypeDef *heint); +DAL_StatusTypeDef DAL_EINT_RegisterCallback(EINT_HandleTypeDef *heint, EINT_CallbackIDTypeDef CallbackID, void (*pPendingCbfn)(void)); +DAL_StatusTypeDef DAL_EINT_GetHandle(EINT_HandleTypeDef *heint, uint32_t EintLine); +/** + * @} + */ + +/** @defgroup EINT_Exported_Functions_Group2 IO operation functions + * @brief IO operation functions + * @{ + */ +/* IO operation functions *****************************************************/ +void DAL_EINT_IRQHandler(EINT_HandleTypeDef *heint); +uint32_t DAL_EINT_GetPending(EINT_HandleTypeDef *heint, uint32_t Edge); +void DAL_EINT_ClearPending(EINT_HandleTypeDef *heint, uint32_t Edge); +void DAL_EINT_GenerateSWI(EINT_HandleTypeDef *heint); + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* APM32f4xx_DAL_EINT_H */ + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_eth.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_eth.h new file mode 100644 index 0000000000..72b7b23b2f --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_eth.h @@ -0,0 +1,2175 @@ +/** + * + * @file apm32f4xx_dal_eth.h + * @brief Header file of ETH DAL module. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef APM32F4xx_DAL_ETH_H +#define APM32F4xx_DAL_ETH_H + +#ifdef __cplusplus +extern "C" { +#endif + + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal_def.h" + +#if defined(ETH) + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @addtogroup ETH + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ +#ifndef ETH_TX_DESC_CNT +#define ETH_TX_DESC_CNT 4U +#endif /* ETH_TX_DESC_CNT */ + +#ifndef ETH_RX_DESC_CNT +#define ETH_RX_DESC_CNT 4U +#endif /* ETH_RX_DESC_CNT */ + + +/*********************** Descriptors struct def section ************************/ +/** @defgroup ETH_Exported_Types ETH Exported Types + * @{ + */ + +/** + * @brief ETH DMA Descriptor structure definition + */ +typedef struct +{ + __IO uint32_t DESC0; + __IO uint32_t DESC1; + __IO uint32_t DESC2; + __IO uint32_t DESC3; + __IO uint32_t DESC4; + __IO uint32_t DESC5; + __IO uint32_t DESC6; + __IO uint32_t DESC7; + uint32_t BackupAddr0; /* used to store rx buffer 1 address */ + uint32_t BackupAddr1; /* used to store rx buffer 2 address */ +} ETH_DMADescTypeDef; +/** + * + */ + +/** + * @brief ETH Buffers List structure definition + */ +typedef struct __ETH_BufferTypeDef +{ + uint8_t *buffer; /*gState = DAL_ETH_STATE_RESET; \ + (__HANDLE__)->MspInitCallback = NULL; \ + (__HANDLE__)->MspDeInitCallback = NULL; \ + } while(0) +#else +#define __DAL_ETH_RESET_HANDLE_STATE(__HANDLE__) do{ \ + (__HANDLE__)->gState = DAL_ETH_STATE_RESET; \ + } while(0) +#endif /*USE_DAL_ETH_REGISTER_CALLBACKS */ + +/** + * @brief Enables the specified ETHERNET DMA interrupts. + * @param __HANDLE__ : ETH Handle + * @param __INTERRUPT__: specifies the ETHERNET DMA interrupt sources to be + * enabled @ref ETH_DMA_Interrupts + * @retval None + */ +#define __DAL_ETH_DMA_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->DMAINTEN \ + |= (__INTERRUPT__)) + +/** + * @brief Disables the specified ETHERNET DMA interrupts. + * @param __HANDLE__ : ETH Handle + * @param __INTERRUPT__: specifies the ETHERNET DMA interrupt sources to be + * disabled. @ref ETH_DMA_Interrupts + * @retval None + */ +#define __DAL_ETH_DMA_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->DMAINTEN \ + &= ~(__INTERRUPT__)) + +/** + * @brief Gets the ETHERNET DMA IT source enabled or disabled. + * @param __HANDLE__ : ETH Handle + * @param __INTERRUPT__: specifies the interrupt source to get . @ref ETH_DMA_Interrupts + * @retval The ETH DMA IT Source enabled or disabled + */ +#define __DAL_ETH_DMA_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->DMAINTEN &\ + (__INTERRUPT__)) == (__INTERRUPT__)) + +/** + * @brief Gets the ETHERNET DMA IT pending bit. + * @param __HANDLE__ : ETH Handle + * @param __INTERRUPT__: specifies the interrupt source to get . @ref ETH_DMA_Interrupts + * @retval The state of ETH DMA IT (SET or RESET) + */ +#define __DAL_ETH_DMA_GET_IT(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->DMASTS &\ + (__INTERRUPT__)) == (__INTERRUPT__)) + +/** + * @brief Clears the ETHERNET DMA IT pending bit. + * @param __HANDLE__ : ETH Handle + * @param __INTERRUPT__: specifies the interrupt pending bit to clear. @ref ETH_DMA_Interrupts + * @retval None + */ +#define __DAL_ETH_DMA_CLEAR_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->DMASTS = (__INTERRUPT__)) + +/** + * @brief Checks whether the specified ETHERNET DMA flag is set or not. + * @param __HANDLE__: ETH Handle + * @param __FLAG__: specifies the flag to check. @ref ETH_DMA_Status_Flags + * @retval The state of ETH DMA FLAG (SET or RESET). + */ +#define __DAL_ETH_DMA_GET_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->DMACSR &\ + ( __FLAG__)) == ( __FLAG__)) + +/** + * @brief Clears the specified ETHERNET DMA flag. + * @param __HANDLE__: ETH Handle + * @param __FLAG__: specifies the flag to check. @ref ETH_DMA_Status_Flags + * @retval The state of ETH DMA FLAG (SET or RESET). + */ +#define __DAL_ETH_DMA_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->DMACSR = ( __FLAG__)) + +/** + * @brief Enables the specified ETHERNET MAC interrupts. + * @param __HANDLE__ : ETH Handle + * @param __INTERRUPT__: specifies the ETHERNET MAC interrupt sources to be + * enabled @ref ETH_MAC_Interrupts + * @arg ETH_MAC_IT_TST + * @arg ETH_MAC_IT_PMT + * @retval None + */ +#define __DAL_ETH_MAC_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->MACIMASK \ + |= (__INTERRUPT__)) + +/** + * @brief Disables the specified ETHERNET MAC interrupts. + * @param __HANDLE__ : ETH Handle + * @param __INTERRUPT__: specifies the ETHERNET MAC interrupt sources to be + * enabled @ref ETH_MAC_Interrupts + * @arg ETH_MAC_IT_TST + * @arg ETH_MAC_IT_PMT + * @retval None + */ +#define __DAL_ETH_MAC_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->MACIMASK \ + &= ~(__INTERRUPT__)) + +/** + * @brief Checks whether the specified ETHERNET MAC flag is set or not. + * @param __HANDLE__: ETH Handle + * @param __INTERRUPT__: specifies the flag to check. @ref ETH_MAC_Interrupts + * @retval The state of ETH MAC IT (SET or RESET). + */ +#define __DAL_ETH_MAC_GET_IT(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->MACISTS &\ + ( __INTERRUPT__)) == ( __INTERRUPT__)) + +/*!< External interrupt line 19 Connected to the ETH wakeup EINT Line */ +#define ETH_WAKEUP_EINT_LINE ((uint32_t)0x00080000U) + +/** + * @brief Enable the ETH WAKEUP Exti Line. + * @param __EINT_LINE__: specifies the ETH WAKEUP Exti sources to be enabled. + * @arg ETH_WAKEUP_EINT_LINE + * @retval None. + */ +#define __DAL_ETH_WAKEUP_EINT_ENABLE_IT(__EINT_LINE__) (EINT->IMASK |= (__EINT_LINE__)) + +/** + * @brief checks whether the specified ETH WAKEUP Exti interrupt flag is set or not. + * @param __EINT_LINE__: specifies the ETH WAKEUP Exti sources to be cleared. + * @arg ETH_WAKEUP_EINT_LINE + * @retval EINT ETH WAKEUP Line Status. + */ +#define __DAL_ETH_WAKEUP_EINT_GET_FLAG(__EINT_LINE__) (EINT->IPEND & (__EINT_LINE__)) + +/** + * @brief Clear the ETH WAKEUP Exti flag. + * @param __EINT_LINE__: specifies the ETH WAKEUP Exti sources to be cleared. + * @arg ETH_WAKEUP_EINT_LINE + * @retval None. + */ +#define __DAL_ETH_WAKEUP_EINT_CLEAR_FLAG(__EINT_LINE__) (EINT->IPEND = (__EINT_LINE__)) + + +/** + * @brief enable rising edge interrupt on selected EINT line. + * @param __EINT_LINE__: specifies the ETH WAKEUP EINT sources to be disabled. + * @arg ETH_WAKEUP_EINT_LINE + * @retval None + */ +#define __DAL_ETH_WAKEUP_EINT_ENABLE_RISING_EDGE(__EINT_LINE__) (EINT->FTEN &= ~(__EINT_LINE__)); \ + (EINT->RTEN |= (__EINT_LINE__)) + +/** + * @brief enable falling edge interrupt on selected EINT line. + * @param __EINT_LINE__: specifies the ETH WAKEUP EINT sources to be disabled. + * @arg ETH_WAKEUP_EINT_LINE + * @retval None + */ +#define __DAL_ETH_WAKEUP_EINT_ENABLE_FALLING_EDGE(__EINT_LINE__) (EINT->RTEN &= ~(__EINT_LINE__));\ + (EINT->FTEN |= (__EINT_LINE__)) + +/** + * @brief enable falling edge interrupt on selected EINT line. + * @param __EINT_LINE__: specifies the ETH WAKEUP EINT sources to be disabled. + * @arg ETH_WAKEUP_EINT_LINE + * @retval None + */ +#define __DAL_ETH_WAKEUP_EINT_ENABLE_RISING_FALLING_EDGE(__EINT_LINE__) (EINT->RTEN |= (__EINT_LINE__));\ + (EINT->FTEN |= (__EINT_LINE__)) + +/** + * @brief Generates a Software interrupt on selected EINT line. + * @param __EINT_LINE__: specifies the ETH WAKEUP EINT sources to be disabled. + * @arg ETH_WAKEUP_EINT_LINE + * @retval None + */ +#define __DAL_ETH_WAKEUP_EINT_GENERATE_SWIT(__EINT_LINE__) (EINT->SWINTE |= (__EINT_LINE__)) + +#define __DAL_ETH_GET_PTP_CONTROL(__HANDLE__, __FLAG__) (((((__HANDLE__)->Instance->PTPTSCTRL) & \ + (__FLAG__)) == (__FLAG__)) ? SET : RESET) + +#define __DAL_ETH_SET_PTP_CONTROL(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->PTPTSCTRL |= (__FLAG__)) +/** + * @} + */ + + +/* Exported functions --------------------------------------------------------*/ + +/** @addtogroup ETH_Exported_Functions + * @{ + */ + +/** @addtogroup ETH_Exported_Functions_Group1 + * @{ + */ +/* Initialization and de initialization functions **********************************/ +DAL_StatusTypeDef DAL_ETH_Init(ETH_HandleTypeDef *heth); +DAL_StatusTypeDef DAL_ETH_DeInit(ETH_HandleTypeDef *heth); +void DAL_ETH_MspInit(ETH_HandleTypeDef *heth); +void DAL_ETH_MspDeInit(ETH_HandleTypeDef *heth); + +/* Callbacks Register/UnRegister functions ***********************************/ +#if (USE_DAL_ETH_REGISTER_CALLBACKS == 1) +DAL_StatusTypeDef DAL_ETH_RegisterCallback(ETH_HandleTypeDef *heth, DAL_ETH_CallbackIDTypeDef CallbackID, + pETH_CallbackTypeDef pCallback); +DAL_StatusTypeDef DAL_ETH_UnRegisterCallback(ETH_HandleTypeDef *heth, DAL_ETH_CallbackIDTypeDef CallbackID); +#endif /* USE_DAL_ETH_REGISTER_CALLBACKS */ + +/** + * @} + */ + +/** @addtogroup ETH_Exported_Functions_Group2 + * @{ + */ +/* IO operation functions *******************************************************/ +DAL_StatusTypeDef DAL_ETH_Start(ETH_HandleTypeDef *heth); +DAL_StatusTypeDef DAL_ETH_Start_IT(ETH_HandleTypeDef *heth); +DAL_StatusTypeDef DAL_ETH_Stop(ETH_HandleTypeDef *heth); +DAL_StatusTypeDef DAL_ETH_Stop_IT(ETH_HandleTypeDef *heth); + +DAL_StatusTypeDef DAL_ETH_ReadData(ETH_HandleTypeDef *heth, void **pAppBuff); +DAL_StatusTypeDef DAL_ETH_RegisterRxAllocateCallback(ETH_HandleTypeDef *heth, + pETH_rxAllocateCallbackTypeDef rxAllocateCallback); +DAL_StatusTypeDef DAL_ETH_UnRegisterRxAllocateCallback(ETH_HandleTypeDef *heth); +DAL_StatusTypeDef DAL_ETH_RegisterRxLinkCallback(ETH_HandleTypeDef *heth, pETH_rxLinkCallbackTypeDef rxLinkCallback); +DAL_StatusTypeDef DAL_ETH_UnRegisterRxLinkCallback(ETH_HandleTypeDef *heth); +DAL_StatusTypeDef DAL_ETH_GetRxDataErrorCode(ETH_HandleTypeDef *heth, uint32_t *pErrorCode); +DAL_StatusTypeDef DAL_ETH_RegisterTxFreeCallback(ETH_HandleTypeDef *heth, pETH_txFreeCallbackTypeDef txFreeCallback); +DAL_StatusTypeDef DAL_ETH_UnRegisterTxFreeCallback(ETH_HandleTypeDef *heth); +DAL_StatusTypeDef DAL_ETH_ReleaseTxPacket(ETH_HandleTypeDef *heth); + +#ifdef DAL_ETH_USE_PTP +DAL_StatusTypeDef DAL_ETH_PTP_SetConfig(ETH_HandleTypeDef *heth, ETH_PTP_ConfigTypeDef *ptpconfig); +DAL_StatusTypeDef DAL_ETH_PTP_GetConfig(ETH_HandleTypeDef *heth, ETH_PTP_ConfigTypeDef *ptpconfig); +DAL_StatusTypeDef DAL_ETH_PTP_SetTime(ETH_HandleTypeDef *heth, ETH_TimeTypeDef *time); +DAL_StatusTypeDef DAL_ETH_PTP_GetTime(ETH_HandleTypeDef *heth, ETH_TimeTypeDef *time); +DAL_StatusTypeDef DAL_ETH_PTP_AddTimeOffset(ETH_HandleTypeDef *heth, ETH_PtpUpdateTypeDef ptpoffsettype, + ETH_TimeTypeDef *timeoffset); +DAL_StatusTypeDef DAL_ETH_PTP_InsertTxTimestamp(ETH_HandleTypeDef *heth); +DAL_StatusTypeDef DAL_ETH_PTP_GetTxTimestamp(ETH_HandleTypeDef *heth, ETH_TimeStampTypeDef *timestamp); +DAL_StatusTypeDef DAL_ETH_PTP_GetRxTimestamp(ETH_HandleTypeDef *heth, ETH_TimeStampTypeDef *timestamp); +DAL_StatusTypeDef DAL_ETH_RegisterTxPtpCallback(ETH_HandleTypeDef *heth, pETH_txPtpCallbackTypeDef txPtpCallback); +DAL_StatusTypeDef DAL_ETH_UnRegisterTxPtpCallback(ETH_HandleTypeDef *heth); +#endif /* DAL_ETH_USE_PTP */ + +DAL_StatusTypeDef DAL_ETH_Transmit(ETH_HandleTypeDef *heth, ETH_TxPacketConfig *pTxConfig, uint32_t Timeout); +DAL_StatusTypeDef DAL_ETH_Transmit_IT(ETH_HandleTypeDef *heth, ETH_TxPacketConfig *pTxConfig); + +DAL_StatusTypeDef DAL_ETH_WritePHYRegister(ETH_HandleTypeDef *heth, uint32_t PHYAddr, uint32_t PHYReg, + uint32_t RegValue); +DAL_StatusTypeDef DAL_ETH_ReadPHYRegister(ETH_HandleTypeDef *heth, uint32_t PHYAddr, uint32_t PHYReg, + uint32_t *pRegValue); + +void DAL_ETH_IRQHandler(ETH_HandleTypeDef *heth); +void DAL_ETH_TxCpltCallback(ETH_HandleTypeDef *heth); +void DAL_ETH_RxCpltCallback(ETH_HandleTypeDef *heth); +void DAL_ETH_ErrorCallback(ETH_HandleTypeDef *heth); +void DAL_ETH_PMTCallback(ETH_HandleTypeDef *heth); +void DAL_ETH_WakeUpCallback(ETH_HandleTypeDef *heth); +void DAL_ETH_RxAllocateCallback(uint8_t **buff); +void DAL_ETH_RxLinkCallback(void **pStart, void **pEnd, uint8_t *buff, uint16_t Length); +void DAL_ETH_TxFreeCallback(uint32_t *buff); +void DAL_ETH_TxPtpCallback(uint32_t *buff, ETH_TimeStampTypeDef *timestamp); +/** + * @} + */ + +/** @addtogroup ETH_Exported_Functions_Group3 + * @{ + */ +/* Peripheral Control functions **********************************************/ +/* MAC & DMA Configuration APIs **********************************************/ +DAL_StatusTypeDef DAL_ETH_GetMACConfig(ETH_HandleTypeDef *heth, ETH_MACConfigTypeDef *macconf); +DAL_StatusTypeDef DAL_ETH_GetDMAConfig(ETH_HandleTypeDef *heth, ETH_DMAConfigTypeDef *dmaconf); +DAL_StatusTypeDef DAL_ETH_SetMACConfig(ETH_HandleTypeDef *heth, ETH_MACConfigTypeDef *macconf); +DAL_StatusTypeDef DAL_ETH_SetDMAConfig(ETH_HandleTypeDef *heth, ETH_DMAConfigTypeDef *dmaconf); +void DAL_ETH_SetMDIOClockRange(ETH_HandleTypeDef *heth); + +/* MAC VLAN Processing APIs ************************************************/ +void DAL_ETH_SetRxVLANIdentifier(ETH_HandleTypeDef *heth, uint32_t ComparisonBits, + uint32_t VLANIdentifier); + +/* MAC L2 Packet Filtering APIs **********************************************/ +DAL_StatusTypeDef DAL_ETH_GetMACFilterConfig(ETH_HandleTypeDef *heth, ETH_MACFilterConfigTypeDef *pFilterConfig); +DAL_StatusTypeDef DAL_ETH_SetMACFilterConfig(ETH_HandleTypeDef *heth, ETH_MACFilterConfigTypeDef *pFilterConfig); +DAL_StatusTypeDef DAL_ETH_SetHashTable(ETH_HandleTypeDef *heth, uint32_t *pHashTable); +DAL_StatusTypeDef DAL_ETH_SetSourceMACAddrMatch(ETH_HandleTypeDef *heth, uint32_t AddrNbr, uint8_t *pMACAddr); + +/* MAC Power Down APIs *****************************************************/ +void DAL_ETH_EnterPowerDownMode(ETH_HandleTypeDef *heth, ETH_PowerDownConfigTypeDef *pPowerDownConfig); +void DAL_ETH_ExitPowerDownMode(ETH_HandleTypeDef *heth); +DAL_StatusTypeDef DAL_ETH_SetWakeUpFilter(ETH_HandleTypeDef *heth, uint32_t *pFilter, uint32_t Count); + +/** + * @} + */ + +/** @addtogroup ETH_Exported_Functions_Group4 + * @{ + */ +/* Peripheral State functions **************************************************/ +DAL_ETH_StateTypeDef DAL_ETH_GetState(ETH_HandleTypeDef *heth); +uint32_t DAL_ETH_GetError(ETH_HandleTypeDef *heth); +uint32_t DAL_ETH_GetDMAError(ETH_HandleTypeDef *heth); +uint32_t DAL_ETH_GetMACError(ETH_HandleTypeDef *heth); +uint32_t DAL_ETH_GetMACWakeUpSource(ETH_HandleTypeDef *heth); +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#endif /* ETH */ + +#ifdef __cplusplus +} +#endif + +#endif /* APM32F4xx_DAL_ETH_H */ + + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_flash.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_flash.h new file mode 100644 index 0000000000..3abb8be042 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_flash.h @@ -0,0 +1,449 @@ +/** + * + * @file apm32f4xx_dal_flash.h + * @brief Header file of FLASH DAL module. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2017 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file in + * the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef APM32F4xx_DAL_FLASH_H +#define APM32F4xx_DAL_FLASH_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal_def.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @addtogroup FLASH + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ +/** @defgroup FLASH_Exported_Types FLASH Exported Types + * @{ + */ + +/** + * @brief FLASH Procedure structure definition + */ +typedef enum +{ + FLASH_PROC_NONE = 0U, + FLASH_PROC_SECTERASE, + FLASH_PROC_MASSERASE, + FLASH_PROC_PROGRAM +} FLASH_ProcedureTypeDef; + +/** + * @brief FLASH handle Structure definition + */ +typedef struct +{ + __IO FLASH_ProcedureTypeDef ProcedureOnGoing; /*Internal variable to indicate which procedure is ongoing or not in IT context*/ + + __IO uint32_t NbSectorsToErase; /*Internal variable to save the remaining sectors to erase in IT context*/ + + __IO uint8_t VoltageForErase; /*Internal variable to provide voltage range selected by user in IT context*/ + + __IO uint32_t Sector; /*Internal variable to define the current sector which is erasing*/ + + __IO uint32_t Bank; /*Internal variable to save current bank selected during mass erase*/ + + __IO uint32_t Address; /*Internal variable to save address selected for program*/ + + DAL_LockTypeDef Lock; /* FLASH locking object */ + + __IO uint32_t ErrorCode; /* FLASH error code */ + +}FLASH_ProcessTypeDef; + +/** + * @} + */ + +/* Exported constants --------------------------------------------------------*/ +/** @defgroup FLASH_Exported_Constants FLASH Exported Constants + * @{ + */ +/** @defgroup FLASH_Error_Code FLASH Error Code + * @brief FLASH Error Code + * @{ + */ +#define DAL_FLASH_ERROR_NONE 0x00000000U /*!< No error */ +#define DAL_FLASH_ERROR_RD 0x00000001U /*!< Read Protection error */ +#define DAL_FLASH_ERROR_PGS 0x00000002U /*!< Programming Sequence error */ +#define DAL_FLASH_ERROR_PGP 0x00000004U /*!< Programming Parallelism error */ +#define DAL_FLASH_ERROR_PGA 0x00000008U /*!< Programming Alignment error */ +#define DAL_FLASH_ERROR_WRP 0x00000010U /*!< Write protection error */ +#define DAL_FLASH_ERROR_OPERATION 0x00000020U /*!< Operation Error */ +/** + * @} + */ + +/** @defgroup FLASH_Type_Program FLASH Type Program + * @{ + */ +#define FLASH_TYPEPROGRAM_BYTE 0x00000000U /*!< Program byte (8-bit) at a specified address */ +#define FLASH_TYPEPROGRAM_HALFWORD 0x00000001U /*!< Program a half-word (16-bit) at a specified address */ +#define FLASH_TYPEPROGRAM_WORD 0x00000002U /*!< Program a word (32-bit) at a specified address */ +#define FLASH_TYPEPROGRAM_DOUBLEWORD 0x00000003U /*!< Program a double word (64-bit) at a specified address */ +/** + * @} + */ + +/** @defgroup FLASH_Flag_definition FLASH Flag definition + * @brief Flag definition + * @{ + */ +#define FLASH_FLAG_EOP FLASH_STS_OPRCMP /*!< FLASH End of Operation flag */ +#define FLASH_FLAG_OPERR FLASH_STS_OPRERR /*!< FLASH operation Error flag */ +#define FLASH_FLAG_WRPERR FLASH_STS_WPROTERR /*!< FLASH Write protected error flag */ +#define FLASH_FLAG_PGAERR FLASH_STS_PGALGERR /*!< FLASH Programming Alignment error flag */ +#define FLASH_FLAG_PGPERR FLASH_STS_PGPRLERR /*!< FLASH Programming Parallelism error flag */ +#define FLASH_FLAG_PGSERR FLASH_STS_PGSEQERR /*!< FLASH Programming Sequence error flag */ +#if defined(FLASH_STS_RPROERR) +#define FLASH_FLAG_RDERR FLASH_STS_RPROERR /*!< Read Protection error flag (PCROP) */ +#endif /* FLASH_STS_RPROERR */ +#define FLASH_FLAG_BSY FLASH_STS_BUSY /*!< FLASH Busy flag */ +/** + * @} + */ + +/** @defgroup FLASH_Interrupt_definition FLASH Interrupt definition + * @brief FLASH Interrupt definition + * @{ + */ +#define FLASH_IT_EOP FLASH_CTRL_OPCINTEN /*!< End of FLASH Operation Interrupt source */ +#define FLASH_IT_ERR 0x02000000U /*!< Error Interrupt source */ +/** + * @} + */ + +/** @defgroup FLASH_Program_Parallelism FLASH Program Parallelism + * @{ + */ +#define FLASH_PSIZE_BYTE 0x00000000U +#define FLASH_PSIZE_HALF_WORD 0x00000100U +#define FLASH_PSIZE_WORD 0x00000200U +#define FLASH_PSIZE_DOUBLE_WORD 0x00000300U +#define CR_PSIZE_MASK 0xFFFFFCFFU +/** + * @} + */ + +/** @defgroup FLASH_Keys FLASH Keys + * @{ + */ +#define RDP_KEY ((uint16_t)0x00A5) +#define FLASH_KEY1 0x45670123U +#define FLASH_KEY2 0xCDEF89ABU +#define FLASH_OPT_KEY1 0x08192A3BU +#define FLASH_OPT_KEY2 0x4C5D6E7FU +/** + * @} + */ + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ +/** @defgroup FLASH_Exported_Macros FLASH Exported Macros + * @{ + */ +/** + * @brief Set the FLASH Latency. + * @param __LATENCY__ FLASH Latency + * The value of this parameter depend on device used within the same series + * @retval none + */ +#define __DAL_FLASH_SET_LATENCY(__LATENCY__) (*(__IO uint8_t *)ACCTRL_BYTE0_ADDRESS = (uint8_t)(__LATENCY__)) + +/** + * @brief Get the FLASH Latency. + * @retval FLASH Latency + * The value of this parameter depend on device used within the same series + */ +#define __DAL_FLASH_GET_LATENCY() (READ_BIT((FLASH->ACCTRL), FLASH_ACCTRL_WAITP)) + +/** + * @brief Enable the FLASH prefetch buffer. + * @retval none + */ +#define __DAL_FLASH_PREFETCH_BUFFER_ENABLE() (FLASH->ACCTRL |= FLASH_ACCTRL_PREFEN) + +/** + * @brief Disable the FLASH prefetch buffer. + * @retval none + */ +#define __DAL_FLASH_PREFETCH_BUFFER_DISABLE() (FLASH->ACCTRL &= (~FLASH_ACCTRL_PREFEN)) + +/** + * @brief Enable the FLASH instruction cache. + * @retval none + */ +#define __DAL_FLASH_INSTRUCTION_CACHE_ENABLE() (FLASH->ACCTRL |= FLASH_ACCTRL_ICACHEEN) + +/** + * @brief Disable the FLASH instruction cache. + * @retval none + */ +#define __DAL_FLASH_INSTRUCTION_CACHE_DISABLE() (FLASH->ACCTRL &= (~FLASH_ACCTRL_ICACHEEN)) + +/** + * @brief Enable the FLASH data cache. + * @retval none + */ +#define __DAL_FLASH_DATA_CACHE_ENABLE() (FLASH->ACCTRL |= FLASH_ACCTRL_DCACHEEN) + +/** + * @brief Disable the FLASH data cache. + * @retval none + */ +#define __DAL_FLASH_DATA_CACHE_DISABLE() (FLASH->ACCTRL &= (~FLASH_ACCTRL_DCACHEEN)) + +/** + * @brief Resets the FLASH instruction Cache. + * @note This function must be used only when the Instruction Cache is disabled. + * @retval None + */ +#define __DAL_FLASH_INSTRUCTION_CACHE_RESET() do {FLASH->ACCTRL |= FLASH_ACCTRL_ICACHERST; \ + FLASH->ACCTRL &= ~FLASH_ACCTRL_ICACHERST; \ + }while(0U) + +/** + * @brief Resets the FLASH data Cache. + * @note This function must be used only when the data Cache is disabled. + * @retval None + */ +#define __DAL_FLASH_DATA_CACHE_RESET() do {FLASH->ACCTRL |= FLASH_ACCTRL_DCACHERST; \ + FLASH->ACCTRL &= ~FLASH_ACCTRL_DCACHERST; \ + }while(0U) +/** + * @brief Enable the specified FLASH interrupt. + * @param __INTERRUPT__ FLASH interrupt + * This parameter can be any combination of the following values: + * @arg FLASH_IT_EOP: End of FLASH Operation Interrupt + * @arg FLASH_IT_ERR: Error Interrupt + * @retval none + */ +#define __DAL_FLASH_ENABLE_IT(__INTERRUPT__) (FLASH->CTRL |= (__INTERRUPT__)) + +/** + * @brief Disable the specified FLASH interrupt. + * @param __INTERRUPT__ FLASH interrupt + * This parameter can be any combination of the following values: + * @arg FLASH_IT_EOP: End of FLASH Operation Interrupt + * @arg FLASH_IT_ERR: Error Interrupt + * @retval none + */ +#define __DAL_FLASH_DISABLE_IT(__INTERRUPT__) (FLASH->CTRL &= ~(uint32_t)(__INTERRUPT__)) + +/** + * @brief Get the specified FLASH flag status. + * @param __FLAG__ specifies the FLASH flags to check. + * This parameter can be any combination of the following values: + * @arg FLASH_FLAG_EOP : FLASH End of Operation flag + * @arg FLASH_FLAG_OPERR : FLASH operation Error flag + * @arg FLASH_FLAG_WRPERR: FLASH Write protected error flag + * @arg FLASH_FLAG_PGAERR: FLASH Programming Alignment error flag + * @arg FLASH_FLAG_PGPERR: FLASH Programming Parallelism error flag + * @arg FLASH_FLAG_PGSERR: FLASH Programming Sequence error flag + * @arg FLASH_FLAG_RDERR : FLASH Read Protection error flag (PCROP) (*) + * @arg FLASH_FLAG_BSY : FLASH Busy flag + * (*) FLASH_FLAG_RDERR is not available for APM32F405xx/407xx/417xx devices + * @retval The new state of __FLAG__ (SET or RESET). + */ +#define __DAL_FLASH_GET_FLAG(__FLAG__) ((FLASH->STS & (__FLAG__))) + +/** + * @brief Clear the specified FLASH flags. + * @param __FLAG__ specifies the FLASH flags to clear. + * This parameter can be any combination of the following values: + * @arg FLASH_FLAG_EOP : FLASH End of Operation flag + * @arg FLASH_FLAG_OPERR : FLASH operation Error flag + * @arg FLASH_FLAG_WRPERR: FLASH Write protected error flag + * @arg FLASH_FLAG_PGAERR: FLASH Programming Alignment error flag + * @arg FLASH_FLAG_PGPERR: FLASH Programming Parallelism error flag + * @arg FLASH_FLAG_PGSERR: FLASH Programming Sequence error flag + * @arg FLASH_FLAG_RDERR : FLASH Read Protection error flag (PCROP) (*) + * (*) FLASH_FLAG_RDERR is not available for APM32F405xx/407xx/417xx devices + * @retval none + */ +#define __DAL_FLASH_CLEAR_FLAG(__FLAG__) (FLASH->STS = (__FLAG__)) +/** + * @} + */ + +/* Include FLASH DAL Extension module */ +#include "apm32f4xx_dal_flash_ex.h" +#include "apm32f4xx_dal_flash_ramfunc.h" + +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup FLASH_Exported_Functions + * @{ + */ +/** @addtogroup FLASH_Exported_Functions_Group1 + * @{ + */ +/* Program operation functions ***********************************************/ +DAL_StatusTypeDef DAL_FLASH_Program(uint32_t TypeProgram, uint32_t Address, uint64_t Data); +DAL_StatusTypeDef DAL_FLASH_Program_IT(uint32_t TypeProgram, uint32_t Address, uint64_t Data); +/* FLASH IRQ handler method */ +void DAL_FLASH_IRQHandler(void); +/* Callbacks in non blocking modes */ +void DAL_FLASH_EndOfOperationCallback(uint32_t ReturnValue); +void DAL_FLASH_OperationErrorCallback(uint32_t ReturnValue); +/** + * @} + */ + +/** @addtogroup FLASH_Exported_Functions_Group2 + * @{ + */ +/* Peripheral Control functions **********************************************/ +DAL_StatusTypeDef DAL_FLASH_Unlock(void); +DAL_StatusTypeDef DAL_FLASH_Lock(void); +DAL_StatusTypeDef DAL_FLASH_OB_Unlock(void); +DAL_StatusTypeDef DAL_FLASH_OB_Lock(void); +/* Option bytes control */ +DAL_StatusTypeDef DAL_FLASH_OB_Launch(void); +/** + * @} + */ + +/** @addtogroup FLASH_Exported_Functions_Group3 + * @{ + */ +/* Peripheral State functions ************************************************/ +uint32_t DAL_FLASH_GetError(void); +DAL_StatusTypeDef FLASH_WaitForLastOperation(uint32_t Timeout); +/** + * @} + */ + +/** + * @} + */ +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/** @defgroup FLASH_Private_Variables FLASH Private Variables + * @{ + */ + +/** + * @} + */ +/* Private constants ---------------------------------------------------------*/ +/** @defgroup FLASH_Private_Constants FLASH Private Constants + * @{ + */ + +/** + * @brief ACCTRL register byte 0 (Bits[7:0]) base address + */ +#define ACCTRL_BYTE0_ADDRESS 0x40023C00U +/** + * @brief OPTCTRL register byte 0 (Bits[7:0]) base address + */ +#define OPTCTRL_BYTE0_ADDRESS 0x40023C14U +/** + * @brief OPTCTRL register byte 1 (Bits[15:8]) base address + */ +#define OPTCTRL_BYTE1_ADDRESS 0x40023C15U +/** + * @brief OPTCTRL register byte 2 (Bits[23:16]) base address + */ +#define OPTCTRL_BYTE2_ADDRESS 0x40023C16U +/** + * @brief OPTCTRL register byte 3 (Bits[31:24]) base address + */ +#define OPTCTRL_BYTE3_ADDRESS 0x40023C17U + +/** + * @} + */ + +/* Private macros ------------------------------------------------------------*/ +/** @defgroup FLASH_Private_Macros FLASH Private Macros + * @{ + */ + +/** @defgroup FLASH_IS_FLASH_Definitions FLASH Private macros to check input parameters + * @{ + */ +#define IS_FLASH_TYPEPROGRAM(VALUE)(((VALUE) == FLASH_TYPEPROGRAM_BYTE) || \ + ((VALUE) == FLASH_TYPEPROGRAM_HALFWORD) || \ + ((VALUE) == FLASH_TYPEPROGRAM_WORD) || \ + ((VALUE) == FLASH_TYPEPROGRAM_DOUBLEWORD)) +/** + * @} + */ + +/** + * @} + */ + +/* Private functions ---------------------------------------------------------*/ +/** @defgroup FLASH_Private_Functions FLASH Private Functions + * @{ + */ + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* APM32F4xx_DAL_FLASH_H */ + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_flash_ex.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_flash_ex.h new file mode 100644 index 0000000000..a745162b39 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_flash_ex.h @@ -0,0 +1,594 @@ +/** + * + * @file apm32f4xx_dal_flash_ex.h + * @brief Header file of FLASH DAL Extension module. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2017 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file in + * the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef APM32F4xx_DAL_FLASH_EX_H +#define APM32F4xx_DAL_FLASH_EX_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal_def.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @addtogroup FLASHEx + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ +/** @defgroup FLASHEx_Exported_Types FLASH Exported Types + * @{ + */ + +/** + * @brief FLASH Erase structure definition + */ +typedef struct +{ + uint32_t TypeErase; /*!< Mass erase or sector Erase. + This parameter can be a value of @ref FLASHEx_Type_Erase */ + + uint32_t Banks; /*!< Select banks to erase when Mass erase is enabled. + This parameter must be a value of @ref FLASHEx_Banks */ + + uint32_t Sector; /*!< Initial FLASH sector to erase when Mass erase is disabled + This parameter must be a value of @ref FLASHEx_Sectors */ + + uint32_t NbSectors; /*!< Number of sectors to be erased. + This parameter must be a value between 1 and (max number of sectors - value of Initial sector)*/ + + uint32_t VoltageRange;/*!< The device voltage range which defines the erase parallelism + This parameter must be a value of @ref FLASHEx_Voltage_Range */ + +} FLASH_EraseInitTypeDef; + +/** + * @brief FLASH Option Bytes Program structure definition + */ +typedef struct +{ + uint32_t OptionType; /*!< Option byte to be configured. + This parameter can be a value of @ref FLASHEx_Option_Type */ + + uint32_t WRPState; /*!< Write protection activation or deactivation. + This parameter can be a value of @ref FLASHEx_WRP_State */ + + uint32_t WRPSector; /*!< Specifies the sector(s) to be write protected. + The value of this parameter depend on device used within the same series */ + + uint32_t Banks; /*!< Select banks for WRP activation/deactivation of all sectors. + This parameter must be a value of @ref FLASHEx_Banks */ + + uint32_t RDPLevel; /*!< Set the read protection level. + This parameter can be a value of @ref FLASHEx_Option_Bytes_Read_Protection */ + + uint32_t BORLevel; /*!< Set the BOR Level. + This parameter can be a value of @ref FLASHEx_BOR_Reset_Level */ + + uint8_t USERConfig; /*!< Program the FLASH User Option Byte: IWDT_SW / RST_STOP / RST_STDBY. */ + +} FLASH_OBProgramInitTypeDef; + +/** + * @brief FLASH Advanced Option Bytes Program structure definition + */ +#if defined(APM32F411xx) +typedef struct +{ + uint32_t OptionType; /*!< Option byte to be configured for extension. + This parameter can be a value of @ref FLASHEx_Advanced_Option_Type */ + + uint32_t PCROPState; /*!< PCROP activation or deactivation. + This parameter can be a value of @ref FLASHEx_PCROP_State */ + + uint16_t Sectors; /*!< specifies the sector(s) set for PCROP. + This parameter can be a value of @ref FLASHEx_Option_Bytes_PC_ReadWrite_Protection */ + +}FLASH_AdvOBProgramInitTypeDef; +#endif /* APM32F411xx */ +/** + * @} + */ + +/* Exported constants --------------------------------------------------------*/ + +/** @defgroup FLASHEx_Exported_Constants FLASH Exported Constants + * @{ + */ + +/** @defgroup FLASHEx_Type_Erase FLASH Type Erase + * @{ + */ +#define FLASH_TYPEERASE_SECTORS 0x00000000U /*!< Sectors erase only */ +#define FLASH_TYPEERASE_MASSERASE 0x00000001U /*!< Flash Mass erase activation */ +/** + * @} + */ + +/** @defgroup FLASHEx_Voltage_Range FLASH Voltage Range + * @{ + */ +#define FLASH_VOLTAGE_RANGE_1 0x00000000U /*!< Device operating range: 1.8V to 2.1V */ +#define FLASH_VOLTAGE_RANGE_2 0x00000001U /*!< Device operating range: 2.1V to 2.7V */ +#define FLASH_VOLTAGE_RANGE_3 0x00000002U /*!< Device operating range: 2.7V to 3.6V */ +#define FLASH_VOLTAGE_RANGE_4 0x00000003U /*!< Device operating range: 2.7V to 3.6V + External Vpp */ +/** + * @} + */ + +/** @defgroup FLASHEx_WRP_State FLASH WRP State + * @{ + */ +#define OB_WRPSTATE_DISABLE 0x00000000U /*!< Disable the write protection of the desired bank 1 sectors */ +#define OB_WRPSTATE_ENABLE 0x00000001U /*!< Enable the write protection of the desired bank 1 sectors */ +/** + * @} + */ + +/** @defgroup FLASHEx_Option_Type FLASH Option Type + * @{ + */ +#define OPTIONBYTE_WRP 0x00000001U /*!< WRP option byte configuration */ +#define OPTIONBYTE_RDP 0x00000002U /*!< RDP option byte configuration */ +#define OPTIONBYTE_USER 0x00000004U /*!< USER option byte configuration */ +#define OPTIONBYTE_BOR 0x00000008U /*!< BOR option byte configuration */ +/** + * @} + */ + +/** @defgroup FLASHEx_Option_Bytes_Read_Protection FLASH Option Bytes Read Protection + * @{ + */ +#define OB_RDP_LEVEL_0 ((uint8_t)0xAA) +#define OB_RDP_LEVEL_1 ((uint8_t)0x55) +#define OB_RDP_LEVEL_2 ((uint8_t)0xCC) /*!< Warning: When enabling read protection level 2 + it s no more possible to go back to level 1 or 0 */ +/** + * @} + */ + +/** @defgroup FLASHEx_Option_Bytes_IWatchdog FLASH Option Bytes IWatchdog + * @{ + */ +#define OB_IWDT_SW ((uint8_t)0x20) /*!< Software IWDT selected */ +#define OB_IWDT_HW ((uint8_t)0x00) /*!< Hardware IWDT selected */ +/** + * @} + */ + +/** @defgroup FLASHEx_Option_Bytes_nRST_STOP FLASH Option Bytes nRST_STOP + * @{ + */ +#define OB_STOP_NO_RST ((uint8_t)0x40) /*!< No reset generated when entering in STOP */ +#define OB_STOP_RST ((uint8_t)0x00) /*!< Reset generated when entering in STOP */ +/** + * @} + */ + + +/** @defgroup FLASHEx_Option_Bytes_nRST_STDBY FLASH Option Bytes nRST_STDBY + * @{ + */ +#define OB_STDBY_NO_RST ((uint8_t)0x80) /*!< No reset generated when entering in STANDBY */ +#define OB_STDBY_RST ((uint8_t)0x00) /*!< Reset generated when entering in STANDBY */ +/** + * @} + */ + +/** @defgroup FLASHEx_BOR_Reset_Level FLASH BOR Reset Level + * @{ + */ +#define OB_BOR_LEVEL3 ((uint8_t)0x00) /*!< Supply voltage ranges from 2.70 to 3.60 V */ +#define OB_BOR_LEVEL2 ((uint8_t)0x04) /*!< Supply voltage ranges from 2.40 to 2.70 V */ +#define OB_BOR_LEVEL1 ((uint8_t)0x08) /*!< Supply voltage ranges from 2.10 to 2.40 V */ +#define OB_BOR_OFF ((uint8_t)0x0C) /*!< Supply voltage ranges from 1.62 to 2.10 V */ +/** + * @} + */ + +#if defined(APM32F411xx) +/** @defgroup FLASHEx_PCROP_State FLASH PCROP State + * @{ + */ +#define OB_PCROP_STATE_DISABLE 0x00000000U /*!< Disable PCROP */ +#define OB_PCROP_STATE_ENABLE 0x00000001U /*!< Enable PCROP */ +/** + * @} + */ +#endif /* APM32F411xx */ + +/** @defgroup FLASHEx_Advanced_Option_Type FLASH Advanced Option Type + * @{ + */ + +#if defined(APM32F411xx) +#define OPTIONBYTE_PCROP 0x00000001U /*!= FLASH_BASE) && ((ADDRESS) <= FLASH_END)) || \ + (((ADDRESS) >= FLASH_OTP_BASE) && ((ADDRESS) <= FLASH_OTP_END))) + +#define IS_FLASH_NBSECTORS(NBSECTORS) (((NBSECTORS) != 0) && ((NBSECTORS) <= FLASH_SECTOR_TOTAL)) + +#if defined(APM32F405xx) || defined(APM32F407xx) || defined(APM32F417xx) || defined(APM32F465xx) +#define IS_OB_WRP_SECTOR(SECTOR)((((SECTOR) & 0xFFFFF000U) == 0x00000000U) && ((SECTOR) != 0x00000000U)) +#endif /* APM32F405xx || APM32F407xx || APM32F417xx || APM32F465xx */ + +#if defined(APM32F411xx) +#define IS_OB_WRP_SECTOR(SECTOR)((((SECTOR) & 0xFFFFF000U) == 0x00000000U) && ((SECTOR) != 0x00000000U)) +#endif /* APM32F411xx */ + +#if defined(APM32F411xx) +#define IS_OB_PCROP(SECTOR)((((SECTOR) & 0xFFFFF000U) == 0x00000000U) && ((SECTOR) != 0x00000000U)) +#endif /* APM32F411xx */ + +#if defined(APM32F411xx) +#define IS_OB_PCROP_SELECT(PCROP) (((PCROP) == OB_PCROP_SELECTED) || ((PCROP) == OB_PCROP_DESELECTED)) +#endif /* APM32F411xx */ +/** + * @} + */ + +/** + * @} + */ + +/* Private functions ---------------------------------------------------------*/ +/** @defgroup FLASHEx_Private_Functions FLASH Private Functions + * @{ + */ +void FLASH_Erase_Sector(uint32_t Sector, uint8_t VoltageRange); +void FLASH_FlushCaches(void); +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* APM32F4xx_DAL_FLASH_EX_H */ + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_flash_ramfunc.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_flash_ramfunc.h new file mode 100644 index 0000000000..7d2af2ee74 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_flash_ramfunc.h @@ -0,0 +1,98 @@ +/** + * + * @file apm32f4xx_dal_flash_ramfunc.h + * @brief Header file of FLASH RAMFUNC driver. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2017 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file in + * the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef APM32F4xx_FLASH_RAMFUNC_H +#define APM32F4xx_FLASH_RAMFUNC_H + +#ifdef __cplusplus + extern "C" { +#endif +#if defined(APM32F411xx) +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal_def.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @addtogroup FLASH_RAMFUNC + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ +/* Exported macro ------------------------------------------------------------*/ +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup FLASH_RAMFUNC_Exported_Functions + * @{ + */ + +/** @addtogroup FLASH_RAMFUNC_Exported_Functions_Group1 + * @{ + */ +__RAM_FUNC DAL_StatusTypeDef DAL_FLASHEx_StopFlashInterfaceClk(void); +__RAM_FUNC DAL_StatusTypeDef DAL_FLASHEx_StartFlashInterfaceClk(void); +__RAM_FUNC DAL_StatusTypeDef DAL_FLASHEx_EnableFlashSleepMode(void); +__RAM_FUNC DAL_StatusTypeDef DAL_FLASHEx_DisableFlashSleepMode(void); +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#endif /* APM32F411xx */ +#ifdef __cplusplus +} +#endif + + +#endif /* APM32F4xx_FLASH_RAMFUNC_H */ + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_gpio.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_gpio.h new file mode 100644 index 0000000000..5519058312 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_gpio.h @@ -0,0 +1,349 @@ +/** + * + * @file apm32f4xx_dal_gpio.h + * @brief Header file of GPIO DAL module. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2017 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef APM32F4xx_DAL_GPIO_H +#define APM32F4xx_DAL_GPIO_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal_def.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @addtogroup GPIO + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ +/** @defgroup GPIO_Exported_Types GPIO Exported Types + * @{ + */ + +/** + * @brief GPIO Init structure definition + */ +typedef struct +{ + uint32_t Pin; /*!< Specifies the GPIO pins to be configured. + This parameter can be any value of @ref GPIO_pins_define */ + + uint32_t Mode; /*!< Specifies the operating mode for the selected pins. + This parameter can be a value of @ref GPIO_mode_define */ + + uint32_t Pull; /*!< Specifies the Pull-up or Pull-Down activation for the selected pins. + This parameter can be a value of @ref GPIO_pull_define */ + + uint32_t Speed; /*!< Specifies the speed for the selected pins. + This parameter can be a value of @ref GPIO_speed_define */ + + uint32_t Alternate; /*!< Peripheral to be connected to the selected pins. + This parameter can be a value of @ref GPIO_Alternate_function_selection */ +}GPIO_InitTypeDef; + +/** + * @brief GPIO Bit SET and Bit RESET enumeration + */ +typedef enum +{ + GPIO_PIN_RESET = 0, + GPIO_PIN_SET +}GPIO_PinState; +/** + * @} + */ + +/* Exported constants --------------------------------------------------------*/ + +/** @defgroup GPIO_Exported_Constants GPIO Exported Constants + * @{ + */ + +/** @defgroup GPIO_pins_define GPIO pins define + * @{ + */ +#define GPIO_PIN_0 ((uint16_t)0x0001) /* Pin 0 selected */ +#define GPIO_PIN_1 ((uint16_t)0x0002) /* Pin 1 selected */ +#define GPIO_PIN_2 ((uint16_t)0x0004) /* Pin 2 selected */ +#define GPIO_PIN_3 ((uint16_t)0x0008) /* Pin 3 selected */ +#define GPIO_PIN_4 ((uint16_t)0x0010) /* Pin 4 selected */ +#define GPIO_PIN_5 ((uint16_t)0x0020) /* Pin 5 selected */ +#define GPIO_PIN_6 ((uint16_t)0x0040) /* Pin 6 selected */ +#define GPIO_PIN_7 ((uint16_t)0x0080) /* Pin 7 selected */ +#define GPIO_PIN_8 ((uint16_t)0x0100) /* Pin 8 selected */ +#define GPIO_PIN_9 ((uint16_t)0x0200) /* Pin 9 selected */ +#define GPIO_PIN_10 ((uint16_t)0x0400) /* Pin 10 selected */ +#define GPIO_PIN_11 ((uint16_t)0x0800) /* Pin 11 selected */ +#define GPIO_PIN_12 ((uint16_t)0x1000) /* Pin 12 selected */ +#define GPIO_PIN_13 ((uint16_t)0x2000) /* Pin 13 selected */ +#define GPIO_PIN_14 ((uint16_t)0x4000) /* Pin 14 selected */ +#define GPIO_PIN_15 ((uint16_t)0x8000) /* Pin 15 selected */ +#define GPIO_PIN_All ((uint16_t)0xFFFF) /* All pins selected */ + +#define GPIO_PIN_MASK 0x0000FFFFU /* PIN mask for assert test */ +/** + * @} + */ + +/** @defgroup GPIO_mode_define GPIO mode define + * @brief GPIO Configuration Mode + * Elements values convention: 0x00WX00YZ + * - W : EINT trigger detection on 3 bits + * - X : EINT mode (IT or Event) on 2 bits + * - Y : Output type (Push Pull or Open Drain) on 1 bit + * - Z : GPIO mode (Input, Output, Alternate or Analog) on 2 bits + * @{ + */ +#define GPIO_MODE_INPUT MODE_INPUT /*!< Input Floating Mode */ +#define GPIO_MODE_OUTPUT_PP (MODE_OUTPUT | OUTPUT_PP) /*!< Output Push Pull Mode */ +#define GPIO_MODE_OUTPUT_OD (MODE_OUTPUT | OUTPUT_OD) /*!< Output Open Drain Mode */ +#define GPIO_MODE_AF_PP (MODE_AF | OUTPUT_PP) /*!< Alternate Function Push Pull Mode */ +#define GPIO_MODE_AF_OD (MODE_AF | OUTPUT_OD) /*!< Alternate Function Open Drain Mode */ + +#define GPIO_MODE_ANALOG MODE_ANALOG /*!< Analog Mode */ + +#define GPIO_MODE_IT_RISING (MODE_INPUT | EINT_IT | TRIGGER_RISING) /*!< External Interrupt Mode with Rising edge trigger detection */ +#define GPIO_MODE_IT_FALLING (MODE_INPUT | EINT_IT | TRIGGER_FALLING) /*!< External Interrupt Mode with Falling edge trigger detection */ +#define GPIO_MODE_IT_RISING_FALLING (MODE_INPUT | EINT_IT | TRIGGER_RISING | TRIGGER_FALLING) /*!< External Interrupt Mode with Rising/Falling edge trigger detection */ + +#define GPIO_MODE_EVT_RISING (MODE_INPUT | EINT_EVT | TRIGGER_RISING) /*!< External Event Mode with Rising edge trigger detection */ +#define GPIO_MODE_EVT_FALLING (MODE_INPUT | EINT_EVT | TRIGGER_FALLING) /*!< External Event Mode with Falling edge trigger detection */ +#define GPIO_MODE_EVT_RISING_FALLING (MODE_INPUT | EINT_EVT | TRIGGER_RISING | TRIGGER_FALLING) /*!< External Event Mode with Rising/Falling edge trigger detection */ + +/** + * @} + */ + +/** @defgroup GPIO_speed_define GPIO speed define + * @brief GPIO Output Maximum frequency + * @{ + */ +#define GPIO_SPEED_FREQ_LOW 0x00000000U /*!< IO works at 2 MHz, please refer to the product datasheet */ +#define GPIO_SPEED_FREQ_MEDIUM 0x00000001U /*!< range 12,5 MHz to 50 MHz, please refer to the product datasheet */ +#define GPIO_SPEED_FREQ_HIGH 0x00000002U /*!< range 25 MHz to 100 MHz, please refer to the product datasheet */ +#define GPIO_SPEED_FREQ_VERY_HIGH 0x00000003U /*!< range 50 MHz to 200 MHz, please refer to the product datasheet */ +/** + * @} + */ + + /** @defgroup GPIO_pull_define GPIO pull define + * @brief GPIO Pull-Up or Pull-Down Activation + * @{ + */ +#define GPIO_NOPULL 0x00000000U /*!< No Pull-up or Pull-down activation */ +#define GPIO_PULLUP 0x00000001U /*!< Pull-up activation */ +#define GPIO_PULLDOWN 0x00000002U /*!< Pull-down activation */ +/** + * @} + */ + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ +/** @defgroup GPIO_Exported_Macros GPIO Exported Macros + * @{ + */ + +/** + * @brief Checks whether the specified EINT line flag is set or not. + * @param __EINT_LINE__ specifies the EINT line flag to check. + * This parameter can be GPIO_PIN_x where x can be(0..15) + * @retval The new state of __EINT_LINE__ (SET or RESET). + */ +#define __DAL_GPIO_EINT_GET_FLAG(__EINT_LINE__) (EINT->IPEND & (__EINT_LINE__)) + +/** + * @brief Clears the EINT's line pending flags. + * @param __EINT_LINE__ specifies the EINT lines flags to clear. + * This parameter can be any combination of GPIO_PIN_x where x can be (0..15) + * @retval None + */ +#define __DAL_GPIO_EINT_CLEAR_FLAG(__EINT_LINE__) (EINT->IPEND = (__EINT_LINE__)) + +/** + * @brief Checks whether the specified EINT line is asserted or not. + * @param __EINT_LINE__ specifies the EINT line to check. + * This parameter can be GPIO_PIN_x where x can be(0..15) + * @retval The new state of __EINT_LINE__ (SET or RESET). + */ +#define __DAL_GPIO_EINT_GET_IT(__EINT_LINE__) (EINT->IPEND & (__EINT_LINE__)) + +/** + * @brief Clears the EINT's line pending bits. + * @param __EINT_LINE__ specifies the EINT lines to clear. + * This parameter can be any combination of GPIO_PIN_x where x can be (0..15) + * @retval None + */ +#define __DAL_GPIO_EINT_CLEAR_IT(__EINT_LINE__) (EINT->IPEND = (__EINT_LINE__)) + +/** + * @brief Generates a Software interrupt on selected EINT line. + * @param __EINT_LINE__ specifies the EINT line to check. + * This parameter can be GPIO_PIN_x where x can be(0..15) + * @retval None + */ +#define __DAL_GPIO_EINT_GENERATE_SWIT(__EINT_LINE__) (EINT->SWINTE |= (__EINT_LINE__)) +/** + * @} + */ + +/* Include GPIO DAL Extension module */ +#include "apm32f4xx_dal_gpio_ex.h" + +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup GPIO_Exported_Functions + * @{ + */ + +/** @addtogroup GPIO_Exported_Functions_Group1 + * @{ + */ +/* Initialization and de-initialization functions *****************************/ +void DAL_GPIO_Init(GPIO_TypeDef *GPIOx, GPIO_InitTypeDef *GPIO_Init); +void DAL_GPIO_DeInit(GPIO_TypeDef *GPIOx, uint32_t GPIO_Pin); +/** + * @} + */ + +/** @addtogroup GPIO_Exported_Functions_Group2 + * @{ + */ +/* IO operation functions *****************************************************/ +GPIO_PinState DAL_GPIO_ReadPin(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin); +void DAL_GPIO_WritePin(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin, GPIO_PinState PinState); +void DAL_GPIO_TogglePin(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin); +DAL_StatusTypeDef DAL_GPIO_LockPin(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin); +void DAL_GPIO_EINT_IRQHandler(uint16_t GPIO_Pin); +void DAL_GPIO_EINT_Callback(uint16_t GPIO_Pin); + +/** + * @} + */ + +/** + * @} + */ +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/** @defgroup GPIO_Private_Constants GPIO Private Constants + * @{ + */ +#define GPIO_MODE_Pos 0U +#define GPIO_MODE (0x3UL << GPIO_MODE_Pos) +#define MODE_INPUT (0x0UL << GPIO_MODE_Pos) +#define MODE_OUTPUT (0x1UL << GPIO_MODE_Pos) +#define MODE_AF (0x2UL << GPIO_MODE_Pos) +#define MODE_ANALOG (0x3UL << GPIO_MODE_Pos) +#define OUTPUT_TYPE_Pos 4U +#define OUTPUT_TYPE (0x1UL << OUTPUT_TYPE_Pos) +#define OUTPUT_PP (0x0UL << OUTPUT_TYPE_Pos) +#define OUTPUT_OD (0x1UL << OUTPUT_TYPE_Pos) +#define EINT_MODE_Pos 16U +#define EINT_MODE (0x3UL << EINT_MODE_Pos) +#define EINT_IT (0x1UL << EINT_MODE_Pos) +#define EINT_EVT (0x2UL << EINT_MODE_Pos) +#define TRIGGER_MODE_Pos 20U +#define TRIGGER_MODE (0x7UL << TRIGGER_MODE_Pos) +#define TRIGGER_RISING (0x1UL << TRIGGER_MODE_Pos) +#define TRIGGER_FALLING (0x2UL << TRIGGER_MODE_Pos) + +/** + * @} + */ + +/* Private macros ------------------------------------------------------------*/ +/** @defgroup GPIO_Private_Macros GPIO Private Macros + * @{ + */ +#define IS_GPIO_PIN_ACTION(ACTION) (((ACTION) == GPIO_PIN_RESET) || ((ACTION) == GPIO_PIN_SET)) +#define IS_GPIO_PIN(PIN) (((((uint32_t)PIN) & GPIO_PIN_MASK ) != 0x00U) && ((((uint32_t)PIN) & ~GPIO_PIN_MASK) == 0x00U)) +#define IS_GPIO_MODE(MODE) (((MODE) == GPIO_MODE_INPUT) ||\ + ((MODE) == GPIO_MODE_OUTPUT_PP) ||\ + ((MODE) == GPIO_MODE_OUTPUT_OD) ||\ + ((MODE) == GPIO_MODE_AF_PP) ||\ + ((MODE) == GPIO_MODE_AF_OD) ||\ + ((MODE) == GPIO_MODE_IT_RISING) ||\ + ((MODE) == GPIO_MODE_IT_FALLING) ||\ + ((MODE) == GPIO_MODE_IT_RISING_FALLING) ||\ + ((MODE) == GPIO_MODE_EVT_RISING) ||\ + ((MODE) == GPIO_MODE_EVT_FALLING) ||\ + ((MODE) == GPIO_MODE_EVT_RISING_FALLING) ||\ + ((MODE) == GPIO_MODE_ANALOG)) +#define IS_GPIO_SPEED(SPEED) (((SPEED) == GPIO_SPEED_FREQ_LOW) || ((SPEED) == GPIO_SPEED_FREQ_MEDIUM) || \ + ((SPEED) == GPIO_SPEED_FREQ_HIGH) || ((SPEED) == GPIO_SPEED_FREQ_VERY_HIGH)) +#define IS_GPIO_PULL(PULL) (((PULL) == GPIO_NOPULL) || ((PULL) == GPIO_PULLUP) || \ + ((PULL) == GPIO_PULLDOWN)) +/** + * @} + */ + +/* Private functions ---------------------------------------------------------*/ +/** @defgroup GPIO_Private_Functions GPIO Private Functions + * @{ + */ + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* APM32F4xx_DAL_GPIO_H */ + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_gpio_ex.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_gpio_ex.h new file mode 100644 index 0000000000..42fc64c136 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_gpio_ex.h @@ -0,0 +1,681 @@ +/** + * + * @file apm32f4xx_dal_gpio_ex.h + * @brief Header file of GPIO DAL Extension module. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2017 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef APM32F4xx_DAL_GPIO_EX_H +#define APM32F4xx_DAL_GPIO_EX_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal_def.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @defgroup GPIOEx GPIOEx + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ +/* Exported constants --------------------------------------------------------*/ +/** @defgroup GPIOEx_Exported_Constants GPIO Exported Constants + * @{ + */ + +/** @defgroup GPIO_Alternate_function_selection GPIO Alternate Function Selection + * @{ + */ + +/*---------------------------------- APM32F407xx/APM32F417xx------------------*/ +#if defined(APM32F407xx) || defined(APM32F417xx) +/** + * @brief AF 0 selection + */ +#define GPIO_AF0_RTC_50Hz ((uint8_t)0x00) /* RTC_50Hz Alternate Function mapping */ +#define GPIO_AF0_MCO ((uint8_t)0x00) /* MCO (MCO1 and MCO2) Alternate Function mapping */ +#define GPIO_AF0_TAMPER ((uint8_t)0x00) /* TAMPER (TAMPER_1 and TAMPER_2) Alternate Function mapping */ +#define GPIO_AF0_SWJ ((uint8_t)0x00) /* SWJ (SWD and JTAG) Alternate Function mapping */ +#define GPIO_AF0_TRACE ((uint8_t)0x00) /* TRACE Alternate Function mapping */ + +/** + * @brief AF 1 selection + */ +#define GPIO_AF1_TMR1 ((uint8_t)0x01) /* TIM1 Alternate Function mapping */ +#define GPIO_AF1_TMR2 ((uint8_t)0x01) /* TIM2 Alternate Function mapping */ + +/** + * @brief AF 2 selection + */ +#define GPIO_AF2_TMR3 ((uint8_t)0x02) /* TIM3 Alternate Function mapping */ +#define GPIO_AF2_TMR4 ((uint8_t)0x02) /* TIM4 Alternate Function mapping */ +#define GPIO_AF2_TMR5 ((uint8_t)0x02) /* TIM5 Alternate Function mapping */ + +/** + * @brief AF 3 selection + */ +#define GPIO_AF3_TMR8 ((uint8_t)0x03) /* TIM8 Alternate Function mapping */ +#define GPIO_AF3_TMR9 ((uint8_t)0x03) /* TIM9 Alternate Function mapping */ +#define GPIO_AF3_TMR10 ((uint8_t)0x03) /* TIM10 Alternate Function mapping */ +#define GPIO_AF3_TMR11 ((uint8_t)0x03) /* TIM11 Alternate Function mapping */ + +/** + * @brief AF 4 selection + */ +#define GPIO_AF4_I2C1 ((uint8_t)0x04) /* I2C1 Alternate Function mapping */ +#define GPIO_AF4_I2C2 ((uint8_t)0x04) /* I2C2 Alternate Function mapping */ +#define GPIO_AF4_I2C3 ((uint8_t)0x04) /* I2C3 Alternate Function mapping */ + +/** + * @brief AF 5 selection + */ +#define GPIO_AF5_SPI1 ((uint8_t)0x05) /* SPI1 Alternate Function mapping */ +#define GPIO_AF5_SPI2 ((uint8_t)0x05) /* SPI2/I2S2 Alternate Function mapping */ +#define GPIO_AF5_I2S3ext ((uint8_t)0x05) /* I2S3ext_SD Alternate Function mapping */ + +/** + * @brief AF 6 selection + */ +#define GPIO_AF6_SPI3 ((uint8_t)0x06) /* SPI3/I2S3 Alternate Function mapping */ +#define GPIO_AF6_I2S2ext ((uint8_t)0x06) /* I2S2ext_SD Alternate Function mapping */ + +/** + * @brief AF 7 selection + */ +#define GPIO_AF7_USART1 ((uint8_t)0x07) /* USART1 Alternate Function mapping */ +#define GPIO_AF7_USART2 ((uint8_t)0x07) /* USART2 Alternate Function mapping */ +#define GPIO_AF7_USART3 ((uint8_t)0x07) /* USART3 Alternate Function mapping */ +#define GPIO_AF7_I2S3ext ((uint8_t)0x07) /* I2S3ext_SD Alternate Function mapping */ + +/** + * @brief AF 8 selection + */ +#define GPIO_AF8_UART4 ((uint8_t)0x08) /* UART4 Alternate Function mapping */ +#define GPIO_AF8_UART5 ((uint8_t)0x08) /* UART5 Alternate Function mapping */ +#define GPIO_AF8_USART6 ((uint8_t)0x08) /* USART6 Alternate Function mapping */ + +/** + * @brief AF 9 selection + */ +#define GPIO_AF9_CAN1 ((uint8_t)0x09) /* CAN1 Alternate Function mapping */ +#define GPIO_AF9_CAN2 ((uint8_t)0x09) /* CAN2 Alternate Function mapping */ +#define GPIO_AF9_TMR12 ((uint8_t)0x09) /* TIM12 Alternate Function mapping */ +#define GPIO_AF9_TMR13 ((uint8_t)0x09) /* TIM13 Alternate Function mapping */ +#define GPIO_AF9_TMR14 ((uint8_t)0x09) /* TIM14 Alternate Function mapping */ + +/** + * @brief AF 10 selection + */ +#define GPIO_AF10_OTG_FS ((uint8_t)0x0A) /* OTG_FS Alternate Function mapping */ +#define GPIO_AF10_OTG_HS ((uint8_t)0x0A) /* OTG_HS Alternate Function mapping */ + +/** + * @brief AF 11 selection + */ +#define GPIO_AF11_ETH ((uint8_t)0x0B) /* ETHERNET Alternate Function mapping */ + +/** + * @brief AF 12 selection + */ +#define GPIO_AF12_SMC ((uint8_t)0x0C) /* SMC Alternate Function mapping */ +#define GPIO_AF12_DMC ((uint8_t)0x0C) /* DMC Alternate Function mapping */ +#define GPIO_AF12_OTG_HS_FS ((uint8_t)0x0C) /* OTG HS configured in FS, Alternate Function mapping */ +#define GPIO_AF12_SDIO ((uint8_t)0x0C) /* SDIO Alternate Function mapping */ + +/** + * @brief AF 13 selection + */ +#define GPIO_AF13_DCI ((uint8_t)0x0D) /* DCI Alternate Function mapping */ + +/** + * @brief AF 15 selection + */ +#define GPIO_AF15_EVENTOUT ((uint8_t)0x0F) /* EVENTOUT Alternate Function mapping */ +#endif /* APM32F407xx || APM32F417xx */ +/*----------------------------------------------------------------------------*/ + +/*---------------------------------- APM32F405xx------------------*/ +#if defined(APM32F405xx) +/** + * @brief AF 0 selection + */ +#define GPIO_AF0_RTC_50Hz ((uint8_t)0x00) /* RTC_50Hz Alternate Function mapping */ +#define GPIO_AF0_MCO ((uint8_t)0x00) /* MCO (MCO1 and MCO2) Alternate Function mapping */ +#define GPIO_AF0_TAMPER ((uint8_t)0x00) /* TAMPER (TAMPER_1 and TAMPER_2) Alternate Function mapping */ +#define GPIO_AF0_SWJ ((uint8_t)0x00) /* SWJ (SWD and JTAG) Alternate Function mapping */ +#define GPIO_AF0_TRACE ((uint8_t)0x00) /* TRACE Alternate Function mapping */ + +/** + * @brief AF 1 selection + */ +#define GPIO_AF1_TMR1 ((uint8_t)0x01) /* TIM1 Alternate Function mapping */ +#define GPIO_AF1_TMR2 ((uint8_t)0x01) /* TIM2 Alternate Function mapping */ + +/** + * @brief AF 2 selection + */ +#define GPIO_AF2_TMR3 ((uint8_t)0x02) /* TIM3 Alternate Function mapping */ +#define GPIO_AF2_TMR4 ((uint8_t)0x02) /* TIM4 Alternate Function mapping */ +#define GPIO_AF2_TMR5 ((uint8_t)0x02) /* TIM5 Alternate Function mapping */ + +/** + * @brief AF 3 selection + */ +#define GPIO_AF3_TMR8 ((uint8_t)0x03) /* TIM8 Alternate Function mapping */ +#define GPIO_AF3_TMR9 ((uint8_t)0x03) /* TIM9 Alternate Function mapping */ +#define GPIO_AF3_TMR10 ((uint8_t)0x03) /* TIM10 Alternate Function mapping */ +#define GPIO_AF3_TMR11 ((uint8_t)0x03) /* TIM11 Alternate Function mapping */ + +/** + * @brief AF 4 selection + */ +#define GPIO_AF4_I2C1 ((uint8_t)0x04) /* I2C1 Alternate Function mapping */ +#define GPIO_AF4_I2C2 ((uint8_t)0x04) /* I2C2 Alternate Function mapping */ +#define GPIO_AF4_I2C3 ((uint8_t)0x04) /* I2C3 Alternate Function mapping */ + +/** + * @brief AF 5 selection + */ +#define GPIO_AF5_SPI1 ((uint8_t)0x05) /* SPI1 Alternate Function mapping */ +#define GPIO_AF5_SPI2 ((uint8_t)0x05) /* SPI2/I2S2 Alternate Function mapping */ +#define GPIO_AF5_I2S3ext ((uint8_t)0x05) /* I2S3ext_SD Alternate Function mapping */ + +/** + * @brief AF 6 selection + */ +#define GPIO_AF6_SPI3 ((uint8_t)0x06) /* SPI3/I2S3 Alternate Function mapping */ +#define GPIO_AF6_I2S2ext ((uint8_t)0x06) /* I2S2ext_SD Alternate Function mapping */ + +/** + * @brief AF 7 selection + */ +#define GPIO_AF7_USART1 ((uint8_t)0x07) /* USART1 Alternate Function mapping */ +#define GPIO_AF7_USART2 ((uint8_t)0x07) /* USART2 Alternate Function mapping */ +#define GPIO_AF7_USART3 ((uint8_t)0x07) /* USART3 Alternate Function mapping */ +#define GPIO_AF7_I2S3ext ((uint8_t)0x07) /* I2S3ext_SD Alternate Function mapping */ + +/** + * @brief AF 8 selection + */ +#define GPIO_AF8_UART4 ((uint8_t)0x08) /* UART4 Alternate Function mapping */ +#define GPIO_AF8_UART5 ((uint8_t)0x08) /* UART5 Alternate Function mapping */ +#define GPIO_AF8_USART6 ((uint8_t)0x08) /* USART6 Alternate Function mapping */ + +/** + * @brief AF 9 selection + */ +#define GPIO_AF9_CAN1 ((uint8_t)0x09) /* CAN1 Alternate Function mapping */ +#define GPIO_AF9_CAN2 ((uint8_t)0x09) /* CAN2 Alternate Function mapping */ +#define GPIO_AF9_TMR12 ((uint8_t)0x09) /* TIM12 Alternate Function mapping */ +#define GPIO_AF9_TMR13 ((uint8_t)0x09) /* TIM13 Alternate Function mapping */ +#define GPIO_AF9_TMR14 ((uint8_t)0x09) /* TIM14 Alternate Function mapping */ + +/** + * @brief AF 10 selection + */ +#define GPIO_AF10_OTG_FS ((uint8_t)0x0A) /* OTG_FS Alternate Function mapping */ +#define GPIO_AF10_OTG_HS ((uint8_t)0x0A) /* OTG_HS Alternate Function mapping */ + +/** + * @brief AF 12 selection + */ +#define GPIO_AF12_SMC ((uint8_t)0x0C) /* EMMC Alternate Function mapping */ +#define GPIO_AF12_OTG_HS_FS ((uint8_t)0x0C) /* OTG HS configured in FS, Alternate Function mapping */ +#define GPIO_AF12_SDIO ((uint8_t)0x0C) /* SDIO Alternate Function mapping */ + +/** + * @brief AF 15 selection + */ +#define GPIO_AF15_EVENTOUT ((uint8_t)0x0F) /* EVENTOUT Alternate Function mapping */ +#endif /* APM32F405xx */ + +/*----------------------------------------------------------------------------*/ + +/*---------------------------------- APM32F465xx------------------*/ +#if defined(APM32F465xx) +/** + * @brief AF 0 selection + */ +#define GPIO_AF0_RTC_50Hz ((uint8_t)0x00) /* RTC_50Hz Alternate Function mapping */ +#define GPIO_AF0_MCO ((uint8_t)0x00) /* MCO (MCO1 and MCO2) Alternate Function mapping */ +#define GPIO_AF0_TAMPER ((uint8_t)0x00) /* TAMPER (TAMPER_1 and TAMPER_2) Alternate Function mapping */ +#define GPIO_AF0_SWJ ((uint8_t)0x00) /* SWJ (SWD and JTAG) Alternate Function mapping */ +#define GPIO_AF0_TRACE ((uint8_t)0x00) /* TRACE Alternate Function mapping */ + +/** + * @brief AF 1 selection + */ +#define GPIO_AF1_TMR1 ((uint8_t)0x01) /* TIM1 Alternate Function mapping */ +#define GPIO_AF1_TMR2 ((uint8_t)0x01) /* TIM2 Alternate Function mapping */ + +/** + * @brief AF 2 selection + */ +#define GPIO_AF2_TMR3 ((uint8_t)0x02) /* TIM3 Alternate Function mapping */ +#define GPIO_AF2_TMR4 ((uint8_t)0x02) /* TIM4 Alternate Function mapping */ +#define GPIO_AF2_TMR5 ((uint8_t)0x02) /* TIM5 Alternate Function mapping */ + +/** + * @brief AF 3 selection + */ +#define GPIO_AF3_TMR8 ((uint8_t)0x03) /* TIM8 Alternate Function mapping */ +#define GPIO_AF3_TMR9 ((uint8_t)0x03) /* TIM9 Alternate Function mapping */ +#define GPIO_AF3_TMR10 ((uint8_t)0x03) /* TIM10 Alternate Function mapping */ +#define GPIO_AF3_TMR11 ((uint8_t)0x03) /* TIM11 Alternate Function mapping */ + +/** + * @brief AF 4 selection + */ +#define GPIO_AF4_I2C1 ((uint8_t)0x04) /* I2C1 Alternate Function mapping */ +#define GPIO_AF4_I2C2 ((uint8_t)0x04) /* I2C2 Alternate Function mapping */ +#define GPIO_AF4_I2C3 ((uint8_t)0x04) /* I2C3 Alternate Function mapping */ + +/** + * @brief AF 5 selection + */ +#define GPIO_AF5_SPI1 ((uint8_t)0x05) /* SPI1 Alternate Function mapping */ +#define GPIO_AF5_SPI2 ((uint8_t)0x05) /* SPI2/I2S2 Alternate Function mapping */ +#define GPIO_AF5_I2S3ext ((uint8_t)0x05) /* I2S3ext_SD Alternate Function mapping */ + +/** + * @brief AF 6 selection + */ +#define GPIO_AF6_SPI3 ((uint8_t)0x06) /* SPI3/I2S3 Alternate Function mapping */ +#define GPIO_AF6_I2S2ext ((uint8_t)0x06) /* I2S2ext_SD Alternate Function mapping */ + +/** + * @brief AF 7 selection + */ +#define GPIO_AF7_USART1 ((uint8_t)0x07) /* USART1 Alternate Function mapping */ +#define GPIO_AF7_USART2 ((uint8_t)0x07) /* USART2 Alternate Function mapping */ +#define GPIO_AF7_USART3 ((uint8_t)0x07) /* USART3 Alternate Function mapping */ +#define GPIO_AF7_I2S3ext ((uint8_t)0x07) /* I2S3ext_SD Alternate Function mapping */ + +/** + * @brief AF 8 selection + */ +#define GPIO_AF8_UART4 ((uint8_t)0x08) /* UART4 Alternate Function mapping */ +#define GPIO_AF8_UART5 ((uint8_t)0x08) /* UART5 Alternate Function mapping */ +#define GPIO_AF8_USART6 ((uint8_t)0x08) /* USART6 Alternate Function mapping */ + +/** + * @brief AF 9 selection + */ +#define GPIO_AF9_CAN1 ((uint8_t)0x09) /* CAN1 Alternate Function mapping */ +#define GPIO_AF9_CAN2 ((uint8_t)0x09) /* CAN2 Alternate Function mapping */ +#define GPIO_AF9_TMR12 ((uint8_t)0x09) /* TIM12 Alternate Function mapping */ +#define GPIO_AF9_TMR13 ((uint8_t)0x09) /* TIM13 Alternate Function mapping */ +#define GPIO_AF9_TMR14 ((uint8_t)0x09) /* TIM14 Alternate Function mapping */ + +/** + * @brief AF 10 selection + */ +#define GPIO_AF10_OTG_FS ((uint8_t)0x0A) /* OTG_FS Alternate Function mapping */ +#define GPIO_AF10_OTG_HS ((uint8_t)0x0A) /* OTG_HS Alternate Function mapping */ + +/** + * @brief AF 12 selection + */ +#define GPIO_AF12_SMC ((uint8_t)0x0C) /* EMMC Alternate Function mapping */ +#define GPIO_AF12_OTG_HS_FS ((uint8_t)0x0C) /* OTG HS configured in FS, Alternate Function mapping */ +#define GPIO_AF12_SDIO ((uint8_t)0x0C) /* SDIO Alternate Function mapping */ + +/** + * @brief AF 15 selection + */ +#define GPIO_AF15_EVENTOUT ((uint8_t)0x0F) /* EVENTOUT Alternate Function mapping */ +#endif /* APM32F465xx */ + +/*----------------------------------------------------------------------------*/ + +/*---------------------------------------- APM32F411xx------------------------*/ +#if defined(APM32F411xx) +/** + * @brief AF 0 selection + */ +#define GPIO_AF0_RTC_50Hz ((uint8_t)0x00) /* RTC_50Hz Alternate Function mapping */ +#define GPIO_AF0_MCO ((uint8_t)0x00) /* MCO (MCO1 and MCO2) Alternate Function mapping */ +#define GPIO_AF0_TAMPER ((uint8_t)0x00) /* TAMPER (TAMPER_1 and TAMPER_2) Alternate Function mapping */ +#define GPIO_AF0_SWJ ((uint8_t)0x00) /* SWJ (SWD and JTAG) Alternate Function mapping */ +#define GPIO_AF0_TRACE ((uint8_t)0x00) /* TRACE Alternate Function mapping */ + +/** + * @brief AF 1 selection + */ +#define GPIO_AF1_TMR1 ((uint8_t)0x01) /* TIM1 Alternate Function mapping */ +#define GPIO_AF1_TMR2 ((uint8_t)0x01) /* TIM2 Alternate Function mapping */ + +/** + * @brief AF 2 selection + */ +#define GPIO_AF2_TMR3 ((uint8_t)0x02) /* TIM3 Alternate Function mapping */ +#define GPIO_AF2_TMR4 ((uint8_t)0x02) /* TIM4 Alternate Function mapping */ +#define GPIO_AF2_TMR5 ((uint8_t)0x02) /* TIM5 Alternate Function mapping */ + +/** + * @brief AF 3 selection + */ +#define GPIO_AF3_TMR8 ((uint8_t)0x03) /* TIM8 Alternate Function mapping */ +#define GPIO_AF3_TMR9 ((uint8_t)0x03) /* TIM9 Alternate Function mapping */ +#define GPIO_AF3_TMR10 ((uint8_t)0x03) /* TIM10 Alternate Function mapping */ +#define GPIO_AF3_TMR11 ((uint8_t)0x03) /* TIM11 Alternate Function mapping */ + +/** + * @brief AF 4 selection + */ +#define GPIO_AF4_I2C1 ((uint8_t)0x04) /* I2C1 Alternate Function mapping */ +#define GPIO_AF4_I2C2 ((uint8_t)0x04) /* I2C2 Alternate Function mapping */ +#define GPIO_AF4_I2C3 ((uint8_t)0x04) /* I2C3 Alternate Function mapping */ + +/** + * @brief AF 5 selection + */ +#define GPIO_AF5_SPI1 ((uint8_t)0x05) /* SPI1/I2S1 Alternate Function mapping */ +#define GPIO_AF5_SPI2 ((uint8_t)0x05) /* SPI2/I2S2 Alternate Function mapping */ +#define GPIO_AF5_SPI3 ((uint8_t)0x05) /* SPI3/I2S3 Alternate Function mapping */ +#define GPIO_AF5_SPI4 ((uint8_t)0x05) /* SPI4 Alternate Function mapping */ +#define GPIO_AF5_I2S3ext ((uint8_t)0x05) /* I2S3ext_SD Alternate Function mapping */ + +/** + * @brief AF 6 selection + */ +#define GPIO_AF6_SPI2 ((uint8_t)0x06) /* I2S2 Alternate Function mapping */ +#define GPIO_AF6_SPI3 ((uint8_t)0x06) /* SPI3/I2S3 Alternate Function mapping */ +#define GPIO_AF6_SPI4 ((uint8_t)0x06) /* SPI4/I2S4 Alternate Function mapping */ +#define GPIO_AF6_SPI5 ((uint8_t)0x06) /* SPI5/I2S5 Alternate Function mapping */ +#define GPIO_AF6_I2S2ext ((uint8_t)0x06) /* I2S2ext_SD Alternate Function mapping */ + +/** + * @brief AF 7 selection + */ +#define GPIO_AF7_SPI3 ((uint8_t)0x07) /* SPI3/I2S3 Alternate Function mapping */ +#define GPIO_AF7_USART1 ((uint8_t)0x07) /* USART1 Alternate Function mapping */ +#define GPIO_AF7_USART2 ((uint8_t)0x07) /* USART2 Alternate Function mapping */ +#define GPIO_AF7_USART3 ((uint8_t)0x07) /* USART3 Alternate Function mapping */ +#define GPIO_AF7_I2S3ext ((uint8_t)0x07) /* I2S3ext_SD Alternate Function mapping */ + +/** + * @brief AF 8 selection + */ +#define GPIO_AF8_USART3 ((uint8_t)0x08) /* USART3 Alternate Function mapping */ +#define GPIO_AF8_UART4 ((uint8_t)0x08) /* UART4 Alternate Function mapping */ +#define GPIO_AF8_UART5 ((uint8_t)0x08) /* UART5 Alternate Function mapping */ +#define GPIO_AF8_USART6 ((uint8_t)0x08) /* USART6 Alternate Function mapping */ +#define GPIO_AF8_CAN1 ((uint8_t)0x08) /* CAN1 Alternate Function mapping */ + +/** + * @brief AF 9 selection + */ +#define GPIO_AF9_CAN1 ((uint8_t)0x09) /* CAN1 Alternate Function mapping */ +#define GPIO_AF9_CAN2 ((uint8_t)0x09) /* CAN2 Alternate Function mapping */ +#define GPIO_AF9_TMR12 ((uint8_t)0x09) /* TIM12 Alternate Function mapping */ +#define GPIO_AF9_TMR13 ((uint8_t)0x09) /* TIM13 Alternate Function mapping */ +#define GPIO_AF9_TMR14 ((uint8_t)0x09) /* TIM14 Alternate Function mapping */ +#define GPIO_AF9_I2C2 ((uint8_t)0x09) /* I2C2 Alternate Function mapping */ +#define GPIO_AF9_I2C3 ((uint8_t)0x09) /* I2C3 Alternate Function mapping */ +#define GPIO_AF9_QSPI ((uint8_t)0x09) /* QSPI Alternate Function mapping */ + +/** + * @brief AF 10 selection + */ +#define GPIO_AF10_OTG_FS ((uint8_t)0x0A) /* OTG_FS Alternate Function mapping */ +#define GPIO_AF10_QSPI ((uint8_t)0x0A) /* QSPI Alternate Function mapping */ +#define GPIO_AF10_SMC ((uint8_t)0x0A) /* SMC Alternate Function mapping */ + +/** + * @brief AF 11 selection + */ +#define GPIO_AF11_SDIO ((uint8_t)0x0B) /* SDIO Alternate Function mapping */ +#define GPIO_AF11_SMC ((uint8_t)0x0B) /* SMC Alternate Function mapping */ + +/** + * @brief AF 15 selection + */ +#define GPIO_AF15_EVENTOUT ((uint8_t)0x0F) /* EVENTOUT Alternate Function mapping */ +#endif /* APM32F411xx */ + +/** + * @} + */ + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ +/** @defgroup GPIOEx_Exported_Macros GPIO Exported Macros + * @{ + */ +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +/** @defgroup GPIOEx_Exported_Functions GPIO Exported Functions + * @{ + */ +/** + * @} + */ + +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/** @defgroup GPIOEx_Private_Constants GPIO Private Constants + * @{ + */ +/** + * @} + */ + +/* Private macros ------------------------------------------------------------*/ +/** @defgroup GPIOEx_Private_Macros GPIO Private Macros + * @{ + */ +/** @defgroup GPIOEx_Get_Port_Index GPIO Get Port Index + * @{ + */ +#if defined(APM32F405xx) || defined(APM32F407xx) || defined(APM32F417xx) || defined(APM32F465xx) +#define GPIO_GET_INDEX(__GPIOx__) (uint8_t)(((__GPIOx__) == (GPIOA))? 0U :\ + ((__GPIOx__) == (GPIOB))? 1U :\ + ((__GPIOx__) == (GPIOC))? 2U :\ + ((__GPIOx__) == (GPIOD))? 3U :\ + ((__GPIOx__) == (GPIOE))? 4U :\ + ((__GPIOx__) == (GPIOF))? 5U :\ + ((__GPIOx__) == (GPIOG))? 6U :\ + ((__GPIOx__) == (GPIOH))? 7U : 8U) +#endif /* APM32F405xx || APM32F407xx || APM32F417xx || APM32F465xx */ + +#if defined(APM32F411xx) +#define GPIO_GET_INDEX(__GPIOx__) (uint8_t)(((__GPIOx__) == (GPIOA))? 0U :\ + ((__GPIOx__) == (GPIOB))? 1U :\ + ((__GPIOx__) == (GPIOC))? 2U :\ + ((__GPIOx__) == (GPIOD))? 3U :\ + ((__GPIOx__) == (GPIOE))? 4U : 7U) +#endif /* APM32F411xx */ + +/** + * @} + */ + +/** @defgroup GPIOEx_IS_Alternat_function_selection GPIO Check Alternate Function + * @{ + */ + +/*---------------------------------- APM32F407xx/APM32F417xx------------------*/ +#if defined(APM32F407xx) || defined(APM32F417xx) +#define IS_GPIO_AF(AF) (((AF) == GPIO_AF0_RTC_50Hz) || ((AF) == GPIO_AF9_TMR14) || \ + ((AF) == GPIO_AF0_MCO) || ((AF) == GPIO_AF0_TAMPER) || \ + ((AF) == GPIO_AF0_SWJ) || ((AF) == GPIO_AF0_TRACE) || \ + ((AF) == GPIO_AF1_TMR1) || ((AF) == GPIO_AF1_TMR2) || \ + ((AF) == GPIO_AF2_TMR3) || ((AF) == GPIO_AF2_TMR4) || \ + ((AF) == GPIO_AF2_TMR5) || ((AF) == GPIO_AF3_TMR8) || \ + ((AF) == GPIO_AF4_I2C1) || ((AF) == GPIO_AF4_I2C2) || \ + ((AF) == GPIO_AF4_I2C3) || ((AF) == GPIO_AF5_SPI1) || \ + ((AF) == GPIO_AF5_SPI2) || ((AF) == GPIO_AF9_TMR13) || \ + ((AF) == GPIO_AF6_SPI3) || ((AF) == GPIO_AF9_TMR12) || \ + ((AF) == GPIO_AF7_USART1) || ((AF) == GPIO_AF7_USART2) || \ + ((AF) == GPIO_AF7_USART3) || ((AF) == GPIO_AF8_UART4) || \ + ((AF) == GPIO_AF8_UART5) || ((AF) == GPIO_AF8_USART6) || \ + ((AF) == GPIO_AF9_CAN1) || ((AF) == GPIO_AF9_CAN2) || \ + ((AF) == GPIO_AF10_OTG_FS) || ((AF) == GPIO_AF10_OTG_HS) || \ + ((AF) == GPIO_AF11_ETH) || ((AF) == GPIO_AF12_OTG_HS_FS) || \ + ((AF) == GPIO_AF12_SDIO) || ((AF) == GPIO_AF13_DCI) || \ + ((AF) == GPIO_AF12_SMC) || ((AF) == GPIO_AF12_DMC) || \ + ((AF) == GPIO_AF15_EVENTOUT)) + +#endif /* APM32F407xx || APM32F417xx */ +/*----------------------------------------------------------------------------*/ + +/*---------------------------------- APM32F405xx------------------*/ +#if defined(APM32F405xx) +#define IS_GPIO_AF(AF) (((AF) == GPIO_AF0_RTC_50Hz) || ((AF) == GPIO_AF9_TMR14) || \ + ((AF) == GPIO_AF0_MCO) || ((AF) == GPIO_AF0_TAMPER) || \ + ((AF) == GPIO_AF0_SWJ) || ((AF) == GPIO_AF0_TRACE) || \ + ((AF) == GPIO_AF1_TMR1) || ((AF) == GPIO_AF1_TMR2) || \ + ((AF) == GPIO_AF2_TMR3) || ((AF) == GPIO_AF2_TMR4) || \ + ((AF) == GPIO_AF2_TMR5) || ((AF) == GPIO_AF3_TMR8) || \ + ((AF) == GPIO_AF4_I2C1) || ((AF) == GPIO_AF4_I2C2) || \ + ((AF) == GPIO_AF4_I2C3) || ((AF) == GPIO_AF5_SPI1) || \ + ((AF) == GPIO_AF5_SPI2) || ((AF) == GPIO_AF9_TMR13) || \ + ((AF) == GPIO_AF6_SPI3) || ((AF) == GPIO_AF9_TMR12) || \ + ((AF) == GPIO_AF7_USART1) || ((AF) == GPIO_AF7_USART2) || \ + ((AF) == GPIO_AF7_USART3) || ((AF) == GPIO_AF8_UART4) || \ + ((AF) == GPIO_AF8_UART5) || ((AF) == GPIO_AF8_USART6) || \ + ((AF) == GPIO_AF9_CAN1) || ((AF) == GPIO_AF9_CAN2) || \ + ((AF) == GPIO_AF10_OTG_FS) || ((AF) == GPIO_AF10_OTG_HS) || \ + ((AF) == GPIO_AF12_OTG_HS_FS) || ((AF) == GPIO_AF12_SDIO) || \ + ((AF) == GPIO_AF12_SMC) || ((AF) == GPIO_AF15_EVENTOUT)) + +#endif /* APM32F405xx */ + +/*----------------------------------------------------------------------------*/ + +/*---------------------------------- APM32F465xx------------------*/ +#if defined(APM32F465xx) +#define IS_GPIO_AF(AF) (((AF) == GPIO_AF0_RTC_50Hz) || ((AF) == GPIO_AF9_TMR14) || \ + ((AF) == GPIO_AF0_MCO) || ((AF) == GPIO_AF0_TAMPER) || \ + ((AF) == GPIO_AF0_SWJ) || ((AF) == GPIO_AF0_TRACE) || \ + ((AF) == GPIO_AF1_TMR1) || ((AF) == GPIO_AF1_TMR2) || \ + ((AF) == GPIO_AF2_TMR3) || ((AF) == GPIO_AF2_TMR4) || \ + ((AF) == GPIO_AF2_TMR5) || ((AF) == GPIO_AF3_TMR8) || \ + ((AF) == GPIO_AF4_I2C1) || ((AF) == GPIO_AF4_I2C2) || \ + ((AF) == GPIO_AF4_I2C3) || ((AF) == GPIO_AF5_SPI1) || \ + ((AF) == GPIO_AF5_SPI2) || ((AF) == GPIO_AF9_TMR13) || \ + ((AF) == GPIO_AF6_SPI3) || ((AF) == GPIO_AF9_TMR12) || \ + ((AF) == GPIO_AF7_USART1) || ((AF) == GPIO_AF7_USART2) || \ + ((AF) == GPIO_AF7_USART3) || ((AF) == GPIO_AF8_UART4) || \ + ((AF) == GPIO_AF8_UART5) || ((AF) == GPIO_AF8_USART6) || \ + ((AF) == GPIO_AF9_CAN1) || ((AF) == GPIO_AF9_CAN2) || \ + ((AF) == GPIO_AF10_OTG_FS) || ((AF) == GPIO_AF10_OTG_HS) || \ + ((AF) == GPIO_AF12_OTG_HS_FS) || ((AF) == GPIO_AF12_SDIO) || \ + ((AF) == GPIO_AF12_SMC) || ((AF) == GPIO_AF15_EVENTOUT)) + +#endif /* APM32F465xx */ + +/*----------------------------------------------------------------------------*/ + +/*---------------------------------------- APM32F411xx------------------------*/ +#if defined(APM32F411xx) +#define IS_GPIO_AF(AF) (((AF) == GPIO_AF0_RTC_50Hz) || ((AF) == GPIO_AF11_SMC) || \ + ((AF) == GPIO_AF0_MCO) || ((AF) == GPIO_AF0_TAMPER) || \ + ((AF) == GPIO_AF0_SWJ) || ((AF) == GPIO_AF0_TRACE) || \ + ((AF) == GPIO_AF1_TMR1) || ((AF) == GPIO_AF1_TMR2) || \ + ((AF) == GPIO_AF2_TMR3) || ((AF) == GPIO_AF2_TMR4) || \ + ((AF) == GPIO_AF2_TMR5) || ((AF) == GPIO_AF3_TMR8) || \ + ((AF) == GPIO_AF3_TMR9) || ((AF) == GPIO_AF3_TMR10) || \ + ((AF) == GPIO_AF3_TMR11) || ((AF) == GPIO_AF4_I2C1) || \ + ((AF) == GPIO_AF4_I2C2) || ((AF) == GPIO_AF4_I2C3) || \ + ((AF) == GPIO_AF5_SPI1) || ((AF) == GPIO_AF5_SPI2) || \ + ((AF) == GPIO_AF5_SPI3) || ((AF) == GPIO_AF5_SPI4) || \ + ((AF) == GPIO_AF5_I2S3ext) || ((AF) == GPIO_AF6_SPI2) || \ + ((AF) == GPIO_AF6_SPI3) || ((AF) == GPIO_AF6_SPI4) || \ + ((AF) == GPIO_AF6_SPI5) || ((AF) == GPIO_AF6_I2S2ext) || \ + ((AF) == GPIO_AF7_SPI3) || ((AF) == GPIO_AF7_USART1) || \ + ((AF) == GPIO_AF7_USART2) || ((AF) == GPIO_AF7_USART3) || \ + ((AF) == GPIO_AF7_I2S3ext) || ((AF) == GPIO_AF8_USART3) || \ + ((AF) == GPIO_AF8_UART4) || ((AF) == GPIO_AF8_UART5) || \ + ((AF) == GPIO_AF8_USART6) || ((AF) == GPIO_AF8_CAN1) || \ + ((AF) == GPIO_AF9_CAN2) || ((AF) == GPIO_AF9_TMR12) || \ + ((AF) == GPIO_AF9_TMR13) || ((AF) == GPIO_AF9_TMR14) || \ + ((AF) == GPIO_AF9_I2C2) || ((AF) == GPIO_AF9_I2C3) || \ + ((AF) == GPIO_AF9_QSPI) || ((AF) == GPIO_AF10_OTG_FS) || \ + ((AF) == GPIO_AF10_QSPI) || ((AF) == GPIO_AF10_SMC) || \ + ((AF) == GPIO_AF11_SDIO) || ((AF) == GPIO_AF15_EVENTOUT)) + +#endif /* APM32F411xx */ +/*----------------------------------------------------------------------------*/ + +/** + * @} + */ + +/** + * @} + */ + +/* Private functions ---------------------------------------------------------*/ +/** @defgroup GPIOEx_Private_Functions GPIO Private Functions + * @{ + */ + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* APM32F4xx_DAL_GPIO_EX_H */ + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_hash.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_hash.h new file mode 100644 index 0000000000..919c4bbc0c --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_hash.h @@ -0,0 +1,657 @@ +/** + * + * @file apm32f4xx_dal_hash.h + * @brief Header file of HASH DAL module. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef APM32F4xx_DAL_HASH_H +#define APM32F4xx_DAL_HASH_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal_def.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ +#if defined (HASH) +/** @addtogroup HASH + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ +/** @defgroup HASH_Exported_Types HASH Exported Types + * @{ + */ + +/** + * @brief HASH Configuration Structure definition + */ +typedef struct +{ + uint32_t DataType; /*!< 32-bit data, 16-bit data, 8-bit data or 1-bit data. + This parameter can be a value of @ref HASH_Data_Type. */ + + uint32_t KeySize; /*!< The key size is used only in HMAC operation. */ + + uint8_t *pKey; /*!< The key is used only in HMAC operation. */ + +} HASH_InitTypeDef; + +/** + * @brief DAL State structures definition + */ +typedef enum +{ + DAL_HASH_STATE_RESET = 0x00U, /*!< Peripheral is not initialized */ + DAL_HASH_STATE_READY = 0x01U, /*!< Peripheral Initialized and ready for use */ + DAL_HASH_STATE_BUSY = 0x02U, /*!< Processing (hashing) is ongoing */ + DAL_HASH_STATE_TIMEOUT = 0x06U, /*!< Timeout state */ + DAL_HASH_STATE_ERROR = 0x07U, /*!< Error state */ + DAL_HASH_STATE_SUSPENDED = 0x08U /*!< Suspended state */ +} DAL_HASH_StateTypeDef; + +/** + * @brief DAL phase structures definition + */ +typedef enum +{ + DAL_HASH_PHASE_READY = 0x01U, /*!< HASH peripheral is ready to start */ + DAL_HASH_PHASE_PROCESS = 0x02U, /*!< HASH peripheral is in HASH processing phase */ + DAL_HASH_PHASE_HMAC_STEP_1 = 0x03U, /*!< HASH peripheral is in HMAC step 1 processing phase + (step 1 consists in entering the inner hash function key) */ + DAL_HASH_PHASE_HMAC_STEP_2 = 0x04U, /*!< HASH peripheral is in HMAC step 2 processing phase + (step 2 consists in entering the message text) */ + DAL_HASH_PHASE_HMAC_STEP_3 = 0x05U /*!< HASH peripheral is in HMAC step 3 processing phase + (step 3 consists in entering the outer hash function key) */ +} DAL_HASH_PhaseTypeDef; + +/** + * @brief DAL HASH mode suspend definitions + */ +typedef enum +{ + DAL_HASH_SUSPEND_NONE = 0x00U, /*!< HASH peripheral suspension not requested */ + DAL_HASH_SUSPEND = 0x01U /*!< HASH peripheral suspension is requested */ +} DAL_HASH_SuspendTypeDef; + +#if (USE_DAL_HASH_REGISTER_CALLBACKS == 1U) +/** + * @brief DAL HASH common Callback ID enumeration definition + */ +typedef enum +{ + DAL_HASH_MSPINIT_CB_ID = 0x00U, /*!< HASH MspInit callback ID */ + DAL_HASH_MSPDEINIT_CB_ID = 0x01U, /*!< HASH MspDeInit callback ID */ + DAL_HASH_INPUTCPLT_CB_ID = 0x02U, /*!< HASH input completion callback ID */ + DAL_HASH_DGSTCPLT_CB_ID = 0x03U, /*!< HASH digest computation completion callback ID */ + DAL_HASH_ERROR_CB_ID = 0x04U, /*!< HASH error callback ID */ +} DAL_HASH_CallbackIDTypeDef; +#endif /* USE_DAL_HASH_REGISTER_CALLBACKS */ + + +/** + * @brief HASH Handle Structure definition + */ +#if (USE_DAL_HASH_REGISTER_CALLBACKS == 1) +typedef struct __HASH_HandleTypeDef +#else +typedef struct +#endif /* (USE_DAL_HASH_REGISTER_CALLBACKS) */ +{ + HASH_InitTypeDef Init; /*!< HASH required parameters */ + + uint8_t *pHashInBuffPtr; /*!< Pointer to input buffer */ + + uint8_t *pHashOutBuffPtr; /*!< Pointer to output buffer (digest) */ + + uint8_t *pHashKeyBuffPtr; /*!< Pointer to key buffer (HMAC only) */ + + uint8_t *pHashMsgBuffPtr; /*!< Pointer to message buffer (HMAC only) */ + + uint32_t HashBuffSize; /*!< Size of buffer to be processed */ + + __IO uint32_t HashInCount; /*!< Counter of inputted data */ + + __IO uint32_t HashITCounter; /*!< Counter of issued interrupts */ + + __IO uint32_t HashKeyCount; /*!< Counter for Key inputted data (HMAC only) */ + + DAL_StatusTypeDef Status; /*!< HASH peripheral status */ + + DAL_HASH_PhaseTypeDef Phase; /*!< HASH peripheral phase */ + + DMA_HandleTypeDef *hdmain; /*!< HASH In DMA Handle parameters */ + + DAL_LockTypeDef Lock; /*!< Locking object */ + + __IO DAL_HASH_StateTypeDef State; /*!< HASH peripheral state */ + + DAL_HASH_SuspendTypeDef SuspendRequest; /*!< HASH peripheral suspension request flag */ + + FlagStatus DigestCalculationDisable; /*!< Digest calculation phase skip (MDMAT bit control) for multi-buffers DMA-based HMAC computation */ + + __IO uint32_t NbWordsAlreadyPushed; /*!< Numbers of words already pushed in FIFO before inputting new block */ + + __IO uint32_t ErrorCode; /*!< HASH Error code */ + + __IO uint32_t Accumulation; /*!< HASH multi buffers accumulation flag */ + +#if (USE_DAL_HASH_REGISTER_CALLBACKS == 1) + void (* InCpltCallback)(struct __HASH_HandleTypeDef *hhash); /*!< HASH input completion callback */ + + void (* DgstCpltCallback)(struct __HASH_HandleTypeDef *hhash); /*!< HASH digest computation completion callback */ + + void (* ErrorCallback)(struct __HASH_HandleTypeDef *hhash); /*!< HASH error callback */ + + void (* MspInitCallback)(struct __HASH_HandleTypeDef *hhash); /*!< HASH Msp Init callback */ + + void (* MspDeInitCallback)(struct __HASH_HandleTypeDef *hhash); /*!< HASH Msp DeInit callback */ + +#endif /* (USE_DAL_HASH_REGISTER_CALLBACKS) */ +} HASH_HandleTypeDef; + +#if (USE_DAL_HASH_REGISTER_CALLBACKS == 1U) +/** + * @brief DAL HASH Callback pointer definition + */ +typedef void (*pHASH_CallbackTypeDef)(HASH_HandleTypeDef *hhash); /*!< pointer to a HASH common callback functions */ +#endif /* USE_DAL_HASH_REGISTER_CALLBACKS */ + +/** + * @} + */ + +/* Exported constants --------------------------------------------------------*/ + +/** @defgroup HASH_Exported_Constants HASH Exported Constants + * @{ + */ + +/** @defgroup HASH_Algo_Selection HASH algorithm selection + * @{ + */ +#define HASH_ALGOSELECTION_SHA1 0x00000000U /*!< HASH function is SHA1 */ +#define HASH_ALGOSELECTION_MD5 HASH_CTRL_ALGSEL_0 /*!< HASH function is MD5 */ + +/** + * @} + */ + +/** @defgroup HASH_Algorithm_Mode HASH algorithm mode + * @{ + */ +#define HASH_ALGOMODE_HASH 0x00000000U /*!< Algorithm is HASH */ +#define HASH_ALGOMODE_HMAC HASH_CTRL_MODESEL /*!< Algorithm is HMAC */ +/** + * @} + */ + +/** @defgroup HASH_Data_Type HASH input data type + * @{ + */ +#define HASH_DATATYPE_32B 0x00000000U /*!< 32-bit data. No swapping */ +#define HASH_DATATYPE_16B HASH_CTRL_DTYPE_0 /*!< 16-bit data. Each half word is swapped */ +#define HASH_DATATYPE_8B HASH_CTRL_DTYPE_1 /*!< 8-bit data. All bytes are swapped */ +#define HASH_DATATYPE_1B HASH_CTRL_DTYPE /*!< 1-bit data. In the word all bits are swapped */ +/** + * @} + */ + +/** @defgroup HASH_HMAC_Long_key_only_for_HMAC_mode HMAC key length type + * @{ + */ +#define HASH_HMAC_KEYTYPE_SHORTKEY 0x00000000U /*!< HMAC Key size is <= 64 bytes */ +#define HASH_HMAC_KEYTYPE_LONGKEY HASH_CTRL_LKEYSEL /*!< HMAC Key size is > 64 bytes */ +/** + * @} + */ + +/** @defgroup HASH_flags_definition HASH flags definitions + * @{ + */ +#define HASH_FLAG_DINIS HASH_STS_INDATAINT /*!< 16 locations are free in the DIN : a new block can be entered in the Peripheral */ +#define HASH_FLAG_DCIS HASH_STS_DCALCINT /*!< Digest calculation complete */ +#define HASH_FLAG_DMAS HASH_STS_DMA /*!< DMA interface is enabled (DMAE=1) or a transfer is ongoing */ +#define HASH_FLAG_BUSY HASH_STS_BUSY /*!< The hash core is Busy, processing a block of data */ +#define HASH_FLAG_DINNE HASH_CTRL_DINNEMPT /*!< DIN not empty : the input buffer contains at least one word of data */ + +/** + * @} + */ + +/** @defgroup HASH_interrupts_definition HASH interrupts definitions + * @{ + */ +#define HASH_IT_DINI HASH_INT_INDATA /*!< A new block can be entered into the input buffer (DIN) */ +#define HASH_IT_DCI HASH_INT_DCALC /*!< Digest calculation complete */ + +/** + * @} + */ + +/** @defgroup HASH_Error_Definition HASH Error Definition + * @{ + */ +#define DAL_HASH_ERROR_NONE 0x00000000U /*!< No error */ +#define DAL_HASH_ERROR_IT 0x00000001U /*!< IT-based process error */ +#define DAL_HASH_ERROR_DMA 0x00000002U /*!< DMA-based process error */ +#if (USE_DAL_HASH_REGISTER_CALLBACKS == 1U) +#define DAL_HASH_ERROR_INVALID_CALLBACK 0x00000004U /*!< Invalid Callback error */ +#endif /* USE_DAL_HASH_REGISTER_CALLBACKS */ +/** + * @} + */ + +/** + * @} + */ + +/* Exported macros -----------------------------------------------------------*/ +/** @defgroup HASH_Exported_Macros HASH Exported Macros + * @{ + */ + +/** @brief Check whether or not the specified HASH flag is set. + * @param __FLAG__ specifies the flag to check. + * This parameter can be one of the following values: + * @arg @ref HASH_FLAG_DINIS A new block can be entered into the input buffer. + * @arg @ref HASH_FLAG_DCIS Digest calculation complete. + * @arg @ref HASH_FLAG_DMAS DMA interface is enabled (DMAE=1) or a transfer is ongoing. + * @arg @ref HASH_FLAG_BUSY The hash core is Busy : processing a block of data. + * @arg @ref HASH_FLAG_DINNE DIN not empty : the input buffer contains at least one word of data. + * @retval The new state of __FLAG__ (TRUE or FALSE). + */ +#define __DAL_HASH_GET_FLAG(__FLAG__) (((__FLAG__) > 8U) ? \ + ((HASH->CTRL & (__FLAG__)) == (__FLAG__)) :\ + ((HASH->STS & (__FLAG__)) == (__FLAG__)) ) + + +/** @brief Clear the specified HASH flag. + * @param __FLAG__ specifies the flag to clear. + * This parameter can be one of the following values: + * @arg @ref HASH_FLAG_DINIS A new block can be entered into the input buffer. + * @arg @ref HASH_FLAG_DCIS Digest calculation complete + * @retval None + */ +#define __DAL_HASH_CLEAR_FLAG(__FLAG__) CLEAR_BIT(HASH->STS, (__FLAG__)) + + +/** @brief Enable the specified HASH interrupt. + * @param __INTERRUPT__ specifies the HASH interrupt source to enable. + * This parameter can be one of the following values: + * @arg @ref HASH_IT_DINI A new block can be entered into the input buffer (DIN) + * @arg @ref HASH_IT_DCI Digest calculation complete + * @retval None + */ +#define __DAL_HASH_ENABLE_IT(__INTERRUPT__) SET_BIT(HASH->INT, (__INTERRUPT__)) + +/** @brief Disable the specified HASH interrupt. + * @param __INTERRUPT__ specifies the HASH interrupt source to disable. + * This parameter can be one of the following values: + * @arg @ref HASH_IT_DINI A new block can be entered into the input buffer (DIN) + * @arg @ref HASH_IT_DCI Digest calculation complete + * @retval None + */ +#define __DAL_HASH_DISABLE_IT(__INTERRUPT__) CLEAR_BIT(HASH->INT, (__INTERRUPT__)) + +/** @brief Reset HASH handle state. + * @param __HANDLE__ HASH handle. + * @retval None + */ + +#if (USE_DAL_HASH_REGISTER_CALLBACKS == 1) +#define __DAL_HASH_RESET_HANDLE_STATE(__HANDLE__) do{\ + (__HANDLE__)->State = DAL_HASH_STATE_RESET;\ + (__HANDLE__)->MspInitCallback = NULL; \ + (__HANDLE__)->MspDeInitCallback = NULL; \ + }while(0) +#else +#define __DAL_HASH_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = DAL_HASH_STATE_RESET) +#endif /* USE_DAL_HASH_REGISTER_CALLBACKS */ + + +/** @brief Reset HASH handle status. + * @param __HANDLE__ HASH handle. + * @retval None + */ +#define __DAL_HASH_RESET_HANDLE_STATUS(__HANDLE__) ((__HANDLE__)->Status = DAL_OK) + +/** + * @brief Enable the multi-buffer DMA transfer mode. + * @note This bit is set when hashing large files when multiple DMA transfers are needed. + * @retval None + */ +#define __DAL_HASH_SET_MDMAT() SET_BIT(HASH->CTRL, HASH_CTRL_MDMAT) + +/** + * @brief Disable the multi-buffer DMA transfer mode. + * @retval None + */ +#define __DAL_HASH_RESET_MDMAT() CLEAR_BIT(HASH->CTRL, HASH_CTRL_MDMAT) + + +/** + * @brief Start the digest computation. + * @retval None + */ +#define __DAL_HASH_START_DIGEST() SET_BIT(HASH->START, HASH_START_DIGCAL) + +/** + * @brief Set the number of valid bits in the last word written in data register DIN. + * @param __SIZE__ size in bytes of last data written in Data register. + * @retval None + */ +#define __DAL_HASH_SET_NBVALIDBITS(__SIZE__) MODIFY_REG(HASH->START, HASH_START_LWNUM, 8U * ((__SIZE__) % 4U)) + +/** + * @brief Reset the HASH core. + * @retval None + */ +#define __DAL_HASH_INIT() SET_BIT(HASH->CTRL, HASH_CTRL_INITCAL) + +/** + * @} + */ + + +/* Private macros --------------------------------------------------------*/ +/** @defgroup HASH_Private_Macros HASH Private Macros + * @{ + */ +/** + * @brief Return digest length in bytes. + * @retval Digest length + */ +#if defined(HASH_CTRL_MDMAT) +#define HASH_DIGEST_LENGTH() ((READ_BIT(HASH->CTRL, HASH_CTRL_ALGSEL) == HASH_ALGOSELECTION_SHA1) ? 20U : \ + ((READ_BIT(HASH->CTRL, HASH_CTRL_ALGSEL) == HASH_ALGOSELECTION_SHA224) ? 28U : \ + ((READ_BIT(HASH->CTRL, HASH_CTRL_ALGSEL) == HASH_ALGOSELECTION_SHA256) ? 32U : 16U ) ) ) +#else +#define HASH_DIGEST_LENGTH() ((READ_BIT(HASH->CTRL, HASH_CTRL_ALGSEL) == HASH_ALGOSELECTION_SHA1) ? 20U : 16) +#endif /* HASH_CTRL_MDMAT*/ +/** + * @brief Return number of words already pushed in the FIFO. + * @retval Number of words already pushed in the FIFO + */ +#define HASH_NBW_PUSHED() ((READ_BIT(HASH->CTRL, HASH_CTRL_WNUM)) >> 8U) + +/** + * @brief Ensure that HASH input data type is valid. + * @param __DATATYPE__ HASH input data type. + * @retval SET (__DATATYPE__ is valid) or RESET (__DATATYPE__ is invalid) + */ +#define IS_HASH_DATATYPE(__DATATYPE__) (((__DATATYPE__) == HASH_DATATYPE_32B)|| \ + ((__DATATYPE__) == HASH_DATATYPE_16B)|| \ + ((__DATATYPE__) == HASH_DATATYPE_8B) || \ + ((__DATATYPE__) == HASH_DATATYPE_1B)) + +/** + * @brief Ensure that input data buffer size is valid for multi-buffer HASH + * processing in DMA mode. + * @note This check is valid only for multi-buffer HASH processing in DMA mode. + * @param __SIZE__ input data buffer size. + * @retval SET (__SIZE__ is valid) or RESET (__SIZE__ is invalid) + */ +#define IS_HASH_DMA_MULTIBUFFER_SIZE(__SIZE__) ((READ_BIT(HASH->CTRL, HASH_CTRL_MDMAT) == 0U) || (((__SIZE__) % 4U) == 0U)) + +/** + * @brief Ensure that input data buffer size is valid for multi-buffer HMAC + * processing in DMA mode. + * @note This check is valid only for multi-buffer HMAC processing in DMA mode. + * @param __HANDLE__ HASH handle. + * @param __SIZE__ input data buffer size. + * @retval SET (__SIZE__ is valid) or RESET (__SIZE__ is invalid) + */ +#define IS_HMAC_DMA_MULTIBUFFER_SIZE(__HANDLE__,__SIZE__) ((((__HANDLE__)->DigestCalculationDisable) == RESET)\ + || (((__SIZE__) % 4U) == 0U)) +/** + * @brief Ensure that handle phase is set to HASH processing. + * @param __HANDLE__ HASH handle. + * @retval SET (handle phase is set to HASH processing) or RESET (handle phase is not set to HASH processing) + */ +#define IS_HASH_PROCESSING(__HANDLE__) ((__HANDLE__)->Phase == DAL_HASH_PHASE_PROCESS) + +/** + * @brief Ensure that handle phase is set to HMAC processing. + * @param __HANDLE__ HASH handle. + * @retval SET (handle phase is set to HMAC processing) or RESET (handle phase is not set to HMAC processing) + */ +#define IS_HMAC_PROCESSING(__HANDLE__) (((__HANDLE__)->Phase == DAL_HASH_PHASE_HMAC_STEP_1) || \ + ((__HANDLE__)->Phase == DAL_HASH_PHASE_HMAC_STEP_2) || \ + ((__HANDLE__)->Phase == DAL_HASH_PHASE_HMAC_STEP_3)) + +/** + * @} + */ + +/* Include HASH DAL Extended module */ +#include "apm32f4xx_dal_hash_ex.h" +/* Exported functions --------------------------------------------------------*/ + +/** @addtogroup HASH_Exported_Functions HASH Exported Functions + * @{ + */ + +/** @addtogroup HASH_Exported_Functions_Group1 Initialization and de-initialization functions + * @{ + */ + +/* Initialization/de-initialization methods **********************************/ +DAL_StatusTypeDef DAL_HASH_Init(HASH_HandleTypeDef *hhash); +DAL_StatusTypeDef DAL_HASH_DeInit(HASH_HandleTypeDef *hhash); +void DAL_HASH_MspInit(HASH_HandleTypeDef *hhash); +void DAL_HASH_MspDeInit(HASH_HandleTypeDef *hhash); +void DAL_HASH_InCpltCallback(HASH_HandleTypeDef *hhash); +void DAL_HASH_DgstCpltCallback(HASH_HandleTypeDef *hhash); +void DAL_HASH_ErrorCallback(HASH_HandleTypeDef *hhash); +/* Callbacks Register/UnRegister functions ***********************************/ +#if (USE_DAL_HASH_REGISTER_CALLBACKS == 1) +DAL_StatusTypeDef DAL_HASH_RegisterCallback(HASH_HandleTypeDef *hhash, DAL_HASH_CallbackIDTypeDef CallbackID, + pHASH_CallbackTypeDef pCallback); +DAL_StatusTypeDef DAL_HASH_UnRegisterCallback(HASH_HandleTypeDef *hhash, DAL_HASH_CallbackIDTypeDef CallbackID); +#endif /* USE_DAL_HASH_REGISTER_CALLBACKS */ + + +/** + * @} + */ + +/** @addtogroup HASH_Exported_Functions_Group2 HASH processing functions in polling mode + * @{ + */ + + +/* HASH processing using polling *********************************************/ +DAL_StatusTypeDef DAL_HASH_SHA1_Start(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, uint8_t *pOutBuffer, + uint32_t Timeout); +DAL_StatusTypeDef DAL_HASH_MD5_Start(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, uint8_t *pOutBuffer, + uint32_t Timeout); +DAL_StatusTypeDef DAL_HASH_MD5_Accmlt(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size); +DAL_StatusTypeDef DAL_HASH_SHA1_Accmlt(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size); +DAL_StatusTypeDef DAL_HASH_MD5_Accmlt_End(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, + uint8_t *pOutBuffer, uint32_t Timeout); +DAL_StatusTypeDef DAL_HASH_SHA1_Accmlt_End(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, + uint8_t *pOutBuffer, uint32_t Timeout); + + +/** + * @} + */ + +/** @addtogroup HASH_Exported_Functions_Group3 HASH processing functions in interrupt mode + * @{ + */ + +/* HASH processing using IT **************************************************/ +DAL_StatusTypeDef DAL_HASH_SHA1_Start_IT(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, + uint8_t *pOutBuffer); +DAL_StatusTypeDef DAL_HASH_SHA1_Accmlt_IT(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size); +DAL_StatusTypeDef DAL_HASH_SHA1_Accmlt_End_IT(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, + uint8_t *pOutBuffer); +DAL_StatusTypeDef DAL_HASH_MD5_Start_IT(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, + uint8_t *pOutBuffer); +DAL_StatusTypeDef DAL_HASH_MD5_Accmlt_IT(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size); +DAL_StatusTypeDef DAL_HASH_MD5_Accmlt_End_IT(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, + uint8_t *pOutBuffer); +void DAL_HASH_IRQHandler(HASH_HandleTypeDef *hhash); +/** + * @} + */ + +/** @addtogroup HASH_Exported_Functions_Group4 HASH processing functions in DMA mode + * @{ + */ + +/* HASH processing using DMA *************************************************/ +DAL_StatusTypeDef DAL_HASH_SHA1_Start_DMA(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size); +DAL_StatusTypeDef DAL_HASH_SHA1_Finish(HASH_HandleTypeDef *hhash, uint8_t *pOutBuffer, uint32_t Timeout); +DAL_StatusTypeDef DAL_HASH_MD5_Start_DMA(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size); +DAL_StatusTypeDef DAL_HASH_MD5_Finish(HASH_HandleTypeDef *hhash, uint8_t *pOutBuffer, uint32_t Timeout); + +/** + * @} + */ + +/** @addtogroup HASH_Exported_Functions_Group5 HMAC processing functions in polling mode + * @{ + */ + +/* HASH-MAC processing using polling *****************************************/ +DAL_StatusTypeDef DAL_HMAC_SHA1_Start(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, uint8_t *pOutBuffer, + uint32_t Timeout); +DAL_StatusTypeDef DAL_HMAC_MD5_Start(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, uint8_t *pOutBuffer, + uint32_t Timeout); + +/** + * @} + */ + +/** @addtogroup HASH_Exported_Functions_Group6 HMAC processing functions in interrupt mode + * @{ + */ + +DAL_StatusTypeDef DAL_HMAC_MD5_Start_IT(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, + uint8_t *pOutBuffer); +DAL_StatusTypeDef DAL_HMAC_SHA1_Start_IT(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, + uint8_t *pOutBuffer); + +/** + * @} + */ + +/** @addtogroup HASH_Exported_Functions_Group7 HMAC processing functions in DMA mode + * @{ + */ + +/* HASH-HMAC processing using DMA ********************************************/ +DAL_StatusTypeDef DAL_HMAC_SHA1_Start_DMA(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size); +DAL_StatusTypeDef DAL_HMAC_MD5_Start_DMA(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size); + +/** + * @} + */ + +/** @addtogroup HASH_Exported_Functions_Group8 Peripheral states functions + * @{ + */ + + +/* Peripheral State methods **************************************************/ +DAL_HASH_StateTypeDef DAL_HASH_GetState(HASH_HandleTypeDef *hhash); +DAL_StatusTypeDef DAL_HASH_GetStatus(HASH_HandleTypeDef *hhash); +void DAL_HASH_ContextSaving(HASH_HandleTypeDef *hhash, uint8_t *pMemBuffer); +void DAL_HASH_ContextRestoring(HASH_HandleTypeDef *hhash, uint8_t *pMemBuffer); +void DAL_HASH_SwFeed_ProcessSuspend(HASH_HandleTypeDef *hhash); +DAL_StatusTypeDef DAL_HASH_DMAFeed_ProcessSuspend(HASH_HandleTypeDef *hhash); +uint32_t DAL_HASH_GetError(HASH_HandleTypeDef *hhash); + +/** + * @} + */ + +/** + * @} + */ + +/* Private functions -----------------------------------------------------------*/ + +/** @addtogroup HASH_Private_Functions HASH Private Functions + * @{ + */ + +/* Private functions */ +DAL_StatusTypeDef HASH_Start(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, uint8_t *pOutBuffer, + uint32_t Timeout, uint32_t Algorithm); +DAL_StatusTypeDef HASH_Accumulate(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, uint32_t Algorithm); +DAL_StatusTypeDef HASH_Accumulate_IT(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, uint32_t Algorithm); +DAL_StatusTypeDef HASH_Start_IT(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, uint8_t *pOutBuffer, + uint32_t Algorithm); +DAL_StatusTypeDef HASH_Start_DMA(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, uint32_t Algorithm); +DAL_StatusTypeDef HASH_Finish(HASH_HandleTypeDef *hhash, uint8_t *pOutBuffer, uint32_t Timeout); +DAL_StatusTypeDef HMAC_Start(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, uint8_t *pOutBuffer, + uint32_t Timeout, uint32_t Algorithm); +DAL_StatusTypeDef HMAC_Start_IT(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, uint8_t *pOutBuffer, + uint32_t Algorithm); +DAL_StatusTypeDef HMAC_Start_DMA(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, uint32_t Algorithm); + +/** + * @} + */ + +/** + * @} + */ +#endif /* HASH*/ +/** + * @} + */ + + +#ifdef __cplusplus +} +#endif + + +#endif /* APM32F4xx_DAL_HASH_H */ + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_hash_ex.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_hash_ex.h new file mode 100644 index 0000000000..48426bf746 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_hash_ex.h @@ -0,0 +1,199 @@ +/** + * + * @file apm32f4xx_dal_hash_ex.h + * @brief Header file of HASH DAL module. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef APM32F4xx_DAL_HASH_EX_H +#define APM32F4xx_DAL_HASH_EX_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal_def.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ +#if defined (HASH) +/** @addtogroup HASHEx + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ +/* Exported constants --------------------------------------------------------*/ +/* Exported macro ------------------------------------------------------------*/ + + +/* Exported functions --------------------------------------------------------*/ + +/** @addtogroup HASHEx_Exported_Functions HASH Extended Exported Functions + * @{ + */ + +/** @addtogroup HASHEx_Exported_Functions_Group1 HASH extended processing functions in polling mode + * @{ + */ + +DAL_StatusTypeDef DAL_HASHEx_SHA224_Start(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, + uint8_t *pOutBuffer, uint32_t Timeout); +DAL_StatusTypeDef DAL_HASHEx_SHA224_Accmlt(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size); +DAL_StatusTypeDef DAL_HASHEx_SHA224_Accmlt_End(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, + uint8_t *pOutBuffer, uint32_t Timeout); +DAL_StatusTypeDef DAL_HASHEx_SHA256_Start(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, + uint8_t *pOutBuffer, uint32_t Timeout); +DAL_StatusTypeDef DAL_HASHEx_SHA256_Accmlt(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size); +DAL_StatusTypeDef DAL_HASHEx_SHA256_Accmlt_End(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, + uint8_t *pOutBuffer, uint32_t Timeout); + +/** + * @} + */ + +/** @addtogroup HASHEx_Exported_Functions_Group2 HASH extended processing functions in interrupt mode + * @{ + */ + +DAL_StatusTypeDef DAL_HASHEx_SHA224_Start_IT(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, + uint8_t *pOutBuffer); +DAL_StatusTypeDef DAL_HASHEx_SHA224_Accmlt_IT(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size); +DAL_StatusTypeDef DAL_HASHEx_SHA224_Accmlt_End_IT(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, + uint8_t *pOutBuffer); +DAL_StatusTypeDef DAL_HASHEx_SHA256_Start_IT(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, + uint8_t *pOutBuffer); +DAL_StatusTypeDef DAL_HASHEx_SHA256_Accmlt_IT(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size); +DAL_StatusTypeDef DAL_HASHEx_SHA256_Accmlt_End_IT(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, + uint8_t *pOutBuffer); + +/** + * @} + */ + +/** @addtogroup HASHEx_Exported_Functions_Group3 HASH extended processing functions in DMA mode + * @{ + */ +DAL_StatusTypeDef DAL_HASHEx_SHA224_Start_DMA(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size); +DAL_StatusTypeDef DAL_HASHEx_SHA224_Finish(HASH_HandleTypeDef *hhash, uint8_t *pOutBuffer, uint32_t Timeout); +DAL_StatusTypeDef DAL_HASHEx_SHA256_Start_DMA(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size); +DAL_StatusTypeDef DAL_HASHEx_SHA256_Finish(HASH_HandleTypeDef *hhash, uint8_t *pOutBuffer, uint32_t Timeout); + +/** + * @} + */ + +/** @addtogroup HASHEx_Exported_Functions_Group4 HMAC extended processing functions in polling mode + * @{ + */ +DAL_StatusTypeDef DAL_HMACEx_SHA224_Start(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, + uint8_t *pOutBuffer, uint32_t Timeout); +DAL_StatusTypeDef DAL_HMACEx_SHA256_Start(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, + uint8_t *pOutBuffer, uint32_t Timeout); +/** + * @} + */ + +/** @addtogroup HASHEx_Exported_Functions_Group5 HMAC extended processing functions in interrupt mode + * @{ + */ + +DAL_StatusTypeDef DAL_HMACEx_SHA224_Start_IT(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, + uint8_t *pOutBuffer); +DAL_StatusTypeDef DAL_HMACEx_SHA256_Start_IT(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, + uint8_t *pOutBuffer); + +/** + * @} + */ + +/** @addtogroup HASHEx_Exported_Functions_Group6 HMAC extended processing functions in DMA mode + * @{ + */ + +DAL_StatusTypeDef DAL_HMACEx_SHA224_Start_DMA(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size); +DAL_StatusTypeDef DAL_HMACEx_SHA256_Start_DMA(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size); + +/** + * @} + */ + +/** @addtogroup HASHEx_Exported_Functions_Group7 Multi-buffer HMAC extended processing functions in DMA mode + * @{ + */ + +DAL_StatusTypeDef DAL_HMACEx_MD5_Step1_2_DMA(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size); +DAL_StatusTypeDef DAL_HMACEx_MD5_Step2_DMA(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size); +DAL_StatusTypeDef DAL_HMACEx_MD5_Step2_3_DMA(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size); + +DAL_StatusTypeDef DAL_HMACEx_SHA1_Step1_2_DMA(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size); +DAL_StatusTypeDef DAL_HMACEx_SHA1_Step2_DMA(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size); +DAL_StatusTypeDef DAL_HMACEx_SHA1_Step2_3_DMA(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size); +DAL_StatusTypeDef DAL_HMACEx_SHA224_Step1_2_DMA(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size); +DAL_StatusTypeDef DAL_HMACEx_SHA224_Step2_DMA(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size); +DAL_StatusTypeDef DAL_HMACEx_SHA224_Step2_3_DMA(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size); + +DAL_StatusTypeDef DAL_HMACEx_SHA256_Step1_2_DMA(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size); +DAL_StatusTypeDef DAL_HMACEx_SHA256_Step2_DMA(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size); +DAL_StatusTypeDef DAL_HMACEx_SHA256_Step2_3_DMA(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size); +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ +#endif /* HASH*/ +/** + * @} + */ + + +#ifdef __cplusplus +} +#endif + + +#endif /* APM32F4xx_DAL_HASH_EX_H */ + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_hcd.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_hcd.h new file mode 100644 index 0000000000..083e40b3bd --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_hcd.h @@ -0,0 +1,341 @@ +/** + * + * @file apm32f4xx_dal_hcd.h + * @brief Header file of HCD DAL module. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef APM32F4xx_DAL_HCD_H +#define APM32F4xx_DAL_HCD_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_ddl_usb.h" + +#if defined (USB_OTG_FS) || defined (USB_OTG_HS) +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @addtogroup HCD HCD + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ +/** @defgroup HCD_Exported_Types HCD Exported Types + * @{ + */ + +/** @defgroup HCD_Exported_Types_Group1 HCD State Structure definition + * @{ + */ +typedef enum +{ + DAL_HCD_STATE_RESET = 0x00, + DAL_HCD_STATE_READY = 0x01, + DAL_HCD_STATE_ERROR = 0x02, + DAL_HCD_STATE_BUSY = 0x03, + DAL_HCD_STATE_TIMEOUT = 0x04 +} HCD_StateTypeDef; + +typedef USB_OTG_GlobalTypeDef HCD_TypeDef; +typedef USB_OTG_CfgTypeDef HCD_InitTypeDef; +typedef USB_OTG_HCTypeDef HCD_HCTypeDef; +typedef USB_OTG_URBStateTypeDef HCD_URBStateTypeDef; +typedef USB_OTG_HCStateTypeDef HCD_HCStateTypeDef; +/** + * @} + */ + +/** @defgroup HCD_Exported_Types_Group2 HCD Handle Structure definition + * @{ + */ +#if (USE_DAL_HCD_REGISTER_CALLBACKS == 1U) +typedef struct __HCD_HandleTypeDef +#else +typedef struct +#endif /* USE_DAL_HCD_REGISTER_CALLBACKS */ +{ + HCD_TypeDef *Instance; /*!< Register base address */ + HCD_InitTypeDef Init; /*!< HCD required parameters */ + HCD_HCTypeDef hc[16]; /*!< Host channels parameters */ + DAL_LockTypeDef Lock; /*!< HCD peripheral status */ + __IO HCD_StateTypeDef State; /*!< HCD communication state */ + __IO uint32_t ErrorCode; /*!< HCD Error code */ + void *pData; /*!< Pointer Stack Handler */ +#if (USE_DAL_HCD_REGISTER_CALLBACKS == 1U) + void (* SOFCallback)(struct __HCD_HandleTypeDef *hhcd); /*!< USB OTG HCD SOF callback */ + void (* ConnectCallback)(struct __HCD_HandleTypeDef *hhcd); /*!< USB OTG HCD Connect callback */ + void (* DisconnectCallback)(struct __HCD_HandleTypeDef *hhcd); /*!< USB OTG HCD Disconnect callback */ + void (* PortEnabledCallback)(struct __HCD_HandleTypeDef *hhcd); /*!< USB OTG HCD Port Enable callback */ + void (* PortDisabledCallback)(struct __HCD_HandleTypeDef *hhcd); /*!< USB OTG HCD Port Disable callback */ + void (* HC_NotifyURBChangeCallback)(struct __HCD_HandleTypeDef *hhcd, uint8_t chnum, + HCD_URBStateTypeDef urb_state); /*!< USB OTG HCD Host Channel Notify URB Change callback */ + + void (* MspInitCallback)(struct __HCD_HandleTypeDef *hhcd); /*!< USB OTG HCD Msp Init callback */ + void (* MspDeInitCallback)(struct __HCD_HandleTypeDef *hhcd); /*!< USB OTG HCD Msp DeInit callback */ +#endif /* USE_DAL_HCD_REGISTER_CALLBACKS */ +} HCD_HandleTypeDef; +/** + * @} + */ + +/** + * @} + */ + +/* Exported constants --------------------------------------------------------*/ +/** @defgroup HCD_Exported_Constants HCD Exported Constants + * @{ + */ + +/** @defgroup HCD_Speed HCD Speed + * @{ + */ +#define HCD_SPEED_HIGH USBH_HS_SPEED +#define HCD_SPEED_FULL USBH_FSLS_SPEED +#define HCD_SPEED_LOW USBH_FSLS_SPEED +/** + * @} + */ + +/** @defgroup HCD_Device_Speed HCD Device Speed + * @{ + */ +#define HCD_DEVICE_SPEED_HIGH 0U +#define HCD_DEVICE_SPEED_FULL 1U +#define HCD_DEVICE_SPEED_LOW 2U +/** + * @} + */ + +/** @defgroup HCD_PHY_Module HCD PHY Module + * @{ + */ +#define HCD_PHY_ULPI 1U +#define HCD_PHY_EMBEDDED 2U +/** + * @} + */ + +/** @defgroup HCD_Error_Code_definition HCD Error Code definition + * @brief HCD Error Code definition + * @{ + */ +#if (USE_DAL_HCD_REGISTER_CALLBACKS == 1U) +#define DAL_HCD_ERROR_INVALID_CALLBACK (0x00000010U) /*!< Invalid Callback error */ +#endif /* USE_DAL_HCD_REGISTER_CALLBACKS */ + +/** + * @} + */ + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ +/** @defgroup HCD_Exported_Macros HCD Exported Macros + * @brief macros to handle interrupts and specific clock configurations + * @{ + */ +#define __DAL_HCD_ENABLE(__HANDLE__) (void)USB_EnableGlobalInt ((__HANDLE__)->Instance) +#define __DAL_HCD_DISABLE(__HANDLE__) (void)USB_DisableGlobalInt ((__HANDLE__)->Instance) + +#define __DAL_HCD_GET_FLAG(__HANDLE__, __INTERRUPT__) ((USB_ReadInterrupts((__HANDLE__)->Instance)\ + & (__INTERRUPT__)) == (__INTERRUPT__)) +#define __DAL_HCD_CLEAR_FLAG(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->GCINT) = (__INTERRUPT__)) +#define __DAL_HCD_IS_INVALID_INTERRUPT(__HANDLE__) (USB_ReadInterrupts((__HANDLE__)->Instance) == 0U) + +#define __DAL_HCD_CLEAR_HC_INT(chnum, __INTERRUPT__) (USBx_HC(chnum)->HCHINT = (__INTERRUPT__)) +#define __DAL_HCD_MASK_HALT_HC_INT(chnum) (USBx_HC(chnum)->HCHIMASK &= ~USB_OTG_HCHIMASK_TSFCMPANM) +#define __DAL_HCD_UNMASK_HALT_HC_INT(chnum) (USBx_HC(chnum)->HCHIMASK |= USB_OTG_HCHIMASK_TSFCMPANM) +#define __DAL_HCD_MASK_ACK_HC_INT(chnum) (USBx_HC(chnum)->HCHIMASK &= ~USB_OTG_HCHIMASK_RXTXACKM) +#define __DAL_HCD_UNMASK_ACK_HC_INT(chnum) (USBx_HC(chnum)->HCHIMASK |= USB_OTG_HCHIMASK_RXTXACKM) +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup HCD_Exported_Functions HCD Exported Functions + * @{ + */ + +/** @defgroup HCD_Exported_Functions_Group1 Initialization and de-initialization functions + * @{ + */ +DAL_StatusTypeDef DAL_HCD_Init(HCD_HandleTypeDef *hhcd); +DAL_StatusTypeDef DAL_HCD_DeInit(HCD_HandleTypeDef *hhcd); +DAL_StatusTypeDef DAL_HCD_HC_Init(HCD_HandleTypeDef *hhcd, uint8_t ch_num, + uint8_t epnum, uint8_t dev_address, + uint8_t speed, uint8_t ep_type, uint16_t mps); + +DAL_StatusTypeDef DAL_HCD_HC_Halt(HCD_HandleTypeDef *hhcd, uint8_t ch_num); +void DAL_HCD_MspInit(HCD_HandleTypeDef *hhcd); +void DAL_HCD_MspDeInit(HCD_HandleTypeDef *hhcd); + +#if (USE_DAL_HCD_REGISTER_CALLBACKS == 1U) +/** @defgroup DAL_HCD_Callback_ID_enumeration_definition DAL USB OTG HCD Callback ID enumeration definition + * @brief DAL USB OTG HCD Callback ID enumeration definition + * @{ + */ +typedef enum +{ + DAL_HCD_SOF_CB_ID = 0x01, /*!< USB HCD SOF callback ID */ + DAL_HCD_CONNECT_CB_ID = 0x02, /*!< USB HCD Connect callback ID */ + DAL_HCD_DISCONNECT_CB_ID = 0x03, /*!< USB HCD Disconnect callback ID */ + DAL_HCD_PORT_ENABLED_CB_ID = 0x04, /*!< USB HCD Port Enable callback ID */ + DAL_HCD_PORT_DISABLED_CB_ID = 0x05, /*!< USB HCD Port Disable callback ID */ + + DAL_HCD_MSPINIT_CB_ID = 0x06, /*!< USB HCD MspInit callback ID */ + DAL_HCD_MSPDEINIT_CB_ID = 0x07 /*!< USB HCD MspDeInit callback ID */ + +} DAL_HCD_CallbackIDTypeDef; +/** + * @} + */ + +/** @defgroup DAL_HCD_Callback_pointer_definition DAL USB OTG HCD Callback pointer definition + * @brief DAL USB OTG HCD Callback pointer definition + * @{ + */ + +typedef void (*pHCD_CallbackTypeDef)(HCD_HandleTypeDef *hhcd); /*!< pointer to a common USB OTG HCD callback function */ +typedef void (*pHCD_HC_NotifyURBChangeCallbackTypeDef)(HCD_HandleTypeDef *hhcd, + uint8_t epnum, + HCD_URBStateTypeDef urb_state); /*!< pointer to USB OTG HCD host channel callback */ +/** + * @} + */ + +DAL_StatusTypeDef DAL_HCD_RegisterCallback(HCD_HandleTypeDef *hhcd, + DAL_HCD_CallbackIDTypeDef CallbackID, + pHCD_CallbackTypeDef pCallback); + +DAL_StatusTypeDef DAL_HCD_UnRegisterCallback(HCD_HandleTypeDef *hhcd, + DAL_HCD_CallbackIDTypeDef CallbackID); + +DAL_StatusTypeDef DAL_HCD_RegisterHC_NotifyURBChangeCallback(HCD_HandleTypeDef *hhcd, + pHCD_HC_NotifyURBChangeCallbackTypeDef pCallback); + +DAL_StatusTypeDef DAL_HCD_UnRegisterHC_NotifyURBChangeCallback(HCD_HandleTypeDef *hhcd); +#endif /* USE_DAL_HCD_REGISTER_CALLBACKS */ +/** + * @} + */ + +/* I/O operation functions ***************************************************/ +/** @addtogroup HCD_Exported_Functions_Group2 Input and Output operation functions + * @{ + */ +DAL_StatusTypeDef DAL_HCD_HC_SubmitRequest(HCD_HandleTypeDef *hhcd, uint8_t ch_num, + uint8_t direction, uint8_t ep_type, + uint8_t token, uint8_t *pbuff, + uint16_t length, uint8_t do_ping); + +/* Non-Blocking mode: Interrupt */ +void DAL_HCD_IRQHandler(HCD_HandleTypeDef *hhcd); +void DAL_HCD_WKUP_IRQHandler(HCD_HandleTypeDef *hhcd); +void DAL_HCD_SOF_Callback(HCD_HandleTypeDef *hhcd); +void DAL_HCD_Connect_Callback(HCD_HandleTypeDef *hhcd); +void DAL_HCD_Disconnect_Callback(HCD_HandleTypeDef *hhcd); +void DAL_HCD_PortEnabled_Callback(HCD_HandleTypeDef *hhcd); +void DAL_HCD_PortDisabled_Callback(HCD_HandleTypeDef *hhcd); +void DAL_HCD_HC_NotifyURBChange_Callback(HCD_HandleTypeDef *hhcd, uint8_t chnum, + HCD_URBStateTypeDef urb_state); +/** + * @} + */ + +/* Peripheral Control functions **********************************************/ +/** @addtogroup HCD_Exported_Functions_Group3 Peripheral Control functions + * @{ + */ +DAL_StatusTypeDef DAL_HCD_ResetPort(HCD_HandleTypeDef *hhcd); +DAL_StatusTypeDef DAL_HCD_Start(HCD_HandleTypeDef *hhcd); +DAL_StatusTypeDef DAL_HCD_Stop(HCD_HandleTypeDef *hhcd); +/** + * @} + */ + +/* Peripheral State functions ************************************************/ +/** @addtogroup HCD_Exported_Functions_Group4 Peripheral State functions + * @{ + */ +HCD_StateTypeDef DAL_HCD_GetState(HCD_HandleTypeDef *hhcd); +HCD_URBStateTypeDef DAL_HCD_HC_GetURBState(HCD_HandleTypeDef *hhcd, uint8_t chnum); +HCD_HCStateTypeDef DAL_HCD_HC_GetState(HCD_HandleTypeDef *hhcd, uint8_t chnum); +uint32_t DAL_HCD_HC_GetXferCount(HCD_HandleTypeDef *hhcd, uint8_t chnum); +uint32_t DAL_HCD_GetCurrentFrame(HCD_HandleTypeDef *hhcd); +uint32_t DAL_HCD_GetCurrentSpeed(HCD_HandleTypeDef *hhcd); +void DAL_HCD_ConfigToggle(HCD_HandleTypeDef* hhcd, uint8_t pipe, uint8_t toggle); +uint8_t DAL_HCD_ReadToggle(HCD_HandleTypeDef* hhcd, uint8_t pipe); +/** + * @} + */ + +/** + * @} + */ + +/* Private macros ------------------------------------------------------------*/ +/** @defgroup HCD_Private_Macros HCD Private Macros + * @{ + */ +/** + * @} + */ +/* Private functions prototypes ----------------------------------------------*/ + +/** + * @} + */ +/** + * @} + */ +#endif /* defined (USB_OTG_FS) || defined (USB_OTG_HS) */ + +#ifdef __cplusplus +} +#endif + +#endif /* APM32F4xx_DAL_HCD_H */ diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_i2c.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_i2c.h new file mode 100644 index 0000000000..2e10ce4d70 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_i2c.h @@ -0,0 +1,765 @@ +/** + * + * @file apm32f4xx_dal_i2c.h + * @brief Header file of I2C DAL module. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef APM32F4xx_DAL_I2C_H +#define APM32F4xx_DAL_I2C_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal_def.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @addtogroup I2C + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ +/** @defgroup I2C_Exported_Types I2C Exported Types + * @{ + */ + +/** @defgroup I2C_Configuration_Structure_definition I2C Configuration Structure definition + * @brief I2C Configuration Structure definition + * @{ + */ +typedef struct +{ + uint32_t ClockSpeed; /*!< Specifies the clock frequency. + This parameter must be set to a value lower than 400kHz */ + + uint32_t DutyCycle; /*!< Specifies the I2C fast mode duty cycle. + This parameter can be a value of @ref I2C_duty_cycle_in_fast_mode */ + + uint32_t OwnAddress1; /*!< Specifies the first device own address. + This parameter can be a 7-bit or 10-bit address. */ + + uint32_t AddressingMode; /*!< Specifies if 7-bit or 10-bit addressing mode is selected. + This parameter can be a value of @ref I2C_addressing_mode */ + + uint32_t DualAddressMode; /*!< Specifies if dual addressing mode is selected. + This parameter can be a value of @ref I2C_dual_addressing_mode */ + + uint32_t OwnAddress2; /*!< Specifies the second device own address if dual addressing mode is selected + This parameter can be a 7-bit address. */ + + uint32_t GeneralCallMode; /*!< Specifies if general call mode is selected. + This parameter can be a value of @ref I2C_general_call_addressing_mode */ + + uint32_t NoStretchMode; /*!< Specifies if nostretch mode is selected. + This parameter can be a value of @ref I2C_nostretch_mode */ + +} I2C_InitTypeDef; + +/** + * @} + */ + +/** @defgroup DAL_state_structure_definition DAL state structure definition + * @brief DAL State structure definition + * @note DAL I2C State value coding follow below described bitmap : + * b7-b6 Error information + * 00 : No Error + * 01 : Abort (Abort user request on going) + * 10 : Timeout + * 11 : Error + * b5 Peripheral initialization status + * 0 : Reset (Peripheral not initialized) + * 1 : Init done (Peripheral initialized and ready to use. DAL I2C Init function called) + * b4 (not used) + * x : Should be set to 0 + * b3 + * 0 : Ready or Busy (No Listen mode ongoing) + * 1 : Listen (Peripheral in Address Listen Mode) + * b2 Intrinsic process state + * 0 : Ready + * 1 : Busy (Peripheral busy with some configuration or internal operations) + * b1 Rx state + * 0 : Ready (no Rx operation ongoing) + * 1 : Busy (Rx operation ongoing) + * b0 Tx state + * 0 : Ready (no Tx operation ongoing) + * 1 : Busy (Tx operation ongoing) + * @{ + */ +typedef enum +{ + DAL_I2C_STATE_RESET = 0x00U, /*!< Peripheral is not yet Initialized */ + DAL_I2C_STATE_READY = 0x20U, /*!< Peripheral Initialized and ready for use */ + DAL_I2C_STATE_BUSY = 0x24U, /*!< An internal process is ongoing */ + DAL_I2C_STATE_BUSY_TX = 0x21U, /*!< Data Transmission process is ongoing */ + DAL_I2C_STATE_BUSY_RX = 0x22U, /*!< Data Reception process is ongoing */ + DAL_I2C_STATE_LISTEN = 0x28U, /*!< Address Listen Mode is ongoing */ + DAL_I2C_STATE_BUSY_TX_LISTEN = 0x29U, /*!< Address Listen Mode and Data Transmission + process is ongoing */ + DAL_I2C_STATE_BUSY_RX_LISTEN = 0x2AU, /*!< Address Listen Mode and Data Reception + process is ongoing */ + DAL_I2C_STATE_ABORT = 0x60U, /*!< Abort user request ongoing */ + DAL_I2C_STATE_TIMEOUT = 0xA0U, /*!< Timeout state */ + DAL_I2C_STATE_ERROR = 0xE0U /*!< Error */ + +} DAL_I2C_StateTypeDef; + +/** + * @} + */ + +/** @defgroup DAL_mode_structure_definition DAL mode structure definition + * @brief DAL Mode structure definition + * @note DAL I2C Mode value coding follow below described bitmap :\n + * b7 (not used)\n + * x : Should be set to 0\n + * b6\n + * 0 : None\n + * 1 : Memory (DAL I2C communication is in Memory Mode)\n + * b5\n + * 0 : None\n + * 1 : Slave (DAL I2C communication is in Slave Mode)\n + * b4\n + * 0 : None\n + * 1 : Master (DAL I2C communication is in Master Mode)\n + * b3-b2-b1-b0 (not used)\n + * xxxx : Should be set to 0000 + * @{ + */ +typedef enum +{ + DAL_I2C_MODE_NONE = 0x00U, /*!< No I2C communication on going */ + DAL_I2C_MODE_MASTER = 0x10U, /*!< I2C communication is in Master Mode */ + DAL_I2C_MODE_SLAVE = 0x20U, /*!< I2C communication is in Slave Mode */ + DAL_I2C_MODE_MEM = 0x40U /*!< I2C communication is in Memory Mode */ + +} DAL_I2C_ModeTypeDef; + +/** + * @} + */ + +/** @defgroup I2C_Error_Code_definition I2C Error Code definition + * @brief I2C Error Code definition + * @{ + */ +#define DAL_I2C_ERROR_NONE 0x00000000U /*!< No error */ +#define DAL_I2C_ERROR_BERR 0x00000001U /*!< BERR error */ +#define DAL_I2C_ERROR_ARLO 0x00000002U /*!< ARLO error */ +#define DAL_I2C_ERROR_AF 0x00000004U /*!< AF error */ +#define DAL_I2C_ERROR_OVR 0x00000008U /*!< OVR error */ +#define DAL_I2C_ERROR_DMA 0x00000010U /*!< DMA transfer error */ +#define DAL_I2C_ERROR_TIMEOUT 0x00000020U /*!< Timeout Error */ +#define DAL_I2C_ERROR_SIZE 0x00000040U /*!< Size Management error */ +#define DAL_I2C_ERROR_DMA_PARAM 0x00000080U /*!< DMA Parameter Error */ +#define DAL_I2C_WRONG_START 0x00000200U /*!< Wrong start Error */ +#if (USE_DAL_I2C_REGISTER_CALLBACKS == 1) +#define DAL_I2C_ERROR_INVALID_CALLBACK 0x00000100U /*!< Invalid Callback error */ +#endif /* USE_DAL_I2C_REGISTER_CALLBACKS */ +/** + * @} + */ + +/** @defgroup I2C_handle_Structure_definition I2C handle Structure definition + * @brief I2C handle Structure definition + * @{ + */ +#if (USE_DAL_I2C_REGISTER_CALLBACKS == 1) +typedef struct __I2C_HandleTypeDef +#else +typedef struct +#endif /* USE_DAL_I2C_REGISTER_CALLBACKS */ +{ + I2C_TypeDef *Instance; /*!< I2C registers base address */ + + I2C_InitTypeDef Init; /*!< I2C communication parameters */ + + uint8_t *pBuffPtr; /*!< Pointer to I2C transfer buffer */ + + uint16_t XferSize; /*!< I2C transfer size */ + + __IO uint16_t XferCount; /*!< I2C transfer counter */ + + __IO uint32_t XferOptions; /*!< I2C transfer options */ + + __IO uint32_t PreviousState; /*!< I2C communication Previous state and mode + context for internal usage */ + + DMA_HandleTypeDef *hdmatx; /*!< I2C Tx DMA handle parameters */ + + DMA_HandleTypeDef *hdmarx; /*!< I2C Rx DMA handle parameters */ + + DAL_LockTypeDef Lock; /*!< I2C locking object */ + + __IO DAL_I2C_StateTypeDef State; /*!< I2C communication state */ + + __IO DAL_I2C_ModeTypeDef Mode; /*!< I2C communication mode */ + + __IO uint32_t ErrorCode; /*!< I2C Error code */ + + __IO uint32_t Devaddress; /*!< I2C Target device address */ + + __IO uint32_t Memaddress; /*!< I2C Target memory address */ + + __IO uint32_t MemaddSize; /*!< I2C Target memory address size */ + + __IO uint32_t EventCount; /*!< I2C Event counter */ + + +#if (USE_DAL_I2C_REGISTER_CALLBACKS == 1) + void (* MasterTxCpltCallback)(struct __I2C_HandleTypeDef *hi2c); /*!< I2C Master Tx Transfer completed callback */ + void (* MasterRxCpltCallback)(struct __I2C_HandleTypeDef *hi2c); /*!< I2C Master Rx Transfer completed callback */ + void (* SlaveTxCpltCallback)(struct __I2C_HandleTypeDef *hi2c); /*!< I2C Slave Tx Transfer completed callback */ + void (* SlaveRxCpltCallback)(struct __I2C_HandleTypeDef *hi2c); /*!< I2C Slave Rx Transfer completed callback */ + void (* ListenCpltCallback)(struct __I2C_HandleTypeDef *hi2c); /*!< I2C Listen Complete callback */ + void (* MemTxCpltCallback)(struct __I2C_HandleTypeDef *hi2c); /*!< I2C Memory Tx Transfer completed callback */ + void (* MemRxCpltCallback)(struct __I2C_HandleTypeDef *hi2c); /*!< I2C Memory Rx Transfer completed callback */ + void (* ErrorCallback)(struct __I2C_HandleTypeDef *hi2c); /*!< I2C Error callback */ + void (* AbortCpltCallback)(struct __I2C_HandleTypeDef *hi2c); /*!< I2C Abort callback */ + + void (* AddrCallback)(struct __I2C_HandleTypeDef *hi2c, uint8_t TransferDirection, uint16_t AddrMatchCode); /*!< I2C Slave Address Match callback */ + + void (* MspInitCallback)(struct __I2C_HandleTypeDef *hi2c); /*!< I2C Msp Init callback */ + void (* MspDeInitCallback)(struct __I2C_HandleTypeDef *hi2c); /*!< I2C Msp DeInit callback */ + +#endif /* USE_DAL_I2C_REGISTER_CALLBACKS */ +} I2C_HandleTypeDef; + +#if (USE_DAL_I2C_REGISTER_CALLBACKS == 1) +/** + * @brief DAL I2C Callback ID enumeration definition + */ +typedef enum +{ + DAL_I2C_MASTER_TX_COMPLETE_CB_ID = 0x00U, /*!< I2C Master Tx Transfer completed callback ID */ + DAL_I2C_MASTER_RX_COMPLETE_CB_ID = 0x01U, /*!< I2C Master Rx Transfer completed callback ID */ + DAL_I2C_SLAVE_TX_COMPLETE_CB_ID = 0x02U, /*!< I2C Slave Tx Transfer completed callback ID */ + DAL_I2C_SLAVE_RX_COMPLETE_CB_ID = 0x03U, /*!< I2C Slave Rx Transfer completed callback ID */ + DAL_I2C_LISTEN_COMPLETE_CB_ID = 0x04U, /*!< I2C Listen Complete callback ID */ + DAL_I2C_MEM_TX_COMPLETE_CB_ID = 0x05U, /*!< I2C Memory Tx Transfer callback ID */ + DAL_I2C_MEM_RX_COMPLETE_CB_ID = 0x06U, /*!< I2C Memory Rx Transfer completed callback ID */ + DAL_I2C_ERROR_CB_ID = 0x07U, /*!< I2C Error callback ID */ + DAL_I2C_ABORT_CB_ID = 0x08U, /*!< I2C Abort callback ID */ + + DAL_I2C_MSPINIT_CB_ID = 0x09U, /*!< I2C Msp Init callback ID */ + DAL_I2C_MSPDEINIT_CB_ID = 0x0AU /*!< I2C Msp DeInit callback ID */ + +} DAL_I2C_CallbackIDTypeDef; + +/** + * @brief DAL I2C Callback pointer definition + */ +typedef void (*pI2C_CallbackTypeDef)(I2C_HandleTypeDef *hi2c); /*!< pointer to an I2C callback function */ +typedef void (*pI2C_AddrCallbackTypeDef)(I2C_HandleTypeDef *hi2c, uint8_t TransferDirection, uint16_t AddrMatchCode); /*!< pointer to an I2C Address Match callback function */ + +#endif /* USE_DAL_I2C_REGISTER_CALLBACKS */ +/** + * @} + */ + +/** + * @} + */ +/* Exported constants --------------------------------------------------------*/ + +/** @defgroup I2C_Exported_Constants I2C Exported Constants + * @{ + */ + +/** @defgroup I2C_duty_cycle_in_fast_mode I2C duty cycle in fast mode + * @{ + */ +#define I2C_DUTYCYCLE_2 0x00000000U +#define I2C_DUTYCYCLE_16_9 I2C_CLKCTRL_FDUTYCFG +/** + * @} + */ + +/** @defgroup I2C_addressing_mode I2C addressing mode + * @{ + */ +#define I2C_ADDRESSINGMODE_7BIT 0x00004000U +#define I2C_ADDRESSINGMODE_10BIT (I2C_SADDR1_ADDRLEN | 0x00004000U) +/** + * @} + */ + +/** @defgroup I2C_dual_addressing_mode I2C dual addressing mode + * @{ + */ +#define I2C_DUALADDRESS_DISABLE 0x00000000U +#define I2C_DUALADDRESS_ENABLE I2C_SADDR2_ADDRNUM +/** + * @} + */ + +/** @defgroup I2C_general_call_addressing_mode I2C general call addressing mode + * @{ + */ +#define I2C_GENERALCALL_DISABLE 0x00000000U +#define I2C_GENERALCALL_ENABLE I2C_CTRL1_SRBEN +/** + * @} + */ + +/** @defgroup I2C_nostretch_mode I2C nostretch mode + * @{ + */ +#define I2C_NOSTRETCH_DISABLE 0x00000000U +#define I2C_NOSTRETCH_ENABLE I2C_CTRL1_CLKSTRETCHD +/** + * @} + */ + +/** @defgroup I2C_Memory_Address_Size I2C Memory Address Size + * @{ + */ +#define I2C_MEMADD_SIZE_8BIT 0x00000001U +#define I2C_MEMADD_SIZE_16BIT 0x00000010U +/** + * @} + */ + +/** @defgroup I2C_XferDirection_definition I2C XferDirection definition + * @{ + */ +#define I2C_DIRECTION_RECEIVE 0x00000000U +#define I2C_DIRECTION_TRANSMIT 0x00000001U +/** + * @} + */ + +/** @defgroup I2C_XferOptions_definition I2C XferOptions definition + * @{ + */ +#define I2C_FIRST_FRAME 0x00000001U +#define I2C_FIRST_AND_NEXT_FRAME 0x00000002U +#define I2C_NEXT_FRAME 0x00000004U +#define I2C_FIRST_AND_LAST_FRAME 0x00000008U +#define I2C_LAST_FRAME_NO_STOP 0x00000010U +#define I2C_LAST_FRAME 0x00000020U + +/* List of XferOptions in usage of : + * 1- Restart condition in all use cases (direction change or not) + */ +#define I2C_OTHER_FRAME (0x00AA0000U) +#define I2C_OTHER_AND_LAST_FRAME (0xAA000000U) +/** + * @} + */ + +/** @defgroup I2C_Interrupt_configuration_definition I2C Interrupt configuration definition + * @brief I2C Interrupt definition + * Elements values convention: 0xXXXXXXXX + * - XXXXXXXX : Interrupt control mask + * @{ + */ +#define I2C_IT_BUF I2C_CTRL2_BUFIEN +#define I2C_IT_EVT I2C_CTRL2_EVIEN +#define I2C_IT_ERR I2C_CTRL2_ERRIEN +/** + * @} + */ + +/** @defgroup I2C_Flag_definition I2C Flag definition + * @{ + */ + +#define I2C_FLAG_OVR 0x00010800U +#define I2C_FLAG_AF 0x00010400U +#define I2C_FLAG_ARLO 0x00010200U +#define I2C_FLAG_BERR 0x00010100U +#define I2C_FLAG_TXE 0x00010080U +#define I2C_FLAG_RXNE 0x00010040U +#define I2C_FLAG_STOPF 0x00010010U +#define I2C_FLAG_ADD10 0x00010008U +#define I2C_FLAG_BTF 0x00010004U +#define I2C_FLAG_ADDR 0x00010002U +#define I2C_FLAG_SB 0x00010001U +#define I2C_FLAG_DUALF 0x00100080U +#define I2C_FLAG_GENCALL 0x00100010U +#define I2C_FLAG_TRA 0x00100004U +#define I2C_FLAG_BUSY 0x00100002U +#define I2C_FLAG_MSL 0x00100001U +/** + * @} + */ + +/** + * @} + */ + +/* Exported macros -----------------------------------------------------------*/ + +/** @defgroup I2C_Exported_Macros I2C Exported Macros + * @{ + */ + +/** @brief Reset I2C handle state. + * @param __HANDLE__ specifies the I2C Handle. + * @retval None + */ +#if (USE_DAL_I2C_REGISTER_CALLBACKS == 1) +#define __DAL_I2C_RESET_HANDLE_STATE(__HANDLE__) do{ \ + (__HANDLE__)->State = DAL_I2C_STATE_RESET; \ + (__HANDLE__)->MspInitCallback = NULL; \ + (__HANDLE__)->MspDeInitCallback = NULL; \ + } while(0) +#else +#define __DAL_I2C_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = DAL_I2C_STATE_RESET) +#endif + +/** @brief Enable or disable the specified I2C interrupts. + * @param __HANDLE__ specifies the I2C Handle. + * @param __INTERRUPT__ specifies the interrupt source to enable or disable. + * This parameter can be one of the following values: + * @arg I2C_IT_BUF: Buffer interrupt enable + * @arg I2C_IT_EVT: Event interrupt enable + * @arg I2C_IT_ERR: Error interrupt enable + * @retval None + */ +#define __DAL_I2C_ENABLE_IT(__HANDLE__, __INTERRUPT__) SET_BIT((__HANDLE__)->Instance->CTRL2,(__INTERRUPT__)) +#define __DAL_I2C_DISABLE_IT(__HANDLE__, __INTERRUPT__) CLEAR_BIT((__HANDLE__)->Instance->CTRL2, (__INTERRUPT__)) + +/** @brief Checks if the specified I2C interrupt source is enabled or disabled. + * @param __HANDLE__ specifies the I2C Handle. + * @param __INTERRUPT__ specifies the I2C interrupt source to check. + * This parameter can be one of the following values: + * @arg I2C_IT_BUF: Buffer interrupt enable + * @arg I2C_IT_EVT: Event interrupt enable + * @arg I2C_IT_ERR: Error interrupt enable + * @retval The new state of __INTERRUPT__ (TRUE or FALSE). + */ +#define __DAL_I2C_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) ((((__HANDLE__)->Instance->CTRL2 & (__INTERRUPT__)) == (__INTERRUPT__)) ? SET : RESET) + +/** @brief Checks whether the specified I2C flag is set or not. + * @param __HANDLE__ specifies the I2C Handle. + * @param __FLAG__ specifies the flag to check. + * This parameter can be one of the following values: + * @arg I2C_FLAG_OVR: Overrun/Underrun flag + * @arg I2C_FLAG_AF: Acknowledge failure flag + * @arg I2C_FLAG_ARLO: Arbitration lost flag + * @arg I2C_FLAG_BERR: Bus error flag + * @arg I2C_FLAG_TXE: Data register empty flag + * @arg I2C_FLAG_RXNE: Data register not empty flag + * @arg I2C_FLAG_STOPF: Stop detection flag + * @arg I2C_FLAG_ADD10: 10-bit header sent flag + * @arg I2C_FLAG_BTF: Byte transfer finished flag + * @arg I2C_FLAG_ADDR: Address sent flag + * Address matched flag + * @arg I2C_FLAG_SB: Start bit flag + * @arg I2C_FLAG_DUALF: Dual flag + * @arg I2C_FLAG_GENCALL: General call header flag + * @arg I2C_FLAG_TRA: Transmitter/Receiver flag + * @arg I2C_FLAG_BUSY: Bus busy flag + * @arg I2C_FLAG_MSL: Master/Slave flag + * @retval The new state of __FLAG__ (TRUE or FALSE). + */ +#define __DAL_I2C_GET_FLAG(__HANDLE__, __FLAG__) ((((uint8_t)((__FLAG__) >> 16U)) == 0x01U) ? \ + (((((__HANDLE__)->Instance->STS1) & ((__FLAG__) & I2C_FLAG_MASK)) == ((__FLAG__) & I2C_FLAG_MASK)) ? SET : RESET) : \ + (((((__HANDLE__)->Instance->STS2) & ((__FLAG__) & I2C_FLAG_MASK)) == ((__FLAG__) & I2C_FLAG_MASK)) ? SET : RESET)) + +/** @brief Clears the I2C pending flags which are cleared by writing 0 in a specific bit. + * @param __HANDLE__ specifies the I2C Handle. + * @param __FLAG__ specifies the flag to clear. + * This parameter can be any combination of the following values: + * @arg I2C_FLAG_OVR: Overrun/Underrun flag (Slave mode) + * @arg I2C_FLAG_AF: Acknowledge failure flag + * @arg I2C_FLAG_ARLO: Arbitration lost flag (Master mode) + * @arg I2C_FLAG_BERR: Bus error flag + * @retval None + */ +#define __DAL_I2C_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->STS1 = ~((__FLAG__) & I2C_FLAG_MASK)) + +/** @brief Clears the I2C ADDR pending flag. + * @param __HANDLE__ specifies the I2C Handle. + * This parameter can be I2C where x: 1, 2, or 3 to select the I2C peripheral. + * @retval None + */ +#define __DAL_I2C_CLEAR_ADDRFLAG(__HANDLE__) \ + do{ \ + __IO uint32_t tmpreg = 0x00U; \ + tmpreg = (__HANDLE__)->Instance->STS1; \ + tmpreg = (__HANDLE__)->Instance->STS2; \ + UNUSED(tmpreg); \ + } while(0) + +/** @brief Clears the I2C STOPF pending flag. + * @param __HANDLE__ specifies the I2C Handle. + * @retval None + */ +#define __DAL_I2C_CLEAR_STOPFLAG(__HANDLE__) \ + do{ \ + __IO uint32_t tmpreg = 0x00U; \ + tmpreg = (__HANDLE__)->Instance->STS1; \ + SET_BIT((__HANDLE__)->Instance->CTRL1, I2C_CTRL1_I2CEN); \ + UNUSED(tmpreg); \ + } while(0) + +/** @brief Enable the specified I2C peripheral. + * @param __HANDLE__ specifies the I2C Handle. + * @retval None + */ +#define __DAL_I2C_ENABLE(__HANDLE__) SET_BIT((__HANDLE__)->Instance->CTRL1, I2C_CTRL1_I2CEN) + +/** @brief Disable the specified I2C peripheral. + * @param __HANDLE__ specifies the I2C Handle. + * @retval None + */ +#define __DAL_I2C_DISABLE(__HANDLE__) CLEAR_BIT((__HANDLE__)->Instance->CTRL1, I2C_CTRL1_I2CEN) + +/** + * @} + */ + +/* Include I2C DAL Extension module */ +#include "apm32f4xx_dal_i2c_ex.h" + +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup I2C_Exported_Functions + * @{ + */ + +/** @addtogroup I2C_Exported_Functions_Group1 Initialization and de-initialization functions + * @{ + */ +/* Initialization and de-initialization functions******************************/ +DAL_StatusTypeDef DAL_I2C_Init(I2C_HandleTypeDef *hi2c); +DAL_StatusTypeDef DAL_I2C_DeInit(I2C_HandleTypeDef *hi2c); +void DAL_I2C_MspInit(I2C_HandleTypeDef *hi2c); +void DAL_I2C_MspDeInit(I2C_HandleTypeDef *hi2c); + +/* Callbacks Register/UnRegister functions ***********************************/ +#if (USE_DAL_I2C_REGISTER_CALLBACKS == 1) +DAL_StatusTypeDef DAL_I2C_RegisterCallback(I2C_HandleTypeDef *hi2c, DAL_I2C_CallbackIDTypeDef CallbackID, pI2C_CallbackTypeDef pCallback); +DAL_StatusTypeDef DAL_I2C_UnRegisterCallback(I2C_HandleTypeDef *hi2c, DAL_I2C_CallbackIDTypeDef CallbackID); + +DAL_StatusTypeDef DAL_I2C_RegisterAddrCallback(I2C_HandleTypeDef *hi2c, pI2C_AddrCallbackTypeDef pCallback); +DAL_StatusTypeDef DAL_I2C_UnRegisterAddrCallback(I2C_HandleTypeDef *hi2c); +#endif /* USE_DAL_I2C_REGISTER_CALLBACKS */ +/** + * @} + */ + +/** @addtogroup I2C_Exported_Functions_Group2 Input and Output operation functions + * @{ + */ +/* IO operation functions ****************************************************/ +/******* Blocking mode: Polling */ +DAL_StatusTypeDef DAL_I2C_Master_Transmit(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t Timeout); +DAL_StatusTypeDef DAL_I2C_Master_Receive(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t Timeout); +DAL_StatusTypeDef DAL_I2C_Slave_Transmit(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size, uint32_t Timeout); +DAL_StatusTypeDef DAL_I2C_Slave_Receive(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size, uint32_t Timeout); +DAL_StatusTypeDef DAL_I2C_Mem_Write(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size, uint32_t Timeout); +DAL_StatusTypeDef DAL_I2C_Mem_Read(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size, uint32_t Timeout); +DAL_StatusTypeDef DAL_I2C_IsDeviceReady(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint32_t Trials, uint32_t Timeout); + +/******* Non-Blocking mode: Interrupt */ +DAL_StatusTypeDef DAL_I2C_Master_Transmit_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size); +DAL_StatusTypeDef DAL_I2C_Master_Receive_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size); +DAL_StatusTypeDef DAL_I2C_Slave_Transmit_IT(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size); +DAL_StatusTypeDef DAL_I2C_Slave_Receive_IT(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size); +DAL_StatusTypeDef DAL_I2C_Mem_Write_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size); +DAL_StatusTypeDef DAL_I2C_Mem_Read_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size); + +DAL_StatusTypeDef DAL_I2C_Master_Seq_Transmit_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t XferOptions); +DAL_StatusTypeDef DAL_I2C_Master_Seq_Receive_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t XferOptions); +DAL_StatusTypeDef DAL_I2C_Slave_Seq_Transmit_IT(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size, uint32_t XferOptions); +DAL_StatusTypeDef DAL_I2C_Slave_Seq_Receive_IT(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size, uint32_t XferOptions); +DAL_StatusTypeDef DAL_I2C_EnableListen_IT(I2C_HandleTypeDef *hi2c); +DAL_StatusTypeDef DAL_I2C_DisableListen_IT(I2C_HandleTypeDef *hi2c); +DAL_StatusTypeDef DAL_I2C_Master_Abort_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress); + +/******* Non-Blocking mode: DMA */ +DAL_StatusTypeDef DAL_I2C_Master_Transmit_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size); +DAL_StatusTypeDef DAL_I2C_Master_Receive_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size); +DAL_StatusTypeDef DAL_I2C_Slave_Transmit_DMA(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size); +DAL_StatusTypeDef DAL_I2C_Slave_Receive_DMA(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size); +DAL_StatusTypeDef DAL_I2C_Mem_Write_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size); +DAL_StatusTypeDef DAL_I2C_Mem_Read_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size); + +DAL_StatusTypeDef DAL_I2C_Master_Seq_Transmit_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t XferOptions); +DAL_StatusTypeDef DAL_I2C_Master_Seq_Receive_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t XferOptions); +DAL_StatusTypeDef DAL_I2C_Slave_Seq_Transmit_DMA(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size, uint32_t XferOptions); +DAL_StatusTypeDef DAL_I2C_Slave_Seq_Receive_DMA(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size, uint32_t XferOptions); +/** + * @} + */ + +/** @addtogroup I2C_IRQ_Handler_and_Callbacks IRQ Handler and Callbacks + * @{ + */ +/******* I2C IRQHandler and Callbacks used in non blocking modes (Interrupt and DMA) */ +void DAL_I2C_EV_IRQHandler(I2C_HandleTypeDef *hi2c); +void DAL_I2C_ER_IRQHandler(I2C_HandleTypeDef *hi2c); +void DAL_I2C_MasterTxCpltCallback(I2C_HandleTypeDef *hi2c); +void DAL_I2C_MasterRxCpltCallback(I2C_HandleTypeDef *hi2c); +void DAL_I2C_SlaveTxCpltCallback(I2C_HandleTypeDef *hi2c); +void DAL_I2C_SlaveRxCpltCallback(I2C_HandleTypeDef *hi2c); +void DAL_I2C_AddrCallback(I2C_HandleTypeDef *hi2c, uint8_t TransferDirection, uint16_t AddrMatchCode); +void DAL_I2C_ListenCpltCallback(I2C_HandleTypeDef *hi2c); +void DAL_I2C_MemTxCpltCallback(I2C_HandleTypeDef *hi2c); +void DAL_I2C_MemRxCpltCallback(I2C_HandleTypeDef *hi2c); +void DAL_I2C_ErrorCallback(I2C_HandleTypeDef *hi2c); +void DAL_I2C_AbortCpltCallback(I2C_HandleTypeDef *hi2c); +/** + * @} + */ + +/** @addtogroup I2C_Exported_Functions_Group3 Peripheral State, Mode and Error functions + * @{ + */ +/* Peripheral State, Mode and Error functions *********************************/ +DAL_I2C_StateTypeDef DAL_I2C_GetState(I2C_HandleTypeDef *hi2c); +DAL_I2C_ModeTypeDef DAL_I2C_GetMode(I2C_HandleTypeDef *hi2c); +uint32_t DAL_I2C_GetError(I2C_HandleTypeDef *hi2c); + +/** + * @} + */ + +/** + * @} + */ +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/** @defgroup I2C_Private_Constants I2C Private Constants + * @{ + */ +#define I2C_FLAG_MASK 0x0000FFFFU +#define I2C_MIN_PCLK_FREQ_STANDARD 2000000U /*!< 2 MHz */ +#define I2C_MIN_PCLK_FREQ_FAST 4000000U /*!< 4 MHz */ +/** + * @} + */ + +/* Private macros ------------------------------------------------------------*/ +/** @defgroup I2C_Private_Macros I2C Private Macros + * @{ + */ + +#define I2C_MIN_PCLK_FREQ(__PCLK__, __SPEED__) (((__SPEED__) <= 100000U) ? ((__PCLK__) < I2C_MIN_PCLK_FREQ_STANDARD) : ((__PCLK__) < I2C_MIN_PCLK_FREQ_FAST)) +#define I2C_CLKCTRL_CALCULATION(__PCLK__, __SPEED__, __COEFF__) (((((__PCLK__) - 1U)/((__SPEED__) * (__COEFF__))) + 1U) & I2C_CLKCTRL_CLKS) +#define I2C_FREQRANGE(__PCLK__) ((__PCLK__)/1000000U) +#define I2C_RISE_TIME(__FREQRANGE__, __SPEED__) (((__SPEED__) <= 100000U) ? ((__FREQRANGE__) + 1U) : ((((__FREQRANGE__) * 300U) / 1000U) + 1U)) +#define I2C_SPEED_STANDARD(__PCLK__, __SPEED__) ((I2C_CLKCTRL_CALCULATION((__PCLK__), (__SPEED__), 2U) < 4U)? 4U:I2C_CLKCTRL_CALCULATION((__PCLK__), (__SPEED__), 2U)) +#define I2C_SPEED_FAST(__PCLK__, __SPEED__, __DUTYCYCLE__) (((__DUTYCYCLE__) == I2C_DUTYCYCLE_2)? I2C_CLKCTRL_CALCULATION((__PCLK__), (__SPEED__), 3U) : (I2C_CLKCTRL_CALCULATION((__PCLK__), (__SPEED__), 25U) | I2C_DUTYCYCLE_16_9)) +#define I2C_SPEED(__PCLK__, __SPEED__, __DUTYCYCLE__) (((__SPEED__) <= 100000U)? (I2C_SPEED_STANDARD((__PCLK__), (__SPEED__))) : \ + ((I2C_SPEED_FAST((__PCLK__), (__SPEED__), (__DUTYCYCLE__)) & I2C_CLKCTRL_CLKS) == 0U)? 1U : \ + ((I2C_SPEED_FAST((__PCLK__), (__SPEED__), (__DUTYCYCLE__))) | I2C_CLKCTRL_SPEEDCFG)) + +#define I2C_7BIT_ADD_WRITE(__ADDRESS__) ((uint8_t)((__ADDRESS__) & (uint8_t)(~I2C_SADDR1_ADDR0))) +#define I2C_7BIT_ADD_READ(__ADDRESS__) ((uint8_t)((__ADDRESS__) | I2C_SADDR1_ADDR0)) + +#define I2C_10BIT_ADDRESS(__ADDRESS__) ((uint8_t)((uint16_t)((__ADDRESS__) & (uint16_t)0x00FF))) +#define I2C_10BIT_HEADER_WRITE(__ADDRESS__) ((uint8_t)((uint16_t)((uint16_t)(((uint16_t)((__ADDRESS__) & (uint16_t)0x0300)) >> 7) | (uint16_t)0x00F0))) +#define I2C_10BIT_HEADER_READ(__ADDRESS__) ((uint8_t)((uint16_t)((uint16_t)(((uint16_t)((__ADDRESS__) & (uint16_t)0x0300)) >> 7) | (uint16_t)(0x00F1)))) + +#define I2C_MEM_ADD_MSB(__ADDRESS__) ((uint8_t)((uint16_t)(((uint16_t)((__ADDRESS__) & (uint16_t)0xFF00)) >> 8))) +#define I2C_MEM_ADD_LSB(__ADDRESS__) ((uint8_t)((uint16_t)((__ADDRESS__) & (uint16_t)0x00FF))) + +/** @defgroup I2C_IS_RTC_Definitions I2C Private macros to check input parameters + * @{ + */ +#define IS_I2C_DUTY_CYCLE(CYCLE) (((CYCLE) == I2C_DUTYCYCLE_2) || \ + ((CYCLE) == I2C_DUTYCYCLE_16_9)) +#define IS_I2C_ADDRESSING_MODE(ADDRESS) (((ADDRESS) == I2C_ADDRESSINGMODE_7BIT) || \ + ((ADDRESS) == I2C_ADDRESSINGMODE_10BIT)) +#define IS_I2C_DUAL_ADDRESS(ADDRESS) (((ADDRESS) == I2C_DUALADDRESS_DISABLE) || \ + ((ADDRESS) == I2C_DUALADDRESS_ENABLE)) +#define IS_I2C_GENERAL_CALL(CALL) (((CALL) == I2C_GENERALCALL_DISABLE) || \ + ((CALL) == I2C_GENERALCALL_ENABLE)) +#define IS_I2C_NO_STRETCH(STRETCH) (((STRETCH) == I2C_NOSTRETCH_DISABLE) || \ + ((STRETCH) == I2C_NOSTRETCH_ENABLE)) +#define IS_I2C_MEMADD_SIZE(SIZE) (((SIZE) == I2C_MEMADD_SIZE_8BIT) || \ + ((SIZE) == I2C_MEMADD_SIZE_16BIT)) +#define IS_I2C_CLOCK_SPEED(SPEED) (((SPEED) > 0U) && ((SPEED) <= 400000U)) +#define IS_I2C_OWN_ADDRESS1(ADDRESS1) (((ADDRESS1) & 0xFFFFFC00U) == 0U) +#define IS_I2C_OWN_ADDRESS2(ADDRESS2) (((ADDRESS2) & 0xFFFFFF01U) == 0U) +#define IS_I2C_TRANSFER_OPTIONS_REQUEST(REQUEST) (((REQUEST) == I2C_FIRST_FRAME) || \ + ((REQUEST) == I2C_FIRST_AND_NEXT_FRAME) || \ + ((REQUEST) == I2C_NEXT_FRAME) || \ + ((REQUEST) == I2C_FIRST_AND_LAST_FRAME) || \ + ((REQUEST) == I2C_LAST_FRAME) || \ + ((REQUEST) == I2C_LAST_FRAME_NO_STOP) || \ + IS_I2C_TRANSFER_OTHER_OPTIONS_REQUEST(REQUEST)) + +#define IS_I2C_TRANSFER_OTHER_OPTIONS_REQUEST(REQUEST) (((REQUEST) == I2C_OTHER_FRAME) || \ + ((REQUEST) == I2C_OTHER_AND_LAST_FRAME)) + +#define I2C_CHECK_FLAG(__ISR__, __FLAG__) ((((__ISR__) & ((__FLAG__) & I2C_FLAG_MASK)) == ((__FLAG__) & I2C_FLAG_MASK)) ? SET : RESET) +#define I2C_CHECK_IT_SOURCE(__CTRL1__, __IT__) ((((__CTRL1__) & (__IT__)) == (__IT__)) ? SET : RESET) +/** + * @} + */ + +/** + * @} + */ + +/* Private functions ---------------------------------------------------------*/ +/** @defgroup I2C_Private_Functions I2C Private Functions + * @{ + */ + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + + +#endif /* APM32F4xx_DAL_I2C_H */ + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_i2c_ex.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_i2c_ex.h new file mode 100644 index 0000000000..5ba9f3f30b --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_i2c_ex.h @@ -0,0 +1,139 @@ +/** + * + * @file apm32f4xx_dal_i2c_ex.h + * @brief Header file of I2C DAL Extension module. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef APM32F4xx_DAL_I2C_EX_H +#define APM32F4xx_DAL_I2C_EX_H + +#ifdef __cplusplus +extern "C" { +#endif + +#if defined(I2C_FILTER_ANFDIS)&&defined(I2C_FILTER_DNFCFG) +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal_def.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @addtogroup I2CEx + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ +/* Exported constants --------------------------------------------------------*/ +/** @defgroup I2CEx_Exported_Constants I2C Exported Constants + * @{ + */ + +/** @defgroup I2CEx_Analog_Filter I2C Analog Filter + * @{ + */ +#define I2C_ANALOGFILTER_ENABLE 0x00000000U +#define I2C_ANALOGFILTER_DISABLE I2C_FILTER_ANFDIS +/** + * @} + */ + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup I2CEx_Exported_Functions + * @{ + */ + +/** @addtogroup I2CEx_Exported_Functions_Group1 + * @{ + */ +/* Peripheral Control functions ************************************************/ +DAL_StatusTypeDef DAL_I2CEx_ConfigAnalogFilter(I2C_HandleTypeDef *hi2c, uint32_t AnalogFilter); +DAL_StatusTypeDef DAL_I2CEx_ConfigDigitalFilter(I2C_HandleTypeDef *hi2c, uint32_t DigitalFilter); +/** + * @} + */ + +/** + * @} + */ +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/** @defgroup I2CEx_Private_Constants I2C Private Constants + * @{ + */ + +/** + * @} + */ + +/* Private macros ------------------------------------------------------------*/ +/** @defgroup I2CEx_Private_Macros I2C Private Macros + * @{ + */ +#define IS_I2C_ANALOG_FILTER(FILTER) (((FILTER) == I2C_ANALOGFILTER_ENABLE) || \ + ((FILTER) == I2C_ANALOGFILTER_DISABLE)) +#define IS_I2C_DIGITAL_FILTER(FILTER) ((FILTER) <= 0x0000000FU) +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* APM32F4xx_DAL_I2C_EX_H */ + + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_i2s.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_i2s.h new file mode 100644 index 0000000000..ccd7b0b48f --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_i2s.h @@ -0,0 +1,616 @@ +/** + * + * @file apm32f4xx_dal_i2s.h + * @brief Header file of I2S DAL module. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef APM32F4xx_DAL_I2S_H +#define APM32F4xx_DAL_I2S_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal_def.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @addtogroup I2S + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ +/** @defgroup I2S_Exported_Types I2S Exported Types + * @{ + */ + +/** + * @brief I2S Init structure definition + */ +typedef struct +{ + uint32_t Mode; /*!< Specifies the I2S operating mode. + This parameter can be a value of @ref I2S_Mode */ + + uint32_t Standard; /*!< Specifies the standard used for the I2S communication. + This parameter can be a value of @ref I2S_Standard */ + + uint32_t DataFormat; /*!< Specifies the data format for the I2S communication. + This parameter can be a value of @ref I2S_Data_Format */ + + uint32_t MCLKOutput; /*!< Specifies whether the I2S MCLK output is enabled or not. + This parameter can be a value of @ref I2S_MCLK_Output */ + + uint32_t AudioFreq; /*!< Specifies the frequency selected for the I2S communication. + This parameter can be a value of @ref I2S_Audio_Frequency */ + + uint32_t CPOL; /*!< Specifies the idle state of the I2S clock. + This parameter can be a value of @ref I2S_Clock_Polarity */ + + uint32_t ClockSource; /*!< Specifies the I2S Clock Source. + This parameter can be a value of @ref I2S_Clock_Source */ + uint32_t FullDuplexMode; /*!< Specifies the I2S FullDuplex mode. + This parameter can be a value of @ref I2S_FullDuplex_Mode */ +} I2S_InitTypeDef; + +/** + * @brief DAL State structures definition + */ +typedef enum +{ + DAL_I2S_STATE_RESET = 0x00U, /*!< I2S not yet initialized or disabled */ + DAL_I2S_STATE_READY = 0x01U, /*!< I2S initialized and ready for use */ + DAL_I2S_STATE_BUSY = 0x02U, /*!< I2S internal process is ongoing */ + DAL_I2S_STATE_BUSY_TX = 0x03U, /*!< Data Transmission process is ongoing */ + DAL_I2S_STATE_BUSY_RX = 0x04U, /*!< Data Reception process is ongoing */ + DAL_I2S_STATE_BUSY_TX_RX = 0x05U, /*!< Data Transmission and Reception process is ongoing */ + DAL_I2S_STATE_TIMEOUT = 0x06U, /*!< I2S timeout state */ + DAL_I2S_STATE_ERROR = 0x07U /*!< I2S error state */ +} DAL_I2S_StateTypeDef; + +/** + * @brief I2S handle Structure definition + */ +typedef struct __I2S_HandleTypeDef +{ + SPI_TypeDef *Instance; /*!< I2S registers base address */ + + I2S_InitTypeDef Init; /*!< I2S communication parameters */ + + uint16_t *pTxBuffPtr; /*!< Pointer to I2S Tx transfer buffer */ + + __IO uint16_t TxXferSize; /*!< I2S Tx transfer size */ + + __IO uint16_t TxXferCount; /*!< I2S Tx transfer Counter */ + + uint16_t *pRxBuffPtr; /*!< Pointer to I2S Rx transfer buffer */ + + __IO uint16_t RxXferSize; /*!< I2S Rx transfer size */ + + __IO uint16_t RxXferCount; /*!< I2S Rx transfer counter + (This field is initialized at the + same value as transfer size at the + beginning of the transfer and + decremented when a sample is received + NbSamplesReceived = RxBufferSize-RxBufferCount) */ + void (*IrqHandlerISR)(struct __I2S_HandleTypeDef *hi2s); /*!< I2S function pointer on IrqHandler */ + + DMA_HandleTypeDef *hdmatx; /*!< I2S Tx DMA handle parameters */ + + DMA_HandleTypeDef *hdmarx; /*!< I2S Rx DMA handle parameters */ + + __IO DAL_LockTypeDef Lock; /*!< I2S locking object */ + + __IO DAL_I2S_StateTypeDef State; /*!< I2S communication state */ + + __IO uint32_t ErrorCode; /*!< I2S Error code + This parameter can be a value of @ref I2S_Error */ + +#if (USE_DAL_I2S_REGISTER_CALLBACKS == 1U) + void (* TxCpltCallback)(struct __I2S_HandleTypeDef *hi2s); /*!< I2S Tx Completed callback */ + void (* RxCpltCallback)(struct __I2S_HandleTypeDef *hi2s); /*!< I2S Rx Completed callback */ + void (* TxRxCpltCallback)(struct __I2S_HandleTypeDef *hi2s); /*!< I2S TxRx Completed callback */ + void (* TxHalfCpltCallback)(struct __I2S_HandleTypeDef *hi2s); /*!< I2S Tx Half Completed callback */ + void (* RxHalfCpltCallback)(struct __I2S_HandleTypeDef *hi2s); /*!< I2S Rx Half Completed callback */ + void (* TxRxHalfCpltCallback)(struct __I2S_HandleTypeDef *hi2s); /*!< I2S TxRx Half Completed callback */ + void (* ErrorCallback)(struct __I2S_HandleTypeDef *hi2s); /*!< I2S Error callback */ + void (* MspInitCallback)(struct __I2S_HandleTypeDef *hi2s); /*!< I2S Msp Init callback */ + void (* MspDeInitCallback)(struct __I2S_HandleTypeDef *hi2s); /*!< I2S Msp DeInit callback */ + +#endif /* USE_DAL_I2S_REGISTER_CALLBACKS */ +} I2S_HandleTypeDef; + +#if (USE_DAL_I2S_REGISTER_CALLBACKS == 1U) +/** + * @brief DAL I2S Callback ID enumeration definition + */ +typedef enum +{ + DAL_I2S_TX_COMPLETE_CB_ID = 0x00U, /*!< I2S Tx Completed callback ID */ + DAL_I2S_RX_COMPLETE_CB_ID = 0x01U, /*!< I2S Rx Completed callback ID */ + DAL_I2S_TX_RX_COMPLETE_CB_ID = 0x02U, /*!< I2S TxRx Completed callback ID */ + DAL_I2S_TX_HALF_COMPLETE_CB_ID = 0x03U, /*!< I2S Tx Half Completed callback ID */ + DAL_I2S_RX_HALF_COMPLETE_CB_ID = 0x04U, /*!< I2S Rx Half Completed callback ID */ + DAL_I2S_TX_RX_HALF_COMPLETE_CB_ID = 0x05U, /*!< I2S TxRx Half Completed callback ID */ + DAL_I2S_ERROR_CB_ID = 0x06U, /*!< I2S Error callback ID */ + DAL_I2S_MSPINIT_CB_ID = 0x07U, /*!< I2S Msp Init callback ID */ + DAL_I2S_MSPDEINIT_CB_ID = 0x08U /*!< I2S Msp DeInit callback ID */ + +} DAL_I2S_CallbackIDTypeDef; + +/** + * @brief DAL I2S Callback pointer definition + */ +typedef void (*pI2S_CallbackTypeDef)(I2S_HandleTypeDef *hi2s); /*!< pointer to an I2S callback function */ + +#endif /* USE_DAL_I2S_REGISTER_CALLBACKS */ +/** + * @} + */ + +/* Exported constants --------------------------------------------------------*/ +/** @defgroup I2S_Exported_Constants I2S Exported Constants + * @{ + */ +/** @defgroup I2S_Error I2S Error + * @{ + */ +#define DAL_I2S_ERROR_NONE (0x00000000U) /*!< No error */ +#define DAL_I2S_ERROR_TIMEOUT (0x00000001U) /*!< Timeout error */ +#define DAL_I2S_ERROR_OVR (0x00000002U) /*!< OVR error */ +#define DAL_I2S_ERROR_UDR (0x00000004U) /*!< UDR error */ +#define DAL_I2S_ERROR_DMA (0x00000008U) /*!< DMA transfer error */ +#define DAL_I2S_ERROR_PRESCALER (0x00000010U) /*!< Prescaler Calculation error */ +#if (USE_DAL_I2S_REGISTER_CALLBACKS == 1U) +#define DAL_I2S_ERROR_INVALID_CALLBACK (0x00000020U) /*!< Invalid Callback error */ +#endif /* USE_DAL_I2S_REGISTER_CALLBACKS */ +#define DAL_I2S_ERROR_BUSY_LINE_RX (0x00000040U) /*!< Busy Rx Line error */ +/** + * @} + */ + +/** @defgroup I2S_Mode I2S Mode + * @{ + */ +#define I2S_MODE_SLAVE_TX (0x00000000U) +#define I2S_MODE_SLAVE_RX (SPI_I2SCFG_I2SMOD_0) +#define I2S_MODE_MASTER_TX (SPI_I2SCFG_I2SMOD_1) +#define I2S_MODE_MASTER_RX ((SPI_I2SCFG_I2SMOD_0 | SPI_I2SCFG_I2SMOD_1)) +/** + * @} + */ + +/** @defgroup I2S_Standard I2S Standard + * @{ + */ +#define I2S_STANDARD_PHILIPS (0x00000000U) +#define I2S_STANDARD_MSB (SPI_I2SCFG_I2SSSEL_0) +#define I2S_STANDARD_LSB (SPI_I2SCFG_I2SSSEL_1) +#define I2S_STANDARD_PCM_SHORT ((SPI_I2SCFG_I2SSSEL_0 | SPI_I2SCFG_I2SSSEL_1)) +#define I2S_STANDARD_PCM_LONG ((SPI_I2SCFG_I2SSSEL_0 | SPI_I2SCFG_I2SSSEL_1 | SPI_I2SCFG_PFSSEL)) +/** + * @} + */ + +/** @defgroup I2S_Data_Format I2S Data Format + * @{ + */ +#define I2S_DATAFORMAT_16B (0x00000000U) +#define I2S_DATAFORMAT_16B_EXTENDED (SPI_I2SCFG_CHLEN) +#define I2S_DATAFORMAT_24B ((SPI_I2SCFG_CHLEN | SPI_I2SCFG_DATALEN_0)) +#define I2S_DATAFORMAT_32B ((SPI_I2SCFG_CHLEN | SPI_I2SCFG_DATALEN_1)) +/** + * @} + */ + +/** @defgroup I2S_MCLK_Output I2S MCLK Output + * @{ + */ +#define I2S_MCLKOUTPUT_ENABLE (SPI_I2SPSC_MCOEN) +#define I2S_MCLKOUTPUT_DISABLE (0x00000000U) +/** + * @} + */ + +/** @defgroup I2S_Audio_Frequency I2S Audio Frequency + * @{ + */ +#define I2S_AUDIOFREQ_192K (192000U) +#define I2S_AUDIOFREQ_96K (96000U) +#define I2S_AUDIOFREQ_48K (48000U) +#define I2S_AUDIOFREQ_44K (44100U) +#define I2S_AUDIOFREQ_32K (32000U) +#define I2S_AUDIOFREQ_22K (22050U) +#define I2S_AUDIOFREQ_16K (16000U) +#define I2S_AUDIOFREQ_11K (11025U) +#define I2S_AUDIOFREQ_8K (8000U) +#define I2S_AUDIOFREQ_DEFAULT (2U) +/** + * @} + */ + +/** @defgroup I2S_FullDuplex_Mode I2S FullDuplex Mode + * @{ + */ +#define I2S_FULLDUPLEXMODE_DISABLE (0x00000000U) +#define I2S_FULLDUPLEXMODE_ENABLE (0x00000001U) +/** + * @} + */ + +/** @defgroup I2S_Clock_Polarity I2S Clock Polarity + * @{ + */ +#define I2S_CPOL_LOW (0x00000000U) +#define I2S_CPOL_HIGH (SPI_I2SCFG_CPOL) +/** + * @} + */ + +/** @defgroup I2S_Interrupts_Definition I2S Interrupts Definition + * @{ + */ +#define I2S_IT_TXE SPI_CTRL2_TXBEIEN +#define I2S_IT_RXNE SPI_CTRL2_RXBNEIEN +#define I2S_IT_ERR SPI_CTRL2_ERRIEN +/** + * @} + */ + +/** @defgroup I2S_Flags_Definition I2S Flags Definition + * @{ + */ +#define I2S_FLAG_TXE SPI_STS_TXBEFLG +#define I2S_FLAG_RXNE SPI_STS_RXBNEFLG + +#define I2S_FLAG_UDR SPI_STS_UDRFLG +#define I2S_FLAG_OVR SPI_STS_OVRFLG +#define I2S_FLAG_FRE SPI_STS_FFERR + +#define I2S_FLAG_CHSIDE SPI_STS_SCHDIR +#define I2S_FLAG_BSY SPI_STS_BSYFLG + +#define I2S_FLAG_MASK (SPI_STS_RXBNEFLG\ + | SPI_STS_TXBEFLG | SPI_STS_UDRFLG | SPI_STS_OVRFLG | SPI_STS_FFERR | SPI_STS_SCHDIR | SPI_STS_BSYFLG) +/** + * @} + */ + +/** @defgroup I2S_Clock_Source I2S Clock Source Definition + * @{ + */ +#if defined(APM32F405xx) || defined(APM32F407xx) || defined(APM32F417xx) || defined(APM32F465xx) || defined(APM32F411xx) +#define I2S_CLOCK_PLL (0x00000000U) +#define I2S_CLOCK_EXTERNAL (0x00000001U) +#endif /* APM32F405xx || APM32F407xx || APM32F417xx || APM32F465xx || APM32F411xx */ + +/** + * @} + */ + +/** + * @} + */ + +/* Exported macros -----------------------------------------------------------*/ +/** @defgroup I2S_Exported_macros I2S Exported Macros + * @{ + */ + +/** @brief Reset I2S handle state + * @param __HANDLE__ specifies the I2S Handle. + * @retval None + */ +#if (USE_DAL_I2S_REGISTER_CALLBACKS == 1U) +#define __DAL_I2S_RESET_HANDLE_STATE(__HANDLE__) do{ \ + (__HANDLE__)->State = DAL_I2S_STATE_RESET; \ + (__HANDLE__)->MspInitCallback = NULL; \ + (__HANDLE__)->MspDeInitCallback = NULL; \ + } while(0) +#else +#define __DAL_I2S_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = DAL_I2S_STATE_RESET) +#endif /* USE_DAL_I2S_REGISTER_CALLBACKS */ + +/** @brief Enable the specified SPI peripheral (in I2S mode). + * @param __HANDLE__ specifies the I2S Handle. + * @retval None + */ +#define __DAL_I2S_ENABLE(__HANDLE__) (SET_BIT((__HANDLE__)->Instance->I2SCFG, SPI_I2SCFG_I2SEN)) + +/** @brief Disable the specified SPI peripheral (in I2S mode). + * @param __HANDLE__ specifies the I2S Handle. + * @retval None + */ +#define __DAL_I2S_DISABLE(__HANDLE__) (CLEAR_BIT((__HANDLE__)->Instance->I2SCFG, SPI_I2SCFG_I2SEN)) + +/** @brief Enable the specified I2S interrupts. + * @param __HANDLE__ specifies the I2S Handle. + * @param __INTERRUPT__ specifies the interrupt source to enable or disable. + * This parameter can be one of the following values: + * @arg I2S_IT_TXE: Tx buffer empty interrupt enable + * @arg I2S_IT_RXNE: RX buffer not empty interrupt enable + * @arg I2S_IT_ERR: Error interrupt enable + * @retval None + */ +#define __DAL_I2S_ENABLE_IT(__HANDLE__, __INTERRUPT__) (SET_BIT((__HANDLE__)->Instance->CTRL2,(__INTERRUPT__))) + +/** @brief Disable the specified I2S interrupts. + * @param __HANDLE__ specifies the I2S Handle. + * @param __INTERRUPT__ specifies the interrupt source to enable or disable. + * This parameter can be one of the following values: + * @arg I2S_IT_TXE: Tx buffer empty interrupt enable + * @arg I2S_IT_RXNE: RX buffer not empty interrupt enable + * @arg I2S_IT_ERR: Error interrupt enable + * @retval None + */ +#define __DAL_I2S_DISABLE_IT(__HANDLE__, __INTERRUPT__) (CLEAR_BIT((__HANDLE__)->Instance->CTRL2,(__INTERRUPT__))) + +/** @brief Checks if the specified I2S interrupt source is enabled or disabled. + * @param __HANDLE__ specifies the I2S Handle. + * This parameter can be I2S where x: 1, 2, or 3 to select the I2S peripheral. + * @param __INTERRUPT__ specifies the I2S interrupt source to check. + * This parameter can be one of the following values: + * @arg I2S_IT_TXE: Tx buffer empty interrupt enable + * @arg I2S_IT_RXNE: RX buffer not empty interrupt enable + * @arg I2S_IT_ERR: Error interrupt enable + * @retval The new state of __IT__ (TRUE or FALSE). + */ +#define __DAL_I2S_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) ((((__HANDLE__)->Instance->CTRL2\ + & (__INTERRUPT__)) == (__INTERRUPT__)) ? SET : RESET) + +/** @brief Checks whether the specified I2S flag is set or not. + * @param __HANDLE__ specifies the I2S Handle. + * @param __FLAG__ specifies the flag to check. + * This parameter can be one of the following values: + * @arg I2S_FLAG_RXNE: Receive buffer not empty flag + * @arg I2S_FLAG_TXE: Transmit buffer empty flag + * @arg I2S_FLAG_UDR: Underrun flag + * @arg I2S_FLAG_OVR: Overrun flag + * @arg I2S_FLAG_FRE: Frame error flag + * @arg I2S_FLAG_CHSIDE: Channel Side flag + * @arg I2S_FLAG_BSY: Busy flag + * @retval The new state of __FLAG__ (TRUE or FALSE). + */ +#define __DAL_I2S_GET_FLAG(__HANDLE__, __FLAG__) ((((__HANDLE__)->Instance->STS) & (__FLAG__)) == (__FLAG__)) + +/** @brief Clears the I2S OVR pending flag. + * @param __HANDLE__ specifies the I2S Handle. + * @retval None + */ +#define __DAL_I2S_CLEAR_OVRFLAG(__HANDLE__) do{ \ + __IO uint32_t tmpreg_ovr = 0x00U; \ + tmpreg_ovr = (__HANDLE__)->Instance->DATA; \ + tmpreg_ovr = (__HANDLE__)->Instance->STS; \ + UNUSED(tmpreg_ovr); \ + }while(0U) +/** @brief Clears the I2S UDR pending flag. + * @param __HANDLE__ specifies the I2S Handle. + * @retval None + */ +#define __DAL_I2S_CLEAR_UDRFLAG(__HANDLE__) do{\ + __IO uint32_t tmpreg_udr = 0x00U;\ + tmpreg_udr = ((__HANDLE__)->Instance->STS);\ + UNUSED(tmpreg_udr); \ + }while(0U) +/** @brief Flush the I2S DR Register. + * @param __HANDLE__ specifies the I2S Handle. + * @retval None + */ +#define __DAL_I2S_FLUSH_RX_DR(__HANDLE__) do{\ + __IO uint32_t tmpreg_dr = 0x00U;\ + tmpreg_dr = ((__HANDLE__)->Instance->DATA);\ + UNUSED(tmpreg_dr); \ + }while(0U) +/** + * @} + */ + +/* Include I2S Extension module */ +#include "apm32f4xx_dal_i2s_ex.h" + +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup I2S_Exported_Functions + * @{ + */ + +/** @addtogroup I2S_Exported_Functions_Group1 + * @{ + */ +/* Initialization/de-initialization functions ********************************/ +DAL_StatusTypeDef DAL_I2S_Init(I2S_HandleTypeDef *hi2s); +DAL_StatusTypeDef DAL_I2S_DeInit(I2S_HandleTypeDef *hi2s); +void DAL_I2S_MspInit(I2S_HandleTypeDef *hi2s); +void DAL_I2S_MspDeInit(I2S_HandleTypeDef *hi2s); + +/* Callbacks Register/UnRegister functions ***********************************/ +#if (USE_DAL_I2S_REGISTER_CALLBACKS == 1U) +DAL_StatusTypeDef DAL_I2S_RegisterCallback(I2S_HandleTypeDef *hi2s, DAL_I2S_CallbackIDTypeDef CallbackID, + pI2S_CallbackTypeDef pCallback); +DAL_StatusTypeDef DAL_I2S_UnRegisterCallback(I2S_HandleTypeDef *hi2s, DAL_I2S_CallbackIDTypeDef CallbackID); +#endif /* USE_DAL_I2S_REGISTER_CALLBACKS */ +/** + * @} + */ + +/** @addtogroup I2S_Exported_Functions_Group2 + * @{ + */ +/* I/O operation functions ***************************************************/ +/* Blocking mode: Polling */ +DAL_StatusTypeDef DAL_I2S_Transmit(I2S_HandleTypeDef *hi2s, uint16_t *pData, uint16_t Size, uint32_t Timeout); +DAL_StatusTypeDef DAL_I2S_Receive(I2S_HandleTypeDef *hi2s, uint16_t *pData, uint16_t Size, uint32_t Timeout); + +/* Non-Blocking mode: Interrupt */ +DAL_StatusTypeDef DAL_I2S_Transmit_IT(I2S_HandleTypeDef *hi2s, uint16_t *pData, uint16_t Size); +DAL_StatusTypeDef DAL_I2S_Receive_IT(I2S_HandleTypeDef *hi2s, uint16_t *pData, uint16_t Size); +void DAL_I2S_IRQHandler(I2S_HandleTypeDef *hi2s); + +/* Non-Blocking mode: DMA */ +DAL_StatusTypeDef DAL_I2S_Transmit_DMA(I2S_HandleTypeDef *hi2s, uint16_t *pData, uint16_t Size); +DAL_StatusTypeDef DAL_I2S_Receive_DMA(I2S_HandleTypeDef *hi2s, uint16_t *pData, uint16_t Size); + +DAL_StatusTypeDef DAL_I2S_DMAPause(I2S_HandleTypeDef *hi2s); +DAL_StatusTypeDef DAL_I2S_DMAResume(I2S_HandleTypeDef *hi2s); +DAL_StatusTypeDef DAL_I2S_DMAStop(I2S_HandleTypeDef *hi2s); + +/* Callbacks used in non blocking modes (Interrupt and DMA) *******************/ +void DAL_I2S_TxHalfCpltCallback(I2S_HandleTypeDef *hi2s); +void DAL_I2S_TxCpltCallback(I2S_HandleTypeDef *hi2s); +void DAL_I2S_RxHalfCpltCallback(I2S_HandleTypeDef *hi2s); +void DAL_I2S_RxCpltCallback(I2S_HandleTypeDef *hi2s); +void DAL_I2S_ErrorCallback(I2S_HandleTypeDef *hi2s); +/** + * @} + */ + +/** @addtogroup I2S_Exported_Functions_Group3 + * @{ + */ +/* Peripheral Control and State functions ************************************/ +DAL_I2S_StateTypeDef DAL_I2S_GetState(I2S_HandleTypeDef *hi2s); +uint32_t DAL_I2S_GetError(I2S_HandleTypeDef *hi2s); +/** + * @} + */ + +/** + * @} + */ + +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/* Private macros ------------------------------------------------------------*/ +/** @defgroup I2S_Private_Macros I2S Private Macros + * @{ + */ + +/** @brief Check whether the specified SPI flag is set or not. + * @param __STS__ copy of I2S STS register. + * @param __FLAG__ specifies the flag to check. + * This parameter can be one of the following values: + * @arg I2S_FLAG_RXNE: Receive buffer not empty flag + * @arg I2S_FLAG_TXE: Transmit buffer empty flag + * @arg I2S_FLAG_UDR: Underrun error flag + * @arg I2S_FLAG_OVR: Overrun flag + * @arg I2S_FLAG_CHSIDE: Channel side flag + * @arg I2S_FLAG_BSY: Busy flag + * @retval SET or RESET. + */ +#define I2S_CHECK_FLAG(__STS__, __FLAG__) ((((__STS__)\ + & ((__FLAG__) & I2S_FLAG_MASK)) == ((__FLAG__) & I2S_FLAG_MASK)) ? SET : RESET) + +/** @brief Check whether the specified SPI Interrupt is set or not. + * @param __CTRL2__ copy of I2S CTRL2 register. + * @param __INTERRUPT__ specifies the SPI interrupt source to check. + * This parameter can be one of the following values: + * @arg I2S_IT_TXE: Tx buffer empty interrupt enable + * @arg I2S_IT_RXNE: RX buffer not empty interrupt enable + * @arg I2S_IT_ERR: Error interrupt enable + * @retval SET or RESET. + */ +#define I2S_CHECK_IT_SOURCE(__CTRL2__, __INTERRUPT__) ((((__CTRL2__)\ + & (__INTERRUPT__)) == (__INTERRUPT__)) ? SET : RESET) + +/** @brief Checks if I2S Mode parameter is in allowed range. + * @param __MODE__ specifies the I2S Mode. + * This parameter can be a value of @ref I2S_Mode + * @retval None + */ +#define IS_I2S_MODE(__MODE__) (((__MODE__) == I2S_MODE_SLAVE_TX) || \ + ((__MODE__) == I2S_MODE_SLAVE_RX) || \ + ((__MODE__) == I2S_MODE_MASTER_TX) || \ + ((__MODE__) == I2S_MODE_MASTER_RX)) + +#define IS_I2S_STANDARD(__STANDARD__) (((__STANDARD__) == I2S_STANDARD_PHILIPS) || \ + ((__STANDARD__) == I2S_STANDARD_MSB) || \ + ((__STANDARD__) == I2S_STANDARD_LSB) || \ + ((__STANDARD__) == I2S_STANDARD_PCM_SHORT) || \ + ((__STANDARD__) == I2S_STANDARD_PCM_LONG)) + +#define IS_I2S_DATA_FORMAT(__FORMAT__) (((__FORMAT__) == I2S_DATAFORMAT_16B) || \ + ((__FORMAT__) == I2S_DATAFORMAT_16B_EXTENDED) || \ + ((__FORMAT__) == I2S_DATAFORMAT_24B) || \ + ((__FORMAT__) == I2S_DATAFORMAT_32B)) + +#define IS_I2S_MCLK_OUTPUT(__OUTPUT__) (((__OUTPUT__) == I2S_MCLKOUTPUT_ENABLE) || \ + ((__OUTPUT__) == I2S_MCLKOUTPUT_DISABLE)) + +#define IS_I2S_AUDIO_FREQ(__FREQ__) ((((__FREQ__) >= I2S_AUDIOFREQ_8K) && \ + ((__FREQ__) <= I2S_AUDIOFREQ_192K)) || \ + ((__FREQ__) == I2S_AUDIOFREQ_DEFAULT)) + +#define IS_I2S_FULLDUPLEX_MODE(MODE) (((MODE) == I2S_FULLDUPLEXMODE_DISABLE) || \ + ((MODE) == I2S_FULLDUPLEXMODE_ENABLE)) + +/** @brief Checks if I2S Serial clock steady state parameter is in allowed range. + * @param __CPOL__ specifies the I2S serial clock steady state. + * This parameter can be a value of @ref I2S_Clock_Polarity + * @retval None + */ +#define IS_I2S_CPOL(__CPOL__) (((__CPOL__) == I2S_CPOL_LOW) || \ + ((__CPOL__) == I2S_CPOL_HIGH)) + +#if defined(APM32F405xx) || defined(APM32F407xx) || defined(APM32F417xx) || defined(APM32F465xx) || defined(APM32F411xx) +#define IS_I2S_CLOCKSOURCE(CLOCK) (((CLOCK) == I2S_CLOCK_EXTERNAL) ||\ + ((CLOCK) == I2S_CLOCK_PLL)) +#endif /* APM32F405xx || APM32F407xx || APM32F417xx || APM32F465xx || APM32F411xx */ + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* APM32F4xx_DAL_I2S_H */ + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_i2s_ex.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_i2s_ex.h new file mode 100644 index 0000000000..51dc8bb2d2 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_i2s_ex.h @@ -0,0 +1,207 @@ +/** + * + * @file apm32f4xx_dal_i2s_ex.h + * @brief Header file of I2S DAL module. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef APM32F4xx_DAL_I2S_EX_H +#define APM32F4xx_DAL_I2S_EX_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal_def.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ +#if defined(SPI_I2S_FULLDUPLEX_SUPPORT) +/** @addtogroup I2SEx I2SEx + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ +/* Exported constants --------------------------------------------------------*/ +/* Exported macros -----------------------------------------------------------*/ +/** @defgroup I2SEx_Exported_Macros I2S Extended Exported Macros + * @{ + */ + +#define I2SxEXT(__INSTANCE__) ((__INSTANCE__) == (SPI2)? (SPI_TypeDef *)(I2S2ext_BASE): (SPI_TypeDef *)(I2S3ext_BASE)) + +/** @brief Enable or disable the specified I2SExt peripheral. + * @param __HANDLE__ specifies the I2S Handle. + * @retval None + */ +#define __DAL_I2SEXT_ENABLE(__HANDLE__) (I2SxEXT((__HANDLE__)->Instance)->I2SCFG |= SPI_I2SCFG_I2SEN) +#define __DAL_I2SEXT_DISABLE(__HANDLE__) (I2SxEXT((__HANDLE__)->Instance)->I2SCFG &= ~SPI_I2SCFG_I2SEN) + +/** @brief Enable or disable the specified I2SExt interrupts. + * @param __HANDLE__ specifies the I2S Handle. + * @param __INTERRUPT__ specifies the interrupt source to enable or disable. + * This parameter can be one of the following values: + * @arg I2S_IT_TXE: Tx buffer empty interrupt enable + * @arg I2S_IT_RXNE: RX buffer not empty interrupt enable + * @arg I2S_IT_ERR: Error interrupt enable + * @retval None + */ +#define __DAL_I2SEXT_ENABLE_IT(__HANDLE__, __INTERRUPT__) (I2SxEXT((__HANDLE__)->Instance)->CTRL2 |= (__INTERRUPT__)) +#define __DAL_I2SEXT_DISABLE_IT(__HANDLE__, __INTERRUPT__) (I2SxEXT((__HANDLE__)->Instance)->CTRL2 &= ~(__INTERRUPT__)) + +/** @brief Checks if the specified I2SExt interrupt source is enabled or disabled. + * @param __HANDLE__ specifies the I2S Handle. + * This parameter can be I2S where x: 1, 2, or 3 to select the I2S peripheral. + * @param __INTERRUPT__ specifies the I2S interrupt source to check. + * This parameter can be one of the following values: + * @arg I2S_IT_TXE: Tx buffer empty interrupt enable + * @arg I2S_IT_RXNE: RX buffer not empty interrupt enable + * @arg I2S_IT_ERR: Error interrupt enable + * @retval The new state of __IT__ (TRUE or FALSE). + */ +#define __DAL_I2SEXT_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) (((I2SxEXT((__HANDLE__)->Instance)->CTRL2\ + & (__INTERRUPT__)) == (__INTERRUPT__)) ? SET : RESET) + +/** @brief Checks whether the specified I2SExt flag is set or not. + * @param __HANDLE__ specifies the I2S Handle. + * @param __FLAG__ specifies the flag to check. + * This parameter can be one of the following values: + * @arg I2S_FLAG_RXNE: Receive buffer not empty flag + * @arg I2S_FLAG_TXE: Transmit buffer empty flag + * @arg I2S_FLAG_UDR: Underrun flag + * @arg I2S_FLAG_OVR: Overrun flag + * @arg I2S_FLAG_FRE: Frame error flag + * @arg I2S_FLAG_CHSIDE: Channel Side flag + * @arg I2S_FLAG_BSY: Busy flag + * @retval The new state of __FLAG__ (TRUE or FALSE). + */ +#define __DAL_I2SEXT_GET_FLAG(__HANDLE__, __FLAG__) (((I2SxEXT((__HANDLE__)->Instance)->STS) & (__FLAG__)) == (__FLAG__)) + +/** @brief Clears the I2SExt OVR pending flag. + * @param __HANDLE__ specifies the I2S Handle. + * @retval None + */ +#define __DAL_I2SEXT_CLEAR_OVRFLAG(__HANDLE__) do{ \ + __IO uint32_t tmpreg_ovr = 0x00U; \ + tmpreg_ovr = I2SxEXT((__HANDLE__)->Instance)->DATA;\ + tmpreg_ovr = I2SxEXT((__HANDLE__)->Instance)->STS;\ + UNUSED(tmpreg_ovr); \ + }while(0U) +/** @brief Clears the I2SExt UDR pending flag. + * @param __HANDLE__ specifies the I2S Handle. + * @retval None + */ +#define __DAL_I2SEXT_CLEAR_UDRFLAG(__HANDLE__) do{ \ + __IO uint32_t tmpreg_udr = 0x00U; \ + tmpreg_udr = I2SxEXT((__HANDLE__)->Instance)->STS;\ + UNUSED(tmpreg_udr); \ + }while(0U) +/** @brief Flush the I2S and I2SExt DR Registers. + * @param __HANDLE__ specifies the I2S Handle. + * @retval None + */ +#define __DAL_I2SEXT_FLUSH_RX_DR(__HANDLE__) do{ \ + __IO uint32_t tmpreg_dr = 0x00U; \ + tmpreg_dr = I2SxEXT((__HANDLE__)->Instance)->DATA; \ + tmpreg_dr = ((__HANDLE__)->Instance->DATA); \ + UNUSED(tmpreg_dr); \ + }while(0U) +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup I2SEx_Exported_Functions I2S Extended Exported Functions + * @{ + */ + +/** @addtogroup I2SEx_Exported_Functions_Group1 I2S Extended IO operation functions + * @{ + */ + +/* Extended features functions *************************************************/ +/* Blocking mode: Polling */ +DAL_StatusTypeDef DAL_I2SEx_TransmitReceive(I2S_HandleTypeDef *hi2s, uint16_t *pTxData, uint16_t *pRxData, + uint16_t Size, uint32_t Timeout); +/* Non-Blocking mode: Interrupt */ +DAL_StatusTypeDef DAL_I2SEx_TransmitReceive_IT(I2S_HandleTypeDef *hi2s, uint16_t *pTxData, uint16_t *pRxData, + uint16_t Size); +/* Non-Blocking mode: DMA */ +DAL_StatusTypeDef DAL_I2SEx_TransmitReceive_DMA(I2S_HandleTypeDef *hi2s, uint16_t *pTxData, uint16_t *pRxData, + uint16_t Size); +/* I2S IRQHandler and Callbacks used in non blocking modes (Interrupt and DMA) */ +void DAL_I2SEx_FullDuplex_IRQHandler(I2S_HandleTypeDef *hi2s); +void DAL_I2SEx_TxRxHalfCpltCallback(I2S_HandleTypeDef *hi2s); +void DAL_I2SEx_TxRxCpltCallback(I2S_HandleTypeDef *hi2s); +/** + * @} + */ + +/** + * @} + */ +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/* Private macros ------------------------------------------------------------*/ + +/** + * @} + */ + +/* Private functions ---------------------------------------------------------*/ + +/** + * @} + */ + +#endif /* SPI_I2S_FULLDUPLEX_SUPPORT */ +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + + +#endif /* APM32F4xx_DAL_I2S_EX_H */ + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_irda.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_irda.h new file mode 100644 index 0000000000..a01418b2d6 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_irda.h @@ -0,0 +1,706 @@ +/** + * + * @file apm32f4xx_dal_irda.h + * @brief Header file of IRDA DAL module. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef APM32F4xx_DAL_IRDA_H +#define APM32F4xx_DAL_IRDA_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal_def.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @addtogroup IRDA + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ +/** @defgroup IRDA_Exported_Types IRDA Exported Types + * @{ + */ +/** + * @brief IRDA Init Structure definition + */ +typedef struct +{ + uint32_t BaudRate; /*!< This member configures the IRDA communication baud rate. + The baud rate is computed using the following formula: + - IntegerDivider = ((PCLKx) / (8 * (hirda->Init.BaudRate))) + - FractionalDivider = ((IntegerDivider - ((uint32_t) IntegerDivider)) * 8) + 0.5 */ + + uint32_t WordLength; /*!< Specifies the number of data bits transmitted or received in a frame. + This parameter can be a value of @ref IRDA_Word_Length */ + + uint32_t Parity; /*!< Specifies the parity mode. + This parameter can be a value of @ref IRDA_Parity + @note When parity is enabled, the computed parity is inserted + at the MSB position of the transmitted data (9th bit when + the word length is set to 9 data bits; 8th bit when the + word length is set to 8 data bits). */ + + uint32_t Mode; /*!< Specifies whether the Receive or Transmit mode is enabled or disabled. + This parameter can be a value of @ref IRDA_Mode */ + + uint8_t Prescaler; /*!< Specifies the Prescaler value to be programmed + in the IrDA low-power Baud Register, for defining pulse width on which + burst acceptance/rejection will be decided. This value is used as divisor + of system clock to achieve required pulse width. */ + + uint32_t IrDAMode; /*!< Specifies the IrDA mode + This parameter can be a value of @ref IRDA_Low_Power */ +} IRDA_InitTypeDef; + +/** + * @brief DAL IRDA State structures definition + * @note DAL IRDA State value is a combination of 2 different substates: gState and RxState. + * - gState contains IRDA state information related to global Handle management + * and also information related to Tx operations. + * gState value coding follow below described bitmap : + * b7-b6 Error information + * 00 : No Error + * 01 : (Not Used) + * 10 : Timeout + * 11 : Error + * b5 IP initialisation status + * 0 : Reset (IP not initialized) + * 1 : Init done (IP initialized. DAL IRDA Init function already called) + * b4-b3 (not used) + * xx : Should be set to 00 + * b2 Intrinsic process state + * 0 : Ready + * 1 : Busy (IP busy with some configuration or internal operations) + * b1 (not used) + * x : Should be set to 0 + * b0 Tx state + * 0 : Ready (no Tx operation ongoing) + * 1 : Busy (Tx operation ongoing) + * - RxState contains information related to Rx operations. + * RxState value coding follow below described bitmap : + * b7-b6 (not used) + * xx : Should be set to 00 + * b5 IP initialisation status + * 0 : Reset (IP not initialized) + * 1 : Init done (IP initialized) + * b4-b2 (not used) + * xxx : Should be set to 000 + * b1 Rx state + * 0 : Ready (no Rx operation ongoing) + * 1 : Busy (Rx operation ongoing) + * b0 (not used) + * x : Should be set to 0. + */ +typedef enum +{ + DAL_IRDA_STATE_RESET = 0x00U, /*!< Peripheral is not yet Initialized + Value is allowed for gState and RxState */ + DAL_IRDA_STATE_READY = 0x20U, /*!< Peripheral Initialized and ready for use + Value is allowed for gState and RxState */ + DAL_IRDA_STATE_BUSY = 0x24U, /*!< An internal process is ongoing + Value is allowed for gState only */ + DAL_IRDA_STATE_BUSY_TX = 0x21U, /*!< Data Transmission process is ongoing + Value is allowed for gState only */ + DAL_IRDA_STATE_BUSY_RX = 0x22U, /*!< Data Reception process is ongoing + Value is allowed for RxState only */ + DAL_IRDA_STATE_BUSY_TX_RX = 0x23U, /*!< Data Transmission and Reception process is ongoing + Not to be used for neither gState nor RxState. + Value is result of combination (Or) between gState and RxState values */ + DAL_IRDA_STATE_TIMEOUT = 0xA0U, /*!< Timeout state + Value is allowed for gState only */ + DAL_IRDA_STATE_ERROR = 0xE0U /*!< Error + Value is allowed for gState only */ +} DAL_IRDA_StateTypeDef; + +/** + * @brief IRDA handle Structure definition + */ +#if (USE_DAL_IRDA_REGISTER_CALLBACKS == 1) +typedef struct __IRDA_HandleTypeDef +#else +typedef struct +#endif /* USE_DAL_IRDA_REGISTER_CALLBACKS */ +{ + USART_TypeDef *Instance; /*!< USART registers base address */ + + IRDA_InitTypeDef Init; /*!< IRDA communication parameters */ + + const uint8_t *pTxBuffPtr; /*!< Pointer to IRDA Tx transfer Buffer */ + + uint16_t TxXferSize; /*!< IRDA Tx Transfer size */ + + __IO uint16_t TxXferCount; /*!< IRDA Tx Transfer Counter */ + + uint8_t *pRxBuffPtr; /*!< Pointer to IRDA Rx transfer Buffer */ + + uint16_t RxXferSize; /*!< IRDA Rx Transfer size */ + + __IO uint16_t RxXferCount; /*!< IRDA Rx Transfer Counter */ + + DMA_HandleTypeDef *hdmatx; /*!< IRDA Tx DMA Handle parameters */ + + DMA_HandleTypeDef *hdmarx; /*!< IRDA Rx DMA Handle parameters */ + + DAL_LockTypeDef Lock; /*!< Locking object */ + + __IO DAL_IRDA_StateTypeDef gState; /*!< IRDA state information related to global Handle management + and also related to Tx operations. + This parameter can be a value of @ref DAL_IRDA_StateTypeDef */ + + __IO DAL_IRDA_StateTypeDef RxState; /*!< IRDA state information related to Rx operations. + This parameter can be a value of @ref DAL_IRDA_StateTypeDef */ + + __IO uint32_t ErrorCode; /*!< IRDA Error code */ + +#if (USE_DAL_IRDA_REGISTER_CALLBACKS == 1) + void (* TxHalfCpltCallback)(struct __IRDA_HandleTypeDef *hirda); /*!< IRDA Tx Half Complete Callback */ + + void (* TxCpltCallback)(struct __IRDA_HandleTypeDef *hirda); /*!< IRDA Tx Complete Callback */ + + void (* RxHalfCpltCallback)(struct __IRDA_HandleTypeDef *hirda); /*!< IRDA Rx Half Complete Callback */ + + void (* RxCpltCallback)(struct __IRDA_HandleTypeDef *hirda); /*!< IRDA Rx Complete Callback */ + + void (* ErrorCallback)(struct __IRDA_HandleTypeDef *hirda); /*!< IRDA Error Callback */ + + void (* AbortCpltCallback)(struct __IRDA_HandleTypeDef *hirda); /*!< IRDA Abort Complete Callback */ + + void (* AbortTransmitCpltCallback)(struct __IRDA_HandleTypeDef *hirda); /*!< IRDA Abort Transmit Complete Callback */ + + void (* AbortReceiveCpltCallback)(struct __IRDA_HandleTypeDef *hirda); /*!< IRDA Abort Receive Complete Callback */ + + + void (* MspInitCallback)(struct __IRDA_HandleTypeDef *hirda); /*!< IRDA Msp Init callback */ + + void (* MspDeInitCallback)(struct __IRDA_HandleTypeDef *hirda); /*!< IRDA Msp DeInit callback */ +#endif /* USE_DAL_IRDA_REGISTER_CALLBACKS */ + +} IRDA_HandleTypeDef; + +#if (USE_DAL_IRDA_REGISTER_CALLBACKS == 1) +/** + * @brief DAL IRDA Callback ID enumeration definition + */ +typedef enum +{ + DAL_IRDA_TX_HALFCOMPLETE_CB_ID = 0x00U, /*!< IRDA Tx Half Complete Callback ID */ + DAL_IRDA_TX_COMPLETE_CB_ID = 0x01U, /*!< IRDA Tx Complete Callback ID */ + DAL_IRDA_RX_HALFCOMPLETE_CB_ID = 0x02U, /*!< IRDA Rx Half Complete Callback ID */ + DAL_IRDA_RX_COMPLETE_CB_ID = 0x03U, /*!< IRDA Rx Complete Callback ID */ + DAL_IRDA_ERROR_CB_ID = 0x04U, /*!< IRDA Error Callback ID */ + DAL_IRDA_ABORT_COMPLETE_CB_ID = 0x05U, /*!< IRDA Abort Complete Callback ID */ + DAL_IRDA_ABORT_TRANSMIT_COMPLETE_CB_ID = 0x06U, /*!< IRDA Abort Transmit Complete Callback ID */ + DAL_IRDA_ABORT_RECEIVE_COMPLETE_CB_ID = 0x07U, /*!< IRDA Abort Receive Complete Callback ID */ + + DAL_IRDA_MSPINIT_CB_ID = 0x08U, /*!< IRDA MspInit callback ID */ + DAL_IRDA_MSPDEINIT_CB_ID = 0x09U /*!< IRDA MspDeInit callback ID */ + +} DAL_IRDA_CallbackIDTypeDef; + +/** + * @brief DAL IRDA Callback pointer definition + */ +typedef void (*pIRDA_CallbackTypeDef)(IRDA_HandleTypeDef *hirda); /*!< pointer to an IRDA callback function */ + +#endif /* USE_DAL_IRDA_REGISTER_CALLBACKS */ + +/** + * @} + */ + +/* Exported constants --------------------------------------------------------*/ +/** @defgroup IRDA_Exported_Constants IRDA Exported constants + * @{ + */ +/** @defgroup IRDA_Error_Code IRDA Error Code + * @{ + */ +#define DAL_IRDA_ERROR_NONE 0x00000000U /*!< No error */ +#define DAL_IRDA_ERROR_PE 0x00000001U /*!< Parity error */ +#define DAL_IRDA_ERROR_NE 0x00000002U /*!< Noise error */ +#define DAL_IRDA_ERROR_FE 0x00000004U /*!< Frame error */ +#define DAL_IRDA_ERROR_ORE 0x00000008U /*!< Overrun error */ +#define DAL_IRDA_ERROR_DMA 0x00000010U /*!< DMA transfer error */ +#if (USE_DAL_IRDA_REGISTER_CALLBACKS == 1) +#define DAL_IRDA_ERROR_INVALID_CALLBACK ((uint32_t)0x00000020U) /*!< Invalid Callback error */ +#endif /* USE_DAL_IRDA_REGISTER_CALLBACKS */ +/** + * @} + */ + +/** @defgroup IRDA_Word_Length IRDA Word Length + * @{ + */ +#define IRDA_WORDLENGTH_8B 0x00000000U +#define IRDA_WORDLENGTH_9B ((uint32_t)USART_CTRL1_DBLCFG) +/** + * @} + */ + +/** @defgroup IRDA_Parity IRDA Parity + * @{ + */ +#define IRDA_PARITY_NONE 0x00000000U +#define IRDA_PARITY_EVEN ((uint32_t)USART_CTRL1_PCEN) +#define IRDA_PARITY_ODD ((uint32_t)(USART_CTRL1_PCEN | USART_CTRL1_PCFG)) +/** + * @} + */ + +/** @defgroup IRDA_Mode IRDA Transfer Mode + * @{ + */ +#define IRDA_MODE_RX ((uint32_t)USART_CTRL1_RXEN) +#define IRDA_MODE_TX ((uint32_t)USART_CTRL1_TXEN) +#define IRDA_MODE_TX_RX ((uint32_t)(USART_CTRL1_TXEN |USART_CTRL1_RXEN)) +/** + * @} + */ + +/** @defgroup IRDA_Low_Power IRDA Low Power + * @{ + */ +#define IRDA_POWERMODE_LOWPOWER ((uint32_t)USART_CTRL3_IRLPEN) +#define IRDA_POWERMODE_NORMAL 0x00000000U +/** + * @} + */ + +/** @defgroup IRDA_Flags IRDA Flags + * Elements values convention: 0xXXXX + * - 0xXXXX : Flag mask in the SR register + * @{ + */ +#define IRDA_FLAG_TXE ((uint32_t)USART_STS_TXBEFLG) +#define IRDA_FLAG_TC ((uint32_t)USART_STS_TXCFLG) +#define IRDA_FLAG_RXNE ((uint32_t)USART_STS_RXBNEFLG) +#define IRDA_FLAG_IDLE ((uint32_t)USART_STS_IDLEFLG) +#define IRDA_FLAG_ORE ((uint32_t)USART_STS_OVREFLG) +#define IRDA_FLAG_NE ((uint32_t)USART_STS_NEFLG) +#define IRDA_FLAG_FE ((uint32_t)USART_STS_FEFLG) +#define IRDA_FLAG_PE ((uint32_t)USART_STS_PEFLG) +/** + * @} + */ + +/** @defgroup IRDA_Interrupt_definition IRDA Interrupt Definitions + * Elements values convention: 0xY000XXXX + * - XXXX : Interrupt mask in the XX register + * - Y : Interrupt source register (2bits) + * - 01: CTRL1 register + * - 10: CTRL2 register + * - 11: CTRL3 register + * @{ + */ +#define IRDA_IT_PE ((uint32_t)(IRDA_CTRL1_REG_INDEX << 28U | USART_CTRL1_PEIEN)) +#define IRDA_IT_TXE ((uint32_t)(IRDA_CTRL1_REG_INDEX << 28U | USART_CTRL1_TXBEIEN)) +#define IRDA_IT_TC ((uint32_t)(IRDA_CTRL1_REG_INDEX << 28U | USART_CTRL1_TXCIEN)) +#define IRDA_IT_RXNE ((uint32_t)(IRDA_CTRL1_REG_INDEX << 28U | USART_CTRL1_RXBNEIEN)) +#define IRDA_IT_IDLE ((uint32_t)(IRDA_CTRL1_REG_INDEX << 28U | USART_CTRL1_IDLEIEN)) + +#define IRDA_IT_LBD ((uint32_t)(IRDA_CTRL2_REG_INDEX << 28U | USART_CTRL2_LBDIEN)) + +#define IRDA_IT_CTS ((uint32_t)(IRDA_CTRL3_REG_INDEX << 28U | USART_CTRL3_CTSIEN)) +#define IRDA_IT_ERR ((uint32_t)(IRDA_CTRL3_REG_INDEX << 28U | USART_CTRL3_ERRIEN)) +/** + * @} + */ + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ +/** @defgroup IRDA_Exported_Macros IRDA Exported Macros + * @{ + */ + +/** @brief Reset IRDA handle gstate & RxState + * @param __HANDLE__ specifies the IRDA Handle. + * IRDA Handle selects the USARTx or UARTy peripheral + * (USART,UART availability and x,y values depending on device). + * @retval None + */ +#if USE_DAL_IRDA_REGISTER_CALLBACKS == 1 +#define __DAL_IRDA_RESET_HANDLE_STATE(__HANDLE__) do{ \ + (__HANDLE__)->gState = DAL_IRDA_STATE_RESET; \ + (__HANDLE__)->RxState = DAL_IRDA_STATE_RESET; \ + (__HANDLE__)->MspInitCallback = NULL; \ + (__HANDLE__)->MspDeInitCallback = NULL; \ + } while(0U) +#else +#define __DAL_IRDA_RESET_HANDLE_STATE(__HANDLE__) do{ \ + (__HANDLE__)->gState = DAL_IRDA_STATE_RESET; \ + (__HANDLE__)->RxState = DAL_IRDA_STATE_RESET; \ + } while(0U) +#endif /*USE_DAL_IRDA_REGISTER_CALLBACKS */ + +/** @brief Flush the IRDA DATA register + * @param __HANDLE__ specifies the IRDA Handle. + * IRDA Handle selects the USARTx or UARTy peripheral + * (USART,UART availability and x,y values depending on device). + * @retval None + */ +#define __DAL_IRDA_FLUSH_DRREGISTER(__HANDLE__) ((__HANDLE__)->Instance->DATA) + +/** @brief Check whether the specified IRDA flag is set or not. + * @param __HANDLE__ specifies the IRDA Handle. + * IRDA Handle selects the USARTx or UARTy peripheral + * (USART,UART availability and x,y values depending on device). + * @param __FLAG__ specifies the flag to check. + * This parameter can be one of the following values: + * @arg IRDA_FLAG_TXE: Transmit data register empty flag + * @arg IRDA_FLAG_TC: Transmission Complete flag + * @arg IRDA_FLAG_RXNE: Receive data register not empty flag + * @arg IRDA_FLAG_IDLE: Idle Line detection flag + * @arg IRDA_FLAG_ORE: OverRun Error flag + * @arg IRDA_FLAG_NE: Noise Error flag + * @arg IRDA_FLAG_FE: Framing Error flag + * @arg IRDA_FLAG_PE: Parity Error flag + * @retval The new state of __FLAG__ (TRUE or FALSE). + */ +#define __DAL_IRDA_GET_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->STS & (__FLAG__)) == (__FLAG__)) + +/** @brief Clear the specified IRDA pending flag. + * @param __HANDLE__ specifies the IRDA Handle. + * IRDA Handle selects the USARTx or UARTy peripheral + * (USART,UART availability and x,y values depending on device). + * @param __FLAG__ specifies the flag to check. + * This parameter can be any combination of the following values: + * @arg IRDA_FLAG_TC: Transmission Complete flag. + * @arg IRDA_FLAG_RXNE: Receive data register not empty flag. + * + * @note PE (Parity error), FE (Framing error), NE (Noise error), ORE (OverRun + * error) and IDLE (Idle line detected) flags are cleared by software + * sequence: a read operation to USART_STS register followed by a read + * operation to USART_DATA register. + * @note RXNE flag can be also cleared by a read to the USART_DATA register. + * @note TC flag can be also cleared by software sequence: a read operation to + * USART_STS register followed by a write operation to USART_DATA register. + * @note TXE flag is cleared only by a write to the USART_DATA register. + * @retval None + */ +#define __DAL_IRDA_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->STS = ~(__FLAG__)) + +/** @brief Clear the IRDA PE pending flag. + * @param __HANDLE__ specifies the IRDA Handle. + * IRDA Handle selects the USARTx or UARTy peripheral + * (USART,UART availability and x,y values depending on device). + * @retval None + */ +#define __DAL_IRDA_CLEAR_PEFLAG(__HANDLE__) \ + do{ \ + __IO uint32_t tmpreg = 0x00U; \ + tmpreg = (__HANDLE__)->Instance->STS; \ + tmpreg = (__HANDLE__)->Instance->DATA; \ + UNUSED(tmpreg); \ + } while(0U) + +/** @brief Clear the IRDA FE pending flag. + * @param __HANDLE__ specifies the IRDA Handle. + * IRDA Handle selects the USARTx or UARTy peripheral + * (USART,UART availability and x,y values depending on device). + * @retval None + */ +#define __DAL_IRDA_CLEAR_FEFLAG(__HANDLE__) __DAL_IRDA_CLEAR_PEFLAG(__HANDLE__) + +/** @brief Clear the IRDA NE pending flag. + * @param __HANDLE__ specifies the IRDA Handle. + * IRDA Handle selects the USARTx or UARTy peripheral + * (USART,UART availability and x,y values depending on device). + * @retval None + */ +#define __DAL_IRDA_CLEAR_NEFLAG(__HANDLE__) __DAL_IRDA_CLEAR_PEFLAG(__HANDLE__) + +/** @brief Clear the IRDA ORE pending flag. + * @param __HANDLE__ specifies the IRDA Handle. + * IRDA Handle selects the USARTx or UARTy peripheral + * (USART,UART availability and x,y values depending on device). + * @retval None + */ +#define __DAL_IRDA_CLEAR_OREFLAG(__HANDLE__) __DAL_IRDA_CLEAR_PEFLAG(__HANDLE__) + +/** @brief Clear the IRDA IDLE pending flag. + * @param __HANDLE__ specifies the IRDA Handle. + * IRDA Handle selects the USARTx or UARTy peripheral + * (USART,UART availability and x,y values depending on device). + * @retval None + */ +#define __DAL_IRDA_CLEAR_IDLEFLAG(__HANDLE__) __DAL_IRDA_CLEAR_PEFLAG(__HANDLE__) + +/** @brief Enable the specified IRDA interrupt. + * @param __HANDLE__ specifies the IRDA Handle. + * IRDA Handle selects the USARTx or UARTy peripheral + * (USART,UART availability and x,y values depending on device). + * @param __INTERRUPT__ specifies the IRDA interrupt source to enable. + * This parameter can be one of the following values: + * @arg IRDA_IT_TXE: Transmit Data Register empty interrupt + * @arg IRDA_IT_TC: Transmission complete interrupt + * @arg IRDA_IT_RXNE: Receive Data register not empty interrupt + * @arg IRDA_IT_IDLE: Idle line detection interrupt + * @arg IRDA_IT_PE: Parity Error interrupt + * @arg IRDA_IT_ERR: Error interrupt(Frame error, noise error, overrun error) + * @retval None + */ +#define __DAL_IRDA_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((((__INTERRUPT__) >> 28U) == IRDA_CTRL1_REG_INDEX)? ((__HANDLE__)->Instance->CTRL1 |= ((__INTERRUPT__) & IRDA_IT_MASK)): \ + (((__INTERRUPT__) >> 28U) == IRDA_CTRL2_REG_INDEX)? ((__HANDLE__)->Instance->CTRL2 |= ((__INTERRUPT__) & IRDA_IT_MASK)): \ + ((__HANDLE__)->Instance->CTRL3 |= ((__INTERRUPT__) & IRDA_IT_MASK))) +/** @brief Disable the specified IRDA interrupt. + * @param __HANDLE__ specifies the IRDA Handle. + * IRDA Handle selects the USARTx or UARTy peripheral + * (USART,UART availability and x,y values depending on device). + * @param __INTERRUPT__ specifies the IRDA interrupt source to disable. + * This parameter can be one of the following values: + * @arg IRDA_IT_TXE: Transmit Data Register empty interrupt + * @arg IRDA_IT_TC: Transmission complete interrupt + * @arg IRDA_IT_RXNE: Receive Data register not empty interrupt + * @arg IRDA_IT_IDLE: Idle line detection interrupt + * @arg IRDA_IT_PE: Parity Error interrupt + * @arg IRDA_IT_ERR: Error interrupt(Frame error, noise error, overrun error) + * @retval None + */ +#define __DAL_IRDA_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((((__INTERRUPT__) >> 28U) == IRDA_CTRL1_REG_INDEX)? ((__HANDLE__)->Instance->CTRL1 &= ~((__INTERRUPT__) & IRDA_IT_MASK)): \ + (((__INTERRUPT__) >> 28U) == IRDA_CTRL2_REG_INDEX)? ((__HANDLE__)->Instance->CTRL2 &= ~((__INTERRUPT__) & IRDA_IT_MASK)): \ + ((__HANDLE__)->Instance->CTRL3 &= ~ ((__INTERRUPT__) & IRDA_IT_MASK))) + +/** @brief Check whether the specified IRDA interrupt has occurred or not. + * @param __HANDLE__ specifies the IRDA Handle. + * IRDA Handle selects the USARTx or UARTy peripheral + * (USART,UART availability and x,y values depending on device). + * @param __IT__ specifies the IRDA interrupt source to check. + * This parameter can be one of the following values: + * @arg IRDA_IT_TXE: Transmit Data Register empty interrupt + * @arg IRDA_IT_TC: Transmission complete interrupt + * @arg IRDA_IT_RXNE: Receive Data register not empty interrupt + * @arg IRDA_IT_IDLE: Idle line detection interrupt + * @arg IRDA_IT_ERR: Error interrupt + * @arg IRDA_IT_PE: Parity Error interrupt + * @retval The new state of __IT__ (TRUE or FALSE). + */ +#define __DAL_IRDA_GET_IT_SOURCE(__HANDLE__, __IT__) (((((__IT__) >> 28U) == IRDA_CTRL1_REG_INDEX)? (__HANDLE__)->Instance->CTRL1:(((((uint32_t)(__IT__)) >> 28U) == IRDA_CTRL2_REG_INDEX)? \ + (__HANDLE__)->Instance->CTRL2 : (__HANDLE__)->Instance->CTRL3)) & (((uint32_t)(__IT__)) & IRDA_IT_MASK)) + +/** @brief Macro to enable the IRDA's one bit sample method + * @param __HANDLE__ specifies the IRDA Handle. + * @retval None + */ +#define __DAL_IRDA_ONE_BIT_SAMPLE_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CTRL3 |= USART_CTRL3_SAMCFG) + +/** @brief Macro to disable the IRDA's one bit sample method + * @param __HANDLE__ specifies the IRDA Handle. + * @retval None + */ +#define __DAL_IRDA_ONE_BIT_SAMPLE_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CTRL3 &= (uint16_t)~((uint16_t)USART_CTRL3_SAMCFG)) + +/** @brief Enable UART/USART associated to IRDA Handle + * @param __HANDLE__ specifies the IRDA Handle. + * IRDA Handle selects the USARTx or UARTy peripheral + * (USART,UART availability and x,y values depending on device). + * @retval None + */ +#define __DAL_IRDA_ENABLE(__HANDLE__) (SET_BIT((__HANDLE__)->Instance->CTRL1, USART_CTRL1_UEN)) + +/** @brief Disable UART/USART associated to IRDA Handle + * @param __HANDLE__ specifies the IRDA Handle. + * IRDA Handle selects the USARTx or UARTy peripheral + * (USART,UART availability and x,y values depending on device). + * @retval None + */ +#define __DAL_IRDA_DISABLE(__HANDLE__) (CLEAR_BIT((__HANDLE__)->Instance->CTRL1, USART_CTRL1_UEN)) + +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup IRDA_Exported_Functions + * @{ + */ + +/** @addtogroup IRDA_Exported_Functions_Group1 + * @{ + */ +/* Initialization/de-initialization functions **********************************/ +DAL_StatusTypeDef DAL_IRDA_Init(IRDA_HandleTypeDef *hirda); +DAL_StatusTypeDef DAL_IRDA_DeInit(IRDA_HandleTypeDef *hirda); +void DAL_IRDA_MspInit(IRDA_HandleTypeDef *hirda); +void DAL_IRDA_MspDeInit(IRDA_HandleTypeDef *hirda); + +#if (USE_DAL_IRDA_REGISTER_CALLBACKS == 1) +/* Callbacks Register/UnRegister functions ***********************************/ +DAL_StatusTypeDef DAL_IRDA_RegisterCallback(IRDA_HandleTypeDef *hirda, DAL_IRDA_CallbackIDTypeDef CallbackID, pIRDA_CallbackTypeDef pCallback); +DAL_StatusTypeDef DAL_IRDA_UnRegisterCallback(IRDA_HandleTypeDef *hirda, DAL_IRDA_CallbackIDTypeDef CallbackID); +#endif /* USE_DAL_IRDA_REGISTER_CALLBACKS */ + +/** + * @} + */ + +/** @addtogroup IRDA_Exported_Functions_Group2 + * @{ + */ +/* IO operation functions *******************************************************/ +DAL_StatusTypeDef DAL_IRDA_Transmit(IRDA_HandleTypeDef *hirda, const uint8_t *pData, uint16_t Size, uint32_t Timeout); +DAL_StatusTypeDef DAL_IRDA_Receive(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size, uint32_t Timeout); +DAL_StatusTypeDef DAL_IRDA_Transmit_IT(IRDA_HandleTypeDef *hirda, const uint8_t *pData, uint16_t Size); +DAL_StatusTypeDef DAL_IRDA_Receive_IT(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size); +DAL_StatusTypeDef DAL_IRDA_Transmit_DMA(IRDA_HandleTypeDef *hirda, const uint8_t *pData, uint16_t Size); +DAL_StatusTypeDef DAL_IRDA_Receive_DMA(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size); +DAL_StatusTypeDef DAL_IRDA_DMAPause(IRDA_HandleTypeDef *hirda); +DAL_StatusTypeDef DAL_IRDA_DMAResume(IRDA_HandleTypeDef *hirda); +DAL_StatusTypeDef DAL_IRDA_DMAStop(IRDA_HandleTypeDef *hirda); +/* Transfer Abort functions */ +DAL_StatusTypeDef DAL_IRDA_Abort(IRDA_HandleTypeDef *hirda); +DAL_StatusTypeDef DAL_IRDA_AbortTransmit(IRDA_HandleTypeDef *hirda); +DAL_StatusTypeDef DAL_IRDA_AbortReceive(IRDA_HandleTypeDef *hirda); +DAL_StatusTypeDef DAL_IRDA_Abort_IT(IRDA_HandleTypeDef *hirda); +DAL_StatusTypeDef DAL_IRDA_AbortTransmit_IT(IRDA_HandleTypeDef *hirda); +DAL_StatusTypeDef DAL_IRDA_AbortReceive_IT(IRDA_HandleTypeDef *hirda); + +void DAL_IRDA_IRQHandler(IRDA_HandleTypeDef *hirda); +void DAL_IRDA_TxCpltCallback(IRDA_HandleTypeDef *hirda); +void DAL_IRDA_RxCpltCallback(IRDA_HandleTypeDef *hirda); +void DAL_IRDA_TxHalfCpltCallback(IRDA_HandleTypeDef *hirda); +void DAL_IRDA_RxHalfCpltCallback(IRDA_HandleTypeDef *hirda); +void DAL_IRDA_ErrorCallback(IRDA_HandleTypeDef *hirda); +void DAL_IRDA_AbortCpltCallback(IRDA_HandleTypeDef *hirda); +void DAL_IRDA_AbortTransmitCpltCallback(IRDA_HandleTypeDef *hirda); +void DAL_IRDA_AbortReceiveCpltCallback(IRDA_HandleTypeDef *hirda); +/** + * @} + */ + +/** @addtogroup IRDA_Exported_Functions_Group3 + * @{ + */ +/* Peripheral State functions **************************************************/ +DAL_IRDA_StateTypeDef DAL_IRDA_GetState(IRDA_HandleTypeDef *hirda); +uint32_t DAL_IRDA_GetError(IRDA_HandleTypeDef *hirda); +/** + * @} + */ + +/** + * @} + */ + +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/** @defgroup IRDA_Private_Constants IRDA Private Constants + * @{ + */ + +/** @brief IRDA interruptions flag mask + * + */ +#define IRDA_IT_MASK ((uint32_t) USART_CTRL1_PEIEN | USART_CTRL1_TXBEIEN | USART_CTRL1_TXCIEN | USART_CTRL1_RXBNEIEN | \ + USART_CTRL1_IDLEIEN | USART_CTRL2_LBDIEN | USART_CTRL3_CTSIEN | USART_CTRL3_ERRIEN ) + +#define IRDA_CTRL1_REG_INDEX 1U +#define IRDA_CTRL2_REG_INDEX 2U +#define IRDA_CTRL3_REG_INDEX 3U +/** + * @} + */ + +/* Private macros --------------------------------------------------------*/ +/** @defgroup IRDA_Private_Macros IRDA Private Macros + * @{ + */ +#define IS_IRDA_WORD_LENGTH(LENGTH) (((LENGTH) == IRDA_WORDLENGTH_8B) || \ + ((LENGTH) == IRDA_WORDLENGTH_9B)) + +#define IS_IRDA_PARITY(PARITY) (((PARITY) == IRDA_PARITY_NONE) || \ + ((PARITY) == IRDA_PARITY_EVEN) || \ + ((PARITY) == IRDA_PARITY_ODD)) + +#define IS_IRDA_MODE(MODE) ((((MODE) & 0x0000FFF3U) == 0x00U) && ((MODE) != 0x00000000U)) + +#define IS_IRDA_POWERMODE(MODE) (((MODE) == IRDA_POWERMODE_LOWPOWER) || \ + ((MODE) == IRDA_POWERMODE_NORMAL)) + +#define IS_IRDA_BAUDRATE(BAUDRATE) ((BAUDRATE) < 115201U) + +#define IRDA_DIV(_PCLK_, _BAUD_) ((uint32_t)((((uint64_t)(_PCLK_))*25U)/(4U*(((uint64_t)(_BAUD_)))))) + +#define IRDA_DIVMANT(_PCLK_, _BAUD_) (IRDA_DIV((_PCLK_), (_BAUD_))/100U) + +#define IRDA_DIVFRAQ(_PCLK_, _BAUD_) ((((IRDA_DIV((_PCLK_), (_BAUD_)) - (IRDA_DIVMANT((_PCLK_), (_BAUD_)) * 100U)) * 16U) + 50U) / 100U) + +/* UART BR = mantissa + overflow + fraction + = (UART DIVMANT << 4) + (UART DIVFRAQ & 0xF0) + (UART DIVFRAQ & 0x0FU) */ +#define IRDA_BR(_PCLK_, _BAUD_) (((IRDA_DIVMANT((_PCLK_), (_BAUD_)) << 4U) + \ + (IRDA_DIVFRAQ((_PCLK_), (_BAUD_)) & 0xF0U)) + \ + (IRDA_DIVFRAQ((_PCLK_), (_BAUD_)) & 0x0FU)) + +/** + * @} + */ + +/* Private functions ---------------------------------------------------------*/ +/** @defgroup IRDA_Private_Functions IRDA Private Functions + * @{ + */ + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* APM32F4xx_DAL_IRDA_H */ + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_iwdt.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_iwdt.h new file mode 100644 index 0000000000..8cee787c3d --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_iwdt.h @@ -0,0 +1,244 @@ +/** + * + * @file apm32f4xx_dal_iwdt.h + * @brief Header file of IWDT DAL module. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef APM32F4xx_DAL_IWDT_H +#define APM32F4xx_DAL_IWDT_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal_def.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @defgroup IWDT IWDT + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ +/** @defgroup IWDT_Exported_Types IWDT Exported Types + * @{ + */ + +/** + * @brief IWDT Init structure definition + */ +typedef struct +{ + uint32_t Prescaler; /*!< Select the prescaler of the IWDT. + This parameter can be a value of @ref IWDT_Prescaler */ + + uint32_t Reload; /*!< Specifies the IWDT down-counter reload value. + This parameter must be a number between Min_Data = 0 and Max_Data = 0x0FFF */ + +} IWDT_InitTypeDef; + +/** + * @brief IWDT Handle Structure definition + */ +typedef struct +{ + IWDT_TypeDef *Instance; /*!< Register base address */ + + IWDT_InitTypeDef Init; /*!< IWDT required parameters */ +} IWDT_HandleTypeDef; + + +/** + * @} + */ + +/* Exported constants --------------------------------------------------------*/ +/** @defgroup IWDT_Exported_Constants IWDT Exported Constants + * @{ + */ + +/** @defgroup IWDT_Prescaler IWDT Prescaler + * @{ + */ +#define IWDT_PSCESCALER_4 0x00000000u /*!< IWDT prescaler set to 4 */ +#define IWDT_PSCESCALER_8 IWDT_PSC_PSC_0 /*!< IWDT prescaler set to 8 */ +#define IWDT_PSCESCALER_16 IWDT_PSC_PSC_1 /*!< IWDT prescaler set to 16 */ +#define IWDT_PSCESCALER_32 (IWDT_PSC_PSC_1 | IWDT_PSC_PSC_0) /*!< IWDT prescaler set to 32 */ +#define IWDT_PSCESCALER_64 IWDT_PSC_PSC_2 /*!< IWDT prescaler set to 64 */ +#define IWDT_PSCESCALER_128 (IWDT_PSC_PSC_2 | IWDT_PSC_PSC_0) /*!< IWDT prescaler set to 128 */ +#define IWDT_PSCESCALER_256 (IWDT_PSC_PSC_2 | IWDT_PSC_PSC_1) /*!< IWDT prescaler set to 256 */ +/** + * @} + */ + +/** + * @} + */ + +/* Exported macros -----------------------------------------------------------*/ +/** @defgroup IWDT_Exported_Macros IWDT Exported Macros + * @{ + */ + +/** + * @brief Enable the IWDT peripheral. + * @param __HANDLE__ IWDT handle + * @retval None + */ +#define __DAL_IWDT_START(__HANDLE__) WRITE_REG((__HANDLE__)->Instance->KEY, IWDT_KEY_ENABLE) + +/** + * @brief Reload IWDT counter with value defined in the reload register + * (write access to IWDT_PSC and IWDT_CNTRLD registers disabled). + * @param __HANDLE__ IWDT handle + * @retval None + */ +#define __DAL_IWDT_RELOAD_COUNTER(__HANDLE__) WRITE_REG((__HANDLE__)->Instance->KEY, IWDT_KEY_RELOAD) + +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +/** @defgroup IWDT_Exported_Functions IWDT Exported Functions + * @{ + */ + +/** @defgroup IWDT_Exported_Functions_Group1 Initialization and Start functions + * @{ + */ +/* Initialization/Start functions ********************************************/ +DAL_StatusTypeDef DAL_IWDT_Init(IWDT_HandleTypeDef *hiwdt); +/** + * @} + */ + +/** @defgroup IWDT_Exported_Functions_Group2 IO operation functions + * @{ + */ +/* I/O operation functions ****************************************************/ +DAL_StatusTypeDef DAL_IWDT_Refresh(IWDT_HandleTypeDef *hiwdt); +/** + * @} + */ + +/** + * @} + */ + +/* Private constants ---------------------------------------------------------*/ +/** @defgroup IWDT_Private_Constants IWDT Private Constants + * @{ + */ + +/** + * @brief IWDT Key Register BitMask + */ +#define IWDT_KEY_RELOAD 0x0000AAAAu /*!< IWDT Reload Counter Enable */ +#define IWDT_KEY_ENABLE 0x0000CCCCu /*!< IWDT Peripheral Enable */ +#define IWDT_KEY_WRITE_ACCESS_ENABLE 0x00005555u /*!< IWDT KR Write Access Enable */ +#define IWDT_KEY_WRITE_ACCESS_DISABLE 0x00000000u /*!< IWDT KR Write Access Disable */ + +/** + * @} + */ + +/* Private macros ------------------------------------------------------------*/ +/** @defgroup IWDT_Private_Macros IWDT Private Macros + * @{ + */ + +/** + * @brief Enable write access to IWDT_PSC and IWDT_CNTRLD registers. + * @param __HANDLE__ IWDT handle + * @retval None + */ +#define IWDT_ENABLE_WRITE_ACCESS(__HANDLE__) WRITE_REG((__HANDLE__)->Instance->KEY, IWDT_KEY_WRITE_ACCESS_ENABLE) + +/** + * @brief Disable write access to IWDT_PSC and IWDT_CNTRLD registers. + * @param __HANDLE__ IWDT handle + * @retval None + */ +#define IWDT_DISABLE_WRITE_ACCESS(__HANDLE__) WRITE_REG((__HANDLE__)->Instance->KEY, IWDT_KEY_WRITE_ACCESS_DISABLE) + +/** + * @brief Check IWDT prescaler value. + * @param __PRESCALER__ IWDT prescaler value + * @retval None + */ +#define IS_IWDT_PSCESCALER(__PRESCALER__) (((__PRESCALER__) == IWDT_PSCESCALER_4) || \ + ((__PRESCALER__) == IWDT_PSCESCALER_8) || \ + ((__PRESCALER__) == IWDT_PSCESCALER_16) || \ + ((__PRESCALER__) == IWDT_PSCESCALER_32) || \ + ((__PRESCALER__) == IWDT_PSCESCALER_64) || \ + ((__PRESCALER__) == IWDT_PSCESCALER_128)|| \ + ((__PRESCALER__) == IWDT_PSCESCALER_256)) + +/** + * @brief Check IWDT reload value. + * @param __RELOAD__ IWDT reload value + * @retval None + */ +#define IS_IWDT_RELOAD(__RELOAD__) ((__RELOAD__) <= IWDT_CNTRLD_CNTRLD) + + + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + + +#ifdef __cplusplus +} +#endif + +#endif /* APM32F4xx_DAL_IWDT_H */ diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_log.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_log.h new file mode 100644 index 0000000000..a71bf5ab9a --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_log.h @@ -0,0 +1,163 @@ +/** + * @file apm32f4xx_dal_log.h + * @brief Header file containing functions prototypes of LOG DAL library. + * + * @attention + * + * Copyright (C) 2023 Geehy Semiconductor + * + * You may not use this file except in compliance with the + * GEEHY COPYRIGHT NOTICE (GEEHY SOFTWARE PACKAGE LICENSE). + * + * The program is only for reference, which is distributed in the hope + * that it will be useful and instructional for customers to develop + * their software. Unless required by applicable law or agreed to in + * writing, the program is distributed on an "AS IS" BASIS, WITHOUT + * ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied. + * See the GEEHY SOFTWARE PACKAGE LICENSE for the governing permissions + * and limitations under the License. + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef APM32F4XX_DAL_LOG_H +#define APM32F4XX_DAL_LOG_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal_def.h" +#include + +/** @addtogroup APM32F4xx_DAL_Driver + @{ +*/ + +/** @defgroup LOG + @{ +*/ + +/* Exported macro ------------------------------------------------------------*/ +/** @defgroup LOG_Exported_Macros LOG Exported Macros + * @{ + */ + +#if !defined (USE_LOG_COMPONENT) +#define USE_LOG_COMPONENT 0U +#endif + +#define LOG_COLOR_BLACK "30" +#define LOG_COLOR_RED "31" +#define LOG_COLOR_GREEN "32" +#define LOG_COLOR_BROWN "33" +#define LOG_COLOR_BLUE "34" +#define LOG_COLOR_PURPLE "35" +#define LOG_COLOR_CYAN "36" +#define LOG_COLOR_WHITE "37" + +#define LOG_BG_COLOR_BLACK "40" +#define LOG_BG_COLOR_RED "41" +#define LOG_BG_COLOR_GREEN "42" +#define LOG_BG_COLOR_BROWN "43" +#define LOG_BG_COLOR_BLUE "44" +#define LOG_BG_COLOR_PURPLE "45" +#define LOG_BG_COLOR_CYAN "46" +#define LOG_BG_COLOR_WHITE "47" + +#define LOG_COLOR(COLOR) "\033[0;" COLOR "m" +#define LOG_BOLD(COLOR) "\033[1;" COLOR "m" +#define LOG_BG_BLK_COLOR(COLOR) "\033[40;" COLOR "m" +#define LOG_COLOR_RESET "\033[0m" + +#define LOG_COLOR_DEBUG LOG_COLOR(LOG_COLOR_GREEN) +#define LOG_COLOR_INFO LOG_COLOR(LOG_COLOR_BLUE) +#define LOG_COLOR_WARNING LOG_COLOR(LOG_COLOR_BROWN) +#define LOG_COLOR_ERROR LOG_COLOR(LOG_COLOR_RED) + +#define LOG_FORMAT(letter, format) LOG_COLOR_ ## letter "[%s] " format LOG_COLOR_RESET + +/** + * @} + */ + +/* Exported types ------------------------------------------------------------*/ +/** @defgroup LOG_Exported_Types LOG Exported Types + * @{ + */ + +/** + * @brief DAL log level + */ +typedef enum +{ + DAL_LOG_NONE, + DAL_LOG_DEBUG, + DAL_LOG_INFO, + DAL_LOG_WARNING, + DAL_LOG_ERROR, +} DAL_LOG_LEVEL_T; +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup LOG_Exported_Functions + * @{ + */ + +typedef int (*LOG_FUNC_T)(const char *, va_list); + +/* Control functions */ +void DAL_LOG_SetCallback(LOG_FUNC_T callback); +void DAL_LOG_Print(const char *format, ...); + +#define DAL_LOG_LEVEL(level, tag, format, ...) \ + do { \ + if (level == DAL_LOG_INFO) \ + { \ + DAL_LOG_Print(LOG_FORMAT(INFO, format), tag, ##__VA_ARGS__); \ + } \ + else if (level == DAL_LOG_DEBUG) \ + { \ + DAL_LOG_Print(LOG_FORMAT(DEBUG, format), tag, ##__VA_ARGS__); \ + } \ + else if (level == DAL_LOG_WARNING) \ + { \ + DAL_LOG_Print(LOG_FORMAT(WARNING, format), tag, ##__VA_ARGS__); \ + } \ + else if (level == DAL_LOG_ERROR) \ + { \ + DAL_LOG_Print(LOG_FORMAT(ERROR, format), tag, ##__VA_ARGS__); \ + } \ + } while(0U) + +#if (USE_LOG_COMPONENT == 1U) + #define DAL_LOGI(tag, format, ...) DAL_LOG_LEVEL(DAL_LOG_INFO, tag, format, ##__VA_ARGS__) + #define DAL_LOGE(tag, format, ...) DAL_LOG_LEVEL(DAL_LOG_ERROR, tag, format, ##__VA_ARGS__) + #define DAL_LOGW(tag, format, ...) DAL_LOG_LEVEL(DAL_LOG_WARNING, tag, format, ##__VA_ARGS__) + #define DAL_LOGD(tag, format, ...) DAL_LOG_LEVEL(DAL_LOG_DEBUG, tag, format, ##__VA_ARGS__) +#else + #define DAL_LOGI(tag, format, ...) ((void)0U) + #define DAL_LOGE(tag, format, ...) ((void)0U) + #define DAL_LOGW(tag, format, ...) ((void)0U) + #define DAL_LOGD(tag, format, ...) ((void)0U) +#endif /* DAL_LOG_ENABLE */ + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* APM32F4XX_DAL_LOG_H */ diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_mmc.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_mmc.h new file mode 100644 index 0000000000..ce8f79dfd3 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_mmc.h @@ -0,0 +1,771 @@ +/** + * + * @file apm32f4xx_dal_mmc.h + * @brief Header file of MMC DAL module. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef APM32F4xx_DAL_MMC_H +#define APM32F4xx_DAL_MMC_H + +#if defined(SDIO) + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_ddl_sdmmc.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @addtogroup MMC + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ +/** @defgroup MMC_Exported_Types MMC Exported Types + * @{ + */ + +/** @defgroup MMC_Exported_Types_Group1 MMC State enumeration structure + * @{ + */ +typedef enum +{ + DAL_MMC_STATE_RESET = 0x00000000U, /*!< MMC not yet initialized or disabled */ + DAL_MMC_STATE_READY = 0x00000001U, /*!< MMC initialized and ready for use */ + DAL_MMC_STATE_TIMEOUT = 0x00000002U, /*!< MMC Timeout state */ + DAL_MMC_STATE_BUSY = 0x00000003U, /*!< MMC process ongoing */ + DAL_MMC_STATE_PROGRAMMING = 0x00000004U, /*!< MMC Programming State */ + DAL_MMC_STATE_RECEIVING = 0x00000005U, /*!< MMC Receinving State */ + DAL_MMC_STATE_TRANSFER = 0x00000006U, /*!< MMC Transfer State */ + DAL_MMC_STATE_ERROR = 0x0000000FU /*!< MMC is in error state */ +}DAL_MMC_StateTypeDef; +/** + * @} + */ + +/** @defgroup MMC_Exported_Types_Group2 MMC Card State enumeration structure + * @{ + */ +typedef uint32_t DAL_MMC_CardStateTypeDef; + +#define DAL_MMC_CARD_READY 0x00000001U /*!< Card state is ready */ +#define DAL_MMC_CARD_IDENTIFICATION 0x00000002U /*!< Card is in identification state */ +#define DAL_MMC_CARD_STANDBY 0x00000003U /*!< Card is in standby state */ +#define DAL_MMC_CARD_TRANSFER 0x00000004U /*!< Card is in transfer state */ +#define DAL_MMC_CARD_SENDING 0x00000005U /*!< Card is sending an operation */ +#define DAL_MMC_CARD_RECEIVING 0x00000006U /*!< Card is receiving operation information */ +#define DAL_MMC_CARD_PROGRAMMING 0x00000007U /*!< Card is in programming state */ +#define DAL_MMC_CARD_DISCONNECTED 0x00000008U /*!< Card is disconnected */ +#define DAL_MMC_CARD_ERROR 0x000000FFU /*!< Card response Error */ +/** + * @} + */ + +/** @defgroup MMC_Exported_Types_Group3 MMC Handle Structure definition + * @{ + */ +#define MMC_InitTypeDef SDIO_InitTypeDef +#define MMC_TypeDef SDIO_TypeDef + +/** + * @brief MMC Card Information Structure definition + */ +typedef struct +{ + uint32_t CardType; /*!< Specifies the card Type */ + + uint32_t Class; /*!< Specifies the class of the card class */ + + uint32_t RelCardAdd; /*!< Specifies the Relative Card Address */ + + uint32_t BlockNbr; /*!< Specifies the Card Capacity in blocks */ + + uint32_t BlockSize; /*!< Specifies one block size in bytes */ + + uint32_t LogBlockNbr; /*!< Specifies the Card logical Capacity in blocks */ + + uint32_t LogBlockSize; /*!< Specifies logical block size in bytes */ + +}DAL_MMC_CardInfoTypeDef; + +/** + * @brief MMC handle Structure definition + */ +#if defined (USE_DAL_MMC_REGISTER_CALLBACKS) && (USE_DAL_MMC_REGISTER_CALLBACKS == 1U) +typedef struct __MMC_HandleTypeDef +#else +typedef struct +#endif /* USE_DAL_MMC_REGISTER_CALLBACKS */ +{ + MMC_TypeDef *Instance; /*!< MMC registers base address */ + + MMC_InitTypeDef Init; /*!< MMC required parameters */ + + DAL_LockTypeDef Lock; /*!< MMC locking object */ + + uint8_t *pTxBuffPtr; /*!< Pointer to MMC Tx transfer Buffer */ + + uint32_t TxXferSize; /*!< MMC Tx Transfer size */ + + uint8_t *pRxBuffPtr; /*!< Pointer to MMC Rx transfer Buffer */ + + uint32_t RxXferSize; /*!< MMC Rx Transfer size */ + + __IO uint32_t Context; /*!< MMC transfer context */ + + __IO DAL_MMC_StateTypeDef State; /*!< MMC card State */ + + __IO uint32_t ErrorCode; /*!< MMC Card Error codes */ + + DMA_HandleTypeDef *hdmarx; /*!< MMC Rx DMA handle parameters */ + + DMA_HandleTypeDef *hdmatx; /*!< MMC Tx DMA handle parameters */ + + DAL_MMC_CardInfoTypeDef MmcCard; /*!< MMC Card information */ + + uint32_t CSD[4U]; /*!< MMC card specific data table */ + + uint32_t CID[4U]; /*!< MMC card identification number table */ + + uint32_t Ext_CSD[128]; + +#if defined (USE_DAL_MMC_REGISTER_CALLBACKS) && (USE_DAL_MMC_REGISTER_CALLBACKS == 1U) + void (* TxCpltCallback) (struct __MMC_HandleTypeDef *hmmc); + void (* RxCpltCallback) (struct __MMC_HandleTypeDef *hmmc); + void (* ErrorCallback) (struct __MMC_HandleTypeDef *hmmc); + void (* AbortCpltCallback) (struct __MMC_HandleTypeDef *hmmc); + + void (* MspInitCallback) (struct __MMC_HandleTypeDef *hmmc); + void (* MspDeInitCallback) (struct __MMC_HandleTypeDef *hmmc); +#endif +}MMC_HandleTypeDef; + +/** + * @} + */ + +/** @defgroup MMC_Exported_Types_Group4 Card Specific Data: CSD Register + * @{ + */ +typedef struct +{ + __IO uint8_t CSDStruct; /*!< CSD structure */ + __IO uint8_t SysSpecVersion; /*!< System specification version */ + __IO uint8_t Reserved1; /*!< Reserved */ + __IO uint8_t TAAC; /*!< Data read access time 1 */ + __IO uint8_t NSAC; /*!< Data read access time 2 in CLK cycles */ + __IO uint8_t MaxBusClkFrec; /*!< Max. bus clock frequency */ + __IO uint16_t CardComdClasses; /*!< Card command classes */ + __IO uint8_t RdBlockLen; /*!< Max. read data block length */ + __IO uint8_t PartBlockRead; /*!< Partial blocks for read allowed */ + __IO uint8_t WrBlockMisalign; /*!< Write block misalignment */ + __IO uint8_t RdBlockMisalign; /*!< Read block misalignment */ + __IO uint8_t DSRImpl; /*!< DSR implemented */ + __IO uint8_t Reserved2; /*!< Reserved */ + __IO uint32_t DeviceSize; /*!< Device Size */ + __IO uint8_t MaxRdCurrentVDDMin; /*!< Max. read current @ VDD min */ + __IO uint8_t MaxRdCurrentVDDMax; /*!< Max. read current @ VDD max */ + __IO uint8_t MaxWrCurrentVDDMin; /*!< Max. write current @ VDD min */ + __IO uint8_t MaxWrCurrentVDDMax; /*!< Max. write current @ VDD max */ + __IO uint8_t DeviceSizeMul; /*!< Device size multiplier */ + __IO uint8_t EraseGrSize; /*!< Erase group size */ + __IO uint8_t EraseGrMul; /*!< Erase group size multiplier */ + __IO uint8_t WrProtectGrSize; /*!< Write protect group size */ + __IO uint8_t WrProtectGrEnable; /*!< Write protect group enable */ + __IO uint8_t ManDeflECC; /*!< Manufacturer default ECC */ + __IO uint8_t WrSpeedFact; /*!< Write speed factor */ + __IO uint8_t MaxWrBlockLen; /*!< Max. write data block length */ + __IO uint8_t WriteBlockPaPartial; /*!< Partial blocks for write allowed */ + __IO uint8_t Reserved3; /*!< Reserved */ + __IO uint8_t ContentProtectAppli; /*!< Content protection application */ + __IO uint8_t FileFormatGroup; /*!< File format group */ + __IO uint8_t CopyFlag; /*!< Copy flag (OTP) */ + __IO uint8_t PermWrProtect; /*!< Permanent write protection */ + __IO uint8_t TempWrProtect; /*!< Temporary write protection */ + __IO uint8_t FileFormat; /*!< File format */ + __IO uint8_t ECC; /*!< ECC code */ + __IO uint8_t CSD_CRC; /*!< CSD CRC */ + __IO uint8_t Reserved4; /*!< Always 1 */ + +}DAL_MMC_CardCSDTypeDef; +/** + * @} + */ + +/** @defgroup MMC_Exported_Types_Group5 Card Identification Data: CID Register + * @{ + */ +typedef struct +{ + __IO uint8_t ManufacturerID; /*!< Manufacturer ID */ + __IO uint16_t OEM_AppliID; /*!< OEM/Application ID */ + __IO uint32_t ProdName1; /*!< Product Name part1 */ + __IO uint8_t ProdName2; /*!< Product Name part2 */ + __IO uint8_t ProdRev; /*!< Product Revision */ + __IO uint32_t ProdSN; /*!< Product Serial Number */ + __IO uint8_t Reserved1; /*!< Reserved1 */ + __IO uint16_t ManufactDate; /*!< Manufacturing Date */ + __IO uint8_t CID_CRC; /*!< CID CRC */ + __IO uint8_t Reserved2; /*!< Always 1 */ + +}DAL_MMC_CardCIDTypeDef; +/** + * @} + */ + +#if defined (USE_DAL_MMC_REGISTER_CALLBACKS) && (USE_DAL_MMC_REGISTER_CALLBACKS == 1U) +/** @defgroup MMC_Exported_Types_Group6 MMC Callback ID enumeration definition + * @{ + */ +typedef enum +{ + DAL_MMC_TX_CPLT_CB_ID = 0x00U, /*!< MMC Tx Complete Callback ID */ + DAL_MMC_RX_CPLT_CB_ID = 0x01U, /*!< MMC Rx Complete Callback ID */ + DAL_MMC_ERROR_CB_ID = 0x02U, /*!< MMC Error Callback ID */ + DAL_MMC_ABORT_CB_ID = 0x03U, /*!< MMC Abort Callback ID */ + + DAL_MMC_MSP_INIT_CB_ID = 0x10U, /*!< MMC MspInit Callback ID */ + DAL_MMC_MSP_DEINIT_CB_ID = 0x11U /*!< MMC MspDeInit Callback ID */ +}DAL_MMC_CallbackIDTypeDef; +/** + * @} + */ + +/** @defgroup MMC_Exported_Types_Group7 MMC Callback pointer definition + * @{ + */ +typedef void (*pMMC_CallbackTypeDef) (MMC_HandleTypeDef *hmmc); +/** + * @} + */ +#endif +/** + * @} + */ + +/* Exported constants --------------------------------------------------------*/ +/** @defgroup MMC_Exported_Constants Exported Constants + * @{ + */ + +#define MMC_BLOCKSIZE 512U /*!< Block size is 512 bytes */ + +/** @defgroup MMC_Exported_Constansts_Group1 MMC Error status enumeration Structure definition + * @{ + */ +#define DAL_MMC_ERROR_NONE SDMMC_ERROR_NONE /*!< No error */ +#define DAL_MMC_ERROR_CMD_CRC_FAIL SDMMC_ERROR_CMD_CRC_FAIL /*!< Command response received (but CRC check failed) */ +#define DAL_MMC_ERROR_DATA_CRC_FAIL SDMMC_ERROR_DATA_CRC_FAIL /*!< Data block sent/received (CRC check failed) */ +#define DAL_MMC_ERROR_CMD_RSP_TIMEOUT SDMMC_ERROR_CMD_RSP_TIMEOUT /*!< Command response timeout */ +#define DAL_MMC_ERROR_DATA_TIMEOUT SDMMC_ERROR_DATA_TIMEOUT /*!< Data timeout */ +#define DAL_MMC_ERROR_TX_UNDERRUN SDMMC_ERROR_TX_UNDERRUN /*!< Transmit FIFO underrun */ +#define DAL_MMC_ERROR_RX_OVERRUN SDMMC_ERROR_RX_OVERRUN /*!< Receive FIFO overrun */ +#define DAL_MMC_ERROR_ADDR_MISALIGNED SDMMC_ERROR_ADDR_MISALIGNED /*!< Misaligned address */ +#define DAL_MMC_ERROR_BLOCK_LEN_ERR SDMMC_ERROR_BLOCK_LEN_ERR /*!< Transferred block length is not allowed for the card or the + number of transferred bytes does not match the block length */ +#define DAL_MMC_ERROR_ERASE_SEQ_ERR SDMMC_ERROR_ERASE_SEQ_ERR /*!< An error in the sequence of erase command occurs */ +#define DAL_MMC_ERROR_BAD_ERASE_PARAM SDMMC_ERROR_BAD_ERASE_PARAM /*!< An invalid selection for erase groups */ +#define DAL_MMC_ERROR_WRITE_PROT_VIOLATION SDMMC_ERROR_WRITE_PROT_VIOLATION /*!< Attempt to program a write protect block */ +#define DAL_MMC_ERROR_LOCK_UNLOCK_FAILED SDMMC_ERROR_LOCK_UNLOCK_FAILED /*!< Sequence or password error has been detected in unlock + command or if there was an attempt to access a locked card */ +#define DAL_MMC_ERROR_COM_CRC_FAILED SDMMC_ERROR_COM_CRC_FAILED /*!< CRC check of the previous command failed */ +#define DAL_MMC_ERROR_ILLEGAL_CMD SDMMC_ERROR_ILLEGAL_CMD /*!< Command is not legal for the card state */ +#define DAL_MMC_ERROR_CARD_ECC_FAILED SDMMC_ERROR_CARD_ECC_FAILED /*!< Card internal ECC was applied but failed to correct the data */ +#define DAL_MMC_ERROR_CC_ERR SDMMC_ERROR_CC_ERR /*!< Internal card controller error */ +#define DAL_MMC_ERROR_GENERAL_UNKNOWN_ERR SDMMC_ERROR_GENERAL_UNKNOWN_ERR /*!< General or unknown error */ +#define DAL_MMC_ERROR_STREAM_READ_UNDERRUN SDMMC_ERROR_STREAM_READ_UNDERRUN /*!< The card could not sustain data reading in stream rmode */ +#define DAL_MMC_ERROR_STREAM_WRITE_OVERRUN SDMMC_ERROR_STREAM_WRITE_OVERRUN /*!< The card could not sustain data programming in stream mode */ +#define DAL_MMC_ERROR_CID_CSD_OVERWRITE SDMMC_ERROR_CID_CSD_OVERWRITE /*!< CID/CSD overwrite error */ +#define DAL_MMC_ERROR_WP_ERASE_SKIP SDMMC_ERROR_WP_ERASE_SKIP /*!< Only partial address space was erased */ +#define DAL_MMC_ERROR_CARD_ECC_DISABLED SDMMC_ERROR_CARD_ECC_DISABLED /*!< Command has been executed without using internal ECC */ +#define DAL_MMC_ERROR_ERASE_RESET SDMMC_ERROR_ERASE_RESET /*!< Erase sequence was cleared before executing because an out + of erase sequence command was received */ +#define DAL_MMC_ERROR_AKE_SEQ_ERR SDMMC_ERROR_AKE_SEQ_ERR /*!< Error in sequence of authentication */ +#define DAL_MMC_ERROR_INVALID_VOLTRANGE SDMMC_ERROR_INVALID_VOLTRANGE /*!< Error in case of invalid voltage range */ +#define DAL_MMC_ERROR_ADDR_OUT_OF_RANGE SDMMC_ERROR_ADDR_OUT_OF_RANGE /*!< Error when addressed block is out of range */ +#define DAL_MMC_ERROR_REQUEST_NOT_APPLICABLE SDMMC_ERROR_REQUEST_NOT_APPLICABLE /*!< Error when command request is not applicable */ +#define DAL_MMC_ERROR_PARAM SDMMC_ERROR_INVALID_PARAMETER /*!< the used parameter is not valid */ +#define DAL_MMC_ERROR_UNSUPPORTED_FEATURE SDMMC_ERROR_UNSUPPORTED_FEATURE /*!< Error when feature is not insupported */ +#define DAL_MMC_ERROR_BUSY SDMMC_ERROR_BUSY /*!< Error when transfer process is busy */ +#define DAL_MMC_ERROR_DMA SDMMC_ERROR_DMA /*!< Error while DMA transfer */ +#define DAL_MMC_ERROR_TIMEOUT SDMMC_ERROR_TIMEOUT /*!< Timeout error */ + +#if defined (USE_DAL_MMC_REGISTER_CALLBACKS) && (USE_DAL_MMC_REGISTER_CALLBACKS == 1U) +#define DAL_MMC_ERROR_INVALID_CALLBACK SDMMC_ERROR_INVALID_PARAMETER /*!< Invalid callback error */ +#endif +/** + * @} + */ + +/** @defgroup MMC_Exported_Constansts_Group2 MMC context enumeration + * @{ + */ +#define MMC_CONTEXT_NONE 0x00000000U /*!< None */ +#define MMC_CONTEXT_READ_SINGLE_BLOCK 0x00000001U /*!< Read single block operation */ +#define MMC_CONTEXT_READ_MULTIPLE_BLOCK 0x00000002U /*!< Read multiple blocks operation */ +#define MMC_CONTEXT_WRITE_SINGLE_BLOCK 0x00000010U /*!< Write single block operation */ +#define MMC_CONTEXT_WRITE_MULTIPLE_BLOCK 0x00000020U /*!< Write multiple blocks operation */ +#define MMC_CONTEXT_IT 0x00000008U /*!< Process in Interrupt mode */ +#define MMC_CONTEXT_DMA 0x00000080U /*!< Process in DMA mode */ + +/** + * @} + */ + +/** @defgroup MMC_Exported_Constansts_Group3 MMC Voltage mode + * @{ + */ +/** + * @brief + */ +#define MMC_HIGH_VOLTAGE_RANGE 0x80FF8000U /*!< High voltage in byte mode */ +#define MMC_DUAL_VOLTAGE_RANGE 0x80FF8080U /*!< Dual voltage in byte mode */ +#define MMC_LOW_VOLTAGE_RANGE 0x80000080U /*!< Low voltage in byte mode */ +#define EMMC_HIGH_VOLTAGE_RANGE 0xC0FF8000U /*!< High voltage in sector mode */ +#define EMMC_DUAL_VOLTAGE_RANGE 0xC0FF8080U /*!< Dual voltage in sector mode */ +#define EMMC_LOW_VOLTAGE_RANGE 0xC0000080U /*!< Low voltage in sector mode */ +#define MMC_INVALID_VOLTAGE_RANGE 0x0001FF01U +/** + * @} + */ + +/** @defgroup MMC_Exported_Constansts_Group4 MMC Memory Cards + * @{ + */ +#define MMC_LOW_CAPACITY_CARD 0x00000000U /*!< MMC Card Capacity <=2Gbytes */ +#define MMC_HIGH_CAPACITY_CARD 0x00000001U /*!< MMC Card Capacity >2Gbytes and <2Tbytes */ + +/** + * @} + */ + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ +/** @defgroup MMC_Exported_macros MMC Exported Macros + * @brief macros to handle interrupts and specific clock configurations + * @{ + */ +/** @brief Reset MMC handle state. + * @param __HANDLE__ : MMC handle. + * @retval None + */ +#if defined (USE_DAL_MMC_REGISTER_CALLBACKS) && (USE_DAL_MMC_REGISTER_CALLBACKS == 1U) +#define __DAL_MMC_RESET_HANDLE_STATE(__HANDLE__) do { \ + (__HANDLE__)->State = DAL_MMC_STATE_RESET; \ + (__HANDLE__)->MspInitCallback = NULL; \ + (__HANDLE__)->MspDeInitCallback = NULL; \ + } while(0) +#else +#define __DAL_MMC_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = DAL_MMC_STATE_RESET) +#endif + +/** + * @brief Enable the MMC device. + * @retval None + */ +#define __DAL_MMC_ENABLE(__HANDLE__) __SDIO_ENABLE((__HANDLE__)->Instance) + +/** + * @brief Disable the MMC device. + * @retval None + */ +#define __DAL_MMC_DISABLE(__HANDLE__) __SDIO_DISABLE((__HANDLE__)->Instance) + +/** + * @brief Enable the SDMMC DMA transfer. + * @retval None + */ +#define __DAL_MMC_DMA_ENABLE(__HANDLE__) __SDIO_DMA_ENABLE((__HANDLE__)->Instance) + +/** + * @brief Disable the SDMMC DMA transfer. + * @retval None + */ +#define __DAL_MMC_DMA_DISABLE(__HANDLE__) __SDIO_DMA_DISABLE((__HANDLE__)->Instance) + +/** + * @brief Enable the MMC device interrupt. + * @param __HANDLE__: MMC Handle + * @param __INTERRUPT__: specifies the SDMMC interrupt sources to be enabled. + * This parameter can be one or a combination of the following values: + * @arg SDIO_IT_CCRCFAIL: Command response received (CRC check failed) interrupt + * @arg SDIO_IT_DCRCFAIL: Data block sent/received (CRC check failed) interrupt + * @arg SDIO_IT_CTIMEOUT: Command response timeout interrupt + * @arg SDIO_IT_DTIMEOUT: Data timeout interrupt + * @arg SDIO_IT_TXUNDERR: Transmit FIFO underrun error interrupt + * @arg SDIO_IT_RXOVERR: Received FIFO overrun error interrupt + * @arg SDIO_IT_CMDREND: Command response received (CRC check passed) interrupt + * @arg SDIO_IT_CMDSENT: Command sent (no response required) interrupt + * @arg SDIO_IT_DATAEND: Data end (data counter, DATACOUNT, is zero) interrupt + * @arg SDIO_IT_DBCKEND: Data block sent/received (CRC check passed) interrupt + * @arg SDIO_IT_CMDACT: Command transfer in progress interrupt + * @arg SDIO_IT_TXACT: Data transmit in progress interrupt + * @arg SDIO_IT_RXACT: Data receive in progress interrupt + * @arg SDIO_IT_TXFIFOHE: Transmit FIFO Half Empty interrupt + * @arg SDIO_IT_RXFIFOHF: Receive FIFO Half Full interrupt + * @arg SDIO_IT_TXFIFOF: Transmit FIFO full interrupt + * @arg SDIO_IT_RXFIFOF: Receive FIFO full interrupt + * @arg SDIO_IT_TXFIFOE: Transmit FIFO empty interrupt + * @arg SDIO_IT_RXFIFOE: Receive FIFO empty interrupt + * @arg SDIO_IT_TXDAVL: Data available in transmit FIFO interrupt + * @arg SDIO_IT_RXDAVL: Data available in receive FIFO interrupt + * @arg SDIO_IT_SDIOIT: SD I/O interrupt received interrupt + * @retval None + */ +#define __DAL_MMC_ENABLE_IT(__HANDLE__, __INTERRUPT__) __SDIO_ENABLE_IT((__HANDLE__)->Instance, (__INTERRUPT__)) + +/** + * @brief Disable the MMC device interrupt. + * @param __HANDLE__: MMC Handle + * @param __INTERRUPT__: specifies the SDMMC interrupt sources to be disabled. + * This parameter can be one or a combination of the following values: + * @arg SDIO_IT_CCRCFAIL: Command response received (CRC check failed) interrupt + * @arg SDIO_IT_DCRCFAIL: Data block sent/received (CRC check failed) interrupt + * @arg SDIO_IT_CTIMEOUT: Command response timeout interrupt + * @arg SDIO_IT_DTIMEOUT: Data timeout interrupt + * @arg SDIO_IT_TXUNDERR: Transmit FIFO underrun error interrupt + * @arg SDIO_IT_RXOVERR: Received FIFO overrun error interrupt + * @arg SDIO_IT_CMDREND: Command response received (CRC check passed) interrupt + * @arg SDIO_IT_CMDSENT: Command sent (no response required) interrupt + * @arg SDIO_IT_DATAEND: Data end (data counter, DATACOUNT, is zero) interrupt + * @arg SDIO_IT_DBCKEND: Data block sent/received (CRC check passed) interrupt + * @arg SDIO_IT_CMDACT: Command transfer in progress interrupt + * @arg SDIO_IT_TXACT: Data transmit in progress interrupt + * @arg SDIO_IT_RXACT: Data receive in progress interrupt + * @arg SDIO_IT_TXFIFOHE: Transmit FIFO Half Empty interrupt + * @arg SDIO_IT_RXFIFOHF: Receive FIFO Half Full interrupt + * @arg SDIO_IT_TXFIFOF: Transmit FIFO full interrupt + * @arg SDIO_IT_RXFIFOF: Receive FIFO full interrupt + * @arg SDIO_IT_TXFIFOE: Transmit FIFO empty interrupt + * @arg SDIO_IT_RXFIFOE: Receive FIFO empty interrupt + * @arg SDIO_IT_TXDAVL: Data available in transmit FIFO interrupt + * @arg SDIO_IT_RXDAVL: Data available in receive FIFO interrupt + * @arg SDIO_IT_SDIOIT: SD I/O interrupt received interrupt + * @retval None + */ +#define __DAL_MMC_DISABLE_IT(__HANDLE__, __INTERRUPT__) __SDIO_DISABLE_IT((__HANDLE__)->Instance, (__INTERRUPT__)) + +/** + * @brief Check whether the specified MMC flag is set or not. + * @param __HANDLE__: MMC Handle + * @param __FLAG__: specifies the flag to check. + * This parameter can be one of the following values: + * @arg SDIO_FLAG_CCRCFAIL: Command response received (CRC check failed) + * @arg SDIO_FLAG_DCRCFAIL: Data block sent/received (CRC check failed) + * @arg SDIO_FLAG_CTIMEOUT: Command response timeout + * @arg SDIO_FLAG_DTIMEOUT: Data timeout + * @arg SDIO_FLAG_TXUNDERR: Transmit FIFO underrun error + * @arg SDIO_FLAG_RXOVERR: Received FIFO overrun error + * @arg SDIO_FLAG_CMDREND: Command response received (CRC check passed) + * @arg SDIO_FLAG_CMDSENT: Command sent (no response required) + * @arg SDIO_FLAG_DATAEND: Data end (data counter, DATACOUNT, is zero) + * @arg SDIO_FLAG_DBCKEND: Data block sent/received (CRC check passed) + * @arg SDIO_FLAG_CMDACT: Command transfer in progress + * @arg SDIO_FLAG_TXACT: Data transmit in progress + * @arg SDIO_FLAG_RXACT: Data receive in progress + * @arg SDIO_FLAG_TXFIFOHE: Transmit FIFO Half Empty + * @arg SDIO_FLAG_RXFIFOHF: Receive FIFO Half Full + * @arg SDIO_FLAG_TXFIFOF: Transmit FIFO full + * @arg SDIO_FLAG_RXFIFOF: Receive FIFO full + * @arg SDIO_FLAG_TXFIFOE: Transmit FIFO empty + * @arg SDIO_FLAG_RXFIFOE: Receive FIFO empty + * @arg SDIO_FLAG_TXDAVL: Data available in transmit FIFO + * @arg SDIO_FLAG_RXDAVL: Data available in receive FIFO + * @arg SDIO_FLAG_SDIOIT: SD I/O interrupt received + * @retval The new state of MMC FLAG (SET or RESET). + */ +#define __DAL_MMC_GET_FLAG(__HANDLE__, __FLAG__) __SDIO_GET_FLAG((__HANDLE__)->Instance, (__FLAG__)) + +/** + * @brief Clear the MMC's pending flags. + * @param __HANDLE__: MMC Handle + * @param __FLAG__: specifies the flag to clear. + * This parameter can be one or a combination of the following values: + * @arg SDIO_FLAG_CCRCFAIL: Command response received (CRC check failed) + * @arg SDIO_FLAG_DCRCFAIL: Data block sent/received (CRC check failed) + * @arg SDIO_FLAG_CTIMEOUT: Command response timeout + * @arg SDIO_FLAG_DTIMEOUT: Data timeout + * @arg SDIO_FLAG_TXUNDERR: Transmit FIFO underrun error + * @arg SDIO_FLAG_RXOVERR: Received FIFO overrun error + * @arg SDIO_FLAG_CMDREND: Command response received (CRC check passed) + * @arg SDIO_FLAG_CMDSENT: Command sent (no response required) + * @arg SDIO_FLAG_DATAEND: Data end (data counter, DATACOUNT, is zero) + * @arg SDIO_FLAG_DBCKEND: Data block sent/received (CRC check passed) + * @arg SDIO_FLAG_SDIOIT: SD I/O interrupt received + * @retval None + */ +#define __DAL_MMC_CLEAR_FLAG(__HANDLE__, __FLAG__) __SDIO_CLEAR_FLAG((__HANDLE__)->Instance, (__FLAG__)) + +/** + * @brief Check whether the specified MMC interrupt has occurred or not. + * @param __HANDLE__: MMC Handle + * @param __INTERRUPT__: specifies the SDMMC interrupt source to check. + * This parameter can be one of the following values: + * @arg SDIO_IT_CCRCFAIL: Command response received (CRC check failed) interrupt + * @arg SDIO_IT_DCRCFAIL: Data block sent/received (CRC check failed) interrupt + * @arg SDIO_IT_CTIMEOUT: Command response timeout interrupt + * @arg SDIO_IT_DTIMEOUT: Data timeout interrupt + * @arg SDIO_IT_TXUNDERR: Transmit FIFO underrun error interrupt + * @arg SDIO_IT_RXOVERR: Received FIFO overrun error interrupt + * @arg SDIO_IT_CMDREND: Command response received (CRC check passed) interrupt + * @arg SDIO_IT_CMDSENT: Command sent (no response required) interrupt + * @arg SDIO_IT_DATAEND: Data end (data counter, DATACOUNT, is zero) interrupt + * @arg SDIO_IT_DBCKEND: Data block sent/received (CRC check passed) interrupt + * @arg SDIO_IT_CMDACT: Command transfer in progress interrupt + * @arg SDIO_IT_TXACT: Data transmit in progress interrupt + * @arg SDIO_IT_RXACT: Data receive in progress interrupt + * @arg SDIO_IT_TXFIFOHE: Transmit FIFO Half Empty interrupt + * @arg SDIO_IT_RXFIFOHF: Receive FIFO Half Full interrupt + * @arg SDIO_IT_TXFIFOF: Transmit FIFO full interrupt + * @arg SDIO_IT_RXFIFOF: Receive FIFO full interrupt + * @arg SDIO_IT_TXFIFOE: Transmit FIFO empty interrupt + * @arg SDIO_IT_RXFIFOE: Receive FIFO empty interrupt + * @arg SDIO_IT_TXDAVL: Data available in transmit FIFO interrupt + * @arg SDIO_IT_RXDAVL: Data available in receive FIFO interrupt + * @arg SDIO_IT_SDIOIT: SD I/O interrupt received interrupt + * @retval The new state of MMC IT (SET or RESET). + */ +#define __DAL_MMC_GET_IT(__HANDLE__, __INTERRUPT__) __SDIO_GET_IT((__HANDLE__)->Instance, (__INTERRUPT__)) + +/** + * @brief Clear the MMC's interrupt pending bits. + * @param __HANDLE__: MMC Handle + * @param __INTERRUPT__: specifies the interrupt pending bit to clear. + * This parameter can be one or a combination of the following values: + * @arg SDIO_IT_CCRCFAIL: Command response received (CRC check failed) interrupt + * @arg SDIO_IT_DCRCFAIL: Data block sent/received (CRC check failed) interrupt + * @arg SDIO_IT_CTIMEOUT: Command response timeout interrupt + * @arg SDIO_IT_DTIMEOUT: Data timeout interrupt + * @arg SDIO_IT_TXUNDERR: Transmit FIFO underrun error interrupt + * @arg SDIO_IT_RXOVERR: Received FIFO overrun error interrupt + * @arg SDIO_IT_CMDREND: Command response received (CRC check passed) interrupt + * @arg SDIO_IT_CMDSENT: Command sent (no response required) interrupt + * @arg SDIO_IT_DATAEND: Data end (data counter, DATACOUNT, is zero) interrupt + * @arg SDIO_IT_DBCKEND: Data block sent/received (CRC check passed) interrupt + * @arg SDIO_IT_TXFIFOHE: Transmit FIFO Half Empty interrupt + * @arg SDIO_IT_RXFIFOHF: Receive FIFO Half Full interrupt + * @arg SDIO_IT_RXFIFOF: Receive FIFO full interrupt + * @arg SDIO_IT_TXFIFOE: Transmit FIFO empty interrupt + * @arg SDIO_IT_SDIOIT: SD I/O interrupt received interrupt + * @retval None + */ +#define __DAL_MMC_CLEAR_IT(__HANDLE__, __INTERRUPT__) __SDIO_CLEAR_IT((__HANDLE__)->Instance, (__INTERRUPT__)) + +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +/** @defgroup MMC_Exported_Functions MMC Exported Functions + * @{ + */ + +/** @defgroup MMC_Exported_Functions_Group1 Initialization and de-initialization functions + * @{ + */ +DAL_StatusTypeDef DAL_MMC_Init(MMC_HandleTypeDef *hmmc); +DAL_StatusTypeDef DAL_MMC_InitCard(MMC_HandleTypeDef *hmmc); +DAL_StatusTypeDef DAL_MMC_DeInit (MMC_HandleTypeDef *hmmc); +void DAL_MMC_MspInit(MMC_HandleTypeDef *hmmc); +void DAL_MMC_MspDeInit(MMC_HandleTypeDef *hmmc); + +/** + * @} + */ + +/** @defgroup MMC_Exported_Functions_Group2 Input and Output operation functions + * @{ + */ +/* Blocking mode: Polling */ +DAL_StatusTypeDef DAL_MMC_ReadBlocks(MMC_HandleTypeDef *hmmc, uint8_t *pData, uint32_t BlockAdd, uint32_t NumberOfBlocks, uint32_t Timeout); +DAL_StatusTypeDef DAL_MMC_WriteBlocks(MMC_HandleTypeDef *hmmc, uint8_t *pData, uint32_t BlockAdd, uint32_t NumberOfBlocks, uint32_t Timeout); +DAL_StatusTypeDef DAL_MMC_Erase(MMC_HandleTypeDef *hmmc, uint32_t BlockStartAdd, uint32_t BlockEndAdd); +/* Non-Blocking mode: IT */ +DAL_StatusTypeDef DAL_MMC_ReadBlocks_IT(MMC_HandleTypeDef *hmmc, uint8_t *pData, uint32_t BlockAdd, uint32_t NumberOfBlocks); +DAL_StatusTypeDef DAL_MMC_WriteBlocks_IT(MMC_HandleTypeDef *hmmc, uint8_t *pData, uint32_t BlockAdd, uint32_t NumberOfBlocks); +/* Non-Blocking mode: DMA */ +DAL_StatusTypeDef DAL_MMC_ReadBlocks_DMA(MMC_HandleTypeDef *hmmc, uint8_t *pData, uint32_t BlockAdd, uint32_t NumberOfBlocks); +DAL_StatusTypeDef DAL_MMC_WriteBlocks_DMA(MMC_HandleTypeDef *hmmc, uint8_t *pData, uint32_t BlockAdd, uint32_t NumberOfBlocks); + +void DAL_MMC_IRQHandler(MMC_HandleTypeDef *hmmc); + +/* Callback in non blocking modes (DMA) */ +void DAL_MMC_TxCpltCallback(MMC_HandleTypeDef *hmmc); +void DAL_MMC_RxCpltCallback(MMC_HandleTypeDef *hmmc); +void DAL_MMC_ErrorCallback(MMC_HandleTypeDef *hmmc); +void DAL_MMC_AbortCallback(MMC_HandleTypeDef *hmmc); + +#if defined (USE_DAL_MMC_REGISTER_CALLBACKS) && (USE_DAL_MMC_REGISTER_CALLBACKS == 1U) +/* MMC callback registering/unregistering */ +DAL_StatusTypeDef DAL_MMC_RegisterCallback (MMC_HandleTypeDef *hmmc, DAL_MMC_CallbackIDTypeDef CallbackId, pMMC_CallbackTypeDef pCallback); +DAL_StatusTypeDef DAL_MMC_UnRegisterCallback(MMC_HandleTypeDef *hmmc, DAL_MMC_CallbackIDTypeDef CallbackId); +#endif +/** + * @} + */ + +/** @defgroup MMC_Exported_Functions_Group3 Peripheral Control functions + * @{ + */ +DAL_StatusTypeDef DAL_MMC_ConfigWideBusOperation(MMC_HandleTypeDef *hmmc, uint32_t WideMode); +/** + * @} + */ + +/** @defgroup MMC_Exported_Functions_Group4 MMC card related functions + * @{ + */ +DAL_MMC_CardStateTypeDef DAL_MMC_GetCardState(MMC_HandleTypeDef *hmmc); +DAL_StatusTypeDef DAL_MMC_GetCardCID(MMC_HandleTypeDef *hmmc, DAL_MMC_CardCIDTypeDef *pCID); +DAL_StatusTypeDef DAL_MMC_GetCardCSD(MMC_HandleTypeDef *hmmc, DAL_MMC_CardCSDTypeDef *pCSD); +DAL_StatusTypeDef DAL_MMC_GetCardInfo(MMC_HandleTypeDef *hmmc, DAL_MMC_CardInfoTypeDef *pCardInfo); +DAL_StatusTypeDef DAL_MMC_GetCardExtCSD(MMC_HandleTypeDef *hmmc, uint32_t *pExtCSD, uint32_t Timeout); +/** + * @} + */ + +/** @defgroup MMC_Exported_Functions_Group5 Peripheral State and Errors functions + * @{ + */ +DAL_MMC_StateTypeDef DAL_MMC_GetState(MMC_HandleTypeDef *hmmc); +uint32_t DAL_MMC_GetError(MMC_HandleTypeDef *hmmc); +/** + * @} + */ + +/** @defgroup MMC_Exported_Functions_Group6 Peripheral Abort management + * @{ + */ +DAL_StatusTypeDef DAL_MMC_Abort(MMC_HandleTypeDef *hmmc); +DAL_StatusTypeDef DAL_MMC_Abort_IT(MMC_HandleTypeDef *hmmc); +/** + * @} + */ + +/* Private types -------------------------------------------------------------*/ +/** @defgroup MMC_Private_Types MMC Private Types + * @{ + */ + +/** + * @} + */ + +/* Private defines -----------------------------------------------------------*/ +/** @defgroup MMC_Private_Defines MMC Private Defines + * @{ + */ + +/** + * @} + */ + +/* Private variables ---------------------------------------------------------*/ +/** @defgroup MMC_Private_Variables MMC Private Variables + * @{ + */ + +/** + * @} + */ + +/* Private constants ---------------------------------------------------------*/ +/** @defgroup MMC_Private_Constants MMC Private Constants + * @{ + */ + +/** + * @} + */ + +/* Private macros ------------------------------------------------------------*/ +/** @defgroup MMC_Private_Macros MMC Private Macros + * @{ + */ + +/** + * @} + */ + +/* Private functions prototypes ----------------------------------------------*/ +/** @defgroup MMC_Private_Functions_Prototypes MMC Private Functions Prototypes + * @{ + */ + +/** + * @} + */ + +/* Private functions ---------------------------------------------------------*/ +/** @defgroup MMC_Private_Functions MMC Private Functions + * @{ + */ + +/** + * @} + */ + + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* SDIO */ + +#endif /* APM32F4xx_DAL_MMC_H */ diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_nand.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_nand.h new file mode 100644 index 0000000000..47c06998d5 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_nand.h @@ -0,0 +1,407 @@ +/** + * + * @file apm32f4xx_dal_nand.h + * @brief Header file of NAND DAL module. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef APM32F4xx_DAL_NAND_H +#define APM32F4xx_DAL_NAND_H + +#ifdef __cplusplus +extern "C" { +#endif + +#if defined(SMC_Bank2_3) + +/* Includes ------------------------------------------------------------------*/ +#if defined(SMC_Bank2_3) +#include "apm32f4xx_ddl_smc.h" +#endif /* SMC_Bank2_3 */ + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @addtogroup NAND + * @{ + */ + +/* Exported typedef ----------------------------------------------------------*/ +/* Exported types ------------------------------------------------------------*/ +/** @defgroup NAND_Exported_Types NAND Exported Types + * @{ + */ + +/** + * @brief DAL NAND State structures definition + */ +typedef enum +{ + DAL_NAND_STATE_RESET = 0x00U, /*!< NAND not yet initialized or disabled */ + DAL_NAND_STATE_READY = 0x01U, /*!< NAND initialized and ready for use */ + DAL_NAND_STATE_BUSY = 0x02U, /*!< NAND internal process is ongoing */ + DAL_NAND_STATE_ERROR = 0x03U /*!< NAND error state */ +} DAL_NAND_StateTypeDef; + +/** + * @brief NAND Memory electronic signature Structure definition + */ +typedef struct +{ + /*State = DAL_NAND_STATE_RESET; \ + (__HANDLE__)->MspInitCallback = NULL; \ + (__HANDLE__)->MspDeInitCallback = NULL; \ + } while(0) +#else +#define __DAL_NAND_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = DAL_NAND_STATE_RESET) +#endif /* USE_DAL_NAND_REGISTER_CALLBACKS */ + +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup NAND_Exported_Functions NAND Exported Functions + * @{ + */ + +/** @addtogroup NAND_Exported_Functions_Group1 Initialization and de-initialization functions + * @{ + */ + +/* Initialization/de-initialization functions ********************************/ +DAL_StatusTypeDef DAL_NAND_Init(NAND_HandleTypeDef *hnand, FMC_NAND_PCC_TimingTypeDef *ComSpace_Timing, + FMC_NAND_PCC_TimingTypeDef *AttSpace_Timing); +DAL_StatusTypeDef DAL_NAND_DeInit(NAND_HandleTypeDef *hnand); + +DAL_StatusTypeDef DAL_NAND_ConfigDevice(NAND_HandleTypeDef *hnand, NAND_DeviceConfigTypeDef *pDeviceConfig); + +DAL_StatusTypeDef DAL_NAND_Read_ID(NAND_HandleTypeDef *hnand, NAND_IDTypeDef *pNAND_ID); + +void DAL_NAND_MspInit(NAND_HandleTypeDef *hnand); +void DAL_NAND_MspDeInit(NAND_HandleTypeDef *hnand); +void DAL_NAND_IRQHandler(NAND_HandleTypeDef *hnand); +void DAL_NAND_ITCallback(NAND_HandleTypeDef *hnand); + +/** + * @} + */ + +/** @addtogroup NAND_Exported_Functions_Group2 Input and Output functions + * @{ + */ + +/* IO operation functions ****************************************************/ +DAL_StatusTypeDef DAL_NAND_Reset(NAND_HandleTypeDef *hnand); + +DAL_StatusTypeDef DAL_NAND_Read_Page_8b(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress, uint8_t *pBuffer, + uint32_t NumPageToRead); +DAL_StatusTypeDef DAL_NAND_Write_Page_8b(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress, uint8_t *pBuffer, + uint32_t NumPageToWrite); +DAL_StatusTypeDef DAL_NAND_Read_SpareArea_8b(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress, + uint8_t *pBuffer, uint32_t NumSpareAreaToRead); +DAL_StatusTypeDef DAL_NAND_Write_SpareArea_8b(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress, + uint8_t *pBuffer, uint32_t NumSpareAreaTowrite); + +DAL_StatusTypeDef DAL_NAND_Read_Page_16b(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress, uint16_t *pBuffer, + uint32_t NumPageToRead); +DAL_StatusTypeDef DAL_NAND_Write_Page_16b(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress, uint16_t *pBuffer, + uint32_t NumPageToWrite); +DAL_StatusTypeDef DAL_NAND_Read_SpareArea_16b(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress, + uint16_t *pBuffer, uint32_t NumSpareAreaToRead); +DAL_StatusTypeDef DAL_NAND_Write_SpareArea_16b(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress, + uint16_t *pBuffer, uint32_t NumSpareAreaTowrite); + +DAL_StatusTypeDef DAL_NAND_Erase_Block(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress); + +uint32_t DAL_NAND_Address_Inc(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress); + +#if (USE_DAL_NAND_REGISTER_CALLBACKS == 1) +/* NAND callback registering/unregistering */ +DAL_StatusTypeDef DAL_NAND_RegisterCallback(NAND_HandleTypeDef *hnand, DAL_NAND_CallbackIDTypeDef CallbackId, + pNAND_CallbackTypeDef pCallback); +DAL_StatusTypeDef DAL_NAND_UnRegisterCallback(NAND_HandleTypeDef *hnand, DAL_NAND_CallbackIDTypeDef CallbackId); +#endif /* USE_DAL_NAND_REGISTER_CALLBACKS */ + +/** + * @} + */ + +/** @addtogroup NAND_Exported_Functions_Group3 Peripheral Control functions + * @{ + */ + +/* NAND Control functions ****************************************************/ +DAL_StatusTypeDef DAL_NAND_ECC_Enable(NAND_HandleTypeDef *hnand); +DAL_StatusTypeDef DAL_NAND_ECC_Disable(NAND_HandleTypeDef *hnand); +DAL_StatusTypeDef DAL_NAND_GetECC(NAND_HandleTypeDef *hnand, uint32_t *ECCval, uint32_t Timeout); + +/** + * @} + */ + +/** @addtogroup NAND_Exported_Functions_Group4 Peripheral State functions + * @{ + */ +/* NAND State functions *******************************************************/ +DAL_NAND_StateTypeDef DAL_NAND_GetState(NAND_HandleTypeDef *hnand); +uint32_t DAL_NAND_Read_Status(NAND_HandleTypeDef *hnand); +/** + * @} + */ + +/** + * @} + */ + +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/** @defgroup NAND_Private_Constants NAND Private Constants + * @{ + */ + +#define NAND_DEVICE 0x80000000UL + +#define NAND_WRITE_TIMEOUT 0x01000000UL + +#define CMD_AREA (1UL<<16U) /* A16 = CLE high */ +#define ADDR_AREA (1UL<<17U) /* A17 = ALE high */ + +#define NAND_CMD_AREA_A ((uint8_t)0x00) +#define NAND_CMD_AREA_B ((uint8_t)0x01) +#define NAND_CMD_AREA_C ((uint8_t)0x50) +#define NAND_CMD_AREA_TRUE1 ((uint8_t)0x30) + +#define NAND_CMD_WRITE0 ((uint8_t)0x80) +#define NAND_CMD_WRITE_TRUE1 ((uint8_t)0x10) +#define NAND_CMD_ERASE0 ((uint8_t)0x60) +#define NAND_CMD_ERASE1 ((uint8_t)0xD0) +#define NAND_CMD_READID ((uint8_t)0x90) +#define NAND_CMD_STATUS ((uint8_t)0x70) +#define NAND_CMD_LOCK_STATUS ((uint8_t)0x7A) +#define NAND_CMD_RESET ((uint8_t)0xFF) + +/* NAND memory status */ +#define NAND_VALID_ADDRESS 0x00000100UL +#define NAND_INVALID_ADDRESS 0x00000200UL +#define NAND_TIMEOUT_ERROR 0x00000400UL +#define NAND_BUSY 0x00000000UL +#define NAND_ERROR 0x00000001UL +#define NAND_READY 0x00000040UL +/** + * @} + */ + +/* Private macros ------------------------------------------------------------*/ +/** @defgroup NAND_Private_Macros NAND Private Macros + * @{ + */ + +/** + * @brief NAND memory address computation. + * @param __ADDRESS__ NAND memory address. + * @param __HANDLE__ NAND handle. + * @retval NAND Raw address value + */ +#define ARRAY_ADDRESS(__ADDRESS__ , __HANDLE__) ((__ADDRESS__)->Page + \ + (((__ADDRESS__)->Block + \ + (((__ADDRESS__)->Plane) * \ + ((__HANDLE__)->Config.PlaneSize))) * \ + ((__HANDLE__)->Config.BlockSize))) + +/** + * @brief NAND memory Column address computation. + * @param __HANDLE__ NAND handle. + * @retval NAND Raw address value + */ +#define COLUMN_ADDRESS( __HANDLE__) ((__HANDLE__)->Config.PageSize) + +/** + * @brief NAND memory address cycling. + * @param __ADDRESS__ NAND memory address. + * @retval NAND address cycling value. + */ +#define ADDR_1ST_CYCLE(__ADDRESS__) (uint8_t)(__ADDRESS__) /* 1st addressing cycle */ +#define ADDR_2ND_CYCLE(__ADDRESS__) (uint8_t)((__ADDRESS__) >> 8) /* 2nd addressing cycle */ +#define ADDR_3RD_CYCLE(__ADDRESS__) (uint8_t)((__ADDRESS__) >> 16) /* 3rd addressing cycle */ +#define ADDR_4TH_CYCLE(__ADDRESS__) (uint8_t)((__ADDRESS__) >> 24) /* 4th addressing cycle */ + +/** + * @brief NAND memory Columns cycling. + * @param __ADDRESS__ NAND memory address. + * @retval NAND Column address cycling value. + */ +#define COLUMN_1ST_CYCLE(__ADDRESS__) (uint8_t)((__ADDRESS__) & 0xFFU) /* 1st Column addressing cycle */ +#define COLUMN_2ND_CYCLE(__ADDRESS__) (uint8_t)((__ADDRESS__) >> 8) /* 2nd Column addressing cycle */ + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#endif /* defined(SMC_Bank2_3) */ + +#ifdef __cplusplus +} +#endif + +#endif /* APM32F4xx_DAL_NAND_H */ diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_nor.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_nor.h new file mode 100644 index 0000000000..2bab16ea73 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_nor.h @@ -0,0 +1,352 @@ +/** + * + * @file apm32f4xx_dal_nor.h + * @brief Header file of NOR DAL module. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef APM32F4xx_DAL_NOR_H +#define APM32F4xx_DAL_NOR_H + +#ifdef __cplusplus +extern "C" { +#endif + +#if defined(SMC_Bank1) + +/* Includes ------------------------------------------------------------------*/ +#if defined(SMC_Bank1) +#include "apm32f4xx_ddl_smc.h" +#endif + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @addtogroup NOR + * @{ + */ + +/* Exported typedef ----------------------------------------------------------*/ +/** @defgroup NOR_Exported_Types NOR Exported Types + * @{ + */ + +/** + * @brief DAL SRAM State structures definition + */ +typedef enum +{ + DAL_NOR_STATE_RESET = 0x00U, /*!< NOR not yet initialized or disabled */ + DAL_NOR_STATE_READY = 0x01U, /*!< NOR initialized and ready for use */ + DAL_NOR_STATE_BUSY = 0x02U, /*!< NOR internal processing is ongoing */ + DAL_NOR_STATE_ERROR = 0x03U, /*!< NOR error state */ + DAL_NOR_STATE_PROTECTED = 0x04U /*!< NOR NORSRAM device write protected */ +} DAL_NOR_StateTypeDef; + +/** + * @brief FMC NOR Status typedef + */ +typedef enum +{ + DAL_NOR_STATUS_SUCCESS = 0U, + DAL_NOR_STATUS_ONGOING, + DAL_NOR_STATUS_ERROR, + DAL_NOR_STATUS_TIMEOUT +} DAL_NOR_StatusTypeDef; + +/** + * @brief FMC NOR ID typedef + */ +typedef struct +{ + uint16_t Manufacturer_Code; /*!< Defines the device's manufacturer code used to identify the memory */ + + uint16_t Device_Code1; + + uint16_t Device_Code2; + + uint16_t Device_Code3; /*!< Defines the device's codes used to identify the memory. + These codes can be accessed by performing read operations with specific + control signals and addresses set.They can also be accessed by issuing + an Auto Select command */ +} NOR_IDTypeDef; + +/** + * @brief FMC NOR CFI typedef + */ +typedef struct +{ + /*!< Defines the information stored in the memory's Common flash interface + which contains a description of various electrical and timing parameters, + density information and functions supported by the memory */ + + uint16_t CFI_1; + + uint16_t CFI_2; + + uint16_t CFI_3; + + uint16_t CFI_4; +} NOR_CFITypeDef; + +/** + * @brief NOR handle Structure definition + */ +#if (USE_DAL_NOR_REGISTER_CALLBACKS == 1) +typedef struct __NOR_HandleTypeDef +#else +typedef struct +#endif /* USE_DAL_NOR_REGISTER_CALLBACKS */ + +{ + FMC_NORSRAM_TypeDef *Instance; /*!< Register base address */ + + FMC_NORSRAM_EXTENDED_TypeDef *Extended; /*!< Extended mode register base address */ + + FMC_NORSRAM_InitTypeDef Init; /*!< NOR device control configuration parameters */ + + DAL_LockTypeDef Lock; /*!< NOR locking object */ + + __IO DAL_NOR_StateTypeDef State; /*!< NOR device access state */ + + uint32_t CommandSet; /*!< NOR algorithm command set and control */ + +#if (USE_DAL_NOR_REGISTER_CALLBACKS == 1) + void (* MspInitCallback)(struct __NOR_HandleTypeDef *hnor); /*!< NOR Msp Init callback */ + void (* MspDeInitCallback)(struct __NOR_HandleTypeDef *hnor); /*!< NOR Msp DeInit callback */ +#endif /* USE_DAL_NOR_REGISTER_CALLBACKS */ +} NOR_HandleTypeDef; + +#if (USE_DAL_NOR_REGISTER_CALLBACKS == 1) +/** + * @brief DAL NOR Callback ID enumeration definition + */ +typedef enum +{ + DAL_NOR_MSP_INIT_CB_ID = 0x00U, /*!< NOR MspInit Callback ID */ + DAL_NOR_MSP_DEINIT_CB_ID = 0x01U /*!< NOR MspDeInit Callback ID */ +} DAL_NOR_CallbackIDTypeDef; + +/** + * @brief DAL NOR Callback pointer definition + */ +typedef void (*pNOR_CallbackTypeDef)(NOR_HandleTypeDef *hnor); +#endif /* USE_DAL_NOR_REGISTER_CALLBACKS */ +/** + * @} + */ + +/* Exported constants --------------------------------------------------------*/ +/* Exported macro ------------------------------------------------------------*/ +/** @defgroup NOR_Exported_Macros NOR Exported Macros + * @{ + */ +/** @brief Reset NOR handle state + * @param __HANDLE__ specifies the NOR handle. + * @retval None + */ +#if (USE_DAL_NOR_REGISTER_CALLBACKS == 1) +#define __DAL_NOR_RESET_HANDLE_STATE(__HANDLE__) do { \ + (__HANDLE__)->State = DAL_NOR_STATE_RESET; \ + (__HANDLE__)->MspInitCallback = NULL; \ + (__HANDLE__)->MspDeInitCallback = NULL; \ + } while(0) +#else +#define __DAL_NOR_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = DAL_NOR_STATE_RESET) +#endif /* USE_DAL_NOR_REGISTER_CALLBACKS */ +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup NOR_Exported_Functions NOR Exported Functions + * @{ + */ + +/** @addtogroup NOR_Exported_Functions_Group1 Initialization and de-initialization functions + * @{ + */ + +/* Initialization/de-initialization functions ********************************/ +DAL_StatusTypeDef DAL_NOR_Init(NOR_HandleTypeDef *hnor, FMC_NORSRAM_TimingTypeDef *Timing, + FMC_NORSRAM_TimingTypeDef *ExtTiming); +DAL_StatusTypeDef DAL_NOR_DeInit(NOR_HandleTypeDef *hnor); +void DAL_NOR_MspInit(NOR_HandleTypeDef *hnor); +void DAL_NOR_MspDeInit(NOR_HandleTypeDef *hnor); +void DAL_NOR_MspWait(NOR_HandleTypeDef *hnor, uint32_t Timeout); +/** + * @} + */ + +/** @addtogroup NOR_Exported_Functions_Group2 Input and Output functions + * @{ + */ + +/* I/O operation functions ***************************************************/ +DAL_StatusTypeDef DAL_NOR_Read_ID(NOR_HandleTypeDef *hnor, NOR_IDTypeDef *pNOR_ID); +DAL_StatusTypeDef DAL_NOR_ReturnToReadMode(NOR_HandleTypeDef *hnor); +DAL_StatusTypeDef DAL_NOR_Read(NOR_HandleTypeDef *hnor, uint32_t *pAddress, uint16_t *pData); +DAL_StatusTypeDef DAL_NOR_Program(NOR_HandleTypeDef *hnor, uint32_t *pAddress, uint16_t *pData); + +DAL_StatusTypeDef DAL_NOR_ReadBuffer(NOR_HandleTypeDef *hnor, uint32_t uwAddress, uint16_t *pData, + uint32_t uwBufferSize); +DAL_StatusTypeDef DAL_NOR_ProgramBuffer(NOR_HandleTypeDef *hnor, uint32_t uwAddress, uint16_t *pData, + uint32_t uwBufferSize); + +DAL_StatusTypeDef DAL_NOR_Erase_Block(NOR_HandleTypeDef *hnor, uint32_t BlockAddress, uint32_t Address); +DAL_StatusTypeDef DAL_NOR_Erase_Chip(NOR_HandleTypeDef *hnor, uint32_t Address); +DAL_StatusTypeDef DAL_NOR_Read_CFI(NOR_HandleTypeDef *hnor, NOR_CFITypeDef *pNOR_CFI); + +#if (USE_DAL_NOR_REGISTER_CALLBACKS == 1) +/* NOR callback registering/unregistering */ +DAL_StatusTypeDef DAL_NOR_RegisterCallback(NOR_HandleTypeDef *hnor, DAL_NOR_CallbackIDTypeDef CallbackId, + pNOR_CallbackTypeDef pCallback); +DAL_StatusTypeDef DAL_NOR_UnRegisterCallback(NOR_HandleTypeDef *hnor, DAL_NOR_CallbackIDTypeDef CallbackId); +#endif /* USE_DAL_NOR_REGISTER_CALLBACKS */ +/** + * @} + */ + +/** @addtogroup NOR_Exported_Functions_Group3 NOR Control functions + * @{ + */ + +/* NOR Control functions *****************************************************/ +DAL_StatusTypeDef DAL_NOR_WriteOperation_Enable(NOR_HandleTypeDef *hnor); +DAL_StatusTypeDef DAL_NOR_WriteOperation_Disable(NOR_HandleTypeDef *hnor); +/** + * @} + */ + +/** @addtogroup NOR_Exported_Functions_Group4 NOR State functions + * @{ + */ + +/* NOR State functions ********************************************************/ +DAL_NOR_StateTypeDef DAL_NOR_GetState(NOR_HandleTypeDef *hnor); +DAL_NOR_StatusTypeDef DAL_NOR_GetStatus(NOR_HandleTypeDef *hnor, uint32_t Address, uint32_t Timeout); +/** + * @} + */ + +/** + * @} + */ + +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/** @defgroup NOR_Private_Constants NOR Private Constants + * @{ + */ +/* NOR device IDs addresses */ +#define MC_ADDRESS ((uint16_t)0x0000) +#define DEVICE_CODE1_ADDR ((uint16_t)0x0001) +#define DEVICE_CODE2_ADDR ((uint16_t)0x000E) +#define DEVICE_CODE3_ADDR ((uint16_t)0x000F) + +/* NOR CFI IDs addresses */ +#define CFI1_ADDRESS ((uint16_t)0x0061) +#define CFI2_ADDRESS ((uint16_t)0x0062) +#define CFI3_ADDRESS ((uint16_t)0x0063) +#define CFI4_ADDRESS ((uint16_t)0x0064) + +/* NOR operation wait timeout */ +#define NOR_TMEOUT ((uint16_t)0xFFFF) + +/* NOR memory data width */ +#define NOR_MEMORY_8B ((uint8_t)0x00) +#define NOR_MEMORY_16B ((uint8_t)0x01) + +/* NOR memory device read/write start address */ +#define NOR_MEMORY_ADRESS1 (0x60000000U) +#define NOR_MEMORY_ADRESS2 (0x64000000U) +#define NOR_MEMORY_ADRESS3 (0x68000000U) +#define NOR_MEMORY_ADRESS4 (0x6C000000U) +/** + * @} + */ + +/* Private macros ------------------------------------------------------------*/ +/** @defgroup NOR_Private_Macros NOR Private Macros + * @{ + */ +/** + * @brief NOR memory address shifting. + * @param __NOR_ADDRESS NOR base address + * @param __NOR_MEMORY_WIDTH_ NOR memory width + * @param __ADDRESS__ NOR memory address + * @retval NOR shifted address value + */ +#define NOR_ADDR_SHIFT(__NOR_ADDRESS, __NOR_MEMORY_WIDTH_, __ADDRESS__) \ + ((uint32_t)(((__NOR_MEMORY_WIDTH_) == NOR_MEMORY_16B)? \ + ((uint32_t)((__NOR_ADDRESS) + (2U * (__ADDRESS__)))): \ + ((uint32_t)((__NOR_ADDRESS) + (__ADDRESS__))))) + +/** + * @brief NOR memory write data to specified address. + * @param __ADDRESS__ NOR memory address + * @param __DATA__ Data to write + * @retval None + */ +#define NOR_WRITE(__ADDRESS__, __DATA__) do{ \ + (*(__IO uint16_t *)((uint32_t)(__ADDRESS__)) = (__DATA__)); \ + __DSB(); \ + } while(0) + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#endif /* SMC_Bank1 */ + +#ifdef __cplusplus +} +#endif + +#endif /* APM32F4xx_DAL_NOR_H */ diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_pccard.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_pccard.h new file mode 100644 index 0000000000..42c6ae5826 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_pccard.h @@ -0,0 +1,307 @@ +/** + * + * @file apm32f4xx_dal_pccard.h + * @brief Header file of PCCARD DAL module. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef APM32F4xx_DAL_PCCARD_H +#define APM32F4xx_DAL_PCCARD_H + +#ifdef __cplusplus +extern "C" { +#endif + +#if defined(SMC_Bank4) + +/* Includes ------------------------------------------------------------------*/ +#if defined(SMC_Bank4) +#include "apm32f4xx_ddl_smc.h" +#endif /* SMC_Bank4 */ + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @addtogroup PCCARD + * @{ + */ + +/* Exported typedef ----------------------------------------------------------*/ +/** @defgroup PCCARD_Exported_Types PCCARD Exported Types + * @{ + */ + +/** + * @brief DAL PCCARD State structures definition + */ +typedef enum +{ + DAL_PCCARD_STATE_RESET = 0x00U, /*!< PCCARD peripheral not yet initialized or disabled */ + DAL_PCCARD_STATE_READY = 0x01U, /*!< PCCARD peripheral ready */ + DAL_PCCARD_STATE_BUSY = 0x02U, /*!< PCCARD peripheral busy */ + DAL_PCCARD_STATE_ERROR = 0x04U /*!< PCCARD peripheral error */ +} DAL_PCCARD_StateTypeDef; + +typedef enum +{ + DAL_PCCARD_STATUS_SUCCESS = 0U, + DAL_PCCARD_STATUS_ONGOING, + DAL_PCCARD_STATUS_ERROR, + DAL_PCCARD_STATUS_TIMEOUT +} DAL_PCCARD_StatusTypeDef; + +/** + * @brief FMC_PCCARD handle Structure definition + */ +#if (USE_DAL_PCCARD_REGISTER_CALLBACKS == 1) +typedef struct __PCCARD_HandleTypeDef +#else +typedef struct +#endif /* USE_DAL_PCCARD_REGISTER_CALLBACKS */ +{ + FMC_PCCARD_TypeDef *Instance; /*!< Register base address for PCCARD device */ + + FMC_PCCARD_InitTypeDef Init; /*!< PCCARD device control configuration parameters */ + + __IO DAL_PCCARD_StateTypeDef State; /*!< PCCARD device access state */ + + DAL_LockTypeDef Lock; /*!< PCCARD Lock */ + +#if (USE_DAL_PCCARD_REGISTER_CALLBACKS == 1) + void (* MspInitCallback)(struct __PCCARD_HandleTypeDef *hpccard); /*!< PCCARD Msp Init callback */ + void (* MspDeInitCallback)(struct __PCCARD_HandleTypeDef *hpccard); /*!< PCCARD Msp DeInit callback */ + void (* ItCallback)(struct __PCCARD_HandleTypeDef *hpccard); /*!< PCCARD IT callback */ +#endif +} PCCARD_HandleTypeDef; + +#if (USE_DAL_PCCARD_REGISTER_CALLBACKS == 1) +/** + * @brief DAL PCCARD Callback ID enumeration definition + */ +typedef enum +{ + DAL_PCCARD_MSP_INIT_CB_ID = 0x00U, /*!< PCCARD MspInit Callback ID */ + DAL_PCCARD_MSP_DEINIT_CB_ID = 0x01U, /*!< PCCARD MspDeInit Callback ID */ + DAL_PCCARD_IT_CB_ID = 0x02U /*!< PCCARD IT Callback ID */ +} DAL_PCCARD_CallbackIDTypeDef; + +/** + * @brief DAL PCCARD Callback pointer definition + */ +typedef void (*pPCCARD_CallbackTypeDef)(PCCARD_HandleTypeDef *hpccard); +#endif +/** + * @} + */ + +/* Exported constants --------------------------------------------------------*/ +/* Exported macro ------------------------------------------------------------*/ +/** @defgroup PCCARD_Exported_Macros PCCARD Exported Macros + * @{ + */ +/** @brief Reset PCCARD handle state + * @param __HANDLE__ specifies the PCCARD handle. + * @retval None + */ +#if (USE_DAL_PCCARD_REGISTER_CALLBACKS == 1) +#define __DAL_PCCARD_RESET_HANDLE_STATE(__HANDLE__) do { \ + (__HANDLE__)->State = DAL_PCCARD_STATE_RESET; \ + (__HANDLE__)->MspInitCallback = NULL; \ + (__HANDLE__)->MspDeInitCallback = NULL; \ + } while(0) +#else +#define __DAL_PCCARD_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = DAL_PCCARD_STATE_RESET) +#endif +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup PCCARD_Exported_Functions + * @{ + */ + +/** @addtogroup PCCARD_Exported_Functions_Group1 + * @{ + */ +/* Initialization/de-initialization functions **********************************/ +DAL_StatusTypeDef DAL_PCCARD_Init(PCCARD_HandleTypeDef *hpccard, FMC_NAND_PCC_TimingTypeDef *ComSpaceTiming, + FMC_NAND_PCC_TimingTypeDef *AttSpaceTiming, FMC_NAND_PCC_TimingTypeDef *IOSpaceTiming); +DAL_StatusTypeDef DAL_PCCARD_DeInit(PCCARD_HandleTypeDef *hpccard); +void DAL_PCCARD_MspInit(PCCARD_HandleTypeDef *hpccard); +void DAL_PCCARD_MspDeInit(PCCARD_HandleTypeDef *hpccard); +/** + * @} + */ + +/** @addtogroup PCCARD_Exported_Functions_Group2 + * @{ + */ +/* IO operation functions *****************************************************/ +DAL_StatusTypeDef DAL_PCCARD_Read_ID(PCCARD_HandleTypeDef *hpccard, uint8_t CompactFlash_ID[], uint8_t *pStatus); +DAL_StatusTypeDef DAL_PCCARD_Write_Sector(PCCARD_HandleTypeDef *hpccard, uint16_t *pBuffer, uint16_t SectorAddress, + uint8_t *pStatus); +DAL_StatusTypeDef DAL_PCCARD_Read_Sector(PCCARD_HandleTypeDef *hpccard, uint16_t *pBuffer, uint16_t SectorAddress, + uint8_t *pStatus); +DAL_StatusTypeDef DAL_PCCARD_Erase_Sector(PCCARD_HandleTypeDef *hpccard, uint16_t SectorAddress, uint8_t *pStatus); +DAL_StatusTypeDef DAL_PCCARD_Reset(PCCARD_HandleTypeDef *hpccard); +void DAL_PCCARD_IRQHandler(PCCARD_HandleTypeDef *hpccard); +void DAL_PCCARD_ITCallback(PCCARD_HandleTypeDef *hpccard); + +#if (USE_DAL_PCCARD_REGISTER_CALLBACKS == 1) +/* PCCARD callback registering/unregistering */ +DAL_StatusTypeDef DAL_PCCARD_RegisterCallback(PCCARD_HandleTypeDef *hpccard, DAL_PCCARD_CallbackIDTypeDef CallbackId, + pPCCARD_CallbackTypeDef pCallback); +DAL_StatusTypeDef DAL_PCCARD_UnRegisterCallback(PCCARD_HandleTypeDef *hpccard, + DAL_PCCARD_CallbackIDTypeDef CallbackId); +#endif +/** + * @} + */ + +/** @addtogroup PCCARD_Exported_Functions_Group3 + * @{ + */ +/* PCCARD State functions *******************************************************/ +DAL_PCCARD_StateTypeDef DAL_PCCARD_GetState(PCCARD_HandleTypeDef *hpccard); +DAL_PCCARD_StatusTypeDef DAL_PCCARD_GetStatus(PCCARD_HandleTypeDef *hpccard); +DAL_PCCARD_StatusTypeDef DAL_PCCARD_ReadStatus(PCCARD_HandleTypeDef *hpccard); +/** + * @} + */ + +/** + * @} + */ +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/** @defgroup PCCARD_Private_Constants PCCARD Private Constants + * @{ + */ +#define PCCARD_DEVICE_ADDRESS 0x90000000U +#define PCCARD_ATTRIBUTE_SPACE_ADDRESS 0x98000000U /* Attribute space size to @0x9BFF FFFF */ +#define PCCARD_COMMON_SPACE_ADDRESS PCCARD_DEVICE_ADDRESS /* Common space size to @0x93FF FFFF */ +#define PCCARD_IO_SPACE_ADDRESS 0x9C000000U /* IO space size to @0x9FFF FFFF */ +#define PCCARD_IO_SPACE_PRIMARY_ADDR 0x9C0001F0U /* IO space size to @0x9FFF FFFF */ + +/* Flash-ATA registers description */ +#define ATA_DATA ((uint8_t)0x00) /* Data register */ +#define ATA_SECTOR_COUNT ((uint8_t)0x02) /* Sector Count register */ +#define ATA_SECTOR_NUMBER ((uint8_t)0x03) /* Sector Number register */ +#define ATA_CYLINDER_LOW ((uint8_t)0x04) /* Cylinder low register */ +#define ATA_CYLINDER_HIGH ((uint8_t)0x05) /* Cylinder high register */ +#define ATA_CARD_HEAD ((uint8_t)0x06) /* Card/Head register */ +#define ATA_STATUS_CMD ((uint8_t)0x07) /* Status(read)/Command(write) register */ +#define ATA_STATUS_CMD_ALTERNATE ((uint8_t)0x0E) /* Alternate Status(read)/Command(write) register */ +#define ATA_COMMON_DATA_AREA ((uint16_t)0x0400) /* Start of data area (for Common access only!) */ +#define ATA_CARD_CONFIGURATION ((uint16_t)0x0202) /* Card Configuration and Status Register */ + +/* Flash-ATA commands */ +#define ATA_READ_SECTOR_CMD ((uint8_t)0x20) +#define ATA_WRITE_SECTOR_CMD ((uint8_t)0x30) +#define ATA_ERASE_SECTOR_CMD ((uint8_t)0xC0) +#define ATA_IDENTIFY_CMD ((uint8_t)0xEC) + +/* PC Card/Compact Flash status */ +#define PCCARD_TIMEOUT_ERROR ((uint8_t)0x60) +#define PCCARD_BUSY ((uint8_t)0x80) +#define PCCARD_PROGR ((uint8_t)0x01) +#define PCCARD_READY ((uint8_t)0x40) + +#define PCCARD_SECTOR_SIZE 255U /* In half words */ + +/** + * @} + */ +/* Compact Flash redefinition */ +#define DAL_CF_Init DAL_PCCARD_Init +#define DAL_CF_DeInit DAL_PCCARD_DeInit +#define DAL_CF_MspInit DAL_PCCARD_MspInit +#define DAL_CF_MspDeInit DAL_PCCARD_MspDeInit + +#define DAL_CF_Read_ID DAL_PCCARD_Read_ID +#define DAL_CF_Write_Sector DAL_PCCARD_Write_Sector +#define DAL_CF_Read_Sector DAL_PCCARD_Read_Sector +#define DAL_CF_Erase_Sector DAL_PCCARD_Erase_Sector +#define DAL_CF_Reset DAL_PCCARD_Reset +#define DAL_CF_IRQHandler DAL_PCCARD_IRQHandler +#define DAL_CF_ITCallback DAL_PCCARD_ITCallback + +#define DAL_CF_GetState DAL_PCCARD_GetState +#define DAL_CF_GetStatus DAL_PCCARD_GetStatus +#define DAL_CF_ReadStatus DAL_PCCARD_ReadStatus + +#define DAL_CF_STATUS_SUCCESS DAL_PCCARD_STATUS_SUCCESS +#define DAL_CF_STATUS_ONGOING DAL_PCCARD_STATUS_ONGOING +#define DAL_CF_STATUS_ERROR DAL_PCCARD_STATUS_ERROR +#define DAL_CF_STATUS_TIMEOUT DAL_PCCARD_STATUS_TIMEOUT +#define DAL_CF_StatusTypeDef DAL_PCCARD_StatusTypeDef + +#define CF_DEVICE_ADDRESS PCCARD_DEVICE_ADDRESS +#define CF_ATTRIBUTE_SPACE_ADDRESS PCCARD_ATTRIBUTE_SPACE_ADDRESS +#define CF_COMMON_SPACE_ADDRESS PCCARD_COMMON_SPACE_ADDRESS +#define CF_IO_SPACE_ADDRESS PCCARD_IO_SPACE_ADDRESS +#define CF_IO_SPACE_PRIMARY_ADDR PCCARD_IO_SPACE_PRIMARY_ADDR + +#define CF_TIMEOUT_ERROR PCCARD_TIMEOUT_ERROR +#define CF_BUSY PCCARD_BUSY +#define CF_PROGR PCCARD_PROGR +#define CF_READY PCCARD_READY + +#define CF_SECTOR_SIZE PCCARD_SECTOR_SIZE + +/* Private macros ------------------------------------------------------------*/ +/** + * @} + */ + + +/** + * @} + */ + +#endif /* SMC_Bank4 */ + +#ifdef __cplusplus +} +#endif + +#endif /* APM32F4xx_DAL_PCCARD_H */ diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_pcd.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_pcd.h new file mode 100644 index 0000000000..b215ae5977 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_pcd.h @@ -0,0 +1,484 @@ +/** + * + * @file apm32f4xx_dal_pcd.h + * @brief Header file of PCD DAL module. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef APM32F4xx_DAL_PCD_H +#define APM32F4xx_DAL_PCD_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_ddl_usb.h" + +#if defined (USB_OTG_FS) || defined (USB_OTG_HS) + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @addtogroup PCD + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ +/** @defgroup PCD_Exported_Types PCD Exported Types + * @{ + */ + +/** + * @brief PCD State structure definition + */ +typedef enum +{ + DAL_PCD_STATE_RESET = 0x00, + DAL_PCD_STATE_READY = 0x01, + DAL_PCD_STATE_ERROR = 0x02, + DAL_PCD_STATE_BUSY = 0x03, + DAL_PCD_STATE_TIMEOUT = 0x04 +} PCD_StateTypeDef; + +/* Device LPM suspend state */ +typedef enum +{ + LPM_L0 = 0x00, /* on */ + LPM_L1 = 0x01, /* LPM L1 sleep */ + LPM_L2 = 0x02, /* suspend */ + LPM_L3 = 0x03, /* off */ +} PCD_LPM_StateTypeDef; + +typedef enum +{ + PCD_LPM_L0_ACTIVE = 0x00, /* on */ + PCD_LPM_L1_ACTIVE = 0x01, /* LPM L1 sleep */ +} PCD_LPM_MsgTypeDef; + +typedef enum +{ + PCD_BCD_ERROR = 0xFF, + PCD_BCD_CONTACT_DETECTION = 0xFE, + PCD_BCD_STD_DOWNSTREAM_PORT = 0xFD, + PCD_BCD_CHARGING_DOWNSTREAM_PORT = 0xFC, + PCD_BCD_DEDICATED_CHARGING_PORT = 0xFB, + PCD_BCD_DISCOVERY_COMPLETED = 0x00, + +} PCD_BCD_MsgTypeDef; + +#if defined (USB_OTG_FS) || defined (USB_OTG_HS) +typedef USB_OTG_GlobalTypeDef PCD_TypeDef; +typedef USB_OTG_CfgTypeDef PCD_InitTypeDef; +typedef USB_OTG_EPTypeDef PCD_EPTypeDef; +#endif /* defined (USB_OTG_FS) || defined (USB_OTG_HS) */ + +/** + * @brief PCD Handle Structure definition + */ +#if (USE_DAL_PCD_REGISTER_CALLBACKS == 1U) +typedef struct __PCD_HandleTypeDef +#else +typedef struct +#endif /* USE_DAL_PCD_REGISTER_CALLBACKS */ +{ + PCD_TypeDef *Instance; /*!< Register base address */ + PCD_InitTypeDef Init; /*!< PCD required parameters */ + __IO uint8_t USB_Address; /*!< USB Address */ + PCD_EPTypeDef IN_ep[16]; /*!< IN endpoint parameters */ + PCD_EPTypeDef OUT_ep[16]; /*!< OUT endpoint parameters */ + DAL_LockTypeDef Lock; /*!< PCD peripheral status */ + __IO PCD_StateTypeDef State; /*!< PCD communication state */ + __IO uint32_t ErrorCode; /*!< PCD Error code */ + uint32_t Setup[12]; /*!< Setup packet buffer */ + PCD_LPM_StateTypeDef LPM_State; /*!< LPM State */ + uint32_t BESL; + uint32_t FrameNumber; /*!< Store Current Frame number */ + + + uint32_t lpm_active; /*!< Enable or disable the Link Power Management . + This parameter can be set to ENABLE or DISABLE */ + + uint32_t battery_charging_active; /*!< Enable or disable Battery charging. + This parameter can be set to ENABLE or DISABLE */ + void *pData; /*!< Pointer to upper stack Handler */ + +#if (USE_DAL_PCD_REGISTER_CALLBACKS == 1U) + void (* SOFCallback)(struct __PCD_HandleTypeDef *hpcd); /*!< USB OTG PCD SOF callback */ + void (* SetupStageCallback)(struct __PCD_HandleTypeDef *hpcd); /*!< USB OTG PCD Setup Stage callback */ + void (* ResetCallback)(struct __PCD_HandleTypeDef *hpcd); /*!< USB OTG PCD Reset callback */ + void (* SuspendCallback)(struct __PCD_HandleTypeDef *hpcd); /*!< USB OTG PCD Suspend callback */ + void (* ResumeCallback)(struct __PCD_HandleTypeDef *hpcd); /*!< USB OTG PCD Resume callback */ + void (* ConnectCallback)(struct __PCD_HandleTypeDef *hpcd); /*!< USB OTG PCD Connect callback */ + void (* DisconnectCallback)(struct __PCD_HandleTypeDef *hpcd); /*!< USB OTG PCD Disconnect callback */ + + void (* DataOutStageCallback)(struct __PCD_HandleTypeDef *hpcd, uint8_t epnum); /*!< USB OTG PCD Data OUT Stage callback */ + void (* DataInStageCallback)(struct __PCD_HandleTypeDef *hpcd, uint8_t epnum); /*!< USB OTG PCD Data IN Stage callback */ + void (* ISOOUTIncompleteCallback)(struct __PCD_HandleTypeDef *hpcd, uint8_t epnum); /*!< USB OTG PCD ISO OUT Incomplete callback */ + void (* ISOINIncompleteCallback)(struct __PCD_HandleTypeDef *hpcd, uint8_t epnum); /*!< USB OTG PCD ISO IN Incomplete callback */ + void (* BCDCallback)(struct __PCD_HandleTypeDef *hpcd, PCD_BCD_MsgTypeDef msg); /*!< USB OTG PCD BCD callback */ + void (* LPMCallback)(struct __PCD_HandleTypeDef *hpcd, PCD_LPM_MsgTypeDef msg); /*!< USB OTG PCD LPM callback */ + + void (* MspInitCallback)(struct __PCD_HandleTypeDef *hpcd); /*!< USB OTG PCD Msp Init callback */ + void (* MspDeInitCallback)(struct __PCD_HandleTypeDef *hpcd); /*!< USB OTG PCD Msp DeInit callback */ +#endif /* USE_DAL_PCD_REGISTER_CALLBACKS */ +} PCD_HandleTypeDef; + +/** + * @} + */ + +/* Include PCD DAL Extended module */ +#include "apm32f4xx_dal_pcd_ex.h" + +/* Exported constants --------------------------------------------------------*/ +/** @defgroup PCD_Exported_Constants PCD Exported Constants + * @{ + */ + +/** @defgroup PCD_Speed PCD Speed + * @{ + */ +#define PCD_SPEED_HIGH USBD_HS_SPEED +#define PCD_SPEED_HIGH_IN_FULL USBD_HSINFS_SPEED +#define PCD_SPEED_FULL USBD_FS_SPEED +/** + * @} + */ + +/** @defgroup PCD_PHY_Module PCD PHY Module + * @{ + */ +#define PCD_PHY_ULPI 1U +#define PCD_PHY_EMBEDDED 2U +#define PCD_PHY_UTMI 3U +/** + * @} + */ + +/** @defgroup PCD_Error_Code_definition PCD Error Code definition + * @brief PCD Error Code definition + * @{ + */ +#if (USE_DAL_PCD_REGISTER_CALLBACKS == 1U) +#define DAL_PCD_ERROR_INVALID_CALLBACK (0x00000010U) /*!< Invalid Callback error */ +#endif /* USE_DAL_PCD_REGISTER_CALLBACKS */ + +/** + * @} + */ + +/** + * @} + */ + +/* Exported macros -----------------------------------------------------------*/ +/** @defgroup PCD_Exported_Macros PCD Exported Macros + * @brief macros to handle interrupts and specific clock configurations + * @{ + */ +#if defined (USB_OTG_FS) || defined (USB_OTG_HS) +#define __DAL_PCD_ENABLE(__HANDLE__) (void)USB_EnableGlobalInt ((__HANDLE__)->Instance) +#define __DAL_PCD_DISABLE(__HANDLE__) (void)USB_DisableGlobalInt ((__HANDLE__)->Instance) + +#define __DAL_PCD_GET_FLAG(__HANDLE__, __INTERRUPT__) \ + ((USB_ReadInterrupts((__HANDLE__)->Instance) & (__INTERRUPT__)) == (__INTERRUPT__)) + +#define __DAL_PCD_CLEAR_FLAG(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->GCINT) &= (__INTERRUPT__)) +#define __DAL_PCD_IS_INVALID_INTERRUPT(__HANDLE__) (USB_ReadInterrupts((__HANDLE__)->Instance) == 0U) + +#define __DAL_PCD_UNGATE_PHYCLOCK(__HANDLE__) \ + *(__IO uint32_t *)((uint32_t)((__HANDLE__)->Instance) + USB_OTG_PCGCCTL_BASE) &= ~(USB_OTG_PCGCCTL_STOPCLK) + +#define __DAL_PCD_GATE_PHYCLOCK(__HANDLE__) \ + *(__IO uint32_t *)((uint32_t)((__HANDLE__)->Instance) + USB_OTG_PCGCCTL_BASE) |= USB_OTG_PCGCCTL_STOPCLK + +#define __DAL_PCD_IS_PHY_SUSPENDED(__HANDLE__) \ + ((*(__IO uint32_t *)((uint32_t)((__HANDLE__)->Instance) + USB_OTG_PCGCCTL_BASE)) & 0x10U) + +#define __DAL_USB_OTG_HS_WAKEUP_EINT_ENABLE_IT() EINT->IMASK |= (USB_OTG_HS_WAKEUP_EINT_LINE) +#define __DAL_USB_OTG_HS_WAKEUP_EINT_DISABLE_IT() EINT->IMASK &= ~(USB_OTG_HS_WAKEUP_EINT_LINE) +#define __DAL_USB_OTG_HS_WAKEUP_EINT_GET_FLAG() EINT->IPEND & (USB_OTG_HS_WAKEUP_EINT_LINE) +#define __DAL_USB_OTG_HS_WAKEUP_EINT_CLEAR_FLAG() EINT->IPEND = (USB_OTG_HS_WAKEUP_EINT_LINE) + +#define __DAL_USB_OTG_HS_WAKEUP_EINT_ENABLE_RISING_EDGE() \ + do { \ + EINT->FTEN &= ~(USB_OTG_HS_WAKEUP_EINT_LINE); \ + EINT->RTEN |= USB_OTG_HS_WAKEUP_EINT_LINE; \ + } while(0U) +#define __DAL_USB_OTG_FS_WAKEUP_EINT_ENABLE_IT() EINT->IMASK |= USB_OTG_FS_WAKEUP_EINT_LINE +#define __DAL_USB_OTG_FS_WAKEUP_EINT_DISABLE_IT() EINT->IMASK &= ~(USB_OTG_FS_WAKEUP_EINT_LINE) +#define __DAL_USB_OTG_FS_WAKEUP_EINT_GET_FLAG() EINT->IPEND & (USB_OTG_FS_WAKEUP_EINT_LINE) +#define __DAL_USB_OTG_FS_WAKEUP_EINT_CLEAR_FLAG() EINT->IPEND = USB_OTG_FS_WAKEUP_EINT_LINE + +#define __DAL_USB_OTG_FS_WAKEUP_EINT_ENABLE_RISING_EDGE() \ + do { \ + EINT->FTEN &= ~(USB_OTG_FS_WAKEUP_EINT_LINE); \ + EINT->RTEN |= USB_OTG_FS_WAKEUP_EINT_LINE; \ + } while(0U) +#endif /* defined (USB_OTG_FS) || defined (USB_OTG_HS) */ + + +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup PCD_Exported_Functions PCD Exported Functions + * @{ + */ + +/* Initialization/de-initialization functions ********************************/ +/** @addtogroup PCD_Exported_Functions_Group1 Initialization and de-initialization functions + * @{ + */ +DAL_StatusTypeDef DAL_PCD_Init(PCD_HandleTypeDef *hpcd); +DAL_StatusTypeDef DAL_PCD_DeInit(PCD_HandleTypeDef *hpcd); +void DAL_PCD_MspInit(PCD_HandleTypeDef *hpcd); +void DAL_PCD_MspDeInit(PCD_HandleTypeDef *hpcd); + +#if (USE_DAL_PCD_REGISTER_CALLBACKS == 1U) +/** @defgroup DAL_PCD_Callback_ID_enumeration_definition DAL USB OTG PCD Callback ID enumeration definition + * @brief DAL USB OTG PCD Callback ID enumeration definition + * @{ + */ +typedef enum +{ + DAL_PCD_SOF_CB_ID = 0x01, /*!< USB PCD SOF callback ID */ + DAL_PCD_SETUPSTAGE_CB_ID = 0x02, /*!< USB PCD Setup Stage callback ID */ + DAL_PCD_RESET_CB_ID = 0x03, /*!< USB PCD Reset callback ID */ + DAL_PCD_SUSPEND_CB_ID = 0x04, /*!< USB PCD Suspend callback ID */ + DAL_PCD_RESUME_CB_ID = 0x05, /*!< USB PCD Resume callback ID */ + DAL_PCD_CONNECT_CB_ID = 0x06, /*!< USB PCD Connect callback ID */ + DAL_PCD_DISCONNECT_CB_ID = 0x07, /*!< USB PCD Disconnect callback ID */ + + DAL_PCD_MSPINIT_CB_ID = 0x08, /*!< USB PCD MspInit callback ID */ + DAL_PCD_MSPDEINIT_CB_ID = 0x09 /*!< USB PCD MspDeInit callback ID */ + +} DAL_PCD_CallbackIDTypeDef; +/** + * @} + */ + +/** @defgroup DAL_PCD_Callback_pointer_definition DAL USB OTG PCD Callback pointer definition + * @brief DAL USB OTG PCD Callback pointer definition + * @{ + */ + +typedef void (*pPCD_CallbackTypeDef)(PCD_HandleTypeDef *hpcd); /*!< pointer to a common USB OTG PCD callback function */ +typedef void (*pPCD_DataOutStageCallbackTypeDef)(PCD_HandleTypeDef *hpcd, uint8_t epnum); /*!< pointer to USB OTG PCD Data OUT Stage callback */ +typedef void (*pPCD_DataInStageCallbackTypeDef)(PCD_HandleTypeDef *hpcd, uint8_t epnum); /*!< pointer to USB OTG PCD Data IN Stage callback */ +typedef void (*pPCD_IsoOutIncpltCallbackTypeDef)(PCD_HandleTypeDef *hpcd, uint8_t epnum); /*!< pointer to USB OTG PCD ISO OUT Incomplete callback */ +typedef void (*pPCD_IsoInIncpltCallbackTypeDef)(PCD_HandleTypeDef *hpcd, uint8_t epnum); /*!< pointer to USB OTG PCD ISO IN Incomplete callback */ +typedef void (*pPCD_LpmCallbackTypeDef)(PCD_HandleTypeDef *hpcd, PCD_LPM_MsgTypeDef msg); /*!< pointer to USB OTG PCD LPM callback */ +typedef void (*pPCD_BcdCallbackTypeDef)(PCD_HandleTypeDef *hpcd, PCD_BCD_MsgTypeDef msg); /*!< pointer to USB OTG PCD BCD callback */ + +/** + * @} + */ + +DAL_StatusTypeDef DAL_PCD_RegisterCallback(PCD_HandleTypeDef *hpcd, DAL_PCD_CallbackIDTypeDef CallbackID, + pPCD_CallbackTypeDef pCallback); + +DAL_StatusTypeDef DAL_PCD_UnRegisterCallback(PCD_HandleTypeDef *hpcd, DAL_PCD_CallbackIDTypeDef CallbackID); + +DAL_StatusTypeDef DAL_PCD_RegisterDataOutStageCallback(PCD_HandleTypeDef *hpcd, + pPCD_DataOutStageCallbackTypeDef pCallback); + +DAL_StatusTypeDef DAL_PCD_UnRegisterDataOutStageCallback(PCD_HandleTypeDef *hpcd); + +DAL_StatusTypeDef DAL_PCD_RegisterDataInStageCallback(PCD_HandleTypeDef *hpcd, + pPCD_DataInStageCallbackTypeDef pCallback); + +DAL_StatusTypeDef DAL_PCD_UnRegisterDataInStageCallback(PCD_HandleTypeDef *hpcd); + +DAL_StatusTypeDef DAL_PCD_RegisterIsoOutIncpltCallback(PCD_HandleTypeDef *hpcd, + pPCD_IsoOutIncpltCallbackTypeDef pCallback); + +DAL_StatusTypeDef DAL_PCD_UnRegisterIsoOutIncpltCallback(PCD_HandleTypeDef *hpcd); + +DAL_StatusTypeDef DAL_PCD_RegisterIsoInIncpltCallback(PCD_HandleTypeDef *hpcd, + pPCD_IsoInIncpltCallbackTypeDef pCallback); + +DAL_StatusTypeDef DAL_PCD_UnRegisterIsoInIncpltCallback(PCD_HandleTypeDef *hpcd); + +DAL_StatusTypeDef DAL_PCD_RegisterBcdCallback(PCD_HandleTypeDef *hpcd, pPCD_BcdCallbackTypeDef pCallback); +DAL_StatusTypeDef DAL_PCD_UnRegisterBcdCallback(PCD_HandleTypeDef *hpcd); + +DAL_StatusTypeDef DAL_PCD_RegisterLpmCallback(PCD_HandleTypeDef *hpcd, pPCD_LpmCallbackTypeDef pCallback); +DAL_StatusTypeDef DAL_PCD_UnRegisterLpmCallback(PCD_HandleTypeDef *hpcd); +#endif /* USE_DAL_PCD_REGISTER_CALLBACKS */ +/** + * @} + */ + +/* I/O operation functions ***************************************************/ +/* Non-Blocking mode: Interrupt */ +/** @addtogroup PCD_Exported_Functions_Group2 Input and Output operation functions + * @{ + */ +DAL_StatusTypeDef DAL_PCD_Start(PCD_HandleTypeDef *hpcd); +DAL_StatusTypeDef DAL_PCD_Stop(PCD_HandleTypeDef *hpcd); +void DAL_PCD_IRQHandler(PCD_HandleTypeDef *hpcd); +void DAL_PCD_WKUP_IRQHandler(PCD_HandleTypeDef *hpcd); + +void DAL_PCD_SOFCallback(PCD_HandleTypeDef *hpcd); +void DAL_PCD_SetupStageCallback(PCD_HandleTypeDef *hpcd); +void DAL_PCD_ResetCallback(PCD_HandleTypeDef *hpcd); +void DAL_PCD_SuspendCallback(PCD_HandleTypeDef *hpcd); +void DAL_PCD_ResumeCallback(PCD_HandleTypeDef *hpcd); +void DAL_PCD_ConnectCallback(PCD_HandleTypeDef *hpcd); +void DAL_PCD_DisconnectCallback(PCD_HandleTypeDef *hpcd); + +void DAL_PCD_DataOutStageCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum); +void DAL_PCD_DataInStageCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum); +void DAL_PCD_ISOOUTIncompleteCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum); +void DAL_PCD_ISOINIncompleteCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum); +/** + * @} + */ + +/* Peripheral Control functions **********************************************/ +/** @addtogroup PCD_Exported_Functions_Group3 Peripheral Control functions + * @{ + */ +DAL_StatusTypeDef DAL_PCD_DevConnect(PCD_HandleTypeDef *hpcd); +DAL_StatusTypeDef DAL_PCD_DevDisconnect(PCD_HandleTypeDef *hpcd); +DAL_StatusTypeDef DAL_PCD_SetAddress(PCD_HandleTypeDef *hpcd, uint8_t address); +DAL_StatusTypeDef DAL_PCD_EP_Open(PCD_HandleTypeDef *hpcd, uint8_t ep_addr, uint16_t ep_mps, uint8_t ep_type); +DAL_StatusTypeDef DAL_PCD_EP_Close(PCD_HandleTypeDef *hpcd, uint8_t ep_addr); +DAL_StatusTypeDef DAL_PCD_EP_Receive(PCD_HandleTypeDef *hpcd, uint8_t ep_addr, uint8_t *pBuf, uint32_t len); +DAL_StatusTypeDef DAL_PCD_EP_Transmit(PCD_HandleTypeDef *hpcd, uint8_t ep_addr, uint8_t *pBuf, uint32_t len); +DAL_StatusTypeDef DAL_PCD_EP_SetStall(PCD_HandleTypeDef *hpcd, uint8_t ep_addr); +DAL_StatusTypeDef DAL_PCD_EP_ClrStall(PCD_HandleTypeDef *hpcd, uint8_t ep_addr); +uint8_t DAL_PCD_EP_ReadStallStatus(PCD_HandleTypeDef *hpcd, uint8_t epAddr); +DAL_StatusTypeDef DAL_PCD_EP_Flush(PCD_HandleTypeDef *hpcd, uint8_t ep_addr); +DAL_StatusTypeDef DAL_PCD_EP_Abort(PCD_HandleTypeDef *hpcd, uint8_t ep_addr); +DAL_StatusTypeDef DAL_PCD_ActivateRemoteWakeup(PCD_HandleTypeDef *hpcd); +DAL_StatusTypeDef DAL_PCD_DeActivateRemoteWakeup(PCD_HandleTypeDef *hpcd); +DAL_StatusTypeDef DAL_PCD_SetTestMode(PCD_HandleTypeDef *hpcd, uint8_t testmode); + +uint32_t DAL_PCD_EP_GetRxCount(PCD_HandleTypeDef *hpcd, uint8_t ep_addr); +/** + * @} + */ + +/* Peripheral State functions ************************************************/ +/** @addtogroup PCD_Exported_Functions_Group4 Peripheral State functions + * @{ + */ +PCD_StateTypeDef DAL_PCD_GetState(PCD_HandleTypeDef *hpcd); +/** + * @} + */ + +/** + * @} + */ + +/* Private constants ---------------------------------------------------------*/ +/** @defgroup PCD_Private_Constants PCD Private Constants + * @{ + */ +/** @defgroup USB_EINT_Line_Interrupt USB EINT line interrupt + * @{ + */ +#if defined (USB_OTG_FS) || defined (USB_OTG_HS) +#define USB_OTG_FS_WAKEUP_EINT_LINE (0x1U << 18) /*!< USB FS EINT Line WakeUp Interrupt */ +#define USB_OTG_HS_WAKEUP_EINT_LINE (0x1U << 20) /*!< USB HS EINT Line WakeUp Interrupt */ +#endif /* defined (USB_OTG_FS) || defined (USB_OTG_HS) */ + + +/** + * @} + */ +/** + * @} + */ + +#if defined (USB_OTG_FS) || defined (USB_OTG_HS) +#ifndef USB_OTG_DOEPINT_OTEPSPR +#define USB_OTG_DOEPINT_OTEPSPR (0x1UL << 5) /*!< Status Phase Received interrupt */ +#endif /* defined USB_OTG_DOEPINT_OTEPSPR */ + +#ifndef USB_OTG_DOUTIMASK_OTEPSPRM +#define USB_OTG_DOUTIMASK_OTEPSPRM (0x1UL << 5) /*!< Setup Packet Received interrupt mask */ +#endif /* defined USB_OTG_DOUTIMASK_OTEPSPRM */ + +#ifndef USB_OTG_DOEPINT_NAK +#define USB_OTG_DOEPINT_NAK (0x1UL << 13) /*!< NAK interrupt */ +#endif /* defined USB_OTG_DOEPINT_NAK */ + +#ifndef USB_OTG_DOUTIMASK_NAKM +#define USB_OTG_DOUTIMASK_NAKM (0x1UL << 13) /*!< OUT Packet NAK interrupt mask */ +#endif /* defined USB_OTG_DOUTIMASK_NAKM */ + +#ifndef USB_OTG_DOEPINT_STPKTRX +#define USB_OTG_DOEPINT_STPKTRX (0x1UL << 15) /*!< Setup Packet Received interrupt */ +#endif /* defined USB_OTG_DOEPINT_STPKTRX */ + +#ifndef USB_OTG_DOUTIMASK_NYETM +#define USB_OTG_DOUTIMASK_NYETM (0x1UL << 14) /*!< Setup Packet Received interrupt mask */ +#endif /* defined USB_OTG_DOUTIMASK_NYETM */ +#endif /* defined (USB_OTG_FS) || defined (USB_OTG_HS) */ + +/* Private macros ------------------------------------------------------------*/ +/** @defgroup PCD_Private_Macros PCD Private Macros + * @{ + */ + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ +#endif /* defined (USB_OTG_FS) || defined (USB_OTG_HS) */ + +#ifdef __cplusplus +} +#endif + +#endif /* APM32F4xx_DAL_PCD_H */ diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_pcd_ex.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_pcd_ex.h new file mode 100644 index 0000000000..df8aeff77c --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_pcd_ex.h @@ -0,0 +1,103 @@ +/** + * + * @file apm32f4xx_dal_pcd_ex.h + * @brief Header file of PCD DAL Extension module. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef APM32F4xx_DAL_PCD_EX_H +#define APM32F4xx_DAL_PCD_EX_H + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal_def.h" + +#if defined (USB_OTG_FS) || defined (USB_OTG_HS) +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @addtogroup PCDEx + * @{ + */ +/* Exported types ------------------------------------------------------------*/ +/* Exported constants --------------------------------------------------------*/ +/* Exported macros -----------------------------------------------------------*/ +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup PCDEx_Exported_Functions PCDEx Exported Functions + * @{ + */ +/** @addtogroup PCDEx_Exported_Functions_Group1 Peripheral Control functions + * @{ + */ + +#if defined (USB_OTG_FS) || defined (USB_OTG_HS) +DAL_StatusTypeDef DAL_PCDEx_SetTxFiFo(PCD_HandleTypeDef *hpcd, uint8_t fifo, uint16_t size); +DAL_StatusTypeDef DAL_PCDEx_SetRxFiFo(PCD_HandleTypeDef *hpcd, uint16_t size); +#endif /* defined (USB_OTG_FS) || defined (USB_OTG_HS) */ + +void DAL_PCDEx_LPM_Callback(PCD_HandleTypeDef *hpcd, PCD_LPM_MsgTypeDef msg); +void DAL_PCDEx_BCD_Callback(PCD_HandleTypeDef *hpcd, PCD_BCD_MsgTypeDef msg); + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ +#endif /* defined (USB_OTG_FS) || defined (USB_OTG_HS) */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + + +#endif /* APM32F4xx_DAL_PCD_EX_H */ diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_pmu.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_pmu.h new file mode 100644 index 0000000000..881292ded2 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_pmu.h @@ -0,0 +1,452 @@ +/** + * + * @file apm32f4xx_dal_pmu.h + * @brief Header file of PMU DAL module. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2017 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file in + * the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef APM32F4xx_DAL_PMU_H +#define APM32F4xx_DAL_PMU_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal_def.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @addtogroup PMU + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ + +/** @defgroup PMU_Exported_Types PMU Exported Types + * @{ + */ + +/** + * @brief PMU PVD configuration structure definition + */ +typedef struct +{ + uint32_t PVDLevel; /*!< PVDLevel: Specifies the PVD detection level. + This parameter can be a value of @ref PMU_PVD_detection_level */ + + uint32_t Mode; /*!< Mode: Specifies the operating mode for the selected pins. + This parameter can be a value of @ref PMU_PVD_Mode */ +}PMU_PVDTypeDef; + +/** + * @} + */ + +/* Exported constants --------------------------------------------------------*/ +/** @defgroup PMU_Exported_Constants PMU Exported Constants + * @{ + */ + +/** @defgroup PMU_WakeUp_Pins PMU WakeUp Pins + * @{ + */ +#define PMU_WAKEUP_PIN1 0x00000100U +/** + * @} + */ + +/** @defgroup PMU_PVD_detection_level PMU PVD detection level + * @{ + */ +#define PMU_PVDLEVEL_0 PMU_CTRL_PLSEL_LEV0 +#define PMU_PVDLEVEL_1 PMU_CTRL_PLSEL_LEV1 +#define PMU_PVDLEVEL_2 PMU_CTRL_PLSEL_LEV2 +#define PMU_PVDLEVEL_3 PMU_CTRL_PLSEL_LEV3 +#define PMU_PVDLEVEL_4 PMU_CTRL_PLSEL_LEV4 +#define PMU_PVDLEVEL_5 PMU_CTRL_PLSEL_LEV5 +#define PMU_PVDLEVEL_6 PMU_CTRL_PLSEL_LEV6 +#define PMU_PVDLEVEL_7 PMU_CTRL_PLSEL_LEV7/* External input analog voltage + (Compare internally to VREFINT) */ +/** + * @} + */ + +/** @defgroup PMU_PVD_Mode PMU PVD Mode + * @{ + */ +#define PMU_PVD_MODE_NORMAL 0x00000000U /*!< basic mode is used */ +#define PMU_PVD_MODE_IT_RISING 0x00010001U /*!< External Interrupt Mode with Rising edge trigger detection */ +#define PMU_PVD_MODE_IT_FALLING 0x00010002U /*!< External Interrupt Mode with Falling edge trigger detection */ +#define PMU_PVD_MODE_IT_RISING_FALLING 0x00010003U /*!< External Interrupt Mode with Rising/Falling edge trigger detection */ +#define PMU_PVD_MODE_EVENT_RISING 0x00020001U /*!< Event Mode with Rising edge trigger detection */ +#define PMU_PVD_MODE_EVENT_FALLING 0x00020002U /*!< Event Mode with Falling edge trigger detection */ +#define PMU_PVD_MODE_EVENT_RISING_FALLING 0x00020003U /*!< Event Mode with Rising/Falling edge trigger detection */ +/** + * @} + */ + + +/** @defgroup PMU_Regulator_state_in_STOP_mode PMU Regulator state in SLEEP/STOP mode + * @{ + */ +#define PMU_MAINREGULATOR_ON 0x00000000U +#define PMU_LOWPOWERREGULATOR_ON PMU_CTRL_LPDSCFG +/** + * @} + */ + +/** @defgroup PMU_SLEEP_mode_entry PMU SLEEP mode entry + * @{ + */ +#define PMU_SLEEPENTRY_WFI ((uint8_t)0x01) +#define PMU_SLEEPENTRY_WFE ((uint8_t)0x02) +/** + * @} + */ + +/** @defgroup PMU_STOP_mode_entry PMU STOP mode entry + * @{ + */ +#define PMU_STOPENTRY_WFI ((uint8_t)0x01) +#define PMU_STOPENTRY_WFE ((uint8_t)0x02) +/** + * @} + */ + +/** @defgroup PMU_Flag PMU Flag + * @{ + */ +#define PMU_FLAG_WU PMU_CSTS_WUEFLG +#define PMU_FLAG_SB PMU_CSTS_SBFLG +#define PMU_FLAG_PVDO PMU_CSTS_PVDOFLG +#define PMU_FLAG_BRR PMU_CSTS_BKPRFLG +#define PMU_FLAG_VOSRDY PMU_CSTS_VOSRFLG +/** + * @} + */ + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ +/** @defgroup PMU_Exported_Macro PMU Exported Macro + * @{ + */ + +/** @brief Check PMU flag is set or not. + * @param __FLAG__ specifies the flag to check. + * This parameter can be one of the following values: + * @arg PMU_FLAG_WU: Wake Up flag. This flag indicates that a wakeup event + * was received from the WKUP pin or from the RTC alarm (Alarm A + * or Alarm B), RTC Tamper event, RTC TimeStamp event or RTC Wakeup. + * An additional wakeup event is detected if the WKUP pin is enabled + * (by setting the EWUP bit) when the WKUP pin level is already high. + * @arg PMU_FLAG_SB: StandBy flag. This flag indicates that the system was + * resumed from StandBy mode. + * @arg PMU_FLAG_PVDO: PVD Output. This flag is valid only if PVD is enabled + * by the DAL_PMU_EnablePVD() function. The PVD is stopped by Standby mode + * For this reason, this bit is equal to 0 after Standby or reset + * until the PVDE bit is set. + * @arg PMU_FLAG_BRR: Backup regulator ready flag. This bit is not reset + * when the device wakes up from Standby mode or by a system reset + * or power reset. + * @arg PMU_FLAG_VOSRDY: This flag indicates that the Regulator voltage + * scaling output selection is ready. + * @retval The new state of __FLAG__ (TRUE or FALSE). + */ +#define __DAL_PMU_GET_FLAG(__FLAG__) ((PMU->CSTS & (__FLAG__)) == (__FLAG__)) + +/** @brief Clear the PMU's pending flags. + * @param __FLAG__ specifies the flag to clear. + * This parameter can be one of the following values: + * @arg PMU_FLAG_WU: Wake Up flag + * @arg PMU_FLAG_SB: StandBy flag + */ +#define __DAL_PMU_CLEAR_FLAG(__FLAG__) (PMU->CTRL |= (__FLAG__) << 2U) + +/** + * @brief Enable the PVD Exti Line 16. + * @retval None. + */ +#define __DAL_PMU_PVD_EINT_ENABLE_IT() (EINT->IMASK |= (PMU_EINT_LINE_PVD)) + +/** + * @brief Disable the PVD EINT Line 16. + * @retval None. + */ +#define __DAL_PMU_PVD_EINT_DISABLE_IT() (EINT->IMASK &= ~(PMU_EINT_LINE_PVD)) + +/** + * @brief Enable event on PVD Exti Line 16. + * @retval None. + */ +#define __DAL_PMU_PVD_EINT_ENABLE_EVENT() (EINT->EMASK |= (PMU_EINT_LINE_PVD)) + +/** + * @brief Disable event on PVD Exti Line 16. + * @retval None. + */ +#define __DAL_PMU_PVD_EINT_DISABLE_EVENT() (EINT->EMASK &= ~(PMU_EINT_LINE_PVD)) + +/** + * @brief Enable the PVD Extended Interrupt Rising Trigger. + * @retval None. + */ +#define __DAL_PMU_PVD_EINT_ENABLE_RISING_EDGE() SET_BIT(EINT->RTEN, PMU_EINT_LINE_PVD) + +/** + * @brief Disable the PVD Extended Interrupt Rising Trigger. + * @retval None. + */ +#define __DAL_PMU_PVD_EINT_DISABLE_RISING_EDGE() CLEAR_BIT(EINT->RTEN, PMU_EINT_LINE_PVD) + +/** + * @brief Enable the PVD Extended Interrupt Falling Trigger. + * @retval None. + */ +#define __DAL_PMU_PVD_EINT_ENABLE_FALLING_EDGE() SET_BIT(EINT->FTEN, PMU_EINT_LINE_PVD) + + +/** + * @brief Disable the PVD Extended Interrupt Falling Trigger. + * @retval None. + */ +#define __DAL_PMU_PVD_EINT_DISABLE_FALLING_EDGE() CLEAR_BIT(EINT->FTEN, PMU_EINT_LINE_PVD) + + +/** + * @brief PVD EINT line configuration: set rising & falling edge trigger. + * @retval None. + */ +#define __DAL_PMU_PVD_EINT_ENABLE_RISING_FALLING_EDGE() do{__DAL_PMU_PVD_EINT_ENABLE_RISING_EDGE();\ + __DAL_PMU_PVD_EINT_ENABLE_FALLING_EDGE();\ + }while(0U) + +/** + * @brief Disable the PVD Extended Interrupt Rising & Falling Trigger. + * This parameter can be: + * @retval None. + */ +#define __DAL_PMU_PVD_EINT_DISABLE_RISING_FALLING_EDGE() do{__DAL_PMU_PVD_EINT_DISABLE_RISING_EDGE();\ + __DAL_PMU_PVD_EINT_DISABLE_FALLING_EDGE();\ + }while(0U) + +/** + * @brief checks whether the specified PVD Exti interrupt flag is set or not. + * @retval EINT PVD Line Status. + */ +#define __DAL_PMU_PVD_EINT_GET_FLAG() (EINT->IPEND & (PMU_EINT_LINE_PVD)) + +/** + * @brief Clear the PVD Exti flag. + * @retval None. + */ +#define __DAL_PMU_PVD_EINT_CLEAR_FLAG() (EINT->IPEND = (PMU_EINT_LINE_PVD)) + +/** + * @brief Generates a Software interrupt on PVD EINT line. + * @retval None + */ +#define __DAL_PMU_PVD_EINT_GENERATE_SWIT() (EINT->SWINTE |= (PMU_EINT_LINE_PVD)) + +/** + * @} + */ + +/* Include PMU DAL Extension module */ +#include "apm32f4xx_dal_pmu_ex.h" + +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup PMU_Exported_Functions PMU Exported Functions + * @{ + */ + +/** @addtogroup PMU_Exported_Functions_Group1 Initialization and de-initialization functions + * @{ + */ +/* Initialization and de-initialization functions *****************************/ +void DAL_PMU_DeInit(void); +void DAL_PMU_EnableBkUpAccess(void); +void DAL_PMU_DisableBkUpAccess(void); +/** + * @} + */ + +/** @addtogroup PMU_Exported_Functions_Group2 Peripheral Control functions + * @{ + */ +/* Peripheral Control functions **********************************************/ +/* PVD configuration */ +void DAL_PMU_ConfigPVD(PMU_PVDTypeDef *sConfigPVD); +void DAL_PMU_EnablePVD(void); +void DAL_PMU_DisablePVD(void); + +/* WakeUp pins configuration */ +void DAL_PMU_EnableWakeUpPin(uint32_t WakeUpPinx); +void DAL_PMU_DisableWakeUpPin(uint32_t WakeUpPinx); + +/* Low Power modes entry */ +void DAL_PMU_EnterSTOPMode(uint32_t Regulator, uint8_t STOPEntry); +void DAL_PMU_EnterSLEEPMode(uint32_t Regulator, uint8_t SLEEPEntry); +void DAL_PMU_EnterSTANDBYMode(void); + +/* Power PVD IRQ Handler */ +void DAL_PMU_PVD_IRQHandler(void); +void DAL_PMU_PVDCallback(void); + +/* Cortex System Control functions *******************************************/ +void DAL_PMU_EnableSleepOnExit(void); +void DAL_PMU_DisableSleepOnExit(void); +void DAL_PMU_EnableSEVOnPend(void); +void DAL_PMU_DisableSEVOnPend(void); +/** + * @} + */ + +/** + * @} + */ + +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/** @defgroup PMU_Private_Constants PMU Private Constants + * @{ + */ + +/** @defgroup PMU_PVD_EINT_Line PMU PVD EINT Line + * @{ + */ +#define PMU_EINT_LINE_PVD ((uint32_t)EINT_IMASK_IMASK16) /*!< External interrupt line 16 Connected to the PVD EINT Line */ +/** + * @} + */ + +/** @defgroup PMU_register_alias_address PMU Register alias address + * @{ + */ +/* ------------- PMU registers bit address in the alias region ---------------*/ +#define PMU_OFFSET (PMU_BASE - PERIPH_BASE) +#define PMU_CTRL_OFFSET 0x00U +#define PMU_CSTS_OFFSET 0x04U +#define PMU_CTRL_OFFSET_BB (PMU_OFFSET + PMU_CTRL_OFFSET) +#define PMU_CSTS_OFFSET_BB (PMU_OFFSET + PMU_CSTS_OFFSET) +/** + * @} + */ + +/** @defgroup PMU_CTRL_register_alias PMU CTRL Register alias address + * @{ + */ +/* --- CTRL Register ---*/ +/* Alias word address of DBP bit */ +#define DBP_BIT_NUMBER PMU_CTRL_BPWEN_Pos +#define CTRL_BPWEN_BB (uint32_t)(PERIPH_BB_BASE + (PMU_CTRL_OFFSET_BB * 32U) + (DBP_BIT_NUMBER * 4U)) + +/* Alias word address of PVDE bit */ +#define PVDE_BIT_NUMBER PMU_CTRL_PVDEN_Pos +#define CTRL_PVDEN_BB (uint32_t)(PERIPH_BB_BASE + (PMU_CTRL_OFFSET_BB * 32U) + (PVDE_BIT_NUMBER * 4U)) + +/* Alias word address of VOS bit */ +#define VOS_BIT_NUMBER PMU_CTRL_VOSSEL_Pos +#define CTRL_VOSSEL_BB (uint32_t)(PERIPH_BB_BASE + (PMU_CTRL_OFFSET_BB * 32U) + (VOS_BIT_NUMBER * 4U)) +/** + * @} + */ + +/** @defgroup PMU_CSTS_register_alias PMU CSTS Register alias address + * @{ + */ +/* --- CSTS Register ---*/ +/* Alias word address of EWUP bit */ +#define EWUP_BIT_NUMBER PMU_CSTS_WKUPCFG_Pos +#define CSTS_WKUPCFG_BB (PERIPH_BB_BASE + (PMU_CSTS_OFFSET_BB * 32U) + (EWUP_BIT_NUMBER * 4U)) +/** + * @} + */ + +/** + * @} + */ +/* Private macros ------------------------------------------------------------*/ +/** @defgroup PMU_Private_Macros PMU Private Macros + * @{ + */ + +/** @defgroup PMU_IS_PMU_Definitions PMU Private macros to check input parameters + * @{ + */ +#define IS_PMU_PVD_LEVEL(LEVEL) (((LEVEL) == PMU_PVDLEVEL_0) || ((LEVEL) == PMU_PVDLEVEL_1)|| \ + ((LEVEL) == PMU_PVDLEVEL_2) || ((LEVEL) == PMU_PVDLEVEL_3)|| \ + ((LEVEL) == PMU_PVDLEVEL_4) || ((LEVEL) == PMU_PVDLEVEL_5)|| \ + ((LEVEL) == PMU_PVDLEVEL_6) || ((LEVEL) == PMU_PVDLEVEL_7)) +#define IS_PMU_PVD_MODE(MODE) (((MODE) == PMU_PVD_MODE_IT_RISING)|| ((MODE) == PMU_PVD_MODE_IT_FALLING) || \ + ((MODE) == PMU_PVD_MODE_IT_RISING_FALLING) || ((MODE) == PMU_PVD_MODE_EVENT_RISING) || \ + ((MODE) == PMU_PVD_MODE_EVENT_FALLING) || ((MODE) == PMU_PVD_MODE_EVENT_RISING_FALLING) || \ + ((MODE) == PMU_PVD_MODE_NORMAL)) +#define IS_PMU_REGULATOR(REGULATOR) (((REGULATOR) == PMU_MAINREGULATOR_ON) || \ + ((REGULATOR) == PMU_LOWPOWERREGULATOR_ON)) +#define IS_PMU_SLEEP_ENTRY(ENTRY) (((ENTRY) == PMU_SLEEPENTRY_WFI) || ((ENTRY) == PMU_SLEEPENTRY_WFE)) +#define IS_PMU_STOP_ENTRY(ENTRY) (((ENTRY) == PMU_STOPENTRY_WFI) || ((ENTRY) == PMU_STOPENTRY_WFE)) +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + + +#endif /* APM32F4xx_DAL_PMU_H */ diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_pmu_ex.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_pmu_ex.h new file mode 100644 index 0000000000..359becd9c2 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_pmu_ex.h @@ -0,0 +1,257 @@ +/** + * + * @file apm32f4xx_dal_pmu_ex.h + * @brief Header file of PMU DAL Extension module. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2017 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file in + * the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef APM32F4xx_DAL_PMU_EX_H +#define APM32F4xx_DAL_PMU_EX_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal_def.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @addtogroup PMUEx + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ +/* Exported constants --------------------------------------------------------*/ +/** @defgroup PMUEx_Exported_Constants PMUEx Exported Constants + * @{ + */ + +/** @defgroup PMUEx_Regulator_Voltage_Scale PMUEx Regulator Voltage Scale + * @{ + */ +#if defined(APM32F405xx) || defined(APM32F407xx) || defined(APM32F417xx) || defined(APM32F465xx) +#define PMU_REGULATOR_VOLTAGE_SCALE1 PMU_CTRL_VOSSEL /* Scale 1 mode(default value at reset): the maximum value of fHCLK = 168 MHz. */ +#define PMU_REGULATOR_VOLTAGE_SCALE2 0x00000000U /* Scale 2 mode: the maximum value of fHCLK = 144 MHz. */ +#else +#define PMU_REGULATOR_VOLTAGE_SCALE1 PMU_CTRL_VOSSEL /* Scale 1 mode(default value at reset): the maximum value of fHCLK is 168 MHz. It can be extended to + 180 MHz by activating the over-drive mode. */ +#define PMU_REGULATOR_VOLTAGE_SCALE2 PMU_CTRL_VOSSEL_1 /* Scale 2 mode: the maximum value of fHCLK is 144 MHz. It can be extended to + 168 MHz by activating the over-drive mode. */ +#define PMU_REGULATOR_VOLTAGE_SCALE3 PMU_CTRL_VOSSEL_0 /* Scale 3 mode: the maximum value of fHCLK is 120 MHz. */ +#endif /* APM32F405xx || APM32F407xx || APM32F417xx || APM32F465xx */ +/** + * @} + */ + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ +/** @defgroup PMUEx_Exported_Constants PMUEx Exported Constants + * @{ + */ + +#if defined(APM32F405xx) || defined(APM32F407xx) || defined(APM32F417xx) || defined(APM32F465xx) +/** @brief macros configure the main internal regulator output voltage. + * @param __REGULATOR__ specifies the regulator output voltage to achieve + * a tradeoff between performance and power consumption when the device does + * not operate at the maximum frequency (refer to the datasheets for more details). + * This parameter can be one of the following values: + * @arg PMU_REGULATOR_VOLTAGE_SCALE1: Regulator voltage output Scale 1 mode + * @arg PMU_REGULATOR_VOLTAGE_SCALE2: Regulator voltage output Scale 2 mode + * @retval None + */ +#define __DAL_PMU_VOLTAGESCALING_CONFIG(__REGULATOR__) do { \ + __IO uint32_t tmpreg = 0x00U; \ + MODIFY_REG(PMU->CTRL, PMU_CTRL_VOSSEL, (__REGULATOR__)); \ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(PMU->CTRL, PMU_CTRL_VOSSEL); \ + UNUSED(tmpreg); \ + } while(0U) +#else +/** @brief macros configure the main internal regulator output voltage. + * @param __REGULATOR__ specifies the regulator output voltage to achieve + * a tradeoff between performance and power consumption when the device does + * not operate at the maximum frequency (refer to the datasheets for more details). + * This parameter can be one of the following values: + * @arg PMU_REGULATOR_VOLTAGE_SCALE1: Regulator voltage output Scale 1 mode + * @arg PMU_REGULATOR_VOLTAGE_SCALE2: Regulator voltage output Scale 2 mode + * @arg PMU_REGULATOR_VOLTAGE_SCALE3: Regulator voltage output Scale 3 mode + * @retval None + */ +#define __DAL_PMU_VOLTAGESCALING_CONFIG(__REGULATOR__) do { \ + __IO uint32_t tmpreg = 0x00U; \ + MODIFY_REG(PMU->CTRL, PMU_CTRL_VOSSEL, (__REGULATOR__)); \ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(PMU->CTRL, PMU_CTRL_VOSSEL); \ + UNUSED(tmpreg); \ + } while(0U) +#endif /* APM32F405xx || APM32F407xx || APM32F417xx || APM32F465xx */ + +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup PMUEx_Exported_Functions PMUEx Exported Functions + * @{ + */ + +/** @addtogroup PMUEx_Exported_Functions_Group1 + * @{ + */ +void DAL_PMUEx_EnableFlashPowerDown(void); +void DAL_PMUEx_DisableFlashPowerDown(void); +DAL_StatusTypeDef DAL_PMUEx_EnableBkUpReg(void); +DAL_StatusTypeDef DAL_PMUEx_DisableBkUpReg(void); +uint32_t DAL_PMUEx_GetVoltageRange(void); +DAL_StatusTypeDef DAL_PMUEx_ControlVoltageScaling(uint32_t VoltageScaling); + +#if defined(APM32F411xx) +void DAL_PMUEx_EnableMainRegulatorLowVoltage(void); +void DAL_PMUEx_DisableMainRegulatorLowVoltage(void); +void DAL_PMUEx_EnableLowRegulatorLowVoltage(void); +void DAL_PMUEx_DisableLowRegulatorLowVoltage(void); +#endif /* APM32F411xx */ + +/** + * @} + */ + +/** + * @} + */ +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/** @defgroup PMUEx_Private_Constants PMUEx Private Constants + * @{ + */ + +/** @defgroup PMUEx_register_alias_address PMUEx Register alias address + * @{ + */ +/* ------------- PMU registers bit address in the alias region ---------------*/ +/* --- CTRL Register ---*/ +/* Alias word address of FPDS bit */ +#define FPDSM_BIT_NUMBER PMU_CTRL_FPDSM_Pos +#define CTRL_FPDSM_BB (uint32_t)(PERIPH_BB_BASE + (PMU_CTRL_OFFSET_BB * 32U) + (FPDSM_BIT_NUMBER * 4U)) + +/* Alias word address of ODEN bit */ +#define ODEN_BIT_NUMBER PMU_CTRL_ODEN_Pos +#define CTRL_ODEN_BB (uint32_t)(PERIPH_BB_BASE + (PMU_CTRL_OFFSET_BB * 32U) + (ODEN_BIT_NUMBER * 4U)) + +/* Alias word address of ODSWEN bit */ +#define ODSWEN_BIT_NUMBER PMU_CTRL_ODSWEN_Pos +#define CTRL_ODSWEN_BB (uint32_t)(PERIPH_BB_BASE + (PMU_CTRL_OFFSET_BB * 32U) + (ODSWEN_BIT_NUMBER * 4U)) + +/* Alias word address of MRLVDS bit */ +#define MRLV_BIT_NUMBER PMU_CTRL_MRLV_Pos +#define CTRL_MRLV_BB (uint32_t)(PERIPH_BB_BASE + (PMU_CTRL_OFFSET_BB * 32U) + (MRLV_BIT_NUMBER * 4U)) + +/* Alias word address of LPLVDS bit */ +#define LPRLV_BIT_NUMBER PMU_CTRL_LPRLV_Pos +#define CTRL_LPRLV_BB (uint32_t)(PERIPH_BB_BASE + (PMU_CTRL_OFFSET_BB * 32U) + (LPRLV_BIT_NUMBER * 4U)) + + /** + * @} + */ + +/** @defgroup PMUEx_CSTS_register_alias PMUx CSTS Register alias address + * @{ + */ +/* --- CSTS Register ---*/ +/* Alias word address of BRE bit */ +#define BRE_BIT_NUMBER PMU_CSTS_BKPREN_Pos +#define CSTS_BKPREN_BB (uint32_t)(PERIPH_BB_BASE + (PMU_CSTS_OFFSET_BB * 32U) + (BRE_BIT_NUMBER * 4U)) + +/** + * @} + */ + +/** + * @} + */ + +/* Private macros ------------------------------------------------------------*/ +/** @defgroup PMUEx_Private_Macros PMUEx Private Macros + * @{ + */ + +/** @defgroup PMUEx_IS_PMU_Definitions PMUEx Private macros to check input parameters + * @{ + */ + +#if defined(APM32F405xx) || defined(APM32F407xx) || defined(APM32F417xx) || defined(APM32F465xx) +#define IS_PMU_VOLTAGE_SCALING_RANGE(VOLTAGE) (((VOLTAGE) == PMU_REGULATOR_VOLTAGE_SCALE1) || \ + ((VOLTAGE) == PMU_REGULATOR_VOLTAGE_SCALE2)) +#else +#define IS_PMU_VOLTAGE_SCALING_RANGE(VOLTAGE) (((VOLTAGE) == PMU_REGULATOR_VOLTAGE_SCALE1) || \ + ((VOLTAGE) == PMU_REGULATOR_VOLTAGE_SCALE2) || \ + ((VOLTAGE) == PMU_REGULATOR_VOLTAGE_SCALE3)) +#endif /* APM32F405xx || APM32F407xx || APM32F417xx || APM32F465xx */ + +#define IS_PMU_WAKEUP_PIN(PIN) ((PIN) == PMU_WAKEUP_PIN1) + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + + +#endif /* APM32F4xx_DAL_PMU_EX_H */ diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_qspi.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_qspi.h new file mode 100644 index 0000000000..253480111f --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_qspi.h @@ -0,0 +1,755 @@ +/** + * + * @file apm32f4xx_dal_qspi.h + * @brief Header file of QSPI DAL module. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2017 STMicroelectronics. + * Copyright (C) 2023-2024 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __APM32F4XX_DAL_QSPI_H +#define __APM32F4XX_DAL_QSPI_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal_def.h" + +#if defined (QSPI) + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @addtogroup QSPI + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ +/** @defgroup QSPI_Exported_Types QSPI Exported Types + * @{ + */ + +/** + * @brief QSPI Init structure definition + */ +typedef struct +{ + uint32_t ClockPrescaler; /*!< Specifies the prescaler factor for generating clock based on the AHB clock. + This parameter can be a even number between 2 and 65534. */ + + uint32_t ClockPhase; /*!< Specifies the clock data sample edge. + This parameter can be a value of @ref QSPI_ClockPhase */ + + uint32_t ClockPolarity; /*!< Specifies the clock valid level in the idle state. + This parameter can be a value of @ref QSPI_ClockPolarity */ + + uint32_t ClockStretch; /*!< Specifies the clock stretch enable/disable. + This parameter can be a value of ENABLE or DISABLE */ + + uint32_t TxFifoThreshold; /*!< Specifies the threshold level of the transmit FIFO. + This parameter can be a value between 0 and 7. */ + + uint32_t TxFifoLevel; /*!< Specifies the level of the transmit FIFO startup level. + This parameter can be a value between 0 and 7. */ + + uint32_t RxFifoThreshold; /*!< Specifies the threshold level of the receive FIFO. + This parameter can be a value between 0 and 7. */ + + uint32_t ChipSelectToggle; /*!< Specifies the Chip Select Toggle. + This parameter can be a value of @ref QSPI_ChipSelectToggle */ +} QSPI_InitTypeDef; + +/** + * @brief DAL QSPI State structures definition + */ +typedef enum +{ + DAL_QSPI_STATE_RESET = 0x00, /*!< QSPI not yet initialized or disabled */ + DAL_QSPI_STATE_READY = 0x01, /*!< QSPI initialized and ready for use */ + DAL_QSPI_STATE_BUSY = 0x02, /*!< QSPI internal process is ongoing */ + DAL_QSPI_STATE_BUSY_TX = 0x12, /*!< Data Transmission process is ongoing */ + DAL_QSPI_STATE_BUSY_RX = 0x22, /*!< Data Reception process is ongoing */ + DAL_QSPI_STATE_BUSY_TX_RX = 0x42, /*!< Data Transmission and Reception process is ongoing */ + DAL_QSPI_STATE_ERROR = 0x04, /*!< QSPI error state */ + DAL_QSPI_STATE_ABORT = 0x08, /*!< QSPI abort is ongoing */ +} DAL_QSPI_StateTypeDef; + +/** + * @brief QSPI handle Structure definition + */ +#if (USE_DAL_QSPI_REGISTER_CALLBACKS == 1) +typedef struct __QSPI_HandleTypeDef +#else +typedef struct +#endif +{ + QSPI_TypeDef *Instance; /*!< QSPI registers base address */ + + QSPI_InitTypeDef Init; /*!< QSPI communication parameters */ + + uint8_t *pTxBuffPtr; /*!< Pointer to QSPI Tx transfer Buffer */ + + __IO uint32_t TxXferSize; /*!< QSPI Tx Transfer size */ + + __IO uint32_t TxXferCount; /*!< QSPI Tx Transfer Counter */ + + uint8_t *pRxBuffPtr; /*!< Pointer to QSPI Rx transfer Buffer */ + + __IO uint32_t RxXferSize; /*!< QSPI Rx Transfer size */ + + __IO uint32_t RxXferCount; /*!< QSPI Rx Transfer Counter */ + + DMA_HandleTypeDef *hdmatx; /*!< QSPI Tx DMA handle parameters */ + + DMA_HandleTypeDef *hdmarx; /*!< QSPI Rx DMA handle parameters */ + + __IO DAL_LockTypeDef Lock; /*!< QSPI locking object */ + + __IO DAL_QSPI_StateTypeDef State; /*!< QSPI communication state */ + + __IO uint32_t ErrorCode; /*!< QSPI Error code */ + + uint32_t Timeout; /*!< QSPI timeout value */ +#if (USE_DAL_QSPI_REGISTER_CALLBACKS == 1) + void (* ErrorCallback) (struct __QSPI_HandleTypeDef *hqspi); /*!< QSPI Error Callback */ + void (* AbortCpltCallback) (struct __QSPI_HandleTypeDef *hqspi); /*!< QSPI Abort Complete Callback */ + void (* CmdCpltCallback) (struct __QSPI_HandleTypeDef *hqspi); /*!< QSPI Command Complete Callback */ + void (* RxCpltCallback) (struct __QSPI_HandleTypeDef *hqspi); /*!< QSPI Rx Complete Callback */ + void (* TxCpltCallback) (struct __QSPI_HandleTypeDef *hqspi); /*!< QSPI Tx Complete Callback */ + void (* TxRxCpltCallback) (struct __QSPI_HandleTypeDef *hqspi); /*!< QSPI Transfer Complete Callback */ + + void (* MspInitCallback) (struct __QSPI_HandleTypeDef *hqspi); /*!< QSPI Msp Init callback */ + void (* MspDeInitCallback) (struct __QSPI_HandleTypeDef *hqspi); /*!< QSPI Msp DeInit callback */ +#endif /* USE_DAL_QSPI_REGISTER_CALLBACKS */ +} QSPI_HandleTypeDef; + +/** + * @brief QSPI Command structure definition + */ +typedef struct +{ + uint32_t Instruction; /*!< Specifies the Instruction to be sent. + This parameter can be a value between 0x00 and 0xFF */ + + uint32_t Address; /*!< Specifies the Address to be sent. + This parameter can be a value between 0x00 and 0xFFFFFFFF */ + + uint32_t AddressSize; /*!< Specifies the Address Size. + This parameter can be a value of @ref QSPI_AddressSize */ + + uint32_t InstructionMode; /*!< Specifies the Instruction Mode. + This parameter can be a value of @ref QSPI_InstructionMode */ + + uint32_t InstructionSize; /*!< Specifies the Instruction Size. + This parameter can be a value of @ref QSPI_InstructionSize */ + + uint32_t TransferMode; /*!< Specifies the Transfer Mode. + This parameter can be a value of @ref QSPI_TransferMode */ + + uint32_t FrameFormat; /*!< Specifies the frame format. + This parameter can be a value of @ref QSPI_FrameFormat */ + + uint32_t DataFrameSize; /*!< Specifies the data frame size. + This parameter can be a value of @ref QSPI_DataFrameSize */ + + uint32_t DummyCycles; /*!< Specifies the Number of Dummy Cycles. + This parameter can be a number between 0 and 31 */ + + uint32_t NbData; /*!< Specifies the Number of Data to transfer. + This parameter can be a number between 0 and 0xFFFF */ +} QSPI_CommandTypeDef; + +#if (USE_DAL_QSPI_REGISTER_CALLBACKS == 1) +/** + * @brief DAL QSPI Callback ID enumeration definition + */ +typedef enum +{ + DAL_QSPI_ERROR_CB_ID = 0x00U, /*!< QSPI Error Callback ID */ + DAL_QSPI_ABORT_CB_ID = 0x01U, /*!< QSPI Abort Callback ID */ + DAL_QSPI_CMD_CPLT_CB_ID = 0x02U, /*!< QSPI Command Complete Callback ID */ + DAL_QSPI_RX_CPLT_CB_ID = 0x03U, /*!< QSPI Rx Complete Callback ID */ + DAL_QSPI_TX_CPLT_CB_ID = 0x04U, /*!< QSPI Tx Complete Callback ID */ + DAL_QSPI_TX_RX_CPLT_CB_ID = 0x05U, /*!< QSPI Transfer Complete Callback ID */ + + DAL_QSPI_MSP_INIT_CB_ID = 0x06U, /*!< QSPI MspInit callback ID */ + DAL_QSPI_MSP_DEINIT_CB_ID = 0x07U /*!< QSPI MspDeInit callback ID */ +} DAL_QSPI_CallbackIDTypeDef; + +/** + * @brief DAL QSPI Callback pointer definition + */ +typedef void (*pQSPI_CallbackTypeDef)(QSPI_HandleTypeDef *hqspi); /*!< pointer to an QSPI callback function */ +#endif /* USE_DAL_QSPI_REGISTER_CALLBACKS */ + +/** +* @} +*/ + +/* Exported constants --------------------------------------------------------*/ +/** @defgroup QSPI_Exported_Constants QSPI Exported Constants + * @{ + */ + +/** @defgroup QSPI_Error_Code QSPI Error Code + * @{ + */ +#define DAL_QSPI_ERROR_NONE 0x00000000U /*!< No error */ +#define DAL_QSPI_ERROR_TIMEOUT 0x00000001U /*!< Timeout error */ +#define DAL_QSPI_ERROR_TRANSFER 0x00000002U /*!< Transfer error */ +#define DAL_QSPI_ERROR_DMA 0x00000004U /*!< DMA transfer error */ +#define DAL_QSPI_ERROR_TX_OVR 0x00000008U /*!< Transmit FIFO Overrun */ +#define DAL_QSPI_ERROR_RX_OVR 0x00000010U /*!< Receive FIFO Overrun */ +#define DAL_QSPI_ERROR_RX_UDR 0x00000020U /*!< Receive FIFO UnderRun */ +#define DAL_QSPI_ERROR_MST 0x00000040U /*!< Master operation error*/ +#define DAL_QSPI_ERROR_INVALID_PARAM 0x00000080U /*!< Invalid parameter error */ +#if (USE_DAL_QSPI_REGISTER_CALLBACKS == 1) +#define DAL_QSPI_ERROR_INVALID_CALLBACK 0x00000100U /*!< Invalid Callback error */ +#endif /* USE_DAL_QSPI_REGISTER_CALLBACKS */ +/** + * @} + */ + +/** @defgroup QSPI_FrameFormat QSPI Frame Format + * @{ + */ +#define QSPI_FRAME_FORMAT_STANDARD 0x00000000U /*!< QSPI Standard frame format */ +#define QSPI_FRAME_FORMAT_DUAL QSPI_CTRL1_FRF_0 /*!< QSPI Dual frame format */ +#define QSPI_FRAME_FORMAT_QUAD QSPI_CTRL1_FRF_1 /*!< QSPI Quad frame format */ +/** + * @} + */ + +/** @defgroup QSPI_DataFrameSize QSPI Data Frame Size + * @{ + */ +#define QSPI_DATA_FRAME_SIZE_4BITS 0x00000003U /*!< QSPI data frame size 4 bits */ +#define QSPI_DATA_FRAME_SIZE_5BITS 0x00000004U /*!< QSPI data frame size 5 bits */ +#define QSPI_DATA_FRAME_SIZE_6BITS 0x00000005U /*!< QSPI data frame size 6 bits */ +#define QSPI_DATA_FRAME_SIZE_7BITS 0x00000006U /*!< QSPI data frame size 7 bits */ +#define QSPI_DATA_FRAME_SIZE_8BITS 0x00000007U /*!< QSPI data frame size 8 bits */ +#define QSPI_DATA_FRAME_SIZE_9BITS 0x00000008U /*!< QSPI data frame size 9 bits */ +#define QSPI_DATA_FRAME_SIZE_10BITS 0x00000009U /*!< QSPI data frame size 10 bits */ +#define QSPI_DATA_FRAME_SIZE_11BITS 0x0000000AU /*!< QSPI data frame size 11 bits */ +#define QSPI_DATA_FRAME_SIZE_12BITS 0x0000000BU /*!< QSPI data frame size 12 bits */ +#define QSPI_DATA_FRAME_SIZE_13BITS 0x0000000CU /*!< QSPI data frame size 13 bits */ +#define QSPI_DATA_FRAME_SIZE_14BITS 0x0000000DU /*!< QSPI data frame size 14 bits */ +#define QSPI_DATA_FRAME_SIZE_15BITS 0x0000000EU /*!< QSPI data frame size 15 bits */ +#define QSPI_DATA_FRAME_SIZE_16BITS 0x0000000FU /*!< QSPI data frame size 16 bits */ +#define QSPI_DATA_FRAME_SIZE_17BITS 0x00000010U /*!< QSPI data frame size 17 bits */ +#define QSPI_DATA_FRAME_SIZE_18BITS 0x00000011U /*!< QSPI data frame size 18 bits */ +#define QSPI_DATA_FRAME_SIZE_19BITS 0x00000012U /*!< QSPI data frame size 19 bits */ +#define QSPI_DATA_FRAME_SIZE_20BITS 0x00000013U /*!< QSPI data frame size 20 bits */ +#define QSPI_DATA_FRAME_SIZE_21BITS 0x00000014U /*!< QSPI data frame size 21 bits */ +#define QSPI_DATA_FRAME_SIZE_22BITS 0x00000015U /*!< QSPI data frame size 22 bits */ +#define QSPI_DATA_FRAME_SIZE_23BITS 0x00000016U /*!< QSPI data frame size 23 bits */ +#define QSPI_DATA_FRAME_SIZE_24BITS 0x00000017U /*!< QSPI data frame size 24 bits */ +#define QSPI_DATA_FRAME_SIZE_25BITS 0x00000018U /*!< QSPI data frame size 25 bits */ +#define QSPI_DATA_FRAME_SIZE_26BITS 0x00000019U /*!< QSPI data frame size 26 bits */ +#define QSPI_DATA_FRAME_SIZE_27BITS 0x0000001AU /*!< QSPI data frame size 27 bits */ +#define QSPI_DATA_FRAME_SIZE_28BITS 0x0000001BU /*!< QSPI data frame size 28 bits */ +#define QSPI_DATA_FRAME_SIZE_29BITS 0x0000001CU /*!< QSPI data frame size 29 bits */ +#define QSPI_DATA_FRAME_SIZE_30BITS 0x0000001DU /*!< QSPI data frame size 30 bits */ +#define QSPI_DATA_FRAME_SIZE_31BITS 0x0000001EU /*!< QSPI data frame size 31 bits */ +#define QSPI_DATA_FRAME_SIZE_32BITS 0x0000001FU /*!< QSPI data frame size 32 bits */ + +/** + * @} + */ + +/** @defgroup QSPI_ClockPhase QSPI Clock Phase + * @{ + */ +#define QSPI_CLOCK_PHASE_1ST_EDGE 0x00000000U /*!< QSPI clock active high on the first edge and inactive low on the second edge */ +#define QSPI_CLOCK_PHASE_2ND_EDGE QSPI_CTRL1_CPHA /*!< QSPI clock active low on the first edge and inactive high on the second edge */ +/** + * @} + */ + +/** @defgroup QSPI_ClockPolarity QSPI Clock Polarity + * @{ + */ +#define QSPI_CLOCK_POLARITY_LOW 0x00000000U /*!< QSPI clock inactive state is low */ +#define QSPI_CLOCK_POLARITY_HIGH QSPI_CTRL1_CPOL /*!< QSPI clock inactive state is high */ +/** + * @} + */ + +/** @defgroup QSPI_ChipSelectToggle QSPI Chip Select ChipSelectToggle + * @{ + */ +#define QSPI_CS_TOGGLE_DISABLE 0x00000000U /*!< QSPI chip select signal doesn't toggle between frames */ +#define QSPI_CS_TOGGLE_ENABLE QSPI_CTRL1_SSTEN /*!< QSPI chip select signal toggles between frames */ +/** + * @} + */ + +/** @defgroup QSPI_TransferMode QSPI Transfer Mode + * @{ + */ +#define QSPI_TRANSFER_MODE_TX_RX 0x00000000U /*!< QSPI in transmit/receive mode */ +#define QSPI_TRANSFER_MODE_TX QSPI_CTRL1_TXMODE_0 /*!< QSPI in transmit only mode */ +#define QSPI_TRANSFER_MODE_RX QSPI_CTRL1_TXMODE_1 /*!< QSPI in receive only mode */ +#define QSPI_TRANSFER_MODE_EEPROM_READ (QSPI_CTRL1_TXMODE_1 | QSPI_CTRL1_TXMODE_0) /*!< QSPI in EEPROM read mode */ +/** + * @} + */ + +/** @defgroup QSPI_RXDSampleEdge QSPI RXD Sample Edge + * @{ + */ +#define QSPI_RXD_SAMPLE_EDGE_RISING 0x00000000U /*!< QSPI RXD sample on rising edge */ +#define QSPI_RXD_SAMPLE_EDGE_FALLING QSPI_RSD_RSE /*!< QSPI RXD sample on falling edge */ +/** + * @} + */ + +/** @defgroup QSPI_InstructionSize QSPI Instruction Size + * @{ + */ +#define QSPI_INSTRUCTION_SIZE_NONE 0x00000000U /*!< No instruction */ +#define QSPI_INSTRUCTION_SIZE_4_BITS QSPI_CTRL3_INSLEN_0 /*!< Instruction on 4 bits */ +#define QSPI_INSTRUCTION_SIZE_8_BITS QSPI_CTRL3_INSLEN_1 /*!< Instruction on 8 bits */ +#define QSPI_INSTRUCTION_SIZE_16_BITS (QSPI_CTRL3_INSLEN_1 | QSPI_CTRL3_INSLEN_0) /*!< Instruction on 16 bits */ +/** + * @} + */ + +/** @defgroup QSPI_InstructionMode QSPI Instruction Mode + * @{ + */ +#define QSPI_INSTRUCTION_STANDARD_INS_ADDR 0x00000000U /*!< Send instruction and address in standard SPI mode */ +#define QSPI_INSTRUCTION_STANDARD_INS QSPI_CTRL3_IAT_0 /*!< Send instruction only in standard SPI mode */ +#define QSPI_INSTRUCTION_FRF_INS_ADDR QSPI_CTRL3_IAT_1 /*!< Send instruction and address in FRF mode */ +/** + * @} + */ + +/** @defgroup QSPI_AddressSize QSPI Address Size + * @{ + */ +#define QSPI_ADDRESS_SIZE_NONE 0x00000000U /*!< No address */ +#define QSPI_ADDRESS_SIZE_4_BITS (QSPI_CTRL3_ADDRLEN_0) /*!< Address on 4 bits */ +#define QSPI_ADDRESS_SIZE_8_BITS (QSPI_CTRL3_ADDRLEN_1) /*!< Address on 8 bits */ +#define QSPI_ADDRESS_SIZE_12_BITS (QSPI_CTRL3_ADDRLEN_1 | QSPI_CTRL3_ADDRLEN_0) /*!< Address on 12 bits */ +#define QSPI_ADDRESS_SIZE_16_BITS (QSPI_CTRL3_ADDRLEN_2) /*!< Address on 16 bits */ +#define QSPI_ADDRESS_SIZE_20_BITS (QSPI_CTRL3_ADDRLEN_2 | QSPI_CTRL3_ADDRLEN_0) /*!< Address on 20 bits */ +#define QSPI_ADDRESS_SIZE_24_BITS (QSPI_CTRL3_ADDRLEN_2 | QSPI_CTRL3_ADDRLEN_1) /*!< Address on 24 bits */ +#define QSPI_ADDRESS_SIZE_28_BITS (QSPI_CTRL3_ADDRLEN_2 | QSPI_CTRL3_ADDRLEN_1 | \ + QSPI_CTRL3_ADDRLEN_0) /*!< Address on 28 bits */ +#define QSPI_ADDRESS_SIZE_32_BITS (QSPI_CTRL3_ADDRLEN_3) /*!< Address on 32 bits */ +#define QSPI_ADDRESS_SIZE_36_BITS (QSPI_CTRL3_ADDRLEN_3 | QSPI_CTRL3_ADDRLEN_0) /*!< Address on 36 bits */ +#define QSPI_ADDRESS_SIZE_40_BITS (QSPI_CTRL3_ADDRLEN_3 | QSPI_CTRL3_ADDRLEN_1) /*!< Address on 40 bits */ +#define QSPI_ADDRESS_SIZE_44_BITS (QSPI_CTRL3_ADDRLEN_3 | QSPI_CTRL3_ADDRLEN_1 | \ + QSPI_CTRL3_ADDRLEN_0) /*!< Address on 44 bits */ +#define QSPI_ADDRESS_SIZE_48_BITS (QSPI_CTRL3_ADDRLEN_3 | QSPI_CTRL3_ADDRLEN_2) /*!< Address on 48 bits */ +#define QSPI_ADDRESS_SIZE_52_BITS (QSPI_CTRL3_ADDRLEN_3 | QSPI_CTRL3_ADDRLEN_2 | \ + QSPI_CTRL3_ADDRLEN_0) /*!< Address on 52 bits */ +#define QSPI_ADDRESS_SIZE_56_BITS (QSPI_CTRL3_ADDRLEN_3 | QSPI_CTRL3_ADDRLEN_2 | \ + QSPI_CTRL3_ADDRLEN_1) /*!< Address on 56 bits */ +#define QSPI_ADDRESS_SIZE_60_BITS (QSPI_CTRL3_ADDRLEN_3 | QSPI_CTRL3_ADDRLEN_2 | \ + QSPI_CTRL3_ADDRLEN_1 | QSPI_CTRL3_ADDRLEN_0) /*!< Address on 60 bits */ + +/** + * @} + */ + +/** @defgroup QSPI_Flags QSPI Flags + * @{ + */ +#define QSPI_FLAG_BUSY QSPI_STS_BUSYF /*!< QSPI busy flag */ +#define QSPI_FLAG_TFN QSPI_STS_TFNF /*!< QSPI transmit FIFO not full flag */ +#define QSPI_FLAG_TFE QSPI_STS_TFEF /*!< QSPI transmit FIFO empty flag */ +#define QSPI_FLAG_RFNE QSPI_STS_RFNEF /*!< QSPI receive FIFO not empty flag */ +#define QSPI_FLAG_RFF QSPI_STS_RFFF /*!< QSPI receive FIFO full flag */ +#define QSPI_FLAG_DCE QSPI_STS_DCEF /*!< QSPI data collision error flag */ +/** + * @} + */ + +/** @defgroup QSPI_Interrupts QSPI Interrupts + * @{ + */ +#define QSPI_IT_TFE QSPI_INTEN_TFEIE /*!< QSPI transmit FIFO interrupt */ +#define QSPI_IT_TFO QSPI_INTEN_TFOIE /*!< QSPI transmit FIFO overflow interrupt */ +#define QSPI_IT_RFU QSPI_INTEN_RFUIE /*!< QSPI receive FIFO underflow interrupt */ +#define QSPI_IT_RFO QSPI_INTEN_RFOIE /*!< QSPI receive FIFO overflow interrupt */ +#define QSPI_IT_RFF QSPI_INTEN_RFFIE /*!< QSPI receive FIFO full interrupt */ +#define QSPI_IT_MST QSPI_INTEN_MSTIE /*!< QSPI master operation complete interrupt */ +#define QSPI_IT_ICF 0xFFFFFFFFU /*!< QSPI FIFO status and master operation interrupt */ +/** + * @} + */ + +/** @defgroup QSPI_Timeout_definition QSPI Timeout definition + * @{ + */ +#define DAL_QSPI_TIMEOUT_DEFAULT_VALUE 5000U /*!< 5 s */ +/** + * @} + */ + +/** + * @} + */ + +/* Exported macros -----------------------------------------------------------*/ +/** @defgroup QSPI_Exported_Macros QSPI Exported Macros + * @{ + */ + +/** @brief Reset QSPI handle state + * @param __HANDLE__ specifies the QSPI handle. + * @retval None + */ +#if (USE_DAL_QSPI_REGISTER_CALLBACKS == 1) +#define __DAL_QSPI_RESET_HANDLE_STATE(__HANDLE__) do{ \ + (__HANDLE__)->State = DAL_QSPI_STATE_RESET; \ + (__HANDLE__)->MspInitCallback = NULL; \ + (__HANDLE__)->MspDeInitCallback = NULL; \ + } while(0) +#else +#define __DAL_QSPI_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = DAL_QSPI_STATE_RESET) +#endif /* USE_DAL_QSPI_REGISTER_CALLBACKS */ + +/** + * @brief Enable the specified QSPI peripheral. + * @param __HANDLE__ specifies the QSPI Handle. + * @retval None + */ +#define __DAL_QSPI_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->SSIEN |= QSPI_SSIEN_EN) + +/** + * @brief Disable the specified QSPI peripheral. + * @param __HANDLE__ specifies the QSPI Handle. + * @retval None + */ +#define __DAL_QSPI_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->SSIEN &= ~QSPI_SSIEN_EN) + +/** + * @brief Enable the slave select signal. + * @param __HANDLE__ specifies the QSPI Handle. + * @retval None + */ +#define __DAL_QSPI_ENABLE_SS(__HANDLE__) ((__HANDLE__)->Instance->SLAEN |= QSPI_SLAEN_SLAEN) + +/** + * @brief Disable the slave select signal. + * @param __HANDLE__ specifies the QSPI Handle. + * @retval None + */ +#define __DAL_QSPI_DISABLE_SS(__HANDLE__) ((__HANDLE__)->Instance->SLAEN &= ~QSPI_SLAEN_SLAEN) + +/** + * @brief Disable the specified QSPI clock output. + * @param __HANDLE__ specifies the QSPI Handle. + * @retval None + */ +#define __DAL_QSPI_DISABLE_CLK(__HANDLE__) ((__HANDLE__)->Instance->BR &= ~QSPI_BR_CLKDIV) + +/** + * @brief Enable the specified QSPI interrupts. + * @param __HANDLE__ specifies the QSPI Handle. + * @param __INTERRUPT__ specifies the interrupt source to enable. + * This parameter can be one of the following values: + * @arg QSPI_IT_TFE: QSPI transmit FIFO interrupt + * @arg QSPI_IT_TFO: QSPI transmit FIFO overflow interrupt + * @arg QSPI_IT_RFU: QSPI receive FIFO underflow interrupt + * @arg QSPI_IT_RFO: QSPI receive FIFO overflow interrupt + * @arg QSPI_IT_RFF: QSPI receive FIFO full interrupt + * @arg QSPI_IT_MST: QSPI master operation complete interrupt + * @retval None + */ +#define __DAL_QSPI_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->INTEN |= (__INTERRUPT__)) + +/** + * @brief Disable the specified QSPI interrupts. + * @param __HANDLE__ specifies the QSPI Handle. + * @param __INTERRUPT__ specifies the interrupt source to disable. + * This parameter can be one of the following values: + * @arg QSPI_IT_TFE: QSPI transmit FIFO interrupt + * @arg QSPI_IT_TFO: QSPI transmit FIFO overflow interrupt + * @arg QSPI_IT_RFU: QSPI receive FIFO underflow interrupt + * @arg QSPI_IT_RFO: QSPI receive FIFO overflow interrupt + * @arg QSPI_IT_RFF: QSPI receive FIFO full interrupt + * @arg QSPI_IT_MST: QSPI master operation complete interrupt + * @retval None + */ +#define __DAL_QSPI_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->INTEN &= ~(__INTERRUPT__)) + +/** + * @brief Check whether the specified QSPI interrupt source is enabled or not. + * @param __HANDLE__ specifies the QSPI Handle. + * @param __INTERRUPT__ specifies the QSPI interrupt source to check. + * This parameter can be one of the following values: + * @arg QSPI_IT_TFE: QSPI transmit FIFO interrupt + * @arg QSPI_IT_TFO: QSPI transmit FIFO overflow interrupt + * @arg QSPI_IT_RFU: QSPI receive FIFO underflow interrupt + * @arg QSPI_IT_RFO: QSPI receive FIFO overflow interrupt + * @arg QSPI_IT_RFF: QSPI receive FIFO full interrupt + * @arg QSPI_IT_MST: QSPI master operation complete interrupt + * @retval The new state of __INTERRUPT__ (TRUE or FALSE). + */ +#define __DAL_QSPI_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) ((((__HANDLE__)->Instance->ISTS & (__INTERRUPT__)) == (__INTERRUPT__)) ? SET : RESET) + +/** + * @brief Check whether the specified QSPI flag is set or not. + * @param __HANDLE__ specifies the QSPI Handle. + * @param __FLAG__ specifies the QSPI flag to check. + * This parameter can be one of the following values: + * @arg QSPI_FLAG_BUSY: QSPI busy flag + * @arg QSPI_FLAG_TFN: QSPI transmit FIFO not full flag + * @arg QSPI_FLAG_TFE: QSPI transmit FIFO empty flag + * @arg QSPI_FLAG_RFNE: QSPI receive FIFO not empty flag + * @arg QSPI_FLAG_RFF: QSPI receive FIFO full flag + * @arg QSPI_FLAG_DCE: QSPI data collision error flag + * @retval The new state of __FLAG__ (TRUE or FALSE). + */ +#define __DAL_QSPI_GET_FLAG(__HANDLE__, __FLAG__) ((((__HANDLE__)->Instance->STS & (__FLAG__)) != 0U) ? SET : RESET) + +/** + * @brief Clear the specified QSPI flag. + * @param __HANDLE__ specifies the QSPI Handle. + * @param __FLAG__ specifies the QSPI flag to clear. + * This parameter can be one of the following values: + * @arg QSPI_IT_TFO: QSPI transmit FIFO overflow interrupt + * @arg QSPI_IT_RFU: QSPI receive FIFO underflow interrupt + * @arg QSPI_IT_RFO: QSPI receive FIFO overflow interrupt + * @arg QSPI_IT_MST: QSPI master operation complete interrupt + * @arg QSPI_IT_ICF: QSPI FIFO status and master operation interrupt + * @retval None + */ +#define __DAL_QSPI_CLEAR_FLAG(__HANDLE__, __FLAG__) do { \ + __IO uint32_t tmpreg = 0x00U; \ + if ((__FLAG__) == QSPI_IT_TFO) \ + { \ + tmpreg = (__HANDLE__)->Instance->TFOIC; \ + } \ + else if ((__FLAG__) == QSPI_IT_RFU) \ + { \ + tmpreg = (__HANDLE__)->Instance->RFUIC; \ + } \ + else if ((__FLAG__) == QSPI_IT_RFO) \ + { \ + tmpreg = (__HANDLE__)->Instance->RFOIC; \ + } \ + else if ((__FLAG__) == QSPI_IT_MST) \ + { \ + tmpreg = (__HANDLE__)->Instance->MIC; \ + } \ + else if ((__FLAG__) == QSPI_IT_ICF) \ + { \ + tmpreg = (__HANDLE__)->Instance->ICF; \ + } \ + else \ + { \ + /* Do nothing */ \ + } \ + UNUSED(tmpreg); \ + } while(0) + + /** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup QSPI_Exported_Functions + * @{ + */ + +/** @addtogroup QSPI_Exported_Functions_Group1 + * @{ + */ + +/* Initialization/de-initialization functions ********************************/ +DAL_StatusTypeDef DAL_QSPI_Init(QSPI_HandleTypeDef *hqspi); +DAL_StatusTypeDef DAL_QSPI_DeInit(QSPI_HandleTypeDef *hqspi); +void DAL_QSPI_MspInit(QSPI_HandleTypeDef *hqspi); +void DAL_QSPI_MspDeInit(QSPI_HandleTypeDef *hqspi); +/** + * @} + */ + +/** @addtogroup QSPI_Exported_Functions_Group2 + * @{ + */ + +/* I/O operation functions ***************************************************/ +/* QSPI IRQ handler method */ +void DAL_QSPI_IRQHandler(QSPI_HandleTypeDef *hqspi); + +/* Transmit/Receive functions ***********************************************/ +DAL_StatusTypeDef DAL_QSPI_Command(QSPI_HandleTypeDef *hqspi, QSPI_CommandTypeDef *cmd, uint32_t Timeout); +DAL_StatusTypeDef DAL_QSPI_TransmitReceive(QSPI_HandleTypeDef *hqspi, uint8_t *data_out, uint8_t *data_in, uint32_t Size, uint32_t Timeout); +DAL_StatusTypeDef DAL_QSPI_Transmit(QSPI_HandleTypeDef *hqspi, uint8_t *pData, uint32_t Timeout); +DAL_StatusTypeDef DAL_QSPI_Receive(QSPI_HandleTypeDef *hqspi, uint8_t *pData, uint32_t Timeout); + +DAL_StatusTypeDef DAL_QSPI_Command_IT(QSPI_HandleTypeDef *hqspi, QSPI_CommandTypeDef *cmd); +DAL_StatusTypeDef DAL_QSPI_TransmitReceive_IT(QSPI_HandleTypeDef *hqspi, uint8_t *data_out, uint8_t *data_in, uint32_t Size); +DAL_StatusTypeDef DAL_QSPI_Transmit_IT(QSPI_HandleTypeDef *hqspi, uint8_t *pData); +DAL_StatusTypeDef DAL_QSPI_Receive_IT(QSPI_HandleTypeDef *hqspi, uint8_t *pData); + +DAL_StatusTypeDef DAL_QSPI_Transmit_DMA(QSPI_HandleTypeDef *hqspi, uint8_t *pData); +DAL_StatusTypeDef DAL_QSPI_Receive_DMA(QSPI_HandleTypeDef *hqspi, uint8_t *pData); + +/* Callbacks functions *******************************************************/ +void DAL_QSPI_ErrorCallback(QSPI_HandleTypeDef *hqspi); +void DAL_QSPI_AbortCpltCallback(QSPI_HandleTypeDef *hqspi); + +void DAL_QSPI_CmdCpltCallback(QSPI_HandleTypeDef *hqspi); +void DAL_QSPI_RxCpltCallback(QSPI_HandleTypeDef *hqspi); +void DAL_QSPI_TxCpltCallback(QSPI_HandleTypeDef *hqspi); +void DAL_QSPI_TxRxCpltCallback(QSPI_HandleTypeDef *hqspi); + +#if (USE_DAL_QSPI_REGISTER_CALLBACKS == 1) +/* Callbacks Register/UnRegister functions ***********************************/ +DAL_StatusTypeDef DAL_QSPI_RegisterCallback(QSPI_HandleTypeDef *hqspi, DAL_QSPI_CallbackIDTypeDef CallbackID, pQSPI_CallbackTypeDef pCallback); +DAL_StatusTypeDef DAL_QSPI_UnRegisterCallback(QSPI_HandleTypeDef *hqspi, DAL_QSPI_CallbackIDTypeDef CallbackID); +#endif /* USE_DAL_QSPI_REGISTER_CALLBACKS */ +/** + * @} + */ + +/** @addtogroup QSPI_Exported_Functions_Group3 + * @{ + */ + +/* Peripheral Control and State functions ************************************/ +DAL_QSPI_StateTypeDef DAL_QSPI_GetState(QSPI_HandleTypeDef *hqspi); +uint32_t DAL_QSPI_GetError(QSPI_HandleTypeDef *hqspi); +DAL_StatusTypeDef DAL_QSPI_Abort(QSPI_HandleTypeDef *hqspi); +DAL_StatusTypeDef DAL_QSPI_Abort_IT(QSPI_HandleTypeDef *hqspi); +void DAL_QSPI_SetTimeout(QSPI_HandleTypeDef *hqspi, uint32_t Timeout); +DAL_StatusTypeDef DAL_QSPI_SetTxFifoThreshold(QSPI_HandleTypeDef *hqspi, uint32_t Threshold); +DAL_StatusTypeDef DAL_QSPI_SetTxFifoLevel(QSPI_HandleTypeDef *hqspi, uint32_t Level); +DAL_StatusTypeDef DAL_QSPI_SetRxFifoThreshold(QSPI_HandleTypeDef *hqspi, uint32_t Threshold); +uint32_t DAL_QSPI_GetTxFifoThreshold(QSPI_HandleTypeDef *hqspi); +uint32_t DAL_QSPI_GetTxFifoLevel(QSPI_HandleTypeDef *hqspi); +uint32_t DAL_QSPI_GetRxFifoThreshold(QSPI_HandleTypeDef *hqspi); + +DAL_StatusTypeDef DAL_QSPI_SetFrameFormat(QSPI_HandleTypeDef *hqspi, uint32_t FrameFormat); +DAL_StatusTypeDef DAL_QSPI_SetDataFrameSize(QSPI_HandleTypeDef *hqspi, uint32_t DataFrameSize); +DAL_StatusTypeDef DAL_QSPI_SetTransferMode(QSPI_HandleTypeDef *hqspi, uint32_t TransferMode); +DAL_StatusTypeDef DAL_QSPI_SetFrameNbData(QSPI_HandleTypeDef *hqspi, uint32_t NbData); +uint32_t DAL_QSPI_GetFrameFormat(QSPI_HandleTypeDef *hqspi); +uint32_t DAL_QSPI_GetDataFrameSize(QSPI_HandleTypeDef *hqspi); +uint32_t DAL_QSPI_GetTransferMode(QSPI_HandleTypeDef *hqspi); +uint32_t DAL_QSPI_GetFrameNbData(QSPI_HandleTypeDef *hqspi); +/** + * @} + */ + +/** + * @} + */ + +/* Private macros ------------------------------------------------------------*/ +/** @defgroup QSPI_Private_Macros QSPI Private Macros + * @{ + */ +#define IS_QSPI_CLOCK_PRESCALER(__PRESCALER__) (((__PRESCALER__) >= 2U) && ((__PRESCALER__) <= 65534U) && (((__PRESCALER__) & 0x1U) == 0U)) + +#define IS_QSPI_FRAME_FORMAT(__FORMAT__) (((__FORMAT__) == QSPI_FRAME_FORMAT_STANDARD) || \ + ((__FORMAT__) == QSPI_FRAME_FORMAT_DUAL) || \ + ((__FORMAT__) == QSPI_FRAME_FORMAT_QUAD)) + +#define IS_QSPI_DATA_FRAME_SIZE(__SIZE__) (((__SIZE__) >= 3U) && ((__SIZE__) <= 31U)) + +#define IS_QSPI_CLOCK_PHASE(__PHASE__) (((__PHASE__) == QSPI_CLOCK_PHASE_1ST_EDGE) || \ + ((__PHASE__) == QSPI_CLOCK_PHASE_2ND_EDGE)) + +#define IS_QSPI_CLOCK_POLARITY(__POLARITY__) (((__POLARITY__) == QSPI_CLOCK_POLARITY_LOW) || \ + ((__POLARITY__) == QSPI_CLOCK_POLARITY_HIGH)) + +#define IS_QSPI_CLOCK_STRETCH(__STRETCH__) (((__STRETCH__) == ENABLE) || \ + ((__STRETCH__) == DISABLE)) + +#define IS_QSPI_TX_FIFO_THRESHOLD(__THRESHOLD__) (((__THRESHOLD__) >= 0U) && ((__THRESHOLD__) <= 7U)) + +#define IS_QSPI_TX_FIFO_LEVEL(__LEVEL__) (((__LEVEL__) >= 0U) && ((__LEVEL__) <= 7U)) + +#define IS_QSPI_RX_FIFO_THRESHOLD(__THRESHOLD__) (((__THRESHOLD__) >= 0U) && ((__THRESHOLD__) <= 7U)) + +#define IS_QSPI_CHIP_SELECT_TOGGLE(__TOGGLE__) (((__TOGGLE__) == QSPI_CS_TOGGLE_DISABLE) || \ + ((__TOGGLE__) == QSPI_CS_TOGGLE_ENABLE)) + +#define IS_QSPI_TRANSFER_MODE(__MODE__) (((__MODE__) == QSPI_TRANSFER_MODE_TX_RX) || \ + ((__MODE__) == QSPI_TRANSFER_MODE_TX) || \ + ((__MODE__) == QSPI_TRANSFER_MODE_RX) || \ + ((__MODE__) == QSPI_TRANSFER_MODE_EEPROM_READ)) + +#define IS_QSPI_RXD_SAMPLE_EDGE(__EDGE__) (((__EDGE__) == QSPI_RXD_SAMPLE_EDGE_RISING) || \ + ((__EDGE__) == QSPI_RXD_SAMPLE_EDGE_FALLING)) + +#define IS_QSPI_INSTRUCTION_SIZE(__SIZE__) (((__SIZE__) == QSPI_INSTRUCTION_SIZE_NONE) || \ + ((__SIZE__) == QSPI_INSTRUCTION_SIZE_4_BITS) || \ + ((__SIZE__) == QSPI_INSTRUCTION_SIZE_8_BITS) || \ + ((__SIZE__) == QSPI_INSTRUCTION_SIZE_16_BITS)) + +#define IS_QSPI_INSTRUCTION_MODE(__MODE__) (((__MODE__) == QSPI_INSTRUCTION_STANDARD_INS_ADDR) || \ + ((__MODE__) == QSPI_INSTRUCTION_STANDARD_INS) || \ + ((__MODE__) == QSPI_INSTRUCTION_FRF_INS_ADDR)) + +#define IS_QSPI_INSTRUCTION(__INSTRUCTION__) ((__INSTRUCTION__) <= 0xFFU) + +#define IS_QSPI_ADDRESS_SIZE(__SIZE__) ((__SIZE__) >= QSPI_ADDRESS_SIZE_NONE && (__SIZE__) <= QSPI_ADDRESS_SIZE_60_BITS) + +#define IS_QSPI_ADDRESS(__ADDRESS__) ((__ADDRESS__) <= 0xFFFFFFFFU) + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#endif /* QSPI */ + +#ifdef __cplusplus +} +#endif + +#endif /* __APM32F4XX_DAL_QSPI_H */ + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_rcm.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_rcm.h new file mode 100644 index 0000000000..bbd4b1eb4a --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_rcm.h @@ -0,0 +1,1482 @@ +/** + * + * @file apm32f4xx_dal_rcm.h + * @brief Header file of RCM DAL module. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2017 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file in + * the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef APM32F4xx_DAL_RCM_H +#define APM32F4xx_DAL_RCM_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal_def.h" + +/* Include RCM DAL Extended module */ +/* (include on top of file since RCM structures are defined in extended file) */ +#include "apm32f4xx_dal_rcm_ex.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @addtogroup RCM + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ +/** @defgroup RCM_Exported_Types RCM Exported Types + * @{ + */ + +/** + * @brief RCM Internal/External Oscillator (HSE, HSI, LSE and LSI) configuration structure definition + */ +typedef struct +{ + uint32_t OscillatorType; /*!< The oscillators to be configured. + This parameter can be a value of @ref RCM_Oscillator_Type */ + + uint32_t HSEState; /*!< The new state of the HSE. + This parameter can be a value of @ref RCM_HSE_Config */ + + uint32_t LSEState; /*!< The new state of the LSE. + This parameter can be a value of @ref RCM_LSE_Config */ + + uint32_t HSIState; /*!< The new state of the HSI. + This parameter can be a value of @ref RCM_HSI_Config */ + + uint32_t HSICalibrationValue; /*!< The HSI calibration trimming value (default is RCM_HSICALIBRATION_DEFAULT). + This parameter must be a number between Min_Data = 0x00 and Max_Data = 0x1F */ + + uint32_t LSIState; /*!< The new state of the LSI. + This parameter can be a value of @ref RCM_LSI_Config */ + + RCM_PLLInitTypeDef PLL; /*!< PLL structure parameters */ +}RCM_OscInitTypeDef; + +/** + * @brief RCM System, AHB and APB busses clock configuration structure definition + */ +typedef struct +{ + uint32_t ClockType; /*!< The clock to be configured. + This parameter can be a value of @ref RCM_System_Clock_Type */ + + uint32_t SYSCLKSource; /*!< The clock source (SYSCLKS) used as system clock. + This parameter can be a value of @ref RCM_System_Clock_Source */ + + uint32_t AHBCLKDivider; /*!< The AHB clock (HCLK) divider. This clock is derived from the system clock (SYSCLK). + This parameter can be a value of @ref RCM_AHB_Clock_Source */ + + uint32_t APB1CLKDivider; /*!< The APB1 clock (PCLK1) divider. This clock is derived from the AHB clock (HCLK). + This parameter can be a value of @ref RCM_APB1_APB2_Clock_Source */ + + uint32_t APB2CLKDivider; /*!< The APB2 clock (PCLK2) divider. This clock is derived from the AHB clock (HCLK). + This parameter can be a value of @ref RCM_APB1_APB2_Clock_Source */ + +}RCM_ClkInitTypeDef; + +/** + * @} + */ + +/* Exported constants --------------------------------------------------------*/ +/** @defgroup RCM_Exported_Constants RCM Exported Constants + * @{ + */ + +/** @defgroup RCM_Oscillator_Type Oscillator Type + * @{ + */ +#define RCM_OSCILLATORTYPE_NONE 0x00000000U +#define RCM_OSCILLATORTYPE_HSE 0x00000001U +#define RCM_OSCILLATORTYPE_HSI 0x00000002U +#define RCM_OSCILLATORTYPE_LSE 0x00000004U +#define RCM_OSCILLATORTYPE_LSI 0x00000008U +/** + * @} + */ + +/** @defgroup RCM_HSE_Config HSE Config + * @{ + */ +#define RCM_HSE_OFF 0x00000000U +#define RCM_HSE_ON RCM_CTRL_HSEEN +#define RCM_HSE_BYPASS ((uint32_t)(RCM_CTRL_HSEBCFG | RCM_CTRL_HSEEN)) +/** + * @} + */ + +/** @defgroup RCM_LSE_Config LSE Config + * @{ + */ +#define RCM_LSE_OFF 0x00000000U +#define RCM_LSE_ON RCM_BDCTRL_LSEEN +#define RCM_LSE_BYPASS ((uint32_t)(RCM_BDCTRL_LSEBCFG | RCM_BDCTRL_LSEEN)) +/** + * @} + */ + +/** @defgroup RCM_HSI_Config HSI Config + * @{ + */ +#define RCM_HSI_OFF ((uint8_t)0x00) +#define RCM_HSI_ON ((uint8_t)0x01) + +#define RCM_HSICALIBRATION_DEFAULT 0x10U /* Default HSI calibration trimming value */ +/** + * @} + */ + +/** @defgroup RCM_LSI_Config LSI Config + * @{ + */ +#define RCM_LSI_OFF ((uint8_t)0x00) +#define RCM_LSI_ON ((uint8_t)0x01) +/** + * @} + */ + +/** @defgroup RCM_PLL_Config PLL Config + * @{ + */ +#define RCM_PLL_NONE ((uint8_t)0x00) +#define RCM_PLL_OFF ((uint8_t)0x01) +#define RCM_PLL_ON ((uint8_t)0x02) +/** + * @} + */ + +/** @defgroup RCM_PLL1C_Clock_Divider PLL1C Clock Divider + * @{ + */ +#define RCM_PLL1C_DIV2 0x00000002U +#define RCM_PLL1C_DIV4 0x00000004U +#define RCM_PLL1C_DIV6 0x00000006U +#define RCM_PLL1C_DIV8 0x00000008U +/** + * @} + */ + +/** @defgroup RCM_PLL_Clock_Source PLL Clock Source + * @{ + */ +#define RCM_PLLSOURCE_HSI RCM_PLL1CFG_PLL1CLKS_HSI +#define RCM_PLLSOURCE_HSE RCM_PLL1CFG_PLL1CLKS_HSE +/** + * @} + */ + +/** @defgroup RCM_System_Clock_Type System Clock Type + * @{ + */ +#define RCM_CLOCKTYPE_SYSCLK 0x00000001U +#define RCM_CLOCKTYPE_HCLK 0x00000002U +#define RCM_CLOCKTYPE_PCLK1 0x00000004U +#define RCM_CLOCKTYPE_PCLK2 0x00000008U +/** + * @} + */ + +/** @defgroup RCM_System_Clock_Source System Clock Source + * @note The RCM_SYSCLKSOURCE_PLLRCLK parameter is available only for + * APM32F446xx devices. + * @{ + */ +#define RCM_SYSCLKSOURCE_HSI RCM_CFG_SCLKSEL_HSI +#define RCM_SYSCLKSOURCE_HSE RCM_CFG_SCLKSEL_HSE +#define RCM_SYSCLKSOURCE_PLLCLK RCM_CFG_SCLKSEL_PLL +#define RCM_SYSCLKSOURCE_PLLRCLK ((uint32_t)(RCM_CFG_SCLKSEL_0 | RCM_CFG_SCLKSEL_1)) +/** + * @} + */ + +/** @defgroup RCM_System_Clock_Source_Status System Clock Source Status + * @note The RCM_SYSCLKSOURCE_STATUS_PLLRCLK parameter is available only for + * APM32F446xx devices. + * @{ + */ +#define RCM_SYSCLKSOURCE_STATUS_HSI RCM_CFG_SCLKSWSTS_HSI /*!< HSI used as system clock */ +#define RCM_SYSCLKSOURCE_STATUS_HSE RCM_CFG_SCLKSWSTS_HSE /*!< HSE used as system clock */ +#define RCM_SYSCLKSOURCE_STATUS_PLLCLK RCM_CFG_SCLKSWSTS_PLL /*!< PLL used as system clock */ +#define RCM_SYSCLKSOURCE_STATUS_PLLRCLK ((uint32_t)(RCM_CFG_SCLKSWSTS_0 | RCM_CFG_SCLKSWSTS_1)) /*!< PLLR used as system clock */ +/** + * @} + */ + +/** @defgroup RCM_AHB_Clock_Source AHB Clock Source + * @{ + */ +#define RCM_SYSCLK_DIV1 RCM_CFG_AHBPSC_DIV1 +#define RCM_SYSCLK_DIV2 RCM_CFG_AHBPSC_DIV2 +#define RCM_SYSCLK_DIV4 RCM_CFG_AHBPSC_DIV4 +#define RCM_SYSCLK_DIV8 RCM_CFG_AHBPSC_DIV8 +#define RCM_SYSCLK_DIV16 RCM_CFG_AHBPSC_DIV16 +#define RCM_SYSCLK_DIV64 RCM_CFG_AHBPSC_DIV64 +#define RCM_SYSCLK_DIV128 RCM_CFG_AHBPSC_DIV128 +#define RCM_SYSCLK_DIV256 RCM_CFG_AHBPSC_DIV256 +#define RCM_SYSCLK_DIV512 RCM_CFG_AHBPSC_DIV512 +/** + * @} + */ + +/** @defgroup RCM_APB1_APB2_Clock_Source APB1/APB2 Clock Source + * @{ + */ +#define RCM_HCLK_DIV1 RCM_CFG_APB1PSC_DIV1 +#define RCM_HCLK_DIV2 RCM_CFG_APB1PSC_DIV2 +#define RCM_HCLK_DIV4 RCM_CFG_APB1PSC_DIV4 +#define RCM_HCLK_DIV8 RCM_CFG_APB1PSC_DIV8 +#define RCM_HCLK_DIV16 RCM_CFG_APB1PSC_DIV16 +/** + * @} + */ + +/** @defgroup RCM_RTC_Clock_Source RTC Clock Source + * @{ + */ +#define RCM_RTCCLKSOURCE_NO_CLK 0x00000000U +#define RCM_RTCCLKSOURCE_LSE 0x00000100U +#define RCM_RTCCLKSOURCE_LSI 0x00000200U +#define RCM_RTCCLKSOURCE_HSE_DIVX 0x00000300U +#define RCM_RTCCLKSOURCE_HSE_DIV2 0x00020300U +#define RCM_RTCCLKSOURCE_HSE_DIV3 0x00030300U +#define RCM_RTCCLKSOURCE_HSE_DIV4 0x00040300U +#define RCM_RTCCLKSOURCE_HSE_DIV5 0x00050300U +#define RCM_RTCCLKSOURCE_HSE_DIV6 0x00060300U +#define RCM_RTCCLKSOURCE_HSE_DIV7 0x00070300U +#define RCM_RTCCLKSOURCE_HSE_DIV8 0x00080300U +#define RCM_RTCCLKSOURCE_HSE_DIV9 0x00090300U +#define RCM_RTCCLKSOURCE_HSE_DIV10 0x000A0300U +#define RCM_RTCCLKSOURCE_HSE_DIV11 0x000B0300U +#define RCM_RTCCLKSOURCE_HSE_DIV12 0x000C0300U +#define RCM_RTCCLKSOURCE_HSE_DIV13 0x000D0300U +#define RCM_RTCCLKSOURCE_HSE_DIV14 0x000E0300U +#define RCM_RTCCLKSOURCE_HSE_DIV15 0x000F0300U +#define RCM_RTCCLKSOURCE_HSE_DIV16 0x00100300U +#define RCM_RTCCLKSOURCE_HSE_DIV17 0x00110300U +#define RCM_RTCCLKSOURCE_HSE_DIV18 0x00120300U +#define RCM_RTCCLKSOURCE_HSE_DIV19 0x00130300U +#define RCM_RTCCLKSOURCE_HSE_DIV20 0x00140300U +#define RCM_RTCCLKSOURCE_HSE_DIV21 0x00150300U +#define RCM_RTCCLKSOURCE_HSE_DIV22 0x00160300U +#define RCM_RTCCLKSOURCE_HSE_DIV23 0x00170300U +#define RCM_RTCCLKSOURCE_HSE_DIV24 0x00180300U +#define RCM_RTCCLKSOURCE_HSE_DIV25 0x00190300U +#define RCM_RTCCLKSOURCE_HSE_DIV26 0x001A0300U +#define RCM_RTCCLKSOURCE_HSE_DIV27 0x001B0300U +#define RCM_RTCCLKSOURCE_HSE_DIV28 0x001C0300U +#define RCM_RTCCLKSOURCE_HSE_DIV29 0x001D0300U +#define RCM_RTCCLKSOURCE_HSE_DIV30 0x001E0300U +#define RCM_RTCCLKSOURCE_HSE_DIV31 0x001F0300U +/** + * @} + */ + +/** @defgroup RCM_MCO_Index MCO Index + * @{ + */ +#define RCM_MCO1 0x00000000U +#define RCM_MCO2 0x00000001U +/** + * @} + */ + +/** @defgroup RCM_MCO1_Clock_Source MCO1 Clock Source + * @{ + */ +#define RCM_MCO1SOURCE_HSI 0x00000000U +#define RCM_MCO1SOURCE_LSE RCM_CFG_MCO1SEL_0 +#define RCM_MCO1SOURCE_HSE RCM_CFG_MCO1SEL_1 +#define RCM_MCO1SOURCE_PLLCLK RCM_CFG_MCO1SEL +/** + * @} + */ + +/** @defgroup RCM_MCOx_Clock_Prescaler MCOx Clock Prescaler + * @{ + */ +#define RCM_MCODIV_1 0x00000000U +#define RCM_MCODIV_2 RCM_CFG_MCO1PSC_2 +#define RCM_MCODIV_3 ((uint32_t)RCM_CFG_MCO1PSC_0 | RCM_CFG_MCO1PSC_2) +#define RCM_MCODIV_4 ((uint32_t)RCM_CFG_MCO1PSC_1 | RCM_CFG_MCO1PSC_2) +#define RCM_MCODIV_5 RCM_CFG_MCO1PSC +/** + * @} + */ + +/** @defgroup RCM_Interrupt Interrupts + * @{ + */ +#define RCM_IT_LSIRDY ((uint8_t)0x01) +#define RCM_IT_LSERDY ((uint8_t)0x02) +#define RCM_IT_HSIRDY ((uint8_t)0x04) +#define RCM_IT_HSERDY ((uint8_t)0x08) +#define RCM_IT_PLLRDY ((uint8_t)0x10) +#define RCM_IT_PLL2RDY ((uint8_t)0x20) +#define RCM_IT_CSS ((uint8_t)0x80) +/** + * @} + */ + +/** @defgroup RCM_Flag Flags + * Elements values convention: 0XXYYYYYb + * - YYYYY : Flag position in the register + * - 0XX : Register index + * - 01: CTRL register + * - 10: BDCTRL register + * - 11: CSTS register + * @{ + */ +/* Flags in the CTRL register */ +#define RCM_FLAG_HSIRDY ((uint8_t)0x21) +#define RCM_FLAG_HSERDY ((uint8_t)0x31) +#define RCM_FLAG_PLLRDY ((uint8_t)0x39) +#define RCM_FLAG_PLL2RDY ((uint8_t)0x3B) + +/* Flags in the BDCTRL register */ +#define RCM_FLAG_LSERDY ((uint8_t)0x41) + +/* Flags in the CSTS register */ +#define RCM_FLAG_LSIRDY ((uint8_t)0x61) +#define RCM_FLAG_BORRST ((uint8_t)0x79) +#define RCM_FLAG_PINRST ((uint8_t)0x7A) +#define RCM_FLAG_PORRST ((uint8_t)0x7B) +#define RCM_FLAG_SFTRST ((uint8_t)0x7C) +#define RCM_FLAG_IWDTRST ((uint8_t)0x7D) +#define RCM_FLAG_WWDTRST ((uint8_t)0x7E) +#define RCM_FLAG_LPWRRST ((uint8_t)0x7F) +/** + * @} + */ + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ +/** @defgroup RCM_Exported_Macros RCM Exported Macros + * @{ + */ + +/** @defgroup RCM_AHB1_Clock_Enable_Disable AHB1 Peripheral Clock Enable Disable + * @brief Enable or disable the AHB1 peripheral clock. + * @note After reset, the peripheral clock (used for registers read/write access) + * is disabled and the application software has to enable this clock before + * using it. + * @{ + */ +#define __DAL_RCM_GPIOA_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->AHB1CLKEN, RCM_AHB1CLKEN_PAEN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->AHB1CLKEN, RCM_AHB1CLKEN_PAEN);\ + UNUSED(tmpreg); \ + } while(0U) +#define __DAL_RCM_GPIOB_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->AHB1CLKEN, RCM_AHB1CLKEN_PBEN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->AHB1CLKEN, RCM_AHB1CLKEN_PBEN);\ + UNUSED(tmpreg); \ + } while(0U) +#define __DAL_RCM_GPIOC_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->AHB1CLKEN, RCM_AHB1CLKEN_PCEN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->AHB1CLKEN, RCM_AHB1CLKEN_PCEN);\ + UNUSED(tmpreg); \ + } while(0U) +#define __DAL_RCM_GPIOH_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->AHB1CLKEN, RCM_AHB1CLKEN_PHEN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->AHB1CLKEN, RCM_AHB1CLKEN_PHEN);\ + UNUSED(tmpreg); \ + } while(0U) +#define __DAL_RCM_DMA1_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->AHB1CLKEN, RCM_AHB1CLKEN_DMA1EN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->AHB1CLKEN, RCM_AHB1CLKEN_DMA1EN);\ + UNUSED(tmpreg); \ + } while(0U) +#define __DAL_RCM_DMA2_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->AHB1CLKEN, RCM_AHB1CLKEN_DMA2EN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->AHB1CLKEN, RCM_AHB1CLKEN_DMA2EN);\ + UNUSED(tmpreg); \ + } while(0U) + +#define __DAL_RCM_GPIOA_CLK_DISABLE() (RCM->AHB1CLKEN &= ~(RCM_AHB1CLKEN_PAEN)) +#define __DAL_RCM_GPIOB_CLK_DISABLE() (RCM->AHB1CLKEN &= ~(RCM_AHB1CLKEN_PBEN)) +#define __DAL_RCM_GPIOC_CLK_DISABLE() (RCM->AHB1CLKEN &= ~(RCM_AHB1CLKEN_PCEN)) +#define __DAL_RCM_GPIOH_CLK_DISABLE() (RCM->AHB1CLKEN &= ~(RCM_AHB1CLKEN_PHEN)) +#define __DAL_RCM_DMA1_CLK_DISABLE() (RCM->AHB1CLKEN &= ~(RCM_AHB1CLKEN_DMA1EN)) +#define __DAL_RCM_DMA2_CLK_DISABLE() (RCM->AHB1CLKEN &= ~(RCM_AHB1CLKEN_DMA2EN)) +/** + * @} + */ + +/** @defgroup RCM_AHB1_Peripheral_Clock_Enable_Disable_Status AHB1 Peripheral Clock Enable Disable Status + * @brief Get the enable or disable status of the AHB1 peripheral clock. + * @note After reset, the peripheral clock (used for registers read/write access) + * is disabled and the application software has to enable this clock before + * using it. + * @{ + */ +#define __DAL_RCM_GPIOA_IS_CLK_ENABLED() ((RCM->AHB1CLKEN &(RCM_AHB1CLKEN_PAEN)) != RESET) +#define __DAL_RCM_GPIOB_IS_CLK_ENABLED() ((RCM->AHB1CLKEN &(RCM_AHB1CLKEN_PBEN)) != RESET) +#define __DAL_RCM_GPIOC_IS_CLK_ENABLED() ((RCM->AHB1CLKEN &(RCM_AHB1CLKEN_PCEN)) != RESET) +#define __DAL_RCM_GPIOH_IS_CLK_ENABLED() ((RCM->AHB1CLKEN &(RCM_AHB1CLKEN_PHEN)) != RESET) +#define __DAL_RCM_DMA1_IS_CLK_ENABLED() ((RCM->AHB1CLKEN &(RCM_AHB1CLKEN_DMA1EN)) != RESET) +#define __DAL_RCM_DMA2_IS_CLK_ENABLED() ((RCM->AHB1CLKEN &(RCM_AHB1CLKEN_DMA2EN)) != RESET) + +#define __DAL_RCM_GPIOA_IS_CLK_DISABLED() ((RCM->AHB1CLKEN &(RCM_AHB1CLKEN_PAEN)) == RESET) +#define __DAL_RCM_GPIOB_IS_CLK_DISABLED() ((RCM->AHB1CLKEN &(RCM_AHB1CLKEN_PBEN)) == RESET) +#define __DAL_RCM_GPIOC_IS_CLK_DISABLED() ((RCM->AHB1CLKEN &(RCM_AHB1CLKEN_PCEN)) == RESET) +#define __DAL_RCM_GPIOH_IS_CLK_DISABLED() ((RCM->AHB1CLKEN &(RCM_AHB1CLKEN_PHEN)) == RESET) +#define __DAL_RCM_DMA1_IS_CLK_DISABLED() ((RCM->AHB1CLKEN &(RCM_AHB1CLKEN_DMA1EN)) == RESET) +#define __DAL_RCM_DMA2_IS_CLK_DISABLED() ((RCM->AHB1CLKEN &(RCM_AHB1CLKEN_DMA2EN)) == RESET) +/** + * @} + */ + +/** @defgroup RCM_APB1_Clock_Enable_Disable APB1 Peripheral Clock Enable Disable + * @brief Enable or disable the Low Speed APB (APB1) peripheral clock. + * @note After reset, the peripheral clock (used for registers read/write access) + * is disabled and the application software has to enable this clock before + * using it. + * @{ + */ +#define __DAL_RCM_TMR5_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->APB1CLKEN, RCM_APB1CLKEN_TMR5EN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->APB1CLKEN, RCM_APB1CLKEN_TMR5EN);\ + UNUSED(tmpreg); \ + } while(0U) +#define __DAL_RCM_WWDT_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->APB1CLKEN, RCM_APB1CLKEN_WWDTEN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->APB1CLKEN, RCM_APB1CLKEN_WWDTEN);\ + UNUSED(tmpreg); \ + } while(0U) +#define __DAL_RCM_SPI2_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->APB1CLKEN, RCM_APB1CLKEN_SPI2EN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->APB1CLKEN, RCM_APB1CLKEN_SPI2EN);\ + UNUSED(tmpreg); \ + } while(0U) +#define __DAL_RCM_USART2_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->APB1CLKEN, RCM_APB1CLKEN_USART2EN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->APB1CLKEN, RCM_APB1CLKEN_USART2EN);\ + UNUSED(tmpreg); \ + } while(0U) +#define __DAL_RCM_I2C1_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->APB1CLKEN, RCM_APB1CLKEN_I2C1EN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->APB1CLKEN, RCM_APB1CLKEN_I2C1EN);\ + UNUSED(tmpreg); \ + } while(0U) +#define __DAL_RCM_I2C2_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->APB1CLKEN, RCM_APB1CLKEN_I2C2EN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->APB1CLKEN, RCM_APB1CLKEN_I2C2EN);\ + UNUSED(tmpreg); \ + } while(0U) +#define __DAL_RCM_PMU_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->APB1CLKEN, RCM_APB1CLKEN_PMUEN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->APB1CLKEN, RCM_APB1CLKEN_PMUEN);\ + UNUSED(tmpreg); \ + } while(0U) + +#define __DAL_RCM_TMR5_CLK_DISABLE() (RCM->APB1CLKEN &= ~(RCM_APB1CLKEN_TMR5EN)) +#define __DAL_RCM_WWDT_CLK_DISABLE() (RCM->APB1CLKEN &= ~(RCM_APB1CLKEN_WWDTEN)) +#define __DAL_RCM_SPI2_CLK_DISABLE() (RCM->APB1CLKEN &= ~(RCM_APB1CLKEN_SPI2EN)) +#define __DAL_RCM_USART2_CLK_DISABLE() (RCM->APB1CLKEN &= ~(RCM_APB1CLKEN_USART2EN)) +#define __DAL_RCM_I2C1_CLK_DISABLE() (RCM->APB1CLKEN &= ~(RCM_APB1CLKEN_I2C1EN)) +#define __DAL_RCM_I2C2_CLK_DISABLE() (RCM->APB1CLKEN &= ~(RCM_APB1CLKEN_I2C2EN)) +#define __DAL_RCM_PMU_CLK_DISABLE() (RCM->APB1CLKEN &= ~(RCM_APB1CLKEN_PMUEN)) +/** + * @} + */ + +/** @defgroup RCM_APB1_Peripheral_Clock_Enable_Disable_Status APB1 Peripheral Clock Enable Disable Status + * @brief Get the enable or disable status of the APB1 peripheral clock. + * @note After reset, the peripheral clock (used for registers read/write access) + * is disabled and the application software has to enable this clock before + * using it. + * @{ + */ +#define __DAL_RCM_TMR5_IS_CLK_ENABLED() ((RCM->APB1CLKEN & (RCM_APB1CLKEN_TMR5EN)) != RESET) +#define __DAL_RCM_WWDT_IS_CLK_ENABLED() ((RCM->APB1CLKEN & (RCM_APB1CLKEN_WWDTEN)) != RESET) +#define __DAL_RCM_SPI2_IS_CLK_ENABLED() ((RCM->APB1CLKEN & (RCM_APB1CLKEN_SPI2EN)) != RESET) +#define __DAL_RCM_USART2_IS_CLK_ENABLED() ((RCM->APB1CLKEN & (RCM_APB1CLKEN_USART2EN)) != RESET) +#define __DAL_RCM_I2C1_IS_CLK_ENABLED() ((RCM->APB1CLKEN & (RCM_APB1CLKEN_I2C1EN)) != RESET) +#define __DAL_RCM_I2C2_IS_CLK_ENABLED() ((RCM->APB1CLKEN & (RCM_APB1CLKEN_I2C2EN)) != RESET) +#define __DAL_RCM_PMU_IS_CLK_ENABLED() ((RCM->APB1CLKEN & (RCM_APB1CLKEN_PMUEN)) != RESET) + +#define __DAL_RCM_TMR5_IS_CLK_DISABLED() ((RCM->APB1CLKEN & (RCM_APB1CLKEN_TMR5EN)) == RESET) +#define __DAL_RCM_WWDT_IS_CLK_DISABLED() ((RCM->APB1CLKEN & (RCM_APB1CLKEN_WWDTEN)) == RESET) +#define __DAL_RCM_SPI2_IS_CLK_DISABLED() ((RCM->APB1CLKEN & (RCM_APB1CLKEN_SPI2EN)) == RESET) +#define __DAL_RCM_USART2_IS_CLK_DISABLED() ((RCM->APB1CLKEN & (RCM_APB1CLKEN_USART2EN)) == RESET) +#define __DAL_RCM_I2C1_IS_CLK_DISABLED() ((RCM->APB1CLKEN & (RCM_APB1CLKEN_I2C1EN)) == RESET) +#define __DAL_RCM_I2C2_IS_CLK_DISABLED() ((RCM->APB1CLKEN & (RCM_APB1CLKEN_I2C2EN)) == RESET) +#define __DAL_RCM_PMU_IS_CLK_DISABLED() ((RCM->APB1CLKEN & (RCM_APB1CLKEN_PMUEN)) == RESET) +/** + * @} + */ + +/** @defgroup RCM_APB2_Clock_Enable_Disable APB2 Peripheral Clock Enable Disable + * @brief Enable or disable the High Speed APB (APB2) peripheral clock. + * @note After reset, the peripheral clock (used for registers read/write access) + * is disabled and the application software has to enable this clock before + * using it. + * @{ + */ +#define __DAL_RCM_TMR1_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->APB2CLKEN, RCM_APB2CLKEN_TMR1EN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->APB2CLKEN, RCM_APB2CLKEN_TMR1EN);\ + UNUSED(tmpreg); \ + } while(0U) +#define __DAL_RCM_USART1_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->APB2CLKEN, RCM_APB2CLKEN_USART1EN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->APB2CLKEN, RCM_APB2CLKEN_USART1EN);\ + UNUSED(tmpreg); \ + } while(0U) +#define __DAL_RCM_USART6_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->APB2CLKEN, RCM_APB2CLKEN_USART6EN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->APB2CLKEN, RCM_APB2CLKEN_USART6EN);\ + UNUSED(tmpreg); \ + } while(0U) +#define __DAL_RCM_ADC1_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->APB2CLKEN, RCM_APB2CLKEN_ADC1EN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->APB2CLKEN, RCM_APB2CLKEN_ADC1EN);\ + UNUSED(tmpreg); \ + } while(0U) +#define __DAL_RCM_SPI1_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->APB2CLKEN, RCM_APB2CLKEN_SPI1EN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->APB2CLKEN, RCM_APB2CLKEN_SPI1EN);\ + UNUSED(tmpreg); \ + } while(0U) +#define __DAL_RCM_SYSCFG_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->APB2CLKEN, RCM_APB2CLKEN_SYSCFGEN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->APB2CLKEN, RCM_APB2CLKEN_SYSCFGEN);\ + UNUSED(tmpreg); \ + } while(0U) +#define __DAL_RCM_TMR9_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->APB2CLKEN, RCM_APB2CLKEN_TMR9EN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->APB2CLKEN, RCM_APB2CLKEN_TMR9EN);\ + UNUSED(tmpreg); \ + } while(0U) +#define __DAL_RCM_TMR11_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->APB2CLKEN, RCM_APB2CLKEN_TMR11EN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->APB2CLKEN, RCM_APB2CLKEN_TMR11EN);\ + UNUSED(tmpreg); \ + } while(0U) + +#define __DAL_RCM_TMR1_CLK_DISABLE() (RCM->APB2CLKEN &= ~(RCM_APB2CLKEN_TMR1EN)) +#define __DAL_RCM_USART1_CLK_DISABLE() (RCM->APB2CLKEN &= ~(RCM_APB2CLKEN_USART1EN)) +#define __DAL_RCM_USART6_CLK_DISABLE() (RCM->APB2CLKEN &= ~(RCM_APB2CLKEN_USART6EN)) +#define __DAL_RCM_ADC1_CLK_DISABLE() (RCM->APB2CLKEN &= ~(RCM_APB2CLKEN_ADC1EN)) +#define __DAL_RCM_SPI1_CLK_DISABLE() (RCM->APB2CLKEN &= ~(RCM_APB2CLKEN_SPI1EN)) +#define __DAL_RCM_SYSCFG_CLK_DISABLE() (RCM->APB2CLKEN &= ~(RCM_APB2CLKEN_SYSCFGEN)) +#define __DAL_RCM_TMR9_CLK_DISABLE() (RCM->APB2CLKEN &= ~(RCM_APB2CLKEN_TMR9EN)) +#define __DAL_RCM_TMR11_CLK_DISABLE() (RCM->APB2CLKEN &= ~(RCM_APB2CLKEN_TMR11EN)) +/** + * @} + */ + +/** @defgroup RCM_APB2_Peripheral_Clock_Enable_Disable_Status APB2 Peripheral Clock Enable Disable Status + * @brief Get the enable or disable status of the APB2 peripheral clock. + * @note After reset, the peripheral clock (used for registers read/write access) + * is disabled and the application software has to enable this clock before + * using it. + * @{ + */ +#define __DAL_RCM_TMR1_IS_CLK_ENABLED() ((RCM->APB2CLKEN & (RCM_APB2CLKEN_TMR1EN)) != RESET) +#define __DAL_RCM_USART1_IS_CLK_ENABLED() ((RCM->APB2CLKEN & (RCM_APB2CLKEN_USART1EN)) != RESET) +#define __DAL_RCM_USART6_IS_CLK_ENABLED() ((RCM->APB2CLKEN & (RCM_APB2CLKEN_USART6EN)) != RESET) +#define __DAL_RCM_ADC1_IS_CLK_ENABLED() ((RCM->APB2CLKEN & (RCM_APB2CLKEN_ADC1EN)) != RESET) +#define __DAL_RCM_SPI1_IS_CLK_ENABLED() ((RCM->APB2CLKEN & (RCM_APB2CLKEN_SPI1EN)) != RESET) +#define __DAL_RCM_SYSCFG_IS_CLK_ENABLED() ((RCM->APB2CLKEN & (RCM_APB2CLKEN_SYSCFGEN)) != RESET) +#define __DAL_RCM_TMR9_IS_CLK_ENABLED() ((RCM->APB2CLKEN & (RCM_APB2CLKEN_TMR9EN)) != RESET) +#define __DAL_RCM_TMR11_IS_CLK_ENABLED() ((RCM->APB2CLKEN & (RCM_APB2CLKEN_TMR11EN)) != RESET) + +#define __DAL_RCM_TMR1_IS_CLK_DISABLED() ((RCM->APB2CLKEN & (RCM_APB2CLKEN_TMR1EN)) == RESET) +#define __DAL_RCM_USART1_IS_CLK_DISABLED() ((RCM->APB2CLKEN & (RCM_APB2CLKEN_USART1EN)) == RESET) +#define __DAL_RCM_USART6_IS_CLK_DISABLED() ((RCM->APB2CLKEN & (RCM_APB2CLKEN_USART6EN)) == RESET) +#define __DAL_RCM_ADC1_IS_CLK_DISABLED() ((RCM->APB2CLKEN & (RCM_APB2CLKEN_ADC1EN)) == RESET) +#define __DAL_RCM_SPI1_IS_CLK_DISABLED() ((RCM->APB2CLKEN & (RCM_APB2CLKEN_SPI1EN)) == RESET) +#define __DAL_RCM_SYSCFG_IS_CLK_DISABLED() ((RCM->APB2CLKEN & (RCM_APB2CLKEN_SYSCFGEN)) == RESET) +#define __DAL_RCM_TMR9_IS_CLK_DISABLED() ((RCM->APB2CLKEN & (RCM_APB2CLKEN_TMR9EN)) == RESET) +#define __DAL_RCM_TMR11_IS_CLK_DISABLED() ((RCM->APB2CLKEN & (RCM_APB2CLKEN_TMR11EN)) == RESET) +/** + * @} + */ + +/** @defgroup RCM_AHB1_Force_Release_Reset AHB1 Force Release Reset + * @brief Force or release AHB1 peripheral reset. + * @{ + */ +#define __DAL_RCM_AHB1_FORCE_RESET() (RCM->AHB1RST = 0xFFFFFFFFU) +#define __DAL_RCM_GPIOA_FORCE_RESET() (RCM->AHB1RST |= (RCM_AHB1RST_PARST)) +#define __DAL_RCM_GPIOB_FORCE_RESET() (RCM->AHB1RST |= (RCM_AHB1RST_PBRST)) +#define __DAL_RCM_GPIOC_FORCE_RESET() (RCM->AHB1RST |= (RCM_AHB1RST_PCRST)) +#define __DAL_RCM_GPIOH_FORCE_RESET() (RCM->AHB1RST |= (RCM_AHB1RST_PHRST)) +#define __DAL_RCM_DMA1_FORCE_RESET() (RCM->AHB1RST |= (RCM_AHB1RST_DMA1RST)) +#define __DAL_RCM_DMA2_FORCE_RESET() (RCM->AHB1RST |= (RCM_AHB1RST_DMA2RST)) + +#define __DAL_RCM_AHB1_RELEASE_RESET() (RCM->AHB1RST = 0x00U) +#define __DAL_RCM_GPIOA_RELEASE_RESET() (RCM->AHB1RST &= ~(RCM_AHB1RST_PARST)) +#define __DAL_RCM_GPIOB_RELEASE_RESET() (RCM->AHB1RST &= ~(RCM_AHB1RST_PBRST)) +#define __DAL_RCM_GPIOC_RELEASE_RESET() (RCM->AHB1RST &= ~(RCM_AHB1RST_PCRST)) +#define __DAL_RCM_GPIOH_RELEASE_RESET() (RCM->AHB1RST &= ~(RCM_AHB1RST_PHRST)) +#define __DAL_RCM_DMA1_RELEASE_RESET() (RCM->AHB1RST &= ~(RCM_AHB1RST_DMA1RST)) +#define __DAL_RCM_DMA2_RELEASE_RESET() (RCM->AHB1RST &= ~(RCM_AHB1RST_DMA2RST)) +/** + * @} + */ + +/** @defgroup RCM_APB1_Force_Release_Reset APB1 Force Release Reset + * @brief Force or release APB1 peripheral reset. + * @{ + */ +#define __DAL_RCM_APB1_FORCE_RESET() (RCM->APB1RST = 0xFFFFFFFFU) +#define __DAL_RCM_TMR5_FORCE_RESET() (RCM->APB1RST |= (RCM_APB1RST_TMR5RST)) +#define __DAL_RCM_WWDT_FORCE_RESET() (RCM->APB1RST |= (RCM_APB1RST_WWDTRST)) +#define __DAL_RCM_SPI2_FORCE_RESET() (RCM->APB1RST |= (RCM_APB1RST_SPI2RST)) +#define __DAL_RCM_USART2_FORCE_RESET() (RCM->APB1RST |= (RCM_APB1RST_USART2RST)) +#define __DAL_RCM_I2C1_FORCE_RESET() (RCM->APB1RST |= (RCM_APB1RST_I2C1RST)) +#define __DAL_RCM_I2C2_FORCE_RESET() (RCM->APB1RST |= (RCM_APB1RST_I2C2RST)) +#define __DAL_RCM_PMU_FORCE_RESET() (RCM->APB1RST |= (RCM_APB1RST_PMURST)) + +#define __DAL_RCM_APB1_RELEASE_RESET() (RCM->APB1RST = 0x00U) +#define __DAL_RCM_TMR5_RELEASE_RESET() (RCM->APB1RST &= ~(RCM_APB1RST_TMR5RST)) +#define __DAL_RCM_WWDT_RELEASE_RESET() (RCM->APB1RST &= ~(RCM_APB1RST_WWDTRST)) +#define __DAL_RCM_SPI2_RELEASE_RESET() (RCM->APB1RST &= ~(RCM_APB1RST_SPI2RST)) +#define __DAL_RCM_USART2_RELEASE_RESET() (RCM->APB1RST &= ~(RCM_APB1RST_USART2RST)) +#define __DAL_RCM_I2C1_RELEASE_RESET() (RCM->APB1RST &= ~(RCM_APB1RST_I2C1RST)) +#define __DAL_RCM_I2C2_RELEASE_RESET() (RCM->APB1RST &= ~(RCM_APB1RST_I2C2RST)) +#define __DAL_RCM_PMU_RELEASE_RESET() (RCM->APB1RST &= ~(RCM_APB1RST_PMURST)) +/** + * @} + */ + +/** @defgroup RCM_APB2_Force_Release_Reset APB2 Force Release Reset + * @brief Force or release APB2 peripheral reset. + * @{ + */ +#define __DAL_RCM_APB2_FORCE_RESET() (RCM->APB2RST = 0xFFFFFFFFU) +#define __DAL_RCM_TMR1_FORCE_RESET() (RCM->APB2RST |= (RCM_APB2RST_TMR1RST)) +#define __DAL_RCM_USART1_FORCE_RESET() (RCM->APB2RST |= (RCM_APB2RST_USART1RST)) +#define __DAL_RCM_USART6_FORCE_RESET() (RCM->APB2RST |= (RCM_APB2RST_USART6RST)) +#define __DAL_RCM_ADC_FORCE_RESET() (RCM->APB2RST |= (RCM_APB2RST_ADCRST)) +#define __DAL_RCM_SPI1_FORCE_RESET() (RCM->APB2RST |= (RCM_APB2RST_SPI1RST)) +#define __DAL_RCM_SYSCFG_FORCE_RESET() (RCM->APB2RST |= (RCM_APB2RST_SYSCFGRST)) +#define __DAL_RCM_TMR9_FORCE_RESET() (RCM->APB2RST |= (RCM_APB2RST_TMR9RST)) +#define __DAL_RCM_TMR11_FORCE_RESET() (RCM->APB2RST |= (RCM_APB2RST_TMR11RST)) + +#define __DAL_RCM_APB2_RELEASE_RESET() (RCM->APB2RST = 0x00U) +#define __DAL_RCM_TMR1_RELEASE_RESET() (RCM->APB2RST &= ~(RCM_APB2RST_TMR1RST)) +#define __DAL_RCM_USART1_RELEASE_RESET() (RCM->APB2RST &= ~(RCM_APB2RST_USART1RST)) +#define __DAL_RCM_USART6_RELEASE_RESET() (RCM->APB2RST &= ~(RCM_APB2RST_USART6RST)) +#define __DAL_RCM_ADC_RELEASE_RESET() (RCM->APB2RST &= ~(RCM_APB2RST_ADCRST)) +#define __DAL_RCM_SPI1_RELEASE_RESET() (RCM->APB2RST &= ~(RCM_APB2RST_SPI1RST)) +#define __DAL_RCM_SYSCFG_RELEASE_RESET() (RCM->APB2RST &= ~(RCM_APB2RST_SYSCFGRST)) +#define __DAL_RCM_TMR9_RELEASE_RESET() (RCM->APB2RST &= ~(RCM_APB2RST_TMR9RST)) +#define __DAL_RCM_TMR11_RELEASE_RESET() (RCM->APB2RST &= ~(RCM_APB2RST_TMR11RST)) +/** + * @} + */ + +/** @defgroup RCM_AHB1_LowPower_Enable_Disable AHB1 Peripheral Low Power Enable Disable + * @brief Enable or disable the AHB1 peripheral clock during Low Power (Sleep) mode. + * @note Peripheral clock gating in SLEEP mode can be used to further reduce + * power consumption. + * @note After wake-up from SLEEP mode, the peripheral clock is enabled again. + * @note By default, all peripheral clocks are enabled during SLEEP mode. + * @{ + */ +#define __DAL_RCM_GPIOA_CLK_SLEEP_ENABLE() (RCM->LPAHB1CLKEN |= (RCM_LPAHB1CLKEN_PALPEN)) +#define __DAL_RCM_GPIOB_CLK_SLEEP_ENABLE() (RCM->LPAHB1CLKEN |= (RCM_LPAHB1CLKEN_PBLPEN)) +#define __DAL_RCM_GPIOC_CLK_SLEEP_ENABLE() (RCM->LPAHB1CLKEN |= (RCM_LPAHB1CLKEN_PCLPEN)) +#define __DAL_RCM_GPIOH_CLK_SLEEP_ENABLE() (RCM->LPAHB1CLKEN |= (RCM_LPAHB1CLKEN_PHLPEN)) +#define __DAL_RCM_DMA1_CLK_SLEEP_ENABLE() (RCM->LPAHB1CLKEN |= (RCM_LPAHB1CLKEN_DMA1EN)) +#define __DAL_RCM_DMA2_CLK_SLEEP_ENABLE() (RCM->LPAHB1CLKEN |= (RCM_LPAHB1CLKEN_DMA2EN)) + +#define __DAL_RCM_GPIOA_CLK_SLEEP_DISABLE() (RCM->LPAHB1CLKEN &= ~(RCM_LPAHB1CLKEN_PALPEN)) +#define __DAL_RCM_GPIOB_CLK_SLEEP_DISABLE() (RCM->LPAHB1CLKEN &= ~(RCM_LPAHB1CLKEN_PBLPEN)) +#define __DAL_RCM_GPIOC_CLK_SLEEP_DISABLE() (RCM->LPAHB1CLKEN &= ~(RCM_LPAHB1CLKEN_PCLPEN)) +#define __DAL_RCM_GPIOH_CLK_SLEEP_DISABLE() (RCM->LPAHB1CLKEN &= ~(RCM_LPAHB1CLKEN_PHLPEN)) +#define __DAL_RCM_DMA1_CLK_SLEEP_DISABLE() (RCM->LPAHB1CLKEN &= ~(RCM_LPAHB1CLKEN_DMA1EN)) +#define __DAL_RCM_DMA2_CLK_SLEEP_DISABLE() (RCM->LPAHB1CLKEN &= ~(RCM_LPAHB1CLKEN_DMA2EN)) +/** + * @} + */ + +/** @defgroup RCM_APB1_LowPower_Enable_Disable APB1 Peripheral Low Power Enable Disable + * @brief Enable or disable the APB1 peripheral clock during Low Power (Sleep) mode. + * @note Peripheral clock gating in SLEEP mode can be used to further reduce + * power consumption. + * @note After wake-up from SLEEP mode, the peripheral clock is enabled again. + * @note By default, all peripheral clocks are enabled during SLEEP mode. + * @{ + */ +#define __DAL_RCM_TMR5_CLK_SLEEP_ENABLE() (RCM->LPAPB1CLKEN |= (RCM_LPAPB1CLKEN_TMR5EN)) +#define __DAL_RCM_WWDT_CLK_SLEEP_ENABLE() (RCM->LPAPB1CLKEN |= (RCM_LPAPB1CLKEN_WWDTEN)) +#define __DAL_RCM_SPI2_CLK_SLEEP_ENABLE() (RCM->LPAPB1CLKEN |= (RCM_LPAPB1CLKEN_SPI2EN)) +#define __DAL_RCM_USART2_CLK_SLEEP_ENABLE() (RCM->LPAPB1CLKEN |= (RCM_LPAPB1CLKEN_USART2EN)) +#define __DAL_RCM_I2C1_CLK_SLEEP_ENABLE() (RCM->LPAPB1CLKEN |= (RCM_LPAPB1CLKEN_I2C1EN)) +#define __DAL_RCM_I2C2_CLK_SLEEP_ENABLE() (RCM->LPAPB1CLKEN |= (RCM_LPAPB1CLKEN_I2C2EN)) +#define __DAL_RCM_PMU_CLK_SLEEP_ENABLE() (RCM->LPAPB1CLKEN |= (RCM_LPAPB1CLKEN_PMUEN)) + +#define __DAL_RCM_TMR5_CLK_SLEEP_DISABLE() (RCM->LPAPB1CLKEN &= ~(RCM_LPAPB1CLKEN_TMR5EN)) +#define __DAL_RCM_WWDT_CLK_SLEEP_DISABLE() (RCM->LPAPB1CLKEN &= ~(RCM_LPAPB1CLKEN_WWDTEN)) +#define __DAL_RCM_SPI2_CLK_SLEEP_DISABLE() (RCM->LPAPB1CLKEN &= ~(RCM_LPAPB1CLKEN_SPI2EN)) +#define __DAL_RCM_USART2_CLK_SLEEP_DISABLE() (RCM->LPAPB1CLKEN &= ~(RCM_LPAPB1CLKEN_USART2EN)) +#define __DAL_RCM_I2C1_CLK_SLEEP_DISABLE() (RCM->LPAPB1CLKEN &= ~(RCM_LPAPB1CLKEN_I2C1EN)) +#define __DAL_RCM_I2C2_CLK_SLEEP_DISABLE() (RCM->LPAPB1CLKEN &= ~(RCM_LPAPB1CLKEN_I2C2EN)) +#define __DAL_RCM_PMU_CLK_SLEEP_DISABLE() (RCM->LPAPB1CLKEN &= ~(RCM_LPAPB1CLKEN_PMUEN)) +/** + * @} + */ + +/** @defgroup RCM_APB2_LowPower_Enable_Disable APB2 Peripheral Low Power Enable Disable + * @brief Enable or disable the APB2 peripheral clock during Low Power (Sleep) mode. + * @note Peripheral clock gating in SLEEP mode can be used to further reduce + * power consumption. + * @note After wake-up from SLEEP mode, the peripheral clock is enabled again. + * @note By default, all peripheral clocks are enabled during SLEEP mode. + * @{ + */ +#define __DAL_RCM_TMR1_CLK_SLEEP_ENABLE() (RCM->LPAPB2CLKEN |= (RCM_LPAPB2CLKEN_TMR1EN)) +#define __DAL_RCM_USART1_CLK_SLEEP_ENABLE() (RCM->LPAPB2CLKEN |= (RCM_LPAPB2CLKEN_USART1EN)) +#define __DAL_RCM_USART6_CLK_SLEEP_ENABLE() (RCM->LPAPB2CLKEN |= (RCM_LPAPB2CLKEN_USART6EN)) +#define __DAL_RCM_ADC1_CLK_SLEEP_ENABLE() (RCM->LPAPB2CLKEN |= (RCM_LPAPB2CLKEN_ADC1EN)) +#define __DAL_RCM_SPI1_CLK_SLEEP_ENABLE() (RCM->LPAPB2CLKEN |= (RCM_LPAPB2CLKEN_SPI1EN)) +#define __DAL_RCM_SYSCFG_CLK_SLEEP_ENABLE() (RCM->LPAPB2CLKEN |= (RCM_LPAPB2CLKEN_SYSCFGEN)) +#define __DAL_RCM_TMR9_CLK_SLEEP_ENABLE() (RCM->LPAPB2CLKEN |= (RCM_LPAPB2CLKEN_TMR9EN)) +#define __DAL_RCM_TMR11_CLK_SLEEP_ENABLE() (RCM->LPAPB2CLKEN |= (RCM_LPAPB2CLKEN_TMR11EN)) + +#define __DAL_RCM_TMR1_CLK_SLEEP_DISABLE() (RCM->LPAPB2CLKEN &= ~(RCM_LPAPB2CLKEN_TMR1EN)) +#define __DAL_RCM_USART1_CLK_SLEEP_DISABLE() (RCM->LPAPB2CLKEN &= ~(RCM_LPAPB2CLKEN_USART1EN)) +#define __DAL_RCM_USART6_CLK_SLEEP_DISABLE() (RCM->LPAPB2CLKEN &= ~(RCM_LPAPB2CLKEN_USART6EN)) +#define __DAL_RCM_ADC1_CLK_SLEEP_DISABLE() (RCM->LPAPB2CLKEN &= ~(RCM_LPAPB2CLKEN_ADC1EN)) +#define __DAL_RCM_SPI1_CLK_SLEEP_DISABLE() (RCM->LPAPB2CLKEN &= ~(RCM_LPAPB2CLKEN_SPI1EN)) +#define __DAL_RCM_SYSCFG_CLK_SLEEP_DISABLE() (RCM->LPAPB2CLKEN &= ~(RCM_LPAPB2CLKEN_SYSCFGEN)) +#define __DAL_RCM_TMR9_CLK_SLEEP_DISABLE() (RCM->LPAPB2CLKEN &= ~(RCM_LPAPB2CLKEN_TMR9EN)) +#define __DAL_RCM_TMR11_CLK_SLEEP_DISABLE() (RCM->LPAPB2CLKEN &= ~(RCM_LPAPB2CLKEN_TMR11EN)) +/** + * @} + */ + +/** @defgroup RCM_HSI_Configuration HSI Configuration + * @{ + */ + +/** @brief Macros to enable or disable the Internal High Speed oscillator (HSI). + * @note The HSI is stopped by hardware when entering STOP and STANDBY modes. + * It is used (enabled by hardware) as system clock source after startup + * from Reset, wake-up from STOP and STANDBY mode, or in case of failure + * of the HSE used directly or indirectly as system clock (if the Clock + * Security System CSS is enabled). + * @note HSI can not be stopped if it is used as system clock source. In this case, + * you have to select another source of the system clock then stop the HSI. + * @note After enabling the HSI, the application software should wait on HSIRDY + * flag to be set indicating that HSI clock is stable and can be used as + * system clock source. + * This parameter can be: ENABLE or DISABLE. + * @note When the HSI is stopped, HSIRDY flag goes low after 6 HSI oscillator + * clock cycles. + */ +#define __DAL_RCM_HSI_ENABLE() (*(__IO uint32_t *) RCM_CTRL_HSIEN_BB = ENABLE) +#define __DAL_RCM_HSI_DISABLE() (*(__IO uint32_t *) RCM_CTRL_HSIEN_BB = DISABLE) + +/** @brief Macro to adjust the Internal High Speed oscillator (HSI) calibration value. + * @note The calibration is used to compensate for the variations in voltage + * and temperature that influence the frequency of the internal HSI RC. + * @param __HSICalibrationValue__ specifies the calibration trimming value. + * (default is RCM_HSICALIBRATION_DEFAULT). + * This parameter must be a number between 0 and 0x1F. + */ +#define __DAL_RCM_HSI_CALIBRATIONVALUE_ADJUST(__HSICalibrationValue__) (MODIFY_REG(RCM->CTRL,\ + RCM_CTRL_HSITRM, (uint32_t)(__HSICalibrationValue__) << RCM_CTRL_HSITRM_Pos)) +/** + * @} + */ + +/** @defgroup RCM_LSI_Configuration LSI Configuration + * @{ + */ + +/** @brief Macros to enable or disable the Internal Low Speed oscillator (LSI). + * @note After enabling the LSI, the application software should wait on + * LSIRDY flag to be set indicating that LSI clock is stable and can + * be used to clock the IWDT and/or the RTC. + * @note LSI can not be disabled if the IWDT is running. + * @note When the LSI is stopped, LSIRDY flag goes low after 6 LSI oscillator + * clock cycles. + */ +#define __DAL_RCM_LSI_ENABLE() (*(__IO uint32_t *) RCM_CSTS_LSIEN_BB = ENABLE) +#define __DAL_RCM_LSI_DISABLE() (*(__IO uint32_t *) RCM_CSTS_LSIEN_BB = DISABLE) +/** + * @} + */ + +/** @defgroup RCM_HSE_Configuration HSE Configuration + * @{ + */ + +/** + * @brief Macro to configure the External High Speed oscillator (HSE). + * @note Transition HSE Bypass to HSE On and HSE On to HSE Bypass are not supported by this macro. + * User should request a transition to HSE Off first and then HSE On or HSE Bypass. + * @note After enabling the HSE (RCM_HSE_ON or RCM_HSE_Bypass), the application + * software should wait on HSERDY flag to be set indicating that HSE clock + * is stable and can be used to clock the PLL and/or system clock. + * @note HSE state can not be changed if it is used directly or through the + * PLL as system clock. In this case, you have to select another source + * of the system clock then change the HSE state (ex. disable it). + * @note The HSE is stopped by hardware when entering STOP and STANDBY modes. + * @note This function reset the CSSON bit, so if the clock security system(CSS) + * was previously enabled you have to enable it again after calling this + * function. + * @param __STATE__ specifies the new state of the HSE. + * This parameter can be one of the following values: + * @arg RCM_HSE_OFF: turn OFF the HSE oscillator, HSERDY flag goes low after + * 6 HSE oscillator clock cycles. + * @arg RCM_HSE_ON: turn ON the HSE oscillator. + * @arg RCM_HSE_BYPASS: HSE oscillator bypassed with external clock. + */ +#define __DAL_RCM_HSE_CONFIG(__STATE__) \ + do { \ + if ((__STATE__) == RCM_HSE_ON) \ + { \ + SET_BIT(RCM->CTRL, RCM_CTRL_HSEEN); \ + } \ + else if ((__STATE__) == RCM_HSE_BYPASS) \ + { \ + SET_BIT(RCM->CTRL, RCM_CTRL_HSEBCFG); \ + SET_BIT(RCM->CTRL, RCM_CTRL_HSEEN); \ + } \ + else \ + { \ + CLEAR_BIT(RCM->CTRL, RCM_CTRL_HSEEN); \ + CLEAR_BIT(RCM->CTRL, RCM_CTRL_HSEBCFG); \ + } \ + } while(0U) +/** + * @} + */ + +/** @defgroup RCM_LSE_Configuration LSE Configuration + * @{ + */ + +/** + * @brief Macro to configure the External Low Speed oscillator (LSE). + * @note Transition LSE Bypass to LSE On and LSE On to LSE Bypass are not supported by this macro. + * User should request a transition to LSE Off first and then LSE On or LSE Bypass. + * @note As the LSE is in the Backup domain and write access is denied to + * this domain after reset, you have to enable write access using + * DAL_PMU_EnableBkUpAccess() function before to configure the LSE + * (to be done once after reset). + * @note After enabling the LSE (RCM_LSE_ON or RCM_LSE_BYPASS), the application + * software should wait on LSERDY flag to be set indicating that LSE clock + * is stable and can be used to clock the RTC. + * @param __STATE__ specifies the new state of the LSE. + * This parameter can be one of the following values: + * @arg RCM_LSE_OFF: turn OFF the LSE oscillator, LSERDY flag goes low after + * 6 LSE oscillator clock cycles. + * @arg RCM_LSE_ON: turn ON the LSE oscillator. + * @arg RCM_LSE_BYPASS: LSE oscillator bypassed with external clock. + */ +#define __DAL_RCM_LSE_CONFIG(__STATE__) \ + do { \ + if((__STATE__) == RCM_LSE_ON) \ + { \ + SET_BIT(RCM->BDCTRL, RCM_BDCTRL_LSEEN); \ + } \ + else if((__STATE__) == RCM_LSE_BYPASS) \ + { \ + SET_BIT(RCM->BDCTRL, RCM_BDCTRL_LSEBCFG); \ + SET_BIT(RCM->BDCTRL, RCM_BDCTRL_LSEEN); \ + } \ + else \ + { \ + CLEAR_BIT(RCM->BDCTRL, RCM_BDCTRL_LSEEN); \ + CLEAR_BIT(RCM->BDCTRL, RCM_BDCTRL_LSEBCFG); \ + } \ + } while(0U) +/** + * @} + */ + +/** @defgroup RCM_Internal_RTC_Clock_Configuration RTC Clock Configuration + * @{ + */ + +/** @brief Macros to enable or disable the RTC clock. + * @note These macros must be used only after the RTC clock source was selected. + */ +#define __DAL_RCM_RTC_ENABLE() (*(__IO uint32_t *) RCM_BDCTRL_RTCCLKEN_BB = ENABLE) +#define __DAL_RCM_RTC_DISABLE() (*(__IO uint32_t *) RCM_BDCTRL_RTCCLKEN_BB = DISABLE) + +/** @brief Macros to configure the RTC clock (RTCCLK). + * @note As the RTC clock configuration bits are in the Backup domain and write + * access is denied to this domain after reset, you have to enable write + * access using the Power Backup Access macro before to configure + * the RTC clock source (to be done once after reset). + * @note Once the RTC clock is configured it can't be changed unless the + * Backup domain is reset using __DAL_RCM_BackupReset_RELEASE() macro, or by + * a Power On Reset (POR). + * @param __RTCCLKSource__ specifies the RTC clock source. + * This parameter can be one of the following values: + * @arg @ref RCM_RTCCLKSOURCE_NO_CLK : No clock selected as RTC clock. + * @arg @ref RCM_RTCCLKSOURCE_LSE : LSE selected as RTC clock. + * @arg @ref RCM_RTCCLKSOURCE_LSI : LSI selected as RTC clock. + * @arg @ref RCM_RTCCLKSOURCE_HSE_DIVX HSE divided by X selected as RTC clock (X can be retrieved thanks to @ref __DAL_RCM_GET_RTC_HSE_PRESCALER() + * @note If the LSE or LSI is used as RTC clock source, the RTC continues to + * work in STOP and STANDBY modes, and can be used as wake-up source. + * However, when the HSE clock is used as RTC clock source, the RTC + * cannot be used in STOP and STANDBY modes. + * @note The maximum input clock frequency for RTC is 1MHz (when using HSE as + * RTC clock source). + */ +#define __DAL_RCM_RTC_CLKPRESCALER(__RTCCLKSource__) (((__RTCCLKSource__) & RCM_BDCTRL_RTCSRCSEL) == RCM_BDCTRL_RTCSRCSEL) ? \ + MODIFY_REG(RCM->CFG, RCM_CFG_RTCPSC, ((__RTCCLKSource__) & 0xFFFFCFFU)) : CLEAR_BIT(RCM->CFG, RCM_CFG_RTCPSC) + +#define __DAL_RCM_RTC_CONFIG(__RTCCLKSource__) do { __DAL_RCM_RTC_CLKPRESCALER(__RTCCLKSource__); \ + RCM->BDCTRL |= ((__RTCCLKSource__) & 0x00000FFFU); \ + } while(0U) + +/** @brief Macro to get the RTC clock source. + * @retval The clock source can be one of the following values: + * @arg @ref RCM_RTCCLKSOURCE_NO_CLK No clock selected as RTC clock + * @arg @ref RCM_RTCCLKSOURCE_LSE LSE selected as RTC clock + * @arg @ref RCM_RTCCLKSOURCE_LSI LSI selected as RTC clock + * @arg @ref RCM_RTCCLKSOURCE_HSE_DIVX HSE divided by X selected as RTC clock (X can be retrieved thanks to @ref __DAL_RCM_GET_RTC_HSE_PRESCALER() + */ +#define __DAL_RCM_GET_RTC_SOURCE() (READ_BIT(RCM->BDCTRL, RCM_BDCTRL_RTCSRCSEL)) + +/** + * @brief Get the RTC and HSE clock divider (RTCPRE). + * @retval Returned value can be one of the following values: + * @arg @ref RCM_RTCCLKSOURCE_HSE_DIVX HSE divided by X selected as RTC clock (X can be retrieved thanks to @ref __DAL_RCM_GET_RTC_HSE_PRESCALER() + */ +#define __DAL_RCM_GET_RTC_HSE_PRESCALER() (READ_BIT(RCM->CFG, RCM_CFG_RTCPSC) | RCM_BDCTRL_RTCSRCSEL) + +/** @brief Macros to force or release the Backup domain reset. + * @note This function resets the RTC peripheral (including the backup registers) + * and the RTC clock source selection in RCM_CSTS register. + * @note The BKPSRAM is not affected by this reset. + */ +#define __DAL_RCM_BACKUPRESET_FORCE() (*(__IO uint32_t *) RCM_BDCTRL_BDRST_BB = ENABLE) +#define __DAL_RCM_BACKUPRESET_RELEASE() (*(__IO uint32_t *) RCM_BDCTRL_BDRST_BB = DISABLE) +/** + * @} + */ + +/** @defgroup RCM_PLL_Configuration PLL Configuration + * @{ + */ + +/** @brief Macros to enable or disable the main PLL. + * @note After enabling the main PLL, the application software should wait on + * PLLRDY flag to be set indicating that PLL clock is stable and can + * be used as system clock source. + * @note The main PLL can not be disabled if it is used as system clock source + * @note The main PLL is disabled by hardware when entering STOP and STANDBY modes. + */ +#define __DAL_RCM_PLL_ENABLE() (*(__IO uint32_t *) RCM_CTRL_PLL1EN_BB = ENABLE) +#define __DAL_RCM_PLL_DISABLE() (*(__IO uint32_t *) RCM_CTRL_PLL1EN_BB = DISABLE) + +/** @brief Macro to configure the PLL clock source. + * @note This function must be used only when the main PLL is disabled. + * @param __PLLSOURCE__ specifies the PLL entry clock source. + * This parameter can be one of the following values: + * @arg RCM_PLLSOURCE_HSI: HSI oscillator clock selected as PLL clock entry + * @arg RCM_PLLSOURCE_HSE: HSE oscillator clock selected as PLL clock entry + * + */ +#define __DAL_RCM_PLL_PLLSOURCE_CONFIG(__PLLSOURCE__) MODIFY_REG(RCM->PLL1CFG, RCM_PLL1CFG_PLL1CLKS, (__PLLSOURCE__)) + +/** @brief Macro to configure the PLL multiplication factor. + * @note This function must be used only when the main PLL is disabled. + * @param __PLLB__ specifies the division factor for PLL VCO input clock + * This parameter must be a number between Min_Data = 2 and Max_Data = 63. + * @note You have to set the PLLB parameter correctly to ensure that the VCO input + * frequency ranges from 1 to 2 MHz. It is recommended to select a frequency + * of 2 MHz to limit PLL jitter. + * + */ +#define __DAL_RCM_PLL_PLLB_CONFIG(__PLLB__) MODIFY_REG(RCM->PLL1CFG, RCM_PLL1CFG_PLLB, (__PLLB__)) +/** + * @} + */ + +/** @defgroup RCM_Get_Clock_source Get Clock source + * @{ + */ +/** + * @brief Macro to configure the system clock source. + * @param __RCM_SYSCLKSOURCE__ specifies the system clock source. + * This parameter can be one of the following values: + * - RCM_SYSCLKSOURCE_HSI: HSI oscillator is used as system clock source. + * - RCM_SYSCLKSOURCE_HSE: HSE oscillator is used as system clock source. + * - RCM_SYSCLKSOURCE_PLLCLK: PLL output is used as system clock source. + * - RCM_SYSCLKSOURCE_PLLRCLK: PLLR output is used as system clock source. This + * parameter is available only for APM32F446xx devices. + */ +#define __DAL_RCM_SYSCLK_CONFIG(__RCM_SYSCLKSOURCE__) MODIFY_REG(RCM->CFG, RCM_CFG_SCLKSEL, (__RCM_SYSCLKSOURCE__)) + +/** @brief Macro to get the clock source used as system clock. + * @retval The clock source used as system clock. The returned value can be one + * of the following: + * - RCM_SYSCLKSOURCE_STATUS_HSI: HSI used as system clock. + * - RCM_SYSCLKSOURCE_STATUS_HSE: HSE used as system clock. + * - RCM_SYSCLKSOURCE_STATUS_PLLCLK: PLL used as system clock. + * - RCM_SYSCLKSOURCE_STATUS_PLLRCLK: PLLR used as system clock. This parameter + * is available only for APM32F446xx devices. + */ +#define __DAL_RCM_GET_SYSCLK_SOURCE() (RCM->CFG & RCM_CFG_SCLKSWSTS) + +/** @brief Macro to get the oscillator used as PLL clock source. + * @retval The oscillator used as PLL clock source. The returned value can be one + * of the following: + * - RCM_PLLSOURCE_HSI: HSI oscillator is used as PLL clock source. + * - RCM_PLLSOURCE_HSE: HSE oscillator is used as PLL clock source. + */ +#define __DAL_RCM_GET_PLL_OSCSOURCE() ((uint32_t)(RCM->PLL1CFG & RCM_PLL1CFG_PLL1CLKS)) +/** + * @} + */ + +/** @defgroup RCMEx_MCOx_Clock_Config RCM Extended MCOx Clock Config + * @{ + */ + +/** @brief Macro to configure the MCO1 clock. + * @param __MCOCLKSOURCE__ specifies the MCO clock source. + * This parameter can be one of the following values: + * @arg RCM_MCO1SOURCE_HSI: HSI clock selected as MCO1 source + * @arg RCM_MCO1SOURCE_LSE: LSE clock selected as MCO1 source + * @arg RCM_MCO1SOURCE_HSE: HSE clock selected as MCO1 source + * @arg RCM_MCO1SOURCE_PLLCLK: main PLL clock selected as MCO1 source + * @param __MCODIV__ specifies the MCO clock prescaler. + * This parameter can be one of the following values: + * @arg RCM_MCODIV_1: no division applied to MCOx clock + * @arg RCM_MCODIV_2: division by 2 applied to MCOx clock + * @arg RCM_MCODIV_3: division by 3 applied to MCOx clock + * @arg RCM_MCODIV_4: division by 4 applied to MCOx clock + * @arg RCM_MCODIV_5: division by 5 applied to MCOx clock + */ +#define __DAL_RCM_MCO1_CONFIG(__MCOCLKSOURCE__, __MCODIV__) \ + MODIFY_REG(RCM->CFG, (RCM_CFG_MCO1SEL | RCM_CFG_MCO1PSC), ((__MCOCLKSOURCE__) | (__MCODIV__))) + +/** @brief Macro to configure the MCO2 clock. + * @param __MCOCLKSOURCE__ specifies the MCO clock source. + * This parameter can be one of the following values: + * @arg RCM_MCO2SOURCE_SYSCLK: System clock (SYSCLK) selected as MCO2 source + * @arg RCM_MCO2SOURCE_PLLI2SCLK: PLLI2S clock selected as MCO2 source, available for all APM32F4 devices + * @arg RCM_MCO2SOURCE_I2SCLK: I2SCLK clock selected as MCO2 source, available only for APM32F410Rx devices + * @arg RCM_MCO2SOURCE_HSE: HSE clock selected as MCO2 source + * @arg RCM_MCO2SOURCE_PLLCLK: main PLL clock selected as MCO2 source + * @param __MCODIV__ specifies the MCO clock prescaler. + * This parameter can be one of the following values: + * @arg RCM_MCODIV_1: no division applied to MCOx clock + * @arg RCM_MCODIV_2: division by 2 applied to MCOx clock + * @arg RCM_MCODIV_3: division by 3 applied to MCOx clock + * @arg RCM_MCODIV_4: division by 4 applied to MCOx clock + * @arg RCM_MCODIV_5: division by 5 applied to MCOx clock + */ +#define __DAL_RCM_MCO2_CONFIG(__MCOCLKSOURCE__, __MCODIV__) \ + MODIFY_REG(RCM->CFG, (RCM_CFG_MCO2SEL | RCM_CFG_MCO2PSC), ((__MCOCLKSOURCE__) | ((__MCODIV__) << 3U))); +/** + * @} + */ + +/** @defgroup RCM_Flags_Interrupts_Management Flags Interrupts Management + * @brief macros to manage the specified RCM Flags and interrupts. + * @{ + */ + +/** @brief Enable RCM interrupt (Perform Byte access to RCM_INT[14:8] bits to enable + * the selected interrupts). + * @param __INTERRUPT__ specifies the RCM interrupt sources to be enabled. + * This parameter can be any combination of the following values: + * @arg RCM_IT_LSIRDY: LSI ready interrupt. + * @arg RCM_IT_LSERDY: LSE ready interrupt. + * @arg RCM_IT_HSIRDY: HSI ready interrupt. + * @arg RCM_IT_HSERDY: HSE ready interrupt. + * @arg RCM_IT_PLLRDY: Main PLL ready interrupt. + * @arg RCM_IT_PLL2RDY: PLLI2S ready interrupt. + */ +#define __DAL_RCM_ENABLE_IT(__INTERRUPT__) (*(__IO uint8_t *) RCM_INT_BYTE1_ADDRESS |= (__INTERRUPT__)) + +/** @brief Disable RCM interrupt (Perform Byte access to RCM_INT[14:8] bits to disable + * the selected interrupts). + * @param __INTERRUPT__ specifies the RCM interrupt sources to be disabled. + * This parameter can be any combination of the following values: + * @arg RCM_IT_LSIRDY: LSI ready interrupt. + * @arg RCM_IT_LSERDY: LSE ready interrupt. + * @arg RCM_IT_HSIRDY: HSI ready interrupt. + * @arg RCM_IT_HSERDY: HSE ready interrupt. + * @arg RCM_IT_PLLRDY: Main PLL ready interrupt. + * @arg RCM_IT_PLL2RDY: PLLI2S ready interrupt. + */ +#define __DAL_RCM_DISABLE_IT(__INTERRUPT__) (*(__IO uint8_t *) RCM_INT_BYTE1_ADDRESS &= (uint8_t)(~(__INTERRUPT__))) + +/** @brief Clear the RCM's interrupt pending bits (Perform Byte access to RCM_INT[23:16] + * bits to clear the selected interrupt pending bits. + * @param __INTERRUPT__ specifies the interrupt pending bit to clear. + * This parameter can be any combination of the following values: + * @arg RCM_IT_LSIRDY: LSI ready interrupt. + * @arg RCM_IT_LSERDY: LSE ready interrupt. + * @arg RCM_IT_HSIRDY: HSI ready interrupt. + * @arg RCM_IT_HSERDY: HSE ready interrupt. + * @arg RCM_IT_PLLRDY: Main PLL ready interrupt. + * @arg RCM_IT_PLL2RDY: PLLI2S ready interrupt. + * @arg RCM_IT_CSS: Clock Security System interrupt + */ +#define __DAL_RCM_CLEAR_IT(__INTERRUPT__) (*(__IO uint8_t *) RCM_INT_BYTE2_ADDRESS = (__INTERRUPT__)) + +/** @brief Check the RCM's interrupt has occurred or not. + * @param __INTERRUPT__ specifies the RCM interrupt source to check. + * This parameter can be one of the following values: + * @arg RCM_IT_LSIRDY: LSI ready interrupt. + * @arg RCM_IT_LSERDY: LSE ready interrupt. + * @arg RCM_IT_HSIRDY: HSI ready interrupt. + * @arg RCM_IT_HSERDY: HSE ready interrupt. + * @arg RCM_IT_PLLRDY: Main PLL ready interrupt. + * @arg RCM_IT_PLL2RDY: PLLI2S ready interrupt. + * @arg RCM_IT_CSS: Clock Security System interrupt + * @retval The new state of __INTERRUPT__ (TRUE or FALSE). + */ +#define __DAL_RCM_GET_IT(__INTERRUPT__) ((RCM->INT & (__INTERRUPT__)) == (__INTERRUPT__)) + +/** @brief Set RMVF bit to clear the reset flags: RCM_FLAG_PINRST, RCM_FLAG_PORRST, + * RCM_FLAG_SFTRST, RCM_FLAG_IWDTRST, RCM_FLAG_WWDTRST and RCM_FLAG_LPWRRST. + */ +#define __DAL_RCM_CLEAR_RESET_FLAGS() (RCM->CSTS |= RCM_CSTS_RSTFLGCLR) + +/** @brief Check RCM flag is set or not. + * @param __FLAG__ specifies the flag to check. + * This parameter can be one of the following values: + * @arg RCM_FLAG_HSIRDY: HSI oscillator clock ready. + * @arg RCM_FLAG_HSERDY: HSE oscillator clock ready. + * @arg RCM_FLAG_PLLRDY: Main PLL clock ready. + * @arg RCM_FLAG_PLL2RDY: PLLI2S clock ready. + * @arg RCM_FLAG_LSERDY: LSE oscillator clock ready. + * @arg RCM_FLAG_LSIRDY: LSI oscillator clock ready. + * @arg RCM_FLAG_BORRST: POR/PDR or BOR reset. + * @arg RCM_FLAG_PINRST: Pin reset. + * @arg RCM_FLAG_PORRST: POR/PDR reset. + * @arg RCM_FLAG_SFTRST: Software reset. + * @arg RCM_FLAG_IWDTRST: Independent Watchdog reset. + * @arg RCM_FLAG_WWDTRST: Window Watchdog reset. + * @arg RCM_FLAG_LPWRRST: Low Power reset. + * @retval The new state of __FLAG__ (TRUE or FALSE). + */ +#define RCM_FLAG_MASK ((uint8_t)0x1FU) +#define __DAL_RCM_GET_FLAG(__FLAG__) (((((((__FLAG__) >> 5U) == 1U)? RCM->CTRL :((((__FLAG__) >> 5U) == 2U) ? RCM->BDCTRL :((((__FLAG__) >> 5U) == 3U)? RCM->CSTS :RCM->INT))) & (1U << ((__FLAG__) & RCM_FLAG_MASK)))!= 0U)? 1U : 0U) + +/** + * @} + */ + +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ + /** @addtogroup RCM_Exported_Functions + * @{ + */ + +/** @addtogroup RCM_Exported_Functions_Group1 + * @{ + */ +/* Initialization and de-initialization functions ******************************/ +DAL_StatusTypeDef DAL_RCM_DeInit(void); +DAL_StatusTypeDef DAL_RCM_OscConfig(RCM_OscInitTypeDef *RCM_OscInitStruct); +DAL_StatusTypeDef DAL_RCM_ClockConfig(RCM_ClkInitTypeDef *RCM_ClkInitStruct, uint32_t FLatency); +/** + * @} + */ + +/** @addtogroup RCM_Exported_Functions_Group2 + * @{ + */ +/* Peripheral Control functions ************************************************/ +void DAL_RCM_MCOConfig(uint32_t RCM_MCOx, uint32_t RCM_MCOSource, uint32_t RCM_MCODiv); +void DAL_RCM_EnableCSS(void); +void DAL_RCM_DisableCSS(void); +uint32_t DAL_RCM_GetSysClockFreq(void); +uint32_t DAL_RCM_GetHCLKFreq(void); +uint32_t DAL_RCM_GetPCLK1Freq(void); +uint32_t DAL_RCM_GetPCLK2Freq(void); +void DAL_RCM_GetOscConfig(RCM_OscInitTypeDef *RCM_OscInitStruct); +void DAL_RCM_GetClockConfig(RCM_ClkInitTypeDef *RCM_ClkInitStruct, uint32_t *pFLatency); + +/* CSS NMI IRQ handler */ +void DAL_RCM_NMI_IRQHandler(void); + +/* User Callbacks in non blocking mode (IT mode) */ +void DAL_RCM_CSSCallback(void); + +/** + * @} + */ + +/** + * @} + */ + +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/** @defgroup RCM_Private_Constants RCM Private Constants + * @{ + */ + +/** @defgroup RCM_BitAddress_AliasRegion RCM BitAddress AliasRegion + * @brief RCM registers bit address in the alias region + * @{ + */ +#define RCM_OFFSET (RCM_BASE - PERIPH_BASE) +/* --- CTRL Register --- */ +/* Alias word address of HSIEN bit */ +#define RCM_CTRL_OFFSET (RCM_OFFSET + 0x00U) +#define RCM_HSIEN_BIT_NUMBER 0x00U +#define RCM_CTRL_HSIEN_BB (PERIPH_BB_BASE + (RCM_CTRL_OFFSET * 32U) + (RCM_HSIEN_BIT_NUMBER * 4U)) +/* Alias word address of CSSEN bit */ +#define RCM_CSSEN_BIT_NUMBER 0x13U +#define RCM_CTRL_CSSEN_BB (PERIPH_BB_BASE + (RCM_CTRL_OFFSET * 32U) + (RCM_CSSEN_BIT_NUMBER * 4U)) +/* Alias word address of PLL1EN bit */ +#define RCM_PLLEN_BIT_NUMBER 0x18U +#define RCM_CTRL_PLL1EN_BB (PERIPH_BB_BASE + (RCM_CTRL_OFFSET * 32U) + (RCM_PLLEN_BIT_NUMBER * 4U)) + +/* --- BDCTRL Register --- */ +/* Alias word address of RTCEN bit */ +#define RCM_BDCTRL_OFFSET (RCM_OFFSET + 0x70U) +#define RCM_RTCEN_BIT_NUMBER 0x0FU +#define RCM_BDCTRL_RTCCLKEN_BB (PERIPH_BB_BASE + (RCM_BDCTRL_OFFSET * 32U) + (RCM_RTCEN_BIT_NUMBER * 4U)) +/* Alias word address of BDRST bit */ +#define RCM_BDRST_BIT_NUMBER 0x10U +#define RCM_BDCTRL_BDRST_BB (PERIPH_BB_BASE + (RCM_BDCTRL_OFFSET * 32U) + (RCM_BDRST_BIT_NUMBER * 4U)) + +/* --- CSTS Register --- */ +/* Alias word address of LSION bit */ +#define RCM_CSTS_OFFSET (RCM_OFFSET + 0x74U) +#define RCM_LSIEN_BIT_NUMBER 0x00U +#define RCM_CSTS_LSIEN_BB (PERIPH_BB_BASE + (RCM_CSTS_OFFSET * 32U) + (RCM_LSIEN_BIT_NUMBER * 4U)) + +/* CTRL register byte 3 (Bits[23:16]) base address */ +#define RCM_CTRL_BYTE2_ADDRESS 0x40023802U + +/* INT register byte 2 (Bits[15:8]) base address */ +#define RCM_INT_BYTE1_ADDRESS ((uint32_t)(RCM_BASE + 0x0CU + 0x01U)) + +/* INT register byte 3 (Bits[23:16]) base address */ +#define RCM_INT_BYTE2_ADDRESS ((uint32_t)(RCM_BASE + 0x0CU + 0x02U)) + +/* BDCTRL register base address */ +#define RCM_BDCTRL_BYTE0_ADDRESS (PERIPH_BASE + RCM_BDCTRL_OFFSET) + +#define RCM_DBP_TIMEOUT_VALUE 2U +#define RCM_LSE_TIMEOUT_VALUE LSE_STARTUP_TIMEOUT + +#define HSE_TIMEOUT_VALUE HSE_STARTUP_TIMEOUT +#define HSI_TIMEOUT_VALUE 2U /* 2 ms */ +#define LSI_TIMEOUT_VALUE 2U /* 2 ms */ +#define CLOCKSWITCH_TIMEOUT_VALUE 5000U /* 5 s */ + +/** + * @} + */ + +/** + * @} + */ + +/* Private macros ------------------------------------------------------------*/ +/** @defgroup RCM_Private_Macros RCM Private Macros + * @{ + */ + +/** @defgroup RCM_IS_RCM_Definitions RCM Private macros to check input parameters + * @{ + */ +#define IS_RCM_OSCILLATORTYPE(OSCILLATOR) ((OSCILLATOR) <= 15U) + +#define IS_RCM_HSE(HSE) (((HSE) == RCM_HSE_OFF) || ((HSE) == RCM_HSE_ON) || \ + ((HSE) == RCM_HSE_BYPASS)) + +#define IS_RCM_LSE(LSE) (((LSE) == RCM_LSE_OFF) || ((LSE) == RCM_LSE_ON) || \ + ((LSE) == RCM_LSE_BYPASS)) + +#define IS_RCM_HSI(HSI) (((HSI) == RCM_HSI_OFF) || ((HSI) == RCM_HSI_ON)) + +#define IS_RCM_LSI(LSI) (((LSI) == RCM_LSI_OFF) || ((LSI) == RCM_LSI_ON)) + +#define IS_RCM_PLL(PLL) (((PLL) == RCM_PLL_NONE) ||((PLL) == RCM_PLL_OFF) || ((PLL) == RCM_PLL_ON)) + +#define IS_RCM_PLLSOURCE(SOURCE) (((SOURCE) == RCM_PLLSOURCE_HSI) || \ + ((SOURCE) == RCM_PLLSOURCE_HSE)) + +#define IS_RCM_SYSCLKSOURCE(SOURCE) (((SOURCE) == RCM_SYSCLKSOURCE_HSI) || \ + ((SOURCE) == RCM_SYSCLKSOURCE_HSE) || \ + ((SOURCE) == RCM_SYSCLKSOURCE_PLLCLK) || \ + ((SOURCE) == RCM_SYSCLKSOURCE_PLLRCLK)) + +#define IS_RCM_RTCCLKSOURCE(__SOURCE__) (((__SOURCE__) == RCM_RTCCLKSOURCE_LSE) || \ + ((__SOURCE__) == RCM_RTCCLKSOURCE_LSI) || \ + ((__SOURCE__) == RCM_RTCCLKSOURCE_HSE_DIV2) || \ + ((__SOURCE__) == RCM_RTCCLKSOURCE_HSE_DIV3) || \ + ((__SOURCE__) == RCM_RTCCLKSOURCE_HSE_DIV4) || \ + ((__SOURCE__) == RCM_RTCCLKSOURCE_HSE_DIV5) || \ + ((__SOURCE__) == RCM_RTCCLKSOURCE_HSE_DIV6) || \ + ((__SOURCE__) == RCM_RTCCLKSOURCE_HSE_DIV7) || \ + ((__SOURCE__) == RCM_RTCCLKSOURCE_HSE_DIV8) || \ + ((__SOURCE__) == RCM_RTCCLKSOURCE_HSE_DIV9) || \ + ((__SOURCE__) == RCM_RTCCLKSOURCE_HSE_DIV10) || \ + ((__SOURCE__) == RCM_RTCCLKSOURCE_HSE_DIV11) || \ + ((__SOURCE__) == RCM_RTCCLKSOURCE_HSE_DIV12) || \ + ((__SOURCE__) == RCM_RTCCLKSOURCE_HSE_DIV13) || \ + ((__SOURCE__) == RCM_RTCCLKSOURCE_HSE_DIV14) || \ + ((__SOURCE__) == RCM_RTCCLKSOURCE_HSE_DIV15) || \ + ((__SOURCE__) == RCM_RTCCLKSOURCE_HSE_DIV16) || \ + ((__SOURCE__) == RCM_RTCCLKSOURCE_HSE_DIV17) || \ + ((__SOURCE__) == RCM_RTCCLKSOURCE_HSE_DIV18) || \ + ((__SOURCE__) == RCM_RTCCLKSOURCE_HSE_DIV19) || \ + ((__SOURCE__) == RCM_RTCCLKSOURCE_HSE_DIV20) || \ + ((__SOURCE__) == RCM_RTCCLKSOURCE_HSE_DIV21) || \ + ((__SOURCE__) == RCM_RTCCLKSOURCE_HSE_DIV22) || \ + ((__SOURCE__) == RCM_RTCCLKSOURCE_HSE_DIV23) || \ + ((__SOURCE__) == RCM_RTCCLKSOURCE_HSE_DIV24) || \ + ((__SOURCE__) == RCM_RTCCLKSOURCE_HSE_DIV25) || \ + ((__SOURCE__) == RCM_RTCCLKSOURCE_HSE_DIV26) || \ + ((__SOURCE__) == RCM_RTCCLKSOURCE_HSE_DIV27) || \ + ((__SOURCE__) == RCM_RTCCLKSOURCE_HSE_DIV28) || \ + ((__SOURCE__) == RCM_RTCCLKSOURCE_HSE_DIV29) || \ + ((__SOURCE__) == RCM_RTCCLKSOURCE_HSE_DIV30) || \ + ((__SOURCE__) == RCM_RTCCLKSOURCE_HSE_DIV31)) + +#define IS_RCM_PLLB_VALUE(VALUE) ((VALUE) <= 63U) + +#define IS_RCM_PLL1C_VALUE(VALUE) (((VALUE) == 2U) || ((VALUE) == 4U) || ((VALUE) == 6U) || ((VALUE) == 8U)) + +#define IS_RCM_PLLD_VALUE(VALUE) ((2U <= (VALUE)) && ((VALUE) <= 15U)) + +#define IS_RCM_HCLK(HCLK) (((HCLK) == RCM_SYSCLK_DIV1) || ((HCLK) == RCM_SYSCLK_DIV2) || \ + ((HCLK) == RCM_SYSCLK_DIV4) || ((HCLK) == RCM_SYSCLK_DIV8) || \ + ((HCLK) == RCM_SYSCLK_DIV16) || ((HCLK) == RCM_SYSCLK_DIV64) || \ + ((HCLK) == RCM_SYSCLK_DIV128) || ((HCLK) == RCM_SYSCLK_DIV256) || \ + ((HCLK) == RCM_SYSCLK_DIV512)) + +#define IS_RCM_CLOCKTYPE(CLK) ((1U <= (CLK)) && ((CLK) <= 15U)) + +#define IS_RCM_PCLK(PCLK) (((PCLK) == RCM_HCLK_DIV1) || ((PCLK) == RCM_HCLK_DIV2) || \ + ((PCLK) == RCM_HCLK_DIV4) || ((PCLK) == RCM_HCLK_DIV8) || \ + ((PCLK) == RCM_HCLK_DIV16)) + +#define IS_RCM_MCO(MCOx) (((MCOx) == RCM_MCO1) || ((MCOx) == RCM_MCO2)) + +#define IS_RCM_MCO1SOURCE(SOURCE) (((SOURCE) == RCM_MCO1SOURCE_HSI) || ((SOURCE) == RCM_MCO1SOURCE_LSE) || \ + ((SOURCE) == RCM_MCO1SOURCE_HSE) || ((SOURCE) == RCM_MCO1SOURCE_PLLCLK)) + +#define IS_RCM_MCODIV(DIV) (((DIV) == RCM_MCODIV_1) || ((DIV) == RCM_MCODIV_2) || \ + ((DIV) == RCM_MCODIV_3) || ((DIV) == RCM_MCODIV_4) || \ + ((DIV) == RCM_MCODIV_5)) +#define IS_RCM_CALIBRATION_VALUE(VALUE) ((VALUE) <= 0x1FU) + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* APM32F4xx_DAL_RCM_H */ + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_rcm_ex.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_rcm_ex.h new file mode 100644 index 0000000000..c184995fb5 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_rcm_ex.h @@ -0,0 +1,1950 @@ +/** + * + * @file apm32f4xx_dal_rcm_ex.h + * @brief Header file of RCM DAL Extension module. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2017 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file in + * the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef APM32F4xx_DAL_RCM_EX_H +#define APM32F4xx_DAL_RCM_EX_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal_def.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @addtogroup RCMEx + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ +/** @defgroup RCMEx_Exported_Types RCMEx Exported Types + * @{ + */ + +/** + * @brief RCM PLL configuration structure definition + */ +typedef struct +{ + uint32_t PLLState; /*!< The new state of the PLL. + This parameter can be a value of @ref RCM_PLL_Config */ + + uint32_t PLLSource; /*!< RCM_PLLSource: PLL entry clock source. + This parameter must be a value of @ref RCM_PLL_Clock_Source */ + + uint32_t PLLB; /*!< PLLB: Division factor for PLL VCO input clock. + This parameter must be a number between Min_Data = 0 and Max_Data = 63 */ + + uint32_t PLL1A; /*!< PLL1A: Multiplication factor for PLL VCO output clock. + This parameter must be a number between Min_Data = 50 and Max_Data = 432 + except for APM32F411xx devices where the Min_Data = 192 */ + + uint32_t PLL1C; /*!< PLL1C: Division factor for main system clock (SYSCLK). + This parameter must be a value of @ref RCM_PLL1C_Clock_Divider */ + + uint32_t PLLD; /*!< PLLD: Division factor for OTG FS, SDIO and RNG clocks. + This parameter must be a number between Min_Data = 2 and Max_Data = 15 */ + +}RCM_PLLInitTypeDef; + +#if defined(APM32F405xx) || defined(APM32F407xx) || defined(APM32F417xx) ||\ + defined(APM32F465xx) || defined(APM32F411xx) +/** + * @brief PLLI2S Clock structure definition + */ +typedef struct +{ +#if defined(APM32F411xx) + uint32_t PLL2B; /*!< PLLB: Division factor for PLLI2S VCO input clock. + This parameter must be a number between Min_Data = 2 and Max_Data = 62 */ +#endif /* APM32F411xx */ + + uint32_t PLL2A; /*!< Specifies the multiplication factor for PLLI2S VCO output clock. + This parameter must be a number between Min_Data = 50 and Max_Data = 432 + Except for APM32F411xx devices where the Min_Data = 192. + This parameter will be used only when PLLI2S is selected as Clock Source I2S or SAI */ + + uint32_t PLL2C; /*!< Specifies the division factor for I2S clock. + This parameter must be a number between Min_Data = 2 and Max_Data = 7. + This parameter will be used only when PLLI2S is selected as Clock Source I2S or SAI */ + +}RCM_PLLI2SInitTypeDef; + +/** + * @brief RCM extended clocks structure definition + */ +typedef struct +{ + uint32_t PeriphClockSelection; /*!< The Extended Clock to be configured. + This parameter can be a value of @ref RCMEx_Periph_Clock_Selection */ +#if defined(APM32F407xx) || defined(APM32F417xx) + uint32_t SDRAMClockDivision; /*!< The SDRAM clock division. + This parameter can be a value of @ref RCMEx_SDRAM_Clock_Division */ +#endif /* APM32F407xx || APM32F417xx */ + RCM_PLLI2SInitTypeDef PLLI2S; /*!< PLL I2S structure parameters. + This parameter will be used only when PLLI2S is selected as Clock Source I2S or SAI */ + + uint32_t RTCClockSelection; /*!< Specifies RTC Clock Prescalers Selection. + This parameter can be a value of @ref RCM_RTC_Clock_Source */ +#if defined(APM32F411xx) + uint8_t TMRPresSelection; /*!< Specifies TMR Clock Source Selection. + This parameter can be a value of @ref RCMEx_TMR_PRescaler_Selection */ +#endif /* APM32F411xx */ +}RCM_PeriphCLKInitTypeDef; +#endif /* APM32F405xx || APM32F407xx || APM32F417xx || APM32F465xx || APM32F411xx */ +/** + * @} + */ + +/* Exported constants --------------------------------------------------------*/ +/** @defgroup RCMEx_Exported_Constants RCMEx Exported Constants + * @{ + */ + +/** @defgroup RCMEx_Periph_Clock_Selection RCM Periph Clock Selection + * @{ + */ + +/*-------- Peripheral Clock source for APM32F40xxx/APM32F41xxx/APM32F465xx ---------------*/ +#if defined(APM32F405xx) || defined(APM32F407xx) || defined(APM32F417xx) ||\ + defined(APM32F465xx) || defined(APM32F411xx) +#define RCM_PERIPHCLK_I2S 0x00000001U +#define RCM_PERIPHCLK_RTC 0x00000002U +#define RCM_PERIPHCLK_PLLI2S 0x00000004U +#if defined(APM32F407xx) || defined(APM32F417xx) +#define RCM_PERIPHCLK_SDRAM 0x00000008U +#endif /* APM32F407xx || APM32F417xx */ +#endif /* APM32F405xx || APM32F407xx || APM32F417xx || APM32F465xx || APM32F411xx */ +#if defined(APM32F411xx) +#define RCM_PERIPHCLK_TMR 0x00000008U +#endif /* APM32F411xx */ +/*----------------------------------------------------------------------------*/ +/** + * @} + */ + +#if defined(APM32F407xx) || defined(APM32F417xx) +/** @defgroup RCMEx_SDRAM_Clock_Division SDRAM Clock Division + * @{ + */ +#define RCM_SDRAM_DIV_1 0x00000000U +#define RCM_SDRAM_DIV_2 0x00000001U +#define RCM_SDRAM_DIV_4 0x00000002U + +/** + * @} + */ +#endif /* APM32F407xx || APM32F417xx */ + +#if defined(APM32F405xx) || defined(APM32F407xx) || defined(APM32F417xx) || \ + defined(APM32F465xx) || defined(APM32F411xx) +/** @defgroup RCMEx_I2S_Clock_Source I2S Clock Source + * @{ + */ +#define RCM_I2SCLKSOURCE_PLLI2S 0x00000000U +#define RCM_I2SCLKSOURCE_EXT 0x00000001U +/** + * @} + */ +#endif /* APM32F405xx || APM32F407xx || APM32F417xx || APM32F465xx || APM32F411xx */ + +#if defined(APM32F411xx) +/** @defgroup RCMEx_TMR_PRescaler_Selection RCM TMR PRescaler Selection + * @{ + */ +#define RCM_TMRPRES_DESACTIVATED ((uint8_t)0x00) +#define RCM_TMRPRES_ACTIVATED ((uint8_t)0x01) +/** + * @} + */ +#endif /* APM32F411xx */ + +#if defined(APM32F411xx) +/** @defgroup RCMEx_LSE_Dual_Mode_Selection RCM LSE Dual Mode Selection + * @{ + */ +#define RCM_LSE_LOWPOWER_MODE ((uint8_t)0x00) +#define RCM_LSE_HIGHDRIVE_MODE ((uint8_t)0x01) +/** + * @} + */ +#endif /* APM32F411xx */ + +#if defined(APM32F405xx) || defined(APM32F407xx) || defined(APM32F417xx) || \ + defined(APM32F465xx) || defined(APM32F411xx) +/** @defgroup RCM_MCO2_Clock_Source MCO2 Clock Source + * @{ + */ +#define RCM_MCO2SOURCE_SYSCLK 0x00000000U +#define RCM_MCO2SOURCE_PLLI2SCLK RCM_CFG_MCO2SEL_0 +#define RCM_MCO2SOURCE_HSE RCM_CFG_MCO2SEL_1 +#define RCM_MCO2SOURCE_PLLCLK RCM_CFG_MCO2SEL +/** + * @} + */ +#endif /* APM32F405xx || APM32F407xx || APM32F417xx || + APM32F465xx || APM32F411xx */ + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ +/** @defgroup RCMEx_Exported_Macros RCMEx Exported Macros + * @{ + */ + +/*----------------------------------- APM32F40xxx/APM32F41xxx/APM32F465xx-----------------*/ +#if defined(APM32F405xx) || defined(APM32F407xx) || defined(APM32F417xx) || defined(APM32F465xx) +/** @defgroup RCMEx_AHB1_Clock_Enable_Disable AHB1 Peripheral Clock Enable Disable + * @brief Enables or disables the AHB1 peripheral clock. + * @note After reset, the peripheral clock (used for registers read/write access) + * is disabled and the application software has to enable this clock before + * using it. + * @{ + */ +#define __DAL_RCM_BKPSRAM_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->AHB1CLKEN, RCM_AHB1CLKEN_BKPSRAMEN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->AHB1CLKEN, RCM_AHB1CLKEN_BKPSRAMEN);\ + UNUSED(tmpreg); \ + } while(0U) +#define __DAL_RCM_CCMDATARAMEN_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->AHB1CLKEN, RCM_AHB1CLKEN_DRAMEN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->AHB1CLKEN, RCM_AHB1CLKEN_DRAMEN);\ + UNUSED(tmpreg); \ + } while(0U) +#define __DAL_RCM_CRC_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->AHB1CLKEN, RCM_AHB1CLKEN_CRCEN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->AHB1CLKEN, RCM_AHB1CLKEN_CRCEN);\ + UNUSED(tmpreg); \ + } while(0U) +#define __DAL_RCM_GPIOD_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->AHB1CLKEN, RCM_AHB1CLKEN_PDEN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->AHB1CLKEN, RCM_AHB1CLKEN_PDEN);\ + UNUSED(tmpreg); \ + } while(0U) +#define __DAL_RCM_GPIOE_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->AHB1CLKEN, RCM_AHB1CLKEN_PEEN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->AHB1CLKEN, RCM_AHB1CLKEN_PEEN);\ + UNUSED(tmpreg); \ + } while(0U) +#define __DAL_RCM_GPIOI_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->AHB1CLKEN, RCM_AHB1CLKEN_PIEN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->AHB1CLKEN, RCM_AHB1CLKEN_PIEN);\ + UNUSED(tmpreg); \ + } while(0U) +#define __DAL_RCM_GPIOF_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->AHB1CLKEN, RCM_AHB1CLKEN_PFEN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->AHB1CLKEN, RCM_AHB1CLKEN_PFEN);\ + UNUSED(tmpreg); \ + } while(0U) +#define __DAL_RCM_GPIOG_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->AHB1CLKEN, RCM_AHB1CLKEN_PGEN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->AHB1CLKEN, RCM_AHB1CLKEN_PGEN);\ + UNUSED(tmpreg); \ + } while(0U) +#define __DAL_RCM_USB_OTG_HS_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->AHB1CLKEN, RCM_AHB1CLKEN_OTGHS1EN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->AHB1CLKEN, RCM_AHB1CLKEN_OTGHS1EN);\ + UNUSED(tmpreg); \ + } while(0U) +#define __DAL_RCM_USB_OTG_HS_ULPI_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->AHB1CLKEN, RCM_AHB1CLKEN_OTGHSULPIEN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->AHB1CLKEN, RCM_AHB1CLKEN_OTGHSULPIEN);\ + UNUSED(tmpreg); \ + } while(0U) +#define __DAL_RCM_GPIOD_CLK_DISABLE() (RCM->AHB1CLKEN &= ~(RCM_AHB1CLKEN_PDEN)) +#define __DAL_RCM_GPIOE_CLK_DISABLE() (RCM->AHB1CLKEN &= ~(RCM_AHB1CLKEN_PEEN)) +#define __DAL_RCM_GPIOF_CLK_DISABLE() (RCM->AHB1CLKEN &= ~(RCM_AHB1CLKEN_PFEN)) +#define __DAL_RCM_GPIOG_CLK_DISABLE() (RCM->AHB1CLKEN &= ~(RCM_AHB1CLKEN_PGEN)) +#define __DAL_RCM_GPIOI_CLK_DISABLE() (RCM->AHB1CLKEN &= ~(RCM_AHB1CLKEN_PIEN)) +#define __DAL_RCM_USB_OTG_HS_CLK_DISABLE() (RCM->AHB1CLKEN &= ~(RCM_AHB1CLKEN_OTGHS1EN)) +#define __DAL_RCM_USB_OTG_HS_ULPI_CLK_DISABLE() (RCM->AHB1CLKEN &= ~(RCM_AHB1CLKEN_OTGHSULPIEN)) +#define __DAL_RCM_BKPSRAM_CLK_DISABLE() (RCM->AHB1CLKEN &= ~(RCM_AHB1CLKEN_BKPSRAMEN)) +#define __DAL_RCM_CCMDATARAMEN_CLK_DISABLE() (RCM->AHB1CLKEN &= ~(RCM_AHB1CLKEN_DRAMEN)) +#define __DAL_RCM_CRC_CLK_DISABLE() (RCM->AHB1CLKEN &= ~(RCM_AHB1CLKEN_CRCEN)) +#if defined(APM32F407xx) || defined(APM32F417xx) +/** + * @brief Enable ETHERNET clock. + */ +#define __DAL_RCM_ETHMAC_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->AHB1CLKEN, RCM_AHB1CLKEN_ETHEN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->AHB1CLKEN, RCM_AHB1CLKEN_ETHEN);\ + UNUSED(tmpreg); \ + } while(0U) +#define __DAL_RCM_ETHMACTX_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->AHB1CLKEN, RCM_AHB1CLKEN_ETHTXEN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->AHB1CLKEN, RCM_AHB1CLKEN_ETHTXEN);\ + UNUSED(tmpreg); \ + } while(0U) +#define __DAL_RCM_ETHMACRX_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->AHB1CLKEN, RCM_AHB1CLKEN_ETHRXEN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->AHB1CLKEN, RCM_AHB1CLKEN_ETHRXEN);\ + UNUSED(tmpreg); \ + } while(0U) +#define __DAL_RCM_ETHMACPTP_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->AHB1CLKEN, RCM_AHB1CLKEN_ETHPTPEN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->AHB1CLKEN, RCM_AHB1CLKEN_ETHPTPEN);\ + UNUSED(tmpreg); \ + } while(0U) +#define __DAL_RCM_ETH_CLK_ENABLE() do { \ + __DAL_RCM_ETHMAC_CLK_ENABLE(); \ + __DAL_RCM_ETHMACTX_CLK_ENABLE(); \ + __DAL_RCM_ETHMACRX_CLK_ENABLE(); \ + } while(0U) + +/** + * @brief Disable ETHERNET clock. + */ +#define __DAL_RCM_ETHMAC_CLK_DISABLE() (RCM->AHB1CLKEN &= ~(RCM_AHB1CLKEN_ETHEN)) +#define __DAL_RCM_ETHMACTX_CLK_DISABLE() (RCM->AHB1CLKEN &= ~(RCM_AHB1CLKEN_ETHTXEN)) +#define __DAL_RCM_ETHMACRX_CLK_DISABLE() (RCM->AHB1CLKEN &= ~(RCM_AHB1CLKEN_ETHRXEN)) +#define __DAL_RCM_ETHMACPTP_CLK_DISABLE() (RCM->AHB1CLKEN &= ~(RCM_AHB1CLKEN_ETHPTPEN)) +#define __DAL_RCM_ETH_CLK_DISABLE() do { \ + __DAL_RCM_ETHMACTX_CLK_DISABLE(); \ + __DAL_RCM_ETHMACRX_CLK_DISABLE(); \ + __DAL_RCM_ETHMAC_CLK_DISABLE(); \ + } while(0U) +#endif /* APM32F407xx || APM32F417xx */ +/** + * @} + */ + +/** @defgroup RCMEx_AHB1_Peripheral_Clock_Enable_Disable_Status AHB1 Peripheral Clock Enable Disable Status + * @brief Get the enable or disable status of the AHB1 peripheral clock. + * @note After reset, the peripheral clock (used for registers read/write access) + * is disabled and the application software has to enable this clock before + * using it. + * @{ + */ +#define __DAL_RCM_BKPSRAM_IS_CLK_ENABLED() ((RCM->AHB1CLKEN & (RCM_AHB1CLKEN_BKPSRAMEN)) != RESET) +#define __DAL_RCM_CCMDATARAMEN_IS_CLK_ENABLED() ((RCM->AHB1CLKEN & (RCM_AHB1CLKEN_DRAMEN)) != RESET) +#define __DAL_RCM_CRC_IS_CLK_ENABLED() ((RCM->AHB1CLKEN & (RCM_AHB1CLKEN_CRCEN)) != RESET) +#define __DAL_RCM_GPIOD_IS_CLK_ENABLED() ((RCM->AHB1CLKEN & (RCM_AHB1CLKEN_PDEN)) != RESET) +#define __DAL_RCM_GPIOE_IS_CLK_ENABLED() ((RCM->AHB1CLKEN & (RCM_AHB1CLKEN_PEEN)) != RESET) +#define __DAL_RCM_GPIOI_IS_CLK_ENABLED() ((RCM->AHB1CLKEN & (RCM_AHB1CLKEN_PIEN)) != RESET) +#define __DAL_RCM_GPIOF_IS_CLK_ENABLED() ((RCM->AHB1CLKEN & (RCM_AHB1CLKEN_PFEN)) != RESET) +#define __DAL_RCM_GPIOG_IS_CLK_ENABLED() ((RCM->AHB1CLKEN & (RCM_AHB1CLKEN_PGEN)) != RESET) +#define __DAL_RCM_USB_OTG_HS_IS_CLK_ENABLED() ((RCM->AHB1CLKEN & (RCM_AHB1CLKEN_OTGHS1EN)) != RESET) +#define __DAL_RCM_USB_OTG_HS_ULPI_IS_CLK_ENABLED() ((RCM->AHB1CLKEN & (RCM_AHB1CLKEN_OTGHSULPIEN)) != RESET) + +#define __DAL_RCM_GPIOD_IS_CLK_DISABLED() ((RCM->AHB1CLKEN & (RCM_AHB1CLKEN_PDEN)) == RESET) +#define __DAL_RCM_GPIOE_IS_CLK_DISABLED() ((RCM->AHB1CLKEN & (RCM_AHB1CLKEN_PEEN)) == RESET) +#define __DAL_RCM_GPIOF_IS_CLK_DISABLED() ((RCM->AHB1CLKEN & (RCM_AHB1CLKEN_PFEN)) == RESET) +#define __DAL_RCM_GPIOG_IS_CLK_DISABLED() ((RCM->AHB1CLKEN & (RCM_AHB1CLKEN_PGEN)) == RESET) +#define __DAL_RCM_GPIOI_IS_CLK_DISABLED() ((RCM->AHB1CLKEN & (RCM_AHB1CLKEN_PIEN)) == RESET) +#define __DAL_RCM_USB_OTG_HS_IS_CLK_DISABLED() ((RCM->AHB1CLKEN & (RCM_AHB1CLKEN_OTGHS1EN)) == RESET) +#define __DAL_RCM_USB_OTG_HS_ULPI_IS_CLK_DISABLED() ((RCM->AHB1CLKEN & (RCM_AHB1CLKEN_OTGHSULPIEN))== RESET) +#define __DAL_RCM_BKPSRAM_IS_CLK_DISABLED() ((RCM->AHB1CLKEN & (RCM_AHB1CLKEN_BKPSRAMEN)) == RESET) +#define __DAL_RCM_CCMDATARAMEN_IS_CLK_DISABLED() ((RCM->AHB1CLKEN & (RCM_AHB1CLKEN_DRAMEN)) == RESET) +#define __DAL_RCM_CRC_IS_CLK_DISABLED() ((RCM->AHB1CLKEN & (RCM_AHB1CLKEN_CRCEN)) == RESET) +#if defined(APM32F407xx) || defined(APM32F417xx) +/** + * @brief Enable ETHERNET clock. + */ +#define __DAL_RCM_ETHMAC_IS_CLK_ENABLED() ((RCM->AHB1CLKEN & (RCM_AHB1CLKEN_ETHEN)) != RESET) +#define __DAL_RCM_ETHMACTX_IS_CLK_ENABLED() ((RCM->AHB1CLKEN & (RCM_AHB1CLKEN_ETHTXEN)) != RESET) +#define __DAL_RCM_ETHMACRX_IS_CLK_ENABLED() ((RCM->AHB1CLKEN & (RCM_AHB1CLKEN_ETHRXEN)) != RESET) +#define __DAL_RCM_ETHMACPTP_IS_CLK_ENABLED() ((RCM->AHB1CLKEN & (RCM_AHB1CLKEN_ETHPTPEN)) != RESET) +#define __DAL_RCM_ETH_IS_CLK_ENABLED() (__DAL_RCM_ETHMAC_IS_CLK_ENABLED() && \ + __DAL_RCM_ETHMACTX_IS_CLK_ENABLED() && \ + __DAL_RCM_ETHMACRX_IS_CLK_ENABLED()) +/** + * @brief Disable ETHERNET clock. + */ +#define __DAL_RCM_ETHMAC_IS_CLK_DISABLED() ((RCM->AHB1CLKEN & (RCM_AHB1CLKEN_ETHEN)) == RESET) +#define __DAL_RCM_ETHMACTX_IS_CLK_DISABLED() ((RCM->AHB1CLKEN & (RCM_AHB1CLKEN_ETHTXEN)) == RESET) +#define __DAL_RCM_ETHMACRX_IS_CLK_DISABLED() ((RCM->AHB1CLKEN & (RCM_AHB1CLKEN_ETHRXEN)) == RESET) +#define __DAL_RCM_ETHMACPTP_IS_CLK_DISABLED() ((RCM->AHB1CLKEN & (RCM_AHB1CLKEN_ETHPTPEN)) == RESET) +#define __DAL_RCM_ETH_IS_CLK_DISABLED() (__DAL_RCM_ETHMAC_IS_CLK_DISABLED() && \ + __DAL_RCM_ETHMACTX_IS_CLK_DISABLED() && \ + __DAL_RCM_ETHMACRX_IS_CLK_DISABLED()) +#endif /* APM32F407xx || APM32F417xx */ +/** + * @} + */ + +/** @defgroup RCMEx_AHB2_Clock_Enable_Disable AHB2 Peripheral Clock Enable Disable + * @brief Enable or disable the AHB2 peripheral clock. + * @note After reset, the peripheral clock (used for registers read/write access) + * is disabled and the application software has to enable this clock before + * using it. + * @{ + */ +#define __DAL_RCM_USB_OTG_FS_CLK_ENABLE() do {(RCM->AHB2CLKEN |= (RCM_AHB2CLKEN_OTGFSEN));\ + __DAL_RCM_SYSCFG_CLK_ENABLE();\ + }while(0U) + +#define __DAL_RCM_USB_OTG_FS_CLK_DISABLE() (RCM->AHB2CLKEN &= ~(RCM_AHB2CLKEN_OTGFSEN)) + +#define __DAL_RCM_RNG_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->AHB2CLKEN, RCM_AHB2CLKEN_RNGEN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->AHB2CLKEN, RCM_AHB2CLKEN_RNGEN);\ + UNUSED(tmpreg); \ + } while(0U) +#define __DAL_RCM_RNG_CLK_DISABLE() (RCM->AHB2CLKEN &= ~(RCM_AHB2CLKEN_RNGEN)) + +#if defined(APM32F407xx) || defined(APM32F417xx) +#define __DAL_RCM_DCI_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->AHB2CLKEN, RCM_AHB2CLKEN_DCIEN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->AHB2CLKEN, RCM_AHB2CLKEN_DCIEN);\ + UNUSED(tmpreg); \ + } while(0U) +#define __DAL_RCM_DCI_CLK_DISABLE() (RCM->AHB2CLKEN &= ~(RCM_AHB2CLKEN_DCIEN)) +#endif /* APM32F407xx || APM32F417xx */ + +#if defined(APM32F417xx) +#define __DAL_RCM_CRYP_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->AHB2CLKEN, RCM_AHB2CLKEN_CRYPEN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->AHB2CLKEN, RCM_AHB2CLKEN_CRYPEN);\ + UNUSED(tmpreg); \ + } while(0U) +#define __DAL_RCM_HASH_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->AHB2CLKEN, RCM_AHB2CLKEN_HASHEN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->AHB2CLKEN, RCM_AHB2CLKEN_HASHEN);\ + UNUSED(tmpreg); \ + } while(0U) +#define __DAL_RCM_CRYP_CLK_DISABLE() (RCM->AHB2CLKEN &= ~(RCM_AHB2CLKEN_CRYPEN)) +#define __DAL_RCM_HASH_CLK_DISABLE() (RCM->AHB2CLKEN &= ~(RCM_AHB2CLKEN_HASHEN)) +#endif /* APM32F417xx */ +/** + * @} + */ + + +/** @defgroup RCMEx_AHB2_Peripheral_Clock_Enable_Disable_Status AHB2 Peripheral Clock Enable Disable Status + * @brief Get the enable or disable status of the AHB2 peripheral clock. + * @note After reset, the peripheral clock (used for registers read/write access) + * is disabled and the application software has to enable this clock before + * using it. + * @{ + */ +#define __DAL_RCM_USB_OTG_FS_IS_CLK_ENABLED() ((RCM->AHB2CLKEN & (RCM_AHB2CLKEN_OTGFSEN)) != RESET) +#define __DAL_RCM_USB_OTG_FS_IS_CLK_DISABLED() ((RCM->AHB2CLKEN & (RCM_AHB2CLKEN_OTGFSEN)) == RESET) + +#define __DAL_RCM_RNG_IS_CLK_ENABLED() ((RCM->AHB2CLKEN & (RCM_AHB2CLKEN_RNGEN)) != RESET) +#define __DAL_RCM_RNG_IS_CLK_DISABLED() ((RCM->AHB2CLKEN & (RCM_AHB2CLKEN_RNGEN)) == RESET) + +#if defined(APM32F407xx) || defined(APM32F417xx) +#define __DAL_RCM_DCI_IS_CLK_ENABLED() ((RCM->AHB2CLKEN & (RCM_AHB2CLKEN_DCIEN)) != RESET) +#define __DAL_RCM_DCI_IS_CLK_DISABLED() ((RCM->AHB2CLKEN & (RCM_AHB2CLKEN_DCIEN)) == RESET) +#endif /* APM32F407xx || APM32F417xx */ + +#if defined(APM32F417xx) +#define __DAL_RCM_CRYP_IS_CLK_ENABLED() ((RCM->AHB2CLKEN & (RCM_AHB2CLKEN_CRYPEN)) != RESET) +#define __DAL_RCM_HASH_IS_CLK_ENABLED() ((RCM->AHB2CLKEN & (RCM_AHB2CLKEN_HASHEN)) != RESET) + +#define __DAL_RCM_CRYP_IS_CLK_DISABLED() ((RCM->AHB2CLKEN & (RCM_AHB2CLKEN_CRYPEN)) == RESET) +#define __DAL_RCM_HASH_IS_CLK_DISABLED() ((RCM->AHB2CLKEN & (RCM_AHB2CLKEN_HASHEN)) == RESET) +#endif /* APM32F417xx */ +/** + * @} + */ + +/** @defgroup RCMEx_AHB3_Clock_Enable_Disable AHB3 Peripheral Clock Enable Disable + * @brief Enables or disables the AHB3 peripheral clock. + * @note After reset, the peripheral clock (used for registers read/write access) + * is disabled and the application software has to enable this clock before + * using it. + * @{ + */ +#if defined(APM32F405xx) || defined(APM32F407xx) || defined(APM32F417xx) || defined(APM32F465xx) +#define __DAL_RCM_EMMC_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->AHB3CLKEN, RCM_AHB3CLKEN_EMMCEN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->AHB3CLKEN, RCM_AHB3CLKEN_EMMCEN);\ + UNUSED(tmpreg); \ + } while(0U) +#define __DAL_RCM_EMMC_CLK_DISABLE() (RCM->AHB3CLKEN &= ~(RCM_AHB3CLKEN_EMMCEN)) +#endif /* APM32F405xx || APM32F407xx || APM32F417xx || APM32F465xx */ +/** + * @} + */ + +/** @defgroup RCMEx_AHB3_Peripheral_Clock_Enable_Disable_Status AHB3 Peripheral Clock Enable Disable Status + * @brief Get the enable or disable status of the AHB3 peripheral clock. + * @note After reset, the peripheral clock (used for registers read/write access) + * is disabled and the application software has to enable this clock before + * using it. + * @{ + */ +#if defined(APM32F405xx) || defined(APM32F407xx) || defined(APM32F417xx) || defined(APM32F465xx) +#define __DAL_RCM_EMMC_IS_CLK_ENABLED() ((RCM->AHB3CLKEN & (RCM_AHB3CLKEN_EMMCEN)) != RESET) +#define __DAL_RCM_EMMC_IS_CLK_DISABLED() ((RCM->AHB3CLKEN & (RCM_AHB3CLKEN_EMMCEN)) == RESET) +#endif /* APM32F405xx || APM32F407xx || APM32F417xx || APM32F465xx */ +/** + * @} + */ + +/** @defgroup RCMEx_APB1_Clock_Enable_Disable APB1 Peripheral Clock Enable Disable + * @brief Enable or disable the Low Speed APB (APB1) peripheral clock. + * @note After reset, the peripheral clock (used for registers read/write access) + * is disabled and the application software has to enable this clock before + * using it. + * @{ + */ +#define __DAL_RCM_TMR6_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->APB1CLKEN, RCM_APB1CLKEN_TMR6EN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->APB1CLKEN, RCM_APB1CLKEN_TMR6EN);\ + UNUSED(tmpreg); \ + } while(0U) +#define __DAL_RCM_TMR7_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->APB1CLKEN, RCM_APB1CLKEN_TMR7EN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->APB1CLKEN, RCM_APB1CLKEN_TMR7EN);\ + UNUSED(tmpreg); \ + } while(0U) +#define __DAL_RCM_TMR12_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->APB1CLKEN, RCM_APB1CLKEN_TMR12EN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->APB1CLKEN, RCM_APB1CLKEN_TMR12EN);\ + UNUSED(tmpreg); \ + } while(0U) +#define __DAL_RCM_TMR13_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->APB1CLKEN, RCM_APB1CLKEN_TMR13EN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->APB1CLKEN, RCM_APB1CLKEN_TMR13EN);\ + UNUSED(tmpreg); \ + } while(0U) +#define __DAL_RCM_TMR14_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->APB1CLKEN, RCM_APB1CLKEN_TMR14EN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->APB1CLKEN, RCM_APB1CLKEN_TMR14EN);\ + UNUSED(tmpreg); \ + } while(0U) +#define __DAL_RCM_USART3_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->APB1CLKEN, RCM_APB1CLKEN_USART3EN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->APB1CLKEN, RCM_APB1CLKEN_USART3EN);\ + UNUSED(tmpreg); \ + } while(0U) +#define __DAL_RCM_UART4_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->APB1CLKEN, RCM_APB1CLKEN_UART4EN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->APB1CLKEN, RCM_APB1CLKEN_UART4EN);\ + UNUSED(tmpreg); \ + } while(0U) +#define __DAL_RCM_UART5_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->APB1CLKEN, RCM_APB1CLKEN_UART5EN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->APB1CLKEN, RCM_APB1CLKEN_UART5EN);\ + UNUSED(tmpreg); \ + } while(0U) +#define __DAL_RCM_CAN1_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->APB1CLKEN, RCM_APB1CLKEN_CAN1EN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->APB1CLKEN, RCM_APB1CLKEN_CAN1EN);\ + UNUSED(tmpreg); \ + } while(0U) +#define __DAL_RCM_CAN2_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->APB1CLKEN, RCM_APB1CLKEN_CAN2EN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->APB1CLKEN, RCM_APB1CLKEN_CAN2EN);\ + UNUSED(tmpreg); \ + } while(0U) +#define __DAL_RCM_DAC_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->APB1CLKEN, RCM_APB1CLKEN_DACEN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->APB1CLKEN, RCM_APB1CLKEN_DACEN);\ + UNUSED(tmpreg); \ + } while(0U) +#define __DAL_RCM_TMR2_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->APB1CLKEN, RCM_APB1CLKEN_TMR2EN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->APB1CLKEN, RCM_APB1CLKEN_TMR2EN);\ + UNUSED(tmpreg); \ + } while(0U) +#define __DAL_RCM_TMR3_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->APB1CLKEN, RCM_APB1CLKEN_TMR3EN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->APB1CLKEN, RCM_APB1CLKEN_TMR3EN);\ + UNUSED(tmpreg); \ + } while(0U) +#define __DAL_RCM_TMR4_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->APB1CLKEN, RCM_APB1CLKEN_TMR4EN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->APB1CLKEN, RCM_APB1CLKEN_TMR4EN);\ + UNUSED(tmpreg); \ + } while(0U) +#define __DAL_RCM_SPI3_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->APB1CLKEN, RCM_APB1CLKEN_SPI3EN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->APB1CLKEN, RCM_APB1CLKEN_SPI3EN);\ + UNUSED(tmpreg); \ + } while(0U) +#define __DAL_RCM_I2C3_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->APB1CLKEN, RCM_APB1CLKEN_I2C3EN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->APB1CLKEN, RCM_APB1CLKEN_I2C3EN);\ + UNUSED(tmpreg); \ + } while(0U) +#define __DAL_RCM_TMR2_CLK_DISABLE() (RCM->APB1CLKEN &= ~(RCM_APB1CLKEN_TMR2EN)) +#define __DAL_RCM_TMR3_CLK_DISABLE() (RCM->APB1CLKEN &= ~(RCM_APB1CLKEN_TMR3EN)) +#define __DAL_RCM_TMR4_CLK_DISABLE() (RCM->APB1CLKEN &= ~(RCM_APB1CLKEN_TMR4EN)) +#define __DAL_RCM_SPI3_CLK_DISABLE() (RCM->APB1CLKEN &= ~(RCM_APB1CLKEN_SPI3EN)) +#define __DAL_RCM_I2C3_CLK_DISABLE() (RCM->APB1CLKEN &= ~(RCM_APB1CLKEN_I2C3EN)) +#define __DAL_RCM_TMR6_CLK_DISABLE() (RCM->APB1CLKEN &= ~(RCM_APB1CLKEN_TMR6EN)) +#define __DAL_RCM_TMR7_CLK_DISABLE() (RCM->APB1CLKEN &= ~(RCM_APB1CLKEN_TMR7EN)) +#define __DAL_RCM_TMR12_CLK_DISABLE() (RCM->APB1CLKEN &= ~(RCM_APB1CLKEN_TMR12EN)) +#define __DAL_RCM_TMR13_CLK_DISABLE() (RCM->APB1CLKEN &= ~(RCM_APB1CLKEN_TMR13EN)) +#define __DAL_RCM_TMR14_CLK_DISABLE() (RCM->APB1CLKEN &= ~(RCM_APB1CLKEN_TMR14EN)) +#define __DAL_RCM_USART3_CLK_DISABLE() (RCM->APB1CLKEN &= ~(RCM_APB1CLKEN_USART3EN)) +#define __DAL_RCM_UART4_CLK_DISABLE() (RCM->APB1CLKEN &= ~(RCM_APB1CLKEN_UART4EN)) +#define __DAL_RCM_UART5_CLK_DISABLE() (RCM->APB1CLKEN &= ~(RCM_APB1CLKEN_UART5EN)) +#define __DAL_RCM_CAN1_CLK_DISABLE() (RCM->APB1CLKEN &= ~(RCM_APB1CLKEN_CAN1EN)) +#define __DAL_RCM_CAN2_CLK_DISABLE() (RCM->APB1CLKEN &= ~(RCM_APB1CLKEN_CAN2EN)) +#define __DAL_RCM_DAC_CLK_DISABLE() (RCM->APB1CLKEN &= ~(RCM_APB1CLKEN_DACEN)) +/** + * @} + */ + +/** @defgroup RCMEx_APB1_Peripheral_Clock_Enable_Disable_Status APB1 Peripheral Clock Enable Disable Status + * @brief Get the enable or disable status of the APB1 peripheral clock. + * @note After reset, the peripheral clock (used for registers read/write access) + * is disabled and the application software has to enable this clock before + * using it. + * @{ + */ +#define __DAL_RCM_TMR2_IS_CLK_ENABLED() ((RCM->APB1CLKEN & (RCM_APB1CLKEN_TMR2EN)) != RESET) +#define __DAL_RCM_TMR3_IS_CLK_ENABLED() ((RCM->APB1CLKEN & (RCM_APB1CLKEN_TMR3EN)) != RESET) +#define __DAL_RCM_TMR4_IS_CLK_ENABLED() ((RCM->APB1CLKEN & (RCM_APB1CLKEN_TMR4EN)) != RESET) +#define __DAL_RCM_SPI3_IS_CLK_ENABLED() ((RCM->APB1CLKEN & (RCM_APB1CLKEN_SPI3EN)) != RESET) +#define __DAL_RCM_I2C3_IS_CLK_ENABLED() ((RCM->APB1CLKEN & (RCM_APB1CLKEN_I2C3EN)) != RESET) +#define __DAL_RCM_TMR6_IS_CLK_ENABLED() ((RCM->APB1CLKEN & (RCM_APB1CLKEN_TMR6EN)) != RESET) +#define __DAL_RCM_TMR7_IS_CLK_ENABLED() ((RCM->APB1CLKEN & (RCM_APB1CLKEN_TMR7EN)) != RESET) +#define __DAL_RCM_TMR12_IS_CLK_ENABLED() ((RCM->APB1CLKEN & (RCM_APB1CLKEN_TMR12EN)) != RESET) +#define __DAL_RCM_TMR13_IS_CLK_ENABLED() ((RCM->APB1CLKEN & (RCM_APB1CLKEN_TMR13EN)) != RESET) +#define __DAL_RCM_TMR14_IS_CLK_ENABLED() ((RCM->APB1CLKEN & (RCM_APB1CLKEN_TMR14EN)) != RESET) +#define __DAL_RCM_USART3_IS_CLK_ENABLED() ((RCM->APB1CLKEN & (RCM_APB1CLKEN_USART3EN)) != RESET) +#define __DAL_RCM_UART4_IS_CLK_ENABLED() ((RCM->APB1CLKEN & (RCM_APB1CLKEN_UART4EN)) != RESET) +#define __DAL_RCM_UART5_IS_CLK_ENABLED() ((RCM->APB1CLKEN & (RCM_APB1CLKEN_UART5EN)) != RESET) +#define __DAL_RCM_CAN1_IS_CLK_ENABLED() ((RCM->APB1CLKEN & (RCM_APB1CLKEN_CAN1EN)) != RESET) +#define __DAL_RCM_CAN2_IS_CLK_ENABLED() ((RCM->APB1CLKEN & (RCM_APB1CLKEN_CAN2EN)) != RESET) +#define __DAL_RCM_DAC_IS_CLK_ENABLED() ((RCM->APB1CLKEN & (RCM_APB1CLKEN_DACEN)) != RESET) + +#define __DAL_RCM_TMR2_IS_CLK_DISABLED() ((RCM->APB1CLKEN & (RCM_APB1CLKEN_TMR2EN)) == RESET) +#define __DAL_RCM_TMR3_IS_CLK_DISABLED() ((RCM->APB1CLKEN & (RCM_APB1CLKEN_TMR3EN)) == RESET) +#define __DAL_RCM_TMR4_IS_CLK_DISABLED() ((RCM->APB1CLKEN & (RCM_APB1CLKEN_TMR4EN)) == RESET) +#define __DAL_RCM_SPI3_IS_CLK_DISABLED() ((RCM->APB1CLKEN & (RCM_APB1CLKEN_SPI3EN)) == RESET) +#define __DAL_RCM_I2C3_IS_CLK_DISABLED() ((RCM->APB1CLKEN & (RCM_APB1CLKEN_I2C3EN)) == RESET) +#define __DAL_RCM_TMR6_IS_CLK_DISABLED() ((RCM->APB1CLKEN & (RCM_APB1CLKEN_TMR6EN)) == RESET) +#define __DAL_RCM_TMR7_IS_CLK_DISABLED() ((RCM->APB1CLKEN & (RCM_APB1CLKEN_TMR7EN)) == RESET) +#define __DAL_RCM_TMR12_IS_CLK_DISABLED() ((RCM->APB1CLKEN & (RCM_APB1CLKEN_TMR12EN)) == RESET) +#define __DAL_RCM_TMR13_IS_CLK_DISABLED() ((RCM->APB1CLKEN & (RCM_APB1CLKEN_TMR13EN)) == RESET) +#define __DAL_RCM_TMR14_IS_CLK_DISABLED() ((RCM->APB1CLKEN & (RCM_APB1CLKEN_TMR14EN)) == RESET) +#define __DAL_RCM_USART3_IS_CLK_DISABLED() ((RCM->APB1CLKEN & (RCM_APB1CLKEN_USART3EN)) == RESET) +#define __DAL_RCM_UART4_IS_CLK_DISABLED() ((RCM->APB1CLKEN & (RCM_APB1CLKEN_UART4EN)) == RESET) +#define __DAL_RCM_UART5_IS_CLK_DISABLED() ((RCM->APB1CLKEN & (RCM_APB1CLKEN_UART5EN)) == RESET) +#define __DAL_RCM_CAN1_IS_CLK_DISABLED() ((RCM->APB1CLKEN & (RCM_APB1CLKEN_CAN1EN)) == RESET) +#define __DAL_RCM_CAN2_IS_CLK_DISABLED() ((RCM->APB1CLKEN & (RCM_APB1CLKEN_CAN2EN)) == RESET) +#define __DAL_RCM_DAC_IS_CLK_DISABLED() ((RCM->APB1CLKEN & (RCM_APB1CLKEN_DACEN)) == RESET) + /** + * @} + */ + +/** @defgroup RCMEx_APB2_Clock_Enable_Disable APB2 Peripheral Clock Enable Disable + * @brief Enable or disable the High Speed APB (APB2) peripheral clock. + * @note After reset, the peripheral clock (used for registers read/write access) + * is disabled and the application software has to enable this clock before + * using it. + * @{ + */ +#define __DAL_RCM_TMR8_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->APB2CLKEN, RCM_APB2CLKEN_TMR8EN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->APB2CLKEN, RCM_APB2CLKEN_TMR8EN);\ + UNUSED(tmpreg); \ + } while(0U) +#define __DAL_RCM_ADC2_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->APB2CLKEN, RCM_APB2CLKEN_ADC2EN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->APB2CLKEN, RCM_APB2CLKEN_ADC2EN);\ + UNUSED(tmpreg); \ + } while(0U) +#define __DAL_RCM_ADC3_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->APB2CLKEN, RCM_APB2CLKEN_ADC3EN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->APB2CLKEN, RCM_APB2CLKEN_ADC3EN);\ + UNUSED(tmpreg); \ + } while(0U) +#define __DAL_RCM_SDIO_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->APB2CLKEN, RCM_APB2CLKEN_SDIOEN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->APB2CLKEN, RCM_APB2CLKEN_SDIOEN);\ + UNUSED(tmpreg); \ + } while(0U) +#define __DAL_RCM_TMR10_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->APB2CLKEN, RCM_APB2CLKEN_TMR10EN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->APB2CLKEN, RCM_APB2CLKEN_TMR10EN);\ + UNUSED(tmpreg); \ + } while(0U) + +#define __DAL_RCM_SDIO_CLK_DISABLE() (RCM->APB2CLKEN &= ~(RCM_APB2CLKEN_SDIOEN)) +#define __DAL_RCM_TMR10_CLK_DISABLE() (RCM->APB2CLKEN &= ~(RCM_APB2CLKEN_TMR10EN)) +#define __DAL_RCM_TMR8_CLK_DISABLE() (RCM->APB2CLKEN &= ~(RCM_APB2CLKEN_TMR8EN)) +#define __DAL_RCM_ADC2_CLK_DISABLE() (RCM->APB2CLKEN &= ~(RCM_APB2CLKEN_ADC2EN)) +#define __DAL_RCM_ADC3_CLK_DISABLE() (RCM->APB2CLKEN &= ~(RCM_APB2CLKEN_ADC3EN)) +/** + * @} + */ + +/** @defgroup RCMEx_APB2_Peripheral_Clock_Enable_Disable_Status APB2 Peripheral Clock Enable Disable Status + * @brief Get the enable or disable status of the APB2 peripheral clock. + * @note After reset, the peripheral clock (used for registers read/write access) + * is disabled and the application software has to enable this clock before + * using it. + * @{ + */ +#define __DAL_RCM_SDIO_IS_CLK_ENABLED() ((RCM->APB2CLKEN & (RCM_APB2CLKEN_SDIOEN)) != RESET) +#define __DAL_RCM_TMR10_IS_CLK_ENABLED() ((RCM->APB2CLKEN & (RCM_APB2CLKEN_TMR10EN)) != RESET) +#define __DAL_RCM_TMR8_IS_CLK_ENABLED() ((RCM->APB2CLKEN & (RCM_APB2CLKEN_TMR8EN)) != RESET) +#define __DAL_RCM_ADC2_IS_CLK_ENABLED() ((RCM->APB2CLKEN & (RCM_APB2CLKEN_ADC2EN)) != RESET) +#define __DAL_RCM_ADC3_IS_CLK_ENABLED() ((RCM->APB2CLKEN & (RCM_APB2CLKEN_ADC3EN)) != RESET) + +#define __DAL_RCM_SDIO_IS_CLK_DISABLED() ((RCM->APB2CLKEN & (RCM_APB2CLKEN_SDIOEN)) == RESET) +#define __DAL_RCM_TMR10_IS_CLK_DISABLED() ((RCM->APB2CLKEN & (RCM_APB2CLKEN_TMR10EN)) == RESET) +#define __DAL_RCM_TMR8_IS_CLK_DISABLED() ((RCM->APB2CLKEN & (RCM_APB2CLKEN_TMR8EN)) == RESET) +#define __DAL_RCM_ADC2_IS_CLK_DISABLED() ((RCM->APB2CLKEN & (RCM_APB2CLKEN_ADC2EN)) == RESET) +#define __DAL_RCM_ADC3_IS_CLK_DISABLED() ((RCM->APB2CLKEN & (RCM_APB2CLKEN_ADC3EN)) == RESET) +/** + * @} + */ + +/** @defgroup RCMEx_AHB1_Force_Release_Reset AHB1 Force Release Reset + * @brief Force or release AHB1 peripheral reset. + * @{ + */ +#define __DAL_RCM_GPIOD_FORCE_RESET() (RCM->AHB1RST |= (RCM_AHB1RST_PDRST)) +#define __DAL_RCM_GPIOE_FORCE_RESET() (RCM->AHB1RST |= (RCM_AHB1RST_PERST)) +#define __DAL_RCM_GPIOF_FORCE_RESET() (RCM->AHB1RST |= (RCM_AHB1RST_PFRST)) +#define __DAL_RCM_GPIOG_FORCE_RESET() (RCM->AHB1RST |= (RCM_AHB1RST_PGRST)) +#define __DAL_RCM_GPIOI_FORCE_RESET() (RCM->AHB1RST |= (RCM_AHB1RST_PIRST)) +#define __DAL_RCM_ETHMAC_FORCE_RESET() (RCM->AHB1RST |= (RCM_AHB1RST_ETHRST)) +#define __DAL_RCM_USB_OTG_HS_FORCE_RESET() (RCM->AHB1RST |= (RCM_AHB1RST_OTGHS1RST)) +#define __DAL_RCM_CRC_FORCE_RESET() (RCM->AHB1RST |= (RCM_AHB1RST_CRCRST)) + +#define __DAL_RCM_GPIOD_RELEASE_RESET() (RCM->AHB1RST &= ~(RCM_AHB1RST_PDRST)) +#define __DAL_RCM_GPIOE_RELEASE_RESET() (RCM->AHB1RST &= ~(RCM_AHB1RST_PERST)) +#define __DAL_RCM_GPIOF_RELEASE_RESET() (RCM->AHB1RST &= ~(RCM_AHB1RST_PFRST)) +#define __DAL_RCM_GPIOG_RELEASE_RESET() (RCM->AHB1RST &= ~(RCM_AHB1RST_PGRST)) +#define __DAL_RCM_GPIOI_RELEASE_RESET() (RCM->AHB1RST &= ~(RCM_AHB1RST_PIRST)) +#define __DAL_RCM_ETHMAC_RELEASE_RESET() (RCM->AHB1RST &= ~(RCM_AHB1RST_ETHRST)) +#define __DAL_RCM_USB_OTG_HS_RELEASE_RESET() (RCM->AHB1RST &= ~(RCM_AHB1RST_OTGHS1RST)) +#define __DAL_RCM_CRC_RELEASE_RESET() (RCM->AHB1RST &= ~(RCM_AHB1RST_CRCRST)) +/** + * @} + */ + +/** @defgroup RCMEx_AHB2_Force_Release_Reset AHB2 Force Release Reset + * @brief Force or release AHB2 peripheral reset. + * @{ + */ +#define __DAL_RCM_AHB2_FORCE_RESET() (RCM->AHB2RST = 0xFFFFFFFFU) +#define __DAL_RCM_AHB2_RELEASE_RESET() (RCM->AHB2RST = 0x00U) + +#if defined(APM32F407xx) || defined(APM32F417xx) +#define __DAL_RCM_DCI_FORCE_RESET() (RCM->AHB2RST |= (RCM_AHB2RST_DCIRST)) +#define __DAL_RCM_DCI_RELEASE_RESET() (RCM->AHB2RST &= ~(RCM_AHB2RST_DCIRST)) +#endif /* APM32F407xx || APM32F417xx */ + +#if defined(APM32F417xx) +#define __DAL_RCM_CRYP_FORCE_RESET() (RCM->AHB2RST |= (RCM_AHB2RST_CRYPRST)) +#define __DAL_RCM_HASH_FORCE_RESET() (RCM->AHB2RST |= (RCM_AHB2RST_HASHRST)) + +#define __DAL_RCM_CRYP_RELEASE_RESET() (RCM->AHB2RST &= ~(RCM_AHB2RST_CRYPRST)) +#define __DAL_RCM_HASH_RELEASE_RESET() (RCM->AHB2RST &= ~(RCM_AHB2RST_HASHRST)) +#endif /* APM32F417xx */ + +#define __DAL_RCM_USB_OTG_FS_FORCE_RESET() (RCM->AHB2RST |= (RCM_AHB2RST_OTGFSRST)) +#define __DAL_RCM_USB_OTG_FS_RELEASE_RESET() (RCM->AHB2RST &= ~(RCM_AHB2RST_OTGFSRST)) + +#define __DAL_RCM_RNG_FORCE_RESET() (RCM->AHB2RST |= (RCM_AHB2RST_RNGRST)) +#define __DAL_RCM_RNG_RELEASE_RESET() (RCM->AHB2RST &= ~(RCM_AHB2RST_RNGRST)) +/** + * @} + */ + +/** @defgroup RCMEx_AHB3_Force_Release_Reset AHB3 Force Release Reset + * @brief Force or release AHB3 peripheral reset. + * @{ + */ +#define __DAL_RCM_AHB3_FORCE_RESET() (RCM->AHB3RST = 0xFFFFFFFFU) +#define __DAL_RCM_AHB3_RELEASE_RESET() (RCM->AHB3RST = 0x00U) + +#if defined(APM32F405xx) || defined(APM32F407xx) || defined(APM32F417xx) || defined(APM32F465xx) +#define __DAL_RCM_EMMC_FORCE_RESET() (RCM->AHB3RST |= (RCM_AHB3RST_EMMCRST)) +#define __DAL_RCM_EMMC_RELEASE_RESET() (RCM->AHB3RST &= ~(RCM_AHB3RST_EMMCRST)) +#endif /* APM32F405xx || APM32F407xx || APM32F417xx || APM32F465xx */ + +/** + * @} + */ + +/** @defgroup RCMEx_APB1_Force_Release_Reset APB1 Force Release Reset + * @brief Force or release APB1 peripheral reset. + * @{ + */ +#define __DAL_RCM_TMR6_FORCE_RESET() (RCM->APB1RST |= (RCM_APB1RST_TMR6RST)) +#define __DAL_RCM_TMR7_FORCE_RESET() (RCM->APB1RST |= (RCM_APB1RST_TMR7RST)) +#define __DAL_RCM_TMR12_FORCE_RESET() (RCM->APB1RST |= (RCM_APB1RST_TMR12RST)) +#define __DAL_RCM_TMR13_FORCE_RESET() (RCM->APB1RST |= (RCM_APB1RST_TMR13RST)) +#define __DAL_RCM_TMR14_FORCE_RESET() (RCM->APB1RST |= (RCM_APB1RST_TMR14RST)) +#define __DAL_RCM_USART3_FORCE_RESET() (RCM->APB1RST |= (RCM_APB1RST_USART3RST)) +#define __DAL_RCM_UART4_FORCE_RESET() (RCM->APB1RST |= (RCM_APB1RST_UART4RST)) +#define __DAL_RCM_UART5_FORCE_RESET() (RCM->APB1RST |= (RCM_APB1RST_UART5RST)) +#define __DAL_RCM_CAN1_FORCE_RESET() (RCM->APB1RST |= (RCM_APB1RST_CAN1RST)) +#define __DAL_RCM_CAN2_FORCE_RESET() (RCM->APB1RST |= (RCM_APB1RST_CAN2RST)) +#define __DAL_RCM_DAC_FORCE_RESET() (RCM->APB1RST |= (RCM_APB1RST_DACRST)) +#define __DAL_RCM_TMR2_FORCE_RESET() (RCM->APB1RST |= (RCM_APB1RST_TMR2RST)) +#define __DAL_RCM_TMR3_FORCE_RESET() (RCM->APB1RST |= (RCM_APB1RST_TMR3RST)) +#define __DAL_RCM_TMR4_FORCE_RESET() (RCM->APB1RST |= (RCM_APB1RST_TMR4RST)) +#define __DAL_RCM_SPI3_FORCE_RESET() (RCM->APB1RST |= (RCM_APB1RST_SPI3RST)) +#define __DAL_RCM_I2C3_FORCE_RESET() (RCM->APB1RST |= (RCM_APB1RST_I2C3RST)) + +#define __DAL_RCM_TMR2_RELEASE_RESET() (RCM->APB1RST &= ~(RCM_APB1RST_TMR2RST)) +#define __DAL_RCM_TMR3_RELEASE_RESET() (RCM->APB1RST &= ~(RCM_APB1RST_TMR3RST)) +#define __DAL_RCM_TMR4_RELEASE_RESET() (RCM->APB1RST &= ~(RCM_APB1RST_TMR4RST)) +#define __DAL_RCM_SPI3_RELEASE_RESET() (RCM->APB1RST &= ~(RCM_APB1RST_SPI3RST)) +#define __DAL_RCM_I2C3_RELEASE_RESET() (RCM->APB1RST &= ~(RCM_APB1RST_I2C3RST)) +#define __DAL_RCM_TMR6_RELEASE_RESET() (RCM->APB1RST &= ~(RCM_APB1RST_TMR6RST)) +#define __DAL_RCM_TMR7_RELEASE_RESET() (RCM->APB1RST &= ~(RCM_APB1RST_TMR7RST)) +#define __DAL_RCM_TMR12_RELEASE_RESET() (RCM->APB1RST &= ~(RCM_APB1RST_TMR12RST)) +#define __DAL_RCM_TMR13_RELEASE_RESET() (RCM->APB1RST &= ~(RCM_APB1RST_TMR13RST)) +#define __DAL_RCM_TMR14_RELEASE_RESET() (RCM->APB1RST &= ~(RCM_APB1RST_TMR14RST)) +#define __DAL_RCM_USART3_RELEASE_RESET() (RCM->APB1RST &= ~(RCM_APB1RST_USART3RST)) +#define __DAL_RCM_UART4_RELEASE_RESET() (RCM->APB1RST &= ~(RCM_APB1RST_UART4RST)) +#define __DAL_RCM_UART5_RELEASE_RESET() (RCM->APB1RST &= ~(RCM_APB1RST_UART5RST)) +#define __DAL_RCM_CAN1_RELEASE_RESET() (RCM->APB1RST &= ~(RCM_APB1RST_CAN1RST)) +#define __DAL_RCM_CAN2_RELEASE_RESET() (RCM->APB1RST &= ~(RCM_APB1RST_CAN2RST)) +#define __DAL_RCM_DAC_RELEASE_RESET() (RCM->APB1RST &= ~(RCM_APB1RST_DACRST)) +/** + * @} + */ + +/** @defgroup RCMEx_APB2_Force_Release_Reset APB2 Force Release Reset + * @brief Force or release APB2 peripheral reset. + * @{ + */ +#define __DAL_RCM_TMR8_FORCE_RESET() (RCM->APB2RST |= (RCM_APB2RST_TMR8RST)) +#define __DAL_RCM_SDIO_FORCE_RESET() (RCM->APB2RST |= (RCM_APB2RST_SDIORST)) +#define __DAL_RCM_TMR10_FORCE_RESET() (RCM->APB2RST |= (RCM_APB2RST_TMR10RST)) + +#define __DAL_RCM_SDIO_RELEASE_RESET() (RCM->APB2RST &= ~(RCM_APB2RST_SDIORST)) +#define __DAL_RCM_TMR10_RELEASE_RESET()(RCM->APB2RST &= ~(RCM_APB2RST_TMR10RST)) +#define __DAL_RCM_TMR8_RELEASE_RESET() (RCM->APB2RST &= ~(RCM_APB2RST_TMR8RST)) +/** + * @} + */ + +/** @defgroup RCMEx_AHB1_LowPower_Enable_Disable AHB1 Peripheral Low Power Enable Disable + * @brief Enable or disable the AHB1 peripheral clock during Low Power (Sleep) mode. + * @note Peripheral clock gating in SLEEP mode can be used to further reduce + * power consumption. + * @note After wakeup from SLEEP mode, the peripheral clock is enabled again. + * @note By default, all peripheral clocks are enabled during SLEEP mode. + * @{ + */ +#define __DAL_RCM_GPIOD_CLK_SLEEP_ENABLE() (RCM->LPAHB1CLKEN |= (RCM_LPAHB1CLKEN_PDLPEN)) +#define __DAL_RCM_GPIOE_CLK_SLEEP_ENABLE() (RCM->LPAHB1CLKEN |= (RCM_LPAHB1CLKEN_PELPEN)) +#define __DAL_RCM_GPIOF_CLK_SLEEP_ENABLE() (RCM->LPAHB1CLKEN |= (RCM_LPAHB1CLKEN_PFLPEN)) +#define __DAL_RCM_GPIOG_CLK_SLEEP_ENABLE() (RCM->LPAHB1CLKEN |= (RCM_LPAHB1CLKEN_PGLPEN)) +#define __DAL_RCM_GPIOI_CLK_SLEEP_ENABLE() (RCM->LPAHB1CLKEN |= (RCM_LPAHB1CLKEN_PILPEN)) +#define __DAL_RCM_SRAM2_CLK_SLEEP_ENABLE() (RCM->LPAHB1CLKEN |= (RCM_LPAHB1CLKEN_SRAM2EN)) + +#if defined(APM32F407xx) || defined(APM32F417xx) +#define __DAL_RCM_ETHMAC_CLK_SLEEP_ENABLE() (RCM->LPAHB1CLKEN |= (RCM_LPAHB1CLKEN_ETHEN)) +#define __DAL_RCM_ETHMACTX_CLK_SLEEP_ENABLE() (RCM->LPAHB1CLKEN |= (RCM_LPAHB1CLKEN_ETHTXEN)) +#define __DAL_RCM_ETHMACRX_CLK_SLEEP_ENABLE() (RCM->LPAHB1CLKEN |= (RCM_LPAHB1CLKEN_ETHRXEN)) +#define __DAL_RCM_ETHMACPTP_CLK_SLEEP_ENABLE() (RCM->LPAHB1CLKEN |= (RCM_LPAHB1CLKEN_ETHPTPEN)) +#endif /* APM32F407xx || APM32F417xx */ + +#define __DAL_RCM_USB_OTG_HS_CLK_SLEEP_ENABLE() (RCM->LPAHB1CLKEN |= (RCM_LPAHB1CLKEN_OTGHS1EN)) +#define __DAL_RCM_USB_OTG_HS_ULPI_CLK_SLEEP_ENABLE() (RCM->LPAHB1CLKEN |= (RCM_LPAHB1CLKEN_OTGHSULPIEN)) +#define __DAL_RCM_CRC_CLK_SLEEP_ENABLE() (RCM->LPAHB1CLKEN |= (RCM_LPAHB1CLKEN_CRCLPEN)) +#define __DAL_RCM_FLITF_CLK_SLEEP_ENABLE() (RCM->LPAHB1CLKEN |= (RCM_LPAHB1CLKEN_FMCEN)) +#define __DAL_RCM_SRAM1_CLK_SLEEP_ENABLE() (RCM->LPAHB1CLKEN |= (RCM_LPAHB1CLKEN_SRAM1EN)) +#define __DAL_RCM_BKPSRAM_CLK_SLEEP_ENABLE() (RCM->LPAHB1CLKEN |= (RCM_LPAHB1CLKEN_BKPSRAMEN)) + +#define __DAL_RCM_GPIOD_CLK_SLEEP_DISABLE() (RCM->LPAHB1CLKEN &= ~(RCM_LPAHB1CLKEN_PDLPEN)) +#define __DAL_RCM_GPIOE_CLK_SLEEP_DISABLE() (RCM->LPAHB1CLKEN &= ~(RCM_LPAHB1CLKEN_PELPEN)) +#define __DAL_RCM_GPIOF_CLK_SLEEP_DISABLE() (RCM->LPAHB1CLKEN &= ~(RCM_LPAHB1CLKEN_PFLPEN)) +#define __DAL_RCM_GPIOG_CLK_SLEEP_DISABLE() (RCM->LPAHB1CLKEN &= ~(RCM_LPAHB1CLKEN_PGLPEN)) +#define __DAL_RCM_GPIOI_CLK_SLEEP_DISABLE() (RCM->LPAHB1CLKEN &= ~(RCM_LPAHB1CLKEN_PILPEN)) +#define __DAL_RCM_SRAM2_CLK_SLEEP_DISABLE() (RCM->LPAHB1CLKEN &= ~(RCM_LPAHB1CLKEN_SRAM2EN)) + +#if defined(APM32F407xx) || defined(APM32F417xx) +#define __DAL_RCM_ETHMAC_CLK_SLEEP_DISABLE() (RCM->LPAHB1CLKEN &= ~(RCM_LPAHB1CLKEN_ETHEN)) +#define __DAL_RCM_ETHMACTX_CLK_SLEEP_DISABLE() (RCM->LPAHB1CLKEN &= ~(RCM_LPAHB1CLKEN_ETHTXEN)) +#define __DAL_RCM_ETHMACRX_CLK_SLEEP_DISABLE() (RCM->LPAHB1CLKEN &= ~(RCM_LPAHB1CLKEN_ETHRXEN)) +#define __DAL_RCM_ETHMACPTP_CLK_SLEEP_DISABLE() (RCM->LPAHB1CLKEN &= ~(RCM_LPAHB1CLKEN_ETHPTPEN)) +#endif /* APM32F407xx || APM32F417xx */ + +#define __DAL_RCM_USB_OTG_HS_CLK_SLEEP_DISABLE() (RCM->LPAHB1CLKEN &= ~(RCM_LPAHB1CLKEN_OTGHS1EN)) +#define __DAL_RCM_USB_OTG_HS_ULPI_CLK_SLEEP_DISABLE() (RCM->LPAHB1CLKEN &= ~(RCM_LPAHB1CLKEN_OTGHSULPIEN)) +#define __DAL_RCM_CRC_CLK_SLEEP_DISABLE() (RCM->LPAHB1CLKEN &= ~(RCM_LPAHB1CLKEN_CRCLPEN)) +#define __DAL_RCM_FLITF_CLK_SLEEP_DISABLE() (RCM->LPAHB1CLKEN &= ~(RCM_LPAHB1CLKEN_FMCEN)) +#define __DAL_RCM_SRAM1_CLK_SLEEP_DISABLE() (RCM->LPAHB1CLKEN &= ~(RCM_LPAHB1CLKEN_SRAM1EN)) +#define __DAL_RCM_BKPSRAM_CLK_SLEEP_DISABLE() (RCM->LPAHB1CLKEN &= ~(RCM_LPAHB1CLKEN_BKPSRAMEN)) +/** + * @} + */ + +/** @defgroup RCMEx_AHB2_LowPower_Enable_Disable AHB2 Peripheral Low Power Enable Disable + * @brief Enable or disable the AHB2 peripheral clock during Low Power (Sleep) mode. + * @note Peripheral clock gating in SLEEP mode can be used to further reduce + * power consumption. + * @note After wake-up from SLEEP mode, the peripheral clock is enabled again. + * @note By default, all peripheral clocks are enabled during SLEEP mode. + * @{ + */ +#define __DAL_RCM_USB_OTG_FS_CLK_SLEEP_ENABLE() (RCM->LPAHB2CLKEN |= (RCM_LPAHB2CLKEN_OTGFSEN)) +#define __DAL_RCM_USB_OTG_FS_CLK_SLEEP_DISABLE() (RCM->LPAHB2CLKEN &= ~(RCM_LPAHB2CLKEN_OTGFSEN)) + +#define __DAL_RCM_RNG_CLK_SLEEP_ENABLE() (RCM->LPAHB2CLKEN |= (RCM_LPAHB2CLKEN_RNGEN)) +#define __DAL_RCM_RNG_CLK_SLEEP_DISABLE() (RCM->LPAHB2CLKEN &= ~(RCM_LPAHB2CLKEN_RNGEN)) + +#if defined(APM32F407xx) || defined(APM32F417xx) +#define __DAL_RCM_DCI_CLK_SLEEP_ENABLE() (RCM->LPAHB2CLKEN |= (RCM_LPAHB2CLKEN_DCIEN)) +#define __DAL_RCM_DCI_CLK_SLEEP_DISABLE() (RCM->LPAHB2CLKEN &= ~(RCM_LPAHB2CLKEN_DCIEN)) +#endif /* APM32F407xx || APM32F417xx */ + +#if defined(APM32F417xx) +#define __DAL_RCM_CRYP_CLK_SLEEP_ENABLE() (RCM->LPAHB2CLKEN |= (RCM_LPAHB2CLKEN_CRYPEN)) +#define __DAL_RCM_HASH_CLK_SLEEP_ENABLE() (RCM->LPAHB2CLKEN |= (RCM_LPAHB2CLKEN_HASHEN)) + +#define __DAL_RCM_CRYP_CLK_SLEEP_DISABLE() (RCM->LPAHB2CLKEN &= ~(RCM_LPAHB2CLKEN_CRYPEN)) +#define __DAL_RCM_HASH_CLK_SLEEP_DISABLE() (RCM->LPAHB2CLKEN &= ~(RCM_LPAHB2CLKEN_HASHEN)) +#endif /* APM32F417xx */ +/** + * @} + */ + +/** @defgroup RCMEx_AHB3_LowPower_Enable_Disable AHB3 Peripheral Low Power Enable Disable + * @brief Enable or disable the AHB3 peripheral clock during Low Power (Sleep) mode. + * @note Peripheral clock gating in SLEEP mode can be used to further reduce + * power consumption. + * @note After wakeup from SLEEP mode, the peripheral clock is enabled again. + * @note By default, all peripheral clocks are enabled during SLEEP mode. + * @{ + */ +#if defined(APM32F405xx) || defined(APM32F407xx) || defined(APM32F417xx) || defined(APM32F465xx) +#define __DAL_RCM_EMMC_CLK_SLEEP_ENABLE() (RCM->LPAHB3CLKEN |= (RCM_LPAHB3CLKEN_EMMCEN)) +#define __DAL_RCM_EMMC_CLK_SLEEP_DISABLE() (RCM->LPAHB3CLKEN &= ~(RCM_LPAHB3CLKEN_EMMCEN)) +#endif /* APM32F405xx || APM32F407xx || APM32F417xx || APM32F465xx */ +/** + * @} + */ + +/** @defgroup RCMEx_APB1_LowPower_Enable_Disable APB1 Peripheral Low Power Enable Disable + * @brief Enable or disable the APB1 peripheral clock during Low Power (Sleep) mode. + * @note Peripheral clock gating in SLEEP mode can be used to further reduce + * power consumption. + * @note After wakeup from SLEEP mode, the peripheral clock is enabled again. + * @note By default, all peripheral clocks are enabled during SLEEP mode. + * @{ + */ +#define __DAL_RCM_TMR6_CLK_SLEEP_ENABLE() (RCM->LPAPB1CLKEN |= (RCM_LPAPB1CLKEN_TMR6EN)) +#define __DAL_RCM_TMR7_CLK_SLEEP_ENABLE() (RCM->LPAPB1CLKEN |= (RCM_LPAPB1CLKEN_TMR7EN)) +#define __DAL_RCM_TMR12_CLK_SLEEP_ENABLE() (RCM->LPAPB1CLKEN |= (RCM_LPAPB1CLKEN_TMR12EN)) +#define __DAL_RCM_TMR13_CLK_SLEEP_ENABLE() (RCM->LPAPB1CLKEN |= (RCM_LPAPB1CLKEN_TMR13EN)) +#define __DAL_RCM_TMR14_CLK_SLEEP_ENABLE() (RCM->LPAPB1CLKEN |= (RCM_LPAPB1CLKEN_TMR14EN)) +#define __DAL_RCM_USART3_CLK_SLEEP_ENABLE() (RCM->LPAPB1CLKEN |= (RCM_LPAPB1CLKEN_USART3EN)) +#define __DAL_RCM_UART4_CLK_SLEEP_ENABLE() (RCM->LPAPB1CLKEN |= (RCM_LPAPB1CLKEN_UART4EN)) +#define __DAL_RCM_UART5_CLK_SLEEP_ENABLE() (RCM->LPAPB1CLKEN |= (RCM_LPAPB1CLKEN_UART5EN)) +#define __DAL_RCM_CAN1_CLK_SLEEP_ENABLE() (RCM->LPAPB1CLKEN |= (RCM_LPAPB1CLKEN_CAN1EN)) +#define __DAL_RCM_CAN2_CLK_SLEEP_ENABLE() (RCM->LPAPB1CLKEN |= (RCM_LPAPB1CLKEN_CAN2EN)) +#define __DAL_RCM_DAC_CLK_SLEEP_ENABLE() (RCM->LPAPB1CLKEN |= (RCM_LPAPB1CLKEN_DACEN)) +#define __DAL_RCM_TMR2_CLK_SLEEP_ENABLE() (RCM->LPAPB1CLKEN |= (RCM_LPAPB1CLKEN_TMR2EN)) +#define __DAL_RCM_TMR3_CLK_SLEEP_ENABLE() (RCM->LPAPB1CLKEN |= (RCM_LPAPB1CLKEN_TMR3EN)) +#define __DAL_RCM_TMR4_CLK_SLEEP_ENABLE() (RCM->LPAPB1CLKEN |= (RCM_LPAPB1CLKEN_TMR4EN)) +#define __DAL_RCM_SPI3_CLK_SLEEP_ENABLE() (RCM->LPAPB1CLKEN |= (RCM_LPAPB1CLKEN_SPI3EN)) +#define __DAL_RCM_I2C3_CLK_SLEEP_ENABLE() (RCM->LPAPB1CLKEN |= (RCM_LPAPB1CLKEN_I2C3EN)) + +#define __DAL_RCM_TMR2_CLK_SLEEP_DISABLE() (RCM->LPAPB1CLKEN &= ~(RCM_LPAPB1CLKEN_TMR2EN)) +#define __DAL_RCM_TMR3_CLK_SLEEP_DISABLE() (RCM->LPAPB1CLKEN &= ~(RCM_LPAPB1CLKEN_TMR3EN)) +#define __DAL_RCM_TMR4_CLK_SLEEP_DISABLE() (RCM->LPAPB1CLKEN &= ~(RCM_LPAPB1CLKEN_TMR4EN)) +#define __DAL_RCM_SPI3_CLK_SLEEP_DISABLE() (RCM->LPAPB1CLKEN &= ~(RCM_LPAPB1CLKEN_SPI3EN)) +#define __DAL_RCM_I2C3_CLK_SLEEP_DISABLE() (RCM->LPAPB1CLKEN &= ~(RCM_LPAPB1CLKEN_I2C3EN)) +#define __DAL_RCM_TMR6_CLK_SLEEP_DISABLE() (RCM->LPAPB1CLKEN &= ~(RCM_LPAPB1CLKEN_TMR6EN)) +#define __DAL_RCM_TMR7_CLK_SLEEP_DISABLE() (RCM->LPAPB1CLKEN &= ~(RCM_LPAPB1CLKEN_TMR7EN)) +#define __DAL_RCM_TMR12_CLK_SLEEP_DISABLE() (RCM->LPAPB1CLKEN &= ~(RCM_LPAPB1CLKEN_TMR12EN)) +#define __DAL_RCM_TMR13_CLK_SLEEP_DISABLE() (RCM->LPAPB1CLKEN &= ~(RCM_LPAPB1CLKEN_TMR13EN)) +#define __DAL_RCM_TMR14_CLK_SLEEP_DISABLE() (RCM->LPAPB1CLKEN &= ~(RCM_LPAPB1CLKEN_TMR14EN)) +#define __DAL_RCM_USART3_CLK_SLEEP_DISABLE() (RCM->LPAPB1CLKEN &= ~(RCM_LPAPB1CLKEN_USART3EN)) +#define __DAL_RCM_UART4_CLK_SLEEP_DISABLE() (RCM->LPAPB1CLKEN &= ~(RCM_LPAPB1CLKEN_UART4EN)) +#define __DAL_RCM_UART5_CLK_SLEEP_DISABLE() (RCM->LPAPB1CLKEN &= ~(RCM_LPAPB1CLKEN_UART5EN)) +#define __DAL_RCM_CAN1_CLK_SLEEP_DISABLE() (RCM->LPAPB1CLKEN &= ~(RCM_LPAPB1CLKEN_CAN1EN)) +#define __DAL_RCM_CAN2_CLK_SLEEP_DISABLE() (RCM->LPAPB1CLKEN &= ~(RCM_LPAPB1CLKEN_CAN2EN)) +#define __DAL_RCM_DAC_CLK_SLEEP_DISABLE() (RCM->LPAPB1CLKEN &= ~(RCM_LPAPB1CLKEN_DACEN)) +/** + * @} + */ + +/** @defgroup RCMEx_APB2_LowPower_Enable_Disable APB2 Peripheral Low Power Enable Disable + * @brief Enable or disable the APB2 peripheral clock during Low Power (Sleep) mode. + * @note Peripheral clock gating in SLEEP mode can be used to further reduce + * power consumption. + * @note After wakeup from SLEEP mode, the peripheral clock is enabled again. + * @note By default, all peripheral clocks are enabled during SLEEP mode. + * @{ + */ +#define __DAL_RCM_TMR8_CLK_SLEEP_ENABLE() (RCM->LPAPB2CLKEN |= (RCM_LPAPB2CLKEN_TMR8EN)) +#define __DAL_RCM_ADC2_CLK_SLEEP_ENABLE() (RCM->LPAPB2CLKEN |= (RCM_LPAPB2CLKEN_ADC2EN)) +#define __DAL_RCM_ADC3_CLK_SLEEP_ENABLE() (RCM->LPAPB2CLKEN |= (RCM_LPAPB2CLKEN_ADC3EN)) +#define __DAL_RCM_SDIO_CLK_SLEEP_ENABLE() (RCM->LPAPB2CLKEN |= (RCM_LPAPB2CLKEN_SDIOEN)) +#define __DAL_RCM_TMR10_CLK_SLEEP_ENABLE()(RCM->LPAPB2CLKEN |= (RCM_LPAPB2CLKEN_TMR10EN)) + +#define __DAL_RCM_SDIO_CLK_SLEEP_DISABLE() (RCM->LPAPB2CLKEN &= ~(RCM_LPAPB2CLKEN_SDIOEN)) +#define __DAL_RCM_TMR10_CLK_SLEEP_DISABLE()(RCM->LPAPB2CLKEN &= ~(RCM_LPAPB2CLKEN_TMR10EN)) +#define __DAL_RCM_TMR8_CLK_SLEEP_DISABLE() (RCM->LPAPB2CLKEN &= ~(RCM_LPAPB2CLKEN_TMR8EN)) +#define __DAL_RCM_ADC2_CLK_SLEEP_DISABLE() (RCM->LPAPB2CLKEN &= ~(RCM_LPAPB2CLKEN_ADC2EN)) +#define __DAL_RCM_ADC3_CLK_SLEEP_DISABLE() (RCM->LPAPB2CLKEN &= ~(RCM_LPAPB2CLKEN_ADC3EN)) +/** + * @} + */ +#endif /* APM32F405xx || APM32F407xx || APM32F417xx || APM32F465xx */ +/*----------------------------------------------------------------------------*/ + +/*-------------------------------- APM32F411xx -------------------------------*/ +#if defined(APM32F411xx) +/** @defgroup RCMEx_AHB1_Clock_Enable_Disable AHB1 Peripheral Clock Enable Disable + * @brief Enables or disables the AHB1 peripheral clock. + * @note After reset, the peripheral clock (used for registers read/write access) + * is disabled and the application software has to enable this clock before + * using it. + * @{ + */ +#define __DAL_RCM_GPIOD_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->AHB1CLKEN, RCM_AHB1CLKEN_PDEN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->AHB1CLKEN, RCM_AHB1CLKEN_PDEN);\ + UNUSED(tmpreg); \ + } while(0U) +#define __DAL_RCM_GPIOE_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->AHB1CLKEN, RCM_AHB1CLKEN_PEEN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->AHB1CLKEN, RCM_AHB1CLKEN_PEEN);\ + UNUSED(tmpreg); \ + } while(0U) +#define __DAL_RCM_CRC_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->AHB1CLKEN, RCM_AHB1CLKEN_CRCEN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->AHB1CLKEN, RCM_AHB1CLKEN_CRCEN);\ + UNUSED(tmpreg); \ + } while(0U) +#define __DAL_RCM_GPIOD_CLK_DISABLE() (RCM->AHB1CLKEN &= ~(RCM_AHB1CLKEN_PDEN)) +#define __DAL_RCM_GPIOE_CLK_DISABLE() (RCM->AHB1CLKEN &= ~(RCM_AHB1CLKEN_PEEN)) +#define __DAL_RCM_CRC_CLK_DISABLE() (RCM->AHB1CLKEN &= ~(RCM_AHB1CLKEN_CRCEN)) +/** + * @} + */ + +/** @defgroup RCMEx_AHB1_Peripheral_Clock_Enable_Disable_Status AHB1 Peripheral Clock Enable Disable Status + * @brief Get the enable or disable status of the AHB1 peripheral clock. + * @note After reset, the peripheral clock (used for registers read/write access) + * is disabled and the application software has to enable this clock before + * using it. + * @{ + */ +#define __DAL_RCM_GPIOD_IS_CLK_ENABLED() ((RCM->AHB1CLKEN & (RCM_AHB1CLKEN_PDEN)) != RESET) +#define __DAL_RCM_GPIOE_IS_CLK_ENABLED() ((RCM->AHB1CLKEN & (RCM_AHB1CLKEN_PEEN)) != RESET) +#define __DAL_RCM_CRC_IS_CLK_ENABLED() ((RCM->AHB1CLKEN & (RCM_AHB1CLKEN_CRCEN)) != RESET) + +#define __DAL_RCM_GPIOD_IS_CLK_DISABLED() ((RCM->AHB1CLKEN & (RCM_AHB1CLKEN_PDEN)) == RESET) +#define __DAL_RCM_GPIOE_IS_CLK_DISABLED() ((RCM->AHB1CLKEN & (RCM_AHB1CLKEN_PEEN)) == RESET) +#define __DAL_RCM_CRC_IS_CLK_DISABLED() ((RCM->AHB1CLKEN & (RCM_AHB1CLKEN_CRCEN)) == RESET) +/** + * @} + */ + +/** @defgroup RCMEX_AHB2_Clock_Enable_Disable AHB2 Peripheral Clock Enable Disable + * @brief Enable or disable the AHB2 peripheral clock. + * @note After reset, the peripheral clock (used for registers read/write access) + * is disabled and the application software has to enable this clock before + * using it. + * @{ + */ +#define __DAL_RCM_USB_OTG_FS_CLK_ENABLE() do {(RCM->AHB2CLKEN |= (RCM_AHB2CLKEN_OTGFSEN));\ + __DAL_RCM_SYSCFG_CLK_ENABLE();\ + }while(0U) + +#define __DAL_RCM_USB_OTG_FS_CLK_DISABLE() (RCM->AHB2CLKEN &= ~(RCM_AHB2CLKEN_OTGFSEN)) + +#define __DAL_RCM_RNG_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->AHB2CLKEN, RCM_AHB2CLKEN_RNGEN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->AHB2CLKEN, RCM_AHB2CLKEN_RNGEN);\ + UNUSED(tmpreg); \ + } while(0U) +#define __DAL_RCM_RNG_CLK_DISABLE() (RCM->AHB2CLKEN &= ~(RCM_AHB2CLKEN_RNGEN)) + +#define __DAL_RCM_SMC_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->AHB2CLKEN, RCM_AHB2CLKEN_SMCEN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->AHB2CLKEN, RCM_AHB2CLKEN_SMCEN);\ + UNUSED(tmpreg); \ + } while(0U) +#define __DAL_RCM_SMC_CLK_DISABLE() (RCM->AHB2CLKEN &= ~(RCM_AHB2CLKEN_SMCEN)) + +#define __DAL_RCM_QSPI_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->AHB2CLKEN, RCM_AHB2CLKEN_QSPIEN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->AHB2CLKEN, RCM_AHB2CLKEN_QSPIEN);\ + UNUSED(tmpreg); \ + } while(0U) +#define __DAL_RCM_QSPI_CLK_DISABLE() (RCM->AHB2CLKEN &= ~(RCM_AHB2CLKEN_QSPIEN)) +/** + * @} + */ + +/** @defgroup RCMEx_AHB2_Peripheral_Clock_Enable_Disable_Status AHB2 Peripheral Clock Enable Disable Status + * @brief Get the enable or disable status of the AHB2 peripheral clock. + * @note After reset, the peripheral clock (used for registers read/write access) + * is disabled and the application software has to enable this clock before + * using it. + * @{ + */ +#define __DAL_RCM_USB_OTG_FS_IS_CLK_ENABLED() ((RCM->AHB2CLKEN & (RCM_AHB2CLKEN_OTGFSEN)) != RESET) +#define __DAL_RCM_USB_OTG_FS_IS_CLK_DISABLED() ((RCM->AHB2CLKEN & (RCM_AHB2CLKEN_OTGFSEN)) == RESET) + +#define __DAL_RCM_RNG_IS_CLK_ENABLED() ((RCM->AHB2CLKEN & (RCM_AHB2CLKEN_RNGEN)) != RESET) +#define __DAL_RCM_RNG_IS_CLK_DISABLED() ((RCM->AHB2CLKEN & (RCM_AHB2CLKEN_RNGEN)) == RESET) + +#define __DAL_RCM_SMC_IS_CLK_ENABLED() ((RCM->AHB2CLKEN & (RCM_AHB2CLKEN_SMCEN)) != RESET) +#define __DAL_RCM_SMC_IS_CLK_DISABLED() ((RCM->AHB2CLKEN & (RCM_AHB2CLKEN_SMCEN)) == RESET) + +#define __DAL_RCM_QSPI_IS_CLK_ENABLED() ((RCM->AHB2CLKEN & (RCM_AHB2CLKEN_QSPIEN)) != RESET) +#define __DAL_RCM_QSPI_IS_CLK_DISABLED() ((RCM->AHB2CLKEN & (RCM_AHB2CLKEN_QSPIEN)) == RESET) +/** + * @} + */ + +/** @defgroup RCMEx_APB1_Clock_Enable_Disable APB1 Peripheral Clock Enable Disable + * @brief Enable or disable the Low Speed APB (APB1) peripheral clock. + * @note After reset, the peripheral clock (used for registers read/write access) + * is disabled and the application software has to enable this clock before + * using it. + * @{ + */ +#define __DAL_RCM_TMR12_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->APB1CLKEN, RCM_APB1CLKEN_TMR12EN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->APB1CLKEN, RCM_APB1CLKEN_TMR12EN);\ + UNUSED(tmpreg); \ + } while(0U) +#define __DAL_RCM_TMR13_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->APB1CLKEN, RCM_APB1CLKEN_TMR13EN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->APB1CLKEN, RCM_APB1CLKEN_TMR13EN);\ + UNUSED(tmpreg); \ + } while(0U) +#define __DAL_RCM_TMR14_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->APB1CLKEN, RCM_APB1CLKEN_TMR14EN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->APB1CLKEN, RCM_APB1CLKEN_TMR14EN);\ + UNUSED(tmpreg); \ + } while(0U) +#define __DAL_RCM_USART3_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->APB1CLKEN, RCM_APB1CLKEN_USART3EN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->APB1CLKEN, RCM_APB1CLKEN_USART3EN);\ + UNUSED(tmpreg); \ + } while(0U) +#define __DAL_RCM_UART4_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->APB1CLKEN, RCM_APB1CLKEN_UART4EN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->APB1CLKEN, RCM_APB1CLKEN_UART4EN);\ + UNUSED(tmpreg); \ + } while(0U) +#define __DAL_RCM_UART5_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->APB1CLKEN, RCM_APB1CLKEN_UART5EN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->APB1CLKEN, RCM_APB1CLKEN_UART5EN);\ + UNUSED(tmpreg); \ + } while(0U) +#define __DAL_RCM_CAN1_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->APB1CLKEN, RCM_APB1CLKEN_CAN1EN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->APB1CLKEN, RCM_APB1CLKEN_CAN1EN);\ + UNUSED(tmpreg); \ + } while(0U) +#define __DAL_RCM_CAN2_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->APB1CLKEN, RCM_APB1CLKEN_CAN2EN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->APB1CLKEN, RCM_APB1CLKEN_CAN2EN);\ + UNUSED(tmpreg); \ + } while(0U) +#define __DAL_RCM_TMR2_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->APB1CLKEN, RCM_APB1CLKEN_TMR2EN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->APB1CLKEN, RCM_APB1CLKEN_TMR2EN);\ + UNUSED(tmpreg); \ + } while(0U) +#define __DAL_RCM_TMR3_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->APB1CLKEN, RCM_APB1CLKEN_TMR3EN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->APB1CLKEN, RCM_APB1CLKEN_TMR3EN);\ + UNUSED(tmpreg); \ + } while(0U) +#define __DAL_RCM_TMR4_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->APB1CLKEN, RCM_APB1CLKEN_TMR4EN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->APB1CLKEN, RCM_APB1CLKEN_TMR4EN);\ + UNUSED(tmpreg); \ + } while(0U) +#define __DAL_RCM_SPI3_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->APB1CLKEN, RCM_APB1CLKEN_SPI3EN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->APB1CLKEN, RCM_APB1CLKEN_SPI3EN);\ + UNUSED(tmpreg); \ + } while(0U) +#define __DAL_RCM_I2C3_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->APB1CLKEN, RCM_APB1CLKEN_I2C3EN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->APB1CLKEN, RCM_APB1CLKEN_I2C3EN);\ + UNUSED(tmpreg); \ + } while(0U) + +#define __DAL_RCM_TMR12_CLK_DISABLE() (RCM->APB1CLKEN &= ~(RCM_APB1CLKEN_TMR12EN)) +#define __DAL_RCM_TMR13_CLK_DISABLE() (RCM->APB1CLKEN &= ~(RCM_APB1CLKEN_TMR13EN)) +#define __DAL_RCM_TMR14_CLK_DISABLE() (RCM->APB1CLKEN &= ~(RCM_APB1CLKEN_TMR14EN)) +#define __DAL_RCM_USART3_CLK_DISABLE() (RCM->APB1CLKEN &= ~(RCM_APB1CLKEN_USART3EN)) +#define __DAL_RCM_UART4_CLK_DISABLE() (RCM->APB1CLKEN &= ~(RCM_APB1CLKEN_UART4EN)) +#define __DAL_RCM_UART5_CLK_DISABLE() (RCM->APB1CLKEN &= ~(RCM_APB1CLKEN_UART5EN)) +#define __DAL_RCM_CAN1_CLK_DISABLE() (RCM->APB1CLKEN &= ~(RCM_APB1CLKEN_CAN1EN)) +#define __DAL_RCM_CAN2_CLK_DISABLE() (RCM->APB1CLKEN &= ~(RCM_APB1CLKEN_CAN2EN)) +#define __DAL_RCM_TMR2_CLK_DISABLE() (RCM->APB1CLKEN &= ~(RCM_APB1CLKEN_TMR2EN)) +#define __DAL_RCM_TMR3_CLK_DISABLE() (RCM->APB1CLKEN &= ~(RCM_APB1CLKEN_TMR3EN)) +#define __DAL_RCM_TMR4_CLK_DISABLE() (RCM->APB1CLKEN &= ~(RCM_APB1CLKEN_TMR4EN)) +#define __DAL_RCM_SPI3_CLK_DISABLE() (RCM->APB1CLKEN &= ~(RCM_APB1CLKEN_SPI3EN)) +#define __DAL_RCM_I2C3_CLK_DISABLE() (RCM->APB1CLKEN &= ~(RCM_APB1CLKEN_I2C3EN)) +/** + * @} + */ + +/** @defgroup RCMEx_APB1_Peripheral_Clock_Enable_Disable_Status APB1 Peripheral Clock Enable Disable Status + * @brief Get the enable or disable status of the APB1 peripheral clock. + * @note After reset, the peripheral clock (used for registers read/write access) + * is disabled and the application software has to enable this clock before + * using it. + * @{ + */ +#define __DAL_RCM_TMR12_IS_CLK_ENABLED() ((RCM->APB1CLKEN & (RCM_APB1CLKEN_TMR12EN)) != RESET) +#define __DAL_RCM_TMR13_IS_CLK_ENABLED() ((RCM->APB1CLKEN & (RCM_APB1CLKEN_TMR13EN)) != RESET) +#define __DAL_RCM_TMR14_IS_CLK_ENABLED() ((RCM->APB1CLKEN & (RCM_APB1CLKEN_TMR14EN)) != RESET) +#define __DAL_RCM_USART3_IS_CLK_ENABLED() ((RCM->APB1CLKEN & (RCM_APB1CLKEN_USART3EN)) != RESET) +#define __DAL_RCM_UART4_IS_CLK_ENABLED() ((RCM->APB1CLKEN & (RCM_APB1CLKEN_UART4EN)) != RESET) +#define __DAL_RCM_UART5_IS_CLK_ENABLED() ((RCM->APB1CLKEN & (RCM_APB1CLKEN_UART5EN)) != RESET) +#define __DAL_RCM_CAN1_IS_CLK_ENABLED() ((RCM->APB1CLKEN & (RCM_APB1CLKEN_CAN1EN)) != RESET) +#define __DAL_RCM_CAN2_IS_CLK_ENABLED() ((RCM->APB1CLKEN & (RCM_APB1CLKEN_CAN2EN)) != RESET) +#define __DAL_RCM_TMR2_IS_CLK_ENABLED() ((RCM->APB1CLKEN & (RCM_APB1CLKEN_TMR2EN)) != RESET) +#define __DAL_RCM_TMR3_IS_CLK_ENABLED() ((RCM->APB1CLKEN & (RCM_APB1CLKEN_TMR3EN)) != RESET) +#define __DAL_RCM_TMR4_IS_CLK_ENABLED() ((RCM->APB1CLKEN & (RCM_APB1CLKEN_TMR4EN)) != RESET) +#define __DAL_RCM_SPI3_IS_CLK_ENABLED() ((RCM->APB1CLKEN & (RCM_APB1CLKEN_SPI3EN)) != RESET) +#define __DAL_RCM_I2C3_IS_CLK_ENABLED() ((RCM->APB1CLKEN & (RCM_APB1CLKEN_I2C3EN)) != RESET) + +#define __DAL_RCM_TMR12_IS_CLK_DISABLED() ((RCM->APB1CLKEN & (RCM_APB1CLKEN_TMR12EN)) == RESET) +#define __DAL_RCM_TMR13_IS_CLK_DISABLED() ((RCM->APB1CLKEN & (RCM_APB1CLKEN_TMR13EN)) == RESET) +#define __DAL_RCM_TMR14_IS_CLK_DISABLED() ((RCM->APB1CLKEN & (RCM_APB1CLKEN_TMR14EN)) == RESET) +#define __DAL_RCM_USART3_IS_CLK_DISABLED() ((RCM->APB1CLKEN & (RCM_APB1CLKEN_USART3EN)) == RESET) +#define __DAL_RCM_UART4_IS_CLK_DISABLED() ((RCM->APB1CLKEN & (RCM_APB1CLKEN_UART4EN)) == RESET) +#define __DAL_RCM_UART5_IS_CLK_DISABLED() ((RCM->APB1CLKEN & (RCM_APB1CLKEN_UART5EN)) == RESET) +#define __DAL_RCM_CAN1_IS_CLK_DISABLED() ((RCM->APB1CLKEN & (RCM_APB1CLKEN_CAN1EN)) == RESET) +#define __DAL_RCM_CAN2_IS_CLK_DISABLED() ((RCM->APB1CLKEN & (RCM_APB1CLKEN_CAN2EN)) == RESET) +#define __DAL_RCM_TMR2_IS_CLK_DISABLED() ((RCM->APB1CLKEN & (RCM_APB1CLKEN_TMR2EN)) == RESET) +#define __DAL_RCM_TMR3_IS_CLK_DISABLED() ((RCM->APB1CLKEN & (RCM_APB1CLKEN_TMR3EN)) == RESET) +#define __DAL_RCM_TMR4_IS_CLK_DISABLED() ((RCM->APB1CLKEN & (RCM_APB1CLKEN_TMR4EN)) == RESET) +#define __DAL_RCM_SPI3_IS_CLK_DISABLED() ((RCM->APB1CLKEN & (RCM_APB1CLKEN_SPI3EN)) == RESET) +#define __DAL_RCM_I2C3_IS_CLK_DISABLED() ((RCM->APB1CLKEN & (RCM_APB1CLKEN_I2C3EN)) == RESET) +/** + * @} + */ + +/** @defgroup RCMEx_APB2_Clock_Enable_Disable APB2 Peripheral Clock Enable Disable + * @brief Enable or disable the High Speed APB (APB2) peripheral clock. + * @{ + */ +#define __DAL_RCM_TMR8_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->APB2CLKEN, RCM_APB2CLKEN_TMR8EN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->APB2CLKEN, RCM_APB2CLKEN_TMR8EN);\ + UNUSED(tmpreg); \ + } while(0U) +#define __DAL_RCM_ADC2_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->APB2CLKEN, RCM_APB2CLKEN_ADC2EN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->APB2CLKEN, RCM_APB2CLKEN_ADC2EN);\ + UNUSED(tmpreg); \ + } while(0U) +#define __DAL_RCM_SPI5_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->APB2CLKEN, RCM_APB2CLKEN_SPI5EN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->APB2CLKEN, RCM_APB2CLKEN_SPI5EN);\ + UNUSED(tmpreg); \ + } while(0U) +#define __DAL_RCM_SDIO_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->APB2CLKEN, RCM_APB2CLKEN_SDIOEN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->APB2CLKEN, RCM_APB2CLKEN_SDIOEN);\ + UNUSED(tmpreg); \ + } while(0U) +#define __DAL_RCM_SPI4_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->APB2CLKEN, RCM_APB2CLKEN_SPI4EN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->APB2CLKEN, RCM_APB2CLKEN_SPI4EN);\ + UNUSED(tmpreg); \ + } while(0U) +#define __DAL_RCM_TMR10_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCM->APB2CLKEN, RCM_APB2CLKEN_TMR10EN);\ + /* Delay after an RCM peripheral clock enabling */ \ + tmpreg = READ_BIT(RCM->APB2CLKEN, RCM_APB2CLKEN_TMR10EN);\ + UNUSED(tmpreg); \ + } while(0U) +#define __DAL_RCM_SDIO_CLK_DISABLE() (RCM->APB2CLKEN &= ~(RCM_APB2CLKEN_SDIOEN)) +#define __DAL_RCM_SPI4_CLK_DISABLE() (RCM->APB2CLKEN &= ~(RCM_APB2CLKEN_SPI4EN)) +#define __DAL_RCM_TMR10_CLK_DISABLE() (RCM->APB2CLKEN &= ~(RCM_APB2CLKEN_TMR10EN)) +#define __DAL_RCM_SPI5_CLK_DISABLE() (RCM->APB2CLKEN &= ~(RCM_APB2CLKEN_SPI5EN)) +#define __DAL_RCM_TMR8_CLK_DISABLE() (RCM->APB2CLKEN &= ~(RCM_APB2CLKEN_TMR8EN)) +#define __DAL_RCM_ADC2_CLK_DISABLE() (RCM->APB2CLKEN &= ~(RCM_APB2CLKEN_ADC2EN)) +/** + * @} + */ + +/** @defgroup RCMEx_APB2_Peripheral_Clock_Enable_Disable_Status APB2 Peripheral Clock Enable Disable Status + * @brief Get the enable or disable status of the APB2 peripheral clock. + * @note After reset, the peripheral clock (used for registers read/write access) + * is disabled and the application software has to enable this clock before + * using it. + * @{ + */ +#define __DAL_RCM_SDIO_IS_CLK_ENABLED() ((RCM->APB2CLKEN & (RCM_APB2CLKEN_SDIOEN)) != RESET) +#define __DAL_RCM_SPI4_IS_CLK_ENABLED() ((RCM->APB2CLKEN & (RCM_APB2CLKEN_SPI4EN)) != RESET) +#define __DAL_RCM_TMR10_IS_CLK_ENABLED() ((RCM->APB2CLKEN & (RCM_APB2CLKEN_TMR10EN)) != RESET) +#define __DAL_RCM_SPI5_IS_CLK_ENABLED() ((RCM->APB2CLKEN & (RCM_APB2CLKEN_SPI5EN)) != RESET) +#define __DAL_RCM_TMR8_IS_CLK_ENABLED() ((RCM->APB2CLKEN & (RCM_APB2CLKEN_TMR8EN)) != RESET) +#define __DAL_RCM_ADC2_IS_CLK_ENABLED() ((RCM->APB2CLKEN & (RCM_APB2CLKEN_ADC2EN)) != RESET) + +#define __DAL_RCM_SDIO_IS_CLK_DISABLED() ((RCM->APB2CLKEN & (RCM_APB2CLKEN_SDIOEN)) == RESET) +#define __DAL_RCM_SPI4_IS_CLK_DISABLED() ((RCM->APB2CLKEN & (RCM_APB2CLKEN_SPI4EN)) == RESET) +#define __DAL_RCM_TMR10_IS_CLK_DISABLED() ((RCM->APB2CLKEN & (RCM_APB2CLKEN_TMR10EN)) == RESET) +#define __DAL_RCM_SPI5_IS_CLK_DISABLED() ((RCM->APB2CLKEN & (RCM_APB2CLKEN_SPI5EN)) == RESET) +#define __DAL_RCM_TMR8_IS_CLK_DISABLED() ((RCM->APB2CLKEN & (RCM_APB2CLKEN_TMR8EN)) == RESET) +#define __DAL_RCM_ADC2_IS_CLK_DISABLED() ((RCM->APB2CLKEN & (RCM_APB2CLKEN_ADC2EN)) == RESET) +/** + * @} + */ + +/** @defgroup RCMEx_AHB1_Force_Release_Reset AHB1 Force Release Reset + * @brief Force or release AHB1 peripheral reset. + * @{ + */ +#define __DAL_RCM_GPIOD_FORCE_RESET() (RCM->AHB1RST |= (RCM_AHB1RST_PDRST)) +#define __DAL_RCM_GPIOE_FORCE_RESET() (RCM->AHB1RST |= (RCM_AHB1RST_PERST)) +#define __DAL_RCM_CRC_FORCE_RESET() (RCM->AHB1RST |= (RCM_AHB1RST_CRCRST)) + +#define __DAL_RCM_GPIOD_RELEASE_RESET() (RCM->AHB1RST &= ~(RCM_AHB1RST_PDRST)) +#define __DAL_RCM_GPIOE_RELEASE_RESET() (RCM->AHB1RST &= ~(RCM_AHB1RST_PERST)) +#define __DAL_RCM_CRC_RELEASE_RESET() (RCM->AHB1RST &= ~(RCM_AHB1RST_CRCRST)) +/** + * @} + */ + +/** @defgroup RCMEx_AHB2_Force_Release_Reset AHB2 Force Release Reset + * @brief Force or release AHB2 peripheral reset. + * @{ + */ +#define __DAL_RCM_AHB2_FORCE_RESET() (RCM->AHB2RST = 0xFFFFFFFFU) +#define __DAL_RCM_USB_OTG_FS_FORCE_RESET() (RCM->AHB2RST |= (RCM_AHB2RST_OTGFSRST)) + +#define __DAL_RCM_AHB2_RELEASE_RESET() (RCM->AHB2RST = 0x00U) +#define __DAL_RCM_USB_OTG_FS_RELEASE_RESET() (RCM->AHB2RST &= ~(RCM_AHB2RST_OTGFSRST)) + +#define __DAL_RCM_RNG_FORCE_RESET() (RCM->AHB2RST |= (RCM_AHB2RST_RNGRST)) +#define __DAL_RCM_RNG_RELEASE_RESET() (RCM->AHB2RST &= ~(RCM_AHB2RST_RNGRST)) + +#define __DAL_RCM_SMC_FORCE_RESET() (RCM->AHB2RST |= (RCM_AHB2RST_SMCRST)) +#define __DAL_RCM_SMC_RELEASE_RESET() (RCM->AHB2RST &= ~(RCM_AHB2RST_SMCRST)) + +#define __DAL_RCM_QSPI_FORCE_RESET() (RCM->AHB2RST |= (RCM_AHB2RST_QSPIRST)) +#define __DAL_RCM_QSPI_RELEASE_RESET() (RCM->AHB2RST &= ~(RCM_AHB2RST_QSPIRST)) +/** + * @} + */ + +/** @defgroup RCMEx_AHB3_Force_Release_Reset AHB3 Force Release Reset + * @brief Force or release AHB3 peripheral reset. + * @{ + */ +#define __DAL_RCM_AHB3_FORCE_RESET() (RCM->AHB3RST = 0xFFFFFFFFU) +#define __DAL_RCM_AHB3_RELEASE_RESET() (RCM->AHB3RST = 0x00U) +/** + * @} + */ + +/** @defgroup RCMEx_APB1_Force_Release_Reset APB1 Force Release Reset + * @brief Force or release APB1 peripheral reset. + * @{ + */ +#define __DAL_RCM_TMR2_FORCE_RESET() (RCM->APB1RST |= (RCM_APB1RST_TMR2RST)) +#define __DAL_RCM_TMR3_FORCE_RESET() (RCM->APB1RST |= (RCM_APB1RST_TMR3RST)) +#define __DAL_RCM_TMR4_FORCE_RESET() (RCM->APB1RST |= (RCM_APB1RST_TMR4RST)) +#define __DAL_RCM_SPI3_FORCE_RESET() (RCM->APB1RST |= (RCM_APB1RST_SPI3RST)) +#define __DAL_RCM_I2C3_FORCE_RESET() (RCM->APB1RST |= (RCM_APB1RST_I2C3RST)) +#define __DAL_RCM_TMR12_FORCE_RESET() (RCM->APB1RST |= (RCM_APB1RST_TMR12RST)) +#define __DAL_RCM_TMR13_FORCE_RESET() (RCM->APB1RST |= (RCM_APB1RST_TMR13RST)) +#define __DAL_RCM_TMR14_FORCE_RESET() (RCM->APB1RST |= (RCM_APB1RST_TMR14RST)) +#define __DAL_RCM_USART3_FORCE_RESET() (RCM->APB1RST |= (RCM_APB1RST_USART3RST)) +#define __DAL_RCM_UART4_FORCE_RESET() (RCM->APB1RST |= (RCM_APB1RST_UART4RST)) +#define __DAL_RCM_UART5_FORCE_RESET() (RCM->APB1RST |= (RCM_APB1RST_UART5RST)) +#define __DAL_RCM_CAN1_FORCE_RESET() (RCM->APB1RST |= (RCM_APB1RST_CAN1RST)) +#define __DAL_RCM_CAN2_FORCE_RESET() (RCM->APB1RST |= (RCM_APB1RST_CAN2RST)) + +#define __DAL_RCM_TMR2_RELEASE_RESET() (RCM->APB1RST &= ~(RCM_APB1RST_TMR2RST)) +#define __DAL_RCM_TMR3_RELEASE_RESET() (RCM->APB1RST &= ~(RCM_APB1RST_TMR3RST)) +#define __DAL_RCM_TMR4_RELEASE_RESET() (RCM->APB1RST &= ~(RCM_APB1RST_TMR4RST)) +#define __DAL_RCM_SPI3_RELEASE_RESET() (RCM->APB1RST &= ~(RCM_APB1RST_SPI3RST)) +#define __DAL_RCM_I2C3_RELEASE_RESET() (RCM->APB1RST &= ~(RCM_APB1RST_I2C3RST)) +#define __DAL_RCM_TMR12_RELEASE_RESET() (RCM->APB1RST &= ~(RCM_APB1RST_TMR12RST)) +#define __DAL_RCM_TMR13_RELEASE_RESET() (RCM->APB1RST &= ~(RCM_APB1RST_TMR13RST)) +#define __DAL_RCM_TMR14_RELEASE_RESET() (RCM->APB1RST &= ~(RCM_APB1RST_TMR14RST)) +#define __DAL_RCM_USART3_RELEASE_RESET() (RCM->APB1RST &= ~(RCM_APB1RST_USART3RST)) +#define __DAL_RCM_UART4_RELEASE_RESET() (RCM->APB1RST &= ~(RCM_APB1RST_UART4RST)) +#define __DAL_RCM_UART5_RELEASE_RESET() (RCM->APB1RST &= ~(RCM_APB1RST_UART5RST)) +#define __DAL_RCM_CAN1_RELEASE_RESET() (RCM->APB1RST &= ~(RCM_APB1RST_CAN1RST)) +#define __DAL_RCM_CAN2_RELEASE_RESET() (RCM->APB1RST &= ~(RCM_APB1RST_CAN2RST)) +/** + * @} + */ + +/** @defgroup RCMEx_APB2_Force_Release_Reset APB2 Force Release Reset + * @brief Force or release APB2 peripheral reset. + * @{ + */ +#define __DAL_RCM_SPI5_FORCE_RESET() (RCM->APB2RST |= (RCM_APB2RST_SPI5RST)) +#define __DAL_RCM_SDIO_FORCE_RESET() (RCM->APB2RST |= (RCM_APB2RST_SDIORST)) +#define __DAL_RCM_SPI4_FORCE_RESET() (RCM->APB2RST |= (RCM_APB2RST_SPI4RST)) +#define __DAL_RCM_TMR10_FORCE_RESET() (RCM->APB2RST |= (RCM_APB2RST_TMR10RST)) +#define __DAL_RCM_TMR8_FORCE_RESET() (RCM->APB2RST |= (RCM_APB2RST_TMR8RST)) +#define __DAL_RCM_ADC2_FORCE_RESET() (RCM->APB2RST |= (RCM_APB2RST_ADC2RST)) + +#define __DAL_RCM_SDIO_RELEASE_RESET() (RCM->APB2RST &= ~(RCM_APB2RST_SDIORST)) +#define __DAL_RCM_SPI4_RELEASE_RESET() (RCM->APB2RST &= ~(RCM_APB2RST_SPI4RST)) +#define __DAL_RCM_TMR10_RELEASE_RESET() (RCM->APB2RST &= ~(RCM_APB2RST_TMR10RST)) +#define __DAL_RCM_SPI5_RELEASE_RESET() (RCM->APB2RST &= ~(RCM_APB2RST_SPI5RST)) +#define __DAL_RCM_TMR8_RELEASE_RESET() (RCM->APB2RST &= ~(RCM_APB2RST_TMR8RST)) +#define __DAL_RCM_ADC2_RELEASE_RESET() (RCM->APB2RST &= ~(RCM_APB2RST_ADC2RST)) +/** + * @} + */ + +/** @defgroup RCMEx_AHB1_LowPower_Enable_Disable AHB1 Peripheral Low Power Enable Disable + * @brief Enable or disable the AHB1 peripheral clock during Low Power (Sleep) mode. + * @note Peripheral clock gating in SLEEP mode can be used to further reduce + * power consumption. + * @note After wakeup from SLEEP mode, the peripheral clock is enabled again. + * @note By default, all peripheral clocks are enabled during SLEEP mode. + * @{ + */ +#define __DAL_RCM_GPIOD_CLK_SLEEP_ENABLE() (RCM->LPAHB1CLKEN |= (RCM_LPAHB1CLKEN_PDLPEN)) +#define __DAL_RCM_GPIOE_CLK_SLEEP_ENABLE() (RCM->LPAHB1CLKEN |= (RCM_LPAHB1CLKEN_PELPEN)) +#define __DAL_RCM_CRC_CLK_SLEEP_ENABLE() (RCM->LPAHB1CLKEN |= (RCM_LPAHB1CLKEN_CRCLPEN)) +#define __DAL_RCM_FLITF_CLK_SLEEP_ENABLE() (RCM->LPAHB1CLKEN |= (RCM_LPAHB1CLKEN_FMCEN)) +#define __DAL_RCM_SRAM1_CLK_SLEEP_ENABLE() (RCM->LPAHB1CLKEN |= (RCM_LPAHB1CLKEN_SRAM1EN)) + +#define __DAL_RCM_GPIOD_CLK_SLEEP_DISABLE() (RCM->LPAHB1CLKEN &= ~(RCM_LPAHB1CLKEN_PDLPEN)) +#define __DAL_RCM_GPIOE_CLK_SLEEP_DISABLE() (RCM->LPAHB1CLKEN &= ~(RCM_LPAHB1CLKEN_PELPEN)) +#define __DAL_RCM_CRC_CLK_SLEEP_DISABLE() (RCM->LPAHB1CLKEN &= ~(RCM_LPAHB1CLKEN_CRCLPEN)) +#define __DAL_RCM_FLITF_CLK_SLEEP_DISABLE() (RCM->LPAHB1CLKEN &= ~(RCM_LPAHB1CLKEN_FMCEN)) +#define __DAL_RCM_SRAM1_CLK_SLEEP_DISABLE() (RCM->LPAHB1CLKEN &= ~(RCM_LPAHB1CLKEN_SRAM1EN)) +/** + * @} + */ + +/** @defgroup RCMEx_AHB2_LowPower_Enable_Disable AHB2 Peripheral Low Power Enable Disable + * @brief Enable or disable the AHB2 peripheral clock during Low Power (Sleep) mode. + * @note Peripheral clock gating in SLEEP mode can be used to further reduce + * power consumption. + * @note After wake-up from SLEEP mode, the peripheral clock is enabled again. + * @note By default, all peripheral clocks are enabled during SLEEP mode. + * @{ + */ +#define __DAL_RCM_USB_OTG_FS_CLK_SLEEP_ENABLE() (RCM->LPAHB2CLKEN |= (RCM_LPAHB2CLKEN_OTGFSEN)) +#define __DAL_RCM_USB_OTG_FS_CLK_SLEEP_DISABLE() (RCM->LPAHB2CLKEN &= ~(RCM_LPAHB2CLKEN_OTGFSEN)) + +#define __DAL_RCM_RNG_CLK_SLEEP_ENABLE() (RCM->LPAHB2CLKEN |= (RCM_LPAHB2CLKEN_RNGEN)) +#define __DAL_RCM_RNG_CLK_SLEEP_DISABLE() (RCM->LPAHB2CLKEN &= ~(RCM_LPAHB2CLKEN_RNGEN)) + +#define __DAL_RCM_SMC_CLK_SLEEP_ENABLE() (RCM->LPAHB2CLKEN |= (RCM_LPAHB2CLKEN_SMCEN)) +#define __DAL_RCM_SMC_CLK_SLEEP_DISABLE() (RCM->LPAHB2CLKEN &= ~(RCM_LPAHB2CLKEN_SMCEN)) + +#define __DAL_RCM_QSPI_CLK_SLEEP_ENABLE() (RCM->LPAHB2CLKEN |= (RCM_LPAHB2CLKEN_QSPIEN)) +#define __DAL_RCM_QSPI_CLK_SLEEP_DISABLE() (RCM->LPAHB2CLKEN &= ~(RCM_LPAHB2CLKEN_QSPIEN)) +/** + * @} + */ + +/** @defgroup RCMEx_APB1_LowPower_Enable_Disable APB1 Peripheral Low Power Enable Disable + * @brief Enable or disable the APB1 peripheral clock during Low Power (Sleep) mode. + * @{ + */ +#define __DAL_RCM_TMR2_CLK_SLEEP_ENABLE() (RCM->LPAPB1CLKEN |= (RCM_LPAPB1CLKEN_TMR2EN)) +#define __DAL_RCM_TMR3_CLK_SLEEP_ENABLE() (RCM->LPAPB1CLKEN |= (RCM_LPAPB1CLKEN_TMR3EN)) +#define __DAL_RCM_TMR4_CLK_SLEEP_ENABLE() (RCM->LPAPB1CLKEN |= (RCM_LPAPB1CLKEN_TMR4EN)) +#define __DAL_RCM_SPI3_CLK_SLEEP_ENABLE() (RCM->LPAPB1CLKEN |= (RCM_LPAPB1CLKEN_SPI3EN)) +#define __DAL_RCM_I2C3_CLK_SLEEP_ENABLE() (RCM->LPAPB1CLKEN |= (RCM_LPAPB1CLKEN_I2C3EN)) +#define __DAL_RCM_TMR12_CLK_SLEEP_ENABLE() (RCM->LPAPB1CLKEN |= (RCM_LPAPB1CLKEN_TMR12EN)) +#define __DAL_RCM_TMR13_CLK_SLEEP_ENABLE() (RCM->LPAPB1CLKEN |= (RCM_LPAPB1CLKEN_TMR13EN)) +#define __DAL_RCM_TMR14_CLK_SLEEP_ENABLE() (RCM->LPAPB1CLKEN |= (RCM_LPAPB1CLKEN_TMR14EN)) +#define __DAL_RCM_USART3_CLK_SLEEP_ENABLE() (RCM->LPAPB1CLKEN |= (RCM_LPAPB1CLKEN_USART3EN)) +#define __DAL_RCM_UART4_CLK_SLEEP_ENABLE() (RCM->LPAPB1CLKEN |= (RCM_LPAPB1CLKEN_UART4EN)) +#define __DAL_RCM_UART5_CLK_SLEEP_ENABLE() (RCM->LPAPB1CLKEN |= (RCM_LPAPB1CLKEN_UART5EN)) +#define __DAL_RCM_CAN1_CLK_SLEEP_ENABLE() (RCM->LPAPB1CLKEN |= (RCM_LPAPB1CLKEN_CAN1EN)) +#define __DAL_RCM_CAN2_CLK_SLEEP_ENABLE() (RCM->LPAPB1CLKEN |= (RCM_LPAPB1CLKEN_CAN2EN)) + +#define __DAL_RCM_TMR2_CLK_SLEEP_DISABLE() (RCM->LPAPB1CLKEN &= ~(RCM_LPAPB1CLKEN_TMR2EN)) +#define __DAL_RCM_TMR3_CLK_SLEEP_DISABLE() (RCM->LPAPB1CLKEN &= ~(RCM_LPAPB1CLKEN_TMR3EN)) +#define __DAL_RCM_TMR4_CLK_SLEEP_DISABLE() (RCM->LPAPB1CLKEN &= ~(RCM_LPAPB1CLKEN_TMR4EN)) +#define __DAL_RCM_SPI3_CLK_SLEEP_DISABLE() (RCM->LPAPB1CLKEN &= ~(RCM_LPAPB1CLKEN_SPI3EN)) +#define __DAL_RCM_I2C3_CLK_SLEEP_DISABLE() (RCM->LPAPB1CLKEN &= ~(RCM_LPAPB1CLKEN_I2C3EN)) +#define __DAL_RCM_TMR12_CLK_SLEEP_DISABLE() (RCM->LPAPB1CLKEN &= ~(RCM_LPAPB1CLKEN_TMR12EN)) +#define __DAL_RCM_TMR13_CLK_SLEEP_DISABLE() (RCM->LPAPB1CLKEN &= ~(RCM_LPAPB1CLKEN_TMR13EN)) +#define __DAL_RCM_TMR14_CLK_SLEEP_DISABLE() (RCM->LPAPB1CLKEN &= ~(RCM_LPAPB1CLKEN_TMR14EN)) +#define __DAL_RCM_USART3_CLK_SLEEP_DISABLE() (RCM->LPAPB1CLKEN &= ~(RCM_LPAPB1CLKEN_USART3EN)) +#define __DAL_RCM_UART4_CLK_SLEEP_DISABLE() (RCM->LPAPB1CLKEN &= ~(RCM_LPAPB1CLKEN_UART4EN)) +#define __DAL_RCM_UART5_CLK_SLEEP_DISABLE() (RCM->LPAPB1CLKEN &= ~(RCM_LPAPB1CLKEN_UART5EN)) +#define __DAL_RCM_CAN1_CLK_SLEEP_DISABLE() (RCM->LPAPB1CLKEN &= ~(RCM_LPAPB1CLKEN_CAN1EN)) +#define __DAL_RCM_CAN2_CLK_SLEEP_DISABLE() (RCM->LPAPB1CLKEN &= ~(RCM_LPAPB1CLKEN_CAN2EN)) +/** + * @} + */ + +/** @defgroup RCMEx_APB2_LowPower_Enable_Disable APB2 Peripheral Low Power Enable Disable + * @brief Enable or disable the APB2 peripheral clock during Low Power (Sleep) mode. + * @{ + */ +#define __DAL_RCM_SPI5_CLK_SLEEP_ENABLE() (RCM->LPAPB2CLKEN |= (RCM_LPAPB2CLKEN_SPI5LPEN)) +#define __DAL_RCM_SDIO_CLK_SLEEP_ENABLE() (RCM->LPAPB2CLKEN |= (RCM_LPAPB2CLKEN_SDIOEN)) +#define __DAL_RCM_SPI4_CLK_SLEEP_ENABLE() (RCM->LPAPB2CLKEN |= (RCM_LPAPB2CLKEN_SPI4EN)) +#define __DAL_RCM_TMR10_CLK_SLEEP_ENABLE() (RCM->LPAPB2CLKEN |= (RCM_LPAPB2CLKEN_TMR10EN)) +#define __DAL_RCM_TMR8_CLK_SLEEP_ENABLE() (RCM->LPAPB2CLKEN |= (RCM_LPAPB2CLKEN_TMR8EN)) +#define __DAL_RCM_ADC2_CLK_SLEEP_ENABLE() (RCM->LPAPB2CLKEN |= (RCM_LPAPB2CLKEN_ADC2EN)) + +#define __DAL_RCM_SDIO_CLK_SLEEP_DISABLE() (RCM->LPAPB2CLKEN &= ~(RCM_LPAPB2CLKEN_SDIOEN)) +#define __DAL_RCM_SPI4_CLK_SLEEP_DISABLE() (RCM->LPAPB2CLKEN &= ~(RCM_LPAPB2CLKEN_SPI4EN)) +#define __DAL_RCM_TMR10_CLK_SLEEP_DISABLE() (RCM->LPAPB2CLKEN &= ~(RCM_LPAPB2CLKEN_TMR10EN)) +#define __DAL_RCM_SPI5_CLK_SLEEP_DISABLE() (RCM->LPAPB2CLKEN &= ~(RCM_LPAPB2CLKEN_SPI5LPEN)) +#define __DAL_RCM_TMR8_CLK_SLEEP_DISABLE() (RCM->LPAPB2CLKEN &= ~(RCM_LPAPB2CLKEN_TMR8EN)) +#define __DAL_RCM_ADC2_CLK_SLEEP_DISABLE() (RCM->LPAPB2CLKEN &= ~(RCM_LPAPB2CLKEN_ADC2EN)) +/** + * @} + */ +#endif /* APM32F411xx */ +/*----------------------------------------------------------------------------*/ + +/*------------------------------- PLL Configuration --------------------------*/ +/** @brief Macro to configure the main PLL clock source, multiplication and division factors. + * @note This function must be used only when the main PLL is disabled. + * @param __RCM_PLLSource__ specifies the PLL entry clock source. + * This parameter can be one of the following values: + * @arg RCM_PLLSOURCE_HSI: HSI oscillator clock selected as PLL clock entry + * @arg RCM_PLLSOURCE_HSE: HSE oscillator clock selected as PLL clock entry + * @note This clock source (RCM_PLLSource) is common for the main PLL and PLLI2S. + * @param __PLLB__ specifies the division factor for PLL VCO input clock + * This parameter must be a number between Min_Data = 2 and Max_Data = 63. + * @note You have to set the PLLB parameter correctly to ensure that the VCO input + * frequency ranges from 1 to 2 MHz. It is recommended to select a frequency + * of 2 MHz to limit PLL jitter. + * @param __PLL1A__ specifies the multiplication factor for PLL VCO output clock + * This parameter must be a number between Min_Data = 50 and Max_Data = 432 + * Except for APM32F411xx devices where Min_Data = 192. + * @note You have to set the PLL1A parameter correctly to ensure that the VCO + * output frequency is between 100 and 432 MHz, Except for APM32F411xx devices + * where frequency is between 192 and 432 MHz. + * @param __PLL1C__ specifies the division factor for main system clock (SYSCLK) + * This parameter must be a number in the range {2, 4, 6, or 8}. + * + * @param __PLLD__ specifies the division factor for OTG FS, SDIO and RNG clocks + * This parameter must be a number between Min_Data = 2 and Max_Data = 15. + * @note If the USB OTG FS is used in your application, you have to set the + * PLLD parameter correctly to have 48 MHz clock for the USB. However, + * the SDIO and RNG need a frequency lower than or equal to 48 MHz to work + * correctly. + * + */ +#define __DAL_RCM_PLL_CONFIG(__RCM_PLLSource__, __PLLB__, __PLL1A__, __PLL1C__, __PLLD__) \ + (RCM->PLL1CFG = (0x20000000U | (__RCM_PLLSource__) | (__PLLB__)| \ + ((__PLL1A__) << RCM_PLL1CFG_PLL1A_Pos) | \ + ((((__PLL1C__) >> 1U) -1U) << RCM_PLL1CFG_PLL1C_Pos) | \ + ((__PLLD__) << RCM_PLL1CFG_PLLD_Pos))) +/*----------------------------------------------------------------------------*/ + +/*----------------------------PLLI2S Configuration ---------------------------*/ +#if defined(APM32F405xx) || defined(APM32F407xx) || defined(APM32F417xx) || \ + defined(APM32F465xx) || defined(APM32F411xx) + +/** @brief Macros to enable or disable the PLLI2S. + * @note The PLLI2S is disabled by hardware when entering STOP and STANDBY modes. + */ +#define __DAL_RCM_PLLI2S_ENABLE() (*(__IO uint32_t *) RCM_CTRL_PLL2EN_BB = ENABLE) +#define __DAL_RCM_PLLI2S_DISABLE() (*(__IO uint32_t *) RCM_CTRL_PLL2EN_BB = DISABLE) + +#endif /* APM32F405xx || APM32F407xx || APM32F417xx || APM32F465xx || APM32F411xx */ + +/** @brief Macro to configure the PLLI2S clock multiplication and division factors . + * @note This macro must be used only when the PLLI2S is disabled. + * @note PLLI2S clock source is common with the main PLL (configured in + * DAL_RCM_ClockConfig() API). + * @param __PLL2A__ specifies the multiplication factor for PLLI2S VCO output clock + * This parameter must be a number between Min_Data = 50 and Max_Data = 432. + * @note You have to set the PLL2A parameter correctly to ensure that the VCO + * output frequency is between Min_Data = 100 and Max_Data = 432 MHz. + * + * @param __PLL2C__ specifies the division factor for I2S clock + * This parameter must be a number between Min_Data = 2 and Max_Data = 7. + * @note You have to set the PLL2C parameter correctly to not exceed 192 MHz + * on the I2S clock frequency. + * + */ +#define __DAL_RCM_PLLI2S_CONFIG(__PLL2A__, __PLL2C__) \ + (RCM->PLL2CFG = (((__PLL2A__) << RCM_PLL2CFG_PLL2A_Pos) |\ + ((__PLL2C__) << RCM_PLL2CFG_PLL2C_Pos))) + +#if defined(APM32F411xx) +/** @brief Macro to configure the PLLI2S clock multiplication and division factors . + * @note This macro must be used only when the PLLI2S is disabled. + * @note This macro must be used only when the PLLI2S is disabled. + * @note PLLI2S clock source is common with the main PLL (configured in + * DAL_RCM_ClockConfig() API). + * @param __PLL2B__ specifies the division factor for PLLI2S VCO input clock + * This parameter must be a number between Min_Data = 2 and Max_Data = 63. + * @note The PLL2B parameter is only used with APM32F411xx Devices + * @note You have to set the PLL2B parameter correctly to ensure that the VCO input + * frequency ranges from 1 to 2 MHz. It is recommended to select a frequency + * of 2 MHz to limit PLLI2S jitter. + * @param __PLL2A__ specifies the multiplication factor for PLLI2S VCO output clock + * This parameter must be a number between Min_Data = 192 and Max_Data = 432. + * @note You have to set the PLL2A parameter correctly to ensure that the VCO + * output frequency is between Min_Data = 192 and Max_Data = 432 MHz. + * @param __PLL2C__ specifies the division factor for I2S clock + * This parameter must be a number between Min_Data = 2 and Max_Data = 7. + * @note You have to set the PLL2C parameter correctly to not exceed 192 MHz + * on the I2S clock frequency. + */ +#define __DAL_RCM_PLLI2S_I2SCLK_CONFIG(__PLL2B__, __PLL2A__, __PLL2C__) (RCM->PLL2CFG = ((__PLL2B__) |\ + ((__PLL2A__) << RCM_PLL2CFG_PLL2A_Pos) |\ + ((__PLL2C__) << RCM_PLL2CFG_PLL2C_Pos))) +#endif /* APM32F411xx */ + +/*------------------------- Peripheral Clock selection -----------------------*/ +#if defined(APM32F405xx) || defined(APM32F407xx) || defined(APM32F417xx) ||\ + defined(APM32F465xx) || defined(APM32F411xx) +/** @brief Macro to configure the I2S clock source (I2SCLK). + * @note This function must be called before enabling the I2S APB clock. + * @param __SOURCE__ specifies the I2S clock source. + * This parameter can be one of the following values: + * @arg RCM_I2SCLKSOURCE_PLLI2S: PLLI2S clock used as I2S clock source. + * @arg RCM_I2SCLKSOURCE_EXT: External clock mapped on the I2S_CKIN pin + * used as I2S clock source. + */ +#define __DAL_RCM_I2S_CONFIG(__SOURCE__) (*(__IO uint32_t *) RCM_CFG_I2SSEL_BB = (__SOURCE__)) + + +/** @brief Macro to get the I2S clock source (I2SCLK). + * @retval The clock source can be one of the following values: + * @arg @ref RCM_I2SCLKSOURCE_PLLI2S: PLLI2S clock used as I2S clock source. + * @arg @ref RCM_I2SCLKSOURCE_EXT External clock mapped on the I2S_CKIN pin + * used as I2S clock source + */ +#define __DAL_RCM_GET_I2S_SOURCE() ((uint32_t)(READ_BIT(RCM->CFG, RCM_CFG_I2SSEL))) +#endif /* APM32F40xxx || APM32F41xxx || APM32F465xx */ + +#if defined(APM32F411xx) +/** @brief Macro to configure the Timers clocks prescalers + * @note This feature is only available with APM32F429x/439x Devices. + * @param __PRESC__ specifies the Timers clocks prescalers selection + * This parameter can be one of the following values: + * @arg RCM_TMRPRES_DESACTIVATED: The Timers kernels clocks prescaler is + * equal to HPRE if PPREx is corresponding to division by 1 or 2, + * else it is equal to [(HPRE * PPREx) / 2] if PPREx is corresponding to + * division by 4 or more. + * @arg RCM_TMRPRES_ACTIVATED: The Timers kernels clocks prescaler is + * equal to HPRE if PPREx is corresponding to division by 1, 2 or 4, + * else it is equal to [(HPRE * PPREx) / 4] if PPREx is corresponding + * to division by 8 or more. + */ +#define __DAL_RCM_TMRCLKPRESCALER(__PRESC__) (*(__IO uint32_t *) RCM_CFGSEL_CLKPSEL_BB = (__PRESC__)) + +#endif /* APM32F411xx */ + +/*----------------------------------------------------------------------------*/ + +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup RCMEx_Exported_Functions + * @{ + */ + +/** @addtogroup RCMEx_Exported_Functions_Group1 + * @{ + */ +DAL_StatusTypeDef DAL_RCMEx_PeriphCLKConfig(RCM_PeriphCLKInitTypeDef *PeriphClkInit); +void DAL_RCMEx_GetPeriphCLKConfig(RCM_PeriphCLKInitTypeDef *PeriphClkInit); + +uint32_t DAL_RCMEx_GetPeriphCLKFreq(uint32_t PeriphClk); + +#if defined(APM32F411xx) && defined(RCM_BDCTRL_LSEMOD) +void DAL_RCMEx_SelectLSEMode(uint8_t Mode); +#endif /* APM32F411xx */ +#if defined(RCM_PLLI2S_SUPPORT) +DAL_StatusTypeDef DAL_RCMEx_EnablePLLI2S(RCM_PLLI2SInitTypeDef *PLLI2SInit); +DAL_StatusTypeDef DAL_RCMEx_DisablePLLI2S(void); +#endif /* RCM_PLLI2S_SUPPORT */ +/** + * @} + */ + +/** + * @} + */ +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/** @defgroup RCMEx_Private_Constants RCMEx Private Constants + * @{ + */ + +/** @defgroup RCMEx_BitAddress_AliasRegion RCM BitAddress AliasRegion + * @brief RCM registers bit address in the alias region + * @{ + */ +/* --- CTRL Register ---*/ + +#if defined(APM32F405xx) || defined(APM32F407xx) || defined(APM32F417xx) || \ + defined(APM32F465xx) || defined(APM32F411xx) +/* Alias word address of PLL2EN bit */ +#define RCM_PLL2EN_BIT_NUMBER 0x1AU +#define RCM_CTRL_PLL2EN_BB (PERIPH_BB_BASE + (RCM_CTRL_OFFSET * 32U) + (RCM_PLL2EN_BIT_NUMBER * 4U)) +#endif /* APM32F405xx || APM32F407xx || APM32F417xx || APM32F465xx || APM32F411xx */ + +/* --- DCKCFGR Register ---*/ +#if defined(APM32F411xx) +/* Alias word address of TMRPRE bit */ +#define RCM_CFGSEL_OFFSET (RCM_OFFSET + 0x8CU) +#define RCM_CLKPSEL_BIT_NUMBER 0x18U +#define RCM_CFGSEL_CLKPSEL_BB (PERIPH_BB_BASE + (RCM_CFGSEL_OFFSET * 32U) + (RCM_CLKPSEL_BIT_NUMBER * 4U)) +#endif /* APM32F411xx */ + +/* --- CFG Register ---*/ +#define RCM_CFG_OFFSET (RCM_OFFSET + 0x08U) +#if defined(APM32F405xx) || defined(APM32F407xx) || defined(APM32F417xx) || \ + defined(APM32F465xx) || defined(APM32F411xx) +/* Alias word address of I2SSRC bit */ +#define RCM_I2SSEL_BIT_NUMBER 0x17U +#define RCM_CFG_I2SSEL_BB (PERIPH_BB_BASE + (RCM_CFG_OFFSET * 32U) + (RCM_I2SSEL_BIT_NUMBER * 4U)) + +#define PLLI2S_TIMEOUT_VALUE 2U /* Timeout value fixed to 2 ms */ +#endif /* APM32F405xx || APM32F407xx || APM32F417xx || APM32F465xx || APM32F411xx */ + +#define PLL_TIMEOUT_VALUE 2U /* 2 ms */ +/** + * @} + */ + +/** + * @} + */ + +/* Private macros ------------------------------------------------------------*/ +/** @defgroup RCMEx_Private_Macros RCMEx Private Macros + * @{ + */ +/** @defgroup RCMEx_IS_RCM_Definitions RCM Private macros to check input parameters + * @{ + */ +#if defined(APM32F407xx) || defined(APM32F417xx) +#define IS_RCM_SDRAM_DIV(DIV) (((DIV) == RCM_SDRAM_DIV_1) ||\ + ((DIV) == RCM_SDRAM_DIV_2) ||\ + ((DIV) == RCM_SDRAM_DIV_4)) +#endif /* APM32F407xx || APM32F417xx */ + +#define IS_RCM_PLL1A_VALUE(VALUE) ((50U <= (VALUE)) && ((VALUE) <= 432U)) +#define IS_RCM_PLL2A_VALUE(VALUE) ((50U <= (VALUE)) && ((VALUE) <= 432U)) + +#if defined(APM32F405xx) || defined(APM32F407xx) || defined(APM32F417xx) || defined(APM32F465xx) +#define IS_RCM_PERIPHCLOCK(SELECTION) ((1U <= (SELECTION)) && ((SELECTION) <= 0x0000000FU)) +#endif /* APM32F405xx || APM32F407xx || APM32F417xx || APM32F465xx */ + +#if defined(APM32F411xx) +#define IS_RCM_PERIPHCLOCK(SELECTION) ((1U <= (SELECTION)) && ((SELECTION) <= 0x0000000FU)) +#endif /* APM32F411xx */ + +#define IS_RCM_PLL2C_VALUE(VALUE) ((2U <= (VALUE)) && ((VALUE) <= 7U)) + +#if defined(APM32F411xx) +#define IS_RCM_PLL2B_VALUE(VALUE) ((2U <= (VALUE)) && ((VALUE) <= 63U)) +#if defined(RCM_BDCTRL_LSEMOD) +#define IS_RCM_LSE_MODE(MODE) (((MODE) == RCM_LSE_LOWPOWER_MODE) ||\ + ((MODE) == RCM_LSE_HIGHDRIVE_MODE)) +#endif /* RCM_BDCTRL_LSEMOD */ +#endif /* APM32F411xx */ + +#if defined(APM32F405xx) || defined(APM32F407xx) || defined(APM32F417xx) || \ + defined(APM32F465xx) || defined(APM32F411xx) + +#define IS_RCM_MCO2SOURCE(SOURCE) (((SOURCE) == RCM_MCO2SOURCE_SYSCLK) || ((SOURCE) == RCM_MCO2SOURCE_PLLI2SCLK)|| \ + ((SOURCE) == RCM_MCO2SOURCE_HSE) || ((SOURCE) == RCM_MCO2SOURCE_PLLCLK)) + +#endif /* APM32F405xx || APM32F407xx || APM32F417xx || APM32F465xx || APM32F411xx */ + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ +#ifdef __cplusplus +} +#endif + +#endif /* APM32F4xx_DAL_RCM_EX_H */ + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_rng.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_rng.h new file mode 100644 index 0000000000..b8edb96a82 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_rng.h @@ -0,0 +1,385 @@ +/** + * + * @file apm32f4xx_dal_rng.h + * @brief Header file of RNG DAL module. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef APM32F4xx_DAL_RNG_H +#define APM32F4xx_DAL_RNG_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal_def.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +#if defined (RNG) + +/** @defgroup RNG RNG + * @brief RNG DAL module driver + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ + +/** @defgroup RNG_Exported_Types RNG Exported Types + * @{ + */ + +/** @defgroup RNG_Exported_Types_Group1 RNG Init Structure definition + * @{ + */ + +/** + * @} + */ + +/** @defgroup RNG_Exported_Types_Group2 RNG State Structure definition + * @{ + */ +typedef enum +{ + DAL_RNG_STATE_RESET = 0x00U, /*!< RNG not yet initialized or disabled */ + DAL_RNG_STATE_READY = 0x01U, /*!< RNG initialized and ready for use */ + DAL_RNG_STATE_BUSY = 0x02U, /*!< RNG internal process is ongoing */ + DAL_RNG_STATE_TIMEOUT = 0x03U, /*!< RNG timeout state */ + DAL_RNG_STATE_ERROR = 0x04U /*!< RNG error state */ + +} DAL_RNG_StateTypeDef; + +/** + * @} + */ + +/** @defgroup RNG_Exported_Types_Group3 RNG Handle Structure definition + * @{ + */ +#if (USE_DAL_RNG_REGISTER_CALLBACKS == 1) +typedef struct __RNG_HandleTypeDef +#else +typedef struct +#endif /* USE_DAL_RNG_REGISTER_CALLBACKS */ +{ + RNG_TypeDef *Instance; /*!< Register base address */ + + DAL_LockTypeDef Lock; /*!< RNG locking object */ + + __IO DAL_RNG_StateTypeDef State; /*!< RNG communication state */ + + __IO uint32_t ErrorCode; /*!< RNG Error code */ + + uint32_t RandomNumber; /*!< Last Generated RNG Data */ + +#if (USE_DAL_RNG_REGISTER_CALLBACKS == 1) + void (* ReadyDataCallback)(struct __RNG_HandleTypeDef *hrng, uint32_t random32bit); /*!< RNG Data Ready Callback */ + void (* ErrorCallback)(struct __RNG_HandleTypeDef *hrng); /*!< RNG Error Callback */ + + void (* MspInitCallback)(struct __RNG_HandleTypeDef *hrng); /*!< RNG Msp Init callback */ + void (* MspDeInitCallback)(struct __RNG_HandleTypeDef *hrng); /*!< RNG Msp DeInit callback */ +#endif /* USE_DAL_RNG_REGISTER_CALLBACKS */ + +} RNG_HandleTypeDef; + +#if (USE_DAL_RNG_REGISTER_CALLBACKS == 1) +/** + * @brief DAL RNG Callback ID enumeration definition + */ +typedef enum +{ + DAL_RNG_ERROR_CB_ID = 0x00U, /*!< RNG Error Callback ID */ + + DAL_RNG_MSPINIT_CB_ID = 0x01U, /*!< RNG MspInit callback ID */ + DAL_RNG_MSPDEINIT_CB_ID = 0x02U /*!< RNG MspDeInit callback ID */ + +} DAL_RNG_CallbackIDTypeDef; + +/** + * @brief DAL RNG Callback pointer definition + */ +typedef void (*pRNG_CallbackTypeDef)(RNG_HandleTypeDef *hrng); /*!< pointer to a common RNG callback function */ +typedef void (*pRNG_ReadyDataCallbackTypeDef)(RNG_HandleTypeDef *hrng, uint32_t random32bit); /*!< pointer to an RNG Data Ready specific callback function */ + +#endif /* USE_DAL_RNG_REGISTER_CALLBACKS */ + +/** + * @} + */ + +/** + * @} + */ + +/* Exported constants --------------------------------------------------------*/ +/** @defgroup RNG_Exported_Constants RNG Exported Constants + * @{ + */ + +/** @defgroup RNG_Exported_Constants_Group1 RNG Interrupt definition + * @{ + */ +#define RNG_IT_DRDY RNG_STS_DATARDY /*!< Data Ready interrupt */ +#define RNG_IT_CEI RNG_STS_CLKERINT /*!< Clock error interrupt */ +#define RNG_IT_SEI RNG_STS_FSINT /*!< Seed error interrupt */ +/** + * @} + */ + +/** @defgroup RNG_Exported_Constants_Group2 RNG Flag definition + * @{ + */ +#define RNG_FLAG_DRDY RNG_STS_DATARDY /*!< Data ready */ +#define RNG_FLAG_CECS RNG_STS_CLKERCSTS /*!< Clock error current status */ +#define RNG_FLAG_SECS RNG_STS_FSCSTS /*!< Seed error current status */ +/** + * @} + */ + +/** @defgroup RNG_Error_Definition RNG Error Definition + * @{ + */ +#define DAL_RNG_ERROR_NONE 0x00000000U /*!< No error */ +#if (USE_DAL_RNG_REGISTER_CALLBACKS == 1) +#define DAL_RNG_ERROR_INVALID_CALLBACK 0x00000001U /*!< Invalid Callback error */ +#endif /* USE_DAL_RNG_REGISTER_CALLBACKS */ +#define DAL_RNG_ERROR_TIMEOUT 0x00000002U /*!< Timeout error */ +#define DAL_RNG_ERROR_BUSY 0x00000004U /*!< Busy error */ +#define DAL_RNG_ERROR_SEED 0x00000008U /*!< Seed error */ +#define DAL_RNG_ERROR_CLOCK 0x00000010U /*!< Clock error */ +/** + * @} + */ + +/** + * @} + */ + +/* Exported macros -----------------------------------------------------------*/ +/** @defgroup RNG_Exported_Macros RNG Exported Macros + * @{ + */ + +/** @brief Reset RNG handle state + * @param __HANDLE__ RNG Handle + * @retval None + */ +#if (USE_DAL_RNG_REGISTER_CALLBACKS == 1) +#define __DAL_RNG_RESET_HANDLE_STATE(__HANDLE__) do{ \ + (__HANDLE__)->State = DAL_RNG_STATE_RESET; \ + (__HANDLE__)->MspInitCallback = NULL; \ + (__HANDLE__)->MspDeInitCallback = NULL; \ + } while(0U) +#else +#define __DAL_RNG_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = DAL_RNG_STATE_RESET) +#endif /* USE_DAL_RNG_REGISTER_CALLBACKS */ + +/** + * @brief Enables the RNG peripheral. + * @param __HANDLE__ RNG Handle + * @retval None + */ +#define __DAL_RNG_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CTRL |= RNG_CTRL_RNGEN) + +/** + * @brief Disables the RNG peripheral. + * @param __HANDLE__ RNG Handle + * @retval None + */ +#define __DAL_RNG_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CTRL &= ~RNG_CTRL_RNGEN) + +/** + * @brief Check the selected RNG flag status. + * @param __HANDLE__ RNG Handle + * @param __FLAG__ RNG flag + * This parameter can be one of the following values: + * @arg RNG_FLAG_DRDY: Data ready + * @arg RNG_FLAG_CECS: Clock error current status + * @arg RNG_FLAG_SECS: Seed error current status + * @retval The new state of __FLAG__ (SET or RESET). + */ +#define __DAL_RNG_GET_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->STS & (__FLAG__)) == (__FLAG__)) + +/** + * @brief Clears the selected RNG flag status. + * @param __HANDLE__ RNG handle + * @param __FLAG__ RNG flag to clear + * @note WARNING: This is a dummy macro for DAL code alignment, + * flags RNG_FLAG_DRDY, RNG_FLAG_CECS and RNG_FLAG_SECS are read-only. + * @retval None + */ +#define __DAL_RNG_CLEAR_FLAG(__HANDLE__, __FLAG__) /* dummy macro */ + +/** + * @brief Enables the RNG interrupts. + * @param __HANDLE__ RNG Handle + * @retval None + */ +#define __DAL_RNG_ENABLE_IT(__HANDLE__) ((__HANDLE__)->Instance->CTRL |= RNG_CTRL_INTEN) + +/** + * @brief Disables the RNG interrupts. + * @param __HANDLE__ RNG Handle + * @retval None + */ +#define __DAL_RNG_DISABLE_IT(__HANDLE__) ((__HANDLE__)->Instance->CTRL &= ~RNG_CTRL_INTEN) + +/** + * @brief Checks whether the specified RNG interrupt has occurred or not. + * @param __HANDLE__ RNG Handle + * @param __INTERRUPT__ specifies the RNG interrupt status flag to check. + * This parameter can be one of the following values: + * @arg RNG_IT_DRDY: Data ready interrupt + * @arg RNG_IT_CEI: Clock error interrupt + * @arg RNG_IT_SEI: Seed error interrupt + * @retval The new state of __INTERRUPT__ (SET or RESET). + */ +#define __DAL_RNG_GET_IT(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->STS & (__INTERRUPT__)) == (__INTERRUPT__)) + +/** + * @brief Clear the RNG interrupt status flags. + * @param __HANDLE__ RNG Handle + * @param __INTERRUPT__ specifies the RNG interrupt status flag to clear. + * This parameter can be one of the following values: + * @arg RNG_IT_CEI: Clock error interrupt + * @arg RNG_IT_SEI: Seed error interrupt + * @note RNG_IT_DRDY flag is read-only, reading RNG_DATA register automatically clears RNG_IT_DRDY. + * @retval None + */ +#define __DAL_RNG_CLEAR_IT(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->STS) = ~(__INTERRUPT__)) + +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +/** @defgroup RNG_Exported_Functions RNG Exported Functions + * @{ + */ + +/** @defgroup RNG_Exported_Functions_Group1 Initialization and configuration functions + * @{ + */ +DAL_StatusTypeDef DAL_RNG_Init(RNG_HandleTypeDef *hrng); +DAL_StatusTypeDef DAL_RNG_DeInit(RNG_HandleTypeDef *hrng); +void DAL_RNG_MspInit(RNG_HandleTypeDef *hrng); +void DAL_RNG_MspDeInit(RNG_HandleTypeDef *hrng); + +/* Callbacks Register/UnRegister functions ***********************************/ +#if (USE_DAL_RNG_REGISTER_CALLBACKS == 1) +DAL_StatusTypeDef DAL_RNG_RegisterCallback(RNG_HandleTypeDef *hrng, DAL_RNG_CallbackIDTypeDef CallbackID, + pRNG_CallbackTypeDef pCallback); +DAL_StatusTypeDef DAL_RNG_UnRegisterCallback(RNG_HandleTypeDef *hrng, DAL_RNG_CallbackIDTypeDef CallbackID); + +DAL_StatusTypeDef DAL_RNG_RegisterReadyDataCallback(RNG_HandleTypeDef *hrng, pRNG_ReadyDataCallbackTypeDef pCallback); +DAL_StatusTypeDef DAL_RNG_UnRegisterReadyDataCallback(RNG_HandleTypeDef *hrng); +#endif /* USE_DAL_RNG_REGISTER_CALLBACKS */ + +/** + * @} + */ + +/** @defgroup RNG_Exported_Functions_Group2 Peripheral Control functions + * @{ + */ +uint32_t DAL_RNG_GetRandomNumber(RNG_HandleTypeDef + *hrng); /* Obsolete, use DAL_RNG_GenerateRandomNumber() instead */ +uint32_t DAL_RNG_GetRandomNumber_IT(RNG_HandleTypeDef + *hrng); /* Obsolete, use DAL_RNG_GenerateRandomNumber_IT() instead */ +DAL_StatusTypeDef DAL_RNG_GenerateRandomNumber(RNG_HandleTypeDef *hrng, uint32_t *random32bit); +DAL_StatusTypeDef DAL_RNG_GenerateRandomNumber_IT(RNG_HandleTypeDef *hrng); +uint32_t DAL_RNG_ReadLastRandomNumber(RNG_HandleTypeDef *hrng); + +void DAL_RNG_IRQHandler(RNG_HandleTypeDef *hrng); +void DAL_RNG_ErrorCallback(RNG_HandleTypeDef *hrng); +void DAL_RNG_ReadyDataCallback(RNG_HandleTypeDef *hrng, uint32_t random32bit); + +/** + * @} + */ + +/** @defgroup RNG_Exported_Functions_Group3 Peripheral State functions + * @{ + */ +DAL_RNG_StateTypeDef DAL_RNG_GetState(RNG_HandleTypeDef *hrng); +uint32_t DAL_RNG_GetError(RNG_HandleTypeDef *hrng); +/** + * @} + */ + +/** + * @} + */ + +/* Private macros ------------------------------------------------------------*/ +/** @defgroup RNG_Private_Macros RNG Private Macros + * @{ + */ +#define IS_RNG_IT(IT) (((IT) == RNG_IT_CEI) || \ + ((IT) == RNG_IT_SEI)) + +#define IS_RNG_FLAG(FLAG) (((FLAG) == RNG_FLAG_DRDY) || \ + ((FLAG) == RNG_FLAG_CECS) || \ + ((FLAG) == RNG_FLAG_SECS)) + +/** + * @} + */ + +/** + * @} + */ + +#endif /* RNG */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + + +#endif /* APM32F4xx_DAL_RNG_H */ + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_rtc.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_rtc.h new file mode 100644 index 0000000000..de71578235 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_rtc.h @@ -0,0 +1,939 @@ +/** + * + * @file apm32f4xx_dal_rtc.h + * @brief Header file of RTC DAL module. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2017 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef APM32F4xx_DAL_RTC_H +#define APM32F4xx_DAL_RTC_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ + +#include "apm32f4xx_dal_def.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @addtogroup RTC + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ + +/** @defgroup RTC_Exported_Types RTC Exported Types + * @{ + */ + +/** + * @brief DAL State structures definition + */ +typedef enum +{ + DAL_RTC_STATE_RESET = 0x00U, /*!< RTC not yet initialized or disabled */ + DAL_RTC_STATE_READY = 0x01U, /*!< RTC initialized and ready for use */ + DAL_RTC_STATE_BUSY = 0x02U, /*!< RTC process is ongoing */ + DAL_RTC_STATE_TIMEOUT = 0x03U, /*!< RTC timeout state */ + DAL_RTC_STATE_ERROR = 0x04U /*!< RTC error state */ +} DAL_RTCStateTypeDef; + +/** + * @brief RTC Configuration Structure definition + */ +typedef struct +{ + uint32_t HourFormat; /*!< Specifies the RTC Hour Format. + This parameter can be a value of @ref RTC_Hour_Formats */ + + uint32_t AsynchPrediv; /*!< Specifies the RTC Asynchronous Predivider value. + This parameter must be a number between Min_Data = 0x00 and Max_Data = 0x7F */ + + uint32_t SynchPrediv; /*!< Specifies the RTC Synchronous Predivider value. + This parameter must be a number between Min_Data = 0x0000 and Max_Data = 0x7FFF */ + + uint32_t OutPut; /*!< Specifies which signal will be routed to the RTC output. + This parameter can be a value of @ref RTC_Output_selection_Definitions */ + + uint32_t OutPutPolarity; /*!< Specifies the polarity of the output signal. + This parameter can be a value of @ref RTC_Output_Polarity_Definitions */ + + uint32_t OutPutType; /*!< Specifies the RTC Output Pin mode. + This parameter can be a value of @ref RTC_Output_Type_ALARM_OUT */ +} RTC_InitTypeDef; + +/** + * @brief RTC Time structure definition + */ +typedef struct +{ + uint8_t Hours; /*!< Specifies the RTC Time Hour. + This parameter must be a number between Min_Data = 0 and Max_Data = 12 if the RTC_HourFormat_12 is selected + This parameter must be a number between Min_Data = 0 and Max_Data = 23 if the RTC_HourFormat_24 is selected */ + + uint8_t Minutes; /*!< Specifies the RTC Time Minutes. + This parameter must be a number between Min_Data = 0 and Max_Data = 59 */ + + uint8_t Seconds; /*!< Specifies the RTC Time Seconds. + This parameter must be a number between Min_Data = 0 and Max_Data = 59 */ + + uint8_t TimeFormat; /*!< Specifies the RTC AM/PM Time. + This parameter can be a value of @ref RTC_AM_PM_Definitions */ + + uint32_t SubSeconds; /*!< Specifies the RTC_SUBSEC RTC Sub Second register content. + This parameter corresponds to a time unit range between [0-1] Second + with [1 Sec / SecondFraction +1] granularity */ + + uint32_t SecondFraction; /*!< Specifies the range or granularity of Sub Second register content + corresponding to Synchronous prescaler factor value (PREDIV_S) + This parameter corresponds to a time unit range between [0-1] Second + with [1 Sec / SecondFraction +1] granularity. + This field will be used only by DAL_RTC_GetTime function */ + + uint32_t DayLightSaving; /*!< This interface is deprecated. To manage Daylight + Saving Time, please use DAL_RTC_DST_xxx functions */ + + uint32_t StoreOperation; /*!< This interface is deprecated. To manage Daylight + Saving Time, please use DAL_RTC_DST_xxx functions */ +} RTC_TimeTypeDef; + +/** + * @brief RTC Date structure definition + */ +typedef struct +{ + uint8_t WeekDay; /*!< Specifies the RTC Date WeekDay. + This parameter can be a value of @ref RTC_WeekDay_Definitions */ + + uint8_t Month; /*!< Specifies the RTC Date Month (in BCD format). + This parameter can be a value of @ref RTC_Month_Date_Definitions */ + + uint8_t Date; /*!< Specifies the RTC Date. + This parameter must be a number between Min_Data = 1 and Max_Data = 31 */ + + uint8_t Year; /*!< Specifies the RTC Date Year. + This parameter must be a number between Min_Data = 0 and Max_Data = 99 */ + +} RTC_DateTypeDef; + +/** + * @brief RTC Alarm structure definition + */ +typedef struct +{ + RTC_TimeTypeDef AlarmTime; /*!< Specifies the RTC Alarm Time members */ + + uint32_t AlarmMask; /*!< Specifies the RTC Alarm Masks. + This parameter can be a value of @ref RTC_AlarmMask_Definitions */ + + uint32_t AlarmSubSecondMask; /*!< Specifies the RTC Alarm SubSeconds Masks. + This parameter can be a value of @ref RTC_Alarm_Sub_Seconds_Masks_Definitions */ + + uint32_t AlarmDateWeekDaySel; /*!< Specifies the RTC Alarm is on Date or WeekDay. + This parameter can be a value of @ref RTC_AlarmDateWeekDay_Definitions */ + + uint8_t AlarmDateWeekDay; /*!< Specifies the RTC Alarm Date/WeekDay. + If the Alarm Date is selected, this parameter must be set to a value in the 1-31 range. + If the Alarm WeekDay is selected, this parameter can be a value of @ref RTC_WeekDay_Definitions */ + + uint32_t Alarm; /*!< Specifies the alarm . + This parameter can be a value of @ref RTC_Alarms_Definitions */ +} RTC_AlarmTypeDef; + +/** + * @brief RTC Handle Structure definition + */ +#if (USE_DAL_RTC_REGISTER_CALLBACKS == 1) +typedef struct __RTC_HandleTypeDef +#else +typedef struct +#endif /* USE_DAL_RTC_REGISTER_CALLBACKS */ +{ + RTC_TypeDef *Instance; /*!< Register base address */ + + RTC_InitTypeDef Init; /*!< RTC required parameters */ + + DAL_LockTypeDef Lock; /*!< RTC locking object */ + + __IO DAL_RTCStateTypeDef State; /*!< Time communication state */ + +#if (USE_DAL_RTC_REGISTER_CALLBACKS == 1) + void (* AlarmAEventCallback) (struct __RTC_HandleTypeDef *hrtc); /*!< RTC Alarm A Event callback */ + + void (* AlarmBEventCallback) (struct __RTC_HandleTypeDef *hrtc); /*!< RTC Alarm B Event callback */ + + void (* TimeStampEventCallback) (struct __RTC_HandleTypeDef *hrtc); /*!< RTC Timestamp Event callback */ + + void (* WakeUpTimerEventCallback) (struct __RTC_HandleTypeDef *hrtc); /*!< RTC WakeUpTimer Event callback */ + + void (* Tamper1EventCallback) (struct __RTC_HandleTypeDef *hrtc); /*!< RTC Tamper 1 Event callback */ + +#if defined(RTC_TAMPER2_SUPPORT) + void (* Tamper2EventCallback) (struct __RTC_HandleTypeDef *hrtc); /*!< RTC Tamper 2 Event callback */ +#endif /* RTC_TAMPER2_SUPPORT */ + + void (* MspInitCallback) (struct __RTC_HandleTypeDef *hrtc); /*!< RTC Msp Init callback */ + + void (* MspDeInitCallback) (struct __RTC_HandleTypeDef *hrtc); /*!< RTC Msp DeInit callback */ + +#endif /* USE_DAL_RTC_REGISTER_CALLBACKS */ + +} RTC_HandleTypeDef; + +#if (USE_DAL_RTC_REGISTER_CALLBACKS == 1) +/** + * @brief DAL RTC Callback ID enumeration definition + */ +typedef enum +{ + DAL_RTC_ALARM_A_EVENT_CB_ID = 0x00U, /*!< RTC Alarm A Event Callback ID */ + DAL_RTC_ALARM_B_EVENT_CB_ID = 0x01U, /*!< RTC Alarm B Event Callback ID */ + DAL_RTC_TIMESTAMP_EVENT_CB_ID = 0x02U, /*!< RTC Timestamp Event Callback ID */ + DAL_RTC_WAKEUPTIMER_EVENT_CB_ID = 0x03U, /*!< RTC Wakeup Timer Event Callback ID */ + DAL_RTC_TAMPER1_EVENT_CB_ID = 0x04U, /*!< RTC Tamper 1 Callback ID */ +#if defined(RTC_TAMPER2_SUPPORT) + DAL_RTC_TAMPER2_EVENT_CB_ID = 0x05U, /*!< RTC Tamper 2 Callback ID */ +#endif /* RTC_TAMPER2_SUPPORT */ + DAL_RTC_MSPINIT_CB_ID = 0x0EU, /*!< RTC Msp Init callback ID */ + DAL_RTC_MSPDEINIT_CB_ID = 0x0FU /*!< RTC Msp DeInit callback ID */ +} DAL_RTC_CallbackIDTypeDef; + +/** + * @brief DAL RTC Callback pointer definition + */ +typedef void (*pRTC_CallbackTypeDef)(RTC_HandleTypeDef *hrtc); /*!< pointer to an RTC callback function */ +#endif /* USE_DAL_RTC_REGISTER_CALLBACKS */ + +/** + * @} + */ + +/* Exported constants --------------------------------------------------------*/ + +/** @defgroup RTC_Exported_Constants RTC Exported Constants + * @{ + */ + +/** @defgroup RTC_Hour_Formats RTC Hour Formats + * @{ + */ +#define RTC_HOURFORMAT_24 0x00000000U +#define RTC_HOURFORMAT_12 RTC_CTRL_TIMEFCFG +/** + * @} + */ + +/** @defgroup RTC_Output_selection_Definitions RTC Output Selection Definitions + * @{ + */ +#define RTC_OUTPUT_DISABLE 0x00000000U +#define RTC_OUTPUT_ALARMA RTC_CTRL_OUTSEL_0 +#define RTC_OUTPUT_ALARMB RTC_CTRL_OUTSEL_1 +#define RTC_OUTPUT_WAKEUP RTC_CTRL_OUTSEL +/** + * @} + */ + +/** @defgroup RTC_Output_Polarity_Definitions RTC Output Polarity Definitions + * @{ + */ +#define RTC_OUTPUT_POLARITY_HIGH 0x00000000U +#define RTC_OUTPUT_POLARITY_LOW RTC_CTRL_POLCFG +/** + * @} + */ + +/** @defgroup RTC_Output_Type_ALARM_OUT RTC Output Type ALARM OUT + * @{ + */ +#define RTC_OUTPUT_TYPE_OPENDRAIN 0x00000000U +#define RTC_OUTPUT_TYPE_PUSHPULL RTC_TACFG_ALRMOT +/** + * @} + */ + +/** @defgroup RTC_AM_PM_Definitions RTC AM PM Definitions + * @{ + */ +#define RTC_HOURFORMAT12_AM ((uint8_t)0x00) +#define RTC_HOURFORMAT12_PM ((uint8_t)0x01) +/** + * @} + */ + +/** @defgroup RTC_DayLightSaving_Definitions RTC DayLight Saving Definitions + * @{ + */ +#define RTC_DAYLIGHTSAVING_SUB1H RTC_CTRL_WTCCFG +#define RTC_DAYLIGHTSAVING_ADD1H RTC_CTRL_STCCFG +#define RTC_DAYLIGHTSAVING_NONE 0x00000000U +/** + * @} + */ + +/** @defgroup RTC_StoreOperation_Definitions RTC Store Operation Definitions + * @{ + */ +#define RTC_STOREOPERATION_RESET 0x00000000U +#define RTC_STOREOPERATION_SET RTC_CTRL_BAKP +/** + * @} + */ + +/** @defgroup RTC_Input_parameter_format_definitions RTC Input Parameter Format Definitions + * @{ + */ +#define RTC_FORMAT_BIN 0x00000000U +#define RTC_FORMAT_BCD 0x00000001U +/** + * @} + */ + +/** @defgroup RTC_Month_Date_Definitions RTC Month Date Definitions (in BCD format) + * @{ + */ +#define RTC_MONTH_JANUARY ((uint8_t)0x01) +#define RTC_MONTH_FEBRUARY ((uint8_t)0x02) +#define RTC_MONTH_MARCH ((uint8_t)0x03) +#define RTC_MONTH_APRIL ((uint8_t)0x04) +#define RTC_MONTH_MAY ((uint8_t)0x05) +#define RTC_MONTH_JUNE ((uint8_t)0x06) +#define RTC_MONTH_JULY ((uint8_t)0x07) +#define RTC_MONTH_AUGUST ((uint8_t)0x08) +#define RTC_MONTH_SEPTEMBER ((uint8_t)0x09) +#define RTC_MONTH_OCTOBER ((uint8_t)0x10) +#define RTC_MONTH_NOVEMBER ((uint8_t)0x11) +#define RTC_MONTH_DECEMBER ((uint8_t)0x12) +/** + * @} + */ + +/** @defgroup RTC_WeekDay_Definitions RTC WeekDay Definitions + * @{ + */ +#define RTC_WEEKDAY_MONDAY ((uint8_t)0x01) +#define RTC_WEEKDAY_TUESDAY ((uint8_t)0x02) +#define RTC_WEEKDAY_WEDNESDAY ((uint8_t)0x03) +#define RTC_WEEKDAY_THURSDAY ((uint8_t)0x04) +#define RTC_WEEKDAY_FRIDAY ((uint8_t)0x05) +#define RTC_WEEKDAY_SATURDAY ((uint8_t)0x06) +#define RTC_WEEKDAY_SUNDAY ((uint8_t)0x07) +/** + * @} + */ + +/** @defgroup RTC_AlarmDateWeekDay_Definitions RTC Alarm Date WeekDay Definitions + * @{ + */ +#define RTC_ALARMDATEWEEKDAYSEL_DATE 0x00000000U +#define RTC_ALARMDATEWEEKDAYSEL_WEEKDAY RTC_ALRMA_WEEKSEL +/** + * @} + */ + +/** @defgroup RTC_AlarmMask_Definitions RTC Alarm Mask Definitions + * @{ + */ +#define RTC_ALARMMASK_NONE 0x00000000U +#define RTC_ALARMMASK_DATEWEEKDAY RTC_ALRMA_DATEMEN +#define RTC_ALARMMASK_HOURS RTC_ALRMA_HRMEN +#define RTC_ALARMMASK_MINUTES RTC_ALRMA_MINMEN +#define RTC_ALARMMASK_SECONDS RTC_ALRMA_SECMEN +#define RTC_ALARMMASK_ALL (RTC_ALARMMASK_DATEWEEKDAY | \ + RTC_ALARMMASK_HOURS | \ + RTC_ALARMMASK_MINUTES | \ + RTC_ALARMMASK_SECONDS) +/** + * @} + */ + +/** @defgroup RTC_Alarms_Definitions RTC Alarms Definitions + * @{ + */ +#define RTC_ALARM_A RTC_CTRL_ALRAEN +#define RTC_ALARM_B RTC_CTRL_ALRBEN +/** + * @} + */ + +/** @defgroup RTC_Alarm_Sub_Seconds_Masks_Definitions RTC Alarm Sub Seconds Masks Definitions + * @{ + */ +/*!< All Alarm SS fields are masked. There is no comparison on sub seconds for Alarm */ +#define RTC_ALARMSUBSECONDMASK_ALL 0x00000000U +/*!< SS[14:1] are don't care in Alarm comparison. Only SS[0] is compared. */ +#define RTC_ALARMSUBSECONDMASK_SS14_1 RTC_ALRMASS_MASKSEL_0 +/*!< SS[14:2] are don't care in Alarm comparison. Only SS[1:0] are compared. */ +#define RTC_ALARMSUBSECONDMASK_SS14_2 RTC_ALRMASS_MASKSEL_1 +/*!< SS[14:3] are don't care in Alarm comparison. Only SS[2:0] are compared. */ +#define RTC_ALARMSUBSECONDMASK_SS14_3 (RTC_ALRMASS_MASKSEL_0 | RTC_ALRMASS_MASKSEL_1) +/*!< SS[14:4] are don't care in Alarm comparison. Only SS[3:0] are compared. */ +#define RTC_ALARMSUBSECONDMASK_SS14_4 RTC_ALRMASS_MASKSEL_2 +/*!< SS[14:5] are don't care in Alarm comparison. Only SS[4:0] are compared. */ +#define RTC_ALARMSUBSECONDMASK_SS14_5 (RTC_ALRMASS_MASKSEL_0 | RTC_ALRMASS_MASKSEL_2) +/*!< SS[14:6] are don't care in Alarm comparison. Only SS[5:0] are compared. */ +#define RTC_ALARMSUBSECONDMASK_SS14_6 (RTC_ALRMASS_MASKSEL_1 | RTC_ALRMASS_MASKSEL_2) +/*!< SS[14:7] are don't care in Alarm comparison. Only SS[6:0] are compared. */ +#define RTC_ALARMSUBSECONDMASK_SS14_7 (RTC_ALRMASS_MASKSEL_0 | RTC_ALRMASS_MASKSEL_1 | RTC_ALRMASS_MASKSEL_2) +/*!< SS[14:8] are don't care in Alarm comparison. Only SS[7:0] are compared. */ +#define RTC_ALARMSUBSECONDMASK_SS14_8 RTC_ALRMASS_MASKSEL_3 +/*!< SS[14:9] are don't care in Alarm comparison. Only SS[8:0] are compared. */ +#define RTC_ALARMSUBSECONDMASK_SS14_9 (RTC_ALRMASS_MASKSEL_0 | RTC_ALRMASS_MASKSEL_3) +/*!< SS[14:10] are don't care in Alarm comparison. Only SS[9:0] are compared. */ +#define RTC_ALARMSUBSECONDMASK_SS14_10 (RTC_ALRMASS_MASKSEL_1 | RTC_ALRMASS_MASKSEL_3) +/*!< SS[14:11] are don't care in Alarm comparison. Only SS[10:0] are compared. */ +#define RTC_ALARMSUBSECONDMASK_SS14_11 (RTC_ALRMASS_MASKSEL_0 | RTC_ALRMASS_MASKSEL_1 | RTC_ALRMASS_MASKSEL_3) +/*!< SS[14:12] are don't care in Alarm comparison. Only SS[11:0] are compared. */ +#define RTC_ALARMSUBSECONDMASK_SS14_12 (RTC_ALRMASS_MASKSEL_2 | RTC_ALRMASS_MASKSEL_3) +/*!< SS[14:13] are don't care in Alarm comparison. Only SS[12:0] are compared. */ +#define RTC_ALARMSUBSECONDMASK_SS14_13 (RTC_ALRMASS_MASKSEL_0 | RTC_ALRMASS_MASKSEL_2 | RTC_ALRMASS_MASKSEL_3) +/*!< SS[14] is don't care in Alarm comparison. Only SS[13:0] are compared. */ +#define RTC_ALARMSUBSECONDMASK_SS14 (RTC_ALRMASS_MASKSEL_1 | RTC_ALRMASS_MASKSEL_2 | RTC_ALRMASS_MASKSEL_3) +/*!< SS[14:0] are compared and must match to activate alarm. */ +#define RTC_ALARMSUBSECONDMASK_NONE RTC_ALRMASS_MASKSEL +/** + * @} + */ + +/** @defgroup RTC_Interrupts_Definitions RTC Interrupts Definitions + * @{ + */ +#define RTC_IT_TS RTC_CTRL_TSIEN /*!< Enable Timestamp Interrupt */ +#define RTC_IT_WUT RTC_CTRL_WUTIEN /*!< Enable Wakeup timer Interrupt */ +#define RTC_IT_ALRB RTC_CTRL_ALRBIEN /*!< Enable Alarm B Interrupt */ +#define RTC_IT_ALRA RTC_CTRL_ALRAIEN /*!< Enable Alarm A Interrupt */ +/** + * @} + */ + +/** @defgroup RTC_Flags_Definitions RTC Flags Definitions + * @{ + */ +#define RTC_FLAG_RECALPF RTC_STS_RCALPFLG /*!< Recalibration pending flag */ +#if defined(RTC_TAMPER2_SUPPORT) +#define RTC_FLAG_TAMP2F RTC_STS_TP2FLG /*!< Tamper 2 event flag */ +#endif /* RTC_TAMPER2_SUPPORT */ +#define RTC_FLAG_TAMP1F RTC_STS_TP1FLG /*!< Tamper 1 event flag */ +#define RTC_FLAG_TSOVF RTC_STS_TSOVRFLG /*!< Timestamp overflow flag */ +#define RTC_FLAG_TSF RTC_STS_TSFLG /*!< Timestamp event flag */ +#define RTC_FLAG_WUTF RTC_STS_WUTFLG /*!< Wakeup timer event flag */ +#define RTC_FLAG_ALRBF RTC_STS_ALRBFLG /*!< Alarm B event flag */ +#define RTC_FLAG_ALRAF RTC_STS_ALRAFLG /*!< Alarm A event flag */ +#define RTC_FLAG_INITF RTC_STS_RINITFLG /*!< RTC in initialization mode flag */ +#define RTC_FLAG_RSF RTC_STS_RSFLG /*!< Register synchronization flag */ +#define RTC_FLAG_INITS RTC_STS_INITSFLG /*!< RTC initialization status flag */ +#define RTC_FLAG_SHPF RTC_STS_SOPFLG /*!< Shift operation pending flag */ +#define RTC_FLAG_WUTWF RTC_STS_WUTWFLG /*!< WUTR register write allowance flag */ +#define RTC_FLAG_ALRBWF RTC_STS_ALRBWFLG /*!< ALRMBR register write allowance flag */ +#define RTC_FLAG_ALRAWF RTC_STS_ALRAWFLG /*!< ALRMAR register write allowance flag */ +/** + * @} + */ + +/** + * @} + */ + +/* Exported macros -----------------------------------------------------------*/ + +/** @defgroup RTC_Exported_Macros RTC Exported Macros + * @{ + */ + +/** @brief Reset RTC handle state + * @param __HANDLE__ specifies the RTC handle. + * @retval None + */ +#if (USE_DAL_RTC_REGISTER_CALLBACKS == 1) +#define __DAL_RTC_RESET_HANDLE_STATE(__HANDLE__) do { \ + (__HANDLE__)->State = DAL_RTC_STATE_RESET; \ + (__HANDLE__)->MspInitCallback = NULL; \ + (__HANDLE__)->MspDeInitCallback = NULL; \ + } while(0U) +#else +#define __DAL_RTC_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = DAL_RTC_STATE_RESET) +#endif /* USE_DAL_RTC_REGISTER_CALLBACKS */ + +/** + * @brief Disable the write protection for RTC registers. + * @param __HANDLE__ specifies the RTC handle. + * @retval None + */ +#define __DAL_RTC_WRITEPROTECTION_DISABLE(__HANDLE__) do { \ + (__HANDLE__)->Instance->WRPROT = 0xCAU; \ + (__HANDLE__)->Instance->WRPROT = 0x53U; \ + } while(0U) + +/** + * @brief Enable the write protection for RTC registers. + * @param __HANDLE__ specifies the RTC handle. + * @retval None + */ +#define __DAL_RTC_WRITEPROTECTION_ENABLE(__HANDLE__) do { \ + (__HANDLE__)->Instance->WRPROT = 0xFFU; \ + } while(0U) + + +/** + * @brief Enable the RTC ALARMA peripheral. + * @param __HANDLE__ specifies the RTC handle. + * @retval None + */ +#define __DAL_RTC_ALARMA_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CTRL |= (RTC_CTRL_ALRAEN)) + +/** + * @brief Disable the RTC ALARMA peripheral. + * @param __HANDLE__ specifies the RTC handle. + * @retval None + */ +#define __DAL_RTC_ALARMA_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CTRL &= ~(RTC_CTRL_ALRAEN)) + +/** + * @brief Enable the RTC ALARMB peripheral. + * @param __HANDLE__ specifies the RTC handle. + * @retval None + */ +#define __DAL_RTC_ALARMB_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CTRL |= (RTC_CTRL_ALRBEN)) + +/** + * @brief Disable the RTC ALARMB peripheral. + * @param __HANDLE__ specifies the RTC handle. + * @retval None + */ +#define __DAL_RTC_ALARMB_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CTRL &= ~(RTC_CTRL_ALRBEN)) + +/** + * @brief Enable the RTC Alarm interrupt. + * @param __HANDLE__ specifies the RTC handle. + * @param __INTERRUPT__ specifies the RTC Alarm interrupt sources to be enabled or disabled. + * This parameter can be any combination of the following values: + * @arg RTC_IT_ALRA: Alarm A interrupt + * @arg RTC_IT_ALRB: Alarm B interrupt + * @retval None + */ +#define __DAL_RTC_ALARM_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CTRL |= (__INTERRUPT__)) + +/** + * @brief Disable the RTC Alarm interrupt. + * @param __HANDLE__ specifies the RTC handle. + * @param __INTERRUPT__ specifies the RTC Alarm interrupt sources to be enabled or disabled. + * This parameter can be any combination of the following values: + * @arg RTC_IT_ALRA: Alarm A interrupt + * @arg RTC_IT_ALRB: Alarm B interrupt + * @retval None + */ +#define __DAL_RTC_ALARM_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CTRL &= ~(__INTERRUPT__)) + +/** + * @brief Check whether the specified RTC Alarm interrupt has occurred or not. + * @param __HANDLE__ specifies the RTC handle. + * @param __INTERRUPT__ specifies the RTC Alarm interrupt to check. + * This parameter can be: + * @arg RTC_IT_ALRA: Alarm A interrupt + * @arg RTC_IT_ALRB: Alarm B interrupt + * @retval None + */ +#define __DAL_RTC_ALARM_GET_IT(__HANDLE__, __INTERRUPT__) (((((__HANDLE__)->Instance->STS) & ((__INTERRUPT__) >> 4U)) != 0U) ? 1U : 0U) + +/** + * @brief Get the selected RTC Alarm's flag status. + * @param __HANDLE__ specifies the RTC handle. + * @param __FLAG__ specifies the RTC Alarm Flag to check. + * This parameter can be: + * @arg RTC_FLAG_ALRAF: Alarm A interrupt flag + * @arg RTC_FLAG_ALRAWF: Alarm A 'write allowed' flag + * @arg RTC_FLAG_ALRBF: Alarm B interrupt flag + * @arg RTC_FLAG_ALRBWF: Alarm B 'write allowed' flag + * @retval None + */ +#define __DAL_RTC_ALARM_GET_FLAG(__HANDLE__, __FLAG__) (((((__HANDLE__)->Instance->STS) & (__FLAG__)) != 0U) ? 1U : 0U) + +/** + * @brief Clear the RTC Alarm's pending flags. + * @param __HANDLE__ specifies the RTC handle. + * @param __FLAG__ specifies the RTC Alarm flag to be cleared. + * This parameter can be: + * @arg RTC_FLAG_ALRAF + * @arg RTC_FLAG_ALRBF + * @retval None + */ +#define __DAL_RTC_ALARM_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->STS) = (~((__FLAG__) | RTC_STS_INITEN)|((__HANDLE__)->Instance->STS & RTC_STS_INITEN)) + +/** + * @brief Check whether the specified RTC Alarm interrupt has been enabled or not. + * @param __HANDLE__ specifies the RTC handle. + * @param __INTERRUPT__ specifies the RTC Alarm interrupt sources to check. + * This parameter can be: + * @arg RTC_IT_ALRA: Alarm A interrupt + * @arg RTC_IT_ALRB: Alarm B interrupt + * @retval None + */ +#define __DAL_RTC_ALARM_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) (((((__HANDLE__)->Instance->CTRL) & (__INTERRUPT__)) != 0U) ? 1U : 0U) + +/** + * @brief Enable interrupt on the RTC Alarm associated EINT line. + * @retval None + */ +#define __DAL_RTC_ALARM_EINT_ENABLE_IT() (EINT->IMASK |= RTC_EINT_LINE_ALARM_EVENT) + +/** + * @brief Disable interrupt on the RTC Alarm associated EINT line. + * @retval None + */ +#define __DAL_RTC_ALARM_EINT_DISABLE_IT() (EINT->IMASK &= ~RTC_EINT_LINE_ALARM_EVENT) + +/** + * @brief Enable event on the RTC Alarm associated EINT line. + * @retval None. + */ +#define __DAL_RTC_ALARM_EINT_ENABLE_EVENT() (EINT->EMASK |= RTC_EINT_LINE_ALARM_EVENT) + +/** + * @brief Disable event on the RTC Alarm associated EINT line. + * @retval None. + */ +#define __DAL_RTC_ALARM_EINT_DISABLE_EVENT() (EINT->EMASK &= ~RTC_EINT_LINE_ALARM_EVENT) + +/** + * @brief Enable falling edge trigger on the RTC Alarm associated EINT line. + * @retval None. + */ +#define __DAL_RTC_ALARM_EINT_ENABLE_FALLING_EDGE() (EINT->FTEN |= RTC_EINT_LINE_ALARM_EVENT) + +/** + * @brief Disable falling edge trigger on the RTC Alarm associated EINT line. + * @retval None. + */ +#define __DAL_RTC_ALARM_EINT_DISABLE_FALLING_EDGE() (EINT->FTEN &= ~RTC_EINT_LINE_ALARM_EVENT) + +/** + * @brief Enable rising edge trigger on the RTC Alarm associated EINT line. + * @retval None. + */ +#define __DAL_RTC_ALARM_EINT_ENABLE_RISING_EDGE() (EINT->RTEN |= RTC_EINT_LINE_ALARM_EVENT) + +/** + * @brief Disable rising edge trigger on the RTC Alarm associated EINT line. + * @retval None. + */ +#define __DAL_RTC_ALARM_EINT_DISABLE_RISING_EDGE() (EINT->RTEN &= ~RTC_EINT_LINE_ALARM_EVENT) + +/** + * @brief Enable rising & falling edge trigger on the RTC Alarm associated EINT line. + * @retval None. + */ +#define __DAL_RTC_ALARM_EINT_ENABLE_RISING_FALLING_EDGE() do { \ + __DAL_RTC_ALARM_EINT_ENABLE_RISING_EDGE(); \ + __DAL_RTC_ALARM_EINT_ENABLE_FALLING_EDGE(); \ + } while(0U) + +/** + * @brief Disable rising & falling edge trigger on the RTC Alarm associated EINT line. + * @retval None. + */ +#define __DAL_RTC_ALARM_EINT_DISABLE_RISING_FALLING_EDGE() do { \ + __DAL_RTC_ALARM_EINT_DISABLE_RISING_EDGE(); \ + __DAL_RTC_ALARM_EINT_DISABLE_FALLING_EDGE(); \ + } while(0U) + +/** + * @brief Check whether the RTC Alarm associated EINT line interrupt flag is set or not. + * @retval Line Status. + */ +#define __DAL_RTC_ALARM_EINT_GET_FLAG() (EINT->IPEND & RTC_EINT_LINE_ALARM_EVENT) + +/** + * @brief Clear the RTC Alarm associated EINT line flag. + * @retval None. + */ +#define __DAL_RTC_ALARM_EINT_CLEAR_FLAG() (EINT->IPEND = RTC_EINT_LINE_ALARM_EVENT) + +/** + * @brief Generate a Software interrupt on RTC Alarm associated EINT line. + * @retval None. + */ +#define __DAL_RTC_ALARM_EINT_GENERATE_SWIT() (EINT->SWINTE |= RTC_EINT_LINE_ALARM_EVENT) +/** + * @} + */ + +/* Include RTC DAL Extended module */ +#include "apm32f4xx_dal_rtc_ex.h" + +/* Exported functions --------------------------------------------------------*/ + +/** @addtogroup RTC_Exported_Functions + * @{ + */ + +/** @addtogroup RTC_Exported_Functions_Group1 + * @{ + */ +/* Initialization and de-initialization functions ****************************/ +DAL_StatusTypeDef DAL_RTC_Init(RTC_HandleTypeDef *hrtc); +DAL_StatusTypeDef DAL_RTC_DeInit(RTC_HandleTypeDef *hrtc); +void DAL_RTC_MspInit(RTC_HandleTypeDef *hrtc); +void DAL_RTC_MspDeInit(RTC_HandleTypeDef *hrtc); + +/* Callbacks Register/UnRegister functions ***********************************/ +#if (USE_DAL_RTC_REGISTER_CALLBACKS == 1) +DAL_StatusTypeDef DAL_RTC_RegisterCallback(RTC_HandleTypeDef *hrtc, DAL_RTC_CallbackIDTypeDef CallbackID, pRTC_CallbackTypeDef pCallback); +DAL_StatusTypeDef DAL_RTC_UnRegisterCallback(RTC_HandleTypeDef *hrtc, DAL_RTC_CallbackIDTypeDef CallbackID); +#endif /* USE_DAL_RTC_REGISTER_CALLBACKS */ +/** + * @} + */ + +/** @addtogroup RTC_Exported_Functions_Group2 + * @{ + */ +/* RTC Time and Date functions ************************************************/ +DAL_StatusTypeDef DAL_RTC_SetTime(RTC_HandleTypeDef *hrtc, RTC_TimeTypeDef *sTime, uint32_t Format); +DAL_StatusTypeDef DAL_RTC_GetTime(RTC_HandleTypeDef *hrtc, RTC_TimeTypeDef *sTime, uint32_t Format); +DAL_StatusTypeDef DAL_RTC_SetDate(RTC_HandleTypeDef *hrtc, RTC_DateTypeDef *sDate, uint32_t Format); +DAL_StatusTypeDef DAL_RTC_GetDate(RTC_HandleTypeDef *hrtc, RTC_DateTypeDef *sDate, uint32_t Format); +/** + * @} + */ + +/** @addtogroup RTC_Exported_Functions_Group3 + * @{ + */ +/* RTC Alarm functions ********************************************************/ +DAL_StatusTypeDef DAL_RTC_SetAlarm(RTC_HandleTypeDef *hrtc, RTC_AlarmTypeDef *sAlarm, uint32_t Format); +DAL_StatusTypeDef DAL_RTC_SetAlarm_IT(RTC_HandleTypeDef *hrtc, RTC_AlarmTypeDef *sAlarm, uint32_t Format); +DAL_StatusTypeDef DAL_RTC_DeactivateAlarm(RTC_HandleTypeDef *hrtc, uint32_t Alarm); +DAL_StatusTypeDef DAL_RTC_GetAlarm(RTC_HandleTypeDef *hrtc, RTC_AlarmTypeDef *sAlarm, uint32_t Alarm, uint32_t Format); +void DAL_RTC_AlarmIRQHandler(RTC_HandleTypeDef *hrtc); +DAL_StatusTypeDef DAL_RTC_PollForAlarmAEvent(RTC_HandleTypeDef *hrtc, uint32_t Timeout); +void DAL_RTC_AlarmAEventCallback(RTC_HandleTypeDef *hrtc); +/** + * @} + */ + +/** @addtogroup RTC_Exported_Functions_Group4 + * @{ + */ +/* Peripheral Control functions ***********************************************/ +DAL_StatusTypeDef DAL_RTC_WaitForSynchro(RTC_HandleTypeDef *hrtc); + +/* RTC Daylight Saving Time functions *****************************************/ +void DAL_RTC_DST_Add1Hour(RTC_HandleTypeDef *hrtc); +void DAL_RTC_DST_Sub1Hour(RTC_HandleTypeDef *hrtc); +void DAL_RTC_DST_SetStoreOperation(RTC_HandleTypeDef *hrtc); +void DAL_RTC_DST_ClearStoreOperation(RTC_HandleTypeDef *hrtc); +uint32_t DAL_RTC_DST_ReadStoreOperation(RTC_HandleTypeDef *hrtc); +/** + * @} + */ + +/** @addtogroup RTC_Exported_Functions_Group5 + * @{ + */ +/* Peripheral State functions *************************************************/ +DAL_RTCStateTypeDef DAL_RTC_GetState(RTC_HandleTypeDef *hrtc); +/** + * @} + */ + +/** + * @} + */ + +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ + +/** @defgroup RTC_Private_Constants RTC Private Constants + * @{ + */ +/* Masks Definition */ +#define RTC_TIME_RESERVED_MASK ((uint32_t)(RTC_TIME_HRT | RTC_TIME_HRU | \ + RTC_TIME_MINT | RTC_TIME_MINU | \ + RTC_TIME_SECT | RTC_TIME_SECU | \ + RTC_TIME_TIMEFCFG)) +#define RTC_DATE_RESERVED_MASK ((uint32_t)(RTC_DATE_YRT | RTC_DATE_YRU | \ + RTC_DATE_MONT | RTC_DATE_MONU | \ + RTC_DATE_DAYT | RTC_DATE_DAYU | \ + RTC_DATE_WEEKSEL)) +#define RTC_INIT_MASK 0xFFFFFFFFU +#define RTC_RSF_MASK ((uint32_t)~(RTC_STS_INITEN | RTC_STS_RSFLG)) +#define RTC_FLAGS_MASK ((uint32_t)(RTC_FLAG_INITF | RTC_FLAG_INITS | \ + RTC_FLAG_ALRAF | RTC_FLAG_ALRAWF | \ + RTC_FLAG_ALRBF | RTC_FLAG_ALRBWF | \ + RTC_FLAG_WUTF | RTC_FLAG_WUTWF | \ + RTC_FLAG_RECALPF | RTC_FLAG_SHPF | \ + RTC_FLAG_TSF | RTC_FLAG_TSOVF | \ + RTC_FLAG_RSF | RTC_TAMPER_FLAGS_MASK)) + +#define RTC_TIMEOUT_VALUE 1000U + +#define RTC_EINT_LINE_ALARM_EVENT EINT_IMASK_IMASK17 /*!< External interrupt line 17 Connected to the RTC Alarm event */ +/** + * @} + */ + +/* Private macros ------------------------------------------------------------*/ + +/** @defgroup RTC_Private_Macros RTC Private Macros + * @{ + */ + +/** @defgroup RTC_IS_RTC_Definitions RTC Private macros to check input parameters + * @{ + */ +#define IS_RTC_HOUR_FORMAT(FORMAT) (((FORMAT) == RTC_HOURFORMAT_12) || \ + ((FORMAT) == RTC_HOURFORMAT_24)) + +#define IS_RTC_OUTPUT(OUTPUT) (((OUTPUT) == RTC_OUTPUT_DISABLE) || \ + ((OUTPUT) == RTC_OUTPUT_ALARMA) || \ + ((OUTPUT) == RTC_OUTPUT_ALARMB) || \ + ((OUTPUT) == RTC_OUTPUT_WAKEUP)) + +#define IS_RTC_OUTPUT_POL(POL) (((POL) == RTC_OUTPUT_POLARITY_HIGH) || \ + ((POL) == RTC_OUTPUT_POLARITY_LOW)) + +#define IS_RTC_OUTPUT_TYPE(TYPE) (((TYPE) == RTC_OUTPUT_TYPE_OPENDRAIN) || \ + ((TYPE) == RTC_OUTPUT_TYPE_PUSHPULL)) + +#define IS_RTC_ASYNCH_PREDIV(PREDIV) ((PREDIV) <= 0x7FU) +#define IS_RTC_SYNCH_PREDIV(PREDIV) ((PREDIV) <= 0x7FFFU) + +#define IS_RTC_HOUR12(HOUR) (((HOUR) > 0U) && ((HOUR) <= 12U)) +#define IS_RTC_HOUR24(HOUR) ((HOUR) <= 23U) +#define IS_RTC_MINUTES(MINUTES) ((MINUTES) <= 59U) +#define IS_RTC_SECONDS(SECONDS) ((SECONDS) <= 59U) + +#define IS_RTC_HOURFORMAT12(PM) (((PM) == RTC_HOURFORMAT12_AM) || \ + ((PM) == RTC_HOURFORMAT12_PM)) + +#define IS_RTC_DAYLIGHT_SAVING(SAVE) (((SAVE) == RTC_DAYLIGHTSAVING_SUB1H) || \ + ((SAVE) == RTC_DAYLIGHTSAVING_ADD1H) || \ + ((SAVE) == RTC_DAYLIGHTSAVING_NONE)) + +#define IS_RTC_STORE_OPERATION(OPERATION) (((OPERATION) == RTC_STOREOPERATION_RESET) || \ + ((OPERATION) == RTC_STOREOPERATION_SET)) + +#define IS_RTC_FORMAT(FORMAT) (((FORMAT) == RTC_FORMAT_BIN) || ((FORMAT) == RTC_FORMAT_BCD)) + +#define IS_RTC_YEAR(YEAR) ((YEAR) <= 99U) +#define IS_RTC_MONTH(MONTH) (((MONTH) >= 1U) && ((MONTH) <= 12U)) +#define IS_RTC_DATE(DATE) (((DATE) >= 1U) && ((DATE) <= 31U)) + +#define IS_RTC_WEEKDAY(WEEKDAY) (((WEEKDAY) == RTC_WEEKDAY_MONDAY) || \ + ((WEEKDAY) == RTC_WEEKDAY_TUESDAY) || \ + ((WEEKDAY) == RTC_WEEKDAY_WEDNESDAY) || \ + ((WEEKDAY) == RTC_WEEKDAY_THURSDAY) || \ + ((WEEKDAY) == RTC_WEEKDAY_FRIDAY) || \ + ((WEEKDAY) == RTC_WEEKDAY_SATURDAY) || \ + ((WEEKDAY) == RTC_WEEKDAY_SUNDAY)) + +#define IS_RTC_ALARM_DATE_WEEKDAY_DATE(DATE) (((DATE) > 0U) && ((DATE) <= 31U)) + +#define IS_RTC_ALARM_DATE_WEEKDAY_WEEKDAY(WEEKDAY) (((WEEKDAY) == RTC_WEEKDAY_MONDAY) || \ + ((WEEKDAY) == RTC_WEEKDAY_TUESDAY) || \ + ((WEEKDAY) == RTC_WEEKDAY_WEDNESDAY) || \ + ((WEEKDAY) == RTC_WEEKDAY_THURSDAY) || \ + ((WEEKDAY) == RTC_WEEKDAY_FRIDAY) || \ + ((WEEKDAY) == RTC_WEEKDAY_SATURDAY) || \ + ((WEEKDAY) == RTC_WEEKDAY_SUNDAY)) + +#define IS_RTC_ALARM_DATE_WEEKDAY_SEL(SEL) (((SEL) == RTC_ALARMDATEWEEKDAYSEL_DATE) || \ + ((SEL) == RTC_ALARMDATEWEEKDAYSEL_WEEKDAY)) + +#define IS_RTC_ALARM_MASK(MASK) (((MASK) & ((uint32_t)~RTC_ALARMMASK_ALL)) == 0U) + +#define IS_RTC_ALARM(ALARM) (((ALARM) == RTC_ALARM_A) || ((ALARM) == RTC_ALARM_B)) + +#define IS_RTC_ALARM_SUB_SECOND_VALUE(VALUE) ((VALUE) <= RTC_ALRMASS_SUBSEC) + +#define IS_RTC_ALARM_SUB_SECOND_MASK(MASK) (((MASK) == RTC_ALARMSUBSECONDMASK_ALL) || \ + ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_1) || \ + ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_2) || \ + ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_3) || \ + ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_4) || \ + ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_5) || \ + ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_6) || \ + ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_7) || \ + ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_8) || \ + ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_9) || \ + ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_10) || \ + ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_11) || \ + ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_12) || \ + ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_13) || \ + ((MASK) == RTC_ALARMSUBSECONDMASK_SS14) || \ + ((MASK) == RTC_ALARMSUBSECONDMASK_NONE)) +/** + * @} + */ + +/** + * @} + */ + +/* Private functions ---------------------------------------------------------*/ + +/** @defgroup RTC_Private_Functions RTC Private Functions + * @{ + */ +DAL_StatusTypeDef RTC_EnterInitMode(RTC_HandleTypeDef *hrtc); +DAL_StatusTypeDef RTC_ExitInitMode(RTC_HandleTypeDef *hrtc); +uint8_t RTC_ByteToBcd2(uint8_t number); +uint8_t RTC_Bcd2ToByte(uint8_t number); +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* APM32F4xx_DAL_RTC_H */ diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_rtc_ex.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_rtc_ex.h new file mode 100644 index 0000000000..28f1de5a09 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_rtc_ex.h @@ -0,0 +1,1106 @@ +/** + * + * @file apm32f4xx_dal_rtc_ex.h + * @brief Header file of RTC DAL Extended module. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2017 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef APM32F4xx_DAL_RTC_EX_H +#define APM32F4xx_DAL_RTC_EX_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ + +#include "apm32f4xx_dal_def.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @addtogroup RTCEx + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ + +/** @defgroup RTCEx_Exported_Types RTCEx Exported Types + * @{ + */ + +/** + * @brief RTC Tamper structure definition + */ +typedef struct +{ + uint32_t Tamper; /*!< Specifies the Tamper Pin. + This parameter can be a value of @ref RTCEx_Tamper_Pin_Definitions */ + + uint32_t PinSelection; /*!< Specifies the Tamper Pin. + This parameter can be a value of @ref RTCEx_Tamper_Pin_Selection */ + + uint32_t Trigger; /*!< Specifies the Tamper Trigger. + This parameter can be a value of @ref RTCEx_Tamper_Trigger_Definitions */ + + uint32_t Filter; /*!< Specifies the RTC Filter Tamper. + This parameter can be a value of @ref RTCEx_Tamper_Filter_Definitions */ + + uint32_t SamplingFrequency; /*!< Specifies the sampling frequency. + This parameter can be a value of @ref RTCEx_Tamper_Sampling_Frequencies_Definitions */ + + uint32_t PrechargeDuration; /*!< Specifies the Precharge Duration . + This parameter can be a value of @ref RTCEx_Tamper_Pin_Precharge_Duration_Definitions */ + + uint32_t TamperPullUp; /*!< Specifies the Tamper PullUp . + This parameter can be a value of @ref RTCEx_Tamper_Pull_Up_Definitions */ + + uint32_t TimeStampOnTamperDetection; /*!< Specifies the TimeStampOnTamperDetection. + This parameter can be a value of @ref RTCEx_Tamper_TimeStampOnTamperDetection_Definitions */ +} RTC_TamperTypeDef; +/** + * @} + */ + +/* Exported constants --------------------------------------------------------*/ + +/** @defgroup RTCEx_Exported_Constants RTCEx Exported Constants + * @{ + */ + +/** @defgroup RTCEx_Backup_Registers_Definitions RTCEx Backup Registers Definitions + * @{ + */ +#define RTC_BKP_DR0 0x00000000U +#define RTC_BKP_DR1 0x00000001U +#define RTC_BKP_DR2 0x00000002U +#define RTC_BKP_DR3 0x00000003U +#define RTC_BKP_DR4 0x00000004U +#define RTC_BKP_DR5 0x00000005U +#define RTC_BKP_DR6 0x00000006U +#define RTC_BKP_DR7 0x00000007U +#define RTC_BKP_DR8 0x00000008U +#define RTC_BKP_DR9 0x00000009U +#define RTC_BKP_DR10 0x0000000AU +#define RTC_BKP_DR11 0x0000000BU +#define RTC_BKP_DR12 0x0000000CU +#define RTC_BKP_DR13 0x0000000DU +#define RTC_BKP_DR14 0x0000000EU +#define RTC_BKP_DR15 0x0000000FU +#define RTC_BKP_DR16 0x00000010U +#define RTC_BKP_DR17 0x00000011U +#define RTC_BKP_DR18 0x00000012U +#define RTC_BKP_DR19 0x00000013U +/** + * @} + */ + +/** @defgroup RTCEx_Timestamp_Edges_Definitions RTCEx Timestamp Edges Definitions + * @{ + */ +#define RTC_TIMESTAMPEDGE_RISING 0x00000000U +#define RTC_TIMESTAMPEDGE_FALLING RTC_CTRL_TSETECFG +/** + * @} + */ + +/** @defgroup RTCEx_Timestamp_Pin_Selection RTC Timestamp Pin Selection + * @{ + */ +#define RTC_TIMESTAMPPIN_DEFAULT 0x00000000U +#if defined(RTC_AF2_SUPPORT) +#define RTC_TIMESTAMPPIN_POS1 RTC_TACFG_TSMSEL +#endif /* RTC_AF2_SUPPORT */ +/** + * @} + */ + +/** @defgroup RTCEx_Tamper_Pin_Definitions RTCEx Tamper Pins Definitions + * @{ + */ +#define RTC_TAMPER_1 RTC_TACFG_TP1EN +#if defined(RTC_TAMPER2_SUPPORT) +#define RTC_TAMPER_2 RTC_TACFG_TP2EN +#endif /* RTC_TAMPER2_SUPPORT */ +/** + * @} + */ + +/** @defgroup RTCEx_Tamper_Pin_Selection RTC tamper Pins Selection + * @{ + */ +#define RTC_TAMPERPIN_DEFAULT 0x00000000U +#if defined(RTC_AF2_SUPPORT) +#define RTC_TAMPERPIN_POS1 RTC_TACFG_TP1MSEL +#endif /* RTC_AF2_SUPPORT */ +/** + * @} + */ + +/** @defgroup RTCEx_Tamper_Interrupt_Definitions RTCEx Tamper Interrupt Definitions + * @{ + */ +#define RTC_IT_TAMP RTC_TACFG_TPIEN /*!< Enable global Tamper Interrupt */ +#define RTC_IT_TAMP1 ((uint32_t)0x00020000) +#define RTC_IT_TAMP2 ((uint32_t)0x00040000) + +/** + * @} + */ + +/** @defgroup RTCEx_Tamper_Trigger_Definitions RTCEx Tamper Triggers Definitions + * @{ + */ +#define RTC_TAMPERTRIGGER_RISINGEDGE 0x00000000U +#define RTC_TAMPERTRIGGER_FALLINGEDGE RTC_TACFG_TP1ALCFG +#define RTC_TAMPERTRIGGER_LOWLEVEL RTC_TAMPERTRIGGER_RISINGEDGE +#define RTC_TAMPERTRIGGER_HIGHLEVEL RTC_TAMPERTRIGGER_FALLINGEDGE +/** + * @} + */ + +/** @defgroup RTCEx_Tamper_Filter_Definitions RTCEx Tamper Filter Definitions + * @{ + */ +#define RTC_TAMPERFILTER_DISABLE 0x00000000U /*!< Tamper filter is disabled */ + +#define RTC_TAMPERFILTER_2SAMPLE RTC_TACFG_TPFCSEL_0 /*!< Tamper is activated after 2 + consecutive samples at the active level */ +#define RTC_TAMPERFILTER_4SAMPLE RTC_TACFG_TPFCSEL_1 /*!< Tamper is activated after 4 + consecutive samples at the active level */ +#define RTC_TAMPERFILTER_8SAMPLE RTC_TACFG_TPFCSEL /*!< Tamper is activated after 8 + consecutive samples at the active level */ +#define RTC_TAMPERFILTER_MASK RTC_TACFG_TPFCSEL /*!< Masking all bits except those of + field TAMPFLT */ +/** + * @} + */ + +/** @defgroup RTCEx_Tamper_Sampling_Frequencies_Definitions RTCEx Tamper Sampling Frequencies Definitions + * @{ + */ +#define RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV32768 0x00000000U /*!< Each of the tamper inputs are sampled + with a frequency = RTCCLK / 32768 */ +#define RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV16384 RTC_TACFG_TPSFSEL_0 /*!< Each of the tamper inputs are sampled + with a frequency = RTCCLK / 16384 */ +#define RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV8192 RTC_TACFG_TPSFSEL_1 /*!< Each of the tamper inputs are sampled + with a frequency = RTCCLK / 8192 */ +#define RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV4096 (RTC_TACFG_TPSFSEL_0 | RTC_TACFG_TPSFSEL_1) /*!< Each of the tamper inputs are sampled + with a frequency = RTCCLK / 4096 */ +#define RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV2048 RTC_TACFG_TPSFSEL_2 /*!< Each of the tamper inputs are sampled + with a frequency = RTCCLK / 2048 */ +#define RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV1024 (RTC_TACFG_TPSFSEL_0 | RTC_TACFG_TPSFSEL_2) /*!< Each of the tamper inputs are sampled + with a frequency = RTCCLK / 1024 */ +#define RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV512 (RTC_TACFG_TPSFSEL_1 | RTC_TACFG_TPSFSEL_2) /*!< Each of the tamper inputs are sampled + with a frequency = RTCCLK / 512 */ +#define RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV256 RTC_TACFG_TPSFSEL /*!< Each of the tamper inputs are sampled + with a frequency = RTCCLK / 256 */ +#define RTC_TAMPERSAMPLINGFREQ_RTCCLK_MASK RTC_TACFG_TPSFSEL /*!< Masking all bits except those of + field TAMPFREQ */ +/** + * @} + */ + +/** @defgroup RTCEx_Tamper_Pin_Precharge_Duration_Definitions RTCEx Tamper Pin Precharge Duration Definitions + * @{ + */ +#define RTC_TAMPERPRECHARGEDURATION_1RTCCLK 0x00000000U /*!< Tamper pins are pre-charged before + sampling during 1 RTCCLK cycle */ +#define RTC_TAMPERPRECHARGEDURATION_2RTCCLK RTC_TACFG_TPPRDUSEL_0 /*!< Tamper pins are pre-charged before + sampling during 2 RTCCLK cycles */ +#define RTC_TAMPERPRECHARGEDURATION_4RTCCLK RTC_TACFG_TPPRDUSEL_1 /*!< Tamper pins are pre-charged before + sampling during 4 RTCCLK cycles */ +#define RTC_TAMPERPRECHARGEDURATION_8RTCCLK RTC_TACFG_TPPRDUSEL /*!< Tamper pins are pre-charged before + sampling during 8 RTCCLK cycles */ +#define RTC_TAMPERPRECHARGEDURATION_MASK RTC_TACFG_TPPRDUSEL /*!< Masking all bits except those of + field TAMPPRCH */ +/** + * @} + */ + +/** @defgroup RTCEx_Tamper_Pull_Up_Definitions RTCEx Tamper Pull Up Definitions + * @{ + */ +#define RTC_TAMPER_PULLUP_ENABLE 0x00000000U /*!< Tamper pins are pre-charged before sampling */ +#define RTC_TAMPER_PULLUP_DISABLE RTC_TACFG_TPPUDIS /*!< Tamper pins are not pre-charged before sampling */ +#define RTC_TAMPER_PULLUP_MASK RTC_TACFG_TPPUDIS /*!< Masking all bits except bit TAMPPUDIS */ +/** + * @} + */ + +/** @defgroup RTCEx_Tamper_TimeStampOnTamperDetection_Definitions RTCEx Tamper TimeStamp On Tamper Detection Definitions + * @{ + */ +#define RTC_TIMESTAMPONTAMPERDETECTION_ENABLE RTC_TACFG_TPTSEN /*!< TimeStamp on Tamper Detection event saved */ +#define RTC_TIMESTAMPONTAMPERDETECTION_DISABLE 0x00000000U /*!< TimeStamp on Tamper Detection event is not saved */ +#define RTC_TIMESTAMPONTAMPERDETECTION_MASK RTC_TACFG_TPTSEN /*!< Masking all bits except bit TAMPTS */ +/** + * @} + */ + +/** @defgroup RTCEx_Wakeup_Timer_Definitions RTCEx Wakeup Timer Definitions + * @{ + */ +#define RTC_WAKEUPCLOCK_RTCCLK_DIV16 0x00000000U +#define RTC_WAKEUPCLOCK_RTCCLK_DIV8 RTC_CTRL_WUCLKSEL_0 +#define RTC_WAKEUPCLOCK_RTCCLK_DIV4 RTC_CTRL_WUCLKSEL_1 +#define RTC_WAKEUPCLOCK_RTCCLK_DIV2 (RTC_CTRL_WUCLKSEL_0 | RTC_CTRL_WUCLKSEL_1) +#define RTC_WAKEUPCLOCK_CK_SPRE_16BITS RTC_CTRL_WUCLKSEL_2 +#define RTC_WAKEUPCLOCK_CK_SPRE_17BITS (RTC_CTRL_WUCLKSEL_1 | RTC_CTRL_WUCLKSEL_2) +/** + * @} + */ + +/** @defgroup RTCEx_Coarse_Calibration_Definitions RTCEx Coarse Calib Definitions + * @{ + */ +#define RTC_CALIBSIGN_POSITIVE 0x00000000U +#define RTC_CALIBSIGN_NEGATIVE RTC_DCAL_DCALCFG +/** + * @} + */ + +/** @defgroup RTCEx_Smooth_calib_period_Definitions RTCEx Smooth Calib Period Definitions + * @{ + */ +#define RTC_SMOOTHCALIB_PERIOD_32SEC 0x00000000U /*!< If RTCCLK = 32768 Hz, smooth calibration + period is 32s, otherwise 2^20 RTCCLK pulses */ +#define RTC_SMOOTHCALIB_PERIOD_16SEC RTC_CAL_CAL16CFG /*!< If RTCCLK = 32768 Hz, smooth calibration + period is 16s, otherwise 2^19 RTCCLK pulses */ +#define RTC_SMOOTHCALIB_PERIOD_8SEC RTC_CAL_CAL8CFG /*!< If RTCCLK = 32768 Hz, smooth calibration + period is 8s, otherwise 2^18 RTCCLK pulses */ +/** + * @} + */ + +/** @defgroup RTCEx_Smooth_calib_Plus_pulses_Definitions RTCEx Smooth Calib Plus Pulses Definitions + * @{ + */ +#define RTC_SMOOTHCALIB_PLUSPULSES_SET RTC_CAL_ICALFEN /*!< The number of RTCCLK pulses added + during a X -second window = Y - CALM[8:0] + with Y = 512, 256, 128 when X = 32, 16, 8 */ +#define RTC_SMOOTHCALIB_PLUSPULSES_RESET 0x00000000U /*!< The number of RTCCLK pulses subbstited + during a 32-second window = CALM[8:0] */ +/** + * @} + */ + +/** @defgroup RTCEx_Add_1_Second_Parameter_Definitions RTCEx Add 1 Second Parameter Definitions + * @{ + */ +#define RTC_SHIFTADD1S_RESET 0x00000000U +#define RTC_SHIFTADD1S_SET RTC_SHIFT_ADD1SECEN +/** + * @} + */ + +/** @defgroup RTCEx_Calib_Output_selection_Definitions RTCEx Calib Output Selection Definitions + * @{ + */ +#define RTC_CALIBOUTPUT_512HZ 0x00000000U +#define RTC_CALIBOUTPUT_1HZ RTC_CTRL_CALOSEL +/** + * @} + */ + +/** + * @} + */ + +/* Exported macros -----------------------------------------------------------*/ + +/** @defgroup RTCEx_Exported_Macros RTCEx Exported Macros + * @{ + */ + +/* ---------------------------------WAKEUPTIMER-------------------------------*/ + +/** @defgroup RTCEx_WakeUp_Timer RTCEx WakeUp Timer + * @{ + */ + +/** + * @brief Enable the RTC WakeUp Timer peripheral. + * @param __HANDLE__ specifies the RTC handle. + * @retval None + */ +#define __DAL_RTC_WAKEUPTIMER_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CTRL |= (RTC_CTRL_WUTEN)) + +/** + * @brief Disable the RTC Wakeup Timer peripheral. + * @param __HANDLE__ specifies the RTC handle. + * @retval None + */ +#define __DAL_RTC_WAKEUPTIMER_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CTRL &= ~(RTC_CTRL_WUTEN)) + +/** + * @brief Enable the RTC Wakeup Timer interrupt. + * @param __HANDLE__ specifies the RTC handle. + * @param __INTERRUPT__ specifies the RTC Wakeup Timer interrupt sources to be enabled or disabled. + * This parameter can be: + * @arg RTC_IT_WUT: Wakeup Timer interrupt + * @retval None + */ +#define __DAL_RTC_WAKEUPTIMER_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CTRL |= (__INTERRUPT__)) + +/** + * @brief Disable the RTC Wakeup Timer interrupt. + * @param __HANDLE__ specifies the RTC handle. + * @param __INTERRUPT__ specifies the RTC Wakeup Timer interrupt sources to be enabled or disabled. + * This parameter can be: + * @arg RTC_IT_WUT: Wakeup Timer interrupt + * @retval None + */ +#define __DAL_RTC_WAKEUPTIMER_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CTRL &= ~(__INTERRUPT__)) + +/** + * @brief Check whether the specified RTC Wakeup Timer interrupt has occurred or not. + * @param __HANDLE__ specifies the RTC handle. + * @param __INTERRUPT__ specifies the RTC Wakeup Timer interrupt to check. + * This parameter can be: + * @arg RTC_IT_WUT: Wakeup Timer interrupt + * @retval None + */ +#define __DAL_RTC_WAKEUPTIMER_GET_IT(__HANDLE__, __INTERRUPT__) (((((__HANDLE__)->Instance->STS) & ((__INTERRUPT__) >> 4U)) != 0U) ? 1U : 0U) + +/** + * @brief Check whether the specified RTC Wakeup timer interrupt has been enabled or not. + * @param __HANDLE__ specifies the RTC handle. + * @param __INTERRUPT__ specifies the RTC Wakeup timer interrupt sources to check. + * This parameter can be: + * @arg RTC_IT_WUT: WakeUpTimer interrupt + * @retval None + */ +#define __DAL_RTC_WAKEUPTIMER_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) (((((__HANDLE__)->Instance->CTRL) & (__INTERRUPT__)) != 0U) ? 1U : 0U) + +/** + * @brief Get the selected RTC Wakeup Timer's flag status. + * @param __HANDLE__ specifies the RTC handle. + * @param __FLAG__ specifies the RTC Wakeup Timer flag to check. + * This parameter can be: + * @arg RTC_FLAG_WUTF: Wakeup Timer interrupt flag + * @arg RTC_FLAG_WUTWF: Wakeup Timer 'write allowed' flag + * @retval None + */ +#define __DAL_RTC_WAKEUPTIMER_GET_FLAG(__HANDLE__, __FLAG__) (((((__HANDLE__)->Instance->STS) & (__FLAG__)) != 0U)? 1U : 0U) + +/** + * @brief Clear the RTC Wakeup timer's pending flags. + * @param __HANDLE__ specifies the RTC handle. + * @param __FLAG__ specifies the RTC Wakeup Timer Flag to clear. + * This parameter can be: + * @arg RTC_FLAG_WUTF: Wakeup Timer interrupt Flag + * @retval None + */ +#define __DAL_RTC_WAKEUPTIMER_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->STS) = (~((__FLAG__) | RTC_STS_INITEN)|((__HANDLE__)->Instance->STS & RTC_STS_INITEN)) + +/** + * @brief Enable interrupt on the RTC Wakeup Timer associated EINT line. + * @retval None + */ +#define __DAL_RTC_WAKEUPTIMER_EINT_ENABLE_IT() (EINT->IMASK |= RTC_EINT_LINE_WAKEUPTIMER_EVENT) + +/** + * @brief Disable interrupt on the RTC Wakeup Timer associated EINT line. + * @retval None + */ +#define __DAL_RTC_WAKEUPTIMER_EINT_DISABLE_IT() (EINT->IMASK &= ~RTC_EINT_LINE_WAKEUPTIMER_EVENT) + +/** + * @brief Enable event on the RTC Wakeup Timer associated EINT line. + * @retval None. + */ +#define __DAL_RTC_WAKEUPTIMER_EINT_ENABLE_EVENT() (EINT->EMASK |= RTC_EINT_LINE_WAKEUPTIMER_EVENT) + +/** + * @brief Disable event on the RTC Wakeup Timer associated EINT line. + * @retval None. + */ +#define __DAL_RTC_WAKEUPTIMER_EINT_DISABLE_EVENT() (EINT->EMASK &= ~RTC_EINT_LINE_WAKEUPTIMER_EVENT) + +/** + * @brief Enable falling edge trigger on the RTC Wakeup Timer associated EINT line. + * @retval None. + */ +#define __DAL_RTC_WAKEUPTIMER_EINT_ENABLE_FALLING_EDGE() (EINT->FTEN |= RTC_EINT_LINE_WAKEUPTIMER_EVENT) + +/** + * @brief Disable falling edge trigger on the RTC Wakeup Timer associated EINT line. + * @retval None. + */ +#define __DAL_RTC_WAKEUPTIMER_EINT_DISABLE_FALLING_EDGE() (EINT->FTEN &= ~RTC_EINT_LINE_WAKEUPTIMER_EVENT) + +/** + * @brief Enable rising edge trigger on the RTC Wakeup Timer associated EINT line. + * @retval None. + */ +#define __DAL_RTC_WAKEUPTIMER_EINT_ENABLE_RISING_EDGE() (EINT->RTEN |= RTC_EINT_LINE_WAKEUPTIMER_EVENT) + +/** + * @brief Disable rising edge trigger on the RTC Wakeup Timer associated EINT line. + * @retval None. + */ +#define __DAL_RTC_WAKEUPTIMER_EINT_DISABLE_RISING_EDGE() (EINT->RTEN &= ~RTC_EINT_LINE_WAKEUPTIMER_EVENT) + +/** + * @brief Enable rising & falling edge trigger on the RTC Wakeup Timer associated EINT line. + * @retval None. + */ +#define __DAL_RTC_WAKEUPTIMER_EINT_ENABLE_RISING_FALLING_EDGE() do { \ + __DAL_RTC_WAKEUPTIMER_EINT_ENABLE_RISING_EDGE(); \ + __DAL_RTC_WAKEUPTIMER_EINT_ENABLE_FALLING_EDGE(); \ + } while(0U) + +/** + * @brief Disable rising & falling edge trigger on the RTC Wakeup Timer associated EINT line. + * This parameter can be: + * @retval None. + */ +#define __DAL_RTC_WAKEUPTIMER_EINT_DISABLE_RISING_FALLING_EDGE() do { \ + __DAL_RTC_WAKEUPTIMER_EINT_DISABLE_RISING_EDGE(); \ + __DAL_RTC_WAKEUPTIMER_EINT_DISABLE_FALLING_EDGE(); \ + } while(0U) + +/** + * @brief Check whether the RTC Wakeup Timer associated EINT line interrupt flag is set or not. + * @retval Line Status. + */ +#define __DAL_RTC_WAKEUPTIMER_EINT_GET_FLAG() (EINT->IPEND & RTC_EINT_LINE_WAKEUPTIMER_EVENT) + +/** + * @brief Clear the RTC Wakeup Timer associated EINT line flag. + * @retval None. + */ +#define __DAL_RTC_WAKEUPTIMER_EINT_CLEAR_FLAG() (EINT->IPEND = RTC_EINT_LINE_WAKEUPTIMER_EVENT) + +/** + * @brief Generate a Software interrupt on the RTC Wakeup Timer associated EINT line. + * @retval None. + */ +#define __DAL_RTC_WAKEUPTIMER_EINT_GENERATE_SWIT() (EINT->SWINTE |= RTC_EINT_LINE_WAKEUPTIMER_EVENT) + +/** + * @} + */ + +/* ---------------------------------TIMESTAMP---------------------------------*/ + +/** @defgroup RTCEx_Timestamp RTCEx Timestamp + * @{ + */ + +/** + * @brief Enable the RTC Timestamp peripheral. + * @param __HANDLE__ specifies the RTC handle. + * @retval None + */ +#define __DAL_RTC_TIMESTAMP_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CTRL |= (RTC_CTRL_TSEN)) + +/** + * @brief Disable the RTC Timestamp peripheral. + * @param __HANDLE__ specifies the RTC handle. + * @retval None + */ +#define __DAL_RTC_TIMESTAMP_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CTRL &= ~(RTC_CTRL_TSEN)) + +/** + * @brief Enable the RTC Timestamp interrupt. + * @param __HANDLE__ specifies the RTC handle. + * @param __INTERRUPT__ specifies the RTC Timestamp interrupt sources to be enabled or disabled. + * This parameter can be: + * @arg RTC_IT_TS: TimeStamp interrupt + * @retval None + */ +#define __DAL_RTC_TIMESTAMP_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CTRL |= (__INTERRUPT__)) + +/** + * @brief Disable the RTC Timestamp interrupt. + * @param __HANDLE__ specifies the RTC handle. + * @param __INTERRUPT__ specifies the RTC Timestamp interrupt sources to be enabled or disabled. + * This parameter can be: + * @arg RTC_IT_TS: TimeStamp interrupt + * @retval None + */ +#define __DAL_RTC_TIMESTAMP_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CTRL &= ~(__INTERRUPT__)) + +/** + * @brief Check whether the specified RTC Timestamp interrupt has occurred or not. + * @param __HANDLE__ specifies the RTC handle. + * @param __INTERRUPT__ specifies the RTC Timestamp interrupt to check. + * This parameter can be: + * @arg RTC_IT_TS: TimeStamp interrupt + * @retval None + */ +#define __DAL_RTC_TIMESTAMP_GET_IT(__HANDLE__, __INTERRUPT__) (((((__HANDLE__)->Instance->STS) & ((__INTERRUPT__) >> 4U)) != 0U) ? 1U : 0U) + +/** + * @brief Check whether the specified RTC Timestamp interrupt has been enabled or not. + * @param __HANDLE__ specifies the RTC handle. + * @param __INTERRUPT__ specifies the RTC Timestamp interrupt source to check. + * This parameter can be: + * @arg RTC_IT_TS: TimeStamp interrupt + * @retval None + */ +#define __DAL_RTC_TIMESTAMP_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) (((((__HANDLE__)->Instance->CTRL) & (__INTERRUPT__)) != 0U) ? 1U : 0U) + +/** + * @brief Get the selected RTC Timestamp's flag status. + * @param __HANDLE__ specifies the RTC handle. + * @param __FLAG__ specifies the RTC Timestamp flag to check. + * This parameter can be: + * @arg RTC_FLAG_TSF: Timestamp interrupt flag + * @arg RTC_FLAG_TSOVF: Timestamp overflow flag + * @retval None + */ +#define __DAL_RTC_TIMESTAMP_GET_FLAG(__HANDLE__, __FLAG__) (((((__HANDLE__)->Instance->STS) & (__FLAG__)) != 0U)? 1U : 0U) + +/** + * @brief Clear the RTC Timestamp's pending flags. + * @param __HANDLE__ specifies the RTC handle. + * @param __FLAG__ specifies the RTC Timestamp flag to clear. + * This parameter can be: + * @arg RTC_FLAG_TSF: Timestamp interrupt flag + * @arg RTC_FLAG_TSOVF: Timestamp overflow flag + * @retval None + */ +#define __DAL_RTC_TIMESTAMP_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->STS) = (~((__FLAG__) | RTC_STS_INITEN)|((__HANDLE__)->Instance->STS & RTC_STS_INITEN)) + +/** + * @} + */ + +/* ---------------------------------TAMPER------------------------------------*/ + +/** @defgroup RTCEx_Tamper RTCEx Tamper + * @{ + */ + +/** + * @brief Enable the RTC Tamper1 input detection. + * @param __HANDLE__ specifies the RTC handle. + * @retval None + */ +#define __DAL_RTC_TAMPER1_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->TACFG |= (RTC_TACFG_TP1EN)) + +/** + * @brief Disable the RTC Tamper1 input detection. + * @param __HANDLE__ specifies the RTC handle. + * @retval None + */ +#define __DAL_RTC_TAMPER1_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->TACFG &= ~(RTC_TACFG_TP1EN)) + +#if defined(RTC_TAMPER2_SUPPORT) +/** + * @brief Enable the RTC Tamper2 input detection. + * @param __HANDLE__ specifies the RTC handle. + * @retval None + */ +#define __DAL_RTC_TAMPER2_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->TACFG |= (RTC_TACFG_TP2EN)) + +/** + * @brief Disable the RTC Tamper2 input detection. + * @param __HANDLE__ specifies the RTC handle. + * @retval None + */ +#define __DAL_RTC_TAMPER2_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->TACFG &= ~(RTC_TACFG_TP2EN)) +#endif /* RTC_TAMPER2_SUPPORT */ + +/** + * @brief Enable the RTC Tamper interrupt. + * @param __HANDLE__ specifies the RTC handle. + * @param __INTERRUPT__ specifies the RTC Tamper interrupt sources to be enabled. + * This parameter can be any combination of the following values: + * @arg RTC_IT_TAMP: Tamper global interrupt + * @retval None + */ +#define __DAL_RTC_TAMPER_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->TACFG |= (__INTERRUPT__)) + +/** + * @brief Disable the RTC Tamper interrupt. + * @param __HANDLE__ specifies the RTC handle. + * @param __INTERRUPT__ specifies the RTC Tamper interrupt sources to be disabled. + * This parameter can be any combination of the following values: + * @arg RTC_IT_TAMP: Tamper global interrupt + * @retval None + */ +#define __DAL_RTC_TAMPER_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->TACFG &= ~(__INTERRUPT__)) + +/** + * @brief Check whether the specified RTC Tamper interrupt has occurred or not. + * @param __HANDLE__ specifies the RTC handle. + * @param __INTERRUPT__ specifies the RTC Tamper interrupt to check. + * This parameter can be: + * @arg RTC_IT_TAMP1: Tamper 1 interrupt + * @arg RTC_IT_TAMP2: Tamper 2 interrupt + * @note RTC_IT_TAMP2 is not applicable to all devices. + * @retval None + */ +#define __DAL_RTC_TAMPER_GET_IT(__HANDLE__, __INTERRUPT__) (((((__HANDLE__)->Instance->STS) & ((__INTERRUPT__) >> 4U)) != 0U) ? 1U : 0U) + +/** + * @brief Check whether the specified RTC Tamper interrupt has been enabled or not. + * @param __HANDLE__ specifies the RTC handle. + * @param __INTERRUPT__ specifies the RTC Tamper interrupt source to check. + * This parameter can be: + * @arg RTC_IT_TAMP: Tamper global interrupt + * @retval None + */ +#define __DAL_RTC_TAMPER_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) (((((__HANDLE__)->Instance->TACFG) & (__INTERRUPT__)) != 0U) ? 1U : 0U) + +/** + * @brief Get the selected RTC Tamper's flag status. + * @param __HANDLE__ specifies the RTC handle. + * @param __FLAG__ specifies the RTC Tamper flag to be checked. + * This parameter can be: + * @arg RTC_FLAG_TAMP1F: Tamper 1 interrupt flag + * @arg RTC_FLAG_TAMP2F: Tamper 2 interrupt flag + * @note RTC_FLAG_TAMP2F is not applicable to all devices. + * @retval None + */ +#define __DAL_RTC_TAMPER_GET_FLAG(__HANDLE__, __FLAG__) (((((__HANDLE__)->Instance->STS) & (__FLAG__)) != 0U)? 1U : 0U) + +/** + * @brief Clear the RTC Tamper's pending flags. + * @param __HANDLE__ specifies the RTC handle. + * @param __FLAG__ specifies the RTC Tamper Flag to clear. + * This parameter can be: + * @arg RTC_FLAG_TAMP1F: Tamper 1 interrupt flag + * @arg RTC_FLAG_TAMP2F: Tamper 2 interrupt flag + * @note RTC_FLAG_TAMP2F is not applicable to all devices. + * @retval None + */ +#define __DAL_RTC_TAMPER_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->STS) = (~((__FLAG__) | RTC_STS_INITEN)|((__HANDLE__)->Instance->STS & RTC_STS_INITEN)) +/** + * @} + */ + +/* --------------------------TAMPER/TIMESTAMP---------------------------------*/ +/** @defgroup RTCEx_Tamper_Timestamp EINT RTC Tamper Timestamp EINT + * @{ + */ + +/** + * @brief Enable interrupt on the RTC Tamper and Timestamp associated EINT line. + * @retval None + */ +#define __DAL_RTC_TAMPER_TIMESTAMP_EINT_ENABLE_IT() (EINT->IMASK |= RTC_EINT_LINE_TAMPER_TIMESTAMP_EVENT) + +/** + * @brief Disable interrupt on the RTC Tamper and Timestamp associated EINT line. + * @retval None + */ +#define __DAL_RTC_TAMPER_TIMESTAMP_EINT_DISABLE_IT() (EINT->IMASK &= ~RTC_EINT_LINE_TAMPER_TIMESTAMP_EVENT) + +/** + * @brief Enable event on the RTC Tamper and Timestamp associated EINT line. + * @retval None. + */ +#define __DAL_RTC_TAMPER_TIMESTAMP_EINT_ENABLE_EVENT() (EINT->EMASK |= RTC_EINT_LINE_TAMPER_TIMESTAMP_EVENT) + +/** + * @brief Disable event on the RTC Tamper and Timestamp associated EINT line. + * @retval None. + */ +#define __DAL_RTC_TAMPER_TIMESTAMP_EINT_DISABLE_EVENT() (EINT->EMASK &= ~RTC_EINT_LINE_TAMPER_TIMESTAMP_EVENT) + +/** + * @brief Enable falling edge trigger on the RTC Tamper and Timestamp associated EINT line. + * @retval None. + */ +#define __DAL_RTC_TAMPER_TIMESTAMP_EINT_ENABLE_FALLING_EDGE() (EINT->FTEN |= RTC_EINT_LINE_TAMPER_TIMESTAMP_EVENT) + +/** + * @brief Disable falling edge trigger on the RTC Tamper and Timestamp associated EINT line. + * @retval None. + */ +#define __DAL_RTC_TAMPER_TIMESTAMP_EINT_DISABLE_FALLING_EDGE() (EINT->FTEN &= ~RTC_EINT_LINE_TAMPER_TIMESTAMP_EVENT) + +/** + * @brief Enable rising edge trigger on the RTC Tamper and Timestamp associated EINT line. + * @retval None. + */ +#define __DAL_RTC_TAMPER_TIMESTAMP_EINT_ENABLE_RISING_EDGE() (EINT->RTEN |= RTC_EINT_LINE_TAMPER_TIMESTAMP_EVENT) + +/** + * @brief Disable rising edge trigger on the RTC Tamper and Timestamp associated EINT line. + * @retval None. + */ +#define __DAL_RTC_TAMPER_TIMESTAMP_EINT_DISABLE_RISING_EDGE() (EINT->RTEN &= ~RTC_EINT_LINE_TAMPER_TIMESTAMP_EVENT) + +/** + * @brief Enable rising & falling edge trigger on the RTC Tamper and Timestamp associated EINT line. + * @retval None. + */ +#define __DAL_RTC_TAMPER_TIMESTAMP_EINT_ENABLE_RISING_FALLING_EDGE() do { \ + __DAL_RTC_TAMPER_TIMESTAMP_EINT_ENABLE_RISING_EDGE(); \ + __DAL_RTC_TAMPER_TIMESTAMP_EINT_ENABLE_FALLING_EDGE(); \ + } while(0U) + +/** + * @brief Disable rising & falling edge trigger on the RTC Tamper and Timestamp associated EINT line. + * This parameter can be: + * @retval None. + */ +#define __DAL_RTC_TAMPER_TIMESTAMP_EINT_DISABLE_RISING_FALLING_EDGE() do { \ + __DAL_RTC_TAMPER_TIMESTAMP_EINT_DISABLE_RISING_EDGE(); \ + __DAL_RTC_TAMPER_TIMESTAMP_EINT_DISABLE_FALLING_EDGE(); \ + } while(0U) + +/** + * @brief Check whether the RTC Tamper and Timestamp associated EINT line interrupt flag is set or not. + * @retval Line Status. + */ +#define __DAL_RTC_TAMPER_TIMESTAMP_EINT_GET_FLAG() (EINT->IPEND & RTC_EINT_LINE_TAMPER_TIMESTAMP_EVENT) + +/** + * @brief Clear the RTC Tamper and Timestamp associated EINT line flag. + * @retval None. + */ +#define __DAL_RTC_TAMPER_TIMESTAMP_EINT_CLEAR_FLAG() (EINT->IPEND = RTC_EINT_LINE_TAMPER_TIMESTAMP_EVENT) + +/** + * @brief Generate a Software interrupt on the RTC Tamper and Timestamp associated EINT line + * @retval None. + */ +#define __DAL_RTC_TAMPER_TIMESTAMP_EINT_GENERATE_SWIT() (EINT->SWINTE |= RTC_EINT_LINE_TAMPER_TIMESTAMP_EVENT) +/** + * @} + */ + +/* ------------------------------CALIBRATION----------------------------------*/ + +/** @defgroup RTCEx_Calibration RTCEx Calibration + * @{ + */ + +/** + * @brief Enable the Coarse calibration process. + * @param __HANDLE__ specifies the RTC handle. + * @retval None + */ +#define __DAL_RTC_COARSE_CALIB_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CTRL |= (RTC_CTRL_DCALEN)) + +/** + * @brief Disable the Coarse calibration process. + * @param __HANDLE__ specifies the RTC handle. + * @retval None + */ +#define __DAL_RTC_COARSE_CALIB_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CTRL &= ~(RTC_CTRL_DCALEN)) + +/** + * @brief Enable the RTC calibration output. + * @param __HANDLE__ specifies the RTC handle. + * @retval None + */ +#define __DAL_RTC_DCALATION_OUTPUT_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CTRL |= (RTC_CTRL_CALOEN)) + +/** + * @brief Disable the calibration output. + * @param __HANDLE__ specifies the RTC handle. + * @retval None + */ +#define __DAL_RTC_DCALATION_OUTPUT_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CTRL &= ~(RTC_CTRL_CALOEN)) + +/** + * @brief Enable the clock reference detection. + * @param __HANDLE__ specifies the RTC handle. + * @retval None + */ +#define __DAL_RTC_CLOCKREF_DETECTION_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CTRL |= (RTC_CTRL_RCLKDEN)) + +/** + * @brief Disable the clock reference detection. + * @param __HANDLE__ specifies the RTC handle. + * @retval None + */ +#define __DAL_RTC_CLOCKREF_DETECTION_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CTRL &= ~(RTC_CTRL_RCLKDEN)) + +/** + * @brief Get the selected RTC shift operation's flag status. + * @param __HANDLE__ specifies the RTC handle. + * @param __FLAG__ specifies the RTC shift operation Flag is pending or not. + * This parameter can be: + * @arg RTC_FLAG_SHPF: Shift pending flag + * @retval None + */ +#define __DAL_RTC_SHIFT_GET_FLAG(__HANDLE__, __FLAG__) (((((__HANDLE__)->Instance->STS) & (__FLAG__)) != 0U)? 1U : 0U) +/** + * @} + */ + +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ + +/** @defgroup RTCEx_Exported_Functions RTCEx Exported Functions + * @{ + */ + +/** @addtogroup RTCEx_Exported_Functions_Group1 + * @{ + */ +/* RTC Timestamp and Tamper functions *****************************************/ +DAL_StatusTypeDef DAL_RTCEx_SetTimeStamp(RTC_HandleTypeDef *hrtc, uint32_t RTC_TimeStampEdge, uint32_t RTC_TimeStampPin); +DAL_StatusTypeDef DAL_RTCEx_SetTimeStamp_IT(RTC_HandleTypeDef *hrtc, uint32_t RTC_TimeStampEdge, uint32_t RTC_TimeStampPin); +DAL_StatusTypeDef DAL_RTCEx_DeactivateTimeStamp(RTC_HandleTypeDef *hrtc); +DAL_StatusTypeDef DAL_RTCEx_GetTimeStamp(RTC_HandleTypeDef *hrtc, RTC_TimeTypeDef *sTimeStamp, RTC_DateTypeDef *sTimeStampDate, uint32_t Format); + +DAL_StatusTypeDef DAL_RTCEx_SetTamper(RTC_HandleTypeDef *hrtc, RTC_TamperTypeDef *sTamper); +DAL_StatusTypeDef DAL_RTCEx_SetTamper_IT(RTC_HandleTypeDef *hrtc, RTC_TamperTypeDef *sTamper); +DAL_StatusTypeDef DAL_RTCEx_DeactivateTamper(RTC_HandleTypeDef *hrtc, uint32_t Tamper); +void DAL_RTCEx_TamperTimeStampIRQHandler(RTC_HandleTypeDef *hrtc); + +void DAL_RTCEx_Tamper1EventCallback(RTC_HandleTypeDef *hrtc); +#if defined(RTC_TAMPER2_SUPPORT) +void DAL_RTCEx_Tamper2EventCallback(RTC_HandleTypeDef *hrtc); +#endif /* RTC_TAMPER2_SUPPORT */ +void DAL_RTCEx_TimeStampEventCallback(RTC_HandleTypeDef *hrtc); +DAL_StatusTypeDef DAL_RTCEx_PollForTimeStampEvent(RTC_HandleTypeDef *hrtc, uint32_t Timeout); +DAL_StatusTypeDef DAL_RTCEx_PollForTamper1Event(RTC_HandleTypeDef *hrtc, uint32_t Timeout); +#if defined(RTC_TAMPER2_SUPPORT) +DAL_StatusTypeDef DAL_RTCEx_PollForTamper2Event(RTC_HandleTypeDef *hrtc, uint32_t Timeout); +#endif /* RTC_TAMPER2_SUPPORT */ +/** + * @} + */ + +/** @addtogroup RTCEx_Exported_Functions_Group2 + * @{ + */ +/* RTC Wakeup functions ******************************************************/ +DAL_StatusTypeDef DAL_RTCEx_SetWakeUpTimer(RTC_HandleTypeDef *hrtc, uint32_t WakeUpCounter, uint32_t WakeUpClock); +DAL_StatusTypeDef DAL_RTCEx_SetWakeUpTimer_IT(RTC_HandleTypeDef *hrtc, uint32_t WakeUpCounter, uint32_t WakeUpClock); +DAL_StatusTypeDef DAL_RTCEx_DeactivateWakeUpTimer(RTC_HandleTypeDef *hrtc); +uint32_t DAL_RTCEx_GetWakeUpTimer(RTC_HandleTypeDef *hrtc); +void DAL_RTCEx_WakeUpTimerIRQHandler(RTC_HandleTypeDef *hrtc); +void DAL_RTCEx_WakeUpTimerEventCallback(RTC_HandleTypeDef *hrtc); +DAL_StatusTypeDef DAL_RTCEx_PollForWakeUpTimerEvent(RTC_HandleTypeDef *hrtc, uint32_t Timeout); +/** + * @} + */ + +/** @addtogroup RTCEx_Exported_Functions_Group3 + * @{ + */ +/* Extended Control functions ************************************************/ +void DAL_RTCEx_BKUPWrite(RTC_HandleTypeDef *hrtc, uint32_t BackupRegister, uint32_t Data); +uint32_t DAL_RTCEx_BKUPRead(RTC_HandleTypeDef *hrtc, uint32_t BackupRegister); + +DAL_StatusTypeDef DAL_RTCEx_SetCoarseCalib(RTC_HandleTypeDef *hrtc, uint32_t CalibSign, uint32_t Value); +DAL_StatusTypeDef DAL_RTCEx_DeactivateCoarseCalib(RTC_HandleTypeDef *hrtc); +DAL_StatusTypeDef DAL_RTCEx_SetSmoothCalib(RTC_HandleTypeDef *hrtc, uint32_t SmoothCalibPeriod, uint32_t SmoothCalibPlusPulses, uint32_t SmoothCalibMinusPulsesValue); +DAL_StatusTypeDef DAL_RTCEx_SetSynchroShift(RTC_HandleTypeDef *hrtc, uint32_t ShiftAdd1S, uint32_t ShiftSubFS); +DAL_StatusTypeDef DAL_RTCEx_SetCalibrationOutPut(RTC_HandleTypeDef *hrtc, uint32_t CalibOutput); +DAL_StatusTypeDef DAL_RTCEx_DeactivateCalibrationOutPut(RTC_HandleTypeDef *hrtc); +DAL_StatusTypeDef DAL_RTCEx_SetRefClock(RTC_HandleTypeDef *hrtc); +DAL_StatusTypeDef DAL_RTCEx_DeactivateRefClock(RTC_HandleTypeDef *hrtc); +DAL_StatusTypeDef DAL_RTCEx_EnableBypassShadow(RTC_HandleTypeDef *hrtc); +DAL_StatusTypeDef DAL_RTCEx_DisableBypassShadow(RTC_HandleTypeDef *hrtc); +/** + * @} + */ + +/** @addtogroup RTCEx_Exported_Functions_Group4 + * @{ + */ +/* Extended RTC features functions *******************************************/ +void DAL_RTCEx_AlarmBEventCallback(RTC_HandleTypeDef *hrtc); +DAL_StatusTypeDef DAL_RTCEx_PollForAlarmBEvent(RTC_HandleTypeDef *hrtc, uint32_t Timeout); +/** + * @} + */ + +/** + * @} + */ + +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ + +/** @defgroup RTCEx_Private_Constants RTCEx Private Constants + * @{ + */ +#define RTC_EINT_LINE_TAMPER_TIMESTAMP_EVENT EINT_IMASK_IMASK21 /*!< External interrupt line 21 Connected to the RTC Tamper and Timestamp event */ +#define RTC_EINT_LINE_WAKEUPTIMER_EVENT EINT_IMASK_IMASK22 /*!< External interrupt line 22 Connected to the RTC Wakeup event */ +/** + * @} + */ + +/** @defgroup RTCEx_Private_Constants RTCEx Private Constants + * @{ + */ +/* Masks Definition */ +#if defined(RTC_TAMPER2_SUPPORT) +#define RTC_TAMPER_ENABLE_BITS_MASK ((uint32_t) (RTC_TAMPER_1 | \ + RTC_TAMPER_2)) + +#define RTC_TAMPER_FLAGS_MASK ((uint32_t) (RTC_FLAG_TAMP1F | \ + RTC_FLAG_TAMP2F)) +#else /* RTC_TAMPER2_SUPPORT */ +#define RTC_TAMPER_ENABLE_BITS_MASK RTC_TAMPER_1 + +#define RTC_TAMPER_FLAGS_MASK RTC_FLAG_TAMP1F +#endif /* RTC_TAMPER2_SUPPORT */ +/** + * @} + */ + +/* Private macros ------------------------------------------------------------*/ + +/** @defgroup RTCEx_Private_Macros RTCEx Private Macros + * @{ + */ + +/** @defgroup RTCEx_IS_RTC_Definitions Private macros to check input parameters + * @{ + */ +#define IS_RTC_BKP(BKP) ((BKP) < (uint32_t) RTC_BKP_NUMBER) + +#define IS_TIMESTAMP_EDGE(EDGE) (((EDGE) == RTC_TIMESTAMPEDGE_RISING) || \ + ((EDGE) == RTC_TIMESTAMPEDGE_FALLING)) + +#define IS_RTC_TAMPER(TAMPER) ((((TAMPER) & ((uint32_t)~RTC_TAMPER_ENABLE_BITS_MASK)) == 0x00U) && ((TAMPER) != 0U)) + +#if defined(RTC_AF2_SUPPORT) +#define IS_RTC_TAMPER_PIN(PIN) (((PIN) == RTC_TAMPERPIN_DEFAULT) || \ + ((PIN) == RTC_TAMPERPIN_POS1)) +#else /* RTC_AF2_SUPPORT */ +#define IS_RTC_TAMPER_PIN(PIN) ((PIN) == RTC_TAMPERPIN_DEFAULT) +#endif /* RTC_AF2_SUPPORT */ + +#if defined(RTC_AF2_SUPPORT) +#define IS_RTC_TIMESTAMP_PIN(PIN) (((PIN) == RTC_TIMESTAMPPIN_DEFAULT) || \ + ((PIN) == RTC_TIMESTAMPPIN_POS1)) +#else /* RTC_AF2_SUPPORT */ +#define IS_RTC_TIMESTAMP_PIN(PIN) ((PIN) == RTC_TIMESTAMPPIN_DEFAULT) +#endif /* RTC_AF2_SUPPORT */ + +#define IS_RTC_TAMPER_TRIGGER(TRIGGER) (((TRIGGER) == RTC_TAMPERTRIGGER_RISINGEDGE) || \ + ((TRIGGER) == RTC_TAMPERTRIGGER_FALLINGEDGE) || \ + ((TRIGGER) == RTC_TAMPERTRIGGER_LOWLEVEL) || \ + ((TRIGGER) == RTC_TAMPERTRIGGER_HIGHLEVEL)) + +#define IS_RTC_TAMPER_FILTER(FILTER) (((FILTER) == RTC_TAMPERFILTER_DISABLE) || \ + ((FILTER) == RTC_TAMPERFILTER_2SAMPLE) || \ + ((FILTER) == RTC_TAMPERFILTER_4SAMPLE) || \ + ((FILTER) == RTC_TAMPERFILTER_8SAMPLE)) + +#define IS_RTC_TAMPER_FILTER_CONFIG_CORRECT(FILTER, TRIGGER) \ + ( ( ((FILTER) != RTC_TAMPERFILTER_DISABLE) \ + && ( ((TRIGGER) == RTC_TAMPERTRIGGER_LOWLEVEL) \ + || ((TRIGGER) == RTC_TAMPERTRIGGER_HIGHLEVEL))) \ + || ( ((FILTER) == RTC_TAMPERFILTER_DISABLE) \ + && ( ((TRIGGER) == RTC_TAMPERTRIGGER_RISINGEDGE) \ + || ((TRIGGER) == RTC_TAMPERTRIGGER_FALLINGEDGE)))) + +#define IS_RTC_TAMPER_SAMPLING_FREQ(FREQ) (((FREQ) == RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV32768)|| \ + ((FREQ) == RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV16384)|| \ + ((FREQ) == RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV8192) || \ + ((FREQ) == RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV4096) || \ + ((FREQ) == RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV2048) || \ + ((FREQ) == RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV1024) || \ + ((FREQ) == RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV512) || \ + ((FREQ) == RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV256)) + +#define IS_RTC_TAMPER_PRECHARGE_DURATION(DURATION) (((DURATION) == RTC_TAMPERPRECHARGEDURATION_1RTCCLK) || \ + ((DURATION) == RTC_TAMPERPRECHARGEDURATION_2RTCCLK) || \ + ((DURATION) == RTC_TAMPERPRECHARGEDURATION_4RTCCLK) || \ + ((DURATION) == RTC_TAMPERPRECHARGEDURATION_8RTCCLK)) + +#define IS_RTC_TAMPER_PULLUP_STATE(STATE) (((STATE) == RTC_TAMPER_PULLUP_ENABLE) || \ + ((STATE) == RTC_TAMPER_PULLUP_DISABLE)) + +#define IS_RTC_TAMPER_TIMESTAMPONTAMPER_DETECTION(DETECTION) (((DETECTION) == RTC_TIMESTAMPONTAMPERDETECTION_ENABLE) || \ + ((DETECTION) == RTC_TIMESTAMPONTAMPERDETECTION_DISABLE)) + +#define IS_RTC_WAKEUP_CLOCK(CLOCK) (((CLOCK) == RTC_WAKEUPCLOCK_RTCCLK_DIV16) || \ + ((CLOCK) == RTC_WAKEUPCLOCK_RTCCLK_DIV8) || \ + ((CLOCK) == RTC_WAKEUPCLOCK_RTCCLK_DIV4) || \ + ((CLOCK) == RTC_WAKEUPCLOCK_RTCCLK_DIV2) || \ + ((CLOCK) == RTC_WAKEUPCLOCK_CK_SPRE_16BITS) || \ + ((CLOCK) == RTC_WAKEUPCLOCK_CK_SPRE_17BITS)) + +#define IS_RTC_WAKEUP_COUNTER(COUNTER) ((COUNTER) <= RTC_AUTORLD_WUAUTORE) + +#define IS_RTC_CALIB_SIGN(SIGN) (((SIGN) == RTC_CALIBSIGN_POSITIVE) || \ + ((SIGN) == RTC_CALIBSIGN_NEGATIVE)) + +#define IS_RTC_CALIB_VALUE(VALUE) ((VALUE) < 0x20U) + +#define IS_RTC_SMOOTH_CALIB_PERIOD(PERIOD) (((PERIOD) == RTC_SMOOTHCALIB_PERIOD_32SEC) || \ + ((PERIOD) == RTC_SMOOTHCALIB_PERIOD_16SEC) || \ + ((PERIOD) == RTC_SMOOTHCALIB_PERIOD_8SEC)) + +#define IS_RTC_SMOOTH_CALIB_PLUS(PLUS) (((PLUS) == RTC_SMOOTHCALIB_PLUSPULSES_SET) || \ + ((PLUS) == RTC_SMOOTHCALIB_PLUSPULSES_RESET)) + +#define IS_RTC_SMOOTH_CALIB_MINUS(VALUE) ((VALUE) <= RTC_CAL_RECALF) + +#define IS_RTC_SHIFT_ADD1SECEN(SEL) (((SEL) == RTC_SHIFTADD1S_RESET) || \ + ((SEL) == RTC_SHIFTADD1S_SET)) + +#define IS_RTC_SHIFT_SFSEC(FS) ((FS) <= RTC_SHIFT_SFSEC) + +#define IS_RTC_CALIB_OUTPUT(OUTPUT) (((OUTPUT) == RTC_CALIBOUTPUT_512HZ) || \ + ((OUTPUT) == RTC_CALIBOUTPUT_1HZ)) +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* APM32F4xx_DAL_RTC_EX_H */ diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_sd.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_sd.h new file mode 100644 index 0000000000..27ff35f5ee --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_sd.h @@ -0,0 +1,782 @@ +/** + * + * @file apm32f4xx_dal_sd.h + * @brief Header file of SD DAL module. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef APM32F4xx_DAL_SD_H +#define APM32F4xx_DAL_SD_H + +#ifdef __cplusplus + extern "C" { +#endif + +#if defined(SDIO) + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_ddl_sdmmc.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @defgroup SD SD + * @brief SD DAL module driver + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ +/** @defgroup SD_Exported_Types SD Exported Types + * @{ + */ + +/** @defgroup SD_Exported_Types_Group1 SD State enumeration structure + * @{ + */ +typedef enum +{ + DAL_SD_STATE_RESET = 0x00000000U, /*!< SD not yet initialized or disabled */ + DAL_SD_STATE_READY = 0x00000001U, /*!< SD initialized and ready for use */ + DAL_SD_STATE_TIMEOUT = 0x00000002U, /*!< SD Timeout state */ + DAL_SD_STATE_BUSY = 0x00000003U, /*!< SD process ongoing */ + DAL_SD_STATE_PROGRAMMING = 0x00000004U, /*!< SD Programming State */ + DAL_SD_STATE_RECEIVING = 0x00000005U, /*!< SD Receiving State */ + DAL_SD_STATE_TRANSFER = 0x00000006U, /*!< SD Transfer State */ + DAL_SD_STATE_ERROR = 0x0000000FU /*!< SD is in error state */ +}DAL_SD_StateTypeDef; +/** + * @} + */ + +/** @defgroup SD_Exported_Types_Group2 SD Card State enumeration structure + * @{ + */ +typedef uint32_t DAL_SD_CardStateTypeDef; + +#define DAL_SD_CARD_READY 0x00000001U /*!< Card state is ready */ +#define DAL_SD_CARD_IDENTIFICATION 0x00000002U /*!< Card is in identification state */ +#define DAL_SD_CARD_STANDBY 0x00000003U /*!< Card is in standby state */ +#define DAL_SD_CARD_TRANSFER 0x00000004U /*!< Card is in transfer state */ +#define DAL_SD_CARD_SENDING 0x00000005U /*!< Card is sending an operation */ +#define DAL_SD_CARD_RECEIVING 0x00000006U /*!< Card is receiving operation information */ +#define DAL_SD_CARD_PROGRAMMING 0x00000007U /*!< Card is in programming state */ +#define DAL_SD_CARD_DISCONNECTED 0x00000008U /*!< Card is disconnected */ +#define DAL_SD_CARD_ERROR 0x000000FFU /*!< Card response Error */ +/** + * @} + */ + +/** @defgroup SD_Exported_Types_Group3 SD Handle Structure definition + * @{ + */ +#define SD_InitTypeDef SDIO_InitTypeDef +#define SD_TypeDef SDIO_TypeDef + +/** + * @brief SD Card Information Structure definition + */ +typedef struct +{ + uint32_t CardType; /*!< Specifies the card Type */ + + uint32_t CardVersion; /*!< Specifies the card version */ + + uint32_t Class; /*!< Specifies the class of the card class */ + + uint32_t RelCardAdd; /*!< Specifies the Relative Card Address */ + + uint32_t BlockNbr; /*!< Specifies the Card Capacity in blocks */ + + uint32_t BlockSize; /*!< Specifies one block size in bytes */ + + uint32_t LogBlockNbr; /*!< Specifies the Card logical Capacity in blocks */ + + uint32_t LogBlockSize; /*!< Specifies logical block size in bytes */ + +}DAL_SD_CardInfoTypeDef; + +/** + * @brief SD handle Structure definition + */ +#if defined (USE_DAL_SD_REGISTER_CALLBACKS) && (USE_DAL_SD_REGISTER_CALLBACKS == 1U) +typedef struct __SD_HandleTypeDef +#else +typedef struct +#endif /* USE_DAL_SD_REGISTER_CALLBACKS */ +{ + SD_TypeDef *Instance; /*!< SD registers base address */ + + SD_InitTypeDef Init; /*!< SD required parameters */ + + DAL_LockTypeDef Lock; /*!< SD locking object */ + + uint8_t *pTxBuffPtr; /*!< Pointer to SD Tx transfer Buffer */ + + uint32_t TxXferSize; /*!< SD Tx Transfer size */ + + uint8_t *pRxBuffPtr; /*!< Pointer to SD Rx transfer Buffer */ + + uint32_t RxXferSize; /*!< SD Rx Transfer size */ + + __IO uint32_t Context; /*!< SD transfer context */ + + __IO DAL_SD_StateTypeDef State; /*!< SD card State */ + + __IO uint32_t ErrorCode; /*!< SD Card Error codes */ + + DMA_HandleTypeDef *hdmatx; /*!< SD Tx DMA handle parameters */ + + DMA_HandleTypeDef *hdmarx; /*!< SD Rx DMA handle parameters */ + + DAL_SD_CardInfoTypeDef SdCard; /*!< SD Card information */ + + uint32_t CSD[4]; /*!< SD card specific data table */ + + uint32_t CID[4]; /*!< SD card identification number table */ + +#if defined (USE_DAL_SD_REGISTER_CALLBACKS) && (USE_DAL_SD_REGISTER_CALLBACKS == 1U) + void (* TxCpltCallback) (struct __SD_HandleTypeDef *hsd); + void (* RxCpltCallback) (struct __SD_HandleTypeDef *hsd); + void (* ErrorCallback) (struct __SD_HandleTypeDef *hsd); + void (* AbortCpltCallback) (struct __SD_HandleTypeDef *hsd); + + void (* MspInitCallback) (struct __SD_HandleTypeDef *hsd); + void (* MspDeInitCallback) (struct __SD_HandleTypeDef *hsd); +#endif /* USE_DAL_SD_REGISTER_CALLBACKS */ +}SD_HandleTypeDef; + +/** + * @} + */ + +/** @defgroup SD_Exported_Types_Group4 Card Specific Data: CSD Register + * @{ + */ +typedef struct +{ + __IO uint8_t CSDStruct; /*!< CSD structure */ + __IO uint8_t SysSpecVersion; /*!< System specification version */ + __IO uint8_t Reserved1; /*!< Reserved */ + __IO uint8_t TAAC; /*!< Data read access time 1 */ + __IO uint8_t NSAC; /*!< Data read access time 2 in CLK cycles */ + __IO uint8_t MaxBusClkFrec; /*!< Max. bus clock frequency */ + __IO uint16_t CardComdClasses; /*!< Card command classes */ + __IO uint8_t RdBlockLen; /*!< Max. read data block length */ + __IO uint8_t PartBlockRead; /*!< Partial blocks for read allowed */ + __IO uint8_t WrBlockMisalign; /*!< Write block misalignment */ + __IO uint8_t RdBlockMisalign; /*!< Read block misalignment */ + __IO uint8_t DSRImpl; /*!< DSR implemented */ + __IO uint8_t Reserved2; /*!< Reserved */ + __IO uint32_t DeviceSize; /*!< Device Size */ + __IO uint8_t MaxRdCurrentVDDMin; /*!< Max. read current @ VDD min */ + __IO uint8_t MaxRdCurrentVDDMax; /*!< Max. read current @ VDD max */ + __IO uint8_t MaxWrCurrentVDDMin; /*!< Max. write current @ VDD min */ + __IO uint8_t MaxWrCurrentVDDMax; /*!< Max. write current @ VDD max */ + __IO uint8_t DeviceSizeMul; /*!< Device size multiplier */ + __IO uint8_t EraseGrSize; /*!< Erase group size */ + __IO uint8_t EraseGrMul; /*!< Erase group size multiplier */ + __IO uint8_t WrProtectGrSize; /*!< Write protect group size */ + __IO uint8_t WrProtectGrEnable; /*!< Write protect group enable */ + __IO uint8_t ManDeflECC; /*!< Manufacturer default ECC */ + __IO uint8_t WrSpeedFact; /*!< Write speed factor */ + __IO uint8_t MaxWrBlockLen; /*!< Max. write data block length */ + __IO uint8_t WriteBlockPaPartial; /*!< Partial blocks for write allowed */ + __IO uint8_t Reserved3; /*!< Reserved */ + __IO uint8_t ContentProtectAppli; /*!< Content protection application */ + __IO uint8_t FileFormatGroup; /*!< File format group */ + __IO uint8_t CopyFlag; /*!< Copy flag (OTP) */ + __IO uint8_t PermWrProtect; /*!< Permanent write protection */ + __IO uint8_t TempWrProtect; /*!< Temporary write protection */ + __IO uint8_t FileFormat; /*!< File format */ + __IO uint8_t ECC; /*!< ECC code */ + __IO uint8_t CSD_CRC; /*!< CSD CRC */ + __IO uint8_t Reserved4; /*!< Always 1 */ +}DAL_SD_CardCSDTypeDef; +/** + * @} + */ + +/** @defgroup SD_Exported_Types_Group5 Card Identification Data: CID Register + * @{ + */ +typedef struct +{ + __IO uint8_t ManufacturerID; /*!< Manufacturer ID */ + __IO uint16_t OEM_AppliID; /*!< OEM/Application ID */ + __IO uint32_t ProdName1; /*!< Product Name part1 */ + __IO uint8_t ProdName2; /*!< Product Name part2 */ + __IO uint8_t ProdRev; /*!< Product Revision */ + __IO uint32_t ProdSN; /*!< Product Serial Number */ + __IO uint8_t Reserved1; /*!< Reserved1 */ + __IO uint16_t ManufactDate; /*!< Manufacturing Date */ + __IO uint8_t CID_CRC; /*!< CID CRC */ + __IO uint8_t Reserved2; /*!< Always 1 */ + +}DAL_SD_CardCIDTypeDef; +/** + * @} + */ + +/** @defgroup SD_Exported_Types_Group6 SD Card Status returned by ACMD13 + * @{ + */ +typedef struct +{ + __IO uint8_t DataBusWidth; /*!< Shows the currently defined data bus width */ + __IO uint8_t SecuredMode; /*!< Card is in secured mode of operation */ + __IO uint16_t CardType; /*!< Carries information about card type */ + __IO uint32_t ProtectedAreaSize; /*!< Carries information about the capacity of protected area */ + __IO uint8_t SpeedClass; /*!< Carries information about the speed class of the card */ + __IO uint8_t PerformanceMove; /*!< Carries information about the card's performance move */ + __IO uint8_t AllocationUnitSize; /*!< Carries information about the card's allocation unit size */ + __IO uint16_t EraseSize; /*!< Determines the number of AUs to be erased in one operation */ + __IO uint8_t EraseTimeout; /*!< Determines the timeout for any number of AU erase */ + __IO uint8_t EraseOffset; /*!< Carries information about the erase offset */ + +}DAL_SD_CardStatusTypeDef; +/** + * @} + */ + +#if defined (USE_DAL_SD_REGISTER_CALLBACKS) && (USE_DAL_SD_REGISTER_CALLBACKS == 1U) +/** @defgroup SD_Exported_Types_Group7 SD Callback ID enumeration definition + * @{ + */ +typedef enum +{ + DAL_SD_TX_CPLT_CB_ID = 0x00U, /*!< SD Tx Complete Callback ID */ + DAL_SD_RX_CPLT_CB_ID = 0x01U, /*!< SD Rx Complete Callback ID */ + DAL_SD_ERROR_CB_ID = 0x02U, /*!< SD Error Callback ID */ + DAL_SD_ABORT_CB_ID = 0x03U, /*!< SD Abort Callback ID */ + + DAL_SD_MSP_INIT_CB_ID = 0x10U, /*!< SD MspInit Callback ID */ + DAL_SD_MSP_DEINIT_CB_ID = 0x11U /*!< SD MspDeInit Callback ID */ +}DAL_SD_CallbackIDTypeDef; +/** + * @} + */ + +/** @defgroup SD_Exported_Types_Group8 SD Callback pointer definition + * @{ + */ +typedef void (*pSD_CallbackTypeDef) (SD_HandleTypeDef *hsd); +/** + * @} + */ +#endif /* USE_DAL_SD_REGISTER_CALLBACKS */ +/** + * @} + */ + +/* Exported constants --------------------------------------------------------*/ +/** @defgroup SD_Exported_Constants Exported Constants + * @{ + */ + +#define BLOCKSIZE 512U /*!< Block size is 512 bytes */ + +/** @defgroup SD_Exported_Constansts_Group1 SD Error status enumeration Structure definition + * @{ + */ +#define DAL_SD_ERROR_NONE SDMMC_ERROR_NONE /*!< No error */ +#define DAL_SD_ERROR_CMD_CRC_FAIL SDMMC_ERROR_CMD_CRC_FAIL /*!< Command response received (but CRC check failed) */ +#define DAL_SD_ERROR_DATA_CRC_FAIL SDMMC_ERROR_DATA_CRC_FAIL /*!< Data block sent/received (CRC check failed) */ +#define DAL_SD_ERROR_CMD_RSP_TIMEOUT SDMMC_ERROR_CMD_RSP_TIMEOUT /*!< Command response timeout */ +#define DAL_SD_ERROR_DATA_TIMEOUT SDMMC_ERROR_DATA_TIMEOUT /*!< Data timeout */ +#define DAL_SD_ERROR_TX_UNDERRUN SDMMC_ERROR_TX_UNDERRUN /*!< Transmit FIFO underrun */ +#define DAL_SD_ERROR_RX_OVERRUN SDMMC_ERROR_RX_OVERRUN /*!< Receive FIFO overrun */ +#define DAL_SD_ERROR_ADDR_MISALIGNED SDMMC_ERROR_ADDR_MISALIGNED /*!< Misaligned address */ +#define DAL_SD_ERROR_BLOCK_LEN_ERR SDMMC_ERROR_BLOCK_LEN_ERR /*!< Transferred block length is not allowed for the card or the + number of transferred bytes does not match the block length */ +#define DAL_SD_ERROR_ERASE_SEQ_ERR SDMMC_ERROR_ERASE_SEQ_ERR /*!< An error in the sequence of erase command occurs */ +#define DAL_SD_ERROR_BAD_ERASE_PARAM SDMMC_ERROR_BAD_ERASE_PARAM /*!< An invalid selection for erase groups */ +#define DAL_SD_ERROR_WRITE_PROT_VIOLATION SDMMC_ERROR_WRITE_PROT_VIOLATION /*!< Attempt to program a write protect block */ +#define DAL_SD_ERROR_LOCK_UNLOCK_FAILED SDMMC_ERROR_LOCK_UNLOCK_FAILED /*!< Sequence or password error has been detected in unlock + command or if there was an attempt to access a locked card */ +#define DAL_SD_ERROR_COM_CRC_FAILED SDMMC_ERROR_COM_CRC_FAILED /*!< CRC check of the previous command failed */ +#define DAL_SD_ERROR_ILLEGAL_CMD SDMMC_ERROR_ILLEGAL_CMD /*!< Command is not legal for the card state */ +#define DAL_SD_ERROR_CARD_ECC_FAILED SDMMC_ERROR_CARD_ECC_FAILED /*!< Card internal ECC was applied but failed to correct the data */ +#define DAL_SD_ERROR_CC_ERR SDMMC_ERROR_CC_ERR /*!< Internal card controller error */ +#define DAL_SD_ERROR_GENERAL_UNKNOWN_ERR SDMMC_ERROR_GENERAL_UNKNOWN_ERR /*!< General or unknown error */ +#define DAL_SD_ERROR_STREAM_READ_UNDERRUN SDMMC_ERROR_STREAM_READ_UNDERRUN /*!< The card could not sustain data reading in stream rmode */ +#define DAL_SD_ERROR_STREAM_WRITE_OVERRUN SDMMC_ERROR_STREAM_WRITE_OVERRUN /*!< The card could not sustain data programming in stream mode */ +#define DAL_SD_ERROR_CID_CSD_OVERWRITE SDMMC_ERROR_CID_CSD_OVERWRITE /*!< CID/CSD overwrite error */ +#define DAL_SD_ERROR_WP_ERASE_SKIP SDMMC_ERROR_WP_ERASE_SKIP /*!< Only partial address space was erased */ +#define DAL_SD_ERROR_CARD_ECC_DISABLED SDMMC_ERROR_CARD_ECC_DISABLED /*!< Command has been executed without using internal ECC */ +#define DAL_SD_ERROR_ERASE_RESET SDMMC_ERROR_ERASE_RESET /*!< Erase sequence was cleared before executing because an out + of erase sequence command was received */ +#define DAL_SD_ERROR_AKE_SEQ_ERR SDMMC_ERROR_AKE_SEQ_ERR /*!< Error in sequence of authentication */ +#define DAL_SD_ERROR_INVALID_VOLTRANGE SDMMC_ERROR_INVALID_VOLTRANGE /*!< Error in case of invalid voltage range */ +#define DAL_SD_ERROR_ADDR_OUT_OF_RANGE SDMMC_ERROR_ADDR_OUT_OF_RANGE /*!< Error when addressed block is out of range */ +#define DAL_SD_ERROR_REQUEST_NOT_APPLICABLE SDMMC_ERROR_REQUEST_NOT_APPLICABLE /*!< Error when command request is not applicable */ +#define DAL_SD_ERROR_PARAM SDMMC_ERROR_INVALID_PARAMETER /*!< the used parameter is not valid */ +#define DAL_SD_ERROR_UNSUPPORTED_FEATURE SDMMC_ERROR_UNSUPPORTED_FEATURE /*!< Error when feature is not insupported */ +#define DAL_SD_ERROR_BUSY SDMMC_ERROR_BUSY /*!< Error when transfer process is busy */ +#define DAL_SD_ERROR_DMA SDMMC_ERROR_DMA /*!< Error while DMA transfer */ +#define DAL_SD_ERROR_TIMEOUT SDMMC_ERROR_TIMEOUT /*!< Timeout error */ + +#if defined (USE_DAL_SD_REGISTER_CALLBACKS) && (USE_DAL_SD_REGISTER_CALLBACKS == 1U) +#define DAL_SD_ERROR_INVALID_CALLBACK SDMMC_ERROR_INVALID_PARAMETER /*!< Invalid callback error */ +#endif /* USE_DAL_SD_REGISTER_CALLBACKS */ +/** + * @} + */ + +/** @defgroup SD_Exported_Constansts_Group2 SD context enumeration + * @{ + */ +#define SD_CONTEXT_NONE 0x00000000U /*!< None */ +#define SD_CONTEXT_READ_SINGLE_BLOCK 0x00000001U /*!< Read single block operation */ +#define SD_CONTEXT_READ_MULTIPLE_BLOCK 0x00000002U /*!< Read multiple blocks operation */ +#define SD_CONTEXT_WRITE_SINGLE_BLOCK 0x00000010U /*!< Write single block operation */ +#define SD_CONTEXT_WRITE_MULTIPLE_BLOCK 0x00000020U /*!< Write multiple blocks operation */ +#define SD_CONTEXT_IT 0x00000008U /*!< Process in Interrupt mode */ +#define SD_CONTEXT_DMA 0x00000080U /*!< Process in DMA mode */ + +/** + * @} + */ + +/** @defgroup SD_Exported_Constansts_Group3 SD Supported Memory Cards + * @{ + */ +#define CARD_SDSC 0x00000000U /*!< SD Standard Capacity <2Go */ +#define CARD_SDHC_SDXC 0x00000001U /*!< SD High Capacity <32Go, SD Extended Capacity <2To */ +#define CARD_SECURED 0x00000003U + +/** + * @} + */ + +/** @defgroup SD_Exported_Constansts_Group4 SD Supported Version + * @{ + */ +#define CARD_V1_X 0x00000000U +#define CARD_V2_X 0x00000001U +/** + * @} + */ + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ +/** @defgroup SD_Exported_macros SD Exported Macros + * @brief macros to handle interrupts and specific clock configurations + * @{ + */ +/** @brief Reset SD handle state. + * @param __HANDLE__ : SD handle. + * @retval None + */ +#if defined (USE_DAL_SD_REGISTER_CALLBACKS) && (USE_DAL_SD_REGISTER_CALLBACKS == 1U) +#define __DAL_SD_RESET_HANDLE_STATE(__HANDLE__) do { \ + (__HANDLE__)->State = DAL_SD_STATE_RESET; \ + (__HANDLE__)->MspInitCallback = NULL; \ + (__HANDLE__)->MspDeInitCallback = NULL; \ + } while(0) +#else +#define __DAL_SD_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = DAL_SD_STATE_RESET) +#endif /* USE_DAL_SD_REGISTER_CALLBACKS */ + +/** + * @brief Enable the SD device. + * @retval None + */ +#define __DAL_SD_ENABLE(__HANDLE__) __SDIO_ENABLE((__HANDLE__)->Instance) + +/** + * @brief Disable the SD device. + * @retval None + */ +#define __DAL_SD_DISABLE(__HANDLE__) __SDIO_DISABLE((__HANDLE__)->Instance) + +/** + * @brief Enable the SDMMC DMA transfer. + * @retval None + */ +#define __DAL_SD_DMA_ENABLE(__HANDLE__) __SDIO_DMA_ENABLE((__HANDLE__)->Instance) + +/** + * @brief Disable the SDMMC DMA transfer. + * @retval None + */ +#define __DAL_SD_DMA_DISABLE(__HANDLE__) __SDIO_DMA_DISABLE((__HANDLE__)->Instance) + +/** + * @brief Enable the SD device interrupt. + * @param __HANDLE__: SD Handle + * @param __INTERRUPT__: specifies the SDMMC interrupt sources to be enabled. + * This parameter can be one or a combination of the following values: + * @arg SDIO_IT_CCRCFAIL: Command response received (CRC check failed) interrupt + * @arg SDIO_IT_DCRCFAIL: Data block sent/received (CRC check failed) interrupt + * @arg SDIO_IT_CTIMEOUT: Command response timeout interrupt + * @arg SDIO_IT_DTIMEOUT: Data timeout interrupt + * @arg SDIO_IT_TXUNDERR: Transmit FIFO underrun error interrupt + * @arg SDIO_IT_RXOVERR: Received FIFO overrun error interrupt + * @arg SDIO_IT_CMDREND: Command response received (CRC check passed) interrupt + * @arg SDIO_IT_CMDSENT: Command sent (no response required) interrupt + * @arg SDIO_IT_DATAEND: Data end (data counter, DATACOUNT, is zero) interrupt + * @arg SDIO_IT_DBCKEND: Data block sent/received (CRC check passed) interrupt + * @arg SDIO_IT_CMDACT: Command transfer in progress interrupt + * @arg SDIO_IT_TXACT: Data transmit in progress interrupt + * @arg SDIO_IT_RXACT: Data receive in progress interrupt + * @arg SDIO_IT_TXFIFOHE: Transmit FIFO Half Empty interrupt + * @arg SDIO_IT_RXFIFOHF: Receive FIFO Half Full interrupt + * @arg SDIO_IT_TXFIFOF: Transmit FIFO full interrupt + * @arg SDIO_IT_RXFIFOF: Receive FIFO full interrupt + * @arg SDIO_IT_TXFIFOE: Transmit FIFO empty interrupt + * @arg SDIO_IT_RXFIFOE: Receive FIFO empty interrupt + * @arg SDIO_IT_TXDAVL: Data available in transmit FIFO interrupt + * @arg SDIO_IT_RXDAVL: Data available in receive FIFO interrupt + * @arg SDIO_IT_SDIOIT: SDIO interrupt received interrupt + * @retval None + */ +#define __DAL_SD_ENABLE_IT(__HANDLE__, __INTERRUPT__) __SDIO_ENABLE_IT((__HANDLE__)->Instance, (__INTERRUPT__)) + +/** + * @brief Disable the SD device interrupt. + * @param __HANDLE__: SD Handle + * @param __INTERRUPT__: specifies the SDMMC interrupt sources to be disabled. + * This parameter can be one or a combination of the following values: + * @arg SDIO_IT_CCRCFAIL: Command response received (CRC check failed) interrupt + * @arg SDIO_IT_DCRCFAIL: Data block sent/received (CRC check failed) interrupt + * @arg SDIO_IT_CTIMEOUT: Command response timeout interrupt + * @arg SDIO_IT_DTIMEOUT: Data timeout interrupt + * @arg SDIO_IT_TXUNDERR: Transmit FIFO underrun error interrupt + * @arg SDIO_IT_RXOVERR: Received FIFO overrun error interrupt + * @arg SDIO_IT_CMDREND: Command response received (CRC check passed) interrupt + * @arg SDIO_IT_CMDSENT: Command sent (no response required) interrupt + * @arg SDIO_IT_DATAEND: Data end (data counter, DATACOUNT, is zero) interrupt + * @arg SDIO_IT_DBCKEND: Data block sent/received (CRC check passed) interrupt + * @arg SDIO_IT_CMDACT: Command transfer in progress interrupt + * @arg SDIO_IT_TXACT: Data transmit in progress interrupt + * @arg SDIO_IT_RXACT: Data receive in progress interrupt + * @arg SDIO_IT_TXFIFOHE: Transmit FIFO Half Empty interrupt + * @arg SDIO_IT_RXFIFOHF: Receive FIFO Half Full interrupt + * @arg SDIO_IT_TXFIFOF: Transmit FIFO full interrupt + * @arg SDIO_IT_RXFIFOF: Receive FIFO full interrupt + * @arg SDIO_IT_TXFIFOE: Transmit FIFO empty interrupt + * @arg SDIO_IT_RXFIFOE: Receive FIFO empty interrupt + * @arg SDIO_IT_TXDAVL: Data available in transmit FIFO interrupt + * @arg SDIO_IT_RXDAVL: Data available in receive FIFO interrupt + * @arg SDIO_IT_SDIOIT: SDIO interrupt received interrupt + * @retval None + */ +#define __DAL_SD_DISABLE_IT(__HANDLE__, __INTERRUPT__) __SDIO_DISABLE_IT((__HANDLE__)->Instance, (__INTERRUPT__)) + +/** + * @brief Check whether the specified SD flag is set or not. + * @param __HANDLE__: SD Handle + * @param __FLAG__: specifies the flag to check. + * This parameter can be one of the following values: + * @arg SDIO_FLAG_CCRCFAIL: Command response received (CRC check failed) + * @arg SDIO_FLAG_DCRCFAIL: Data block sent/received (CRC check failed) + * @arg SDIO_FLAG_CTIMEOUT: Command response timeout + * @arg SDIO_FLAG_DTIMEOUT: Data timeout + * @arg SDIO_FLAG_TXUNDERR: Transmit FIFO underrun error + * @arg SDIO_FLAG_RXOVERR: Received FIFO overrun error + * @arg SDIO_FLAG_CMDREND: Command response received (CRC check passed) + * @arg SDIO_FLAG_CMDSENT: Command sent (no response required) + * @arg SDIO_FLAG_DATAEND: Data end (data counter, DATACOUNT, is zero) + * @arg SDIO_FLAG_DBCKEND: Data block sent/received (CRC check passed) + * @arg SDIO_FLAG_CMDACT: Command transfer in progress + * @arg SDIO_FLAG_TXACT: Data transmit in progress + * @arg SDIO_FLAG_RXACT: Data receive in progress + * @arg SDIO_FLAG_TXFIFOHE: Transmit FIFO Half Empty + * @arg SDIO_FLAG_RXFIFOHF: Receive FIFO Half Full + * @arg SDIO_FLAG_TXFIFOF: Transmit FIFO full + * @arg SDIO_FLAG_RXFIFOF: Receive FIFO full + * @arg SDIO_FLAG_TXFIFOE: Transmit FIFO empty + * @arg SDIO_FLAG_RXFIFOE: Receive FIFO empty + * @arg SDIO_FLAG_TXDAVL: Data available in transmit FIFO + * @arg SDIO_FLAG_RXDAVL: Data available in receive FIFO + * @arg SDIO_FLAG_SDIOIT: SDIO interrupt received + * @retval The new state of SD FLAG (SET or RESET). + */ +#define __DAL_SD_GET_FLAG(__HANDLE__, __FLAG__) __SDIO_GET_FLAG((__HANDLE__)->Instance, (__FLAG__)) + +/** + * @brief Clear the SD's pending flags. + * @param __HANDLE__: SD Handle + * @param __FLAG__: specifies the flag to clear. + * This parameter can be one or a combination of the following values: + * @arg SDIO_FLAG_CCRCFAIL: Command response received (CRC check failed) + * @arg SDIO_FLAG_DCRCFAIL: Data block sent/received (CRC check failed) + * @arg SDIO_FLAG_CTIMEOUT: Command response timeout + * @arg SDIO_FLAG_DTIMEOUT: Data timeout + * @arg SDIO_FLAG_TXUNDERR: Transmit FIFO underrun error + * @arg SDIO_FLAG_RXOVERR: Received FIFO overrun error + * @arg SDIO_FLAG_CMDREND: Command response received (CRC check passed) + * @arg SDIO_FLAG_CMDSENT: Command sent (no response required) + * @arg SDIO_FLAG_DATAEND: Data end (data counter, DATACOUNT, is zero) + * @arg SDIO_FLAG_DBCKEND: Data block sent/received (CRC check passed) + * @arg SDIO_FLAG_SDIOIT: SDIO interrupt received + * @retval None + */ +#define __DAL_SD_CLEAR_FLAG(__HANDLE__, __FLAG__) __SDIO_CLEAR_FLAG((__HANDLE__)->Instance, (__FLAG__)) + +/** + * @brief Check whether the specified SD interrupt has occurred or not. + * @param __HANDLE__: SD Handle + * @param __INTERRUPT__: specifies the SDMMC interrupt source to check. + * This parameter can be one of the following values: + * @arg SDIO_IT_CCRCFAIL: Command response received (CRC check failed) interrupt + * @arg SDIO_IT_DCRCFAIL: Data block sent/received (CRC check failed) interrupt + * @arg SDIO_IT_CTIMEOUT: Command response timeout interrupt + * @arg SDIO_IT_DTIMEOUT: Data timeout interrupt + * @arg SDIO_IT_TXUNDERR: Transmit FIFO underrun error interrupt + * @arg SDIO_IT_RXOVERR: Received FIFO overrun error interrupt + * @arg SDIO_IT_CMDREND: Command response received (CRC check passed) interrupt + * @arg SDIO_IT_CMDSENT: Command sent (no response required) interrupt + * @arg SDIO_IT_DATAEND: Data end (data counter, DATACOUNT, is zero) interrupt + * @arg SDIO_IT_DBCKEND: Data block sent/received (CRC check passed) interrupt + * @arg SDIO_IT_CMDACT: Command transfer in progress interrupt + * @arg SDIO_IT_TXACT: Data transmit in progress interrupt + * @arg SDIO_IT_RXACT: Data receive in progress interrupt + * @arg SDIO_IT_TXFIFOHE: Transmit FIFO Half Empty interrupt + * @arg SDIO_IT_RXFIFOHF: Receive FIFO Half Full interrupt + * @arg SDIO_IT_TXFIFOF: Transmit FIFO full interrupt + * @arg SDIO_IT_RXFIFOF: Receive FIFO full interrupt + * @arg SDIO_IT_TXFIFOE: Transmit FIFO empty interrupt + * @arg SDIO_IT_RXFIFOE: Receive FIFO empty interrupt + * @arg SDIO_IT_TXDAVL: Data available in transmit FIFO interrupt + * @arg SDIO_IT_RXDAVL: Data available in receive FIFO interrupt + * @arg SDIO_IT_SDIOIT: SDIO interrupt received interrupt + * @retval The new state of SD IT (SET or RESET). + */ +#define __DAL_SD_GET_IT(__HANDLE__, __INTERRUPT__) __SDIO_GET_IT((__HANDLE__)->Instance, (__INTERRUPT__)) + +/** + * @brief Clear the SD's interrupt pending bits. + * @param __HANDLE__: SD Handle + * @param __INTERRUPT__: specifies the interrupt pending bit to clear. + * This parameter can be one or a combination of the following values: + * @arg SDIO_IT_CCRCFAIL: Command response received (CRC check failed) interrupt + * @arg SDIO_IT_DCRCFAIL: Data block sent/received (CRC check failed) interrupt + * @arg SDIO_IT_CTIMEOUT: Command response timeout interrupt + * @arg SDIO_IT_DTIMEOUT: Data timeout interrupt + * @arg SDIO_IT_TXUNDERR: Transmit FIFO underrun error interrupt + * @arg SDIO_IT_RXOVERR: Received FIFO overrun error interrupt + * @arg SDIO_IT_CMDREND: Command response received (CRC check passed) interrupt + * @arg SDIO_IT_CMDSENT: Command sent (no response required) interrupt + * @arg SDIO_IT_DATAEND: Data end (data counter, DATACOUNT, is zero) interrupt + * @arg SDIO_IT_SDIOIT: SDIO interrupt received interrupt + * @retval None + */ +#define __DAL_SD_CLEAR_IT(__HANDLE__, __INTERRUPT__) __SDIO_CLEAR_IT((__HANDLE__)->Instance, (__INTERRUPT__)) + +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +/** @defgroup SD_Exported_Functions SD Exported Functions + * @{ + */ + +/** @defgroup SD_Exported_Functions_Group1 Initialization and de-initialization functions + * @{ + */ +DAL_StatusTypeDef DAL_SD_Init(SD_HandleTypeDef *hsd); +DAL_StatusTypeDef DAL_SD_InitCard(SD_HandleTypeDef *hsd); +DAL_StatusTypeDef DAL_SD_DeInit (SD_HandleTypeDef *hsd); +void DAL_SD_MspInit(SD_HandleTypeDef *hsd); +void DAL_SD_MspDeInit(SD_HandleTypeDef *hsd); +/** + * @} + */ + +/** @defgroup SD_Exported_Functions_Group2 Input and Output operation functions + * @{ + */ +/* Blocking mode: Polling */ +DAL_StatusTypeDef DAL_SD_ReadBlocks(SD_HandleTypeDef *hsd, uint8_t *pData, uint32_t BlockAdd, uint32_t NumberOfBlocks, uint32_t Timeout); +DAL_StatusTypeDef DAL_SD_WriteBlocks(SD_HandleTypeDef *hsd, uint8_t *pData, uint32_t BlockAdd, uint32_t NumberOfBlocks, uint32_t Timeout); +DAL_StatusTypeDef DAL_SD_Erase(SD_HandleTypeDef *hsd, uint32_t BlockStartAdd, uint32_t BlockEndAdd); +/* Non-Blocking mode: IT */ +DAL_StatusTypeDef DAL_SD_ReadBlocks_IT(SD_HandleTypeDef *hsd, uint8_t *pData, uint32_t BlockAdd, uint32_t NumberOfBlocks); +DAL_StatusTypeDef DAL_SD_WriteBlocks_IT(SD_HandleTypeDef *hsd, uint8_t *pData, uint32_t BlockAdd, uint32_t NumberOfBlocks); +/* Non-Blocking mode: DMA */ +DAL_StatusTypeDef DAL_SD_ReadBlocks_DMA(SD_HandleTypeDef *hsd, uint8_t *pData, uint32_t BlockAdd, uint32_t NumberOfBlocks); +DAL_StatusTypeDef DAL_SD_WriteBlocks_DMA(SD_HandleTypeDef *hsd, uint8_t *pData, uint32_t BlockAdd, uint32_t NumberOfBlocks); + +void DAL_SD_IRQHandler(SD_HandleTypeDef *hsd); + +/* Callback in non blocking modes (DMA) */ +void DAL_SD_TxCpltCallback(SD_HandleTypeDef *hsd); +void DAL_SD_RxCpltCallback(SD_HandleTypeDef *hsd); +void DAL_SD_ErrorCallback(SD_HandleTypeDef *hsd); +void DAL_SD_AbortCallback(SD_HandleTypeDef *hsd); + +#if defined (USE_DAL_SD_REGISTER_CALLBACKS) && (USE_DAL_SD_REGISTER_CALLBACKS == 1U) +/* SD callback registering/unregistering */ +DAL_StatusTypeDef DAL_SD_RegisterCallback (SD_HandleTypeDef *hsd, DAL_SD_CallbackIDTypeDef CallbackId, pSD_CallbackTypeDef pCallback); +DAL_StatusTypeDef DAL_SD_UnRegisterCallback(SD_HandleTypeDef *hsd, DAL_SD_CallbackIDTypeDef CallbackId); +#endif /* USE_DAL_SD_REGISTER_CALLBACKS */ + +/** + * @} + */ + +/** @defgroup SD_Exported_Functions_Group3 Peripheral Control functions + * @{ + */ +DAL_StatusTypeDef DAL_SD_ConfigWideBusOperation(SD_HandleTypeDef *hsd, uint32_t WideMode); +/** + * @} + */ + +/** @defgroup SD_Exported_Functions_Group4 SD card related functions + * @{ + */ +DAL_StatusTypeDef DAL_SD_SendSDStatus(SD_HandleTypeDef *hsd, uint32_t *pSDstatus); +DAL_SD_CardStateTypeDef DAL_SD_GetCardState(SD_HandleTypeDef *hsd); +DAL_StatusTypeDef DAL_SD_GetCardCID(SD_HandleTypeDef *hsd, DAL_SD_CardCIDTypeDef *pCID); +DAL_StatusTypeDef DAL_SD_GetCardCSD(SD_HandleTypeDef *hsd, DAL_SD_CardCSDTypeDef *pCSD); +DAL_StatusTypeDef DAL_SD_GetCardStatus(SD_HandleTypeDef *hsd, DAL_SD_CardStatusTypeDef *pStatus); +DAL_StatusTypeDef DAL_SD_GetCardInfo(SD_HandleTypeDef *hsd, DAL_SD_CardInfoTypeDef *pCardInfo); +/** + * @} + */ + +/** @defgroup SD_Exported_Functions_Group5 Peripheral State and Errors functions + * @{ + */ +DAL_SD_StateTypeDef DAL_SD_GetState(SD_HandleTypeDef *hsd); +uint32_t DAL_SD_GetError(SD_HandleTypeDef *hsd); +/** + * @} + */ + +/** @defgroup SD_Exported_Functions_Group6 Perioheral Abort management + * @{ + */ +DAL_StatusTypeDef DAL_SD_Abort(SD_HandleTypeDef *hsd); +DAL_StatusTypeDef DAL_SD_Abort_IT(SD_HandleTypeDef *hsd); +/** + * @} + */ + +/* Private types -------------------------------------------------------------*/ +/** @defgroup SD_Private_Types SD Private Types + * @{ + */ + +/** + * @} + */ + +/* Private defines -----------------------------------------------------------*/ +/** @defgroup SD_Private_Defines SD Private Defines + * @{ + */ + +/** + * @} + */ + +/* Private variables ---------------------------------------------------------*/ +/** @defgroup SD_Private_Variables SD Private Variables + * @{ + */ + +/** + * @} + */ + +/* Private constants ---------------------------------------------------------*/ +/** @defgroup SD_Private_Constants SD Private Constants + * @{ + */ + +/** + * @} + */ + +/* Private macros ------------------------------------------------------------*/ +/** @defgroup SD_Private_Macros SD Private Macros + * @{ + */ + +/** + * @} + */ + +/* Private functions prototypes ----------------------------------------------*/ +/** @defgroup SD_Private_Functions_Prototypes SD Private Functions Prototypes + * @{ + */ + +/** + * @} + */ + +/* Private functions ---------------------------------------------------------*/ +/** @defgroup SD_Private_Functions SD Private Functions + * @{ + */ + +/** + * @} + */ + + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#endif /* SDIO */ + +#ifdef __cplusplus +} +#endif + + +#endif /* APM32F4xx_DAL_SD_H */ diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_sdram.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_sdram.h new file mode 100644 index 0000000000..ddbce1b576 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_sdram.h @@ -0,0 +1,254 @@ +/** + * + * @file apm32f4xx_dal_sdram.h + * @brief Header file of SDRAM DAL module. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef APM32F4xx_DAL_SDRAM_H +#define APM32F4xx_DAL_SDRAM_H + +#ifdef __cplusplus +extern "C" { +#endif + +#if defined(DMC) + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_ddl_dmc.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @addtogroup SDRAM + * @{ + */ + +/* Exported typedef ----------------------------------------------------------*/ + +/** @defgroup SDRAM_Exported_Types SDRAM Exported Types + * @{ + */ + +/** + * @brief DAL SDRAM State structure definition + */ +typedef enum +{ + DAL_SDRAM_STATE_RESET = 0x00U, /*!< SDRAM not yet initialized or disabled */ + DAL_SDRAM_STATE_READY = 0x01U, /*!< SDRAM initialized and ready for use */ + DAL_SDRAM_STATE_BUSY = 0x02U, /*!< SDRAM internal process is ongoing */ + DAL_SDRAM_STATE_ERROR = 0x03U, /*!< SDRAM error state */ + DAL_SDRAM_STATE_WRITE_PROTECTED = 0x04U, /*!< SDRAM device write protected */ + DAL_SDRAM_STATE_PRECHARGED = 0x05U /*!< SDRAM device precharged */ + +} DAL_SDRAM_StateTypeDef; + +/** + * @brief SDRAM handle Structure definition + */ +#if (USE_DAL_SDRAM_REGISTER_CALLBACKS == 1) +typedef struct __SDRAM_HandleTypeDef +#else +typedef struct +#endif /* USE_DAL_SDRAM_REGISTER_CALLBACKS */ +{ + DMC_SDRAM_TypeDef *Instance; /*!< Register base address */ + + DMC_SDRAM_InitTypeDef Init; /*!< SDRAM device configuration parameters */ + + __IO DAL_SDRAM_StateTypeDef State; /*!< SDRAM access state */ + + DAL_LockTypeDef Lock; /*!< SDRAM locking object */ + + DMA_HandleTypeDef *hdma; /*!< Pointer DMA handler */ + +#if (USE_DAL_SDRAM_REGISTER_CALLBACKS == 1) + void (* MspInitCallback)(struct __SDRAM_HandleTypeDef *hsdram); /*!< SDRAM Msp Init callback */ + void (* MspDeInitCallback)(struct __SDRAM_HandleTypeDef *hsdram); /*!< SDRAM Msp DeInit callback */ + void (* DmaXferCpltCallback)(DMA_HandleTypeDef *hdma); /*!< SDRAM DMA Xfer Complete callback */ + void (* DmaXferErrorCallback)(DMA_HandleTypeDef *hdma); /*!< SDRAM DMA Xfer Error callback */ +#endif /* USE_DAL_SDRAM_REGISTER_CALLBACKS */ +} SDRAM_HandleTypeDef; + +#if (USE_DAL_SDRAM_REGISTER_CALLBACKS == 1) +/** + * @brief DAL SDRAM Callback ID enumeration definition + */ +typedef enum +{ + DAL_SDRAM_MSP_INIT_CB_ID = 0x00U, /*!< SDRAM MspInit Callback ID */ + DAL_SDRAM_MSP_DEINIT_CB_ID = 0x01U, /*!< SDRAM MspDeInit Callback ID */ + DAL_SDRAM_DMA_XFER_CPLT_CB_ID = 0x02U, /*!< SDRAM DMA Xfer Complete Callback ID */ + DAL_SDRAM_DMA_XFER_ERR_CB_ID = 0x03U /*!< SDRAM DMA Xfer Error Callback ID */ +} DAL_SDRAM_CallbackIDTypeDef; + +/** + * @brief DAL SDRAM Callback pointer definition + */ +typedef void (*pSDRAM_CallbackTypeDef)(SDRAM_HandleTypeDef *hsdram); +typedef void (*pSDRAM_DmaCallbackTypeDef)(DMA_HandleTypeDef *hdma); +#endif /* USE_DAL_SDRAM_REGISTER_CALLBACKS */ +/** + * @} + */ + +/* Exported constants --------------------------------------------------------*/ +/* Exported macro ------------------------------------------------------------*/ + +/** @defgroup SDRAM_Exported_Macros SDRAM Exported Macros + * @{ + */ + +/** @brief Reset SDRAM handle state + * @param __HANDLE__ specifies the SDRAM handle. + * @retval None + */ +#if (USE_DAL_SDRAM_REGISTER_CALLBACKS == 1) +#define __DAL_SDRAM_RESET_HANDLE_STATE(__HANDLE__) do { \ + (__HANDLE__)->State = DAL_SDRAM_STATE_RESET; \ + (__HANDLE__)->MspInitCallback = NULL; \ + (__HANDLE__)->MspDeInitCallback = NULL; \ + } while(0) +#else +#define __DAL_SDRAM_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = DAL_SDRAM_STATE_RESET) +#endif /* USE_DAL_SDRAM_REGISTER_CALLBACKS */ +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ + +/** @addtogroup SDRAM_Exported_Functions SDRAM Exported Functions + * @{ + */ + +/** @addtogroup SDRAM_Exported_Functions_Group1 + * @{ + */ + +/* Initialization/de-initialization functions *********************************/ +DAL_StatusTypeDef DAL_SDRAM_Init(SDRAM_HandleTypeDef *hsdram, DMC_SDRAM_TimingTypeDef *Timing); +DAL_StatusTypeDef DAL_SDRAM_DeInit(SDRAM_HandleTypeDef *hsdram); +void DAL_SDRAM_MspInit(SDRAM_HandleTypeDef *hsdram); +void DAL_SDRAM_MspDeInit(SDRAM_HandleTypeDef *hsdram); + +void DAL_SDRAM_DMA_XferCpltCallback(DMA_HandleTypeDef *hdma); +void DAL_SDRAM_DMA_XferErrorCallback(DMA_HandleTypeDef *hdma); + +/** + * @} + */ + +/** @addtogroup SDRAM_Exported_Functions_Group2 + * @{ + */ +/* I/O operation functions ****************************************************/ +DAL_StatusTypeDef DAL_SDRAM_Read_8b(SDRAM_HandleTypeDef *hsdram, uint32_t *pAddress, uint8_t *pDstBuffer, + uint32_t BufferSize); +DAL_StatusTypeDef DAL_SDRAM_Write_8b(SDRAM_HandleTypeDef *hsdram, uint32_t *pAddress, uint8_t *pSrcBuffer, + uint32_t BufferSize); +DAL_StatusTypeDef DAL_SDRAM_Read_16b(SDRAM_HandleTypeDef *hsdram, uint32_t *pAddress, uint16_t *pDstBuffer, + uint32_t BufferSize); +DAL_StatusTypeDef DAL_SDRAM_Write_16b(SDRAM_HandleTypeDef *hsdram, uint32_t *pAddress, uint16_t *pSrcBuffer, + uint32_t BufferSize); +DAL_StatusTypeDef DAL_SDRAM_Read_32b(SDRAM_HandleTypeDef *hsdram, uint32_t *pAddress, uint32_t *pDstBuffer, + uint32_t BufferSize); +DAL_StatusTypeDef DAL_SDRAM_Write_32b(SDRAM_HandleTypeDef *hsdram, uint32_t *pAddress, uint32_t *pSrcBuffer, + uint32_t BufferSize); + +DAL_StatusTypeDef DAL_SDRAM_Read_DMA(SDRAM_HandleTypeDef *hsdram, uint32_t *pAddress, uint32_t *pDstBuffer, + uint32_t BufferSize); +DAL_StatusTypeDef DAL_SDRAM_Write_DMA(SDRAM_HandleTypeDef *hsdram, uint32_t *pAddress, uint32_t *pSrcBuffer, + uint32_t BufferSize); + +#if (USE_DAL_SDRAM_REGISTER_CALLBACKS == 1) +/* SDRAM callback registering/unregistering */ +DAL_StatusTypeDef DAL_SDRAM_RegisterCallback(SDRAM_HandleTypeDef *hsdram, DAL_SDRAM_CallbackIDTypeDef CallbackId, + pSDRAM_CallbackTypeDef pCallback); +DAL_StatusTypeDef DAL_SDRAM_UnRegisterCallback(SDRAM_HandleTypeDef *hsdram, DAL_SDRAM_CallbackIDTypeDef CallbackId); +DAL_StatusTypeDef DAL_SDRAM_RegisterDmaCallback(SDRAM_HandleTypeDef *hsdram, DAL_SDRAM_CallbackIDTypeDef CallbackId, + pSDRAM_DmaCallbackTypeDef pCallback); +#endif /* USE_DAL_SDRAM_REGISTER_CALLBACKS */ + +/** + * @} + */ + +/** @addtogroup SDRAM_Exported_Functions_Group3 + * @{ + */ +/* SDRAM Control functions *****************************************************/ +DAL_StatusTypeDef DAL_SDRAM_ProgramRefreshPeriod(SDRAM_HandleTypeDef *hsdram, uint32_t RefreshPeriod); +DAL_StatusTypeDef DAL_SDRAM_SetOpenBankNumber(SDRAM_HandleTypeDef *hsdram, uint32_t OpenBankNumber); +uint32_t DAL_SDRAM_GetModeStatus(SDRAM_HandleTypeDef *hsdram); + +/** + * @} + */ + +/** @addtogroup SDRAM_Exported_Functions_Group4 + * @{ + */ +/* SDRAM State functions ********************************************************/ +DAL_SDRAM_StateTypeDef DAL_SDRAM_GetState(SDRAM_HandleTypeDef *hsdram); +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#endif /* DMC */ + +#ifdef __cplusplus +} +#endif + +#endif /* APM32F4xx_DAL_SDRAM_H */ diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_smartcard.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_smartcard.h new file mode 100644 index 0000000000..2909569a0f --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_smartcard.h @@ -0,0 +1,779 @@ +/** + * + * @file apm32f4xx_dal_smartcard.h + * @brief Header file of SMARTCARD DAL module. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef APM32F4xx_DAL_SMARTCARD_H +#define APM32F4xx_DAL_SMARTCARD_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal_def.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @addtogroup SMARTCARD + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ +/** @defgroup SMARTCARD_Exported_Types SMARTCARD Exported Types + * @{ + */ + +/** + * @brief SMARTCARD Init Structure definition + */ +typedef struct +{ + uint32_t BaudRate; /*!< This member configures the SmartCard communication baud rate. + The baud rate is computed using the following formula: + - IntegerDivider = ((PCLKx) / (16 * (hsc->Init.BaudRate))) + - FractionalDivider = ((IntegerDivider - ((uint32_t) IntegerDivider)) * 16) + 0.5 */ + + uint32_t WordLength; /*!< Specifies the number of data bits transmitted or received in a frame. + This parameter can be a value of @ref SMARTCARD_Word_Length */ + + uint32_t StopBits; /*!< Specifies the number of stop bits transmitted. + This parameter can be a value of @ref SMARTCARD_Stop_Bits */ + + uint32_t Parity; /*!< Specifies the parity mode. + This parameter can be a value of @ref SMARTCARD_Parity + @note When parity is enabled, the computed parity is inserted + at the MSB position of the transmitted data (9th bit when + the word length is set to 9 data bits; 8th bit when the + word length is set to 8 data bits).*/ + + uint32_t Mode; /*!< Specifies whether the Receive or Transmit mode is enabled or disabled. + This parameter can be a value of @ref SMARTCARD_Mode */ + + uint32_t CLKPolarity; /*!< Specifies the steady state of the serial clock. + This parameter can be a value of @ref SMARTCARD_Clock_Polarity */ + + uint32_t CLKPhase; /*!< Specifies the clock transition on which the bit capture is made. + This parameter can be a value of @ref SMARTCARD_Clock_Phase */ + + uint32_t CLKLastBit; /*!< Specifies whether the clock pulse corresponding to the last transmitted + data bit (MSB) has to be output on the SCLK pin in synchronous mode. + This parameter can be a value of @ref SMARTCARD_Last_Bit */ + + uint32_t Prescaler; /*!< Specifies the SmartCard Prescaler value used for dividing the system clock + to provide the smartcard clock. The value given in the register (5 significant bits) + is multiplied by 2 to give the division factor of the source clock frequency. + This parameter can be a value of @ref SMARTCARD_Prescaler */ + + uint32_t GuardTime; /*!< Specifies the SmartCard Guard Time value in terms of number of baud clocks */ + + uint32_t NACKState; /*!< Specifies the SmartCard NACK Transmission state. + This parameter can be a value of @ref SMARTCARD_NACK_State */ +}SMARTCARD_InitTypeDef; + +/** + * @brief DAL SMARTCARD State structures definition + * @note DAL SMARTCARD State value is a combination of 2 different substates: gState and RxState. + * - gState contains SMARTCARD state information related to global Handle management + * and also information related to Tx operations. + * gState value coding follow below described bitmap : + * b7-b6 Error information + * 00 : No Error + * 01 : (Not Used) + * 10 : Timeout + * 11 : Error + * b5 IP initialization status + * 0 : Reset (IP not initialized) + * 1 : Init done (IP initialized. DAL SMARTCARD Init function already called) + * b4-b3 (not used) + * xx : Should be set to 00 + * b2 Intrinsic process state + * 0 : Ready + * 1 : Busy (IP busy with some configuration or internal operations) + * b1 (not used) + * x : Should be set to 0 + * b0 Tx state + * 0 : Ready (no Tx operation ongoing) + * 1 : Busy (Tx operation ongoing) + * - RxState contains information related to Rx operations. + * RxState value coding follow below described bitmap : + * b7-b6 (not used) + * xx : Should be set to 00 + * b5 IP initialization status + * 0 : Reset (IP not initialized) + * 1 : Init done (IP initialized) + * b4-b2 (not used) + * xxx : Should be set to 000 + * b1 Rx state + * 0 : Ready (no Rx operation ongoing) + * 1 : Busy (Rx operation ongoing) + * b0 (not used) + * x : Should be set to 0. + */ +typedef enum +{ + DAL_SMARTCARD_STATE_RESET = 0x00U, /*!< Peripheral is not yet Initialized + Value is allowed for gState and RxState */ + DAL_SMARTCARD_STATE_READY = 0x20U, /*!< Peripheral Initialized and ready for use + Value is allowed for gState and RxState */ + DAL_SMARTCARD_STATE_BUSY = 0x24U, /*!< an internal process is ongoing + Value is allowed for gState only */ + DAL_SMARTCARD_STATE_BUSY_TX = 0x21U, /*!< Data Transmission process is ongoing + Value is allowed for gState only */ + DAL_SMARTCARD_STATE_BUSY_RX = 0x22U, /*!< Data Reception process is ongoing + Value is allowed for RxState only */ + DAL_SMARTCARD_STATE_BUSY_TX_RX = 0x23U, /*!< Data Transmission and Reception process is ongoing + Not to be used for neither gState nor RxState. + Value is result of combination (Or) between gState and RxState values */ + DAL_SMARTCARD_STATE_TIMEOUT = 0xA0U, /*!< Timeout state + Value is allowed for gState only */ + DAL_SMARTCARD_STATE_ERROR = 0xE0U /*!< Error + Value is allowed for gState only */ +}DAL_SMARTCARD_StateTypeDef; + +/** + * @brief SMARTCARD handle Structure definition + */ +typedef struct __SMARTCARD_HandleTypeDef +{ + USART_TypeDef *Instance; /*!< USART registers base address */ + + SMARTCARD_InitTypeDef Init; /*!< SmartCard communication parameters */ + + const uint8_t *pTxBuffPtr; /*!< Pointer to SmartCard Tx transfer Buffer */ + + uint16_t TxXferSize; /*!< SmartCard Tx Transfer size */ + + __IO uint16_t TxXferCount; /*!< SmartCard Tx Transfer Counter */ + + uint8_t *pRxBuffPtr; /*!< Pointer to SmartCard Rx transfer Buffer */ + + uint16_t RxXferSize; /*!< SmartCard Rx Transfer size */ + + __IO uint16_t RxXferCount; /*!< SmartCard Rx Transfer Counter */ + + DMA_HandleTypeDef *hdmatx; /*!< SmartCard Tx DMA Handle parameters */ + + DMA_HandleTypeDef *hdmarx; /*!< SmartCard Rx DMA Handle parameters */ + + DAL_LockTypeDef Lock; /*!< Locking object */ + + __IO DAL_SMARTCARD_StateTypeDef gState; /*!< SmartCard state information related to global Handle management + and also related to Tx operations. + This parameter can be a value of @ref DAL_SMARTCARD_StateTypeDef */ + + __IO DAL_SMARTCARD_StateTypeDef RxState; /*!< SmartCard state information related to Rx operations. + This parameter can be a value of @ref DAL_SMARTCARD_StateTypeDef */ + + __IO uint32_t ErrorCode; /*!< SmartCard Error code */ + +#if (USE_DAL_SMARTCARD_REGISTER_CALLBACKS == 1) + void (* TxCpltCallback)(struct __SMARTCARD_HandleTypeDef *hsc); /*!< SMARTCARD Tx Complete Callback */ + + void (* RxCpltCallback)(struct __SMARTCARD_HandleTypeDef *hsc); /*!< SMARTCARD Rx Complete Callback */ + + void (* ErrorCallback)(struct __SMARTCARD_HandleTypeDef *hsc); /*!< SMARTCARD Error Callback */ + + void (* AbortCpltCallback)(struct __SMARTCARD_HandleTypeDef *hsc); /*!< SMARTCARD Abort Complete Callback */ + + void (* AbortTransmitCpltCallback)(struct __SMARTCARD_HandleTypeDef *hsc); /*!< SMARTCARD Abort Transmit Complete Callback */ + + void (* AbortReceiveCpltCallback)(struct __SMARTCARD_HandleTypeDef *hsc); /*!< SMARTCARD Abort Receive Complete Callback */ + + void (* MspInitCallback)(struct __SMARTCARD_HandleTypeDef *hsc); /*!< SMARTCARD Msp Init callback */ + + void (* MspDeInitCallback)(struct __SMARTCARD_HandleTypeDef *hsc); /*!< SMARTCARD Msp DeInit callback */ +#endif /* USE_DAL_SMARTCARD_REGISTER_CALLBACKS */ + +} SMARTCARD_HandleTypeDef; + +#if (USE_DAL_SMARTCARD_REGISTER_CALLBACKS == 1) +/** + * @brief DAL SMARTCARD Callback ID enumeration definition + */ +typedef enum +{ + DAL_SMARTCARD_TX_COMPLETE_CB_ID = 0x00U, /*!< SMARTCARD Tx Complete Callback ID */ + DAL_SMARTCARD_RX_COMPLETE_CB_ID = 0x01U, /*!< SMARTCARD Rx Complete Callback ID */ + DAL_SMARTCARD_ERROR_CB_ID = 0x02U, /*!< SMARTCARD Error Callback ID */ + DAL_SMARTCARD_ABORT_COMPLETE_CB_ID = 0x03U, /*!< SMARTCARD Abort Complete Callback ID */ + DAL_SMARTCARD_ABORT_TRANSMIT_COMPLETE_CB_ID = 0x04U, /*!< SMARTCARD Abort Transmit Complete Callback ID */ + DAL_SMARTCARD_ABORT_RECEIVE_COMPLETE_CB_ID = 0x05U, /*!< SMARTCARD Abort Receive Complete Callback ID */ + + DAL_SMARTCARD_MSPINIT_CB_ID = 0x08U, /*!< SMARTCARD MspInit callback ID */ + DAL_SMARTCARD_MSPDEINIT_CB_ID = 0x09U /*!< SMARTCARD MspDeInit callback ID */ + +} DAL_SMARTCARD_CallbackIDTypeDef; + +/** + * @brief DAL SMARTCARD Callback pointer definition + */ +typedef void (*pSMARTCARD_CallbackTypeDef)(SMARTCARD_HandleTypeDef *hsc); /*!< pointer to an SMARTCARD callback function */ + +#endif /* USE_DAL_SMARTCARD_REGISTER_CALLBACKS */ + +/** + * @} + */ + +/* Exported constants --------------------------------------------------------*/ +/** @defgroup SMARTCARD_Exported_Constants SMARTCARD Exported constants + * @{ + */ + +/** @defgroup SMARTCARD_Error_Code SMARTCARD Error Code + * @{ + */ +#define DAL_SMARTCARD_ERROR_NONE 0x00000000U /*!< No error */ +#define DAL_SMARTCARD_ERROR_PE 0x00000001U /*!< Parity error */ +#define DAL_SMARTCARD_ERROR_NE 0x00000002U /*!< Noise error */ +#define DAL_SMARTCARD_ERROR_FE 0x00000004U /*!< Frame error */ +#define DAL_SMARTCARD_ERROR_ORE 0x00000008U /*!< Overrun error */ +#define DAL_SMARTCARD_ERROR_DMA 0x00000010U /*!< DMA transfer error */ +#if (USE_DAL_SMARTCARD_REGISTER_CALLBACKS == 1) +#define DAL_SMARTCARD_ERROR_INVALID_CALLBACK 0x00000020U /*!< Invalid Callback error */ +#endif /* USE_DAL_SMARTCARD_REGISTER_CALLBACKS */ +/** + * @} + */ + +/** @defgroup SMARTCARD_Word_Length SMARTCARD Word Length + * @{ + */ +#define SMARTCARD_WORDLENGTH_9B ((uint32_t)USART_CTRL1_DBLCFG) +/** + * @} + */ + +/** @defgroup SMARTCARD_Stop_Bits SMARTCARD Number of Stop Bits + * @{ + */ +#define SMARTCARD_STOPBITS_0_5 ((uint32_t)USART_CTRL2_STOPCFG_0) +#define SMARTCARD_STOPBITS_1_5 ((uint32_t)(USART_CTRL2_STOPCFG_0 | USART_CTRL2_STOPCFG_1)) +/** + * @} + */ + +/** @defgroup SMARTCARD_Parity SMARTCARD Parity + * @{ + */ +#define SMARTCARD_PARITY_EVEN ((uint32_t)USART_CTRL1_PCEN) +#define SMARTCARD_PARITY_ODD ((uint32_t)(USART_CTRL1_PCEN | USART_CTRL1_PCFG)) +/** + * @} + */ + +/** @defgroup SMARTCARD_Mode SMARTCARD Mode + * @{ + */ +#define SMARTCARD_MODE_RX ((uint32_t)USART_CTRL1_RXEN) +#define SMARTCARD_MODE_TX ((uint32_t)USART_CTRL1_TXEN) +#define SMARTCARD_MODE_TX_RX ((uint32_t)(USART_CTRL1_TXEN |USART_CTRL1_RXEN)) +/** + * @} + */ + +/** @defgroup SMARTCARD_Clock_Polarity SMARTCARD Clock Polarity + * @{ + */ +#define SMARTCARD_POLARITY_LOW 0x00000000U +#define SMARTCARD_POLARITY_HIGH ((uint32_t)USART_CTRL2_CPOL) +/** + * @} + */ + +/** @defgroup SMARTCARD_Clock_Phase SMARTCARD Clock Phase + * @{ + */ +#define SMARTCARD_PHASE_1EDGE 0x00000000U +#define SMARTCARD_PHASE_2EDGE ((uint32_t)USART_CTRL2_CPHA) +/** + * @} + */ + +/** @defgroup SMARTCARD_Last_Bit SMARTCARD Last Bit + * @{ + */ +#define SMARTCARD_LASTBIT_DISABLE 0x00000000U +#define SMARTCARD_LASTBIT_ENABLE ((uint32_t)USART_CTRL2_LBCPOEN) +/** + * @} + */ + +/** @defgroup SMARTCARD_NACK_State SMARTCARD NACK State + * @{ + */ +#define SMARTCARD_NACK_ENABLE ((uint32_t)USART_CTRL3_SCNACKEN) +#define SMARTCARD_NACK_DISABLE 0x00000000U +/** + * @} + */ + +/** @defgroup SMARTCARD_DMA_Requests SMARTCARD DMA requests + * @{ + */ +#define SMARTCARD_DMAREQ_TX ((uint32_t)USART_CTRL3_DMATXEN) +#define SMARTCARD_DMAREQ_RX ((uint32_t)USART_CTRL3_DMARXEN) +/** + * @} + */ + +/** @defgroup SMARTCARD_Prescaler SMARTCARD Prescaler + * @{ + */ +#define SMARTCARD_PRESCALER_SYSCLK_DIV2 0x00000001U /*!< SYSCLK divided by 2 */ +#define SMARTCARD_PRESCALER_SYSCLK_DIV4 0x00000002U /*!< SYSCLK divided by 4 */ +#define SMARTCARD_PRESCALER_SYSCLK_DIV6 0x00000003U /*!< SYSCLK divided by 6 */ +#define SMARTCARD_PRESCALER_SYSCLK_DIV8 0x00000004U /*!< SYSCLK divided by 8 */ +#define SMARTCARD_PRESCALER_SYSCLK_DIV10 0x00000005U /*!< SYSCLK divided by 10 */ +#define SMARTCARD_PRESCALER_SYSCLK_DIV12 0x00000006U /*!< SYSCLK divided by 12 */ +#define SMARTCARD_PRESCALER_SYSCLK_DIV14 0x00000007U /*!< SYSCLK divided by 14 */ +#define SMARTCARD_PRESCALER_SYSCLK_DIV16 0x00000008U /*!< SYSCLK divided by 16 */ +#define SMARTCARD_PRESCALER_SYSCLK_DIV18 0x00000009U /*!< SYSCLK divided by 18 */ +#define SMARTCARD_PRESCALER_SYSCLK_DIV20 0x0000000AU /*!< SYSCLK divided by 20 */ +#define SMARTCARD_PRESCALER_SYSCLK_DIV22 0x0000000BU /*!< SYSCLK divided by 22 */ +#define SMARTCARD_PRESCALER_SYSCLK_DIV24 0x0000000CU /*!< SYSCLK divided by 24 */ +#define SMARTCARD_PRESCALER_SYSCLK_DIV26 0x0000000DU /*!< SYSCLK divided by 26 */ +#define SMARTCARD_PRESCALER_SYSCLK_DIV28 0x0000000EU /*!< SYSCLK divided by 28 */ +#define SMARTCARD_PRESCALER_SYSCLK_DIV30 0x0000000FU /*!< SYSCLK divided by 30 */ +#define SMARTCARD_PRESCALER_SYSCLK_DIV32 0x00000010U /*!< SYSCLK divided by 32 */ +#define SMARTCARD_PRESCALER_SYSCLK_DIV34 0x00000011U /*!< SYSCLK divided by 34 */ +#define SMARTCARD_PRESCALER_SYSCLK_DIV36 0x00000012U /*!< SYSCLK divided by 36 */ +#define SMARTCARD_PRESCALER_SYSCLK_DIV38 0x00000013U /*!< SYSCLK divided by 38 */ +#define SMARTCARD_PRESCALER_SYSCLK_DIV40 0x00000014U /*!< SYSCLK divided by 40 */ +#define SMARTCARD_PRESCALER_SYSCLK_DIV42 0x00000015U /*!< SYSCLK divided by 42 */ +#define SMARTCARD_PRESCALER_SYSCLK_DIV44 0x00000016U /*!< SYSCLK divided by 44 */ +#define SMARTCARD_PRESCALER_SYSCLK_DIV46 0x00000017U /*!< SYSCLK divided by 46 */ +#define SMARTCARD_PRESCALER_SYSCLK_DIV48 0x00000018U /*!< SYSCLK divided by 48 */ +#define SMARTCARD_PRESCALER_SYSCLK_DIV50 0x00000019U /*!< SYSCLK divided by 50 */ +#define SMARTCARD_PRESCALER_SYSCLK_DIV52 0x0000001AU /*!< SYSCLK divided by 52 */ +#define SMARTCARD_PRESCALER_SYSCLK_DIV54 0x0000001BU /*!< SYSCLK divided by 54 */ +#define SMARTCARD_PRESCALER_SYSCLK_DIV56 0x0000001CU /*!< SYSCLK divided by 56 */ +#define SMARTCARD_PRESCALER_SYSCLK_DIV58 0x0000001DU /*!< SYSCLK divided by 58 */ +#define SMARTCARD_PRESCALER_SYSCLK_DIV60 0x0000001EU /*!< SYSCLK divided by 60 */ +#define SMARTCARD_PRESCALER_SYSCLK_DIV62 0x0000001FU /*!< SYSCLK divided by 62 */ +/** + * @} + */ + +/** @defgroup SmartCard_Flags SMARTCARD Flags + * Elements values convention: 0xXXXX + * - 0xXXXX : Flag mask in the SR register + * @{ + */ +#define SMARTCARD_FLAG_TXE ((uint32_t)USART_STS_TXBEFLG) +#define SMARTCARD_FLAG_TC ((uint32_t)USART_STS_TXCFLG) +#define SMARTCARD_FLAG_RXNE ((uint32_t)USART_STS_RXBNEFLG) +#define SMARTCARD_FLAG_IDLE ((uint32_t)USART_STS_IDLEFLG) +#define SMARTCARD_FLAG_ORE ((uint32_t)USART_STS_OVREFLG) +#define SMARTCARD_FLAG_NE ((uint32_t)USART_STS_NEFLG) +#define SMARTCARD_FLAG_FE ((uint32_t)USART_STS_FEFLG) +#define SMARTCARD_FLAG_PE ((uint32_t)USART_STS_PEFLG) +/** + * @} + */ + +/** @defgroup SmartCard_Interrupt_definition SMARTCARD Interrupts Definition + * Elements values convention: 0xY000XXXX + * - XXXX : Interrupt mask in the Y register + * - Y : Interrupt source register (2bits) + * - 01: CTRL1 register + * - 11: CTRL3 register + * @{ + */ +#define SMARTCARD_IT_PE ((uint32_t)(SMARTCARD_CTRL1_REG_INDEX << 28U | USART_CTRL1_PEIEN)) +#define SMARTCARD_IT_TXE ((uint32_t)(SMARTCARD_CTRL1_REG_INDEX << 28U | USART_CTRL1_TXBEIEN)) +#define SMARTCARD_IT_TC ((uint32_t)(SMARTCARD_CTRL1_REG_INDEX << 28U | USART_CTRL1_TXCIEN)) +#define SMARTCARD_IT_RXNE ((uint32_t)(SMARTCARD_CTRL1_REG_INDEX << 28U | USART_CTRL1_RXBNEIEN)) +#define SMARTCARD_IT_IDLE ((uint32_t)(SMARTCARD_CTRL1_REG_INDEX << 28U | USART_CTRL1_IDLEIEN)) +#define SMARTCARD_IT_ERR ((uint32_t)(SMARTCARD_CTRL3_REG_INDEX << 28U | USART_CTRL3_ERRIEN)) +/** + * @} + */ + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ +/** @defgroup SMARTCARD_Exported_Macros SMARTCARD Exported Macros + * @{ + */ + +/** @brief Reset SMARTCARD handle gstate & RxState + * @param __HANDLE__ specifies the SMARTCARD Handle. + * SMARTCARD Handle selects the USARTx peripheral (USART availability and x value depending on device). + * @retval None + */ +#if USE_DAL_SMARTCARD_REGISTER_CALLBACKS == 1 +#define __DAL_SMARTCARD_RESET_HANDLE_STATE(__HANDLE__) do{ \ + (__HANDLE__)->gState = DAL_SMARTCARD_STATE_RESET; \ + (__HANDLE__)->RxState = DAL_SMARTCARD_STATE_RESET; \ + (__HANDLE__)->MspInitCallback = NULL; \ + (__HANDLE__)->MspDeInitCallback = NULL; \ + } while(0U) +#else +#define __DAL_SMARTCARD_RESET_HANDLE_STATE(__HANDLE__) do{ \ + (__HANDLE__)->gState = DAL_SMARTCARD_STATE_RESET; \ + (__HANDLE__)->RxState = DAL_SMARTCARD_STATE_RESET; \ + } while(0U) +#endif /*USE_DAL_SMARTCARD_REGISTER_CALLBACKS */ + +/** @brief Flush the Smartcard DATA register + * @param __HANDLE__ specifies the SMARTCARD Handle. + * SMARTCARD Handle selects the USARTx peripheral (USART availability and x value depending on device). + * @retval None + */ +#define __DAL_SMARTCARD_FLUSH_DRREGISTER(__HANDLE__) ((__HANDLE__)->Instance->DATA) + +/** @brief Check whether the specified Smartcard flag is set or not. + * @param __HANDLE__ specifies the SMARTCARD Handle. + * SMARTCARD Handle selects the USARTx peripheral (USART availability and x value depending on device). + * @param __FLAG__ specifies the flag to check. + * This parameter can be one of the following values: + * @arg SMARTCARD_FLAG_TXE: Transmit data register empty flag + * @arg SMARTCARD_FLAG_TC: Transmission Complete flag + * @arg SMARTCARD_FLAG_RXNE: Receive data register not empty flag + * @arg SMARTCARD_FLAG_IDLE: Idle Line detection flag + * @arg SMARTCARD_FLAG_ORE: Overrun Error flag + * @arg SMARTCARD_FLAG_NE: Noise Error flag + * @arg SMARTCARD_FLAG_FE: Framing Error flag + * @arg SMARTCARD_FLAG_PE: Parity Error flag + * @retval The new state of __FLAG__ (TRUE or FALSE). + */ +#define __DAL_SMARTCARD_GET_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->STS & (__FLAG__)) == (__FLAG__)) + +/** @brief Clear the specified Smartcard pending flags. + * @param __HANDLE__ specifies the SMARTCARD Handle. + * SMARTCARD Handle selects the USARTx peripheral (USART availability and x value depending on device). + * @param __FLAG__ specifies the flag to check. + * This parameter can be any combination of the following values: + * @arg SMARTCARD_FLAG_TC: Transmission Complete flag. + * @arg SMARTCARD_FLAG_RXNE: Receive data register not empty flag. + * + * @note PE (Parity error), FE (Framing error), NE (Noise error) and ORE (Overrun + * error) flags are cleared by software sequence: a read operation to + * USART_STS register followed by a read operation to USART_DATA register. + * @note RXNE flag can be also cleared by a read to the USART_DATA register. + * @note TC flag can be also cleared by software sequence: a read operation to + * USART_STS register followed by a write operation to USART_DATA register. + * @note TXE flag is cleared only by a write to the USART_DATA register. + * @retval None + */ +#define __DAL_SMARTCARD_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->STS = ~(__FLAG__)) + +/** @brief Clear the SMARTCARD PE pending flag. + * @param __HANDLE__ specifies the USART Handle. + * SMARTCARD Handle selects the USARTx peripheral (USART availability and x value depending on device). + * @retval None + */ +#define __DAL_SMARTCARD_CLEAR_PEFLAG(__HANDLE__) \ + do{ \ + __IO uint32_t tmpreg = 0x00U; \ + tmpreg = (__HANDLE__)->Instance->STS; \ + tmpreg = (__HANDLE__)->Instance->DATA; \ + UNUSED(tmpreg); \ + } while(0U) + +/** @brief Clear the SMARTCARD FE pending flag. + * @param __HANDLE__ specifies the USART Handle. + * SMARTCARD Handle selects the USARTx peripheral (USART availability and x value depending on device). + * @retval None + */ +#define __DAL_SMARTCARD_CLEAR_FEFLAG(__HANDLE__) __DAL_SMARTCARD_CLEAR_PEFLAG(__HANDLE__) + +/** @brief Clear the SMARTCARD NE pending flag. + * @param __HANDLE__ specifies the USART Handle. + * SMARTCARD Handle selects the USARTx peripheral (USART availability and x value depending on device). + * @retval None + */ +#define __DAL_SMARTCARD_CLEAR_NEFLAG(__HANDLE__) __DAL_SMARTCARD_CLEAR_PEFLAG(__HANDLE__) + +/** @brief Clear the SMARTCARD ORE pending flag. + * @param __HANDLE__ specifies the USART Handle. + * SMARTCARD Handle selects the USARTx peripheral (USART availability and x value depending on device). + * @retval None + */ +#define __DAL_SMARTCARD_CLEAR_OREFLAG(__HANDLE__) __DAL_SMARTCARD_CLEAR_PEFLAG(__HANDLE__) + +/** @brief Clear the SMARTCARD IDLE pending flag. + * @param __HANDLE__ specifies the USART Handle. + * SMARTCARD Handle selects the USARTx peripheral (USART availability and x value depending on device). + * @retval None + */ +#define __DAL_SMARTCARD_CLEAR_IDLEFLAG(__HANDLE__) __DAL_SMARTCARD_CLEAR_PEFLAG(__HANDLE__) + +/** @brief Enable the specified SmartCard interrupt. + * @param __HANDLE__ specifies the SMARTCARD Handle. + * SMARTCARD Handle selects the USARTx peripheral (USART availability and x value depending on device). + * @param __INTERRUPT__ specifies the SMARTCARD interrupt to enable. + * This parameter can be one of the following values: + * @arg SMARTCARD_IT_TXE: Transmit Data Register empty interrupt + * @arg SMARTCARD_IT_TC: Transmission complete interrupt + * @arg SMARTCARD_IT_RXNE: Receive Data register not empty interrupt + * @arg SMARTCARD_IT_IDLE: Idle line detection interrupt + * @arg SMARTCARD_IT_PE: Parity Error interrupt + * @arg SMARTCARD_IT_ERR: Error interrupt(Frame error, noise error, overrun error) + * @retval None + */ +#define __DAL_SMARTCARD_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((((__INTERRUPT__) >> 28U) == SMARTCARD_CTRL1_REG_INDEX)? ((__HANDLE__)->Instance->CTRL1 |= ((__INTERRUPT__) & SMARTCARD_IT_MASK)): \ + ((__HANDLE__)->Instance->CTRL3 |= ((__INTERRUPT__) & SMARTCARD_IT_MASK))) + +/** @brief Disable the specified SmartCard interrupt. + * @param __HANDLE__ specifies the SMARTCARD Handle. + * SMARTCARD Handle selects the USARTx peripheral (USART availability and x value depending on device). + * @param __INTERRUPT__ specifies the SMARTCARD interrupt to disable. + * This parameter can be one of the following values: + * @arg SMARTCARD_IT_TXE: Transmit Data Register empty interrupt + * @arg SMARTCARD_IT_TC: Transmission complete interrupt + * @arg SMARTCARD_IT_RXNE: Receive Data register not empty interrupt + * @arg SMARTCARD_IT_IDLE: Idle line detection interrupt + * @arg SMARTCARD_IT_PE: Parity Error interrupt + * @arg SMARTCARD_IT_ERR: Error interrupt(Frame error, noise error, overrun error) + * @retval None + */ +#define __DAL_SMARTCARD_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((((__INTERRUPT__) >> 28U) == SMARTCARD_CTRL1_REG_INDEX)? ((__HANDLE__)->Instance->CTRL1 &= ~((__INTERRUPT__) & SMARTCARD_IT_MASK)): \ + ((__HANDLE__)->Instance->CTRL3 &= ~ ((__INTERRUPT__) & SMARTCARD_IT_MASK))) + +/** @brief Checks whether the specified SmartCard interrupt has occurred or not. + * @param __HANDLE__ specifies the SmartCard Handle. + * @param __IT__ specifies the SMARTCARD interrupt source to check. + * This parameter can be one of the following values: + * @arg SMARTCARD_IT_TXE: Transmit Data Register empty interrupt + * @arg SMARTCARD_IT_TC: Transmission complete interrupt + * @arg SMARTCARD_IT_RXNE: Receive Data register not empty interrupt + * @arg SMARTCARD_IT_IDLE: Idle line detection interrupt + * @arg SMARTCARD_IT_ERR: Error interrupt + * @arg SMARTCARD_IT_PE: Parity Error interrupt + * @retval The new state of __IT__ (TRUE or FALSE). + */ +#define __DAL_SMARTCARD_GET_IT_SOURCE(__HANDLE__, __IT__) (((((__IT__) >> 28U) == SMARTCARD_CTRL1_REG_INDEX)? (__HANDLE__)->Instance->CTRL1: (__HANDLE__)->Instance->CTRL3) & (((uint32_t)(__IT__)) & SMARTCARD_IT_MASK)) + +/** @brief Macro to enable the SMARTCARD's one bit sample method + * @param __HANDLE__ specifies the SMARTCARD Handle. + * @retval None + */ +#define __DAL_SMARTCARD_ONE_BIT_SAMPLE_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CTRL3|= USART_CTRL3_SAMCFG) + +/** @brief Macro to disable the SMARTCARD's one bit sample method + * @param __HANDLE__ specifies the SMARTCARD Handle. + * @retval None + */ +#define __DAL_SMARTCARD_ONE_BIT_SAMPLE_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CTRL3 &= (uint16_t)~((uint16_t)USART_CTRL3_SAMCFG)) + +/** @brief Enable the USART associated to the SMARTCARD Handle + * @param __HANDLE__ specifies the SMARTCARD Handle. + * SMARTCARD Handle selects the USARTx peripheral (USART availability and x value depending on device). + * @retval None + */ +#define __DAL_SMARTCARD_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CTRL1 |= USART_CTRL1_UEN) + +/** @brief Disable the USART associated to the SMARTCARD Handle + * @param __HANDLE__ specifies the SMARTCARD Handle. + * SMARTCARD Handle selects the USARTx peripheral (USART availability and x value depending on device). + * @retval None + */ +#define __DAL_SMARTCARD_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CTRL1 &= ~USART_CTRL1_UEN) + +/** @brief Macros to enable the SmartCard DMA request. + * @param __HANDLE__ specifies the SmartCard Handle. + * @param __REQUEST__ specifies the SmartCard DMA request. + * This parameter can be one of the following values: + * @arg SMARTCARD_DMAREQ_TX: SmartCard DMA transmit request + * @arg SMARTCARD_DMAREQ_RX: SmartCard DMA receive request + * @retval None + */ +#define __DAL_SMARTCARD_DMA_REQUEST_ENABLE(__HANDLE__, __REQUEST__) ((__HANDLE__)->Instance->CTRL3 |= (__REQUEST__)) + +/** @brief Macros to disable the SmartCard DMA request. + * @param __HANDLE__ specifies the SmartCard Handle. + * @param __REQUEST__ specifies the SmartCard DMA request. + * This parameter can be one of the following values: + * @arg SMARTCARD_DMAREQ_TX: SmartCard DMA transmit request + * @arg SMARTCARD_DMAREQ_RX: SmartCard DMA receive request + * @retval None + */ +#define __DAL_SMARTCARD_DMA_REQUEST_DISABLE(__HANDLE__, __REQUEST__) ((__HANDLE__)->Instance->CTRL3 &= ~(__REQUEST__)) + +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup SMARTCARD_Exported_Functions + * @{ + */ + +/** @addtogroup SMARTCARD_Exported_Functions_Group1 + * @{ + */ +/* Initialization/de-initialization functions **********************************/ +DAL_StatusTypeDef DAL_SMARTCARD_Init(SMARTCARD_HandleTypeDef *hsc); +DAL_StatusTypeDef DAL_SMARTCARD_ReInit(SMARTCARD_HandleTypeDef *hsc); +DAL_StatusTypeDef DAL_SMARTCARD_DeInit(SMARTCARD_HandleTypeDef *hsc); +void DAL_SMARTCARD_MspInit(SMARTCARD_HandleTypeDef *hsc); +void DAL_SMARTCARD_MspDeInit(SMARTCARD_HandleTypeDef *hsc); +#if (USE_DAL_SMARTCARD_REGISTER_CALLBACKS == 1) +/* Callbacks Register/UnRegister functions ***********************************/ +DAL_StatusTypeDef DAL_SMARTCARD_RegisterCallback(SMARTCARD_HandleTypeDef *hsc, DAL_SMARTCARD_CallbackIDTypeDef CallbackID, pSMARTCARD_CallbackTypeDef pCallback); +DAL_StatusTypeDef DAL_SMARTCARD_UnRegisterCallback(SMARTCARD_HandleTypeDef *hsc, DAL_SMARTCARD_CallbackIDTypeDef CallbackID); +#endif /* USE_DAL_SMARTCARD_REGISTER_CALLBACKS */ +/** + * @} + */ + +/** @addtogroup SMARTCARD_Exported_Functions_Group2 + * @{ + */ +/* IO operation functions *******************************************************/ +DAL_StatusTypeDef DAL_SMARTCARD_Transmit(SMARTCARD_HandleTypeDef *hsc, const uint8_t *pData, uint16_t Size, uint32_t Timeout); +DAL_StatusTypeDef DAL_SMARTCARD_Receive(SMARTCARD_HandleTypeDef *hsc, uint8_t *pData, uint16_t Size, uint32_t Timeout); +DAL_StatusTypeDef DAL_SMARTCARD_Transmit_IT(SMARTCARD_HandleTypeDef *hsc, const uint8_t *pData, uint16_t Size); +DAL_StatusTypeDef DAL_SMARTCARD_Receive_IT(SMARTCARD_HandleTypeDef *hsc, uint8_t *pData, uint16_t Size); +DAL_StatusTypeDef DAL_SMARTCARD_Transmit_DMA(SMARTCARD_HandleTypeDef *hsc, const uint8_t *pData, uint16_t Size); +DAL_StatusTypeDef DAL_SMARTCARD_Receive_DMA(SMARTCARD_HandleTypeDef *hsc, uint8_t *pData, uint16_t Size); +/* Transfer Abort functions */ +DAL_StatusTypeDef DAL_SMARTCARD_Abort(SMARTCARD_HandleTypeDef *hsc); +DAL_StatusTypeDef DAL_SMARTCARD_AbortTransmit(SMARTCARD_HandleTypeDef *hsc); +DAL_StatusTypeDef DAL_SMARTCARD_AbortReceive(SMARTCARD_HandleTypeDef *hsc); +DAL_StatusTypeDef DAL_SMARTCARD_Abort_IT(SMARTCARD_HandleTypeDef *hsc); +DAL_StatusTypeDef DAL_SMARTCARD_AbortTransmit_IT(SMARTCARD_HandleTypeDef *hsc); +DAL_StatusTypeDef DAL_SMARTCARD_AbortReceive_IT(SMARTCARD_HandleTypeDef *hsc); + +void DAL_SMARTCARD_IRQHandler(SMARTCARD_HandleTypeDef *hsc); +void DAL_SMARTCARD_TxCpltCallback(SMARTCARD_HandleTypeDef *hsc); +void DAL_SMARTCARD_RxCpltCallback(SMARTCARD_HandleTypeDef *hsc); +void DAL_SMARTCARD_ErrorCallback(SMARTCARD_HandleTypeDef *hsc); +void DAL_SMARTCARD_AbortCpltCallback(SMARTCARD_HandleTypeDef *hsc); +void DAL_SMARTCARD_AbortTransmitCpltCallback(SMARTCARD_HandleTypeDef *hsc); +void DAL_SMARTCARD_AbortReceiveCpltCallback(SMARTCARD_HandleTypeDef *hsc); +/** + * @} + */ + +/** @addtogroup SMARTCARD_Exported_Functions_Group3 + * @{ + */ +/* Peripheral State functions **************************************************/ +DAL_SMARTCARD_StateTypeDef DAL_SMARTCARD_GetState(SMARTCARD_HandleTypeDef *hsc); +uint32_t DAL_SMARTCARD_GetError(SMARTCARD_HandleTypeDef *hsc); +/** + * @} + */ + +/** + * @} + */ +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/** @defgroup SMARTCARD_Private_Constants SMARTCARD Private Constants + * @{ + */ + +/** @brief SMARTCARD interruptions flag mask + * + */ +#define SMARTCARD_IT_MASK ((uint32_t) USART_CTRL1_PEIEN | USART_CTRL1_TXBEIEN | USART_CTRL1_TXCIEN | USART_CTRL1_RXBNEIEN | \ + USART_CTRL1_IDLEIEN | USART_CTRL3_ERRIEN ) + +#define SMARTCARD_CTRL1_REG_INDEX 1U +#define SMARTCARD_CTRL3_REG_INDEX 3U +/** + * @} + */ + +/* Private macros --------------------------------------------------------*/ +/** @defgroup SMARTCARD_Private_Macros SMARTCARD Private Macros + * @{ + */ +#define IS_SMARTCARD_WORD_LENGTH(LENGTH) ((LENGTH) == SMARTCARD_WORDLENGTH_9B) +#define IS_SMARTCARD_STOPBITS(STOPBITS) (((STOPBITS) == SMARTCARD_STOPBITS_0_5) || \ + ((STOPBITS) == SMARTCARD_STOPBITS_1_5)) +#define IS_SMARTCARD_PARITY(PARITY) (((PARITY) == SMARTCARD_PARITY_EVEN) || \ + ((PARITY) == SMARTCARD_PARITY_ODD)) +#define IS_SMARTCARD_MODE(MODE) ((((MODE) & 0x0000FFF3U) == 0x00U) && ((MODE) != 0x000000U)) +#define IS_SMARTCARD_POLARITY(CPOL) (((CPOL) == SMARTCARD_POLARITY_LOW) || ((CPOL) == SMARTCARD_POLARITY_HIGH)) +#define IS_SMARTCARD_PHASE(CPHA) (((CPHA) == SMARTCARD_PHASE_1EDGE) || ((CPHA) == SMARTCARD_PHASE_2EDGE)) +#define IS_SMARTCARD_LASTBIT(LASTBIT) (((LASTBIT) == SMARTCARD_LASTBIT_DISABLE) || \ + ((LASTBIT) == SMARTCARD_LASTBIT_ENABLE)) +#define IS_SMARTCARD_NACK_STATE(NACK) (((NACK) == SMARTCARD_NACK_ENABLE) || \ + ((NACK) == SMARTCARD_NACK_DISABLE)) +#define IS_SMARTCARD_BAUDRATE(BAUDRATE) ((BAUDRATE) < 10500001U) + +#define SMARTCARD_DIV(__PCLK__, __BAUD__) ((uint32_t)((((uint64_t)(__PCLK__))*25U)/(4U*((uint64_t)(__BAUD__))))) +#define SMARTCARD_DIVMANT(__PCLK__, __BAUD__) (SMARTCARD_DIV((__PCLK__), (__BAUD__))/100U) +#define SMARTCARD_DIVFRAQ(__PCLK__, __BAUD__) ((((SMARTCARD_DIV((__PCLK__), (__BAUD__)) - (SMARTCARD_DIVMANT((__PCLK__), (__BAUD__)) * 100U)) * 16U) + 50U) / 100U) +/* SMARTCARD BR = mantissa + overflow + fraction + = (SMARTCARD DIVMANT << 4) + (SMARTCARD DIVFRAQ & 0xF0) + (SMARTCARD DIVFRAQ & 0x0FU) */ +#define SMARTCARD_BR(__PCLK__, __BAUD__) (((SMARTCARD_DIVMANT((__PCLK__), (__BAUD__)) << 4U) + \ + (SMARTCARD_DIVFRAQ((__PCLK__), (__BAUD__)) & 0xF0U)) + \ + (SMARTCARD_DIVFRAQ((__PCLK__), (__BAUD__)) & 0x0FU)) + +/** + * @} + */ + +/* Private functions ---------------------------------------------------------*/ +/** @defgroup SMARTCARD_Private_Functions SMARTCARD Private Functions + * @{ + */ + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* APM32F4xx_DAL_SMARTCARD_H */ + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_smbus.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_smbus.h new file mode 100644 index 0000000000..293df88457 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_smbus.h @@ -0,0 +1,755 @@ +/** + * + * @file apm32f4xx_dal_smbus.h + * @brief Header file of SMBUS DAL module. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef APM32F4xx_DAL_SMBUS_H +#define APM32F4xx_DAL_SMBUS_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal_def.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @addtogroup SMBUS + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ +/** @defgroup SMBUS_Exported_Types SMBUS Exported Types + * @{ + */ + +/** + * @brief SMBUS Configuration Structure definition + */ +typedef struct +{ + uint32_t ClockSpeed; /*!< Specifies the clock frequency. + This parameter must be set to a value lower than 100kHz */ + + uint32_t AnalogFilter; /*!< Specifies if Analog Filter is enable or not. + This parameter can be a value of @ref SMBUS_Analog_Filter */ + + uint32_t OwnAddress1; /*!< Specifies the first device own address. + This parameter can be a 7-bit or 10-bit address. */ + + uint32_t AddressingMode; /*!< Specifies if 7-bit or 10-bit addressing mode is selected. + This parameter can be a value of @ref SMBUS_addressing_mode */ + + uint32_t DualAddressMode; /*!< Specifies if dual addressing mode is selected. + This parameter can be a value of @ref SMBUS_dual_addressing_mode */ + + uint32_t OwnAddress2; /*!< Specifies the second device own address if dual addressing mode is + selected. This parameter can be a 7-bit address. */ + + uint32_t GeneralCallMode; /*!< Specifies if general call mode is selected. + This parameter can be a value of @ref SMBUS_general_call_addressing_mode */ + + uint32_t NoStretchMode; /*!< Specifies if nostretch mode is selected. + This parameter can be a value of @ref SMBUS_nostretch_mode */ + + uint32_t PacketErrorCheckMode; /*!< Specifies if Packet Error Check mode is selected. + This parameter can be a value of @ref SMBUS_packet_error_check_mode */ + + uint32_t PeripheralMode; /*!< Specifies which mode of Periphal is selected. + This parameter can be a value of @ref SMBUS_peripheral_mode */ + +} SMBUS_InitTypeDef; + +/** + * @brief DAL State structure definition + * @note DAL SMBUS State value coding follow below described bitmap : + * b7-b6 Error information + * 00 : No Error + * 01 : Abort (Abort user request on going) + * 10 : Timeout + * 11 : Error + * b5 IP initialisation status + * 0 : Reset (IP not initialized) + * 1 : Init done (IP initialized and ready to use. DAL SMBUS Init function called) + * b4 (not used) + * x : Should be set to 0 + * b3 + * 0 : Ready or Busy (No Listen mode ongoing) + * 1 : Listen (IP in Address Listen Mode) + * b2 Intrinsic process state + * 0 : Ready + * 1 : Busy (IP busy with some configuration or internal operations) + * b1 Rx state + * 0 : Ready (no Rx operation ongoing) + * 1 : Busy (Rx operation ongoing) + * b0 Tx state + * 0 : Ready (no Tx operation ongoing) + * 1 : Busy (Tx operation ongoing) + */ +typedef enum +{ + + DAL_SMBUS_STATE_RESET = 0x00U, /*!< Peripheral is not yet Initialized */ + DAL_SMBUS_STATE_READY = 0x20U, /*!< Peripheral Initialized and ready for use */ + DAL_SMBUS_STATE_BUSY = 0x24U, /*!< An internal process is ongoing */ + DAL_SMBUS_STATE_BUSY_TX = 0x21U, /*!< Data Transmission process is ongoing */ + DAL_SMBUS_STATE_BUSY_RX = 0x22U, /*!< Data Reception process is ongoing */ + DAL_SMBUS_STATE_LISTEN = 0x28U, /*!< Address Listen Mode is ongoing */ + DAL_SMBUS_STATE_BUSY_TX_LISTEN = 0x29U, /*!< Address Listen Mode and Data Transmission + process is ongoing */ + DAL_SMBUS_STATE_BUSY_RX_LISTEN = 0x2AU, /*!< Address Listen Mode and Data Reception + process is ongoing */ + DAL_SMBUS_STATE_ABORT = 0x60U, /*!< Abort user request ongoing */ + DAL_SMBUS_STATE_TIMEOUT = 0xA0U, /*!< Timeout state */ + DAL_SMBUS_STATE_ERROR = 0xE0U /*!< Error */ +} DAL_SMBUS_StateTypeDef; + +/** + * @brief DAL Mode structure definition + * @note DAL SMBUS Mode value coding follow below described bitmap : + * b7 (not used) + * x : Should be set to 0 + * b6 (not used) + * x : Should be set to 0 + * b5 + * 0 : None + * 1 : Slave (DAL SMBUS communication is in Slave/Device Mode) + * b4 + * 0 : None + * 1 : Master (DAL SMBUS communication is in Master/Host Mode) + * b3-b2-b1-b0 (not used) + * xxxx : Should be set to 0000 + */ +typedef enum +{ + DAL_SMBUS_MODE_NONE = 0x00U, /*!< No SMBUS communication on going */ + DAL_SMBUS_MODE_MASTER = 0x10U, /*!< SMBUS communication is in Master Mode */ + DAL_SMBUS_MODE_SLAVE = 0x20U, /*!< SMBUS communication is in Slave Mode */ + +} DAL_SMBUS_ModeTypeDef; + +/** + * @brief SMBUS handle Structure definition + */ +typedef struct __SMBUS_HandleTypeDef +{ + I2C_TypeDef *Instance; /*!< SMBUS registers base address */ + + SMBUS_InitTypeDef Init; /*!< SMBUS communication parameters */ + + uint8_t *pBuffPtr; /*!< Pointer to SMBUS transfer buffer */ + + uint16_t XferSize; /*!< SMBUS transfer size */ + + __IO uint16_t XferCount; /*!< SMBUS transfer counter */ + + __IO uint32_t XferOptions; /*!< SMBUS transfer options this parameter can + be a value of @ref SMBUS_OPTIONS */ + + __IO uint32_t PreviousState; /*!< SMBUS communication Previous state and mode + context for internal usage */ + + DAL_LockTypeDef Lock; /*!< SMBUS locking object */ + + __IO DAL_SMBUS_StateTypeDef State; /*!< SMBUS communication state */ + + __IO DAL_SMBUS_ModeTypeDef Mode; /*!< SMBUS communication mode */ + + __IO uint32_t ErrorCode; /*!< SMBUS Error code */ + + __IO uint32_t Devaddress; /*!< SMBUS Target device address */ + + __IO uint32_t EventCount; /*!< SMBUS Event counter */ + + uint8_t XferPEC; /*!< SMBUS PEC data in reception mode */ + +#if (USE_DAL_SMBUS_REGISTER_CALLBACKS == 1) + void (* MasterTxCpltCallback)(struct __SMBUS_HandleTypeDef *hsmbus); /*!< SMBUS Master Tx Transfer completed callback */ + void (* MasterRxCpltCallback)(struct __SMBUS_HandleTypeDef *hsmbus); /*!< SMBUS Master Rx Transfer completed callback */ + void (* SlaveTxCpltCallback)(struct __SMBUS_HandleTypeDef *hsmbus); /*!< SMBUS Slave Tx Transfer completed callback */ + void (* SlaveRxCpltCallback)(struct __SMBUS_HandleTypeDef *hsmbus); /*!< SMBUS Slave Rx Transfer completed callback */ + void (* ListenCpltCallback)(struct __SMBUS_HandleTypeDef *hsmbus); /*!< SMBUS Listen Complete callback */ + void (* MemTxCpltCallback)(struct __SMBUS_HandleTypeDef *hsmbus); /*!< SMBUS Memory Tx Transfer completed callback */ + void (* MemRxCpltCallback)(struct __SMBUS_HandleTypeDef *hsmbus); /*!< SMBUS Memory Rx Transfer completed callback */ + void (* ErrorCallback)(struct __SMBUS_HandleTypeDef *hsmbus); /*!< SMBUS Error callback */ + void (* AbortCpltCallback)(struct __SMBUS_HandleTypeDef *hsmbus); /*!< SMBUS Abort callback */ + void (* AddrCallback)(struct __SMBUS_HandleTypeDef *hsmbus, uint8_t TransferDirection, uint16_t AddrMatchCode); /*!< SMBUS Slave Address Match callback */ + void (* MspInitCallback)(struct __SMBUS_HandleTypeDef *hsmbus); /*!< SMBUS Msp Init callback */ + void (* MspDeInitCallback)(struct __SMBUS_HandleTypeDef *hsmbus); /*!< SMBUS Msp DeInit callback */ + +#endif /* USE_DAL_SMBUS_REGISTER_CALLBACKS */ +} SMBUS_HandleTypeDef; + +#if (USE_DAL_SMBUS_REGISTER_CALLBACKS == 1) +/** + * @brief DAL SMBUS Callback ID enumeration definition + */ +typedef enum +{ + DAL_SMBUS_MASTER_TX_COMPLETE_CB_ID = 0x00U, /*!< SMBUS Master Tx Transfer completed callback ID */ + DAL_SMBUS_MASTER_RX_COMPLETE_CB_ID = 0x01U, /*!< SMBUS Master Rx Transfer completed callback ID */ + DAL_SMBUS_SLAVE_TX_COMPLETE_CB_ID = 0x02U, /*!< SMBUS Slave Tx Transfer completed callback ID */ + DAL_SMBUS_SLAVE_RX_COMPLETE_CB_ID = 0x03U, /*!< SMBUS Slave Rx Transfer completed callback ID */ + DAL_SMBUS_LISTEN_COMPLETE_CB_ID = 0x04U, /*!< SMBUS Listen Complete callback ID */ + DAL_SMBUS_ERROR_CB_ID = 0x07U, /*!< SMBUS Error callback ID */ + DAL_SMBUS_ABORT_CB_ID = 0x08U, /*!< SMBUS Abort callback ID */ + DAL_SMBUS_MSPINIT_CB_ID = 0x09U, /*!< SMBUS Msp Init callback ID */ + DAL_SMBUS_MSPDEINIT_CB_ID = 0x0AU /*!< SMBUS Msp DeInit callback ID */ + +} DAL_SMBUS_CallbackIDTypeDef; + +/** + * @brief DAL SMBUS Callback pointer definition + */ +typedef void (*pSMBUS_CallbackTypeDef)(SMBUS_HandleTypeDef *hsmbus); /*!< pointer to an I2C callback function */ +typedef void (*pSMBUS_AddrCallbackTypeDef)(SMBUS_HandleTypeDef *hsmbus, uint8_t TransferDirection, uint16_t AddrMatchCode); /*!< pointer to an I2C Address Match callback function */ + +#endif /* USE_DAL_SMBUS_REGISTER_CALLBACKS */ + +/** + * @} + */ + +/* Exported constants --------------------------------------------------------*/ +/** @defgroup SMBUS_Exported_Constants SMBUS Exported Constants + * @{ + */ + +/** @defgroup SMBUS_Error_Code_definition SMBUS Error Code + * @brief SMBUS Error Code + * @{ + */ +#define DAL_SMBUS_ERROR_NONE 0x00000000U /*!< No error */ +#define DAL_SMBUS_ERROR_BERR 0x00000001U /*!< BERR error */ +#define DAL_SMBUS_ERROR_ARLO 0x00000002U /*!< ARLO error */ +#define DAL_SMBUS_ERROR_AF 0x00000004U /*!< AF error */ +#define DAL_SMBUS_ERROR_OVR 0x00000008U /*!< OVR error */ +#define DAL_SMBUS_ERROR_TIMEOUT 0x00000010U /*!< Timeout Error */ +#define DAL_SMBUS_ERROR_ALERT 0x00000020U /*!< Alert error */ +#define DAL_SMBUS_ERROR_PECERR 0x00000040U /*!< PEC error */ +#if (USE_DAL_SMBUS_REGISTER_CALLBACKS == 1) +#define DAL_SMBUS_ERROR_INVALID_CALLBACK 0x00000080U /*!< Invalid Callback error */ +#endif /* USE_DAL_SMBUS_REGISTER_CALLBACKS */ + +/** + * @} + */ + +/** @defgroup SMBUS_Analog_Filter SMBUS Analog Filter + * @{ + */ +#define SMBUS_ANALOGFILTER_ENABLE 0x00000000U +#define SMBUS_ANALOGFILTER_DISABLE I2C_FILTER_ANFDIS +/** + * @} + */ + +/** @defgroup SMBUS_addressing_mode SMBUS addressing mode + * @{ + */ +#define SMBUS_ADDRESSINGMODE_7BIT 0x00004000U +#define SMBUS_ADDRESSINGMODE_10BIT (I2C_SADDR1_ADDRLEN | 0x00004000U) +/** + * @} + */ + +/** @defgroup SMBUS_dual_addressing_mode SMBUS dual addressing mode + * @{ + */ +#define SMBUS_DUALADDRESS_DISABLE 0x00000000U +#define SMBUS_DUALADDRESS_ENABLE I2C_SADDR2_ADDRNUM +/** + * @} + */ + +/** @defgroup SMBUS_general_call_addressing_mode SMBUS general call addressing mode + * @{ + */ +#define SMBUS_GENERALCALL_DISABLE 0x00000000U +#define SMBUS_GENERALCALL_ENABLE I2C_CTRL1_SRBEN +/** + * @} + */ + +/** @defgroup SMBUS_nostretch_mode SMBUS nostretch mode + * @{ + */ +#define SMBUS_NOSTRETCH_DISABLE 0x00000000U +#define SMBUS_NOSTRETCH_ENABLE I2C_CTRL1_CLKSTRETCHD +/** + * @} + */ + +/** @defgroup SMBUS_packet_error_check_mode SMBUS packet error check mode + * @{ + */ +#define SMBUS_PEC_DISABLE 0x00000000U +#define SMBUS_PEC_ENABLE I2C_CTRL1_PECEN +/** + * @} + */ + +/** @defgroup SMBUS_peripheral_mode SMBUS peripheral mode +* @{ +*/ +#define SMBUS_PERIPHERAL_MODE_SMBUS_HOST (uint32_t)(I2C_CTRL1_SMBEN | I2C_CTRL1_SMBTCFG | I2C_CTRL1_ARPEN) +#define SMBUS_PERIPHERAL_MODE_SMBUS_SLAVE I2C_CTRL1_SMBEN +#define SMBUS_PERIPHERAL_MODE_SMBUS_SLAVE_ARP (uint32_t)(I2C_CTRL1_SMBEN | I2C_CTRL1_ARPEN) +/** +* @} +*/ + +/** @defgroup SMBUS_XferDirection_definition SMBUS XferDirection definition + * @{ + */ +#define SMBUS_DIRECTION_RECEIVE 0x00000000U +#define SMBUS_DIRECTION_TRANSMIT 0x00000001U +/** + * @} + */ + +/** @defgroup SMBUS_XferOptions_definition SMBUS XferOptions definition + * @{ + */ +#define SMBUS_FIRST_FRAME 0x00000001U +#define SMBUS_NEXT_FRAME 0x00000002U +#define SMBUS_FIRST_AND_LAST_FRAME_NO_PEC 0x00000003U +#define SMBUS_LAST_FRAME_NO_PEC 0x00000004U +#define SMBUS_FIRST_AND_LAST_FRAME_WITH_PEC 0x00000005U +#define SMBUS_LAST_FRAME_WITH_PEC 0x00000006U +/** + * @} + */ + +/** @defgroup SMBUS_Interrupt_configuration_definition SMBUS Interrupt configuration definition + * @{ + */ +#define SMBUS_IT_BUF I2C_CTRL2_BUFIEN +#define SMBUS_IT_EVT I2C_CTRL2_EVIEN +#define SMBUS_IT_ERR I2C_CTRL2_ERRIEN +/** + * @} + */ + +/** @defgroup SMBUS_Flag_definition SMBUS Flag definition + * @{ + */ +#define SMBUS_FLAG_SMBALERT 0x00018000U +#define SMBUS_FLAG_TIMEOUT 0x00014000U +#define SMBUS_FLAG_PECERR 0x00011000U +#define SMBUS_FLAG_OVR 0x00010800U +#define SMBUS_FLAG_AF 0x00010400U +#define SMBUS_FLAG_ARLO 0x00010200U +#define SMBUS_FLAG_BERR 0x00010100U +#define SMBUS_FLAG_TXE 0x00010080U +#define SMBUS_FLAG_RXNE 0x00010040U +#define SMBUS_FLAG_STOPF 0x00010010U +#define SMBUS_FLAG_ADD10 0x00010008U +#define SMBUS_FLAG_BTF 0x00010004U +#define SMBUS_FLAG_ADDR 0x00010002U +#define SMBUS_FLAG_SB 0x00010001U +#define SMBUS_FLAG_DUALF 0x00100080U +#define SMBUS_FLAG_SMBHOST 0x00100040U +#define SMBUS_FLAG_SMBDEFAULT 0x00100020U +#define SMBUS_FLAG_GENCALL 0x00100010U +#define SMBUS_FLAG_TRA 0x00100004U +#define SMBUS_FLAG_BUSY 0x00100002U +#define SMBUS_FLAG_MSL 0x00100001U +/** + * @} + */ + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ +/** @defgroup SMBUS_Exported_Macros SMBUS Exported Macros + * @{ + */ + +/** @brief Reset SMBUS handle state + * @param __HANDLE__ specifies the SMBUS Handle. + * This parameter can be SMBUS where x: 1, 2, or 3 to select the SMBUS peripheral. + * @retval None + */ +#if (USE_DAL_SMBUS_REGISTER_CALLBACKS == 1) +#define __DAL_SMBUS_RESET_HANDLE_STATE(__HANDLE__) do{ \ + (__HANDLE__)->State = DAL_SMBUS_STATE_RESET; \ + (__HANDLE__)->MspInitCallback = NULL; \ + (__HANDLE__)->MspDeInitCallback = NULL; \ + } while(0) +#else +#define __DAL_SMBUS_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = DAL_SMBUS_STATE_RESET) +#endif + +/** @brief Enable or disable the specified SMBUS interrupts. + * @param __HANDLE__ specifies the SMBUS Handle. + * This parameter can be SMBUS where x: 1, 2, or 3 to select the SMBUS peripheral. + * @param __INTERRUPT__ specifies the interrupt source to enable or disable. + * This parameter can be one of the following values: + * @arg SMBUS_IT_BUF: Buffer interrupt enable + * @arg SMBUS_IT_EVT: Event interrupt enable + * @arg SMBUS_IT_ERR: Error interrupt enable + * @retval None + */ +#define __DAL_SMBUS_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CTRL2 |= (__INTERRUPT__)) +#define __DAL_SMBUS_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CTRL2 &= (~(__INTERRUPT__))) + +/** @brief Checks if the specified SMBUS interrupt source is enabled or disabled. + * @param __HANDLE__ specifies the SMBUS Handle. + * This parameter can be SMBUS where x: 1, 2, or 3 to select the SMBUS peripheral. + * @param __INTERRUPT__ specifies the SMBUS interrupt source to check. + * This parameter can be one of the following values: + * @arg SMBUS_IT_BUF: Buffer interrupt enable + * @arg SMBUS_IT_EVT: Event interrupt enable + * @arg SMBUS_IT_ERR: Error interrupt enable + * @retval The new state of __INTERRUPT__ (TRUE or FALSE). + */ +#define __DAL_SMBUS_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) ((((__HANDLE__)->Instance->CTRL2 & (__INTERRUPT__)) == (__INTERRUPT__)) ? SET : RESET) + +/** @brief Checks whether the specified SMBUS flag is set or not. + * @param __HANDLE__ specifies the SMBUS Handle. + * This parameter can be SMBUS where x: 1, 2, or 3 to select the SMBUS peripheral. + * @param __FLAG__ specifies the flag to check. + * This parameter can be one of the following values: + * @arg SMBUS_FLAG_SMBALERT: SMBus Alert flag + * @arg SMBUS_FLAG_TIMEOUT: Timeout or Tlow error flag + * @arg SMBUS_FLAG_PECERR: PEC error in reception flag + * @arg SMBUS_FLAG_OVR: Overrun/Underrun flag + * @arg SMBUS_FLAG_AF: Acknowledge failure flag + * @arg SMBUS_FLAG_ARLO: Arbitration lost flag + * @arg SMBUS_FLAG_BERR: Bus error flag + * @arg SMBUS_FLAG_TXE: Data register empty flag + * @arg SMBUS_FLAG_RXNE: Data register not empty flag + * @arg SMBUS_FLAG_STOPF: Stop detection flag + * @arg SMBUS_FLAG_ADD10: 10-bit header sent flag + * @arg SMBUS_FLAG_BTF: Byte transfer finished flag + * @arg SMBUS_FLAG_ADDR: Address sent flag + * Address matched flag + * @arg SMBUS_FLAG_SB: Start bit flag + * @arg SMBUS_FLAG_DUALF: Dual flag + * @arg SMBUS_FLAG_SMBHOST: SMBus host header + * @arg SMBUS_FLAG_SMBDEFAULT: SMBus default header + * @arg SMBUS_FLAG_GENCALL: General call header flag + * @arg SMBUS_FLAG_TRA: Transmitter/Receiver flag + * @arg SMBUS_FLAG_BUSY: Bus busy flag + * @arg SMBUS_FLAG_MSL: Master/Slave flag + * @retval The new state of __FLAG__ (TRUE or FALSE). + */ +#define __DAL_SMBUS_GET_FLAG(__HANDLE__, __FLAG__) ((((uint8_t)((__FLAG__) >> 16U)) == 0x01U)?((((__HANDLE__)->Instance->STS1) & ((__FLAG__) & SMBUS_FLAG_MASK)) == ((__FLAG__) & SMBUS_FLAG_MASK)): \ + ((((__HANDLE__)->Instance->STS2) & ((__FLAG__) & SMBUS_FLAG_MASK)) == ((__FLAG__) & SMBUS_FLAG_MASK))) + +/** @brief Clears the SMBUS pending flags which are cleared by writing 0 in a specific bit. + * @param __HANDLE__ specifies the SMBUS Handle. + * This parameter can be SMBUS where x: 1, 2, or 3 to select the SMBUS peripheral. + * @param __FLAG__ specifies the flag to clear. + * This parameter can be any combination of the following values: + * @arg SMBUS_FLAG_SMBALERT: SMBus Alert flag + * @arg SMBUS_FLAG_TIMEOUT: Timeout or Tlow error flag + * @arg SMBUS_FLAG_PECERR: PEC error in reception flag + * @arg SMBUS_FLAG_OVR: Overrun/Underrun flag (Slave mode) + * @arg SMBUS_FLAG_AF: Acknowledge failure flag + * @arg SMBUS_FLAG_ARLO: Arbitration lost flag (Master mode) + * @arg SMBUS_FLAG_BERR: Bus error flag + * @retval None + */ +#define __DAL_SMBUS_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->STS1 = ~((__FLAG__) & SMBUS_FLAG_MASK)) + +/** @brief Clears the SMBUS ADDR pending flag. + * @param __HANDLE__ specifies the SMBUS Handle. + * This parameter can be SMBUS where x: 1, 2, or 3 to select the SMBUS peripheral. + * @retval None + */ +#define __DAL_SMBUS_CLEAR_ADDRFLAG(__HANDLE__) \ + do{ \ + __IO uint32_t tmpreg = 0x00U; \ + tmpreg = (__HANDLE__)->Instance->STS1; \ + tmpreg = (__HANDLE__)->Instance->STS2; \ + UNUSED(tmpreg); \ + } while(0) + +/** @brief Clears the SMBUS STOPF pending flag. + * @param __HANDLE__ specifies the SMBUS Handle. + * This parameter can be SMBUS where x: 1, 2, or 3 to select the SMBUS peripheral. + * @retval None + */ +#define __DAL_SMBUS_CLEAR_STOPFLAG(__HANDLE__) \ + do{ \ + __IO uint32_t tmpreg = 0x00U; \ + tmpreg = (__HANDLE__)->Instance->STS1; \ + (__HANDLE__)->Instance->CTRL1 |= I2C_CTRL1_I2CEN; \ + UNUSED(tmpreg); \ + } while(0) + +/** @brief Enable the SMBUS peripheral. + * @param __HANDLE__ specifies the SMBUS Handle. + * This parameter can be SMBUSx where x: 1 or 2 to select the SMBUS peripheral. + * @retval None + */ +#define __DAL_SMBUS_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CTRL1 |= I2C_CTRL1_I2CEN) + +/** @brief Disable the SMBUS peripheral. + * @param __HANDLE__ specifies the SMBUS Handle. + * This parameter can be SMBUSx where x: 1 or 2 to select the SMBUS peripheral. + * @retval None + */ +#define __DAL_SMBUS_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CTRL1 &= ~I2C_CTRL1_I2CEN) + +/** @brief Generate a Non-Acknowledge SMBUS peripheral in Slave mode. + * @param __HANDLE__ specifies the SMBUS Handle. + * @retval None + */ +#define __DAL_SMBUS_GENERATE_NACK(__HANDLE__) (CLEAR_BIT((__HANDLE__)->Instance->CTRL1, I2C_CTRL1_ACKEN)) + +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup SMBUS_Exported_Functions + * @{ + */ + +/** @addtogroup SMBUS_Exported_Functions_Group1 Initialization and de-initialization functions + * @{ + */ + +/* Initialization/de-initialization functions **********************************/ +DAL_StatusTypeDef DAL_SMBUS_Init(SMBUS_HandleTypeDef *hsmbus); +DAL_StatusTypeDef DAL_SMBUS_DeInit(SMBUS_HandleTypeDef *hsmbus); +void DAL_SMBUS_MspInit(SMBUS_HandleTypeDef *hsmbus); +void DAL_SMBUS_MspDeInit(SMBUS_HandleTypeDef *hsmbus); + +/* Callbacks Register/UnRegister functions ************************************/ +#if (USE_DAL_SMBUS_REGISTER_CALLBACKS == 1) +DAL_StatusTypeDef DAL_SMBUS_RegisterCallback(SMBUS_HandleTypeDef *hsmbus, DAL_SMBUS_CallbackIDTypeDef CallbackID, pSMBUS_CallbackTypeDef pCallback); +DAL_StatusTypeDef DAL_SMBUS_UnRegisterCallback(SMBUS_HandleTypeDef *hsmbus, DAL_SMBUS_CallbackIDTypeDef CallbackID); + +DAL_StatusTypeDef DAL_SMBUS_RegisterAddrCallback(SMBUS_HandleTypeDef *hsmbus, pSMBUS_AddrCallbackTypeDef pCallback); +DAL_StatusTypeDef DAL_SMBUS_UnRegisterAddrCallback(SMBUS_HandleTypeDef *hsmbus); +#endif /* USE_DAL_SMBUS_REGISTER_CALLBACKS */ + +/** + * @} + */ + +/** @addtogroup SMBUS_Exported_Functions_Group2 Input and Output operation functions + * @{ + */ + +/* IO operation functions *****************************************************/ +/** @addtogroup Blocking_mode_Polling Blocking mode Polling + * @{ + */ +/******* Blocking mode: Polling */ +DAL_StatusTypeDef DAL_SMBUS_IsDeviceReady(SMBUS_HandleTypeDef *hsmbus, uint16_t DevAddress, uint32_t Trials, uint32_t Timeout); +/** + * @} + */ + +/** @addtogroup Non-Blocking_mode_Interrupt Non-Blocking mode Interrupt + * @{ + */ +/******* Non-Blocking mode: Interrupt */ +DAL_StatusTypeDef DAL_SMBUS_Master_Transmit_IT(SMBUS_HandleTypeDef *hsmbus, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t XferOptions); +DAL_StatusTypeDef DAL_SMBUS_Master_Receive_IT(SMBUS_HandleTypeDef *hsmbus, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t XferOptions); +DAL_StatusTypeDef DAL_SMBUS_Master_Abort_IT(SMBUS_HandleTypeDef *hsmbus, uint16_t DevAddress); +DAL_StatusTypeDef DAL_SMBUS_Slave_Transmit_IT(SMBUS_HandleTypeDef *hsmbus, uint8_t *pData, uint16_t Size, uint32_t XferOptions); +DAL_StatusTypeDef DAL_SMBUS_Slave_Receive_IT(SMBUS_HandleTypeDef *hsmbus, uint8_t *pData, uint16_t Size, uint32_t XferOptions); + +DAL_StatusTypeDef DAL_SMBUS_EnableAlert_IT(SMBUS_HandleTypeDef *hsmbus); +DAL_StatusTypeDef DAL_SMBUS_DisableAlert_IT(SMBUS_HandleTypeDef *hsmbus); +DAL_StatusTypeDef DAL_SMBUS_EnableListen_IT(SMBUS_HandleTypeDef *hsmbus); +DAL_StatusTypeDef DAL_SMBUS_DisableListen_IT(SMBUS_HandleTypeDef *hsmbus); + +/****** Filter Configuration functions */ +#if defined(I2C_FILTER_ANFDIS)&&defined(I2C_FILTER_DNFCFG) +DAL_StatusTypeDef DAL_SMBUS_ConfigAnalogFilter(SMBUS_HandleTypeDef *hsmbus, uint32_t AnalogFilter); +DAL_StatusTypeDef DAL_SMBUS_ConfigDigitalFilter(SMBUS_HandleTypeDef *hsmbus, uint32_t DigitalFilter); +#endif +/** + * @} + */ + +/** @addtogroup SMBUS_IRQ_Handler_and_Callbacks IRQ Handler and Callbacks + * @{ + */ +/******* SMBUS IRQHandler and Callbacks used in non blocking modes (Interrupt) */ +void DAL_SMBUS_EV_IRQHandler(SMBUS_HandleTypeDef *hsmbus); +void DAL_SMBUS_ER_IRQHandler(SMBUS_HandleTypeDef *hsmbus); +void DAL_SMBUS_MasterTxCpltCallback(SMBUS_HandleTypeDef *hsmbus); +void DAL_SMBUS_MasterRxCpltCallback(SMBUS_HandleTypeDef *hsmbus); +void DAL_SMBUS_SlaveTxCpltCallback(SMBUS_HandleTypeDef *hsmbus); +void DAL_SMBUS_SlaveRxCpltCallback(SMBUS_HandleTypeDef *hsmbus); +void DAL_SMBUS_AddrCallback(SMBUS_HandleTypeDef *hsmbus, uint8_t TransferDirection, uint16_t AddrMatchCode); +void DAL_SMBUS_ListenCpltCallback(SMBUS_HandleTypeDef *hsmbus); +void DAL_SMBUS_ErrorCallback(SMBUS_HandleTypeDef *hsmbus); +void DAL_SMBUS_AbortCpltCallback(SMBUS_HandleTypeDef *hsmbus); + +/** + * @} + */ + +/** @addtogroup SMBUS_Exported_Functions_Group3 Peripheral State, Mode and Error functions + * @{ + */ + +/* Peripheral State, mode and Errors functions **************************************************/ +DAL_SMBUS_StateTypeDef DAL_SMBUS_GetState(SMBUS_HandleTypeDef *hsmbus); +DAL_SMBUS_ModeTypeDef DAL_SMBUS_GetMode(SMBUS_HandleTypeDef *hsmbus); +uint32_t DAL_SMBUS_GetError(SMBUS_HandleTypeDef *hsmbus); + +/** + * @} + */ + +/** + * @} + */ +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/** @defgroup SMBUS_Private_Constants SMBUS Private Constants + * @{ + */ +#define SMBUS_FLAG_MASK 0x0000FFFFU +/** + * @} + */ + +/* Private macros ------------------------------------------------------------*/ +/** @defgroup SMBUS_Private_Macros SMBUS Private Macros + * @{ + */ + +#define SMBUS_FREQRANGE(__PCLK__) ((__PCLK__)/1000000U) + +#define SMBUS_RISE_TIME(__FREQRANGE__) ( ((__FREQRANGE__) + 1U)) + +#define SMBUS_SPEED_STANDARD(__PCLK__, __SPEED__) (((((__PCLK__)/((__SPEED__) << 1U)) & I2C_CLKCTRL_CLKS) < 4U)? 4U:((__PCLK__) / ((__SPEED__) << 1U))) + +#define SMBUS_7BIT_ADD_WRITE(__ADDRESS__) ((uint8_t)((__ADDRESS__) & (~I2C_SADDR1_ADDR0))) + +#define SMBUS_7BIT_ADD_READ(__ADDRESS__) ((uint8_t)((__ADDRESS__) | I2C_SADDR1_ADDR0)) + +#define SMBUS_10BIT_ADDRESS(__ADDRESS__) ((uint8_t)((uint16_t)((__ADDRESS__) & (uint16_t)0x00FF))) + +#define SMBUS_10BIT_HEADER_WRITE(__ADDRESS__) ((uint8_t)((uint16_t)((uint16_t)(((uint16_t)((__ADDRESS__) & (uint16_t)0x0300)) >> 7) | (uint16_t)0x00F0))) + +#define SMBUS_10BIT_HEADER_READ(__ADDRESS__) ((uint8_t)((uint16_t)((uint16_t)(((uint16_t)((__ADDRESS__) & (uint16_t)0x0300)) >> 7) | (uint16_t)(0x00F1)))) + +#define SMBUS_GET_PEC_MODE(__HANDLE__) ((__HANDLE__)->Instance->CTRL1 & I2C_CTRL1_PECEN) + +#define SMBUS_GET_PEC_VALUE(__HANDLE__) ((__HANDLE__)->XferPEC) + +#if defined(I2C_FILTER_ANFDIS)&&defined(I2C_FILTER_DNFCFG) +#define IS_SMBUS_ANALOG_FILTER(FILTER) (((FILTER) == SMBUS_ANALOGFILTER_ENABLE) || \ + ((FILTER) == SMBUS_ANALOGFILTER_DISABLE)) +#define IS_SMBUS_DIGITAL_FILTER(FILTER) ((FILTER) <= 0x0000000FU) +#endif +#define IS_SMBUS_ADDRESSING_MODE(ADDRESS) (((ADDRESS) == SMBUS_ADDRESSINGMODE_7BIT) || \ + ((ADDRESS) == SMBUS_ADDRESSINGMODE_10BIT)) + +#define IS_SMBUS_DUAL_ADDRESS(ADDRESS) (((ADDRESS) == SMBUS_DUALADDRESS_DISABLE) || \ + ((ADDRESS) == SMBUS_DUALADDRESS_ENABLE)) + +#define IS_SMBUS_GENERAL_CALL(CALL) (((CALL) == SMBUS_GENERALCALL_DISABLE) || \ + ((CALL) == SMBUS_GENERALCALL_ENABLE)) + +#define IS_SMBUS_NO_STRETCH(STRETCH) (((STRETCH) == SMBUS_NOSTRETCH_DISABLE) || \ + ((STRETCH) == SMBUS_NOSTRETCH_ENABLE)) + +#define IS_SMBUS_PEC(PEC) (((PEC) == SMBUS_PEC_DISABLE) || \ + ((PEC) == SMBUS_PEC_ENABLE)) + +#define IS_SMBUS_PERIPHERAL_MODE(MODE) (((MODE) == SMBUS_PERIPHERAL_MODE_SMBUS_HOST) || \ + ((MODE) == SMBUS_PERIPHERAL_MODE_SMBUS_SLAVE) || \ + ((MODE) == SMBUS_PERIPHERAL_MODE_SMBUS_SLAVE_ARP)) + +#define IS_SMBUS_CLOCK_SPEED(SPEED) (((SPEED) > 0U) && ((SPEED) <= 100000U)) + +#define IS_SMBUS_OWN_ADDRESS1(ADDRESS1) (((ADDRESS1) & 0xFFFFFC00U) == 0U) + +#define IS_SMBUS_OWN_ADDRESS2(ADDRESS2) (((ADDRESS2) & 0xFFFFFF01U) == 0U) + +#define IS_SMBUS_TRANSFER_OPTIONS_REQUEST(REQUEST) (((REQUEST) == SMBUS_FIRST_FRAME) || \ + ((REQUEST) == SMBUS_NEXT_FRAME) || \ + ((REQUEST) == SMBUS_FIRST_AND_LAST_FRAME_NO_PEC) || \ + ((REQUEST) == SMBUS_LAST_FRAME_NO_PEC) || \ + ((REQUEST) == SMBUS_FIRST_AND_LAST_FRAME_WITH_PEC) || \ + ((REQUEST) == SMBUS_LAST_FRAME_WITH_PEC)) + +/** + * @} + */ + +/* Private Functions ---------------------------------------------------------*/ +/** @defgroup SMBUS_Private_Functions SMBUS Private Functions + * @{ + */ + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +/** +* @} +*/ + +#ifdef __cplusplus +} +#endif + + +#endif /* APM32F4xx_DAL_SMBUS_H */ + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_spi.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_spi.h new file mode 100644 index 0000000000..f919ce8af1 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_spi.h @@ -0,0 +1,753 @@ +/** + * + * @file apm32f4xx_dal_spi.h + * @brief Header file of SPI DAL module. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef APM32F4xx_DAL_SPI_H +#define APM32F4xx_DAL_SPI_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal_def.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @addtogroup SPI + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ +/** @defgroup SPI_Exported_Types SPI Exported Types + * @{ + */ + +/** + * @brief SPI Configuration Structure definition + */ +typedef struct +{ + uint32_t Mode; /*!< Specifies the SPI operating mode. + This parameter can be a value of @ref SPI_Mode */ + + uint32_t Direction; /*!< Specifies the SPI bidirectional mode state. + This parameter can be a value of @ref SPI_Direction */ + + uint32_t DataSize; /*!< Specifies the SPI data size. + This parameter can be a value of @ref SPI_Data_Size */ + + uint32_t CLKPolarity; /*!< Specifies the serial clock steady state. + This parameter can be a value of @ref SPI_Clock_Polarity */ + + uint32_t CLKPhase; /*!< Specifies the clock active edge for the bit capture. + This parameter can be a value of @ref SPI_Clock_Phase */ + + uint32_t NSS; /*!< Specifies whether the NSS signal is managed by + hardware (NSS pin) or by software using the SSI bit. + This parameter can be a value of @ref SPI_Slave_Select_management */ + + uint32_t BaudRatePrescaler; /*!< Specifies the Baud Rate prescaler value which will be + used to configure the transmit and receive SCK clock. + This parameter can be a value of @ref SPI_BaudRate_Prescaler + @note The communication clock is derived from the master + clock. The slave clock does not need to be set. */ + + uint32_t FirstBit; /*!< Specifies whether data transfers start from MSB or LSB bit. + This parameter can be a value of @ref SPI_MSB_LSB_transmission */ + + uint32_t TIMode; /*!< Specifies if the TI mode is enabled or not. + This parameter can be a value of @ref SPI_TI_mode */ + + uint32_t CRCCalculation; /*!< Specifies if the CRC calculation is enabled or not. + This parameter can be a value of @ref SPI_CRC_Calculation */ + + uint32_t CRCPolynomial; /*!< Specifies the polynomial used for the CRC calculation. + This parameter must be an odd number between Min_Data = 1 and Max_Data = 65535 */ +} SPI_InitTypeDef; + +/** + * @brief DAL SPI State structure definition + */ +typedef enum +{ + DAL_SPI_STATE_RESET = 0x00U, /*!< Peripheral not Initialized */ + DAL_SPI_STATE_READY = 0x01U, /*!< Peripheral Initialized and ready for use */ + DAL_SPI_STATE_BUSY = 0x02U, /*!< an internal process is ongoing */ + DAL_SPI_STATE_BUSY_TX = 0x03U, /*!< Data Transmission process is ongoing */ + DAL_SPI_STATE_BUSY_RX = 0x04U, /*!< Data Reception process is ongoing */ + DAL_SPI_STATE_BUSY_TX_RX = 0x05U, /*!< Data Transmission and Reception process is ongoing */ + DAL_SPI_STATE_ERROR = 0x06U, /*!< SPI error state */ + DAL_SPI_STATE_ABORT = 0x07U /*!< SPI abort is ongoing */ +} DAL_SPI_StateTypeDef; + +/** + * @brief SPI handle Structure definition + */ +typedef struct __SPI_HandleTypeDef +{ + SPI_TypeDef *Instance; /*!< SPI registers base address */ + + SPI_InitTypeDef Init; /*!< SPI communication parameters */ + + uint8_t *pTxBuffPtr; /*!< Pointer to SPI Tx transfer Buffer */ + + uint16_t TxXferSize; /*!< SPI Tx Transfer size */ + + __IO uint16_t TxXferCount; /*!< SPI Tx Transfer Counter */ + + uint8_t *pRxBuffPtr; /*!< Pointer to SPI Rx transfer Buffer */ + + uint16_t RxXferSize; /*!< SPI Rx Transfer size */ + + __IO uint16_t RxXferCount; /*!< SPI Rx Transfer Counter */ + + void (*RxISR)(struct __SPI_HandleTypeDef *hspi); /*!< function pointer on Rx ISR */ + + void (*TxISR)(struct __SPI_HandleTypeDef *hspi); /*!< function pointer on Tx ISR */ + + DMA_HandleTypeDef *hdmatx; /*!< SPI Tx DMA Handle parameters */ + + DMA_HandleTypeDef *hdmarx; /*!< SPI Rx DMA Handle parameters */ + + DAL_LockTypeDef Lock; /*!< Locking object */ + + __IO DAL_SPI_StateTypeDef State; /*!< SPI communication state */ + + __IO uint32_t ErrorCode; /*!< SPI Error code */ + +#if (USE_DAL_SPI_REGISTER_CALLBACKS == 1U) + void (* TxCpltCallback)(struct __SPI_HandleTypeDef *hspi); /*!< SPI Tx Completed callback */ + void (* RxCpltCallback)(struct __SPI_HandleTypeDef *hspi); /*!< SPI Rx Completed callback */ + void (* TxRxCpltCallback)(struct __SPI_HandleTypeDef *hspi); /*!< SPI TxRx Completed callback */ + void (* TxHalfCpltCallback)(struct __SPI_HandleTypeDef *hspi); /*!< SPI Tx Half Completed callback */ + void (* RxHalfCpltCallback)(struct __SPI_HandleTypeDef *hspi); /*!< SPI Rx Half Completed callback */ + void (* TxRxHalfCpltCallback)(struct __SPI_HandleTypeDef *hspi); /*!< SPI TxRx Half Completed callback */ + void (* ErrorCallback)(struct __SPI_HandleTypeDef *hspi); /*!< SPI Error callback */ + void (* AbortCpltCallback)(struct __SPI_HandleTypeDef *hspi); /*!< SPI Abort callback */ + void (* MspInitCallback)(struct __SPI_HandleTypeDef *hspi); /*!< SPI Msp Init callback */ + void (* MspDeInitCallback)(struct __SPI_HandleTypeDef *hspi); /*!< SPI Msp DeInit callback */ + +#endif /* USE_DAL_SPI_REGISTER_CALLBACKS */ +} SPI_HandleTypeDef; + +#if (USE_DAL_SPI_REGISTER_CALLBACKS == 1U) +/** + * @brief DAL SPI Callback ID enumeration definition + */ +typedef enum +{ + DAL_SPI_TX_COMPLETE_CB_ID = 0x00U, /*!< SPI Tx Completed callback ID */ + DAL_SPI_RX_COMPLETE_CB_ID = 0x01U, /*!< SPI Rx Completed callback ID */ + DAL_SPI_TX_RX_COMPLETE_CB_ID = 0x02U, /*!< SPI TxRx Completed callback ID */ + DAL_SPI_TX_HALF_COMPLETE_CB_ID = 0x03U, /*!< SPI Tx Half Completed callback ID */ + DAL_SPI_RX_HALF_COMPLETE_CB_ID = 0x04U, /*!< SPI Rx Half Completed callback ID */ + DAL_SPI_TX_RX_HALF_COMPLETE_CB_ID = 0x05U, /*!< SPI TxRx Half Completed callback ID */ + DAL_SPI_ERROR_CB_ID = 0x06U, /*!< SPI Error callback ID */ + DAL_SPI_ABORT_CB_ID = 0x07U, /*!< SPI Abort callback ID */ + DAL_SPI_MSPINIT_CB_ID = 0x08U, /*!< SPI Msp Init callback ID */ + DAL_SPI_MSPDEINIT_CB_ID = 0x09U /*!< SPI Msp DeInit callback ID */ + +} DAL_SPI_CallbackIDTypeDef; + +/** + * @brief DAL SPI Callback pointer definition + */ +typedef void (*pSPI_CallbackTypeDef)(SPI_HandleTypeDef *hspi); /*!< pointer to an SPI callback function */ + +#endif /* USE_DAL_SPI_REGISTER_CALLBACKS */ +/** + * @} + */ + +/* Exported constants --------------------------------------------------------*/ +/** @defgroup SPI_Exported_Constants SPI Exported Constants + * @{ + */ + +/** @defgroup SPI_Error_Code SPI Error Code + * @{ + */ +#define DAL_SPI_ERROR_NONE (0x00000000U) /*!< No error */ +#define DAL_SPI_ERROR_MODF (0x00000001U) /*!< MODF error */ +#define DAL_SPI_ERROR_CRC (0x00000002U) /*!< CRC error */ +#define DAL_SPI_ERROR_OVR (0x00000004U) /*!< OVR error */ +#define DAL_SPI_ERROR_FRE (0x00000008U) /*!< FRE error */ +#define DAL_SPI_ERROR_DMA (0x00000010U) /*!< DMA transfer error */ +#define DAL_SPI_ERROR_FLAG (0x00000020U) /*!< Error on RXNE/TXE/BSY Flag */ +#define DAL_SPI_ERROR_ABORT (0x00000040U) /*!< Error during SPI Abort procedure */ +#if (USE_DAL_SPI_REGISTER_CALLBACKS == 1U) +#define DAL_SPI_ERROR_INVALID_CALLBACK (0x00000080U) /*!< Invalid Callback error */ +#endif /* USE_DAL_SPI_REGISTER_CALLBACKS */ +/** + * @} + */ + +/** @defgroup SPI_Mode SPI Mode + * @{ + */ +#define SPI_MODE_SLAVE (0x00000000U) +#define SPI_MODE_MASTER (SPI_CTRL1_MSMCFG | SPI_CTRL1_ISSEL) +/** + * @} + */ + +/** @defgroup SPI_Direction SPI Direction Mode + * @{ + */ +#define SPI_DIRECTION_2LINES (0x00000000U) +#define SPI_DIRECTION_2LINES_RXONLY SPI_CTRL1_RXOMEN +#define SPI_DIRECTION_1LINE SPI_CTRL1_BMEN +/** + * @} + */ + +/** @defgroup SPI_Data_Size SPI Data Size + * @{ + */ +#define SPI_DATASIZE_8BIT (0x00000000U) +#define SPI_DATASIZE_16BIT SPI_CTRL1_DFLSEL +/** + * @} + */ + +/** @defgroup SPI_Clock_Polarity SPI Clock Polarity + * @{ + */ +#define SPI_POLARITY_LOW (0x00000000U) +#define SPI_POLARITY_HIGH SPI_CTRL1_CPOL +/** + * @} + */ + +/** @defgroup SPI_Clock_Phase SPI Clock Phase + * @{ + */ +#define SPI_PHASE_1EDGE (0x00000000U) +#define SPI_PHASE_2EDGE SPI_CTRL1_CPHA +/** + * @} + */ + +/** @defgroup SPI_Slave_Select_management SPI Slave Select Management + * @{ + */ +#define SPI_NSS_SOFT SPI_CTRL1_SSEN +#define SPI_NSS_HARD_INPUT (0x00000000U) +#define SPI_NSS_HARD_OUTPUT (SPI_CTRL2_SSOEN << 16U) +/** + * @} + */ + +/** @defgroup SPI_BaudRate_Prescaler SPI BaudRate Prescaler + * @{ + */ +#define SPI_BAUDRATEPRESCALER_2 (0x00000000U) +#define SPI_BAUDRATEPRESCALER_4 (SPI_CTRL1_BRSEL_0) +#define SPI_BAUDRATEPRESCALER_8 (SPI_CTRL1_BRSEL_1) +#define SPI_BAUDRATEPRESCALER_16 (SPI_CTRL1_BRSEL_1 | SPI_CTRL1_BRSEL_0) +#define SPI_BAUDRATEPRESCALER_32 (SPI_CTRL1_BRSEL_2) +#define SPI_BAUDRATEPRESCALER_64 (SPI_CTRL1_BRSEL_2 | SPI_CTRL1_BRSEL_0) +#define SPI_BAUDRATEPRESCALER_128 (SPI_CTRL1_BRSEL_2 | SPI_CTRL1_BRSEL_1) +#define SPI_BAUDRATEPRESCALER_256 (SPI_CTRL1_BRSEL_2 | SPI_CTRL1_BRSEL_1 | SPI_CTRL1_BRSEL_0) +/** + * @} + */ + +/** @defgroup SPI_MSB_LSB_transmission SPI MSB LSB Transmission + * @{ + */ +#define SPI_FIRSTBIT_MSB (0x00000000U) +#define SPI_FIRSTBIT_LSB SPI_CTRL1_LSBSEL +/** + * @} + */ + +/** @defgroup SPI_TI_mode SPI TI Mode + * @{ + */ +#define SPI_TIMODE_DISABLE (0x00000000U) +#define SPI_TIMODE_ENABLE SPI_CTRL2_FRFCFG +/** + * @} + */ + +/** @defgroup SPI_CRC_Calculation SPI CRC Calculation + * @{ + */ +#define SPI_CRCCALCULATION_DISABLE (0x00000000U) +#define SPI_CRCCALCULATION_ENABLE SPI_CTRL1_CRCEN +/** + * @} + */ + +/** @defgroup SPI_Interrupt_definition SPI Interrupt Definition + * @{ + */ +#define SPI_IT_TXE SPI_CTRL2_TXBEIEN +#define SPI_IT_RXNE SPI_CTRL2_RXBNEIEN +#define SPI_IT_ERR SPI_CTRL2_ERRIEN +/** + * @} + */ + +/** @defgroup SPI_Flags_definition SPI Flags Definition + * @{ + */ +#define SPI_FLAG_RXNE SPI_STS_RXBNEFLG /* SPI status flag: Rx buffer not empty flag */ +#define SPI_FLAG_TXE SPI_STS_TXBEFLG /* SPI status flag: Tx buffer empty flag */ +#define SPI_FLAG_BSY SPI_STS_BSYFLG /* SPI status flag: Busy flag */ +#define SPI_FLAG_CRCERR SPI_STS_CRCEFLG /* SPI Error flag: CRC error flag */ +#define SPI_FLAG_MODF SPI_STS_MEFLG /* SPI Error flag: Mode fault flag */ +#define SPI_FLAG_OVR SPI_STS_OVRFLG /* SPI Error flag: Overrun flag */ +#define SPI_FLAG_FRE SPI_STS_FFERR /* SPI Error flag: TI mode frame format error flag */ +#define SPI_FLAG_MASK (SPI_STS_RXBNEFLG | SPI_STS_TXBEFLG | SPI_STS_BSYFLG | SPI_STS_CRCEFLG\ + | SPI_STS_MEFLG | SPI_STS_OVRFLG | SPI_STS_FFERR) +/** + * @} + */ + +/** + * @} + */ + +/* Exported macros -----------------------------------------------------------*/ +/** @defgroup SPI_Exported_Macros SPI Exported Macros + * @{ + */ + +/** @brief Reset SPI handle state. + * @param __HANDLE__ specifies the SPI Handle. + * This parameter can be SPI where x: 1, 2, or 3 to select the SPI peripheral. + * @retval None + */ +#if (USE_DAL_SPI_REGISTER_CALLBACKS == 1U) +#define __DAL_SPI_RESET_HANDLE_STATE(__HANDLE__) do{ \ + (__HANDLE__)->State = DAL_SPI_STATE_RESET; \ + (__HANDLE__)->MspInitCallback = NULL; \ + (__HANDLE__)->MspDeInitCallback = NULL; \ + } while(0) +#else +#define __DAL_SPI_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = DAL_SPI_STATE_RESET) +#endif /* USE_DAL_SPI_REGISTER_CALLBACKS */ + +/** @brief Enable the specified SPI interrupts. + * @param __HANDLE__ specifies the SPI Handle. + * This parameter can be SPI where x: 1, 2, or 3 to select the SPI peripheral. + * @param __INTERRUPT__ specifies the interrupt source to enable. + * This parameter can be one of the following values: + * @arg SPI_IT_TXE: Tx buffer empty interrupt enable + * @arg SPI_IT_RXNE: RX buffer not empty interrupt enable + * @arg SPI_IT_ERR: Error interrupt enable + * @retval None + */ +#define __DAL_SPI_ENABLE_IT(__HANDLE__, __INTERRUPT__) SET_BIT((__HANDLE__)->Instance->CTRL2, (__INTERRUPT__)) + +/** @brief Disable the specified SPI interrupts. + * @param __HANDLE__ specifies the SPI handle. + * This parameter can be SPIx where x: 1, 2, or 3 to select the SPI peripheral. + * @param __INTERRUPT__ specifies the interrupt source to disable. + * This parameter can be one of the following values: + * @arg SPI_IT_TXE: Tx buffer empty interrupt enable + * @arg SPI_IT_RXNE: RX buffer not empty interrupt enable + * @arg SPI_IT_ERR: Error interrupt enable + * @retval None + */ +#define __DAL_SPI_DISABLE_IT(__HANDLE__, __INTERRUPT__) CLEAR_BIT((__HANDLE__)->Instance->CTRL2, (__INTERRUPT__)) + +/** @brief Check whether the specified SPI interrupt source is enabled or not. + * @param __HANDLE__ specifies the SPI Handle. + * This parameter can be SPI where x: 1, 2, or 3 to select the SPI peripheral. + * @param __INTERRUPT__ specifies the SPI interrupt source to check. + * This parameter can be one of the following values: + * @arg SPI_IT_TXE: Tx buffer empty interrupt enable + * @arg SPI_IT_RXNE: RX buffer not empty interrupt enable + * @arg SPI_IT_ERR: Error interrupt enable + * @retval The new state of __IT__ (TRUE or FALSE). + */ +#define __DAL_SPI_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) ((((__HANDLE__)->Instance->CTRL2\ + & (__INTERRUPT__)) == (__INTERRUPT__)) ? SET : RESET) + +/** @brief Check whether the specified SPI flag is set or not. + * @param __HANDLE__ specifies the SPI Handle. + * This parameter can be SPI where x: 1, 2, or 3 to select the SPI peripheral. + * @param __FLAG__ specifies the flag to check. + * This parameter can be one of the following values: + * @arg SPI_FLAG_RXNE: Receive buffer not empty flag + * @arg SPI_FLAG_TXE: Transmit buffer empty flag + * @arg SPI_FLAG_CRCERR: CRC error flag + * @arg SPI_FLAG_MODF: Mode fault flag + * @arg SPI_FLAG_OVR: Overrun flag + * @arg SPI_FLAG_BSY: Busy flag + * @arg SPI_FLAG_FRE: Frame format error flag + * @retval The new state of __FLAG__ (TRUE or FALSE). + */ +#define __DAL_SPI_GET_FLAG(__HANDLE__, __FLAG__) ((((__HANDLE__)->Instance->STS) & (__FLAG__)) == (__FLAG__)) + +/** @brief Clear the SPI CRCERR pending flag. + * @param __HANDLE__ specifies the SPI Handle. + * This parameter can be SPI where x: 1, 2, or 3 to select the SPI peripheral. + * @retval None + */ +#define __DAL_SPI_CLEAR_CRCERRFLAG(__HANDLE__) ((__HANDLE__)->Instance->STS = (uint16_t)(~SPI_FLAG_CRCERR)) + +/** @brief Clear the SPI MODF pending flag. + * @param __HANDLE__ specifies the SPI Handle. + * This parameter can be SPI where x: 1, 2, or 3 to select the SPI peripheral. + * @retval None + */ +#define __DAL_SPI_CLEAR_MODFFLAG(__HANDLE__) \ + do{ \ + __IO uint32_t tmpreg_modf = 0x00U; \ + tmpreg_modf = (__HANDLE__)->Instance->STS; \ + CLEAR_BIT((__HANDLE__)->Instance->CTRL1, SPI_CTRL1_SPIEN); \ + UNUSED(tmpreg_modf); \ + } while(0U) + +/** @brief Clear the SPI OVR pending flag. + * @param __HANDLE__ specifies the SPI Handle. + * This parameter can be SPI where x: 1, 2, or 3 to select the SPI peripheral. + * @retval None + */ +#define __DAL_SPI_CLEAR_OVRFLAG(__HANDLE__) \ + do{ \ + __IO uint32_t tmpreg_ovr = 0x00U; \ + tmpreg_ovr = (__HANDLE__)->Instance->DATA; \ + tmpreg_ovr = (__HANDLE__)->Instance->STS; \ + UNUSED(tmpreg_ovr); \ + } while(0U) + +/** @brief Clear the SPI FRE pending flag. + * @param __HANDLE__ specifies the SPI Handle. + * This parameter can be SPI where x: 1, 2, or 3 to select the SPI peripheral. + * @retval None + */ +#define __DAL_SPI_CLEAR_FREFLAG(__HANDLE__) \ + do{ \ + __IO uint32_t tmpreg_fre = 0x00U; \ + tmpreg_fre = (__HANDLE__)->Instance->STS; \ + UNUSED(tmpreg_fre); \ + }while(0U) + +/** @brief Enable the SPI peripheral. + * @param __HANDLE__ specifies the SPI Handle. + * This parameter can be SPI where x: 1, 2, or 3 to select the SPI peripheral. + * @retval None + */ +#define __DAL_SPI_ENABLE(__HANDLE__) SET_BIT((__HANDLE__)->Instance->CTRL1, SPI_CTRL1_SPIEN) + +/** @brief Disable the SPI peripheral. + * @param __HANDLE__ specifies the SPI Handle. + * This parameter can be SPI where x: 1, 2, or 3 to select the SPI peripheral. + * @retval None + */ +#define __DAL_SPI_DISABLE(__HANDLE__) CLEAR_BIT((__HANDLE__)->Instance->CTRL1, SPI_CTRL1_SPIEN) + +/** + * @} + */ + +/* Private macros ------------------------------------------------------------*/ +/** @defgroup SPI_Private_Macros SPI Private Macros + * @{ + */ + +/** @brief Set the SPI transmit-only mode. + * @param __HANDLE__ specifies the SPI Handle. + * This parameter can be SPI where x: 1, 2, or 3 to select the SPI peripheral. + * @retval None + */ +#define SPI_1LINE_TX(__HANDLE__) SET_BIT((__HANDLE__)->Instance->CTRL1, SPI_CTRL1_BMOEN) + +/** @brief Set the SPI receive-only mode. + * @param __HANDLE__ specifies the SPI Handle. + * This parameter can be SPI where x: 1, 2, or 3 to select the SPI peripheral. + * @retval None + */ +#define SPI_1LINE_RX(__HANDLE__) CLEAR_BIT((__HANDLE__)->Instance->CTRL1, SPI_CTRL1_BMOEN) + +/** @brief Reset the CRC calculation of the SPI. + * @param __HANDLE__ specifies the SPI Handle. + * This parameter can be SPI where x: 1, 2, or 3 to select the SPI peripheral. + * @retval None + */ +#define SPI_RESET_CRC(__HANDLE__) do{CLEAR_BIT((__HANDLE__)->Instance->CTRL1, SPI_CTRL1_CRCEN);\ + SET_BIT((__HANDLE__)->Instance->CTRL1, SPI_CTRL1_CRCEN);}while(0U) + +/** @brief Check whether the specified SPI flag is set or not. + * @param __STS__ copy of SPI STS register. + * @param __FLAG__ specifies the flag to check. + * This parameter can be one of the following values: + * @arg SPI_FLAG_RXNE: Receive buffer not empty flag + * @arg SPI_FLAG_TXE: Transmit buffer empty flag + * @arg SPI_FLAG_CRCERR: CRC error flag + * @arg SPI_FLAG_MODF: Mode fault flag + * @arg SPI_FLAG_OVR: Overrun flag + * @arg SPI_FLAG_BSY: Busy flag + * @arg SPI_FLAG_FRE: Frame format error flag + * @retval SET or RESET. + */ +#define SPI_CHECK_FLAG(__STS__, __FLAG__) ((((__STS__) & ((__FLAG__) & SPI_FLAG_MASK)) == \ + ((__FLAG__) & SPI_FLAG_MASK)) ? SET : RESET) + +/** @brief Check whether the specified SPI Interrupt is set or not. + * @param __CTRL2__ copy of SPI CTRL2 register. + * @param __INTERRUPT__ specifies the SPI interrupt source to check. + * This parameter can be one of the following values: + * @arg SPI_IT_TXE: Tx buffer empty interrupt enable + * @arg SPI_IT_RXNE: RX buffer not empty interrupt enable + * @arg SPI_IT_ERR: Error interrupt enable + * @retval SET or RESET. + */ +#define SPI_CHECK_IT_SOURCE(__CTRL2__, __INTERRUPT__) ((((__CTRL2__) & (__INTERRUPT__)) == \ + (__INTERRUPT__)) ? SET : RESET) + +/** @brief Checks if SPI Mode parameter is in allowed range. + * @param __MODE__ specifies the SPI Mode. + * This parameter can be a value of @ref SPI_Mode + * @retval None + */ +#define IS_SPI_MODE(__MODE__) (((__MODE__) == SPI_MODE_SLAVE) || \ + ((__MODE__) == SPI_MODE_MASTER)) + +/** @brief Checks if SPI Direction Mode parameter is in allowed range. + * @param __MODE__ specifies the SPI Direction Mode. + * This parameter can be a value of @ref SPI_Direction + * @retval None + */ +#define IS_SPI_DIRECTION(__MODE__) (((__MODE__) == SPI_DIRECTION_2LINES) || \ + ((__MODE__) == SPI_DIRECTION_2LINES_RXONLY) || \ + ((__MODE__) == SPI_DIRECTION_1LINE)) + +/** @brief Checks if SPI Direction Mode parameter is 2 lines. + * @param __MODE__ specifies the SPI Direction Mode. + * @retval None + */ +#define IS_SPI_DIRECTION_2LINES(__MODE__) ((__MODE__) == SPI_DIRECTION_2LINES) + +/** @brief Checks if SPI Direction Mode parameter is 1 or 2 lines. + * @param __MODE__ specifies the SPI Direction Mode. + * @retval None + */ +#define IS_SPI_DIRECTION_2LINES_OR_1LINE(__MODE__) (((__MODE__) == SPI_DIRECTION_2LINES) || \ + ((__MODE__) == SPI_DIRECTION_1LINE)) + +/** @brief Checks if SPI Data Size parameter is in allowed range. + * @param __DATASIZE__ specifies the SPI Data Size. + * This parameter can be a value of @ref SPI_Data_Size + * @retval None + */ +#define IS_SPI_DATASIZE(__DATASIZE__) (((__DATASIZE__) == SPI_DATASIZE_16BIT) || \ + ((__DATASIZE__) == SPI_DATASIZE_8BIT)) + +/** @brief Checks if SPI Serial clock steady state parameter is in allowed range. + * @param __CPOL__ specifies the SPI serial clock steady state. + * This parameter can be a value of @ref SPI_Clock_Polarity + * @retval None + */ +#define IS_SPI_CPOL(__CPOL__) (((__CPOL__) == SPI_POLARITY_LOW) || \ + ((__CPOL__) == SPI_POLARITY_HIGH)) + +/** @brief Checks if SPI Clock Phase parameter is in allowed range. + * @param __CPHA__ specifies the SPI Clock Phase. + * This parameter can be a value of @ref SPI_Clock_Phase + * @retval None + */ +#define IS_SPI_CPHA(__CPHA__) (((__CPHA__) == SPI_PHASE_1EDGE) || \ + ((__CPHA__) == SPI_PHASE_2EDGE)) + +/** @brief Checks if SPI Slave Select parameter is in allowed range. + * @param __NSS__ specifies the SPI Slave Select management parameter. + * This parameter can be a value of @ref SPI_Slave_Select_management + * @retval None + */ +#define IS_SPI_NSS(__NSS__) (((__NSS__) == SPI_NSS_SOFT) || \ + ((__NSS__) == SPI_NSS_HARD_INPUT) || \ + ((__NSS__) == SPI_NSS_HARD_OUTPUT)) + +/** @brief Checks if SPI Baudrate prescaler parameter is in allowed range. + * @param __PRESCALER__ specifies the SPI Baudrate prescaler. + * This parameter can be a value of @ref SPI_BaudRate_Prescaler + * @retval None + */ +#define IS_SPI_BAUDRATE_PRESCALER(__PRESCALER__) (((__PRESCALER__) == SPI_BAUDRATEPRESCALER_2) || \ + ((__PRESCALER__) == SPI_BAUDRATEPRESCALER_4) || \ + ((__PRESCALER__) == SPI_BAUDRATEPRESCALER_8) || \ + ((__PRESCALER__) == SPI_BAUDRATEPRESCALER_16) || \ + ((__PRESCALER__) == SPI_BAUDRATEPRESCALER_32) || \ + ((__PRESCALER__) == SPI_BAUDRATEPRESCALER_64) || \ + ((__PRESCALER__) == SPI_BAUDRATEPRESCALER_128) || \ + ((__PRESCALER__) == SPI_BAUDRATEPRESCALER_256)) + +/** @brief Checks if SPI MSB LSB transmission parameter is in allowed range. + * @param __BIT__ specifies the SPI MSB LSB transmission (whether data transfer starts from MSB or LSB bit). + * This parameter can be a value of @ref SPI_MSB_LSB_transmission + * @retval None + */ +#define IS_SPI_FIRST_BIT(__BIT__) (((__BIT__) == SPI_FIRSTBIT_MSB) || \ + ((__BIT__) == SPI_FIRSTBIT_LSB)) + +/** @brief Checks if SPI TI mode parameter is in allowed range. + * @param __MODE__ specifies the SPI TI mode. + * This parameter can be a value of @ref SPI_TI_mode + * @retval None + */ +#define IS_SPI_TIMODE(__MODE__) (((__MODE__) == SPI_TIMODE_DISABLE) || \ + ((__MODE__) == SPI_TIMODE_ENABLE)) + +/** @brief Checks if SPI CRC calculation enabled state is in allowed range. + * @param __CALCULATION__ specifies the SPI CRC calculation enable state. + * This parameter can be a value of @ref SPI_CRC_Calculation + * @retval None + */ +#define IS_SPI_CRC_CALCULATION(__CALCULATION__) (((__CALCULATION__) == SPI_CRCCALCULATION_DISABLE) || \ + ((__CALCULATION__) == SPI_CRCCALCULATION_ENABLE)) + +/** @brief Checks if SPI polynomial value to be used for the CRC calculation, is in allowed range. + * @param __POLYNOMIAL__ specifies the SPI polynomial value to be used for the CRC calculation. + * This parameter must be a number between Min_Data = 0 and Max_Data = 65535 + * @retval None + */ +#define IS_SPI_CRC_POLYNOMIAL(__POLYNOMIAL__) (((__POLYNOMIAL__) >= 0x1U) && \ + ((__POLYNOMIAL__) <= 0xFFFFU) && \ + (((__POLYNOMIAL__)&0x1U) != 0U)) + +/** @brief Checks if DMA handle is valid. + * @param __HANDLE__ specifies a DMA Handle. + * @retval None + */ +#define IS_SPI_DMA_HANDLE(__HANDLE__) ((__HANDLE__) != NULL) + +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup SPI_Exported_Functions + * @{ + */ + +/** @addtogroup SPI_Exported_Functions_Group1 + * @{ + */ +/* Initialization/de-initialization functions ********************************/ +DAL_StatusTypeDef DAL_SPI_Init(SPI_HandleTypeDef *hspi); +DAL_StatusTypeDef DAL_SPI_DeInit(SPI_HandleTypeDef *hspi); +void DAL_SPI_MspInit(SPI_HandleTypeDef *hspi); +void DAL_SPI_MspDeInit(SPI_HandleTypeDef *hspi); + +/* Callbacks Register/UnRegister functions ***********************************/ +#if (USE_DAL_SPI_REGISTER_CALLBACKS == 1U) +DAL_StatusTypeDef DAL_SPI_RegisterCallback(SPI_HandleTypeDef *hspi, DAL_SPI_CallbackIDTypeDef CallbackID, + pSPI_CallbackTypeDef pCallback); +DAL_StatusTypeDef DAL_SPI_UnRegisterCallback(SPI_HandleTypeDef *hspi, DAL_SPI_CallbackIDTypeDef CallbackID); +#endif /* USE_DAL_SPI_REGISTER_CALLBACKS */ +/** + * @} + */ + +/** @addtogroup SPI_Exported_Functions_Group2 + * @{ + */ +/* I/O operation functions ***************************************************/ +DAL_StatusTypeDef DAL_SPI_Transmit(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size, uint32_t Timeout); +DAL_StatusTypeDef DAL_SPI_Receive(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size, uint32_t Timeout); +DAL_StatusTypeDef DAL_SPI_TransmitReceive(SPI_HandleTypeDef *hspi, uint8_t *pTxData, uint8_t *pRxData, uint16_t Size, + uint32_t Timeout); +DAL_StatusTypeDef DAL_SPI_Transmit_IT(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size); +DAL_StatusTypeDef DAL_SPI_Receive_IT(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size); +DAL_StatusTypeDef DAL_SPI_TransmitReceive_IT(SPI_HandleTypeDef *hspi, uint8_t *pTxData, uint8_t *pRxData, + uint16_t Size); +DAL_StatusTypeDef DAL_SPI_Transmit_DMA(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size); +DAL_StatusTypeDef DAL_SPI_Receive_DMA(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size); +DAL_StatusTypeDef DAL_SPI_TransmitReceive_DMA(SPI_HandleTypeDef *hspi, uint8_t *pTxData, uint8_t *pRxData, + uint16_t Size); +DAL_StatusTypeDef DAL_SPI_DMAPause(SPI_HandleTypeDef *hspi); +DAL_StatusTypeDef DAL_SPI_DMAResume(SPI_HandleTypeDef *hspi); +DAL_StatusTypeDef DAL_SPI_DMAStop(SPI_HandleTypeDef *hspi); +/* Transfer Abort functions */ +DAL_StatusTypeDef DAL_SPI_Abort(SPI_HandleTypeDef *hspi); +DAL_StatusTypeDef DAL_SPI_Abort_IT(SPI_HandleTypeDef *hspi); + +void DAL_SPI_IRQHandler(SPI_HandleTypeDef *hspi); +void DAL_SPI_TxCpltCallback(SPI_HandleTypeDef *hspi); +void DAL_SPI_RxCpltCallback(SPI_HandleTypeDef *hspi); +void DAL_SPI_TxRxCpltCallback(SPI_HandleTypeDef *hspi); +void DAL_SPI_TxHalfCpltCallback(SPI_HandleTypeDef *hspi); +void DAL_SPI_RxHalfCpltCallback(SPI_HandleTypeDef *hspi); +void DAL_SPI_TxRxHalfCpltCallback(SPI_HandleTypeDef *hspi); +void DAL_SPI_ErrorCallback(SPI_HandleTypeDef *hspi); +void DAL_SPI_AbortCpltCallback(SPI_HandleTypeDef *hspi); +/** + * @} + */ + +/** @addtogroup SPI_Exported_Functions_Group3 + * @{ + */ +/* Peripheral State and Error functions ***************************************/ +DAL_SPI_StateTypeDef DAL_SPI_GetState(SPI_HandleTypeDef *hspi); +uint32_t DAL_SPI_GetError(SPI_HandleTypeDef *hspi); +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* APM32F4xx_DAL_SPI_H */ + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_sram.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_sram.h new file mode 100644 index 0000000000..607bef94dd --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_sram.h @@ -0,0 +1,258 @@ +/** + * + * @file apm32f4xx_dal_sram.h + * @brief Header file of SRAM DAL module. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef APM32F4xx_DAL_SRAM_H +#define APM32F4xx_DAL_SRAM_H + +#ifdef __cplusplus +extern "C" { +#endif + +#if defined(SMC_Bank1) + +/* Includes ------------------------------------------------------------------*/ +#if defined(SMC_Bank1) +#include "apm32f4xx_ddl_smc.h" +#endif /* SMC_Bank1 */ + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ +/** @addtogroup SRAM + * @{ + */ + +/* Exported typedef ----------------------------------------------------------*/ + +/** @defgroup SRAM_Exported_Types SRAM Exported Types + * @{ + */ +/** + * @brief DAL SRAM State structures definition + */ +typedef enum +{ + DAL_SRAM_STATE_RESET = 0x00U, /*!< SRAM not yet initialized or disabled */ + DAL_SRAM_STATE_READY = 0x01U, /*!< SRAM initialized and ready for use */ + DAL_SRAM_STATE_BUSY = 0x02U, /*!< SRAM internal process is ongoing */ + DAL_SRAM_STATE_ERROR = 0x03U, /*!< SRAM error state */ + DAL_SRAM_STATE_PROTECTED = 0x04U /*!< SRAM peripheral NORSRAM device write protected */ + +} DAL_SRAM_StateTypeDef; + +/** + * @brief SRAM handle Structure definition + */ +#if (USE_DAL_SRAM_REGISTER_CALLBACKS == 1) +typedef struct __SRAM_HandleTypeDef +#else +typedef struct +#endif /* USE_DAL_SRAM_REGISTER_CALLBACKS */ +{ + FMC_NORSRAM_TypeDef *Instance; /*!< Register base address */ + + FMC_NORSRAM_EXTENDED_TypeDef *Extended; /*!< Extended mode register base address */ + + FMC_NORSRAM_InitTypeDef Init; /*!< SRAM device control configuration parameters */ + + DAL_LockTypeDef Lock; /*!< SRAM locking object */ + + __IO DAL_SRAM_StateTypeDef State; /*!< SRAM device access state */ + + DMA_HandleTypeDef *hdma; /*!< Pointer DMA handler */ + +#if (USE_DAL_SRAM_REGISTER_CALLBACKS == 1) + void (* MspInitCallback)(struct __SRAM_HandleTypeDef *hsram); /*!< SRAM Msp Init callback */ + void (* MspDeInitCallback)(struct __SRAM_HandleTypeDef *hsram); /*!< SRAM Msp DeInit callback */ + void (* DmaXferCpltCallback)(DMA_HandleTypeDef *hdma); /*!< SRAM DMA Xfer Complete callback */ + void (* DmaXferErrorCallback)(DMA_HandleTypeDef *hdma); /*!< SRAM DMA Xfer Error callback */ +#endif /* USE_DAL_SRAM_REGISTER_CALLBACKS */ +} SRAM_HandleTypeDef; + +#if (USE_DAL_SRAM_REGISTER_CALLBACKS == 1) +/** + * @brief DAL SRAM Callback ID enumeration definition + */ +typedef enum +{ + DAL_SRAM_MSP_INIT_CB_ID = 0x00U, /*!< SRAM MspInit Callback ID */ + DAL_SRAM_MSP_DEINIT_CB_ID = 0x01U, /*!< SRAM MspDeInit Callback ID */ + DAL_SRAM_DMA_XFER_CPLT_CB_ID = 0x02U, /*!< SRAM DMA Xfer Complete Callback ID */ + DAL_SRAM_DMA_XFER_ERR_CB_ID = 0x03U /*!< SRAM DMA Xfer Complete Callback ID */ +} DAL_SRAM_CallbackIDTypeDef; + +/** + * @brief DAL SRAM Callback pointer definition + */ +typedef void (*pSRAM_CallbackTypeDef)(SRAM_HandleTypeDef *hsram); +typedef void (*pSRAM_DmaCallbackTypeDef)(DMA_HandleTypeDef *hdma); +#endif /* USE_DAL_SRAM_REGISTER_CALLBACKS */ +/** + * @} + */ + +/* Exported constants --------------------------------------------------------*/ +/* Exported macro ------------------------------------------------------------*/ + +/** @defgroup SRAM_Exported_Macros SRAM Exported Macros + * @{ + */ + +/** @brief Reset SRAM handle state + * @param __HANDLE__ SRAM handle + * @retval None + */ +#if (USE_DAL_SRAM_REGISTER_CALLBACKS == 1) +#define __DAL_SRAM_RESET_HANDLE_STATE(__HANDLE__) do { \ + (__HANDLE__)->State = DAL_SRAM_STATE_RESET; \ + (__HANDLE__)->MspInitCallback = NULL; \ + (__HANDLE__)->MspDeInitCallback = NULL; \ + } while(0) +#else +#define __DAL_SRAM_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = DAL_SRAM_STATE_RESET) +#endif /* USE_DAL_SRAM_REGISTER_CALLBACKS */ + +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup SRAM_Exported_Functions SRAM Exported Functions + * @{ + */ + +/** @addtogroup SRAM_Exported_Functions_Group1 Initialization and de-initialization functions + * @{ + */ + +/* Initialization/de-initialization functions ********************************/ +DAL_StatusTypeDef DAL_SRAM_Init(SRAM_HandleTypeDef *hsram, FMC_NORSRAM_TimingTypeDef *Timing, + FMC_NORSRAM_TimingTypeDef *ExtTiming); +DAL_StatusTypeDef DAL_SRAM_DeInit(SRAM_HandleTypeDef *hsram); +void DAL_SRAM_MspInit(SRAM_HandleTypeDef *hsram); +void DAL_SRAM_MspDeInit(SRAM_HandleTypeDef *hsram); + +/** + * @} + */ + +/** @addtogroup SRAM_Exported_Functions_Group2 Input Output and memory control functions + * @{ + */ + +/* I/O operation functions ***************************************************/ +DAL_StatusTypeDef DAL_SRAM_Read_8b(SRAM_HandleTypeDef *hsram, uint32_t *pAddress, uint8_t *pDstBuffer, + uint32_t BufferSize); +DAL_StatusTypeDef DAL_SRAM_Write_8b(SRAM_HandleTypeDef *hsram, uint32_t *pAddress, uint8_t *pSrcBuffer, + uint32_t BufferSize); +DAL_StatusTypeDef DAL_SRAM_Read_16b(SRAM_HandleTypeDef *hsram, uint32_t *pAddress, uint16_t *pDstBuffer, + uint32_t BufferSize); +DAL_StatusTypeDef DAL_SRAM_Write_16b(SRAM_HandleTypeDef *hsram, uint32_t *pAddress, uint16_t *pSrcBuffer, + uint32_t BufferSize); +DAL_StatusTypeDef DAL_SRAM_Read_32b(SRAM_HandleTypeDef *hsram, uint32_t *pAddress, uint32_t *pDstBuffer, + uint32_t BufferSize); +DAL_StatusTypeDef DAL_SRAM_Write_32b(SRAM_HandleTypeDef *hsram, uint32_t *pAddress, uint32_t *pSrcBuffer, + uint32_t BufferSize); +DAL_StatusTypeDef DAL_SRAM_Read_DMA(SRAM_HandleTypeDef *hsram, uint32_t *pAddress, uint32_t *pDstBuffer, + uint32_t BufferSize); +DAL_StatusTypeDef DAL_SRAM_Write_DMA(SRAM_HandleTypeDef *hsram, uint32_t *pAddress, uint32_t *pSrcBuffer, + uint32_t BufferSize); + +void DAL_SRAM_DMA_XferCpltCallback(DMA_HandleTypeDef *hdma); +void DAL_SRAM_DMA_XferErrorCallback(DMA_HandleTypeDef *hdma); + +#if (USE_DAL_SRAM_REGISTER_CALLBACKS == 1) +/* SRAM callback registering/unregistering */ +DAL_StatusTypeDef DAL_SRAM_RegisterCallback(SRAM_HandleTypeDef *hsram, DAL_SRAM_CallbackIDTypeDef CallbackId, + pSRAM_CallbackTypeDef pCallback); +DAL_StatusTypeDef DAL_SRAM_UnRegisterCallback(SRAM_HandleTypeDef *hsram, DAL_SRAM_CallbackIDTypeDef CallbackId); +DAL_StatusTypeDef DAL_SRAM_RegisterDmaCallback(SRAM_HandleTypeDef *hsram, DAL_SRAM_CallbackIDTypeDef CallbackId, + pSRAM_DmaCallbackTypeDef pCallback); +#endif /* USE_DAL_SRAM_REGISTER_CALLBACKS */ + +/** + * @} + */ + +/** @addtogroup SRAM_Exported_Functions_Group3 Control functions + * @{ + */ + +/* SRAM Control functions ****************************************************/ +DAL_StatusTypeDef DAL_SRAM_WriteOperation_Enable(SRAM_HandleTypeDef *hsram); +DAL_StatusTypeDef DAL_SRAM_WriteOperation_Disable(SRAM_HandleTypeDef *hsram); + +/** + * @} + */ + +/** @addtogroup SRAM_Exported_Functions_Group4 Peripheral State functions + * @{ + */ + +/* SRAM State functions ******************************************************/ +DAL_SRAM_StateTypeDef DAL_SRAM_GetState(SRAM_HandleTypeDef *hsram); + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#endif /* SMC_Bank1 */ + +#ifdef __cplusplus +} +#endif + +#endif /* APM32F4xx_DAL_SRAM_H */ diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_tmr.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_tmr.h new file mode 100644 index 0000000000..3f1be343a9 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_tmr.h @@ -0,0 +1,2171 @@ +/** + * + * @file apm32f4xx_dal_tmr.h + * @brief Header file of TMR DAL module. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef APM32F4xx_DAL_TMR_H +#define APM32F4xx_DAL_TMR_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal_def.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @addtogroup TMR + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ +/** @defgroup TMR_Exported_Types TMR Exported Types + * @{ + */ + +/** + * @brief TMR Time base Configuration Structure definition + */ +typedef struct +{ + uint32_t Prescaler; /*!< Specifies the prescaler value used to divide the TMR clock. + This parameter can be a number between Min_Data = 0x0000 and Max_Data = 0xFFFF */ + + uint32_t CounterMode; /*!< Specifies the counter mode. + This parameter can be a value of @ref TMR_Counter_Mode */ + + uint32_t Period; /*!< Specifies the period value to be loaded into the active + Auto-Reload Register at the next update event. + This parameter can be a number between Min_Data = 0x0000 and Max_Data = 0xFFFF. */ + + uint32_t ClockDivision; /*!< Specifies the clock division. + This parameter can be a value of @ref TMR_ClockDivision */ + + uint32_t RepetitionCounter; /*!< Specifies the repetition counter value. Each time the REPCNT downcounter + reaches zero, an update event is generated and counting restarts + from the REPCNT value (N). + This means in PWM mode that (N+1) corresponds to: + - the number of PWM periods in edge-aligned mode + - the number of half PWM period in center-aligned mode + GP timers: this parameter must be a number between Min_Data = 0x00 and + Max_Data = 0xFF. + Advanced timers: this parameter must be a number between Min_Data = 0x0000 and + Max_Data = 0xFFFF. */ + + uint32_t AutoReloadPreload; /*!< Specifies the auto-reload preload. + This parameter can be a value of @ref TMR_AutoReloadPreload */ +} TMR_Base_InitTypeDef; + +/** + * @brief TMR Output Compare Configuration Structure definition + */ +typedef struct +{ + uint32_t OCMode; /*!< Specifies the TMR mode. + This parameter can be a value of @ref TMR_Output_Compare_and_PWM_modes */ + + uint32_t Pulse; /*!< Specifies the pulse value to be loaded into the Capture Compare Register. + This parameter can be a number between Min_Data = 0x0000 and Max_Data = 0xFFFF */ + + uint32_t OCPolarity; /*!< Specifies the output polarity. + This parameter can be a value of @ref TMR_Output_Compare_Polarity */ + + uint32_t OCNPolarity; /*!< Specifies the complementary output polarity. + This parameter can be a value of @ref TMR_Output_Compare_N_Polarity + @note This parameter is valid only for timer instances supporting break feature. */ + + uint32_t OCFastMode; /*!< Specifies the Fast mode state. + This parameter can be a value of @ref TMR_Output_Fast_State + @note This parameter is valid only in PWM1 and PWM2 mode. */ + + + uint32_t OCIdleState; /*!< Specifies the TMR Output Compare pin state during Idle state. + This parameter can be a value of @ref TMR_Output_Compare_Idle_State + @note This parameter is valid only for timer instances supporting break feature. */ + + uint32_t OCNIdleState; /*!< Specifies the TMR Output Compare pin state during Idle state. + This parameter can be a value of @ref TMR_Output_Compare_N_Idle_State + @note This parameter is valid only for timer instances supporting break feature. */ +} TMR_OC_InitTypeDef; + +/** + * @brief TMR One Pulse Mode Configuration Structure definition + */ +typedef struct +{ + uint32_t OCMode; /*!< Specifies the TMR mode. + This parameter can be a value of @ref TMR_Output_Compare_and_PWM_modes */ + + uint32_t Pulse; /*!< Specifies the pulse value to be loaded into the Capture Compare Register. + This parameter can be a number between Min_Data = 0x0000 and Max_Data = 0xFFFF */ + + uint32_t OCPolarity; /*!< Specifies the output polarity. + This parameter can be a value of @ref TMR_Output_Compare_Polarity */ + + uint32_t OCNPolarity; /*!< Specifies the complementary output polarity. + This parameter can be a value of @ref TMR_Output_Compare_N_Polarity + @note This parameter is valid only for timer instances supporting break feature. */ + + uint32_t OCIdleState; /*!< Specifies the TMR Output Compare pin state during Idle state. + This parameter can be a value of @ref TMR_Output_Compare_Idle_State + @note This parameter is valid only for timer instances supporting break feature. */ + + uint32_t OCNIdleState; /*!< Specifies the TMR Output Compare pin state during Idle state. + This parameter can be a value of @ref TMR_Output_Compare_N_Idle_State + @note This parameter is valid only for timer instances supporting break feature. */ + + uint32_t ICPolarity; /*!< Specifies the active edge of the input signal. + This parameter can be a value of @ref TMR_Input_Capture_Polarity */ + + uint32_t ICSelection; /*!< Specifies the input. + This parameter can be a value of @ref TMR_Input_Capture_Selection */ + + uint32_t ICFilter; /*!< Specifies the input capture filter. + This parameter can be a number between Min_Data = 0x0 and Max_Data = 0xF */ +} TMR_OnePulse_InitTypeDef; + +/** + * @brief TMR Input Capture Configuration Structure definition + */ +typedef struct +{ + uint32_t ICPolarity; /*!< Specifies the active edge of the input signal. + This parameter can be a value of @ref TMR_Input_Capture_Polarity */ + + uint32_t ICSelection; /*!< Specifies the input. + This parameter can be a value of @ref TMR_Input_Capture_Selection */ + + uint32_t ICPrescaler; /*!< Specifies the Input Capture Prescaler. + This parameter can be a value of @ref TMR_Input_Capture_Prescaler */ + + uint32_t ICFilter; /*!< Specifies the input capture filter. + This parameter can be a number between Min_Data = 0x0 and Max_Data = 0xF */ +} TMR_IC_InitTypeDef; + +/** + * @brief TMR Encoder Configuration Structure definition + */ +typedef struct +{ + uint32_t EncoderMode; /*!< Specifies the active edge of the input signal. + This parameter can be a value of @ref TMR_Encoder_Mode */ + + uint32_t IC1Polarity; /*!< Specifies the active edge of the input signal. + This parameter can be a value of @ref TMR_Encoder_Input_Polarity */ + + uint32_t IC1Selection; /*!< Specifies the input. + This parameter can be a value of @ref TMR_Input_Capture_Selection */ + + uint32_t IC1Prescaler; /*!< Specifies the Input Capture Prescaler. + This parameter can be a value of @ref TMR_Input_Capture_Prescaler */ + + uint32_t IC1Filter; /*!< Specifies the input capture filter. + This parameter can be a number between Min_Data = 0x0 and Max_Data = 0xF */ + + uint32_t IC2Polarity; /*!< Specifies the active edge of the input signal. + This parameter can be a value of @ref TMR_Encoder_Input_Polarity */ + + uint32_t IC2Selection; /*!< Specifies the input. + This parameter can be a value of @ref TMR_Input_Capture_Selection */ + + uint32_t IC2Prescaler; /*!< Specifies the Input Capture Prescaler. + This parameter can be a value of @ref TMR_Input_Capture_Prescaler */ + + uint32_t IC2Filter; /*!< Specifies the input capture filter. + This parameter can be a number between Min_Data = 0x0 and Max_Data = 0xF */ +} TMR_Encoder_InitTypeDef; + +/** + * @brief Clock Configuration Handle Structure definition + */ +typedef struct +{ + uint32_t ClockSource; /*!< TMR clock sources + This parameter can be a value of @ref TMR_Clock_Source */ + uint32_t ClockPolarity; /*!< TMR clock polarity + This parameter can be a value of @ref TMR_Clock_Polarity */ + uint32_t ClockPrescaler; /*!< TMR clock prescaler + This parameter can be a value of @ref TMR_Clock_Prescaler */ + uint32_t ClockFilter; /*!< TMR clock filter + This parameter can be a number between Min_Data = 0x0 and Max_Data = 0xF */ +} TMR_ClockConfigTypeDef; + +/** + * @brief TMR Clear Input Configuration Handle Structure definition + */ +typedef struct +{ + uint32_t ClearInputState; /*!< TMR clear Input state + This parameter can be ENABLE or DISABLE */ + uint32_t ClearInputSource; /*!< TMR clear Input sources + This parameter can be a value of @ref TMR_ClearInput_Source */ + uint32_t ClearInputPolarity; /*!< TMR Clear Input polarity + This parameter can be a value of @ref TMR_ClearInput_Polarity */ + uint32_t ClearInputPrescaler; /*!< TMR Clear Input prescaler + This parameter must be 0: When OCRef clear feature is used with ETR source, + ETR prescaler must be off */ + uint32_t ClearInputFilter; /*!< TMR Clear Input filter + This parameter can be a number between Min_Data = 0x0 and Max_Data = 0xF */ +} TMR_ClearInputConfigTypeDef; + +/** + * @brief TMR Master configuration Structure definition + */ +typedef struct +{ + uint32_t MasterOutputTrigger; /*!< Trigger output (TRGO) selection + This parameter can be a value of @ref TMR_Master_Mode_Selection */ + uint32_t MasterSlaveMode; /*!< Master/slave mode selection + This parameter can be a value of @ref TMR_Master_Slave_Mode + @note When the Master/slave mode is enabled, the effect of + an event on the trigger input (TRGI) is delayed to allow a + perfect synchronization between the current timer and its + slaves (through TRGO). It is not mandatory in case of timer + synchronization mode. */ +} TMR_MasterConfigTypeDef; + +/** + * @brief TMR Slave configuration Structure definition + */ +typedef struct +{ + uint32_t SlaveMode; /*!< Slave mode selection + This parameter can be a value of @ref TMR_Slave_Mode */ + uint32_t InputTrigger; /*!< Input Trigger source + This parameter can be a value of @ref TMR_Trigger_Selection */ + uint32_t TriggerPolarity; /*!< Input Trigger polarity + This parameter can be a value of @ref TMR_Trigger_Polarity */ + uint32_t TriggerPrescaler; /*!< Input trigger prescaler + This parameter can be a value of @ref TMR_Trigger_Prescaler */ + uint32_t TriggerFilter; /*!< Input trigger filter + This parameter can be a number between Min_Data = 0x0 and Max_Data = 0xF */ + +} TMR_SlaveConfigTypeDef; + +/** + * @brief TMR Break input(s) and Dead time configuration Structure definition + * @note 2 break inputs can be configured (BKIN and BKIN2) with configurable + * filter and polarity. + */ +typedef struct +{ + uint32_t OffStateRunMode; /*!< TMR off state in run mode, This parameter can be a value of @ref TMR_OSSR_Off_State_Selection_for_Run_mode_state */ + + uint32_t OffStateIDLEMode; /*!< TMR off state in IDLE mode, This parameter can be a value of @ref TMR_OSSI_Off_State_Selection_for_Idle_mode_state */ + + uint32_t LockLevel; /*!< TMR Lock level, This parameter can be a value of @ref TMR_Lock_level */ + + uint32_t DeadTime; /*!< TMR dead Time, This parameter can be a number between Min_Data = 0x00 and Max_Data = 0xFF */ + + uint32_t BreakState; /*!< TMR Break State, This parameter can be a value of @ref TMR_Break_Input_enable_disable */ + + uint32_t BreakPolarity; /*!< TMR Break input polarity, This parameter can be a value of @ref TMR_Break_Polarity */ + + uint32_t BreakFilter; /*!< Specifies the break input filter.This parameter can be a number between Min_Data = 0x0 and Max_Data = 0xF */ + + uint32_t AutomaticOutput; /*!< TMR Automatic Output Enable state, This parameter can be a value of @ref TMR_AOE_Bit_Set_Reset */ + +} TMR_BreakDeadTimeConfigTypeDef; + +/** + * @brief DAL State structures definition + */ +typedef enum +{ + DAL_TMR_STATE_RESET = 0x00U, /*!< Peripheral not yet initialized or disabled */ + DAL_TMR_STATE_READY = 0x01U, /*!< Peripheral Initialized and ready for use */ + DAL_TMR_STATE_BUSY = 0x02U, /*!< An internal process is ongoing */ + DAL_TMR_STATE_TIMEOUT = 0x03U, /*!< Timeout state */ + DAL_TMR_STATE_ERROR = 0x04U /*!< Reception process is ongoing */ +} DAL_TMR_StateTypeDef; + +/** + * @brief TMR Channel States definition + */ +typedef enum +{ + DAL_TMR_CHANNEL_STATE_RESET = 0x00U, /*!< TMR Channel initial state */ + DAL_TMR_CHANNEL_STATE_READY = 0x01U, /*!< TMR Channel ready for use */ + DAL_TMR_CHANNEL_STATE_BUSY = 0x02U, /*!< An internal process is ongoing on the TMR channel */ +} DAL_TMR_ChannelStateTypeDef; + +/** + * @brief DMA Burst States definition + */ +typedef enum +{ + DAL_DMA_BURST_STATE_RESET = 0x00U, /*!< DMA Burst initial state */ + DAL_DMA_BURST_STATE_READY = 0x01U, /*!< DMA Burst ready for use */ + DAL_DMA_BURST_STATE_BUSY = 0x02U, /*!< Ongoing DMA Burst */ +} DAL_TMR_DMABurstStateTypeDef; + +/** + * @brief DAL Active channel structures definition + */ +typedef enum +{ + DAL_TMR_ACTIVE_CHANNEL_1 = 0x01U, /*!< The active channel is 1 */ + DAL_TMR_ACTIVE_CHANNEL_2 = 0x02U, /*!< The active channel is 2 */ + DAL_TMR_ACTIVE_CHANNEL_3 = 0x04U, /*!< The active channel is 3 */ + DAL_TMR_ACTIVE_CHANNEL_4 = 0x08U, /*!< The active channel is 4 */ + DAL_TMR_ACTIVE_CHANNEL_CLEARED = 0x00U /*!< All active channels cleared */ +} DAL_TMR_ActiveChannel; + +/** + * @brief TMR Time Base Handle Structure definition + */ +#if (USE_DAL_TMR_REGISTER_CALLBACKS == 1) +typedef struct __TMR_HandleTypeDef +#else +typedef struct +#endif /* USE_DAL_TMR_REGISTER_CALLBACKS */ +{ + TMR_TypeDef *Instance; /*!< Register base address */ + TMR_Base_InitTypeDef Init; /*!< TMR Time Base required parameters */ + DAL_TMR_ActiveChannel Channel; /*!< Active channel */ + DMA_HandleTypeDef *hdma[7]; /*!< DMA Handlers array + This array is accessed by a @ref DMA_Handle_index */ + DAL_LockTypeDef Lock; /*!< Locking object */ + __IO DAL_TMR_StateTypeDef State; /*!< TMR operation state */ + __IO DAL_TMR_ChannelStateTypeDef ChannelState[4]; /*!< TMR channel operation state */ + __IO DAL_TMR_ChannelStateTypeDef ChannelNState[4]; /*!< TMR complementary channel operation state */ + __IO DAL_TMR_DMABurstStateTypeDef DMABurstState; /*!< DMA burst operation state */ + +#if (USE_DAL_TMR_REGISTER_CALLBACKS == 1) + void (* Base_MspInitCallback)(struct __TMR_HandleTypeDef *htmr); /*!< TMR Base Msp Init Callback */ + void (* Base_MspDeInitCallback)(struct __TMR_HandleTypeDef *htmr); /*!< TMR Base Msp DeInit Callback */ + void (* IC_MspInitCallback)(struct __TMR_HandleTypeDef *htmr); /*!< TMR IC Msp Init Callback */ + void (* IC_MspDeInitCallback)(struct __TMR_HandleTypeDef *htmr); /*!< TMR IC Msp DeInit Callback */ + void (* OC_MspInitCallback)(struct __TMR_HandleTypeDef *htmr); /*!< TMR OC Msp Init Callback */ + void (* OC_MspDeInitCallback)(struct __TMR_HandleTypeDef *htmr); /*!< TMR OC Msp DeInit Callback */ + void (* PWM_MspInitCallback)(struct __TMR_HandleTypeDef *htmr); /*!< TMR PWM Msp Init Callback */ + void (* PWM_MspDeInitCallback)(struct __TMR_HandleTypeDef *htmr); /*!< TMR PWM Msp DeInit Callback */ + void (* OnePulse_MspInitCallback)(struct __TMR_HandleTypeDef *htmr); /*!< TMR One Pulse Msp Init Callback */ + void (* OnePulse_MspDeInitCallback)(struct __TMR_HandleTypeDef *htmr); /*!< TMR One Pulse Msp DeInit Callback */ + void (* Encoder_MspInitCallback)(struct __TMR_HandleTypeDef *htmr); /*!< TMR Encoder Msp Init Callback */ + void (* Encoder_MspDeInitCallback)(struct __TMR_HandleTypeDef *htmr); /*!< TMR Encoder Msp DeInit Callback */ + void (* HallSensor_MspInitCallback)(struct __TMR_HandleTypeDef *htmr); /*!< TMR Hall Sensor Msp Init Callback */ + void (* HallSensor_MspDeInitCallback)(struct __TMR_HandleTypeDef *htmr); /*!< TMR Hall Sensor Msp DeInit Callback */ + void (* PeriodElapsedCallback)(struct __TMR_HandleTypeDef *htmr); /*!< TMR Period Elapsed Callback */ + void (* PeriodElapsedHalfCpltCallback)(struct __TMR_HandleTypeDef *htmr); /*!< TMR Period Elapsed half complete Callback */ + void (* TriggerCallback)(struct __TMR_HandleTypeDef *htmr); /*!< TMR Trigger Callback */ + void (* TriggerHalfCpltCallback)(struct __TMR_HandleTypeDef *htmr); /*!< TMR Trigger half complete Callback */ + void (* IC_CaptureCallback)(struct __TMR_HandleTypeDef *htmr); /*!< TMR Input Capture Callback */ + void (* IC_CaptureHalfCpltCallback)(struct __TMR_HandleTypeDef *htmr); /*!< TMR Input Capture half complete Callback */ + void (* OC_DelayElapsedCallback)(struct __TMR_HandleTypeDef *htmr); /*!< TMR Output Compare Delay Elapsed Callback */ + void (* PWM_PulseFinishedCallback)(struct __TMR_HandleTypeDef *htmr); /*!< TMR PWM Pulse Finished Callback */ + void (* PWM_PulseFinishedHalfCpltCallback)(struct __TMR_HandleTypeDef *htmr); /*!< TMR PWM Pulse Finished half complete Callback */ + void (* ErrorCallback)(struct __TMR_HandleTypeDef *htmr); /*!< TMR Error Callback */ + void (* CommutationCallback)(struct __TMR_HandleTypeDef *htmr); /*!< TMR Commutation Callback */ + void (* CommutationHalfCpltCallback)(struct __TMR_HandleTypeDef *htmr); /*!< TMR Commutation half complete Callback */ + void (* BreakCallback)(struct __TMR_HandleTypeDef *htmr); /*!< TMR Break Callback */ +#endif /* USE_DAL_TMR_REGISTER_CALLBACKS */ +} TMR_HandleTypeDef; + +#if (USE_DAL_TMR_REGISTER_CALLBACKS == 1) +/** + * @brief DAL TMR Callback ID enumeration definition + */ +typedef enum +{ + DAL_TMR_BASE_MSPINIT_CB_ID = 0x00U /*!< TMR Base MspInit Callback ID */ + , DAL_TMR_BASE_MSPDEINIT_CB_ID = 0x01U /*!< TMR Base MspDeInit Callback ID */ + , DAL_TMR_IC_MSPINIT_CB_ID = 0x02U /*!< TMR IC MspInit Callback ID */ + , DAL_TMR_IC_MSPDEINIT_CB_ID = 0x03U /*!< TMR IC MspDeInit Callback ID */ + , DAL_TMR_OC_MSPINIT_CB_ID = 0x04U /*!< TMR OC MspInit Callback ID */ + , DAL_TMR_OC_MSPDEINIT_CB_ID = 0x05U /*!< TMR OC MspDeInit Callback ID */ + , DAL_TMR_PWM_MSPINIT_CB_ID = 0x06U /*!< TMR PWM MspInit Callback ID */ + , DAL_TMR_PWM_MSPDEINIT_CB_ID = 0x07U /*!< TMR PWM MspDeInit Callback ID */ + , DAL_TMR_ONE_PULSE_MSPINIT_CB_ID = 0x08U /*!< TMR One Pulse MspInit Callback ID */ + , DAL_TMR_ONE_PULSE_MSPDEINIT_CB_ID = 0x09U /*!< TMR One Pulse MspDeInit Callback ID */ + , DAL_TMR_ENCODER_MSPINIT_CB_ID = 0x0AU /*!< TMR Encoder MspInit Callback ID */ + , DAL_TMR_ENCODER_MSPDEINIT_CB_ID = 0x0BU /*!< TMR Encoder MspDeInit Callback ID */ + , DAL_TMR_HALL_SENSOR_MSPINIT_CB_ID = 0x0CU /*!< TMR Hall Sensor MspDeInit Callback ID */ + , DAL_TMR_HALL_SENSOR_MSPDEINIT_CB_ID = 0x0DU /*!< TMR Hall Sensor MspDeInit Callback ID */ + , DAL_TMR_PERIOD_ELAPSED_CB_ID = 0x0EU /*!< TMR Period Elapsed Callback ID */ + , DAL_TMR_PERIOD_ELAPSED_HALF_CB_ID = 0x0FU /*!< TMR Period Elapsed half complete Callback ID */ + , DAL_TMR_TRIGGER_CB_ID = 0x10U /*!< TMR Trigger Callback ID */ + , DAL_TMR_TRIGGER_HALF_CB_ID = 0x11U /*!< TMR Trigger half complete Callback ID */ + + , DAL_TMR_IC_CAPTURE_CB_ID = 0x12U /*!< TMR Input Capture Callback ID */ + , DAL_TMR_IC_CAPTURE_HALF_CB_ID = 0x13U /*!< TMR Input Capture half complete Callback ID */ + , DAL_TMR_OC_DELAY_ELAPSED_CB_ID = 0x14U /*!< TMR Output Compare Delay Elapsed Callback ID */ + , DAL_TMR_PWM_PULSE_FINISHED_CB_ID = 0x15U /*!< TMR PWM Pulse Finished Callback ID */ + , DAL_TMR_PWM_PULSE_FINISHED_HALF_CB_ID = 0x16U /*!< TMR PWM Pulse Finished half complete Callback ID */ + , DAL_TMR_ERROR_CB_ID = 0x17U /*!< TMR Error Callback ID */ + , DAL_TMR_COMMUTATION_CB_ID = 0x18U /*!< TMR Commutation Callback ID */ + , DAL_TMR_COMMUTATION_HALF_CB_ID = 0x19U /*!< TMR Commutation half complete Callback ID */ + , DAL_TMR_BREAK_CB_ID = 0x1AU /*!< TMR Break Callback ID */ +} DAL_TMR_CallbackIDTypeDef; + +/** + * @brief DAL TMR Callback pointer definition + */ +typedef void (*pTMR_CallbackTypeDef)(TMR_HandleTypeDef *htmr); /*!< pointer to the TMR callback function */ + +#endif /* USE_DAL_TMR_REGISTER_CALLBACKS */ + +/** + * @} + */ +/* End of exported types -----------------------------------------------------*/ + +/* Exported constants --------------------------------------------------------*/ +/** @defgroup TMR_Exported_Constants TMR Exported Constants + * @{ + */ + +/** @defgroup TMR_ClearInput_Source TMR Clear Input Source + * @{ + */ +#define TMR_CLEARINPUTSOURCE_NONE 0x00000000U /*!< OCREF_CLR is disabled */ +#define TMR_CLEARINPUTSOURCE_ETR 0x00000001U /*!< OCREF_CLR is connected to ETRF input */ +/** + * @} + */ + +/** @defgroup TMR_DMA_Base_address TMR DMA Base Address + * @{ + */ +#define TMR_DMABASE_CTRL1 0x00000000U +#define TMR_DMABASE_CTRL2 0x00000001U +#define TMR_DMABASE_SMCTRL 0x00000002U +#define TMR_DMABASE_DIEN 0x00000003U +#define TMR_DMABASE_STS 0x00000004U +#define TMR_DMABASE_CEG 0x00000005U +#define TMR_DMABASE_CCM1 0x00000006U +#define TMR_DMABASE_CCM2 0x00000007U +#define TMR_DMABASE_CCEN 0x00000008U +#define TMR_DMABASE_CNT 0x00000009U +#define TMR_DMABASE_PSC 0x0000000AU +#define TMR_DMABASE_AUTORLD 0x0000000BU +#define TMR_DMABASE_REPCNT 0x0000000CU +#define TMR_DMABASE_CC1 0x0000000DU +#define TMR_DMABASE_CC2 0x0000000EU +#define TMR_DMABASE_CC3 0x0000000FU +#define TMR_DMABASE_CC4 0x00000010U +#define TMR_DMABASE_BDT 0x00000011U +#define TMR_DMABASE_DCR 0x00000012U +#define TMR_DMABASE_DMAR 0x00000013U +/** + * @} + */ + +/** @defgroup TMR_Event_Source TMR Event Source + * @{ + */ +#define TMR_EVENTSOURCE_UPDATE TMR_CEG_UEG /*!< Reinitialize the counter and generates an update of the registers */ +#define TMR_EVENTSOURCE_CC1 TMR_CEG_CC1EG /*!< A capture/compare event is generated on channel 1 */ +#define TMR_EVENTSOURCE_CC2 TMR_CEG_CC2EG /*!< A capture/compare event is generated on channel 2 */ +#define TMR_EVENTSOURCE_CC3 TMR_CEG_CC3EG /*!< A capture/compare event is generated on channel 3 */ +#define TMR_EVENTSOURCE_CC4 TMR_CEG_CC4EG /*!< A capture/compare event is generated on channel 4 */ +#define TMR_EVENTSOURCE_COM TMR_CEG_COMG /*!< A commutation event is generated */ +#define TMR_EVENTSOURCE_TRIGGER TMR_CEG_TEG /*!< A trigger event is generated */ +#define TMR_EVENTSOURCE_BREAK TMR_CEG_BEG /*!< A break event is generated */ +/** + * @} + */ + +/** @defgroup TMR_Input_Channel_Polarity TMR Input Channel polarity + * @{ + */ +#define TMR_INPUTCHANNELPOLARITY_RISING 0x00000000U /*!< Polarity for TIx source */ +#define TMR_INPUTCHANNELPOLARITY_FALLING TMR_CCEN_CC1POL /*!< Polarity for TIx source */ +#define TMR_INPUTCHANNELPOLARITY_BOTHEDGE (TMR_CCEN_CC1POL | TMR_CCEN_CC1NPOL) /*!< Polarity for TIx source */ +/** + * @} + */ + +/** @defgroup TMR_ETR_Polarity TMR ETR Polarity + * @{ + */ +#define TMR_ETRPOLARITY_INVERTED TMR_SMCTRL_ETPOL /*!< Polarity for ETR source */ +#define TMR_ETRPOLARITY_NONINVERTED 0x00000000U /*!< Polarity for ETR source */ +/** + * @} + */ + +/** @defgroup TMR_ETR_Prescaler TMR ETR Prescaler + * @{ + */ +#define TMR_ETRPRESCALER_DIV1 0x00000000U /*!< No prescaler is used */ +#define TMR_ETRPRESCALER_DIV2 TMR_SMCTRL_ETPCFG_0 /*!< ETR input source is divided by 2 */ +#define TMR_ETRPRESCALER_DIV4 TMR_SMCTRL_ETPCFG_1 /*!< ETR input source is divided by 4 */ +#define TMR_ETRPRESCALER_DIV8 TMR_SMCTRL_ETPCFG /*!< ETR input source is divided by 8 */ +/** + * @} + */ + +/** @defgroup TMR_Counter_Mode TMR Counter Mode + * @{ + */ +#define TMR_COUNTERMODE_UP 0x00000000U /*!< Counter used as up-counter */ +#define TMR_COUNTERMODE_DOWN TMR_CTRL1_CNTDIR /*!< Counter used as down-counter */ +#define TMR_COUNTERMODE_CENTERALIGNED1 TMR_CTRL1_CAMSEL_0 /*!< Center-aligned mode 1 */ +#define TMR_COUNTERMODE_CENTERALIGNED2 TMR_CTRL1_CAMSEL_1 /*!< Center-aligned mode 2 */ +#define TMR_COUNTERMODE_CENTERALIGNED3 TMR_CTRL1_CAMSEL /*!< Center-aligned mode 3 */ +/** + * @} + */ + +/** @defgroup TMR_ClockDivision TMR Clock Division + * @{ + */ +#define TMR_CLOCKDIVISION_DIV1 0x00000000U /*!< Clock division: tDTS=tCK_INT */ +#define TMR_CLOCKDIVISION_DIV2 TMR_CTRL1_CLKDIV_0 /*!< Clock division: tDTS=2*tCK_INT */ +#define TMR_CLOCKDIVISION_DIV4 TMR_CTRL1_CLKDIV_1 /*!< Clock division: tDTS=4*tCK_INT */ +/** + * @} + */ + +/** @defgroup TMR_Output_Compare_State TMR Output Compare State + * @{ + */ +#define TMR_OUTPUTSTATE_DISABLE 0x00000000U /*!< Capture/Compare 1 output disabled */ +#define TMR_OUTPUTSTATE_ENABLE TMR_CCEN_CC1EN /*!< Capture/Compare 1 output enabled */ +/** + * @} + */ + +/** @defgroup TMR_AutoReloadPreload TMR Auto-Reload Preload + * @{ + */ +#define TMR_AUTORELOAD_PRELOAD_DISABLE 0x00000000U /*!< TMRx_ARR register is not buffered */ +#define TMR_AUTORELOAD_PRELOAD_ENABLE TMR_CTRL1_ARPEN /*!< TMRx_ARR register is buffered */ + +/** + * @} + */ + +/** @defgroup TMR_Output_Fast_State TMR Output Fast State + * @{ + */ +#define TMR_OCFAST_DISABLE 0x00000000U /*!< Output Compare fast disable */ +#define TMR_OCFAST_ENABLE TMR_CCM1_OC1FEN /*!< Output Compare fast enable */ +/** + * @} + */ + +/** @defgroup TMR_Output_Compare_N_State TMR Complementary Output Compare State + * @{ + */ +#define TMR_OUTPUTNSTATE_DISABLE 0x00000000U /*!< OCxN is disabled */ +#define TMR_OUTPUTNSTATE_ENABLE TMR_CCEN_CC1NEN /*!< OCxN is enabled */ +/** + * @} + */ + +/** @defgroup TMR_Output_Compare_Polarity TMR Output Compare Polarity + * @{ + */ +#define TMR_OCPOLARITY_HIGH 0x00000000U /*!< Capture/Compare output polarity */ +#define TMR_OCPOLARITY_LOW TMR_CCEN_CC1POL /*!< Capture/Compare output polarity */ +/** + * @} + */ + +/** @defgroup TMR_Output_Compare_N_Polarity TMR Complementary Output Compare Polarity + * @{ + */ +#define TMR_OCNPOLARITY_HIGH 0x00000000U /*!< Capture/Compare complementary output polarity */ +#define TMR_OCNPOLARITY_LOW TMR_CCEN_CC1NPOL /*!< Capture/Compare complementary output polarity */ +/** + * @} + */ + +/** @defgroup TMR_Output_Compare_Idle_State TMR Output Compare Idle State + * @{ + */ +#define TMR_OCIDLESTATE_SET TMR_CTRL2_OC1OIS /*!< Output Idle state: OCx=1 when MOE=0 */ +#define TMR_OCIDLESTATE_RESET 0x00000000U /*!< Output Idle state: OCx=0 when MOE=0 */ +/** + * @} + */ + +/** @defgroup TMR_Output_Compare_N_Idle_State TMR Complementary Output Compare Idle State + * @{ + */ +#define TMR_OCNIDLESTATE_SET TMR_CTRL2_OC1NOIS /*!< Complementary output Idle state: OCxN=1 when MOE=0 */ +#define TMR_OCNIDLESTATE_RESET 0x00000000U /*!< Complementary output Idle state: OCxN=0 when MOE=0 */ +/** + * @} + */ + +/** @defgroup TMR_Input_Capture_Polarity TMR Input Capture Polarity + * @{ + */ +#define TMR_ICPOLARITY_RISING TMR_INPUTCHANNELPOLARITY_RISING /*!< Capture triggered by rising edge on timer input */ +#define TMR_ICPOLARITY_FALLING TMR_INPUTCHANNELPOLARITY_FALLING /*!< Capture triggered by falling edge on timer input */ +#define TMR_ICPOLARITY_BOTHEDGE TMR_INPUTCHANNELPOLARITY_BOTHEDGE /*!< Capture triggered by both rising and falling edges on timer input*/ +/** + * @} + */ + +/** @defgroup TMR_Encoder_Input_Polarity TMR Encoder Input Polarity + * @{ + */ +#define TMR_ENCODERINPUTPOLARITY_RISING TMR_INPUTCHANNELPOLARITY_RISING /*!< Encoder input with rising edge polarity */ +#define TMR_ENCODERINPUTPOLARITY_FALLING TMR_INPUTCHANNELPOLARITY_FALLING /*!< Encoder input with falling edge polarity */ +/** + * @} + */ + +/** @defgroup TMR_Input_Capture_Selection TMR Input Capture Selection + * @{ + */ +#define TMR_ICSELECTION_DIRECTTI TMR_CCM1_CC1SEL_0 /*!< TMR Input 1, 2, 3 or 4 is selected to be connected to IC1, IC2, IC3 or IC4, respectively */ +#define TMR_ICSELECTION_INDIRECTTI TMR_CCM1_CC1SEL_1 /*!< TMR Input 1, 2, 3 or 4 is selected to be connected to IC2, IC1, IC4 or IC3, respectively */ +#define TMR_ICSELECTION_TRC TMR_CCM1_CC1SEL /*!< TMR Input 1, 2, 3 or 4 is selected to be connected to TRC */ +/** + * @} + */ + +/** @defgroup TMR_Input_Capture_Prescaler TMR Input Capture Prescaler + * @{ + */ +#define TMR_ICPSC_DIV1 0x00000000U /*!< Capture performed each time an edge is detected on the capture input */ +#define TMR_ICPSC_DIV2 TMR_CCM1_IC1PSC_0 /*!< Capture performed once every 2 events */ +#define TMR_ICPSC_DIV4 TMR_CCM1_IC1PSC_1 /*!< Capture performed once every 4 events */ +#define TMR_ICPSC_DIV8 TMR_CCM1_IC1PSC /*!< Capture performed once every 8 events */ +/** + * @} + */ + +/** @defgroup TMR_One_Pulse_Mode TMR One Pulse Mode + * @{ + */ +#define TMR_OPMODE_SINGLE TMR_CTRL1_SPMEN /*!< Counter stops counting at the next update event */ +#define TMR_OPMODE_REPETITIVE 0x00000000U /*!< Counter is not stopped at update event */ +/** + * @} + */ + +/** @defgroup TMR_Encoder_Mode TMR Encoder Mode + * @{ + */ +#define TMR_ENCODERMODE_TI1 TMR_SMCTRL_SMFSEL_0 /*!< Quadrature encoder mode 1, x2 mode, counts up/down on TI1FP1 edge depending on TI2FP2 level */ +#define TMR_ENCODERMODE_TI2 TMR_SMCTRL_SMFSEL_1 /*!< Quadrature encoder mode 2, x2 mode, counts up/down on TI2FP2 edge depending on TI1FP1 level. */ +#define TMR_ENCODERMODE_TI12 (TMR_SMCTRL_SMFSEL_1 | TMR_SMCTRL_SMFSEL_0) /*!< Quadrature encoder mode 3, x4 mode, counts up/down on both TI1FP1 and TI2FP2 edges depending on the level of the other input. */ +/** + * @} + */ + +/** @defgroup TMR_Interrupt_definition TMR interrupt Definition + * @{ + */ +#define TMR_IT_UPDATE TMR_DIEN_UIEN /*!< Update interrupt */ +#define TMR_IT_CC1 TMR_DIEN_CC1IEN /*!< Capture/Compare 1 interrupt */ +#define TMR_IT_CC2 TMR_DIEN_CC2IEN /*!< Capture/Compare 2 interrupt */ +#define TMR_IT_CC3 TMR_DIEN_CC3IEN /*!< Capture/Compare 3 interrupt */ +#define TMR_IT_CC4 TMR_DIEN_CC4IEN /*!< Capture/Compare 4 interrupt */ +#define TMR_IT_COM TMR_DIEN_COMIEN /*!< Commutation interrupt */ +#define TMR_IT_TRIGGER TMR_DIEN_TRGIEN /*!< Trigger interrupt */ +#define TMR_IT_BREAK TMR_DIEN_BRKIEN /*!< Break interrupt */ +/** + * @} + */ + +/** @defgroup TMR_Commutation_Source TMR Commutation Source + * @{ + */ +#define TMR_COMMUTATION_TRGI TMR_CTRL2_CCUSEL /*!< When Capture/compare control bits are preloaded, they are updated by setting the COMG bit or when an rising edge occurs on trigger input */ +#define TMR_COMMUTATION_SOFTWARE 0x00000000U /*!< When Capture/compare control bits are preloaded, they are updated by setting the COMG bit */ +/** + * @} + */ + +/** @defgroup TMR_DMA_sources TMR DMA Sources + * @{ + */ +#define TMR_DMA_UPDATE TMR_DIEN_UDIEN /*!< DMA request is triggered by the update event */ +#define TMR_DMA_CC1 TMR_DIEN_CC1DEN /*!< DMA request is triggered by the capture/compare macth 1 event */ +#define TMR_DMA_CC2 TMR_DIEN_CC2DEN /*!< DMA request is triggered by the capture/compare macth 2 event event */ +#define TMR_DMA_CC3 TMR_DIEN_CC3DEN /*!< DMA request is triggered by the capture/compare macth 3 event event */ +#define TMR_DMA_CC4 TMR_DIEN_CC4DEN /*!< DMA request is triggered by the capture/compare macth 4 event event */ +#define TMR_DMA_COM TMR_DIEN_COMDEN /*!< DMA request is triggered by the commutation event */ +#define TMR_DMA_TRIGGER TMR_DIEN_TRGDEN /*!< DMA request is triggered by the trigger event */ +/** + * @} + */ + +/** @defgroup TMR_CC_DMA_Request CCx DMA request selection + * @{ + */ +#define TMR_CCDMAREQUEST_CC 0x00000000U /*!< CCx DMA request sent when capture or compare match event occurs */ +#define TMR_CCDMAREQUEST_UPDATE TMR_CTRL2_CCDSEL /*!< CCx DMA requests sent when update event occurs */ +/** + * @} + */ + +/** @defgroup TMR_Flag_definition TMR Flag Definition + * @{ + */ +#define TMR_FLAG_UPDATE TMR_STS_UIFLG /*!< Update interrupt flag */ +#define TMR_FLAG_CC1 TMR_STS_CC1IFLG /*!< Capture/Compare 1 interrupt flag */ +#define TMR_FLAG_CC2 TMR_STS_CC2IFLG /*!< Capture/Compare 2 interrupt flag */ +#define TMR_FLAG_CC3 TMR_STS_CC3IFLG /*!< Capture/Compare 3 interrupt flag */ +#define TMR_FLAG_CC4 TMR_STS_CC4IFLG /*!< Capture/Compare 4 interrupt flag */ +#define TMR_FLAG_COM TMR_STS_COMIFLG /*!< Commutation interrupt flag */ +#define TMR_FLAG_TRIGGER TMR_STS_TRGIFLG /*!< Trigger interrupt flag */ +#define TMR_FLAG_BREAK TMR_STS_BRKIFLG /*!< Break interrupt flag */ +#define TMR_FLAG_CC1OF TMR_STS_CC1RCFLG /*!< Capture 1 overcapture flag */ +#define TMR_FLAG_CC2OF TMR_STS_CC2RCFLG /*!< Capture 2 overcapture flag */ +#define TMR_FLAG_CC3OF TMR_STS_CC3RCFLG /*!< Capture 3 overcapture flag */ +#define TMR_FLAG_CC4OF TMR_STS_CC4RCFLG /*!< Capture 4 overcapture flag */ +/** + * @} + */ + +/** @defgroup TMR_Channel TMR Channel + * @{ + */ +#define TMR_CHANNEL_1 0x00000000U /*!< Capture/compare channel 1 identifier */ +#define TMR_CHANNEL_2 0x00000004U /*!< Capture/compare channel 2 identifier */ +#define TMR_CHANNEL_3 0x00000008U /*!< Capture/compare channel 3 identifier */ +#define TMR_CHANNEL_4 0x0000000CU /*!< Capture/compare channel 4 identifier */ +#define TMR_CHANNEL_ALL 0x0000003CU /*!< Global Capture/compare channel identifier */ +/** + * @} + */ + +/** @defgroup TMR_Clock_Source TMR Clock Source + * @{ + */ +#define TMR_CLOCKSOURCE_INTERNAL TMR_SMCTRL_ETPCFG_0 /*!< Internal clock source */ +#define TMR_CLOCKSOURCE_ETRMODE1 TMR_TS_ETRF /*!< External clock source mode 1 (ETRF) */ +#define TMR_CLOCKSOURCE_ETRMODE2 TMR_SMCTRL_ETPCFG_1 /*!< External clock source mode 2 */ +#define TMR_CLOCKSOURCE_TI1ED TMR_TS_TI1F_ED /*!< External clock source mode 1 (TTI1FP1 + edge detect.) */ +#define TMR_CLOCKSOURCE_TI1 TMR_TS_TI1FP1 /*!< External clock source mode 1 (TTI1FP1) */ +#define TMR_CLOCKSOURCE_TI2 TMR_TS_TI2FP2 /*!< External clock source mode 1 (TTI2FP2) */ +#define TMR_CLOCKSOURCE_ITR0 TMR_TS_ITR0 /*!< External clock source mode 1 (ITR0) */ +#define TMR_CLOCKSOURCE_ITR1 TMR_TS_ITR1 /*!< External clock source mode 1 (ITR1) */ +#define TMR_CLOCKSOURCE_ITR2 TMR_TS_ITR2 /*!< External clock source mode 1 (ITR2) */ +#define TMR_CLOCKSOURCE_ITR3 TMR_TS_ITR3 /*!< External clock source mode 1 (ITR3) */ +/** + * @} + */ + +/** @defgroup TMR_Clock_Polarity TMR Clock Polarity + * @{ + */ +#define TMR_CLOCKPOLARITY_INVERTED TMR_ETRPOLARITY_INVERTED /*!< Polarity for ETRx clock sources */ +#define TMR_CLOCKPOLARITY_NONINVERTED TMR_ETRPOLARITY_NONINVERTED /*!< Polarity for ETRx clock sources */ +#define TMR_CLOCKPOLARITY_RISING TMR_INPUTCHANNELPOLARITY_RISING /*!< Polarity for TIx clock sources */ +#define TMR_CLOCKPOLARITY_FALLING TMR_INPUTCHANNELPOLARITY_FALLING /*!< Polarity for TIx clock sources */ +#define TMR_CLOCKPOLARITY_BOTHEDGE TMR_INPUTCHANNELPOLARITY_BOTHEDGE /*!< Polarity for TIx clock sources */ +/** + * @} + */ + +/** @defgroup TMR_Clock_Prescaler TMR Clock Prescaler + * @{ + */ +#define TMR_CLOCKPRESCALER_DIV1 TMR_ETRPRESCALER_DIV1 /*!< No prescaler is used */ +#define TMR_CLOCKPRESCALER_DIV2 TMR_ETRPRESCALER_DIV2 /*!< Prescaler for External ETR Clock: Capture performed once every 2 events. */ +#define TMR_CLOCKPRESCALER_DIV4 TMR_ETRPRESCALER_DIV4 /*!< Prescaler for External ETR Clock: Capture performed once every 4 events. */ +#define TMR_CLOCKPRESCALER_DIV8 TMR_ETRPRESCALER_DIV8 /*!< Prescaler for External ETR Clock: Capture performed once every 8 events. */ +/** + * @} + */ + +/** @defgroup TMR_ClearInput_Polarity TMR Clear Input Polarity + * @{ + */ +#define TMR_CLEARINPUTPOLARITY_INVERTED TMR_ETRPOLARITY_INVERTED /*!< Polarity for ETRx pin */ +#define TMR_CLEARINPUTPOLARITY_NONINVERTED TMR_ETRPOLARITY_NONINVERTED /*!< Polarity for ETRx pin */ +/** + * @} + */ + +/** @defgroup TMR_ClearInput_Prescaler TMR Clear Input Prescaler + * @{ + */ +#define TMR_CLEARINPUTPRESCALER_DIV1 TMR_ETRPRESCALER_DIV1 /*!< No prescaler is used */ +#define TMR_CLEARINPUTPRESCALER_DIV2 TMR_ETRPRESCALER_DIV2 /*!< Prescaler for External ETR pin: Capture performed once every 2 events. */ +#define TMR_CLEARINPUTPRESCALER_DIV4 TMR_ETRPRESCALER_DIV4 /*!< Prescaler for External ETR pin: Capture performed once every 4 events. */ +#define TMR_CLEARINPUTPRESCALER_DIV8 TMR_ETRPRESCALER_DIV8 /*!< Prescaler for External ETR pin: Capture performed once every 8 events. */ +/** + * @} + */ + +/** @defgroup TMR_OSSR_Off_State_Selection_for_Run_mode_state TMR OSSR OffState Selection for Run mode state + * @{ + */ +#define TMR_OSSR_ENABLE TMR_BDT_RMOS /*!< When inactive, OC/OCN outputs are enabled (still controlled by the timer) */ +#define TMR_OSSR_DISABLE 0x00000000U /*!< When inactive, OC/OCN outputs are disabled (not controlled any longer by the timer) */ +/** + * @} + */ + +/** @defgroup TMR_OSSI_Off_State_Selection_for_Idle_mode_state TMR OSSI OffState Selection for Idle mode state + * @{ + */ +#define TMR_OSSI_ENABLE TMR_BDT_IMOS /*!< When inactive, OC/OCN outputs are enabled (still controlled by the timer) */ +#define TMR_OSSI_DISABLE 0x00000000U /*!< When inactive, OC/OCN outputs are disabled (not controlled any longer by the timer) */ +/** + * @} + */ +/** @defgroup TMR_Lock_level TMR Lock level + * @{ + */ +#define TMR_LOCKLEVEL_OFF 0x00000000U /*!< LOCK OFF */ +#define TMR_LOCKLEVEL_1 TMR_BDT_LOCKCFG_0 /*!< LOCK Level 1 */ +#define TMR_LOCKLEVEL_2 TMR_BDT_LOCKCFG_1 /*!< LOCK Level 2 */ +#define TMR_LOCKLEVEL_3 TMR_BDT_LOCKCFG /*!< LOCK Level 3 */ +/** + * @} + */ + +/** @defgroup TMR_Break_Input_enable_disable TMR Break Input Enable + * @{ + */ +#define TMR_BREAK_ENABLE TMR_BDT_BRKEN /*!< Break input BRK is enabled */ +#define TMR_BREAK_DISABLE 0x00000000U /*!< Break input BRK is disabled */ +/** + * @} + */ + +/** @defgroup TMR_Break_Polarity TMR Break Input Polarity + * @{ + */ +#define TMR_BREAKPOLARITY_LOW 0x00000000U /*!< Break input BRK is active low */ +#define TMR_BREAKPOLARITY_HIGH TMR_BDT_BRKPOL /*!< Break input BRK is active high */ +/** + * @} + */ + +/** @defgroup TMR_AOE_Bit_Set_Reset TMR Automatic Output Enable + * @{ + */ +#define TMR_AUTOMATICOUTPUT_DISABLE 0x00000000U /*!< MOE can be set only by software */ +#define TMR_AUTOMATICOUTPUT_ENABLE TMR_BDT_AOEN /*!< MOE can be set by software or automatically at the next update event (if none of the break inputs BRK and BRK2 is active) */ +/** + * @} + */ + +/** @defgroup TMR_Master_Mode_Selection TMR Master Mode Selection + * @{ + */ +#define TMR_TRGO_RESET 0x00000000U /*!< TMRx_EGR.UG bit is used as trigger output (TRGO) */ +#define TMR_TRGO_ENABLE TMR_CTRL2_MMSEL_0 /*!< TMRx_CR1.CEN bit is used as trigger output (TRGO) */ +#define TMR_TRGO_UPDATE TMR_CTRL2_MMSEL_1 /*!< Update event is used as trigger output (TRGO) */ +#define TMR_TRGO_OC1 (TMR_CTRL2_MMSEL_1 | TMR_CTRL2_MMSEL_0) /*!< Capture or a compare match 1 is used as trigger output (TRGO) */ +#define TMR_TRGO_OC1REF TMR_CTRL2_MMSEL_2 /*!< OC1REF signal is used as trigger output (TRGO) */ +#define TMR_TRGO_OC2REF (TMR_CTRL2_MMSEL_2 | TMR_CTRL2_MMSEL_0) /*!< OC2REF signal is used as trigger output(TRGO) */ +#define TMR_TRGO_OC3REF (TMR_CTRL2_MMSEL_2 | TMR_CTRL2_MMSEL_1) /*!< OC3REF signal is used as trigger output(TRGO) */ +#define TMR_TRGO_OC4REF (TMR_CTRL2_MMSEL_2 | TMR_CTRL2_MMSEL_1 | TMR_CTRL2_MMSEL_0) /*!< OC4REF signal is used as trigger output(TRGO) */ +/** + * @} + */ + +/** @defgroup TMR_Master_Slave_Mode TMR Master/Slave Mode + * @{ + */ +#define TMR_MASTERSLAVEMODE_ENABLE TMR_SMCTRL_MSMEN /*!< No action */ +#define TMR_MASTERSLAVEMODE_DISABLE 0x00000000U /*!< Master/slave mode is selected */ +/** + * @} + */ + +/** @defgroup TMR_Slave_Mode TMR Slave mode + * @{ + */ +#define TMR_SLAVEMODE_DISABLE 0x00000000U /*!< Slave mode disabled */ +#define TMR_SLAVEMODE_RESET TMR_SMCTRL_SMFSEL_2 /*!< Reset Mode */ +#define TMR_SLAVEMODE_GATED (TMR_SMCTRL_SMFSEL_2 | TMR_SMCTRL_SMFSEL_0) /*!< Gated Mode */ +#define TMR_SLAVEMODE_TRIGGER (TMR_SMCTRL_SMFSEL_2 | TMR_SMCTRL_SMFSEL_1) /*!< Trigger Mode */ +#define TMR_SLAVEMODE_EXTERNAL1 (TMR_SMCTRL_SMFSEL_2 | TMR_SMCTRL_SMFSEL_1 | TMR_SMCTRL_SMFSEL_0) /*!< External Clock Mode 1 */ +/** + * @} + */ + +/** @defgroup TMR_Output_Compare_and_PWM_modes TMR Output Compare and PWM Modes + * @{ + */ +#define TMR_OCMODE_TIMING 0x00000000U /*!< Frozen */ +#define TMR_OCMODE_ACTIVE TMR_CCM1_OC1MOD_0 /*!< Set channel to active level on match */ +#define TMR_OCMODE_INACTIVE TMR_CCM1_OC1MOD_1 /*!< Set channel to inactive level on match */ +#define TMR_OCMODE_TOGGLE (TMR_CCM1_OC1MOD_1 | TMR_CCM1_OC1MOD_0) /*!< Toggle */ +#define TMR_OCMODE_PWM1 (TMR_CCM1_OC1MOD_2 | TMR_CCM1_OC1MOD_1) /*!< PWM mode 1 */ +#define TMR_OCMODE_PWM2 (TMR_CCM1_OC1MOD_2 | TMR_CCM1_OC1MOD_1 | TMR_CCM1_OC1MOD_0) /*!< PWM mode 2 */ +#define TMR_OCMODE_FORCED_ACTIVE (TMR_CCM1_OC1MOD_2 | TMR_CCM1_OC1MOD_0) /*!< Force active level */ +#define TMR_OCMODE_FORCED_INACTIVE TMR_CCM1_OC1MOD_2 /*!< Force inactive level */ +/** + * @} + */ + +/** @defgroup TMR_Trigger_Selection TMR Trigger Selection + * @{ + */ +#define TMR_TS_ITR0 0x00000000U /*!< Internal Trigger 0 (ITR0) */ +#define TMR_TS_ITR1 TMR_SMCTRL_TRGSEL_0 /*!< Internal Trigger 1 (ITR1) */ +#define TMR_TS_ITR2 TMR_SMCTRL_TRGSEL_1 /*!< Internal Trigger 2 (ITR2) */ +#define TMR_TS_ITR3 (TMR_SMCTRL_TRGSEL_0 | TMR_SMCTRL_TRGSEL_1) /*!< Internal Trigger 3 (ITR3) */ +#define TMR_TS_TI1F_ED TMR_SMCTRL_TRGSEL_2 /*!< TI1 Edge Detector (TI1F_ED) */ +#define TMR_TS_TI1FP1 (TMR_SMCTRL_TRGSEL_0 | TMR_SMCTRL_TRGSEL_2) /*!< Filtered Timer Input 1 (TI1FP1) */ +#define TMR_TS_TI2FP2 (TMR_SMCTRL_TRGSEL_1 | TMR_SMCTRL_TRGSEL_2) /*!< Filtered Timer Input 2 (TI2FP2) */ +#define TMR_TS_ETRF (TMR_SMCTRL_TRGSEL_0 | TMR_SMCTRL_TRGSEL_1 | TMR_SMCTRL_TRGSEL_2) /*!< Filtered External Trigger input (ETRF) */ +#define TMR_TS_NONE 0x0000FFFFU /*!< No trigger selected */ +/** + * @} + */ + +/** @defgroup TMR_Trigger_Polarity TMR Trigger Polarity + * @{ + */ +#define TMR_TRIGGERPOLARITY_INVERTED TMR_ETRPOLARITY_INVERTED /*!< Polarity for ETRx trigger sources */ +#define TMR_TRIGGERPOLARITY_NONINVERTED TMR_ETRPOLARITY_NONINVERTED /*!< Polarity for ETRx trigger sources */ +#define TMR_TRIGGERPOLARITY_RISING TMR_INPUTCHANNELPOLARITY_RISING /*!< Polarity for TIxFPx or TI1_ED trigger sources */ +#define TMR_TRIGGERPOLARITY_FALLING TMR_INPUTCHANNELPOLARITY_FALLING /*!< Polarity for TIxFPx or TI1_ED trigger sources */ +#define TMR_TRIGGERPOLARITY_BOTHEDGE TMR_INPUTCHANNELPOLARITY_BOTHEDGE /*!< Polarity for TIxFPx or TI1_ED trigger sources */ +/** + * @} + */ + +/** @defgroup TMR_Trigger_Prescaler TMR Trigger Prescaler + * @{ + */ +#define TMR_TRIGGERPRESCALER_DIV1 TMR_ETRPRESCALER_DIV1 /*!< No prescaler is used */ +#define TMR_TRIGGERPRESCALER_DIV2 TMR_ETRPRESCALER_DIV2 /*!< Prescaler for External ETR Trigger: Capture performed once every 2 events. */ +#define TMR_TRIGGERPRESCALER_DIV4 TMR_ETRPRESCALER_DIV4 /*!< Prescaler for External ETR Trigger: Capture performed once every 4 events. */ +#define TMR_TRIGGERPRESCALER_DIV8 TMR_ETRPRESCALER_DIV8 /*!< Prescaler for External ETR Trigger: Capture performed once every 8 events. */ +/** + * @} + */ + +/** @defgroup TMR_TI1_Selection TMR TI1 Input Selection + * @{ + */ +#define TMR_TI1SELECTION_CH1 0x00000000U /*!< The TMRx_CH1 pin is connected to TI1 input */ +#define TMR_TI1SELECTION_XORCOMBINATION TMR_CTRL2_TI1SEL /*!< The TMRx_CH1, CH2 and CH3 pins are connected to the TI1 input (XOR combination) */ +/** + * @} + */ + +/** @defgroup TMR_DMA_Burst_Length TMR DMA Burst Length + * @{ + */ +#define TMR_DMABURSTLENGTH_1TRANSFER 0x00000000U /*!< The transfer is done to 1 register starting from TMRx_CR1 + TMRx_DCR.DBA */ +#define TMR_DMABURSTLENGTH_2TRANSFERS 0x00000100U /*!< The transfer is done to 2 registers starting from TMRx_CR1 + TMRx_DCR.DBA */ +#define TMR_DMABURSTLENGTH_3TRANSFERS 0x00000200U /*!< The transfer is done to 3 registers starting from TMRx_CR1 + TMRx_DCR.DBA */ +#define TMR_DMABURSTLENGTH_4TRANSFERS 0x00000300U /*!< The transfer is done to 4 registers starting from TMRx_CR1 + TMRx_DCR.DBA */ +#define TMR_DMABURSTLENGTH_5TRANSFERS 0x00000400U /*!< The transfer is done to 5 registers starting from TMRx_CR1 + TMRx_DCR.DBA */ +#define TMR_DMABURSTLENGTH_6TRANSFERS 0x00000500U /*!< The transfer is done to 6 registers starting from TMRx_CR1 + TMRx_DCR.DBA */ +#define TMR_DMABURSTLENGTH_7TRANSFERS 0x00000600U /*!< The transfer is done to 7 registers starting from TMRx_CR1 + TMRx_DCR.DBA */ +#define TMR_DMABURSTLENGTH_8TRANSFERS 0x00000700U /*!< The transfer is done to 8 registers starting from TMRx_CR1 + TMRx_DCR.DBA */ +#define TMR_DMABURSTLENGTH_9TRANSFERS 0x00000800U /*!< The transfer is done to 9 registers starting from TMRx_CR1 + TMRx_DCR.DBA */ +#define TMR_DMABURSTLENGTH_10TRANSFERS 0x00000900U /*!< The transfer is done to 10 registers starting from TMRx_CR1 + TMRx_DCR.DBA */ +#define TMR_DMABURSTLENGTH_11TRANSFERS 0x00000A00U /*!< The transfer is done to 11 registers starting from TMRx_CR1 + TMRx_DCR.DBA */ +#define TMR_DMABURSTLENGTH_12TRANSFERS 0x00000B00U /*!< The transfer is done to 12 registers starting from TMRx_CR1 + TMRx_DCR.DBA */ +#define TMR_DMABURSTLENGTH_13TRANSFERS 0x00000C00U /*!< The transfer is done to 13 registers starting from TMRx_CR1 + TMRx_DCR.DBA */ +#define TMR_DMABURSTLENGTH_14TRANSFERS 0x00000D00U /*!< The transfer is done to 14 registers starting from TMRx_CR1 + TMRx_DCR.DBA */ +#define TMR_DMABURSTLENGTH_15TRANSFERS 0x00000E00U /*!< The transfer is done to 15 registers starting from TMRx_CR1 + TMRx_DCR.DBA */ +#define TMR_DMABURSTLENGTH_16TRANSFERS 0x00000F00U /*!< The transfer is done to 16 registers starting from TMRx_CR1 + TMRx_DCR.DBA */ +#define TMR_DMABURSTLENGTH_17TRANSFERS 0x00001000U /*!< The transfer is done to 17 registers starting from TMRx_CR1 + TMRx_DCR.DBA */ +#define TMR_DMABURSTLENGTH_18TRANSFERS 0x00001100U /*!< The transfer is done to 18 registers starting from TMRx_CR1 + TMRx_DCR.DBA */ +/** + * @} + */ + +/** @defgroup DMA_Handle_index TMR DMA Handle Index + * @{ + */ +#define TMR_DMA_ID_UPDATE ((uint16_t) 0x0000) /*!< Index of the DMA handle used for Update DMA requests */ +#define TMR_DMA_ID_CC1 ((uint16_t) 0x0001) /*!< Index of the DMA handle used for Capture/Compare 1 DMA requests */ +#define TMR_DMA_ID_CC2 ((uint16_t) 0x0002) /*!< Index of the DMA handle used for Capture/Compare 2 DMA requests */ +#define TMR_DMA_ID_CC3 ((uint16_t) 0x0003) /*!< Index of the DMA handle used for Capture/Compare 3 DMA requests */ +#define TMR_DMA_ID_CC4 ((uint16_t) 0x0004) /*!< Index of the DMA handle used for Capture/Compare 4 DMA requests */ +#define TMR_DMA_ID_COMMUTATION ((uint16_t) 0x0005) /*!< Index of the DMA handle used for Commutation DMA requests */ +#define TMR_DMA_ID_TRIGGER ((uint16_t) 0x0006) /*!< Index of the DMA handle used for Trigger DMA requests */ +/** + * @} + */ + +/** @defgroup Channel_CC_State TMR Capture/Compare Channel State + * @{ + */ +#define TMR_CCx_ENABLE 0x00000001U /*!< Input or output channel is enabled */ +#define TMR_CCx_DISABLE 0x00000000U /*!< Input or output channel is disabled */ +#define TMR_CCxN_ENABLE 0x00000004U /*!< Complementary output channel is enabled */ +#define TMR_CCxN_DISABLE 0x00000000U /*!< Complementary output channel is enabled */ +/** + * @} + */ + +/** + * @} + */ +/* End of exported constants -------------------------------------------------*/ + +/* Exported macros -----------------------------------------------------------*/ +/** @defgroup TMR_Exported_Macros TMR Exported Macros + * @{ + */ + +/** @brief Reset TMR handle state. + * @param __HANDLE__ TMR handle. + * @retval None + */ +#if (USE_DAL_TMR_REGISTER_CALLBACKS == 1) +#define __DAL_TMR_RESET_HANDLE_STATE(__HANDLE__) do { \ + (__HANDLE__)->State = DAL_TMR_STATE_RESET; \ + (__HANDLE__)->ChannelState[0] = DAL_TMR_CHANNEL_STATE_RESET; \ + (__HANDLE__)->ChannelState[1] = DAL_TMR_CHANNEL_STATE_RESET; \ + (__HANDLE__)->ChannelState[2] = DAL_TMR_CHANNEL_STATE_RESET; \ + (__HANDLE__)->ChannelState[3] = DAL_TMR_CHANNEL_STATE_RESET; \ + (__HANDLE__)->ChannelNState[0] = DAL_TMR_CHANNEL_STATE_RESET; \ + (__HANDLE__)->ChannelNState[1] = DAL_TMR_CHANNEL_STATE_RESET; \ + (__HANDLE__)->ChannelNState[2] = DAL_TMR_CHANNEL_STATE_RESET; \ + (__HANDLE__)->ChannelNState[3] = DAL_TMR_CHANNEL_STATE_RESET; \ + (__HANDLE__)->DMABurstState = DAL_DMA_BURST_STATE_RESET; \ + (__HANDLE__)->Base_MspInitCallback = NULL; \ + (__HANDLE__)->Base_MspDeInitCallback = NULL; \ + (__HANDLE__)->IC_MspInitCallback = NULL; \ + (__HANDLE__)->IC_MspDeInitCallback = NULL; \ + (__HANDLE__)->OC_MspInitCallback = NULL; \ + (__HANDLE__)->OC_MspDeInitCallback = NULL; \ + (__HANDLE__)->PWM_MspInitCallback = NULL; \ + (__HANDLE__)->PWM_MspDeInitCallback = NULL; \ + (__HANDLE__)->OnePulse_MspInitCallback = NULL; \ + (__HANDLE__)->OnePulse_MspDeInitCallback = NULL; \ + (__HANDLE__)->Encoder_MspInitCallback = NULL; \ + (__HANDLE__)->Encoder_MspDeInitCallback = NULL; \ + (__HANDLE__)->HallSensor_MspInitCallback = NULL; \ + (__HANDLE__)->HallSensor_MspDeInitCallback = NULL; \ + } while(0) +#else +#define __DAL_TMR_RESET_HANDLE_STATE(__HANDLE__) do { \ + (__HANDLE__)->State = DAL_TMR_STATE_RESET; \ + (__HANDLE__)->ChannelState[0] = DAL_TMR_CHANNEL_STATE_RESET; \ + (__HANDLE__)->ChannelState[1] = DAL_TMR_CHANNEL_STATE_RESET; \ + (__HANDLE__)->ChannelState[2] = DAL_TMR_CHANNEL_STATE_RESET; \ + (__HANDLE__)->ChannelState[3] = DAL_TMR_CHANNEL_STATE_RESET; \ + (__HANDLE__)->ChannelNState[0] = DAL_TMR_CHANNEL_STATE_RESET; \ + (__HANDLE__)->ChannelNState[1] = DAL_TMR_CHANNEL_STATE_RESET; \ + (__HANDLE__)->ChannelNState[2] = DAL_TMR_CHANNEL_STATE_RESET; \ + (__HANDLE__)->ChannelNState[3] = DAL_TMR_CHANNEL_STATE_RESET; \ + (__HANDLE__)->DMABurstState = DAL_DMA_BURST_STATE_RESET; \ + } while(0) +#endif /* USE_DAL_TMR_REGISTER_CALLBACKS */ + +/** + * @brief Enable the TMR peripheral. + * @param __HANDLE__ TMR handle + * @retval None + */ +#define __DAL_TMR_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CTRL1|=(TMR_CTRL1_CNTEN)) + +/** + * @brief Enable the TMR main Output. + * @param __HANDLE__ TMR handle + * @retval None + */ +#define __DAL_TMR_MOE_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->BDT|=(TMR_BDT_MOEN)) + +/** + * @brief Disable the TMR peripheral. + * @param __HANDLE__ TMR handle + * @retval None + */ +#define __DAL_TMR_DISABLE(__HANDLE__) \ + do { \ + if (((__HANDLE__)->Instance->CCEN & TMR_CCEN_CCxE_MASK) == 0UL) \ + { \ + if(((__HANDLE__)->Instance->CCEN & TMR_CCEN_CCxNE_MASK) == 0UL) \ + { \ + (__HANDLE__)->Instance->CTRL1 &= ~(TMR_CTRL1_CNTEN); \ + } \ + } \ + } while(0) + +/** + * @brief Disable the TMR main Output. + * @param __HANDLE__ TMR handle + * @retval None + * @note The Main Output Enable of a timer instance is disabled only if all the CCx and CCxN channels have been + * disabled + */ +#define __DAL_TMR_MOE_DISABLE(__HANDLE__) \ + do { \ + if (((__HANDLE__)->Instance->CCEN & TMR_CCEN_CCxE_MASK) == 0UL) \ + { \ + if(((__HANDLE__)->Instance->CCEN & TMR_CCEN_CCxNE_MASK) == 0UL) \ + { \ + (__HANDLE__)->Instance->BDT &= ~(TMR_BDT_MOEN); \ + } \ + } \ + } while(0) + +/** + * @brief Disable the TMR main Output. + * @param __HANDLE__ TMR handle + * @retval None + * @note The Main Output Enable of a timer instance is disabled unconditionally + */ +#define __DAL_TMR_MOE_DISABLE_UNCONDITIONALLY(__HANDLE__) (__HANDLE__)->Instance->BDT &= ~(TMR_BDT_MOEN) + +/** @brief Enable the specified TMR interrupt. + * @param __HANDLE__ specifies the TMR Handle. + * @param __INTERRUPT__ specifies the TMR interrupt source to enable. + * This parameter can be one of the following values: + * @arg TMR_IT_UPDATE: Update interrupt + * @arg TMR_IT_CC1: Capture/Compare 1 interrupt + * @arg TMR_IT_CC2: Capture/Compare 2 interrupt + * @arg TMR_IT_CC3: Capture/Compare 3 interrupt + * @arg TMR_IT_CC4: Capture/Compare 4 interrupt + * @arg TMR_IT_COM: Commutation interrupt + * @arg TMR_IT_TRIGGER: Trigger interrupt + * @arg TMR_IT_BREAK: Break interrupt + * @retval None + */ +#define __DAL_TMR_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->DIEN |= (__INTERRUPT__)) + +/** @brief Disable the specified TMR interrupt. + * @param __HANDLE__ specifies the TMR Handle. + * @param __INTERRUPT__ specifies the TMR interrupt source to disable. + * This parameter can be one of the following values: + * @arg TMR_IT_UPDATE: Update interrupt + * @arg TMR_IT_CC1: Capture/Compare 1 interrupt + * @arg TMR_IT_CC2: Capture/Compare 2 interrupt + * @arg TMR_IT_CC3: Capture/Compare 3 interrupt + * @arg TMR_IT_CC4: Capture/Compare 4 interrupt + * @arg TMR_IT_COM: Commutation interrupt + * @arg TMR_IT_TRIGGER: Trigger interrupt + * @arg TMR_IT_BREAK: Break interrupt + * @retval None + */ +#define __DAL_TMR_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->DIEN &= ~(__INTERRUPT__)) + +/** @brief Enable the specified DMA request. + * @param __HANDLE__ specifies the TMR Handle. + * @param __DMA__ specifies the TMR DMA request to enable. + * This parameter can be one of the following values: + * @arg TMR_DMA_UPDATE: Update DMA request + * @arg TMR_DMA_CC1: Capture/Compare 1 DMA request + * @arg TMR_DMA_CC2: Capture/Compare 2 DMA request + * @arg TMR_DMA_CC3: Capture/Compare 3 DMA request + * @arg TMR_DMA_CC4: Capture/Compare 4 DMA request + * @arg TMR_DMA_COM: Commutation DMA request + * @arg TMR_DMA_TRIGGER: Trigger DMA request + * @retval None + */ +#define __DAL_TMR_ENABLE_DMA(__HANDLE__, __DMA__) ((__HANDLE__)->Instance->DIEN |= (__DMA__)) + +/** @brief Disable the specified DMA request. + * @param __HANDLE__ specifies the TMR Handle. + * @param __DMA__ specifies the TMR DMA request to disable. + * This parameter can be one of the following values: + * @arg TMR_DMA_UPDATE: Update DMA request + * @arg TMR_DMA_CC1: Capture/Compare 1 DMA request + * @arg TMR_DMA_CC2: Capture/Compare 2 DMA request + * @arg TMR_DMA_CC3: Capture/Compare 3 DMA request + * @arg TMR_DMA_CC4: Capture/Compare 4 DMA request + * @arg TMR_DMA_COM: Commutation DMA request + * @arg TMR_DMA_TRIGGER: Trigger DMA request + * @retval None + */ +#define __DAL_TMR_DISABLE_DMA(__HANDLE__, __DMA__) ((__HANDLE__)->Instance->DIEN &= ~(__DMA__)) + +/** @brief Check whether the specified TMR interrupt flag is set or not. + * @param __HANDLE__ specifies the TMR Handle. + * @param __FLAG__ specifies the TMR interrupt flag to check. + * This parameter can be one of the following values: + * @arg TMR_FLAG_UPDATE: Update interrupt flag + * @arg TMR_FLAG_CC1: Capture/Compare 1 interrupt flag + * @arg TMR_FLAG_CC2: Capture/Compare 2 interrupt flag + * @arg TMR_FLAG_CC3: Capture/Compare 3 interrupt flag + * @arg TMR_FLAG_CC4: Capture/Compare 4 interrupt flag + * @arg TMR_FLAG_COM: Commutation interrupt flag + * @arg TMR_FLAG_TRIGGER: Trigger interrupt flag + * @arg TMR_FLAG_BREAK: Break interrupt flag + * @arg TMR_FLAG_CC1OF: Capture/Compare 1 overcapture flag + * @arg TMR_FLAG_CC2OF: Capture/Compare 2 overcapture flag + * @arg TMR_FLAG_CC3OF: Capture/Compare 3 overcapture flag + * @arg TMR_FLAG_CC4OF: Capture/Compare 4 overcapture flag + * @retval The new state of __FLAG__ (TRUE or FALSE). + */ +#define __DAL_TMR_GET_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->STS &(__FLAG__)) == (__FLAG__)) + +/** @brief Clear the specified TMR interrupt flag. + * @param __HANDLE__ specifies the TMR Handle. + * @param __FLAG__ specifies the TMR interrupt flag to clear. + * This parameter can be one of the following values: + * @arg TMR_FLAG_UPDATE: Update interrupt flag + * @arg TMR_FLAG_CC1: Capture/Compare 1 interrupt flag + * @arg TMR_FLAG_CC2: Capture/Compare 2 interrupt flag + * @arg TMR_FLAG_CC3: Capture/Compare 3 interrupt flag + * @arg TMR_FLAG_CC4: Capture/Compare 4 interrupt flag + * @arg TMR_FLAG_COM: Commutation interrupt flag + * @arg TMR_FLAG_TRIGGER: Trigger interrupt flag + * @arg TMR_FLAG_BREAK: Break interrupt flag + * @arg TMR_FLAG_CC1OF: Capture/Compare 1 overcapture flag + * @arg TMR_FLAG_CC2OF: Capture/Compare 2 overcapture flag + * @arg TMR_FLAG_CC3OF: Capture/Compare 3 overcapture flag + * @arg TMR_FLAG_CC4OF: Capture/Compare 4 overcapture flag + * @retval The new state of __FLAG__ (TRUE or FALSE). + */ +#define __DAL_TMR_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->STS = ~(__FLAG__)) + +/** + * @brief Check whether the specified TMR interrupt source is enabled or not. + * @param __HANDLE__ TMR handle + * @param __INTERRUPT__ specifies the TMR interrupt source to check. + * This parameter can be one of the following values: + * @arg TMR_IT_UPDATE: Update interrupt + * @arg TMR_IT_CC1: Capture/Compare 1 interrupt + * @arg TMR_IT_CC2: Capture/Compare 2 interrupt + * @arg TMR_IT_CC3: Capture/Compare 3 interrupt + * @arg TMR_IT_CC4: Capture/Compare 4 interrupt + * @arg TMR_IT_COM: Commutation interrupt + * @arg TMR_IT_TRIGGER: Trigger interrupt + * @arg TMR_IT_BREAK: Break interrupt + * @retval The state of TMR_IT (SET or RESET). + */ +#define __DAL_TMR_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) ((((__HANDLE__)->Instance->DIEN & (__INTERRUPT__)) \ + == (__INTERRUPT__)) ? SET : RESET) + +/** @brief Clear the TMR interrupt pending bits. + * @param __HANDLE__ TMR handle + * @param __INTERRUPT__ specifies the interrupt pending bit to clear. + * This parameter can be one of the following values: + * @arg TMR_IT_UPDATE: Update interrupt + * @arg TMR_IT_CC1: Capture/Compare 1 interrupt + * @arg TMR_IT_CC2: Capture/Compare 2 interrupt + * @arg TMR_IT_CC3: Capture/Compare 3 interrupt + * @arg TMR_IT_CC4: Capture/Compare 4 interrupt + * @arg TMR_IT_COM: Commutation interrupt + * @arg TMR_IT_TRIGGER: Trigger interrupt + * @arg TMR_IT_BREAK: Break interrupt + * @retval None + */ +#define __DAL_TMR_CLEAR_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->STS = ~(__INTERRUPT__)) + +/** + * @brief Indicates whether or not the TMR Counter is used as downcounter. + * @param __HANDLE__ TMR handle. + * @retval False (Counter used as upcounter) or True (Counter used as downcounter) + * @note This macro is particularly useful to get the counting mode when the timer operates in Center-aligned mode + * or Encoder mode. + */ +#define __DAL_TMR_IS_TMR_COUNTING_DOWN(__HANDLE__) (((__HANDLE__)->Instance->CTRL1 &(TMR_CTRL1_CNTDIR)) == (TMR_CTRL1_CNTDIR)) + +/** + * @brief Set the TMR Prescaler on runtime. + * @param __HANDLE__ TMR handle. + * @param __PRESC__ specifies the Prescaler new value. + * @retval None + */ +#define __DAL_TMR_SET_PRESCALER(__HANDLE__, __PRESC__) ((__HANDLE__)->Instance->PSC = (__PRESC__)) + +/** + * @brief Set the TMR Counter Register value on runtime. + * @param __HANDLE__ TMR handle. + * @param __COUNTER__ specifies the Counter register new value. + * @retval None + */ +#define __DAL_TMR_SET_COUNTER(__HANDLE__, __COUNTER__) ((__HANDLE__)->Instance->CNT = (__COUNTER__)) + +/** + * @brief Get the TMR Counter Register value on runtime. + * @param __HANDLE__ TMR handle. + * @retval 16-bit or 32-bit value of the timer counter register (TMRx_CNT) + */ +#define __DAL_TMR_GET_COUNTER(__HANDLE__) ((__HANDLE__)->Instance->CNT) + +/** + * @brief Set the TMR Autoreload Register value on runtime without calling another time any Init function. + * @param __HANDLE__ TMR handle. + * @param __AUTORELOAD__ specifies the Counter register new value. + * @retval None + */ +#define __DAL_TMR_SET_AUTORELOAD(__HANDLE__, __AUTORELOAD__) \ + do{ \ + (__HANDLE__)->Instance->AUTORLD = (__AUTORELOAD__); \ + (__HANDLE__)->Init.Period = (__AUTORELOAD__); \ + } while(0) + +/** + * @brief Get the TMR Autoreload Register value on runtime. + * @param __HANDLE__ TMR handle. + * @retval 16-bit or 32-bit value of the timer auto-reload register(TMRx_AUTORLD) + */ +#define __DAL_TMR_GET_AUTORELOAD(__HANDLE__) ((__HANDLE__)->Instance->AUTORLD) + +/** + * @brief Set the TMR Clock Division value on runtime without calling another time any Init function. + * @param __HANDLE__ TMR handle. + * @param __CKD__ specifies the clock division value. + * This parameter can be one of the following value: + * @arg TMR_CLOCKDIVISION_DIV1: tDTS=tCK_INT + * @arg TMR_CLOCKDIVISION_DIV2: tDTS=2*tCK_INT + * @arg TMR_CLOCKDIVISION_DIV4: tDTS=4*tCK_INT + * @retval None + */ +#define __DAL_TMR_SET_CLOCKDIVISION(__HANDLE__, __CKD__) \ + do{ \ + (__HANDLE__)->Instance->CTRL1 &= (~TMR_CTRL1_CLKDIV); \ + (__HANDLE__)->Instance->CTRL1 |= (__CKD__); \ + (__HANDLE__)->Init.ClockDivision = (__CKD__); \ + } while(0) + +/** + * @brief Get the TMR Clock Division value on runtime. + * @param __HANDLE__ TMR handle. + * @retval The clock division can be one of the following values: + * @arg TMR_CLOCKDIVISION_DIV1: tDTS=tCK_INT + * @arg TMR_CLOCKDIVISION_DIV2: tDTS=2*tCK_INT + * @arg TMR_CLOCKDIVISION_DIV4: tDTS=4*tCK_INT + */ +#define __DAL_TMR_GET_CLOCKDIVISION(__HANDLE__) ((__HANDLE__)->Instance->CTRL1 & TMR_CTRL1_CLKDIV) + +/** + * @brief Set the TMR Input Capture prescaler on runtime without calling another time DAL_TMR_IC_ConfigChannel() + * function. + * @param __HANDLE__ TMR handle. + * @param __CHANNEL__ TMR Channels to be configured. + * This parameter can be one of the following values: + * @arg TMR_CHANNEL_1: TMR Channel 1 selected + * @arg TMR_CHANNEL_2: TMR Channel 2 selected + * @arg TMR_CHANNEL_3: TMR Channel 3 selected + * @arg TMR_CHANNEL_4: TMR Channel 4 selected + * @param __ICPSC__ specifies the Input Capture4 prescaler new value. + * This parameter can be one of the following values: + * @arg TMR_ICPSC_DIV1: no prescaler + * @arg TMR_ICPSC_DIV2: capture is done once every 2 events + * @arg TMR_ICPSC_DIV4: capture is done once every 4 events + * @arg TMR_ICPSC_DIV8: capture is done once every 8 events + * @retval None + */ +#define __DAL_TMR_SET_ICPRESCALER(__HANDLE__, __CHANNEL__, __ICPSC__) \ + do{ \ + TMR_RESET_ICPRESCALERVALUE((__HANDLE__), (__CHANNEL__)); \ + TMR_SET_ICPRESCALERVALUE((__HANDLE__), (__CHANNEL__), (__ICPSC__)); \ + } while(0) + +/** + * @brief Get the TMR Input Capture prescaler on runtime. + * @param __HANDLE__ TMR handle. + * @param __CHANNEL__ TMR Channels to be configured. + * This parameter can be one of the following values: + * @arg TMR_CHANNEL_1: get input capture 1 prescaler value + * @arg TMR_CHANNEL_2: get input capture 2 prescaler value + * @arg TMR_CHANNEL_3: get input capture 3 prescaler value + * @arg TMR_CHANNEL_4: get input capture 4 prescaler value + * @retval The input capture prescaler can be one of the following values: + * @arg TMR_ICPSC_DIV1: no prescaler + * @arg TMR_ICPSC_DIV2: capture is done once every 2 events + * @arg TMR_ICPSC_DIV4: capture is done once every 4 events + * @arg TMR_ICPSC_DIV8: capture is done once every 8 events + */ +#define __DAL_TMR_GET_ICPRESCALER(__HANDLE__, __CHANNEL__) \ + (((__CHANNEL__) == TMR_CHANNEL_1) ? ((__HANDLE__)->Instance->CCM1 & TMR_CCM1_IC1PSC) :\ + ((__CHANNEL__) == TMR_CHANNEL_2) ? (((__HANDLE__)->Instance->CCM1 & TMR_CCM1_IC2PSC) >> 8U) :\ + ((__CHANNEL__) == TMR_CHANNEL_3) ? ((__HANDLE__)->Instance->CCM2 & TMR_CCM2_IC3PSC) :\ + (((__HANDLE__)->Instance->CCM2 & TMR_CCM2_IC4PSC)) >> 8U) + +/** + * @brief Set the TMR Capture Compare Register value on runtime without calling another time ConfigChannel function. + * @param __HANDLE__ TMR handle. + * @param __CHANNEL__ TMR Channels to be configured. + * This parameter can be one of the following values: + * @arg TMR_CHANNEL_1: TMR Channel 1 selected + * @arg TMR_CHANNEL_2: TMR Channel 2 selected + * @arg TMR_CHANNEL_3: TMR Channel 3 selected + * @arg TMR_CHANNEL_4: TMR Channel 4 selected + * @param __COMPARE__ specifies the Capture Compare register new value. + * @retval None + */ +#define __DAL_TMR_SET_COMPARE(__HANDLE__, __CHANNEL__, __COMPARE__) \ + (((__CHANNEL__) == TMR_CHANNEL_1) ? ((__HANDLE__)->Instance->CC1 = (__COMPARE__)) :\ + ((__CHANNEL__) == TMR_CHANNEL_2) ? ((__HANDLE__)->Instance->CC2 = (__COMPARE__)) :\ + ((__CHANNEL__) == TMR_CHANNEL_3) ? ((__HANDLE__)->Instance->CC3 = (__COMPARE__)) :\ + ((__HANDLE__)->Instance->CC4 = (__COMPARE__))) + +/** + * @brief Get the TMR Capture Compare Register value on runtime. + * @param __HANDLE__ TMR handle. + * @param __CHANNEL__ TMR Channel associated with the capture compare register + * This parameter can be one of the following values: + * @arg TMR_CHANNEL_1: get capture/compare 1 register value + * @arg TMR_CHANNEL_2: get capture/compare 2 register value + * @arg TMR_CHANNEL_3: get capture/compare 3 register value + * @arg TMR_CHANNEL_4: get capture/compare 4 register value + * @retval 16-bit or 32-bit value of the capture/compare register (TMRx_CCRy) + */ +#define __DAL_TMR_GET_COMPARE(__HANDLE__, __CHANNEL__) \ + (((__CHANNEL__) == TMR_CHANNEL_1) ? ((__HANDLE__)->Instance->CC1) :\ + ((__CHANNEL__) == TMR_CHANNEL_2) ? ((__HANDLE__)->Instance->CC2) :\ + ((__CHANNEL__) == TMR_CHANNEL_3) ? ((__HANDLE__)->Instance->CC3) :\ + ((__HANDLE__)->Instance->CC4)) + +/** + * @brief Set the TMR Output compare preload. + * @param __HANDLE__ TMR handle. + * @param __CHANNEL__ TMR Channels to be configured. + * This parameter can be one of the following values: + * @arg TMR_CHANNEL_1: TMR Channel 1 selected + * @arg TMR_CHANNEL_2: TMR Channel 2 selected + * @arg TMR_CHANNEL_3: TMR Channel 3 selected + * @arg TMR_CHANNEL_4: TMR Channel 4 selected + * @retval None + */ +#define __DAL_TMR_ENABLE_OCxPRELOAD(__HANDLE__, __CHANNEL__) \ + (((__CHANNEL__) == TMR_CHANNEL_1) ? ((__HANDLE__)->Instance->CCM1 |= TMR_CCM1_OC1PEN) :\ + ((__CHANNEL__) == TMR_CHANNEL_2) ? ((__HANDLE__)->Instance->CCM1 |= TMR_CCM1_OC2PEN) :\ + ((__CHANNEL__) == TMR_CHANNEL_3) ? ((__HANDLE__)->Instance->CCM2 |= TMR_CCM2_OC3PEN) :\ + ((__HANDLE__)->Instance->CCM2 |= TMR_CCM2_OC4PEN)) + +/** + * @brief Reset the TMR Output compare preload. + * @param __HANDLE__ TMR handle. + * @param __CHANNEL__ TMR Channels to be configured. + * This parameter can be one of the following values: + * @arg TMR_CHANNEL_1: TMR Channel 1 selected + * @arg TMR_CHANNEL_2: TMR Channel 2 selected + * @arg TMR_CHANNEL_3: TMR Channel 3 selected + * @arg TMR_CHANNEL_4: TMR Channel 4 selected + * @retval None + */ +#define __DAL_TMR_DISABLE_OCxPRELOAD(__HANDLE__, __CHANNEL__) \ + (((__CHANNEL__) == TMR_CHANNEL_1) ? ((__HANDLE__)->Instance->CCM1 &= ~TMR_CCM1_OC1PEN) :\ + ((__CHANNEL__) == TMR_CHANNEL_2) ? ((__HANDLE__)->Instance->CCM1 &= ~TMR_CCM1_OC2PEN) :\ + ((__CHANNEL__) == TMR_CHANNEL_3) ? ((__HANDLE__)->Instance->CCM2 &= ~TMR_CCM2_OC3PEN) :\ + ((__HANDLE__)->Instance->CCM2 &= ~TMR_CCM2_OC4PEN)) + +/** + * @brief Enable fast mode for a given channel. + * @param __HANDLE__ TMR handle. + * @param __CHANNEL__ TMR Channels to be configured. + * This parameter can be one of the following values: + * @arg TMR_CHANNEL_1: TMR Channel 1 selected + * @arg TMR_CHANNEL_2: TMR Channel 2 selected + * @arg TMR_CHANNEL_3: TMR Channel 3 selected + * @arg TMR_CHANNEL_4: TMR Channel 4 selected + * @note When fast mode is enabled an active edge on the trigger input acts + * like a compare match on CCx output. Delay to sample the trigger + * input and to activate CCx output is reduced to 3 clock cycles. + * @note Fast mode acts only if the channel is configured in PWM1 or PWM2 mode. + * @retval None + */ +#define __DAL_TMR_ENABLE_OCxFAST(__HANDLE__, __CHANNEL__) \ + (((__CHANNEL__) == TMR_CHANNEL_1) ? ((__HANDLE__)->Instance->CCM1 |= TMR_CCM1_OC1FEN) :\ + ((__CHANNEL__) == TMR_CHANNEL_2) ? ((__HANDLE__)->Instance->CCM1 |= TMR_CCM1_OC2FEN) :\ + ((__CHANNEL__) == TMR_CHANNEL_3) ? ((__HANDLE__)->Instance->CCM2 |= TMR_CCM2_OC3FEN) :\ + ((__HANDLE__)->Instance->CCM2 |= TMR_CCM2_OC4FEN)) + +/** + * @brief Disable fast mode for a given channel. + * @param __HANDLE__ TMR handle. + * @param __CHANNEL__ TMR Channels to be configured. + * This parameter can be one of the following values: + * @arg TMR_CHANNEL_1: TMR Channel 1 selected + * @arg TMR_CHANNEL_2: TMR Channel 2 selected + * @arg TMR_CHANNEL_3: TMR Channel 3 selected + * @arg TMR_CHANNEL_4: TMR Channel 4 selected + * @note When fast mode is disabled CCx output behaves normally depending + * on counter and CCx values even when the trigger is ON. The minimum + * delay to activate CCx output when an active edge occurs on the + * trigger input is 5 clock cycles. + * @retval None + */ +#define __DAL_TMR_DISABLE_OCxFAST(__HANDLE__, __CHANNEL__) \ + (((__CHANNEL__) == TMR_CHANNEL_1) ? ((__HANDLE__)->Instance->CCM1 &= ~TMR_CCM1_OC1FEN) :\ + ((__CHANNEL__) == TMR_CHANNEL_2) ? ((__HANDLE__)->Instance->CCM1 &= ~TMR_CCM1_OC2FEN) :\ + ((__CHANNEL__) == TMR_CHANNEL_3) ? ((__HANDLE__)->Instance->CCM2 &= ~TMR_CCM2_OC3FEN) :\ + ((__HANDLE__)->Instance->CCM2 &= ~TMR_CCM2_OC4FEN)) + +/** + * @brief Set the Update Request Source (URS) bit of the TMRx_CTRL1 register. + * @param __HANDLE__ TMR handle. + * @note When the URS bit of the TMRx_CTRL1 register is set, only counter + * overflow/underflow generates an update interrupt or DMA request (if + * enabled) + * @retval None + */ +#define __DAL_TMR_URS_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CTRL1|= TMR_CTRL1_URSSEL) + +/** + * @brief Reset the Update Request Source (URS) bit of the TMRx_CTRL1 register. + * @param __HANDLE__ TMR handle. + * @note When the URS bit of the TMRx_CTRL1 register is reset, any of the + * following events generate an update interrupt or DMA request (if + * enabled): + * _ Counter overflow underflow + * _ Setting the UG bit + * _ Update generation through the slave mode controller + * @retval None + */ +#define __DAL_TMR_URS_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CTRL1&=~TMR_CTRL1_URSSEL) + +/** + * @brief Set the TMR Capture x input polarity on runtime. + * @param __HANDLE__ TMR handle. + * @param __CHANNEL__ TMR Channels to be configured. + * This parameter can be one of the following values: + * @arg TMR_CHANNEL_1: TMR Channel 1 selected + * @arg TMR_CHANNEL_2: TMR Channel 2 selected + * @arg TMR_CHANNEL_3: TMR Channel 3 selected + * @arg TMR_CHANNEL_4: TMR Channel 4 selected + * @param __POLARITY__ Polarity for TIx source + * @arg TMR_INPUTCHANNELPOLARITY_RISING: Rising Edge + * @arg TMR_INPUTCHANNELPOLARITY_FALLING: Falling Edge + * @arg TMR_INPUTCHANNELPOLARITY_BOTHEDGE: Rising and Falling Edge + * @retval None + */ +#define __DAL_TMR_SET_CAPTUREPOLARITY(__HANDLE__, __CHANNEL__, __POLARITY__) \ + do{ \ + TMR_RESET_CAPTUREPOLARITY((__HANDLE__), (__CHANNEL__)); \ + TMR_SET_CAPTUREPOLARITY((__HANDLE__), (__CHANNEL__), (__POLARITY__)); \ + }while(0) + +/** @brief Select the Capture/compare DMA request source. + * @param __HANDLE__ specifies the TMR Handle. + * @param __CCDMA__ specifies Capture/compare DMA request source + * This parameter can be one of the following values: + * @arg TMR_CCDMAREQUEST_CC: CCx DMA request generated on Capture/Compare event + * @arg TMR_CCDMAREQUEST_UPDATE: CCx DMA request generated on Update event + * @retval None + */ +#define __DAL_TMR_SELECT_CCDMAREQUEST(__HANDLE__, __CCDMA__) \ + MODIFY_REG((__HANDLE__)->Instance->CTRL2, TMR_CTRL2_CCDSEL, (__CCDMA__)) + +/** + * @} + */ +/* End of exported macros ----------------------------------------------------*/ + +/* Private constants ---------------------------------------------------------*/ +/** @defgroup TMR_Private_Constants TMR Private Constants + * @{ + */ +/* The counter of a timer instance is disabled only if all the CCx and CCxN + channels have been disabled */ +#define TMR_CCEN_CCxE_MASK ((uint32_t)(TMR_CCEN_CC1EN | TMR_CCEN_CC2EN | TMR_CCEN_CC3EN | TMR_CCEN_CC4EN)) +#define TMR_CCEN_CCxNE_MASK ((uint32_t)(TMR_CCEN_CC1NEN | TMR_CCEN_CC2NEN | TMR_CCEN_CC3NEN)) +/** + * @} + */ +/* End of private constants --------------------------------------------------*/ + +/* Private macros ------------------------------------------------------------*/ +/** @defgroup TMR_Private_Macros TMR Private Macros + * @{ + */ +#define IS_TMR_CLEARINPUT_SOURCE(__MODE__) (((__MODE__) == TMR_CLEARINPUTSOURCE_NONE) || \ + ((__MODE__) == TMR_CLEARINPUTSOURCE_ETR)) + +#define IS_TMR_DMA_BASE(__BASE__) (((__BASE__) == TMR_DMABASE_CTRL1) || \ + ((__BASE__) == TMR_DMABASE_CTRL2) || \ + ((__BASE__) == TMR_DMABASE_SMCTRL) || \ + ((__BASE__) == TMR_DMABASE_DIEN) || \ + ((__BASE__) == TMR_DMABASE_STS) || \ + ((__BASE__) == TMR_DMABASE_CEG) || \ + ((__BASE__) == TMR_DMABASE_CCM1) || \ + ((__BASE__) == TMR_DMABASE_CCM2) || \ + ((__BASE__) == TMR_DMABASE_CCEN) || \ + ((__BASE__) == TMR_DMABASE_CNT) || \ + ((__BASE__) == TMR_DMABASE_PSC) || \ + ((__BASE__) == TMR_DMABASE_AUTORLD) || \ + ((__BASE__) == TMR_DMABASE_REPCNT) || \ + ((__BASE__) == TMR_DMABASE_CC1) || \ + ((__BASE__) == TMR_DMABASE_CC2) || \ + ((__BASE__) == TMR_DMABASE_CC3) || \ + ((__BASE__) == TMR_DMABASE_CC4) || \ + ((__BASE__) == TMR_DMABASE_BDT)) + +#define IS_TMR_EVENT_SOURCE(__SOURCE__) ((((__SOURCE__) & 0xFFFFFF00U) == 0x00000000U) && ((__SOURCE__) != 0x00000000U)) + +#define IS_TMR_COUNTER_MODE(__MODE__) (((__MODE__) == TMR_COUNTERMODE_UP) || \ + ((__MODE__) == TMR_COUNTERMODE_DOWN) || \ + ((__MODE__) == TMR_COUNTERMODE_CENTERALIGNED1) || \ + ((__MODE__) == TMR_COUNTERMODE_CENTERALIGNED2) || \ + ((__MODE__) == TMR_COUNTERMODE_CENTERALIGNED3)) + +#define IS_TMR_CLOCKDIVISION_DIV(__DIV__) (((__DIV__) == TMR_CLOCKDIVISION_DIV1) || \ + ((__DIV__) == TMR_CLOCKDIVISION_DIV2) || \ + ((__DIV__) == TMR_CLOCKDIVISION_DIV4)) + +#define IS_TMR_AUTORELOAD_PRELOAD(PRELOAD) (((PRELOAD) == TMR_AUTORELOAD_PRELOAD_DISABLE) || \ + ((PRELOAD) == TMR_AUTORELOAD_PRELOAD_ENABLE)) + +#define IS_TMR_FAST_STATE(__STATE__) (((__STATE__) == TMR_OCFAST_DISABLE) || \ + ((__STATE__) == TMR_OCFAST_ENABLE)) + +#define IS_TMR_OC_POLARITY(__POLARITY__) (((__POLARITY__) == TMR_OCPOLARITY_HIGH) || \ + ((__POLARITY__) == TMR_OCPOLARITY_LOW)) + +#define IS_TMR_OCN_POLARITY(__POLARITY__) (((__POLARITY__) == TMR_OCNPOLARITY_HIGH) || \ + ((__POLARITY__) == TMR_OCNPOLARITY_LOW)) + +#define IS_TMR_OCIDLE_STATE(__STATE__) (((__STATE__) == TMR_OCIDLESTATE_SET) || \ + ((__STATE__) == TMR_OCIDLESTATE_RESET)) + +#define IS_TMR_OCNIDLE_STATE(__STATE__) (((__STATE__) == TMR_OCNIDLESTATE_SET) || \ + ((__STATE__) == TMR_OCNIDLESTATE_RESET)) + +#define IS_TMR_ENCODERINPUT_POLARITY(__POLARITY__) (((__POLARITY__) == TMR_ENCODERINPUTPOLARITY_RISING) || \ + ((__POLARITY__) == TMR_ENCODERINPUTPOLARITY_FALLING)) + +#define IS_TMR_IC_POLARITY(__POLARITY__) (((__POLARITY__) == TMR_ICPOLARITY_RISING) || \ + ((__POLARITY__) == TMR_ICPOLARITY_FALLING) || \ + ((__POLARITY__) == TMR_ICPOLARITY_BOTHEDGE)) + +#define IS_TMR_IC_SELECTION(__SELECTION__) (((__SELECTION__) == TMR_ICSELECTION_DIRECTTI) || \ + ((__SELECTION__) == TMR_ICSELECTION_INDIRECTTI) || \ + ((__SELECTION__) == TMR_ICSELECTION_TRC)) + +#define IS_TMR_IC_PRESCALER(__PRESCALER__) (((__PRESCALER__) == TMR_ICPSC_DIV1) || \ + ((__PRESCALER__) == TMR_ICPSC_DIV2) || \ + ((__PRESCALER__) == TMR_ICPSC_DIV4) || \ + ((__PRESCALER__) == TMR_ICPSC_DIV8)) + +#define IS_TMR_OPM_MODE(__MODE__) (((__MODE__) == TMR_OPMODE_SINGLE) || \ + ((__MODE__) == TMR_OPMODE_REPETITIVE)) + +#define IS_TMR_ENCODER_MODE(__MODE__) (((__MODE__) == TMR_ENCODERMODE_TI1) || \ + ((__MODE__) == TMR_ENCODERMODE_TI2) || \ + ((__MODE__) == TMR_ENCODERMODE_TI12)) + +#define IS_TMR_DMA_SOURCE(__SOURCE__) ((((__SOURCE__) & 0xFFFF80FFU) == 0x00000000U) && ((__SOURCE__) != 0x00000000U)) + +#define IS_TMR_CHANNELS(__CHANNEL__) (((__CHANNEL__) == TMR_CHANNEL_1) || \ + ((__CHANNEL__) == TMR_CHANNEL_2) || \ + ((__CHANNEL__) == TMR_CHANNEL_3) || \ + ((__CHANNEL__) == TMR_CHANNEL_4) || \ + ((__CHANNEL__) == TMR_CHANNEL_ALL)) + +#define IS_TMR_OPM_CHANNELS(__CHANNEL__) (((__CHANNEL__) == TMR_CHANNEL_1) || \ + ((__CHANNEL__) == TMR_CHANNEL_2)) + +#define IS_TMR_COMPLEMENTARY_CHANNELS(__CHANNEL__) (((__CHANNEL__) == TMR_CHANNEL_1) || \ + ((__CHANNEL__) == TMR_CHANNEL_2) || \ + ((__CHANNEL__) == TMR_CHANNEL_3)) + +#define IS_TMR_CLOCKSOURCE(__CLOCK__) (((__CLOCK__) == TMR_CLOCKSOURCE_INTERNAL) || \ + ((__CLOCK__) == TMR_CLOCKSOURCE_ETRMODE1) || \ + ((__CLOCK__) == TMR_CLOCKSOURCE_ETRMODE2) || \ + ((__CLOCK__) == TMR_CLOCKSOURCE_TI1ED) || \ + ((__CLOCK__) == TMR_CLOCKSOURCE_TI1) || \ + ((__CLOCK__) == TMR_CLOCKSOURCE_TI2) || \ + ((__CLOCK__) == TMR_CLOCKSOURCE_ITR0) || \ + ((__CLOCK__) == TMR_CLOCKSOURCE_ITR1) || \ + ((__CLOCK__) == TMR_CLOCKSOURCE_ITR2) || \ + ((__CLOCK__) == TMR_CLOCKSOURCE_ITR3)) + +#define IS_TMR_CLOCKPOLARITY(__POLARITY__) (((__POLARITY__) == TMR_CLOCKPOLARITY_INVERTED) || \ + ((__POLARITY__) == TMR_CLOCKPOLARITY_NONINVERTED) || \ + ((__POLARITY__) == TMR_CLOCKPOLARITY_RISING) || \ + ((__POLARITY__) == TMR_CLOCKPOLARITY_FALLING) || \ + ((__POLARITY__) == TMR_CLOCKPOLARITY_BOTHEDGE)) + +#define IS_TMR_CLOCKPRESCALER(__PRESCALER__) (((__PRESCALER__) == TMR_CLOCKPRESCALER_DIV1) || \ + ((__PRESCALER__) == TMR_CLOCKPRESCALER_DIV2) || \ + ((__PRESCALER__) == TMR_CLOCKPRESCALER_DIV4) || \ + ((__PRESCALER__) == TMR_CLOCKPRESCALER_DIV8)) + +#define IS_TMR_CLOCKFILTER(__ICFILTER__) ((__ICFILTER__) <= 0xFU) + +#define IS_TMR_CLEARINPUT_POLARITY(__POLARITY__) (((__POLARITY__) == TMR_CLEARINPUTPOLARITY_INVERTED) || \ + ((__POLARITY__) == TMR_CLEARINPUTPOLARITY_NONINVERTED)) + +#define IS_TMR_CLEARINPUT_PRESCALER(__PRESCALER__) (((__PRESCALER__) == TMR_CLEARINPUTPRESCALER_DIV1) || \ + ((__PRESCALER__) == TMR_CLEARINPUTPRESCALER_DIV2) || \ + ((__PRESCALER__) == TMR_CLEARINPUTPRESCALER_DIV4) || \ + ((__PRESCALER__) == TMR_CLEARINPUTPRESCALER_DIV8)) + +#define IS_TMR_CLEARINPUT_FILTER(__ICFILTER__) ((__ICFILTER__) <= 0xFU) + +#define IS_TMR_OSSR_STATE(__STATE__) (((__STATE__) == TMR_OSSR_ENABLE) || \ + ((__STATE__) == TMR_OSSR_DISABLE)) + +#define IS_TMR_OSSI_STATE(__STATE__) (((__STATE__) == TMR_OSSI_ENABLE) || \ + ((__STATE__) == TMR_OSSI_DISABLE)) + +#define IS_TMR_LOCK_LEVEL(__LEVEL__) (((__LEVEL__) == TMR_LOCKLEVEL_OFF) || \ + ((__LEVEL__) == TMR_LOCKLEVEL_1) || \ + ((__LEVEL__) == TMR_LOCKLEVEL_2) || \ + ((__LEVEL__) == TMR_LOCKLEVEL_3)) + +#define IS_TMR_BREAK_FILTER(__BRKFILTER__) ((__BRKFILTER__) <= 0xFUL) + + +#define IS_TMR_BREAK_STATE(__STATE__) (((__STATE__) == TMR_BREAK_ENABLE) || \ + ((__STATE__) == TMR_BREAK_DISABLE)) + +#define IS_TMR_BREAK_POLARITY(__POLARITY__) (((__POLARITY__) == TMR_BREAKPOLARITY_LOW) || \ + ((__POLARITY__) == TMR_BREAKPOLARITY_HIGH)) + +#define IS_TMR_AUTOMATIC_OUTPUT_STATE(__STATE__) (((__STATE__) == TMR_AUTOMATICOUTPUT_ENABLE) || \ + ((__STATE__) == TMR_AUTOMATICOUTPUT_DISABLE)) + +#define IS_TMR_TRGO_SOURCE(__SOURCE__) (((__SOURCE__) == TMR_TRGO_RESET) || \ + ((__SOURCE__) == TMR_TRGO_ENABLE) || \ + ((__SOURCE__) == TMR_TRGO_UPDATE) || \ + ((__SOURCE__) == TMR_TRGO_OC1) || \ + ((__SOURCE__) == TMR_TRGO_OC1REF) || \ + ((__SOURCE__) == TMR_TRGO_OC2REF) || \ + ((__SOURCE__) == TMR_TRGO_OC3REF) || \ + ((__SOURCE__) == TMR_TRGO_OC4REF)) + +#define IS_TMR_MSM_STATE(__STATE__) (((__STATE__) == TMR_MASTERSLAVEMODE_ENABLE) || \ + ((__STATE__) == TMR_MASTERSLAVEMODE_DISABLE)) + +#define IS_TMR_SLAVE_MODE(__MODE__) (((__MODE__) == TMR_SLAVEMODE_DISABLE) || \ + ((__MODE__) == TMR_SLAVEMODE_RESET) || \ + ((__MODE__) == TMR_SLAVEMODE_GATED) || \ + ((__MODE__) == TMR_SLAVEMODE_TRIGGER) || \ + ((__MODE__) == TMR_SLAVEMODE_EXTERNAL1)) + +#define IS_TMR_PWM_MODE(__MODE__) (((__MODE__) == TMR_OCMODE_PWM1) || \ + ((__MODE__) == TMR_OCMODE_PWM2)) + +#define IS_TMR_OC_MODE(__MODE__) (((__MODE__) == TMR_OCMODE_TIMING) || \ + ((__MODE__) == TMR_OCMODE_ACTIVE) || \ + ((__MODE__) == TMR_OCMODE_INACTIVE) || \ + ((__MODE__) == TMR_OCMODE_TOGGLE) || \ + ((__MODE__) == TMR_OCMODE_FORCED_ACTIVE) || \ + ((__MODE__) == TMR_OCMODE_FORCED_INACTIVE)) + +#define IS_TMR_TRIGGER_SELECTION(__SELECTION__) (((__SELECTION__) == TMR_TS_ITR0) || \ + ((__SELECTION__) == TMR_TS_ITR1) || \ + ((__SELECTION__) == TMR_TS_ITR2) || \ + ((__SELECTION__) == TMR_TS_ITR3) || \ + ((__SELECTION__) == TMR_TS_TI1F_ED) || \ + ((__SELECTION__) == TMR_TS_TI1FP1) || \ + ((__SELECTION__) == TMR_TS_TI2FP2) || \ + ((__SELECTION__) == TMR_TS_ETRF)) + +#define IS_TMR_INTERNAL_TRIGGEREVENT_SELECTION(__SELECTION__) (((__SELECTION__) == TMR_TS_ITR0) || \ + ((__SELECTION__) == TMR_TS_ITR1) || \ + ((__SELECTION__) == TMR_TS_ITR2) || \ + ((__SELECTION__) == TMR_TS_ITR3) || \ + ((__SELECTION__) == TMR_TS_NONE)) + +#define IS_TMR_TRIGGERPOLARITY(__POLARITY__) (((__POLARITY__) == TMR_TRIGGERPOLARITY_INVERTED ) || \ + ((__POLARITY__) == TMR_TRIGGERPOLARITY_NONINVERTED) || \ + ((__POLARITY__) == TMR_TRIGGERPOLARITY_RISING ) || \ + ((__POLARITY__) == TMR_TRIGGERPOLARITY_FALLING ) || \ + ((__POLARITY__) == TMR_TRIGGERPOLARITY_BOTHEDGE )) + +#define IS_TMR_TRIGGERPRESCALER(__PRESCALER__) (((__PRESCALER__) == TMR_TRIGGERPRESCALER_DIV1) || \ + ((__PRESCALER__) == TMR_TRIGGERPRESCALER_DIV2) || \ + ((__PRESCALER__) == TMR_TRIGGERPRESCALER_DIV4) || \ + ((__PRESCALER__) == TMR_TRIGGERPRESCALER_DIV8)) + +#define IS_TMR_TRIGGERFILTER(__ICFILTER__) ((__ICFILTER__) <= 0xFU) + +#define IS_TMR_TI1SELECTION(__TI1SELECTION__) (((__TI1SELECTION__) == TMR_TI1SELECTION_CH1) || \ + ((__TI1SELECTION__) == TMR_TI1SELECTION_XORCOMBINATION)) + +#define IS_TMR_DMA_LENGTH(__LENGTH__) (((__LENGTH__) == TMR_DMABURSTLENGTH_1TRANSFER) || \ + ((__LENGTH__) == TMR_DMABURSTLENGTH_2TRANSFERS) || \ + ((__LENGTH__) == TMR_DMABURSTLENGTH_3TRANSFERS) || \ + ((__LENGTH__) == TMR_DMABURSTLENGTH_4TRANSFERS) || \ + ((__LENGTH__) == TMR_DMABURSTLENGTH_5TRANSFERS) || \ + ((__LENGTH__) == TMR_DMABURSTLENGTH_6TRANSFERS) || \ + ((__LENGTH__) == TMR_DMABURSTLENGTH_7TRANSFERS) || \ + ((__LENGTH__) == TMR_DMABURSTLENGTH_8TRANSFERS) || \ + ((__LENGTH__) == TMR_DMABURSTLENGTH_9TRANSFERS) || \ + ((__LENGTH__) == TMR_DMABURSTLENGTH_10TRANSFERS) || \ + ((__LENGTH__) == TMR_DMABURSTLENGTH_11TRANSFERS) || \ + ((__LENGTH__) == TMR_DMABURSTLENGTH_12TRANSFERS) || \ + ((__LENGTH__) == TMR_DMABURSTLENGTH_13TRANSFERS) || \ + ((__LENGTH__) == TMR_DMABURSTLENGTH_14TRANSFERS) || \ + ((__LENGTH__) == TMR_DMABURSTLENGTH_15TRANSFERS) || \ + ((__LENGTH__) == TMR_DMABURSTLENGTH_16TRANSFERS) || \ + ((__LENGTH__) == TMR_DMABURSTLENGTH_17TRANSFERS) || \ + ((__LENGTH__) == TMR_DMABURSTLENGTH_18TRANSFERS)) + +#define IS_TMR_DMA_DATA_LENGTH(LENGTH) (((LENGTH) >= 0x1U) && ((LENGTH) < 0x10000U)) + +#define IS_TMR_IC_FILTER(__ICFILTER__) ((__ICFILTER__) <= 0xFU) + +#define IS_TMR_DEADTIME(__DEADTIME__) ((__DEADTIME__) <= 0xFFU) + +#define IS_TMR_SLAVEMODE_TRIGGER_ENABLED(__TRIGGER__) ((__TRIGGER__) == TMR_SLAVEMODE_TRIGGER) + +#define TMR_SET_ICPRESCALERVALUE(__HANDLE__, __CHANNEL__, __ICPSC__) \ + (((__CHANNEL__) == TMR_CHANNEL_1) ? ((__HANDLE__)->Instance->CCM1 |= (__ICPSC__)) :\ + ((__CHANNEL__) == TMR_CHANNEL_2) ? ((__HANDLE__)->Instance->CCM1 |= ((__ICPSC__) << 8U)) :\ + ((__CHANNEL__) == TMR_CHANNEL_3) ? ((__HANDLE__)->Instance->CCM2 |= (__ICPSC__)) :\ + ((__HANDLE__)->Instance->CCM2 |= ((__ICPSC__) << 8U))) + +#define TMR_RESET_ICPRESCALERVALUE(__HANDLE__, __CHANNEL__) \ + (((__CHANNEL__) == TMR_CHANNEL_1) ? ((__HANDLE__)->Instance->CCM1 &= ~TMR_CCM1_IC1PSC) :\ + ((__CHANNEL__) == TMR_CHANNEL_2) ? ((__HANDLE__)->Instance->CCM1 &= ~TMR_CCM1_IC2PSC) :\ + ((__CHANNEL__) == TMR_CHANNEL_3) ? ((__HANDLE__)->Instance->CCM2 &= ~TMR_CCM2_IC3PSC) :\ + ((__HANDLE__)->Instance->CCM2 &= ~TMR_CCM2_IC4PSC)) + +#define TMR_SET_CAPTUREPOLARITY(__HANDLE__, __CHANNEL__, __POLARITY__) \ + (((__CHANNEL__) == TMR_CHANNEL_1) ? ((__HANDLE__)->Instance->CCEN |= (__POLARITY__)) :\ + ((__CHANNEL__) == TMR_CHANNEL_2) ? ((__HANDLE__)->Instance->CCEN |= ((__POLARITY__) << 4U)) :\ + ((__CHANNEL__) == TMR_CHANNEL_3) ? ((__HANDLE__)->Instance->CCEN |= ((__POLARITY__) << 8U)) :\ + ((__HANDLE__)->Instance->CCEN |= (((__POLARITY__) << 12U)))) + +#define TMR_RESET_CAPTUREPOLARITY(__HANDLE__, __CHANNEL__) \ + (((__CHANNEL__) == TMR_CHANNEL_1) ? ((__HANDLE__)->Instance->CCEN &= ~(TMR_CCEN_CC1POL | TMR_CCEN_CC1NPOL)) :\ + ((__CHANNEL__) == TMR_CHANNEL_2) ? ((__HANDLE__)->Instance->CCEN &= ~(TMR_CCEN_CC2POL | TMR_CCEN_CC2NPOL)) :\ + ((__CHANNEL__) == TMR_CHANNEL_3) ? ((__HANDLE__)->Instance->CCEN &= ~(TMR_CCEN_CC3POL | TMR_CCEN_CC3NPOL)) :\ + ((__HANDLE__)->Instance->CCEN &= ~(TMR_CCEN_CC4POL | TMR_CCEN_CC4NPOL))) + +#define TMR_CHANNEL_STATE_GET(__HANDLE__, __CHANNEL__)\ + (((__CHANNEL__) == TMR_CHANNEL_1) ? (__HANDLE__)->ChannelState[0] :\ + ((__CHANNEL__) == TMR_CHANNEL_2) ? (__HANDLE__)->ChannelState[1] :\ + ((__CHANNEL__) == TMR_CHANNEL_3) ? (__HANDLE__)->ChannelState[2] :\ + (__HANDLE__)->ChannelState[3]) + +#define TMR_CHANNEL_STATE_SET(__HANDLE__, __CHANNEL__, __CHANNEL_STATE__) \ + (((__CHANNEL__) == TMR_CHANNEL_1) ? ((__HANDLE__)->ChannelState[0] = (__CHANNEL_STATE__)) :\ + ((__CHANNEL__) == TMR_CHANNEL_2) ? ((__HANDLE__)->ChannelState[1] = (__CHANNEL_STATE__)) :\ + ((__CHANNEL__) == TMR_CHANNEL_3) ? ((__HANDLE__)->ChannelState[2] = (__CHANNEL_STATE__)) :\ + ((__HANDLE__)->ChannelState[3] = (__CHANNEL_STATE__))) + +#define TMR_CHANNEL_STATE_SET_ALL(__HANDLE__, __CHANNEL_STATE__) do { \ + (__HANDLE__)->ChannelState[0] = (__CHANNEL_STATE__); \ + (__HANDLE__)->ChannelState[1] = (__CHANNEL_STATE__); \ + (__HANDLE__)->ChannelState[2] = (__CHANNEL_STATE__); \ + (__HANDLE__)->ChannelState[3] = (__CHANNEL_STATE__); \ + } while(0) + +#define TMR_CHANNEL_N_STATE_GET(__HANDLE__, __CHANNEL__)\ + (((__CHANNEL__) == TMR_CHANNEL_1) ? (__HANDLE__)->ChannelNState[0] :\ + ((__CHANNEL__) == TMR_CHANNEL_2) ? (__HANDLE__)->ChannelNState[1] :\ + ((__CHANNEL__) == TMR_CHANNEL_3) ? (__HANDLE__)->ChannelNState[2] :\ + (__HANDLE__)->ChannelNState[3]) + +#define TMR_CHANNEL_N_STATE_SET(__HANDLE__, __CHANNEL__, __CHANNEL_STATE__) \ + (((__CHANNEL__) == TMR_CHANNEL_1) ? ((__HANDLE__)->ChannelNState[0] = (__CHANNEL_STATE__)) :\ + ((__CHANNEL__) == TMR_CHANNEL_2) ? ((__HANDLE__)->ChannelNState[1] = (__CHANNEL_STATE__)) :\ + ((__CHANNEL__) == TMR_CHANNEL_3) ? ((__HANDLE__)->ChannelNState[2] = (__CHANNEL_STATE__)) :\ + ((__HANDLE__)->ChannelNState[3] = (__CHANNEL_STATE__))) + +#define TMR_CHANNEL_N_STATE_SET_ALL(__HANDLE__, __CHANNEL_STATE__) do { \ + (__HANDLE__)->ChannelNState[0] = \ + (__CHANNEL_STATE__); \ + (__HANDLE__)->ChannelNState[1] = \ + (__CHANNEL_STATE__); \ + (__HANDLE__)->ChannelNState[2] = \ + (__CHANNEL_STATE__); \ + (__HANDLE__)->ChannelNState[3] = \ + (__CHANNEL_STATE__); \ + } while(0) + +/** + * @} + */ +/* End of private macros -----------------------------------------------------*/ + +/* Include TMR DAL Extended module */ +#include "apm32f4xx_dal_tmr_ex.h" + +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup TMR_Exported_Functions TMR Exported Functions + * @{ + */ + +/** @addtogroup TMR_Exported_Functions_Group1 TMR Time Base functions + * @brief Time Base functions + * @{ + */ +/* Time Base functions ********************************************************/ +DAL_StatusTypeDef DAL_TMR_Base_Init(TMR_HandleTypeDef *htmr); +DAL_StatusTypeDef DAL_TMR_Base_DeInit(TMR_HandleTypeDef *htmr); +void DAL_TMR_Base_MspInit(TMR_HandleTypeDef *htmr); +void DAL_TMR_Base_MspDeInit(TMR_HandleTypeDef *htmr); +/* Blocking mode: Polling */ +DAL_StatusTypeDef DAL_TMR_Base_Start(TMR_HandleTypeDef *htmr); +DAL_StatusTypeDef DAL_TMR_Base_Stop(TMR_HandleTypeDef *htmr); +/* Non-Blocking mode: Interrupt */ +DAL_StatusTypeDef DAL_TMR_Base_Start_IT(TMR_HandleTypeDef *htmr); +DAL_StatusTypeDef DAL_TMR_Base_Stop_IT(TMR_HandleTypeDef *htmr); +/* Non-Blocking mode: DMA */ +DAL_StatusTypeDef DAL_TMR_Base_Start_DMA(TMR_HandleTypeDef *htmr, uint32_t *pData, uint16_t Length); +DAL_StatusTypeDef DAL_TMR_Base_Stop_DMA(TMR_HandleTypeDef *htmr); +/** + * @} + */ + +/** @addtogroup TMR_Exported_Functions_Group2 TMR Output Compare functions + * @brief TMR Output Compare functions + * @{ + */ +/* Timer Output Compare functions *********************************************/ +DAL_StatusTypeDef DAL_TMR_OC_Init(TMR_HandleTypeDef *htmr); +DAL_StatusTypeDef DAL_TMR_OC_DeInit(TMR_HandleTypeDef *htmr); +void DAL_TMR_OC_MspInit(TMR_HandleTypeDef *htmr); +void DAL_TMR_OC_MspDeInit(TMR_HandleTypeDef *htmr); +/* Blocking mode: Polling */ +DAL_StatusTypeDef DAL_TMR_OC_Start(TMR_HandleTypeDef *htmr, uint32_t Channel); +DAL_StatusTypeDef DAL_TMR_OC_Stop(TMR_HandleTypeDef *htmr, uint32_t Channel); +/* Non-Blocking mode: Interrupt */ +DAL_StatusTypeDef DAL_TMR_OC_Start_IT(TMR_HandleTypeDef *htmr, uint32_t Channel); +DAL_StatusTypeDef DAL_TMR_OC_Stop_IT(TMR_HandleTypeDef *htmr, uint32_t Channel); +/* Non-Blocking mode: DMA */ +DAL_StatusTypeDef DAL_TMR_OC_Start_DMA(TMR_HandleTypeDef *htmr, uint32_t Channel, uint32_t *pData, uint16_t Length); +DAL_StatusTypeDef DAL_TMR_OC_Stop_DMA(TMR_HandleTypeDef *htmr, uint32_t Channel); +/** + * @} + */ + +/** @addtogroup TMR_Exported_Functions_Group3 TMR PWM functions + * @brief TMR PWM functions + * @{ + */ +/* Timer PWM functions ********************************************************/ +DAL_StatusTypeDef DAL_TMR_PWM_Init(TMR_HandleTypeDef *htmr); +DAL_StatusTypeDef DAL_TMR_PWM_DeInit(TMR_HandleTypeDef *htmr); +void DAL_TMR_PWM_MspInit(TMR_HandleTypeDef *htmr); +void DAL_TMR_PWM_MspDeInit(TMR_HandleTypeDef *htmr); +/* Blocking mode: Polling */ +DAL_StatusTypeDef DAL_TMR_PWM_Start(TMR_HandleTypeDef *htmr, uint32_t Channel); +DAL_StatusTypeDef DAL_TMR_PWM_Stop(TMR_HandleTypeDef *htmr, uint32_t Channel); +/* Non-Blocking mode: Interrupt */ +DAL_StatusTypeDef DAL_TMR_PWM_Start_IT(TMR_HandleTypeDef *htmr, uint32_t Channel); +DAL_StatusTypeDef DAL_TMR_PWM_Stop_IT(TMR_HandleTypeDef *htmr, uint32_t Channel); +/* Non-Blocking mode: DMA */ +DAL_StatusTypeDef DAL_TMR_PWM_Start_DMA(TMR_HandleTypeDef *htmr, uint32_t Channel, uint32_t *pData, uint16_t Length); +DAL_StatusTypeDef DAL_TMR_PWM_Stop_DMA(TMR_HandleTypeDef *htmr, uint32_t Channel); +/** + * @} + */ + +/** @addtogroup TMR_Exported_Functions_Group4 TMR Input Capture functions + * @brief TMR Input Capture functions + * @{ + */ +/* Timer Input Capture functions **********************************************/ +DAL_StatusTypeDef DAL_TMR_IC_Init(TMR_HandleTypeDef *htmr); +DAL_StatusTypeDef DAL_TMR_IC_DeInit(TMR_HandleTypeDef *htmr); +void DAL_TMR_IC_MspInit(TMR_HandleTypeDef *htmr); +void DAL_TMR_IC_MspDeInit(TMR_HandleTypeDef *htmr); +/* Blocking mode: Polling */ +DAL_StatusTypeDef DAL_TMR_IC_Start(TMR_HandleTypeDef *htmr, uint32_t Channel); +DAL_StatusTypeDef DAL_TMR_IC_Stop(TMR_HandleTypeDef *htmr, uint32_t Channel); +/* Non-Blocking mode: Interrupt */ +DAL_StatusTypeDef DAL_TMR_IC_Start_IT(TMR_HandleTypeDef *htmr, uint32_t Channel); +DAL_StatusTypeDef DAL_TMR_IC_Stop_IT(TMR_HandleTypeDef *htmr, uint32_t Channel); +/* Non-Blocking mode: DMA */ +DAL_StatusTypeDef DAL_TMR_IC_Start_DMA(TMR_HandleTypeDef *htmr, uint32_t Channel, uint32_t *pData, uint16_t Length); +DAL_StatusTypeDef DAL_TMR_IC_Stop_DMA(TMR_HandleTypeDef *htmr, uint32_t Channel); +/** + * @} + */ + +/** @addtogroup TMR_Exported_Functions_Group5 TMR One Pulse functions + * @brief TMR One Pulse functions + * @{ + */ +/* Timer One Pulse functions **************************************************/ +DAL_StatusTypeDef DAL_TMR_OnePulse_Init(TMR_HandleTypeDef *htmr, uint32_t OnePulseMode); +DAL_StatusTypeDef DAL_TMR_OnePulse_DeInit(TMR_HandleTypeDef *htmr); +void DAL_TMR_OnePulse_MspInit(TMR_HandleTypeDef *htmr); +void DAL_TMR_OnePulse_MspDeInit(TMR_HandleTypeDef *htmr); +/* Blocking mode: Polling */ +DAL_StatusTypeDef DAL_TMR_OnePulse_Start(TMR_HandleTypeDef *htmr, uint32_t OutputChannel); +DAL_StatusTypeDef DAL_TMR_OnePulse_Stop(TMR_HandleTypeDef *htmr, uint32_t OutputChannel); +/* Non-Blocking mode: Interrupt */ +DAL_StatusTypeDef DAL_TMR_OnePulse_Start_IT(TMR_HandleTypeDef *htmr, uint32_t OutputChannel); +DAL_StatusTypeDef DAL_TMR_OnePulse_Stop_IT(TMR_HandleTypeDef *htmr, uint32_t OutputChannel); +/** + * @} + */ + +/** @addtogroup TMR_Exported_Functions_Group6 TMR Encoder functions + * @brief TMR Encoder functions + * @{ + */ +/* Timer Encoder functions ****************************************************/ +DAL_StatusTypeDef DAL_TMR_Encoder_Init(TMR_HandleTypeDef *htmr, TMR_Encoder_InitTypeDef *sConfig); +DAL_StatusTypeDef DAL_TMR_Encoder_DeInit(TMR_HandleTypeDef *htmr); +void DAL_TMR_Encoder_MspInit(TMR_HandleTypeDef *htmr); +void DAL_TMR_Encoder_MspDeInit(TMR_HandleTypeDef *htmr); +/* Blocking mode: Polling */ +DAL_StatusTypeDef DAL_TMR_Encoder_Start(TMR_HandleTypeDef *htmr, uint32_t Channel); +DAL_StatusTypeDef DAL_TMR_Encoder_Stop(TMR_HandleTypeDef *htmr, uint32_t Channel); +/* Non-Blocking mode: Interrupt */ +DAL_StatusTypeDef DAL_TMR_Encoder_Start_IT(TMR_HandleTypeDef *htmr, uint32_t Channel); +DAL_StatusTypeDef DAL_TMR_Encoder_Stop_IT(TMR_HandleTypeDef *htmr, uint32_t Channel); +/* Non-Blocking mode: DMA */ +DAL_StatusTypeDef DAL_TMR_Encoder_Start_DMA(TMR_HandleTypeDef *htmr, uint32_t Channel, uint32_t *pData1, + uint32_t *pData2, uint16_t Length); +DAL_StatusTypeDef DAL_TMR_Encoder_Stop_DMA(TMR_HandleTypeDef *htmr, uint32_t Channel); +/** + * @} + */ + +/** @addtogroup TMR_Exported_Functions_Group7 TMR IRQ handler management + * @brief IRQ handler management + * @{ + */ +/* Interrupt Handler functions ***********************************************/ +void DAL_TMR_IRQHandler(TMR_HandleTypeDef *htmr); +/** + * @} + */ + +/** @defgroup TMR_Exported_Functions_Group8 TMR Peripheral Control functions + * @brief Peripheral Control functions + * @{ + */ +/* Control functions *********************************************************/ +DAL_StatusTypeDef DAL_TMR_OC_ConfigChannel(TMR_HandleTypeDef *htmr, TMR_OC_InitTypeDef *sConfig, uint32_t Channel); +DAL_StatusTypeDef DAL_TMR_PWM_ConfigChannel(TMR_HandleTypeDef *htmr, TMR_OC_InitTypeDef *sConfig, uint32_t Channel); +DAL_StatusTypeDef DAL_TMR_IC_ConfigChannel(TMR_HandleTypeDef *htmr, TMR_IC_InitTypeDef *sConfig, uint32_t Channel); +DAL_StatusTypeDef DAL_TMR_OnePulse_ConfigChannel(TMR_HandleTypeDef *htmr, TMR_OnePulse_InitTypeDef *sConfig, + uint32_t OutputChannel, uint32_t InputChannel); +DAL_StatusTypeDef DAL_TMR_ConfigOCrefClear(TMR_HandleTypeDef *htmr, TMR_ClearInputConfigTypeDef *sClearInputConfig, + uint32_t Channel); +DAL_StatusTypeDef DAL_TMR_ConfigClockSource(TMR_HandleTypeDef *htmr, TMR_ClockConfigTypeDef *sClockSourceConfig); +DAL_StatusTypeDef DAL_TMR_ConfigTI1Input(TMR_HandleTypeDef *htmr, uint32_t TI1_Selection); +DAL_StatusTypeDef DAL_TMR_SlaveConfigSynchro(TMR_HandleTypeDef *htmr, TMR_SlaveConfigTypeDef *sSlaveConfig); +DAL_StatusTypeDef DAL_TMR_SlaveConfigSynchro_IT(TMR_HandleTypeDef *htmr, TMR_SlaveConfigTypeDef *sSlaveConfig); +DAL_StatusTypeDef DAL_TMR_DMABurst_WriteStart(TMR_HandleTypeDef *htmr, uint32_t BurstBaseAddress, + uint32_t BurstRequestSrc, uint32_t *BurstBuffer, uint32_t BurstLength); +DAL_StatusTypeDef DAL_TMR_DMABurst_MultiWriteStart(TMR_HandleTypeDef *htmr, uint32_t BurstBaseAddress, + uint32_t BurstRequestSrc, uint32_t *BurstBuffer, + uint32_t BurstLength, uint32_t DataLength); +DAL_StatusTypeDef DAL_TMR_DMABurst_WriteStop(TMR_HandleTypeDef *htmr, uint32_t BurstRequestSrc); +DAL_StatusTypeDef DAL_TMR_DMABurst_ReadStart(TMR_HandleTypeDef *htmr, uint32_t BurstBaseAddress, + uint32_t BurstRequestSrc, uint32_t *BurstBuffer, uint32_t BurstLength); +DAL_StatusTypeDef DAL_TMR_DMABurst_MultiReadStart(TMR_HandleTypeDef *htmr, uint32_t BurstBaseAddress, + uint32_t BurstRequestSrc, uint32_t *BurstBuffer, + uint32_t BurstLength, uint32_t DataLength); +DAL_StatusTypeDef DAL_TMR_DMABurst_ReadStop(TMR_HandleTypeDef *htmr, uint32_t BurstRequestSrc); +DAL_StatusTypeDef DAL_TMR_GenerateEvent(TMR_HandleTypeDef *htmr, uint32_t EventSource); +uint32_t DAL_TMR_ReadCapturedValue(TMR_HandleTypeDef *htmr, uint32_t Channel); +/** + * @} + */ + +/** @defgroup TMR_Exported_Functions_Group9 TMR Callbacks functions + * @brief TMR Callbacks functions + * @{ + */ +/* Callback in non blocking modes (Interrupt and DMA) *************************/ +void DAL_TMR_PeriodElapsedCallback(TMR_HandleTypeDef *htmr); +void DAL_TMR_PeriodElapsedHalfCpltCallback(TMR_HandleTypeDef *htmr); +void DAL_TMR_OC_DelayElapsedCallback(TMR_HandleTypeDef *htmr); +void DAL_TMR_IC_CaptureCallback(TMR_HandleTypeDef *htmr); +void DAL_TMR_IC_CaptureHalfCpltCallback(TMR_HandleTypeDef *htmr); +void DAL_TMR_PWM_PulseFinishedCallback(TMR_HandleTypeDef *htmr); +void DAL_TMR_PWM_PulseFinishedHalfCpltCallback(TMR_HandleTypeDef *htmr); +void DAL_TMR_TriggerCallback(TMR_HandleTypeDef *htmr); +void DAL_TMR_TriggerHalfCpltCallback(TMR_HandleTypeDef *htmr); +void DAL_TMR_ErrorCallback(TMR_HandleTypeDef *htmr); + +/* Callbacks Register/UnRegister functions ***********************************/ +#if (USE_DAL_TMR_REGISTER_CALLBACKS == 1) +DAL_StatusTypeDef DAL_TMR_RegisterCallback(TMR_HandleTypeDef *htmr, DAL_TMR_CallbackIDTypeDef CallbackID, + pTMR_CallbackTypeDef pCallback); +DAL_StatusTypeDef DAL_TMR_UnRegisterCallback(TMR_HandleTypeDef *htmr, DAL_TMR_CallbackIDTypeDef CallbackID); +#endif /* USE_DAL_TMR_REGISTER_CALLBACKS */ + +/** + * @} + */ + +/** @defgroup TMR_Exported_Functions_Group10 TMR Peripheral State functions + * @brief Peripheral State functions + * @{ + */ +/* Peripheral State functions ************************************************/ +DAL_TMR_StateTypeDef DAL_TMR_Base_GetState(TMR_HandleTypeDef *htmr); +DAL_TMR_StateTypeDef DAL_TMR_OC_GetState(TMR_HandleTypeDef *htmr); +DAL_TMR_StateTypeDef DAL_TMR_PWM_GetState(TMR_HandleTypeDef *htmr); +DAL_TMR_StateTypeDef DAL_TMR_IC_GetState(TMR_HandleTypeDef *htmr); +DAL_TMR_StateTypeDef DAL_TMR_OnePulse_GetState(TMR_HandleTypeDef *htmr); +DAL_TMR_StateTypeDef DAL_TMR_Encoder_GetState(TMR_HandleTypeDef *htmr); + +/* Peripheral Channel state functions ************************************************/ +DAL_TMR_ActiveChannel DAL_TMR_GetActiveChannel(TMR_HandleTypeDef *htmr); +DAL_TMR_ChannelStateTypeDef DAL_TMR_GetChannelState(TMR_HandleTypeDef *htmr, uint32_t Channel); +DAL_TMR_DMABurstStateTypeDef DAL_TMR_DMABurstState(TMR_HandleTypeDef *htmr); +/** + * @} + */ + +/** + * @} + */ +/* End of exported functions -------------------------------------------------*/ + +/* Private functions----------------------------------------------------------*/ +/** @defgroup TMR_Private_Functions TMR Private Functions + * @{ + */ +void TMR_Base_SetConfig(TMR_TypeDef *TMRx, TMR_Base_InitTypeDef *Structure); +void TMR_TI1_SetConfig(TMR_TypeDef *TMRx, uint32_t TMR_ICPolarity, uint32_t TMR_ICSelection, uint32_t TMR_ICFilter); +void TMR_OC2_SetConfig(TMR_TypeDef *TMRx, TMR_OC_InitTypeDef *OC_Config); +void TMR_ETR_SetConfig(TMR_TypeDef *TMRx, uint32_t TMR_ExtTRGPrescaler, + uint32_t TMR_ExtTRGPolarity, uint32_t ExtTRGFilter); + +void TMR_DMADelayPulseCplt(DMA_HandleTypeDef *hdma); +void TMR_DMADelayPulseHalfCplt(DMA_HandleTypeDef *hdma); +void TMR_DMAError(DMA_HandleTypeDef *hdma); +void TMR_DMACaptureCplt(DMA_HandleTypeDef *hdma); +void TMR_DMACaptureHalfCplt(DMA_HandleTypeDef *hdma); +void TMR_CCxChannelCmd(TMR_TypeDef *TMRx, uint32_t Channel, uint32_t ChannelState); + +#if (USE_DAL_TMR_REGISTER_CALLBACKS == 1) +void TMR_ResetCallback(TMR_HandleTypeDef *htmr); +#endif /* USE_DAL_TMR_REGISTER_CALLBACKS */ + +/** + * @} + */ +/* End of private functions --------------------------------------------------*/ + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* APM32F4xx_DAL_TMR_H */ diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_tmr_ex.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_tmr_ex.h new file mode 100644 index 0000000000..f3544c361b --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_tmr_ex.h @@ -0,0 +1,378 @@ +/** + * + * @file apm32f4xx_dal_tmr_ex.h + * @brief Header file of TMR DAL Extended module. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef APM32F4xx_DAL_TMR_EX_H +#define APM32F4xx_DAL_TMR_EX_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal_def.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @addtogroup TMREx + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ +/** @defgroup TMREx_Exported_Types TMR Extended Exported Types + * @{ + */ + +/** + * @brief TMR Hall sensor Configuration Structure definition + */ + +typedef struct +{ + uint32_t IC1Polarity; /*!< Specifies the active edge of the input signal. + This parameter can be a value of @ref TMR_Input_Capture_Polarity */ + + uint32_t IC1Prescaler; /*!< Specifies the Input Capture Prescaler. + This parameter can be a value of @ref TMR_Input_Capture_Prescaler */ + + uint32_t IC1Filter; /*!< Specifies the input capture filter. + This parameter can be a number between Min_Data = 0x0 and Max_Data = 0xF */ + + uint32_t Commutation_Delay; /*!< Specifies the pulse value to be loaded into the Capture Compare Register. + This parameter can be a number between Min_Data = 0x0000 and Max_Data = 0xFFFF */ +} TMR_HallSensor_InitTypeDef; +/** + * @} + */ +/* End of exported types -----------------------------------------------------*/ + +/* Exported constants --------------------------------------------------------*/ +/** @defgroup TMREx_Exported_Constants TMR Extended Exported Constants + * @{ + */ + +/** @defgroup TMREx_Remap TMR Extended Remapping + * @{ + */ +#if defined (TMR2) +#if defined(TMR8) +#define TMR_TMR2_TMR8_TRGO 0x00000000U /*!< TMR2 ITR1 is connected to TMR8 TRGO */ +#else +#define TMR_TMR2_ETH_PTP TMR_OR_RMPSEL_0 /*!< TMR2 ITR1 is connected to PTP trigger output */ +#endif /* TMR8 */ +#define TMR_TMR2_USBFS_SOF TMR_OR_RMPSEL_1 /*!< TMR2 ITR1 is connected to OTG FS SOF */ +#define TMR_TMR2_USBHS_SOF (TMR_OR_RMPSEL_1 | TMR_OR_RMPSEL_0) /*!< TMR2 ITR1 is connected to OTG HS SOF */ +#endif /* TMR2 */ + +#define TMR_TMR5_GPIO 0x00000000U /*!< TMR5 TI4 is connected to GPIO */ +#define TMR_TMR5_LSI TMR_OR_TI4_RMPSEL_0 /*!< TMR5 TI4 is connected to LSI */ +#define TMR_TMR5_LSE TMR_OR_TI4_RMPSEL_1 /*!< TMR5 TI4 is connected to LSE */ +#define TMR_TMR5_RTC (TMR_OR_TI4_RMPSEL_1 | TMR_OR_TI4_RMPSEL_0) /*!< TMR5 TI4 is connected to the RTC wakeup interrupt */ + +#define TMR_TMR11_GPIO 0x00000000U /*!< TMR11 TI1 is connected to GPIO */ +#define TMR_TMR11_HSE TMR_OR_TI1_RMPSEL_1 /*!< TMR11 TI1 is connected to HSE_RTC clock */ +#if defined(SPDIFRX) +#define TMR_TMR11_SPDIFRX TMR_OR_TI1_RMPSEL_0 /*!< TMR11 TI1 is connected to SPDIFRX_FRAME_SYNC */ +#endif /* SPDIFRX*/ + +#if defined(LPTMR_OR_TMR1_ITR2_RMP) && defined(LPTMR_OR_TMR5_ITR1_RMP) && defined(LPTMR_OR_TMR5_ITR1_RMP) +#define LPTMR_REMAP_MASK 0x10000000U + +#define TMR_TMR9_TMR3_TRGO LPTMR_REMAP_MASK /*!< TMR9 ITR1 is connected to TMR3 TRGO */ +#define TMR_TMR9_LPTMR (LPTMR_REMAP_MASK | LPTMR_OR_TMR9_ITR1_RMP) /*!< TMR9 ITR1 is connected to LPTMR1 output */ + +#define TMR_TMR5_TMR3_TRGO LPTMR_REMAP_MASK /*!< TMR5 ITR1 is connected to TMR3 TRGO */ +#define TMR_TMR5_LPTMR (LPTMR_REMAP_MASK | LPTMR_OR_TMR5_ITR1_RMP) /*!< TMR5 ITR1 is connected to LPTMR1 output */ + +#define TMR_TMR1_TMR3_TRGO LPTMR_REMAP_MASK /*!< TMR1 ITR2 is connected to TMR3 TRGO */ +#define TMR_TMR1_LPTMR (LPTMR_REMAP_MASK | LPTMR_OR_TMR1_ITR2_RMP) /*!< TMR1 ITR2 is connected to LPTMR1 output */ +#endif /* LPTMR_OR_TMR1_ITR2_RMP && LPTMR_OR_TMR5_ITR1_RMP && LPTMR_OR_TMR5_ITR1_RMP */ +/** + * @} + */ + +/** + * @} + */ +/* End of exported constants -------------------------------------------------*/ + +/* Exported macro ------------------------------------------------------------*/ +/** @defgroup TMREx_Exported_Macros TMR Extended Exported Macros + * @{ + */ + +/** + * @} + */ +/* End of exported macro -----------------------------------------------------*/ + +/* Private macro -------------------------------------------------------------*/ +/** @defgroup TMREx_Private_Macros TMR Extended Private Macros + * @{ + */ +#if defined(SPDIFRX) +#define IS_TMR_REMAP(INSTANCE, TMR_REMAP) \ + ((((INSTANCE) == TMR2) && (((TMR_REMAP) == TMR_TMR2_TMR8_TRGO) || \ + ((TMR_REMAP) == TMR_TMR2_USBFS_SOF) || \ + ((TMR_REMAP) == TMR_TMR2_USBHS_SOF))) || \ + (((INSTANCE) == TMR5) && (((TMR_REMAP) == TMR_TMR5_GPIO) || \ + ((TMR_REMAP) == TMR_TMR5_LSI) || \ + ((TMR_REMAP) == TMR_TMR5_LSE) || \ + ((TMR_REMAP) == TMR_TMR5_RTC))) || \ + (((INSTANCE) == TMR11) && (((TMR_REMAP) == TMR_TMR11_GPIO) || \ + ((TMR_REMAP) == TMR_TMR11_SPDIFRX) || \ + ((TMR_REMAP) == TMR_TMR11_HSE)))) +#elif defined(TMR2) +#if defined(LPTMR_OR_TMR1_ITR2_RMP) && defined(LPTMR_OR_TMR5_ITR1_RMP) && defined(LPTMR_OR_TMR5_ITR1_RMP) +#define IS_TMR_REMAP(INSTANCE, TMR_REMAP) \ + ((((INSTANCE) == TMR2) && (((TMR_REMAP) == TMR_TMR2_TMR8_TRGO) || \ + ((TMR_REMAP) == TMR_TMR2_USBFS_SOF) || \ + ((TMR_REMAP) == TMR_TMR2_USBHS_SOF))) || \ + (((INSTANCE) == TMR5) && (((TMR_REMAP) == TMR_TMR5_GPIO) || \ + ((TMR_REMAP) == TMR_TMR5_LSI) || \ + ((TMR_REMAP) == TMR_TMR5_LSE) || \ + ((TMR_REMAP) == TMR_TMR5_RTC))) || \ + (((INSTANCE) == TMR11) && (((TMR_REMAP) == TMR_TMR11_GPIO) || \ + ((TMR_REMAP) == TMR_TMR11_HSE))) || \ + (((INSTANCE) == TMR1) && (((TMR_REMAP) == TMR_TMR1_TMR3_TRGO) || \ + ((TMR_REMAP) == TMR_TMR1_LPTMR))) || \ + (((INSTANCE) == TMR5) && (((TMR_REMAP) == TMR_TMR5_TMR3_TRGO) || \ + ((TMR_REMAP) == TMR_TMR5_LPTMR))) || \ + (((INSTANCE) == TMR9) && (((TMR_REMAP) == TMR_TMR9_TMR3_TRGO) || \ + ((TMR_REMAP) == TMR_TMR9_LPTMR)))) +#elif defined(TMR8) +#define IS_TMR_REMAP(INSTANCE, TMR_REMAP) \ + ((((INSTANCE) == TMR2) && (((TMR_REMAP) == TMR_TMR2_TMR8_TRGO) || \ + ((TMR_REMAP) == TMR_TMR2_USBFS_SOF) || \ + ((TMR_REMAP) == TMR_TMR2_USBHS_SOF))) || \ + (((INSTANCE) == TMR5) && (((TMR_REMAP) == TMR_TMR5_GPIO) || \ + ((TMR_REMAP) == TMR_TMR5_LSI) || \ + ((TMR_REMAP) == TMR_TMR5_LSE) || \ + ((TMR_REMAP) == TMR_TMR5_RTC))) || \ + (((INSTANCE) == TMR11) && (((TMR_REMAP) == TMR_TMR11_GPIO) || \ + ((TMR_REMAP) == TMR_TMR11_HSE)))) +#else +#define IS_TMR_REMAP(INSTANCE, TMR_REMAP) \ + ((((INSTANCE) == TMR2) && (((TMR_REMAP) == TMR_TMR2_ETH_PTP) || \ + ((TMR_REMAP) == TMR_TMR2_USBFS_SOF) || \ + ((TMR_REMAP) == TMR_TMR2_USBHS_SOF))) || \ + (((INSTANCE) == TMR5) && (((TMR_REMAP) == TMR_TMR5_GPIO) || \ + ((TMR_REMAP) == TMR_TMR5_LSI) || \ + ((TMR_REMAP) == TMR_TMR5_LSE) || \ + ((TMR_REMAP) == TMR_TMR5_RTC))) || \ + (((INSTANCE) == TMR11) && (((TMR_REMAP) == TMR_TMR11_GPIO) || \ + ((TMR_REMAP) == TMR_TMR11_HSE)))) +#endif /* LPTMR_OR_TMR1_ITR2_RMP && LPTMR_OR_TMR5_ITR1_RMP && LPTMR_OR_TMR5_ITR1_RMP */ +#else +#define IS_TMR_REMAP(INSTANCE, TMR_REMAP) \ + ((((INSTANCE) == TMR5) && (((TMR_REMAP) == TMR_TMR5_GPIO) || \ + ((TMR_REMAP) == TMR_TMR5_LSI) || \ + ((TMR_REMAP) == TMR_TMR5_LSE) || \ + ((TMR_REMAP) == TMR_TMR5_RTC))) || \ + (((INSTANCE) == TMR11) && (((TMR_REMAP) == TMR_TMR11_GPIO) || \ + ((TMR_REMAP) == TMR_TMR11_HSE)))) +#endif /* SPDIFRX */ + +/** + * @} + */ +/* End of private macro ------------------------------------------------------*/ + +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup TMREx_Exported_Functions TMR Extended Exported Functions + * @{ + */ + +/** @addtogroup TMREx_Exported_Functions_Group1 Extended Timer Hall Sensor functions + * @brief Timer Hall Sensor functions + * @{ + */ +/* Timer Hall Sensor functions **********************************************/ +DAL_StatusTypeDef DAL_TMREx_HallSensor_Init(TMR_HandleTypeDef *htim, TMR_HallSensor_InitTypeDef *sConfig); +DAL_StatusTypeDef DAL_TMREx_HallSensor_DeInit(TMR_HandleTypeDef *htim); + +void DAL_TMREx_HallSensor_MspInit(TMR_HandleTypeDef *htim); +void DAL_TMREx_HallSensor_MspDeInit(TMR_HandleTypeDef *htim); + +/* Blocking mode: Polling */ +DAL_StatusTypeDef DAL_TMREx_HallSensor_Start(TMR_HandleTypeDef *htim); +DAL_StatusTypeDef DAL_TMREx_HallSensor_Stop(TMR_HandleTypeDef *htim); +/* Non-Blocking mode: Interrupt */ +DAL_StatusTypeDef DAL_TMREx_HallSensor_Start_IT(TMR_HandleTypeDef *htim); +DAL_StatusTypeDef DAL_TMREx_HallSensor_Stop_IT(TMR_HandleTypeDef *htim); +/* Non-Blocking mode: DMA */ +DAL_StatusTypeDef DAL_TMREx_HallSensor_Start_DMA(TMR_HandleTypeDef *htim, uint32_t *pData, uint16_t Length); +DAL_StatusTypeDef DAL_TMREx_HallSensor_Stop_DMA(TMR_HandleTypeDef *htim); +/** + * @} + */ + +/** @addtogroup TMREx_Exported_Functions_Group2 Extended Timer Complementary Output Compare functions + * @brief Timer Complementary Output Compare functions + * @{ + */ +/* Timer Complementary Output Compare functions *****************************/ +/* Blocking mode: Polling */ +DAL_StatusTypeDef DAL_TMREx_OCN_Start(TMR_HandleTypeDef *htim, uint32_t Channel); +DAL_StatusTypeDef DAL_TMREx_OCN_Stop(TMR_HandleTypeDef *htim, uint32_t Channel); + +/* Non-Blocking mode: Interrupt */ +DAL_StatusTypeDef DAL_TMREx_OCN_Start_IT(TMR_HandleTypeDef *htim, uint32_t Channel); +DAL_StatusTypeDef DAL_TMREx_OCN_Stop_IT(TMR_HandleTypeDef *htim, uint32_t Channel); + +/* Non-Blocking mode: DMA */ +DAL_StatusTypeDef DAL_TMREx_OCN_Start_DMA(TMR_HandleTypeDef *htim, uint32_t Channel, uint32_t *pData, uint16_t Length); +DAL_StatusTypeDef DAL_TMREx_OCN_Stop_DMA(TMR_HandleTypeDef *htim, uint32_t Channel); +/** + * @} + */ + +/** @addtogroup TMREx_Exported_Functions_Group3 Extended Timer Complementary PWM functions + * @brief Timer Complementary PWM functions + * @{ + */ +/* Timer Complementary PWM functions ****************************************/ +/* Blocking mode: Polling */ +DAL_StatusTypeDef DAL_TMREx_PWMN_Start(TMR_HandleTypeDef *htim, uint32_t Channel); +DAL_StatusTypeDef DAL_TMREx_PWMN_Stop(TMR_HandleTypeDef *htim, uint32_t Channel); + +/* Non-Blocking mode: Interrupt */ +DAL_StatusTypeDef DAL_TMREx_PWMN_Start_IT(TMR_HandleTypeDef *htim, uint32_t Channel); +DAL_StatusTypeDef DAL_TMREx_PWMN_Stop_IT(TMR_HandleTypeDef *htim, uint32_t Channel); +/* Non-Blocking mode: DMA */ +DAL_StatusTypeDef DAL_TMREx_PWMN_Start_DMA(TMR_HandleTypeDef *htim, uint32_t Channel, uint32_t *pData, uint16_t Length); +DAL_StatusTypeDef DAL_TMREx_PWMN_Stop_DMA(TMR_HandleTypeDef *htim, uint32_t Channel); +/** + * @} + */ + +/** @addtogroup TMREx_Exported_Functions_Group4 Extended Timer Complementary One Pulse functions + * @brief Timer Complementary One Pulse functions + * @{ + */ +/* Timer Complementary One Pulse functions **********************************/ +/* Blocking mode: Polling */ +DAL_StatusTypeDef DAL_TMREx_OnePulseN_Start(TMR_HandleTypeDef *htim, uint32_t OutputChannel); +DAL_StatusTypeDef DAL_TMREx_OnePulseN_Stop(TMR_HandleTypeDef *htim, uint32_t OutputChannel); + +/* Non-Blocking mode: Interrupt */ +DAL_StatusTypeDef DAL_TMREx_OnePulseN_Start_IT(TMR_HandleTypeDef *htim, uint32_t OutputChannel); +DAL_StatusTypeDef DAL_TMREx_OnePulseN_Stop_IT(TMR_HandleTypeDef *htim, uint32_t OutputChannel); +/** + * @} + */ + +/** @addtogroup TMREx_Exported_Functions_Group5 Extended Peripheral Control functions + * @brief Peripheral Control functions + * @{ + */ +/* Extended Control functions ************************************************/ +DAL_StatusTypeDef DAL_TMREx_ConfigCommutEvent(TMR_HandleTypeDef *htim, uint32_t InputTrigger, + uint32_t CommutationSource); +DAL_StatusTypeDef DAL_TMREx_ConfigCommutEvent_IT(TMR_HandleTypeDef *htim, uint32_t InputTrigger, + uint32_t CommutationSource); +DAL_StatusTypeDef DAL_TMREx_ConfigCommutEvent_DMA(TMR_HandleTypeDef *htim, uint32_t InputTrigger, + uint32_t CommutationSource); +DAL_StatusTypeDef DAL_TMREx_MasterConfigSynchronization(TMR_HandleTypeDef *htim, + TMR_MasterConfigTypeDef *sMasterConfig); +DAL_StatusTypeDef DAL_TMREx_ConfigBreakDeadTime(TMR_HandleTypeDef *htim, + TMR_BreakDeadTimeConfigTypeDef *sBreakDeadTimeConfig); +DAL_StatusTypeDef DAL_TMREx_RemapConfig(TMR_HandleTypeDef *htim, uint32_t Remap); +/** + * @} + */ + +/** @addtogroup TMREx_Exported_Functions_Group6 Extended Callbacks functions + * @brief Extended Callbacks functions + * @{ + */ +/* Extended Callback **********************************************************/ +void DAL_TMREx_CommutCallback(TMR_HandleTypeDef *htim); +void DAL_TMREx_CommutHalfCpltCallback(TMR_HandleTypeDef *htim); +void DAL_TMREx_BreakCallback(TMR_HandleTypeDef *htim); +/** + * @} + */ + +/** @addtogroup TMREx_Exported_Functions_Group7 Extended Peripheral State functions + * @brief Extended Peripheral State functions + * @{ + */ +/* Extended Peripheral State functions ***************************************/ +DAL_TMR_StateTypeDef DAL_TMREx_HallSensor_GetState(TMR_HandleTypeDef *htim); +DAL_TMR_ChannelStateTypeDef DAL_TMREx_GetChannelNState(TMR_HandleTypeDef *htim, uint32_t ChannelN); +/** + * @} + */ + +/** + * @} + */ +/* End of exported functions -------------------------------------------------*/ + +/* Private functions----------------------------------------------------------*/ +/** @addtogroup TMREx_Private_Functions TMR Extended Private Functions + * @{ + */ +void TMREx_DMACommutationCplt(DMA_HandleTypeDef *hdma); +void TMREx_DMACommutationHalfCplt(DMA_HandleTypeDef *hdma); +/** + * @} + */ +/* End of private functions --------------------------------------------------*/ + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + + +#endif /* APM32F4xx_DAL_TMR_EX_H */ diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_uart.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_uart.h new file mode 100644 index 0000000000..df346d49f5 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_uart.h @@ -0,0 +1,908 @@ +/** + * + * @file apm32f4xx_dal_uart.h + * @brief Header file of UART DAL module. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef APM32F4xx_DAL_UART_H +#define APM32F4xx_DAL_UART_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal_def.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @addtogroup UART + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ +/** @defgroup UART_Exported_Types UART Exported Types + * @{ + */ + +/** + * @brief UART Init Structure definition + */ +typedef struct +{ + uint32_t BaudRate; /*!< This member configures the UART communication baud rate. + The baud rate is computed using the following formula: + - IntegerDivider = ((PCLKx) / (8 * (OVR8+1) * (huart->Init.BaudRate))) + - FractionalDivider = ((IntegerDivider - ((uint32_t) IntegerDivider)) * 8 * (OVR8+1)) + 0.5 + Where OVR8 is the "oversampling by 8 mode" configuration bit in the CTRL1 register. */ + + uint32_t WordLength; /*!< Specifies the number of data bits transmitted or received in a frame. + This parameter can be a value of @ref UART_Word_Length */ + + uint32_t StopBits; /*!< Specifies the number of stop bits transmitted. + This parameter can be a value of @ref UART_Stop_Bits */ + + uint32_t Parity; /*!< Specifies the parity mode. + This parameter can be a value of @ref UART_Parity + @note When parity is enabled, the computed parity is inserted + at the MSB position of the transmitted data (9th bit when + the word length is set to 9 data bits; 8th bit when the + word length is set to 8 data bits). */ + + uint32_t Mode; /*!< Specifies whether the Receive or Transmit mode is enabled or disabled. + This parameter can be a value of @ref UART_Mode */ + + uint32_t HwFlowCtl; /*!< Specifies whether the hardware flow control mode is enabled or disabled. + This parameter can be a value of @ref UART_Hardware_Flow_Control */ + + uint32_t OverSampling; /*!< Specifies whether the Over sampling 8 is enabled or disabled, to achieve higher speed (up to fPCLK/8). + This parameter can be a value of @ref UART_Over_Sampling */ +} UART_InitTypeDef; + +/** + * @brief DAL UART State structures definition + * @note DAL UART State value is a combination of 2 different substates: gState and RxState. + * - gState contains UART state information related to global Handle management + * and also information related to Tx operations. + * gState value coding follow below described bitmap : + * b7-b6 Error information + * 00 : No Error + * 01 : (Not Used) + * 10 : Timeout + * 11 : Error + * b5 Peripheral initialization status + * 0 : Reset (Peripheral not initialized) + * 1 : Init done (Peripheral initialized. DAL UART Init function already called) + * b4-b3 (not used) + * xx : Should be set to 00 + * b2 Intrinsic process state + * 0 : Ready + * 1 : Busy (Peripheral busy with some configuration or internal operations) + * b1 (not used) + * x : Should be set to 0 + * b0 Tx state + * 0 : Ready (no Tx operation ongoing) + * 1 : Busy (Tx operation ongoing) + * - RxState contains information related to Rx operations. + * RxState value coding follow below described bitmap : + * b7-b6 (not used) + * xx : Should be set to 00 + * b5 Peripheral initialization status + * 0 : Reset (Peripheral not initialized) + * 1 : Init done (Peripheral initialized) + * b4-b2 (not used) + * xxx : Should be set to 000 + * b1 Rx state + * 0 : Ready (no Rx operation ongoing) + * 1 : Busy (Rx operation ongoing) + * b0 (not used) + * x : Should be set to 0. + */ +typedef enum +{ + DAL_UART_STATE_RESET = 0x00U, /*!< Peripheral is not yet Initialized + Value is allowed for gState and RxState */ + DAL_UART_STATE_READY = 0x20U, /*!< Peripheral Initialized and ready for use + Value is allowed for gState and RxState */ + DAL_UART_STATE_BUSY = 0x24U, /*!< an internal process is ongoing + Value is allowed for gState only */ + DAL_UART_STATE_BUSY_TX = 0x21U, /*!< Data Transmission process is ongoing + Value is allowed for gState only */ + DAL_UART_STATE_BUSY_RX = 0x22U, /*!< Data Reception process is ongoing + Value is allowed for RxState only */ + DAL_UART_STATE_BUSY_TX_RX = 0x23U, /*!< Data Transmission and Reception process is ongoing + Not to be used for neither gState nor RxState. + Value is result of combination (Or) between gState and RxState values */ + DAL_UART_STATE_TIMEOUT = 0xA0U, /*!< Timeout state + Value is allowed for gState only */ + DAL_UART_STATE_ERROR = 0xE0U /*!< Error + Value is allowed for gState only */ +} DAL_UART_StateTypeDef; + +/** + * @brief DAL UART Reception type definition + * @note DAL UART Reception type value aims to identify which type of Reception is ongoing. + * It is expected to admit following values : + * DAL_UART_RECEPTION_STANDARD = 0x00U, + * DAL_UART_RECEPTION_TOIDLE = 0x01U, + */ +typedef uint32_t DAL_UART_RxTypeTypeDef; + +/** + * @brief UART handle Structure definition + */ +typedef struct __UART_HandleTypeDef +{ + USART_TypeDef *Instance; /*!< UART registers base address */ + + UART_InitTypeDef Init; /*!< UART communication parameters */ + + const uint8_t *pTxBuffPtr; /*!< Pointer to UART Tx transfer Buffer */ + + uint16_t TxXferSize; /*!< UART Tx Transfer size */ + + __IO uint16_t TxXferCount; /*!< UART Tx Transfer Counter */ + + uint8_t *pRxBuffPtr; /*!< Pointer to UART Rx transfer Buffer */ + + uint16_t RxXferSize; /*!< UART Rx Transfer size */ + + __IO uint16_t RxXferCount; /*!< UART Rx Transfer Counter */ + + __IO DAL_UART_RxTypeTypeDef ReceptionType; /*!< Type of ongoing reception */ + + DMA_HandleTypeDef *hdmatx; /*!< UART Tx DMA Handle parameters */ + + DMA_HandleTypeDef *hdmarx; /*!< UART Rx DMA Handle parameters */ + + DAL_LockTypeDef Lock; /*!< Locking object */ + + __IO DAL_UART_StateTypeDef gState; /*!< UART state information related to global Handle management + and also related to Tx operations. + This parameter can be a value of @ref DAL_UART_StateTypeDef */ + + __IO DAL_UART_StateTypeDef RxState; /*!< UART state information related to Rx operations. + This parameter can be a value of @ref DAL_UART_StateTypeDef */ + + __IO uint32_t ErrorCode; /*!< UART Error code */ + +#if (USE_DAL_UART_REGISTER_CALLBACKS == 1) + void (* TxHalfCpltCallback)(struct __UART_HandleTypeDef *huart); /*!< UART Tx Half Complete Callback */ + void (* TxCpltCallback)(struct __UART_HandleTypeDef *huart); /*!< UART Tx Complete Callback */ + void (* RxHalfCpltCallback)(struct __UART_HandleTypeDef *huart); /*!< UART Rx Half Complete Callback */ + void (* RxCpltCallback)(struct __UART_HandleTypeDef *huart); /*!< UART Rx Complete Callback */ + void (* ErrorCallback)(struct __UART_HandleTypeDef *huart); /*!< UART Error Callback */ + void (* AbortCpltCallback)(struct __UART_HandleTypeDef *huart); /*!< UART Abort Complete Callback */ + void (* AbortTransmitCpltCallback)(struct __UART_HandleTypeDef *huart); /*!< UART Abort Transmit Complete Callback */ + void (* AbortReceiveCpltCallback)(struct __UART_HandleTypeDef *huart); /*!< UART Abort Receive Complete Callback */ + void (* WakeupCallback)(struct __UART_HandleTypeDef *huart); /*!< UART Wakeup Callback */ + void (* RxEventCallback)(struct __UART_HandleTypeDef *huart, uint16_t Pos); /*!< UART Reception Event Callback */ + + void (* MspInitCallback)(struct __UART_HandleTypeDef *huart); /*!< UART Msp Init callback */ + void (* MspDeInitCallback)(struct __UART_HandleTypeDef *huart); /*!< UART Msp DeInit callback */ +#endif /* USE_DAL_UART_REGISTER_CALLBACKS */ + +} UART_HandleTypeDef; + +#if (USE_DAL_UART_REGISTER_CALLBACKS == 1) +/** + * @brief DAL UART Callback ID enumeration definition + */ +typedef enum +{ + DAL_UART_TX_HALFCOMPLETE_CB_ID = 0x00U, /*!< UART Tx Half Complete Callback ID */ + DAL_UART_TX_COMPLETE_CB_ID = 0x01U, /*!< UART Tx Complete Callback ID */ + DAL_UART_RX_HALFCOMPLETE_CB_ID = 0x02U, /*!< UART Rx Half Complete Callback ID */ + DAL_UART_RX_COMPLETE_CB_ID = 0x03U, /*!< UART Rx Complete Callback ID */ + DAL_UART_ERROR_CB_ID = 0x04U, /*!< UART Error Callback ID */ + DAL_UART_ABORT_COMPLETE_CB_ID = 0x05U, /*!< UART Abort Complete Callback ID */ + DAL_UART_ABORT_TRANSMIT_COMPLETE_CB_ID = 0x06U, /*!< UART Abort Transmit Complete Callback ID */ + DAL_UART_ABORT_RECEIVE_COMPLETE_CB_ID = 0x07U, /*!< UART Abort Receive Complete Callback ID */ + DAL_UART_WAKEUP_CB_ID = 0x08U, /*!< UART Wakeup Callback ID */ + + DAL_UART_MSPINIT_CB_ID = 0x0BU, /*!< UART MspInit callback ID */ + DAL_UART_MSPDEINIT_CB_ID = 0x0CU /*!< UART MspDeInit callback ID */ + +} DAL_UART_CallbackIDTypeDef; + +/** + * @brief DAL UART Callback pointer definition + */ +typedef void (*pUART_CallbackTypeDef)(UART_HandleTypeDef *huart); /*!< pointer to an UART callback function */ +typedef void (*pUART_RxEventCallbackTypeDef)(struct __UART_HandleTypeDef *huart, uint16_t Pos); /*!< pointer to a UART Rx Event specific callback function */ + +#endif /* USE_DAL_UART_REGISTER_CALLBACKS */ + +/** + * @} + */ + +/* Exported constants --------------------------------------------------------*/ +/** @defgroup UART_Exported_Constants UART Exported Constants + * @{ + */ + +/** @defgroup UART_Error_Code UART Error Code + * @{ + */ +#define DAL_UART_ERROR_NONE 0x00000000U /*!< No error */ +#define DAL_UART_ERROR_PE 0x00000001U /*!< Parity error */ +#define DAL_UART_ERROR_NE 0x00000002U /*!< Noise error */ +#define DAL_UART_ERROR_FE 0x00000004U /*!< Frame error */ +#define DAL_UART_ERROR_ORE 0x00000008U /*!< Overrun error */ +#define DAL_UART_ERROR_DMA 0x00000010U /*!< DMA transfer error */ +#if (USE_DAL_UART_REGISTER_CALLBACKS == 1) +#define DAL_UART_ERROR_INVALID_CALLBACK 0x00000020U /*!< Invalid Callback error */ +#endif /* USE_DAL_UART_REGISTER_CALLBACKS */ +/** + * @} + */ + +/** @defgroup UART_Word_Length UART Word Length + * @{ + */ +#define UART_WORDLENGTH_8B 0x00000000U +#define UART_WORDLENGTH_9B ((uint32_t)USART_CTRL1_DBLCFG) +/** + * @} + */ + +/** @defgroup UART_Stop_Bits UART Number of Stop Bits + * @{ + */ +#define UART_STOPBITS_1 0x00000000U +#define UART_STOPBITS_2 ((uint32_t)USART_CTRL2_STOPCFG_1) +/** + * @} + */ + +/** @defgroup UART_Parity UART Parity + * @{ + */ +#define UART_PARITY_NONE 0x00000000U +#define UART_PARITY_EVEN ((uint32_t)USART_CTRL1_PCEN) +#define UART_PARITY_ODD ((uint32_t)(USART_CTRL1_PCEN | USART_CTRL1_PCFG)) +/** + * @} + */ + +/** @defgroup UART_Hardware_Flow_Control UART Hardware Flow Control + * @{ + */ +#define UART_HWCONTROL_NONE 0x00000000U +#define UART_HWCONTROL_RTS ((uint32_t)USART_CTRL3_RTSEN) +#define UART_HWCONTROL_CTS ((uint32_t)USART_CTRL3_CTSEN) +#define UART_HWCONTROL_RTS_CTS ((uint32_t)(USART_CTRL3_RTSEN | USART_CTRL3_CTSEN)) +/** + * @} + */ + +/** @defgroup UART_Mode UART Transfer Mode + * @{ + */ +#define UART_MODE_RX ((uint32_t)USART_CTRL1_RXEN) +#define UART_MODE_TX ((uint32_t)USART_CTRL1_TXEN) +#define UART_MODE_TX_RX ((uint32_t)(USART_CTRL1_TXEN | USART_CTRL1_RXEN)) +/** + * @} + */ + +/** @defgroup UART_State UART State + * @{ + */ +#define UART_STATE_DISABLE 0x00000000U +#define UART_STATE_ENABLE ((uint32_t)USART_CTRL1_UEN) +/** + * @} + */ + +/** @defgroup UART_Over_Sampling UART Over Sampling + * @{ + */ +#define UART_OVERSAMPLING_16 0x00000000U +#define UART_OVERSAMPLING_8 ((uint32_t)USART_CTRL1_OSMCFG) +/** + * @} + */ + +/** @defgroup UART_LIN_Break_Detection_Length UART LIN Break Detection Length + * @{ + */ +#define UART_LINBREAKDETECTLENGTH_10B 0x00000000U +#define UART_LINBREAKDETECTLENGTH_11B ((uint32_t)USART_CTRL2_LBDLCFG) +/** + * @} + */ + +/** @defgroup UART_WakeUp_functions UART Wakeup Functions + * @{ + */ +#define UART_WAKEUPMETHOD_IDLELINE 0x00000000U +#define UART_WAKEUPMETHOD_ADDRESSMARK ((uint32_t)USART_CTRL1_WUPMCFG) +/** + * @} + */ + +/** @defgroup UART_Flags UART FLags + * Elements values convention: 0xXXXX + * - 0xXXXX : Flag mask in the SR register + * @{ + */ +#define UART_FLAG_CTS ((uint32_t)USART_STS_CTSFLG) +#define UART_FLAG_LBD ((uint32_t)USART_STS_LBDFLG) +#define UART_FLAG_TXE ((uint32_t)USART_STS_TXBEFLG) +#define UART_FLAG_TC ((uint32_t)USART_STS_TXCFLG) +#define UART_FLAG_RXNE ((uint32_t)USART_STS_RXBNEFLG) +#define UART_FLAG_IDLE ((uint32_t)USART_STS_IDLEFLG) +#define UART_FLAG_ORE ((uint32_t)USART_STS_OVREFLG) +#define UART_FLAG_NE ((uint32_t)USART_STS_NEFLG) +#define UART_FLAG_FE ((uint32_t)USART_STS_FEFLG) +#define UART_FLAG_PE ((uint32_t)USART_STS_PEFLG) +/** + * @} + */ + +/** @defgroup UART_Interrupt_definition UART Interrupt Definitions + * Elements values convention: 0xY000XXXX + * - XXXX : Interrupt mask (16 bits) in the Y register + * - Y : Interrupt source register (2bits) + * - 0001: CTRL1 register + * - 0010: CTRL2 register + * - 0011: CTRL3 register + * @{ + */ + +#define UART_IT_PE ((uint32_t)(UART_CTRL1_REG_INDEX << 28U | USART_CTRL1_PEIEN)) +#define UART_IT_TXE ((uint32_t)(UART_CTRL1_REG_INDEX << 28U | USART_CTRL1_TXBEIEN)) +#define UART_IT_TC ((uint32_t)(UART_CTRL1_REG_INDEX << 28U | USART_CTRL1_TXCIEN)) +#define UART_IT_RXNE ((uint32_t)(UART_CTRL1_REG_INDEX << 28U | USART_CTRL1_RXBNEIEN)) +#define UART_IT_IDLE ((uint32_t)(UART_CTRL1_REG_INDEX << 28U | USART_CTRL1_IDLEIEN)) + +#define UART_IT_LBD ((uint32_t)(UART_CTRL2_REG_INDEX << 28U | USART_CTRL2_LBDIEN)) + +#define UART_IT_CTS ((uint32_t)(UART_CTRL3_REG_INDEX << 28U | USART_CTRL3_CTSIEN)) +#define UART_IT_ERR ((uint32_t)(UART_CTRL3_REG_INDEX << 28U | USART_CTRL3_ERRIEN)) +/** + * @} + */ + +/** @defgroup UART_RECEPTION_TYPE_Values UART Reception type values + * @{ + */ +#define DAL_UART_RECEPTION_STANDARD (0x00000000U) /*!< Standard reception */ +#define DAL_UART_RECEPTION_TOIDLE (0x00000001U) /*!< Reception till completion or IDLE event */ +/** + * @} + */ + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ +/** @defgroup UART_Exported_Macros UART Exported Macros + * @{ + */ + +/** @brief Reset UART handle gstate & RxState + * @param __HANDLE__ specifies the UART Handle. + * UART Handle selects the USARTx or UARTy peripheral + * (USART,UART availability and x,y values depending on device). + * @retval None + */ +#if (USE_DAL_UART_REGISTER_CALLBACKS == 1) +#define __DAL_UART_RESET_HANDLE_STATE(__HANDLE__) do{ \ + (__HANDLE__)->gState = DAL_UART_STATE_RESET; \ + (__HANDLE__)->RxState = DAL_UART_STATE_RESET; \ + (__HANDLE__)->MspInitCallback = NULL; \ + (__HANDLE__)->MspDeInitCallback = NULL; \ + } while(0U) +#else +#define __DAL_UART_RESET_HANDLE_STATE(__HANDLE__) do{ \ + (__HANDLE__)->gState = DAL_UART_STATE_RESET; \ + (__HANDLE__)->RxState = DAL_UART_STATE_RESET; \ + } while(0U) +#endif /*USE_DAL_UART_REGISTER_CALLBACKS */ + +/** @brief Flushes the UART DATA register + * @param __HANDLE__ specifies the UART Handle. + * UART Handle selects the USARTx or UARTy peripheral + * (USART,UART availability and x,y values depending on device). + */ +#define __DAL_UART_FLUSH_DRREGISTER(__HANDLE__) ((__HANDLE__)->Instance->DATA) + +/** @brief Checks whether the specified UART flag is set or not. + * @param __HANDLE__ specifies the UART Handle. + * UART Handle selects the USARTx or UARTy peripheral + * (USART,UART availability and x,y values depending on device). + * @param __FLAG__ specifies the flag to check. + * This parameter can be one of the following values: + * @arg UART_FLAG_CTS: CTS Change flag (not available for UART4 and UART5) + * @arg UART_FLAG_LBD: LIN Break detection flag + * @arg UART_FLAG_TXE: Transmit data register empty flag + * @arg UART_FLAG_TC: Transmission Complete flag + * @arg UART_FLAG_RXNE: Receive data register not empty flag + * @arg UART_FLAG_IDLE: Idle Line detection flag + * @arg UART_FLAG_ORE: Overrun Error flag + * @arg UART_FLAG_NE: Noise Error flag + * @arg UART_FLAG_FE: Framing Error flag + * @arg UART_FLAG_PE: Parity Error flag + * @retval The new state of __FLAG__ (TRUE or FALSE). + */ +#define __DAL_UART_GET_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->STS & (__FLAG__)) == (__FLAG__)) + +/** @brief Clears the specified UART pending flag. + * @param __HANDLE__ specifies the UART Handle. + * UART Handle selects the USARTx or UARTy peripheral + * (USART,UART availability and x,y values depending on device). + * @param __FLAG__ specifies the flag to check. + * This parameter can be any combination of the following values: + * @arg UART_FLAG_CTS: CTS Change flag (not available for UART4 and UART5). + * @arg UART_FLAG_LBD: LIN Break detection flag. + * @arg UART_FLAG_TC: Transmission Complete flag. + * @arg UART_FLAG_RXNE: Receive data register not empty flag. + * + * @note PE (Parity error), FE (Framing error), NE (Noise error), ORE (Overrun + * error) and IDLE (Idle line detected) flags are cleared by software + * sequence: a read operation to USART_STS register followed by a read + * operation to USART_DATA register. + * @note RXNE flag can be also cleared by a read to the USART_DATA register. + * @note TC flag can be also cleared by software sequence: a read operation to + * USART_STS register followed by a write operation to USART_DATA register. + * @note TXE flag is cleared only by a write to the USART_DATA register. + * + * @retval None + */ +#define __DAL_UART_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->STS = ~(__FLAG__)) + +/** @brief Clears the UART PE pending flag. + * @param __HANDLE__ specifies the UART Handle. + * UART Handle selects the USARTx or UARTy peripheral + * (USART,UART availability and x,y values depending on device). + * @retval None + */ +#define __DAL_UART_CLEAR_PEFLAG(__HANDLE__) \ + do{ \ + __IO uint32_t tmpreg = 0x00U; \ + tmpreg = (__HANDLE__)->Instance->STS; \ + tmpreg = (__HANDLE__)->Instance->DATA; \ + UNUSED(tmpreg); \ + } while(0U) + +/** @brief Clears the UART FE pending flag. + * @param __HANDLE__ specifies the UART Handle. + * UART Handle selects the USARTx or UARTy peripheral + * (USART,UART availability and x,y values depending on device). + * @retval None + */ +#define __DAL_UART_CLEAR_FEFLAG(__HANDLE__) __DAL_UART_CLEAR_PEFLAG(__HANDLE__) + +/** @brief Clears the UART NE pending flag. + * @param __HANDLE__ specifies the UART Handle. + * UART Handle selects the USARTx or UARTy peripheral + * (USART,UART availability and x,y values depending on device). + * @retval None + */ +#define __DAL_UART_CLEAR_NEFLAG(__HANDLE__) __DAL_UART_CLEAR_PEFLAG(__HANDLE__) + +/** @brief Clears the UART ORE pending flag. + * @param __HANDLE__ specifies the UART Handle. + * UART Handle selects the USARTx or UARTy peripheral + * (USART,UART availability and x,y values depending on device). + * @retval None + */ +#define __DAL_UART_CLEAR_OREFLAG(__HANDLE__) __DAL_UART_CLEAR_PEFLAG(__HANDLE__) + +/** @brief Clears the UART IDLE pending flag. + * @param __HANDLE__ specifies the UART Handle. + * UART Handle selects the USARTx or UARTy peripheral + * (USART,UART availability and x,y values depending on device). + * @retval None + */ +#define __DAL_UART_CLEAR_IDLEFLAG(__HANDLE__) __DAL_UART_CLEAR_PEFLAG(__HANDLE__) + +/** @brief Enable the specified UART interrupt. + * @param __HANDLE__ specifies the UART Handle. + * UART Handle selects the USARTx or UARTy peripheral + * (USART,UART availability and x,y values depending on device). + * @param __INTERRUPT__ specifies the UART interrupt source to enable. + * This parameter can be one of the following values: + * @arg UART_IT_CTS: CTS change interrupt + * @arg UART_IT_LBD: LIN Break detection interrupt + * @arg UART_IT_TXE: Transmit Data Register empty interrupt + * @arg UART_IT_TC: Transmission complete interrupt + * @arg UART_IT_RXNE: Receive Data register not empty interrupt + * @arg UART_IT_IDLE: Idle line detection interrupt + * @arg UART_IT_PE: Parity Error interrupt + * @arg UART_IT_ERR: Error interrupt(Frame error, noise error, overrun error) + * @retval None + */ +#define __DAL_UART_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((((__INTERRUPT__) >> 28U) == UART_CTRL1_REG_INDEX)? ((__HANDLE__)->Instance->CTRL1 |= ((__INTERRUPT__) & UART_IT_MASK)): \ + (((__INTERRUPT__) >> 28U) == UART_CTRL2_REG_INDEX)? ((__HANDLE__)->Instance->CTRL2 |= ((__INTERRUPT__) & UART_IT_MASK)): \ + ((__HANDLE__)->Instance->CTRL3 |= ((__INTERRUPT__) & UART_IT_MASK))) + +/** @brief Disable the specified UART interrupt. + * @param __HANDLE__ specifies the UART Handle. + * UART Handle selects the USARTx or UARTy peripheral + * (USART,UART availability and x,y values depending on device). + * @param __INTERRUPT__ specifies the UART interrupt source to disable. + * This parameter can be one of the following values: + * @arg UART_IT_CTS: CTS change interrupt + * @arg UART_IT_LBD: LIN Break detection interrupt + * @arg UART_IT_TXE: Transmit Data Register empty interrupt + * @arg UART_IT_TC: Transmission complete interrupt + * @arg UART_IT_RXNE: Receive Data register not empty interrupt + * @arg UART_IT_IDLE: Idle line detection interrupt + * @arg UART_IT_PE: Parity Error interrupt + * @arg UART_IT_ERR: Error interrupt(Frame error, noise error, overrun error) + * @retval None + */ +#define __DAL_UART_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((((__INTERRUPT__) >> 28U) == UART_CTRL1_REG_INDEX)? ((__HANDLE__)->Instance->CTRL1 &= ~((__INTERRUPT__) & UART_IT_MASK)): \ + (((__INTERRUPT__) >> 28U) == UART_CTRL2_REG_INDEX)? ((__HANDLE__)->Instance->CTRL2 &= ~((__INTERRUPT__) & UART_IT_MASK)): \ + ((__HANDLE__)->Instance->CTRL3 &= ~ ((__INTERRUPT__) & UART_IT_MASK))) + +/** @brief Checks whether the specified UART interrupt source is enabled or not. + * @param __HANDLE__ specifies the UART Handle. + * UART Handle selects the USARTx or UARTy peripheral + * (USART,UART availability and x,y values depending on device). + * @param __IT__ specifies the UART interrupt source to check. + * This parameter can be one of the following values: + * @arg UART_IT_CTS: CTS change interrupt (not available for UART4 and UART5) + * @arg UART_IT_LBD: LIN Break detection interrupt + * @arg UART_IT_TXE: Transmit Data Register empty interrupt + * @arg UART_IT_TC: Transmission complete interrupt + * @arg UART_IT_RXNE: Receive Data register not empty interrupt + * @arg UART_IT_IDLE: Idle line detection interrupt + * @arg UART_IT_ERR: Error interrupt + * @retval The new state of __IT__ (TRUE or FALSE). + */ +#define __DAL_UART_GET_IT_SOURCE(__HANDLE__, __IT__) (((((__IT__) >> 28U) == UART_CTRL1_REG_INDEX)? (__HANDLE__)->Instance->CTRL1:(((((uint32_t)(__IT__)) >> 28U) == UART_CTRL2_REG_INDEX)? \ + (__HANDLE__)->Instance->CTRL2 : (__HANDLE__)->Instance->CTRL3)) & (((uint32_t)(__IT__)) & UART_IT_MASK)) + +/** @brief Enable CTS flow control + * @note This macro allows to enable CTS hardware flow control for a given UART instance, + * without need to call DAL_UART_Init() function. + * As involving direct access to UART registers, usage of this macro should be fully endorsed by user. + * @note As macro is expected to be used for modifying CTS Hw flow control feature activation, without need + * for USART instance Deinit/Init, following conditions for macro call should be fulfilled : + * - UART instance should have already been initialised (through call of DAL_UART_Init() ) + * - macro could only be called when corresponding UART instance is disabled (i.e __DAL_UART_DISABLE(__HANDLE__)) + * and should be followed by an Enable macro (i.e __DAL_UART_ENABLE(__HANDLE__)). + * @param __HANDLE__ specifies the UART Handle. + * The Handle Instance can be any USARTx (supporting the HW Flow control feature). + * It is used to select the USART peripheral (USART availability and x value depending on device). + * @retval None + */ +#define __DAL_UART_HWCONTROL_CTS_ENABLE(__HANDLE__) \ + do{ \ + ATOMIC_SET_BIT((__HANDLE__)->Instance->CTRL3, USART_CTRL3_CTSEN); \ + (__HANDLE__)->Init.HwFlowCtl |= USART_CTRL3_CTSEN; \ + } while(0U) + +/** @brief Disable CTS flow control + * @note This macro allows to disable CTS hardware flow control for a given UART instance, + * without need to call DAL_UART_Init() function. + * As involving direct access to UART registers, usage of this macro should be fully endorsed by user. + * @note As macro is expected to be used for modifying CTS Hw flow control feature activation, without need + * for USART instance Deinit/Init, following conditions for macro call should be fulfilled : + * - UART instance should have already been initialised (through call of DAL_UART_Init() ) + * - macro could only be called when corresponding UART instance is disabled (i.e __DAL_UART_DISABLE(__HANDLE__)) + * and should be followed by an Enable macro (i.e __DAL_UART_ENABLE(__HANDLE__)). + * @param __HANDLE__ specifies the UART Handle. + * The Handle Instance can be any USARTx (supporting the HW Flow control feature). + * It is used to select the USART peripheral (USART availability and x value depending on device). + * @retval None + */ +#define __DAL_UART_HWCONTROL_CTS_DISABLE(__HANDLE__) \ + do{ \ + ATOMIC_CLEAR_BIT((__HANDLE__)->Instance->CTRL3, USART_CTRL3_CTSEN); \ + (__HANDLE__)->Init.HwFlowCtl &= ~(USART_CTRL3_CTSEN); \ + } while(0U) + +/** @brief Enable RTS flow control + * This macro allows to enable RTS hardware flow control for a given UART instance, + * without need to call DAL_UART_Init() function. + * As involving direct access to UART registers, usage of this macro should be fully endorsed by user. + * @note As macro is expected to be used for modifying RTS Hw flow control feature activation, without need + * for USART instance Deinit/Init, following conditions for macro call should be fulfilled : + * - UART instance should have already been initialised (through call of DAL_UART_Init() ) + * - macro could only be called when corresponding UART instance is disabled (i.e __DAL_UART_DISABLE(__HANDLE__)) + * and should be followed by an Enable macro (i.e __DAL_UART_ENABLE(__HANDLE__)). + * @param __HANDLE__ specifies the UART Handle. + * The Handle Instance can be any USARTx (supporting the HW Flow control feature). + * It is used to select the USART peripheral (USART availability and x value depending on device). + * @retval None + */ +#define __DAL_UART_HWCONTROL_RTS_ENABLE(__HANDLE__) \ + do{ \ + ATOMIC_SET_BIT((__HANDLE__)->Instance->CTRL3, USART_CTRL3_RTSEN); \ + (__HANDLE__)->Init.HwFlowCtl |= USART_CTRL3_RTSEN; \ + } while(0U) + +/** @brief Disable RTS flow control + * This macro allows to disable RTS hardware flow control for a given UART instance, + * without need to call DAL_UART_Init() function. + * As involving direct access to UART registers, usage of this macro should be fully endorsed by user. + * @note As macro is expected to be used for modifying RTS Hw flow control feature activation, without need + * for USART instance Deinit/Init, following conditions for macro call should be fulfilled : + * - UART instance should have already been initialised (through call of DAL_UART_Init() ) + * - macro could only be called when corresponding UART instance is disabled (i.e __DAL_UART_DISABLE(__HANDLE__)) + * and should be followed by an Enable macro (i.e __DAL_UART_ENABLE(__HANDLE__)). + * @param __HANDLE__ specifies the UART Handle. + * The Handle Instance can be any USARTx (supporting the HW Flow control feature). + * It is used to select the USART peripheral (USART availability and x value depending on device). + * @retval None + */ +#define __DAL_UART_HWCONTROL_RTS_DISABLE(__HANDLE__) \ + do{ \ + ATOMIC_CLEAR_BIT((__HANDLE__)->Instance->CTRL3, USART_CTRL3_RTSEN);\ + (__HANDLE__)->Init.HwFlowCtl &= ~(USART_CTRL3_RTSEN); \ + } while(0U) + +/** @brief Macro to enable the UART's one bit sample method + * @param __HANDLE__ specifies the UART Handle. + * @retval None + */ +#define __DAL_UART_ONE_BIT_SAMPLE_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CTRL3|= USART_CTRL3_SAMCFG) + +/** @brief Macro to disable the UART's one bit sample method + * @param __HANDLE__ specifies the UART Handle. + * @retval None + */ +#define __DAL_UART_ONE_BIT_SAMPLE_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CTRL3\ + &= (uint16_t)~((uint16_t)USART_CTRL3_SAMCFG)) + +/** @brief Enable UART + * @param __HANDLE__ specifies the UART Handle. + * @retval None + */ +#define __DAL_UART_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CTRL1 |= USART_CTRL1_UEN) + +/** @brief Disable UART + * @param __HANDLE__ specifies the UART Handle. + * @retval None + */ +#define __DAL_UART_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CTRL1 &= ~USART_CTRL1_UEN) +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup UART_Exported_Functions + * @{ + */ + +/** @addtogroup UART_Exported_Functions_Group1 Initialization and de-initialization functions + * @{ + */ + +/* Initialization/de-initialization functions **********************************/ +DAL_StatusTypeDef DAL_UART_Init(UART_HandleTypeDef *huart); +DAL_StatusTypeDef DAL_HalfDuplex_Init(UART_HandleTypeDef *huart); +DAL_StatusTypeDef DAL_LIN_Init(UART_HandleTypeDef *huart, uint32_t BreakDetectLength); +DAL_StatusTypeDef DAL_MultiProcessor_Init(UART_HandleTypeDef *huart, uint8_t Address, uint32_t WakeUpMethod); +DAL_StatusTypeDef DAL_UART_DeInit(UART_HandleTypeDef *huart); +void DAL_UART_MspInit(UART_HandleTypeDef *huart); +void DAL_UART_MspDeInit(UART_HandleTypeDef *huart); + +/* Callbacks Register/UnRegister functions ***********************************/ +#if (USE_DAL_UART_REGISTER_CALLBACKS == 1) +DAL_StatusTypeDef DAL_UART_RegisterCallback(UART_HandleTypeDef *huart, DAL_UART_CallbackIDTypeDef CallbackID, + pUART_CallbackTypeDef pCallback); +DAL_StatusTypeDef DAL_UART_UnRegisterCallback(UART_HandleTypeDef *huart, DAL_UART_CallbackIDTypeDef CallbackID); + +DAL_StatusTypeDef DAL_UART_RegisterRxEventCallback(UART_HandleTypeDef *huart, pUART_RxEventCallbackTypeDef pCallback); +DAL_StatusTypeDef DAL_UART_UnRegisterRxEventCallback(UART_HandleTypeDef *huart); +#endif /* USE_DAL_UART_REGISTER_CALLBACKS */ + +/** + * @} + */ + +/** @addtogroup UART_Exported_Functions_Group2 IO operation functions + * @{ + */ + +/* IO operation functions *******************************************************/ +DAL_StatusTypeDef DAL_UART_Transmit(UART_HandleTypeDef *huart, const uint8_t *pData, uint16_t Size, uint32_t Timeout); +DAL_StatusTypeDef DAL_UART_Receive(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size, uint32_t Timeout); +DAL_StatusTypeDef DAL_UART_Transmit_IT(UART_HandleTypeDef *huart, const uint8_t *pData, uint16_t Size); +DAL_StatusTypeDef DAL_UART_Receive_IT(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size); +DAL_StatusTypeDef DAL_UART_Transmit_DMA(UART_HandleTypeDef *huart, const uint8_t *pData, uint16_t Size); +DAL_StatusTypeDef DAL_UART_Receive_DMA(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size); +DAL_StatusTypeDef DAL_UART_DMAPause(UART_HandleTypeDef *huart); +DAL_StatusTypeDef DAL_UART_DMAResume(UART_HandleTypeDef *huart); +DAL_StatusTypeDef DAL_UART_DMAStop(UART_HandleTypeDef *huart); + +DAL_StatusTypeDef DAL_UARTEx_ReceiveToIdle(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size, uint16_t *RxLen, + uint32_t Timeout); +DAL_StatusTypeDef DAL_UARTEx_ReceiveToIdle_IT(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size); +DAL_StatusTypeDef DAL_UARTEx_ReceiveToIdle_DMA(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size); + +/* Transfer Abort functions */ +DAL_StatusTypeDef DAL_UART_Abort(UART_HandleTypeDef *huart); +DAL_StatusTypeDef DAL_UART_AbortTransmit(UART_HandleTypeDef *huart); +DAL_StatusTypeDef DAL_UART_AbortReceive(UART_HandleTypeDef *huart); +DAL_StatusTypeDef DAL_UART_Abort_IT(UART_HandleTypeDef *huart); +DAL_StatusTypeDef DAL_UART_AbortTransmit_IT(UART_HandleTypeDef *huart); +DAL_StatusTypeDef DAL_UART_AbortReceive_IT(UART_HandleTypeDef *huart); + +void DAL_UART_IRQHandler(UART_HandleTypeDef *huart); +void DAL_UART_TxCpltCallback(UART_HandleTypeDef *huart); +void DAL_UART_TxHalfCpltCallback(UART_HandleTypeDef *huart); +void DAL_UART_RxCpltCallback(UART_HandleTypeDef *huart); +void DAL_UART_RxHalfCpltCallback(UART_HandleTypeDef *huart); +void DAL_UART_ErrorCallback(UART_HandleTypeDef *huart); +void DAL_UART_AbortCpltCallback(UART_HandleTypeDef *huart); +void DAL_UART_AbortTransmitCpltCallback(UART_HandleTypeDef *huart); +void DAL_UART_AbortReceiveCpltCallback(UART_HandleTypeDef *huart); + +void DAL_UARTEx_RxEventCallback(UART_HandleTypeDef *huart, uint16_t Size); + +/** + * @} + */ + +/** @addtogroup UART_Exported_Functions_Group3 + * @{ + */ +/* Peripheral Control functions ************************************************/ +DAL_StatusTypeDef DAL_LIN_SendBreak(UART_HandleTypeDef *huart); +DAL_StatusTypeDef DAL_MultiProcessor_EnterMuteMode(UART_HandleTypeDef *huart); +DAL_StatusTypeDef DAL_MultiProcessor_ExitMuteMode(UART_HandleTypeDef *huart); +DAL_StatusTypeDef DAL_HalfDuplex_EnableTransmitter(UART_HandleTypeDef *huart); +DAL_StatusTypeDef DAL_HalfDuplex_EnableReceiver(UART_HandleTypeDef *huart); +/** + * @} + */ + +/** @addtogroup UART_Exported_Functions_Group4 + * @{ + */ +/* Peripheral State functions **************************************************/ +DAL_UART_StateTypeDef DAL_UART_GetState(UART_HandleTypeDef *huart); +uint32_t DAL_UART_GetError(UART_HandleTypeDef *huart); +/** + * @} + */ + +/** + * @} + */ +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/** @defgroup UART_Private_Constants UART Private Constants + * @{ + */ +/** @brief UART interruptions flag mask + * + */ +#define UART_IT_MASK 0x0000FFFFU + +#define UART_CTRL1_REG_INDEX 1U +#define UART_CTRL2_REG_INDEX 2U +#define UART_CTRL3_REG_INDEX 3U +/** + * @} + */ + +/* Private macros ------------------------------------------------------------*/ +/** @defgroup UART_Private_Macros UART Private Macros + * @{ + */ +#define IS_UART_WORD_LENGTH(LENGTH) (((LENGTH) == UART_WORDLENGTH_8B) || \ + ((LENGTH) == UART_WORDLENGTH_9B)) +#define IS_UART_LIN_WORD_LENGTH(LENGTH) (((LENGTH) == UART_WORDLENGTH_8B)) +#define IS_UART_STOPBITS(STOPBITS) (((STOPBITS) == UART_STOPBITS_1) || \ + ((STOPBITS) == UART_STOPBITS_2)) +#define IS_UART_PARITY(PARITY) (((PARITY) == UART_PARITY_NONE) || \ + ((PARITY) == UART_PARITY_EVEN) || \ + ((PARITY) == UART_PARITY_ODD)) +#define IS_UART_HARDWARE_FLOW_CONTROL(CONTROL)\ + (((CONTROL) == UART_HWCONTROL_NONE) || \ + ((CONTROL) == UART_HWCONTROL_RTS) || \ + ((CONTROL) == UART_HWCONTROL_CTS) || \ + ((CONTROL) == UART_HWCONTROL_RTS_CTS)) +#define IS_UART_MODE(MODE) ((((MODE) & 0x0000FFF3U) == 0x00U) && ((MODE) != 0x00U)) +#define IS_UART_STATE(STATE) (((STATE) == UART_STATE_DISABLE) || \ + ((STATE) == UART_STATE_ENABLE)) +#define IS_UART_OVERSAMPLING(SAMPLING) (((SAMPLING) == UART_OVERSAMPLING_16) || \ + ((SAMPLING) == UART_OVERSAMPLING_8)) +#define IS_UART_LIN_OVERSAMPLING(SAMPLING) (((SAMPLING) == UART_OVERSAMPLING_16)) +#define IS_UART_LIN_BREAK_DETECT_LENGTH(LENGTH) (((LENGTH) == UART_LINBREAKDETECTLENGTH_10B) || \ + ((LENGTH) == UART_LINBREAKDETECTLENGTH_11B)) +#define IS_UART_WAKEUPMETHOD(WAKEUP) (((WAKEUP) == UART_WAKEUPMETHOD_IDLELINE) || \ + ((WAKEUP) == UART_WAKEUPMETHOD_ADDRESSMARK)) +#define IS_UART_BAUDRATE(BAUDRATE) ((BAUDRATE) <= 10500000U) +#define IS_UART_ADDRESS(ADDRESS) ((ADDRESS) <= 0x0FU) + +#define UART_DIV_SAMPLING16(_PCLK_, _BAUD_) ((uint32_t)((((uint64_t)(_PCLK_))*25U)/(4U*((uint64_t)(_BAUD_))))) +#define UART_DIVMANT_SAMPLING16(_PCLK_, _BAUD_) (UART_DIV_SAMPLING16((_PCLK_), (_BAUD_))/100U) +#define UART_DIVFRAQ_SAMPLING16(_PCLK_, _BAUD_) ((((UART_DIV_SAMPLING16((_PCLK_), (_BAUD_)) - (UART_DIVMANT_SAMPLING16((_PCLK_), (_BAUD_)) * 100U)) * 16U)\ + + 50U) / 100U) +/* UART BR = mantissa + overflow + fraction + = (UART DIVMANT << 4) + (UART DIVFRAQ & 0xF0) + (UART DIVFRAQ & 0x0FU) */ +#define UART_BR_SAMPLING16(_PCLK_, _BAUD_) ((UART_DIVMANT_SAMPLING16((_PCLK_), (_BAUD_)) << 4U) + \ + (UART_DIVFRAQ_SAMPLING16((_PCLK_), (_BAUD_)) & 0xF0U) + \ + (UART_DIVFRAQ_SAMPLING16((_PCLK_), (_BAUD_)) & 0x0FU)) + +#define UART_DIV_SAMPLING8(_PCLK_, _BAUD_) ((uint32_t)((((uint64_t)(_PCLK_))*25U)/(2U*((uint64_t)(_BAUD_))))) +#define UART_DIVMANT_SAMPLING8(_PCLK_, _BAUD_) (UART_DIV_SAMPLING8((_PCLK_), (_BAUD_))/100U) +#define UART_DIVFRAQ_SAMPLING8(_PCLK_, _BAUD_) ((((UART_DIV_SAMPLING8((_PCLK_), (_BAUD_)) - (UART_DIVMANT_SAMPLING8((_PCLK_), (_BAUD_)) * 100U)) * 8U)\ + + 50U) / 100U) +/* UART BR = mantissa + overflow + fraction + = (UART DIVMANT << 4) + ((UART DIVFRAQ & 0xF8) << 1) + (UART DIVFRAQ & 0x07U) */ +#define UART_BR_SAMPLING8(_PCLK_, _BAUD_) ((UART_DIVMANT_SAMPLING8((_PCLK_), (_BAUD_)) << 4U) + \ + ((UART_DIVFRAQ_SAMPLING8((_PCLK_), (_BAUD_)) & 0xF8U) << 1U) + \ + (UART_DIVFRAQ_SAMPLING8((_PCLK_), (_BAUD_)) & 0x07U)) + +/** + * @} + */ + +/* Private functions ---------------------------------------------------------*/ +/** @defgroup UART_Private_Functions UART Private Functions + * @{ + */ + +DAL_StatusTypeDef UART_Start_Receive_IT(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size); +DAL_StatusTypeDef UART_Start_Receive_DMA(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size); + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* APM32F4xx_DAL_UART_H */ + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_usart.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_usart.h new file mode 100644 index 0000000000..7cc2459ba3 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_usart.h @@ -0,0 +1,672 @@ +/** + * + * @file apm32f4xx_dal_usart.h + * @brief Header file of USART DAL module. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef APM32F4xx_DAL_USART_H +#define APM32F4xx_DAL_USART_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal_def.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @addtogroup USART + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ +/** @defgroup USART_Exported_Types USART Exported Types + * @{ + */ + +/** + * @brief USART Init Structure definition + */ +typedef struct +{ + uint32_t BaudRate; /*!< This member configures the Usart communication baud rate. + The baud rate is computed using the following formula: + - IntegerDivider = ((PCLKx) / (8 * (husart->Init.BaudRate))) + - FractionalDivider = ((IntegerDivider - ((uint32_t) IntegerDivider)) * 8) + 0.5 */ + + uint32_t WordLength; /*!< Specifies the number of data bits transmitted or received in a frame. + This parameter can be a value of @ref USART_Word_Length */ + + uint32_t StopBits; /*!< Specifies the number of stop bits transmitted. + This parameter can be a value of @ref USART_Stop_Bits */ + + uint32_t Parity; /*!< Specifies the parity mode. + This parameter can be a value of @ref USART_Parity + @note When parity is enabled, the computed parity is inserted + at the MSB position of the transmitted data (9th bit when + the word length is set to 9 data bits; 8th bit when the + word length is set to 8 data bits). */ + + uint32_t Mode; /*!< Specifies whether the Receive or Transmit mode is enabled or disabled. + This parameter can be a value of @ref USART_Mode */ + + uint32_t CLKPolarity; /*!< Specifies the steady state of the serial clock. + This parameter can be a value of @ref USART_Clock_Polarity */ + + uint32_t CLKPhase; /*!< Specifies the clock transition on which the bit capture is made. + This parameter can be a value of @ref USART_Clock_Phase */ + + uint32_t CLKLastBit; /*!< Specifies whether the clock pulse corresponding to the last transmitted + data bit (MSB) has to be output on the SCLK pin in synchronous mode. + This parameter can be a value of @ref USART_Last_Bit */ +} USART_InitTypeDef; + +/** + * @brief DAL State structures definition + */ +typedef enum +{ + DAL_USART_STATE_RESET = 0x00U, /*!< Peripheral is not yet Initialized */ + DAL_USART_STATE_READY = 0x01U, /*!< Peripheral Initialized and ready for use */ + DAL_USART_STATE_BUSY = 0x02U, /*!< an internal process is ongoing */ + DAL_USART_STATE_BUSY_TX = 0x12U, /*!< Data Transmission process is ongoing */ + DAL_USART_STATE_BUSY_RX = 0x22U, /*!< Data Reception process is ongoing */ + DAL_USART_STATE_BUSY_TX_RX = 0x32U, /*!< Data Transmission Reception process is ongoing */ + DAL_USART_STATE_TIMEOUT = 0x03U, /*!< Timeout state */ + DAL_USART_STATE_ERROR = 0x04U /*!< Error */ +} DAL_USART_StateTypeDef; + +/** + * @brief USART handle Structure definition + */ +typedef struct __USART_HandleTypeDef +{ + USART_TypeDef *Instance; /*!< USART registers base address */ + + USART_InitTypeDef Init; /*!< Usart communication parameters */ + + const uint8_t *pTxBuffPtr; /*!< Pointer to Usart Tx transfer Buffer */ + + uint16_t TxXferSize; /*!< Usart Tx Transfer size */ + + __IO uint16_t TxXferCount; /*!< Usart Tx Transfer Counter */ + + uint8_t *pRxBuffPtr; /*!< Pointer to Usart Rx transfer Buffer */ + + uint16_t RxXferSize; /*!< Usart Rx Transfer size */ + + __IO uint16_t RxXferCount; /*!< Usart Rx Transfer Counter */ + + DMA_HandleTypeDef *hdmatx; /*!< Usart Tx DMA Handle parameters */ + + DMA_HandleTypeDef *hdmarx; /*!< Usart Rx DMA Handle parameters */ + + DAL_LockTypeDef Lock; /*!< Locking object */ + + __IO DAL_USART_StateTypeDef State; /*!< Usart communication state */ + + __IO uint32_t ErrorCode; /*!< USART Error code */ + +#if (USE_DAL_USART_REGISTER_CALLBACKS == 1) + void (* TxHalfCpltCallback)(struct __USART_HandleTypeDef *husart); /*!< USART Tx Half Complete Callback */ + void (* TxCpltCallback)(struct __USART_HandleTypeDef *husart); /*!< USART Tx Complete Callback */ + void (* RxHalfCpltCallback)(struct __USART_HandleTypeDef *husart); /*!< USART Rx Half Complete Callback */ + void (* RxCpltCallback)(struct __USART_HandleTypeDef *husart); /*!< USART Rx Complete Callback */ + void (* TxRxCpltCallback)(struct __USART_HandleTypeDef *husart); /*!< USART Tx Rx Complete Callback */ + void (* ErrorCallback)(struct __USART_HandleTypeDef *husart); /*!< USART Error Callback */ + void (* AbortCpltCallback)(struct __USART_HandleTypeDef *husart); /*!< USART Abort Complete Callback */ + + void (* MspInitCallback)(struct __USART_HandleTypeDef *husart); /*!< USART Msp Init callback */ + void (* MspDeInitCallback)(struct __USART_HandleTypeDef *husart); /*!< USART Msp DeInit callback */ +#endif /* USE_DAL_USART_REGISTER_CALLBACKS */ + +} USART_HandleTypeDef; + +#if (USE_DAL_USART_REGISTER_CALLBACKS == 1) +/** + * @brief DAL USART Callback ID enumeration definition + */ +typedef enum +{ + DAL_USART_TX_HALFCOMPLETE_CB_ID = 0x00U, /*!< USART Tx Half Complete Callback ID */ + DAL_USART_TX_COMPLETE_CB_ID = 0x01U, /*!< USART Tx Complete Callback ID */ + DAL_USART_RX_HALFCOMPLETE_CB_ID = 0x02U, /*!< USART Rx Half Complete Callback ID */ + DAL_USART_RX_COMPLETE_CB_ID = 0x03U, /*!< USART Rx Complete Callback ID */ + DAL_USART_TX_RX_COMPLETE_CB_ID = 0x04U, /*!< USART Tx Rx Complete Callback ID */ + DAL_USART_ERROR_CB_ID = 0x05U, /*!< USART Error Callback ID */ + DAL_USART_ABORT_COMPLETE_CB_ID = 0x06U, /*!< USART Abort Complete Callback ID */ + + DAL_USART_MSPINIT_CB_ID = 0x07U, /*!< USART MspInit callback ID */ + DAL_USART_MSPDEINIT_CB_ID = 0x08U /*!< USART MspDeInit callback ID */ + +} DAL_USART_CallbackIDTypeDef; + +/** + * @brief DAL USART Callback pointer definition + */ +typedef void (*pUSART_CallbackTypeDef)(USART_HandleTypeDef *husart); /*!< pointer to an USART callback function */ + +#endif /* USE_DAL_USART_REGISTER_CALLBACKS */ + +/** + * @} + */ + +/* Exported constants --------------------------------------------------------*/ +/** @defgroup USART_Exported_Constants USART Exported Constants + * @{ + */ + +/** @defgroup USART_Error_Code USART Error Code + * @brief USART Error Code + * @{ + */ +#define DAL_USART_ERROR_NONE 0x00000000U /*!< No error */ +#define DAL_USART_ERROR_PE 0x00000001U /*!< Parity error */ +#define DAL_USART_ERROR_NE 0x00000002U /*!< Noise error */ +#define DAL_USART_ERROR_FE 0x00000004U /*!< Frame error */ +#define DAL_USART_ERROR_ORE 0x00000008U /*!< Overrun error */ +#define DAL_USART_ERROR_DMA 0x00000010U /*!< DMA transfer error */ +#if (USE_DAL_USART_REGISTER_CALLBACKS == 1) +#define DAL_USART_ERROR_INVALID_CALLBACK 0x00000020U /*!< Invalid Callback error */ +#endif /* USE_DAL_USART_REGISTER_CALLBACKS */ +/** + * @} + */ + +/** @defgroup USART_Word_Length USART Word Length + * @{ + */ +#define USART_WORDLENGTH_8B 0x00000000U +#define USART_WORDLENGTH_9B ((uint32_t)USART_CTRL1_DBLCFG) +/** + * @} + */ + +/** @defgroup USART_Stop_Bits USART Number of Stop Bits + * @{ + */ +#define USART_STOPBITS_1 0x00000000U +#define USART_STOPBITS_0_5 ((uint32_t)USART_CTRL2_STOPCFG_0) +#define USART_STOPBITS_2 ((uint32_t)USART_CTRL2_STOPCFG_1) +#define USART_STOPBITS_1_5 ((uint32_t)(USART_CTRL2_STOPCFG_0 | USART_CTRL2_STOPCFG_1)) +/** + * @} + */ + +/** @defgroup USART_Parity USART Parity + * @{ + */ +#define USART_PARITY_NONE 0x00000000U +#define USART_PARITY_EVEN ((uint32_t)USART_CTRL1_PCEN) +#define USART_PARITY_ODD ((uint32_t)(USART_CTRL1_PCEN | USART_CTRL1_PCFG)) +/** + * @} + */ + +/** @defgroup USART_Mode USART Mode + * @{ + */ +#define USART_MODE_RX ((uint32_t)USART_CTRL1_RXEN) +#define USART_MODE_TX ((uint32_t)USART_CTRL1_TXEN) +#define USART_MODE_TX_RX ((uint32_t)(USART_CTRL1_TXEN | USART_CTRL1_RXEN)) +/** + * @} + */ + +/** @defgroup USART_Clock USART Clock + * @{ + */ +#define USART_CLOCK_DISABLE 0x00000000U +#define USART_CLOCK_ENABLE ((uint32_t)USART_CTRL2_CLKEN) +/** + * @} + */ + +/** @defgroup USART_Clock_Polarity USART Clock Polarity + * @{ + */ +#define USART_POLARITY_LOW 0x00000000U +#define USART_POLARITY_HIGH ((uint32_t)USART_CTRL2_CPOL) +/** + * @} + */ + +/** @defgroup USART_Clock_Phase USART Clock Phase + * @{ + */ +#define USART_PHASE_1EDGE 0x00000000U +#define USART_PHASE_2EDGE ((uint32_t)USART_CTRL2_CPHA) +/** + * @} + */ + +/** @defgroup USART_Last_Bit USART Last Bit + * @{ + */ +#define USART_LASTBIT_DISABLE 0x00000000U +#define USART_LASTBIT_ENABLE ((uint32_t)USART_CTRL2_LBCPOEN) +/** + * @} + */ + +/** @defgroup USART_NACK_State USART NACK State + * @{ + */ +#define USART_NACK_ENABLE ((uint32_t)USART_CTRL3_SCNACKEN) +#define USART_NACK_DISABLE 0x00000000U +/** + * @} + */ + +/** @defgroup USART_Flags USART Flags + * Elements values convention: 0xXXXX + * - 0xXXXX : Flag mask in the SR register + * @{ + */ +#define USART_FLAG_TXE ((uint32_t)USART_STS_TXBEFLG) +#define USART_FLAG_TC ((uint32_t)USART_STS_TXCFLG) +#define USART_FLAG_RXNE ((uint32_t)USART_STS_RXBNEFLG) +#define USART_FLAG_IDLE ((uint32_t)USART_STS_IDLEFLG) +#define USART_FLAG_ORE ((uint32_t)USART_STS_OVREFLG) +#define USART_FLAG_NE ((uint32_t)USART_STS_NEFLG) +#define USART_FLAG_FE ((uint32_t)USART_STS_FEFLG) +#define USART_FLAG_PE ((uint32_t)USART_STS_PEFLG) +/** + * @} + */ + +/** @defgroup USART_Interrupt_definition USART Interrupts Definition + * Elements values convention: 0xY000XXXX + * - XXXX : Interrupt mask in the XX register + * - Y : Interrupt source register (2bits) + * - 01: CTRL1 register + * - 10: CTRL2 register + * - 11: CTRL3 register + * @{ + */ +#define USART_IT_PE ((uint32_t)(USART_CTRL1_RXENG_INDEX << 28U | USART_CTRL1_PEIEN)) +#define USART_IT_TXE ((uint32_t)(USART_CTRL1_RXENG_INDEX << 28U | USART_CTRL1_TXBEIEN)) +#define USART_IT_TC ((uint32_t)(USART_CTRL1_RXENG_INDEX << 28U | USART_CTRL1_TXCIEN)) +#define USART_IT_RXNE ((uint32_t)(USART_CTRL1_RXENG_INDEX << 28U | USART_CTRL1_RXBNEIEN)) +#define USART_IT_IDLE ((uint32_t)(USART_CTRL1_RXENG_INDEX << 28U | USART_CTRL1_IDLEIEN)) +#define USART_IT_ERR ((uint32_t)(USART_CTRL3_REG_INDEX << 28U | USART_CTRL3_ERRIEN)) +/** + * @} + */ + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ +/** @defgroup USART_Exported_Macros USART Exported Macros + * @{ + */ + +/** @brief Reset USART handle state + * @param __HANDLE__ specifies the USART Handle. + * USART Handle selects the USARTx peripheral (USART availability and x value depending on device). + * @retval None + */ +#if (USE_DAL_USART_REGISTER_CALLBACKS == 1) +#define __DAL_USART_RESET_HANDLE_STATE(__HANDLE__) do{ \ + (__HANDLE__)->State = DAL_USART_STATE_RESET; \ + (__HANDLE__)->MspInitCallback = NULL; \ + (__HANDLE__)->MspDeInitCallback = NULL; \ + } while(0U) +#else +#define __DAL_USART_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = DAL_USART_STATE_RESET) +#endif /* USE_DAL_USART_REGISTER_CALLBACKS */ + +/** @brief Check whether the specified USART flag is set or not. + * @param __HANDLE__ specifies the USART Handle. + * USART Handle selects the USARTx peripheral (USART availability and x value depending on device). + * @param __FLAG__ specifies the flag to check. + * This parameter can be one of the following values: + * @arg USART_FLAG_TXE: Transmit data register empty flag + * @arg USART_FLAG_TC: Transmission Complete flag + * @arg USART_FLAG_RXNE: Receive data register not empty flag + * @arg USART_FLAG_IDLE: Idle Line detection flag + * @arg USART_FLAG_ORE: Overrun Error flag + * @arg USART_FLAG_NE: Noise Error flag + * @arg USART_FLAG_FE: Framing Error flag + * @arg USART_FLAG_PE: Parity Error flag + * @retval The new state of __FLAG__ (TRUE or FALSE). + */ +#define __DAL_USART_GET_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->STS & (__FLAG__)) == (__FLAG__)) + +/** @brief Clear the specified USART pending flags. + * @param __HANDLE__ specifies the USART Handle. + * USART Handle selects the USARTx peripheral (USART availability and x value depending on device). + * @param __FLAG__ specifies the flag to check. + * This parameter can be any combination of the following values: + * @arg USART_FLAG_TC: Transmission Complete flag. + * @arg USART_FLAG_RXNE: Receive data register not empty flag. + * + * @note PE (Parity error), FE (Framing error), NE (Noise error), ORE (Overrun + * error) and IDLE (Idle line detected) flags are cleared by software + * sequence: a read operation to USART_STS register followed by a read + * operation to USART_DATA register. + * @note RXNE flag can be also cleared by a read to the USART_DATA register. + * @note TC flag can be also cleared by software sequence: a read operation to + * USART_STS register followed by a write operation to USART_DATA register. + * @note TXE flag is cleared only by a write to the USART_DATA register. + * + * @retval None + */ +#define __DAL_USART_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->STS = ~(__FLAG__)) + +/** @brief Clear the USART PE pending flag. + * @param __HANDLE__ specifies the USART Handle. + * USART Handle selects the USARTx peripheral (USART availability and x value depending on device). + * @retval None + */ +#define __DAL_USART_CLEAR_PEFLAG(__HANDLE__) \ + do{ \ + __IO uint32_t tmpreg = 0x00U; \ + tmpreg = (__HANDLE__)->Instance->STS; \ + tmpreg = (__HANDLE__)->Instance->DATA; \ + UNUSED(tmpreg); \ + } while(0U) + +/** @brief Clear the USART FE pending flag. + * @param __HANDLE__ specifies the USART Handle. + * USART Handle selects the USARTx peripheral (USART availability and x value depending on device). + * @retval None + */ +#define __DAL_USART_CLEAR_FEFLAG(__HANDLE__) __DAL_USART_CLEAR_PEFLAG(__HANDLE__) + +/** @brief Clear the USART NE pending flag. + * @param __HANDLE__ specifies the USART Handle. + * USART Handle selects the USARTx peripheral (USART availability and x value depending on device). + * @retval None + */ +#define __DAL_USART_CLEAR_NEFLAG(__HANDLE__) __DAL_USART_CLEAR_PEFLAG(__HANDLE__) + +/** @brief Clear the USART ORE pending flag. + * @param __HANDLE__ specifies the USART Handle. + * USART Handle selects the USARTx peripheral (USART availability and x value depending on device). + * @retval None + */ +#define __DAL_USART_CLEAR_OREFLAG(__HANDLE__) __DAL_USART_CLEAR_PEFLAG(__HANDLE__) + +/** @brief Clear the USART IDLE pending flag. + * @param __HANDLE__ specifies the USART Handle. + * USART Handle selects the USARTx peripheral (USART availability and x value depending on device). + * @retval None + */ +#define __DAL_USART_CLEAR_IDLEFLAG(__HANDLE__) __DAL_USART_CLEAR_PEFLAG(__HANDLE__) + +/** @brief Enables or disables the specified USART interrupts. + * @param __HANDLE__ specifies the USART Handle. + * USART Handle selects the USARTx peripheral (USART availability and x value depending on device). + * @param __INTERRUPT__ specifies the USART interrupt source to check. + * This parameter can be one of the following values: + * @arg USART_IT_TXE: Transmit Data Register empty interrupt + * @arg USART_IT_TC: Transmission complete interrupt + * @arg USART_IT_RXNE: Receive Data register not empty interrupt + * @arg USART_IT_IDLE: Idle line detection interrupt + * @arg USART_IT_PE: Parity Error interrupt + * @arg USART_IT_ERR: Error interrupt(Frame error, noise error, overrun error) + * @retval None + */ +#define __DAL_USART_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((((__INTERRUPT__) >> 28U) == USART_CTRL1_RXENG_INDEX)? ((__HANDLE__)->Instance->CTRL1 |= ((__INTERRUPT__) & USART_IT_MASK)): \ + (((__INTERRUPT__) >> 28U) == USART_CTRL2_REG_INDEX)? ((__HANDLE__)->Instance->CTRL2 |= ((__INTERRUPT__) & USART_IT_MASK)): \ + ((__HANDLE__)->Instance->CTRL3 |= ((__INTERRUPT__) & USART_IT_MASK))) +#define __DAL_USART_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((((__INTERRUPT__) >> 28U) == USART_CTRL1_RXENG_INDEX)? ((__HANDLE__)->Instance->CTRL1 &= ~((__INTERRUPT__) & USART_IT_MASK)): \ + (((__INTERRUPT__) >> 28U) == USART_CTRL2_REG_INDEX)? ((__HANDLE__)->Instance->CTRL2 &= ~((__INTERRUPT__) & USART_IT_MASK)): \ + ((__HANDLE__)->Instance->CTRL3 &= ~ ((__INTERRUPT__) & USART_IT_MASK))) + +/** @brief Checks whether the specified USART interrupt has occurred or not. + * @param __HANDLE__ specifies the USART Handle. + * USART Handle selects the USARTx peripheral (USART availability and x value depending on device). + * @param __IT__ specifies the USART interrupt source to check. + * This parameter can be one of the following values: + * @arg USART_IT_TXE: Transmit Data Register empty interrupt + * @arg USART_IT_TC: Transmission complete interrupt + * @arg USART_IT_RXNE: Receive Data register not empty interrupt + * @arg USART_IT_IDLE: Idle line detection interrupt + * @arg USART_IT_ERR: Error interrupt + * @arg USART_IT_PE: Parity Error interrupt + * @retval The new state of __IT__ (TRUE or FALSE). + */ +#define __DAL_USART_GET_IT_SOURCE(__HANDLE__, __IT__) (((((__IT__) >> 28U) == USART_CTRL1_RXENG_INDEX)? (__HANDLE__)->Instance->CTRL1:(((((uint32_t)(__IT__)) >> 28U) == USART_CTRL2_REG_INDEX)? \ + (__HANDLE__)->Instance->CTRL2 : (__HANDLE__)->Instance->CTRL3)) & (((uint32_t)(__IT__)) & USART_IT_MASK)) + +/** @brief Macro to enable the USART's one bit sample method + * @param __HANDLE__ specifies the USART Handle. + * @retval None + */ +#define __DAL_USART_ONE_BIT_SAMPLE_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CTRL3 |= USART_CTRL3_SAMCFG) + +/** @brief Macro to disable the USART's one bit sample method + * @param __HANDLE__ specifies the USART Handle. + * @retval None + */ +#define __DAL_USART_ONE_BIT_SAMPLE_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CTRL3\ + &= (uint16_t)~((uint16_t)USART_CTRL3_SAMCFG)) + +/** @brief Enable USART + * @param __HANDLE__ specifies the USART Handle. + * USART Handle selects the USARTx peripheral (USART availability and x value depending on device). + * @retval None + */ +#define __DAL_USART_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CTRL1 |= USART_CTRL1_UEN) + +/** @brief Disable USART + * @param __HANDLE__ specifies the USART Handle. + * USART Handle selects the USARTx peripheral (USART availability and x value depending on device). + * @retval None + */ +#define __DAL_USART_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CTRL1 &= ~USART_CTRL1_UEN) + +/** + * @} + */ +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup USART_Exported_Functions + * @{ + */ + +/** @addtogroup USART_Exported_Functions_Group1 + * @{ + */ +/* Initialization/de-initialization functions **********************************/ +DAL_StatusTypeDef DAL_USART_Init(USART_HandleTypeDef *husart); +DAL_StatusTypeDef DAL_USART_DeInit(USART_HandleTypeDef *husart); +void DAL_USART_MspInit(USART_HandleTypeDef *husart); +void DAL_USART_MspDeInit(USART_HandleTypeDef *husart); + +/* Callbacks Register/UnRegister functions ***********************************/ +#if (USE_DAL_USART_REGISTER_CALLBACKS == 1) +DAL_StatusTypeDef DAL_USART_RegisterCallback(USART_HandleTypeDef *husart, DAL_USART_CallbackIDTypeDef CallbackID, + pUSART_CallbackTypeDef pCallback); +DAL_StatusTypeDef DAL_USART_UnRegisterCallback(USART_HandleTypeDef *husart, DAL_USART_CallbackIDTypeDef CallbackID); +#endif /* USE_DAL_USART_REGISTER_CALLBACKS */ + +/** + * @} + */ + +/** @addtogroup USART_Exported_Functions_Group2 + * @{ + */ +/* IO operation functions *******************************************************/ +DAL_StatusTypeDef DAL_USART_Transmit(USART_HandleTypeDef *husart, const uint8_t *pTxData, uint16_t Size, uint32_t Timeout); +DAL_StatusTypeDef DAL_USART_Receive(USART_HandleTypeDef *husart, uint8_t *pRxData, uint16_t Size, uint32_t Timeout); +DAL_StatusTypeDef DAL_USART_TransmitReceive(USART_HandleTypeDef *husart, const uint8_t *pTxData, uint8_t *pRxData, + uint16_t Size, uint32_t Timeout); +DAL_StatusTypeDef DAL_USART_Transmit_IT(USART_HandleTypeDef *husart, const uint8_t *pTxData, uint16_t Size); +DAL_StatusTypeDef DAL_USART_Receive_IT(USART_HandleTypeDef *husart, uint8_t *pRxData, uint16_t Size); +DAL_StatusTypeDef DAL_USART_TransmitReceive_IT(USART_HandleTypeDef *husart, const uint8_t *pTxData, uint8_t *pRxData, + uint16_t Size); +DAL_StatusTypeDef DAL_USART_Transmit_DMA(USART_HandleTypeDef *husart, const uint8_t *pTxData, uint16_t Size); +DAL_StatusTypeDef DAL_USART_Receive_DMA(USART_HandleTypeDef *husart, uint8_t *pRxData, uint16_t Size); +DAL_StatusTypeDef DAL_USART_TransmitReceive_DMA(USART_HandleTypeDef *husart, const uint8_t *pTxData, uint8_t *pRxData, + uint16_t Size); +DAL_StatusTypeDef DAL_USART_DMAPause(USART_HandleTypeDef *husart); +DAL_StatusTypeDef DAL_USART_DMAResume(USART_HandleTypeDef *husart); +DAL_StatusTypeDef DAL_USART_DMAStop(USART_HandleTypeDef *husart); +/* Transfer Abort functions */ +DAL_StatusTypeDef DAL_USART_Abort(USART_HandleTypeDef *husart); +DAL_StatusTypeDef DAL_USART_Abort_IT(USART_HandleTypeDef *husart); + +void DAL_USART_IRQHandler(USART_HandleTypeDef *husart); +void DAL_USART_TxCpltCallback(USART_HandleTypeDef *husart); +void DAL_USART_TxHalfCpltCallback(USART_HandleTypeDef *husart); +void DAL_USART_RxCpltCallback(USART_HandleTypeDef *husart); +void DAL_USART_RxHalfCpltCallback(USART_HandleTypeDef *husart); +void DAL_USART_TxRxCpltCallback(USART_HandleTypeDef *husart); +void DAL_USART_ErrorCallback(USART_HandleTypeDef *husart); +void DAL_USART_AbortCpltCallback(USART_HandleTypeDef *husart); +/** + * @} + */ + +/** @addtogroup USART_Exported_Functions_Group3 + * @{ + */ +/* Peripheral State functions ************************************************/ +DAL_USART_StateTypeDef DAL_USART_GetState(USART_HandleTypeDef *husart); +uint32_t DAL_USART_GetError(USART_HandleTypeDef *husart); +/** + * @} + */ + +/** + * @} + */ +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/** @defgroup USART_Private_Constants USART Private Constants + * @{ + */ +/** @brief USART interruptions flag mask + * + */ +#define USART_IT_MASK ((uint32_t) USART_CTRL1_PEIEN | USART_CTRL1_TXBEIEN | USART_CTRL1_TXCIEN | USART_CTRL1_RXBNEIEN | \ + USART_CTRL1_IDLEIEN | USART_CTRL2_LBDIEN | USART_CTRL3_CTSIEN | USART_CTRL3_ERRIEN ) + +#define USART_CTRL1_RXENG_INDEX 1U +#define USART_CTRL2_REG_INDEX 2U +#define USART_CTRL3_REG_INDEX 3U +/** + * @} + */ + +/* Private macros ------------------------------------------------------------*/ +/** @defgroup USART_Private_Macros USART Private Macros + * @{ + */ +#define IS_USART_NACK_STATE(NACK) (((NACK) == USART_NACK_ENABLE) || \ + ((NACK) == USART_NACK_DISABLE)) + +#define IS_USART_LASTBIT(LASTBIT) (((LASTBIT) == USART_LASTBIT_DISABLE) || \ + ((LASTBIT) == USART_LASTBIT_ENABLE)) + +#define IS_USART_PHASE(CPHA) (((CPHA) == USART_PHASE_1EDGE) || \ + ((CPHA) == USART_PHASE_2EDGE)) + +#define IS_USART_POLARITY(CPOL) (((CPOL) == USART_POLARITY_LOW) || \ + ((CPOL) == USART_POLARITY_HIGH)) + +#define IS_USART_CLOCK(CLOCK) (((CLOCK) == USART_CLOCK_DISABLE) || \ + ((CLOCK) == USART_CLOCK_ENABLE)) + +#define IS_USART_WORD_LENGTH(LENGTH) (((LENGTH) == USART_WORDLENGTH_8B) || \ + ((LENGTH) == USART_WORDLENGTH_9B)) + +#define IS_USART_STOPBITS(STOPBITS) (((STOPBITS) == USART_STOPBITS_1) || \ + ((STOPBITS) == USART_STOPBITS_0_5) || \ + ((STOPBITS) == USART_STOPBITS_1_5) || \ + ((STOPBITS) == USART_STOPBITS_2)) + +#define IS_USART_PARITY(PARITY) (((PARITY) == USART_PARITY_NONE) || \ + ((PARITY) == USART_PARITY_EVEN) || \ + ((PARITY) == USART_PARITY_ODD)) + +#define IS_USART_MODE(MODE) ((((MODE) & (~((uint32_t)USART_MODE_TX_RX))) == 0x00U) && ((MODE) != 0x00U)) + +#define IS_USART_BAUDRATE(BAUDRATE) ((BAUDRATE) <= 12500000U) + +#define USART_DIV(_PCLK_, _BAUD_) ((uint32_t)((((uint64_t)(_PCLK_))*25U)/(2U*((uint64_t)(_BAUD_))))) + +#define USART_DIVMANT(_PCLK_, _BAUD_) (USART_DIV((_PCLK_), (_BAUD_))/100U) + +#define USART_DIVFRAQ(_PCLK_, _BAUD_) ((((USART_DIV((_PCLK_), (_BAUD_)) - (USART_DIVMANT((_PCLK_), (_BAUD_)) * 100U)) * 8U) + 50U) / 100U) + + /* UART BRR = mantissa + overflow + fraction + = (UART DIVMANT << 4) + ((UART DIVFRAQ & 0xF8) << 1) + (UART DIVFRAQ & 0x07U) */ + +#define USART_BR(_PCLK_, _BAUD_) (((USART_DIVMANT((_PCLK_), (_BAUD_)) << 4U) + \ + ((USART_DIVFRAQ((_PCLK_), (_BAUD_)) & 0xF8U) << 1U)) + \ + (USART_DIVFRAQ((_PCLK_), (_BAUD_)) & 0x07U)) +/** + * @} + */ + +/* Private functions ---------------------------------------------------------*/ +/** @defgroup USART_Private_Functions USART Private Functions + * @{ + */ + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* APM32F4xx_DAL_USART_H */ + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_wwdt.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_wwdt.h new file mode 100644 index 0000000000..0923ba16db --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_dal_wwdt.h @@ -0,0 +1,322 @@ +/** + * + * @file apm32f4xx_dal_wwdt.h + * @brief Header file of WWDT DAL module. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef APM32F4xx_DAL_WWDT_H +#define APM32F4xx_DAL_WWDT_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal_def.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @addtogroup WWDT + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ + +/** @defgroup WWDT_Exported_Types WWDT Exported Types + * @{ + */ + +/** + * @brief WWDT Init structure definition + */ +typedef struct +{ + uint32_t Prescaler; /*!< Specifies the prescaler value of the WWDT. + This parameter can be a value of @ref WWDT_Prescaler */ + + uint32_t Window; /*!< Specifies the WWDT window value to be compared to the downcounter. + This parameter must be a number Min_Data = 0x40 and Max_Data = 0x7F */ + + uint32_t Counter; /*!< Specifies the WWDT free-running downcounter value. + This parameter must be a number between Min_Data = 0x40 and Max_Data = 0x7F */ + + uint32_t EWIMode ; /*!< Specifies if WWDT Early Wakeup Interrupt is enable or not. + This parameter can be a value of @ref WWDT_EWI_Mode */ + +} WWDT_InitTypeDef; + +/** + * @brief WWDT handle Structure definition + */ +#if (USE_DAL_WWDT_REGISTER_CALLBACKS == 1) +typedef struct __WWDT_HandleTypeDef +#else +typedef struct +#endif /* USE_DAL_WWDT_REGISTER_CALLBACKS */ +{ + WWDT_TypeDef *Instance; /*!< Register base address */ + + WWDT_InitTypeDef Init; /*!< WWDT required parameters */ + +#if (USE_DAL_WWDT_REGISTER_CALLBACKS == 1) + void (* EwiCallback)(struct __WWDT_HandleTypeDef *hwwdt); /*!< WWDT Early WakeUp Interrupt callback */ + + void (* MspInitCallback)(struct __WWDT_HandleTypeDef *hwwdt); /*!< WWDT Msp Init callback */ +#endif /* USE_DAL_WWDT_REGISTER_CALLBACKS */ +} WWDT_HandleTypeDef; + +#if (USE_DAL_WWDT_REGISTER_CALLBACKS == 1) +/** + * @brief DAL WWDT common Callback ID enumeration definition + */ +typedef enum +{ + DAL_WWDT_EWI_CB_ID = 0x00U, /*!< WWDT EWI callback ID */ + DAL_WWDT_MSPINIT_CB_ID = 0x01U, /*!< WWDT MspInit callback ID */ +} DAL_WWDT_CallbackIDTypeDef; + +/** + * @brief DAL WWDT Callback pointer definition + */ +typedef void (*pWWDT_CallbackTypeDef)(WWDT_HandleTypeDef *hppp); /*!< pointer to a WWDT common callback functions */ + +#endif /* USE_DAL_WWDT_REGISTER_CALLBACKS */ +/** + * @} + */ + +/* Exported constants --------------------------------------------------------*/ + +/** @defgroup WWDT_Exported_Constants WWDT Exported Constants + * @{ + */ + +/** @defgroup WWDT_Interrupt_definition WWDT Interrupt definition + * @{ + */ +#define WWDT_IT_EWI WWDT_CFR_EWIEN /*!< Early wakeup interrupt */ +/** + * @} + */ + +/** @defgroup WWDT_Flag_definition WWDT Flag definition + * @brief WWDT Flag definition + * @{ + */ +#define WWDT_FLAG_EWIF WWDT_STS_EWIFLG /*!< Early wakeup interrupt flag */ +/** + * @} + */ + +/** @defgroup WWDT_Prescaler WWDT Prescaler + * @{ + */ +#define WWDT_PRESCALER_1 0x00000000u /*!< WWDT counter clock = (PCLK1/4096)/1 */ +#define WWDT_PRESCALER_2 WWDT_CFR_TBPSC_0 /*!< WWDT counter clock = (PCLK1/4096)/2 */ +#define WWDT_PRESCALER_4 WWDT_CFR_TBPSC_1 /*!< WWDT counter clock = (PCLK1/4096)/4 */ +#define WWDT_PRESCALER_8 (WWDT_CFR_TBPSC_1 | WWDT_CFR_TBPSC_0) /*!< WWDT counter clock = (PCLK1/4096)/8 */ +/** + * @} + */ + +/** @defgroup WWDT_EWI_Mode WWDT Early Wakeup Interrupt Mode + * @{ + */ +#define WWDT_EWI_DISABLE 0x00000000u /*!< EWI Disable */ +#define WWDT_EWI_ENABLE WWDT_CFR_EWIEN /*!< EWI Enable */ +/** + * @} + */ + +/** + * @} + */ + +/* Private macros ------------------------------------------------------------*/ + +/** @defgroup WWDT_Private_Macros WWDT Private Macros + * @{ + */ +#define IS_WWDT_PRESCALER(__PRESCALER__) (((__PRESCALER__) == WWDT_PRESCALER_1) || \ + ((__PRESCALER__) == WWDT_PRESCALER_2) || \ + ((__PRESCALER__) == WWDT_PRESCALER_4) || \ + ((__PRESCALER__) == WWDT_PRESCALER_8)) + +#define IS_WWDT_WINDOW(__WINDOW__) (((__WINDOW__) >= WWDT_CFR_WIN_6) && ((__WINDOW__) <= WWDT_CFR_WIN)) + +#define IS_WWDT_COUNTER(__COUNTER__) (((__COUNTER__) >= WWDT_CTRL_CNT_6) && ((__COUNTER__) <= WWDT_CTRL_CNT)) + +#define IS_WWDT_EWI_MODE(__MODE__) (((__MODE__) == WWDT_EWI_ENABLE) || \ + ((__MODE__) == WWDT_EWI_DISABLE)) +/** + * @} + */ + + +/* Exported macros ------------------------------------------------------------*/ + +/** @defgroup WWDT_Exported_Macros WWDT Exported Macros + * @{ + */ + +/** + * @brief Enable the WWDT peripheral. + * @param __HANDLE__ WWDT handle + * @retval None + */ +#define __DAL_WWDT_ENABLE(__HANDLE__) SET_BIT((__HANDLE__)->Instance->CTRL, WWDT_CTRL_WWDTEN) + +/** + * @brief Enable the WWDT early wakeup interrupt. + * @param __HANDLE__ WWDT handle + * @param __INTERRUPT__ specifies the interrupt to enable. + * This parameter can be one of the following values: + * @arg WWDT_IT_EWI: Early wakeup interrupt + * @note Once enabled this interrupt cannot be disabled except by a system reset. + * @retval None + */ +#define __DAL_WWDT_ENABLE_IT(__HANDLE__, __INTERRUPT__) SET_BIT((__HANDLE__)->Instance->CFR, (__INTERRUPT__)) + +/** + * @brief Check whether the selected WWDT interrupt has occurred or not. + * @param __HANDLE__ WWDT handle + * @param __INTERRUPT__ specifies the it to check. + * This parameter can be one of the following values: + * @arg WWDT_FLAG_EWIF: Early wakeup interrupt IT + * @retval The new state of WWDT_FLAG (SET or RESET). + */ +#define __DAL_WWDT_GET_IT(__HANDLE__, __INTERRUPT__) __DAL_WWDT_GET_FLAG((__HANDLE__),(__INTERRUPT__)) + +/** @brief Clear the WWDT interrupt pending bits. + * bits to clear the selected interrupt pending bits. + * @param __HANDLE__ WWDT handle + * @param __INTERRUPT__ specifies the interrupt pending bit to clear. + * This parameter can be one of the following values: + * @arg WWDT_FLAG_EWIF: Early wakeup interrupt flag + */ +#define __DAL_WWDT_CLEAR_IT(__HANDLE__, __INTERRUPT__) __DAL_WWDT_CLEAR_FLAG((__HANDLE__), (__INTERRUPT__)) + +/** + * @brief Check whether the specified WWDT flag is set or not. + * @param __HANDLE__ WWDT handle + * @param __FLAG__ specifies the flag to check. + * This parameter can be one of the following values: + * @arg WWDT_FLAG_EWIF: Early wakeup interrupt flag + * @retval The new state of WWDT_FLAG (SET or RESET). + */ +#define __DAL_WWDT_GET_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->STS & (__FLAG__)) == (__FLAG__)) + +/** + * @brief Clear the WWDT's pending flags. + * @param __HANDLE__ WWDT handle + * @param __FLAG__ specifies the flag to clear. + * This parameter can be one of the following values: + * @arg WWDT_FLAG_EWIF: Early wakeup interrupt flag + * @retval None + */ +#define __DAL_WWDT_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->STS = ~(__FLAG__)) + +/** @brief Check whether the specified WWDT interrupt source is enabled or not. + * @param __HANDLE__ WWDT Handle. + * @param __INTERRUPT__ specifies the WWDT interrupt source to check. + * This parameter can be one of the following values: + * @arg WWDT_IT_EWI: Early Wakeup Interrupt + * @retval state of __INTERRUPT__ (TRUE or FALSE). + */ +#define __DAL_WWDT_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->CFR\ + & (__INTERRUPT__)) == (__INTERRUPT__)) + +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ + +/** @addtogroup WWDT_Exported_Functions + * @{ + */ + +/** @addtogroup WWDT_Exported_Functions_Group1 + * @{ + */ +/* Initialization/de-initialization functions **********************************/ +DAL_StatusTypeDef DAL_WWDT_Init(WWDT_HandleTypeDef *hwwdt); +void DAL_WWDT_MspInit(WWDT_HandleTypeDef *hwwdt); +/* Callbacks Register/UnRegister functions ***********************************/ +#if (USE_DAL_WWDT_REGISTER_CALLBACKS == 1) +DAL_StatusTypeDef DAL_WWDT_RegisterCallback(WWDT_HandleTypeDef *hwwdt, DAL_WWDT_CallbackIDTypeDef CallbackID, + pWWDT_CallbackTypeDef pCallback); +DAL_StatusTypeDef DAL_WWDT_UnRegisterCallback(WWDT_HandleTypeDef *hwwdt, DAL_WWDT_CallbackIDTypeDef CallbackID); +#endif /* USE_DAL_WWDT_REGISTER_CALLBACKS */ + +/** + * @} + */ + +/** @addtogroup WWDT_Exported_Functions_Group2 + * @{ + */ +/* I/O operation functions ******************************************************/ +DAL_StatusTypeDef DAL_WWDT_Refresh(WWDT_HandleTypeDef *hwwdt); +void DAL_WWDT_IRQHandler(WWDT_HandleTypeDef *hwwdt); +void DAL_WWDT_EarlyWakeupCallback(WWDT_HandleTypeDef *hwwdt); +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* APM32F4xx_DAL_WWDT_H */ diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_adc.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_adc.h new file mode 100644 index 0000000000..bb0b7a68f9 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_adc.h @@ -0,0 +1,4575 @@ +/** + * + * @file apm32f4xx_ddl_adc.h + * @brief Header file of ADC DDL module. + ****************************************************************************** + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2017 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef APM32F4xx_DDL_ADC_H +#define APM32F4xx_DDL_ADC_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx.h" + +/** @addtogroup APM32F4xx_DDL_Driver + * @{ + */ + +#if defined (ADC1) || defined (ADC2) || defined (ADC3) + +/** @defgroup ADC_DDL ADC + * @{ + */ + +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ + +/* Private constants ---------------------------------------------------------*/ +/** @defgroup ADC_DDL_Private_Constants ADC Private Constants + * @{ + */ + +/* Internal mask for ADC group regular sequencer: */ +/* To select into literal DDL_ADC_REG_RANK_x the relevant bits for: */ +/* - sequencer register offset */ +/* - sequencer rank bits position into the selected register */ + +/* Internal register offset for ADC group regular sequencer configuration */ +/* (offset placed into a spare area of literal definition) */ +#define ADC_REGSEQ1_REGOFFSET 0x00000000UL +#define ADC_REGSEQ2_REGOFFSET 0x00000100UL +#define ADC_REGSEQ3_REGOFFSET 0x00000200UL +#define ADC_REGSEQ4_REGOFFSET 0x00000300UL + +#define ADC_REG_SQRX_REGOFFSET_MASK (ADC_REGSEQ1_REGOFFSET | ADC_REGSEQ2_REGOFFSET | ADC_REGSEQ3_REGOFFSET | ADC_REGSEQ4_REGOFFSET) +#define ADC_REG_RANK_ID_SQRX_MASK (ADC_CHANNEL_ID_NUMBER_MASK_POSBIT0) + +/* Definition of ADC group regular sequencer bits information to be inserted */ +/* into ADC group regular sequencer ranks literals definition. */ +#define ADC_REG_RANK_1_SQRX_BITOFFSET_POS ( 0UL) /* Value equivalent to POSITION_VAL(ADC_REGSEQ3_REGSEQC1) */ +#define ADC_REG_RANK_2_SQRX_BITOFFSET_POS ( 5UL) /* Value equivalent to POSITION_VAL(ADC_REGSEQ3_REGSEQC2) */ +#define ADC_REG_RANK_3_SQRX_BITOFFSET_POS (10UL) /* Value equivalent to POSITION_VAL(ADC_REGSEQ3_REGSEQC3) */ +#define ADC_REG_RANK_4_SQRX_BITOFFSET_POS (15UL) /* Value equivalent to POSITION_VAL(ADC_REGSEQ3_REGSEQC4) */ +#define ADC_REG_RANK_5_SQRX_BITOFFSET_POS (20UL) /* Value equivalent to POSITION_VAL(ADC_REGSEQ3_REGSEQC5) */ +#define ADC_REG_RANK_6_SQRX_BITOFFSET_POS (25UL) /* Value equivalent to POSITION_VAL(ADC_REGSEQ3_REGSEQC6) */ +#define ADC_REG_RANK_7_SQRX_BITOFFSET_POS ( 0UL) /* Value equivalent to POSITION_VAL(ADC_REGSEQ2_REGSEQC7) */ +#define ADC_REG_RANK_8_SQRX_BITOFFSET_POS ( 5UL) /* Value equivalent to POSITION_VAL(ADC_REGSEQ2_REGSEQC8) */ +#define ADC_REG_RANK_9_SQRX_BITOFFSET_POS (10UL) /* Value equivalent to POSITION_VAL(ADC_REGSEQ2_REGSEQC9) */ +#define ADC_REG_RANK_10_SQRX_BITOFFSET_POS (15UL) /* Value equivalent to POSITION_VAL(ADC_REGSEQ2_REGSEQC10) */ +#define ADC_REG_RANK_11_SQRX_BITOFFSET_POS (20UL) /* Value equivalent to POSITION_VAL(ADC_REGSEQ2_REGSEQC11) */ +#define ADC_REG_RANK_12_SQRX_BITOFFSET_POS (25UL) /* Value equivalent to POSITION_VAL(ADC_REGSEQ2_REGSEQC12) */ +#define ADC_REG_RANK_13_SQRX_BITOFFSET_POS ( 0UL) /* Value equivalent to POSITION_VAL(ADC_REGSEQ1_REGSEQC13) */ +#define ADC_REG_RANK_14_SQRX_BITOFFSET_POS ( 5UL) /* Value equivalent to POSITION_VAL(ADC_REGSEQ1_REGSEQC14) */ +#define ADC_REG_RANK_15_SQRX_BITOFFSET_POS (10UL) /* Value equivalent to POSITION_VAL(ADC_REGSEQ1_REGSEQC15) */ +#define ADC_REG_RANK_16_SQRX_BITOFFSET_POS (15UL) /* Value equivalent to POSITION_VAL(ADC_REGSEQ1_REGSEQC16) */ + +/* Internal mask for ADC group injected sequencer: */ +/* To select into literal DDL_ADC_INJ_RANK_x the relevant bits for: */ +/* - data register offset */ +/* - offset register offset */ +/* - sequencer rank bits position into the selected register */ + +/* Internal register offset for ADC group injected data register */ +/* (offset placed into a spare area of literal definition) */ +#define ADC_INJDATA1_REGOFFSET 0x00000000UL +#define ADC_INJDATA2_REGOFFSET 0x00000100UL +#define ADC_INJDATA3_REGOFFSET 0x00000200UL +#define ADC_INJDATA4_REGOFFSET 0x00000300UL + +/* Internal register offset for ADC group injected offset configuration */ +/* (offset placed into a spare area of literal definition) */ +#define ADC_INJDOF1_REGOFFSET 0x00000000UL +#define ADC_INJDOF2_REGOFFSET 0x00001000UL +#define ADC_INJDOF3_REGOFFSET 0x00002000UL +#define ADC_INJDOF4_REGOFFSET 0x00003000UL + +#define ADC_INJ_JDRX_REGOFFSET_MASK (ADC_INJDATA1_REGOFFSET | ADC_INJDATA2_REGOFFSET | ADC_INJDATA3_REGOFFSET | ADC_INJDATA4_REGOFFSET) +#define ADC_INJ_JOFRX_REGOFFSET_MASK (ADC_INJDOF1_REGOFFSET | ADC_INJDOF2_REGOFFSET | ADC_INJDOF3_REGOFFSET | ADC_INJDOF4_REGOFFSET) +#define ADC_INJ_RANK_ID_JSQR_MASK (ADC_CHANNEL_ID_NUMBER_MASK_POSBIT0) + +/* Internal mask for ADC group regular trigger: */ +/* To select into literal DDL_ADC_REG_TRIG_x the relevant bits for: */ +/* - regular trigger source */ +/* - regular trigger edge */ +#define ADC_REG_TRIG_EXT_EDGE_DEFAULT (ADC_CTRL2_REGEXTTRGEN_0) /* Trigger edge set to rising edge (default setting for compatibility with some ADC on other APM32 families having this setting set by HW default value) */ + +/* Mask containing trigger source masks for each of possible */ +/* trigger edge selection duplicated with shifts [0; 4; 8; 12] */ +/* corresponding to {SW start; ext trigger; ext trigger; ext trigger}. */ +#define ADC_REG_TRIG_SOURCE_MASK (((DDL_ADC_REG_TRIG_SOFTWARE & ADC_CTRL2_REGEXTTRGSEL) >> (4UL * 0UL)) | \ + ((ADC_CTRL2_REGEXTTRGSEL) >> (4UL * 1UL)) | \ + ((ADC_CTRL2_REGEXTTRGSEL) >> (4UL * 2UL)) | \ + ((ADC_CTRL2_REGEXTTRGSEL) >> (4UL * 3UL))) + +/* Mask containing trigger edge masks for each of possible */ +/* trigger edge selection duplicated with shifts [0; 4; 8; 12] */ +/* corresponding to {SW start; ext trigger; ext trigger; ext trigger}. */ +#define ADC_REG_TRIG_EDGE_MASK (((DDL_ADC_REG_TRIG_SOFTWARE & ADC_CTRL2_REGEXTTRGEN) >> (4UL * 0UL)) | \ + ((ADC_REG_TRIG_EXT_EDGE_DEFAULT) >> (4UL * 1UL)) | \ + ((ADC_REG_TRIG_EXT_EDGE_DEFAULT) >> (4UL * 2UL)) | \ + ((ADC_REG_TRIG_EXT_EDGE_DEFAULT) >> (4UL * 3UL))) + +/* Definition of ADC group regular trigger bits information. */ +#define ADC_REG_TRIG_EXTSEL_BITOFFSET_POS (24UL) /* Value equivalent to POSITION_VAL(ADC_CTRL2_REGEXTTRGSEL) */ +#define ADC_REG_TRIG_EXTEN_BITOFFSET_POS (28UL) /* Value equivalent to POSITION_VAL(ADC_CTRL2_REGEXTTRGEN) */ + + + +/* Internal mask for ADC group injected trigger: */ +/* To select into literal DDL_ADC_INJ_TRIG_x the relevant bits for: */ +/* - injected trigger source */ +/* - injected trigger edge */ +#define ADC_INJ_TRIG_EXT_EDGE_DEFAULT (ADC_CTRL2_INJEXTTRGEN_0) /* Trigger edge set to rising edge (default setting for compatibility with some ADC on other APM32 families having this setting set by HW default value) */ + +/* Mask containing trigger source masks for each of possible */ +/* trigger edge selection duplicated with shifts [0; 4; 8; 12] */ +/* corresponding to {SW start; ext trigger; ext trigger; ext trigger}. */ +#define ADC_INJ_TRIG_SOURCE_MASK (((DDL_ADC_REG_TRIG_SOFTWARE & ADC_CTRL2_INJGEXTTRGSEL) >> (4UL * 0UL)) | \ + ((ADC_CTRL2_INJGEXTTRGSEL) >> (4UL * 1UL)) | \ + ((ADC_CTRL2_INJGEXTTRGSEL) >> (4UL * 2UL)) | \ + ((ADC_CTRL2_INJGEXTTRGSEL) >> (4UL * 3UL))) + +/* Mask containing trigger edge masks for each of possible */ +/* trigger edge selection duplicated with shifts [0; 4; 8; 12] */ +/* corresponding to {SW start; ext trigger; ext trigger; ext trigger}. */ +#define ADC_INJ_TRIG_EDGE_MASK (((DDL_ADC_INJ_TRIG_SOFTWARE & ADC_CTRL2_INJEXTTRGEN) >> (4UL * 0UL)) | \ + ((ADC_INJ_TRIG_EXT_EDGE_DEFAULT) >> (4UL * 1UL)) | \ + ((ADC_INJ_TRIG_EXT_EDGE_DEFAULT) >> (4UL * 2UL)) | \ + ((ADC_INJ_TRIG_EXT_EDGE_DEFAULT) >> (4UL * 3UL))) + +/* Definition of ADC group injected trigger bits information. */ +#define ADC_INJ_TRIG_EXTSEL_BITOFFSET_POS (16UL) /* Value equivalent to POSITION_VAL(ADC_CTRL2_INJGEXTTRGSEL) */ +#define ADC_INJ_TRIG_EXTEN_BITOFFSET_POS (20UL) /* Value equivalent to POSITION_VAL(ADC_CTRL2_INJEXTTRGEN) */ + +/* Internal mask for ADC channel: */ +/* To select into literal DDL_ADC_CHANNEL_x the relevant bits for: */ +/* - channel identifier defined by number */ +/* - channel differentiation between external channels (connected to */ +/* GPIO pins) and internal channels (connected to internal paths) */ +/* - channel sampling time defined by SMPRx register offset */ +/* and SMPx bits positions into SMPRx register */ +#define ADC_CHANNEL_ID_NUMBER_MASK (ADC_CTRL1_AWDCHSEL) +#define ADC_CHANNEL_ID_NUMBER_BITOFFSET_POS ( 0UL)/* Value equivalent to POSITION_VAL(ADC_CHANNEL_ID_NUMBER_MASK) */ +#define ADC_CHANNEL_ID_MASK (ADC_CHANNEL_ID_NUMBER_MASK | ADC_CHANNEL_ID_INTERNAL_CH_MASK) +/* Equivalent mask of ADC_CHANNEL_NUMBER_MASK aligned on register LSB (bit 0) */ +#define ADC_CHANNEL_ID_NUMBER_MASK_POSBIT0 0x0000001FU /* Equivalent to shift: (ADC_CHANNEL_NUMBER_MASK >> POSITION_VAL(ADC_CHANNEL_NUMBER_MASK)) */ + +/* Channel differentiation between external and internal channels */ +#define ADC_CHANNEL_ID_INTERNAL_CH 0x80000000UL /* Marker of internal channel */ +#define ADC_CHANNEL_ID_INTERNAL_CH_2 0x40000000UL /* Marker of internal channel for other ADC instances, in case of different ADC internal channels mapped on same channel number on different ADC instances */ +#define ADC_CHANNEL_DIFFERENCIATION_TEMPSENSOR_VBAT 0x10000000U /* Dummy bit for driver internal usage, not used in ADC channel setting registers CR1 or SQRx */ +#define ADC_CHANNEL_ID_INTERNAL_CH_MASK (ADC_CHANNEL_ID_INTERNAL_CH | ADC_CHANNEL_ID_INTERNAL_CH_2 | ADC_CHANNEL_DIFFERENCIATION_TEMPSENSOR_VBAT) + +/* Internal register offset for ADC channel sampling time configuration */ +/* (offset placed into a spare area of literal definition) */ +#define ADC_SMPTIM1_REGOFFSET 0x00000000UL +#define ADC_SMPTIM2_REGOFFSET 0x02000000UL +#define ADC_CHANNEL_SMPRX_REGOFFSET_MASK (ADC_SMPTIM1_REGOFFSET | ADC_SMPTIM2_REGOFFSET) + +#define ADC_CHANNEL_SMPx_BITOFFSET_MASK 0x01F00000UL +#define ADC_CHANNEL_SMPx_BITOFFSET_POS (20UL) /* Value equivalent to POSITION_VAL(ADC_CHANNEL_SMPx_BITOFFSET_MASK) */ + +/* Definition of channels ID number information to be inserted into */ +/* channels literals definition. */ +#define ADC_CHANNEL_0_NUMBER 0x00000000UL +#define ADC_CHANNEL_1_NUMBER ( ADC_CTRL1_AWDCHSEL_0) +#define ADC_CHANNEL_2_NUMBER ( ADC_CTRL1_AWDCHSEL_1 ) +#define ADC_CHANNEL_3_NUMBER ( ADC_CTRL1_AWDCHSEL_1 | ADC_CTRL1_AWDCHSEL_0) +#define ADC_CHANNEL_4_NUMBER ( ADC_CTRL1_AWDCHSEL_2 ) +#define ADC_CHANNEL_5_NUMBER ( ADC_CTRL1_AWDCHSEL_2 | ADC_CTRL1_AWDCHSEL_0) +#define ADC_CHANNEL_6_NUMBER ( ADC_CTRL1_AWDCHSEL_2 | ADC_CTRL1_AWDCHSEL_1 ) +#define ADC_CHANNEL_7_NUMBER ( ADC_CTRL1_AWDCHSEL_2 | ADC_CTRL1_AWDCHSEL_1 | ADC_CTRL1_AWDCHSEL_0) +#define ADC_CHANNEL_8_NUMBER ( ADC_CTRL1_AWDCHSEL_3 ) +#define ADC_CHANNEL_9_NUMBER ( ADC_CTRL1_AWDCHSEL_3 | ADC_CTRL1_AWDCHSEL_0) +#define ADC_CHANNEL_10_NUMBER ( ADC_CTRL1_AWDCHSEL_3 | ADC_CTRL1_AWDCHSEL_1 ) +#define ADC_CHANNEL_11_NUMBER ( ADC_CTRL1_AWDCHSEL_3 | ADC_CTRL1_AWDCHSEL_1 | ADC_CTRL1_AWDCHSEL_0) +#define ADC_CHANNEL_12_NUMBER ( ADC_CTRL1_AWDCHSEL_3 | ADC_CTRL1_AWDCHSEL_2 ) +#define ADC_CHANNEL_13_NUMBER ( ADC_CTRL1_AWDCHSEL_3 | ADC_CTRL1_AWDCHSEL_2 | ADC_CTRL1_AWDCHSEL_0) +#define ADC_CHANNEL_14_NUMBER ( ADC_CTRL1_AWDCHSEL_3 | ADC_CTRL1_AWDCHSEL_2 | ADC_CTRL1_AWDCHSEL_1 ) +#define ADC_CHANNEL_15_NUMBER ( ADC_CTRL1_AWDCHSEL_3 | ADC_CTRL1_AWDCHSEL_2 | ADC_CTRL1_AWDCHSEL_1 | ADC_CTRL1_AWDCHSEL_0) +#define ADC_CHANNEL_16_NUMBER (ADC_CTRL1_AWDCHSEL_4 ) +#define ADC_CHANNEL_17_NUMBER (ADC_CTRL1_AWDCHSEL_4 | ADC_CTRL1_AWDCHSEL_0) +#define ADC_CHANNEL_18_NUMBER (ADC_CTRL1_AWDCHSEL_4 | ADC_CTRL1_AWDCHSEL_1 ) + +/* Definition of channels sampling time information to be inserted into */ +/* channels literals definition. */ +#define ADC_CHANNEL_0_SMP (ADC_SMPTIM2_REGOFFSET | (( 0UL) << ADC_CHANNEL_SMPx_BITOFFSET_POS)) /* Value shifted is equivalent to POSITION_VAL(ADC_SMPTIM2_SMPCYCCFG0) */ +#define ADC_CHANNEL_1_SMP (ADC_SMPTIM2_REGOFFSET | (( 3UL) << ADC_CHANNEL_SMPx_BITOFFSET_POS)) /* Value shifted is equivalent to POSITION_VAL(ADC_SMPTIM2_SMPCYCCFG1) */ +#define ADC_CHANNEL_2_SMP (ADC_SMPTIM2_REGOFFSET | (( 6UL) << ADC_CHANNEL_SMPx_BITOFFSET_POS)) /* Value shifted is equivalent to POSITION_VAL(ADC_SMPTIM2_SMPCYCCFG2) */ +#define ADC_CHANNEL_3_SMP (ADC_SMPTIM2_REGOFFSET | (( 9UL) << ADC_CHANNEL_SMPx_BITOFFSET_POS)) /* Value shifted is equivalent to POSITION_VAL(ADC_SMPTIM2_SMPCYCCFG3) */ +#define ADC_CHANNEL_4_SMP (ADC_SMPTIM2_REGOFFSET | ((12UL) << ADC_CHANNEL_SMPx_BITOFFSET_POS)) /* Value shifted is equivalent to POSITION_VAL(ADC_SMPTIM2_SMPCYCCFG4) */ +#define ADC_CHANNEL_5_SMP (ADC_SMPTIM2_REGOFFSET | ((15UL) << ADC_CHANNEL_SMPx_BITOFFSET_POS)) /* Value shifted is equivalent to POSITION_VAL(ADC_SMPTIM2_SMPCYCCFG5) */ +#define ADC_CHANNEL_6_SMP (ADC_SMPTIM2_REGOFFSET | ((18UL) << ADC_CHANNEL_SMPx_BITOFFSET_POS)) /* Value shifted is equivalent to POSITION_VAL(ADC_SMPTIM2_SMPCYCCFG6) */ +#define ADC_CHANNEL_7_SMP (ADC_SMPTIM2_REGOFFSET | ((21UL) << ADC_CHANNEL_SMPx_BITOFFSET_POS)) /* Value shifted is equivalent to POSITION_VAL(ADC_SMPTIM2_SMPCYCCFG7) */ +#define ADC_CHANNEL_8_SMP (ADC_SMPTIM2_REGOFFSET | ((24UL) << ADC_CHANNEL_SMPx_BITOFFSET_POS)) /* Value shifted is equivalent to POSITION_VAL(ADC_SMPTIM2_SMPCYCCFG8) */ +#define ADC_CHANNEL_9_SMP (ADC_SMPTIM2_REGOFFSET | ((27UL) << ADC_CHANNEL_SMPx_BITOFFSET_POS)) /* Value shifted is equivalent to POSITION_VAL(ADC_SMPTIM2_SMPCYCCFG9) */ +#define ADC_CHANNEL_10_SMP (ADC_SMPTIM1_REGOFFSET | (( 0UL) << ADC_CHANNEL_SMPx_BITOFFSET_POS)) /* Value shifted is equivalent to POSITION_VAL(ADC_SMPTIM1_SMPCYCCFG10) */ +#define ADC_CHANNEL_11_SMP (ADC_SMPTIM1_REGOFFSET | (( 3UL) << ADC_CHANNEL_SMPx_BITOFFSET_POS)) /* Value shifted is equivalent to POSITION_VAL(ADC_SMPTIM1_SMPCYCCFG11) */ +#define ADC_CHANNEL_12_SMP (ADC_SMPTIM1_REGOFFSET | (( 6UL) << ADC_CHANNEL_SMPx_BITOFFSET_POS)) /* Value shifted is equivalent to POSITION_VAL(ADC_SMPTIM1_SMPCYCCFG12) */ +#define ADC_CHANNEL_13_SMP (ADC_SMPTIM1_REGOFFSET | (( 9UL) << ADC_CHANNEL_SMPx_BITOFFSET_POS)) /* Value shifted is equivalent to POSITION_VAL(ADC_SMPTIM1_SMPCYCCFG13) */ +#define ADC_CHANNEL_14_SMP (ADC_SMPTIM1_REGOFFSET | ((12UL) << ADC_CHANNEL_SMPx_BITOFFSET_POS)) /* Value shifted is equivalent to POSITION_VAL(ADC_SMPTIM1_SMPCYCCFG14) */ +#define ADC_CHANNEL_15_SMP (ADC_SMPTIM1_REGOFFSET | ((15UL) << ADC_CHANNEL_SMPx_BITOFFSET_POS)) /* Value shifted is equivalent to POSITION_VAL(ADC_SMPTIM1_SMPCYCCFG15) */ +#define ADC_CHANNEL_16_SMP (ADC_SMPTIM1_REGOFFSET | ((18UL) << ADC_CHANNEL_SMPx_BITOFFSET_POS)) /* Value shifted is equivalent to POSITION_VAL(ADC_SMPTIM1_SMPCYCCFG16) */ +#define ADC_CHANNEL_17_SMP (ADC_SMPTIM1_REGOFFSET | ((21UL) << ADC_CHANNEL_SMPx_BITOFFSET_POS)) /* Value shifted is equivalent to POSITION_VAL(ADC_SMPTIM1_SMPCYCCFG17) */ +#define ADC_CHANNEL_18_SMP (ADC_SMPTIM1_REGOFFSET | ((24UL) << ADC_CHANNEL_SMPx_BITOFFSET_POS)) /* Value shifted is equivalent to POSITION_VAL(ADC_SMPTIM1_SMPCYCCFG18) */ + +/* Internal mask for ADC analog watchdog: */ +/* To select into literals DDL_ADC_AWD_CHANNELx_xxx the relevant bits for: */ +/* (concatenation of multiple bits used in different analog watchdogs, */ +/* (feature of several watchdogs not available on all APM32 families)). */ +/* - analog watchdog 1: monitored channel defined by number, */ +/* selection of ADC group (ADC groups regular and-or injected). */ + +/* Internal register offset for ADC analog watchdog channel configuration */ +#define ADC_AWD_CTRL1_REGOFFSET 0x00000000UL + +#define ADC_AWD_CRX_REGOFFSET_MASK (ADC_AWD_CTRL1_REGOFFSET) + +#define ADC_AWD_CTRL1_CHANNEL_MASK (ADC_CTRL1_AWDCHSEL | ADC_CTRL1_INJAWDEN | ADC_CTRL1_REGAWDEN | ADC_CTRL1_AWDSGLEN) +#define ADC_AWD_CR_ALL_CHANNEL_MASK (ADC_AWD_CTRL1_CHANNEL_MASK) + +/* Internal register offset for ADC analog watchdog threshold configuration */ +#define ADC_AWD_TR1_HIGH_REGOFFSET 0x00000000UL +#define ADC_AWD_TR1_LOW_REGOFFSET 0x00000001UL +#define ADC_AWD_TRX_REGOFFSET_MASK (ADC_AWD_TR1_HIGH_REGOFFSET | ADC_AWD_TR1_LOW_REGOFFSET) + +/* ADC registers bits positions */ +#define ADC_CTRL1_RESSEL_BITOFFSET_POS (24UL) /* Value equivalent to POSITION_VAL(ADC_CTRL1_RESSEL) */ +#define ADC_TR_HT_BITOFFSET_POS (16UL) /* Value equivalent to POSITION_VAL(ADC_TR_HT) */ + +/* ADC internal channels related definitions */ +/* Internal voltage reference VrefInt */ +#define VREFINT_CAL_ADDR ((uint16_t*) (0x1FFF7A2AU)) /* Internal voltage reference, address of parameter VREFINT_CAL: VrefInt ADC raw data acquired at temperature 30 DegC (tolerance: +-5 DegC), Vref+ = 3.3 V (tolerance: +-10 mV). */ +#define VREFINT_CAL_VREF ( 3300UL) /* Analog voltage reference (Vref+) value with which temperature sensor has been calibrated in production (tolerance: +-10 mV) (unit: mV). */ +/* Temperature sensor */ +#define TEMPSENSOR_CAL1_ADDR ((uint16_t*) (0x1FFF7A2CU)) /* Internal temperature sensor, address of parameter TS_CAL1: On APM32F4, temperature sensor ADC raw data acquired at temperature 30 DegC (tolerance: +-5 DegC), Vref+ = 3.3 V (tolerance: +-10 mV). */ +#define TEMPSENSOR_CAL2_ADDR ((uint16_t*) (0x1FFF7A2EU)) /* Internal temperature sensor, address of parameter TS_CAL2: On APM32F4, temperature sensor ADC raw data acquired at temperature 110 DegC (tolerance: +-5 DegC), Vref+ = 3.3 V (tolerance: +-10 mV). */ +#define TEMPSENSOR_CAL1_TEMP (( int32_t) 30) /* Internal temperature sensor, temperature at which temperature sensor has been calibrated in production for data into TEMPSENSOR_CAL1_ADDR (tolerance: +-5 DegC) (unit: DegC). */ +#define TEMPSENSOR_CAL2_TEMP (( int32_t) 110) /* Internal temperature sensor, temperature at which temperature sensor has been calibrated in production for data into TEMPSENSOR_CAL2_ADDR (tolerance: +-5 DegC) (unit: DegC). */ +#define TEMPSENSOR_CAL_VREFANALOG ( 3300UL) /* Analog voltage reference (Vref+) voltage with which temperature sensor has been calibrated in production (+-10 mV) (unit: mV). */ + +/** + * @} + */ + + +/* Private macros ------------------------------------------------------------*/ +/** @defgroup ADC_DDL_Private_Macros ADC Private Macros + * @{ + */ + +/** + * @brief Driver macro reserved for internal use: isolate bits with the + * selected mask and shift them to the register LSB + * (shift mask on register position bit 0). + * @param __BITS__ Bits in register 32 bits + * @param __MASK__ Mask in register 32 bits + * @retval Bits in register 32 bits + */ +#define __ADC_MASK_SHIFT(__BITS__, __MASK__) \ + (((__BITS__) & (__MASK__)) >> POSITION_VAL((__MASK__))) + +/** + * @brief Driver macro reserved for internal use: set a pointer to + * a register from a register basis from which an offset + * is applied. + * @param __REG__ Register basis from which the offset is applied. + * @param __REG_OFFFSET__ Offset to be applied (unit number of registers). + * @retval Pointer to register address + */ +#define __ADC_PTR_REG_OFFSET(__REG__, __REG_OFFFSET__) \ + ((__IO uint32_t *)((uint32_t) ((uint32_t)(&(__REG__)) + ((__REG_OFFFSET__) << 2UL)))) + +/** + * @} + */ + + +/* Exported types ------------------------------------------------------------*/ +#if defined(USE_FULL_DDL_DRIVER) +/** @defgroup ADC_DDL_ES_INIT ADC Exported Init structure + * @{ + */ + +/** + * @brief Structure definition of some features of ADC common parameters + * and multimode + * (all ADC instances belonging to the same ADC common instance). + * @note The setting of these parameters by function @ref DDL_ADC_CommonInit() + * is conditioned to ADC instances state (all ADC instances + * sharing the same ADC common instance): + * All ADC instances sharing the same ADC common instance must be + * disabled. + */ +typedef struct +{ + uint32_t CommonClock; /*!< Set parameter common to several ADC: Clock source and prescaler. + This parameter can be a value of @ref ADC_DDL_EC_COMMON_CLOCK_SOURCE + + This feature can be modified afterwards using unitary function @ref DDL_ADC_SetCommonClock(). */ + +#if defined(ADC_MULTIMODE_SUPPORT) + uint32_t Multimode; /*!< Set ADC multimode configuration to operate in independent mode or multimode (for devices with several ADC instances). + This parameter can be a value of @ref ADC_DDL_EC_MULTI_MODE + + This feature can be modified afterwards using unitary function @ref DDL_ADC_SetMultimode(). */ + + uint32_t MultiDMATransfer; /*!< Set ADC multimode conversion data transfer: no transfer or transfer by DMA. + This parameter can be a value of @ref ADC_DDL_EC_MULTI_DMA_TRANSFER + + This feature can be modified afterwards using unitary function @ref DDL_ADC_SetMultiDMATransfer(). */ + + uint32_t MultiTwoSamplingDelay; /*!< Set ADC multimode delay between 2 sampling phases. + This parameter can be a value of @ref ADC_DDL_EC_MULTI_TWOSMP_DELAY + + This feature can be modified afterwards using unitary function @ref DDL_ADC_SetMultiTwoSamplingDelay(). */ +#endif /* ADC_MULTIMODE_SUPPORT */ + +} DDL_ADC_CommonInitTypeDef; + +/** + * @brief Structure definition of some features of ADC instance. + * @note These parameters have an impact on ADC scope: ADC instance. + * Affects both group regular and group injected (availability + * of ADC group injected depends on APM32 families). + * Refer to corresponding unitary functions into + * @ref ADC_DDL_EF_Configuration_ADC_Instance . + * @note The setting of these parameters by function @ref DDL_ADC_Init() + * is conditioned to ADC state: + * ADC instance must be disabled. + * This condition is applied to all ADC features, for efficiency + * and compatibility over all APM32 families. However, the different + * features can be set under different ADC state conditions + * (setting possible with ADC enabled without conversion on going, + * ADC enabled with conversion on going, ...) + * Each feature can be updated afterwards with a unitary function + * and potentially with ADC in a different state than disabled, + * refer to description of each function for setting + * conditioned to ADC state. + */ +typedef struct +{ + uint32_t Resolution; /*!< Set ADC resolution. + This parameter can be a value of @ref ADC_DDL_EC_RESOLUTION + + This feature can be modified afterwards using unitary function @ref DDL_ADC_SetResolution(). */ + + uint32_t DataAlignment; /*!< Set ADC conversion data alignment. + This parameter can be a value of @ref ADC_DDL_EC_DATA_ALIGN + + This feature can be modified afterwards using unitary function @ref DDL_ADC_SetDataAlignment(). */ + + uint32_t SequencersScanMode; /*!< Set ADC scan selection. + This parameter can be a value of @ref ADC_DDL_EC_SCAN_SELECTION + + This feature can be modified afterwards using unitary function @ref DDL_ADC_SetSequencersScanMode(). */ + +} DDL_ADC_InitTypeDef; + +/** + * @brief Structure definition of some features of ADC group regular. + * @note These parameters have an impact on ADC scope: ADC group regular. + * Refer to corresponding unitary functions into + * @ref ADC_DDL_EF_Configuration_ADC_Group_Regular + * (functions with prefix "REG"). + * @note The setting of these parameters by function @ref DDL_ADC_REG_Init() + * is conditioned to ADC state: + * ADC instance must be disabled. + * This condition is applied to all ADC features, for efficiency + * and compatibility over all APM32 families. However, the different + * features can be set under different ADC state conditions + * (setting possible with ADC enabled without conversion on going, + * ADC enabled with conversion on going, ...) + * Each feature can be updated afterwards with a unitary function + * and potentially with ADC in a different state than disabled, + * refer to description of each function for setting + * conditioned to ADC state. + */ +typedef struct +{ + uint32_t TriggerSource; /*!< Set ADC group regular conversion trigger source: internal (SW start) or from external IP (timer event, external interrupt line). + This parameter can be a value of @ref ADC_DDL_EC_REG_TRIGGER_SOURCE + @note On this APM32 series, setting of external trigger edge is performed + using function @ref DDL_ADC_REG_StartConversionExtTrig(). + + This feature can be modified afterwards using unitary function @ref DDL_ADC_REG_SetTriggerSource(). */ + + uint32_t SequencerLength; /*!< Set ADC group regular sequencer length. + This parameter can be a value of @ref ADC_DDL_EC_REG_SEQ_SCAN_LENGTH + @note This parameter is discarded if scan mode is disabled (refer to parameter 'ADC_SequencersScanMode'). + + This feature can be modified afterwards using unitary function @ref DDL_ADC_REG_SetSequencerLength(). */ + + uint32_t SequencerDiscont; /*!< Set ADC group regular sequencer discontinuous mode: sequence subdivided and scan conversions interrupted every selected number of ranks. + This parameter can be a value of @ref ADC_DDL_EC_REG_SEQ_DISCONT_MODE + @note This parameter has an effect only if group regular sequencer is enabled + (scan length of 2 ranks or more). + + This feature can be modified afterwards using unitary function @ref DDL_ADC_REG_SetSequencerDiscont(). */ + + uint32_t ContinuousMode; /*!< Set ADC continuous conversion mode on ADC group regular, whether ADC conversions are performed in single mode (one conversion per trigger) or in continuous mode (after the first trigger, following conversions launched successively automatically). + This parameter can be a value of @ref ADC_DDL_EC_REG_CONTINUOUS_MODE + Note: It is not possible to enable both ADC group regular continuous mode and discontinuous mode. + + This feature can be modified afterwards using unitary function @ref DDL_ADC_REG_SetContinuousMode(). */ + + uint32_t DMATransfer; /*!< Set ADC group regular conversion data transfer: no transfer or transfer by DMA, and DMA requests mode. + This parameter can be a value of @ref ADC_DDL_EC_REG_DMA_TRANSFER + + This feature can be modified afterwards using unitary function @ref DDL_ADC_REG_SetDMATransfer(). */ + +} DDL_ADC_REG_InitTypeDef; + +/** + * @brief Structure definition of some features of ADC group injected. + * @note These parameters have an impact on ADC scope: ADC group injected. + * Refer to corresponding unitary functions into + * @ref ADC_DDL_EF_Configuration_ADC_Group_Regular + * (functions with prefix "INJ"). + * @note The setting of these parameters by function @ref DDL_ADC_INJ_Init() + * is conditioned to ADC state: + * ADC instance must be disabled. + * This condition is applied to all ADC features, for efficiency + * and compatibility over all APM32 families. However, the different + * features can be set under different ADC state conditions + * (setting possible with ADC enabled without conversion on going, + * ADC enabled with conversion on going, ...) + * Each feature can be updated afterwards with a unitary function + * and potentially with ADC in a different state than disabled, + * refer to description of each function for setting + * conditioned to ADC state. + */ +typedef struct +{ + uint32_t TriggerSource; /*!< Set ADC group injected conversion trigger source: internal (SW start) or from external IP (timer event, external interrupt line). + This parameter can be a value of @ref ADC_DDL_EC_INJ_TRIGGER_SOURCE + @note On this APM32 series, setting of external trigger edge is performed + using function @ref DDL_ADC_INJ_StartConversionExtTrig(). + + This feature can be modified afterwards using unitary function @ref DDL_ADC_INJ_SetTriggerSource(). */ + + uint32_t SequencerLength; /*!< Set ADC group injected sequencer length. + This parameter can be a value of @ref ADC_DDL_EC_INJ_SEQ_SCAN_LENGTH + @note This parameter is discarded if scan mode is disabled (refer to parameter 'ADC_SequencersScanMode'). + + This feature can be modified afterwards using unitary function @ref DDL_ADC_INJ_SetSequencerLength(). */ + + uint32_t SequencerDiscont; /*!< Set ADC group injected sequencer discontinuous mode: sequence subdivided and scan conversions interrupted every selected number of ranks. + This parameter can be a value of @ref ADC_DDL_EC_INJ_SEQ_DISCONT_MODE + @note This parameter has an effect only if group injected sequencer is enabled + (scan length of 2 ranks or more). + + This feature can be modified afterwards using unitary function @ref DDL_ADC_INJ_SetSequencerDiscont(). */ + + uint32_t TrigAuto; /*!< Set ADC group injected conversion trigger: independent or from ADC group regular. + This parameter can be a value of @ref ADC_DDL_EC_INJ_TRIG_AUTO + Note: This parameter must be set to set to independent trigger if injected trigger source is set to an external trigger. + + This feature can be modified afterwards using unitary function @ref DDL_ADC_INJ_SetTrigAuto(). */ + +} DDL_ADC_INJ_InitTypeDef; + +/** + * @} + */ +#endif /* USE_FULL_DDL_DRIVER */ + +/* Exported constants --------------------------------------------------------*/ +/** @defgroup ADC_DDL_Exported_Constants ADC Exported Constants + * @{ + */ + +/** @defgroup ADC_DDL_EC_FLAG ADC flags + * @brief Flags defines which can be used with DDL_ADC_ReadReg function + * @{ + */ +#define DDL_ADC_FLAG_STRT ADC_STS_REGCSFLG /*!< ADC flag ADC group regular conversion start */ +#define DDL_ADC_FLAG_EOCS ADC_STS_EOCFLG /*!< ADC flag ADC group regular end of unitary conversion or sequence conversions (to configure flag of end of conversion, use function @ref DDL_ADC_REG_SetFlagEndOfConversion() ) */ +#define DDL_ADC_FLAG_OVR ADC_STS_OVRFLG /*!< ADC flag ADC group regular overrun */ +#define DDL_ADC_FLAG_JSTRT ADC_STS_INJCSFLG /*!< ADC flag ADC group injected conversion start */ +#define DDL_ADC_FLAG_JEOS ADC_STS_INJEOCFLG /*!< ADC flag ADC group injected end of sequence conversions (Note: on this APM32 series, there is no flag ADC group injected end of unitary conversion. Flag noted as "JEOC" is corresponding to flag "JEOS" in other APM32 families) */ +#define DDL_ADC_FLAG_AWD1 ADC_STS_AWDFLG /*!< ADC flag ADC analog watchdog 1 */ +#if defined(ADC_MULTIMODE_SUPPORT) +#define DDL_ADC_FLAG_EOCS_MST ADC_CSTS_EOCFLG1 /*!< ADC flag ADC multimode master group regular end of unitary conversion or sequence conversions (to configure flag of end of conversion, use function @ref DDL_ADC_REG_SetFlagEndOfConversion() ) */ +#define DDL_ADC_FLAG_EOCS_SLV1 ADC_CSTS_EOCFLG2 /*!< ADC flag ADC multimode slave 1 group regular end of unitary conversion or sequence conversions (to configure flag of end of conversion, use function @ref DDL_ADC_REG_SetFlagEndOfConversion() ) */ +#define DDL_ADC_FLAG_EOCS_SLV2 ADC_CSTS_EOCFLG3 /*!< ADC flag ADC multimode slave 2 group regular end of unitary conversion or sequence conversions (to configure flag of end of conversion, use function @ref DDL_ADC_REG_SetFlagEndOfConversion() ) */ +#define DDL_ADC_FLAG_OVR_MST ADC_CSTS_OVRFLG1 /*!< ADC flag ADC multimode master group regular overrun */ +#define DDL_ADC_FLAG_OVR_SLV1 ADC_CSTS_OVRFLG2 /*!< ADC flag ADC multimode slave 1 group regular overrun */ +#define DDL_ADC_FLAG_OVR_SLV2 ADC_CSTS_OVRFLG3 /*!< ADC flag ADC multimode slave 2 group regular overrun */ +#define DDL_ADC_FLAG_JEOS_MST ADC_CSTS_INJEOCFLG1 /*!< ADC flag ADC multimode master group injected end of sequence conversions (Note: on this APM32 series, there is no flag ADC group injected end of unitary conversion. Flag noted as "JEOC" is corresponding to flag "JEOS" in other APM32 families) */ +#define DDL_ADC_FLAG_JEOS_SLV1 ADC_CSTS_INJEOCFLG2 /*!< ADC flag ADC multimode slave 1 group injected end of sequence conversions (Note: on this APM32 series, there is no flag ADC group injected end of unitary conversion. Flag noted as "JEOC" is corresponding to flag "JEOS" in other APM32 families) */ +#define DDL_ADC_FLAG_JEOS_SLV2 ADC_CSTS_INJEOCFLG3 /*!< ADC flag ADC multimode slave 2 group injected end of sequence conversions (Note: on this APM32 series, there is no flag ADC group injected end of unitary conversion. Flag noted as "JEOC" is corresponding to flag "JEOS" in other APM32 families) */ +#define DDL_ADC_FLAG_AWD1_MST ADC_CSTS_AWDFLG1 /*!< ADC flag ADC multimode master analog watchdog 1 of the ADC master */ +#define DDL_ADC_FLAG_AWD1_SLV1 ADC_CSTS_AWDFLG2 /*!< ADC flag ADC multimode slave 1 analog watchdog 1 */ +#define DDL_ADC_FLAG_AWD1_SLV2 ADC_CSTS_AWDFLG3 /*!< ADC flag ADC multimode slave 2 analog watchdog 1 */ +#endif +/** + * @} + */ + +/** @defgroup ADC_DDL_EC_IT ADC interruptions for configuration (interruption enable or disable) + * @brief IT defines which can be used with DDL_ADC_ReadReg and DDL_ADC_WriteReg functions + * @{ + */ +#define DDL_ADC_IT_EOCS ADC_CTRL1_EOCIEN /*!< ADC interruption ADC group regular end of unitary conversion or sequence conversions (to configure flag of end of conversion, use function @ref DDL_ADC_REG_SetFlagEndOfConversion() ) */ +#define DDL_ADC_IT_OVR ADC_CTRL1_OVRIEN /*!< ADC interruption ADC group regular overrun */ +#define DDL_ADC_IT_JEOS ADC_CTRL1_INJEOCIEN /*!< ADC interruption ADC group injected end of sequence conversions (Note: on this APM32 series, there is no flag ADC group injected end of unitary conversion. Flag noted as "JEOC" is corresponding to flag "JEOS" in other APM32 families) */ +#define DDL_ADC_IT_AWD1 ADC_CTRL1_AWDIEN /*!< ADC interruption ADC analog watchdog 1 */ +/** + * @} + */ + +/** @defgroup ADC_DDL_EC_REGISTERS ADC registers compliant with specific purpose + * @{ + */ +/* List of ADC registers intended to be used (most commonly) with */ +/* DMA transfer. */ +/* Refer to function @ref DDL_ADC_DMA_GetRegAddr(). */ +#define DDL_ADC_DMA_REG_REGULAR_DATA 0x00000000UL /* ADC group regular conversion data register (corresponding to register DR) to be used with ADC configured in independent mode. Without DMA transfer, register accessed by LL function @ref DDL_ADC_REG_ReadConversionData32() and other functions @ref DDL_ADC_REG_ReadConversionDatax() */ +#if defined(ADC_MULTIMODE_SUPPORT) +#define DDL_ADC_DMA_REG_REGULAR_DATA_MULTI 0x00000001UL /* ADC group regular conversion data register (corresponding to register CDR) to be used with ADC configured in multimode (available on APM32 devices with several ADC instances). Without DMA transfer, register accessed by LL function @ref DDL_ADC_REG_ReadMultiConversionData32() */ +#endif +/** + * @} + */ + +/** @defgroup ADC_DDL_EC_COMMON_CLOCK_SOURCE ADC common - Clock source + * @{ + */ +#define DDL_ADC_CLOCK_SYNC_PCLK_DIV2 0x00000000UL /*!< ADC synchronous clock derived from AHB clock with prescaler division by 2 */ +#define DDL_ADC_CLOCK_SYNC_PCLK_DIV4 ( ADC_CCTRL_ADCPRE_0) /*!< ADC synchronous clock derived from AHB clock with prescaler division by 4 */ +#define DDL_ADC_CLOCK_SYNC_PCLK_DIV6 (ADC_CCTRL_ADCPRE_1 ) /*!< ADC synchronous clock derived from AHB clock with prescaler division by 6 */ +#define DDL_ADC_CLOCK_SYNC_PCLK_DIV8 (ADC_CCTRL_ADCPRE_1 | ADC_CCTRL_ADCPRE_0) /*!< ADC synchronous clock derived from AHB clock with prescaler division by 8 */ +/** + * @} + */ + +/** @defgroup ADC_DDL_EC_COMMON_PATH_INTERNAL ADC common - Measurement path to internal channels + * @{ + */ +/* Note: Other measurement paths to internal channels may be available */ +/* (connections to other peripherals). */ +/* If they are not listed below, they do not require any specific */ +/* path enable. In this case, Access to measurement path is done */ +/* only by selecting the corresponding ADC internal channel. */ +#define DDL_ADC_PATH_INTERNAL_NONE 0x00000000UL /*!< ADC measurement paths all disabled */ +#define DDL_ADC_PATH_INTERNAL_VREFINT (ADC_CCTRL_TSVREFEN) /*!< ADC measurement path to internal channel VrefInt */ +#define DDL_ADC_PATH_INTERNAL_TEMPSENSOR (ADC_CCTRL_TSVREFEN) /*!< ADC measurement path to internal channel temperature sensor */ +#define DDL_ADC_PATH_INTERNAL_VBAT (ADC_CCTRL_VBATEN) /*!< ADC measurement path to internal channel Vbat */ +/** + * @} + */ + +/** @defgroup ADC_DDL_EC_RESOLUTION ADC instance - Resolution + * @{ + */ +#define DDL_ADC_RESOLUTION_12B 0x00000000UL /*!< ADC resolution 12 bits */ +#define DDL_ADC_RESOLUTION_10B ( ADC_CTRL1_RESSEL_0) /*!< ADC resolution 10 bits */ +#define DDL_ADC_RESOLUTION_8B (ADC_CTRL1_RESSEL_1 ) /*!< ADC resolution 8 bits */ +#define DDL_ADC_RESOLUTION_6B (ADC_CTRL1_RESSEL_1 | ADC_CTRL1_RESSEL_0) /*!< ADC resolution 6 bits */ +/** + * @} + */ + +/** @defgroup ADC_DDL_EC_DATA_ALIGN ADC instance - Data alignment + * @{ + */ +#define DDL_ADC_DATA_ALIGN_RIGHT 0x00000000UL /*!< ADC conversion data alignment: right aligned (alignment on data register LSB bit 0)*/ +#define DDL_ADC_DATA_ALIGN_LEFT (ADC_CTRL2_DALIGNCFG) /*!< ADC conversion data alignment: left aligned (alignment on data register MSB bit 15)*/ +/** + * @} + */ + +/** @defgroup ADC_DDL_EC_SCAN_SELECTION ADC instance - Scan selection + * @{ + */ +#define DDL_ADC_SEQ_SCAN_DISABLE 0x00000000UL /*!< ADC conversion is performed in unitary conversion mode (one channel converted, that defined in rank 1). Configuration of both groups regular and injected sequencers (sequence length, ...) is discarded: equivalent to length of 1 rank.*/ +#define DDL_ADC_SEQ_SCAN_ENABLE (ADC_CTRL1_SCANEN) /*!< ADC conversions are performed in sequence conversions mode, according to configuration of both groups regular and injected sequencers (sequence length, ...). */ +/** + * @} + */ + +/** @defgroup ADC_DDL_EC_GROUPS ADC instance - Groups + * @{ + */ +#define DDL_ADC_GROUP_REGULAR 0x00000001UL /*!< ADC group regular (available on all APM32 devices) */ +#define DDL_ADC_GROUP_INJECTED 0x00000002UL /*!< ADC group injected (not available on all APM32 devices)*/ +#define DDL_ADC_GROUP_REGULAR_INJECTED 0x00000003UL /*!< ADC both groups regular and injected */ +/** + * @} + */ + +/** @defgroup ADC_DDL_EC_CHANNEL ADC instance - Channel number + * @{ + */ +#define DDL_ADC_CHANNEL_0 (ADC_CHANNEL_0_NUMBER | ADC_CHANNEL_0_SMP) /*!< ADC external channel (channel connected to GPIO pin) ADCx_IN0 */ +#define DDL_ADC_CHANNEL_1 (ADC_CHANNEL_1_NUMBER | ADC_CHANNEL_1_SMP) /*!< ADC external channel (channel connected to GPIO pin) ADCx_IN1 */ +#define DDL_ADC_CHANNEL_2 (ADC_CHANNEL_2_NUMBER | ADC_CHANNEL_2_SMP) /*!< ADC external channel (channel connected to GPIO pin) ADCx_IN2 */ +#define DDL_ADC_CHANNEL_3 (ADC_CHANNEL_3_NUMBER | ADC_CHANNEL_3_SMP) /*!< ADC external channel (channel connected to GPIO pin) ADCx_IN3 */ +#define DDL_ADC_CHANNEL_4 (ADC_CHANNEL_4_NUMBER | ADC_CHANNEL_4_SMP) /*!< ADC external channel (channel connected to GPIO pin) ADCx_IN4 */ +#define DDL_ADC_CHANNEL_5 (ADC_CHANNEL_5_NUMBER | ADC_CHANNEL_5_SMP) /*!< ADC external channel (channel connected to GPIO pin) ADCx_IN5 */ +#define DDL_ADC_CHANNEL_6 (ADC_CHANNEL_6_NUMBER | ADC_CHANNEL_6_SMP) /*!< ADC external channel (channel connected to GPIO pin) ADCx_IN6 */ +#define DDL_ADC_CHANNEL_7 (ADC_CHANNEL_7_NUMBER | ADC_CHANNEL_7_SMP) /*!< ADC external channel (channel connected to GPIO pin) ADCx_IN7 */ +#define DDL_ADC_CHANNEL_8 (ADC_CHANNEL_8_NUMBER | ADC_CHANNEL_8_SMP) /*!< ADC external channel (channel connected to GPIO pin) ADCx_IN8 */ +#define DDL_ADC_CHANNEL_9 (ADC_CHANNEL_9_NUMBER | ADC_CHANNEL_9_SMP) /*!< ADC external channel (channel connected to GPIO pin) ADCx_IN9 */ +#define DDL_ADC_CHANNEL_10 (ADC_CHANNEL_10_NUMBER | ADC_CHANNEL_10_SMP) /*!< ADC external channel (channel connected to GPIO pin) ADCx_IN10 */ +#define DDL_ADC_CHANNEL_11 (ADC_CHANNEL_11_NUMBER | ADC_CHANNEL_11_SMP) /*!< ADC external channel (channel connected to GPIO pin) ADCx_IN11 */ +#define DDL_ADC_CHANNEL_12 (ADC_CHANNEL_12_NUMBER | ADC_CHANNEL_12_SMP) /*!< ADC external channel (channel connected to GPIO pin) ADCx_IN12 */ +#define DDL_ADC_CHANNEL_13 (ADC_CHANNEL_13_NUMBER | ADC_CHANNEL_13_SMP) /*!< ADC external channel (channel connected to GPIO pin) ADCx_IN13 */ +#define DDL_ADC_CHANNEL_14 (ADC_CHANNEL_14_NUMBER | ADC_CHANNEL_14_SMP) /*!< ADC external channel (channel connected to GPIO pin) ADCx_IN14 */ +#define DDL_ADC_CHANNEL_15 (ADC_CHANNEL_15_NUMBER | ADC_CHANNEL_15_SMP) /*!< ADC external channel (channel connected to GPIO pin) ADCx_IN15 */ +#define DDL_ADC_CHANNEL_16 (ADC_CHANNEL_16_NUMBER | ADC_CHANNEL_16_SMP) /*!< ADC external channel (channel connected to GPIO pin) ADCx_IN16 */ +#define DDL_ADC_CHANNEL_17 (ADC_CHANNEL_17_NUMBER | ADC_CHANNEL_17_SMP) /*!< ADC external channel (channel connected to GPIO pin) ADCx_IN17 */ +#define DDL_ADC_CHANNEL_18 (ADC_CHANNEL_18_NUMBER | ADC_CHANNEL_18_SMP) /*!< ADC external channel (channel connected to GPIO pin) ADCx_IN18 */ +#define DDL_ADC_CHANNEL_VREFINT (DDL_ADC_CHANNEL_17 | ADC_CHANNEL_ID_INTERNAL_CH) /*!< ADC internal channel connected to VrefInt: Internal voltage reference. On APM32F4, ADC channel available only on ADC instance: ADC1. */ +#define DDL_ADC_CHANNEL_VBAT (DDL_ADC_CHANNEL_18 | ADC_CHANNEL_ID_INTERNAL_CH) /*!< ADC internal channel connected to Vbat/3: Vbat voltage through a divider ladder of factor 1/3 to have Vbat always below Vdda. On APM32F4, ADC channel available only on ADC instance: ADC1. */ +#if defined(APM32F405xx) || defined(APM32F407xx) || defined(APM32F417xx) || defined(APM32F465xx) +#define DDL_ADC_CHANNEL_TEMPSENSOR (DDL_ADC_CHANNEL_16 | ADC_CHANNEL_ID_INTERNAL_CH) /*!< ADC internal channel connected to Temperature sensor. On APM32F4, ADC channel available only on ADC instance: ADC1. */ +#endif /* APM32F405xx || APM32F407xx || APM32F417xx || APM32F465xx */ +#if defined(APM32F411xx) +#define DDL_ADC_CHANNEL_TEMPSENSOR (DDL_ADC_CHANNEL_18 | ADC_CHANNEL_ID_INTERNAL_CH | ADC_CHANNEL_DIFFERENCIATION_TEMPSENSOR_VBAT) /*!< ADC internal channel connected to Temperature sensor. On APM32F4, ADC channel available only on ADC instance: ADC1. This internal channel is shared between temperature sensor and Vbat, only 1 measurement path must be enabled. */ +#endif /* APM32F411xx */ +/** + * @} + */ + +/** @defgroup ADC_DDL_EC_REG_TRIGGER_SOURCE ADC group regular - Trigger source + * @{ + */ +#define DDL_ADC_REG_TRIG_SOFTWARE 0x00000000UL /*!< ADC group regular conversion trigger internal: SW start. */ +#define DDL_ADC_REG_TRIG_EXT_TMR1_CH1 (ADC_REG_TRIG_EXT_EDGE_DEFAULT) /*!< ADC group regular conversion trigger from external IP: TIM1 channel 1 event (capture compare: input capture or output capture). Trigger edge set to rising edge (default setting). */ +#define DDL_ADC_REG_TRIG_EXT_TMR1_CH2 (ADC_CTRL2_REGEXTTRGSEL_0 | ADC_REG_TRIG_EXT_EDGE_DEFAULT) /*!< ADC group regular conversion trigger from external IP: TIM1 channel 2 event (capture compare: input capture or output capture). Trigger edge set to rising edge (default setting). */ +#define DDL_ADC_REG_TRIG_EXT_TMR1_CH3 (ADC_CTRL2_REGEXTTRGSEL_1 | ADC_REG_TRIG_EXT_EDGE_DEFAULT) /*!< ADC group regular conversion trigger from external IP: TIM1 channel 3 event (capture compare: input capture or output capture). Trigger edge set to rising edge (default setting). */ +#define DDL_ADC_REG_TRIG_EXT_TMR2_CH2 (ADC_CTRL2_REGEXTTRGSEL_1 | ADC_CTRL2_REGEXTTRGSEL_0 | ADC_REG_TRIG_EXT_EDGE_DEFAULT) /*!< ADC group regular conversion trigger from external IP: TIM2 channel 2 event (capture compare: input capture or output capture). Trigger edge set to rising edge (default setting). */ +#define DDL_ADC_REG_TRIG_EXT_TMR2_CH3 (ADC_CTRL2_REGEXTTRGSEL_2 | ADC_REG_TRIG_EXT_EDGE_DEFAULT) /*!< ADC group regular conversion trigger from external IP: TIM2 channel 3 event (capture compare: input capture or output capture). Trigger edge set to rising edge (default setting). */ +#define DDL_ADC_REG_TRIG_EXT_TMR2_CH4 (ADC_CTRL2_REGEXTTRGSEL_2 | ADC_CTRL2_REGEXTTRGSEL_0 | ADC_REG_TRIG_EXT_EDGE_DEFAULT) /*!< ADC group regular conversion trigger from external IP: TIM2 channel 4 event (capture compare: input capture or output capture). Trigger edge set to rising edge (default setting). */ +#define DDL_ADC_REG_TRIG_EXT_TMR2_TRGO (ADC_CTRL2_REGEXTTRGSEL_2 | ADC_CTRL2_REGEXTTRGSEL_1 | ADC_REG_TRIG_EXT_EDGE_DEFAULT) /*!< ADC group regular conversion trigger from external IP: TIM2 TRGO. Trigger edge set to rising edge (default setting). */ +#define DDL_ADC_REG_TRIG_EXT_TMR3_CH1 (ADC_CTRL2_REGEXTTRGSEL_2 | ADC_CTRL2_REGEXTTRGSEL_1 | ADC_CTRL2_REGEXTTRGSEL_0 | ADC_REG_TRIG_EXT_EDGE_DEFAULT) /*!< ADC group regular conversion trigger from external IP: TIM3 channel 1 event (capture compare: input capture or output capture). Trigger edge set to rising edge (default setting). */ +#define DDL_ADC_REG_TRIG_EXT_TMR3_TRGO (ADC_CTRL2_REGEXTTRGSEL_3 | ADC_REG_TRIG_EXT_EDGE_DEFAULT) /*!< ADC group regular conversion trigger from external IP: TIM3 TRGO. Trigger edge set to rising edge (default setting). */ +#define DDL_ADC_REG_TRIG_EXT_TMR4_CH4 (ADC_CTRL2_REGEXTTRGSEL_3 | ADC_CTRL2_REGEXTTRGSEL_0 | ADC_REG_TRIG_EXT_EDGE_DEFAULT) /*!< ADC group regular conversion trigger from external IP: TIM4 channel 4 event (capture compare: input capture or output capture). Trigger edge set to rising edge (default setting). */ +#define DDL_ADC_REG_TRIG_EXT_TMR5_CH1 (ADC_CTRL2_REGEXTTRGSEL_3 | ADC_CTRL2_REGEXTTRGSEL_1 | ADC_REG_TRIG_EXT_EDGE_DEFAULT) /*!< ADC group regular conversion trigger from external IP: TIM5 channel 1 event (capture compare: input capture or output capture). Trigger edge set to rising edge (default setting). */ +#define DDL_ADC_REG_TRIG_EXT_TMR5_CH2 (ADC_CTRL2_REGEXTTRGSEL_3 | ADC_CTRL2_REGEXTTRGSEL_1 | ADC_CTRL2_REGEXTTRGSEL_0 | ADC_REG_TRIG_EXT_EDGE_DEFAULT) /*!< ADC group regular conversion trigger from external IP: TIM5 channel 2 event (capture compare: input capture or output capture). Trigger edge set to rising edge (default setting). */ +#define DDL_ADC_REG_TRIG_EXT_TMR5_CH3 (ADC_CTRL2_REGEXTTRGSEL_3 | ADC_CTRL2_REGEXTTRGSEL_2 | ADC_REG_TRIG_EXT_EDGE_DEFAULT) /*!< ADC group regular conversion trigger from external IP: TIM5 channel 3 event (capture compare: input capture or output capture). Trigger edge set to rising edge (default setting). */ +#define DDL_ADC_REG_TRIG_EXT_TMR8_CH1 (ADC_CTRL2_REGEXTTRGSEL_3 | ADC_CTRL2_REGEXTTRGSEL_2 | ADC_CTRL2_REGEXTTRGSEL_0 | ADC_REG_TRIG_EXT_EDGE_DEFAULT) /*!< ADC group regular conversion trigger from external IP: TIM8 channel 1 event (capture compare: input capture or output capture). Trigger edge set to rising edge (default setting). */ +#define DDL_ADC_REG_TRIG_EXT_TMR8_TRGO (ADC_CTRL2_REGEXTTRGSEL_3 | ADC_CTRL2_REGEXTTRGSEL_2 | ADC_CTRL2_REGEXTTRGSEL_1 | ADC_REG_TRIG_EXT_EDGE_DEFAULT) /*!< ADC group regular conversion trigger from external IP: TIM8 TRGO. Trigger edge set to rising edge (default setting). */ +#define DDL_ADC_REG_TRIG_EXT_EINT_LINE11 (ADC_CTRL2_REGEXTTRGSEL_3 | ADC_CTRL2_REGEXTTRGSEL_2 | ADC_CTRL2_REGEXTTRGSEL_1 | ADC_CTRL2_REGEXTTRGSEL_0 | ADC_REG_TRIG_EXT_EDGE_DEFAULT) /*!< ADC group regular conversion trigger from external IP: external interrupt line 11. Trigger edge set to rising edge (default setting). */ +/** + * @} + */ + +/** @defgroup ADC_DDL_EC_REG_TRIGGER_EDGE ADC group regular - Trigger edge + * @{ + */ +#define DDL_ADC_REG_TRIG_EXT_RISING ( ADC_CTRL2_REGEXTTRGEN_0) /*!< ADC group regular conversion trigger polarity set to rising edge */ +#define DDL_ADC_REG_TRIG_EXT_FALLING (ADC_CTRL2_REGEXTTRGEN_1 ) /*!< ADC group regular conversion trigger polarity set to falling edge */ +#define DDL_ADC_REG_TRIG_EXT_RISINGFALLING (ADC_CTRL2_REGEXTTRGEN_1 | ADC_CTRL2_REGEXTTRGEN_0) /*!< ADC group regular conversion trigger polarity set to both rising and falling edges */ +/** + * @} + */ + +/** @defgroup ADC_DDL_EC_REG_CONTINUOUS_MODE ADC group regular - Continuous mode +* @{ +*/ +#define DDL_ADC_REG_CONV_SINGLE 0x00000000UL /*!< ADC conversions are performed in single mode: one conversion per trigger */ +#define DDL_ADC_REG_CONV_CONTINUOUS (ADC_CTRL2_CONTCEN) /*!< ADC conversions are performed in continuous mode: after the first trigger, following conversions launched successively automatically */ +/** + * @} + */ + +/** @defgroup ADC_DDL_EC_REG_DMA_TRANSFER ADC group regular - DMA transfer of ADC conversion data + * @{ + */ +#define DDL_ADC_REG_DMA_TRANSFER_NONE 0x00000000UL /*!< ADC conversions are not transferred by DMA */ +#define DDL_ADC_REG_DMA_TRANSFER_LIMITED ( ADC_CTRL2_DMAEN) /*!< ADC conversion data are transferred by DMA, in limited mode (one shot mode): DMA transfer requests are stopped when number of DMA data transfers (number of ADC conversions) is reached. This ADC mode is intended to be used with DMA mode non-circular. */ +#define DDL_ADC_REG_DMA_TRANSFER_UNLIMITED (ADC_CTRL2_DMADISSEL | ADC_CTRL2_DMAEN) /*!< ADC conversion data are transferred by DMA, in unlimited mode: DMA transfer requests are unlimited, whatever number of DMA data transferred (number of ADC conversions). This ADC mode is intended to be used with DMA mode circular. */ +/** + * @} + */ + +/** @defgroup ADC_DDL_EC_REG_FLAG_EOC_SELECTION ADC group regular - Flag EOC selection (unitary or sequence conversions) + * @{ + */ +#define DDL_ADC_REG_FLAG_EOC_SEQUENCE_CONV 0x00000000UL /*!< ADC flag EOC (end of unitary conversion) selected */ +#define DDL_ADC_REG_FLAG_EOC_UNITARY_CONV (ADC_CTRL2_EOCSEL) /*!< ADC flag EOS (end of sequence conversions) selected */ +/** + * @} + */ + +/** @defgroup ADC_DDL_EC_REG_SEQ_SCAN_LENGTH ADC group regular - Sequencer scan length + * @{ + */ +#define DDL_ADC_REG_SEQ_SCAN_DISABLE 0x00000000UL /*!< ADC group regular sequencer disable (equivalent to sequencer of 1 rank: ADC conversion on only 1 channel) */ +#define DDL_ADC_REG_SEQ_SCAN_ENABLE_2RANKS ( ADC_REGSEQ1_REGSEQLEN_0) /*!< ADC group regular sequencer enable with 2 ranks in the sequence */ +#define DDL_ADC_REG_SEQ_SCAN_ENABLE_3RANKS ( ADC_REGSEQ1_REGSEQLEN_1 ) /*!< ADC group regular sequencer enable with 3 ranks in the sequence */ +#define DDL_ADC_REG_SEQ_SCAN_ENABLE_4RANKS ( ADC_REGSEQ1_REGSEQLEN_1 | ADC_REGSEQ1_REGSEQLEN_0) /*!< ADC group regular sequencer enable with 4 ranks in the sequence */ +#define DDL_ADC_REG_SEQ_SCAN_ENABLE_5RANKS ( ADC_REGSEQ1_REGSEQLEN_2 ) /*!< ADC group regular sequencer enable with 5 ranks in the sequence */ +#define DDL_ADC_REG_SEQ_SCAN_ENABLE_6RANKS ( ADC_REGSEQ1_REGSEQLEN_2 | ADC_REGSEQ1_REGSEQLEN_0) /*!< ADC group regular sequencer enable with 6 ranks in the sequence */ +#define DDL_ADC_REG_SEQ_SCAN_ENABLE_7RANKS ( ADC_REGSEQ1_REGSEQLEN_2 | ADC_REGSEQ1_REGSEQLEN_1 ) /*!< ADC group regular sequencer enable with 7 ranks in the sequence */ +#define DDL_ADC_REG_SEQ_SCAN_ENABLE_8RANKS ( ADC_REGSEQ1_REGSEQLEN_2 | ADC_REGSEQ1_REGSEQLEN_1 | ADC_REGSEQ1_REGSEQLEN_0) /*!< ADC group regular sequencer enable with 8 ranks in the sequence */ +#define DDL_ADC_REG_SEQ_SCAN_ENABLE_9RANKS (ADC_REGSEQ1_REGSEQLEN_3 ) /*!< ADC group regular sequencer enable with 9 ranks in the sequence */ +#define DDL_ADC_REG_SEQ_SCAN_ENABLE_10RANKS (ADC_REGSEQ1_REGSEQLEN_3 | ADC_REGSEQ1_REGSEQLEN_0) /*!< ADC group regular sequencer enable with 10 ranks in the sequence */ +#define DDL_ADC_REG_SEQ_SCAN_ENABLE_11RANKS (ADC_REGSEQ1_REGSEQLEN_3 | ADC_REGSEQ1_REGSEQLEN_1 ) /*!< ADC group regular sequencer enable with 11 ranks in the sequence */ +#define DDL_ADC_REG_SEQ_SCAN_ENABLE_12RANKS (ADC_REGSEQ1_REGSEQLEN_3 | ADC_REGSEQ1_REGSEQLEN_1 | ADC_REGSEQ1_REGSEQLEN_0) /*!< ADC group regular sequencer enable with 12 ranks in the sequence */ +#define DDL_ADC_REG_SEQ_SCAN_ENABLE_13RANKS (ADC_REGSEQ1_REGSEQLEN_3 | ADC_REGSEQ1_REGSEQLEN_2 ) /*!< ADC group regular sequencer enable with 13 ranks in the sequence */ +#define DDL_ADC_REG_SEQ_SCAN_ENABLE_14RANKS (ADC_REGSEQ1_REGSEQLEN_3 | ADC_REGSEQ1_REGSEQLEN_2 | ADC_REGSEQ1_REGSEQLEN_0) /*!< ADC group regular sequencer enable with 14 ranks in the sequence */ +#define DDL_ADC_REG_SEQ_SCAN_ENABLE_15RANKS (ADC_REGSEQ1_REGSEQLEN_3 | ADC_REGSEQ1_REGSEQLEN_2 | ADC_REGSEQ1_REGSEQLEN_1 ) /*!< ADC group regular sequencer enable with 15 ranks in the sequence */ +#define DDL_ADC_REG_SEQ_SCAN_ENABLE_16RANKS (ADC_REGSEQ1_REGSEQLEN_3 | ADC_REGSEQ1_REGSEQLEN_2 | ADC_REGSEQ1_REGSEQLEN_1 | ADC_REGSEQ1_REGSEQLEN_0) /*!< ADC group regular sequencer enable with 16 ranks in the sequence */ +/** + * @} + */ + +/** @defgroup ADC_DDL_EC_REG_SEQ_DISCONT_MODE ADC group regular - Sequencer discontinuous mode + * @{ + */ +#define DDL_ADC_REG_SEQ_DISCONT_DISABLE 0x00000000UL /*!< ADC group regular sequencer discontinuous mode disable */ +#define DDL_ADC_REG_SEQ_DISCONT_1RANK ( ADC_CTRL1_REGDISCEN) /*!< ADC group regular sequencer discontinuous mode enable with sequence interruption every rank */ +#define DDL_ADC_REG_SEQ_DISCONT_2RANKS ( ADC_CTRL1_DISCNUMCFG_0 | ADC_CTRL1_REGDISCEN) /*!< ADC group regular sequencer discontinuous mode enabled with sequence interruption every 2 ranks */ +#define DDL_ADC_REG_SEQ_DISCONT_3RANKS ( ADC_CTRL1_DISCNUMCFG_1 | ADC_CTRL1_REGDISCEN) /*!< ADC group regular sequencer discontinuous mode enable with sequence interruption every 3 ranks */ +#define DDL_ADC_REG_SEQ_DISCONT_4RANKS ( ADC_CTRL1_DISCNUMCFG_1 | ADC_CTRL1_DISCNUMCFG_0 | ADC_CTRL1_REGDISCEN) /*!< ADC group regular sequencer discontinuous mode enable with sequence interruption every 4 ranks */ +#define DDL_ADC_REG_SEQ_DISCONT_5RANKS (ADC_CTRL1_DISCNUMCFG_2 | ADC_CTRL1_REGDISCEN) /*!< ADC group regular sequencer discontinuous mode enable with sequence interruption every 5 ranks */ +#define DDL_ADC_REG_SEQ_DISCONT_6RANKS (ADC_CTRL1_DISCNUMCFG_2 | ADC_CTRL1_DISCNUMCFG_0 | ADC_CTRL1_REGDISCEN) /*!< ADC group regular sequencer discontinuous mode enable with sequence interruption every 6 ranks */ +#define DDL_ADC_REG_SEQ_DISCONT_7RANKS (ADC_CTRL1_DISCNUMCFG_2 | ADC_CTRL1_DISCNUMCFG_1 | ADC_CTRL1_REGDISCEN) /*!< ADC group regular sequencer discontinuous mode enable with sequence interruption every 7 ranks */ +#define DDL_ADC_REG_SEQ_DISCONT_8RANKS (ADC_CTRL1_DISCNUMCFG_2 | ADC_CTRL1_DISCNUMCFG_1 | ADC_CTRL1_DISCNUMCFG_0 | ADC_CTRL1_REGDISCEN) /*!< ADC group regular sequencer discontinuous mode enable with sequence interruption every 8 ranks */ +/** + * @} + */ + +/** @defgroup ADC_DDL_EC_REG_SEQ_RANKS ADC group regular - Sequencer ranks + * @{ + */ +#define DDL_ADC_REG_RANK_1 (ADC_REGSEQ3_REGOFFSET | ADC_REG_RANK_1_SQRX_BITOFFSET_POS) /*!< ADC group regular sequencer rank 1 */ +#define DDL_ADC_REG_RANK_2 (ADC_REGSEQ3_REGOFFSET | ADC_REG_RANK_2_SQRX_BITOFFSET_POS) /*!< ADC group regular sequencer rank 2 */ +#define DDL_ADC_REG_RANK_3 (ADC_REGSEQ3_REGOFFSET | ADC_REG_RANK_3_SQRX_BITOFFSET_POS) /*!< ADC group regular sequencer rank 3 */ +#define DDL_ADC_REG_RANK_4 (ADC_REGSEQ3_REGOFFSET | ADC_REG_RANK_4_SQRX_BITOFFSET_POS) /*!< ADC group regular sequencer rank 4 */ +#define DDL_ADC_REG_RANK_5 (ADC_REGSEQ3_REGOFFSET | ADC_REG_RANK_5_SQRX_BITOFFSET_POS) /*!< ADC group regular sequencer rank 5 */ +#define DDL_ADC_REG_RANK_6 (ADC_REGSEQ3_REGOFFSET | ADC_REG_RANK_6_SQRX_BITOFFSET_POS) /*!< ADC group regular sequencer rank 6 */ +#define DDL_ADC_REG_RANK_7 (ADC_REGSEQ2_REGOFFSET | ADC_REG_RANK_7_SQRX_BITOFFSET_POS) /*!< ADC group regular sequencer rank 7 */ +#define DDL_ADC_REG_RANK_8 (ADC_REGSEQ2_REGOFFSET | ADC_REG_RANK_8_SQRX_BITOFFSET_POS) /*!< ADC group regular sequencer rank 8 */ +#define DDL_ADC_REG_RANK_9 (ADC_REGSEQ2_REGOFFSET | ADC_REG_RANK_9_SQRX_BITOFFSET_POS) /*!< ADC group regular sequencer rank 9 */ +#define DDL_ADC_REG_RANK_10 (ADC_REGSEQ2_REGOFFSET | ADC_REG_RANK_10_SQRX_BITOFFSET_POS) /*!< ADC group regular sequencer rank 10 */ +#define DDL_ADC_REG_RANK_11 (ADC_REGSEQ2_REGOFFSET | ADC_REG_RANK_11_SQRX_BITOFFSET_POS) /*!< ADC group regular sequencer rank 11 */ +#define DDL_ADC_REG_RANK_12 (ADC_REGSEQ2_REGOFFSET | ADC_REG_RANK_12_SQRX_BITOFFSET_POS) /*!< ADC group regular sequencer rank 12 */ +#define DDL_ADC_REG_RANK_13 (ADC_REGSEQ1_REGOFFSET | ADC_REG_RANK_13_SQRX_BITOFFSET_POS) /*!< ADC group regular sequencer rank 13 */ +#define DDL_ADC_REG_RANK_14 (ADC_REGSEQ1_REGOFFSET | ADC_REG_RANK_14_SQRX_BITOFFSET_POS) /*!< ADC group regular sequencer rank 14 */ +#define DDL_ADC_REG_RANK_15 (ADC_REGSEQ1_REGOFFSET | ADC_REG_RANK_15_SQRX_BITOFFSET_POS) /*!< ADC group regular sequencer rank 15 */ +#define DDL_ADC_REG_RANK_16 (ADC_REGSEQ1_REGOFFSET | ADC_REG_RANK_16_SQRX_BITOFFSET_POS) /*!< ADC group regular sequencer rank 16 */ +/** + * @} + */ + +/** @defgroup ADC_DDL_EC_INJ_TRIGGER_SOURCE ADC group injected - Trigger source + * @{ + */ +#define DDL_ADC_INJ_TRIG_SOFTWARE 0x00000000UL /*!< ADC group injected conversion trigger internal: SW start. */ +#define DDL_ADC_INJ_TRIG_EXT_TMR1_CH4 (ADC_INJ_TRIG_EXT_EDGE_DEFAULT) /*!< ADC group injected conversion trigger from external IP: TIM1 channel 4 event (capture compare: input capture or output capture). Trigger edge set to rising edge (default setting). */ +#define DDL_ADC_INJ_TRIG_EXT_TMR1_TRGO (ADC_CTRL2_INJGEXTTRGSEL_0 | ADC_INJ_TRIG_EXT_EDGE_DEFAULT) /*!< ADC group injected conversion trigger from external IP: TIM1 TRGO. Trigger edge set to rising edge (default setting). */ +#define DDL_ADC_INJ_TRIG_EXT_TMR2_CH1 (ADC_CTRL2_INJGEXTTRGSEL_1 | ADC_INJ_TRIG_EXT_EDGE_DEFAULT) /*!< ADC group injected conversion trigger from external IP: TIM2 channel 1 event (capture compare: input capture or output capture). Trigger edge set to rising edge (default setting). */ +#define DDL_ADC_INJ_TRIG_EXT_TMR2_TRGO (ADC_CTRL2_INJGEXTTRGSEL_1 | ADC_CTRL2_INJGEXTTRGSEL_0 | ADC_INJ_TRIG_EXT_EDGE_DEFAULT) /*!< ADC group injected conversion trigger from external IP: TIM2 TRGO. Trigger edge set to rising edge (default setting). */ +#define DDL_ADC_INJ_TRIG_EXT_TMR3_CH2 (ADC_CTRL2_INJGEXTTRGSEL_2 | ADC_INJ_TRIG_EXT_EDGE_DEFAULT) /*!< ADC group injected conversion trigger from external IP: TIM3 channel 2 event (capture compare: input capture or output capture). Trigger edge set to rising edge (default setting). */ +#define DDL_ADC_INJ_TRIG_EXT_TMR3_CH4 (ADC_CTRL2_INJGEXTTRGSEL_2 | ADC_CTRL2_INJGEXTTRGSEL_0 | ADC_INJ_TRIG_EXT_EDGE_DEFAULT) /*!< ADC group injected conversion trigger from external IP: TIM3 channel 4 event (capture compare: input capture or output capture). Trigger edge set to rising edge (default setting). */ +#define DDL_ADC_INJ_TRIG_EXT_TMR4_CH1 (ADC_CTRL2_INJGEXTTRGSEL_2 | ADC_CTRL2_INJGEXTTRGSEL_1 | ADC_INJ_TRIG_EXT_EDGE_DEFAULT) /*!< ADC group injected conversion trigger from external IP: TIM4 channel 1 event (capture compare: input capture or output capture). Trigger edge set to rising edge (default setting). */ +#define DDL_ADC_INJ_TRIG_EXT_TMR4_CH2 (ADC_CTRL2_INJGEXTTRGSEL_2 | ADC_CTRL2_INJGEXTTRGSEL_1 | ADC_CTRL2_INJGEXTTRGSEL_0 | ADC_INJ_TRIG_EXT_EDGE_DEFAULT) /*!< ADC group injected conversion trigger from external IP: TIM4 channel 2 event (capture compare: input capture or output capture). Trigger edge set to rising edge (default setting). */ +#define DDL_ADC_INJ_TRIG_EXT_TMR4_CH3 (ADC_CTRL2_INJGEXTTRGSEL_3 | ADC_INJ_TRIG_EXT_EDGE_DEFAULT) /*!< ADC group injected conversion trigger from external IP: TIM4 channel 3 event (capture compare: input capture or output capture). Trigger edge set to rising edge (default setting). */ +#define DDL_ADC_INJ_TRIG_EXT_TMR4_TRGO (ADC_CTRL2_INJGEXTTRGSEL_3 | ADC_CTRL2_INJGEXTTRGSEL_0 | ADC_INJ_TRIG_EXT_EDGE_DEFAULT) /*!< ADC group injected conversion trigger from external IP: TIM4 TRGO. Trigger edge set to rising edge (default setting). */ +#define DDL_ADC_INJ_TRIG_EXT_TMR5_CH4 (ADC_CTRL2_INJGEXTTRGSEL_3 | ADC_CTRL2_INJGEXTTRGSEL_1 | ADC_INJ_TRIG_EXT_EDGE_DEFAULT) /*!< ADC group injected conversion trigger from external IP: TIM5 channel 4 event (capture compare: input capture or output capture). Trigger edge set to rising edge (default setting). */ +#define DDL_ADC_INJ_TRIG_EXT_TMR5_TRGO (ADC_CTRL2_INJGEXTTRGSEL_3 | ADC_CTRL2_INJGEXTTRGSEL_1 | ADC_CTRL2_INJGEXTTRGSEL_0 | ADC_INJ_TRIG_EXT_EDGE_DEFAULT) /*!< ADC group injected conversion trigger from external IP: TIM5 TRGO. Trigger edge set to rising edge (default setting). */ +#define DDL_ADC_INJ_TRIG_EXT_TMR8_CH2 (ADC_CTRL2_INJGEXTTRGSEL_3 | ADC_CTRL2_INJGEXTTRGSEL_2 | ADC_INJ_TRIG_EXT_EDGE_DEFAULT) /*!< ADC group injected conversion trigger from external IP: TIM8 channel 2 event (capture compare: input capture or output capture). Trigger edge set to rising edge (default setting). */ +#define DDL_ADC_INJ_TRIG_EXT_TMR8_CH3 (ADC_CTRL2_INJGEXTTRGSEL_3 | ADC_CTRL2_INJGEXTTRGSEL_2 | ADC_CTRL2_INJGEXTTRGSEL_0 | ADC_INJ_TRIG_EXT_EDGE_DEFAULT) /*!< ADC group injected conversion trigger from external IP: TIM8 channel 3 event (capture compare: input capture or output capture). Trigger edge set to rising edge (default setting). */ +#define DDL_ADC_INJ_TRIG_EXT_TMR8_CH4 (ADC_CTRL2_INJGEXTTRGSEL_3 | ADC_CTRL2_INJGEXTTRGSEL_2 | ADC_CTRL2_INJGEXTTRGSEL_1 | ADC_INJ_TRIG_EXT_EDGE_DEFAULT) /*!< ADC group injected conversion trigger from external IP: TIM8 channel 4 event (capture compare: input capture or output capture). Trigger edge set to rising edge (default setting). */ +#define DDL_ADC_INJ_TRIG_EXT_EXTI_LINE15 (ADC_CTRL2_INJGEXTTRGSEL_3 | ADC_CTRL2_INJGEXTTRGSEL_2 | ADC_CTRL2_INJGEXTTRGSEL_1 | ADC_CTRL2_INJGEXTTRGSEL_0 | ADC_INJ_TRIG_EXT_EDGE_DEFAULT) /*!< ADC group injected conversion trigger from external IP: external interrupt line 15. Trigger edge set to rising edge (default setting). */ +/** + * @} + */ + +/** @defgroup ADC_DDL_EC_INJ_TRIGGER_EDGE ADC group injected - Trigger edge + * @{ + */ +#define DDL_ADC_INJ_TRIG_EXT_RISING ( ADC_CTRL2_INJEXTTRGEN_0) /*!< ADC group injected conversion trigger polarity set to rising edge */ +#define DDL_ADC_INJ_TRIG_EXT_FALLING (ADC_CTRL2_INJEXTTRGEN_1 ) /*!< ADC group injected conversion trigger polarity set to falling edge */ +#define DDL_ADC_INJ_TRIG_EXT_RISINGFALLING (ADC_CTRL2_INJEXTTRGEN_1 | ADC_CTRL2_INJEXTTRGEN_0) /*!< ADC group injected conversion trigger polarity set to both rising and falling edges */ +/** + * @} + */ + +/** @defgroup ADC_DDL_EC_INJ_TRIG_AUTO ADC group injected - Automatic trigger mode +* @{ +*/ +#define DDL_ADC_INJ_TRIG_INDEPENDENT 0x00000000UL /*!< ADC group injected conversion trigger independent. Setting mandatory if ADC group injected injected trigger source is set to an external trigger. */ +#define DDL_ADC_INJ_TRIG_FROM_GRP_REGULAR (ADC_CTRL1_INJGACEN) /*!< ADC group injected conversion trigger from ADC group regular. Setting compliant only with group injected trigger source set to SW start, without any further action on ADC group injected conversion start or stop: in this case, ADC group injected is controlled only from ADC group regular. */ +/** + * @} + */ + + +/** @defgroup ADC_DDL_EC_INJ_SEQ_SCAN_LENGTH ADC group injected - Sequencer scan length + * @{ + */ +#define DDL_ADC_INJ_SEQ_SCAN_DISABLE 0x00000000UL /*!< ADC group injected sequencer disable (equivalent to sequencer of 1 rank: ADC conversion on only 1 channel) */ +#define DDL_ADC_INJ_SEQ_SCAN_ENABLE_2RANKS ( ADC_INJSEQ_INJSEQLEN_0) /*!< ADC group injected sequencer enable with 2 ranks in the sequence */ +#define DDL_ADC_INJ_SEQ_SCAN_ENABLE_3RANKS (ADC_INJSEQ_INJSEQLEN_1 ) /*!< ADC group injected sequencer enable with 3 ranks in the sequence */ +#define DDL_ADC_INJ_SEQ_SCAN_ENABLE_4RANKS (ADC_INJSEQ_INJSEQLEN_1 | ADC_INJSEQ_INJSEQLEN_0) /*!< ADC group injected sequencer enable with 4 ranks in the sequence */ +/** + * @} + */ + +/** @defgroup ADC_DDL_EC_INJ_SEQ_DISCONT_MODE ADC group injected - Sequencer discontinuous mode + * @{ + */ +#define DDL_ADC_INJ_SEQ_DISCONT_DISABLE 0x00000000UL /*!< ADC group injected sequencer discontinuous mode disable */ +#define DDL_ADC_INJ_SEQ_DISCONT_1RANK (ADC_CTRL1_INJDISCEN) /*!< ADC group injected sequencer discontinuous mode enable with sequence interruption every rank */ +/** + * @} + */ + +/** @defgroup ADC_DDL_EC_INJ_SEQ_RANKS ADC group injected - Sequencer ranks + * @{ + */ +#define DDL_ADC_INJ_RANK_1 (ADC_INJDATA1_REGOFFSET | ADC_INJDOF1_REGOFFSET | 0x00000001UL) /*!< ADC group injected sequencer rank 1 */ +#define DDL_ADC_INJ_RANK_2 (ADC_INJDATA2_REGOFFSET | ADC_INJDOF2_REGOFFSET | 0x00000002UL) /*!< ADC group injected sequencer rank 2 */ +#define DDL_ADC_INJ_RANK_3 (ADC_INJDATA3_REGOFFSET | ADC_INJDOF3_REGOFFSET | 0x00000003UL) /*!< ADC group injected sequencer rank 3 */ +#define DDL_ADC_INJ_RANK_4 (ADC_INJDATA4_REGOFFSET | ADC_INJDOF4_REGOFFSET | 0x00000004UL) /*!< ADC group injected sequencer rank 4 */ +/** + * @} + */ + +/** @defgroup ADC_DDL_EC_CHANNEL_SAMPLINGTIME Channel - Sampling time + * @{ + */ +#define DDL_ADC_SAMPLINGTIME_3CYCLES 0x00000000UL /*!< Sampling time 3 ADC clock cycles */ +#define DDL_ADC_SAMPLINGTIME_15CYCLES (ADC_SMPTIM1_SMPCYCCFG10_0) /*!< Sampling time 15 ADC clock cycles */ +#define DDL_ADC_SAMPLINGTIME_28CYCLES (ADC_SMPTIM1_SMPCYCCFG10_1) /*!< Sampling time 28 ADC clock cycles */ +#define DDL_ADC_SAMPLINGTIME_56CYCLES (ADC_SMPTIM1_SMPCYCCFG10_1 | ADC_SMPTIM1_SMPCYCCFG10_0) /*!< Sampling time 56 ADC clock cycles */ +#define DDL_ADC_SAMPLINGTIME_84CYCLES (ADC_SMPTIM1_SMPCYCCFG10_2) /*!< Sampling time 84 ADC clock cycles */ +#define DDL_ADC_SAMPLINGTIME_112CYCLES (ADC_SMPTIM1_SMPCYCCFG10_2 | ADC_SMPTIM1_SMPCYCCFG10_0) /*!< Sampling time 112 ADC clock cycles */ +#define DDL_ADC_SAMPLINGTIME_144CYCLES (ADC_SMPTIM1_SMPCYCCFG10_2 | ADC_SMPTIM1_SMPCYCCFG10_1) /*!< Sampling time 144 ADC clock cycles */ +#define DDL_ADC_SAMPLINGTIME_480CYCLES (ADC_SMPTIM1_SMPCYCCFG10) /*!< Sampling time 480 ADC clock cycles */ +/** + * @} + */ + +/** @defgroup ADC_DDL_EC_AWD_NUMBER Analog watchdog - Analog watchdog number + * @{ + */ +#define DDL_ADC_AWD1 (ADC_AWD_CTRL1_CHANNEL_MASK | ADC_AWD_CTRL1_REGOFFSET) /*!< ADC analog watchdog number 1 */ +/** + * @} + */ + +/** @defgroup ADC_DDL_EC_AWD_CHANNELS Analog watchdog - Monitored channels + * @{ + */ +#define DDL_ADC_AWD_DISABLE 0x00000000UL /*!< ADC analog watchdog monitoring disabled */ +#define DDL_ADC_AWD_ALL_CHANNELS_REG ( ADC_CTRL1_REGAWDEN ) /*!< ADC analog watchdog monitoring of all channels, converted by group regular only */ +#define DDL_ADC_AWD_ALL_CHANNELS_INJ ( ADC_CTRL1_INJAWDEN ) /*!< ADC analog watchdog monitoring of all channels, converted by group injected only */ +#define DDL_ADC_AWD_ALL_CHANNELS_REG_INJ ( ADC_CTRL1_INJAWDEN | ADC_CTRL1_REGAWDEN ) /*!< ADC analog watchdog monitoring of all channels, converted by either group regular or injected */ +#define DDL_ADC_AWD_CHANNEL_0_REG ((DDL_ADC_CHANNEL_0 & ADC_CHANNEL_ID_MASK) | ADC_CTRL1_REGAWDEN | ADC_CTRL1_AWDSGLEN) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN0, converted by group regular only */ +#define DDL_ADC_AWD_CHANNEL_0_INJ ((DDL_ADC_CHANNEL_0 & ADC_CHANNEL_ID_MASK) | ADC_CTRL1_INJAWDEN | ADC_CTRL1_AWDSGLEN) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN0, converted by group injected only */ +#define DDL_ADC_AWD_CHANNEL_0_REG_INJ ((DDL_ADC_CHANNEL_0 & ADC_CHANNEL_ID_MASK) | ADC_CTRL1_INJAWDEN | ADC_CTRL1_REGAWDEN | ADC_CTRL1_AWDSGLEN) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN0, converted by either group regular or injected */ +#define DDL_ADC_AWD_CHANNEL_1_REG ((DDL_ADC_CHANNEL_1 & ADC_CHANNEL_ID_MASK) | ADC_CTRL1_REGAWDEN | ADC_CTRL1_AWDSGLEN) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN1, converted by group regular only */ +#define DDL_ADC_AWD_CHANNEL_1_INJ ((DDL_ADC_CHANNEL_1 & ADC_CHANNEL_ID_MASK) | ADC_CTRL1_INJAWDEN | ADC_CTRL1_AWDSGLEN) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN1, converted by group injected only */ +#define DDL_ADC_AWD_CHANNEL_1_REG_INJ ((DDL_ADC_CHANNEL_1 & ADC_CHANNEL_ID_MASK) | ADC_CTRL1_INJAWDEN | ADC_CTRL1_REGAWDEN | ADC_CTRL1_AWDSGLEN) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN1, converted by either group regular or injected */ +#define DDL_ADC_AWD_CHANNEL_2_REG ((DDL_ADC_CHANNEL_2 & ADC_CHANNEL_ID_MASK) | ADC_CTRL1_REGAWDEN | ADC_CTRL1_AWDSGLEN) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN2, converted by group regular only */ +#define DDL_ADC_AWD_CHANNEL_2_INJ ((DDL_ADC_CHANNEL_2 & ADC_CHANNEL_ID_MASK) | ADC_CTRL1_INJAWDEN | ADC_CTRL1_AWDSGLEN) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN2, converted by group injected only */ +#define DDL_ADC_AWD_CHANNEL_2_REG_INJ ((DDL_ADC_CHANNEL_2 & ADC_CHANNEL_ID_MASK) | ADC_CTRL1_INJAWDEN | ADC_CTRL1_REGAWDEN | ADC_CTRL1_AWDSGLEN) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN2, converted by either group regular or injected */ +#define DDL_ADC_AWD_CHANNEL_3_REG ((DDL_ADC_CHANNEL_3 & ADC_CHANNEL_ID_MASK) | ADC_CTRL1_REGAWDEN | ADC_CTRL1_AWDSGLEN) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN3, converted by group regular only */ +#define DDL_ADC_AWD_CHANNEL_3_INJ ((DDL_ADC_CHANNEL_3 & ADC_CHANNEL_ID_MASK) | ADC_CTRL1_INJAWDEN | ADC_CTRL1_AWDSGLEN) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN3, converted by group injected only */ +#define DDL_ADC_AWD_CHANNEL_3_REG_INJ ((DDL_ADC_CHANNEL_3 & ADC_CHANNEL_ID_MASK) | ADC_CTRL1_INJAWDEN | ADC_CTRL1_REGAWDEN | ADC_CTRL1_AWDSGLEN) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN3, converted by either group regular or injected */ +#define DDL_ADC_AWD_CHANNEL_4_REG ((DDL_ADC_CHANNEL_4 & ADC_CHANNEL_ID_MASK) | ADC_CTRL1_REGAWDEN | ADC_CTRL1_AWDSGLEN) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN4, converted by group regular only */ +#define DDL_ADC_AWD_CHANNEL_4_INJ ((DDL_ADC_CHANNEL_4 & ADC_CHANNEL_ID_MASK) | ADC_CTRL1_INJAWDEN | ADC_CTRL1_AWDSGLEN) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN4, converted by group injected only */ +#define DDL_ADC_AWD_CHANNEL_4_REG_INJ ((DDL_ADC_CHANNEL_4 & ADC_CHANNEL_ID_MASK) | ADC_CTRL1_INJAWDEN | ADC_CTRL1_REGAWDEN | ADC_CTRL1_AWDSGLEN) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN4, converted by either group regular or injected */ +#define DDL_ADC_AWD_CHANNEL_5_REG ((DDL_ADC_CHANNEL_5 & ADC_CHANNEL_ID_MASK) | ADC_CTRL1_REGAWDEN | ADC_CTRL1_AWDSGLEN) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN5, converted by group regular only */ +#define DDL_ADC_AWD_CHANNEL_5_INJ ((DDL_ADC_CHANNEL_5 & ADC_CHANNEL_ID_MASK) | ADC_CTRL1_INJAWDEN | ADC_CTRL1_AWDSGLEN) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN5, converted by group injected only */ +#define DDL_ADC_AWD_CHANNEL_5_REG_INJ ((DDL_ADC_CHANNEL_5 & ADC_CHANNEL_ID_MASK) | ADC_CTRL1_INJAWDEN | ADC_CTRL1_REGAWDEN | ADC_CTRL1_AWDSGLEN) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN5, converted by either group regular or injected */ +#define DDL_ADC_AWD_CHANNEL_6_REG ((DDL_ADC_CHANNEL_6 & ADC_CHANNEL_ID_MASK) | ADC_CTRL1_REGAWDEN | ADC_CTRL1_AWDSGLEN) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN6, converted by group regular only */ +#define DDL_ADC_AWD_CHANNEL_6_INJ ((DDL_ADC_CHANNEL_6 & ADC_CHANNEL_ID_MASK) | ADC_CTRL1_INJAWDEN | ADC_CTRL1_AWDSGLEN) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN6, converted by group injected only */ +#define DDL_ADC_AWD_CHANNEL_6_REG_INJ ((DDL_ADC_CHANNEL_6 & ADC_CHANNEL_ID_MASK) | ADC_CTRL1_INJAWDEN | ADC_CTRL1_REGAWDEN | ADC_CTRL1_AWDSGLEN) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN6, converted by either group regular or injected */ +#define DDL_ADC_AWD_CHANNEL_7_REG ((DDL_ADC_CHANNEL_7 & ADC_CHANNEL_ID_MASK) | ADC_CTRL1_REGAWDEN | ADC_CTRL1_AWDSGLEN) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN7, converted by group regular only */ +#define DDL_ADC_AWD_CHANNEL_7_INJ ((DDL_ADC_CHANNEL_7 & ADC_CHANNEL_ID_MASK) | ADC_CTRL1_INJAWDEN | ADC_CTRL1_AWDSGLEN) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN7, converted by group injected only */ +#define DDL_ADC_AWD_CHANNEL_7_REG_INJ ((DDL_ADC_CHANNEL_7 & ADC_CHANNEL_ID_MASK) | ADC_CTRL1_INJAWDEN | ADC_CTRL1_REGAWDEN | ADC_CTRL1_AWDSGLEN) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN7, converted by either group regular or injected */ +#define DDL_ADC_AWD_CHANNEL_8_REG ((DDL_ADC_CHANNEL_8 & ADC_CHANNEL_ID_MASK) | ADC_CTRL1_REGAWDEN | ADC_CTRL1_AWDSGLEN) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN8, converted by group regular only */ +#define DDL_ADC_AWD_CHANNEL_8_INJ ((DDL_ADC_CHANNEL_8 & ADC_CHANNEL_ID_MASK) | ADC_CTRL1_INJAWDEN | ADC_CTRL1_AWDSGLEN) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN8, converted by group injected only */ +#define DDL_ADC_AWD_CHANNEL_8_REG_INJ ((DDL_ADC_CHANNEL_8 & ADC_CHANNEL_ID_MASK) | ADC_CTRL1_INJAWDEN | ADC_CTRL1_REGAWDEN | ADC_CTRL1_AWDSGLEN) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN8, converted by either group regular or injected */ +#define DDL_ADC_AWD_CHANNEL_9_REG ((DDL_ADC_CHANNEL_9 & ADC_CHANNEL_ID_MASK) | ADC_CTRL1_REGAWDEN | ADC_CTRL1_AWDSGLEN) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN9, converted by group regular only */ +#define DDL_ADC_AWD_CHANNEL_9_INJ ((DDL_ADC_CHANNEL_9 & ADC_CHANNEL_ID_MASK) | ADC_CTRL1_INJAWDEN | ADC_CTRL1_AWDSGLEN) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN9, converted by group injected only */ +#define DDL_ADC_AWD_CHANNEL_9_REG_INJ ((DDL_ADC_CHANNEL_9 & ADC_CHANNEL_ID_MASK) | ADC_CTRL1_INJAWDEN | ADC_CTRL1_REGAWDEN | ADC_CTRL1_AWDSGLEN) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN9, converted by either group regular or injected */ +#define DDL_ADC_AWD_CHANNEL_10_REG ((DDL_ADC_CHANNEL_10 & ADC_CHANNEL_ID_MASK) | ADC_CTRL1_REGAWDEN | ADC_CTRL1_AWDSGLEN) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN10, converted by group regular only */ +#define DDL_ADC_AWD_CHANNEL_10_INJ ((DDL_ADC_CHANNEL_10 & ADC_CHANNEL_ID_MASK) | ADC_CTRL1_INJAWDEN | ADC_CTRL1_AWDSGLEN) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN10, converted by group injected only */ +#define DDL_ADC_AWD_CHANNEL_10_REG_INJ ((DDL_ADC_CHANNEL_10 & ADC_CHANNEL_ID_MASK) | ADC_CTRL1_INJAWDEN | ADC_CTRL1_REGAWDEN | ADC_CTRL1_AWDSGLEN) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN10, converted by either group regular or injected */ +#define DDL_ADC_AWD_CHANNEL_11_REG ((DDL_ADC_CHANNEL_11 & ADC_CHANNEL_ID_MASK) | ADC_CTRL1_REGAWDEN | ADC_CTRL1_AWDSGLEN) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN11, converted by group regular only */ +#define DDL_ADC_AWD_CHANNEL_11_INJ ((DDL_ADC_CHANNEL_11 & ADC_CHANNEL_ID_MASK) | ADC_CTRL1_INJAWDEN | ADC_CTRL1_AWDSGLEN) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN11, converted by group injected only */ +#define DDL_ADC_AWD_CHANNEL_11_REG_INJ ((DDL_ADC_CHANNEL_11 & ADC_CHANNEL_ID_MASK) | ADC_CTRL1_INJAWDEN | ADC_CTRL1_REGAWDEN | ADC_CTRL1_AWDSGLEN) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN11, converted by either group regular or injected */ +#define DDL_ADC_AWD_CHANNEL_12_REG ((DDL_ADC_CHANNEL_12 & ADC_CHANNEL_ID_MASK) | ADC_CTRL1_REGAWDEN | ADC_CTRL1_AWDSGLEN) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN12, converted by group regular only */ +#define DDL_ADC_AWD_CHANNEL_12_INJ ((DDL_ADC_CHANNEL_12 & ADC_CHANNEL_ID_MASK) | ADC_CTRL1_INJAWDEN | ADC_CTRL1_AWDSGLEN) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN12, converted by group injected only */ +#define DDL_ADC_AWD_CHANNEL_12_REG_INJ ((DDL_ADC_CHANNEL_12 & ADC_CHANNEL_ID_MASK) | ADC_CTRL1_INJAWDEN | ADC_CTRL1_REGAWDEN | ADC_CTRL1_AWDSGLEN) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN12, converted by either group regular or injected */ +#define DDL_ADC_AWD_CHANNEL_13_REG ((DDL_ADC_CHANNEL_13 & ADC_CHANNEL_ID_MASK) | ADC_CTRL1_REGAWDEN | ADC_CTRL1_AWDSGLEN) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN13, converted by group regular only */ +#define DDL_ADC_AWD_CHANNEL_13_INJ ((DDL_ADC_CHANNEL_13 & ADC_CHANNEL_ID_MASK) | ADC_CTRL1_INJAWDEN | ADC_CTRL1_AWDSGLEN) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN13, converted by group injected only */ +#define DDL_ADC_AWD_CHANNEL_13_REG_INJ ((DDL_ADC_CHANNEL_13 & ADC_CHANNEL_ID_MASK) | ADC_CTRL1_INJAWDEN | ADC_CTRL1_REGAWDEN | ADC_CTRL1_AWDSGLEN) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN13, converted by either group regular or injected */ +#define DDL_ADC_AWD_CHANNEL_14_REG ((DDL_ADC_CHANNEL_14 & ADC_CHANNEL_ID_MASK) | ADC_CTRL1_REGAWDEN | ADC_CTRL1_AWDSGLEN) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN14, converted by group regular only */ +#define DDL_ADC_AWD_CHANNEL_14_INJ ((DDL_ADC_CHANNEL_14 & ADC_CHANNEL_ID_MASK) | ADC_CTRL1_INJAWDEN | ADC_CTRL1_AWDSGLEN) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN14, converted by group injected only */ +#define DDL_ADC_AWD_CHANNEL_14_REG_INJ ((DDL_ADC_CHANNEL_14 & ADC_CHANNEL_ID_MASK) | ADC_CTRL1_INJAWDEN | ADC_CTRL1_REGAWDEN | ADC_CTRL1_AWDSGLEN) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN14, converted by either group regular or injected */ +#define DDL_ADC_AWD_CHANNEL_15_REG ((DDL_ADC_CHANNEL_15 & ADC_CHANNEL_ID_MASK) | ADC_CTRL1_REGAWDEN | ADC_CTRL1_AWDSGLEN) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN15, converted by group regular only */ +#define DDL_ADC_AWD_CHANNEL_15_INJ ((DDL_ADC_CHANNEL_15 & ADC_CHANNEL_ID_MASK) | ADC_CTRL1_INJAWDEN | ADC_CTRL1_AWDSGLEN) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN15, converted by group injected only */ +#define DDL_ADC_AWD_CHANNEL_15_REG_INJ ((DDL_ADC_CHANNEL_15 & ADC_CHANNEL_ID_MASK) | ADC_CTRL1_INJAWDEN | ADC_CTRL1_REGAWDEN | ADC_CTRL1_AWDSGLEN) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN15, converted by either group regular or injected */ +#define DDL_ADC_AWD_CHANNEL_16_REG ((DDL_ADC_CHANNEL_16 & ADC_CHANNEL_ID_MASK) | ADC_CTRL1_REGAWDEN | ADC_CTRL1_AWDSGLEN) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN16, converted by group regular only */ +#define DDL_ADC_AWD_CHANNEL_16_INJ ((DDL_ADC_CHANNEL_16 & ADC_CHANNEL_ID_MASK) | ADC_CTRL1_INJAWDEN | ADC_CTRL1_AWDSGLEN) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN16, converted by group injected only */ +#define DDL_ADC_AWD_CHANNEL_16_REG_INJ ((DDL_ADC_CHANNEL_16 & ADC_CHANNEL_ID_MASK) | ADC_CTRL1_INJAWDEN | ADC_CTRL1_REGAWDEN | ADC_CTRL1_AWDSGLEN) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN16, converted by either group regular or injected */ +#define DDL_ADC_AWD_CHANNEL_17_REG ((DDL_ADC_CHANNEL_17 & ADC_CHANNEL_ID_MASK) | ADC_CTRL1_REGAWDEN | ADC_CTRL1_AWDSGLEN) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN17, converted by group regular only */ +#define DDL_ADC_AWD_CHANNEL_17_INJ ((DDL_ADC_CHANNEL_17 & ADC_CHANNEL_ID_MASK) | ADC_CTRL1_INJAWDEN | ADC_CTRL1_AWDSGLEN) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN17, converted by group injected only */ +#define DDL_ADC_AWD_CHANNEL_17_REG_INJ ((DDL_ADC_CHANNEL_17 & ADC_CHANNEL_ID_MASK) | ADC_CTRL1_INJAWDEN | ADC_CTRL1_REGAWDEN | ADC_CTRL1_AWDSGLEN) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN17, converted by either group regular or injected */ +#define DDL_ADC_AWD_CHANNEL_18_REG ((DDL_ADC_CHANNEL_18 & ADC_CHANNEL_ID_MASK) | ADC_CTRL1_REGAWDEN | ADC_CTRL1_AWDSGLEN) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN18, converted by group regular only */ +#define DDL_ADC_AWD_CHANNEL_18_INJ ((DDL_ADC_CHANNEL_18 & ADC_CHANNEL_ID_MASK) | ADC_CTRL1_INJAWDEN | ADC_CTRL1_AWDSGLEN) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN18, converted by group injected only */ +#define DDL_ADC_AWD_CHANNEL_18_REG_INJ ((DDL_ADC_CHANNEL_18 & ADC_CHANNEL_ID_MASK) | ADC_CTRL1_INJAWDEN | ADC_CTRL1_REGAWDEN | ADC_CTRL1_AWDSGLEN) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN18, converted by either group regular or injected */ +#define DDL_ADC_AWD_CH_VREFINT_REG ((DDL_ADC_CHANNEL_VREFINT & ADC_CHANNEL_ID_MASK) | ADC_CTRL1_REGAWDEN | ADC_CTRL1_AWDSGLEN) /*!< ADC analog watchdog monitoring of ADC internal channel connected to VrefInt: Internal voltage reference, converted by group regular only */ +#define DDL_ADC_AWD_CH_VREFINT_INJ ((DDL_ADC_CHANNEL_VREFINT & ADC_CHANNEL_ID_MASK) | ADC_CTRL1_INJAWDEN | ADC_CTRL1_AWDSGLEN) /*!< ADC analog watchdog monitoring of ADC internal channel connected to VrefInt: Internal voltage reference, converted by group injected only */ +#define DDL_ADC_AWD_CH_VREFINT_REG_INJ ((DDL_ADC_CHANNEL_VREFINT & ADC_CHANNEL_ID_MASK) | ADC_CTRL1_INJAWDEN | ADC_CTRL1_REGAWDEN | ADC_CTRL1_AWDSGLEN) /*!< ADC analog watchdog monitoring of ADC internal channel connected to VrefInt: Internal voltage reference, converted by either group regular or injected */ +#define DDL_ADC_AWD_CH_VBAT_REG ((DDL_ADC_CHANNEL_VBAT & ADC_CHANNEL_ID_MASK) | ADC_CTRL1_REGAWDEN | ADC_CTRL1_AWDSGLEN) /*!< ADC analog watchdog monitoring of ADC internal channel connected to Vbat/3: Vbat voltage through a divider ladder of factor 1/3 to have Vbat always below Vdda, converted by group regular only */ +#define DDL_ADC_AWD_CH_VBAT_INJ ((DDL_ADC_CHANNEL_VBAT & ADC_CHANNEL_ID_MASK) | ADC_CTRL1_INJAWDEN | ADC_CTRL1_AWDSGLEN) /*!< ADC analog watchdog monitoring of ADC internal channel connected to Vbat/3: Vbat voltage through a divider ladder of factor 1/3 to have Vbat always below Vdda, converted by group injected only */ +#define DDL_ADC_AWD_CH_VBAT_REG_INJ ((DDL_ADC_CHANNEL_VBAT & ADC_CHANNEL_ID_MASK) | ADC_CTRL1_INJAWDEN | ADC_CTRL1_REGAWDEN | ADC_CTRL1_AWDSGLEN) /*!< ADC analog watchdog monitoring of ADC internal channel connected to Vbat/3: Vbat voltage through a divider ladder of factor 1/3 to have Vbat always below Vdda */ +#if defined(APM32F405xx) || defined(APM32F407xx) || defined(APM32F417xx) || defined(APM32F465xx) +#define DDL_ADC_AWD_CH_TEMPSENSOR_REG ((DDL_ADC_CHANNEL_TEMPSENSOR & ADC_CHANNEL_ID_MASK) | ADC_CTRL1_REGAWDEN | ADC_CTRL1_AWDSGLEN) /*!< ADC analog watchdog monitoring of ADC internal channel connected to Temperature sensor, converted by group regular only */ +#define DDL_ADC_AWD_CH_TEMPSENSOR_INJ ((DDL_ADC_CHANNEL_TEMPSENSOR & ADC_CHANNEL_ID_MASK) | ADC_CTRL1_INJAWDEN | ADC_CTRL1_AWDSGLEN) /*!< ADC analog watchdog monitoring of ADC internal channel connected to Temperature sensor, converted by group injected only */ +#define DDL_ADC_AWD_CH_TEMPSENSOR_REG_INJ ((DDL_ADC_CHANNEL_TEMPSENSOR & ADC_CHANNEL_ID_MASK) | ADC_CTRL1_INJAWDEN | ADC_CTRL1_REGAWDEN | ADC_CTRL1_AWDSGLEN) /*!< ADC analog watchdog monitoring of ADC internal channel connected to Temperature sensor, converted by either group regular or injected */ +#endif /* APM32F405xx || APM32F407xx || APM32F417xx || APM32F465xx */ +#if defined(APM32F411xx) +#define DDL_ADC_AWD_CH_TEMPSENSOR_REG ((DDL_ADC_CHANNEL_TEMPSENSOR & ADC_CHANNEL_ID_MASK) | ADC_CTRL1_REGAWDEN | ADC_CTRL1_AWDSGLEN) /*!< ADC analog watchdog monitoring of ADC internal channel connected to Temperature sensor, converted by group regular only. This internal channel is shared between temperature sensor and Vbat, only 1 measurement path must be enabled. */ +#define DDL_ADC_AWD_CH_TEMPSENSOR_INJ ((DDL_ADC_CHANNEL_TEMPSENSOR & ADC_CHANNEL_ID_MASK) | ADC_CTRL1_INJAWDEN | ADC_CTRL1_AWDSGLEN) /*!< ADC analog watchdog monitoring of ADC internal channel connected to Temperature sensor, converted by group injected only. This internal channel is shared between temperature sensor and Vbat, only 1 measurement path must be enabled. */ +#define DDL_ADC_AWD_CH_TEMPSENSOR_REG_INJ ((DDL_ADC_CHANNEL_TEMPSENSOR & ADC_CHANNEL_ID_MASK) | ADC_CTRL1_INJAWDEN | ADC_CTRL1_REGAWDEN | ADC_CTRL1_AWDSGLEN) /*!< ADC analog watchdog monitoring of ADC internal channel connected to Temperature sensor, converted by either group regular or injected. This internal channel is shared between temperature sensor and Vbat, only 1 measurement path must be enabled. */ +#endif /* APM32F411xx */ +/** + * @} + */ + +/** @defgroup ADC_DDL_EC_AWD_THRESHOLDS Analog watchdog - Thresholds + * @{ + */ +#define DDL_ADC_AWD_THRESHOLD_HIGH (ADC_AWD_TR1_HIGH_REGOFFSET) /*!< ADC analog watchdog threshold high */ +#define DDL_ADC_AWD_THRESHOLD_LOW (ADC_AWD_TR1_LOW_REGOFFSET) /*!< ADC analog watchdog threshold low */ +/** + * @} + */ + +#if defined(ADC_MULTIMODE_SUPPORT) +/** @defgroup ADC_DDL_EC_MULTI_MODE Multimode - Mode + * @{ + */ +#define DDL_ADC_MULTI_INDEPENDENT 0x00000000UL /*!< ADC dual mode disabled (ADC independent mode) */ +#define DDL_ADC_MULTI_DUAL_REG_SIMULT ( ADC_CCTRL_ADCMSEL_2 | ADC_CCTRL_ADCMSEL_1 ) /*!< ADC dual mode enabled: group regular simultaneous */ +#define DDL_ADC_MULTI_DUAL_REG_INTERL ( ADC_CCTRL_ADCMSEL_2 | ADC_CCTRL_ADCMSEL_1 | ADC_CCTRL_ADCMSEL_0) /*!< ADC dual mode enabled: Combined group regular interleaved */ +#define DDL_ADC_MULTI_DUAL_INJ_SIMULT ( ADC_CCTRL_ADCMSEL_2 | ADC_CCTRL_ADCMSEL_0) /*!< ADC dual mode enabled: group injected simultaneous */ +#define DDL_ADC_MULTI_DUAL_INJ_ALTERN (ADC_CCTRL_ADCMSEL_3 | ADC_CCTRL_ADCMSEL_0) /*!< ADC dual mode enabled: group injected alternate trigger. Works only with external triggers (not internal SW start) */ +#define DDL_ADC_MULTI_DUAL_REG_SIM_INJ_SIM ( ADC_CCTRL_ADCMSEL_0) /*!< ADC dual mode enabled: Combined group regular simultaneous + group injected simultaneous */ +#define DDL_ADC_MULTI_DUAL_REG_SIM_INJ_ALT ( ADC_CCTRL_ADCMSEL_1 ) /*!< ADC dual mode enabled: Combined group regular simultaneous + group injected alternate trigger */ +#define DDL_ADC_MULTI_DUAL_REG_INT_INJ_SIM ( ADC_CCTRL_ADCMSEL_1 | ADC_CCTRL_ADCMSEL_0) /*!< ADC dual mode enabled: Combined group regular interleaved + group injected simultaneous */ +#if defined(ADC3) +#define DDL_ADC_MULTI_TRIPLE_REG_SIM_INJ_SIM (ADC_CCTRL_ADCMSEL_4 | ADC_CCTRL_ADCMSEL_0) /*!< ADC triple mode enabled: Combined group regular simultaneous + group injected simultaneous */ +#define DDL_ADC_MULTI_TRIPLE_REG_SIM_INJ_ALT (ADC_CCTRL_ADCMSEL_4 | ADC_CCTRL_ADCMSEL_1 ) /*!< ADC triple mode enabled: Combined group regular simultaneous + group injected alternate trigger */ +#define DDL_ADC_MULTI_TRIPLE_INJ_SIMULT (ADC_CCTRL_ADCMSEL_4 | ADC_CCTRL_ADCMSEL_2 | ADC_CCTRL_ADCMSEL_0) /*!< ADC triple mode enabled: group injected simultaneous */ +#define DDL_ADC_MULTI_TRIPLE_REG_SIMULT (ADC_CCTRL_ADCMSEL_4 | ADC_CCTRL_ADCMSEL_2 | ADC_CCTRL_ADCMSEL_1 ) /*!< ADC triple mode enabled: group regular simultaneous */ +#define DDL_ADC_MULTI_TRIPLE_REG_INTERL (ADC_CCTRL_ADCMSEL_4 | ADC_CCTRL_ADCMSEL_2 | ADC_CCTRL_ADCMSEL_1 | ADC_CCTRL_ADCMSEL_0) /*!< ADC triple mode enabled: Combined group regular interleaved */ +#define DDL_ADC_MULTI_TRIPLE_INJ_ALTERN (ADC_CCTRL_ADCMSEL_4 | ADC_CCTRL_ADCMSEL_0) /*!< ADC triple mode enabled: group injected alternate trigger. Works only with external triggers (not internal SW start) */ +#endif +/** + * @} + */ + +/** @defgroup ADC_DDL_EC_MULTI_DMA_TRANSFER Multimode - DMA transfer + * @{ + */ +#define DDL_ADC_MULTI_REG_DMA_EACH_ADC 0x00000000UL /*!< ADC multimode group regular conversions are transferred by DMA: each ADC uses its own DMA channel, with its individual DMA transfer settings */ +#define DDL_ADC_MULTI_REG_DMA_LIMIT_1 ( ADC_CCTRL_DMAMODE_0) /*!< ADC multimode group regular conversions are transferred by DMA, one DMA channel for all ADC instances (DMA of ADC master), in limited mode (one shot mode): DMA transfer requests are stopped when number of DMA data transfers (number of ADC conversions) is reached. This ADC mode is intended to be used with DMA mode non-circular. Setting of DMA mode 1: 2 or 3 (dual or triple mode) half-words one by one, ADC1 then ADC2 then ADC3. */ +#define DDL_ADC_MULTI_REG_DMA_LIMIT_2 ( ADC_CCTRL_DMAMODE_1 ) /*!< ADC multimode group regular conversions are transferred by DMA, one DMA channel for all ADC instances (DMA of ADC master), in limited mode (one shot mode): DMA transfer requests are stopped when number of DMA data transfers (number of ADC conversions) is reached. This ADC mode is intended to be used with DMA mode non-circular. Setting of DMA mode 2: 2 or 3 (dual or triple mode) half-words one by one, ADC2&1 then ADC1&3 then ADC3&2. */ +#define DDL_ADC_MULTI_REG_DMA_LIMIT_3 ( ADC_CCTRL_DMAMODE_1 | ADC_CCTRL_DMAMODE_0) /*!< ADC multimode group regular conversions are transferred by DMA, one DMA channel for all ADC instances (DMA of ADC master), in limited mode (one shot mode): DMA transfer requests are stopped when number of DMA data transfers (number of ADC conversions) is reached. This ADC mode is intended to be used with DMA mode non-circular. Setting of DMA mode 3: 2 or 3 (dual or triple mode) bytes one by one, ADC2&1 then ADC1&3 then ADC3&2. */ +#define DDL_ADC_MULTI_REG_DMA_UNLMT_1 (ADC_CCTRL_DMAMODEDISSEL | ADC_CCTRL_DMAMODE_0) /*!< ADC multimode group regular conversions are transferred by DMA, one DMA channel for all ADC instances (DMA of ADC master), in unlimited mode: DMA transfer requests are unlimited, whatever number of DMA data transferred (number of ADC conversions) is reached. This ADC mode is intended to be used with DMA mode non-circular. Setting of DMA mode 1: 2 or 3 (dual or triple mode) half-words one by one, ADC1 then ADC2 then ADC3. */ +#define DDL_ADC_MULTI_REG_DMA_UNLMT_2 (ADC_CCTRL_DMAMODEDISSEL | ADC_CCTRL_DMAMODE_1 ) /*!< ADC multimode group regular conversions are transferred by DMA, one DMA channel for all ADC instances (DMA of ADC master), in unlimited mode: DMA transfer requests are unlimited, whatever number of DMA data transferred (number of ADC conversions) is reached. This ADC mode is intended to be used with DMA mode non-circular. Setting of DMA mode 2: 2 or 3 (dual or triple mode) half-words by pairs, ADC2&1 then ADC1&3 then ADC3&2. */ +#define DDL_ADC_MULTI_REG_DMA_UNLMT_3 (ADC_CCTRL_DMAMODEDISSEL | ADC_CCTRL_DMAMODE_1 | ADC_CCTRL_DMAMODE_0) /*!< ADC multimode group regular conversions are transferred by DMA, one DMA channel for all ADC instances (DMA of ADC master), in unlimited mode: DMA transfer requests are unlimited, whatever number of DMA data transferred (number of ADC conversions) is reached. This ADC mode is intended to be used with DMA mode non-circular. Setting of DMA mode 3: 2 or 3 (dual or triple mode) bytes one by one, ADC2&1 then ADC1&3 then ADC3&2. */ +/** + * @} + */ + +/** @defgroup ADC_DDL_EC_MULTI_TWOSMP_DELAY Multimode - Delay between two sampling phases + * @{ + */ +#define DDL_ADC_MULTI_TWOSMP_DELAY_5CYCLES 0x00000000UL /*!< ADC multimode delay between two sampling phases: 5 ADC clock cycles*/ +#define DDL_ADC_MULTI_TWOSMP_DELAY_6CYCLES ( ADC_CCTRL_SMPDEL2_0) /*!< ADC multimode delay between two sampling phases: 6 ADC clock cycles */ +#define DDL_ADC_MULTI_TWOSMP_DELAY_7CYCLES ( ADC_CCTRL_SMPDEL2_1 ) /*!< ADC multimode delay between two sampling phases: 7 ADC clock cycles */ +#define DDL_ADC_MULTI_TWOSMP_DELAY_8CYCLES ( ADC_CCTRL_SMPDEL2_1 | ADC_CCTRL_SMPDEL2_0) /*!< ADC multimode delay between two sampling phases: 8 ADC clock cycles */ +#define DDL_ADC_MULTI_TWOSMP_DELAY_9CYCLES ( ADC_CCTRL_SMPDEL2_2 ) /*!< ADC multimode delay between two sampling phases: 9 ADC clock cycles */ +#define DDL_ADC_MULTI_TWOSMP_DELAY_10CYCLES ( ADC_CCTRL_SMPDEL2_2 | ADC_CCTRL_SMPDEL2_0) /*!< ADC multimode delay between two sampling phases: 10 ADC clock cycles */ +#define DDL_ADC_MULTI_TWOSMP_DELAY_11CYCLES ( ADC_CCTRL_SMPDEL2_2 | ADC_CCTRL_SMPDEL2_1 ) /*!< ADC multimode delay between two sampling phases: 11 ADC clock cycles */ +#define DDL_ADC_MULTI_TWOSMP_DELAY_12CYCLES ( ADC_CCTRL_SMPDEL2_2 | ADC_CCTRL_SMPDEL2_1 | ADC_CCTRL_SMPDEL2_0) /*!< ADC multimode delay between two sampling phases: 12 ADC clock cycles */ +#define DDL_ADC_MULTI_TWOSMP_DELAY_13CYCLES (ADC_CCTRL_SMPDEL2_3 ) /*!< ADC multimode delay between two sampling phases: 13 ADC clock cycles */ +#define DDL_ADC_MULTI_TWOSMP_DELAY_14CYCLES (ADC_CCTRL_SMPDEL2_3 | ADC_CCTRL_SMPDEL2_0) /*!< ADC multimode delay between two sampling phases: 14 ADC clock cycles */ +#define DDL_ADC_MULTI_TWOSMP_DELAY_15CYCLES (ADC_CCTRL_SMPDEL2_3 | ADC_CCTRL_SMPDEL2_1 ) /*!< ADC multimode delay between two sampling phases: 15 ADC clock cycles */ +#define DDL_ADC_MULTI_TWOSMP_DELAY_16CYCLES (ADC_CCTRL_SMPDEL2_3 | ADC_CCTRL_SMPDEL2_1 | ADC_CCTRL_SMPDEL2_0) /*!< ADC multimode delay between two sampling phases: 16 ADC clock cycles */ +#define DDL_ADC_MULTI_TWOSMP_DELAY_17CYCLES (ADC_CCTRL_SMPDEL2_3 | ADC_CCTRL_SMPDEL2_2 ) /*!< ADC multimode delay between two sampling phases: 17 ADC clock cycles */ +#define DDL_ADC_MULTI_TWOSMP_DELAY_18CYCLES (ADC_CCTRL_SMPDEL2_3 | ADC_CCTRL_SMPDEL2_2 | ADC_CCTRL_SMPDEL2_0) /*!< ADC multimode delay between two sampling phases: 18 ADC clock cycles */ +#define DDL_ADC_MULTI_TWOSMP_DELAY_19CYCLES (ADC_CCTRL_SMPDEL2_3 | ADC_CCTRL_SMPDEL2_2 | ADC_CCTRL_SMPDEL2_1 ) /*!< ADC multimode delay between two sampling phases: 19 ADC clock cycles */ +#define DDL_ADC_MULTI_TWOSMP_DELAY_20CYCLES (ADC_CCTRL_SMPDEL2_3 | ADC_CCTRL_SMPDEL2_2 | ADC_CCTRL_SMPDEL2_1 | ADC_CCTRL_SMPDEL2_0) /*!< ADC multimode delay between two sampling phases: 20 ADC clock cycles */ +/** + * @} + */ + +/** @defgroup ADC_DDL_EC_MULTI_MASTER_SLAVE Multimode - ADC master or slave + * @{ + */ +#define DDL_ADC_MULTI_MASTER ( ADC_CDATA_RDATA_MST) /*!< In multimode, selection among several ADC instances: ADC master */ +#define DDL_ADC_MULTI_SLAVE (ADC_CDATA_RDATA_SLV ) /*!< In multimode, selection among several ADC instances: ADC slave */ +#define DDL_ADC_MULTI_MASTER_SLAVE (ADC_CDATA_RDATA_SLV | ADC_CDATA_RDATA_MST) /*!< In multimode, selection among several ADC instances: both ADC master and ADC slave */ +/** + * @} + */ + +#endif /* ADC_MULTIMODE_SUPPORT */ + + +/** @defgroup ADC_DDL_EC_HW_DELAYS Definitions of ADC hardware constraints delays + * @note Only ADC IP HW delays are defined in ADC LL driver driver, + * not timeout values. + * For details on delays values, refer to descriptions in source code + * above each literal definition. + * @{ + */ + +/* Note: Only ADC IP HW delays are defined in ADC LL driver driver, */ +/* not timeout values. */ +/* Timeout values for ADC operations are dependent to device clock */ +/* configuration (system clock versus ADC clock), */ +/* and therefore must be defined in user application. */ +/* Indications for estimation of ADC timeout delays, for this */ +/* APM32 series: */ +/* - ADC enable time: maximum delay is 2us */ +/* (refer to device datasheet, parameter "tSTAB") */ +/* - ADC conversion time: duration depending on ADC clock and ADC */ +/* configuration. */ +/* (refer to device reference manual, section "Timing") */ + +/* Delay for internal voltage reference stabilization time. */ +/* Delay set to maximum value (refer to device datasheet, */ +/* parameter "tSTART"). */ +/* Unit: us */ +#define DDL_ADC_DELAY_VREFINT_STAB_US ( 10UL) /*!< Delay for internal voltage reference stabilization time */ + +/* Delay for temperature sensor stabilization time. */ +/* Literal set to maximum value (refer to device datasheet, */ +/* parameter "tSTART"). */ +/* Unit: us */ +#define DDL_ADC_DELAY_TEMPSENSOR_STAB_US ( 10UL) /*!< Delay for internal voltage reference stabilization time */ + +/** + * @} + */ + +/** + * @} + */ + + +/* Exported macro ------------------------------------------------------------*/ +/** @defgroup ADC_DDL_Exported_Macros ADC Exported Macros + * @{ + */ + +/** @defgroup ADC_DDL_EM_WRITE_READ Common write and read registers Macros + * @{ + */ + +/** + * @brief Write a value in ADC register + * @param __INSTANCE__ ADC Instance + * @param __REG__ Register to be written + * @param __VALUE__ Value to be written in the register + * @retval None + */ +#define DDL_ADC_WriteReg(__INSTANCE__, __REG__, __VALUE__) WRITE_REG(__INSTANCE__->__REG__, (__VALUE__)) + +/** + * @brief Read a value in ADC register + * @param __INSTANCE__ ADC Instance + * @param __REG__ Register to be read + * @retval Register value + */ +#define DDL_ADC_ReadReg(__INSTANCE__, __REG__) READ_REG(__INSTANCE__->__REG__) +/** + * @} + */ + +/** @defgroup ADC_DDL_EM_HELPER_MACRO ADC helper macro + * @{ + */ + +/** + * @brief Helper macro to get ADC channel number in decimal format + * from literals DDL_ADC_CHANNEL_x. + * @note Example: + * __DDL_ADC_CHANNEL_TO_DECIMAL_NB(DDL_ADC_CHANNEL_4) + * will return decimal number "4". + * @note The input can be a value from functions where a channel + * number is returned, either defined with number + * or with bitfield (only one bit must be set). + * @param __CHANNEL__ This parameter can be one of the following values: + * @arg @ref DDL_ADC_CHANNEL_0 + * @arg @ref DDL_ADC_CHANNEL_1 + * @arg @ref DDL_ADC_CHANNEL_2 + * @arg @ref DDL_ADC_CHANNEL_3 + * @arg @ref DDL_ADC_CHANNEL_4 + * @arg @ref DDL_ADC_CHANNEL_5 + * @arg @ref DDL_ADC_CHANNEL_6 + * @arg @ref DDL_ADC_CHANNEL_7 + * @arg @ref DDL_ADC_CHANNEL_8 + * @arg @ref DDL_ADC_CHANNEL_9 + * @arg @ref DDL_ADC_CHANNEL_10 + * @arg @ref DDL_ADC_CHANNEL_11 + * @arg @ref DDL_ADC_CHANNEL_12 + * @arg @ref DDL_ADC_CHANNEL_13 + * @arg @ref DDL_ADC_CHANNEL_14 + * @arg @ref DDL_ADC_CHANNEL_15 + * @arg @ref DDL_ADC_CHANNEL_16 + * @arg @ref DDL_ADC_CHANNEL_17 + * @arg @ref DDL_ADC_CHANNEL_18 + * @arg @ref DDL_ADC_CHANNEL_VREFINT (1) + * @arg @ref DDL_ADC_CHANNEL_TEMPSENSOR (1)(2) + * @arg @ref DDL_ADC_CHANNEL_VBAT (1) + * + * (1) On APM32F4, parameter available only on ADC instance: ADC1.\n + * (2) On devices APM32F42x and APM32F43x, limitation: this internal channel is shared between temperature sensor and Vbat, only 1 measurement path must be enabled. + * @retval Value between Min_Data=0 and Max_Data=18 + */ +#define __DDL_ADC_CHANNEL_TO_DECIMAL_NB(__CHANNEL__) \ + (((__CHANNEL__) & ADC_CHANNEL_ID_NUMBER_MASK) >> ADC_CHANNEL_ID_NUMBER_BITOFFSET_POS) + +/** + * @brief Helper macro to get ADC channel in literal format DDL_ADC_CHANNEL_x + * from number in decimal format. + * @note Example: + * __DDL_ADC_DECIMAL_NB_TO_CHANNEL(4) + * will return a data equivalent to "DDL_ADC_CHANNEL_4". + * @param __DECIMAL_NB__ Value between Min_Data=0 and Max_Data=18 + * @retval Returned value can be one of the following values: + * @arg @ref DDL_ADC_CHANNEL_0 + * @arg @ref DDL_ADC_CHANNEL_1 + * @arg @ref DDL_ADC_CHANNEL_2 + * @arg @ref DDL_ADC_CHANNEL_3 + * @arg @ref DDL_ADC_CHANNEL_4 + * @arg @ref DDL_ADC_CHANNEL_5 + * @arg @ref DDL_ADC_CHANNEL_6 + * @arg @ref DDL_ADC_CHANNEL_7 + * @arg @ref DDL_ADC_CHANNEL_8 + * @arg @ref DDL_ADC_CHANNEL_9 + * @arg @ref DDL_ADC_CHANNEL_10 + * @arg @ref DDL_ADC_CHANNEL_11 + * @arg @ref DDL_ADC_CHANNEL_12 + * @arg @ref DDL_ADC_CHANNEL_13 + * @arg @ref DDL_ADC_CHANNEL_14 + * @arg @ref DDL_ADC_CHANNEL_15 + * @arg @ref DDL_ADC_CHANNEL_16 + * @arg @ref DDL_ADC_CHANNEL_17 + * @arg @ref DDL_ADC_CHANNEL_18 + * @arg @ref DDL_ADC_CHANNEL_VREFINT (1) + * @arg @ref DDL_ADC_CHANNEL_TEMPSENSOR (1)(2) + * @arg @ref DDL_ADC_CHANNEL_VBAT (1) + * + * (1) On APM32F4, parameter available only on ADC instance: ADC1.\n + * (2) On devices APM32F42x and APM32F43x, limitation: this internal channel is shared between temperature sensor and Vbat, only 1 measurement path must be enabled.\n + * (1) For ADC channel read back from ADC register, + * comparison with internal channel parameter to be done + * using helper macro @ref __DDL_ADC_CHANNEL_INTERNAL_TO_EXTERNAL(). + */ +#define __DDL_ADC_DECIMAL_NB_TO_CHANNEL(__DECIMAL_NB__) \ + (((__DECIMAL_NB__) <= 9UL) \ + ? ( \ + ((__DECIMAL_NB__) << ADC_CHANNEL_ID_NUMBER_BITOFFSET_POS) | \ + (ADC_SMPTIM2_REGOFFSET | (((uint32_t) (3UL * (__DECIMAL_NB__))) << ADC_CHANNEL_SMPx_BITOFFSET_POS)) \ + ) \ + : \ + ( \ + ((__DECIMAL_NB__) << ADC_CHANNEL_ID_NUMBER_BITOFFSET_POS) | \ + (ADC_SMPTIM1_REGOFFSET | (((uint32_t) (3UL * ((__DECIMAL_NB__) - 10UL))) << ADC_CHANNEL_SMPx_BITOFFSET_POS)) \ + ) \ + ) + +/** + * @brief Helper macro to determine whether the selected channel + * corresponds to literal definitions of driver. + * @note The different literal definitions of ADC channels are: + * - ADC internal channel: + * DDL_ADC_CHANNEL_VREFINT, DDL_ADC_CHANNEL_TEMPSENSOR, ... + * - ADC external channel (channel connected to a GPIO pin): + * DDL_ADC_CHANNEL_1, DDL_ADC_CHANNEL_2, ... + * @note The channel parameter must be a value defined from literal + * definition of a ADC internal channel (DDL_ADC_CHANNEL_VREFINT, + * DDL_ADC_CHANNEL_TEMPSENSOR, ...), + * ADC external channel (DDL_ADC_CHANNEL_1, DDL_ADC_CHANNEL_2, ...), + * must not be a value from functions where a channel number is + * returned from ADC registers, + * because internal and external channels share the same channel + * number in ADC registers. The differentiation is made only with + * parameters definitions of driver. + * @param __CHANNEL__ This parameter can be one of the following values: + * @arg @ref DDL_ADC_CHANNEL_0 + * @arg @ref DDL_ADC_CHANNEL_1 + * @arg @ref DDL_ADC_CHANNEL_2 + * @arg @ref DDL_ADC_CHANNEL_3 + * @arg @ref DDL_ADC_CHANNEL_4 + * @arg @ref DDL_ADC_CHANNEL_5 + * @arg @ref DDL_ADC_CHANNEL_6 + * @arg @ref DDL_ADC_CHANNEL_7 + * @arg @ref DDL_ADC_CHANNEL_8 + * @arg @ref DDL_ADC_CHANNEL_9 + * @arg @ref DDL_ADC_CHANNEL_10 + * @arg @ref DDL_ADC_CHANNEL_11 + * @arg @ref DDL_ADC_CHANNEL_12 + * @arg @ref DDL_ADC_CHANNEL_13 + * @arg @ref DDL_ADC_CHANNEL_14 + * @arg @ref DDL_ADC_CHANNEL_15 + * @arg @ref DDL_ADC_CHANNEL_16 + * @arg @ref DDL_ADC_CHANNEL_17 + * @arg @ref DDL_ADC_CHANNEL_18 + * @arg @ref DDL_ADC_CHANNEL_VREFINT (1) + * @arg @ref DDL_ADC_CHANNEL_TEMPSENSOR (1)(2) + * @arg @ref DDL_ADC_CHANNEL_VBAT (1) + * + * (1) On APM32F4, parameter available only on ADC instance: ADC1.\n + * (2) On devices APM32F42x and APM32F43x, limitation: this internal channel is shared between temperature sensor and Vbat, only 1 measurement path must be enabled. + * @retval Value "0" if the channel corresponds to a parameter definition of a ADC external channel (channel connected to a GPIO pin). + * Value "1" if the channel corresponds to a parameter definition of a ADC internal channel. + */ +#define __DDL_ADC_IS_CHANNEL_INTERNAL(__CHANNEL__) \ + (((__CHANNEL__) & ADC_CHANNEL_ID_INTERNAL_CH_MASK) != 0UL) + +/** + * @brief Helper macro to convert a channel defined from parameter + * definition of a ADC internal channel (DDL_ADC_CHANNEL_VREFINT, + * DDL_ADC_CHANNEL_TEMPSENSOR, ...), + * to its equivalent parameter definition of a ADC external channel + * (DDL_ADC_CHANNEL_1, DDL_ADC_CHANNEL_2, ...). + * @note The channel parameter can be, additionally to a value + * defined from parameter definition of a ADC internal channel + * (DDL_ADC_CHANNEL_VREFINT, DDL_ADC_CHANNEL_TEMPSENSOR, ...), + * a value defined from parameter definition of + * ADC external channel (DDL_ADC_CHANNEL_1, DDL_ADC_CHANNEL_2, ...) + * or a value from functions where a channel number is returned + * from ADC registers. + * @param __CHANNEL__ This parameter can be one of the following values: + * @arg @ref DDL_ADC_CHANNEL_0 + * @arg @ref DDL_ADC_CHANNEL_1 + * @arg @ref DDL_ADC_CHANNEL_2 + * @arg @ref DDL_ADC_CHANNEL_3 + * @arg @ref DDL_ADC_CHANNEL_4 + * @arg @ref DDL_ADC_CHANNEL_5 + * @arg @ref DDL_ADC_CHANNEL_6 + * @arg @ref DDL_ADC_CHANNEL_7 + * @arg @ref DDL_ADC_CHANNEL_8 + * @arg @ref DDL_ADC_CHANNEL_9 + * @arg @ref DDL_ADC_CHANNEL_10 + * @arg @ref DDL_ADC_CHANNEL_11 + * @arg @ref DDL_ADC_CHANNEL_12 + * @arg @ref DDL_ADC_CHANNEL_13 + * @arg @ref DDL_ADC_CHANNEL_14 + * @arg @ref DDL_ADC_CHANNEL_15 + * @arg @ref DDL_ADC_CHANNEL_16 + * @arg @ref DDL_ADC_CHANNEL_17 + * @arg @ref DDL_ADC_CHANNEL_18 + * @arg @ref DDL_ADC_CHANNEL_VREFINT (1) + * @arg @ref DDL_ADC_CHANNEL_TEMPSENSOR (1)(2) + * @arg @ref DDL_ADC_CHANNEL_VBAT (1) + * + * (1) On APM32F4, parameter available only on ADC instance: ADC1.\n + * (2) On devices APM32F42x and APM32F43x, limitation: this internal channel is shared between temperature sensor and Vbat, only 1 measurement path must be enabled. + * @retval Returned value can be one of the following values: + * @arg @ref DDL_ADC_CHANNEL_0 + * @arg @ref DDL_ADC_CHANNEL_1 + * @arg @ref DDL_ADC_CHANNEL_2 + * @arg @ref DDL_ADC_CHANNEL_3 + * @arg @ref DDL_ADC_CHANNEL_4 + * @arg @ref DDL_ADC_CHANNEL_5 + * @arg @ref DDL_ADC_CHANNEL_6 + * @arg @ref DDL_ADC_CHANNEL_7 + * @arg @ref DDL_ADC_CHANNEL_8 + * @arg @ref DDL_ADC_CHANNEL_9 + * @arg @ref DDL_ADC_CHANNEL_10 + * @arg @ref DDL_ADC_CHANNEL_11 + * @arg @ref DDL_ADC_CHANNEL_12 + * @arg @ref DDL_ADC_CHANNEL_13 + * @arg @ref DDL_ADC_CHANNEL_14 + * @arg @ref DDL_ADC_CHANNEL_15 + * @arg @ref DDL_ADC_CHANNEL_16 + * @arg @ref DDL_ADC_CHANNEL_17 + * @arg @ref DDL_ADC_CHANNEL_18 + */ +#define __DDL_ADC_CHANNEL_INTERNAL_TO_EXTERNAL(__CHANNEL__) \ + ((__CHANNEL__) & ~ADC_CHANNEL_ID_INTERNAL_CH_MASK) + +/** + * @brief Helper macro to determine whether the internal channel + * selected is available on the ADC instance selected. + * @note The channel parameter must be a value defined from parameter + * definition of a ADC internal channel (DDL_ADC_CHANNEL_VREFINT, + * DDL_ADC_CHANNEL_TEMPSENSOR, ...), + * must not be a value defined from parameter definition of + * ADC external channel (DDL_ADC_CHANNEL_1, DDL_ADC_CHANNEL_2, ...) + * or a value from functions where a channel number is + * returned from ADC registers, + * because internal and external channels share the same channel + * number in ADC registers. The differentiation is made only with + * parameters definitions of driver. + * @param __ADC_INSTANCE__ ADC instance + * @param __CHANNEL__ This parameter can be one of the following values: + * @arg @ref DDL_ADC_CHANNEL_VREFINT (1) + * @arg @ref DDL_ADC_CHANNEL_TEMPSENSOR (1)(2) + * @arg @ref DDL_ADC_CHANNEL_VBAT (1) + * + * (1) On APM32F4, parameter available only on ADC instance: ADC1. + * (2) On devices APM32F42x and APM32F43x, limitation: this internal channel is shared between temperature sensor and Vbat, only 1 measurement path must be enabled. + * @retval Value "0" if the internal channel selected is not available on the ADC instance selected. + * Value "1" if the internal channel selected is available on the ADC instance selected. + */ +#define __DDL_ADC_IS_CHANNEL_INTERNAL_AVAILABLE(__ADC_INSTANCE__, __CHANNEL__) \ + ( \ + ((__CHANNEL__) == DDL_ADC_CHANNEL_VREFINT) || \ + ((__CHANNEL__) == DDL_ADC_CHANNEL_TEMPSENSOR) || \ + ((__CHANNEL__) == DDL_ADC_CHANNEL_VBAT) \ + ) +/** + * @brief Helper macro to define ADC analog watchdog parameter: + * define a single channel to monitor with analog watchdog + * from sequencer channel and groups definition. + * @note To be used with function @ref DDL_ADC_SetAnalogWDMonitChannels(). + * Example: + * DDL_ADC_SetAnalogWDMonitChannels( + * ADC1, DDL_ADC_AWD1, + * __DDL_ADC_ANALOGWD_CHANNEL_GROUP(DDL_ADC_CHANNEL4, DDL_ADC_GROUP_REGULAR)) + * @param __CHANNEL__ This parameter can be one of the following values: + * @arg @ref DDL_ADC_CHANNEL_0 + * @arg @ref DDL_ADC_CHANNEL_1 + * @arg @ref DDL_ADC_CHANNEL_2 + * @arg @ref DDL_ADC_CHANNEL_3 + * @arg @ref DDL_ADC_CHANNEL_4 + * @arg @ref DDL_ADC_CHANNEL_5 + * @arg @ref DDL_ADC_CHANNEL_6 + * @arg @ref DDL_ADC_CHANNEL_7 + * @arg @ref DDL_ADC_CHANNEL_8 + * @arg @ref DDL_ADC_CHANNEL_9 + * @arg @ref DDL_ADC_CHANNEL_10 + * @arg @ref DDL_ADC_CHANNEL_11 + * @arg @ref DDL_ADC_CHANNEL_12 + * @arg @ref DDL_ADC_CHANNEL_13 + * @arg @ref DDL_ADC_CHANNEL_14 + * @arg @ref DDL_ADC_CHANNEL_15 + * @arg @ref DDL_ADC_CHANNEL_16 + * @arg @ref DDL_ADC_CHANNEL_17 + * @arg @ref DDL_ADC_CHANNEL_18 + * @arg @ref DDL_ADC_CHANNEL_VREFINT (1) + * @arg @ref DDL_ADC_CHANNEL_TEMPSENSOR (1)(2) + * @arg @ref DDL_ADC_CHANNEL_VBAT (1) + * + * (1) On APM32F4, parameter available only on ADC instance: ADC1.\n + * (2) On devices APM32F42x and APM32F43x, limitation: this internal channel is shared between temperature sensor and Vbat, only 1 measurement path must be enabled.\n + * (1) For ADC channel read back from ADC register, + * comparison with internal channel parameter to be done + * using helper macro @ref __DDL_ADC_CHANNEL_INTERNAL_TO_EXTERNAL(). + * @param __GROUP__ This parameter can be one of the following values: + * @arg @ref DDL_ADC_GROUP_REGULAR + * @arg @ref DDL_ADC_GROUP_INJECTED + * @arg @ref DDL_ADC_GROUP_REGULAR_INJECTED + * @retval Returned value can be one of the following values: + * @arg @ref DDL_ADC_AWD_DISABLE + * @arg @ref DDL_ADC_AWD_ALL_CHANNELS_REG + * @arg @ref DDL_ADC_AWD_ALL_CHANNELS_INJ + * @arg @ref DDL_ADC_AWD_ALL_CHANNELS_REG_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_0_REG + * @arg @ref DDL_ADC_AWD_CHANNEL_0_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_0_REG_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_1_REG + * @arg @ref DDL_ADC_AWD_CHANNEL_1_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_1_REG_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_2_REG + * @arg @ref DDL_ADC_AWD_CHANNEL_2_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_2_REG_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_3_REG + * @arg @ref DDL_ADC_AWD_CHANNEL_3_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_3_REG_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_4_REG + * @arg @ref DDL_ADC_AWD_CHANNEL_4_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_4_REG_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_5_REG + * @arg @ref DDL_ADC_AWD_CHANNEL_5_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_5_REG_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_6_REG + * @arg @ref DDL_ADC_AWD_CHANNEL_6_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_6_REG_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_7_REG + * @arg @ref DDL_ADC_AWD_CHANNEL_7_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_7_REG_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_8_REG + * @arg @ref DDL_ADC_AWD_CHANNEL_8_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_8_REG_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_9_REG + * @arg @ref DDL_ADC_AWD_CHANNEL_9_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_9_REG_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_10_REG + * @arg @ref DDL_ADC_AWD_CHANNEL_10_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_10_REG_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_11_REG + * @arg @ref DDL_ADC_AWD_CHANNEL_11_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_11_REG_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_12_REG + * @arg @ref DDL_ADC_AWD_CHANNEL_12_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_12_REG_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_13_REG + * @arg @ref DDL_ADC_AWD_CHANNEL_13_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_13_REG_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_14_REG + * @arg @ref DDL_ADC_AWD_CHANNEL_14_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_14_REG_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_15_REG + * @arg @ref DDL_ADC_AWD_CHANNEL_15_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_15_REG_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_16_REG + * @arg @ref DDL_ADC_AWD_CHANNEL_16_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_16_REG_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_17_REG + * @arg @ref DDL_ADC_AWD_CHANNEL_17_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_17_REG_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_18_REG + * @arg @ref DDL_ADC_AWD_CHANNEL_18_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_18_REG_INJ + * @arg @ref DDL_ADC_AWD_CH_VREFINT_REG (1) + * @arg @ref DDL_ADC_AWD_CH_VREFINT_INJ (1) + * @arg @ref DDL_ADC_AWD_CH_VREFINT_REG_INJ (1) + * @arg @ref DDL_ADC_AWD_CH_TEMPSENSOR_REG (1)(2) + * @arg @ref DDL_ADC_AWD_CH_TEMPSENSOR_INJ (1)(2) + * @arg @ref DDL_ADC_AWD_CH_TEMPSENSOR_REG_INJ (1)(2) + * @arg @ref DDL_ADC_AWD_CH_VBAT_REG (1) + * @arg @ref DDL_ADC_AWD_CH_VBAT_INJ (1) + * @arg @ref DDL_ADC_AWD_CH_VBAT_REG_INJ (1) + * + * (1) On APM32F4, parameter available only on ADC instance: ADC1.\n + * (2) On devices APM32F42x and APM32F43x, limitation: this internal channel is shared between temperature sensor and Vbat, only 1 measurement path must be enabled. + */ +#define __DDL_ADC_ANALOGWD_CHANNEL_GROUP(__CHANNEL__, __GROUP__) \ + (((__GROUP__) == DDL_ADC_GROUP_REGULAR) \ + ? (((__CHANNEL__) & ADC_CHANNEL_ID_MASK) | ADC_CTRL1_REGAWDEN | ADC_CTRL1_AWDSGLEN) \ + : \ + ((__GROUP__) == DDL_ADC_GROUP_INJECTED) \ + ? (((__CHANNEL__) & ADC_CHANNEL_ID_MASK) | ADC_CTRL1_INJAWDEN | ADC_CTRL1_AWDSGLEN) \ + : \ + (((__CHANNEL__) & ADC_CHANNEL_ID_MASK) | ADC_CTRL1_INJAWDEN | ADC_CTRL1_REGAWDEN | ADC_CTRL1_AWDSGLEN) \ + ) + +/** + * @brief Helper macro to set the value of ADC analog watchdog threshold high + * or low in function of ADC resolution, when ADC resolution is + * different of 12 bits. + * @note To be used with function @ref DDL_ADC_SetAnalogWDThresholds(). + * Example, with a ADC resolution of 8 bits, to set the value of + * analog watchdog threshold high (on 8 bits): + * DDL_ADC_SetAnalogWDThresholds + * (< ADCx param >, + * __DDL_ADC_ANALOGWD_SET_THRESHOLD_RESOLUTION(DDL_ADC_RESOLUTION_8B, ) + * ); + * @param __ADC_RESOLUTION__ This parameter can be one of the following values: + * @arg @ref DDL_ADC_RESOLUTION_12B + * @arg @ref DDL_ADC_RESOLUTION_10B + * @arg @ref DDL_ADC_RESOLUTION_8B + * @arg @ref DDL_ADC_RESOLUTION_6B + * @param __AWD_THRESHOLD__ Value between Min_Data=0x000 and Max_Data=0xFFF + * @retval Value between Min_Data=0x000 and Max_Data=0xFFF + */ +#define __DDL_ADC_ANALOGWD_SET_THRESHOLD_RESOLUTION(__ADC_RESOLUTION__, __AWD_THRESHOLD__) \ + ((__AWD_THRESHOLD__) << ((__ADC_RESOLUTION__) >> (ADC_CTRL1_RESSEL_BITOFFSET_POS - 1UL ))) + +/** + * @brief Helper macro to get the value of ADC analog watchdog threshold high + * or low in function of ADC resolution, when ADC resolution is + * different of 12 bits. + * @note To be used with function @ref DDL_ADC_GetAnalogWDThresholds(). + * Example, with a ADC resolution of 8 bits, to get the value of + * analog watchdog threshold high (on 8 bits): + * < threshold_value_6_bits > = __DDL_ADC_ANALOGWD_GET_THRESHOLD_RESOLUTION + * (DDL_ADC_RESOLUTION_8B, + * DDL_ADC_GetAnalogWDThresholds(, DDL_ADC_AWD_THRESHOLD_HIGH) + * ); + * @param __ADC_RESOLUTION__ This parameter can be one of the following values: + * @arg @ref DDL_ADC_RESOLUTION_12B + * @arg @ref DDL_ADC_RESOLUTION_10B + * @arg @ref DDL_ADC_RESOLUTION_8B + * @arg @ref DDL_ADC_RESOLUTION_6B + * @param __AWD_THRESHOLD_12_BITS__ Value between Min_Data=0x000 and Max_Data=0xFFF + * @retval Value between Min_Data=0x000 and Max_Data=0xFFF + */ +#define __DDL_ADC_ANALOGWD_GET_THRESHOLD_RESOLUTION(__ADC_RESOLUTION__, __AWD_THRESHOLD_12_BITS__) \ + ((__AWD_THRESHOLD_12_BITS__) >> ((__ADC_RESOLUTION__) >> (ADC_CTRL1_RESSEL_BITOFFSET_POS - 1UL ))) + +#if defined(ADC_MULTIMODE_SUPPORT) +/** + * @brief Helper macro to get the ADC multimode conversion data of ADC master + * or ADC slave from raw value with both ADC conversion data concatenated. + * @note This macro is intended to be used when multimode transfer by DMA + * is enabled: refer to function @ref DDL_ADC_SetMultiDMATransfer(). + * In this case the transferred data need to processed with this macro + * to separate the conversion data of ADC master and ADC slave. + * @param __ADC_MULTI_MASTER_SLAVE__ This parameter can be one of the following values: + * @arg @ref DDL_ADC_MULTI_MASTER + * @arg @ref DDL_ADC_MULTI_SLAVE + * @param __ADC_MULTI_CONV_DATA__ Value between Min_Data=0x000 and Max_Data=0xFFF + * @retval Value between Min_Data=0x000 and Max_Data=0xFFF + */ +#define __DDL_ADC_MULTI_CONV_DATA_MASTER_SLAVE(__ADC_MULTI_MASTER_SLAVE__, __ADC_MULTI_CONV_DATA__) \ + (((__ADC_MULTI_CONV_DATA__) >> POSITION_VAL((__ADC_MULTI_MASTER_SLAVE__))) & ADC_CDATA_RDATA_MST) +#endif + +/** + * @brief Helper macro to select the ADC common instance + * to which is belonging the selected ADC instance. + * @note ADC common register instance can be used for: + * - Set parameters common to several ADC instances + * - Multimode (for devices with several ADC instances) + * Refer to functions having argument "ADCxy_COMMON" as parameter. + * @param __ADCx__ ADC instance + * @retval ADC common register instance + */ +#if defined(ADC1) && defined(ADC2) && defined(ADC3) +#define __DDL_ADC_COMMON_INSTANCE(__ADCx__) \ + (ADC123_COMMON) +#elif defined(ADC1) && defined(ADC2) +#define __DDL_ADC_COMMON_INSTANCE(__ADCx__) \ + ((__ADCx__) == ADC1 ? ADC1_COMMON : ADC2_COMMON) +#else +#define __DDL_ADC_COMMON_INSTANCE(__ADCx__) \ + (ADC1_COMMON) +#endif + +/** + * @brief Helper macro to check if all ADC instances sharing the same + * ADC common instance are disabled. + * @note This check is required by functions with setting conditioned to + * ADC state: + * All ADC instances of the ADC common group must be disabled. + * Refer to functions having argument "ADCxy_COMMON" as parameter. + * @note On devices with only 1 ADC common instance, parameter of this macro + * is useless and can be ignored (parameter kept for compatibility + * with devices featuring several ADC common instances). + * @param __ADCXY_COMMON__ ADC common instance + * (can be set directly from CMSIS definition or by using helper macro @ref __DDL_ADC_COMMON_INSTANCE() ) + * @retval Value "0" if all ADC instances sharing the same ADC common instance + * are disabled. + * Value "1" if at least one ADC instance sharing the same ADC common instance + * is enabled. + */ +#if defined(ADC1) && defined(ADC2) && defined(ADC3) +#define __DDL_ADC_IS_ENABLED_ALL_COMMON_INSTANCE(__ADCXY_COMMON__) \ + (DDL_ADC_IsEnabled(ADC1) | \ + DDL_ADC_IsEnabled(ADC2) | \ + DDL_ADC_IsEnabled(ADC3) ) +#elif defined(ADC1) && defined(ADC2) +#define __DDL_ADC_IS_ENABLED_ALL_COMMON_INSTANCE(__ADCXY_COMMON__) \ + (DDL_ADC_IsEnabled(ADC1) | \ + DDL_ADC_IsEnabled(ADC2) ) +#else +#define __DDL_ADC_IS_ENABLED_ALL_COMMON_INSTANCE(__ADCXY_COMMON__) \ + (DDL_ADC_IsEnabled(ADC1)) +#endif + +/** + * @brief Helper macro to define the ADC conversion data full-scale digital + * value corresponding to the selected ADC resolution. + * @note ADC conversion data full-scale corresponds to voltage range + * determined by analog voltage references Vref+ and Vref- + * (refer to reference manual). + * @param __ADC_RESOLUTION__ This parameter can be one of the following values: + * @arg @ref DDL_ADC_RESOLUTION_12B + * @arg @ref DDL_ADC_RESOLUTION_10B + * @arg @ref DDL_ADC_RESOLUTION_8B + * @arg @ref DDL_ADC_RESOLUTION_6B + * @retval ADC conversion data equivalent voltage value (unit: mVolt) + */ +#define __DDL_ADC_DIGITAL_SCALE(__ADC_RESOLUTION__) \ + (0xFFFU >> ((__ADC_RESOLUTION__) >> (ADC_CTRL1_RESSEL_BITOFFSET_POS - 1UL))) + +/** + * @brief Helper macro to convert the ADC conversion data from + * a resolution to another resolution. + * @param __DATA__ ADC conversion data to be converted + * @param __ADC_RESOLUTION_CURRENT__ Resolution of to the data to be converted + * This parameter can be one of the following values: + * @arg @ref DDL_ADC_RESOLUTION_12B + * @arg @ref DDL_ADC_RESOLUTION_10B + * @arg @ref DDL_ADC_RESOLUTION_8B + * @arg @ref DDL_ADC_RESOLUTION_6B + * @param __ADC_RESOLUTION_TARGET__ Resolution of the data after conversion + * This parameter can be one of the following values: + * @arg @ref DDL_ADC_RESOLUTION_12B + * @arg @ref DDL_ADC_RESOLUTION_10B + * @arg @ref DDL_ADC_RESOLUTION_8B + * @arg @ref DDL_ADC_RESOLUTION_6B + * @retval ADC conversion data to the requested resolution + */ +#define __DDL_ADC_CONVERT_DATA_RESOLUTION(__DATA__, __ADC_RESOLUTION_CURRENT__, __ADC_RESOLUTION_TARGET__) \ + (((__DATA__) \ + << ((__ADC_RESOLUTION_CURRENT__) >> (ADC_CTRL1_RESSEL_BITOFFSET_POS - 1UL))) \ + >> ((__ADC_RESOLUTION_TARGET__) >> (ADC_CTRL1_RESSEL_BITOFFSET_POS - 1UL)) \ + ) + +/** + * @brief Helper macro to calculate the voltage (unit: mVolt) + * corresponding to a ADC conversion data (unit: digital value). + * @note Analog reference voltage (Vref+) must be either known from + * user board environment or can be calculated using ADC measurement + * and ADC helper macro @ref __DDL_ADC_CALC_VREFANALOG_VOLTAGE(). + * @param __VREFANALOG_VOLTAGE__ Analog reference voltage (unit mV) + * @param __ADC_DATA__ ADC conversion data (resolution 12 bits) + * (unit: digital value). + * @param __ADC_RESOLUTION__ This parameter can be one of the following values: + * @arg @ref DDL_ADC_RESOLUTION_12B + * @arg @ref DDL_ADC_RESOLUTION_10B + * @arg @ref DDL_ADC_RESOLUTION_8B + * @arg @ref DDL_ADC_RESOLUTION_6B + * @retval ADC conversion data equivalent voltage value (unit: mVolt) + */ +#define __DDL_ADC_CALC_DATA_TO_VOLTAGE(__VREFANALOG_VOLTAGE__,\ + __ADC_DATA__,\ + __ADC_RESOLUTION__) \ + ((__ADC_DATA__) * (__VREFANALOG_VOLTAGE__) \ + / __DDL_ADC_DIGITAL_SCALE(__ADC_RESOLUTION__) \ + ) + +/** + * @brief Helper macro to calculate analog reference voltage (Vref+) + * (unit: mVolt) from ADC conversion data of internal voltage + * reference VrefInt. + * @note Computation is using VrefInt calibration value + * stored in system memory for each device during production. + * @note This voltage depends on user board environment: voltage level + * connected to pin Vref+. + * On devices with small package, the pin Vref+ is not present + * and internally bonded to pin Vdda. + * @note On this APM32 series, calibration data of internal voltage reference + * VrefInt corresponds to a resolution of 12 bits, + * this is the recommended ADC resolution to convert voltage of + * internal voltage reference VrefInt. + * Otherwise, this macro performs the processing to scale + * ADC conversion data to 12 bits. + * @param __VREFINT_ADC_DATA__ ADC conversion data (resolution 12 bits) + * of internal voltage reference VrefInt (unit: digital value). + * @param __ADC_RESOLUTION__ This parameter can be one of the following values: + * @arg @ref DDL_ADC_RESOLUTION_12B + * @arg @ref DDL_ADC_RESOLUTION_10B + * @arg @ref DDL_ADC_RESOLUTION_8B + * @arg @ref DDL_ADC_RESOLUTION_6B + * @retval Analog reference voltage (unit: mV) + */ +#define __DDL_ADC_CALC_VREFANALOG_VOLTAGE(__VREFINT_ADC_DATA__,\ + __ADC_RESOLUTION__) \ + (((uint32_t)(*VREFINT_CAL_ADDR) * VREFINT_CAL_VREF) \ + / __DDL_ADC_CONVERT_DATA_RESOLUTION((__VREFINT_ADC_DATA__), \ + (__ADC_RESOLUTION__), \ + DDL_ADC_RESOLUTION_12B)) + +/** + * @brief Helper macro to calculate the temperature (unit: degree Celsius) + * from ADC conversion data of internal temperature sensor. + * @note Computation is using temperature sensor calibration values + * stored in system memory for each device during production. + * @note Calculation formula: + * Temperature = ((TS_ADC_DATA - TS_CAL1) + * * (TS_CAL2_TEMP - TS_CAL1_TEMP)) + * / (TS_CAL2 - TS_CAL1) + TS_CAL1_TEMP + * with TS_ADC_DATA = temperature sensor raw data measured by ADC + * Avg_Slope = (TS_CAL2 - TS_CAL1) + * / (TS_CAL2_TEMP - TS_CAL1_TEMP) + * TS_CAL1 = equivalent TS_ADC_DATA at temperature + * TEMP_DEGC_CAL1 (calibrated in factory) + * TS_CAL2 = equivalent TS_ADC_DATA at temperature + * TEMP_DEGC_CAL2 (calibrated in factory) + * Caution: Calculation relevancy under reserve that calibration + * parameters are correct (address and data). + * To calculate temperature using temperature sensor + * datasheet typical values (generic values less, therefore + * less accurate than calibrated values), + * use helper macro @ref __DDL_ADC_CALC_TEMPERATURE_TYP_PARAMS(). + * @note As calculation input, the analog reference voltage (Vref+) must be + * defined as it impacts the ADC LSB equivalent voltage. + * @note Analog reference voltage (Vref+) must be either known from + * user board environment or can be calculated using ADC measurement + * and ADC helper macro @ref __DDL_ADC_CALC_VREFANALOG_VOLTAGE(). + * @note On this APM32 series, calibration data of temperature sensor + * corresponds to a resolution of 12 bits, + * this is the recommended ADC resolution to convert voltage of + * temperature sensor. + * Otherwise, this macro performs the processing to scale + * ADC conversion data to 12 bits. + * @param __VREFANALOG_VOLTAGE__ Analog reference voltage (unit mV) + * @param __TEMPSENSOR_ADC_DATA__ ADC conversion data of internal + * temperature sensor (unit: digital value). + * @param __ADC_RESOLUTION__ ADC resolution at which internal temperature + * sensor voltage has been measured. + * This parameter can be one of the following values: + * @arg @ref DDL_ADC_RESOLUTION_12B + * @arg @ref DDL_ADC_RESOLUTION_10B + * @arg @ref DDL_ADC_RESOLUTION_8B + * @arg @ref DDL_ADC_RESOLUTION_6B + * @retval Temperature (unit: degree Celsius) + */ +#define __DDL_ADC_CALC_TEMPERATURE(__VREFANALOG_VOLTAGE__,\ + __TEMPSENSOR_ADC_DATA__,\ + __ADC_RESOLUTION__) \ + (((( ((int32_t)((__DDL_ADC_CONVERT_DATA_RESOLUTION((__TEMPSENSOR_ADC_DATA__), \ + (__ADC_RESOLUTION__), \ + DDL_ADC_RESOLUTION_12B) \ + * (__VREFANALOG_VOLTAGE__)) \ + / TEMPSENSOR_CAL_VREFANALOG) \ + - (int32_t) *TEMPSENSOR_CAL1_ADDR) \ + ) * (int32_t)(TEMPSENSOR_CAL2_TEMP - TEMPSENSOR_CAL1_TEMP) \ + ) / (int32_t)((int32_t)*TEMPSENSOR_CAL2_ADDR - (int32_t)*TEMPSENSOR_CAL1_ADDR) \ + ) + TEMPSENSOR_CAL1_TEMP \ + ) + +/** + * @brief Helper macro to calculate the temperature (unit: degree Celsius) + * from ADC conversion data of internal temperature sensor. + * @note Computation is using temperature sensor typical values + * (refer to device datasheet). + * @note Calculation formula: + * Temperature = (TS_TYP_CALx_VOLT(uV) - TS_ADC_DATA * Conversion_uV) + * / Avg_Slope + CALx_TEMP + * with TS_ADC_DATA = temperature sensor raw data measured by ADC + * (unit: digital value) + * Avg_Slope = temperature sensor slope + * (unit: uV/Degree Celsius) + * TS_TYP_CALx_VOLT = temperature sensor digital value at + * temperature CALx_TEMP (unit: mV) + * Caution: Calculation relevancy under reserve the temperature sensor + * of the current device has characteristics in line with + * datasheet typical values. + * If temperature sensor calibration values are available on + * on this device (presence of macro __DDL_ADC_CALC_TEMPERATURE()), + * temperature calculation will be more accurate using + * helper macro @ref __DDL_ADC_CALC_TEMPERATURE(). + * @note As calculation input, the analog reference voltage (Vref+) must be + * defined as it impacts the ADC LSB equivalent voltage. + * @note Analog reference voltage (Vref+) must be either known from + * user board environment or can be calculated using ADC measurement + * and ADC helper macro @ref __DDL_ADC_CALC_VREFANALOG_VOLTAGE(). + * @note ADC measurement data must correspond to a resolution of 12bits + * (full scale digital value 4095). If not the case, the data must be + * preliminarily rescaled to an equivalent resolution of 12 bits. + * @param __TEMPSENSOR_TYP_AVGSLOPE__ Device datasheet data Temperature sensor slope typical value (unit uV/DegCelsius). + * On APM32F4, refer to device datasheet parameter "Avg_Slope". + * @param __TEMPSENSOR_TYP_CALX_V__ Device datasheet data Temperature sensor voltage typical value (at temperature and Vref+ defined in parameters below) (unit mV). + * On APM32F4, refer to device datasheet parameter "V25". + * @param __TEMPSENSOR_CALX_TEMP__ Device datasheet data Temperature at which temperature sensor voltage (see parameter above) is corresponding (unit mV) + * @param __VREFANALOG_VOLTAGE__ Analog voltage reference (Vref+) voltage (unit mV) + * @param __TEMPSENSOR_ADC_DATA__ ADC conversion data of internal temperature sensor (unit digital value). + * @param __ADC_RESOLUTION__ ADC resolution at which internal temperature sensor voltage has been measured. + * This parameter can be one of the following values: + * @arg @ref DDL_ADC_RESOLUTION_12B + * @arg @ref DDL_ADC_RESOLUTION_10B + * @arg @ref DDL_ADC_RESOLUTION_8B + * @arg @ref DDL_ADC_RESOLUTION_6B + * @retval Temperature (unit: degree Celsius) + */ +#define __DDL_ADC_CALC_TEMPERATURE_TYP_PARAMS(__TEMPSENSOR_TYP_AVGSLOPE__,\ + __TEMPSENSOR_TYP_CALX_V__,\ + __TEMPSENSOR_CALX_TEMP__,\ + __VREFANALOG_VOLTAGE__,\ + __TEMPSENSOR_ADC_DATA__,\ + __ADC_RESOLUTION__) \ + ((( ( \ + (int32_t)(((__TEMPSENSOR_TYP_CALX_V__)) \ + * 1000) \ + - \ + (int32_t)((((__TEMPSENSOR_ADC_DATA__) * (__VREFANALOG_VOLTAGE__)) \ + / __DDL_ADC_DIGITAL_SCALE(__ADC_RESOLUTION__)) \ + * 1000) \ + ) \ + ) / (__TEMPSENSOR_TYP_AVGSLOPE__) \ + ) + (__TEMPSENSOR_CALX_TEMP__) \ + ) + +/** + * @} + */ + +/** + * @} + */ + + +/* Exported functions --------------------------------------------------------*/ +/** @defgroup ADC_DDL_Exported_Functions ADC Exported Functions + * @{ + */ + +/** @defgroup ADC_DDL_EF_DMA_Management ADC DMA management + * @{ + */ +/* Note: LL ADC functions to set DMA transfer are located into sections of */ +/* configuration of ADC instance, groups and multimode (if available): */ +/* @ref DDL_ADC_REG_SetDMATransfer(), ... */ + +/** + * @brief Function to help to configure DMA transfer from ADC: retrieve the + * ADC register address from ADC instance and a list of ADC registers + * intended to be used (most commonly) with DMA transfer. + * @note These ADC registers are data registers: + * when ADC conversion data is available in ADC data registers, + * ADC generates a DMA transfer request. + * @note This macro is intended to be used with LL DMA driver, refer to + * function "DDL_DMA_ConfigAddresses()". + * Example: + * DDL_DMA_ConfigAddresses(DMA1, + * DDL_DMA_CHANNEL_1, + * DDL_ADC_DMA_GetRegAddr(ADC1, DDL_ADC_DMA_REG_REGULAR_DATA), + * (uint32_t)&< array or variable >, + * DDL_DMA_DIRECTION_PERIPH_TO_MEMORY); + * @note For devices with several ADC: in multimode, some devices + * use a different data register outside of ADC instance scope + * (common data register). This macro manages this register difference, + * only ADC instance has to be set as parameter. + * @param ADCx ADC instance + * @param Register This parameter can be one of the following values: + * @arg @ref DDL_ADC_DMA_REG_REGULAR_DATA + * @arg @ref DDL_ADC_DMA_REG_REGULAR_DATA_MULTI (1) + * + * (1) Available on devices with several ADC instances. + * @retval ADC register address + */ +#if defined(ADC_MULTIMODE_SUPPORT) +__STATIC_INLINE uint32_t DDL_ADC_DMA_GetRegAddr(ADC_TypeDef *ADCx, uint32_t Register) +{ + uint32_t data_reg_addr = 0UL; + + if (Register == DDL_ADC_DMA_REG_REGULAR_DATA) + { + /* Retrieve address of register DR */ + data_reg_addr = (uint32_t)&(ADCx->REGDATA); + } + else /* (Register == DDL_ADC_DMA_REG_REGULAR_DATA_MULTI) */ + { + /* Retrieve address of register CDATA */ + data_reg_addr = (uint32_t)&((__DDL_ADC_COMMON_INSTANCE(ADCx))->CDATA); + } + + return data_reg_addr; +} +#else +__STATIC_INLINE uint32_t DDL_ADC_DMA_GetRegAddr(ADC_TypeDef *ADCx, uint32_t Register) +{ + /* Retrieve address of register DR */ + return (uint32_t)&(ADCx->REGDATA); +} +#endif + +/** + * @} + */ + +/** @defgroup ADC_DDL_EF_Configuration_ADC_Common Configuration of ADC hierarchical scope: common to several ADC instances + * @{ + */ + +/** + * @brief Set parameter common to several ADC: Clock source and prescaler. + * @param ADCxy_COMMON ADC common instance + * (can be set directly from CMSIS definition or by using helper macro @ref __DDL_ADC_COMMON_INSTANCE() ) + * @param CommonClock This parameter can be one of the following values: + * @arg @ref DDL_ADC_CLOCK_SYNC_PCLK_DIV2 + * @arg @ref DDL_ADC_CLOCK_SYNC_PCLK_DIV4 + * @arg @ref DDL_ADC_CLOCK_SYNC_PCLK_DIV6 + * @arg @ref DDL_ADC_CLOCK_SYNC_PCLK_DIV8 + * @retval None + */ +__STATIC_INLINE void DDL_ADC_SetCommonClock(ADC_Common_TypeDef *ADCxy_COMMON, uint32_t CommonClock) +{ + MODIFY_REG(ADCxy_COMMON->CCTRL, ADC_CCTRL_ADCPRE, CommonClock); +} + +/** + * @brief Get parameter common to several ADC: Clock source and prescaler. + * @param ADCxy_COMMON ADC common instance + * (can be set directly from CMSIS definition or by using helper macro @ref __DDL_ADC_COMMON_INSTANCE() ) + * @retval Returned value can be one of the following values: + * @arg @ref DDL_ADC_CLOCK_SYNC_PCLK_DIV2 + * @arg @ref DDL_ADC_CLOCK_SYNC_PCLK_DIV4 + * @arg @ref DDL_ADC_CLOCK_SYNC_PCLK_DIV6 + * @arg @ref DDL_ADC_CLOCK_SYNC_PCLK_DIV8 + */ +__STATIC_INLINE uint32_t DDL_ADC_GetCommonClock(ADC_Common_TypeDef *ADCxy_COMMON) +{ + return (uint32_t)(READ_BIT(ADCxy_COMMON->CCTRL, ADC_CCTRL_ADCPRE)); +} + +/** + * @brief Set parameter common to several ADC: measurement path to internal + * channels (VrefInt, temperature sensor, ...). + * @note One or several values can be selected. + * Example: (DDL_ADC_PATH_INTERNAL_VREFINT | + * DDL_ADC_PATH_INTERNAL_TEMPSENSOR) + * @note Stabilization time of measurement path to internal channel: + * After enabling internal paths, before starting ADC conversion, + * a delay is required for internal voltage reference and + * temperature sensor stabilization time. + * Refer to device datasheet. + * Refer to literal @ref DDL_ADC_DELAY_VREFINT_STAB_US. + * Refer to literal @ref DDL_ADC_DELAY_TEMPSENSOR_STAB_US. + * @note ADC internal channel sampling time constraint: + * For ADC conversion of internal channels, + * a sampling time minimum value is required. + * Refer to device datasheet. + * @param ADCxy_COMMON ADC common instance + * (can be set directly from CMSIS definition or by using helper macro @ref __DDL_ADC_COMMON_INSTANCE() ) + * @param PathInternal This parameter can be a combination of the following values: + * @arg @ref DDL_ADC_PATH_INTERNAL_NONE + * @arg @ref DDL_ADC_PATH_INTERNAL_VREFINT + * @arg @ref DDL_ADC_PATH_INTERNAL_TEMPSENSOR + * @arg @ref DDL_ADC_PATH_INTERNAL_VBAT + * @retval None + */ +__STATIC_INLINE void DDL_ADC_SetCommonPathInternalCh(ADC_Common_TypeDef *ADCxy_COMMON, uint32_t PathInternal) +{ + MODIFY_REG(ADCxy_COMMON->CCTRL, ADC_CCTRL_TSVREFEN | ADC_CCTRL_VBATEN, PathInternal); +} + +/** + * @brief Get parameter common to several ADC: measurement path to internal + * channels (VrefInt, temperature sensor, ...). + * @note One or several values can be selected. + * Example: (DDL_ADC_PATH_INTERNAL_VREFINT | + * DDL_ADC_PATH_INTERNAL_TEMPSENSOR) + * @param ADCxy_COMMON ADC common instance + * (can be set directly from CMSIS definition or by using helper macro @ref __DDL_ADC_COMMON_INSTANCE() ) + * @retval Returned value can be a combination of the following values: + * @arg @ref DDL_ADC_PATH_INTERNAL_NONE + * @arg @ref DDL_ADC_PATH_INTERNAL_VREFINT + * @arg @ref DDL_ADC_PATH_INTERNAL_TEMPSENSOR + * @arg @ref DDL_ADC_PATH_INTERNAL_VBAT + */ +__STATIC_INLINE uint32_t DDL_ADC_GetCommonPathInternalCh(ADC_Common_TypeDef *ADCxy_COMMON) +{ + return (uint32_t)(READ_BIT(ADCxy_COMMON->CCTRL, ADC_CCTRL_TSVREFEN | ADC_CCTRL_VBATEN)); +} + +/** + * @} + */ + +/** @defgroup ADC_DDL_EF_Configuration_ADC_Instance Configuration of ADC hierarchical scope: ADC instance + * @{ + */ + +/** + * @brief Set ADC resolution. + * Refer to reference manual for alignments formats + * dependencies to ADC resolutions. + * @param ADCx ADC instance + * @param Resolution This parameter can be one of the following values: + * @arg @ref DDL_ADC_RESOLUTION_12B + * @arg @ref DDL_ADC_RESOLUTION_10B + * @arg @ref DDL_ADC_RESOLUTION_8B + * @arg @ref DDL_ADC_RESOLUTION_6B + * @retval None + */ +__STATIC_INLINE void DDL_ADC_SetResolution(ADC_TypeDef *ADCx, uint32_t Resolution) +{ + MODIFY_REG(ADCx->CTRL1, ADC_CTRL1_RESSEL, Resolution); +} + +/** + * @brief Get ADC resolution. + * Refer to reference manual for alignments formats + * dependencies to ADC resolutions. + * @param ADCx ADC instance + * @retval Returned value can be one of the following values: + * @arg @ref DDL_ADC_RESOLUTION_12B + * @arg @ref DDL_ADC_RESOLUTION_10B + * @arg @ref DDL_ADC_RESOLUTION_8B + * @arg @ref DDL_ADC_RESOLUTION_6B + */ +__STATIC_INLINE uint32_t DDL_ADC_GetResolution(ADC_TypeDef *ADCx) +{ + return (uint32_t)(READ_BIT(ADCx->CTRL1, ADC_CTRL1_RESSEL)); +} + +/** + * @brief Set ADC conversion data alignment. + * @note Refer to reference manual for alignments formats + * dependencies to ADC resolutions. + * @param ADCx ADC instance + * @param DataAlignment This parameter can be one of the following values: + * @arg @ref DDL_ADC_DATA_ALIGN_RIGHT + * @arg @ref DDL_ADC_DATA_ALIGN_LEFT + * @retval None + */ +__STATIC_INLINE void DDL_ADC_SetDataAlignment(ADC_TypeDef *ADCx, uint32_t DataAlignment) +{ + MODIFY_REG(ADCx->CTRL2, ADC_CTRL2_DALIGNCFG, DataAlignment); +} + +/** + * @brief Get ADC conversion data alignment. + * @note Refer to reference manual for alignments formats + * dependencies to ADC resolutions. + * @param ADCx ADC instance + * @retval Returned value can be one of the following values: + * @arg @ref DDL_ADC_DATA_ALIGN_RIGHT + * @arg @ref DDL_ADC_DATA_ALIGN_LEFT + */ +__STATIC_INLINE uint32_t DDL_ADC_GetDataAlignment(ADC_TypeDef *ADCx) +{ + return (uint32_t)(READ_BIT(ADCx->CTRL2, ADC_CTRL2_DALIGNCFG)); +} + +/** + * @brief Set ADC sequencers scan mode, for all ADC groups + * (group regular, group injected). + * @note According to sequencers scan mode : + * - If disabled: ADC conversion is performed in unitary conversion + * mode (one channel converted, that defined in rank 1). + * Configuration of sequencers of all ADC groups + * (sequencer scan length, ...) is discarded: equivalent to + * scan length of 1 rank. + * - If enabled: ADC conversions are performed in sequence conversions + * mode, according to configuration of sequencers of + * each ADC group (sequencer scan length, ...). + * Refer to function @ref DDL_ADC_REG_SetSequencerLength() + * and to function @ref DDL_ADC_INJ_SetSequencerLength(). + * @param ADCx ADC instance + * @param ScanMode This parameter can be one of the following values: + * @arg @ref DDL_ADC_SEQ_SCAN_DISABLE + * @arg @ref DDL_ADC_SEQ_SCAN_ENABLE + * @retval None + */ +__STATIC_INLINE void DDL_ADC_SetSequencersScanMode(ADC_TypeDef *ADCx, uint32_t ScanMode) +{ + MODIFY_REG(ADCx->CTRL1, ADC_CTRL1_SCANEN, ScanMode); +} + +/** + * @brief Get ADC sequencers scan mode, for all ADC groups + * (group regular, group injected). + * @note According to sequencers scan mode : + * - If disabled: ADC conversion is performed in unitary conversion + * mode (one channel converted, that defined in rank 1). + * Configuration of sequencers of all ADC groups + * (sequencer scan length, ...) is discarded: equivalent to + * scan length of 1 rank. + * - If enabled: ADC conversions are performed in sequence conversions + * mode, according to configuration of sequencers of + * each ADC group (sequencer scan length, ...). + * Refer to function @ref DDL_ADC_REG_SetSequencerLength() + * and to function @ref DDL_ADC_INJ_SetSequencerLength(). + * @param ADCx ADC instance + * @retval Returned value can be one of the following values: + * @arg @ref DDL_ADC_SEQ_SCAN_DISABLE + * @arg @ref DDL_ADC_SEQ_SCAN_ENABLE + */ +__STATIC_INLINE uint32_t DDL_ADC_GetSequencersScanMode(ADC_TypeDef *ADCx) +{ + return (uint32_t)(READ_BIT(ADCx->CTRL1, ADC_CTRL1_SCANEN)); +} + +/** + * @} + */ + +/** @defgroup ADC_DDL_EF_Configuration_ADC_Group_Regular Configuration of ADC hierarchical scope: group regular + * @{ + */ + +/** + * @brief Set ADC group regular conversion trigger source: + * internal (SW start) or from external IP (timer event, + * external interrupt line). + * @note On this APM32 series, setting of external trigger edge is performed + * using function @ref DDL_ADC_REG_StartConversionExtTrig(). + * @note Availability of parameters of trigger sources from timer + * depends on timers availability on the selected device. + * @param ADCx ADC instance + * @param TriggerSource This parameter can be one of the following values: + * @arg @ref DDL_ADC_REG_TRIG_SOFTWARE + * @arg @ref DDL_ADC_REG_TRIG_EXT_TMR1_CH1 + * @arg @ref DDL_ADC_REG_TRIG_EXT_TMR1_CH2 + * @arg @ref DDL_ADC_REG_TRIG_EXT_TMR1_CH3 + * @arg @ref DDL_ADC_REG_TRIG_EXT_TMR2_CH2 + * @arg @ref DDL_ADC_REG_TRIG_EXT_TMR2_CH3 + * @arg @ref DDL_ADC_REG_TRIG_EXT_TMR2_CH4 + * @arg @ref DDL_ADC_REG_TRIG_EXT_TMR2_TRGO + * @arg @ref DDL_ADC_REG_TRIG_EXT_TMR3_CH1 + * @arg @ref DDL_ADC_REG_TRIG_EXT_TMR3_TRGO + * @arg @ref DDL_ADC_REG_TRIG_EXT_TMR4_CH4 + * @arg @ref DDL_ADC_REG_TRIG_EXT_TMR5_CH1 + * @arg @ref DDL_ADC_REG_TRIG_EXT_TMR5_CH2 + * @arg @ref DDL_ADC_REG_TRIG_EXT_TMR5_CH3 + * @arg @ref DDL_ADC_REG_TRIG_EXT_TMR8_CH1 + * @arg @ref DDL_ADC_REG_TRIG_EXT_TMR8_TRGO + * @arg @ref DDL_ADC_REG_TRIG_EXT_EINT_LINE11 + * @retval None + */ +__STATIC_INLINE void DDL_ADC_REG_SetTriggerSource(ADC_TypeDef *ADCx, uint32_t TriggerSource) +{ +/* Note: On this APM32 series, ADC group regular external trigger edge */ +/* is used to perform a ADC conversion start. */ +/* This function does not set external trigger edge. */ +/* This feature is set using function */ +/* @ref DDL_ADC_REG_StartConversionExtTrig(). */ + MODIFY_REG(ADCx->CTRL2, ADC_CTRL2_REGEXTTRGSEL, (TriggerSource & ADC_CTRL2_REGEXTTRGSEL)); +} + +/** + * @brief Get ADC group regular conversion trigger source: + * internal (SW start) or from external IP (timer event, + * external interrupt line). + * @note To determine whether group regular trigger source is + * internal (SW start) or external, without detail + * of which peripheral is selected as external trigger, + * (equivalent to + * "if(DDL_ADC_REG_GetTriggerSource(ADC1) == DDL_ADC_REG_TRIG_SOFTWARE)") + * use function @ref DDL_ADC_REG_IsTriggerSourceSWStart. + * @note Availability of parameters of trigger sources from timer + * depends on timers availability on the selected device. + * @param ADCx ADC instance + * @retval Returned value can be one of the following values: + * @arg @ref DDL_ADC_REG_TRIG_SOFTWARE + * @arg @ref DDL_ADC_REG_TRIG_EXT_TMR1_CH1 + * @arg @ref DDL_ADC_REG_TRIG_EXT_TMR1_CH2 + * @arg @ref DDL_ADC_REG_TRIG_EXT_TMR1_CH3 + * @arg @ref DDL_ADC_REG_TRIG_EXT_TMR2_CH2 + * @arg @ref DDL_ADC_REG_TRIG_EXT_TMR2_CH3 + * @arg @ref DDL_ADC_REG_TRIG_EXT_TMR2_CH4 + * @arg @ref DDL_ADC_REG_TRIG_EXT_TMR2_TRGO + * @arg @ref DDL_ADC_REG_TRIG_EXT_TMR3_CH1 + * @arg @ref DDL_ADC_REG_TRIG_EXT_TMR3_TRGO + * @arg @ref DDL_ADC_REG_TRIG_EXT_TMR4_CH4 + * @arg @ref DDL_ADC_REG_TRIG_EXT_TMR5_CH1 + * @arg @ref DDL_ADC_REG_TRIG_EXT_TMR5_CH2 + * @arg @ref DDL_ADC_REG_TRIG_EXT_TMR5_CH3 + * @arg @ref DDL_ADC_REG_TRIG_EXT_TMR8_CH1 + * @arg @ref DDL_ADC_REG_TRIG_EXT_TMR8_TRGO + * @arg @ref DDL_ADC_REG_TRIG_EXT_EINT_LINE11 + */ +__STATIC_INLINE uint32_t DDL_ADC_REG_GetTriggerSource(ADC_TypeDef *ADCx) +{ + uint32_t TriggerSource = READ_BIT(ADCx->CTRL2, ADC_CTRL2_REGEXTTRGSEL | ADC_CTRL2_REGEXTTRGEN); + + /* Value for shift of {0; 4; 8; 12} depending on value of bitfield */ + /* corresponding to ADC_CTRL2_REGEXTTRGEN {0; 1; 2; 3}. */ + uint32_t ShiftExten = ((TriggerSource & ADC_CTRL2_REGEXTTRGEN) >> (ADC_REG_TRIG_EXTEN_BITOFFSET_POS - 2UL)); + + /* Set bitfield corresponding to ADC_CTRL2_REGEXTTRGEN and ADC_CTRL2_REGEXTTRGSEL */ + /* to match with triggers literals definition. */ + return ((TriggerSource + & (ADC_REG_TRIG_SOURCE_MASK << ShiftExten) & ADC_CTRL2_REGEXTTRGSEL) + | ((ADC_REG_TRIG_EDGE_MASK << ShiftExten) & ADC_CTRL2_REGEXTTRGEN) + ); +} + +/** + * @brief Get ADC group regular conversion trigger source internal (SW start) + or external. + * @note In case of group regular trigger source set to external trigger, + * to determine which peripheral is selected as external trigger, + * use function @ref DDL_ADC_REG_GetTriggerSource(). + * @param ADCx ADC instance + * @retval Value "0" if trigger source external trigger + * Value "1" if trigger source SW start. + */ +__STATIC_INLINE uint32_t DDL_ADC_REG_IsTriggerSourceSWStart(ADC_TypeDef *ADCx) +{ + return (READ_BIT(ADCx->CTRL2, ADC_CTRL2_REGEXTTRGEN) == (DDL_ADC_REG_TRIG_SOFTWARE & ADC_CTRL2_REGEXTTRGEN)); +} + +/** + * @brief Get ADC group regular conversion trigger polarity. + * @note Applicable only for trigger source set to external trigger. + * @note On this APM32 series, setting of external trigger edge is performed + * using function @ref DDL_ADC_REG_StartConversionExtTrig(). + * @param ADCx ADC instance + * @retval Returned value can be one of the following values: + * @arg @ref DDL_ADC_REG_TRIG_EXT_RISING + * @arg @ref DDL_ADC_REG_TRIG_EXT_FALLING + * @arg @ref DDL_ADC_REG_TRIG_EXT_RISINGFALLING + */ +__STATIC_INLINE uint32_t DDL_ADC_REG_GetTriggerEdge(ADC_TypeDef *ADCx) +{ + return (uint32_t)(READ_BIT(ADCx->CTRL2, ADC_CTRL2_REGEXTTRGEN)); +} + + +/** + * @brief Set ADC group regular sequencer length and scan direction. + * @note Description of ADC group regular sequencer features: + * - For devices with sequencer fully configurable + * (function "DDL_ADC_REG_SetSequencerRanks()" available): + * sequencer length and each rank affectation to a channel + * are configurable. + * This function performs configuration of: + * - Sequence length: Number of ranks in the scan sequence. + * - Sequence direction: Unless specified in parameters, sequencer + * scan direction is forward (from rank 1 to rank n). + * Sequencer ranks are selected using + * function "DDL_ADC_REG_SetSequencerRanks()". + * - For devices with sequencer not fully configurable + * (function "DDL_ADC_REG_SetSequencerChannels()" available): + * sequencer length and each rank affectation to a channel + * are defined by channel number. + * This function performs configuration of: + * - Sequence length: Number of ranks in the scan sequence is + * defined by number of channels set in the sequence, + * rank of each channel is fixed by channel HW number. + * (channel 0 fixed on rank 0, channel 1 fixed on rank1, ...). + * - Sequence direction: Unless specified in parameters, sequencer + * scan direction is forward (from lowest channel number to + * highest channel number). + * Sequencer ranks are selected using + * function "DDL_ADC_REG_SetSequencerChannels()". + * @note On this APM32 series, group regular sequencer configuration + * is conditioned to ADC instance sequencer mode. + * If ADC instance sequencer mode is disabled, sequencers of + * all groups (group regular, group injected) can be configured + * but their execution is disabled (limited to rank 1). + * Refer to function @ref DDL_ADC_SetSequencersScanMode(). + * @note Sequencer disabled is equivalent to sequencer of 1 rank: + * ADC conversion on only 1 channel. + * @param ADCx ADC instance + * @param SequencerNbRanks This parameter can be one of the following values: + * @arg @ref DDL_ADC_REG_SEQ_SCAN_DISABLE + * @arg @ref DDL_ADC_REG_SEQ_SCAN_ENABLE_2RANKS + * @arg @ref DDL_ADC_REG_SEQ_SCAN_ENABLE_3RANKS + * @arg @ref DDL_ADC_REG_SEQ_SCAN_ENABLE_4RANKS + * @arg @ref DDL_ADC_REG_SEQ_SCAN_ENABLE_5RANKS + * @arg @ref DDL_ADC_REG_SEQ_SCAN_ENABLE_6RANKS + * @arg @ref DDL_ADC_REG_SEQ_SCAN_ENABLE_7RANKS + * @arg @ref DDL_ADC_REG_SEQ_SCAN_ENABLE_8RANKS + * @arg @ref DDL_ADC_REG_SEQ_SCAN_ENABLE_9RANKS + * @arg @ref DDL_ADC_REG_SEQ_SCAN_ENABLE_10RANKS + * @arg @ref DDL_ADC_REG_SEQ_SCAN_ENABLE_11RANKS + * @arg @ref DDL_ADC_REG_SEQ_SCAN_ENABLE_12RANKS + * @arg @ref DDL_ADC_REG_SEQ_SCAN_ENABLE_13RANKS + * @arg @ref DDL_ADC_REG_SEQ_SCAN_ENABLE_14RANKS + * @arg @ref DDL_ADC_REG_SEQ_SCAN_ENABLE_15RANKS + * @arg @ref DDL_ADC_REG_SEQ_SCAN_ENABLE_16RANKS + * @retval None + */ +__STATIC_INLINE void DDL_ADC_REG_SetSequencerLength(ADC_TypeDef *ADCx, uint32_t SequencerNbRanks) +{ + MODIFY_REG(ADCx->REGSEQ1, ADC_REGSEQ1_REGSEQLEN, SequencerNbRanks); +} + +/** + * @brief Get ADC group regular sequencer length and scan direction. + * @note Description of ADC group regular sequencer features: + * - For devices with sequencer fully configurable + * (function "DDL_ADC_REG_SetSequencerRanks()" available): + * sequencer length and each rank affectation to a channel + * are configurable. + * This function retrieves: + * - Sequence length: Number of ranks in the scan sequence. + * - Sequence direction: Unless specified in parameters, sequencer + * scan direction is forward (from rank 1 to rank n). + * Sequencer ranks are selected using + * function "DDL_ADC_REG_SetSequencerRanks()". + * - For devices with sequencer not fully configurable + * (function "DDL_ADC_REG_SetSequencerChannels()" available): + * sequencer length and each rank affectation to a channel + * are defined by channel number. + * This function retrieves: + * - Sequence length: Number of ranks in the scan sequence is + * defined by number of channels set in the sequence, + * rank of each channel is fixed by channel HW number. + * (channel 0 fixed on rank 0, channel 1 fixed on rank1, ...). + * - Sequence direction: Unless specified in parameters, sequencer + * scan direction is forward (from lowest channel number to + * highest channel number). + * Sequencer ranks are selected using + * function "DDL_ADC_REG_SetSequencerChannels()". + * @note On this APM32 series, group regular sequencer configuration + * is conditioned to ADC instance sequencer mode. + * If ADC instance sequencer mode is disabled, sequencers of + * all groups (group regular, group injected) can be configured + * but their execution is disabled (limited to rank 1). + * Refer to function @ref DDL_ADC_SetSequencersScanMode(). + * @note Sequencer disabled is equivalent to sequencer of 1 rank: + * ADC conversion on only 1 channel. + * @param ADCx ADC instance + * @retval Returned value can be one of the following values: + * @arg @ref DDL_ADC_REG_SEQ_SCAN_DISABLE + * @arg @ref DDL_ADC_REG_SEQ_SCAN_ENABLE_2RANKS + * @arg @ref DDL_ADC_REG_SEQ_SCAN_ENABLE_3RANKS + * @arg @ref DDL_ADC_REG_SEQ_SCAN_ENABLE_4RANKS + * @arg @ref DDL_ADC_REG_SEQ_SCAN_ENABLE_5RANKS + * @arg @ref DDL_ADC_REG_SEQ_SCAN_ENABLE_6RANKS + * @arg @ref DDL_ADC_REG_SEQ_SCAN_ENABLE_7RANKS + * @arg @ref DDL_ADC_REG_SEQ_SCAN_ENABLE_8RANKS + * @arg @ref DDL_ADC_REG_SEQ_SCAN_ENABLE_9RANKS + * @arg @ref DDL_ADC_REG_SEQ_SCAN_ENABLE_10RANKS + * @arg @ref DDL_ADC_REG_SEQ_SCAN_ENABLE_11RANKS + * @arg @ref DDL_ADC_REG_SEQ_SCAN_ENABLE_12RANKS + * @arg @ref DDL_ADC_REG_SEQ_SCAN_ENABLE_13RANKS + * @arg @ref DDL_ADC_REG_SEQ_SCAN_ENABLE_14RANKS + * @arg @ref DDL_ADC_REG_SEQ_SCAN_ENABLE_15RANKS + * @arg @ref DDL_ADC_REG_SEQ_SCAN_ENABLE_16RANKS + */ +__STATIC_INLINE uint32_t DDL_ADC_REG_GetSequencerLength(ADC_TypeDef *ADCx) +{ + return (uint32_t)(READ_BIT(ADCx->REGSEQ1, ADC_REGSEQ1_REGSEQLEN)); +} + +/** + * @brief Set ADC group regular sequencer discontinuous mode: + * sequence subdivided and scan conversions interrupted every selected + * number of ranks. + * @note It is not possible to enable both ADC group regular + * continuous mode and sequencer discontinuous mode. + * @note It is not possible to enable both ADC auto-injected mode + * and ADC group regular sequencer discontinuous mode. + * @param ADCx ADC instance + * @param SeqDiscont This parameter can be one of the following values: + * @arg @ref DDL_ADC_REG_SEQ_DISCONT_DISABLE + * @arg @ref DDL_ADC_REG_SEQ_DISCONT_1RANK + * @arg @ref DDL_ADC_REG_SEQ_DISCONT_2RANKS + * @arg @ref DDL_ADC_REG_SEQ_DISCONT_3RANKS + * @arg @ref DDL_ADC_REG_SEQ_DISCONT_4RANKS + * @arg @ref DDL_ADC_REG_SEQ_DISCONT_5RANKS + * @arg @ref DDL_ADC_REG_SEQ_DISCONT_6RANKS + * @arg @ref DDL_ADC_REG_SEQ_DISCONT_7RANKS + * @arg @ref DDL_ADC_REG_SEQ_DISCONT_8RANKS + * @retval None + */ +__STATIC_INLINE void DDL_ADC_REG_SetSequencerDiscont(ADC_TypeDef *ADCx, uint32_t SeqDiscont) +{ + MODIFY_REG(ADCx->CTRL1, ADC_CTRL1_REGDISCEN | ADC_CTRL1_DISCNUMCFG, SeqDiscont); +} + +/** + * @brief Get ADC group regular sequencer discontinuous mode: + * sequence subdivided and scan conversions interrupted every selected + * number of ranks. + * @param ADCx ADC instance + * @retval Returned value can be one of the following values: + * @arg @ref DDL_ADC_REG_SEQ_DISCONT_DISABLE + * @arg @ref DDL_ADC_REG_SEQ_DISCONT_1RANK + * @arg @ref DDL_ADC_REG_SEQ_DISCONT_2RANKS + * @arg @ref DDL_ADC_REG_SEQ_DISCONT_3RANKS + * @arg @ref DDL_ADC_REG_SEQ_DISCONT_4RANKS + * @arg @ref DDL_ADC_REG_SEQ_DISCONT_5RANKS + * @arg @ref DDL_ADC_REG_SEQ_DISCONT_6RANKS + * @arg @ref DDL_ADC_REG_SEQ_DISCONT_7RANKS + * @arg @ref DDL_ADC_REG_SEQ_DISCONT_8RANKS + */ +__STATIC_INLINE uint32_t DDL_ADC_REG_GetSequencerDiscont(ADC_TypeDef *ADCx) +{ + return (uint32_t)(READ_BIT(ADCx->CTRL1, ADC_CTRL1_REGDISCEN | ADC_CTRL1_DISCNUMCFG)); +} + +/** + * @brief Set ADC group regular sequence: channel on the selected + * scan sequence rank. + * @note This function performs configuration of: + * - Channels ordering into each rank of scan sequence: + * whatever channel can be placed into whatever rank. + * @note On this APM32 series, ADC group regular sequencer is + * fully configurable: sequencer length and each rank + * affectation to a channel are configurable. + * Refer to description of function @ref DDL_ADC_REG_SetSequencerLength(). + * @note Depending on devices and packages, some channels may not be available. + * Refer to device datasheet for channels availability. + * @note On this APM32 series, to measure internal channels (VrefInt, + * TempSensor, ...), measurement paths to internal channels must be + * enabled separately. + * This can be done using function @ref DDL_ADC_SetCommonPathInternalCh(). + * @param ADCx ADC instance + * @param Rank This parameter can be one of the following values: + * @arg @ref DDL_ADC_REG_RANK_1 + * @arg @ref DDL_ADC_REG_RANK_2 + * @arg @ref DDL_ADC_REG_RANK_3 + * @arg @ref DDL_ADC_REG_RANK_4 + * @arg @ref DDL_ADC_REG_RANK_5 + * @arg @ref DDL_ADC_REG_RANK_6 + * @arg @ref DDL_ADC_REG_RANK_7 + * @arg @ref DDL_ADC_REG_RANK_8 + * @arg @ref DDL_ADC_REG_RANK_9 + * @arg @ref DDL_ADC_REG_RANK_10 + * @arg @ref DDL_ADC_REG_RANK_11 + * @arg @ref DDL_ADC_REG_RANK_12 + * @arg @ref DDL_ADC_REG_RANK_13 + * @arg @ref DDL_ADC_REG_RANK_14 + * @arg @ref DDL_ADC_REG_RANK_15 + * @arg @ref DDL_ADC_REG_RANK_16 + * @param Channel This parameter can be one of the following values: + * @arg @ref DDL_ADC_CHANNEL_0 + * @arg @ref DDL_ADC_CHANNEL_1 + * @arg @ref DDL_ADC_CHANNEL_2 + * @arg @ref DDL_ADC_CHANNEL_3 + * @arg @ref DDL_ADC_CHANNEL_4 + * @arg @ref DDL_ADC_CHANNEL_5 + * @arg @ref DDL_ADC_CHANNEL_6 + * @arg @ref DDL_ADC_CHANNEL_7 + * @arg @ref DDL_ADC_CHANNEL_8 + * @arg @ref DDL_ADC_CHANNEL_9 + * @arg @ref DDL_ADC_CHANNEL_10 + * @arg @ref DDL_ADC_CHANNEL_11 + * @arg @ref DDL_ADC_CHANNEL_12 + * @arg @ref DDL_ADC_CHANNEL_13 + * @arg @ref DDL_ADC_CHANNEL_14 + * @arg @ref DDL_ADC_CHANNEL_15 + * @arg @ref DDL_ADC_CHANNEL_16 + * @arg @ref DDL_ADC_CHANNEL_17 + * @arg @ref DDL_ADC_CHANNEL_18 + * @arg @ref DDL_ADC_CHANNEL_VREFINT (1) + * @arg @ref DDL_ADC_CHANNEL_TEMPSENSOR (1)(2) + * @arg @ref DDL_ADC_CHANNEL_VBAT (1) + * + * (1) On APM32F4, parameter available only on ADC instance: ADC1.\n + * (2) On devices APM32F42x and APM32F43x, limitation: this internal channel is shared between temperature sensor and Vbat, only 1 measurement path must be enabled. + * @retval None + */ +__STATIC_INLINE void DDL_ADC_REG_SetSequencerRanks(ADC_TypeDef *ADCx, uint32_t Rank, uint32_t Channel) +{ + /* Set bits with content of parameter "Channel" with bits position */ + /* in register and register position depending on parameter "Rank". */ + /* Parameters "Rank" and "Channel" are used with masks because containing */ + /* other bits reserved for other purpose. */ + __IO uint32_t *preg = __ADC_PTR_REG_OFFSET(ADCx->REGSEQ1, __ADC_MASK_SHIFT(Rank, ADC_REG_SQRX_REGOFFSET_MASK)); + + MODIFY_REG(*preg, + ADC_CHANNEL_ID_NUMBER_MASK << (Rank & ADC_REG_RANK_ID_SQRX_MASK), + (Channel & ADC_CHANNEL_ID_NUMBER_MASK) << (Rank & ADC_REG_RANK_ID_SQRX_MASK)); +} + +/** + * @brief Get ADC group regular sequence: channel on the selected + * scan sequence rank. + * @note On this APM32 series, ADC group regular sequencer is + * fully configurable: sequencer length and each rank + * affectation to a channel are configurable. + * Refer to description of function @ref DDL_ADC_REG_SetSequencerLength(). + * @note Depending on devices and packages, some channels may not be available. + * Refer to device datasheet for channels availability. + * @note Usage of the returned channel number: + * - To reinject this channel into another function DDL_ADC_xxx: + * the returned channel number is only partly formatted on definition + * of literals DDL_ADC_CHANNEL_x. Therefore, it has to be compared + * with parts of literals DDL_ADC_CHANNEL_x or using + * helper macro @ref __DDL_ADC_CHANNEL_TO_DECIMAL_NB(). + * Then the selected literal DDL_ADC_CHANNEL_x can be used + * as parameter for another function. + * - To get the channel number in decimal format: + * process the returned value with the helper macro + * @ref __DDL_ADC_CHANNEL_TO_DECIMAL_NB(). + * @param ADCx ADC instance + * @param Rank This parameter can be one of the following values: + * @arg @ref DDL_ADC_REG_RANK_1 + * @arg @ref DDL_ADC_REG_RANK_2 + * @arg @ref DDL_ADC_REG_RANK_3 + * @arg @ref DDL_ADC_REG_RANK_4 + * @arg @ref DDL_ADC_REG_RANK_5 + * @arg @ref DDL_ADC_REG_RANK_6 + * @arg @ref DDL_ADC_REG_RANK_7 + * @arg @ref DDL_ADC_REG_RANK_8 + * @arg @ref DDL_ADC_REG_RANK_9 + * @arg @ref DDL_ADC_REG_RANK_10 + * @arg @ref DDL_ADC_REG_RANK_11 + * @arg @ref DDL_ADC_REG_RANK_12 + * @arg @ref DDL_ADC_REG_RANK_13 + * @arg @ref DDL_ADC_REG_RANK_14 + * @arg @ref DDL_ADC_REG_RANK_15 + * @arg @ref DDL_ADC_REG_RANK_16 + * @retval Returned value can be one of the following values: + * @arg @ref DDL_ADC_CHANNEL_0 + * @arg @ref DDL_ADC_CHANNEL_1 + * @arg @ref DDL_ADC_CHANNEL_2 + * @arg @ref DDL_ADC_CHANNEL_3 + * @arg @ref DDL_ADC_CHANNEL_4 + * @arg @ref DDL_ADC_CHANNEL_5 + * @arg @ref DDL_ADC_CHANNEL_6 + * @arg @ref DDL_ADC_CHANNEL_7 + * @arg @ref DDL_ADC_CHANNEL_8 + * @arg @ref DDL_ADC_CHANNEL_9 + * @arg @ref DDL_ADC_CHANNEL_10 + * @arg @ref DDL_ADC_CHANNEL_11 + * @arg @ref DDL_ADC_CHANNEL_12 + * @arg @ref DDL_ADC_CHANNEL_13 + * @arg @ref DDL_ADC_CHANNEL_14 + * @arg @ref DDL_ADC_CHANNEL_15 + * @arg @ref DDL_ADC_CHANNEL_16 + * @arg @ref DDL_ADC_CHANNEL_17 + * @arg @ref DDL_ADC_CHANNEL_18 + * @arg @ref DDL_ADC_CHANNEL_VREFINT (1) + * @arg @ref DDL_ADC_CHANNEL_TEMPSENSOR (1)(2) + * @arg @ref DDL_ADC_CHANNEL_VBAT (1) + * + * (1) On APM32F4, parameter available only on ADC instance: ADC1.\n + * (2) On devices APM32F42x and APM32F43x, limitation: this internal channel is shared between temperature sensor and Vbat, only 1 measurement path must be enabled.\n + * (1) For ADC channel read back from ADC register, + * comparison with internal channel parameter to be done + * using helper macro @ref __DDL_ADC_CHANNEL_INTERNAL_TO_EXTERNAL(). + */ +__STATIC_INLINE uint32_t DDL_ADC_REG_GetSequencerRanks(ADC_TypeDef *ADCx, uint32_t Rank) +{ + __IO uint32_t *preg = __ADC_PTR_REG_OFFSET(ADCx->REGSEQ1, __ADC_MASK_SHIFT(Rank, ADC_REG_SQRX_REGOFFSET_MASK)); + + return (uint32_t) (READ_BIT(*preg, + ADC_CHANNEL_ID_NUMBER_MASK << (Rank & ADC_REG_RANK_ID_SQRX_MASK)) + >> (Rank & ADC_REG_RANK_ID_SQRX_MASK) + ); +} + +/** + * @brief Set ADC continuous conversion mode on ADC group regular. + * @note Description of ADC continuous conversion mode: + * - single mode: one conversion per trigger + * - continuous mode: after the first trigger, following + * conversions launched successively automatically. + * @note It is not possible to enable both ADC group regular + * continuous mode and sequencer discontinuous mode. + * @param ADCx ADC instance + * @param Continuous This parameter can be one of the following values: + * @arg @ref DDL_ADC_REG_CONV_SINGLE + * @arg @ref DDL_ADC_REG_CONV_CONTINUOUS + * @retval None + */ +__STATIC_INLINE void DDL_ADC_REG_SetContinuousMode(ADC_TypeDef *ADCx, uint32_t Continuous) +{ + MODIFY_REG(ADCx->CTRL2, ADC_CTRL2_CONTCEN, Continuous); +} + +/** + * @brief Get ADC continuous conversion mode on ADC group regular. + * @note Description of ADC continuous conversion mode: + * - single mode: one conversion per trigger + * - continuous mode: after the first trigger, following + * conversions launched successively automatically. + * @param ADCx ADC instance + * @retval Returned value can be one of the following values: + * @arg @ref DDL_ADC_REG_CONV_SINGLE + * @arg @ref DDL_ADC_REG_CONV_CONTINUOUS + */ +__STATIC_INLINE uint32_t DDL_ADC_REG_GetContinuousMode(ADC_TypeDef *ADCx) +{ + return (uint32_t)(READ_BIT(ADCx->CTRL2, ADC_CTRL2_CONTCEN)); +} + +/** + * @brief Set ADC group regular conversion data transfer: no transfer or + * transfer by DMA, and DMA requests mode. + * @note If transfer by DMA selected, specifies the DMA requests + * mode: + * - Limited mode (One shot mode): DMA transfer requests are stopped + * when number of DMA data transfers (number of + * ADC conversions) is reached. + * This ADC mode is intended to be used with DMA mode non-circular. + * - Unlimited mode: DMA transfer requests are unlimited, + * whatever number of DMA data transfers (number of + * ADC conversions). + * This ADC mode is intended to be used with DMA mode circular. + * @note If ADC DMA requests mode is set to unlimited and DMA is set to + * mode non-circular: + * when DMA transfers size will be reached, DMA will stop transfers of + * ADC conversions data ADC will raise an overrun error + * (overrun flag and interruption if enabled). + * @note For devices with several ADC instances: ADC multimode DMA + * settings are available using function @ref DDL_ADC_SetMultiDMATransfer(). + * @note To configure DMA source address (peripheral address), + * use function @ref DDL_ADC_DMA_GetRegAddr(). + * @param ADCx ADC instance + * @param DMATransfer This parameter can be one of the following values: + * @arg @ref DDL_ADC_REG_DMA_TRANSFER_NONE + * @arg @ref DDL_ADC_REG_DMA_TRANSFER_LIMITED + * @arg @ref DDL_ADC_REG_DMA_TRANSFER_UNLIMITED + * @retval None + */ +__STATIC_INLINE void DDL_ADC_REG_SetDMATransfer(ADC_TypeDef *ADCx, uint32_t DMATransfer) +{ + MODIFY_REG(ADCx->CTRL2, ADC_CTRL2_DMAEN | ADC_CTRL2_DMADISSEL, DMATransfer); +} + +/** + * @brief Get ADC group regular conversion data transfer: no transfer or + * transfer by DMA, and DMA requests mode. + * @note If transfer by DMA selected, specifies the DMA requests + * mode: + * - Limited mode (One shot mode): DMA transfer requests are stopped + * when number of DMA data transfers (number of + * ADC conversions) is reached. + * This ADC mode is intended to be used with DMA mode non-circular. + * - Unlimited mode: DMA transfer requests are unlimited, + * whatever number of DMA data transfers (number of + * ADC conversions). + * This ADC mode is intended to be used with DMA mode circular. + * @note If ADC DMA requests mode is set to unlimited and DMA is set to + * mode non-circular: + * when DMA transfers size will be reached, DMA will stop transfers of + * ADC conversions data ADC will raise an overrun error + * (overrun flag and interruption if enabled). + * @note For devices with several ADC instances: ADC multimode DMA + * settings are available using function @ref DDL_ADC_GetMultiDMATransfer(). + * @note To configure DMA source address (peripheral address), + * use function @ref DDL_ADC_DMA_GetRegAddr(). + * @param ADCx ADC instance + * @retval Returned value can be one of the following values: + * @arg @ref DDL_ADC_REG_DMA_TRANSFER_NONE + * @arg @ref DDL_ADC_REG_DMA_TRANSFER_LIMITED + * @arg @ref DDL_ADC_REG_DMA_TRANSFER_UNLIMITED + */ +__STATIC_INLINE uint32_t DDL_ADC_REG_GetDMATransfer(ADC_TypeDef *ADCx) +{ + return (uint32_t)(READ_BIT(ADCx->CTRL2, ADC_CTRL2_DMAEN | ADC_CTRL2_DMADISSEL)); +} + +/** + * @brief Specify which ADC flag between EOC (end of unitary conversion) + * or EOS (end of sequence conversions) is used to indicate + * the end of conversion. + * @note This feature is aimed to be set when using ADC with + * programming model by polling or interruption + * (programming model by DMA usually uses DMA interruptions + * to indicate end of conversion and data transfer). + * @note For ADC group injected, end of conversion (flag&IT) is raised + * only at the end of the sequence. + * @param ADCx ADC instance + * @param EocSelection This parameter can be one of the following values: + * @arg @ref DDL_ADC_REG_FLAG_EOC_SEQUENCE_CONV + * @arg @ref DDL_ADC_REG_FLAG_EOC_UNITARY_CONV + * @retval None + */ +__STATIC_INLINE void DDL_ADC_REG_SetFlagEndOfConversion(ADC_TypeDef *ADCx, uint32_t EocSelection) +{ + MODIFY_REG(ADCx->CTRL2, ADC_CTRL2_EOCSEL, EocSelection); +} + +/** + * @brief Get which ADC flag between EOC (end of unitary conversion) + * or EOS (end of sequence conversions) is used to indicate + * the end of conversion. + * @param ADCx ADC instance + * @retval Returned value can be one of the following values: + * @arg @ref DDL_ADC_REG_FLAG_EOC_SEQUENCE_CONV + * @arg @ref DDL_ADC_REG_FLAG_EOC_UNITARY_CONV + */ +__STATIC_INLINE uint32_t DDL_ADC_REG_GetFlagEndOfConversion(ADC_TypeDef *ADCx) +{ + return (uint32_t)(READ_BIT(ADCx->CTRL2, ADC_CTRL2_EOCSEL)); +} + +/** + * @} + */ + +/** @defgroup ADC_DDL_EF_Configuration_ADC_Group_Injected Configuration of ADC hierarchical scope: group injected + * @{ + */ + +/** + * @brief Set ADC group injected conversion trigger source: + * internal (SW start) or from external IP (timer event, + * external interrupt line). + * @note On this APM32 series, setting of external trigger edge is performed + * using function @ref DDL_ADC_INJ_StartConversionExtTrig(). + * @note Availability of parameters of trigger sources from timer + * depends on timers availability on the selected device. + * @param ADCx ADC instance + * @param TriggerSource This parameter can be one of the following values: + * @arg @ref DDL_ADC_INJ_TRIG_SOFTWARE + * @arg @ref DDL_ADC_INJ_TRIG_EXT_TMR1_CH4 + * @arg @ref DDL_ADC_INJ_TRIG_EXT_TMR1_TRGO + * @arg @ref DDL_ADC_INJ_TRIG_EXT_TMR2_CH1 + * @arg @ref DDL_ADC_INJ_TRIG_EXT_TMR2_TRGO + * @arg @ref DDL_ADC_INJ_TRIG_EXT_TMR3_CH2 + * @arg @ref DDL_ADC_INJ_TRIG_EXT_TMR3_CH4 + * @arg @ref DDL_ADC_INJ_TRIG_EXT_TMR4_CH1 + * @arg @ref DDL_ADC_INJ_TRIG_EXT_TMR4_CH2 + * @arg @ref DDL_ADC_INJ_TRIG_EXT_TMR4_CH3 + * @arg @ref DDL_ADC_INJ_TRIG_EXT_TMR4_TRGO + * @arg @ref DDL_ADC_INJ_TRIG_EXT_TMR5_CH4 + * @arg @ref DDL_ADC_INJ_TRIG_EXT_TMR5_TRGO + * @arg @ref DDL_ADC_INJ_TRIG_EXT_TMR8_CH2 + * @arg @ref DDL_ADC_INJ_TRIG_EXT_TMR8_CH3 + * @arg @ref DDL_ADC_INJ_TRIG_EXT_TMR8_CH4 + * @arg @ref DDL_ADC_INJ_TRIG_EXT_EXTI_LINE15 + * @retval None + */ +__STATIC_INLINE void DDL_ADC_INJ_SetTriggerSource(ADC_TypeDef *ADCx, uint32_t TriggerSource) +{ +/* Note: On this APM32 series, ADC group injected external trigger edge */ +/* is used to perform a ADC conversion start. */ +/* This function does not set external trigger edge. */ +/* This feature is set using function */ +/* @ref DDL_ADC_INJ_StartConversionExtTrig(). */ + MODIFY_REG(ADCx->CTRL2, ADC_CTRL2_INJGEXTTRGSEL, (TriggerSource & ADC_CTRL2_INJGEXTTRGSEL)); +} + +/** + * @brief Get ADC group injected conversion trigger source: + * internal (SW start) or from external IP (timer event, + * external interrupt line). + * @note To determine whether group injected trigger source is + * internal (SW start) or external, without detail + * of which peripheral is selected as external trigger, + * (equivalent to + * "if(DDL_ADC_INJ_GetTriggerSource(ADC1) == DDL_ADC_INJ_TRIG_SOFTWARE)") + * use function @ref DDL_ADC_INJ_IsTriggerSourceSWStart. + * @note Availability of parameters of trigger sources from timer + * depends on timers availability on the selected device. + * @param ADCx ADC instance + * @retval Returned value can be one of the following values: + * @arg @ref DDL_ADC_INJ_TRIG_SOFTWARE + * @arg @ref DDL_ADC_INJ_TRIG_EXT_TMR1_CH4 + * @arg @ref DDL_ADC_INJ_TRIG_EXT_TMR1_TRGO + * @arg @ref DDL_ADC_INJ_TRIG_EXT_TMR2_CH1 + * @arg @ref DDL_ADC_INJ_TRIG_EXT_TMR2_TRGO + * @arg @ref DDL_ADC_INJ_TRIG_EXT_TMR3_CH2 + * @arg @ref DDL_ADC_INJ_TRIG_EXT_TMR3_CH4 + * @arg @ref DDL_ADC_INJ_TRIG_EXT_TMR4_CH1 + * @arg @ref DDL_ADC_INJ_TRIG_EXT_TMR4_CH2 + * @arg @ref DDL_ADC_INJ_TRIG_EXT_TMR4_CH3 + * @arg @ref DDL_ADC_INJ_TRIG_EXT_TMR4_TRGO + * @arg @ref DDL_ADC_INJ_TRIG_EXT_TMR5_CH4 + * @arg @ref DDL_ADC_INJ_TRIG_EXT_TMR5_TRGO + * @arg @ref DDL_ADC_INJ_TRIG_EXT_TMR8_CH2 + * @arg @ref DDL_ADC_INJ_TRIG_EXT_TMR8_CH3 + * @arg @ref DDL_ADC_INJ_TRIG_EXT_TMR8_CH4 + * @arg @ref DDL_ADC_INJ_TRIG_EXT_EXTI_LINE15 + */ +__STATIC_INLINE uint32_t DDL_ADC_INJ_GetTriggerSource(ADC_TypeDef *ADCx) +{ + uint32_t TriggerSource = READ_BIT(ADCx->CTRL2, ADC_CTRL2_INJGEXTTRGSEL | ADC_CTRL2_INJEXTTRGEN); + + /* Value for shift of {0; 4; 8; 12} depending on value of bitfield */ + /* corresponding to ADC_CTRL2_INJEXTTRGEN {0; 1; 2; 3}. */ + uint32_t ShiftExten = ((TriggerSource & ADC_CTRL2_INJEXTTRGEN) >> (ADC_INJ_TRIG_EXTEN_BITOFFSET_POS - 2UL)); + + /* Set bitfield corresponding to ADC_CTRL2_INJEXTTRGEN and ADC_CTRL2_INJGEXTTRGSEL */ + /* to match with triggers literals definition. */ + return ((TriggerSource + & (ADC_INJ_TRIG_SOURCE_MASK << ShiftExten) & ADC_CTRL2_INJGEXTTRGSEL) + | ((ADC_INJ_TRIG_EDGE_MASK << ShiftExten) & ADC_CTRL2_INJEXTTRGEN) + ); +} + +/** + * @brief Get ADC group injected conversion trigger source internal (SW start) + or external + * @note In case of group injected trigger source set to external trigger, + * to determine which peripheral is selected as external trigger, + * use function @ref DDL_ADC_INJ_GetTriggerSource. + * @param ADCx ADC instance + * @retval Value "0" if trigger source external trigger + * Value "1" if trigger source SW start. + */ +__STATIC_INLINE uint32_t DDL_ADC_INJ_IsTriggerSourceSWStart(ADC_TypeDef *ADCx) +{ + return (READ_BIT(ADCx->CTRL2, ADC_CTRL2_INJEXTTRGEN) == (DDL_ADC_INJ_TRIG_SOFTWARE & ADC_CTRL2_INJEXTTRGEN)); +} + +/** + * @brief Get ADC group injected conversion trigger polarity. + * Applicable only for trigger source set to external trigger. + * @param ADCx ADC instance + * @retval Returned value can be one of the following values: + * @arg @ref DDL_ADC_INJ_TRIG_EXT_RISING + * @arg @ref DDL_ADC_INJ_TRIG_EXT_FALLING + * @arg @ref DDL_ADC_INJ_TRIG_EXT_RISINGFALLING + */ +__STATIC_INLINE uint32_t DDL_ADC_INJ_GetTriggerEdge(ADC_TypeDef *ADCx) +{ + return (uint32_t)(READ_BIT(ADCx->CTRL2, ADC_CTRL2_INJEXTTRGEN)); +} + +/** + * @brief Set ADC group injected sequencer length and scan direction. + * @note This function performs configuration of: + * - Sequence length: Number of ranks in the scan sequence. + * - Sequence direction: Unless specified in parameters, sequencer + * scan direction is forward (from rank 1 to rank n). + * @note On this APM32 series, group injected sequencer configuration + * is conditioned to ADC instance sequencer mode. + * If ADC instance sequencer mode is disabled, sequencers of + * all groups (group regular, group injected) can be configured + * but their execution is disabled (limited to rank 1). + * Refer to function @ref DDL_ADC_SetSequencersScanMode(). + * @note Sequencer disabled is equivalent to sequencer of 1 rank: + * ADC conversion on only 1 channel. + * @param ADCx ADC instance + * @param SequencerNbRanks This parameter can be one of the following values: + * @arg @ref DDL_ADC_INJ_SEQ_SCAN_DISABLE + * @arg @ref DDL_ADC_INJ_SEQ_SCAN_ENABLE_2RANKS + * @arg @ref DDL_ADC_INJ_SEQ_SCAN_ENABLE_3RANKS + * @arg @ref DDL_ADC_INJ_SEQ_SCAN_ENABLE_4RANKS + * @retval None + */ +__STATIC_INLINE void DDL_ADC_INJ_SetSequencerLength(ADC_TypeDef *ADCx, uint32_t SequencerNbRanks) +{ + MODIFY_REG(ADCx->INJSEQ, ADC_INJSEQ_INJSEQLEN, SequencerNbRanks); +} + +/** + * @brief Get ADC group injected sequencer length and scan direction. + * @note This function retrieves: + * - Sequence length: Number of ranks in the scan sequence. + * - Sequence direction: Unless specified in parameters, sequencer + * scan direction is forward (from rank 1 to rank n). + * @note On this APM32 series, group injected sequencer configuration + * is conditioned to ADC instance sequencer mode. + * If ADC instance sequencer mode is disabled, sequencers of + * all groups (group regular, group injected) can be configured + * but their execution is disabled (limited to rank 1). + * Refer to function @ref DDL_ADC_SetSequencersScanMode(). + * @note Sequencer disabled is equivalent to sequencer of 1 rank: + * ADC conversion on only 1 channel. + * @param ADCx ADC instance + * @retval Returned value can be one of the following values: + * @arg @ref DDL_ADC_INJ_SEQ_SCAN_DISABLE + * @arg @ref DDL_ADC_INJ_SEQ_SCAN_ENABLE_2RANKS + * @arg @ref DDL_ADC_INJ_SEQ_SCAN_ENABLE_3RANKS + * @arg @ref DDL_ADC_INJ_SEQ_SCAN_ENABLE_4RANKS + */ +__STATIC_INLINE uint32_t DDL_ADC_INJ_GetSequencerLength(ADC_TypeDef *ADCx) +{ + return (uint32_t)(READ_BIT(ADCx->INJSEQ, ADC_INJSEQ_INJSEQLEN)); +} + +/** + * @brief Set ADC group injected sequencer discontinuous mode: + * sequence subdivided and scan conversions interrupted every selected + * number of ranks. + * @note It is not possible to enable both ADC group injected + * auto-injected mode and sequencer discontinuous mode. + * @param ADCx ADC instance + * @param SeqDiscont This parameter can be one of the following values: + * @arg @ref DDL_ADC_INJ_SEQ_DISCONT_DISABLE + * @arg @ref DDL_ADC_INJ_SEQ_DISCONT_1RANK + * @retval None + */ +__STATIC_INLINE void DDL_ADC_INJ_SetSequencerDiscont(ADC_TypeDef *ADCx, uint32_t SeqDiscont) +{ + MODIFY_REG(ADCx->CTRL1, ADC_CTRL1_INJDISCEN, SeqDiscont); +} + +/** + * @brief Get ADC group injected sequencer discontinuous mode: + * sequence subdivided and scan conversions interrupted every selected + * number of ranks. + * @param ADCx ADC instance + * @retval Returned value can be one of the following values: + * @arg @ref DDL_ADC_INJ_SEQ_DISCONT_DISABLE + * @arg @ref DDL_ADC_INJ_SEQ_DISCONT_1RANK + */ +__STATIC_INLINE uint32_t DDL_ADC_INJ_GetSequencerDiscont(ADC_TypeDef *ADCx) +{ + return (uint32_t)(READ_BIT(ADCx->CTRL1, ADC_CTRL1_INJDISCEN)); +} + +/** + * @brief Set ADC group injected sequence: channel on the selected + * sequence rank. + * @note Depending on devices and packages, some channels may not be available. + * Refer to device datasheet for channels availability. + * @note On this APM32 series, to measure internal channels (VrefInt, + * TempSensor, ...), measurement paths to internal channels must be + * enabled separately. + * This can be done using function @ref DDL_ADC_SetCommonPathInternalCh(). + * @param ADCx ADC instance + * @param Rank This parameter can be one of the following values: + * @arg @ref DDL_ADC_INJ_RANK_1 + * @arg @ref DDL_ADC_INJ_RANK_2 + * @arg @ref DDL_ADC_INJ_RANK_3 + * @arg @ref DDL_ADC_INJ_RANK_4 + * @param Channel This parameter can be one of the following values: + * @arg @ref DDL_ADC_CHANNEL_0 + * @arg @ref DDL_ADC_CHANNEL_1 + * @arg @ref DDL_ADC_CHANNEL_2 + * @arg @ref DDL_ADC_CHANNEL_3 + * @arg @ref DDL_ADC_CHANNEL_4 + * @arg @ref DDL_ADC_CHANNEL_5 + * @arg @ref DDL_ADC_CHANNEL_6 + * @arg @ref DDL_ADC_CHANNEL_7 + * @arg @ref DDL_ADC_CHANNEL_8 + * @arg @ref DDL_ADC_CHANNEL_9 + * @arg @ref DDL_ADC_CHANNEL_10 + * @arg @ref DDL_ADC_CHANNEL_11 + * @arg @ref DDL_ADC_CHANNEL_12 + * @arg @ref DDL_ADC_CHANNEL_13 + * @arg @ref DDL_ADC_CHANNEL_14 + * @arg @ref DDL_ADC_CHANNEL_15 + * @arg @ref DDL_ADC_CHANNEL_16 + * @arg @ref DDL_ADC_CHANNEL_17 + * @arg @ref DDL_ADC_CHANNEL_18 + * @arg @ref DDL_ADC_CHANNEL_VREFINT (1) + * @arg @ref DDL_ADC_CHANNEL_TEMPSENSOR (1)(2) + * @arg @ref DDL_ADC_CHANNEL_VBAT (1) + * + * (1) On APM32F4, parameter available only on ADC instance: ADC1.\n + * @retval None + */ +__STATIC_INLINE void DDL_ADC_INJ_SetSequencerRanks(ADC_TypeDef *ADCx, uint32_t Rank, uint32_t Channel) +{ + /* Set bits with content of parameter "Channel" with bits position */ + /* in register depending on parameter "Rank". */ + /* Parameters "Rank" and "Channel" are used with masks because containing */ + /* other bits reserved for other purpose. */ + uint32_t tmpreg1 = (READ_BIT(ADCx->INJSEQ, ADC_INJSEQ_INJSEQLEN) >> ADC_INJSEQ_INJSEQLEN_Pos) + 1UL; + + MODIFY_REG(ADCx->INJSEQ, + ADC_CHANNEL_ID_NUMBER_MASK << (5UL * (uint8_t)(((Rank) + 3UL) - (tmpreg1))), + (Channel & ADC_CHANNEL_ID_NUMBER_MASK) << (5UL * (uint8_t)(((Rank) + 3UL) - (tmpreg1)))); +} + +/** + * @brief Get ADC group injected sequence: channel on the selected + * sequence rank. + * @note Depending on devices and packages, some channels may not be available. + * Refer to device datasheet for channels availability. + * @note Usage of the returned channel number: + * - To reinject this channel into another function DDL_ADC_xxx: + * the returned channel number is only partly formatted on definition + * of literals DDL_ADC_CHANNEL_x. Therefore, it has to be compared + * with parts of literals DDL_ADC_CHANNEL_x or using + * helper macro @ref __DDL_ADC_CHANNEL_TO_DECIMAL_NB(). + * Then the selected literal DDL_ADC_CHANNEL_x can be used + * as parameter for another function. + * - To get the channel number in decimal format: + * process the returned value with the helper macro + * @ref __DDL_ADC_CHANNEL_TO_DECIMAL_NB(). + * @param ADCx ADC instance + * @param Rank This parameter can be one of the following values: + * @arg @ref DDL_ADC_INJ_RANK_1 + * @arg @ref DDL_ADC_INJ_RANK_2 + * @arg @ref DDL_ADC_INJ_RANK_3 + * @arg @ref DDL_ADC_INJ_RANK_4 + * @retval Returned value can be one of the following values: + * @arg @ref DDL_ADC_CHANNEL_0 + * @arg @ref DDL_ADC_CHANNEL_1 + * @arg @ref DDL_ADC_CHANNEL_2 + * @arg @ref DDL_ADC_CHANNEL_3 + * @arg @ref DDL_ADC_CHANNEL_4 + * @arg @ref DDL_ADC_CHANNEL_5 + * @arg @ref DDL_ADC_CHANNEL_6 + * @arg @ref DDL_ADC_CHANNEL_7 + * @arg @ref DDL_ADC_CHANNEL_8 + * @arg @ref DDL_ADC_CHANNEL_9 + * @arg @ref DDL_ADC_CHANNEL_10 + * @arg @ref DDL_ADC_CHANNEL_11 + * @arg @ref DDL_ADC_CHANNEL_12 + * @arg @ref DDL_ADC_CHANNEL_13 + * @arg @ref DDL_ADC_CHANNEL_14 + * @arg @ref DDL_ADC_CHANNEL_15 + * @arg @ref DDL_ADC_CHANNEL_16 + * @arg @ref DDL_ADC_CHANNEL_17 + * @arg @ref DDL_ADC_CHANNEL_18 + * @arg @ref DDL_ADC_CHANNEL_VREFINT (1) + * @arg @ref DDL_ADC_CHANNEL_TEMPSENSOR (1)(2) + * @arg @ref DDL_ADC_CHANNEL_VBAT (1) + * + * (1) On APM32F4, parameter available only on ADC instance: ADC1.\n + * (2) On devices APM32F42x and APM32F43x, limitation: this internal channel is shared between temperature sensor and Vbat, only 1 measurement path must be enabled.\n + * (1) For ADC channel read back from ADC register, + * comparison with internal channel parameter to be done + * using helper macro @ref __DDL_ADC_CHANNEL_INTERNAL_TO_EXTERNAL(). + */ +__STATIC_INLINE uint32_t DDL_ADC_INJ_GetSequencerRanks(ADC_TypeDef *ADCx, uint32_t Rank) +{ + uint32_t tmpreg1 = (READ_BIT(ADCx->INJSEQ, ADC_INJSEQ_INJSEQLEN) >> ADC_INJSEQ_INJSEQLEN_Pos) + 1UL; + + return (uint32_t)(READ_BIT(ADCx->INJSEQ, + ADC_CHANNEL_ID_NUMBER_MASK << (5UL * (uint8_t)(((Rank) + 3UL) - (tmpreg1)))) + >> (5UL * (uint8_t)(((Rank) + 3UL) - (tmpreg1))) + ); +} + +/** + * @brief Set ADC group injected conversion trigger: + * independent or from ADC group regular. + * @note This mode can be used to extend number of data registers + * updated after one ADC conversion trigger and with data + * permanently kept (not erased by successive conversions of scan of + * ADC sequencer ranks), up to 5 data registers: + * 1 data register on ADC group regular, 4 data registers + * on ADC group injected. + * @note If ADC group injected injected trigger source is set to an + * external trigger, this feature must be must be set to + * independent trigger. + * ADC group injected automatic trigger is compliant only with + * group injected trigger source set to SW start, without any + * further action on ADC group injected conversion start or stop: + * in this case, ADC group injected is controlled only + * from ADC group regular. + * @note It is not possible to enable both ADC group injected + * auto-injected mode and sequencer discontinuous mode. + * @param ADCx ADC instance + * @param TrigAuto This parameter can be one of the following values: + * @arg @ref DDL_ADC_INJ_TRIG_INDEPENDENT + * @arg @ref DDL_ADC_INJ_TRIG_FROM_GRP_REGULAR + * @retval None + */ +__STATIC_INLINE void DDL_ADC_INJ_SetTrigAuto(ADC_TypeDef *ADCx, uint32_t TrigAuto) +{ + MODIFY_REG(ADCx->CTRL1, ADC_CTRL1_INJGACEN, TrigAuto); +} + +/** + * @brief Get ADC group injected conversion trigger: + * independent or from ADC group regular. + * @param ADCx ADC instance + * @retval Returned value can be one of the following values: + * @arg @ref DDL_ADC_INJ_TRIG_INDEPENDENT + * @arg @ref DDL_ADC_INJ_TRIG_FROM_GRP_REGULAR + */ +__STATIC_INLINE uint32_t DDL_ADC_INJ_GetTrigAuto(ADC_TypeDef *ADCx) +{ + return (uint32_t)(READ_BIT(ADCx->CTRL1, ADC_CTRL1_INJGACEN)); +} + +/** + * @brief Set ADC group injected offset. + * @note It sets: + * - ADC group injected rank to which the offset programmed + * will be applied + * - Offset level (offset to be subtracted from the raw + * converted data). + * Caution: Offset format is dependent to ADC resolution: + * offset has to be left-aligned on bit 11, the LSB (right bits) + * are set to 0. + * @note Offset cannot be enabled or disabled. + * To emulate offset disabled, set an offset value equal to 0. + * @param ADCx ADC instance + * @param Rank This parameter can be one of the following values: + * @arg @ref DDL_ADC_INJ_RANK_1 + * @arg @ref DDL_ADC_INJ_RANK_2 + * @arg @ref DDL_ADC_INJ_RANK_3 + * @arg @ref DDL_ADC_INJ_RANK_4 + * @param OffsetLevel Value between Min_Data=0x000 and Max_Data=0xFFF + * @retval None + */ +__STATIC_INLINE void DDL_ADC_INJ_SetOffset(ADC_TypeDef *ADCx, uint32_t Rank, uint32_t OffsetLevel) +{ + __IO uint32_t *preg = __ADC_PTR_REG_OFFSET(ADCx->INJDOF1, __ADC_MASK_SHIFT(Rank, ADC_INJ_JOFRX_REGOFFSET_MASK)); + + MODIFY_REG(*preg, + ADC_INJDOF1_INJDOF1, + OffsetLevel); +} + +/** + * @brief Get ADC group injected offset. + * @note It gives offset level (offset to be subtracted from the raw converted data). + * Caution: Offset format is dependent to ADC resolution: + * offset has to be left-aligned on bit 11, the LSB (right bits) + * are set to 0. + * @param ADCx ADC instance + * @param Rank This parameter can be one of the following values: + * @arg @ref DDL_ADC_INJ_RANK_1 + * @arg @ref DDL_ADC_INJ_RANK_2 + * @arg @ref DDL_ADC_INJ_RANK_3 + * @arg @ref DDL_ADC_INJ_RANK_4 + * @retval Value between Min_Data=0x000 and Max_Data=0xFFF + */ +__STATIC_INLINE uint32_t DDL_ADC_INJ_GetOffset(ADC_TypeDef *ADCx, uint32_t Rank) +{ + __IO uint32_t *preg = __ADC_PTR_REG_OFFSET(ADCx->INJDOF1, __ADC_MASK_SHIFT(Rank, ADC_INJ_JOFRX_REGOFFSET_MASK)); + + return (uint32_t)(READ_BIT(*preg, + ADC_INJDOF1_INJDOF1) + ); +} + +/** + * @} + */ + +/** @defgroup ADC_DDL_EF_Configuration_Channels Configuration of ADC hierarchical scope: channels + * @{ + */ + +/** + * @brief Set sampling time of the selected ADC channel + * Unit: ADC clock cycles. + * @note On this device, sampling time is on channel scope: independently + * of channel mapped on ADC group regular or injected. + * @note In case of internal channel (VrefInt, TempSensor, ...) to be + * converted: + * sampling time constraints must be respected (sampling time can be + * adjusted in function of ADC clock frequency and sampling time + * setting). + * Refer to device datasheet for timings values (parameters TS_vrefint, + * TS_temp, ...). + * @note Conversion time is the addition of sampling time and processing time. + * Refer to reference manual for ADC processing time of + * this APM32 series. + * @note In case of ADC conversion of internal channel (VrefInt, + * temperature sensor, ...), a sampling time minimum value + * is required. + * Refer to device datasheet. + * @param ADCx ADC instance + * @param Channel This parameter can be one of the following values: + * @arg @ref DDL_ADC_CHANNEL_0 + * @arg @ref DDL_ADC_CHANNEL_1 + * @arg @ref DDL_ADC_CHANNEL_2 + * @arg @ref DDL_ADC_CHANNEL_3 + * @arg @ref DDL_ADC_CHANNEL_4 + * @arg @ref DDL_ADC_CHANNEL_5 + * @arg @ref DDL_ADC_CHANNEL_6 + * @arg @ref DDL_ADC_CHANNEL_7 + * @arg @ref DDL_ADC_CHANNEL_8 + * @arg @ref DDL_ADC_CHANNEL_9 + * @arg @ref DDL_ADC_CHANNEL_10 + * @arg @ref DDL_ADC_CHANNEL_11 + * @arg @ref DDL_ADC_CHANNEL_12 + * @arg @ref DDL_ADC_CHANNEL_13 + * @arg @ref DDL_ADC_CHANNEL_14 + * @arg @ref DDL_ADC_CHANNEL_15 + * @arg @ref DDL_ADC_CHANNEL_16 + * @arg @ref DDL_ADC_CHANNEL_17 + * @arg @ref DDL_ADC_CHANNEL_18 + * @arg @ref DDL_ADC_CHANNEL_VREFINT (1) + * @arg @ref DDL_ADC_CHANNEL_TEMPSENSOR (1)(2) + * @arg @ref DDL_ADC_CHANNEL_VBAT (1) + * + * (1) On APM32F4, parameter available only on ADC instance: ADC1.\n + * @param SamplingTime This parameter can be one of the following values: + * @arg @ref DDL_ADC_SAMPLINGTIME_3CYCLES + * @arg @ref DDL_ADC_SAMPLINGTIME_15CYCLES + * @arg @ref DDL_ADC_SAMPLINGTIME_28CYCLES + * @arg @ref DDL_ADC_SAMPLINGTIME_56CYCLES + * @arg @ref DDL_ADC_SAMPLINGTIME_84CYCLES + * @arg @ref DDL_ADC_SAMPLINGTIME_112CYCLES + * @arg @ref DDL_ADC_SAMPLINGTIME_144CYCLES + * @arg @ref DDL_ADC_SAMPLINGTIME_480CYCLES + * @retval None + */ +__STATIC_INLINE void DDL_ADC_SetChannelSamplingTime(ADC_TypeDef *ADCx, uint32_t Channel, uint32_t SamplingTime) +{ + /* Set bits with content of parameter "SamplingTime" with bits position */ + /* in register and register position depending on parameter "Channel". */ + /* Parameter "Channel" is used with masks because containing */ + /* other bits reserved for other purpose. */ + __IO uint32_t *preg = __ADC_PTR_REG_OFFSET(ADCx->SMPTIM1, __ADC_MASK_SHIFT(Channel, ADC_CHANNEL_SMPRX_REGOFFSET_MASK)); + + MODIFY_REG(*preg, + ADC_SMPTIM2_SMPCYCCFG0 << __ADC_MASK_SHIFT(Channel, ADC_CHANNEL_SMPx_BITOFFSET_MASK), + SamplingTime << __ADC_MASK_SHIFT(Channel, ADC_CHANNEL_SMPx_BITOFFSET_MASK)); +} + +/** + * @brief Get sampling time of the selected ADC channel + * Unit: ADC clock cycles. + * @note On this device, sampling time is on channel scope: independently + * of channel mapped on ADC group regular or injected. + * @note Conversion time is the addition of sampling time and processing time. + * Refer to reference manual for ADC processing time of + * this APM32 series. + * @param ADCx ADC instance + * @param Channel This parameter can be one of the following values: + * @arg @ref DDL_ADC_CHANNEL_0 + * @arg @ref DDL_ADC_CHANNEL_1 + * @arg @ref DDL_ADC_CHANNEL_2 + * @arg @ref DDL_ADC_CHANNEL_3 + * @arg @ref DDL_ADC_CHANNEL_4 + * @arg @ref DDL_ADC_CHANNEL_5 + * @arg @ref DDL_ADC_CHANNEL_6 + * @arg @ref DDL_ADC_CHANNEL_7 + * @arg @ref DDL_ADC_CHANNEL_8 + * @arg @ref DDL_ADC_CHANNEL_9 + * @arg @ref DDL_ADC_CHANNEL_10 + * @arg @ref DDL_ADC_CHANNEL_11 + * @arg @ref DDL_ADC_CHANNEL_12 + * @arg @ref DDL_ADC_CHANNEL_13 + * @arg @ref DDL_ADC_CHANNEL_14 + * @arg @ref DDL_ADC_CHANNEL_15 + * @arg @ref DDL_ADC_CHANNEL_16 + * @arg @ref DDL_ADC_CHANNEL_17 + * @arg @ref DDL_ADC_CHANNEL_18 + * @arg @ref DDL_ADC_CHANNEL_VREFINT (1) + * @arg @ref DDL_ADC_CHANNEL_TEMPSENSOR (1)(2) + * @arg @ref DDL_ADC_CHANNEL_VBAT (1) + * + * (1) On APM32F4, parameter available only on ADC instance: ADC1.\n + * @retval Returned value can be one of the following values: + * @arg @ref DDL_ADC_SAMPLINGTIME_3CYCLES + * @arg @ref DDL_ADC_SAMPLINGTIME_15CYCLES + * @arg @ref DDL_ADC_SAMPLINGTIME_28CYCLES + * @arg @ref DDL_ADC_SAMPLINGTIME_56CYCLES + * @arg @ref DDL_ADC_SAMPLINGTIME_84CYCLES + * @arg @ref DDL_ADC_SAMPLINGTIME_112CYCLES + * @arg @ref DDL_ADC_SAMPLINGTIME_144CYCLES + * @arg @ref DDL_ADC_SAMPLINGTIME_480CYCLES + */ +__STATIC_INLINE uint32_t DDL_ADC_GetChannelSamplingTime(ADC_TypeDef *ADCx, uint32_t Channel) +{ + __IO uint32_t *preg = __ADC_PTR_REG_OFFSET(ADCx->SMPTIM1, __ADC_MASK_SHIFT(Channel, ADC_CHANNEL_SMPRX_REGOFFSET_MASK)); + + return (uint32_t)(READ_BIT(*preg, + ADC_SMPTIM2_SMPCYCCFG0 << __ADC_MASK_SHIFT(Channel, ADC_CHANNEL_SMPx_BITOFFSET_MASK)) + >> __ADC_MASK_SHIFT(Channel, ADC_CHANNEL_SMPx_BITOFFSET_MASK) + ); +} + +/** + * @} + */ + +/** @defgroup ADC_DDL_EF_Configuration_ADC_AnalogWatchdog Configuration of ADC transversal scope: analog watchdog + * @{ + */ + +/** + * @brief Set ADC analog watchdog monitored channels: + * a single channel or all channels, + * on ADC groups regular and-or injected. + * @note Once monitored channels are selected, analog watchdog + * is enabled. + * @note In case of need to define a single channel to monitor + * with analog watchdog from sequencer channel definition, + * use helper macro @ref __DDL_ADC_ANALOGWD_CHANNEL_GROUP(). + * @note On this APM32 series, there is only 1 kind of analog watchdog + * instance: + * - AWD standard (instance AWD1): + * - channels monitored: can monitor 1 channel or all channels. + * - groups monitored: ADC groups regular and-or injected. + * - resolution: resolution is not limited (corresponds to + * ADC resolution configured). + * @param ADCx ADC instance + * @param AWDChannelGroup This parameter can be one of the following values: + * @arg @ref DDL_ADC_AWD_DISABLE + * @arg @ref DDL_ADC_AWD_ALL_CHANNELS_REG + * @arg @ref DDL_ADC_AWD_ALL_CHANNELS_INJ + * @arg @ref DDL_ADC_AWD_ALL_CHANNELS_REG_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_0_REG + * @arg @ref DDL_ADC_AWD_CHANNEL_0_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_0_REG_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_1_REG + * @arg @ref DDL_ADC_AWD_CHANNEL_1_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_1_REG_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_2_REG + * @arg @ref DDL_ADC_AWD_CHANNEL_2_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_2_REG_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_3_REG + * @arg @ref DDL_ADC_AWD_CHANNEL_3_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_3_REG_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_4_REG + * @arg @ref DDL_ADC_AWD_CHANNEL_4_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_4_REG_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_5_REG + * @arg @ref DDL_ADC_AWD_CHANNEL_5_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_5_REG_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_6_REG + * @arg @ref DDL_ADC_AWD_CHANNEL_6_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_6_REG_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_7_REG + * @arg @ref DDL_ADC_AWD_CHANNEL_7_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_7_REG_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_8_REG + * @arg @ref DDL_ADC_AWD_CHANNEL_8_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_8_REG_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_9_REG + * @arg @ref DDL_ADC_AWD_CHANNEL_9_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_9_REG_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_10_REG + * @arg @ref DDL_ADC_AWD_CHANNEL_10_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_10_REG_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_11_REG + * @arg @ref DDL_ADC_AWD_CHANNEL_11_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_11_REG_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_12_REG + * @arg @ref DDL_ADC_AWD_CHANNEL_12_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_12_REG_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_13_REG + * @arg @ref DDL_ADC_AWD_CHANNEL_13_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_13_REG_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_14_REG + * @arg @ref DDL_ADC_AWD_CHANNEL_14_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_14_REG_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_15_REG + * @arg @ref DDL_ADC_AWD_CHANNEL_15_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_15_REG_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_16_REG + * @arg @ref DDL_ADC_AWD_CHANNEL_16_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_16_REG_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_17_REG + * @arg @ref DDL_ADC_AWD_CHANNEL_17_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_17_REG_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_18_REG + * @arg @ref DDL_ADC_AWD_CHANNEL_18_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_18_REG_INJ + * @arg @ref DDL_ADC_AWD_CH_VREFINT_REG (1) + * @arg @ref DDL_ADC_AWD_CH_VREFINT_INJ (1) + * @arg @ref DDL_ADC_AWD_CH_VREFINT_REG_INJ (1) + * @arg @ref DDL_ADC_AWD_CH_TEMPSENSOR_REG (1)(2) + * @arg @ref DDL_ADC_AWD_CH_TEMPSENSOR_INJ (1)(2) + * @arg @ref DDL_ADC_AWD_CH_TEMPSENSOR_REG_INJ (1)(2) + * @arg @ref DDL_ADC_AWD_CH_VBAT_REG (1) + * @arg @ref DDL_ADC_AWD_CH_VBAT_INJ (1) + * @arg @ref DDL_ADC_AWD_CH_VBAT_REG_INJ (1) + * + * (1) On APM32F4, parameter available only on ADC instance: ADC1.\n + * @retval None + */ +__STATIC_INLINE void DDL_ADC_SetAnalogWDMonitChannels(ADC_TypeDef *ADCx, uint32_t AWDChannelGroup) +{ + MODIFY_REG(ADCx->CTRL1, + (ADC_CTRL1_REGAWDEN | ADC_CTRL1_INJAWDEN | ADC_CTRL1_AWDSGLEN | ADC_CTRL1_AWDCHSEL), + AWDChannelGroup); +} + +/** + * @brief Get ADC analog watchdog monitored channel. + * @note Usage of the returned channel number: + * - To reinject this channel into another function DDL_ADC_xxx: + * the returned channel number is only partly formatted on definition + * of literals DDL_ADC_CHANNEL_x. Therefore, it has to be compared + * with parts of literals DDL_ADC_CHANNEL_x or using + * helper macro @ref __DDL_ADC_CHANNEL_TO_DECIMAL_NB(). + * Then the selected literal DDL_ADC_CHANNEL_x can be used + * as parameter for another function. + * - To get the channel number in decimal format: + * process the returned value with the helper macro + * @ref __DDL_ADC_CHANNEL_TO_DECIMAL_NB(). + * Applicable only when the analog watchdog is set to monitor + * one channel. + * @note On this APM32 series, there is only 1 kind of analog watchdog + * instance: + * - AWD standard (instance AWD1): + * - channels monitored: can monitor 1 channel or all channels. + * - groups monitored: ADC groups regular and-or injected. + * - resolution: resolution is not limited (corresponds to + * ADC resolution configured). + * @param ADCx ADC instance + * @retval Returned value can be one of the following values: + * @arg @ref DDL_ADC_AWD_DISABLE + * @arg @ref DDL_ADC_AWD_ALL_CHANNELS_REG + * @arg @ref DDL_ADC_AWD_ALL_CHANNELS_INJ + * @arg @ref DDL_ADC_AWD_ALL_CHANNELS_REG_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_0_REG + * @arg @ref DDL_ADC_AWD_CHANNEL_0_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_0_REG_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_1_REG + * @arg @ref DDL_ADC_AWD_CHANNEL_1_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_1_REG_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_2_REG + * @arg @ref DDL_ADC_AWD_CHANNEL_2_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_2_REG_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_3_REG + * @arg @ref DDL_ADC_AWD_CHANNEL_3_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_3_REG_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_4_REG + * @arg @ref DDL_ADC_AWD_CHANNEL_4_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_4_REG_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_5_REG + * @arg @ref DDL_ADC_AWD_CHANNEL_5_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_5_REG_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_6_REG + * @arg @ref DDL_ADC_AWD_CHANNEL_6_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_6_REG_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_7_REG + * @arg @ref DDL_ADC_AWD_CHANNEL_7_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_7_REG_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_8_REG + * @arg @ref DDL_ADC_AWD_CHANNEL_8_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_8_REG_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_9_REG + * @arg @ref DDL_ADC_AWD_CHANNEL_9_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_9_REG_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_10_REG + * @arg @ref DDL_ADC_AWD_CHANNEL_10_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_10_REG_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_11_REG + * @arg @ref DDL_ADC_AWD_CHANNEL_11_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_11_REG_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_12_REG + * @arg @ref DDL_ADC_AWD_CHANNEL_12_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_12_REG_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_13_REG + * @arg @ref DDL_ADC_AWD_CHANNEL_13_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_13_REG_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_14_REG + * @arg @ref DDL_ADC_AWD_CHANNEL_14_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_14_REG_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_15_REG + * @arg @ref DDL_ADC_AWD_CHANNEL_15_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_15_REG_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_16_REG + * @arg @ref DDL_ADC_AWD_CHANNEL_16_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_16_REG_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_17_REG + * @arg @ref DDL_ADC_AWD_CHANNEL_17_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_17_REG_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_18_REG + * @arg @ref DDL_ADC_AWD_CHANNEL_18_INJ + * @arg @ref DDL_ADC_AWD_CHANNEL_18_REG_INJ + */ +__STATIC_INLINE uint32_t DDL_ADC_GetAnalogWDMonitChannels(ADC_TypeDef *ADCx) +{ + return (uint32_t)(READ_BIT(ADCx->CTRL1, (ADC_CTRL1_REGAWDEN | ADC_CTRL1_INJAWDEN | ADC_CTRL1_AWDSGLEN | ADC_CTRL1_AWDCHSEL))); +} + +/** + * @brief Set ADC analog watchdog threshold value of threshold + * high or low. + * @note In case of ADC resolution different of 12 bits, + * analog watchdog thresholds data require a specific shift. + * Use helper macro @ref __DDL_ADC_ANALOGWD_SET_THRESHOLD_RESOLUTION(). + * @note On this APM32 series, there is only 1 kind of analog watchdog + * instance: + * - AWD standard (instance AWD1): + * - channels monitored: can monitor 1 channel or all channels. + * - groups monitored: ADC groups regular and-or injected. + * - resolution: resolution is not limited (corresponds to + * ADC resolution configured). + * @param ADCx ADC instance + * @param AWDThresholdsHighLow This parameter can be one of the following values: + * @arg @ref DDL_ADC_AWD_THRESHOLD_HIGH + * @arg @ref DDL_ADC_AWD_THRESHOLD_LOW + * @param AWDThresholdValue Value between Min_Data=0x000 and Max_Data=0xFFF + * @retval None + */ +__STATIC_INLINE void DDL_ADC_SetAnalogWDThresholds(ADC_TypeDef *ADCx, uint32_t AWDThresholdsHighLow, uint32_t AWDThresholdValue) +{ + __IO uint32_t *preg = __ADC_PTR_REG_OFFSET(ADCx->AWDHT, AWDThresholdsHighLow); + + MODIFY_REG(*preg, + ADC_AWDHT_AWDHT, + AWDThresholdValue); +} + +/** + * @brief Get ADC analog watchdog threshold value of threshold high or + * threshold low. + * @note In case of ADC resolution different of 12 bits, + * analog watchdog thresholds data require a specific shift. + * Use helper macro @ref __DDL_ADC_ANALOGWD_GET_THRESHOLD_RESOLUTION(). + * @param ADCx ADC instance + * @param AWDThresholdsHighLow This parameter can be one of the following values: + * @arg @ref DDL_ADC_AWD_THRESHOLD_HIGH + * @arg @ref DDL_ADC_AWD_THRESHOLD_LOW + * @retval Value between Min_Data=0x000 and Max_Data=0xFFF +*/ +__STATIC_INLINE uint32_t DDL_ADC_GetAnalogWDThresholds(ADC_TypeDef *ADCx, uint32_t AWDThresholdsHighLow) +{ + __IO uint32_t *preg = __ADC_PTR_REG_OFFSET(ADCx->AWDHT, AWDThresholdsHighLow); + + return (uint32_t)(READ_BIT(*preg, ADC_AWDHT_AWDHT)); +} + +/** + * @} + */ + +/** @defgroup ADC_DDL_EF_Configuration_ADC_Multimode Configuration of ADC hierarchical scope: multimode + * @{ + */ + +#if defined(ADC_MULTIMODE_SUPPORT) +/** + * @brief Set ADC multimode configuration to operate in independent mode + * or multimode (for devices with several ADC instances). + * @note If multimode configuration: the selected ADC instance is + * either master or slave depending on hardware. + * Refer to reference manual. + * @param ADCxy_COMMON ADC common instance + * (can be set directly from CMSIS definition or by using helper macro @ref __DDL_ADC_COMMON_INSTANCE() ) + * @param Multimode This parameter can be one of the following values: + * @arg @ref DDL_ADC_MULTI_INDEPENDENT + * @arg @ref DDL_ADC_MULTI_DUAL_REG_SIMULT + * @arg @ref DDL_ADC_MULTI_DUAL_REG_INTERL + * @arg @ref DDL_ADC_MULTI_DUAL_INJ_SIMULT + * @arg @ref DDL_ADC_MULTI_DUAL_INJ_ALTERN + * @arg @ref DDL_ADC_MULTI_DUAL_REG_SIM_INJ_SIM + * @arg @ref DDL_ADC_MULTI_DUAL_REG_SIM_INJ_ALT + * @arg @ref DDL_ADC_MULTI_DUAL_REG_INT_INJ_SIM + * @arg @ref DDL_ADC_MULTI_TRIPLE_REG_SIM_INJ_SIM + * @arg @ref DDL_ADC_MULTI_TRIPLE_REG_SIM_INJ_ALT + * @arg @ref DDL_ADC_MULTI_TRIPLE_INJ_SIMULT + * @arg @ref DDL_ADC_MULTI_TRIPLE_REG_SIMULT + * @arg @ref DDL_ADC_MULTI_TRIPLE_REG_INTERL + * @arg @ref DDL_ADC_MULTI_TRIPLE_INJ_ALTERN + * @retval None + */ +__STATIC_INLINE void DDL_ADC_SetMultimode(ADC_Common_TypeDef *ADCxy_COMMON, uint32_t Multimode) +{ + MODIFY_REG(ADCxy_COMMON->CCTRL, ADC_CCTRL_ADCMSEL, Multimode); +} + +/** + * @brief Get ADC multimode configuration to operate in independent mode + * or multimode (for devices with several ADC instances). + * @note If multimode configuration: the selected ADC instance is + * either master or slave depending on hardware. + * Refer to reference manual. + * @param ADCxy_COMMON ADC common instance + * (can be set directly from CMSIS definition or by using helper macro @ref __DDL_ADC_COMMON_INSTANCE() ) + * @retval Returned value can be one of the following values: + * @arg @ref DDL_ADC_MULTI_INDEPENDENT + * @arg @ref DDL_ADC_MULTI_DUAL_REG_SIMULT + * @arg @ref DDL_ADC_MULTI_DUAL_REG_INTERL + * @arg @ref DDL_ADC_MULTI_DUAL_INJ_SIMULT + * @arg @ref DDL_ADC_MULTI_DUAL_INJ_ALTERN + * @arg @ref DDL_ADC_MULTI_DUAL_REG_SIM_INJ_SIM + * @arg @ref DDL_ADC_MULTI_DUAL_REG_SIM_INJ_ALT + * @arg @ref DDL_ADC_MULTI_DUAL_REG_INT_INJ_SIM + * @arg @ref DDL_ADC_MULTI_TRIPLE_REG_SIM_INJ_SIM + * @arg @ref DDL_ADC_MULTI_TRIPLE_REG_SIM_INJ_ALT + * @arg @ref DDL_ADC_MULTI_TRIPLE_INJ_SIMULT + * @arg @ref DDL_ADC_MULTI_TRIPLE_REG_SIMULT + * @arg @ref DDL_ADC_MULTI_TRIPLE_REG_INTERL + * @arg @ref DDL_ADC_MULTI_TRIPLE_INJ_ALTERN + */ +__STATIC_INLINE uint32_t DDL_ADC_GetMultimode(ADC_Common_TypeDef *ADCxy_COMMON) +{ + return (uint32_t)(READ_BIT(ADCxy_COMMON->CCTRL, ADC_CCTRL_ADCMSEL)); +} + +/** + * @brief Set ADC multimode conversion data transfer: no transfer + * or transfer by DMA. + * @note If ADC multimode transfer by DMA is not selected: + * each ADC uses its own DMA channel, with its individual + * DMA transfer settings. + * If ADC multimode transfer by DMA is selected: + * One DMA channel is used for both ADC (DMA of ADC master) + * Specifies the DMA requests mode: + * - Limited mode (One shot mode): DMA transfer requests are stopped + * when number of DMA data transfers (number of + * ADC conversions) is reached. + * This ADC mode is intended to be used with DMA mode non-circular. + * - Unlimited mode: DMA transfer requests are unlimited, + * whatever number of DMA data transfers (number of + * ADC conversions). + * This ADC mode is intended to be used with DMA mode circular. + * @note If ADC DMA requests mode is set to unlimited and DMA is set to + * mode non-circular: + * when DMA transfers size will be reached, DMA will stop transfers of + * ADC conversions data ADC will raise an overrun error + * (overrun flag and interruption if enabled). + * @note How to retrieve multimode conversion data: + * Whatever multimode transfer by DMA setting: using function + * @ref DDL_ADC_REG_ReadMultiConversionData32(). + * If ADC multimode transfer by DMA is selected: conversion data + * is a raw data with ADC master and slave concatenated. + * A macro is available to get the conversion data of + * ADC master or ADC slave: see helper macro + * @ref __DDL_ADC_MULTI_CONV_DATA_MASTER_SLAVE(). + * @param ADCxy_COMMON ADC common instance + * (can be set directly from CMSIS definition or by using helper macro @ref __DDL_ADC_COMMON_INSTANCE() ) + * @param MultiDMATransfer This parameter can be one of the following values: + * @arg @ref DDL_ADC_MULTI_REG_DMA_EACH_ADC + * @arg @ref DDL_ADC_MULTI_REG_DMA_LIMIT_1 + * @arg @ref DDL_ADC_MULTI_REG_DMA_LIMIT_2 + * @arg @ref DDL_ADC_MULTI_REG_DMA_LIMIT_3 + * @arg @ref DDL_ADC_MULTI_REG_DMA_UNLMT_1 + * @arg @ref DDL_ADC_MULTI_REG_DMA_UNLMT_2 + * @arg @ref DDL_ADC_MULTI_REG_DMA_UNLMT_3 + * @retval None + */ +__STATIC_INLINE void DDL_ADC_SetMultiDMATransfer(ADC_Common_TypeDef *ADCxy_COMMON, uint32_t MultiDMATransfer) +{ + MODIFY_REG(ADCxy_COMMON->CCTRL, ADC_CCTRL_DMAMODE | ADC_CCTRL_DMAMODEDISSEL, MultiDMATransfer); +} + +/** + * @brief Get ADC multimode conversion data transfer: no transfer + * or transfer by DMA. + * @note If ADC multimode transfer by DMA is not selected: + * each ADC uses its own DMA channel, with its individual + * DMA transfer settings. + * If ADC multimode transfer by DMA is selected: + * One DMA channel is used for both ADC (DMA of ADC master) + * Specifies the DMA requests mode: + * - Limited mode (One shot mode): DMA transfer requests are stopped + * when number of DMA data transfers (number of + * ADC conversions) is reached. + * This ADC mode is intended to be used with DMA mode non-circular. + * - Unlimited mode: DMA transfer requests are unlimited, + * whatever number of DMA data transfers (number of + * ADC conversions). + * This ADC mode is intended to be used with DMA mode circular. + * @note If ADC DMA requests mode is set to unlimited and DMA is set to + * mode non-circular: + * when DMA transfers size will be reached, DMA will stop transfers of + * ADC conversions data ADC will raise an overrun error + * (overrun flag and interruption if enabled). + * @note How to retrieve multimode conversion data: + * Whatever multimode transfer by DMA setting: using function + * @ref DDL_ADC_REG_ReadMultiConversionData32(). + * If ADC multimode transfer by DMA is selected: conversion data + * is a raw data with ADC master and slave concatenated. + * A macro is available to get the conversion data of + * ADC master or ADC slave: see helper macro + * @ref __DDL_ADC_MULTI_CONV_DATA_MASTER_SLAVE(). + * @param ADCxy_COMMON ADC common instance + * (can be set directly from CMSIS definition or by using helper macro @ref __DDL_ADC_COMMON_INSTANCE() ) + * @retval Returned value can be one of the following values: + * @arg @ref DDL_ADC_MULTI_REG_DMA_EACH_ADC + * @arg @ref DDL_ADC_MULTI_REG_DMA_LIMIT_1 + * @arg @ref DDL_ADC_MULTI_REG_DMA_LIMIT_2 + * @arg @ref DDL_ADC_MULTI_REG_DMA_LIMIT_3 + * @arg @ref DDL_ADC_MULTI_REG_DMA_UNLMT_1 + * @arg @ref DDL_ADC_MULTI_REG_DMA_UNLMT_2 + * @arg @ref DDL_ADC_MULTI_REG_DMA_UNLMT_3 + */ +__STATIC_INLINE uint32_t DDL_ADC_GetMultiDMATransfer(ADC_Common_TypeDef *ADCxy_COMMON) +{ + return (uint32_t)(READ_BIT(ADCxy_COMMON->CCTRL, ADC_CCTRL_DMAMODE | ADC_CCTRL_DMAMODEDISSEL)); +} + +/** + * @brief Set ADC multimode delay between 2 sampling phases. + * @note The sampling delay range depends on ADC resolution: + * - ADC resolution 12 bits can have maximum delay of 12 cycles. + * - ADC resolution 10 bits can have maximum delay of 10 cycles. + * - ADC resolution 8 bits can have maximum delay of 8 cycles. + * - ADC resolution 6 bits can have maximum delay of 6 cycles. + * @param ADCxy_COMMON ADC common instance + * (can be set directly from CMSIS definition or by using helper macro @ref __DDL_ADC_COMMON_INSTANCE() ) + * @param MultiTwoSamplingDelay This parameter can be one of the following values: + * @arg @ref DDL_ADC_MULTI_TWOSMP_DELAY_5CYCLES + * @arg @ref DDL_ADC_MULTI_TWOSMP_DELAY_6CYCLES + * @arg @ref DDL_ADC_MULTI_TWOSMP_DELAY_7CYCLES + * @arg @ref DDL_ADC_MULTI_TWOSMP_DELAY_8CYCLES + * @arg @ref DDL_ADC_MULTI_TWOSMP_DELAY_9CYCLES + * @arg @ref DDL_ADC_MULTI_TWOSMP_DELAY_10CYCLES + * @arg @ref DDL_ADC_MULTI_TWOSMP_DELAY_11CYCLES + * @arg @ref DDL_ADC_MULTI_TWOSMP_DELAY_12CYCLES + * @arg @ref DDL_ADC_MULTI_TWOSMP_DELAY_13CYCLES + * @arg @ref DDL_ADC_MULTI_TWOSMP_DELAY_14CYCLES + * @arg @ref DDL_ADC_MULTI_TWOSMP_DELAY_15CYCLES + * @arg @ref DDL_ADC_MULTI_TWOSMP_DELAY_16CYCLES + * @arg @ref DDL_ADC_MULTI_TWOSMP_DELAY_17CYCLES + * @arg @ref DDL_ADC_MULTI_TWOSMP_DELAY_18CYCLES + * @arg @ref DDL_ADC_MULTI_TWOSMP_DELAY_19CYCLES + * @arg @ref DDL_ADC_MULTI_TWOSMP_DELAY_20CYCLES + * @retval None + */ +__STATIC_INLINE void DDL_ADC_SetMultiTwoSamplingDelay(ADC_Common_TypeDef *ADCxy_COMMON, uint32_t MultiTwoSamplingDelay) +{ + MODIFY_REG(ADCxy_COMMON->CCTRL, ADC_CCTRL_SMPDEL2, MultiTwoSamplingDelay); +} + +/** + * @brief Get ADC multimode delay between 2 sampling phases. + * @param ADCxy_COMMON ADC common instance + * (can be set directly from CMSIS definition or by using helper macro @ref __DDL_ADC_COMMON_INSTANCE() ) + * @retval Returned value can be one of the following values: + * @arg @ref DDL_ADC_MULTI_TWOSMP_DELAY_5CYCLES + * @arg @ref DDL_ADC_MULTI_TWOSMP_DELAY_6CYCLES + * @arg @ref DDL_ADC_MULTI_TWOSMP_DELAY_7CYCLES + * @arg @ref DDL_ADC_MULTI_TWOSMP_DELAY_8CYCLES + * @arg @ref DDL_ADC_MULTI_TWOSMP_DELAY_9CYCLES + * @arg @ref DDL_ADC_MULTI_TWOSMP_DELAY_10CYCLES + * @arg @ref DDL_ADC_MULTI_TWOSMP_DELAY_11CYCLES + * @arg @ref DDL_ADC_MULTI_TWOSMP_DELAY_12CYCLES + * @arg @ref DDL_ADC_MULTI_TWOSMP_DELAY_13CYCLES + * @arg @ref DDL_ADC_MULTI_TWOSMP_DELAY_14CYCLES + * @arg @ref DDL_ADC_MULTI_TWOSMP_DELAY_15CYCLES + * @arg @ref DDL_ADC_MULTI_TWOSMP_DELAY_16CYCLES + * @arg @ref DDL_ADC_MULTI_TWOSMP_DELAY_17CYCLES + * @arg @ref DDL_ADC_MULTI_TWOSMP_DELAY_18CYCLES + * @arg @ref DDL_ADC_MULTI_TWOSMP_DELAY_19CYCLES + * @arg @ref DDL_ADC_MULTI_TWOSMP_DELAY_20CYCLES + */ +__STATIC_INLINE uint32_t DDL_ADC_GetMultiTwoSamplingDelay(ADC_Common_TypeDef *ADCxy_COMMON) +{ + return (uint32_t)(READ_BIT(ADCxy_COMMON->CCTRL, ADC_CCTRL_SMPDEL2)); +} +#endif /* ADC_MULTIMODE_SUPPORT */ + +/** + * @} + */ +/** @defgroup ADC_DDL_EF_Operation_ADC_Instance Operation on ADC hierarchical scope: ADC instance + * @{ + */ + +/** + * @brief Enable the selected ADC instance. + * @note On this APM32 series, after ADC enable, a delay for + * ADC internal analog stabilization is required before performing a + * ADC conversion start. + * Refer to device datasheet, parameter tSTAB. + * @param ADCx ADC instance + * @retval None + */ +__STATIC_INLINE void DDL_ADC_Enable(ADC_TypeDef *ADCx) +{ + SET_BIT(ADCx->CTRL2, ADC_CTRL2_ADCEN); +} + +/** + * @brief Disable the selected ADC instance. + * @param ADCx ADC instance + * @retval None + */ +__STATIC_INLINE void DDL_ADC_Disable(ADC_TypeDef *ADCx) +{ + CLEAR_BIT(ADCx->CTRL2, ADC_CTRL2_ADCEN); +} + +/** + * @brief Get the selected ADC instance enable state. + * @param ADCx ADC instance + * @retval 0: ADC is disabled, 1: ADC is enabled. + */ +__STATIC_INLINE uint32_t DDL_ADC_IsEnabled(ADC_TypeDef *ADCx) +{ + return (READ_BIT(ADCx->CTRL2, ADC_CTRL2_ADCEN) == (ADC_CTRL2_ADCEN)); +} + +/** + * @} + */ + +/** @defgroup ADC_DDL_EF_Operation_ADC_Group_Regular Operation on ADC hierarchical scope: group regular + * @{ + */ + +/** + * @brief Start ADC group regular conversion. + * @note On this APM32 series, this function is relevant only for + * internal trigger (SW start), not for external trigger: + * - If ADC trigger has been set to software start, ADC conversion + * starts immediately. + * - If ADC trigger has been set to external trigger, ADC conversion + * start must be performed using function + * @ref DDL_ADC_REG_StartConversionExtTrig(). + * (if external trigger edge would have been set during ADC other + * settings, ADC conversion would start at trigger event + * as soon as ADC is enabled). + * @param ADCx ADC instance + * @retval None + */ +__STATIC_INLINE void DDL_ADC_REG_StartConversionSWStart(ADC_TypeDef *ADCx) +{ + SET_BIT(ADCx->CTRL2, ADC_CTRL2_REGCHSC); +} + +/** + * @brief Start ADC group regular conversion from external trigger. + * @note ADC conversion will start at next trigger event (on the selected + * trigger edge) following the ADC start conversion command. + * @note On this APM32 series, this function is relevant for + * ADC conversion start from external trigger. + * If internal trigger (SW start) is needed, perform ADC conversion + * start using function @ref DDL_ADC_REG_StartConversionSWStart(). + * @param ExternalTriggerEdge This parameter can be one of the following values: + * @arg @ref DDL_ADC_REG_TRIG_EXT_RISING + * @arg @ref DDL_ADC_REG_TRIG_EXT_FALLING + * @arg @ref DDL_ADC_REG_TRIG_EXT_RISINGFALLING + * @param ADCx ADC instance + * @retval None + */ +__STATIC_INLINE void DDL_ADC_REG_StartConversionExtTrig(ADC_TypeDef *ADCx, uint32_t ExternalTriggerEdge) +{ + SET_BIT(ADCx->CTRL2, ExternalTriggerEdge); +} + +/** + * @brief Stop ADC group regular conversion from external trigger. + * @note No more ADC conversion will start at next trigger event + * following the ADC stop conversion command. + * If a conversion is on-going, it will be completed. + * @note On this APM32 series, there is no specific command + * to stop a conversion on-going or to stop ADC converting + * in continuous mode. These actions can be performed + * using function @ref DDL_ADC_Disable(). + * @param ADCx ADC instance + * @retval None + */ +__STATIC_INLINE void DDL_ADC_REG_StopConversionExtTrig(ADC_TypeDef *ADCx) +{ + CLEAR_BIT(ADCx->CTRL2, ADC_CTRL2_REGEXTTRGEN); +} + +/** + * @brief Get ADC group regular conversion data, range fit for + * all ADC configurations: all ADC resolutions and + * all oversampling increased data width (for devices + * with feature oversampling). + * @param ADCx ADC instance + * @retval Value between Min_Data=0x00000000 and Max_Data=0xFFFFFFFF + */ +__STATIC_INLINE uint32_t DDL_ADC_REG_ReadConversionData32(ADC_TypeDef *ADCx) +{ + return (uint16_t)(READ_BIT(ADCx->REGDATA, ADC_REGDATA_REGDATA)); +} + +/** + * @brief Get ADC group regular conversion data, range fit for + * ADC resolution 12 bits. + * @note For devices with feature oversampling: Oversampling + * can increase data width, function for extended range + * may be needed: @ref DDL_ADC_REG_ReadConversionData32. + * @param ADCx ADC instance + * @retval Value between Min_Data=0x000 and Max_Data=0xFFF + */ +__STATIC_INLINE uint16_t DDL_ADC_REG_ReadConversionData12(ADC_TypeDef *ADCx) +{ + return (uint16_t)(READ_BIT(ADCx->REGDATA, ADC_REGDATA_REGDATA)); +} + +/** + * @brief Get ADC group regular conversion data, range fit for + * ADC resolution 10 bits. + * @note For devices with feature oversampling: Oversampling + * can increase data width, function for extended range + * may be needed: @ref DDL_ADC_REG_ReadConversionData32. + * @param ADCx ADC instance + * @retval Value between Min_Data=0x000 and Max_Data=0x3FF + */ +__STATIC_INLINE uint16_t DDL_ADC_REG_ReadConversionData10(ADC_TypeDef *ADCx) +{ + return (uint16_t)(READ_BIT(ADCx->REGDATA, ADC_REGDATA_REGDATA)); +} + +/** + * @brief Get ADC group regular conversion data, range fit for + * ADC resolution 8 bits. + * @note For devices with feature oversampling: Oversampling + * can increase data width, function for extended range + * may be needed: @ref DDL_ADC_REG_ReadConversionData32. + * @param ADCx ADC instance + * @retval Value between Min_Data=0x00 and Max_Data=0xFF + */ +__STATIC_INLINE uint8_t DDL_ADC_REG_ReadConversionData8(ADC_TypeDef *ADCx) +{ + return (uint16_t)(READ_BIT(ADCx->REGDATA, ADC_REGDATA_REGDATA)); +} + +/** + * @brief Get ADC group regular conversion data, range fit for + * ADC resolution 6 bits. + * @note For devices with feature oversampling: Oversampling + * can increase data width, function for extended range + * may be needed: @ref DDL_ADC_REG_ReadConversionData32. + * @param ADCx ADC instance + * @retval Value between Min_Data=0x00 and Max_Data=0x3F + */ +__STATIC_INLINE uint8_t DDL_ADC_REG_ReadConversionData6(ADC_TypeDef *ADCx) +{ + return (uint16_t)(READ_BIT(ADCx->REGDATA, ADC_REGDATA_REGDATA)); +} + +#if defined(ADC_MULTIMODE_SUPPORT) +/** + * @brief Get ADC multimode conversion data of ADC master, ADC slave + * or raw data with ADC master and slave concatenated. + * @note If raw data with ADC master and slave concatenated is retrieved, + * a macro is available to get the conversion data of + * ADC master or ADC slave: see helper macro + * @ref __DDL_ADC_MULTI_CONV_DATA_MASTER_SLAVE(). + * (however this macro is mainly intended for multimode + * transfer by DMA, because this function can do the same + * by getting multimode conversion data of ADC master or ADC slave + * separately). + * @param ADCxy_COMMON ADC common instance + * (can be set directly from CMSIS definition or by using helper macro @ref __DDL_ADC_COMMON_INSTANCE() ) + * @param ConversionData This parameter can be one of the following values: + * @arg @ref DDL_ADC_MULTI_MASTER + * @arg @ref DDL_ADC_MULTI_SLAVE + * @arg @ref DDL_ADC_MULTI_MASTER_SLAVE + * @retval Value between Min_Data=0x00000000 and Max_Data=0xFFFFFFFF + */ +__STATIC_INLINE uint32_t DDL_ADC_REG_ReadMultiConversionData32(ADC_Common_TypeDef *ADCxy_COMMON, uint32_t ConversionData) +{ + return (uint32_t)(READ_BIT(ADCxy_COMMON->CDATA, + ADC_REGDATA_ADC2DATA) + >> POSITION_VAL(ConversionData) + ); +} +#endif /* ADC_MULTIMODE_SUPPORT */ + +/** + * @} + */ + +/** @defgroup ADC_DDL_EF_Operation_ADC_Group_Injected Operation on ADC hierarchical scope: group injected + * @{ + */ + +/** + * @brief Start ADC group injected conversion. + * @note On this APM32 series, this function is relevant only for + * internal trigger (SW start), not for external trigger: + * - If ADC trigger has been set to software start, ADC conversion + * starts immediately. + * - If ADC trigger has been set to external trigger, ADC conversion + * start must be performed using function + * @ref DDL_ADC_INJ_StartConversionExtTrig(). + * (if external trigger edge would have been set during ADC other + * settings, ADC conversion would start at trigger event + * as soon as ADC is enabled). + * @param ADCx ADC instance + * @retval None + */ +__STATIC_INLINE void DDL_ADC_INJ_StartConversionSWStart(ADC_TypeDef *ADCx) +{ + SET_BIT(ADCx->CTRL2, ADC_CTRL2_INJSWSC); +} + +/** + * @brief Start ADC group injected conversion from external trigger. + * @note ADC conversion will start at next trigger event (on the selected + * trigger edge) following the ADC start conversion command. + * @note On this APM32 series, this function is relevant for + * ADC conversion start from external trigger. + * If internal trigger (SW start) is needed, perform ADC conversion + * start using function @ref DDL_ADC_INJ_StartConversionSWStart(). + * @param ExternalTriggerEdge This parameter can be one of the following values: + * @arg @ref DDL_ADC_INJ_TRIG_EXT_RISING + * @arg @ref DDL_ADC_INJ_TRIG_EXT_FALLING + * @arg @ref DDL_ADC_INJ_TRIG_EXT_RISINGFALLING + * @param ADCx ADC instance + * @retval None + */ +__STATIC_INLINE void DDL_ADC_INJ_StartConversionExtTrig(ADC_TypeDef *ADCx, uint32_t ExternalTriggerEdge) +{ + SET_BIT(ADCx->CTRL2, ExternalTriggerEdge); +} + +/** + * @brief Stop ADC group injected conversion from external trigger. + * @note No more ADC conversion will start at next trigger event + * following the ADC stop conversion command. + * If a conversion is on-going, it will be completed. + * @note On this APM32 series, there is no specific command + * to stop a conversion on-going or to stop ADC converting + * in continuous mode. These actions can be performed + * using function @ref DDL_ADC_Disable(). + * @param ADCx ADC instance + * @retval None + */ +__STATIC_INLINE void DDL_ADC_INJ_StopConversionExtTrig(ADC_TypeDef *ADCx) +{ + CLEAR_BIT(ADCx->CTRL2, ADC_CTRL2_INJEXTTRGEN); +} + +/** + * @brief Get ADC group regular conversion data, range fit for + * all ADC configurations: all ADC resolutions and + * all oversampling increased data width (for devices + * with feature oversampling). + * @param ADCx ADC instance + * @param Rank This parameter can be one of the following values: + * @arg @ref DDL_ADC_INJ_RANK_1 + * @arg @ref DDL_ADC_INJ_RANK_2 + * @arg @ref DDL_ADC_INJ_RANK_3 + * @arg @ref DDL_ADC_INJ_RANK_4 + * @retval Value between Min_Data=0x00000000 and Max_Data=0xFFFFFFFF + */ +__STATIC_INLINE uint32_t DDL_ADC_INJ_ReadConversionData32(ADC_TypeDef *ADCx, uint32_t Rank) +{ + __IO uint32_t *preg = __ADC_PTR_REG_OFFSET(ADCx->INJDATA1, __ADC_MASK_SHIFT(Rank, ADC_INJ_JDRX_REGOFFSET_MASK)); + + return (uint32_t)(READ_BIT(*preg, + ADC_INJDATA1_INJDATA) + ); +} + +/** + * @brief Get ADC group injected conversion data, range fit for + * ADC resolution 12 bits. + * @note For devices with feature oversampling: Oversampling + * can increase data width, function for extended range + * may be needed: @ref DDL_ADC_INJ_ReadConversionData32. + * @param ADCx ADC instance + * @param Rank This parameter can be one of the following values: + * @arg @ref DDL_ADC_INJ_RANK_1 + * @arg @ref DDL_ADC_INJ_RANK_2 + * @arg @ref DDL_ADC_INJ_RANK_3 + * @arg @ref DDL_ADC_INJ_RANK_4 + * @retval Value between Min_Data=0x000 and Max_Data=0xFFF + */ +__STATIC_INLINE uint16_t DDL_ADC_INJ_ReadConversionData12(ADC_TypeDef *ADCx, uint32_t Rank) +{ + __IO uint32_t *preg = __ADC_PTR_REG_OFFSET(ADCx->INJDATA1, __ADC_MASK_SHIFT(Rank, ADC_INJ_JDRX_REGOFFSET_MASK)); + + return (uint16_t)(READ_BIT(*preg, + ADC_INJDATA1_INJDATA) + ); +} + +/** + * @brief Get ADC group injected conversion data, range fit for + * ADC resolution 10 bits. + * @note For devices with feature oversampling: Oversampling + * can increase data width, function for extended range + * may be needed: @ref DDL_ADC_INJ_ReadConversionData32. + * @param ADCx ADC instance + * @param Rank This parameter can be one of the following values: + * @arg @ref DDL_ADC_INJ_RANK_1 + * @arg @ref DDL_ADC_INJ_RANK_2 + * @arg @ref DDL_ADC_INJ_RANK_3 + * @arg @ref DDL_ADC_INJ_RANK_4 + * @retval Value between Min_Data=0x000 and Max_Data=0x3FF + */ +__STATIC_INLINE uint16_t DDL_ADC_INJ_ReadConversionData10(ADC_TypeDef *ADCx, uint32_t Rank) +{ + __IO uint32_t *preg = __ADC_PTR_REG_OFFSET(ADCx->INJDATA1, __ADC_MASK_SHIFT(Rank, ADC_INJ_JDRX_REGOFFSET_MASK)); + + return (uint16_t)(READ_BIT(*preg, + ADC_INJDATA1_INJDATA) + ); +} + +/** + * @brief Get ADC group injected conversion data, range fit for + * ADC resolution 8 bits. + * @note For devices with feature oversampling: Oversampling + * can increase data width, function for extended range + * may be needed: @ref DDL_ADC_INJ_ReadConversionData32. + * @param ADCx ADC instance + * @param Rank This parameter can be one of the following values: + * @arg @ref DDL_ADC_INJ_RANK_1 + * @arg @ref DDL_ADC_INJ_RANK_2 + * @arg @ref DDL_ADC_INJ_RANK_3 + * @arg @ref DDL_ADC_INJ_RANK_4 + * @retval Value between Min_Data=0x00 and Max_Data=0xFF + */ +__STATIC_INLINE uint8_t DDL_ADC_INJ_ReadConversionData8(ADC_TypeDef *ADCx, uint32_t Rank) +{ + __IO uint32_t *preg = __ADC_PTR_REG_OFFSET(ADCx->INJDATA1, __ADC_MASK_SHIFT(Rank, ADC_INJ_JDRX_REGOFFSET_MASK)); + + return (uint8_t)(READ_BIT(*preg, + ADC_INJDATA1_INJDATA) + ); +} + +/** + * @brief Get ADC group injected conversion data, range fit for + * ADC resolution 6 bits. + * @note For devices with feature oversampling: Oversampling + * can increase data width, function for extended range + * may be needed: @ref DDL_ADC_INJ_ReadConversionData32. + * @param ADCx ADC instance + * @param Rank This parameter can be one of the following values: + * @arg @ref DDL_ADC_INJ_RANK_1 + * @arg @ref DDL_ADC_INJ_RANK_2 + * @arg @ref DDL_ADC_INJ_RANK_3 + * @arg @ref DDL_ADC_INJ_RANK_4 + * @retval Value between Min_Data=0x00 and Max_Data=0x3F + */ +__STATIC_INLINE uint8_t DDL_ADC_INJ_ReadConversionData6(ADC_TypeDef *ADCx, uint32_t Rank) +{ + __IO uint32_t *preg = __ADC_PTR_REG_OFFSET(ADCx->INJDATA1, __ADC_MASK_SHIFT(Rank, ADC_INJ_JDRX_REGOFFSET_MASK)); + + return (uint8_t)(READ_BIT(*preg, + ADC_INJDATA1_INJDATA) + ); +} + +/** + * @} + */ + +/** @defgroup ADC_DDL_EF_FLAG_Management ADC flag management + * @{ + */ + +/** + * @brief Get flag ADC group regular end of unitary conversion + * or end of sequence conversions, depending on + * ADC configuration. + * @note To configure flag of end of conversion, + * use function @ref DDL_ADC_REG_SetFlagEndOfConversion(). + * @param ADCx ADC instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_ADC_IsActiveFlag_EOCS(ADC_TypeDef *ADCx) +{ + return (READ_BIT(ADCx->STS, DDL_ADC_FLAG_EOCS) == (DDL_ADC_FLAG_EOCS)); +} + +/** + * @brief Get flag ADC group regular overrun. + * @param ADCx ADC instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_ADC_IsActiveFlag_OVR(ADC_TypeDef *ADCx) +{ + return (READ_BIT(ADCx->STS, DDL_ADC_FLAG_OVR) == (DDL_ADC_FLAG_OVR)); +} + + +/** + * @brief Get flag ADC group injected end of sequence conversions. + * @param ADCx ADC instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_ADC_IsActiveFlag_JEOS(ADC_TypeDef *ADCx) +{ + /* Note: on this APM32 series, there is no flag ADC group injected */ + /* end of unitary conversion. */ + /* Flag noted as "JEOC" is corresponding to flag "JEOS" */ + /* in other APM32 families). */ + return (READ_BIT(ADCx->STS, DDL_ADC_FLAG_JEOS) == (DDL_ADC_FLAG_JEOS)); +} + +/** + * @brief Get flag ADC analog watchdog 1 flag + * @param ADCx ADC instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_ADC_IsActiveFlag_AWD1(ADC_TypeDef *ADCx) +{ + return (READ_BIT(ADCx->STS, DDL_ADC_FLAG_AWD1) == (DDL_ADC_FLAG_AWD1)); +} + +/** + * @brief Clear flag ADC group regular end of unitary conversion + * or end of sequence conversions, depending on + * ADC configuration. + * @note To configure flag of end of conversion, + * use function @ref DDL_ADC_REG_SetFlagEndOfConversion(). + * @param ADCx ADC instance + * @retval None + */ +__STATIC_INLINE void DDL_ADC_ClearFlag_EOCS(ADC_TypeDef *ADCx) +{ + WRITE_REG(ADCx->STS, ~DDL_ADC_FLAG_EOCS); +} + +/** + * @brief Clear flag ADC group regular overrun. + * @param ADCx ADC instance + * @retval None + */ +__STATIC_INLINE void DDL_ADC_ClearFlag_OVR(ADC_TypeDef *ADCx) +{ + WRITE_REG(ADCx->STS, ~DDL_ADC_FLAG_OVR); +} + + +/** + * @brief Clear flag ADC group injected end of sequence conversions. + * @param ADCx ADC instance + * @retval None + */ +__STATIC_INLINE void DDL_ADC_ClearFlag_JEOS(ADC_TypeDef *ADCx) +{ + /* Note: on this APM32 series, there is no flag ADC group injected */ + /* end of unitary conversion. */ + /* Flag noted as "JEOC" is corresponding to flag "JEOS" */ + /* in other APM32 families). */ + WRITE_REG(ADCx->STS, ~DDL_ADC_FLAG_JEOS); +} + +/** + * @brief Clear flag ADC analog watchdog 1. + * @param ADCx ADC instance + * @retval None + */ +__STATIC_INLINE void DDL_ADC_ClearFlag_AWD1(ADC_TypeDef *ADCx) +{ + WRITE_REG(ADCx->STS, ~DDL_ADC_FLAG_AWD1); +} + +#if defined(ADC_MULTIMODE_SUPPORT) +/** + * @brief Get flag multimode ADC group regular end of unitary conversion + * or end of sequence conversions, depending on + * ADC configuration, of the ADC master. + * @note To configure flag of end of conversion, + * use function @ref DDL_ADC_REG_SetFlagEndOfConversion(). + * @param ADCxy_COMMON ADC common instance + * (can be set directly from CMSIS definition or by using helper macro @ref __DDL_ADC_COMMON_INSTANCE() ) + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_ADC_IsActiveFlag_MST_EOCS(ADC_Common_TypeDef *ADCxy_COMMON) +{ + return (READ_BIT(ADCxy_COMMON->CSTS, DDL_ADC_FLAG_EOCS_MST) == (DDL_ADC_FLAG_EOCS_MST)); +} + +/** + * @brief Get flag multimode ADC group regular end of unitary conversion + * or end of sequence conversions, depending on + * ADC configuration, of the ADC slave 1. + * @note To configure flag of end of conversion, + * use function @ref DDL_ADC_REG_SetFlagEndOfConversion(). + * @param ADCxy_COMMON ADC common instance + * (can be set directly from CMSIS definition or by using helper macro @ref __DDL_ADC_COMMON_INSTANCE() ) + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_ADC_IsActiveFlag_SLV1_EOCS(ADC_Common_TypeDef *ADCxy_COMMON) +{ + return (READ_BIT(ADCxy_COMMON->CSTS, DDL_ADC_FLAG_EOCS_SLV1) == (DDL_ADC_FLAG_EOCS_SLV1)); +} + +/** + * @brief Get flag multimode ADC group regular end of unitary conversion + * or end of sequence conversions, depending on + * ADC configuration, of the ADC slave 2. + * @note To configure flag of end of conversion, + * use function @ref DDL_ADC_REG_SetFlagEndOfConversion(). + * @param ADCxy_COMMON ADC common instance + * (can be set directly from CMSIS definition or by using helper macro @ref __DDL_ADC_COMMON_INSTANCE() ) + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_ADC_IsActiveFlag_SLV2_EOCS(ADC_Common_TypeDef *ADCxy_COMMON) +{ + return (READ_BIT(ADCxy_COMMON->CSTS, DDL_ADC_FLAG_EOCS_SLV2) == (DDL_ADC_FLAG_EOCS_SLV2)); +} +/** + * @brief Get flag multimode ADC group regular overrun of the ADC master. + * @param ADCxy_COMMON ADC common instance + * (can be set directly from CMSIS definition or by using helper macro @ref __DDL_ADC_COMMON_INSTANCE() ) + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_ADC_IsActiveFlag_MST_OVR(ADC_Common_TypeDef *ADCxy_COMMON) +{ + return (READ_BIT(ADCxy_COMMON->CSTS, DDL_ADC_FLAG_OVR_MST) == (DDL_ADC_FLAG_OVR_MST)); +} + +/** + * @brief Get flag multimode ADC group regular overrun of the ADC slave 1. + * @param ADCxy_COMMON ADC common instance + * (can be set directly from CMSIS definition or by using helper macro @ref __DDL_ADC_COMMON_INSTANCE() ) + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_ADC_IsActiveFlag_SLV1_OVR(ADC_Common_TypeDef *ADCxy_COMMON) +{ + return (READ_BIT(ADCxy_COMMON->CSTS, DDL_ADC_FLAG_OVR_SLV1) == (DDL_ADC_FLAG_OVR_SLV1)); +} + +/** + * @brief Get flag multimode ADC group regular overrun of the ADC slave 2. + * @param ADCxy_COMMON ADC common instance + * (can be set directly from CMSIS definition or by using helper macro @ref __DDL_ADC_COMMON_INSTANCE() ) + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_ADC_IsActiveFlag_SLV2_OVR(ADC_Common_TypeDef *ADCxy_COMMON) +{ + return (READ_BIT(ADCxy_COMMON->CSTS, DDL_ADC_FLAG_OVR_SLV2) == (DDL_ADC_FLAG_OVR_SLV2)); +} + + +/** + * @brief Get flag multimode ADC group injected end of sequence conversions of the ADC master. + * @param ADCxy_COMMON ADC common instance + * (can be set directly from CMSIS definition or by using helper macro @ref __DDL_ADC_COMMON_INSTANCE() ) + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_ADC_IsActiveFlag_MST_JEOS(ADC_Common_TypeDef *ADCxy_COMMON) +{ + /* Note: on this APM32 series, there is no flag ADC group injected */ + /* end of unitary conversion. */ + /* Flag noted as "JEOC" is corresponding to flag "JEOS" */ + /* in other APM32 families). */ + return (READ_BIT(ADCxy_COMMON->CSTS, ADC_CSTS_INJEOCFLG1) == (ADC_CSTS_INJEOCFLG1)); +} + +/** + * @brief Get flag multimode ADC group injected end of sequence conversions of the ADC slave 1. + * @param ADCxy_COMMON ADC common instance + * (can be set directly from CMSIS definition or by using helper macro @ref __DDL_ADC_COMMON_INSTANCE() ) + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_ADC_IsActiveFlag_SLV1_JEOS(ADC_Common_TypeDef *ADCxy_COMMON) +{ + /* Note: on this APM32 series, there is no flag ADC group injected */ + /* end of unitary conversion. */ + /* Flag noted as "JEOC" is corresponding to flag "JEOS" */ + /* in other APM32 families). */ + return (READ_BIT(ADCxy_COMMON->CSTS, ADC_CSTS_INJEOCFLG2) == (ADC_CSTS_INJEOCFLG2)); +} + +/** + * @brief Get flag multimode ADC group injected end of sequence conversions of the ADC slave 2. + * @param ADCxy_COMMON ADC common instance + * (can be set directly from CMSIS definition or by using helper macro @ref __DDL_ADC_COMMON_INSTANCE() ) + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_ADC_IsActiveFlag_SLV2_JEOS(ADC_Common_TypeDef *ADCxy_COMMON) +{ + /* Note: on this APM32 series, there is no flag ADC group injected */ + /* end of unitary conversion. */ + /* Flag noted as "JEOC" is corresponding to flag "JEOS" */ + /* in other APM32 families). */ + return (READ_BIT(ADCxy_COMMON->CSTS, ADC_CSTS_INJEOCFLG3) == (ADC_CSTS_INJEOCFLG3)); +} + +/** + * @brief Get flag multimode ADC analog watchdog 1 of the ADC master. + * @param ADCxy_COMMON ADC common instance + * (can be set directly from CMSIS definition or by using helper macro @ref __DDL_ADC_COMMON_INSTANCE() ) + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_ADC_IsActiveFlag_MST_AWD1(ADC_Common_TypeDef *ADCxy_COMMON) +{ + return (READ_BIT(ADCxy_COMMON->CSTS, DDL_ADC_FLAG_AWD1_MST) == (DDL_ADC_FLAG_AWD1_MST)); +} + +/** + * @brief Get flag multimode analog watchdog 1 of the ADC slave 1. + * @param ADCxy_COMMON ADC common instance + * (can be set directly from CMSIS definition or by using helper macro @ref __DDL_ADC_COMMON_INSTANCE() ) + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_ADC_IsActiveFlag_SLV1_AWD1(ADC_Common_TypeDef *ADCxy_COMMON) +{ + return (READ_BIT(ADCxy_COMMON->CSTS, DDL_ADC_FLAG_AWD1_SLV1) == (DDL_ADC_FLAG_AWD1_SLV1)); +} + +/** + * @brief Get flag multimode analog watchdog 1 of the ADC slave 2. + * @param ADCxy_COMMON ADC common instance + * (can be set directly from CMSIS definition or by using helper macro @ref __DDL_ADC_COMMON_INSTANCE() ) + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_ADC_IsActiveFlag_SLV2_AWD1(ADC_Common_TypeDef *ADCxy_COMMON) +{ + return (READ_BIT(ADCxy_COMMON->CSTS, DDL_ADC_FLAG_AWD1_SLV2) == (DDL_ADC_FLAG_AWD1_SLV2)); +} + +#endif /* ADC_MULTIMODE_SUPPORT */ + +/** + * @} + */ + +/** @defgroup ADC_DDL_EF_IT_Management ADC IT management + * @{ + */ + +/** + * @brief Enable interruption ADC group regular end of unitary conversion + * or end of sequence conversions, depending on + * ADC configuration. + * @note To configure flag of end of conversion, + * use function @ref DDL_ADC_REG_SetFlagEndOfConversion(). + * @param ADCx ADC instance + * @retval None + */ +__STATIC_INLINE void DDL_ADC_EnableIT_EOCS(ADC_TypeDef *ADCx) +{ + SET_BIT(ADCx->CTRL1, DDL_ADC_IT_EOCS); +} + +/** + * @brief Enable ADC group regular interruption overrun. + * @param ADCx ADC instance + * @retval None + */ +__STATIC_INLINE void DDL_ADC_EnableIT_OVR(ADC_TypeDef *ADCx) +{ + SET_BIT(ADCx->CTRL1, DDL_ADC_IT_OVR); +} + + +/** + * @brief Enable interruption ADC group injected end of sequence conversions. + * @param ADCx ADC instance + * @retval None + */ +__STATIC_INLINE void DDL_ADC_EnableIT_JEOS(ADC_TypeDef *ADCx) +{ + /* Note: on this APM32 series, there is no flag ADC group injected */ + /* end of unitary conversion. */ + /* Flag noted as "JEOC" is corresponding to flag "JEOS" */ + /* in other APM32 families). */ + SET_BIT(ADCx->CTRL1, DDL_ADC_IT_JEOS); +} + +/** + * @brief Enable interruption ADC analog watchdog 1. + * @param ADCx ADC instance + * @retval None + */ +__STATIC_INLINE void DDL_ADC_EnableIT_AWD1(ADC_TypeDef *ADCx) +{ + SET_BIT(ADCx->CTRL1, DDL_ADC_IT_AWD1); +} + +/** + * @brief Disable interruption ADC group regular end of unitary conversion + * or end of sequence conversions, depending on + * ADC configuration. + * @note To configure flag of end of conversion, + * use function @ref DDL_ADC_REG_SetFlagEndOfConversion(). + * @param ADCx ADC instance + * @retval None + */ +__STATIC_INLINE void DDL_ADC_DisableIT_EOCS(ADC_TypeDef *ADCx) +{ + CLEAR_BIT(ADCx->CTRL1, DDL_ADC_IT_EOCS); +} + +/** + * @brief Disable interruption ADC group regular overrun. + * @param ADCx ADC instance + * @retval None + */ +__STATIC_INLINE void DDL_ADC_DisableIT_OVR(ADC_TypeDef *ADCx) +{ + CLEAR_BIT(ADCx->CTRL1, DDL_ADC_IT_OVR); +} + + +/** + * @brief Disable interruption ADC group injected end of sequence conversions. + * @param ADCx ADC instance + * @retval None + */ +__STATIC_INLINE void DDL_ADC_DisableIT_JEOS(ADC_TypeDef *ADCx) +{ + /* Note: on this APM32 series, there is no flag ADC group injected */ + /* end of unitary conversion. */ + /* Flag noted as "JEOC" is corresponding to flag "JEOS" */ + /* in other APM32 families). */ + CLEAR_BIT(ADCx->CTRL1, DDL_ADC_IT_JEOS); +} + +/** + * @brief Disable interruption ADC analog watchdog 1. + * @param ADCx ADC instance + * @retval None + */ +__STATIC_INLINE void DDL_ADC_DisableIT_AWD1(ADC_TypeDef *ADCx) +{ + CLEAR_BIT(ADCx->CTRL1, DDL_ADC_IT_AWD1); +} + +/** + * @brief Get state of interruption ADC group regular end of unitary conversion + * or end of sequence conversions, depending on + * ADC configuration. + * @note To configure flag of end of conversion, + * use function @ref DDL_ADC_REG_SetFlagEndOfConversion(). + * (0: interrupt disabled, 1: interrupt enabled) + * @param ADCx ADC instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_ADC_IsEnabledIT_EOCS(ADC_TypeDef *ADCx) +{ + return (READ_BIT(ADCx->CTRL1, DDL_ADC_IT_EOCS) == (DDL_ADC_IT_EOCS)); +} + +/** + * @brief Get state of interruption ADC group regular overrun + * (0: interrupt disabled, 1: interrupt enabled). + * @param ADCx ADC instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_ADC_IsEnabledIT_OVR(ADC_TypeDef *ADCx) +{ + return (READ_BIT(ADCx->CTRL1, DDL_ADC_IT_OVR) == (DDL_ADC_IT_OVR)); +} + + +/** + * @brief Get state of interruption ADC group injected end of sequence conversions + * (0: interrupt disabled, 1: interrupt enabled). + * @param ADCx ADC instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_ADC_IsEnabledIT_JEOS(ADC_TypeDef *ADCx) +{ + /* Note: on this APM32 series, there is no flag ADC group injected */ + /* end of unitary conversion. */ + /* Flag noted as "JEOC" is corresponding to flag "JEOS" */ + /* in other APM32 families). */ + return (READ_BIT(ADCx->CTRL1, DDL_ADC_IT_JEOS) == (DDL_ADC_IT_JEOS)); +} + +/** + * @brief Get state of interruption ADC analog watchdog 1 + * (0: interrupt disabled, 1: interrupt enabled). + * @param ADCx ADC instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_ADC_IsEnabledIT_AWD1(ADC_TypeDef *ADCx) +{ + return (READ_BIT(ADCx->CTRL1, DDL_ADC_IT_AWD1) == (DDL_ADC_IT_AWD1)); +} + +/** + * @} + */ + +#if defined(USE_FULL_DDL_DRIVER) +/** @defgroup ADC_DDL_EF_Init Initialization and de-initialization functions + * @{ + */ + +/* Initialization of some features of ADC common parameters and multimode */ +ErrorStatus DDL_ADC_CommonDeInit(ADC_Common_TypeDef *ADCxy_COMMON); +ErrorStatus DDL_ADC_CommonInit(ADC_Common_TypeDef *ADCxy_COMMON, DDL_ADC_CommonInitTypeDef *ADC_CommonInitStruct); +void DDL_ADC_CommonStructInit(DDL_ADC_CommonInitTypeDef *ADC_CommonInitStruct); + +/* De-initialization of ADC instance, ADC group regular and ADC group injected */ +/* (availability of ADC group injected depends on APM32 families) */ +ErrorStatus DDL_ADC_DeInit(ADC_TypeDef *ADCx); + +/* Initialization of some features of ADC instance */ +ErrorStatus DDL_ADC_Init(ADC_TypeDef *ADCx, DDL_ADC_InitTypeDef *ADC_InitStruct); +void DDL_ADC_StructInit(DDL_ADC_InitTypeDef *ADC_InitStruct); + +/* Initialization of some features of ADC instance and ADC group regular */ +ErrorStatus DDL_ADC_REG_Init(ADC_TypeDef *ADCx, DDL_ADC_REG_InitTypeDef *ADC_REG_InitStruct); +void DDL_ADC_REG_StructInit(DDL_ADC_REG_InitTypeDef *ADC_REG_InitStruct); + +/* Initialization of some features of ADC instance and ADC group injected */ +ErrorStatus DDL_ADC_INJ_Init(ADC_TypeDef *ADCx, DDL_ADC_INJ_InitTypeDef *ADC_INJ_InitStruct); +void DDL_ADC_INJ_StructInit(DDL_ADC_INJ_InitTypeDef *ADC_INJ_InitStruct); + +/** + * @} + */ +#endif /* USE_FULL_DDL_DRIVER */ + +/** + * @} + */ + +/** + * @} + */ + +#endif /* ADC1 || ADC2 || ADC3 */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* APM32F4xx_DDL_ADC_H */ + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_bus.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_bus.h new file mode 100644 index 0000000000..141766d4d6 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_bus.h @@ -0,0 +1,1433 @@ +/** + * + * @file apm32f4xx_ddl_bus.h + * @brief Header file of BUS DDL module. + + @verbatim + ##### RCM Limitations ##### + ============================================================================== + [..] + A delay between an RCM peripheral clock enable and the effective peripheral + enabling should be taken into account in order to manage the peripheral read/write + from/to registers. + (+) This delay depends on the peripheral mapping. + (++) AHB & APB peripherals, 1 dummy read is necessary + + [..] + Workarounds: + (#) For AHB & APB peripherals, a dummy read to the peripheral register has been + inserted in each DDL_{BUS}_GRP{x}_EnableClock() function. + + @endverbatim + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2017 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file in + * the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef APM32F4xx_DDL_BUS_H +#define APM32F4xx_DDL_BUS_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx.h" + +/** @addtogroup APM32F4xx_DDL_Driver + * @{ + */ + +#if defined(RCM) + +/** @defgroup BUS_DDL BUS + * @{ + */ + +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/* Private macros ------------------------------------------------------------*/ +/* Exported types ------------------------------------------------------------*/ +/* Exported constants --------------------------------------------------------*/ +/** @defgroup BUS_DDL_Exported_Constants BUS Exported Constants + * @{ + */ + +/** @defgroup BUS_DDL_EC_AHB1_GRP1_PERIPH AHB1 GRP1 PERIPH + * @{ + */ +#define DDL_AHB1_GRP1_PERIPH_ALL 0xFFFFFFFFU +#define DDL_AHB1_GRP1_PERIPH_GPIOA RCM_AHB1CLKEN_PAEN +#define DDL_AHB1_GRP1_PERIPH_GPIOB RCM_AHB1CLKEN_PBEN +#define DDL_AHB1_GRP1_PERIPH_GPIOC RCM_AHB1CLKEN_PCEN +#if defined(GPIOD) +#define DDL_AHB1_GRP1_PERIPH_GPIOD RCM_AHB1CLKEN_PDEN +#endif /* GPIOD */ +#if defined(GPIOE) +#define DDL_AHB1_GRP1_PERIPH_GPIOE RCM_AHB1CLKEN_PEEN +#endif /* GPIOE */ +#if defined(GPIOF) +#define DDL_AHB1_GRP1_PERIPH_GPIOF RCM_AHB1CLKEN_PFEN +#endif /* GPIOF */ +#if defined(GPIOG) +#define DDL_AHB1_GRP1_PERIPH_GPIOG RCM_AHB1CLKEN_PGEN +#endif /* GPIOG */ +#if defined(GPIOH) +#define DDL_AHB1_GRP1_PERIPH_GPIOH RCM_AHB1CLKEN_PHEN +#endif /* GPIOH */ +#if defined(GPIOI) +#define DDL_AHB1_GRP1_PERIPH_GPIOI RCM_AHB1CLKEN_PIEN +#endif /* GPIOI */ +#if defined(GPIOJ) +#define DDL_AHB1_GRP1_PERIPH_GPIOJ RCM_AHB1CLKEN_GPIOJEN +#endif /* GPIOJ */ +#if defined(GPIOK) +#define DDL_AHB1_GRP1_PERIPH_GPIOK RCM_AHB1CLKEN_GPIOKEN +#endif /* GPIOK */ +#define DDL_AHB1_GRP1_PERIPH_CRC RCM_AHB1CLKEN_CRCEN +#if defined(RCM_AHB1CLKEN_BKPSRAMEN) +#define DDL_AHB1_GRP1_PERIPH_BKPSRAM RCM_AHB1CLKEN_BKPSRAMEN +#endif /* RCM_AHB1CLKEN_BKPSRAMEN */ +#if defined(RCM_AHB1CLKEN_DRAMEN) +#define DDL_AHB1_GRP1_PERIPH_CCMDATARAM RCM_AHB1CLKEN_DRAMEN +#endif /* RCM_AHB1CLKEN_DRAMEN */ +#define DDL_AHB1_GRP1_PERIPH_DMA1 RCM_AHB1CLKEN_DMA1EN +#define DDL_AHB1_GRP1_PERIPH_DMA2 RCM_AHB1CLKEN_DMA2EN +#if defined(RCM_AHB1CLKEN_RNGEN) +#define DDL_AHB1_GRP1_PERIPH_RNG RCM_AHB1CLKEN_RNGEN +#endif /* RCM_AHB1CLKEN_RNGEN */ +#if defined(ETH) +#define DDL_AHB1_GRP1_PERIPH_ETHMAC RCM_AHB1CLKEN_ETHEN +#define DDL_AHB1_GRP1_PERIPH_ETHMACTX RCM_AHB1CLKEN_ETHTXEN +#define DDL_AHB1_GRP1_PERIPH_ETHMACRX RCM_AHB1CLKEN_ETHRXEN +#define DDL_AHB1_GRP1_PERIPH_ETHMACPTP RCM_AHB1CLKEN_ETHPTPEN +#endif /* ETH */ +#if defined(USB_OTG_HS) +#define DDL_AHB1_GRP1_PERIPH_OTGHS RCM_AHB1CLKEN_OTGHS1EN +#define DDL_AHB1_GRP1_PERIPH_OTGHSULPI RCM_AHB1CLKEN_OTGHSULPIEN +#endif /* USB_OTG_HS */ +#define DDL_AHB1_GRP1_PERIPH_FLITF RCM_LPAHB1CLKEN_FMCEN +#define DDL_AHB1_GRP1_PERIPH_SRAM1 RCM_LPAHB1CLKEN_SRAM1EN +#if defined(RCM_LPAHB1CLKEN_SRAM2EN) +#define DDL_AHB1_GRP1_PERIPH_SRAM2 RCM_LPAHB1CLKEN_SRAM2EN +#endif /* RCM_LPAHB1CLKEN_SRAM2EN */ +#if defined(RCM_LPAHB1CLKEN_SRAM3LPEN) +#define DDL_AHB1_GRP1_PERIPH_SRAM3 RCM_LPAHB1CLKEN_SRAM3LPEN +#endif /* RCM_LPAHB1CLKEN_SRAM3LPEN */ +/** + * @} + */ + +#if defined(RCM_AHB2_SUPPORT) +/** @defgroup BUS_DDL_EC_AHB2_GRP1_PERIPH AHB2 GRP1 PERIPH + * @{ + */ +#define DDL_AHB2_GRP1_PERIPH_ALL 0xFFFFFFFFU +#if defined(DCI) +#define DDL_AHB2_GRP1_PERIPH_DCI RCM_AHB2CLKEN_DCIEN +#endif /* DCI */ + +#define DDL_AHB2_GRP1_PERIPH_FPU RCM_AHB2CLKEN_FPUEN +#if defined(BN) +#define DDL_AHB2_GRP1_PERIPH_BN RCM_AHB2CLKEN_BNEN +#endif /* BN */ + +#if defined(SM3) || defined(SM4) +#define DDL_AHB2_GRP1_PERIPH_SM RCM_AHB2CLKEN_SMEN +#endif /* SM3 || SM4 */ + +#if defined(CRYP) +#define DDL_AHB2_GRP1_PERIPH_CRYP RCM_AHB2CLKEN_CRYPEN +#endif /* CRYP */ +#if defined(HASH) +#define DDL_AHB2_GRP1_PERIPH_HASH RCM_AHB2CLKEN_HASHEN +#endif /* HASH */ +#if defined(RCM_AHB2CLKEN_RNGEN) +#define DDL_AHB2_GRP1_PERIPH_RNG RCM_AHB2CLKEN_RNGEN +#endif /* RCM_AHB2CLKEN_RNGEN */ +#if defined(USB_OTG_FS) +#define DDL_AHB2_GRP1_PERIPH_OTGFS RCM_AHB2CLKEN_OTGFSEN +#endif /* USB_OTG_FS */ +#if defined(QSPI) +#define DDL_AHB2_GRP1_PERIPH_QSPI RCM_AHB2CLKEN_QSPIEN +#endif /* QSPI */ +#if defined(SMC_Bank1) +#define DDL_AHB2_GRP1_PERIPH_SMC RCM_AHB2CLKEN_SMCEN +#endif /* SMC_Bank1 */ +/** + * @} + */ +#endif /* RCM_AHB2_SUPPORT */ + +#if defined(RCM_AHB3_SUPPORT) +/** @defgroup BUS_DDL_EC_AHB3_GRP1_PERIPH AHB3 GRP1 PERIPH + * @{ + */ +#define DDL_AHB3_GRP1_PERIPH_ALL 0xFFFFFFFFU +#if defined(SMC_Bank1) +#define DDL_AHB3_GRP1_PERIPH_EMMC RCM_AHB3CLKEN_EMMCEN +#endif /* SMC_Bank1 */ +/** + * @} + */ +#endif /* RCM_AHB3_SUPPORT */ + +/** @defgroup BUS_DDL_EC_APB1_GRP1_PERIPH APB1 GRP1 PERIPH + * @{ + */ +#define DDL_APB1_GRP1_PERIPH_ALL 0xFFFFFFFFU +#if defined(TMR2) +#define DDL_APB1_GRP1_PERIPH_TMR2 RCM_APB1CLKEN_TMR2EN +#endif /* TMR2 */ +#if defined(TMR3) +#define DDL_APB1_GRP1_PERIPH_TMR3 RCM_APB1CLKEN_TMR3EN +#endif /* TMR3 */ +#if defined(TMR4) +#define DDL_APB1_GRP1_PERIPH_TMR4 RCM_APB1CLKEN_TMR4EN +#endif /* TMR4 */ +#define DDL_APB1_GRP1_PERIPH_TMR5 RCM_APB1CLKEN_TMR5EN +#if defined(TMR6) +#define DDL_APB1_GRP1_PERIPH_TMR6 RCM_APB1CLKEN_TMR6EN +#endif /* TMR6 */ +#if defined(TMR7) +#define DDL_APB1_GRP1_PERIPH_TMR7 RCM_APB1CLKEN_TMR7EN +#endif /* TMR7 */ +#if defined(TMR12) +#define DDL_APB1_GRP1_PERIPH_TMR12 RCM_APB1CLKEN_TMR12EN +#endif /* TMR12 */ +#if defined(TMR13) +#define DDL_APB1_GRP1_PERIPH_TMR13 RCM_APB1CLKEN_TMR13EN +#endif /* TMR13 */ +#if defined(TMR14) +#define DDL_APB1_GRP1_PERIPH_TMR14 RCM_APB1CLKEN_TMR14EN +#endif /* TMR14 */ +#if defined(RCM_APB1CLKEN_RTCAPBEN) +#define DDL_APB1_GRP1_PERIPH_RTCAPB RCM_APB1CLKEN_RTCAPBEN +#endif /* RCM_APB1CLKEN_RTCAPBEN */ +#define DDL_APB1_GRP1_PERIPH_WWDT RCM_APB1CLKEN_WWDTEN +#if defined(SPI2) +#define DDL_APB1_GRP1_PERIPH_SPI2 RCM_APB1CLKEN_SPI2EN +#endif /* SPI2 */ +#if defined(SPI3) +#define DDL_APB1_GRP1_PERIPH_SPI3 RCM_APB1CLKEN_SPI3EN +#endif /* SPI3 */ +#define DDL_APB1_GRP1_PERIPH_USART2 RCM_APB1CLKEN_USART2EN +#if defined(USART3) +#define DDL_APB1_GRP1_PERIPH_USART3 RCM_APB1CLKEN_USART3EN +#endif /* USART3 */ +#if defined(UART4) +#define DDL_APB1_GRP1_PERIPH_UART4 RCM_APB1CLKEN_UART4EN +#endif /* UART4 */ +#if defined(UART5) +#define DDL_APB1_GRP1_PERIPH_UART5 RCM_APB1CLKEN_UART5EN +#endif /* UART5 */ +#define DDL_APB1_GRP1_PERIPH_I2C1 RCM_APB1CLKEN_I2C1EN +#define DDL_APB1_GRP1_PERIPH_I2C2 RCM_APB1CLKEN_I2C2EN +#if defined(I2C3) +#define DDL_APB1_GRP1_PERIPH_I2C3 RCM_APB1CLKEN_I2C3EN +#endif /* I2C3 */ +#if defined(CAN1) +#define DDL_APB1_GRP1_PERIPH_CAN1 RCM_APB1CLKEN_CAN1EN +#endif /* CAN1 */ +#if defined(CAN2) +#define DDL_APB1_GRP1_PERIPH_CAN2 RCM_APB1CLKEN_CAN2EN +#endif /* CAN2 */ +#if defined(CAN3) +#define DDL_APB1_GRP1_PERIPH_CAN3 RCM_APB1CLKEN_CAN3EN +#endif /* CAN3 */ +#define DDL_APB1_GRP1_PERIPH_PMU RCM_APB1CLKEN_PMUEN +#if defined(DAC1) +#define DDL_APB1_GRP1_PERIPH_DAC1 RCM_APB1CLKEN_DACEN +#endif /* DAC1 */ +#if defined(UART7) +#define DDL_APB1_GRP1_PERIPH_UART7 RCM_APB1CLKEN_UART7EN +#endif /* UART7 */ +#if defined(UART8) +#define DDL_APB1_GRP1_PERIPH_UART8 RCM_APB1CLKEN_UART8EN +#endif /* UART8 */ +/** + * @} + */ + +/** @defgroup BUS_DDL_EC_APB2_GRP1_PERIPH APB2 GRP1 PERIPH + * @{ + */ +#define DDL_APB2_GRP1_PERIPH_ALL 0xFFFFFFFFU +#define DDL_APB2_GRP1_PERIPH_TMR1 RCM_APB2CLKEN_TMR1EN +#if defined(TMR8) +#define DDL_APB2_GRP1_PERIPH_TMR8 RCM_APB2CLKEN_TMR8EN +#endif /* TMR8 */ +#define DDL_APB2_GRP1_PERIPH_USART1 RCM_APB2CLKEN_USART1EN +#if defined(USART6) +#define DDL_APB2_GRP1_PERIPH_USART6 RCM_APB2CLKEN_USART6EN +#endif /* USART6 */ +#if defined(UART9) +#define DDL_APB2_GRP1_PERIPH_UART9 RCM_APB2CLKEN_UART9EN +#endif /* UART9 */ +#if defined(UART10) +#define DDL_APB2_GRP1_PERIPH_UART10 RCM_APB2CLKEN_UART10EN +#endif /* UART10 */ +#define DDL_APB2_GRP1_PERIPH_ADC1 RCM_APB2CLKEN_ADC1EN +#if defined(ADC2) +#define DDL_APB2_GRP1_PERIPH_ADC2 RCM_APB2CLKEN_ADC2EN +#endif /* ADC2 */ +#if defined(ADC3) +#define DDL_APB2_GRP1_PERIPH_ADC3 RCM_APB2CLKEN_ADC3EN +#endif /* ADC3 */ +#if defined(SDIO) +#define DDL_APB2_GRP1_PERIPH_SDIO RCM_APB2CLKEN_SDIOEN +#endif /* SDIO */ +#define DDL_APB2_GRP1_PERIPH_SPI1 RCM_APB2CLKEN_SPI1EN +#if defined(SPI4) +#define DDL_APB2_GRP1_PERIPH_SPI4 RCM_APB2CLKEN_SPI4EN +#endif /* SPI4 */ +#define DDL_APB2_GRP1_PERIPH_SYSCFG RCM_APB2CLKEN_SYSCFGEN +#if defined(RCM_APB2CLKEN_EINTEN) +#define DDL_APB2_GRP1_PERIPH_EINT RCM_APB2CLKEN_EINTEN +#endif /* RCM_APB2CLKEN_EINTEN */ +#define DDL_APB2_GRP1_PERIPH_TMR9 RCM_APB2CLKEN_TMR9EN +#if defined(TMR10) +#define DDL_APB2_GRP1_PERIPH_TMR10 RCM_APB2CLKEN_TMR10EN +#endif /* TMR10 */ +#define DDL_APB2_GRP1_PERIPH_TMR11 RCM_APB2CLKEN_TMR11EN +#if defined(SPI5) +#define DDL_APB2_GRP1_PERIPH_SPI5 RCM_APB2CLKEN_SPI5EN +#endif /* SPI5 */ +#if defined(SPI6) +#define DDL_APB2_GRP1_PERIPH_SPI6 RCM_APB2CLKEN_SPI6EN +#endif /* SPI6 */ +#if defined(COMP1) || defined(COMP2) +#define DDL_APB2_GRP1_PERIPH_COMP RCM_APB2CLKEN_SYSCFGEN +#endif /* COMP1 || COMP2 */ +#define DDL_APB2_GRP1_PERIPH_ADC RCM_APB2RST_ADCRST +/** + * @} + */ + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ +/* Exported functions --------------------------------------------------------*/ +/** @defgroup BUS_DDL_Exported_Functions BUS Exported Functions + * @{ + */ + +/** @defgroup BUS_DDL_EF_AHB1 AHB1 + * @{ + */ + +/** + * @brief Enable AHB1 peripherals clock. + * @param Periphs This parameter can be a combination of the following values: + * @arg @ref DDL_AHB1_GRP1_PERIPH_GPIOA + * @arg @ref DDL_AHB1_GRP1_PERIPH_GPIOB + * @arg @ref DDL_AHB1_GRP1_PERIPH_GPIOC + * @arg @ref DDL_AHB1_GRP1_PERIPH_GPIOD (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_GPIOE (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_GPIOF (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_GPIOG (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_GPIOH (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_GPIOI (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_GPIOJ (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_GPIOK (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_CRC + * @arg @ref DDL_AHB1_GRP1_PERIPH_BKPSRAM (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_CCMDATARAM (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_DMA1 + * @arg @ref DDL_AHB1_GRP1_PERIPH_DMA2 + * @arg @ref DDL_AHB1_GRP1_PERIPH_RNG (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_ETHMAC (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_ETHMACTX (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_ETHMACRX (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_ETHMACPTP (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_OTGHS (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_OTGHSULPI (*) + * + * (*) value not defined in all devices. + * @retval None +*/ +__STATIC_INLINE void DDL_AHB1_GRP1_EnableClock(uint32_t Periphs) +{ + __IO uint32_t tmpreg; + SET_BIT(RCM->AHB1CLKEN, Periphs); + /* Delay after an RCM peripheral clock enabling */ + tmpreg = READ_BIT(RCM->AHB1CLKEN, Periphs); + (void)tmpreg; +} + +/** + * @brief Check if AHB1 peripheral clock is enabled or not + * @param Periphs This parameter can be a combination of the following values: + * @arg @ref DDL_AHB1_GRP1_PERIPH_GPIOA + * @arg @ref DDL_AHB1_GRP1_PERIPH_GPIOB + * @arg @ref DDL_AHB1_GRP1_PERIPH_GPIOC + * @arg @ref DDL_AHB1_GRP1_PERIPH_GPIOD (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_GPIOE (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_GPIOF (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_GPIOG (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_GPIOH (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_GPIOI (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_GPIOJ (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_GPIOK (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_CRC + * @arg @ref DDL_AHB1_GRP1_PERIPH_BKPSRAM (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_CCMDATARAM (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_DMA1 + * @arg @ref DDL_AHB1_GRP1_PERIPH_DMA2 + * @arg @ref DDL_AHB1_GRP1_PERIPH_RNG (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_ETHMAC (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_ETHMACTX (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_ETHMACRX (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_ETHMACPTP (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_OTGHS (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_OTGHSULPI (*) + * + * (*) value not defined in all devices. + * @retval State of Periphs (1 or 0). +*/ +__STATIC_INLINE uint32_t DDL_AHB1_GRP1_IsEnabledClock(uint32_t Periphs) +{ + return (READ_BIT(RCM->AHB1CLKEN, Periphs) == Periphs); +} + +/** + * @brief Disable AHB1 peripherals clock. + * @param Periphs This parameter can be a combination of the following values: + * @arg @ref DDL_AHB1_GRP1_PERIPH_GPIOA + * @arg @ref DDL_AHB1_GRP1_PERIPH_GPIOB + * @arg @ref DDL_AHB1_GRP1_PERIPH_GPIOC + * @arg @ref DDL_AHB1_GRP1_PERIPH_GPIOD (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_GPIOE (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_GPIOF (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_GPIOG (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_GPIOH (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_GPIOI (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_GPIOJ (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_GPIOK (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_CRC + * @arg @ref DDL_AHB1_GRP1_PERIPH_BKPSRAM (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_CCMDATARAM (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_DMA1 + * @arg @ref DDL_AHB1_GRP1_PERIPH_DMA2 + * @arg @ref DDL_AHB1_GRP1_PERIPH_RNG (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_ETHMAC (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_ETHMACTX (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_ETHMACRX (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_ETHMACPTP (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_OTGHS (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_OTGHSULPI (*) + * + * (*) value not defined in all devices. + * @retval None +*/ +__STATIC_INLINE void DDL_AHB1_GRP1_DisableClock(uint32_t Periphs) +{ + CLEAR_BIT(RCM->AHB1CLKEN, Periphs); +} + +/** + * @brief Force AHB1 peripherals reset. + * @param Periphs This parameter can be a combination of the following values: + * @arg @ref DDL_AHB1_GRP1_PERIPH_ALL + * @arg @ref DDL_AHB1_GRP1_PERIPH_GPIOA + * @arg @ref DDL_AHB1_GRP1_PERIPH_GPIOB + * @arg @ref DDL_AHB1_GRP1_PERIPH_GPIOC + * @arg @ref DDL_AHB1_GRP1_PERIPH_GPIOD (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_GPIOE (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_GPIOF (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_GPIOG (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_GPIOH (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_GPIOI (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_GPIOJ (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_GPIOK (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_CRC + * @arg @ref DDL_AHB1_GRP1_PERIPH_DMA1 + * @arg @ref DDL_AHB1_GRP1_PERIPH_DMA2 + * @arg @ref DDL_AHB1_GRP1_PERIPH_RNG (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_ETHMAC (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_OTGHS (*) + * + * (*) value not defined in all devices. + * @retval None +*/ +__STATIC_INLINE void DDL_AHB1_GRP1_ForceReset(uint32_t Periphs) +{ + SET_BIT(RCM->AHB1RST, Periphs); +} + +/** + * @brief Release AHB1 peripherals reset. + * @param Periphs This parameter can be a combination of the following values: + * @arg @ref DDL_AHB1_GRP1_PERIPH_ALL + * @arg @ref DDL_AHB1_GRP1_PERIPH_GPIOA + * @arg @ref DDL_AHB1_GRP1_PERIPH_GPIOB + * @arg @ref DDL_AHB1_GRP1_PERIPH_GPIOC + * @arg @ref DDL_AHB1_GRP1_PERIPH_GPIOD (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_GPIOE (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_GPIOF (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_GPIOG (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_GPIOH (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_GPIOI (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_GPIOJ (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_GPIOK (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_CRC + * @arg @ref DDL_AHB1_GRP1_PERIPH_DMA1 + * @arg @ref DDL_AHB1_GRP1_PERIPH_DMA2 + * @arg @ref DDL_AHB1_GRP1_PERIPH_RNG (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_ETHMAC (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_OTGHS (*) + * + * (*) value not defined in all devices. + * @retval None +*/ +__STATIC_INLINE void DDL_AHB1_GRP1_ReleaseReset(uint32_t Periphs) +{ + CLEAR_BIT(RCM->AHB1RST, Periphs); +} + +/** + * @brief Enable AHB1 peripheral clocks in low-power mode + * @param Periphs This parameter can be a combination of the following values: + * @arg @ref DDL_AHB1_GRP1_PERIPH_GPIOA + * @arg @ref DDL_AHB1_GRP1_PERIPH_GPIOB + * @arg @ref DDL_AHB1_GRP1_PERIPH_GPIOC + * @arg @ref DDL_AHB1_GRP1_PERIPH_GPIOD (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_GPIOE (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_GPIOF (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_GPIOG (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_GPIOH (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_GPIOI (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_GPIOJ (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_GPIOK (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_CRC + * @arg @ref DDL_AHB1_GRP1_PERIPH_BKPSRAM (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_FLITF + * @arg @ref DDL_AHB1_GRP1_PERIPH_SRAM1 + * @arg @ref DDL_AHB1_GRP1_PERIPH_SRAM2 (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_SRAM3 (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_DMA1 + * @arg @ref DDL_AHB1_GRP1_PERIPH_DMA2 + * @arg @ref DDL_AHB1_GRP1_PERIPH_RNG (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_ETHMAC (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_ETHMACTX (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_ETHMACRX (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_ETHMACPTP (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_OTGHS (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_OTGHSULPI (*) + * + * (*) value not defined in all devices. + * @retval None +*/ +__STATIC_INLINE void DDL_AHB1_GRP1_EnableClockLowPower(uint32_t Periphs) +{ + __IO uint32_t tmpreg; + SET_BIT(RCM->LPAHB1CLKEN, Periphs); + /* Delay after an RCM peripheral clock enabling */ + tmpreg = READ_BIT(RCM->LPAHB1CLKEN, Periphs); + (void)tmpreg; +} + +/** + * @brief Disable AHB1 peripheral clocks in low-power mode + * @param Periphs This parameter can be a combination of the following values: + * @arg @ref DDL_AHB1_GRP1_PERIPH_GPIOA + * @arg @ref DDL_AHB1_GRP1_PERIPH_GPIOB + * @arg @ref DDL_AHB1_GRP1_PERIPH_GPIOC + * @arg @ref DDL_AHB1_GRP1_PERIPH_GPIOD (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_GPIOE (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_GPIOF (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_GPIOG (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_GPIOH (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_GPIOI (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_GPIOJ (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_GPIOK (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_CRC + * @arg @ref DDL_AHB1_GRP1_PERIPH_BKPSRAM (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_FLITF + * @arg @ref DDL_AHB1_GRP1_PERIPH_SRAM1 + * @arg @ref DDL_AHB1_GRP1_PERIPH_SRAM2 (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_SRAM3 (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_DMA1 + * @arg @ref DDL_AHB1_GRP1_PERIPH_DMA2 + * @arg @ref DDL_AHB1_GRP1_PERIPH_RNG (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_ETHMAC (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_ETHMACTX (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_ETHMACRX (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_ETHMACPTP (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_OTGHS (*) + * @arg @ref DDL_AHB1_GRP1_PERIPH_OTGHSULPI (*) + * + * (*) value not defined in all devices. + * @retval None +*/ +__STATIC_INLINE void DDL_AHB1_GRP1_DisableClockLowPower(uint32_t Periphs) +{ + CLEAR_BIT(RCM->LPAHB1CLKEN, Periphs); +} + +/** + * @} + */ + +#if defined(RCM_AHB2_SUPPORT) +/** @defgroup BUS_DDL_EF_AHB2 AHB2 + * @{ + */ + +/** + * @brief Enable AHB2 peripherals clock. + * @param Periphs This parameter can be a combination of the following values: + * @arg @ref DDL_AHB2_GRP1_PERIPH_DCI (*) + * @arg @ref DDL_AHB2_GRP1_PERIPH_FPU (*) + * @arg @ref DDL_AHB2_GRP1_PERIPH_CRYP (*) + * @arg @ref DDL_AHB2_GRP1_PERIPH_HASH (*) + * @arg @ref DDL_AHB2_GRP1_PERIPH_RNG (*) + * @arg @ref DDL_AHB2_GRP1_PERIPH_OTGFS (*) + * @arg @ref DDL_AHB2_GRP1_PERIPH_QSPI (*) + * @arg @ref DDL_AHB2_GRP1_PERIPH_SMC (*) + * + * (*) value not defined in all devices. + * @retval None + * @note The SMC peripheral is available only in APM32F411xx devices. +*/ +__STATIC_INLINE void DDL_AHB2_GRP1_EnableClock(uint32_t Periphs) +{ + __IO uint32_t tmpreg; + SET_BIT(RCM->AHB2CLKEN, Periphs); + /* Delay after an RCM peripheral clock enabling */ + tmpreg = READ_BIT(RCM->AHB2CLKEN, Periphs); + (void)tmpreg; +} + +/** + * @brief Check if AHB2 peripheral clock is enabled or not + * @param Periphs This parameter can be a combination of the following values: + * @arg @ref DDL_AHB2_GRP1_PERIPH_DCI (*) + * @arg @ref DDL_AHB2_GRP1_PERIPH_FPU (*) + * @arg @ref DDL_AHB2_GRP1_PERIPH_CRYP (*) + * @arg @ref DDL_AHB2_GRP1_PERIPH_HASH (*) + * @arg @ref DDL_AHB2_GRP1_PERIPH_RNG (*) + * @arg @ref DDL_AHB2_GRP1_PERIPH_OTGFS (*) + * @arg @ref DDL_AHB2_GRP1_PERIPH_QSPI (*) + * @arg @ref DDL_AHB2_GRP1_PERIPH_SMC (*) + * + * (*) value not defined in all devices. + * @retval State of Periphs (1 or 0). + * @note The AHB2 SMC peripheral is available only in APM32F411xx devices. +*/ +__STATIC_INLINE uint32_t DDL_AHB2_GRP1_IsEnabledClock(uint32_t Periphs) +{ + return (READ_BIT(RCM->AHB2CLKEN, Periphs) == Periphs); +} + +/** + * @brief Disable AHB2 peripherals clock. + * @param Periphs This parameter can be a combination of the following values: + * @arg @ref DDL_AHB2_GRP1_PERIPH_DCI (*) + * @arg @ref DDL_AHB2_GRP1_PERIPH_FPU (*) + * @arg @ref DDL_AHB2_GRP1_PERIPH_CRYP (*) + * @arg @ref DDL_AHB2_GRP1_PERIPH_HASH (*) + * @arg @ref DDL_AHB2_GRP1_PERIPH_RNG (*) + * @arg @ref DDL_AHB2_GRP1_PERIPH_OTGFS (*) + * @arg @ref DDL_AHB2_GRP1_PERIPH_QSPI (*) + * @arg @ref DDL_AHB2_GRP1_PERIPH_SMC (*) + * + * (*) value not defined in all devices. + * @retval None + * @note The AHB2 SMC peripheral is available only in APM32F411xx devices. +*/ +__STATIC_INLINE void DDL_AHB2_GRP1_DisableClock(uint32_t Periphs) +{ + CLEAR_BIT(RCM->AHB2CLKEN, Periphs); +} + +/** + * @brief Force AHB2 peripherals reset. + * @param Periphs This parameter can be a combination of the following values: + * @arg @ref DDL_AHB2_GRP1_PERIPH_ALL + * @arg @ref DDL_AHB2_GRP1_PERIPH_DCI (*) + * @arg @ref DDL_AHB2_GRP1_PERIPH_FPU (*) + * @arg @ref DDL_AHB2_GRP1_PERIPH_CRYP (*) + * @arg @ref DDL_AHB2_GRP1_PERIPH_HASH (*) + * @arg @ref DDL_AHB2_GRP1_PERIPH_RNG (*) + * @arg @ref DDL_AHB2_GRP1_PERIPH_OTGFS (*) + * @arg @ref DDL_AHB2_GRP1_PERIPH_QSPI (*) + * @arg @ref DDL_AHB2_GRP1_PERIPH_SMC (*) + * + * (*) value not defined in all devices. + * @retval None + * @note The AHB2 SMC peripheral is available only in APM32F411xx devices. +*/ +__STATIC_INLINE void DDL_AHB2_GRP1_ForceReset(uint32_t Periphs) +{ + SET_BIT(RCM->AHB2RST, Periphs); +} + +/** + * @brief Release AHB2 peripherals reset. + * @param Periphs This parameter can be a combination of the following values: + * @arg @ref DDL_AHB2_GRP1_PERIPH_ALL + * @arg @ref DDL_AHB2_GRP1_PERIPH_DCI (*) + * @arg @ref DDL_AHB2_GRP1_PERIPH_FPU (*) + * @arg @ref DDL_AHB2_GRP1_PERIPH_CRYP (*) + * @arg @ref DDL_AHB2_GRP1_PERIPH_HASH (*) + * @arg @ref DDL_AHB2_GRP1_PERIPH_RNG (*) + * @arg @ref DDL_AHB2_GRP1_PERIPH_OTGFS (*) + * @arg @ref DDL_AHB2_GRP1_PERIPH_QSPI (*) + * @arg @ref DDL_AHB2_GRP1_PERIPH_SMC (*) + * + * (*) value not defined in all devices. + * @retval None + * @note The AHB2 SMC peripheral is available only in APM32F411xx devices. +*/ +__STATIC_INLINE void DDL_AHB2_GRP1_ReleaseReset(uint32_t Periphs) +{ + CLEAR_BIT(RCM->AHB2RST, Periphs); +} + +/** + * @brief Enable AHB2 peripheral clocks in low-power mode + * @param Periphs This parameter can be a combination of the following values: + * @arg @ref DDL_AHB2_GRP1_PERIPH_DCI (*) + * @arg @ref DDL_AHB2_GRP1_PERIPH_FPU (*) + * @arg @ref DDL_AHB2_GRP1_PERIPH_CRYP (*) + * @arg @ref DDL_AHB2_GRP1_PERIPH_HASH (*) + * @arg @ref DDL_AHB2_GRP1_PERIPH_RNG (*) + * @arg @ref DDL_AHB2_GRP1_PERIPH_OTGFS (*) + * @arg @ref DDL_AHB2_GRP1_PERIPH_QSPI (*) + * @arg @ref DDL_AHB2_GRP1_PERIPH_SMC (*) + * + * (*) value not defined in all devices. + * @retval None + * @note The AHB2 SMC peripheral is available only in APM32F411xx devices. +*/ +__STATIC_INLINE void DDL_AHB2_GRP1_EnableClockLowPower(uint32_t Periphs) +{ + __IO uint32_t tmpreg; + SET_BIT(RCM->LPAHB2CLKEN, Periphs); + /* Delay after an RCM peripheral clock enabling */ + tmpreg = READ_BIT(RCM->LPAHB2CLKEN, Periphs); + (void)tmpreg; +} + +/** + * @brief Disable AHB2 peripheral clocks in low-power mode + * @param Periphs This parameter can be a combination of the following values: + * @arg @ref DDL_AHB2_GRP1_PERIPH_DCI (*) + * @arg @ref DDL_AHB2_GRP1_PERIPH_FPU (*) + * @arg @ref DDL_AHB2_GRP1_PERIPH_CRYP (*) + * @arg @ref DDL_AHB2_GRP1_PERIPH_HASH (*) + * @arg @ref DDL_AHB2_GRP1_PERIPH_RNG (*) + * @arg @ref DDL_AHB2_GRP1_PERIPH_OTGFS (*) + * @arg @ref DDL_AHB2_GRP1_PERIPH_QSPI (*) + * @arg @ref DDL_AHB2_GRP1_PERIPH_SMC (*) + * + * (*) value not defined in all devices. + * @retval None + * @note The AHB2 SMC peripheral is available only in APM32F411xx devices. +*/ +__STATIC_INLINE void DDL_AHB2_GRP1_DisableClockLowPower(uint32_t Periphs) +{ + CLEAR_BIT(RCM->LPAHB2CLKEN, Periphs); +} + +/** + * @} + */ +#endif /* RCM_AHB2_SUPPORT */ + +#if defined(RCM_AHB3_SUPPORT) +/** @defgroup BUS_DDL_EF_AHB3 AHB3 + * @{ + */ + +/** + * @brief Enable AHB3 peripherals clock. + * @param Periphs This parameter can be a combination of the following values: + * @arg @ref DDL_AHB3_GRP1_PERIPH_EMMC (*) + * + * (*) value not defined in all devices. + * @retval None +*/ +__STATIC_INLINE void DDL_AHB3_GRP1_EnableClock(uint32_t Periphs) +{ + __IO uint32_t tmpreg; + SET_BIT(RCM->AHB3CLKEN, Periphs); + /* Delay after an RCM peripheral clock enabling */ + tmpreg = READ_BIT(RCM->AHB3CLKEN, Periphs); + (void)tmpreg; +} + +/** + * @brief Check if AHB3 peripheral clock is enabled or not + * @param Periphs This parameter can be a combination of the following values: + * @arg @ref DDL_AHB3_GRP1_PERIPH_EMMC (*) + * + * (*) value not defined in all devices. + * @retval State of Periphs (1 or 0). +*/ +__STATIC_INLINE uint32_t DDL_AHB3_GRP1_IsEnabledClock(uint32_t Periphs) +{ + return (READ_BIT(RCM->AHB3CLKEN, Periphs) == Periphs); +} + +/** + * @brief Disable AHB3 peripherals clock. + * @param Periphs This parameter can be a combination of the following values: + * @arg @ref DDL_AHB3_GRP1_PERIPH_EMMC (*) + * + * (*) value not defined in all devices. + * @retval None +*/ +__STATIC_INLINE void DDL_AHB3_GRP1_DisableClock(uint32_t Periphs) +{ + CLEAR_BIT(RCM->AHB3CLKEN, Periphs); +} + +/** + * @brief Force AHB3 peripherals reset. + * @param Periphs This parameter can be a combination of the following values: + * @arg @ref DDL_AHB3_GRP1_PERIPH_ALL + * @arg @ref DDL_AHB3_GRP1_PERIPH_EMMC (*) + * + * (*) value not defined in all devices. + * @retval None +*/ +__STATIC_INLINE void DDL_AHB3_GRP1_ForceReset(uint32_t Periphs) +{ + SET_BIT(RCM->AHB3RST, Periphs); +} + +/** + * @brief Release AHB3 peripherals reset. + * @param Periphs This parameter can be a combination of the following values: + * @arg @ref DDL_AHB2_GRP1_PERIPH_ALL + * @arg @ref DDL_AHB3_GRP1_PERIPH_EMMC (*) + * + * (*) value not defined in all devices. + * @retval None +*/ +__STATIC_INLINE void DDL_AHB3_GRP1_ReleaseReset(uint32_t Periphs) +{ + CLEAR_BIT(RCM->AHB3RST, Periphs); +} + +/** + * @brief Enable AHB3 peripheral clocks in low-power mode + * @param Periphs This parameter can be a combination of the following values: + * @arg @ref DDL_AHB3_GRP1_PERIPH_EMMC (*) + * + * (*) value not defined in all devices. + * @retval None +*/ +__STATIC_INLINE void DDL_AHB3_GRP1_EnableClockLowPower(uint32_t Periphs) +{ + __IO uint32_t tmpreg; + SET_BIT(RCM->LPAHB3CLKEN, Periphs); + /* Delay after an RCM peripheral clock enabling */ + tmpreg = READ_BIT(RCM->LPAHB3CLKEN, Periphs); + (void)tmpreg; +} + +/** + * @brief Disable AHB3 peripheral clocks in low-power mode + * @param Periphs This parameter can be a combination of the following values: + * @arg @ref DDL_AHB3_GRP1_PERIPH_EMMC (*) + * + * (*) value not defined in all devices. + * @retval None +*/ +__STATIC_INLINE void DDL_AHB3_GRP1_DisableClockLowPower(uint32_t Periphs) +{ + CLEAR_BIT(RCM->LPAHB3CLKEN, Periphs); +} + +/** + * @} + */ +#endif /* RCM_AHB3_SUPPORT */ + +/** @defgroup BUS_DDL_EF_APB1 APB1 + * @{ + */ + +/** + * @brief Enable APB1 peripherals clock. + * @param Periphs This parameter can be a combination of the following values: + * @arg @ref DDL_APB1_GRP1_PERIPH_TMR2 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_TMR3 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_TMR4 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_TMR5 + * @arg @ref DDL_APB1_GRP1_PERIPH_TMR6 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_TMR7 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_TMR12 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_TMR13 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_TMR14 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_WWDT + * @arg @ref DDL_APB1_GRP1_PERIPH_SPI2 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_SPI3 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_USART2 + * @arg @ref DDL_APB1_GRP1_PERIPH_USART3 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_UART4 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_UART5 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_I2C1 + * @arg @ref DDL_APB1_GRP1_PERIPH_I2C2 + * @arg @ref DDL_APB1_GRP1_PERIPH_I2C3 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_CAN1 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_CAN2 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_CAN3 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_PMU + * @arg @ref DDL_APB1_GRP1_PERIPH_DAC1 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_UART7 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_UART8 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_RTCAPB (*) + * + * (*) value not defined in all devices. + * @retval None +*/ +__STATIC_INLINE void DDL_APB1_GRP1_EnableClock(uint32_t Periphs) +{ + __IO uint32_t tmpreg; + SET_BIT(RCM->APB1CLKEN, Periphs); + /* Delay after an RCM peripheral clock enabling */ + tmpreg = READ_BIT(RCM->APB1CLKEN, Periphs); + (void)tmpreg; +} + +/** + * @brief Check if APB1 peripheral clock is enabled or not + * @param Periphs This parameter can be a combination of the following values: + * @arg @ref DDL_APB1_GRP1_PERIPH_TMR2 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_TMR3 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_TMR4 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_TMR5 + * @arg @ref DDL_APB1_GRP1_PERIPH_TMR6 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_TMR7 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_TMR12 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_TMR13 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_TMR14 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_WWDT + * @arg @ref DDL_APB1_GRP1_PERIPH_SPI2 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_SPI3 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_USART2 + * @arg @ref DDL_APB1_GRP1_PERIPH_USART3 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_UART4 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_UART5 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_I2C1 + * @arg @ref DDL_APB1_GRP1_PERIPH_I2C2 + * @arg @ref DDL_APB1_GRP1_PERIPH_I2C3 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_CAN1 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_CAN2 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_CAN3 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_PMU + * @arg @ref DDL_APB1_GRP1_PERIPH_DAC1 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_UART7 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_UART8 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_RTCAPB (*) + * + * (*) value not defined in all devices. + * @retval State of Periphs (1 or 0). +*/ +__STATIC_INLINE uint32_t DDL_APB1_GRP1_IsEnabledClock(uint32_t Periphs) +{ + return (READ_BIT(RCM->APB1CLKEN, Periphs) == Periphs); +} + +/** + * @brief Disable APB1 peripherals clock. + * @param Periphs This parameter can be a combination of the following values: + * @arg @ref DDL_APB1_GRP1_PERIPH_TMR2 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_TMR3 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_TMR4 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_TMR5 + * @arg @ref DDL_APB1_GRP1_PERIPH_TMR6 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_TMR7 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_TMR12 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_TMR13 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_TMR14 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_WWDT + * @arg @ref DDL_APB1_GRP1_PERIPH_SPI2 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_SPI3 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_USART2 + * @arg @ref DDL_APB1_GRP1_PERIPH_USART3 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_UART4 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_UART5 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_I2C1 + * @arg @ref DDL_APB1_GRP1_PERIPH_I2C2 + * @arg @ref DDL_APB1_GRP1_PERIPH_I2C3 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_CAN1 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_CAN2 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_CAN3 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_PMU + * @arg @ref DDL_APB1_GRP1_PERIPH_DAC1 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_UART7 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_UART8 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_RTCAPB (*) + * + * (*) value not defined in all devices. + * @retval None +*/ +__STATIC_INLINE void DDL_APB1_GRP1_DisableClock(uint32_t Periphs) +{ + CLEAR_BIT(RCM->APB1CLKEN, Periphs); +} + +/** + * @brief Force APB1 peripherals reset. + * @param Periphs This parameter can be a combination of the following values: + * @arg @ref DDL_APB1_GRP1_PERIPH_TMR2 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_TMR3 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_TMR4 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_TMR5 + * @arg @ref DDL_APB1_GRP1_PERIPH_TMR6 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_TMR7 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_TMR12 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_TMR13 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_TMR14 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_WWDT + * @arg @ref DDL_APB1_GRP1_PERIPH_SPI2 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_SPI3 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_USART2 + * @arg @ref DDL_APB1_GRP1_PERIPH_USART3 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_UART4 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_UART5 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_I2C1 + * @arg @ref DDL_APB1_GRP1_PERIPH_I2C2 + * @arg @ref DDL_APB1_GRP1_PERIPH_I2C3 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_CAN1 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_CAN2 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_CAN3 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_PMU + * @arg @ref DDL_APB1_GRP1_PERIPH_DAC1 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_UART7 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_UART8 (*) + * + * (*) value not defined in all devices. + * @retval None +*/ +__STATIC_INLINE void DDL_APB1_GRP1_ForceReset(uint32_t Periphs) +{ + SET_BIT(RCM->APB1RST, Periphs); +} + +/** + * @brief Release APB1 peripherals reset. + * @param Periphs This parameter can be a combination of the following values: + * @arg @ref DDL_APB1_GRP1_PERIPH_TMR2 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_TMR3 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_TMR4 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_TMR5 + * @arg @ref DDL_APB1_GRP1_PERIPH_TMR6 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_TMR7 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_TMR12 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_TMR13 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_TMR14 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_WWDT + * @arg @ref DDL_APB1_GRP1_PERIPH_SPI2 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_SPI3 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_USART2 + * @arg @ref DDL_APB1_GRP1_PERIPH_USART3 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_UART4 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_UART5 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_I2C1 + * @arg @ref DDL_APB1_GRP1_PERIPH_I2C2 + * @arg @ref DDL_APB1_GRP1_PERIPH_I2C3 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_CAN1 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_CAN2 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_CAN3 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_PMU + * @arg @ref DDL_APB1_GRP1_PERIPH_DAC1 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_UART7 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_UART8 (*) + * + * (*) value not defined in all devices. + * @retval None +*/ +__STATIC_INLINE void DDL_APB1_GRP1_ReleaseReset(uint32_t Periphs) +{ + CLEAR_BIT(RCM->APB1RST, Periphs); +} + +/** + * @brief Enable APB1 peripheral clocks in low-power mode + * @param Periphs This parameter can be a combination of the following values: + * @arg @ref DDL_APB1_GRP1_PERIPH_TMR2 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_TMR3 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_TMR4 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_TMR5 + * @arg @ref DDL_APB1_GRP1_PERIPH_TMR6 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_TMR7 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_TMR12 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_TMR13 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_TMR14 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_WWDT + * @arg @ref DDL_APB1_GRP1_PERIPH_SPI2 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_SPI3 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_USART2 + * @arg @ref DDL_APB1_GRP1_PERIPH_USART3 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_UART4 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_UART5 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_I2C1 + * @arg @ref DDL_APB1_GRP1_PERIPH_I2C2 + * @arg @ref DDL_APB1_GRP1_PERIPH_I2C3 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_CAN1 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_CAN2 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_CAN3 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_PMU + * @arg @ref DDL_APB1_GRP1_PERIPH_DAC1 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_UART7 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_UART8 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_RTCAPB (*) + * + * (*) value not defined in all devices. + * @retval None +*/ +__STATIC_INLINE void DDL_APB1_GRP1_EnableClockLowPower(uint32_t Periphs) +{ + __IO uint32_t tmpreg; + SET_BIT(RCM->LPAPB1CLKEN, Periphs); + /* Delay after an RCM peripheral clock enabling */ + tmpreg = READ_BIT(RCM->LPAPB1CLKEN, Periphs); + (void)tmpreg; +} + +/** + * @brief Disable APB1 peripheral clocks in low-power mode + * @param Periphs This parameter can be a combination of the following values: + * @arg @ref DDL_APB1_GRP1_PERIPH_TMR2 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_TMR3 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_TMR4 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_TMR5 + * @arg @ref DDL_APB1_GRP1_PERIPH_TMR6 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_TMR7 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_TMR12 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_TMR13 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_TMR14 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_WWDT + * @arg @ref DDL_APB1_GRP1_PERIPH_SPI2 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_SPI3 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_USART2 + * @arg @ref DDL_APB1_GRP1_PERIPH_USART3 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_UART4 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_UART5 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_I2C1 + * @arg @ref DDL_APB1_GRP1_PERIPH_I2C2 + * @arg @ref DDL_APB1_GRP1_PERIPH_I2C3 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_CAN1 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_CAN2 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_CAN3 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_PMU + * @arg @ref DDL_APB1_GRP1_PERIPH_DAC1 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_UART7 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_UART8 (*) + * @arg @ref DDL_APB1_GRP1_PERIPH_RTCAPB (*) + * + * (*) value not defined in all devices. + * @retval None +*/ +__STATIC_INLINE void DDL_APB1_GRP1_DisableClockLowPower(uint32_t Periphs) +{ + CLEAR_BIT(RCM->LPAPB1CLKEN, Periphs); +} + +/** + * @} + */ + +/** @defgroup BUS_DDL_EF_APB2 APB2 + * @{ + */ + +/** + * @brief Enable APB2 peripherals clock. + * @param Periphs This parameter can be a combination of the following values: + * @arg @ref DDL_APB2_GRP1_PERIPH_TMR1 + * @arg @ref DDL_APB2_GRP1_PERIPH_TMR8 (*) + * @arg @ref DDL_APB2_GRP1_PERIPH_USART1 + * @arg @ref DDL_APB2_GRP1_PERIPH_USART6 (*) + * @arg @ref DDL_APB2_GRP1_PERIPH_UART9 (*) + * @arg @ref DDL_APB2_GRP1_PERIPH_UART10 (*) + * @arg @ref DDL_APB2_GRP1_PERIPH_ADC1 + * @arg @ref DDL_APB2_GRP1_PERIPH_ADC2 (*) + * @arg @ref DDL_APB2_GRP1_PERIPH_ADC3 (*) + * @arg @ref DDL_APB2_GRP1_PERIPH_SDIO (*) + * @arg @ref DDL_APB2_GRP1_PERIPH_SPI1 + * @arg @ref DDL_APB2_GRP1_PERIPH_SPI4 (*) + * @arg @ref DDL_APB2_GRP1_PERIPH_SYSCFG + * @arg @ref DDL_APB2_GRP1_PERIPH_COMP (*) + * @arg @ref DDL_APB2_GRP1_PERIPH_EINT (*) + * @arg @ref DDL_APB2_GRP1_PERIPH_TMR9 + * @arg @ref DDL_APB2_GRP1_PERIPH_TMR10 (*) + * @arg @ref DDL_APB2_GRP1_PERIPH_TMR11 + * @arg @ref DDL_APB2_GRP1_PERIPH_SPI5 (*) + * @arg @ref DDL_APB2_GRP1_PERIPH_SPI6 (*) + + * + * (*) value not defined in all devices. + * @retval None +*/ +__STATIC_INLINE void DDL_APB2_GRP1_EnableClock(uint32_t Periphs) +{ + __IO uint32_t tmpreg; + SET_BIT(RCM->APB2CLKEN, Periphs); + /* Delay after an RCM peripheral clock enabling */ + tmpreg = READ_BIT(RCM->APB2CLKEN, Periphs); + (void)tmpreg; +} + +/** + * @brief Check if APB2 peripheral clock is enabled or not + * @param Periphs This parameter can be a combination of the following values: + * @arg @ref DDL_APB2_GRP1_PERIPH_TMR1 + * @arg @ref DDL_APB2_GRP1_PERIPH_TMR8 (*) + * @arg @ref DDL_APB2_GRP1_PERIPH_USART1 + * @arg @ref DDL_APB2_GRP1_PERIPH_USART6 (*) + * @arg @ref DDL_APB2_GRP1_PERIPH_UART9 (*) + * @arg @ref DDL_APB2_GRP1_PERIPH_UART10 (*) + * @arg @ref DDL_APB2_GRP1_PERIPH_ADC1 + * @arg @ref DDL_APB2_GRP1_PERIPH_ADC2 (*) + * @arg @ref DDL_APB2_GRP1_PERIPH_ADC3 (*) + * @arg @ref DDL_APB2_GRP1_PERIPH_SDIO (*) + * @arg @ref DDL_APB2_GRP1_PERIPH_SPI1 + * @arg @ref DDL_APB2_GRP1_PERIPH_SPI4 (*) + * @arg @ref DDL_APB2_GRP1_PERIPH_SYSCFG + * @arg @ref DDL_APB2_GRP1_PERIPH_COMP (*) + * @arg @ref DDL_APB2_GRP1_PERIPH_EINT (*) + * @arg @ref DDL_APB2_GRP1_PERIPH_TMR9 + * @arg @ref DDL_APB2_GRP1_PERIPH_TMR10 (*) + * @arg @ref DDL_APB2_GRP1_PERIPH_TMR11 + * @arg @ref DDL_APB2_GRP1_PERIPH_SPI5 (*) + * @arg @ref DDL_APB2_GRP1_PERIPH_SPI6 (*) + * + * (*) value not defined in all devices. + * @retval State of Periphs (1 or 0). +*/ +__STATIC_INLINE uint32_t DDL_APB2_GRP1_IsEnabledClock(uint32_t Periphs) +{ + return (READ_BIT(RCM->APB2CLKEN, Periphs) == Periphs); +} + +/** + * @brief Disable APB2 peripherals clock. + * @param Periphs This parameter can be a combination of the following values: + * @arg @ref DDL_APB2_GRP1_PERIPH_TMR1 + * @arg @ref DDL_APB2_GRP1_PERIPH_TMR8 (*) + * @arg @ref DDL_APB2_GRP1_PERIPH_USART1 + * @arg @ref DDL_APB2_GRP1_PERIPH_USART6 (*) + * @arg @ref DDL_APB2_GRP1_PERIPH_UART9 (*) + * @arg @ref DDL_APB2_GRP1_PERIPH_UART10 (*) + * @arg @ref DDL_APB2_GRP1_PERIPH_ADC1 + * @arg @ref DDL_APB2_GRP1_PERIPH_ADC2 (*) + * @arg @ref DDL_APB2_GRP1_PERIPH_ADC3 (*) + * @arg @ref DDL_APB2_GRP1_PERIPH_SDIO (*) + * @arg @ref DDL_APB2_GRP1_PERIPH_SPI1 + * @arg @ref DDL_APB2_GRP1_PERIPH_SPI4 (*) + * @arg @ref DDL_APB2_GRP1_PERIPH_SYSCFG + * @arg @ref DDL_APB2_GRP1_PERIPH_COMP (*) + * @arg @ref DDL_APB2_GRP1_PERIPH_EINT (*) + * @arg @ref DDL_APB2_GRP1_PERIPH_TMR9 + * @arg @ref DDL_APB2_GRP1_PERIPH_TMR10 (*) + * @arg @ref DDL_APB2_GRP1_PERIPH_TMR11 + * @arg @ref DDL_APB2_GRP1_PERIPH_SPI5 (*) + * @arg @ref DDL_APB2_GRP1_PERIPH_SPI6 (*) + * + * (*) value not defined in all devices. + * @retval None +*/ +__STATIC_INLINE void DDL_APB2_GRP1_DisableClock(uint32_t Periphs) +{ + CLEAR_BIT(RCM->APB2CLKEN, Periphs); +} + +/** + * @brief Force APB2 peripherals reset. + * @param Periphs This parameter can be a combination of the following values: + * @arg @ref DDL_APB2_GRP1_PERIPH_ALL + * @arg @ref DDL_APB2_GRP1_PERIPH_TMR1 + * @arg @ref DDL_APB2_GRP1_PERIPH_TMR8 (*) + * @arg @ref DDL_APB2_GRP1_PERIPH_USART1 + * @arg @ref DDL_APB2_GRP1_PERIPH_USART6 (*) + * @arg @ref DDL_APB2_GRP1_PERIPH_UART9 (*) + * @arg @ref DDL_APB2_GRP1_PERIPH_UART10 (*) + * @arg @ref DDL_APB2_GRP1_PERIPH_ADC + * @arg @ref DDL_APB2_GRP1_PERIPH_ADC1 (*) + * @arg @ref DDL_APB2_GRP1_PERIPH_ADC2 (*) + * @arg @ref DDL_APB2_GRP1_PERIPH_SDIO (*) + * @arg @ref DDL_APB2_GRP1_PERIPH_SPI1 + * @arg @ref DDL_APB2_GRP1_PERIPH_SPI4 (*) + * @arg @ref DDL_APB2_GRP1_PERIPH_SYSCFG + * @arg @ref DDL_APB2_GRP1_PERIPH_TMR9 + * @arg @ref DDL_APB2_GRP1_PERIPH_TMR10 (*) + * @arg @ref DDL_APB2_GRP1_PERIPH_TMR11 + * @arg @ref DDL_APB2_GRP1_PERIPH_SPI5 (*) + * @arg @ref DDL_APB2_GRP1_PERIPH_SPI6 (*) + * + * (*) value not defined in all devices. + * @retval None + * @note ADC1 and ADC2 are not available on all devices. +*/ +__STATIC_INLINE void DDL_APB2_GRP1_ForceReset(uint32_t Periphs) +{ + SET_BIT(RCM->APB2RST, Periphs); +} + +/** + * @brief Release APB2 peripherals reset. + * @param Periphs This parameter can be a combination of the following values: + * @arg @ref DDL_APB2_GRP1_PERIPH_ALL + * @arg @ref DDL_APB2_GRP1_PERIPH_TMR1 + * @arg @ref DDL_APB2_GRP1_PERIPH_TMR8 (*) + * @arg @ref DDL_APB2_GRP1_PERIPH_USART1 + * @arg @ref DDL_APB2_GRP1_PERIPH_USART6 (*) + * @arg @ref DDL_APB2_GRP1_PERIPH_UART9 (*) + * @arg @ref DDL_APB2_GRP1_PERIPH_UART10 (*) + * @arg @ref DDL_APB2_GRP1_PERIPH_ADC + * @arg @ref DDL_APB2_GRP1_PERIPH_ADC1 (*) + * @arg @ref DDL_APB2_GRP1_PERIPH_ADC2 (*) + * @arg @ref DDL_APB2_GRP1_PERIPH_SDIO (*) + * @arg @ref DDL_APB2_GRP1_PERIPH_SPI1 + * @arg @ref DDL_APB2_GRP1_PERIPH_SPI4 (*) + * @arg @ref DDL_APB2_GRP1_PERIPH_SYSCFG + * @arg @ref DDL_APB2_GRP1_PERIPH_EINT (*) + * @arg @ref DDL_APB2_GRP1_PERIPH_TMR9 + * @arg @ref DDL_APB2_GRP1_PERIPH_TMR10 (*) + * @arg @ref DDL_APB2_GRP1_PERIPH_TMR11 + * @arg @ref DDL_APB2_GRP1_PERIPH_SPI5 (*) + * @arg @ref DDL_APB2_GRP1_PERIPH_SPI6 (*) + * + * (*) value not defined in all devices. + * @retval None + * @note ADC1 and ADC2 are not available on all devices. +*/ +__STATIC_INLINE void DDL_APB2_GRP1_ReleaseReset(uint32_t Periphs) +{ + CLEAR_BIT(RCM->APB2RST, Periphs); +} + +/** + * @brief Enable APB2 peripheral clocks in low-power mode + * @param Periphs This parameter can be a combination of the following values: + * @arg @ref DDL_APB2_GRP1_PERIPH_TMR1 + * @arg @ref DDL_APB2_GRP1_PERIPH_TMR8 (*) + * @arg @ref DDL_APB2_GRP1_PERIPH_USART1 + * @arg @ref DDL_APB2_GRP1_PERIPH_USART6 (*) + * @arg @ref DDL_APB2_GRP1_PERIPH_UART9 (*) + * @arg @ref DDL_APB2_GRP1_PERIPH_UART10 (*) + * @arg @ref DDL_APB2_GRP1_PERIPH_ADC1 + * @arg @ref DDL_APB2_GRP1_PERIPH_ADC2 (*) + * @arg @ref DDL_APB2_GRP1_PERIPH_ADC3 (*) + * @arg @ref DDL_APB2_GRP1_PERIPH_SDIO (*) + * @arg @ref DDL_APB2_GRP1_PERIPH_SPI1 + * @arg @ref DDL_APB2_GRP1_PERIPH_SPI4 (*) + * @arg @ref DDL_APB2_GRP1_PERIPH_SYSCFG + * @arg @ref DDL_APB2_GRP1_PERIPH_EINT (*) + * @arg @ref DDL_APB2_GRP1_PERIPH_TMR9 + * @arg @ref DDL_APB2_GRP1_PERIPH_TMR10 (*) + * @arg @ref DDL_APB2_GRP1_PERIPH_TMR11 + * @arg @ref DDL_APB2_GRP1_PERIPH_SPI5 (*) + * @arg @ref DDL_APB2_GRP1_PERIPH_SPI6 (*) + * + * (*) value not defined in all devices. + * @retval None +*/ +__STATIC_INLINE void DDL_APB2_GRP1_EnableClockLowPower(uint32_t Periphs) +{ + __IO uint32_t tmpreg; + SET_BIT(RCM->LPAPB2CLKEN, Periphs); + /* Delay after an RCM peripheral clock enabling */ + tmpreg = READ_BIT(RCM->LPAPB2CLKEN, Periphs); + (void)tmpreg; +} + +/** + * @brief Disable APB2 peripheral clocks in low-power mode + * @param Periphs This parameter can be a combination of the following values: + * @arg @ref DDL_APB2_GRP1_PERIPH_TMR1 + * @arg @ref DDL_APB2_GRP1_PERIPH_TMR8 (*) + * @arg @ref DDL_APB2_GRP1_PERIPH_USART1 + * @arg @ref DDL_APB2_GRP1_PERIPH_USART6 (*) + * @arg @ref DDL_APB2_GRP1_PERIPH_UART9 (*) + * @arg @ref DDL_APB2_GRP1_PERIPH_UART10 (*) + * @arg @ref DDL_APB2_GRP1_PERIPH_ADC1 + * @arg @ref DDL_APB2_GRP1_PERIPH_ADC2 (*) + * @arg @ref DDL_APB2_GRP1_PERIPH_ADC3 (*) + * @arg @ref DDL_APB2_GRP1_PERIPH_SDIO (*) + * @arg @ref DDL_APB2_GRP1_PERIPH_SPI1 + * @arg @ref DDL_APB2_GRP1_PERIPH_SPI4 (*) + * @arg @ref DDL_APB2_GRP1_PERIPH_SYSCFG + * @arg @ref DDL_APB2_GRP1_PERIPH_EINT (*) + * @arg @ref DDL_APB2_GRP1_PERIPH_TMR9 + * @arg @ref DDL_APB2_GRP1_PERIPH_TMR10 (*) + * @arg @ref DDL_APB2_GRP1_PERIPH_TMR11 + * @arg @ref DDL_APB2_GRP1_PERIPH_SPI5 (*) + * @arg @ref DDL_APB2_GRP1_PERIPH_SPI6 (*) + * + * (*) value not defined in all devices. + * @retval None +*/ +__STATIC_INLINE void DDL_APB2_GRP1_DisableClockLowPower(uint32_t Periphs) +{ + CLEAR_BIT(RCM->LPAPB2CLKEN, Periphs); +} + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#endif /* defined(RCM) */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* APM32F4xx_DDL_BUS_H */ + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_comp.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_comp.h new file mode 100644 index 0000000000..2030f16029 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_comp.h @@ -0,0 +1,598 @@ +/** + * + * @file apm32f4xx_ddl_comp.h + * @brief Header file of COMP DDL module. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * Copyright (c) 2017 STMicroelectronics. + * Copyright (C) 2023-2024 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __APM32F4XX_DDL_COMP_H__ +#define __APM32F4XX_DDL_COMP_H__ + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx.h" + +/** @addtogroup APM32F4xx_DDL_Driver + * @{ + */ + + #if defined (COMP1) || defined (COMP2) + +/** @addtogroup COMP_DDL COMP + * @{ + */ + +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/* Private macros ------------------------------------------------------------*/ +/* Exported types ------------------------------------------------------------*/ +#if defined(USE_FULL_DDL_DRIVER) +/** @defgroup COMP_DDL_ES_INIT COMP Exported Init Structure + * @{ + */ + +/** + * @brief COMP Init structure definition + */ +typedef struct +{ + uint32_t Mode; /*!< Set comparator operating mode to adjust speed. + Note: Speed mode is available only for COMP2. + This parameter can be a value of @ref COMP_DDL_EC_SPEEDMODE + + This feature can be modified afterwards using unitary function @ref DDL_COMP_SetSpeedMode(). */ + + uint32_t InputPlus; /*!< Set comparator input plus. + Note: Input plus is available only for COMP2. + This parameter can be a value of @ref COMP_DDL_EC_INPUT_PLUS + + This feature can be modified afterwards using unitary function @ref DDL_COMP_SetInputPlus(). */ + + uint32_t InputMinus; /*!< Set comparator input minus. + This parameter can be a value of @ref COMP_DDL_EC_INPUT_MINUS + + This feature can be modified afterwards using unitary function @ref DDL_COMP_SetInputMinus(). */ + + uint32_t OutputPol; /*!< Set comparator output polarity. + This parameter can be a value of @ref COMP_DDL_EC_OUTPUT_POLARITY + + This feature can be modified afterwards using unitary function @ref DDL_COMP_SetOutputPolarity(). */ + + uint32_t Output; /*!< Set comparator output. + This parameter can be a value of @ref COMP_DDL_EC_OUTPUT + + This feature can be modified afterwards using unitary function @ref DDL_COMP_SetOutput(). */ +} DDL_COMP_InitTypeDef; + +/** + * @} + */ +#endif /* USE_FULL_DDL_DRIVER */ + +/* Exported constants --------------------------------------------------------*/ +/** @defgroup COMP_DDL_Exported_Constants COMP Exported Constants + * @{ + */ + +/** @defgroup COMP_DDL_EC_WINDOWMODE COMP common window mod + * @{ + */ +#define DDL_COMP_WINDOWMODE_DISABLE (0x00000000UL) /*!< Window mode disable: Comparator 1 and comparator 2 are independent. */ +#define DDL_COMP_WINDOWMODE_ENABLE (COMP_CSTS_WMODESEL) /*!< Window mode enable: Comparator 1 and comparator 2 are combined. */ +/** + * @} + */ + +/** @defgroup COMP_DDL_EC_SPEEDMODE COMP speed mode + * @{ + */ +#define DDL_COMP_SPEEDMODE_LOW (0x00000000UL) /*!< Low speed mode: Comparator 2 is in low speed mode. */ +#define DDL_COMP_SPEEDMODE_HIGH (COMP_CSTS_SPEEDM) /*!< High speed mode: Comparator 2 is in high speed mode. */ +/** + * @} + */ + +/** @defgroup COMP_DDL_EC_INPUT_PLUS COMP input plus + * @{ + */ +#define DDL_COMP_INPUT_PLUS_PC2 (0x00000000UL) /*!< Input plus: PC2. Available only for COMP2. */ +/** + * @} + */ + +/** @defgroup COMP_DDL_EC_INPUT_MINUS COMP input minus + * @{ + */ +#define DDL_COMP_INPUT_MINUS_VREFINT (0x00000000UL) /*!< Input minus: Vrefint. */ +#define DDL_COMP_INPUT_MINUS_PC1 (COMP_CSTS_INMCCFG_0) /*!< Input minus: PC1. Available only for COMP1. */ +#define DDL_COMP_INPUT_MINUS_PC3 (COMP_CSTS_INMCCFG_0) /*!< Input minus: PC3. Available only for COMP2. */ +#define DDL_COMP_INPUT_MINUS_1_4_VREFINT (COMP_CSTS_INMCCFG_2) /*!< Input minus: 1/4 Vrefint. Available only for COMP2. */ +#define DDL_COMP_INPUT_MINUS_1_2_VREFINT (COMP_CSTS_INMCCFG_2 | COMP_CSTS_INMCCFG_0) /*!< Input minus: 1/2 Vrefint. Available only for COMP2. */ +#define DDL_COMP_INPUT_MINUS_3_4_VREFINT (COMP_CSTS_INMCCFG_2 | COMP_CSTS_INMCCFG_1) /*!< Input minus: 3/4 Vrefint. Available only for COMP2. */ +/** + * @} + */ + +/** @defgroup COMP_DDL_EC_OUTPUT_POLARITY COMP output polarity + * @{ + */ +#define DDL_COMP_OUTPUTPOL_NONINVERTED (0x00000000UL) /*!< Comparator output is non-inverted. */ +#define DDL_COMP_OUTPUTPOL_INVERTED (COMP_CSTS_POLCFG) /*!< Comparator output is inverted. */ +/** + * @} + */ + +/** @defgroup COMP_DDL_EC_OUTPUT COMP output + * @{ + */ +#define DDL_COMP_OUTPUT_NONE (0x00000000UL) /*!< Comparator output is not connected. */ +#define DDL_COMP_OUTPUT_TMR1BKIN (COMP_CSTS_OUTSEL_0) /*!< Comparator output is connected to TMR1BKIN. */ +#define DDL_COMP_OUTPUT_TMR1IC1 (COMP_CSTS_OUTSEL_1) /*!< Comparator output is connected to TMR1IC1. */ +#define DDL_COMP_OUTPUT_TMR1ETRF (COMP_CSTS_OUTSEL_1 | COMP_CSTS_OUTSEL_0) /*!< Comparator output is connected to TMR1ETRF. */ +#define DDL_COMP_OUTPUT_TMR8BKIN (COMP_CSTS_OUTSEL_2) /*!< Comparator output is connected to TMR8BKIN. */ +#define DDL_COMP_OUTPUT_TMR8IC1 (COMP_CSTS_OUTSEL_2 | COMP_CSTS_OUTSEL_0) /*!< Comparator output is connected to TMR8IC1. */ +#define DDL_COMP_OUTPUT_TMR8ETRF (COMP_CSTS_OUTSEL_2 | COMP_CSTS_OUTSEL_1) /*!< Comparator output is connected to TMR8ETRF. */ +#define DDL_COMP_OUTPUT_TMR2IC4 (COMP_CSTS_OUTSEL_2 | COMP_CSTS_OUTSEL_1 | COMP_CSTS_OUTSEL_0) /*!< Comparator output is connected to TMR2IC4. */ +#define DDL_COMP_OUTPUT_TMR2ETRF (COMP_CSTS_OUTSEL_3) /*!< Comparator output is connected to TMR2ETRF. */ +#define DDL_COMP_OUTPUT_TMR3IC1 (COMP_CSTS_OUTSEL_3 | COMP_CSTS_OUTSEL_0) /*!< Comparator output is connected to TMR3IC1. */ +#define DDL_COMP_OUTPUT_TMR3ETRF (COMP_CSTS_OUTSEL_3 | COMP_CSTS_OUTSEL_1) /*!< Comparator output is connected to TMR3ETRF. */ +#define DDL_COMP_OUTPUT_TMR4IC1 (COMP_CSTS_OUTSEL_3 | COMP_CSTS_OUTSEL_1 | COMP_CSTS_OUTSEL_0) /*!< Comparator output is connected to TMR4IC1. */ +/** + * @} + */ + +/** @defgroup COMP_DDL_EC_OUTPUT_LEVEL COMP output level + * @{ + */ +#define DDL_COMP_OUTPUT_LEVEL_LOW (0x00000000UL) /*!< Comparator output is low level. */ +#define DDL_COMP_OUTPUT_LEVEL_HIGH (0x00000001UL) /*!< Comparator output is high level. */ +/** + * @} + */ + +/** @defgroup COMP_DDL_EC_HW_DELAYS COMP hardware delay + * @{ + */ + +/* Delay for comparator startup time */ +#define DDL_COMP_DELAY_STARTUP_US (80UL) /*!< Comparator startup time. */ +/** + * @} + */ + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ +/** @defgroup COMP_DDL_Exported_Macros COMP Exported Macros + * @{ + */ +/** @defgroup COMP_DDL_EM_WRITE_READ Common write and read registers macro + * @{ + */ + +/** + * @brief Write a value in COMP register. + * @param __INSTANCE__ COMP instance. + * @param __REG__ COMP register. + * @param __VALUE__ Value to be written. + * @retval None + */ +#define DDL_COMP_WriteReg(__INSTANCE__, __REG__, __VALUE__) WRITE_REG(__INSTANCE__->__REG__, (__VALUE__)) + +/** + * @brief Read a value in COMP register. + * @param __INSTANCE__ COMP instance. + * @param __REG__ COMP register. + * @retval Register value + */ +#define DDL_COMP_ReadReg(__INSTANCE__, __REG__) READ_REG(__INSTANCE__->__REG__) +/** + * @} + */ + +/** @defgroup COMP_DDL_EM_HELPER_MACRO Helper macro + * @{ + */ + +/** + * @brief Helper macro to select the COMP common instance + * to which is belonging the selected COMP instance. + * @param __COMPx__ COMP instance. + * @retval COMP common instance or value "0" if there is no COMP common instance. + * @note COMP common register instance can be used to set parameters common to + * several COMP instances. Refer to functions having argument "COMPxy_COMMON" as parameter. + */ +#define __DDL_COMP_COMMON_INSTANCE(__COMPx__) (COMP12_COMMON) + + /** + * @} + */ + + /** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +/** @defgroup COMP_DDL_Exported_Functions COMP Exported Functions + * @{ + */ + +/** @defgroup COMP_DDL_EF_Configuration_comparator_common Configuration of comparator hierarchical scope: common to several COMP instances + * @{ + */ + +/** + * @brief Set comparator window mode. + * @param COMPxy_COMMON COMP common instance. + * @param WindowMode This parameter can be one of the following values: + * @arg @ref DDL_COMP_WINDOWMODE_DISABLE + * @arg @ref DDL_COMP_WINDOWMODE_ENABLE + * @retval None + */ +__STATIC_INLINE void DDL_COMP_SetWindowMode(COMP_Common_TypeDef *COMPxy_COMMON, + uint32_t WindowMode) +{ + /* Note: Window mode is available only for COMP1. */ + MODIFY_REG(COMPxy_COMMON->CSTS, COMP_CSTS_WMODESEL, WindowMode); +} + +/** + * @brief Get comparator window mode. + * @param COMPxy_COMMON COMP common instance. + * @retval Returned value can be one of the following values: + * @arg @ref DDL_COMP_WINDOWMODE_DISABLE + * @arg @ref DDL_COMP_WINDOWMODE_ENABLE + */ +__STATIC_INLINE uint32_t DDL_COMP_GetWindowMode(COMP_Common_TypeDef *COMPxy_COMMON) +{ + /* Note: Window mode is available only for COMP1. */ + return (uint32_t)(READ_BIT(COMPxy_COMMON->CSTS, COMP_CSTS_WMODESEL)); +} + +/** + * @} + */ + +/** @defgroup COMP_DDL_EF_Configuration_comparator_modes Configuration of comparator instance mode + * @{ + */ + +/** + * @brief Set comparator operating mode to adjust speed. + * @param COMPx COMP instance. + * @param Mode This parameter can be one of the following values: + * @arg @ref DDL_COMP_SPEEDMODE_LOW + * @arg @ref DDL_COMP_SPEEDMODE_HIGH + * @retval None + */ +__STATIC_INLINE void DDL_COMP_SetSpeedMode(COMP_TypeDef *COMPx, + uint32_t Mode) +{ + /* Note: Speed mode is available only for COMP2. */ + MODIFY_REG(COMPx->CSTS, COMP_CSTS_SPEEDM, Mode); +} + +/** + * @brief Get comparator operating mode to adjust speed. + * @param COMPx COMP instance. + * @retval Returned value can be one of the following values: + * @arg @ref DDL_COMP_SPEEDMODE_LOW + * @arg @ref DDL_COMP_SPEEDMODE_HIGH + */ +__STATIC_INLINE uint32_t DDL_COMP_GetSpeedMode(COMP_TypeDef *COMPx) +{ + /* Note: Speed mode is available only for COMP2. */ + return (uint32_t)(READ_BIT(COMPx->CSTS, COMP_CSTS_SPEEDM)); +} + +/** + * @} + */ + +/** @defgroup COMP_DDL_EF_Configuration_comparator_inputs Configuration of comparator inputs + * @{ + */ + +/** + * @brief Set comparator input plus. + * @param COMPx COMP instance. + * @param InputPlus This parameter can be one of the following values: + * @arg @ref DDL_COMP_INPUT_PLUS_PC2 + * @retval None + */ +__STATIC_INLINE void DDL_COMP_SetInputPlus(COMP_TypeDef *COMPx, + uint32_t InputPlus) +{ + /* Note: Input plus is available only for COMP2. */ + MODIFY_REG(COMPx->CSTS, COMP_CSTS_INPCCFG, InputPlus); +} + +/** + * @brief Get comparator input plus. + * @param COMPx COMP instance. + * @retval Returned value can be one of the following values: + * @arg @ref DDL_COMP_INPUT_PLUS_PC2 + */ +__STATIC_INLINE uint32_t DDL_COMP_GetInputPlus(COMP_TypeDef *COMPx) +{ + /* Note: Input plus is available only for COMP2. */ + return (uint32_t)(READ_BIT(COMPx->CSTS, COMP_CSTS_INPCCFG)); +} + +/** + * @brief Set comparator input minus. + * @param COMPx COMP instance. + * @param InputMinus This parameter can be one of the following values: + * @arg @ref DDL_COMP_INPUT_MINUS_VREFINT + * @arg @ref DDL_COMP_INPUT_MINUS_PC1 (COMP1 only) + * @arg @ref DDL_COMP_INPUT_MINUS_PC3 (COMP2 only) + * @arg @ref DDL_COMP_INPUT_MINUS_1_4_VREFINT (COMP2 only) + * @arg @ref DDL_COMP_INPUT_MINUS_1_2_VREFINT (COMP2 only) + * @arg @ref DDL_COMP_INPUT_MINUS_3_4_VREFINT (COMP2 only) + * @retval None + */ +__STATIC_INLINE void DDL_COMP_SetInputMinus(COMP_TypeDef *COMPx, + uint32_t InputMinus) +{ + /* Note: Input minus is available only for COMP1 and COMP2. */ + MODIFY_REG(COMPx->CSTS, COMP_CSTS_INMCCFG, InputMinus); +} + +/** + * @brief Get comparator input minus. + * @param COMPx COMP instance. + * @retval Returned value can be one of the following values: + * @arg @ref DDL_COMP_INPUT_MINUS_VREFINT + * @arg @ref DDL_COMP_INPUT_MINUS_PC1 (COMP1 only) + * @arg @ref DDL_COMP_INPUT_MINUS_PC3 (COMP2 only) + * @arg @ref DDL_COMP_INPUT_MINUS_1_4_VREFINT (COMP2 only) + * @arg @ref DDL_COMP_INPUT_MINUS_1_2_VREFINT (COMP2 only) + * @arg @ref DDL_COMP_INPUT_MINUS_3_4_VREFINT (COMP2 only) + */ +__STATIC_INLINE uint32_t DDL_COMP_GetInputMinus(COMP_TypeDef *COMPx) +{ + return (uint32_t)(READ_BIT(COMPx->CSTS, COMP_CSTS_INMCCFG)); +} + +/** + * @} + */ + +/** @defgroup COMP_DDL_EF_Configuration_comparator_output Configuration of comparator output + * @{ + */ + +/** + * @brief Set comparator output polarity. + * @param COMPx COMP instance. + * @param OutputPol This parameter can be one of the following values: + * @arg @ref DDL_COMP_OUTPUTPOL_NONINVERTED + * @arg @ref DDL_COMP_OUTPUTPOL_INVERTED + * @retval None + */ +__STATIC_INLINE void DDL_COMP_SetOutputPolarity(COMP_TypeDef *COMPx, + uint32_t OutputPol) +{ + MODIFY_REG(COMPx->CSTS, COMP_CSTS_POLCFG, OutputPol); +} + +/** + * @brief Get comparator output polarity. + * @param COMPx COMP instance. + * @retval Returned value can be one of the following values: + * @arg @ref DDL_COMP_OUTPUTPOL_NONINVERTED + * @arg @ref DDL_COMP_OUTPUTPOL_INVERTED + */ +__STATIC_INLINE uint32_t DDL_COMP_GetOutputPolarity(COMP_TypeDef *COMPx) +{ + return (uint32_t)(READ_BIT(COMPx->CSTS, COMP_CSTS_POLCFG)); +} + +/** + * @brief Set comparator output. + * @param COMPx COMP instance. + * @param Output This parameter can be one of the following values: + * @arg @ref DDL_COMP_OUTPUT_NONE + * @arg @ref DDL_COMP_OUTPUT_TMR1BKIN + * @arg @ref DDL_COMP_OUTPUT_TMR1IC1 + * @arg @ref DDL_COMP_OUTPUT_TMR1ETRF + * @arg @ref DDL_COMP_OUTPUT_TMR8BKIN + * @arg @ref DDL_COMP_OUTPUT_TMR8IC1 + * @arg @ref DDL_COMP_OUTPUT_TMR8ETRF + * @arg @ref DDL_COMP_OUTPUT_TMR2IC4 + * @arg @ref DDL_COMP_OUTPUT_TMR2ETRF + * @arg @ref DDL_COMP_OUTPUT_TMR3IC1 + * @arg @ref DDL_COMP_OUTPUT_TMR3ETRF + * @arg @ref DDL_COMP_OUTPUT_TMR4IC1 + * @retval None + */ +__STATIC_INLINE void DDL_COMP_SetOutput(COMP_TypeDef *COMPx, + uint32_t Output) +{ + MODIFY_REG(COMPx->CSTS, COMP_CSTS_OUTSEL, Output); +} + +/** + * @brief Get comparator output. + * @param COMPx COMP instance. + * @retval Returned value can be one of the following values: + * @arg @ref DDL_COMP_OUTPUT_NONE + * @arg @ref DDL_COMP_OUTPUT_TMR1BKIN + * @arg @ref DDL_COMP_OUTPUT_TMR1IC1 + * @arg @ref DDL_COMP_OUTPUT_TMR1ETRF + * @arg @ref DDL_COMP_OUTPUT_TMR8BKIN + * @arg @ref DDL_COMP_OUTPUT_TMR8IC1 + * @arg @ref DDL_COMP_OUTPUT_TMR8ETRF + * @arg @ref DDL_COMP_OUTPUT_TMR2IC4 + * @arg @ref DDL_COMP_OUTPUT_TMR2ETRF + * @arg @ref DDL_COMP_OUTPUT_TMR3IC1 + * @arg @ref DDL_COMP_OUTPUT_TMR3ETRF + * @arg @ref DDL_COMP_OUTPUT_TMR4IC1 + */ +__STATIC_INLINE uint32_t DDL_COMP_GetOutput(COMP_TypeDef *COMPx) +{ + return (uint32_t)(READ_BIT(COMPx->CSTS, COMP_CSTS_OUTSEL)); +} + +/** + * @} + */ + + /** @defgroup COMP_DDL_EF_Operation Operation on comparator instance + * @{ + */ + +/** + * @brief Enable comparator instance. + * @param COMPx COMP instance. + * @retval None + * @note After enable from off state, comparator startup time is needed. + */ +__STATIC_INLINE void DDL_COMP_Enable(COMP_TypeDef *COMPx) +{ + SET_BIT(COMPx->CSTS, COMP_CSTS_EN); +} + +/** + * @brief Disable comparator instance. + * @param COMPx COMP instance. + * @retval None + */ +__STATIC_INLINE void DDL_COMP_Disable(COMP_TypeDef *COMPx) +{ + CLEAR_BIT(COMPx->CSTS, COMP_CSTS_EN); +} + +/** + * @brief Get comparator enable state. + * @param COMPx COMP instance. + * @retval State of bit (1 or 0). + * - 0: comparator instance is disabled. + * - 1: comparator instance is enabled. + */ +__STATIC_INLINE uint32_t DDL_COMP_IsEnabled(COMP_TypeDef *COMPx) +{ + return ((READ_BIT(COMPx->CSTS, COMP_CSTS_EN) == (COMP_CSTS_EN)) ? 1UL : 0UL); +} + +/** + * @brief Lock comparator instance. + * @param COMPx COMP instance. + * @retval None + * @note Once locked, comparator configuration can no longer be modified until next reset. + * @note The only way to unlock the comparator is a device hardware reset. + */ +__STATIC_INLINE void DDL_COMP_Lock(COMP_TypeDef *COMPx) +{ + SET_BIT(COMPx->CSTS, COMP_CSTS_LOCK); +} + +/** + * @brief Get comparator lock state. + * @param COMPx COMP instance. + * @retval State of bit (1 or 0). + * - 0: comparator instance is unlocked. + * - 1: comparator instance is locked. + */ +__STATIC_INLINE uint32_t DDL_COMP_IsLocked(COMP_TypeDef *COMPx) +{ + return ((READ_BIT(COMPx->CSTS, COMP_CSTS_LOCK) == (COMP_CSTS_LOCK)) ? 1UL : 0UL); +} + +/** + * @brief Read comparator output level. + * @param COMPx COMP instance. + * @retval Returned value can be one of the following values: + * @arg @ref DDL_COMP_OUTPUT_LEVEL_LOW + * @arg @ref DDL_COMP_OUTPUT_LEVEL_HIGH + * @note The comparator output level depends on the selected polarity. + * If the polarity is not inverted: + * - Comparator output is low level when the input plus is lower than the input minus. + * - Comparator output is high level when the input plus is higher than the input minus. + * If the polarity is inverted: + * - Comparator output is high level when the input plus is lower than the input minus. + * - Comparator output is low level when the input plus is higher than the input minus. + */ +__STATIC_INLINE uint32_t DDL_COMP_ReadOutputLevel(COMP_TypeDef *COMPx) +{ + return (uint32_t)(READ_BIT(COMPx->CSTS, COMP_CSTS_OUTVAL)); +} + +/** + * @} + */ + +#if defined(USE_FULL_DDL_DRIVER) +/** @defgroup COMP_DDL_EF_Init Initialization and de-initialization functions + * @{ + */ + +ErrorStatus DDL_COMP_Init(COMP_TypeDef *COMPx, DDL_COMP_InitTypeDef *COMP_InitStruct); +ErrorStatus DDL_COMP_DeInit(COMP_TypeDef *COMPx); +void DDL_COMP_StructInit(DDL_COMP_InitTypeDef *COMP_InitStruct); + +/** + * @} + */ +#endif /* USE_FULL_DDL_DRIVER */ + +/** + * @} + */ + +/** + * @} + */ + + #endif /* COMP1 || COMP2 */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __APM32F4XX_DDL_COMP_H__ */ + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_cortex.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_cortex.h new file mode 100644 index 0000000000..89f295349f --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_cortex.h @@ -0,0 +1,628 @@ +/** + * + * @file apm32f4xx_ddl_cortex.h + * @brief Header file of CORTEX DDL module. + @verbatim + ============================================================================== + ##### How to use this driver ##### + ============================================================================== + [..] + The LL CORTEX driver contains a set of generic APIs that can be + used by user: + (+) SYSTICK configuration used by DDL_mDelay and DDL_Init1msTick + functions + (+) Low power mode configuration (SCB register of Cortex-MCU) + (+) MPU API to configure and enable regions + (MPU services provided only on some devices) + (+) API to access to MCU info (CPUID register) + (+) API to enable fault handler (SHCSR accesses) + + @endverbatim + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2017 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file in + * the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef APM32F4xx_DDL_CORTEX_H +#define APM32F4xx_DDL_CORTEX_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx.h" + +/** @addtogroup APM32F4xx_DDL_Driver + * @{ + */ + +/** @defgroup CORTEX_DDL CORTEX + * @{ + */ + +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ + +/* Private constants ---------------------------------------------------------*/ + +/* Private macros ------------------------------------------------------------*/ + +/* Exported types ------------------------------------------------------------*/ +/* Exported constants --------------------------------------------------------*/ +/** @defgroup CORTEX_DDL_Exported_Constants CORTEX Exported Constants + * @{ + */ + +/** @defgroup CORTEX_DDL_EC_CLKSOURCE_HCLK SYSTICK Clock Source + * @{ + */ +#define DDL_SYSTICK_CLKSOURCE_HCLK_DIV8 0x00000000U /*!< AHB clock divided by 8 selected as SysTick clock source.*/ +#define DDL_SYSTICK_CLKSOURCE_HCLK SysTick_CTRL_CLKSOURCE_Msk /*!< AHB clock selected as SysTick clock source. */ +/** + * @} + */ + +/** @defgroup CORTEX_DDL_EC_FAULT Handler Fault type + * @{ + */ +#define DDL_HANDLER_FAULT_USG SCB_SHCSR_USGFAULTENA_Msk /*!< Usage fault */ +#define DDL_HANDLER_FAULT_BUS SCB_SHCSR_BUSFAULTENA_Msk /*!< Bus fault */ +#define DDL_HANDLER_FAULT_MEM SCB_SHCSR_MEMFAULTENA_Msk /*!< Memory management fault */ +/** + * @} + */ + +#if __MPU_PRESENT + +/** @defgroup CORTEX_DDL_EC_CTRL_HFNMI_PRIVDEF MPU Control + * @{ + */ +#define DDL_MPU_CTRL_HFNMI_PRIVDEF_NONE 0x00000000U /*!< Disable NMI and privileged SW access */ +#define DDL_MPU_CTRL_HARDFAULT_NMI MPU_CTRL_HFNMIENA_Msk /*!< Enables the operation of MPU during hard fault, NMI, and FAULTMASK handlers */ +#define DDL_MPU_CTRL_PRIVILEGED_DEFAULT MPU_CTRL_PRIVDEFENA_Msk /*!< Enable privileged software access to default memory map */ +#define DDL_MPU_CTRL_HFNMI_PRIVDEF (MPU_CTRL_HFNMIENA_Msk | MPU_CTRL_PRIVDEFENA_Msk) /*!< Enable NMI and privileged SW access */ +/** + * @} + */ + +/** @defgroup CORTEX_DDL_EC_REGION MPU Region Number + * @{ + */ +#define DDL_MPU_REGION_NUMBER0 0x00U /*!< REGION Number 0 */ +#define DDL_MPU_REGION_NUMBER1 0x01U /*!< REGION Number 1 */ +#define DDL_MPU_REGION_NUMBER2 0x02U /*!< REGION Number 2 */ +#define DDL_MPU_REGION_NUMBER3 0x03U /*!< REGION Number 3 */ +#define DDL_MPU_REGION_NUMBER4 0x04U /*!< REGION Number 4 */ +#define DDL_MPU_REGION_NUMBER5 0x05U /*!< REGION Number 5 */ +#define DDL_MPU_REGION_NUMBER6 0x06U /*!< REGION Number 6 */ +#define DDL_MPU_REGION_NUMBER7 0x07U /*!< REGION Number 7 */ +/** + * @} + */ + +/** @defgroup CORTEX_DDL_EC_REGION_SIZE MPU Region Size + * @{ + */ +#define DDL_MPU_REGION_SIZE_32B (0x04U << MPU_RASR_SIZE_Pos) /*!< 32B Size of the MPU protection region */ +#define DDL_MPU_REGION_SIZE_64B (0x05U << MPU_RASR_SIZE_Pos) /*!< 64B Size of the MPU protection region */ +#define DDL_MPU_REGION_SIZE_128B (0x06U << MPU_RASR_SIZE_Pos) /*!< 128B Size of the MPU protection region */ +#define DDL_MPU_REGION_SIZE_256B (0x07U << MPU_RASR_SIZE_Pos) /*!< 256B Size of the MPU protection region */ +#define DDL_MPU_REGION_SIZE_512B (0x08U << MPU_RASR_SIZE_Pos) /*!< 512B Size of the MPU protection region */ +#define DDL_MPU_REGION_SIZE_1KB (0x09U << MPU_RASR_SIZE_Pos) /*!< 1KB Size of the MPU protection region */ +#define DDL_MPU_REGION_SIZE_2KB (0x0AU << MPU_RASR_SIZE_Pos) /*!< 2KB Size of the MPU protection region */ +#define DDL_MPU_REGION_SIZE_4KB (0x0BU << MPU_RASR_SIZE_Pos) /*!< 4KB Size of the MPU protection region */ +#define DDL_MPU_REGION_SIZE_8KB (0x0CU << MPU_RASR_SIZE_Pos) /*!< 8KB Size of the MPU protection region */ +#define DDL_MPU_REGION_SIZE_16KB (0x0DU << MPU_RASR_SIZE_Pos) /*!< 16KB Size of the MPU protection region */ +#define DDL_MPU_REGION_SIZE_32KB (0x0EU << MPU_RASR_SIZE_Pos) /*!< 32KB Size of the MPU protection region */ +#define DDL_MPU_REGION_SIZE_64KB (0x0FU << MPU_RASR_SIZE_Pos) /*!< 64KB Size of the MPU protection region */ +#define DDL_MPU_REGION_SIZE_128KB (0x10U << MPU_RASR_SIZE_Pos) /*!< 128KB Size of the MPU protection region */ +#define DDL_MPU_REGION_SIZE_256KB (0x11U << MPU_RASR_SIZE_Pos) /*!< 256KB Size of the MPU protection region */ +#define DDL_MPU_REGION_SIZE_512KB (0x12U << MPU_RASR_SIZE_Pos) /*!< 512KB Size of the MPU protection region */ +#define DDL_MPU_REGION_SIZE_1MB (0x13U << MPU_RASR_SIZE_Pos) /*!< 1MB Size of the MPU protection region */ +#define DDL_MPU_REGION_SIZE_2MB (0x14U << MPU_RASR_SIZE_Pos) /*!< 2MB Size of the MPU protection region */ +#define DDL_MPU_REGION_SIZE_4MB (0x15U << MPU_RASR_SIZE_Pos) /*!< 4MB Size of the MPU protection region */ +#define DDL_MPU_REGION_SIZE_8MB (0x16U << MPU_RASR_SIZE_Pos) /*!< 8MB Size of the MPU protection region */ +#define DDL_MPU_REGION_SIZE_16MB (0x17U << MPU_RASR_SIZE_Pos) /*!< 16MB Size of the MPU protection region */ +#define DDL_MPU_REGION_SIZE_32MB (0x18U << MPU_RASR_SIZE_Pos) /*!< 32MB Size of the MPU protection region */ +#define DDL_MPU_REGION_SIZE_64MB (0x19U << MPU_RASR_SIZE_Pos) /*!< 64MB Size of the MPU protection region */ +#define DDL_MPU_REGION_SIZE_128MB (0x1AU << MPU_RASR_SIZE_Pos) /*!< 128MB Size of the MPU protection region */ +#define DDL_MPU_REGION_SIZE_256MB (0x1BU << MPU_RASR_SIZE_Pos) /*!< 256MB Size of the MPU protection region */ +#define DDL_MPU_REGION_SIZE_512MB (0x1CU << MPU_RASR_SIZE_Pos) /*!< 512MB Size of the MPU protection region */ +#define DDL_MPU_REGION_SIZE_1GB (0x1DU << MPU_RASR_SIZE_Pos) /*!< 1GB Size of the MPU protection region */ +#define DDL_MPU_REGION_SIZE_2GB (0x1EU << MPU_RASR_SIZE_Pos) /*!< 2GB Size of the MPU protection region */ +#define DDL_MPU_REGION_SIZE_4GB (0x1FU << MPU_RASR_SIZE_Pos) /*!< 4GB Size of the MPU protection region */ +/** + * @} + */ + +/** @defgroup CORTEX_DDL_EC_REGION_PRIVILEDGES MPU Region Privileges + * @{ + */ +#define DDL_MPU_REGION_NO_ACCESS (0x00U << MPU_RASR_AP_Pos) /*!< No access*/ +#define DDL_MPU_REGION_PRIV_RW (0x01U << MPU_RASR_AP_Pos) /*!< RW privileged (privileged access only)*/ +#define DDL_MPU_REGION_PRIV_RW_URO (0x02U << MPU_RASR_AP_Pos) /*!< RW privileged - RO user (Write in a user program generates a fault) */ +#define DDL_MPU_REGION_FULL_ACCESS (0x03U << MPU_RASR_AP_Pos) /*!< RW privileged & user (Full access) */ +#define DDL_MPU_REGION_PRIV_RO (0x05U << MPU_RASR_AP_Pos) /*!< RO privileged (privileged read only)*/ +#define DDL_MPU_REGION_PRIV_RO_URO (0x06U << MPU_RASR_AP_Pos) /*!< RO privileged & user (read only) */ +/** + * @} + */ + +/** @defgroup CORTEX_DDL_EC_TEX MPU TEX Level + * @{ + */ +#define DDL_MPU_TEX_LEVEL0 (0x00U << MPU_RASR_TEX_Pos) /*!< b000 for TEX bits */ +#define DDL_MPU_TEX_LEVEL1 (0x01U << MPU_RASR_TEX_Pos) /*!< b001 for TEX bits */ +#define DDL_MPU_TEX_LEVEL2 (0x02U << MPU_RASR_TEX_Pos) /*!< b010 for TEX bits */ +#define DDL_MPU_TEX_LEVEL4 (0x04U << MPU_RASR_TEX_Pos) /*!< b100 for TEX bits */ +/** + * @} + */ + +/** @defgroup CORTEX_DDL_EC_INSTRUCTION_ACCESS MPU Instruction Access + * @{ + */ +#define DDL_MPU_INSTRUCTION_ACCESS_ENABLE 0x00U /*!< Instruction fetches enabled */ +#define DDL_MPU_INSTRUCTION_ACCESS_DISABLE MPU_RASR_XN_Msk /*!< Instruction fetches disabled*/ +/** + * @} + */ + +/** @defgroup CORTEX_DDL_EC_SHAREABLE_ACCESS MPU Shareable Access + * @{ + */ +#define DDL_MPU_ACCESS_SHAREABLE MPU_RASR_S_Msk /*!< Shareable memory attribute */ +#define DDL_MPU_ACCESS_NOT_SHAREABLE 0x00U /*!< Not Shareable memory attribute */ +/** + * @} + */ + +/** @defgroup CORTEX_DDL_EC_CACHEABLE_ACCESS MPU Cacheable Access + * @{ + */ +#define DDL_MPU_ACCESS_CACHEABLE MPU_RASR_C_Msk /*!< Cacheable memory attribute */ +#define DDL_MPU_ACCESS_NOT_CACHEABLE 0x00U /*!< Not Cacheable memory attribute */ +/** + * @} + */ + +/** @defgroup CORTEX_DDL_EC_BUFFERABLE_ACCESS MPU Bufferable Access + * @{ + */ +#define DDL_MPU_ACCESS_BUFFERABLE MPU_RASR_B_Msk /*!< Bufferable memory attribute */ +#define DDL_MPU_ACCESS_NOT_BUFFERABLE 0x00U /*!< Not Bufferable memory attribute */ +/** + * @} + */ +#endif /* __MPU_PRESENT */ +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ + +/* Exported functions --------------------------------------------------------*/ +/** @defgroup CORTEX_DDL_Exported_Functions CORTEX Exported Functions + * @{ + */ + +/** @defgroup CORTEX_DDL_EF_SYSTICK SYSTICK + * @{ + */ + +/** + * @brief This function checks if the Systick counter flag is active or not. + * @note It can be used in timeout function on application side. + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_SYSTICK_IsActiveCounterFlag(void) +{ + return ((SysTick->CTRL & SysTick_CTRL_COUNTFLAG_Msk) == (SysTick_CTRL_COUNTFLAG_Msk)); +} + +/** + * @brief Configures the SysTick clock source + * @param Source This parameter can be one of the following values: + * @arg @ref DDL_SYSTICK_CLKSOURCE_HCLK_DIV8 + * @arg @ref DDL_SYSTICK_CLKSOURCE_HCLK + * @retval None + */ +__STATIC_INLINE void DDL_SYSTICK_SetClkSource(uint32_t Source) +{ + if (Source == DDL_SYSTICK_CLKSOURCE_HCLK) + { + SET_BIT(SysTick->CTRL, DDL_SYSTICK_CLKSOURCE_HCLK); + } + else + { + CLEAR_BIT(SysTick->CTRL, DDL_SYSTICK_CLKSOURCE_HCLK); + } +} + +/** + * @brief Get the SysTick clock source + * @retval Returned value can be one of the following values: + * @arg @ref DDL_SYSTICK_CLKSOURCE_HCLK_DIV8 + * @arg @ref DDL_SYSTICK_CLKSOURCE_HCLK + */ +__STATIC_INLINE uint32_t DDL_SYSTICK_GetClkSource(void) +{ + return READ_BIT(SysTick->CTRL, DDL_SYSTICK_CLKSOURCE_HCLK); +} + +/** + * @brief Enable SysTick exception request + * @retval None + */ +__STATIC_INLINE void DDL_SYSTICK_EnableIT(void) +{ + SET_BIT(SysTick->CTRL, SysTick_CTRL_TICKINT_Msk); +} + +/** + * @brief Disable SysTick exception request + * @retval None + */ +__STATIC_INLINE void DDL_SYSTICK_DisableIT(void) +{ + CLEAR_BIT(SysTick->CTRL, SysTick_CTRL_TICKINT_Msk); +} + +/** + * @brief Checks if the SYSTICK interrupt is enabled or disabled. + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_SYSTICK_IsEnabledIT(void) +{ + return (READ_BIT(SysTick->CTRL, SysTick_CTRL_TICKINT_Msk) == (SysTick_CTRL_TICKINT_Msk)); +} + +/** + * @} + */ + +/** @defgroup CORTEX_DDL_EF_LOW_POWER_MODE LOW POWER MODE + * @{ + */ + +/** + * @brief Processor uses sleep as its low power mode + * @retval None + */ +__STATIC_INLINE void DDL_LPM_EnableSleep(void) +{ + /* Clear SLEEPDEEP bit of Cortex System Control Register */ + CLEAR_BIT(SCB->SCR, ((uint32_t)SCB_SCR_SLEEPDEEP_Msk)); +} + +/** + * @brief Processor uses deep sleep as its low power mode + * @retval None + */ +__STATIC_INLINE void DDL_LPM_EnableDeepSleep(void) +{ + /* Set SLEEPDEEP bit of Cortex System Control Register */ + SET_BIT(SCB->SCR, ((uint32_t)SCB_SCR_SLEEPDEEP_Msk)); +} + +/** + * @brief Configures sleep-on-exit when returning from Handler mode to Thread mode. + * @note Setting this bit to 1 enables an interrupt-driven application to avoid returning to an + * empty main application. + * @retval None + */ +__STATIC_INLINE void DDL_LPM_EnableSleepOnExit(void) +{ + /* Set SLEEPONEXIT bit of Cortex System Control Register */ + SET_BIT(SCB->SCR, ((uint32_t)SCB_SCR_SLEEPONEXIT_Msk)); +} + +/** + * @brief Do not sleep when returning to Thread mode. + * @retval None + */ +__STATIC_INLINE void DDL_LPM_DisableSleepOnExit(void) +{ + /* Clear SLEEPONEXIT bit of Cortex System Control Register */ + CLEAR_BIT(SCB->SCR, ((uint32_t)SCB_SCR_SLEEPONEXIT_Msk)); +} + +/** + * @brief Enabled events and all interrupts, including disabled interrupts, can wakeup the + * processor. + * @retval None + */ +__STATIC_INLINE void DDL_LPM_EnableEventOnPend(void) +{ + /* Set SEVEONPEND bit of Cortex System Control Register */ + SET_BIT(SCB->SCR, ((uint32_t)SCB_SCR_SEVONPEND_Msk)); +} + +/** + * @brief Only enabled interrupts or events can wakeup the processor, disabled interrupts are + * excluded + * @retval None + */ +__STATIC_INLINE void DDL_LPM_DisableEventOnPend(void) +{ + /* Clear SEVEONPEND bit of Cortex System Control Register */ + CLEAR_BIT(SCB->SCR, ((uint32_t)SCB_SCR_SEVONPEND_Msk)); +} + +/** + * @} + */ + +/** @defgroup CORTEX_DDL_EF_HANDLER HANDLER + * @{ + */ + +/** + * @brief Enable a fault in System handler control register (SHCSR) + * @param Fault This parameter can be a combination of the following values: + * @arg @ref DDL_HANDLER_FAULT_USG + * @arg @ref DDL_HANDLER_FAULT_BUS + * @arg @ref DDL_HANDLER_FAULT_MEM + * @retval None + */ +__STATIC_INLINE void DDL_HANDLER_EnableFault(uint32_t Fault) +{ + /* Enable the system handler fault */ + SET_BIT(SCB->SHCSR, Fault); +} + +/** + * @brief Disable a fault in System handler control register (SHCSR) + * @param Fault This parameter can be a combination of the following values: + * @arg @ref DDL_HANDLER_FAULT_USG + * @arg @ref DDL_HANDLER_FAULT_BUS + * @arg @ref DDL_HANDLER_FAULT_MEM + * @retval None + */ +__STATIC_INLINE void DDL_HANDLER_DisableFault(uint32_t Fault) +{ + /* Disable the system handler fault */ + CLEAR_BIT(SCB->SHCSR, Fault); +} + +/** + * @} + */ + +/** @defgroup CORTEX_DDL_EF_MCU_INFO MCU INFO + * @{ + */ + +/** + * @brief Get Implementer code + * @retval Value should be equal to 0x41 for ARM + */ +__STATIC_INLINE uint32_t DDL_CPUID_GetImplementer(void) +{ + return (uint32_t)(READ_BIT(SCB->CPUID, SCB_CPUID_IMPLEMENTER_Msk) >> SCB_CPUID_IMPLEMENTER_Pos); +} + +/** + * @brief Get Variant number (The r value in the rnpn product revision identifier) + * @retval Value between 0 and 255 (0x0: revision 0) + */ +__STATIC_INLINE uint32_t DDL_CPUID_GetVariant(void) +{ + return (uint32_t)(READ_BIT(SCB->CPUID, SCB_CPUID_VARIANT_Msk) >> SCB_CPUID_VARIANT_Pos); +} + +/** + * @brief Get Constant number + * @retval Value should be equal to 0xF for Cortex-M4 devices + */ +__STATIC_INLINE uint32_t DDL_CPUID_GetConstant(void) +{ + return (uint32_t)(READ_BIT(SCB->CPUID, SCB_CPUID_ARCHITECTURE_Msk) >> SCB_CPUID_ARCHITECTURE_Pos); +} + +/** + * @brief Get Part number + * @retval Value should be equal to 0xC24 for Cortex-M4 + */ +__STATIC_INLINE uint32_t DDL_CPUID_GetParNo(void) +{ + return (uint32_t)(READ_BIT(SCB->CPUID, SCB_CPUID_PARTNO_Msk) >> SCB_CPUID_PARTNO_Pos); +} + +/** + * @brief Get Revision number (The p value in the rnpn product revision identifier, indicates patch release) + * @retval Value between 0 and 255 (0x1: patch 1) + */ +__STATIC_INLINE uint32_t DDL_CPUID_GetRevision(void) +{ + return (uint32_t)(READ_BIT(SCB->CPUID, SCB_CPUID_REVISION_Msk) >> SCB_CPUID_REVISION_Pos); +} + +/** + * @} + */ + +#if __MPU_PRESENT +/** @defgroup CORTEX_DDL_EF_MPU MPU + * @{ + */ + +/** + * @brief Enable MPU with input options + * @param Options This parameter can be one of the following values: + * @arg @ref DDL_MPU_CTRL_HFNMI_PRIVDEF_NONE + * @arg @ref DDL_MPU_CTRL_HARDFAULT_NMI + * @arg @ref DDL_MPU_CTRL_PRIVILEGED_DEFAULT + * @arg @ref DDL_MPU_CTRL_HFNMI_PRIVDEF + * @retval None + */ +__STATIC_INLINE void DDL_MPU_Enable(uint32_t Options) +{ + /* Enable the MPU*/ + WRITE_REG(MPU->CTRL, (MPU_CTRL_ENABLE_Msk | Options)); + /* Ensure MPU settings take effects */ + __DSB(); + /* Sequence instruction fetches using update settings */ + __ISB(); +} + +/** + * @brief Disable MPU + * @retval None + */ +__STATIC_INLINE void DDL_MPU_Disable(void) +{ + /* Make sure outstanding transfers are done */ + __DMB(); + /* Disable MPU*/ + WRITE_REG(MPU->CTRL, 0U); +} + +/** + * @brief Check if MPU is enabled or not + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_MPU_IsEnabled(void) +{ + return (READ_BIT(MPU->CTRL, MPU_CTRL_ENABLE_Msk) == (MPU_CTRL_ENABLE_Msk)); +} + +/** + * @brief Enable a MPU region + * @param Region This parameter can be one of the following values: + * @arg @ref DDL_MPU_REGION_NUMBER0 + * @arg @ref DDL_MPU_REGION_NUMBER1 + * @arg @ref DDL_MPU_REGION_NUMBER2 + * @arg @ref DDL_MPU_REGION_NUMBER3 + * @arg @ref DDL_MPU_REGION_NUMBER4 + * @arg @ref DDL_MPU_REGION_NUMBER5 + * @arg @ref DDL_MPU_REGION_NUMBER6 + * @arg @ref DDL_MPU_REGION_NUMBER7 + * @retval None + */ +__STATIC_INLINE void DDL_MPU_EnableRegion(uint32_t Region) +{ + /* Set Region number */ + WRITE_REG(MPU->RNR, Region); + /* Enable the MPU region */ + SET_BIT(MPU->RASR, MPU_RASR_ENABLE_Msk); +} + +/** + * @brief Configure and enable a region + * @param Region This parameter can be one of the following values: + * @arg @ref DDL_MPU_REGION_NUMBER0 + * @arg @ref DDL_MPU_REGION_NUMBER1 + * @arg @ref DDL_MPU_REGION_NUMBER2 + * @arg @ref DDL_MPU_REGION_NUMBER3 + * @arg @ref DDL_MPU_REGION_NUMBER4 + * @arg @ref DDL_MPU_REGION_NUMBER5 + * @arg @ref DDL_MPU_REGION_NUMBER6 + * @arg @ref DDL_MPU_REGION_NUMBER7 + * @param Address Value of region base address + * @param SubRegionDisable Sub-region disable value between Min_Data = 0x00 and Max_Data = 0xFF + * @param Attributes This parameter can be a combination of the following values: + * @arg @ref DDL_MPU_REGION_SIZE_32B or @ref DDL_MPU_REGION_SIZE_64B or @ref DDL_MPU_REGION_SIZE_128B or @ref DDL_MPU_REGION_SIZE_256B or @ref DDL_MPU_REGION_SIZE_512B + * or @ref DDL_MPU_REGION_SIZE_1KB or @ref DDL_MPU_REGION_SIZE_2KB or @ref DDL_MPU_REGION_SIZE_4KB or @ref DDL_MPU_REGION_SIZE_8KB or @ref DDL_MPU_REGION_SIZE_16KB + * or @ref DDL_MPU_REGION_SIZE_32KB or @ref DDL_MPU_REGION_SIZE_64KB or @ref DDL_MPU_REGION_SIZE_128KB or @ref DDL_MPU_REGION_SIZE_256KB or @ref DDL_MPU_REGION_SIZE_512KB + * or @ref DDL_MPU_REGION_SIZE_1MB or @ref DDL_MPU_REGION_SIZE_2MB or @ref DDL_MPU_REGION_SIZE_4MB or @ref DDL_MPU_REGION_SIZE_8MB or @ref DDL_MPU_REGION_SIZE_16MB + * or @ref DDL_MPU_REGION_SIZE_32MB or @ref DDL_MPU_REGION_SIZE_64MB or @ref DDL_MPU_REGION_SIZE_128MB or @ref DDL_MPU_REGION_SIZE_256MB or @ref DDL_MPU_REGION_SIZE_512MB + * or @ref DDL_MPU_REGION_SIZE_1GB or @ref DDL_MPU_REGION_SIZE_2GB or @ref DDL_MPU_REGION_SIZE_4GB + * @arg @ref DDL_MPU_REGION_NO_ACCESS or @ref DDL_MPU_REGION_PRIV_RW or @ref DDL_MPU_REGION_PRIV_RW_URO or @ref DDL_MPU_REGION_FULL_ACCESS + * or @ref DDL_MPU_REGION_PRIV_RO or @ref DDL_MPU_REGION_PRIV_RO_URO + * @arg @ref DDL_MPU_TEX_LEVEL0 or @ref DDL_MPU_TEX_LEVEL1 or @ref DDL_MPU_TEX_LEVEL2 or @ref DDL_MPU_TEX_LEVEL4 + * @arg @ref DDL_MPU_INSTRUCTION_ACCESS_ENABLE or @ref DDL_MPU_INSTRUCTION_ACCESS_DISABLE + * @arg @ref DDL_MPU_ACCESS_SHAREABLE or @ref DDL_MPU_ACCESS_NOT_SHAREABLE + * @arg @ref DDL_MPU_ACCESS_CACHEABLE or @ref DDL_MPU_ACCESS_NOT_CACHEABLE + * @arg @ref DDL_MPU_ACCESS_BUFFERABLE or @ref DDL_MPU_ACCESS_NOT_BUFFERABLE + * @retval None + */ +__STATIC_INLINE void DDL_MPU_ConfigRegion(uint32_t Region, uint32_t SubRegionDisable, uint32_t Address, uint32_t Attributes) +{ + /* Set Region number */ + WRITE_REG(MPU->RNR, Region); + /* Set base address */ + WRITE_REG(MPU->RBAR, (Address & 0xFFFFFFE0U)); + /* Configure MPU */ + WRITE_REG(MPU->RASR, (MPU_RASR_ENABLE_Msk | Attributes | SubRegionDisable << MPU_RASR_SRD_Pos)); +} + +/** + * @brief Disable a region + * @param Region This parameter can be one of the following values: + * @arg @ref DDL_MPU_REGION_NUMBER0 + * @arg @ref DDL_MPU_REGION_NUMBER1 + * @arg @ref DDL_MPU_REGION_NUMBER2 + * @arg @ref DDL_MPU_REGION_NUMBER3 + * @arg @ref DDL_MPU_REGION_NUMBER4 + * @arg @ref DDL_MPU_REGION_NUMBER5 + * @arg @ref DDL_MPU_REGION_NUMBER6 + * @arg @ref DDL_MPU_REGION_NUMBER7 + * @retval None + */ +__STATIC_INLINE void DDL_MPU_DisableRegion(uint32_t Region) +{ + /* Set Region number */ + WRITE_REG(MPU->RNR, Region); + /* Disable the MPU region */ + CLEAR_BIT(MPU->RASR, MPU_RASR_ENABLE_Msk); +} + +/** + * @} + */ + +#endif /* __MPU_PRESENT */ +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* APM32F4xx_DDL_CORTEX_H */ + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_crc.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_crc.h new file mode 100644 index 0000000000..b5c5f3604e --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_crc.h @@ -0,0 +1,220 @@ +/** + * + * @file apm32f4xx_ddl_crc.h + * @brief Header file of CRC DDL module. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef APM32F4xx_DDL_CRC_H +#define APM32F4xx_DDL_CRC_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx.h" + +/** @addtogroup APM32F4xx_DDL_Driver + * @{ + */ + +#if defined(CRC) + +/** @defgroup CRC_DDL CRC + * @{ + */ + +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/* Private macros ------------------------------------------------------------*/ + +/* Exported types ------------------------------------------------------------*/ +/* Exported constants --------------------------------------------------------*/ +/** @defgroup CRC_DDL_Exported_Constants CRC Exported Constants + * @{ + */ + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ +/** @defgroup CRC_DDL_Exported_Macros CRC Exported Macros + * @{ + */ + +/** @defgroup CRC_DDL_EM_WRITE_READ Common Write and read registers Macros + * @{ + */ + +/** + * @brief Write a value in CRC register + * @param __INSTANCE__ CRC Instance + * @param __REG__ Register to be written + * @param __VALUE__ Value to be written in the register + * @retval None + */ +#define DDL_CRC_WriteReg(__INSTANCE__, __REG__, __VALUE__) WRITE_REG(__INSTANCE__->__REG__, __VALUE__) + +/** + * @brief Read a value in CRC register + * @param __INSTANCE__ CRC Instance + * @param __REG__ Register to be read + * @retval Register value + */ +#define DDL_CRC_ReadReg(__INSTANCE__, __REG__) READ_REG(__INSTANCE__->__REG__) +/** + * @} + */ + +/** + * @} + */ + + +/* Exported functions --------------------------------------------------------*/ +/** @defgroup CRC_DDL_Exported_Functions CRC Exported Functions + * @{ + */ + +/** @defgroup CRC_DDL_EF_Configuration CRC Configuration functions + * @{ + */ + +/** + * @brief Reset the CRC calculation unit. + * @note If Programmable Initial CRC value feature + * is available, also set the Data Register to the value stored in the + * CRC_INIT register, otherwise, reset Data Register to its default value. + * @param CRCx CRC Instance + * @retval None + */ +__STATIC_INLINE void DDL_CRC_ResetCRCCalculationUnit(CRC_TypeDef *CRCx) +{ + SET_BIT(CRCx->CTRL, CRC_CTRL_RST); +} + +/** + * @} + */ + +/** @defgroup CRC_DDL_EF_Data_Management Data_Management + * @{ + */ + +/** + * @brief Write given 32-bit data to the CRC calculator + * @param CRCx CRC Instance + * @param InData value to be provided to CRC calculator between between Min_Data=0 and Max_Data=0xFFFFFFFF + * @retval None + */ +__STATIC_INLINE void DDL_CRC_FeedData32(CRC_TypeDef *CRCx, uint32_t InData) +{ + WRITE_REG(CRCx->DATA, InData); +} + +/** + * @brief Return current CRC calculation result. 32 bits value is returned. + * @param CRCx CRC Instance + * @retval Current CRC calculation result as stored in CRC_DATA register (32 bits). + */ +__STATIC_INLINE uint32_t DDL_CRC_ReadData32(CRC_TypeDef *CRCx) +{ + return (uint32_t)(READ_REG(CRCx->DATA)); +} + +/** + * @brief Return data stored in the Independent Data(IDR) register. + * @note This register can be used as a temporary storage location for one byte. + * @param CRCx CRC Instance + * @retval Value stored in CRC_INDATA register (General-purpose 8-bit data register). + */ +__STATIC_INLINE uint32_t DDL_CRC_Read_IDR(CRC_TypeDef *CRCx) +{ + return (uint32_t)(READ_REG(CRCx->INDATA)); +} + +/** + * @brief Store data in the Independent Data(IDR) register. + * @note This register can be used as a temporary storage location for one byte. + * @param CRCx CRC Instance + * @param InData value to be stored in CRC_INDATA register (8-bit) between Min_Data=0 and Max_Data=0xFF + * @retval None + */ +__STATIC_INLINE void DDL_CRC_Write_IDR(CRC_TypeDef *CRCx, uint32_t InData) +{ + *((uint8_t __IO *)(&CRCx->INDATA)) = (uint8_t) InData; +} +/** + * @} + */ + +#if defined(USE_FULL_DDL_DRIVER) +/** @defgroup CRC_DDL_EF_Init Initialization and de-initialization functions + * @{ + */ + +ErrorStatus DDL_CRC_DeInit(CRC_TypeDef *CRCx); + +/** + * @} + */ +#endif /* USE_FULL_DDL_DRIVER */ + +/** + * @} + */ + +/** + * @} + */ + +#endif /* defined(CRC) */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* APM32F4xx_DDL_CRC_H */ diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_dac.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_dac.h new file mode 100644 index 0000000000..3b795a1d65 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_dac.h @@ -0,0 +1,1410 @@ +/** + * + * @file apm32f4xx_ddl_dac.h + * @brief Header file of DAC DDL module. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + * + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef APM32F4xx_DDL_DAC_H +#define APM32F4xx_DDL_DAC_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx.h" + +/** @addtogroup APM32F4xx_DDL_Driver + * @{ + */ + +#if defined(DAC) + +/** @defgroup DAC_DDL DAC + * @{ + */ + +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ + +/* Private constants ---------------------------------------------------------*/ +/** @defgroup DAC_DDL_Private_Constants DAC Private Constants + * @{ + */ + +/* Internal masks for DAC channels definition */ +/* To select into literal DDL_DAC_CHANNEL_x the relevant bits for: */ +/* - channel bits position into registers CR, MCR, CCR, SHHR, SHRR */ +/* - channel bits position into register SWTRIG */ +/* - channel register offset of data holding register DHRx */ +/* - channel register offset of data output register DORx */ +#define DAC_CTRL_CH1_BITOFFSET 0UL /* Position of channel bits into registers + CR, MCR, CCR, SHHR, SHRR of channel 1 */ +#if defined(DAC_CHANNEL2_SUPPORT) +#define DAC_CTRL_CH2_BITOFFSET 16UL /* Position of channel bits into registers + CR, MCR, CCR, SHHR, SHRR of channel 2 */ +#define DAC_CTRL_CHX_BITOFFSET_MASK (DAC_CTRL_CH1_BITOFFSET | DAC_CTRL_CH2_BITOFFSET) +#else +#define DAC_CTRL_CHX_BITOFFSET_MASK (DAC_CTRL_CH1_BITOFFSET) +#endif /* DAC_CHANNEL2_SUPPORT */ + +#define DAC_SWTR_CH1 (DAC_SWTRG_SWTRG1) /* Channel bit into register SWTRIGR of channel 1. */ +#if defined(DAC_CHANNEL2_SUPPORT) +#define DAC_SWTR_CH2 (DAC_SWTRG_SWTRG2) /* Channel bit into register SWTRIGR of channel 2. */ +#define DAC_SWTR_CHX_MASK (DAC_SWTR_CH1 | DAC_SWTR_CH2) +#else +#define DAC_SWTR_CHX_MASK (DAC_SWTR_CH1) +#endif /* DAC_CHANNEL2_SUPPORT */ + +#define DAC_REG_DHR12R1_REGOFFSET 0x00000000UL /* Register DHR12Rx channel 1 taken as reference */ +#define DAC_REG_DHR12L1_REGOFFSET 0x00100000UL /* Register offset of DHR12Lx channel 1 versus + DHR12Rx channel 1 (shifted left of 20 bits) */ +#define DAC_REG_DHR8R1_REGOFFSET 0x02000000UL /* Register offset of DHR8Rx channel 1 versus + DHR12Rx channel 1 (shifted left of 24 bits) */ +#if defined(DAC_CHANNEL2_SUPPORT) +#define DAC_REG_DHR12R2_REGOFFSET 0x00030000UL /* Register offset of DHR12Rx channel 2 versus + DHR12Rx channel 1 (shifted left of 16 bits) */ +#define DAC_REG_DHR12L2_REGOFFSET 0x00400000UL /* Register offset of DHR12Lx channel 2 versus + DHR12Rx channel 1 (shifted left of 20 bits) */ +#define DAC_REG_DHR8R2_REGOFFSET 0x05000000UL /* Register offset of DHR8Rx channel 2 versus + DHR12Rx channel 1 (shifted left of 24 bits) */ +#endif /* DAC_CHANNEL2_SUPPORT */ +#define DAC_REG_DHR12RX_REGOFFSET_MASK 0x000F0000UL +#define DAC_REG_DHR12LX_REGOFFSET_MASK 0x00F00000UL +#define DAC_REG_DHR8RX_REGOFFSET_MASK 0x0F000000UL +#define DAC_REG_DHRX_REGOFFSET_MASK (DAC_REG_DHR12RX_REGOFFSET_MASK\ + | DAC_REG_DHR12LX_REGOFFSET_MASK | DAC_REG_DHR8RX_REGOFFSET_MASK) + +#define DAC_REG_DOR1_REGOFFSET 0x00000000UL /* Register DORx channel 1 taken as reference */ +#if defined(DAC_CHANNEL2_SUPPORT) +#define DAC_REG_DOR2_REGOFFSET 0x10000000UL /* Register offset of DORx channel 1 versus + DORx channel 2 (shifted left of 28 bits) */ +#define DAC_REG_DORX_REGOFFSET_MASK (DAC_REG_DOR1_REGOFFSET | DAC_REG_DOR2_REGOFFSET) +#endif /* DAC_CHANNEL2_SUPPORT */ + + +#define DAC_REG_DHR_REGOFFSET_MASK_POSBIT0 0x0000000FUL /* Mask of data hold registers offset (DHR12Rx, + DHR12Lx, DHR8Rx, ...) when shifted to position 0 */ +#define DAC_REG_DORX_REGOFFSET_MASK_POSBIT0 0x00000001UL /* Mask of DORx registers offset when shifted + to position 0 */ +#define DAC_REG_SHSRX_REGOFFSET_MASK_POSBIT0 0x00000001UL /* Mask of SHSRx registers offset when shifted + to position 0 */ + +#define DAC_REG_DHR12RX_REGOFFSET_BITOFFSET_POS 16UL /* Position of bits register offset of DHR12Rx + channel 1 or 2 versus DHR12Rx channel 1 + (shifted left of 16 bits) */ +#define DAC_REG_DHR12LX_REGOFFSET_BITOFFSET_POS 20UL /* Position of bits register offset of DHR12Lx + channel 1 or 2 versus DHR12Rx channel 1 + (shifted left of 20 bits) */ +#define DAC_REG_DHR8RX_REGOFFSET_BITOFFSET_POS 24UL /* Position of bits register offset of DHR8Rx + channel 1 or 2 versus DHR12Rx channel 1 + (shifted left of 24 bits) */ +#define DAC_REG_DORX_REGOFFSET_BITOFFSET_POS 28UL /* Position of bits register offset of DORx + channel 1 or 2 versus DORx channel 1 + (shifted left of 28 bits) */ + +/* DAC registers bits positions */ +#if defined(DAC_CHANNEL2_SUPPORT) +#endif +#define DAC_DH12RDUAL_DATACH2_BITOFFSET_POS DAC_DH12RDUAL_DATACH2_Pos +#define DAC_DH12LDUAL_DATACH2_BITOFFSET_POS DAC_DH12LDUAL_DATACH2_Pos +#define DAC_DH8RDUAL_DATACH2_BITOFFSET_POS DAC_DH8RDUAL_DATACH2_Pos + +/* Miscellaneous data */ +#define DAC_DIGITAL_SCALE_12BITS 4095UL /* Full-scale digital value with a resolution of 12 + bits (voltage range determined by analog voltage + references Vref+ and Vref-, refer to reference manual) */ + +/** + * @} + */ + + +/* Private macros ------------------------------------------------------------*/ +/** @defgroup DAC_DDL_Private_Macros DAC Private Macros + * @{ + */ + +/** + * @brief Driver macro reserved for internal use: set a pointer to + * a register from a register basis from which an offset + * is applied. + * @param __REG__ Register basis from which the offset is applied. + * @param __REG_OFFFSET__ Offset to be applied (unit: number of registers). + * @retval Pointer to register address + */ +#define __DAC_PTR_REG_OFFSET(__REG__, __REG_OFFFSET__) \ + ((uint32_t *)((uint32_t) ((uint32_t)(&(__REG__)) + ((__REG_OFFFSET__) << 2UL)))) + +/** + * @} + */ + + +/* Exported types ------------------------------------------------------------*/ +#if defined(USE_FULL_DDL_DRIVER) +/** @defgroup DAC_DDL_ES_INIT DAC Exported Init structure + * @{ + */ + +/** + * @brief Structure definition of some features of DAC instance. + */ +typedef struct +{ + uint32_t TriggerSource; /*!< Set the conversion trigger source for the selected DAC channel: + internal (SW start) or from external peripheral + (timer event, external interrupt line). + This parameter can be a value of @ref DAC_DDL_EC_TRIGGER_SOURCE + + This feature can be modified afterwards using unitary + function @ref DDL_DAC_SetTriggerSource(). */ + + uint32_t WaveAutoGeneration; /*!< Set the waveform automatic generation mode for the selected DAC channel. + This parameter can be a value of @ref DAC_DDL_EC_WAVE_AUTO_GENERATION_MODE + + This feature can be modified afterwards using unitary + function @ref DDL_DAC_SetWaveAutoGeneration(). */ + + uint32_t WaveAutoGenerationConfig; /*!< Set the waveform automatic generation mode for the selected DAC channel. + If waveform automatic generation mode is set to noise, this parameter + can be a value of @ref DAC_DDL_EC_WAVE_NOISE_LFSR_UNMASK_BITS + If waveform automatic generation mode is set to triangle, + this parameter can be a value of @ref DAC_DDL_EC_WAVE_TRIANGLE_AMPLITUDE + @note If waveform automatic generation mode is disabled, + this parameter is discarded. + + This feature can be modified afterwards using unitary + function @ref DDL_DAC_SetWaveNoiseLFSR(), + @ref DDL_DAC_SetWaveTriangleAmplitude() + depending on the wave automatic generation selected. */ + + uint32_t OutputBuffer; /*!< Set the output buffer for the selected DAC channel. + This parameter can be a value of @ref DAC_DDL_EC_OUTPUT_BUFFER + + This feature can be modified afterwards using unitary + function @ref DDL_DAC_SetOutputBuffer(). */ +} DDL_DAC_InitTypeDef; + +/** + * @} + */ +#endif /* USE_FULL_DDL_DRIVER */ + +/* Exported constants --------------------------------------------------------*/ +/** @defgroup DAC_DDL_Exported_Constants DAC Exported Constants + * @{ + */ + +/** @defgroup DAC_DDL_EC_GET_FLAG DAC flags + * @brief Flags defines which can be used with DDL_DAC_ReadReg function + * @{ + */ +/* DAC channel 1 flags */ +#define DDL_DAC_FLAG_DMAUDR1 (DAC_STS_DMAUDFLG1) /*!< DAC channel 1 flag DMA underrun */ +#if defined(DAC_CHANNEL2_SUPPORT) +/* DAC channel 2 flags */ +#define DDL_DAC_FLAG_DMAUDR2 (DAC_STS_DMAUDFLG2) /*!< DAC channel 2 flag DMA underrun */ +#endif /* DAC_CHANNEL2_SUPPORT */ +/** + * @} + */ + +/** @defgroup DAC_DDL_EC_IT DAC interruptions + * @brief IT defines which can be used with DDL_DAC_ReadReg and DDL_DAC_WriteReg functions + * @{ + */ +#define DDL_DAC_IT_DMAUDRIE1 (DAC_CTRL_DMAUDIEN1) /*!< DAC channel 1 interruption DMA underrun */ +#if defined(DAC_CHANNEL2_SUPPORT) +#define DDL_DAC_IT_DMAUDRIE2 (DAC_CTRL_DMAUDIEN2) /*!< DAC channel 2 interruption DMA underrun */ +#endif /* DAC_CHANNEL2_SUPPORT */ +/** + * @} + */ + +/** @defgroup DAC_DDL_EC_CHANNEL DAC channels + * @{ + */ +#define DDL_DAC_CHANNEL_1 (DAC_REG_DOR1_REGOFFSET | DAC_REG_DHR12R1_REGOFFSET | DAC_REG_DHR12L1_REGOFFSET | DAC_REG_DHR8R1_REGOFFSET | DAC_CTRL_CH1_BITOFFSET | DAC_SWTR_CH1) /*!< DAC channel 1 */ +#if defined(DAC_CHANNEL2_SUPPORT) +#define DDL_DAC_CHANNEL_2 (DAC_REG_DOR2_REGOFFSET | DAC_REG_DHR12R2_REGOFFSET | DAC_REG_DHR12L2_REGOFFSET | DAC_REG_DHR8R2_REGOFFSET | DAC_CTRL_CH2_BITOFFSET | DAC_SWTR_CH2) /*!< DAC channel 2 */ +#endif /* DAC_CHANNEL2_SUPPORT */ +/** + * @} + */ + +/** @defgroup DAC_DDL_EC_TRIGGER_SOURCE DAC trigger source + * @{ + */ +#define DDL_DAC_TRIG_SOFTWARE (DAC_CTRL_TRGSELCH1_2 | DAC_CTRL_TRGSELCH1_1 | DAC_CTRL_TRGSELCH1_0) /*!< DAC channel conversion trigger internal (SW start) */ +#define DDL_DAC_TRIG_EXT_TMR2_TRGO (DAC_CTRL_TRGSELCH1_2 ) /*!< DAC channel conversion trigger from external peripheral: TIM2 TRGO. */ +#define DDL_DAC_TRIG_EXT_TMR8_TRGO ( DAC_CTRL_TRGSELCH1_0) /*!< DAC channel conversion trigger from external peripheral: TIM8 TRGO. */ +#define DDL_DAC_TRIG_EXT_TMR4_TRGO (DAC_CTRL_TRGSELCH1_2 | DAC_CTRL_TRGSELCH1_0) /*!< DAC channel conversion trigger from external peripheral: TIM4 TRGO. */ +#define DDL_DAC_TRIG_EXT_TMR6_TRGO 0x00000000UL /*!< DAC channel conversion trigger from external peripheral: TIM6 TRGO. */ +#define DDL_DAC_TRIG_EXT_TMR7_TRGO ( DAC_CTRL_TRGSELCH1_1 ) /*!< DAC channel conversion trigger from external peripheral: TIM7 TRGO. */ +#define DDL_DAC_TRIG_EXT_TMR5_TRGO ( DAC_CTRL_TRGSELCH1_1 | DAC_CTRL_TRGSELCH1_0) /*!< DAC channel conversion trigger from external peripheral: TIM5 TRGO. */ +#define DDL_DAC_TRIG_EXT_EINT_LINE9 (DAC_CTRL_TRGSELCH1_2 | DAC_CTRL_TRGSELCH1_1 ) /*!< DAC channel conversion trigger from external peripheral: external interrupt line 9. */ +/** + * @} + */ + +/** @defgroup DAC_DDL_EC_WAVE_AUTO_GENERATION_MODE DAC waveform automatic generation mode + * @{ + */ +#define DDL_DAC_WAVE_AUTO_GENERATION_NONE 0x00000000UL /*!< DAC channel wave auto generation mode disabled. */ +#define DDL_DAC_WAVE_AUTO_GENERATION_NOISE ( DAC_CTRL_WAVENCH1_0) /*!< DAC channel wave auto generation mode enabled, set generated noise waveform. */ +#define DDL_DAC_WAVE_AUTO_GENERATION_TRIANGLE (DAC_CTRL_WAVENCH1_1 ) /*!< DAC channel wave auto generation mode enabled, set generated triangle waveform. */ +/** + * @} + */ + +/** @defgroup DAC_DDL_EC_WAVE_NOISE_LFSR_UNMASK_BITS DAC wave generation - Noise LFSR unmask bits + * @{ + */ +#define DDL_DAC_NOISE_LFSR_UNMASK_BIT0 0x00000000UL /*!< Noise wave generation, unmask LFSR bit0, for the selected DAC channel */ +#define DDL_DAC_NOISE_LFSR_UNMASK_BITS1_0 ( DAC_CTRL_MAMPSELCH1_0) /*!< Noise wave generation, unmask LFSR bits[1:0], for the selected DAC channel */ +#define DDL_DAC_NOISE_LFSR_UNMASK_BITS2_0 ( DAC_CTRL_MAMPSELCH1_1 ) /*!< Noise wave generation, unmask LFSR bits[2:0], for the selected DAC channel */ +#define DDL_DAC_NOISE_LFSR_UNMASK_BITS3_0 ( DAC_CTRL_MAMPSELCH1_1 | DAC_CTRL_MAMPSELCH1_0) /*!< Noise wave generation, unmask LFSR bits[3:0], for the selected DAC channel */ +#define DDL_DAC_NOISE_LFSR_UNMASK_BITS4_0 ( DAC_CTRL_MAMPSELCH1_2 ) /*!< Noise wave generation, unmask LFSR bits[4:0], for the selected DAC channel */ +#define DDL_DAC_NOISE_LFSR_UNMASK_BITS5_0 ( DAC_CTRL_MAMPSELCH1_2 | DAC_CTRL_MAMPSELCH1_0) /*!< Noise wave generation, unmask LFSR bits[5:0], for the selected DAC channel */ +#define DDL_DAC_NOISE_LFSR_UNMASK_BITS6_0 ( DAC_CTRL_MAMPSELCH1_2 | DAC_CTRL_MAMPSELCH1_1 ) /*!< Noise wave generation, unmask LFSR bits[6:0], for the selected DAC channel */ +#define DDL_DAC_NOISE_LFSR_UNMASK_BITS7_0 ( DAC_CTRL_MAMPSELCH1_2 | DAC_CTRL_MAMPSELCH1_1 | DAC_CTRL_MAMPSELCH1_0) /*!< Noise wave generation, unmask LFSR bits[7:0], for the selected DAC channel */ +#define DDL_DAC_NOISE_LFSR_UNMASK_BITS8_0 (DAC_CTRL_MAMPSELCH1_3 ) /*!< Noise wave generation, unmask LFSR bits[8:0], for the selected DAC channel */ +#define DDL_DAC_NOISE_LFSR_UNMASK_BITS9_0 (DAC_CTRL_MAMPSELCH1_3 | DAC_CTRL_MAMPSELCH1_0) /*!< Noise wave generation, unmask LFSR bits[9:0], for the selected DAC channel */ +#define DDL_DAC_NOISE_LFSR_UNMASK_BITS10_0 (DAC_CTRL_MAMPSELCH1_3 | DAC_CTRL_MAMPSELCH1_1 ) /*!< Noise wave generation, unmask LFSR bits[10:0], for the selected DAC channel */ +#define DDL_DAC_NOISE_LFSR_UNMASK_BITS11_0 (DAC_CTRL_MAMPSELCH1_3 | DAC_CTRL_MAMPSELCH1_1 | DAC_CTRL_MAMPSELCH1_0) /*!< Noise wave generation, unmask LFSR bits[11:0], for the selected DAC channel */ +/** + * @} + */ + +/** @defgroup DAC_DDL_EC_WAVE_TRIANGLE_AMPLITUDE DAC wave generation - Triangle amplitude + * @{ + */ +#define DDL_DAC_TRIANGLE_AMPLITUDE_1 0x00000000UL /*!< Triangle wave generation, amplitude of 1 LSB of DAC output range, for the selected DAC channel */ +#define DDL_DAC_TRIANGLE_AMPLITUDE_3 ( DAC_CTRL_MAMPSELCH1_0) /*!< Triangle wave generation, amplitude of 3 LSB of DAC output range, for the selected DAC channel */ +#define DDL_DAC_TRIANGLE_AMPLITUDE_7 ( DAC_CTRL_MAMPSELCH1_1 ) /*!< Triangle wave generation, amplitude of 7 LSB of DAC output range, for the selected DAC channel */ +#define DDL_DAC_TRIANGLE_AMPLITUDE_15 ( DAC_CTRL_MAMPSELCH1_1 | DAC_CTRL_MAMPSELCH1_0) /*!< Triangle wave generation, amplitude of 15 LSB of DAC output range, for the selected DAC channel */ +#define DDL_DAC_TRIANGLE_AMPLITUDE_31 ( DAC_CTRL_MAMPSELCH1_2 ) /*!< Triangle wave generation, amplitude of 31 LSB of DAC output range, for the selected DAC channel */ +#define DDL_DAC_TRIANGLE_AMPLITUDE_63 ( DAC_CTRL_MAMPSELCH1_2 | DAC_CTRL_MAMPSELCH1_0) /*!< Triangle wave generation, amplitude of 63 LSB of DAC output range, for the selected DAC channel */ +#define DDL_DAC_TRIANGLE_AMPLITUDE_127 ( DAC_CTRL_MAMPSELCH1_2 | DAC_CTRL_MAMPSELCH1_1 ) /*!< Triangle wave generation, amplitude of 127 LSB of DAC output range, for the selected DAC channel */ +#define DDL_DAC_TRIANGLE_AMPLITUDE_255 ( DAC_CTRL_MAMPSELCH1_2 | DAC_CTRL_MAMPSELCH1_1 | DAC_CTRL_MAMPSELCH1_0) /*!< Triangle wave generation, amplitude of 255 LSB of DAC output range, for the selected DAC channel */ +#define DDL_DAC_TRIANGLE_AMPLITUDE_511 (DAC_CTRL_MAMPSELCH1_3 ) /*!< Triangle wave generation, amplitude of 512 LSB of DAC output range, for the selected DAC channel */ +#define DDL_DAC_TRIANGLE_AMPLITUDE_1023 (DAC_CTRL_MAMPSELCH1_3 | DAC_CTRL_MAMPSELCH1_0) /*!< Triangle wave generation, amplitude of 1023 LSB of DAC output range, for the selected DAC channel */ +#define DDL_DAC_TRIANGLE_AMPLITUDE_2047 (DAC_CTRL_MAMPSELCH1_3 | DAC_CTRL_MAMPSELCH1_1 ) /*!< Triangle wave generation, amplitude of 2047 LSB of DAC output range, for the selected DAC channel */ +#define DDL_DAC_TRIANGLE_AMPLITUDE_4095 (DAC_CTRL_MAMPSELCH1_3 | DAC_CTRL_MAMPSELCH1_1 | DAC_CTRL_MAMPSELCH1_0) /*!< Triangle wave generation, amplitude of 4095 LSB of DAC output range, for the selected DAC channel */ +/** + * @} + */ + +/** @defgroup DAC_DDL_EC_OUTPUT_BUFFER DAC channel output buffer + * @{ + */ +#define DDL_DAC_OUTPUT_BUFFER_ENABLE 0x00000000UL /*!< The selected DAC channel output is buffered: higher drive current capability, but also higher current consumption */ +#define DDL_DAC_OUTPUT_BUFFER_DISABLE (DAC_CTRL_BUFFDCH1) /*!< The selected DAC channel output is not buffered: lower drive current capability, but also lower current consumption */ +/** + * @} + */ + +/** @defgroup DAC_DDL_EC_RESOLUTION DAC channel output resolution + * @{ + */ +#define DDL_DAC_RESOLUTION_12B 0x00000000UL /*!< DAC channel resolution 12 bits */ +#define DDL_DAC_RESOLUTION_8B 0x00000002UL /*!< DAC channel resolution 8 bits */ +/** + * @} + */ + +/** @defgroup DAC_DDL_EC_REGISTERS DAC registers compliant with specific purpose + * @{ + */ +/* List of DAC registers intended to be used (most commonly) with */ +/* DMA transfer. */ +/* Refer to function @ref DDL_DAC_DMA_GetRegAddr(). */ +#define DDL_DAC_DMA_REG_DATA_12BITS_RIGHT_ALIGNED DAC_REG_DHR12RX_REGOFFSET_BITOFFSET_POS /*!< DAC channel data holding register 12 bits right aligned */ +#define DDL_DAC_DMA_REG_DATA_12BITS_LEFT_ALIGNED DAC_REG_DHR12LX_REGOFFSET_BITOFFSET_POS /*!< DAC channel data holding register 12 bits left aligned */ +#define DDL_DAC_DMA_REG_DATA_8BITS_RIGHT_ALIGNED DAC_REG_DHR8RX_REGOFFSET_BITOFFSET_POS /*!< DAC channel data holding register 8 bits right aligned */ +/** + * @} + */ + +/** @defgroup DAC_DDL_EC_HW_DELAYS Definitions of DAC hardware constraints delays + * @note Only DAC peripheral HW delays are defined in DAC LL driver driver, + * not timeout values. + * For details on delays values, refer to descriptions in source code + * above each literal definition. + * @{ + */ + +/* Delay for DAC channel voltage settling time from DAC channel startup */ +/* (transition from disable to enable). */ +/* Note: DAC channel startup time depends on board application environment: */ +/* impedance connected to DAC channel output. */ +/* The delay below is specified under conditions: */ +/* - voltage maximum transition (lowest to highest value) */ +/* - until voltage reaches final value +-1LSB */ +/* - DAC channel output buffer enabled */ +/* - load impedance of 5kOhm (min), 50pF (max) */ +/* Literal set to maximum value (refer to device datasheet, */ +/* parameter "tWAKEUP"). */ +/* Unit: us */ +#define DDL_DAC_DELAY_STARTUP_VOLTAGE_SETTLING_US 15UL /*!< Delay for DAC channel voltage settling time from DAC channel startup (transition from disable to enable) */ + +/* Delay for DAC channel voltage settling time. */ +/* Note: DAC channel startup time depends on board application environment: */ +/* impedance connected to DAC channel output. */ +/* The delay below is specified under conditions: */ +/* - voltage maximum transition (lowest to highest value) */ +/* - until voltage reaches final value +-1LSB */ +/* - DAC channel output buffer enabled */ +/* - load impedance of 5kOhm min, 50pF max */ +/* Literal set to maximum value (refer to device datasheet, */ +/* parameter "tSETTLING"). */ +/* Unit: us */ +#define DDL_DAC_DELAY_VOLTAGE_SETTLING_US 12UL /*!< Delay for DAC channel voltage settling time */ + +/** + * @} + */ + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ +/** @defgroup DAC_DDL_Exported_Macros DAC Exported Macros + * @{ + */ + +/** @defgroup DAC_DDL_EM_WRITE_READ Common write and read registers macros + * @{ + */ + +/** + * @brief Write a value in DAC register + * @param __INSTANCE__ DAC Instance + * @param __REG__ Register to be written + * @param __VALUE__ Value to be written in the register + * @retval None + */ +#define DDL_DAC_WriteReg(__INSTANCE__, __REG__, __VALUE__) WRITE_REG(__INSTANCE__->__REG__, (__VALUE__)) + +/** + * @brief Read a value in DAC register + * @param __INSTANCE__ DAC Instance + * @param __REG__ Register to be read + * @retval Register value + */ +#define DDL_DAC_ReadReg(__INSTANCE__, __REG__) READ_REG(__INSTANCE__->__REG__) + +/** + * @} + */ + +/** @defgroup DAC_DDL_EM_HELPER_MACRO DAC helper macro + * @{ + */ + +/** + * @brief Helper macro to get DAC channel number in decimal format + * from literals DDL_DAC_CHANNEL_x. + * Example: + * __DDL_DAC_CHANNEL_TO_DECIMAL_NB(DDL_DAC_CHANNEL_1) + * will return decimal number "1". + * @note The input can be a value from functions where a channel + * number is returned. + * @param __CHANNEL__ This parameter can be one of the following values: + * @arg @ref DDL_DAC_CHANNEL_1 + * @arg @ref DDL_DAC_CHANNEL_2 (1) + * + * (1) On this APM32 serie, parameter not available on all devices. + * Refer to device datasheet for channels availability. + * @retval 1...2 (value "2" depending on DAC channel 2 availability) + */ +#define __DDL_DAC_CHANNEL_TO_DECIMAL_NB(__CHANNEL__) \ + ((__CHANNEL__) & DAC_SWTR_CHX_MASK) + +/** + * @brief Helper macro to get DAC channel in literal format DDL_DAC_CHANNEL_x + * from number in decimal format. + * Example: + * __DDL_DAC_DECIMAL_NB_TO_CHANNEL(1) + * will return a data equivalent to "DDL_DAC_CHANNEL_1". + * @note If the input parameter does not correspond to a DAC channel, + * this macro returns value '0'. + * @param __DECIMAL_NB__ 1...2 (value "2" depending on DAC channel 2 availability) + * @retval Returned value can be one of the following values: + * @arg @ref DDL_DAC_CHANNEL_1 + * @arg @ref DDL_DAC_CHANNEL_2 (1) + * + * (1) On this APM32 serie, parameter not available on all devices. + * Refer to device datasheet for channels availability. + */ +#if defined(DAC_CHANNEL2_SUPPORT) +#define __DDL_DAC_DECIMAL_NB_TO_CHANNEL(__DECIMAL_NB__) \ + (((__DECIMAL_NB__) == 1UL) \ + ? ( \ + DDL_DAC_CHANNEL_1 \ + ) \ + : \ + (((__DECIMAL_NB__) == 2UL) \ + ? ( \ + DDL_DAC_CHANNEL_2 \ + ) \ + : \ + ( \ + 0UL \ + ) \ + ) \ + ) +#else +#define __DDL_DAC_DECIMAL_NB_TO_CHANNEL(__DECIMAL_NB__) \ + (((__DECIMAL_NB__) == 1UL) \ + ? ( \ + DDL_DAC_CHANNEL_1 \ + ) \ + : \ + ( \ + 0UL \ + ) \ + ) +#endif /* DAC_CHANNEL2_SUPPORT */ + +/** + * @brief Helper macro to define the DAC conversion data full-scale digital + * value corresponding to the selected DAC resolution. + * @note DAC conversion data full-scale corresponds to voltage range + * determined by analog voltage references Vref+ and Vref- + * (refer to reference manual). + * @param __DAC_RESOLUTION__ This parameter can be one of the following values: + * @arg @ref DDL_DAC_RESOLUTION_12B + * @arg @ref DDL_DAC_RESOLUTION_8B + * @retval ADC conversion data equivalent voltage value (unit: mVolt) + */ +#define __DDL_DAC_DIGITAL_SCALE(__DAC_RESOLUTION__) \ + ((0x00000FFFUL) >> ((__DAC_RESOLUTION__) << 1UL)) + +/** + * @brief Helper macro to calculate the DAC conversion data (unit: digital + * value) corresponding to a voltage (unit: mVolt). + * @note This helper macro is intended to provide input data in voltage + * rather than digital value, + * to be used with LL DAC functions such as + * @ref DDL_DAC_ConvertData12RightAligned(). + * @note Analog reference voltage (Vref+) must be either known from + * user board environment or can be calculated using ADC measurement + * and ADC helper macro __DDL_ADC_CALC_VREFANALOG_VOLTAGE(). + * @param __VREFANALOG_VOLTAGE__ Analog reference voltage (unit: mV) + * @param __DAC_VOLTAGE__ Voltage to be generated by DAC channel + * (unit: mVolt). + * @param __DAC_RESOLUTION__ This parameter can be one of the following values: + * @arg @ref DDL_DAC_RESOLUTION_12B + * @arg @ref DDL_DAC_RESOLUTION_8B + * @retval DAC conversion data (unit: digital value) + */ +#define __DDL_DAC_CALC_VOLTAGE_TO_DATA(__VREFANALOG_VOLTAGE__,\ + __DAC_VOLTAGE__,\ + __DAC_RESOLUTION__) \ +((__DAC_VOLTAGE__) * __DDL_DAC_DIGITAL_SCALE(__DAC_RESOLUTION__) \ + / (__VREFANALOG_VOLTAGE__) \ +) + +/** + * @} + */ + +/** + * @} + */ + + +/* Exported functions --------------------------------------------------------*/ +/** @defgroup DAC_DDL_Exported_Functions DAC Exported Functions + * @{ + */ +/** + * @brief Set the conversion trigger source for the selected DAC channel. + * @note For conversion trigger source to be effective, DAC trigger + * must be enabled using function @ref DDL_DAC_EnableTrigger(). + * @note To set conversion trigger source, DAC channel must be disabled. + * Otherwise, the setting is discarded. + * @note Availability of parameters of trigger sources from timer + * depends on timers availability on the selected device. + * @param DACx DAC instance + * @param DAC_Channel This parameter can be one of the following values: + * @arg @ref DDL_DAC_CHANNEL_1 + * @arg @ref DDL_DAC_CHANNEL_2 (1) + * + * (1) On this APM32 serie, parameter not available on all devices. + * Refer to device datasheet for channels availability. + * @param TriggerSource This parameter can be one of the following values: + * @arg @ref DDL_DAC_TRIG_SOFTWARE + * @arg @ref DDL_DAC_TRIG_EXT_TMR8_TRGO + * @arg @ref DDL_DAC_TRIG_EXT_TMR7_TRGO + * @arg @ref DDL_DAC_TRIG_EXT_TMR6_TRGO + * @arg @ref DDL_DAC_TRIG_EXT_TMR5_TRGO + * @arg @ref DDL_DAC_TRIG_EXT_TMR4_TRGO + * @arg @ref DDL_DAC_TRIG_EXT_TMR2_TRGO + * @arg @ref DDL_DAC_TRIG_EXT_EINT_LINE9 + * @retval None + */ +__STATIC_INLINE void DDL_DAC_SetTriggerSource(DAC_TypeDef *DACx, uint32_t DAC_Channel, uint32_t TriggerSource) +{ + MODIFY_REG(DACx->CTRL, + DAC_CTRL_TRGSELCH1 << (DAC_Channel & DAC_CTRL_CHX_BITOFFSET_MASK), + TriggerSource << (DAC_Channel & DAC_CTRL_CHX_BITOFFSET_MASK)); +} + +/** + * @brief Get the conversion trigger source for the selected DAC channel. + * @note For conversion trigger source to be effective, DAC trigger + * must be enabled using function @ref DDL_DAC_EnableTrigger(). + * @note Availability of parameters of trigger sources from timer + * depends on timers availability on the selected device. + * @param DACx DAC instance + * @param DAC_Channel This parameter can be one of the following values: + * @arg @ref DDL_DAC_CHANNEL_1 + * @arg @ref DDL_DAC_CHANNEL_2 (1) + * + * (1) On this APM32 serie, parameter not available on all devices. + * Refer to device datasheet for channels availability. + * @retval Returned value can be one of the following values: + * @arg @ref DDL_DAC_TRIG_SOFTWARE + * @arg @ref DDL_DAC_TRIG_EXT_TMR8_TRGO + * @arg @ref DDL_DAC_TRIG_EXT_TMR7_TRGO + * @arg @ref DDL_DAC_TRIG_EXT_TMR6_TRGO + * @arg @ref DDL_DAC_TRIG_EXT_TMR5_TRGO + * @arg @ref DDL_DAC_TRIG_EXT_TMR4_TRGO + * @arg @ref DDL_DAC_TRIG_EXT_TMR2_TRGO + * @arg @ref DDL_DAC_TRIG_EXT_EINT_LINE9 + */ +__STATIC_INLINE uint32_t DDL_DAC_GetTriggerSource(DAC_TypeDef *DACx, uint32_t DAC_Channel) +{ + return (uint32_t)(READ_BIT(DACx->CTRL, DAC_CTRL_TRGSELCH1 << (DAC_Channel & DAC_CTRL_CHX_BITOFFSET_MASK)) + >> (DAC_Channel & DAC_CTRL_CHX_BITOFFSET_MASK) + ); +} + +/** + * @brief Set the waveform automatic generation mode + * for the selected DAC channel. + * @param DACx DAC instance + * @param DAC_Channel This parameter can be one of the following values: + * @arg @ref DDL_DAC_CHANNEL_1 + * @arg @ref DDL_DAC_CHANNEL_2 (1) + * + * (1) On this APM32 serie, parameter not available on all devices. + * Refer to device datasheet for channels availability. + * @param WaveAutoGeneration This parameter can be one of the following values: + * @arg @ref DDL_DAC_WAVE_AUTO_GENERATION_NONE + * @arg @ref DDL_DAC_WAVE_AUTO_GENERATION_NOISE + * @arg @ref DDL_DAC_WAVE_AUTO_GENERATION_TRIANGLE + * @retval None + */ +__STATIC_INLINE void DDL_DAC_SetWaveAutoGeneration(DAC_TypeDef *DACx, uint32_t DAC_Channel, uint32_t WaveAutoGeneration) +{ + MODIFY_REG(DACx->CTRL, + DAC_CTRL_WAVENCH1 << (DAC_Channel & DAC_CTRL_CHX_BITOFFSET_MASK), + WaveAutoGeneration << (DAC_Channel & DAC_CTRL_CHX_BITOFFSET_MASK)); +} + +/** + * @brief Get the waveform automatic generation mode + * for the selected DAC channel. + * @param DACx DAC instance + * @param DAC_Channel This parameter can be one of the following values: + * @arg @ref DDL_DAC_CHANNEL_1 + * @arg @ref DDL_DAC_CHANNEL_2 (1) + * + * (1) On this APM32 serie, parameter not available on all devices. + * Refer to device datasheet for channels availability. + * @retval Returned value can be one of the following values: + * @arg @ref DDL_DAC_WAVE_AUTO_GENERATION_NONE + * @arg @ref DDL_DAC_WAVE_AUTO_GENERATION_NOISE + * @arg @ref DDL_DAC_WAVE_AUTO_GENERATION_TRIANGLE + */ +__STATIC_INLINE uint32_t DDL_DAC_GetWaveAutoGeneration(DAC_TypeDef *DACx, uint32_t DAC_Channel) +{ + return (uint32_t)(READ_BIT(DACx->CTRL, DAC_CTRL_WAVENCH1 << (DAC_Channel & DAC_CTRL_CHX_BITOFFSET_MASK)) + >> (DAC_Channel & DAC_CTRL_CHX_BITOFFSET_MASK) + ); +} + +/** + * @brief Set the noise waveform generation for the selected DAC channel: + * Noise mode and parameters LFSR (linear feedback shift register). + * @note For wave generation to be effective, DAC channel + * wave generation mode must be enabled using + * function @ref DDL_DAC_SetWaveAutoGeneration(). + * @note This setting can be set when the selected DAC channel is disabled + * (otherwise, the setting operation is ignored). + * @param DACx DAC instance + * @param DAC_Channel This parameter can be one of the following values: + * @arg @ref DDL_DAC_CHANNEL_1 + * @arg @ref DDL_DAC_CHANNEL_2 (1) + * + * (1) On this APM32 serie, parameter not available on all devices. + * Refer to device datasheet for channels availability. + * @param NoiseLFSRMask This parameter can be one of the following values: + * @arg @ref DDL_DAC_NOISE_LFSR_UNMASK_BIT0 + * @arg @ref DDL_DAC_NOISE_LFSR_UNMASK_BITS1_0 + * @arg @ref DDL_DAC_NOISE_LFSR_UNMASK_BITS2_0 + * @arg @ref DDL_DAC_NOISE_LFSR_UNMASK_BITS3_0 + * @arg @ref DDL_DAC_NOISE_LFSR_UNMASK_BITS4_0 + * @arg @ref DDL_DAC_NOISE_LFSR_UNMASK_BITS5_0 + * @arg @ref DDL_DAC_NOISE_LFSR_UNMASK_BITS6_0 + * @arg @ref DDL_DAC_NOISE_LFSR_UNMASK_BITS7_0 + * @arg @ref DDL_DAC_NOISE_LFSR_UNMASK_BITS8_0 + * @arg @ref DDL_DAC_NOISE_LFSR_UNMASK_BITS9_0 + * @arg @ref DDL_DAC_NOISE_LFSR_UNMASK_BITS10_0 + * @arg @ref DDL_DAC_NOISE_LFSR_UNMASK_BITS11_0 + * @retval None + */ +__STATIC_INLINE void DDL_DAC_SetWaveNoiseLFSR(DAC_TypeDef *DACx, uint32_t DAC_Channel, uint32_t NoiseLFSRMask) +{ + MODIFY_REG(DACx->CTRL, + DAC_CTRL_MAMPSELCH1 << (DAC_Channel & DAC_CTRL_CHX_BITOFFSET_MASK), + NoiseLFSRMask << (DAC_Channel & DAC_CTRL_CHX_BITOFFSET_MASK)); +} + +/** + * @brief Get the noise waveform generation for the selected DAC channel: + * Noise mode and parameters LFSR (linear feedback shift register). + * @param DACx DAC instance + * @param DAC_Channel This parameter can be one of the following values: + * @arg @ref DDL_DAC_CHANNEL_1 + * @arg @ref DDL_DAC_CHANNEL_2 (1) + * + * (1) On this APM32 serie, parameter not available on all devices. + * Refer to device datasheet for channels availability. + * @retval Returned value can be one of the following values: + * @arg @ref DDL_DAC_NOISE_LFSR_UNMASK_BIT0 + * @arg @ref DDL_DAC_NOISE_LFSR_UNMASK_BITS1_0 + * @arg @ref DDL_DAC_NOISE_LFSR_UNMASK_BITS2_0 + * @arg @ref DDL_DAC_NOISE_LFSR_UNMASK_BITS3_0 + * @arg @ref DDL_DAC_NOISE_LFSR_UNMASK_BITS4_0 + * @arg @ref DDL_DAC_NOISE_LFSR_UNMASK_BITS5_0 + * @arg @ref DDL_DAC_NOISE_LFSR_UNMASK_BITS6_0 + * @arg @ref DDL_DAC_NOISE_LFSR_UNMASK_BITS7_0 + * @arg @ref DDL_DAC_NOISE_LFSR_UNMASK_BITS8_0 + * @arg @ref DDL_DAC_NOISE_LFSR_UNMASK_BITS9_0 + * @arg @ref DDL_DAC_NOISE_LFSR_UNMASK_BITS10_0 + * @arg @ref DDL_DAC_NOISE_LFSR_UNMASK_BITS11_0 + */ +__STATIC_INLINE uint32_t DDL_DAC_GetWaveNoiseLFSR(DAC_TypeDef *DACx, uint32_t DAC_Channel) +{ + return (uint32_t)(READ_BIT(DACx->CTRL, DAC_CTRL_MAMPSELCH1 << (DAC_Channel & DAC_CTRL_CHX_BITOFFSET_MASK)) + >> (DAC_Channel & DAC_CTRL_CHX_BITOFFSET_MASK) + ); +} + +/** + * @brief Set the triangle waveform generation for the selected DAC channel: + * triangle mode and amplitude. + * @note For wave generation to be effective, DAC channel + * wave generation mode must be enabled using + * function @ref DDL_DAC_SetWaveAutoGeneration(). + * @note This setting can be set when the selected DAC channel is disabled + * (otherwise, the setting operation is ignored). + * @param DACx DAC instance + * @param DAC_Channel This parameter can be one of the following values: + * @arg @ref DDL_DAC_CHANNEL_1 + * @arg @ref DDL_DAC_CHANNEL_2 (1) + * + * (1) On this APM32 serie, parameter not available on all devices. + * Refer to device datasheet for channels availability. + * @param TriangleAmplitude This parameter can be one of the following values: + * @arg @ref DDL_DAC_TRIANGLE_AMPLITUDE_1 + * @arg @ref DDL_DAC_TRIANGLE_AMPLITUDE_3 + * @arg @ref DDL_DAC_TRIANGLE_AMPLITUDE_7 + * @arg @ref DDL_DAC_TRIANGLE_AMPLITUDE_15 + * @arg @ref DDL_DAC_TRIANGLE_AMPLITUDE_31 + * @arg @ref DDL_DAC_TRIANGLE_AMPLITUDE_63 + * @arg @ref DDL_DAC_TRIANGLE_AMPLITUDE_127 + * @arg @ref DDL_DAC_TRIANGLE_AMPLITUDE_255 + * @arg @ref DDL_DAC_TRIANGLE_AMPLITUDE_511 + * @arg @ref DDL_DAC_TRIANGLE_AMPLITUDE_1023 + * @arg @ref DDL_DAC_TRIANGLE_AMPLITUDE_2047 + * @arg @ref DDL_DAC_TRIANGLE_AMPLITUDE_4095 + * @retval None + */ +__STATIC_INLINE void DDL_DAC_SetWaveTriangleAmplitude(DAC_TypeDef *DACx, uint32_t DAC_Channel, + uint32_t TriangleAmplitude) +{ + MODIFY_REG(DACx->CTRL, + DAC_CTRL_MAMPSELCH1 << (DAC_Channel & DAC_CTRL_CHX_BITOFFSET_MASK), + TriangleAmplitude << (DAC_Channel & DAC_CTRL_CHX_BITOFFSET_MASK)); +} + +/** + * @brief Get the triangle waveform generation for the selected DAC channel: + * triangle mode and amplitude. + * @param DACx DAC instance + * @param DAC_Channel This parameter can be one of the following values: + * @arg @ref DDL_DAC_CHANNEL_1 + * @arg @ref DDL_DAC_CHANNEL_2 (1) + * + * (1) On this APM32 serie, parameter not available on all devices. + * Refer to device datasheet for channels availability. + * @retval Returned value can be one of the following values: + * @arg @ref DDL_DAC_TRIANGLE_AMPLITUDE_1 + * @arg @ref DDL_DAC_TRIANGLE_AMPLITUDE_3 + * @arg @ref DDL_DAC_TRIANGLE_AMPLITUDE_7 + * @arg @ref DDL_DAC_TRIANGLE_AMPLITUDE_15 + * @arg @ref DDL_DAC_TRIANGLE_AMPLITUDE_31 + * @arg @ref DDL_DAC_TRIANGLE_AMPLITUDE_63 + * @arg @ref DDL_DAC_TRIANGLE_AMPLITUDE_127 + * @arg @ref DDL_DAC_TRIANGLE_AMPLITUDE_255 + * @arg @ref DDL_DAC_TRIANGLE_AMPLITUDE_511 + * @arg @ref DDL_DAC_TRIANGLE_AMPLITUDE_1023 + * @arg @ref DDL_DAC_TRIANGLE_AMPLITUDE_2047 + * @arg @ref DDL_DAC_TRIANGLE_AMPLITUDE_4095 + */ +__STATIC_INLINE uint32_t DDL_DAC_GetWaveTriangleAmplitude(DAC_TypeDef *DACx, uint32_t DAC_Channel) +{ + return (uint32_t)(READ_BIT(DACx->CTRL, DAC_CTRL_MAMPSELCH1 << (DAC_Channel & DAC_CTRL_CHX_BITOFFSET_MASK)) + >> (DAC_Channel & DAC_CTRL_CHX_BITOFFSET_MASK) + ); +} + +/** + * @brief Set the output buffer for the selected DAC channel. + * @param DACx DAC instance + * @param DAC_Channel This parameter can be one of the following values: + * @arg @ref DDL_DAC_CHANNEL_1 + * @arg @ref DDL_DAC_CHANNEL_2 (1) + * + * (1) On this APM32 serie, parameter not available on all devices. + * Refer to device datasheet for channels availability. + * @param OutputBuffer This parameter can be one of the following values: + * @arg @ref DDL_DAC_OUTPUT_BUFFER_ENABLE + * @arg @ref DDL_DAC_OUTPUT_BUFFER_DISABLE + * @retval None + */ +__STATIC_INLINE void DDL_DAC_SetOutputBuffer(DAC_TypeDef *DACx, uint32_t DAC_Channel, uint32_t OutputBuffer) +{ + MODIFY_REG(DACx->CTRL, + DAC_CTRL_BUFFDCH1 << (DAC_Channel & DAC_CTRL_CHX_BITOFFSET_MASK), + OutputBuffer << (DAC_Channel & DAC_CTRL_CHX_BITOFFSET_MASK)); +} + +/** + * @brief Get the output buffer state for the selected DAC channel. + * @param DACx DAC instance + * @param DAC_Channel This parameter can be one of the following values: + * @arg @ref DDL_DAC_CHANNEL_1 + * @arg @ref DDL_DAC_CHANNEL_2 (1) + * + * (1) On this APM32 serie, parameter not available on all devices. + * Refer to device datasheet for channels availability. + * @retval Returned value can be one of the following values: + * @arg @ref DDL_DAC_OUTPUT_BUFFER_ENABLE + * @arg @ref DDL_DAC_OUTPUT_BUFFER_DISABLE + */ +__STATIC_INLINE uint32_t DDL_DAC_GetOutputBuffer(DAC_TypeDef *DACx, uint32_t DAC_Channel) +{ + return (uint32_t)(READ_BIT(DACx->CTRL, DAC_CTRL_BUFFDCH1 << (DAC_Channel & DAC_CTRL_CHX_BITOFFSET_MASK)) + >> (DAC_Channel & DAC_CTRL_CHX_BITOFFSET_MASK) + ); +} + +/** + * @} + */ + +/** @defgroup DAC_DDL_EF_DMA_Management DMA Management + * @{ + */ + +/** + * @brief Enable DAC DMA transfer request of the selected channel. + * @note To configure DMA source address (peripheral address), + * use function @ref DDL_DAC_DMA_GetRegAddr(). + * @param DACx DAC instance + * @param DAC_Channel This parameter can be one of the following values: + * @arg @ref DDL_DAC_CHANNEL_1 + * @arg @ref DDL_DAC_CHANNEL_2 (1) + * + * (1) On this APM32 serie, parameter not available on all devices. + * Refer to device datasheet for channels availability. + * @retval None + */ +__STATIC_INLINE void DDL_DAC_EnableDMAReq(DAC_TypeDef *DACx, uint32_t DAC_Channel) +{ + SET_BIT(DACx->CTRL, + DAC_CTRL_DMAENCH1 << (DAC_Channel & DAC_CTRL_CHX_BITOFFSET_MASK)); +} + +/** + * @brief Disable DAC DMA transfer request of the selected channel. + * @note To configure DMA source address (peripheral address), + * use function @ref DDL_DAC_DMA_GetRegAddr(). + * @param DACx DAC instance + * @param DAC_Channel This parameter can be one of the following values: + * @arg @ref DDL_DAC_CHANNEL_1 + * @arg @ref DDL_DAC_CHANNEL_2 (1) + * + * (1) On this APM32 serie, parameter not available on all devices. + * Refer to device datasheet for channels availability. + * @retval None + */ +__STATIC_INLINE void DDL_DAC_DisableDMAReq(DAC_TypeDef *DACx, uint32_t DAC_Channel) +{ + CLEAR_BIT(DACx->CTRL, + DAC_CTRL_DMAENCH1 << (DAC_Channel & DAC_CTRL_CHX_BITOFFSET_MASK)); +} + +/** + * @brief Get DAC DMA transfer request state of the selected channel. + * (0: DAC DMA transfer request is disabled, 1: DAC DMA transfer request is enabled) + * @param DACx DAC instance + * @param DAC_Channel This parameter can be one of the following values: + * @arg @ref DDL_DAC_CHANNEL_1 + * @arg @ref DDL_DAC_CHANNEL_2 (1) + * + * (1) On this APM32 serie, parameter not available on all devices. + * Refer to device datasheet for channels availability. + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_DAC_IsDMAReqEnabled(DAC_TypeDef *DACx, uint32_t DAC_Channel) +{ + return ((READ_BIT(DACx->CTRL, + DAC_CTRL_DMAENCH1 << (DAC_Channel & DAC_CTRL_CHX_BITOFFSET_MASK)) + == (DAC_CTRL_DMAENCH1 << (DAC_Channel & DAC_CTRL_CHX_BITOFFSET_MASK))) ? 1UL : 0UL); +} + +/** + * @brief Function to help to configure DMA transfer to DAC: retrieve the + * DAC register address from DAC instance and a list of DAC registers + * intended to be used (most commonly) with DMA transfer. + * @note These DAC registers are data holding registers: + * when DAC conversion is requested, DAC generates a DMA transfer + * request to have data available in DAC data holding registers. + * @note This macro is intended to be used with LL DMA driver, refer to + * function "DDL_DMA_ConfigAddresses()". + * Example: + * DDL_DMA_ConfigAddresses(DMA1, + * DDL_DMA_CHANNEL_1, + * (uint32_t)&< array or variable >, + * DDL_DAC_DMA_GetRegAddr(DAC1, DDL_DAC_CHANNEL_1, + * DDL_DAC_DMA_REG_DATA_12BITS_RIGHT_ALIGNED), + * DDL_DMA_DIRECTION_MEMORY_TO_PERIPH); + * @param DACx DAC instance + * @param DAC_Channel This parameter can be one of the following values: + * @arg @ref DDL_DAC_CHANNEL_1 + * @arg @ref DDL_DAC_CHANNEL_2 (1) + * + * (1) On this APM32 serie, parameter not available on all devices. + * Refer to device datasheet for channels availability. + * @param Register This parameter can be one of the following values: + * @arg @ref DDL_DAC_DMA_REG_DATA_12BITS_RIGHT_ALIGNED + * @arg @ref DDL_DAC_DMA_REG_DATA_12BITS_LEFT_ALIGNED + * @arg @ref DDL_DAC_DMA_REG_DATA_8BITS_RIGHT_ALIGNED + * @retval DAC register address + */ +__STATIC_INLINE uint32_t DDL_DAC_DMA_GetRegAddr(DAC_TypeDef *DACx, uint32_t DAC_Channel, uint32_t Register) +{ + /* Retrieve address of register DHR12Rx, DHR12Lx or DHR8Rx depending on */ + /* DAC channel selected. */ + return ((uint32_t)(__DAC_PTR_REG_OFFSET((DACx)->DH12R1, ((DAC_Channel >> (Register & 0x1FUL)) + & DAC_REG_DHR_REGOFFSET_MASK_POSBIT0)))); +} +/** + * @} + */ + +/** @defgroup DAC_DDL_EF_Operation Operation on DAC channels + * @{ + */ + +/** + * @brief Enable DAC selected channel. + * @note After enable from off state, DAC channel requires a delay + * for output voltage to reach accuracy +/- 1 LSB. + * Refer to device datasheet, parameter "tWAKEUP". + * @param DACx DAC instance + * @param DAC_Channel This parameter can be one of the following values: + * @arg @ref DDL_DAC_CHANNEL_1 + * @arg @ref DDL_DAC_CHANNEL_2 (1) + * + * (1) On this APM32 serie, parameter not available on all devices. + * Refer to device datasheet for channels availability. + * @retval None + */ +__STATIC_INLINE void DDL_DAC_Enable(DAC_TypeDef *DACx, uint32_t DAC_Channel) +{ + SET_BIT(DACx->CTRL, + DAC_CTRL_ENCH1 << (DAC_Channel & DAC_CTRL_CHX_BITOFFSET_MASK)); +} + +/** + * @brief Disable DAC selected channel. + * @param DACx DAC instance + * @param DAC_Channel This parameter can be one of the following values: + * @arg @ref DDL_DAC_CHANNEL_1 + * @arg @ref DDL_DAC_CHANNEL_2 (1) + * + * (1) On this APM32 serie, parameter not available on all devices. + * Refer to device datasheet for channels availability. + * @retval None + */ +__STATIC_INLINE void DDL_DAC_Disable(DAC_TypeDef *DACx, uint32_t DAC_Channel) +{ + CLEAR_BIT(DACx->CTRL, + DAC_CTRL_ENCH1 << (DAC_Channel & DAC_CTRL_CHX_BITOFFSET_MASK)); +} + +/** + * @brief Get DAC enable state of the selected channel. + * (0: DAC channel is disabled, 1: DAC channel is enabled) + * @param DACx DAC instance + * @param DAC_Channel This parameter can be one of the following values: + * @arg @ref DDL_DAC_CHANNEL_1 + * @arg @ref DDL_DAC_CHANNEL_2 (1) + * + * (1) On this APM32 serie, parameter not available on all devices. + * Refer to device datasheet for channels availability. + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_DAC_IsEnabled(DAC_TypeDef *DACx, uint32_t DAC_Channel) +{ + return ((READ_BIT(DACx->CTRL, + DAC_CTRL_ENCH1 << (DAC_Channel & DAC_CTRL_CHX_BITOFFSET_MASK)) + == (DAC_CTRL_ENCH1 << (DAC_Channel & DAC_CTRL_CHX_BITOFFSET_MASK))) ? 1UL : 0UL); +} + +/** + * @brief Enable DAC trigger of the selected channel. + * @note - If DAC trigger is disabled, DAC conversion is performed + * automatically once the data holding register is updated, + * using functions "DDL_DAC_ConvertData{8; 12}{Right; Left} Aligned()": + * @ref DDL_DAC_ConvertData12RightAligned(), ... + * - If DAC trigger is enabled, DAC conversion is performed + * only when a hardware of software trigger event is occurring. + * Select trigger source using + * function @ref DDL_DAC_SetTriggerSource(). + * @param DACx DAC instance + * @param DAC_Channel This parameter can be one of the following values: + * @arg @ref DDL_DAC_CHANNEL_1 + * @arg @ref DDL_DAC_CHANNEL_2 (1) + * + * (1) On this APM32 serie, parameter not available on all devices. + * Refer to device datasheet for channels availability. + * @retval None + */ +__STATIC_INLINE void DDL_DAC_EnableTrigger(DAC_TypeDef *DACx, uint32_t DAC_Channel) +{ + SET_BIT(DACx->CTRL, + DAC_CTRL_TRGENCH1 << (DAC_Channel & DAC_CTRL_CHX_BITOFFSET_MASK)); +} + +/** + * @brief Disable DAC trigger of the selected channel. + * @param DACx DAC instance + * @param DAC_Channel This parameter can be one of the following values: + * @arg @ref DDL_DAC_CHANNEL_1 + * @arg @ref DDL_DAC_CHANNEL_2 (1) + * + * (1) On this APM32 serie, parameter not available on all devices. + * Refer to device datasheet for channels availability. + * @retval None + */ +__STATIC_INLINE void DDL_DAC_DisableTrigger(DAC_TypeDef *DACx, uint32_t DAC_Channel) +{ + CLEAR_BIT(DACx->CTRL, + DAC_CTRL_TRGENCH1 << (DAC_Channel & DAC_CTRL_CHX_BITOFFSET_MASK)); +} + +/** + * @brief Get DAC trigger state of the selected channel. + * (0: DAC trigger is disabled, 1: DAC trigger is enabled) + * @param DACx DAC instance + * @param DAC_Channel This parameter can be one of the following values: + * @arg @ref DDL_DAC_CHANNEL_1 + * @arg @ref DDL_DAC_CHANNEL_2 (1) + * + * (1) On this APM32 serie, parameter not available on all devices. + * Refer to device datasheet for channels availability. + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_DAC_IsTriggerEnabled(DAC_TypeDef *DACx, uint32_t DAC_Channel) +{ + return ((READ_BIT(DACx->CTRL, + DAC_CTRL_TRGENCH1 << (DAC_Channel & DAC_CTRL_CHX_BITOFFSET_MASK)) + == (DAC_CTRL_TRGENCH1 << (DAC_Channel & DAC_CTRL_CHX_BITOFFSET_MASK))) ? 1UL : 0UL); +} + +/** + * @brief Trig DAC conversion by software for the selected DAC channel. + * @note Preliminarily, DAC trigger must be set to software trigger + * using function + * @ref DDL_DAC_Init() + * @ref DDL_DAC_SetTriggerSource() + * with parameter "DDL_DAC_TRIGGER_SOFTWARE". + * and DAC trigger must be enabled using + * function @ref DDL_DAC_EnableTrigger(). + * @note For devices featuring DAC with 2 channels: this function + * can perform a SW start of both DAC channels simultaneously. + * Two channels can be selected as parameter. + * Example: (DDL_DAC_CHANNEL_1 | DDL_DAC_CHANNEL_2) + * @param DACx DAC instance + * @param DAC_Channel This parameter can a combination of the following values: + * @arg @ref DDL_DAC_CHANNEL_1 + * @arg @ref DDL_DAC_CHANNEL_2 (1) + * + * (1) On this APM32 serie, parameter not available on all devices. + * Refer to device datasheet for channels availability. + * @retval None + */ +__STATIC_INLINE void DDL_DAC_TrigSWConversion(DAC_TypeDef *DACx, uint32_t DAC_Channel) +{ + SET_BIT(DACx->SWTRG, + (DAC_Channel & DAC_SWTR_CHX_MASK)); +} + +/** + * @brief Set the data to be loaded in the data holding register + * in format 12 bits left alignment (LSB aligned on bit 0), + * for the selected DAC channel. + * @param DACx DAC instance + * @param DAC_Channel This parameter can be one of the following values: + * @arg @ref DDL_DAC_CHANNEL_1 + * @arg @ref DDL_DAC_CHANNEL_2 (1) + * + * (1) On this APM32 serie, parameter not available on all devices. + * Refer to device datasheet for channels availability. + * @param Data Value between Min_Data=0x000 and Max_Data=0xFFF + * @retval None + */ +__STATIC_INLINE void DDL_DAC_ConvertData12RightAligned(DAC_TypeDef *DACx, uint32_t DAC_Channel, uint32_t Data) +{ + __IO uint32_t *preg = __DAC_PTR_REG_OFFSET(DACx->DH12R1, (DAC_Channel >> DAC_REG_DHR12RX_REGOFFSET_BITOFFSET_POS) + & DAC_REG_DHR_REGOFFSET_MASK_POSBIT0); + + MODIFY_REG(*preg, DAC_DH12R1_DATA, Data); +} + +/** + * @brief Set the data to be loaded in the data holding register + * in format 12 bits left alignment (MSB aligned on bit 15), + * for the selected DAC channel. + * @param DACx DAC instance + * @param DAC_Channel This parameter can be one of the following values: + * @arg @ref DDL_DAC_CHANNEL_1 + * @arg @ref DDL_DAC_CHANNEL_2 (1) + * + * (1) On this APM32 serie, parameter not available on all devices. + * Refer to device datasheet for channels availability. + * @param Data Value between Min_Data=0x000 and Max_Data=0xFFF + * @retval None + */ +__STATIC_INLINE void DDL_DAC_ConvertData12LeftAligned(DAC_TypeDef *DACx, uint32_t DAC_Channel, uint32_t Data) +{ + __IO uint32_t *preg = __DAC_PTR_REG_OFFSET(DACx->DH12R1, (DAC_Channel >> DAC_REG_DHR12LX_REGOFFSET_BITOFFSET_POS) + & DAC_REG_DHR_REGOFFSET_MASK_POSBIT0); + + MODIFY_REG(*preg, DAC_DH12L1_DATA, Data); +} + +/** + * @brief Set the data to be loaded in the data holding register + * in format 8 bits left alignment (LSB aligned on bit 0), + * for the selected DAC channel. + * @param DACx DAC instance + * @param DAC_Channel This parameter can be one of the following values: + * @arg @ref DDL_DAC_CHANNEL_1 + * @arg @ref DDL_DAC_CHANNEL_2 (1) + * + * (1) On this APM32 serie, parameter not available on all devices. + * Refer to device datasheet for channels availability. + * @param Data Value between Min_Data=0x00 and Max_Data=0xFF + * @retval None + */ +__STATIC_INLINE void DDL_DAC_ConvertData8RightAligned(DAC_TypeDef *DACx, uint32_t DAC_Channel, uint32_t Data) +{ + __IO uint32_t *preg = __DAC_PTR_REG_OFFSET(DACx->DH12R1, (DAC_Channel >> DAC_REG_DHR8RX_REGOFFSET_BITOFFSET_POS) + & DAC_REG_DHR_REGOFFSET_MASK_POSBIT0); + + MODIFY_REG(*preg, DAC_DH8R1_DATA, Data); +} + +#if defined(DAC_CHANNEL2_SUPPORT) +/** + * @brief Set the data to be loaded in the data holding register + * in format 12 bits left alignment (LSB aligned on bit 0), + * for both DAC channels. + * @param DACx DAC instance + * @param DataChannel1 Value between Min_Data=0x000 and Max_Data=0xFFF + * @param DataChannel2 Value between Min_Data=0x000 and Max_Data=0xFFF + * @retval None + */ +__STATIC_INLINE void DDL_DAC_ConvertDualData12RightAligned(DAC_TypeDef *DACx, uint32_t DataChannel1, + uint32_t DataChannel2) +{ + MODIFY_REG(DACx->DH12RDUAL, + (DAC_DH12RDUAL_DATACH2 | DAC_DH12RDUAL_DATACH1), + ((DataChannel2 << DAC_DH12RDUAL_DATACH2_BITOFFSET_POS) | DataChannel1)); +} + +/** + * @brief Set the data to be loaded in the data holding register + * in format 12 bits left alignment (MSB aligned on bit 15), + * for both DAC channels. + * @param DACx DAC instance + * @param DataChannel1 Value between Min_Data=0x000 and Max_Data=0xFFF + * @param DataChannel2 Value between Min_Data=0x000 and Max_Data=0xFFF + * @retval None + */ +__STATIC_INLINE void DDL_DAC_ConvertDualData12LeftAligned(DAC_TypeDef *DACx, uint32_t DataChannel1, + uint32_t DataChannel2) +{ + /* Note: Data of DAC channel 2 shift value subtracted of 4 because */ + /* data on 16 bits and DAC channel 2 bits field is on the 12 MSB, */ + /* the 4 LSB must be taken into account for the shift value. */ + MODIFY_REG(DACx->DH12LDUAL, + (DAC_DH12LDUAL_DATACH2 | DAC_DH12LDUAL_DATACH1), + ((DataChannel2 << (DAC_DH12LDUAL_DATACH2_BITOFFSET_POS - 4U)) | DataChannel1)); +} + +/** + * @brief Set the data to be loaded in the data holding register + * in format 8 bits left alignment (LSB aligned on bit 0), + * for both DAC channels. + * @param DACx DAC instance + * @param DataChannel1 Value between Min_Data=0x00 and Max_Data=0xFF + * @param DataChannel2 Value between Min_Data=0x00 and Max_Data=0xFF + * @retval None + */ +__STATIC_INLINE void DDL_DAC_ConvertDualData8RightAligned(DAC_TypeDef *DACx, uint32_t DataChannel1, + uint32_t DataChannel2) +{ + MODIFY_REG(DACx->DH8RDUAL, + (DAC_DH8RDUAL_DATACH2 | DAC_DH8RDUAL_DATACH1), + ((DataChannel2 << DAC_DH8RDUAL_DATACH2_BITOFFSET_POS) | DataChannel1)); +} +#endif /* DAC_CHANNEL2_SUPPORT */ + +/** + * @brief Retrieve output data currently generated for the selected DAC channel. + * @note Whatever alignment and resolution settings + * (using functions "DDL_DAC_ConvertData{8; 12}{Right; Left} Aligned()": + * @ref DDL_DAC_ConvertData12RightAligned(), ...), + * output data format is 12 bits right aligned (LSB aligned on bit 0). + * @param DACx DAC instance + * @param DAC_Channel This parameter can be one of the following values: + * @arg @ref DDL_DAC_CHANNEL_1 + * @arg @ref DDL_DAC_CHANNEL_2 (1) + * + * (1) On this APM32 serie, parameter not available on all devices. + * Refer to device datasheet for channels availability. + * @retval Value between Min_Data=0x000 and Max_Data=0xFFF + */ +__STATIC_INLINE uint32_t DDL_DAC_RetrieveOutputData(DAC_TypeDef *DACx, uint32_t DAC_Channel) +{ + __IO uint32_t const *preg = __DAC_PTR_REG_OFFSET(DACx->DATAOCH1, (DAC_Channel >> DAC_REG_DORX_REGOFFSET_BITOFFSET_POS) + & DAC_REG_DORX_REGOFFSET_MASK_POSBIT0); + + return (uint16_t) READ_BIT(*preg, DAC_DATAOCH1_DATA); +} + +/** + * @} + */ + +/** @defgroup DAC_DDL_EF_FLAG_Management FLAG Management + * @{ + */ + +/** + * @brief Get DAC underrun flag for DAC channel 1 + * @param DACx DAC instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_DAC_IsActiveFlag_DMAUDR1(DAC_TypeDef *DACx) +{ + return ((READ_BIT(DACx->STS, DDL_DAC_FLAG_DMAUDR1) == (DDL_DAC_FLAG_DMAUDR1)) ? 1UL : 0UL); +} + +#if defined(DAC_CHANNEL2_SUPPORT) +/** + * @brief Get DAC underrun flag for DAC channel 2 + * @param DACx DAC instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_DAC_IsActiveFlag_DMAUDR2(DAC_TypeDef *DACx) +{ + return ((READ_BIT(DACx->STS, DDL_DAC_FLAG_DMAUDR2) == (DDL_DAC_FLAG_DMAUDR2)) ? 1UL : 0UL); +} +#endif /* DAC_CHANNEL2_SUPPORT */ + +/** + * @brief Clear DAC underrun flag for DAC channel 1 + * @param DACx DAC instance + * @retval None + */ +__STATIC_INLINE void DDL_DAC_ClearFlag_DMAUDR1(DAC_TypeDef *DACx) +{ + WRITE_REG(DACx->STS, DDL_DAC_FLAG_DMAUDR1); +} + +#if defined(DAC_CHANNEL2_SUPPORT) +/** + * @brief Clear DAC underrun flag for DAC channel 2 + * @param DACx DAC instance + * @retval None + */ +__STATIC_INLINE void DDL_DAC_ClearFlag_DMAUDR2(DAC_TypeDef *DACx) +{ + WRITE_REG(DACx->STS, DDL_DAC_FLAG_DMAUDR2); +} +#endif /* DAC_CHANNEL2_SUPPORT */ + +/** + * @} + */ + +/** @defgroup DAC_DDL_EF_IT_Management IT management + * @{ + */ + +/** + * @brief Enable DMA underrun interrupt for DAC channel 1 + * @param DACx DAC instance + * @retval None + */ +__STATIC_INLINE void DDL_DAC_EnableIT_DMAUDR1(DAC_TypeDef *DACx) +{ + SET_BIT(DACx->CTRL, DDL_DAC_IT_DMAUDRIE1); +} + +#if defined(DAC_CHANNEL2_SUPPORT) +/** + * @brief Enable DMA underrun interrupt for DAC channel 2 + * @param DACx DAC instance + * @retval None + */ +__STATIC_INLINE void DDL_DAC_EnableIT_DMAUDR2(DAC_TypeDef *DACx) +{ + SET_BIT(DACx->CTRL, DDL_DAC_IT_DMAUDRIE2); +} +#endif /* DAC_CHANNEL2_SUPPORT */ + +/** + * @brief Disable DMA underrun interrupt for DAC channel 1 + * @param DACx DAC instance + * @retval None + */ +__STATIC_INLINE void DDL_DAC_DisableIT_DMAUDR1(DAC_TypeDef *DACx) +{ + CLEAR_BIT(DACx->CTRL, DDL_DAC_IT_DMAUDRIE1); +} + +#if defined(DAC_CHANNEL2_SUPPORT) +/** + * @brief Disable DMA underrun interrupt for DAC channel 2 + * @param DACx DAC instance + * @retval None + */ +__STATIC_INLINE void DDL_DAC_DisableIT_DMAUDR2(DAC_TypeDef *DACx) +{ + CLEAR_BIT(DACx->CTRL, DDL_DAC_IT_DMAUDRIE2); +} +#endif /* DAC_CHANNEL2_SUPPORT */ + +/** + * @brief Get DMA underrun interrupt for DAC channel 1 + * @param DACx DAC instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_DAC_IsEnabledIT_DMAUDR1(DAC_TypeDef *DACx) +{ + return ((READ_BIT(DACx->CTRL, DDL_DAC_IT_DMAUDRIE1) == (DDL_DAC_IT_DMAUDRIE1)) ? 1UL : 0UL); +} + +#if defined(DAC_CHANNEL2_SUPPORT) +/** + * @brief Get DMA underrun interrupt for DAC channel 2 + * @param DACx DAC instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_DAC_IsEnabledIT_DMAUDR2(DAC_TypeDef *DACx) +{ + return ((READ_BIT(DACx->CTRL, DDL_DAC_IT_DMAUDRIE2) == (DDL_DAC_IT_DMAUDRIE2)) ? 1UL : 0UL); +} +#endif /* DAC_CHANNEL2_SUPPORT */ + +/** + * @} + */ + +#if defined(USE_FULL_DDL_DRIVER) +/** @defgroup DAC_DDL_EF_Init Initialization and de-initialization functions + * @{ + */ + +ErrorStatus DDL_DAC_DeInit(DAC_TypeDef *DACx); +ErrorStatus DDL_DAC_Init(DAC_TypeDef *DACx, uint32_t DAC_Channel, DDL_DAC_InitTypeDef *DAC_InitStruct); +void DDL_DAC_StructInit(DDL_DAC_InitTypeDef *DAC_InitStruct); + +/** + * @} + */ +#endif /* USE_FULL_DDL_DRIVER */ + +/** + * @} + */ + +/** + * @} + */ + +#endif /* DAC */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* APM32F4xx_DDL_DAC_H */ + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_dma.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_dma.h new file mode 100644 index 0000000000..6fcb0967a8 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_dma.h @@ -0,0 +1,2738 @@ +/** + * + * @file apm32f4xx_ddl_dma.h + * @brief Header file of DMA DDL module. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2017 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file in + * the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + * + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef APM32F4xx_DDL_DMA_H +#define APM32F4xx_DDL_DMA_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx.h" + +/** @addtogroup APM32F4xx_DDL_Driver + * @{ + */ + +#if defined (DMA1) || defined (DMA2) + +/** @defgroup DMA_DDL DMA + * @{ + */ + +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/** @defgroup DMA_DDL_Private_Variables DMA Private Variables + * @{ + */ +/* Array used to get the DMA stream register offset versus stream index DDL_DMA_STREAM_x */ +static const uint8_t STREAM_OFFSET_TAB[] = +{ + (uint8_t)(DMA1_Stream0_BASE - DMA1_BASE), + (uint8_t)(DMA1_Stream1_BASE - DMA1_BASE), + (uint8_t)(DMA1_Stream2_BASE - DMA1_BASE), + (uint8_t)(DMA1_Stream3_BASE - DMA1_BASE), + (uint8_t)(DMA1_Stream4_BASE - DMA1_BASE), + (uint8_t)(DMA1_Stream5_BASE - DMA1_BASE), + (uint8_t)(DMA1_Stream6_BASE - DMA1_BASE), + (uint8_t)(DMA1_Stream7_BASE - DMA1_BASE) +}; + +/** + * @} + */ + +/* Private constants ---------------------------------------------------------*/ +/** @defgroup DMA_DDL_Private_Constants DMA Private Constants + * @{ + */ +/** + * @} + */ + + +/* Private macros ------------------------------------------------------------*/ +/* Exported types ------------------------------------------------------------*/ +#if defined(USE_FULL_DDL_DRIVER) +/** @defgroup DMA_DDL_ES_INIT DMA Exported Init structure + * @{ + */ +typedef struct +{ + uint32_t PeriphOrM2MSrcAddress; /*!< Specifies the peripheral base address for DMA transfer + or as Source base address in case of memory to memory transfer direction. + + This parameter must be a value between Min_Data = 0 and Max_Data = 0xFFFFFFFF. */ + + uint32_t MemoryOrM2MDstAddress; /*!< Specifies the memory base address for DMA transfer + or as Destination base address in case of memory to memory transfer direction. + + This parameter must be a value between Min_Data = 0 and Max_Data = 0xFFFFFFFF. */ + + uint32_t Direction; /*!< Specifies if the data will be transferred from memory to peripheral, + from memory to memory or from peripheral to memory. + This parameter can be a value of @ref DMA_DDL_EC_DIRECTION + + This feature can be modified afterwards using unitary function @ref DDL_DMA_SetDataTransferDirection(). */ + + uint32_t Mode; /*!< Specifies the normal or circular operation mode. + This parameter can be a value of @ref DMA_DDL_EC_MODE + @note The circular buffer mode cannot be used if the memory to memory + data transfer direction is configured on the selected Stream + + This feature can be modified afterwards using unitary function @ref DDL_DMA_SetMode(). */ + + uint32_t PeriphOrM2MSrcIncMode; /*!< Specifies whether the Peripheral address or Source address in case of memory to memory transfer direction + is incremented or not. + This parameter can be a value of @ref DMA_DDL_EC_PERIPH + + This feature can be modified afterwards using unitary function @ref DDL_DMA_SetPeriphIncMode(). */ + + uint32_t MemoryOrM2MDstIncMode; /*!< Specifies whether the Memory address or Destination address in case of memory to memory transfer direction + is incremented or not. + This parameter can be a value of @ref DMA_DDL_EC_MEMORY + + This feature can be modified afterwards using unitary function @ref DDL_DMA_SetMemoryIncMode(). */ + + uint32_t PeriphOrM2MSrcDataSize; /*!< Specifies the Peripheral data size alignment or Source data size alignment (byte, half word, word) + in case of memory to memory transfer direction. + This parameter can be a value of @ref DMA_DDL_EC_PDATAALIGN + + This feature can be modified afterwards using unitary function @ref DDL_DMA_SetPeriphSize(). */ + + uint32_t MemoryOrM2MDstDataSize; /*!< Specifies the Memory data size alignment or Destination data size alignment (byte, half word, word) + in case of memory to memory transfer direction. + This parameter can be a value of @ref DMA_DDL_EC_MDATAALIGN + + This feature can be modified afterwards using unitary function @ref DDL_DMA_SetMemorySize(). */ + + uint32_t NbData; /*!< Specifies the number of data to transfer, in data unit. + The data unit is equal to the source buffer configuration set in PeripheralSize + or MemorySize parameters depending in the transfer direction. + This parameter must be a value between Min_Data = 0 and Max_Data = 0x0000FFFF + + This feature can be modified afterwards using unitary function @ref DDL_DMA_SetDataLength(). */ + + uint32_t Channel; /*!< Specifies the peripheral channel. + This parameter can be a value of @ref DMA_DDL_EC_CHANNEL + + This feature can be modified afterwards using unitary function @ref DDL_DMA_SetChannelSelection(). */ + + uint32_t Priority; /*!< Specifies the channel priority level. + This parameter can be a value of @ref DMA_DDL_EC_PRIORITY + + This feature can be modified afterwards using unitary function @ref DDL_DMA_SetStreamPriorityLevel(). */ + + uint32_t FIFOMode; /*!< Specifies if the FIFO mode or Direct mode will be used for the specified stream. + This parameter can be a value of @ref DMA_DDL_FIFOMODE + @note The Direct mode (FIFO mode disabled) cannot be used if the + memory-to-memory data transfer is configured on the selected stream + + This feature can be modified afterwards using unitary functions @ref DDL_DMA_EnableFifoMode() or @ref DDL_DMA_EnableFifoMode() . */ + + uint32_t FIFOThreshold; /*!< Specifies the FIFO threshold level. + This parameter can be a value of @ref DMA_DDL_EC_FIFOTHRESHOLD + + This feature can be modified afterwards using unitary function @ref DDL_DMA_SetFIFOThreshold(). */ + + uint32_t MemBurst; /*!< Specifies the Burst transfer configuration for the memory transfers. + It specifies the amount of data to be transferred in a single non interruptible + transaction. + This parameter can be a value of @ref DMA_DDL_EC_MBURST + @note The burst mode is possible only if the address Increment mode is enabled. + + This feature can be modified afterwards using unitary function @ref DDL_DMA_SetMemoryBurstxfer(). */ + + uint32_t PeriphBurst; /*!< Specifies the Burst transfer configuration for the peripheral transfers. + It specifies the amount of data to be transferred in a single non interruptible + transaction. + This parameter can be a value of @ref DMA_DDL_EC_PBURST + @note The burst mode is possible only if the address Increment mode is enabled. + + This feature can be modified afterwards using unitary function @ref DDL_DMA_SetPeriphBurstxfer(). */ + +} DDL_DMA_InitTypeDef; +/** + * @} + */ +#endif /*USE_FULL_DDL_DRIVER*/ +/* Exported constants --------------------------------------------------------*/ +/** @defgroup DMA_DDL_Exported_Constants DMA Exported Constants + * @{ + */ + +/** @defgroup DMA_DDL_EC_STREAM STREAM + * @{ + */ +#define DDL_DMA_STREAM_0 0x00000000U +#define DDL_DMA_STREAM_1 0x00000001U +#define DDL_DMA_STREAM_2 0x00000002U +#define DDL_DMA_STREAM_3 0x00000003U +#define DDL_DMA_STREAM_4 0x00000004U +#define DDL_DMA_STREAM_5 0x00000005U +#define DDL_DMA_STREAM_6 0x00000006U +#define DDL_DMA_STREAM_7 0x00000007U +#define DDL_DMA_STREAM_ALL 0xFFFF0000U +/** + * @} + */ + +/** @defgroup DMA_DDL_EC_DIRECTION DIRECTION + * @{ + */ +#define DDL_DMA_DIRECTION_PERIPH_TO_MEMORY 0x00000000U /*!< Peripheral to memory direction */ +#define DDL_DMA_DIRECTION_MEMORY_TO_PERIPH DMA_SCFGx_DIRCFG_0 /*!< Memory to peripheral direction */ +#define DDL_DMA_DIRECTION_MEMORY_TO_MEMORY DMA_SCFGx_DIRCFG_1 /*!< Memory to memory direction */ +/** + * @} + */ + +/** @defgroup DMA_DDL_EC_MODE MODE + * @{ + */ +#define DDL_DMA_MODE_NORMAL 0x00000000U /*!< Normal Mode */ +#define DDL_DMA_MODE_CIRCULAR DMA_SCFGx_CIRCMEN /*!< Circular Mode */ +#define DDL_DMA_MODE_PFCTRL DMA_SCFGx_PERFC /*!< Peripheral flow control mode */ +/** + * @} + */ + +/** @defgroup DMA_DDL_EC_DOUBLEBUFFER_MODE DOUBLEBUFFER MODE + * @{ + */ +#define DDL_DMA_DOUBLEBUFFER_MODE_DISABLE 0x00000000U /*!< Disable double buffering mode */ +#define DDL_DMA_DOUBLEBUFFER_MODE_ENABLE DMA_SCFGx_DBM /*!< Enable double buffering mode */ +/** + * @} + */ + +/** @defgroup DMA_DDL_EC_PERIPH PERIPH + * @{ + */ +#define DDL_DMA_PERIPH_NOINCREMENT 0x00000000U /*!< Peripheral increment mode Disable */ +#define DDL_DMA_PERIPH_INCREMENT DMA_SCFGx_PERIM /*!< Peripheral increment mode Enable */ +/** + * @} + */ + +/** @defgroup DMA_DDL_EC_MEMORY MEMORY + * @{ + */ +#define DDL_DMA_MEMORY_NOINCREMENT 0x00000000U /*!< Memory increment mode Disable */ +#define DDL_DMA_MEMORY_INCREMENT DMA_SCFGx_MEMIM /*!< Memory increment mode Enable */ +/** + * @} + */ + +/** @defgroup DMA_DDL_EC_PDATAALIGN PDATAALIGN + * @{ + */ +#define DDL_DMA_PDATAALIGN_BYTE 0x00000000U /*!< Peripheral data alignment : Byte */ +#define DDL_DMA_PDATAALIGN_HALFWORD DMA_SCFGx_PERSIZECFG_0 /*!< Peripheral data alignment : HalfWord */ +#define DDL_DMA_PDATAALIGN_WORD DMA_SCFGx_PERSIZECFG_1 /*!< Peripheral data alignment : Word */ +/** + * @} + */ + +/** @defgroup DMA_DDL_EC_MDATAALIGN MDATAALIGN + * @{ + */ +#define DDL_DMA_MDATAALIGN_BYTE 0x00000000U /*!< Memory data alignment : Byte */ +#define DDL_DMA_MDATAALIGN_HALFWORD DMA_SCFGx_MEMSIZECFG_0 /*!< Memory data alignment : HalfWord */ +#define DDL_DMA_MDATAALIGN_WORD DMA_SCFGx_MEMSIZECFG_1 /*!< Memory data alignment : Word */ +/** + * @} + */ + +/** @defgroup DMA_DDL_EC_OFFSETSIZE OFFSETSIZE + * @{ + */ +#define DDL_DMA_OFFSETSIZE_PSIZE 0x00000000U /*!< Peripheral increment offset size is linked to the PSIZE */ +#define DDL_DMA_OFFSETSIZE_FIXEDTO4 DMA_SCFGx_PERIOSIZE /*!< Peripheral increment offset size is fixed to 4 (32-bit alignment) */ +/** + * @} + */ + +/** @defgroup DMA_DDL_EC_PRIORITY PRIORITY + * @{ + */ +#define DDL_DMA_PRIORITY_LOW 0x00000000U /*!< Priority level : Low */ +#define DDL_DMA_PRIORITY_MEDIUM DMA_SCFGx_PRILCFG_0 /*!< Priority level : Medium */ +#define DDL_DMA_PRIORITY_HIGH DMA_SCFGx_PRILCFG_1 /*!< Priority level : High */ +#define DDL_DMA_PRIORITY_VERYHIGH DMA_SCFGx_PRILCFG /*!< Priority level : Very_High */ +/** + * @} + */ + +/** @defgroup DMA_DDL_EC_CHANNEL CHANNEL + * @{ + */ +#define DDL_DMA_CHANNEL_0 0x00000000U /* Select Channel0 of DMA Instance */ +#define DDL_DMA_CHANNEL_1 DMA_SCFGx_CHSEL_0 /* Select Channel1 of DMA Instance */ +#define DDL_DMA_CHANNEL_2 DMA_SCFGx_CHSEL_1 /* Select Channel2 of DMA Instance */ +#define DDL_DMA_CHANNEL_3 (DMA_SCFGx_CHSEL_0 | DMA_SCFGx_CHSEL_1) /* Select Channel3 of DMA Instance */ +#define DDL_DMA_CHANNEL_4 DMA_SCFGx_CHSEL_2 /* Select Channel4 of DMA Instance */ +#define DDL_DMA_CHANNEL_5 (DMA_SCFGx_CHSEL_2 | DMA_SCFGx_CHSEL_0) /* Select Channel5 of DMA Instance */ +#define DDL_DMA_CHANNEL_6 (DMA_SCFGx_CHSEL_2 | DMA_SCFGx_CHSEL_1) /* Select Channel6 of DMA Instance */ +#define DDL_DMA_CHANNEL_7 (DMA_SCFGx_CHSEL_2 | DMA_SCFGx_CHSEL_1 | DMA_SCFGx_CHSEL_0) /* Select Channel7 of DMA Instance */ +#if defined (DMA_SCFGx_CHSEL_3) +#define DDL_DMA_CHANNEL_8 DMA_SCFGx_CHSEL_3 /* Select Channel8 of DMA Instance */ +#define DDL_DMA_CHANNEL_9 (DMA_SCFGx_CHSEL_3 | DMA_SCFGx_CHSEL_0) /* Select Channel9 of DMA Instance */ +#define DDL_DMA_CHANNEL_10 (DMA_SCFGx_CHSEL_3 | DMA_SCFGx_CHSEL_1) /* Select Channel10 of DMA Instance */ +#define DDL_DMA_CHANNEL_11 (DMA_SCFGx_CHSEL_3 | DMA_SCFGx_CHSEL_1 | DMA_SCFGx_CHSEL_0) /* Select Channel11 of DMA Instance */ +#define DDL_DMA_CHANNEL_12 (DMA_SCFGx_CHSEL_3 | DMA_SCFGx_CHSEL_2) /* Select Channel12 of DMA Instance */ +#define DDL_DMA_CHANNEL_13 (DMA_SCFGx_CHSEL_3 | DMA_SCFGx_CHSEL_2 | DMA_SCFGx_CHSEL_0) /* Select Channel13 of DMA Instance */ +#define DDL_DMA_CHANNEL_14 (DMA_SCFGx_CHSEL_3 | DMA_SCFGx_CHSEL_2 | DMA_SCFGx_CHSEL_1) /* Select Channel14 of DMA Instance */ +#define DDL_DMA_CHANNEL_15 (DMA_SCFGx_CHSEL_3 | DMA_SCFGx_CHSEL_2 | DMA_SCFGx_CHSEL_1 | DMA_SCFGx_CHSEL_0) /* Select Channel15 of DMA Instance */ +#endif /* DMA_SCFGx_CHSEL_3 */ +/** + * @} + */ + +/** @defgroup DMA_DDL_EC_MBURST MBURST + * @{ + */ +#define DDL_DMA_MBURST_SINGLE 0x00000000U /*!< Memory burst single transfer configuration */ +#define DDL_DMA_MBURST_INC4 DMA_SCFGx_MBCFG_0 /*!< Memory burst of 4 beats transfer configuration */ +#define DDL_DMA_MBURST_INC8 DMA_SCFGx_MBCFG_1 /*!< Memory burst of 8 beats transfer configuration */ +#define DDL_DMA_MBURST_INC16 (DMA_SCFGx_MBCFG_0 | DMA_SCFGx_MBCFG_1) /*!< Memory burst of 16 beats transfer configuration */ +/** + * @} + */ + +/** @defgroup DMA_DDL_EC_PBURST PBURST + * @{ + */ +#define DDL_DMA_PBURST_SINGLE 0x00000000U /*!< Peripheral burst single transfer configuration */ +#define DDL_DMA_PBURST_INC4 DMA_SCFGx_PBCFG_0 /*!< Peripheral burst of 4 beats transfer configuration */ +#define DDL_DMA_PBURST_INC8 DMA_SCFGx_PBCFG_1 /*!< Peripheral burst of 8 beats transfer configuration */ +#define DDL_DMA_PBURST_INC16 (DMA_SCFGx_PBCFG_0 | DMA_SCFGx_PBCFG_1) /*!< Peripheral burst of 16 beats transfer configuration */ +/** + * @} + */ + +/** @defgroup DMA_DDL_FIFOMODE DMA_DDL_FIFOMODE + * @{ + */ +#define DDL_DMA_FIFOMODE_DISABLE 0x00000000U /*!< FIFO mode disable (direct mode is enabled) */ +#define DDL_DMA_FIFOMODE_ENABLE DMA_FCTRLx_DMDEN /*!< FIFO mode enable */ +/** + * @} + */ + +/** @defgroup DMA_DDL_EC_FIFOSTATUS_0 FIFOSTATUS 0 + * @{ + */ +#define DDL_DMA_FIFOSTATUS_0_25 0x00000000U /*!< 0 < fifo_level < 1/4 */ +#define DDL_DMA_FIFOSTATUS_25_50 DMA_FCTRLx_FSTS_0 /*!< 1/4 < fifo_level < 1/2 */ +#define DDL_DMA_FIFOSTATUS_50_75 DMA_FCTRLx_FSTS_1 /*!< 1/2 < fifo_level < 3/4 */ +#define DDL_DMA_FIFOSTATUS_75_100 (DMA_FCTRLx_FSTS_1 | DMA_FCTRLx_FSTS_0) /*!< 3/4 < fifo_level < full */ +#define DDL_DMA_FIFOSTATUS_EMPTY DMA_FCTRLx_FSTS_2 /*!< FIFO is empty */ +#define DDL_DMA_FIFOSTATUS_FULL (DMA_FCTRLx_FSTS_2 | DMA_FCTRLx_FSTS_0) /*!< FIFO is full */ +/** + * @} + */ + +/** @defgroup DMA_DDL_EC_FIFOTHRESHOLD FIFOTHRESHOLD + * @{ + */ +#define DDL_DMA_FIFOTHRESHOLD_1_4 0x00000000U /*!< FIFO threshold 1 quart full configuration */ +#define DDL_DMA_FIFOTHRESHOLD_1_2 DMA_FCTRLx_FTHSEL_0 /*!< FIFO threshold half full configuration */ +#define DDL_DMA_FIFOTHRESHOLD_3_4 DMA_FCTRLx_FTHSEL_1 /*!< FIFO threshold 3 quarts full configuration */ +#define DDL_DMA_FIFOTHRESHOLD_FULL DMA_FCTRLx_FTHSEL /*!< FIFO threshold full configuration */ +/** + * @} + */ + +/** @defgroup DMA_DDL_EC_CURRENTTARGETMEM CURRENTTARGETMEM + * @{ + */ +#define DDL_DMA_CURRENTTARGETMEM0 0x00000000U /*!< Set CurrentTarget Memory to Memory 0 */ +#define DDL_DMA_CURRENTTARGETMEM1 DMA_SCFGx_CTARG /*!< Set CurrentTarget Memory to Memory 1 */ +/** + * @} + */ + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ +/** @defgroup DMA_DDL_Exported_Macros DMA Exported Macros + * @{ + */ + +/** @defgroup DMA_DDL_EM_WRITE_READ Common Write and read registers macros + * @{ + */ +/** + * @brief Write a value in DMA register + * @param __INSTANCE__ DMA Instance + * @param __REG__ Register to be written + * @param __VALUE__ Value to be written in the register + * @retval None + */ +#define DDL_DMA_WriteReg(__INSTANCE__, __REG__, __VALUE__) WRITE_REG(__INSTANCE__->__REG__, (__VALUE__)) + +/** + * @brief Read a value in DMA register + * @param __INSTANCE__ DMA Instance + * @param __REG__ Register to be read + * @retval Register value + */ +#define DDL_DMA_ReadReg(__INSTANCE__, __REG__) READ_REG(__INSTANCE__->__REG__) +/** + * @} + */ + +/** @defgroup DMA_DDL_EM_CONVERT_DMAxCHANNELy Convert DMAxStreamy + * @{ + */ +/** + * @brief Convert DMAx_Streamy into DMAx + * @param __STREAM_INSTANCE__ DMAx_Streamy + * @retval DMAx + */ +#define __DDL_DMA_GET_INSTANCE(__STREAM_INSTANCE__) \ +(((uint32_t)(__STREAM_INSTANCE__) > ((uint32_t)DMA1_Stream7)) ? DMA2 : DMA1) + +/** + * @brief Convert DMAx_Streamy into DDL_DMA_STREAM_y + * @param __STREAM_INSTANCE__ DMAx_Streamy + * @retval DDL_DMA_CHANNEL_y + */ +#define __DDL_DMA_GET_STREAM(__STREAM_INSTANCE__) \ +(((uint32_t)(__STREAM_INSTANCE__) == ((uint32_t)DMA1_Stream0)) ? DDL_DMA_STREAM_0 : \ + ((uint32_t)(__STREAM_INSTANCE__) == ((uint32_t)DMA2_Stream0)) ? DDL_DMA_STREAM_0 : \ + ((uint32_t)(__STREAM_INSTANCE__) == ((uint32_t)DMA1_Stream1)) ? DDL_DMA_STREAM_1 : \ + ((uint32_t)(__STREAM_INSTANCE__) == ((uint32_t)DMA2_Stream1)) ? DDL_DMA_STREAM_1 : \ + ((uint32_t)(__STREAM_INSTANCE__) == ((uint32_t)DMA1_Stream2)) ? DDL_DMA_STREAM_2 : \ + ((uint32_t)(__STREAM_INSTANCE__) == ((uint32_t)DMA2_Stream2)) ? DDL_DMA_STREAM_2 : \ + ((uint32_t)(__STREAM_INSTANCE__) == ((uint32_t)DMA1_Stream3)) ? DDL_DMA_STREAM_3 : \ + ((uint32_t)(__STREAM_INSTANCE__) == ((uint32_t)DMA2_Stream3)) ? DDL_DMA_STREAM_3 : \ + ((uint32_t)(__STREAM_INSTANCE__) == ((uint32_t)DMA1_Stream4)) ? DDL_DMA_STREAM_4 : \ + ((uint32_t)(__STREAM_INSTANCE__) == ((uint32_t)DMA2_Stream4)) ? DDL_DMA_STREAM_4 : \ + ((uint32_t)(__STREAM_INSTANCE__) == ((uint32_t)DMA1_Stream5)) ? DDL_DMA_STREAM_5 : \ + ((uint32_t)(__STREAM_INSTANCE__) == ((uint32_t)DMA2_Stream5)) ? DDL_DMA_STREAM_5 : \ + ((uint32_t)(__STREAM_INSTANCE__) == ((uint32_t)DMA1_Stream6)) ? DDL_DMA_STREAM_6 : \ + ((uint32_t)(__STREAM_INSTANCE__) == ((uint32_t)DMA2_Stream6)) ? DDL_DMA_STREAM_6 : \ + DDL_DMA_STREAM_7) + +/** + * @brief Convert DMA Instance DMAx and DDL_DMA_STREAM_y into DMAx_Streamy + * @param __DMA_INSTANCE__ DMAx + * @param __STREAM__ DDL_DMA_STREAM_y + * @retval DMAx_Streamy + */ +#define __DDL_DMA_GET_STREAM_INSTANCE(__DMA_INSTANCE__, __STREAM__) \ +((((uint32_t)(__DMA_INSTANCE__) == ((uint32_t)DMA1)) && ((uint32_t)(__STREAM__) == ((uint32_t)DDL_DMA_STREAM_0))) ? DMA1_Stream0 : \ + (((uint32_t)(__DMA_INSTANCE__) == ((uint32_t)DMA2)) && ((uint32_t)(__STREAM__) == ((uint32_t)DDL_DMA_STREAM_0))) ? DMA2_Stream0 : \ + (((uint32_t)(__DMA_INSTANCE__) == ((uint32_t)DMA1)) && ((uint32_t)(__STREAM__) == ((uint32_t)DDL_DMA_STREAM_1))) ? DMA1_Stream1 : \ + (((uint32_t)(__DMA_INSTANCE__) == ((uint32_t)DMA2)) && ((uint32_t)(__STREAM__) == ((uint32_t)DDL_DMA_STREAM_1))) ? DMA2_Stream1 : \ + (((uint32_t)(__DMA_INSTANCE__) == ((uint32_t)DMA1)) && ((uint32_t)(__STREAM__) == ((uint32_t)DDL_DMA_STREAM_2))) ? DMA1_Stream2 : \ + (((uint32_t)(__DMA_INSTANCE__) == ((uint32_t)DMA2)) && ((uint32_t)(__STREAM__) == ((uint32_t)DDL_DMA_STREAM_2))) ? DMA2_Stream2 : \ + (((uint32_t)(__DMA_INSTANCE__) == ((uint32_t)DMA1)) && ((uint32_t)(__STREAM__) == ((uint32_t)DDL_DMA_STREAM_3))) ? DMA1_Stream3 : \ + (((uint32_t)(__DMA_INSTANCE__) == ((uint32_t)DMA2)) && ((uint32_t)(__STREAM__) == ((uint32_t)DDL_DMA_STREAM_3))) ? DMA2_Stream3 : \ + (((uint32_t)(__DMA_INSTANCE__) == ((uint32_t)DMA1)) && ((uint32_t)(__STREAM__) == ((uint32_t)DDL_DMA_STREAM_4))) ? DMA1_Stream4 : \ + (((uint32_t)(__DMA_INSTANCE__) == ((uint32_t)DMA2)) && ((uint32_t)(__STREAM__) == ((uint32_t)DDL_DMA_STREAM_4))) ? DMA2_Stream4 : \ + (((uint32_t)(__DMA_INSTANCE__) == ((uint32_t)DMA1)) && ((uint32_t)(__STREAM__) == ((uint32_t)DDL_DMA_STREAM_5))) ? DMA1_Stream5 : \ + (((uint32_t)(__DMA_INSTANCE__) == ((uint32_t)DMA2)) && ((uint32_t)(__STREAM__) == ((uint32_t)DDL_DMA_STREAM_5))) ? DMA2_Stream5 : \ + (((uint32_t)(__DMA_INSTANCE__) == ((uint32_t)DMA1)) && ((uint32_t)(__STREAM__) == ((uint32_t)DDL_DMA_STREAM_6))) ? DMA1_Stream6 : \ + (((uint32_t)(__DMA_INSTANCE__) == ((uint32_t)DMA2)) && ((uint32_t)(__STREAM__) == ((uint32_t)DDL_DMA_STREAM_6))) ? DMA2_Stream6 : \ + (((uint32_t)(__DMA_INSTANCE__) == ((uint32_t)DMA1)) && ((uint32_t)(__STREAM__) == ((uint32_t)DDL_DMA_STREAM_7))) ? DMA1_Stream7 : \ + DMA2_Stream7) + +/** + * @} + */ + +/** + * @} + */ + + +/* Exported functions --------------------------------------------------------*/ + /** @defgroup DMA_DDL_Exported_Functions DMA Exported Functions + * @{ + */ + +/** @defgroup DMA_DDL_EF_Configuration Configuration + * @{ + */ +/** + * @brief Enable DMA stream. + * @param DMAx DMAx Instance + * @param Stream This parameter can be one of the following values: + * @arg @ref DDL_DMA_STREAM_0 + * @arg @ref DDL_DMA_STREAM_1 + * @arg @ref DDL_DMA_STREAM_2 + * @arg @ref DDL_DMA_STREAM_3 + * @arg @ref DDL_DMA_STREAM_4 + * @arg @ref DDL_DMA_STREAM_5 + * @arg @ref DDL_DMA_STREAM_6 + * @arg @ref DDL_DMA_STREAM_7 + * @retval None + */ +__STATIC_INLINE void DDL_DMA_EnableStream(DMA_TypeDef *DMAx, uint32_t Stream) +{ + SET_BIT(((DMA_Stream_TypeDef *)((uint32_t)((uint32_t)DMAx + STREAM_OFFSET_TAB[Stream])))->SCFG, DMA_SCFGx_EN); +} + +/** + * @brief Disable DMA stream. + * @param DMAx DMAx Instance + * @param Stream This parameter can be one of the following values: + * @arg @ref DDL_DMA_STREAM_0 + * @arg @ref DDL_DMA_STREAM_1 + * @arg @ref DDL_DMA_STREAM_2 + * @arg @ref DDL_DMA_STREAM_3 + * @arg @ref DDL_DMA_STREAM_4 + * @arg @ref DDL_DMA_STREAM_5 + * @arg @ref DDL_DMA_STREAM_6 + * @arg @ref DDL_DMA_STREAM_7 + * @retval None + */ +__STATIC_INLINE void DDL_DMA_DisableStream(DMA_TypeDef *DMAx, uint32_t Stream) +{ + CLEAR_BIT(((DMA_Stream_TypeDef *)((uint32_t)((uint32_t)DMAx + STREAM_OFFSET_TAB[Stream])))->SCFG, DMA_SCFGx_EN); +} + +/** + * @brief Check if DMA stream is enabled or disabled. + * @param DMAx DMAx Instance + * @param Stream This parameter can be one of the following values: + * @arg @ref DDL_DMA_STREAM_0 + * @arg @ref DDL_DMA_STREAM_1 + * @arg @ref DDL_DMA_STREAM_2 + * @arg @ref DDL_DMA_STREAM_3 + * @arg @ref DDL_DMA_STREAM_4 + * @arg @ref DDL_DMA_STREAM_5 + * @arg @ref DDL_DMA_STREAM_6 + * @arg @ref DDL_DMA_STREAM_7 + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_DMA_IsEnabledStream(DMA_TypeDef *DMAx, uint32_t Stream) +{ + return (READ_BIT(((DMA_Stream_TypeDef*)((uint32_t)((uint32_t)DMAx + STREAM_OFFSET_TAB[Stream])))->SCFG, DMA_SCFGx_EN) == (DMA_SCFGx_EN)); +} + +/** + * @brief Configure all parameters linked to DMA transfer. + * @param DMAx DMAx Instance + * @param Stream This parameter can be one of the following values: + * @arg @ref DDL_DMA_STREAM_0 + * @arg @ref DDL_DMA_STREAM_1 + * @arg @ref DDL_DMA_STREAM_2 + * @arg @ref DDL_DMA_STREAM_3 + * @arg @ref DDL_DMA_STREAM_4 + * @arg @ref DDL_DMA_STREAM_5 + * @arg @ref DDL_DMA_STREAM_6 + * @arg @ref DDL_DMA_STREAM_7 + * @param Configuration This parameter must be a combination of all the following values: + * @arg @ref DDL_DMA_DIRECTION_PERIPH_TO_MEMORY or @ref DDL_DMA_DIRECTION_MEMORY_TO_PERIPH or @ref DDL_DMA_DIRECTION_MEMORY_TO_MEMORY + * @arg @ref DDL_DMA_MODE_NORMAL or @ref DDL_DMA_MODE_CIRCULAR or @ref DDL_DMA_MODE_PFCTRL + * @arg @ref DDL_DMA_PERIPH_INCREMENT or @ref DDL_DMA_PERIPH_NOINCREMENT + * @arg @ref DDL_DMA_MEMORY_INCREMENT or @ref DDL_DMA_MEMORY_NOINCREMENT + * @arg @ref DDL_DMA_PDATAALIGN_BYTE or @ref DDL_DMA_PDATAALIGN_HALFWORD or @ref DDL_DMA_PDATAALIGN_WORD + * @arg @ref DDL_DMA_MDATAALIGN_BYTE or @ref DDL_DMA_MDATAALIGN_HALFWORD or @ref DDL_DMA_MDATAALIGN_WORD + * @arg @ref DDL_DMA_PRIORITY_LOW or @ref DDL_DMA_PRIORITY_MEDIUM or @ref DDL_DMA_PRIORITY_HIGH or @ref DDL_DMA_PRIORITY_VERYHIGH + *@retval None + */ +__STATIC_INLINE void DDL_DMA_ConfigTransfer(DMA_TypeDef *DMAx, uint32_t Stream, uint32_t Configuration) +{ + MODIFY_REG(((DMA_Stream_TypeDef *)((uint32_t)((uint32_t)DMAx + STREAM_OFFSET_TAB[Stream])))->SCFG, + DMA_SCFGx_DIRCFG | DMA_SCFGx_CIRCMEN | DMA_SCFGx_PERIM | DMA_SCFGx_MEMIM | DMA_SCFGx_PERSIZECFG | DMA_SCFGx_MEMSIZECFG | DMA_SCFGx_PRILCFG | DMA_SCFGx_PERFC, + Configuration); +} + +/** + * @brief Set Data transfer direction (read from peripheral or from memory). + * @param DMAx DMAx Instance + * @param Stream This parameter can be one of the following values: + * @arg @ref DDL_DMA_STREAM_0 + * @arg @ref DDL_DMA_STREAM_1 + * @arg @ref DDL_DMA_STREAM_2 + * @arg @ref DDL_DMA_STREAM_3 + * @arg @ref DDL_DMA_STREAM_4 + * @arg @ref DDL_DMA_STREAM_5 + * @arg @ref DDL_DMA_STREAM_6 + * @arg @ref DDL_DMA_STREAM_7 + * @param Direction This parameter can be one of the following values: + * @arg @ref DDL_DMA_DIRECTION_PERIPH_TO_MEMORY + * @arg @ref DDL_DMA_DIRECTION_MEMORY_TO_PERIPH + * @arg @ref DDL_DMA_DIRECTION_MEMORY_TO_MEMORY + * @retval None + */ +__STATIC_INLINE void DDL_DMA_SetDataTransferDirection(DMA_TypeDef *DMAx, uint32_t Stream, uint32_t Direction) +{ + MODIFY_REG(((DMA_Stream_TypeDef*)((uint32_t)((uint32_t)DMAx + STREAM_OFFSET_TAB[Stream])))->SCFG, DMA_SCFGx_DIRCFG, Direction); +} + +/** + * @brief Get Data transfer direction (read from peripheral or from memory). + * @param DMAx DMAx Instance + * @param Stream This parameter can be one of the following values: + * @arg @ref DDL_DMA_STREAM_0 + * @arg @ref DDL_DMA_STREAM_1 + * @arg @ref DDL_DMA_STREAM_2 + * @arg @ref DDL_DMA_STREAM_3 + * @arg @ref DDL_DMA_STREAM_4 + * @arg @ref DDL_DMA_STREAM_5 + * @arg @ref DDL_DMA_STREAM_6 + * @arg @ref DDL_DMA_STREAM_7 + * @retval Returned value can be one of the following values: + * @arg @ref DDL_DMA_DIRECTION_PERIPH_TO_MEMORY + * @arg @ref DDL_DMA_DIRECTION_MEMORY_TO_PERIPH + * @arg @ref DDL_DMA_DIRECTION_MEMORY_TO_MEMORY + */ +__STATIC_INLINE uint32_t DDL_DMA_GetDataTransferDirection(DMA_TypeDef *DMAx, uint32_t Stream) +{ + return (READ_BIT(((DMA_Stream_TypeDef*)((uint32_t)((uint32_t)DMAx + STREAM_OFFSET_TAB[Stream])))->SCFG, DMA_SCFGx_DIRCFG)); +} + +/** + * @brief Set DMA mode normal, circular or peripheral flow control. + * @param DMAx DMAx Instance + * @param Stream This parameter can be one of the following values: + * @arg @ref DDL_DMA_STREAM_0 + * @arg @ref DDL_DMA_STREAM_1 + * @arg @ref DDL_DMA_STREAM_2 + * @arg @ref DDL_DMA_STREAM_3 + * @arg @ref DDL_DMA_STREAM_4 + * @arg @ref DDL_DMA_STREAM_5 + * @arg @ref DDL_DMA_STREAM_6 + * @arg @ref DDL_DMA_STREAM_7 + * @param Mode This parameter can be one of the following values: + * @arg @ref DDL_DMA_MODE_NORMAL + * @arg @ref DDL_DMA_MODE_CIRCULAR + * @arg @ref DDL_DMA_MODE_PFCTRL + * @retval None + */ +__STATIC_INLINE void DDL_DMA_SetMode(DMA_TypeDef *DMAx, uint32_t Stream, uint32_t Mode) +{ + MODIFY_REG(((DMA_Stream_TypeDef*)((uint32_t)((uint32_t)DMAx + STREAM_OFFSET_TAB[Stream])))->SCFG, DMA_SCFGx_CIRCMEN | DMA_SCFGx_PERFC, Mode); +} + +/** + * @brief Get DMA mode normal, circular or peripheral flow control. + * @param DMAx DMAx Instance + * @param Stream This parameter can be one of the following values: + * @arg @ref DDL_DMA_STREAM_0 + * @arg @ref DDL_DMA_STREAM_1 + * @arg @ref DDL_DMA_STREAM_2 + * @arg @ref DDL_DMA_STREAM_3 + * @arg @ref DDL_DMA_STREAM_4 + * @arg @ref DDL_DMA_STREAM_5 + * @arg @ref DDL_DMA_STREAM_6 + * @arg @ref DDL_DMA_STREAM_7 + * @retval Returned value can be one of the following values: + * @arg @ref DDL_DMA_MODE_NORMAL + * @arg @ref DDL_DMA_MODE_CIRCULAR + * @arg @ref DDL_DMA_MODE_PFCTRL + */ +__STATIC_INLINE uint32_t DDL_DMA_GetMode(DMA_TypeDef *DMAx, uint32_t Stream) +{ + return (READ_BIT(((DMA_Stream_TypeDef*)((uint32_t)((uint32_t)DMAx + STREAM_OFFSET_TAB[Stream])))->SCFG, DMA_SCFGx_CIRCMEN | DMA_SCFGx_PERFC)); +} + +/** + * @brief Set Peripheral increment mode. + * @param DMAx DMAx Instance + * @param Stream This parameter can be one of the following values: + * @arg @ref DDL_DMA_STREAM_0 + * @arg @ref DDL_DMA_STREAM_1 + * @arg @ref DDL_DMA_STREAM_2 + * @arg @ref DDL_DMA_STREAM_3 + * @arg @ref DDL_DMA_STREAM_4 + * @arg @ref DDL_DMA_STREAM_5 + * @arg @ref DDL_DMA_STREAM_6 + * @arg @ref DDL_DMA_STREAM_7 + * @param IncrementMode This parameter can be one of the following values: + * @arg @ref DDL_DMA_PERIPH_NOINCREMENT + * @arg @ref DDL_DMA_PERIPH_INCREMENT + * @retval None + */ +__STATIC_INLINE void DDL_DMA_SetPeriphIncMode(DMA_TypeDef *DMAx, uint32_t Stream, uint32_t IncrementMode) +{ + MODIFY_REG(((DMA_Stream_TypeDef*)((uint32_t)((uint32_t)DMAx + STREAM_OFFSET_TAB[Stream])))->SCFG, DMA_SCFGx_PERIM, IncrementMode); +} + +/** + * @brief Get Peripheral increment mode. + * @param DMAx DMAx Instance + * @param Stream This parameter can be one of the following values: + * @arg @ref DDL_DMA_STREAM_0 + * @arg @ref DDL_DMA_STREAM_1 + * @arg @ref DDL_DMA_STREAM_2 + * @arg @ref DDL_DMA_STREAM_3 + * @arg @ref DDL_DMA_STREAM_4 + * @arg @ref DDL_DMA_STREAM_5 + * @arg @ref DDL_DMA_STREAM_6 + * @arg @ref DDL_DMA_STREAM_7 + * @retval Returned value can be one of the following values: + * @arg @ref DDL_DMA_PERIPH_NOINCREMENT + * @arg @ref DDL_DMA_PERIPH_INCREMENT + */ +__STATIC_INLINE uint32_t DDL_DMA_GetPeriphIncMode(DMA_TypeDef *DMAx, uint32_t Stream) +{ + return (READ_BIT(((DMA_Stream_TypeDef*)((uint32_t)((uint32_t)DMAx + STREAM_OFFSET_TAB[Stream])))->SCFG, DMA_SCFGx_PERIM)); +} + +/** + * @brief Set Memory increment mode. + * @param DMAx DMAx Instance + * @param Stream This parameter can be one of the following values: + * @arg @ref DDL_DMA_STREAM_0 + * @arg @ref DDL_DMA_STREAM_1 + * @arg @ref DDL_DMA_STREAM_2 + * @arg @ref DDL_DMA_STREAM_3 + * @arg @ref DDL_DMA_STREAM_4 + * @arg @ref DDL_DMA_STREAM_5 + * @arg @ref DDL_DMA_STREAM_6 + * @arg @ref DDL_DMA_STREAM_7 + * @param IncrementMode This parameter can be one of the following values: + * @arg @ref DDL_DMA_MEMORY_NOINCREMENT + * @arg @ref DDL_DMA_MEMORY_INCREMENT + * @retval None + */ +__STATIC_INLINE void DDL_DMA_SetMemoryIncMode(DMA_TypeDef *DMAx, uint32_t Stream, uint32_t IncrementMode) +{ + MODIFY_REG(((DMA_Stream_TypeDef*)((uint32_t)((uint32_t)DMAx + STREAM_OFFSET_TAB[Stream])))->SCFG, DMA_SCFGx_MEMIM, IncrementMode); +} + +/** + * @brief Get Memory increment mode. + * @param DMAx DMAx Instance + * @param Stream This parameter can be one of the following values: + * @arg @ref DDL_DMA_STREAM_0 + * @arg @ref DDL_DMA_STREAM_1 + * @arg @ref DDL_DMA_STREAM_2 + * @arg @ref DDL_DMA_STREAM_3 + * @arg @ref DDL_DMA_STREAM_4 + * @arg @ref DDL_DMA_STREAM_5 + * @arg @ref DDL_DMA_STREAM_6 + * @arg @ref DDL_DMA_STREAM_7 + * @retval Returned value can be one of the following values: + * @arg @ref DDL_DMA_MEMORY_NOINCREMENT + * @arg @ref DDL_DMA_MEMORY_INCREMENT + */ +__STATIC_INLINE uint32_t DDL_DMA_GetMemoryIncMode(DMA_TypeDef *DMAx, uint32_t Stream) +{ + return (READ_BIT(((DMA_Stream_TypeDef*)((uint32_t)((uint32_t)DMAx + STREAM_OFFSET_TAB[Stream])))->SCFG, DMA_SCFGx_MEMIM)); +} + +/** + * @brief Set Peripheral size. + * @param DMAx DMAx Instance + * @param Stream This parameter can be one of the following values: + * @arg @ref DDL_DMA_STREAM_0 + * @arg @ref DDL_DMA_STREAM_1 + * @arg @ref DDL_DMA_STREAM_2 + * @arg @ref DDL_DMA_STREAM_3 + * @arg @ref DDL_DMA_STREAM_4 + * @arg @ref DDL_DMA_STREAM_5 + * @arg @ref DDL_DMA_STREAM_6 + * @arg @ref DDL_DMA_STREAM_7 + * @param Size This parameter can be one of the following values: + * @arg @ref DDL_DMA_PDATAALIGN_BYTE + * @arg @ref DDL_DMA_PDATAALIGN_HALFWORD + * @arg @ref DDL_DMA_PDATAALIGN_WORD + * @retval None + */ +__STATIC_INLINE void DDL_DMA_SetPeriphSize(DMA_TypeDef *DMAx, uint32_t Stream, uint32_t Size) +{ + MODIFY_REG(((DMA_Stream_TypeDef*)((uint32_t)((uint32_t)DMAx + STREAM_OFFSET_TAB[Stream])))->SCFG, DMA_SCFGx_PERSIZECFG, Size); +} + +/** + * @brief Get Peripheral size. + * @param DMAx DMAx Instance + * @param Stream This parameter can be one of the following values: + * @arg @ref DDL_DMA_STREAM_0 + * @arg @ref DDL_DMA_STREAM_1 + * @arg @ref DDL_DMA_STREAM_2 + * @arg @ref DDL_DMA_STREAM_3 + * @arg @ref DDL_DMA_STREAM_4 + * @arg @ref DDL_DMA_STREAM_5 + * @arg @ref DDL_DMA_STREAM_6 + * @arg @ref DDL_DMA_STREAM_7 + * @retval Returned value can be one of the following values: + * @arg @ref DDL_DMA_PDATAALIGN_BYTE + * @arg @ref DDL_DMA_PDATAALIGN_HALFWORD + * @arg @ref DDL_DMA_PDATAALIGN_WORD + */ +__STATIC_INLINE uint32_t DDL_DMA_GetPeriphSize(DMA_TypeDef *DMAx, uint32_t Stream) +{ + return (READ_BIT(((DMA_Stream_TypeDef*)((uint32_t)((uint32_t)DMAx + STREAM_OFFSET_TAB[Stream])))->SCFG, DMA_SCFGx_PERSIZECFG)); +} + +/** + * @brief Set Memory size. + * @param DMAx DMAx Instance + * @param Stream This parameter can be one of the following values: + * @arg @ref DDL_DMA_STREAM_0 + * @arg @ref DDL_DMA_STREAM_1 + * @arg @ref DDL_DMA_STREAM_2 + * @arg @ref DDL_DMA_STREAM_3 + * @arg @ref DDL_DMA_STREAM_4 + * @arg @ref DDL_DMA_STREAM_5 + * @arg @ref DDL_DMA_STREAM_6 + * @arg @ref DDL_DMA_STREAM_7 + * @param Size This parameter can be one of the following values: + * @arg @ref DDL_DMA_MDATAALIGN_BYTE + * @arg @ref DDL_DMA_MDATAALIGN_HALFWORD + * @arg @ref DDL_DMA_MDATAALIGN_WORD + * @retval None + */ +__STATIC_INLINE void DDL_DMA_SetMemorySize(DMA_TypeDef *DMAx, uint32_t Stream, uint32_t Size) +{ + MODIFY_REG(((DMA_Stream_TypeDef*)((uint32_t)((uint32_t)DMAx + STREAM_OFFSET_TAB[Stream])))->SCFG, DMA_SCFGx_MEMSIZECFG, Size); +} + +/** + * @brief Get Memory size. + * @param DMAx DMAx Instance + * @param Stream This parameter can be one of the following values: + * @arg @ref DDL_DMA_STREAM_0 + * @arg @ref DDL_DMA_STREAM_1 + * @arg @ref DDL_DMA_STREAM_2 + * @arg @ref DDL_DMA_STREAM_3 + * @arg @ref DDL_DMA_STREAM_4 + * @arg @ref DDL_DMA_STREAM_5 + * @arg @ref DDL_DMA_STREAM_6 + * @arg @ref DDL_DMA_STREAM_7 + * @retval Returned value can be one of the following values: + * @arg @ref DDL_DMA_MDATAALIGN_BYTE + * @arg @ref DDL_DMA_MDATAALIGN_HALFWORD + * @arg @ref DDL_DMA_MDATAALIGN_WORD + */ +__STATIC_INLINE uint32_t DDL_DMA_GetMemorySize(DMA_TypeDef *DMAx, uint32_t Stream) +{ + return (READ_BIT(((DMA_Stream_TypeDef*)((uint32_t)((uint32_t)DMAx + STREAM_OFFSET_TAB[Stream])))->SCFG, DMA_SCFGx_MEMSIZECFG)); +} + +/** + * @brief Set Peripheral increment offset size. + * @param DMAx DMAx Instance + * @param Stream This parameter can be one of the following values: + * @arg @ref DDL_DMA_STREAM_0 + * @arg @ref DDL_DMA_STREAM_1 + * @arg @ref DDL_DMA_STREAM_2 + * @arg @ref DDL_DMA_STREAM_3 + * @arg @ref DDL_DMA_STREAM_4 + * @arg @ref DDL_DMA_STREAM_5 + * @arg @ref DDL_DMA_STREAM_6 + * @arg @ref DDL_DMA_STREAM_7 + * @param OffsetSize This parameter can be one of the following values: + * @arg @ref DDL_DMA_OFFSETSIZE_PSIZE + * @arg @ref DDL_DMA_OFFSETSIZE_FIXEDTO4 + * @retval None + */ +__STATIC_INLINE void DDL_DMA_SetIncOffsetSize(DMA_TypeDef *DMAx, uint32_t Stream, uint32_t OffsetSize) +{ + MODIFY_REG(((DMA_Stream_TypeDef*)((uint32_t)((uint32_t)DMAx + STREAM_OFFSET_TAB[Stream])))->SCFG, DMA_SCFGx_PERIOSIZE, OffsetSize); +} + +/** + * @brief Get Peripheral increment offset size. + * @param DMAx DMAx Instance + * @param Stream This parameter can be one of the following values: + * @arg @ref DDL_DMA_STREAM_0 + * @arg @ref DDL_DMA_STREAM_1 + * @arg @ref DDL_DMA_STREAM_2 + * @arg @ref DDL_DMA_STREAM_3 + * @arg @ref DDL_DMA_STREAM_4 + * @arg @ref DDL_DMA_STREAM_5 + * @arg @ref DDL_DMA_STREAM_6 + * @arg @ref DDL_DMA_STREAM_7 + * @retval Returned value can be one of the following values: + * @arg @ref DDL_DMA_OFFSETSIZE_PSIZE + * @arg @ref DDL_DMA_OFFSETSIZE_FIXEDTO4 + */ +__STATIC_INLINE uint32_t DDL_DMA_GetIncOffsetSize(DMA_TypeDef *DMAx, uint32_t Stream) +{ + return (READ_BIT(((DMA_Stream_TypeDef*)((uint32_t)((uint32_t)DMAx + STREAM_OFFSET_TAB[Stream])))->SCFG, DMA_SCFGx_PERIOSIZE)); +} + +/** + * @brief Set Stream priority level. + * @param DMAx DMAx Instance + * @param Stream This parameter can be one of the following values: + * @arg @ref DDL_DMA_STREAM_0 + * @arg @ref DDL_DMA_STREAM_1 + * @arg @ref DDL_DMA_STREAM_2 + * @arg @ref DDL_DMA_STREAM_3 + * @arg @ref DDL_DMA_STREAM_4 + * @arg @ref DDL_DMA_STREAM_5 + * @arg @ref DDL_DMA_STREAM_6 + * @arg @ref DDL_DMA_STREAM_7 + * @param Priority This parameter can be one of the following values: + * @arg @ref DDL_DMA_PRIORITY_LOW + * @arg @ref DDL_DMA_PRIORITY_MEDIUM + * @arg @ref DDL_DMA_PRIORITY_HIGH + * @arg @ref DDL_DMA_PRIORITY_VERYHIGH + * @retval None + */ +__STATIC_INLINE void DDL_DMA_SetStreamPriorityLevel(DMA_TypeDef *DMAx, uint32_t Stream, uint32_t Priority) +{ + MODIFY_REG(((DMA_Stream_TypeDef*)((uint32_t)((uint32_t)DMAx + STREAM_OFFSET_TAB[Stream])))->SCFG, DMA_SCFGx_PRILCFG, Priority); +} + +/** + * @brief Get Stream priority level. + * @param DMAx DMAx Instance + * @param Stream This parameter can be one of the following values: + * @arg @ref DDL_DMA_STREAM_0 + * @arg @ref DDL_DMA_STREAM_1 + * @arg @ref DDL_DMA_STREAM_2 + * @arg @ref DDL_DMA_STREAM_3 + * @arg @ref DDL_DMA_STREAM_4 + * @arg @ref DDL_DMA_STREAM_5 + * @arg @ref DDL_DMA_STREAM_6 + * @arg @ref DDL_DMA_STREAM_7 + * @retval Returned value can be one of the following values: + * @arg @ref DDL_DMA_PRIORITY_LOW + * @arg @ref DDL_DMA_PRIORITY_MEDIUM + * @arg @ref DDL_DMA_PRIORITY_HIGH + * @arg @ref DDL_DMA_PRIORITY_VERYHIGH + */ +__STATIC_INLINE uint32_t DDL_DMA_GetStreamPriorityLevel(DMA_TypeDef *DMAx, uint32_t Stream) +{ + return (READ_BIT(((DMA_Stream_TypeDef*)((uint32_t)((uint32_t)DMAx + STREAM_OFFSET_TAB[Stream])))->SCFG, DMA_SCFGx_PRILCFG)); +} + +/** + * @brief Set Number of data to transfer. + * @note This action has no effect if + * stream is enabled. + * @param DMAx DMAx Instance + * @param Stream This parameter can be one of the following values: + * @arg @ref DDL_DMA_STREAM_0 + * @arg @ref DDL_DMA_STREAM_1 + * @arg @ref DDL_DMA_STREAM_2 + * @arg @ref DDL_DMA_STREAM_3 + * @arg @ref DDL_DMA_STREAM_4 + * @arg @ref DDL_DMA_STREAM_5 + * @arg @ref DDL_DMA_STREAM_6 + * @arg @ref DDL_DMA_STREAM_7 + * @param NbData Between 0 to 0xFFFFFFFF + * @retval None + */ +__STATIC_INLINE void DDL_DMA_SetDataLength(DMA_TypeDef* DMAx, uint32_t Stream, uint32_t NbData) +{ + MODIFY_REG(((DMA_Stream_TypeDef*)((uint32_t)((uint32_t)DMAx + STREAM_OFFSET_TAB[Stream])))->NDATA, DMA_NDATAx, NbData); +} + +/** + * @brief Get Number of data to transfer. + * @note Once the stream is enabled, the return value indicate the + * remaining bytes to be transmitted. + * @param DMAx DMAx Instance + * @param Stream This parameter can be one of the following values: + * @arg @ref DDL_DMA_STREAM_0 + * @arg @ref DDL_DMA_STREAM_1 + * @arg @ref DDL_DMA_STREAM_2 + * @arg @ref DDL_DMA_STREAM_3 + * @arg @ref DDL_DMA_STREAM_4 + * @arg @ref DDL_DMA_STREAM_5 + * @arg @ref DDL_DMA_STREAM_6 + * @arg @ref DDL_DMA_STREAM_7 + * @retval Between 0 to 0xFFFFFFFF + */ +__STATIC_INLINE uint32_t DDL_DMA_GetDataLength(DMA_TypeDef* DMAx, uint32_t Stream) +{ + return (READ_BIT(((DMA_Stream_TypeDef*)((uint32_t)((uint32_t)DMAx + STREAM_OFFSET_TAB[Stream])))->NDATA, DMA_NDATAx)); +} + +/** + * @brief Select Channel number associated to the Stream. + * @param DMAx DMAx Instance + * @param Stream This parameter can be one of the following values: + * @arg @ref DDL_DMA_STREAM_0 + * @arg @ref DDL_DMA_STREAM_1 + * @arg @ref DDL_DMA_STREAM_2 + * @arg @ref DDL_DMA_STREAM_3 + * @arg @ref DDL_DMA_STREAM_4 + * @arg @ref DDL_DMA_STREAM_5 + * @arg @ref DDL_DMA_STREAM_6 + * @arg @ref DDL_DMA_STREAM_7 + * @param Channel This parameter can be one of the following values: + * @arg @ref DDL_DMA_CHANNEL_0 + * @arg @ref DDL_DMA_CHANNEL_1 + * @arg @ref DDL_DMA_CHANNEL_2 + * @arg @ref DDL_DMA_CHANNEL_3 + * @arg @ref DDL_DMA_CHANNEL_4 + * @arg @ref DDL_DMA_CHANNEL_5 + * @arg @ref DDL_DMA_CHANNEL_6 + * @arg @ref DDL_DMA_CHANNEL_7 + * @retval None + */ +__STATIC_INLINE void DDL_DMA_SetChannelSelection(DMA_TypeDef *DMAx, uint32_t Stream, uint32_t Channel) +{ + MODIFY_REG(((DMA_Stream_TypeDef*)((uint32_t)((uint32_t)DMAx + STREAM_OFFSET_TAB[Stream])))->SCFG, DMA_SCFGx_CHSEL, Channel); +} + +/** + * @brief Get the Channel number associated to the Stream. + * @param DMAx DMAx Instance + * @param Stream This parameter can be one of the following values: + * @arg @ref DDL_DMA_STREAM_0 + * @arg @ref DDL_DMA_STREAM_1 + * @arg @ref DDL_DMA_STREAM_2 + * @arg @ref DDL_DMA_STREAM_3 + * @arg @ref DDL_DMA_STREAM_4 + * @arg @ref DDL_DMA_STREAM_5 + * @arg @ref DDL_DMA_STREAM_6 + * @arg @ref DDL_DMA_STREAM_7 + * @retval Returned value can be one of the following values: + * @arg @ref DDL_DMA_CHANNEL_0 + * @arg @ref DDL_DMA_CHANNEL_1 + * @arg @ref DDL_DMA_CHANNEL_2 + * @arg @ref DDL_DMA_CHANNEL_3 + * @arg @ref DDL_DMA_CHANNEL_4 + * @arg @ref DDL_DMA_CHANNEL_5 + * @arg @ref DDL_DMA_CHANNEL_6 + * @arg @ref DDL_DMA_CHANNEL_7 + */ +__STATIC_INLINE uint32_t DDL_DMA_GetChannelSelection(DMA_TypeDef *DMAx, uint32_t Stream) +{ + return (READ_BIT(((DMA_Stream_TypeDef*)((uint32_t)((uint32_t)DMAx + STREAM_OFFSET_TAB[Stream])))->SCFG, DMA_SCFGx_CHSEL)); +} + +/** + * @brief Set Memory burst transfer configuration. + * @param DMAx DMAx Instance + * @param Stream This parameter can be one of the following values: + * @arg @ref DDL_DMA_STREAM_0 + * @arg @ref DDL_DMA_STREAM_1 + * @arg @ref DDL_DMA_STREAM_2 + * @arg @ref DDL_DMA_STREAM_3 + * @arg @ref DDL_DMA_STREAM_4 + * @arg @ref DDL_DMA_STREAM_5 + * @arg @ref DDL_DMA_STREAM_6 + * @arg @ref DDL_DMA_STREAM_7 + * @param Mburst This parameter can be one of the following values: + * @arg @ref DDL_DMA_MBURST_SINGLE + * @arg @ref DDL_DMA_MBURST_INC4 + * @arg @ref DDL_DMA_MBURST_INC8 + * @arg @ref DDL_DMA_MBURST_INC16 + * @retval None + */ +__STATIC_INLINE void DDL_DMA_SetMemoryBurstxfer(DMA_TypeDef *DMAx, uint32_t Stream, uint32_t Mburst) +{ + MODIFY_REG(((DMA_Stream_TypeDef*)((uint32_t)((uint32_t)DMAx + STREAM_OFFSET_TAB[Stream])))->SCFG, DMA_SCFGx_MBCFG, Mburst); +} + +/** + * @brief Get Memory burst transfer configuration. + * @param DMAx DMAx Instance + * @param Stream This parameter can be one of the following values: + * @arg @ref DDL_DMA_STREAM_0 + * @arg @ref DDL_DMA_STREAM_1 + * @arg @ref DDL_DMA_STREAM_2 + * @arg @ref DDL_DMA_STREAM_3 + * @arg @ref DDL_DMA_STREAM_4 + * @arg @ref DDL_DMA_STREAM_5 + * @arg @ref DDL_DMA_STREAM_6 + * @arg @ref DDL_DMA_STREAM_7 + * @retval Returned value can be one of the following values: + * @arg @ref DDL_DMA_MBURST_SINGLE + * @arg @ref DDL_DMA_MBURST_INC4 + * @arg @ref DDL_DMA_MBURST_INC8 + * @arg @ref DDL_DMA_MBURST_INC16 + */ +__STATIC_INLINE uint32_t DDL_DMA_GetMemoryBurstxfer(DMA_TypeDef *DMAx, uint32_t Stream) +{ + return (READ_BIT(((DMA_Stream_TypeDef*)((uint32_t)((uint32_t)DMAx + STREAM_OFFSET_TAB[Stream])))->SCFG, DMA_SCFGx_MBCFG)); +} + +/** + * @brief Set Peripheral burst transfer configuration. + * @param DMAx DMAx Instance + * @param Stream This parameter can be one of the following values: + * @arg @ref DDL_DMA_STREAM_0 + * @arg @ref DDL_DMA_STREAM_1 + * @arg @ref DDL_DMA_STREAM_2 + * @arg @ref DDL_DMA_STREAM_3 + * @arg @ref DDL_DMA_STREAM_4 + * @arg @ref DDL_DMA_STREAM_5 + * @arg @ref DDL_DMA_STREAM_6 + * @arg @ref DDL_DMA_STREAM_7 + * @param Pburst This parameter can be one of the following values: + * @arg @ref DDL_DMA_PBURST_SINGLE + * @arg @ref DDL_DMA_PBURST_INC4 + * @arg @ref DDL_DMA_PBURST_INC8 + * @arg @ref DDL_DMA_PBURST_INC16 + * @retval None + */ +__STATIC_INLINE void DDL_DMA_SetPeriphBurstxfer(DMA_TypeDef *DMAx, uint32_t Stream, uint32_t Pburst) +{ + MODIFY_REG(((DMA_Stream_TypeDef*)((uint32_t)((uint32_t)DMAx + STREAM_OFFSET_TAB[Stream])))->SCFG, DMA_SCFGx_PBCFG, Pburst); +} + +/** + * @brief Get Peripheral burst transfer configuration. + * @param DMAx DMAx Instance + * @param Stream This parameter can be one of the following values: + * @arg @ref DDL_DMA_STREAM_0 + * @arg @ref DDL_DMA_STREAM_1 + * @arg @ref DDL_DMA_STREAM_2 + * @arg @ref DDL_DMA_STREAM_3 + * @arg @ref DDL_DMA_STREAM_4 + * @arg @ref DDL_DMA_STREAM_5 + * @arg @ref DDL_DMA_STREAM_6 + * @arg @ref DDL_DMA_STREAM_7 + * @retval Returned value can be one of the following values: + * @arg @ref DDL_DMA_PBURST_SINGLE + * @arg @ref DDL_DMA_PBURST_INC4 + * @arg @ref DDL_DMA_PBURST_INC8 + * @arg @ref DDL_DMA_PBURST_INC16 + */ +__STATIC_INLINE uint32_t DDL_DMA_GetPeriphBurstxfer(DMA_TypeDef *DMAx, uint32_t Stream) +{ + return (READ_BIT(((DMA_Stream_TypeDef*)((uint32_t)((uint32_t)DMAx + STREAM_OFFSET_TAB[Stream])))->SCFG, DMA_SCFGx_PBCFG)); +} + +/** + * @brief Set Current target (only in double buffer mode) to Memory 1 or Memory 0. + * @param DMAx DMAx Instance + * @param Stream This parameter can be one of the following values: + * @arg @ref DDL_DMA_STREAM_0 + * @arg @ref DDL_DMA_STREAM_1 + * @arg @ref DDL_DMA_STREAM_2 + * @arg @ref DDL_DMA_STREAM_3 + * @arg @ref DDL_DMA_STREAM_4 + * @arg @ref DDL_DMA_STREAM_5 + * @arg @ref DDL_DMA_STREAM_6 + * @arg @ref DDL_DMA_STREAM_7 + * @param CurrentMemory This parameter can be one of the following values: + * @arg @ref DDL_DMA_CURRENTTARGETMEM0 + * @arg @ref DDL_DMA_CURRENTTARGETMEM1 + * @retval None + */ +__STATIC_INLINE void DDL_DMA_SetCurrentTargetMem(DMA_TypeDef *DMAx, uint32_t Stream, uint32_t CurrentMemory) +{ + MODIFY_REG(((DMA_Stream_TypeDef*)((uint32_t)((uint32_t)DMAx + STREAM_OFFSET_TAB[Stream])))->SCFG, DMA_SCFGx_CTARG, CurrentMemory); +} + +/** + * @brief Set Current target (only in double buffer mode) to Memory 1 or Memory 0. + * @param DMAx DMAx Instance + * @param Stream This parameter can be one of the following values: + * @arg @ref DDL_DMA_STREAM_0 + * @arg @ref DDL_DMA_STREAM_1 + * @arg @ref DDL_DMA_STREAM_2 + * @arg @ref DDL_DMA_STREAM_3 + * @arg @ref DDL_DMA_STREAM_4 + * @arg @ref DDL_DMA_STREAM_5 + * @arg @ref DDL_DMA_STREAM_6 + * @arg @ref DDL_DMA_STREAM_7 + * @retval Returned value can be one of the following values: + * @arg @ref DDL_DMA_CURRENTTARGETMEM0 + * @arg @ref DDL_DMA_CURRENTTARGETMEM1 + */ +__STATIC_INLINE uint32_t DDL_DMA_GetCurrentTargetMem(DMA_TypeDef *DMAx, uint32_t Stream) +{ + return (READ_BIT(((DMA_Stream_TypeDef*)((uint32_t)((uint32_t)DMAx + STREAM_OFFSET_TAB[Stream])))->SCFG, DMA_SCFGx_CTARG)); +} + +/** + * @brief Enable the double buffer mode. + * @param DMAx DMAx Instance + * @param Stream This parameter can be one of the following values: + * @arg @ref DDL_DMA_STREAM_0 + * @arg @ref DDL_DMA_STREAM_1 + * @arg @ref DDL_DMA_STREAM_2 + * @arg @ref DDL_DMA_STREAM_3 + * @arg @ref DDL_DMA_STREAM_4 + * @arg @ref DDL_DMA_STREAM_5 + * @arg @ref DDL_DMA_STREAM_6 + * @arg @ref DDL_DMA_STREAM_7 + * @retval None + */ +__STATIC_INLINE void DDL_DMA_EnableDoubleBufferMode(DMA_TypeDef *DMAx, uint32_t Stream) +{ + SET_BIT(((DMA_Stream_TypeDef *)((uint32_t)((uint32_t)DMAx + STREAM_OFFSET_TAB[Stream])))->SCFG, DMA_SCFGx_DBM); +} + +/** + * @brief Disable the double buffer mode. + * @param DMAx DMAx Instance + * @param Stream This parameter can be one of the following values: + * @arg @ref DDL_DMA_STREAM_0 + * @arg @ref DDL_DMA_STREAM_1 + * @arg @ref DDL_DMA_STREAM_2 + * @arg @ref DDL_DMA_STREAM_3 + * @arg @ref DDL_DMA_STREAM_4 + * @arg @ref DDL_DMA_STREAM_5 + * @arg @ref DDL_DMA_STREAM_6 + * @arg @ref DDL_DMA_STREAM_7 + * @retval None + */ +__STATIC_INLINE void DDL_DMA_DisableDoubleBufferMode(DMA_TypeDef *DMAx, uint32_t Stream) +{ + CLEAR_BIT(((DMA_Stream_TypeDef *)((uint32_t)((uint32_t)DMAx + STREAM_OFFSET_TAB[Stream])))->SCFG, DMA_SCFGx_DBM); +} + +/** + * @brief Get FIFO status. + * @param DMAx DMAx Instance + * @param Stream This parameter can be one of the following values: + * @arg @ref DDL_DMA_STREAM_0 + * @arg @ref DDL_DMA_STREAM_1 + * @arg @ref DDL_DMA_STREAM_2 + * @arg @ref DDL_DMA_STREAM_3 + * @arg @ref DDL_DMA_STREAM_4 + * @arg @ref DDL_DMA_STREAM_5 + * @arg @ref DDL_DMA_STREAM_6 + * @arg @ref DDL_DMA_STREAM_7 + * @retval Returned value can be one of the following values: + * @arg @ref DDL_DMA_FIFOSTATUS_0_25 + * @arg @ref DDL_DMA_FIFOSTATUS_25_50 + * @arg @ref DDL_DMA_FIFOSTATUS_50_75 + * @arg @ref DDL_DMA_FIFOSTATUS_75_100 + * @arg @ref DDL_DMA_FIFOSTATUS_EMPTY + * @arg @ref DDL_DMA_FIFOSTATUS_FULL + */ +__STATIC_INLINE uint32_t DDL_DMA_GetFIFOStatus(DMA_TypeDef *DMAx, uint32_t Stream) +{ + return (READ_BIT(((DMA_Stream_TypeDef*)((uint32_t)((uint32_t)DMAx + STREAM_OFFSET_TAB[Stream])))->FCTRL, DMA_FCTRLx_FSTS)); +} + +/** + * @brief Disable Fifo mode. + * @param DMAx DMAx Instance + * @param Stream This parameter can be one of the following values: + * @arg @ref DDL_DMA_STREAM_0 + * @arg @ref DDL_DMA_STREAM_1 + * @arg @ref DDL_DMA_STREAM_2 + * @arg @ref DDL_DMA_STREAM_3 + * @arg @ref DDL_DMA_STREAM_4 + * @arg @ref DDL_DMA_STREAM_5 + * @arg @ref DDL_DMA_STREAM_6 + * @arg @ref DDL_DMA_STREAM_7 + * @retval None + */ +__STATIC_INLINE void DDL_DMA_DisableFifoMode(DMA_TypeDef *DMAx, uint32_t Stream) +{ + CLEAR_BIT(((DMA_Stream_TypeDef *)((uint32_t)((uint32_t)DMAx + STREAM_OFFSET_TAB[Stream])))->FCTRL, DMA_FCTRLx_DMDEN); +} + +/** + * @brief Enable Fifo mode. + * @param DMAx DMAx Instance + * @param Stream This parameter can be one of the following values: + * @arg @ref DDL_DMA_STREAM_0 + * @arg @ref DDL_DMA_STREAM_1 + * @arg @ref DDL_DMA_STREAM_2 + * @arg @ref DDL_DMA_STREAM_3 + * @arg @ref DDL_DMA_STREAM_4 + * @arg @ref DDL_DMA_STREAM_5 + * @arg @ref DDL_DMA_STREAM_6 + * @arg @ref DDL_DMA_STREAM_7 + * @retval None + */ +__STATIC_INLINE void DDL_DMA_EnableFifoMode(DMA_TypeDef *DMAx, uint32_t Stream) +{ + SET_BIT(((DMA_Stream_TypeDef *)((uint32_t)((uint32_t)DMAx + STREAM_OFFSET_TAB[Stream])))->FCTRL, DMA_FCTRLx_DMDEN); +} + +/** + * @brief Select FIFO threshold. + * @param DMAx DMAx Instance + * @param Stream This parameter can be one of the following values: + * @arg @ref DDL_DMA_STREAM_0 + * @arg @ref DDL_DMA_STREAM_1 + * @arg @ref DDL_DMA_STREAM_2 + * @arg @ref DDL_DMA_STREAM_3 + * @arg @ref DDL_DMA_STREAM_4 + * @arg @ref DDL_DMA_STREAM_5 + * @arg @ref DDL_DMA_STREAM_6 + * @arg @ref DDL_DMA_STREAM_7 + * @param Threshold This parameter can be one of the following values: + * @arg @ref DDL_DMA_FIFOTHRESHOLD_1_4 + * @arg @ref DDL_DMA_FIFOTHRESHOLD_1_2 + * @arg @ref DDL_DMA_FIFOTHRESHOLD_3_4 + * @arg @ref DDL_DMA_FIFOTHRESHOLD_FULL + * @retval None + */ +__STATIC_INLINE void DDL_DMA_SetFIFOThreshold(DMA_TypeDef *DMAx, uint32_t Stream, uint32_t Threshold) +{ + MODIFY_REG(((DMA_Stream_TypeDef*)((uint32_t)((uint32_t)DMAx + STREAM_OFFSET_TAB[Stream])))->FCTRL, DMA_FCTRLx_FTHSEL, Threshold); +} + +/** + * @brief Get FIFO threshold. + * @param DMAx DMAx Instance + * @param Stream This parameter can be one of the following values: + * @arg @ref DDL_DMA_STREAM_0 + * @arg @ref DDL_DMA_STREAM_1 + * @arg @ref DDL_DMA_STREAM_2 + * @arg @ref DDL_DMA_STREAM_3 + * @arg @ref DDL_DMA_STREAM_4 + * @arg @ref DDL_DMA_STREAM_5 + * @arg @ref DDL_DMA_STREAM_6 + * @arg @ref DDL_DMA_STREAM_7 + * @retval Returned value can be one of the following values: + * @arg @ref DDL_DMA_FIFOTHRESHOLD_1_4 + * @arg @ref DDL_DMA_FIFOTHRESHOLD_1_2 + * @arg @ref DDL_DMA_FIFOTHRESHOLD_3_4 + * @arg @ref DDL_DMA_FIFOTHRESHOLD_FULL + */ +__STATIC_INLINE uint32_t DDL_DMA_GetFIFOThreshold(DMA_TypeDef *DMAx, uint32_t Stream) +{ + return (READ_BIT(((DMA_Stream_TypeDef*)((uint32_t)((uint32_t)DMAx + STREAM_OFFSET_TAB[Stream])))->FCTRL, DMA_FCTRLx_FTHSEL)); +} + +/** + * @brief Configure the FIFO . + * @param DMAx DMAx Instance + * @param Stream This parameter can be one of the following values: + * @arg @ref DDL_DMA_STREAM_0 + * @arg @ref DDL_DMA_STREAM_1 + * @arg @ref DDL_DMA_STREAM_2 + * @arg @ref DDL_DMA_STREAM_3 + * @arg @ref DDL_DMA_STREAM_4 + * @arg @ref DDL_DMA_STREAM_5 + * @arg @ref DDL_DMA_STREAM_6 + * @arg @ref DDL_DMA_STREAM_7 + * @param FifoMode This parameter can be one of the following values: + * @arg @ref DDL_DMA_FIFOMODE_ENABLE + * @arg @ref DDL_DMA_FIFOMODE_DISABLE + * @param FifoThreshold This parameter can be one of the following values: + * @arg @ref DDL_DMA_FIFOTHRESHOLD_1_4 + * @arg @ref DDL_DMA_FIFOTHRESHOLD_1_2 + * @arg @ref DDL_DMA_FIFOTHRESHOLD_3_4 + * @arg @ref DDL_DMA_FIFOTHRESHOLD_FULL + * @retval None + */ +__STATIC_INLINE void DDL_DMA_ConfigFifo(DMA_TypeDef *DMAx, uint32_t Stream, uint32_t FifoMode, uint32_t FifoThreshold) +{ + MODIFY_REG(((DMA_Stream_TypeDef*)((uint32_t)((uint32_t)DMAx + STREAM_OFFSET_TAB[Stream])))->FCTRL, DMA_FCTRLx_FTHSEL|DMA_FCTRLx_DMDEN, FifoMode|FifoThreshold); +} + +/** + * @brief Configure the Source and Destination addresses. + * @note This API must not be called when the DMA stream is enabled. + * @param DMAx DMAx Instance + * @param Stream This parameter can be one of the following values: + * @arg @ref DDL_DMA_STREAM_0 + * @arg @ref DDL_DMA_STREAM_1 + * @arg @ref DDL_DMA_STREAM_2 + * @arg @ref DDL_DMA_STREAM_3 + * @arg @ref DDL_DMA_STREAM_4 + * @arg @ref DDL_DMA_STREAM_5 + * @arg @ref DDL_DMA_STREAM_6 + * @arg @ref DDL_DMA_STREAM_7 + * @param SrcAddress Between 0 to 0xFFFFFFFF + * @param DstAddress Between 0 to 0xFFFFFFFF + * @param Direction This parameter can be one of the following values: + * @arg @ref DDL_DMA_DIRECTION_PERIPH_TO_MEMORY + * @arg @ref DDL_DMA_DIRECTION_MEMORY_TO_PERIPH + * @arg @ref DDL_DMA_DIRECTION_MEMORY_TO_MEMORY + * @retval None + */ +__STATIC_INLINE void DDL_DMA_ConfigAddresses(DMA_TypeDef* DMAx, uint32_t Stream, uint32_t SrcAddress, uint32_t DstAddress, uint32_t Direction) +{ + /* Direction Memory to Periph */ + if (Direction == DDL_DMA_DIRECTION_MEMORY_TO_PERIPH) + { + WRITE_REG(((DMA_Stream_TypeDef*)((uint32_t)((uint32_t)DMAx + STREAM_OFFSET_TAB[Stream])))->M0ADDR, SrcAddress); + WRITE_REG(((DMA_Stream_TypeDef*)((uint32_t)((uint32_t)DMAx + STREAM_OFFSET_TAB[Stream])))->PADDR, DstAddress); + } + /* Direction Periph to Memory and Memory to Memory */ + else + { + WRITE_REG(((DMA_Stream_TypeDef*)((uint32_t)((uint32_t)DMAx + STREAM_OFFSET_TAB[Stream])))->PADDR, SrcAddress); + WRITE_REG(((DMA_Stream_TypeDef*)((uint32_t)((uint32_t)DMAx + STREAM_OFFSET_TAB[Stream])))->M0ADDR, DstAddress); + } +} + +/** + * @brief Set the Memory address. + * @note Interface used for direction DDL_DMA_DIRECTION_PERIPH_TO_MEMORY or DDL_DMA_DIRECTION_MEMORY_TO_PERIPH only. + * @note This API must not be called when the DMA channel is enabled. + * @param DMAx DMAx Instance + * @param Stream This parameter can be one of the following values: + * @arg @ref DDL_DMA_STREAM_0 + * @arg @ref DDL_DMA_STREAM_1 + * @arg @ref DDL_DMA_STREAM_2 + * @arg @ref DDL_DMA_STREAM_3 + * @arg @ref DDL_DMA_STREAM_4 + * @arg @ref DDL_DMA_STREAM_5 + * @arg @ref DDL_DMA_STREAM_6 + * @arg @ref DDL_DMA_STREAM_7 + * @param MemoryAddress Between 0 to 0xFFFFFFFF + * @retval None + */ +__STATIC_INLINE void DDL_DMA_SetMemoryAddress(DMA_TypeDef* DMAx, uint32_t Stream, uint32_t MemoryAddress) +{ + WRITE_REG(((DMA_Stream_TypeDef*)((uint32_t)((uint32_t)DMAx + STREAM_OFFSET_TAB[Stream])))->M0ADDR, MemoryAddress); +} + +/** + * @brief Set the Peripheral address. + * @note Interface used for direction DDL_DMA_DIRECTION_PERIPH_TO_MEMORY or DDL_DMA_DIRECTION_MEMORY_TO_PERIPH only. + * @note This API must not be called when the DMA channel is enabled. + * @param DMAx DMAx Instance + * @param Stream This parameter can be one of the following values: + * @arg @ref DDL_DMA_STREAM_0 + * @arg @ref DDL_DMA_STREAM_1 + * @arg @ref DDL_DMA_STREAM_2 + * @arg @ref DDL_DMA_STREAM_3 + * @arg @ref DDL_DMA_STREAM_4 + * @arg @ref DDL_DMA_STREAM_5 + * @arg @ref DDL_DMA_STREAM_6 + * @arg @ref DDL_DMA_STREAM_7 + * @param PeriphAddress Between 0 to 0xFFFFFFFF + * @retval None + */ +__STATIC_INLINE void DDL_DMA_SetPeriphAddress(DMA_TypeDef* DMAx, uint32_t Stream, uint32_t PeriphAddress) +{ + WRITE_REG(((DMA_Stream_TypeDef*)((uint32_t)((uint32_t)DMAx + STREAM_OFFSET_TAB[Stream])))->PADDR, PeriphAddress); +} + +/** + * @brief Get the Memory address. + * @note Interface used for direction DDL_DMA_DIRECTION_PERIPH_TO_MEMORY or DDL_DMA_DIRECTION_MEMORY_TO_PERIPH only. + * @param DMAx DMAx Instance + * @param Stream This parameter can be one of the following values: + * @arg @ref DDL_DMA_STREAM_0 + * @arg @ref DDL_DMA_STREAM_1 + * @arg @ref DDL_DMA_STREAM_2 + * @arg @ref DDL_DMA_STREAM_3 + * @arg @ref DDL_DMA_STREAM_4 + * @arg @ref DDL_DMA_STREAM_5 + * @arg @ref DDL_DMA_STREAM_6 + * @arg @ref DDL_DMA_STREAM_7 + * @retval Between 0 to 0xFFFFFFFF + */ +__STATIC_INLINE uint32_t DDL_DMA_GetMemoryAddress(DMA_TypeDef* DMAx, uint32_t Stream) +{ + return (READ_REG(((DMA_Stream_TypeDef*)((uint32_t)((uint32_t)DMAx + STREAM_OFFSET_TAB[Stream])))->M0ADDR)); +} + +/** + * @brief Get the Peripheral address. + * @note Interface used for direction DDL_DMA_DIRECTION_PERIPH_TO_MEMORY or DDL_DMA_DIRECTION_MEMORY_TO_PERIPH only. + * @param DMAx DMAx Instance + * @param Stream This parameter can be one of the following values: + * @arg @ref DDL_DMA_STREAM_0 + * @arg @ref DDL_DMA_STREAM_1 + * @arg @ref DDL_DMA_STREAM_2 + * @arg @ref DDL_DMA_STREAM_3 + * @arg @ref DDL_DMA_STREAM_4 + * @arg @ref DDL_DMA_STREAM_5 + * @arg @ref DDL_DMA_STREAM_6 + * @arg @ref DDL_DMA_STREAM_7 + * @retval Between 0 to 0xFFFFFFFF + */ +__STATIC_INLINE uint32_t DDL_DMA_GetPeriphAddress(DMA_TypeDef* DMAx, uint32_t Stream) +{ + return (READ_REG(((DMA_Stream_TypeDef *)((uint32_t)((uint32_t)DMAx + STREAM_OFFSET_TAB[Stream])))->PADDR)); +} + +/** + * @brief Set the Memory to Memory Source address. + * @note Interface used for direction DDL_DMA_DIRECTION_MEMORY_TO_MEMORY only. + * @note This API must not be called when the DMA channel is enabled. + * @param DMAx DMAx Instance + * @param Stream This parameter can be one of the following values: + * @arg @ref DDL_DMA_STREAM_0 + * @arg @ref DDL_DMA_STREAM_1 + * @arg @ref DDL_DMA_STREAM_2 + * @arg @ref DDL_DMA_STREAM_3 + * @arg @ref DDL_DMA_STREAM_4 + * @arg @ref DDL_DMA_STREAM_5 + * @arg @ref DDL_DMA_STREAM_6 + * @arg @ref DDL_DMA_STREAM_7 + * @param MemoryAddress Between 0 to 0xFFFFFFFF + * @retval None + */ +__STATIC_INLINE void DDL_DMA_SetM2MSrcAddress(DMA_TypeDef* DMAx, uint32_t Stream, uint32_t MemoryAddress) +{ + WRITE_REG(((DMA_Stream_TypeDef*)((uint32_t)((uint32_t)DMAx + STREAM_OFFSET_TAB[Stream])))->PADDR, MemoryAddress); +} + +/** + * @brief Set the Memory to Memory Destination address. + * @note Interface used for direction DDL_DMA_DIRECTION_MEMORY_TO_MEMORY only. + * @note This API must not be called when the DMA channel is enabled. + * @param DMAx DMAx Instance + * @param Stream This parameter can be one of the following values: + * @arg @ref DDL_DMA_STREAM_0 + * @arg @ref DDL_DMA_STREAM_1 + * @arg @ref DDL_DMA_STREAM_2 + * @arg @ref DDL_DMA_STREAM_3 + * @arg @ref DDL_DMA_STREAM_4 + * @arg @ref DDL_DMA_STREAM_5 + * @arg @ref DDL_DMA_STREAM_6 + * @arg @ref DDL_DMA_STREAM_7 + * @param MemoryAddress Between 0 to 0xFFFFFFFF + * @retval None + */ +__STATIC_INLINE void DDL_DMA_SetM2MDstAddress(DMA_TypeDef* DMAx, uint32_t Stream, uint32_t MemoryAddress) + { + WRITE_REG(((DMA_Stream_TypeDef*)((uint32_t)((uint32_t)DMAx + STREAM_OFFSET_TAB[Stream])))->M0ADDR, MemoryAddress); + } + +/** + * @brief Get the Memory to Memory Source address. + * @note Interface used for direction DDL_DMA_DIRECTION_MEMORY_TO_MEMORY only. + * @param DMAx DMAx Instance + * @param Stream This parameter can be one of the following values: + * @arg @ref DDL_DMA_STREAM_0 + * @arg @ref DDL_DMA_STREAM_1 + * @arg @ref DDL_DMA_STREAM_2 + * @arg @ref DDL_DMA_STREAM_3 + * @arg @ref DDL_DMA_STREAM_4 + * @arg @ref DDL_DMA_STREAM_5 + * @arg @ref DDL_DMA_STREAM_6 + * @arg @ref DDL_DMA_STREAM_7 + * @retval Between 0 to 0xFFFFFFFF + */ +__STATIC_INLINE uint32_t DDL_DMA_GetM2MSrcAddress(DMA_TypeDef* DMAx, uint32_t Stream) + { + return (READ_REG(((DMA_Stream_TypeDef *)((uint32_t)((uint32_t)DMAx + STREAM_OFFSET_TAB[Stream])))->PADDR)); + } + +/** + * @brief Get the Memory to Memory Destination address. + * @note Interface used for direction DDL_DMA_DIRECTION_MEMORY_TO_MEMORY only. + * @param DMAx DMAx Instance + * @param Stream This parameter can be one of the following values: + * @arg @ref DDL_DMA_STREAM_0 + * @arg @ref DDL_DMA_STREAM_1 + * @arg @ref DDL_DMA_STREAM_2 + * @arg @ref DDL_DMA_STREAM_3 + * @arg @ref DDL_DMA_STREAM_4 + * @arg @ref DDL_DMA_STREAM_5 + * @arg @ref DDL_DMA_STREAM_6 + * @arg @ref DDL_DMA_STREAM_7 + * @retval Between 0 to 0xFFFFFFFF + */ +__STATIC_INLINE uint32_t DDL_DMA_GetM2MDstAddress(DMA_TypeDef* DMAx, uint32_t Stream) +{ + return (READ_REG(((DMA_Stream_TypeDef*)((uint32_t)((uint32_t)DMAx + STREAM_OFFSET_TAB[Stream])))->M0ADDR)); +} + +/** + * @brief Set Memory 1 address (used in case of Double buffer mode). + * @param DMAx DMAx Instance + * @param Stream This parameter can be one of the following values: + * @arg @ref DDL_DMA_STREAM_0 + * @arg @ref DDL_DMA_STREAM_1 + * @arg @ref DDL_DMA_STREAM_2 + * @arg @ref DDL_DMA_STREAM_3 + * @arg @ref DDL_DMA_STREAM_4 + * @arg @ref DDL_DMA_STREAM_5 + * @arg @ref DDL_DMA_STREAM_6 + * @arg @ref DDL_DMA_STREAM_7 + * @param Address Between 0 to 0xFFFFFFFF + * @retval None + */ +__STATIC_INLINE void DDL_DMA_SetMemory1Address(DMA_TypeDef *DMAx, uint32_t Stream, uint32_t Address) +{ + MODIFY_REG(((DMA_Stream_TypeDef*)((uint32_t)((uint32_t)DMAx + STREAM_OFFSET_TAB[Stream])))->M1ADDR, DMA_M1ADDRx_M1ADDR, Address); +} + +/** + * @brief Get Memory 1 address (used in case of Double buffer mode). + * @param DMAx DMAx Instance + * @param Stream This parameter can be one of the following values: + * @arg @ref DDL_DMA_STREAM_0 + * @arg @ref DDL_DMA_STREAM_1 + * @arg @ref DDL_DMA_STREAM_2 + * @arg @ref DDL_DMA_STREAM_3 + * @arg @ref DDL_DMA_STREAM_4 + * @arg @ref DDL_DMA_STREAM_5 + * @arg @ref DDL_DMA_STREAM_6 + * @arg @ref DDL_DMA_STREAM_7 + * @retval Between 0 to 0xFFFFFFFF + */ +__STATIC_INLINE uint32_t DDL_DMA_GetMemory1Address(DMA_TypeDef *DMAx, uint32_t Stream) +{ + return (((DMA_Stream_TypeDef*)((uint32_t)((uint32_t)DMAx + STREAM_OFFSET_TAB[Stream])))->M1ADDR); +} + +/** + * @} + */ + +/** @defgroup DMA_DDL_EF_FLAG_Management FLAG_Management + * @{ + */ + +/** + * @brief Get Stream 0 half transfer flag. + * @param DMAx DMAx Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_DMA_IsActiveFlag_HT0(DMA_TypeDef *DMAx) +{ + return (READ_BIT(DMAx->LINTSTS ,DMA_LINTSTS_HTXIFLG0)==(DMA_LINTSTS_HTXIFLG0)); +} + +/** + * @brief Get Stream 1 half transfer flag. + * @param DMAx DMAx Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_DMA_IsActiveFlag_HT1(DMA_TypeDef *DMAx) +{ + return (READ_BIT(DMAx->LINTSTS ,DMA_LINTSTS_HTXIFLG1)==(DMA_LINTSTS_HTXIFLG1)); +} + +/** + * @brief Get Stream 2 half transfer flag. + * @param DMAx DMAx Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_DMA_IsActiveFlag_HT2(DMA_TypeDef *DMAx) +{ + return (READ_BIT(DMAx->LINTSTS ,DMA_LINTSTS_HTXIFLG2)==(DMA_LINTSTS_HTXIFLG2)); +} + +/** + * @brief Get Stream 3 half transfer flag. + * @param DMAx DMAx Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_DMA_IsActiveFlag_HT3(DMA_TypeDef *DMAx) +{ + return (READ_BIT(DMAx->LINTSTS ,DMA_LINTSTS_HTXIFLG3)==(DMA_LINTSTS_HTXIFLG3)); +} + +/** + * @brief Get Stream 4 half transfer flag. + * @param DMAx DMAx Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_DMA_IsActiveFlag_HT4(DMA_TypeDef *DMAx) +{ + return (READ_BIT(DMAx->HINTSTS ,DMA_HINTSTS_HTXIFLG4)==(DMA_HINTSTS_HTXIFLG4)); +} + +/** + * @brief Get Stream 5 half transfer flag. + * @param DMAx DMAx Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_DMA_IsActiveFlag_HT5(DMA_TypeDef *DMAx) +{ + return (READ_BIT(DMAx->HINTSTS ,DMA_HINTSTS_HTXIFLG5)==(DMA_HINTSTS_HTXIFLG5)); +} + +/** + * @brief Get Stream 6 half transfer flag. + * @param DMAx DMAx Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_DMA_IsActiveFlag_HT6(DMA_TypeDef *DMAx) +{ + return (READ_BIT(DMAx->HINTSTS ,DMA_HINTSTS_HTXIFLG6)==(DMA_HINTSTS_HTXIFLG6)); +} + +/** + * @brief Get Stream 7 half transfer flag. + * @param DMAx DMAx Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_DMA_IsActiveFlag_HT7(DMA_TypeDef *DMAx) +{ + return (READ_BIT(DMAx->HINTSTS ,DMA_HINTSTS_HTXIFLG7)==(DMA_HINTSTS_HTXIFLG7)); +} + +/** + * @brief Get Stream 0 transfer complete flag. + * @param DMAx DMAx Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_DMA_IsActiveFlag_TC0(DMA_TypeDef *DMAx) +{ + return (READ_BIT(DMAx->LINTSTS ,DMA_LINTSTS_TXCIFLG0)==(DMA_LINTSTS_TXCIFLG0)); +} + +/** + * @brief Get Stream 1 transfer complete flag. + * @param DMAx DMAx Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_DMA_IsActiveFlag_TC1(DMA_TypeDef *DMAx) +{ + return (READ_BIT(DMAx->LINTSTS ,DMA_LINTSTS_TXCIFLG1)==(DMA_LINTSTS_TXCIFLG1)); +} + +/** + * @brief Get Stream 2 transfer complete flag. + * @param DMAx DMAx Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_DMA_IsActiveFlag_TC2(DMA_TypeDef *DMAx) +{ + return (READ_BIT(DMAx->LINTSTS ,DMA_LINTSTS_TXCIFLG2)==(DMA_LINTSTS_TXCIFLG2)); +} + +/** + * @brief Get Stream 3 transfer complete flag. + * @param DMAx DMAx Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_DMA_IsActiveFlag_TC3(DMA_TypeDef *DMAx) +{ + return (READ_BIT(DMAx->LINTSTS ,DMA_LINTSTS_TXCIFLG3)==(DMA_LINTSTS_TXCIFLG3)); +} + +/** + * @brief Get Stream 4 transfer complete flag. + * @param DMAx DMAx Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_DMA_IsActiveFlag_TC4(DMA_TypeDef *DMAx) +{ + return (READ_BIT(DMAx->HINTSTS ,DMA_HINTSTS_TXCIFLG4)==(DMA_HINTSTS_TXCIFLG4)); +} + +/** + * @brief Get Stream 5 transfer complete flag. + * @param DMAx DMAx Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_DMA_IsActiveFlag_TC5(DMA_TypeDef *DMAx) +{ + return (READ_BIT(DMAx->HINTSTS ,DMA_HINTSTS_TXCIFLG5)==(DMA_HINTSTS_TXCIFLG5)); +} + +/** + * @brief Get Stream 6 transfer complete flag. + * @param DMAx DMAx Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_DMA_IsActiveFlag_TC6(DMA_TypeDef *DMAx) +{ + return (READ_BIT(DMAx->HINTSTS ,DMA_HINTSTS_TXCIFLG6)==(DMA_HINTSTS_TXCIFLG6)); +} + +/** + * @brief Get Stream 7 transfer complete flag. + * @param DMAx DMAx Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_DMA_IsActiveFlag_TC7(DMA_TypeDef *DMAx) +{ + return (READ_BIT(DMAx->HINTSTS ,DMA_HINTSTS_TXCIFLG7)==(DMA_HINTSTS_TXCIFLG7)); +} + +/** + * @brief Get Stream 0 transfer error flag. + * @param DMAx DMAx Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_DMA_IsActiveFlag_TE0(DMA_TypeDef *DMAx) +{ + return (READ_BIT(DMAx->LINTSTS ,DMA_LINTSTS_TXEIFLG0)==(DMA_LINTSTS_TXEIFLG0)); +} + +/** + * @brief Get Stream 1 transfer error flag. + * @param DMAx DMAx Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_DMA_IsActiveFlag_TE1(DMA_TypeDef *DMAx) +{ + return (READ_BIT(DMAx->LINTSTS ,DMA_LINTSTS_TXEIFLG1)==(DMA_LINTSTS_TXEIFLG1)); +} + +/** + * @brief Get Stream 2 transfer error flag. + * @param DMAx DMAx Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_DMA_IsActiveFlag_TE2(DMA_TypeDef *DMAx) +{ + return (READ_BIT(DMAx->LINTSTS ,DMA_LINTSTS_TXEIFLG2)==(DMA_LINTSTS_TXEIFLG2)); +} + +/** + * @brief Get Stream 3 transfer error flag. + * @param DMAx DMAx Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_DMA_IsActiveFlag_TE3(DMA_TypeDef *DMAx) +{ + return (READ_BIT(DMAx->LINTSTS ,DMA_LINTSTS_TXEIFLG3)==(DMA_LINTSTS_TXEIFLG3)); +} + +/** + * @brief Get Stream 4 transfer error flag. + * @param DMAx DMAx Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_DMA_IsActiveFlag_TE4(DMA_TypeDef *DMAx) +{ + return (READ_BIT(DMAx->HINTSTS ,DMA_HINTSTS_TXEIFLG4)==(DMA_HINTSTS_TXEIFLG4)); +} + +/** + * @brief Get Stream 5 transfer error flag. + * @param DMAx DMAx Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_DMA_IsActiveFlag_TE5(DMA_TypeDef *DMAx) +{ + return (READ_BIT(DMAx->HINTSTS ,DMA_HINTSTS_TXEIFLG5)==(DMA_HINTSTS_TXEIFLG5)); +} + +/** + * @brief Get Stream 6 transfer error flag. + * @param DMAx DMAx Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_DMA_IsActiveFlag_TE6(DMA_TypeDef *DMAx) +{ + return (READ_BIT(DMAx->HINTSTS ,DMA_HINTSTS_TXEIFLG6)==(DMA_HINTSTS_TXEIFLG6)); +} + +/** + * @brief Get Stream 7 transfer error flag. + * @param DMAx DMAx Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_DMA_IsActiveFlag_TE7(DMA_TypeDef *DMAx) +{ + return (READ_BIT(DMAx->HINTSTS ,DMA_HINTSTS_TXEIFLG7)==(DMA_HINTSTS_TXEIFLG7)); +} + +/** + * @brief Get Stream 0 direct mode error flag. + * @param DMAx DMAx Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_DMA_IsActiveFlag_DME0(DMA_TypeDef *DMAx) +{ + return (READ_BIT(DMAx->LINTSTS ,DMA_LINTSTS_DMEIFLG0)==(DMA_LINTSTS_DMEIFLG0)); +} + +/** + * @brief Get Stream 1 direct mode error flag. + * @param DMAx DMAx Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_DMA_IsActiveFlag_DME1(DMA_TypeDef *DMAx) +{ + return (READ_BIT(DMAx->LINTSTS ,DMA_LINTSTS_DMEIFLG1)==(DMA_LINTSTS_DMEIFLG1)); +} + +/** + * @brief Get Stream 2 direct mode error flag. + * @param DMAx DMAx Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_DMA_IsActiveFlag_DME2(DMA_TypeDef *DMAx) +{ + return (READ_BIT(DMAx->LINTSTS ,DMA_LINTSTS_DMEIFLG2)==(DMA_LINTSTS_DMEIFLG2)); +} + +/** + * @brief Get Stream 3 direct mode error flag. + * @param DMAx DMAx Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_DMA_IsActiveFlag_DME3(DMA_TypeDef *DMAx) +{ + return (READ_BIT(DMAx->LINTSTS ,DMA_LINTSTS_DMEIFLG3)==(DMA_LINTSTS_DMEIFLG3)); +} + +/** + * @brief Get Stream 4 direct mode error flag. + * @param DMAx DMAx Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_DMA_IsActiveFlag_DME4(DMA_TypeDef *DMAx) +{ + return (READ_BIT(DMAx->HINTSTS ,DMA_HINTSTS_DMEIFLG4)==(DMA_HINTSTS_DMEIFLG4)); +} + +/** + * @brief Get Stream 5 direct mode error flag. + * @param DMAx DMAx Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_DMA_IsActiveFlag_DME5(DMA_TypeDef *DMAx) +{ + return (READ_BIT(DMAx->HINTSTS ,DMA_HINTSTS_DMEIFLG5)==(DMA_HINTSTS_DMEIFLG5)); +} + +/** + * @brief Get Stream 6 direct mode error flag. + * @param DMAx DMAx Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_DMA_IsActiveFlag_DME6(DMA_TypeDef *DMAx) +{ + return (READ_BIT(DMAx->HINTSTS ,DMA_HINTSTS_DMEIFLG6)==(DMA_HINTSTS_DMEIFLG6)); +} + +/** + * @brief Get Stream 7 direct mode error flag. + * @param DMAx DMAx Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_DMA_IsActiveFlag_DME7(DMA_TypeDef *DMAx) +{ + return (READ_BIT(DMAx->HINTSTS ,DMA_HINTSTS_DMEIFLG7)==(DMA_HINTSTS_DMEIFLG7)); +} + +/** + * @brief Get Stream 0 FIFO error flag. + * @param DMAx DMAx Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_DMA_IsActiveFlag_FE0(DMA_TypeDef *DMAx) +{ + return (READ_BIT(DMAx->LINTSTS ,DMA_LINTSTS_FEIFLG0)==(DMA_LINTSTS_FEIFLG0)); +} + +/** + * @brief Get Stream 1 FIFO error flag. + * @param DMAx DMAx Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_DMA_IsActiveFlag_FE1(DMA_TypeDef *DMAx) +{ + return (READ_BIT(DMAx->LINTSTS ,DMA_LINTSTS_FEIFLG1)==(DMA_LINTSTS_FEIFLG1)); +} + +/** + * @brief Get Stream 2 FIFO error flag. + * @param DMAx DMAx Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_DMA_IsActiveFlag_FE2(DMA_TypeDef *DMAx) +{ + return (READ_BIT(DMAx->LINTSTS ,DMA_LINTSTS_FEIFLG2)==(DMA_LINTSTS_FEIFLG2)); +} + +/** + * @brief Get Stream 3 FIFO error flag. + * @param DMAx DMAx Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_DMA_IsActiveFlag_FE3(DMA_TypeDef *DMAx) +{ + return (READ_BIT(DMAx->LINTSTS ,DMA_LINTSTS_FEIFLG3)==(DMA_LINTSTS_FEIFLG3)); +} + +/** + * @brief Get Stream 4 FIFO error flag. + * @param DMAx DMAx Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_DMA_IsActiveFlag_FE4(DMA_TypeDef *DMAx) +{ + return (READ_BIT(DMAx->HINTSTS ,DMA_HINTSTS_FEIFLG4)==(DMA_HINTSTS_FEIFLG4)); +} + +/** + * @brief Get Stream 5 FIFO error flag. + * @param DMAx DMAx Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_DMA_IsActiveFlag_FE5(DMA_TypeDef *DMAx) +{ + return (READ_BIT(DMAx->HINTSTS ,DMA_HINTSTS_FEIFLG5)==(DMA_HINTSTS_FEIFLG5)); +} + +/** + * @brief Get Stream 6 FIFO error flag. + * @param DMAx DMAx Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_DMA_IsActiveFlag_FE6(DMA_TypeDef *DMAx) +{ + return (READ_BIT(DMAx->HINTSTS ,DMA_HINTSTS_FEIFLG6)==(DMA_HINTSTS_FEIFLG6)); +} + +/** + * @brief Get Stream 7 FIFO error flag. + * @param DMAx DMAx Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_DMA_IsActiveFlag_FE7(DMA_TypeDef *DMAx) +{ + return (READ_BIT(DMAx->HINTSTS ,DMA_HINTSTS_FEIFLG7)==(DMA_HINTSTS_FEIFLG7)); +} + +/** + * @brief Clear Stream 0 half transfer flag. + * @param DMAx DMAx Instance + * @retval None + */ +__STATIC_INLINE void DDL_DMA_ClearFlag_HT0(DMA_TypeDef *DMAx) +{ + WRITE_REG(DMAx->LIFCLR , DMA_LIFCLR_CHTXIFLG0); +} + +/** + * @brief Clear Stream 1 half transfer flag. + * @param DMAx DMAx Instance + * @retval None + */ +__STATIC_INLINE void DDL_DMA_ClearFlag_HT1(DMA_TypeDef *DMAx) +{ + WRITE_REG(DMAx->LIFCLR , DMA_LIFCLR_CHTXIFLG1); +} + +/** + * @brief Clear Stream 2 half transfer flag. + * @param DMAx DMAx Instance + * @retval None + */ +__STATIC_INLINE void DDL_DMA_ClearFlag_HT2(DMA_TypeDef *DMAx) +{ + WRITE_REG(DMAx->LIFCLR , DMA_LIFCLR_CHTXIFLG2); +} + +/** + * @brief Clear Stream 3 half transfer flag. + * @param DMAx DMAx Instance + * @retval None + */ +__STATIC_INLINE void DDL_DMA_ClearFlag_HT3(DMA_TypeDef *DMAx) +{ + WRITE_REG(DMAx->LIFCLR , DMA_LIFCLR_CHTXIFLG3); +} + +/** + * @brief Clear Stream 4 half transfer flag. + * @param DMAx DMAx Instance + * @retval None + */ +__STATIC_INLINE void DDL_DMA_ClearFlag_HT4(DMA_TypeDef *DMAx) +{ + WRITE_REG(DMAx->HIFCLR , DMA_HIFCLR_CHTXIFLG4); +} + +/** + * @brief Clear Stream 5 half transfer flag. + * @param DMAx DMAx Instance + * @retval None + */ +__STATIC_INLINE void DDL_DMA_ClearFlag_HT5(DMA_TypeDef *DMAx) +{ + WRITE_REG(DMAx->HIFCLR , DMA_HIFCLR_CHTXIFLG5); +} + +/** + * @brief Clear Stream 6 half transfer flag. + * @param DMAx DMAx Instance + * @retval None + */ +__STATIC_INLINE void DDL_DMA_ClearFlag_HT6(DMA_TypeDef *DMAx) +{ + WRITE_REG(DMAx->HIFCLR , DMA_HIFCLR_CHTXIFLG6); +} + +/** + * @brief Clear Stream 7 half transfer flag. + * @param DMAx DMAx Instance + * @retval None + */ +__STATIC_INLINE void DDL_DMA_ClearFlag_HT7(DMA_TypeDef *DMAx) +{ + WRITE_REG(DMAx->HIFCLR , DMA_HIFCLR_CHTXIFLG7); +} + +/** + * @brief Clear Stream 0 transfer complete flag. + * @param DMAx DMAx Instance + * @retval None + */ +__STATIC_INLINE void DDL_DMA_ClearFlag_TC0(DMA_TypeDef *DMAx) +{ + WRITE_REG(DMAx->LIFCLR , DMA_LIFCLR_CTXCIFLG0); +} + +/** + * @brief Clear Stream 1 transfer complete flag. + * @param DMAx DMAx Instance + * @retval None + */ +__STATIC_INLINE void DDL_DMA_ClearFlag_TC1(DMA_TypeDef *DMAx) +{ + WRITE_REG(DMAx->LIFCLR , DMA_LIFCLR_CTXCIFLG1); +} + +/** + * @brief Clear Stream 2 transfer complete flag. + * @param DMAx DMAx Instance + * @retval None + */ +__STATIC_INLINE void DDL_DMA_ClearFlag_TC2(DMA_TypeDef *DMAx) +{ + WRITE_REG(DMAx->LIFCLR , DMA_LIFCLR_CTXCIFLG2); +} + +/** + * @brief Clear Stream 3 transfer complete flag. + * @param DMAx DMAx Instance + * @retval None + */ +__STATIC_INLINE void DDL_DMA_ClearFlag_TC3(DMA_TypeDef *DMAx) +{ + WRITE_REG(DMAx->LIFCLR , DMA_LIFCLR_CTXCIFLG3); +} + +/** + * @brief Clear Stream 4 transfer complete flag. + * @param DMAx DMAx Instance + * @retval None + */ +__STATIC_INLINE void DDL_DMA_ClearFlag_TC4(DMA_TypeDef *DMAx) +{ + WRITE_REG(DMAx->HIFCLR , DMA_HIFCLR_CTXCIFLG4); +} + +/** + * @brief Clear Stream 5 transfer complete flag. + * @param DMAx DMAx Instance + * @retval None + */ +__STATIC_INLINE void DDL_DMA_ClearFlag_TC5(DMA_TypeDef *DMAx) +{ + WRITE_REG(DMAx->HIFCLR , DMA_HIFCLR_CTXCIFLG5); +} + +/** + * @brief Clear Stream 6 transfer complete flag. + * @param DMAx DMAx Instance + * @retval None + */ +__STATIC_INLINE void DDL_DMA_ClearFlag_TC6(DMA_TypeDef *DMAx) +{ + WRITE_REG(DMAx->HIFCLR , DMA_HIFCLR_CTXCIFLG6); +} + +/** + * @brief Clear Stream 7 transfer complete flag. + * @param DMAx DMAx Instance + * @retval None + */ +__STATIC_INLINE void DDL_DMA_ClearFlag_TC7(DMA_TypeDef *DMAx) +{ + WRITE_REG(DMAx->HIFCLR , DMA_HIFCLR_CTXCIFLG7); +} + +/** + * @brief Clear Stream 0 transfer error flag. + * @param DMAx DMAx Instance + * @retval None + */ +__STATIC_INLINE void DDL_DMA_ClearFlag_TE0(DMA_TypeDef *DMAx) +{ + WRITE_REG(DMAx->LIFCLR , DMA_LIFCLR_CTXEIFLG0); +} + +/** + * @brief Clear Stream 1 transfer error flag. + * @param DMAx DMAx Instance + * @retval None + */ +__STATIC_INLINE void DDL_DMA_ClearFlag_TE1(DMA_TypeDef *DMAx) +{ + WRITE_REG(DMAx->LIFCLR , DMA_LIFCLR_CTXEIFLG1); +} + +/** + * @brief Clear Stream 2 transfer error flag. + * @param DMAx DMAx Instance + * @retval None + */ +__STATIC_INLINE void DDL_DMA_ClearFlag_TE2(DMA_TypeDef *DMAx) +{ + WRITE_REG(DMAx->LIFCLR , DMA_LIFCLR_CTXEIFLG2); +} + +/** + * @brief Clear Stream 3 transfer error flag. + * @param DMAx DMAx Instance + * @retval None + */ +__STATIC_INLINE void DDL_DMA_ClearFlag_TE3(DMA_TypeDef *DMAx) +{ + WRITE_REG(DMAx->LIFCLR , DMA_LIFCLR_CTXEIFLG3); +} + +/** + * @brief Clear Stream 4 transfer error flag. + * @param DMAx DMAx Instance + * @retval None + */ +__STATIC_INLINE void DDL_DMA_ClearFlag_TE4(DMA_TypeDef *DMAx) +{ + WRITE_REG(DMAx->HIFCLR , DMA_HIFCLR_CTXEIFLG4); +} + +/** + * @brief Clear Stream 5 transfer error flag. + * @param DMAx DMAx Instance + * @retval None + */ +__STATIC_INLINE void DDL_DMA_ClearFlag_TE5(DMA_TypeDef *DMAx) +{ + WRITE_REG(DMAx->HIFCLR , DMA_HIFCLR_CTXEIFLG5); +} + +/** + * @brief Clear Stream 6 transfer error flag. + * @param DMAx DMAx Instance + * @retval None + */ +__STATIC_INLINE void DDL_DMA_ClearFlag_TE6(DMA_TypeDef *DMAx) +{ + WRITE_REG(DMAx->HIFCLR , DMA_HIFCLR_CTXEIFLG6); +} + +/** + * @brief Clear Stream 7 transfer error flag. + * @param DMAx DMAx Instance + * @retval None + */ +__STATIC_INLINE void DDL_DMA_ClearFlag_TE7(DMA_TypeDef *DMAx) +{ + WRITE_REG(DMAx->HIFCLR , DMA_HIFCLR_CTXEIFLG7); +} + +/** + * @brief Clear Stream 0 direct mode error flag. + * @param DMAx DMAx Instance + * @retval None + */ +__STATIC_INLINE void DDL_DMA_ClearFlag_DME0(DMA_TypeDef *DMAx) +{ + WRITE_REG(DMAx->LIFCLR , DMA_LIFCLR_CDMEIFLG0); +} + +/** + * @brief Clear Stream 1 direct mode error flag. + * @param DMAx DMAx Instance + * @retval None + */ +__STATIC_INLINE void DDL_DMA_ClearFlag_DME1(DMA_TypeDef *DMAx) +{ + WRITE_REG(DMAx->LIFCLR , DMA_LIFCLR_CDMEIFLG1); +} + +/** + * @brief Clear Stream 2 direct mode error flag. + * @param DMAx DMAx Instance + * @retval None + */ +__STATIC_INLINE void DDL_DMA_ClearFlag_DME2(DMA_TypeDef *DMAx) +{ + WRITE_REG(DMAx->LIFCLR , DMA_LIFCLR_CDMEIFLG2); +} + +/** + * @brief Clear Stream 3 direct mode error flag. + * @param DMAx DMAx Instance + * @retval None + */ +__STATIC_INLINE void DDL_DMA_ClearFlag_DME3(DMA_TypeDef *DMAx) +{ + WRITE_REG(DMAx->LIFCLR , DMA_LIFCLR_CDMEIFLG3); +} + +/** + * @brief Clear Stream 4 direct mode error flag. + * @param DMAx DMAx Instance + * @retval None + */ +__STATIC_INLINE void DDL_DMA_ClearFlag_DME4(DMA_TypeDef *DMAx) +{ + WRITE_REG(DMAx->HIFCLR , DMA_HIFCLR_CDMEIFLG4); +} + +/** + * @brief Clear Stream 5 direct mode error flag. + * @param DMAx DMAx Instance + * @retval None + */ +__STATIC_INLINE void DDL_DMA_ClearFlag_DME5(DMA_TypeDef *DMAx) +{ + WRITE_REG(DMAx->HIFCLR , DMA_HIFCLR_CDMEIFLG5); +} + +/** + * @brief Clear Stream 6 direct mode error flag. + * @param DMAx DMAx Instance + * @retval None + */ +__STATIC_INLINE void DDL_DMA_ClearFlag_DME6(DMA_TypeDef *DMAx) +{ + WRITE_REG(DMAx->HIFCLR , DMA_HIFCLR_CDMEIFLG6); +} + +/** + * @brief Clear Stream 7 direct mode error flag. + * @param DMAx DMAx Instance + * @retval None + */ +__STATIC_INLINE void DDL_DMA_ClearFlag_DME7(DMA_TypeDef *DMAx) +{ + WRITE_REG(DMAx->HIFCLR , DMA_HIFCLR_CDMEIFLG7); +} + +/** + * @brief Clear Stream 0 FIFO error flag. + * @param DMAx DMAx Instance + * @retval None + */ +__STATIC_INLINE void DDL_DMA_ClearFlag_FE0(DMA_TypeDef *DMAx) +{ + WRITE_REG(DMAx->LIFCLR , DMA_LIFCLR_CFEIFLG0); +} + +/** + * @brief Clear Stream 1 FIFO error flag. + * @param DMAx DMAx Instance + * @retval None + */ +__STATIC_INLINE void DDL_DMA_ClearFlag_FE1(DMA_TypeDef *DMAx) +{ + WRITE_REG(DMAx->LIFCLR , DMA_LIFCLR_CFEIFLG1); +} + +/** + * @brief Clear Stream 2 FIFO error flag. + * @param DMAx DMAx Instance + * @retval None + */ +__STATIC_INLINE void DDL_DMA_ClearFlag_FE2(DMA_TypeDef *DMAx) +{ + WRITE_REG(DMAx->LIFCLR , DMA_LIFCLR_CFEIFLG2); +} + +/** + * @brief Clear Stream 3 FIFO error flag. + * @param DMAx DMAx Instance + * @retval None + */ +__STATIC_INLINE void DDL_DMA_ClearFlag_FE3(DMA_TypeDef *DMAx) +{ + WRITE_REG(DMAx->LIFCLR , DMA_LIFCLR_CFEIFLG3); +} + +/** + * @brief Clear Stream 4 FIFO error flag. + * @param DMAx DMAx Instance + * @retval None + */ +__STATIC_INLINE void DDL_DMA_ClearFlag_FE4(DMA_TypeDef *DMAx) +{ + WRITE_REG(DMAx->HIFCLR , DMA_HIFCLR_CFEIFLG4); +} + +/** + * @brief Clear Stream 5 FIFO error flag. + * @param DMAx DMAx Instance + * @retval None + */ +__STATIC_INLINE void DDL_DMA_ClearFlag_FE5(DMA_TypeDef *DMAx) +{ + WRITE_REG(DMAx->HIFCLR , DMA_HIFCLR_CFEIFLG5); +} + +/** + * @brief Clear Stream 6 FIFO error flag. + * @param DMAx DMAx Instance + * @retval None + */ +__STATIC_INLINE void DDL_DMA_ClearFlag_FE6(DMA_TypeDef *DMAx) +{ + WRITE_REG(DMAx->HIFCLR , DMA_HIFCLR_CFEIFLG6); +} + +/** + * @brief Clear Stream 7 FIFO error flag. + * @param DMAx DMAx Instance + * @retval None + */ +__STATIC_INLINE void DDL_DMA_ClearFlag_FE7(DMA_TypeDef *DMAx) +{ + WRITE_REG(DMAx->HIFCLR , DMA_HIFCLR_CFEIFLG7); +} + +/** + * @} + */ + +/** @defgroup DMA_DDL_EF_IT_Management IT_Management + * @{ + */ + +/** + * @brief Enable Half transfer interrupt. + * @param DMAx DMAx Instance + * @param Stream This parameter can be one of the following values: + * @arg @ref DDL_DMA_STREAM_0 + * @arg @ref DDL_DMA_STREAM_1 + * @arg @ref DDL_DMA_STREAM_2 + * @arg @ref DDL_DMA_STREAM_3 + * @arg @ref DDL_DMA_STREAM_4 + * @arg @ref DDL_DMA_STREAM_5 + * @arg @ref DDL_DMA_STREAM_6 + * @arg @ref DDL_DMA_STREAM_7 + * @retval None + */ +__STATIC_INLINE void DDL_DMA_EnableIT_HT(DMA_TypeDef *DMAx, uint32_t Stream) +{ + SET_BIT(((DMA_Stream_TypeDef *)((uint32_t)((uint32_t)DMAx + STREAM_OFFSET_TAB[Stream])))->SCFG, DMA_SCFGx_HTXIEN); +} + +/** + * @brief Enable Transfer error interrupt. + * @param DMAx DMAx Instance + * @param Stream This parameter can be one of the following values: + * @arg @ref DDL_DMA_STREAM_0 + * @arg @ref DDL_DMA_STREAM_1 + * @arg @ref DDL_DMA_STREAM_2 + * @arg @ref DDL_DMA_STREAM_3 + * @arg @ref DDL_DMA_STREAM_4 + * @arg @ref DDL_DMA_STREAM_5 + * @arg @ref DDL_DMA_STREAM_6 + * @arg @ref DDL_DMA_STREAM_7 + * @retval None + */ +__STATIC_INLINE void DDL_DMA_EnableIT_TE(DMA_TypeDef *DMAx, uint32_t Stream) +{ + SET_BIT(((DMA_Stream_TypeDef *)((uint32_t)((uint32_t)DMAx + STREAM_OFFSET_TAB[Stream])))->SCFG, DMA_SCFGx_TXEIEN); +} + +/** + * @brief Enable Transfer complete interrupt. + * @param DMAx DMAx Instance + * @param Stream This parameter can be one of the following values: + * @arg @ref DDL_DMA_STREAM_0 + * @arg @ref DDL_DMA_STREAM_1 + * @arg @ref DDL_DMA_STREAM_2 + * @arg @ref DDL_DMA_STREAM_3 + * @arg @ref DDL_DMA_STREAM_4 + * @arg @ref DDL_DMA_STREAM_5 + * @arg @ref DDL_DMA_STREAM_6 + * @arg @ref DDL_DMA_STREAM_7 + * @retval None + */ +__STATIC_INLINE void DDL_DMA_EnableIT_TC(DMA_TypeDef *DMAx, uint32_t Stream) +{ + SET_BIT(((DMA_Stream_TypeDef *)((uint32_t)((uint32_t)DMAx + STREAM_OFFSET_TAB[Stream])))->SCFG, DMA_SCFGx_TXCIEN); +} + +/** + * @brief Enable Direct mode error interrupt. + * @param DMAx DMAx Instance + * @param Stream This parameter can be one of the following values: + * @arg @ref DDL_DMA_STREAM_0 + * @arg @ref DDL_DMA_STREAM_1 + * @arg @ref DDL_DMA_STREAM_2 + * @arg @ref DDL_DMA_STREAM_3 + * @arg @ref DDL_DMA_STREAM_4 + * @arg @ref DDL_DMA_STREAM_5 + * @arg @ref DDL_DMA_STREAM_6 + * @arg @ref DDL_DMA_STREAM_7 + * @retval None + */ +__STATIC_INLINE void DDL_DMA_EnableIT_DME(DMA_TypeDef *DMAx, uint32_t Stream) +{ + SET_BIT(((DMA_Stream_TypeDef *)((uint32_t)((uint32_t)DMAx + STREAM_OFFSET_TAB[Stream])))->SCFG, DMA_SCFGx_DMEIEN); +} + +/** + * @brief Enable FIFO error interrupt. + * @param DMAx DMAx Instance + * @param Stream This parameter can be one of the following values: + * @arg @ref DDL_DMA_STREAM_0 + * @arg @ref DDL_DMA_STREAM_1 + * @arg @ref DDL_DMA_STREAM_2 + * @arg @ref DDL_DMA_STREAM_3 + * @arg @ref DDL_DMA_STREAM_4 + * @arg @ref DDL_DMA_STREAM_5 + * @arg @ref DDL_DMA_STREAM_6 + * @arg @ref DDL_DMA_STREAM_7 + * @retval None + */ +__STATIC_INLINE void DDL_DMA_EnableIT_FE(DMA_TypeDef *DMAx, uint32_t Stream) +{ + SET_BIT(((DMA_Stream_TypeDef *)((uint32_t)((uint32_t)DMAx + STREAM_OFFSET_TAB[Stream])))->FCTRL, DMA_FCTRLx_FEIEN); +} + +/** + * @brief Disable Half transfer interrupt. + * @param DMAx DMAx Instance + * @param Stream This parameter can be one of the following values: + * @arg @ref DDL_DMA_STREAM_0 + * @arg @ref DDL_DMA_STREAM_1 + * @arg @ref DDL_DMA_STREAM_2 + * @arg @ref DDL_DMA_STREAM_3 + * @arg @ref DDL_DMA_STREAM_4 + * @arg @ref DDL_DMA_STREAM_5 + * @arg @ref DDL_DMA_STREAM_6 + * @arg @ref DDL_DMA_STREAM_7 + * @retval None + */ +__STATIC_INLINE void DDL_DMA_DisableIT_HT(DMA_TypeDef *DMAx, uint32_t Stream) +{ + CLEAR_BIT(((DMA_Stream_TypeDef *)((uint32_t)((uint32_t)DMAx + STREAM_OFFSET_TAB[Stream])))->SCFG, DMA_SCFGx_HTXIEN); +} + +/** + * @brief Disable Transfer error interrupt. + * @param DMAx DMAx Instance + * @param Stream This parameter can be one of the following values: + * @arg @ref DDL_DMA_STREAM_0 + * @arg @ref DDL_DMA_STREAM_1 + * @arg @ref DDL_DMA_STREAM_2 + * @arg @ref DDL_DMA_STREAM_3 + * @arg @ref DDL_DMA_STREAM_4 + * @arg @ref DDL_DMA_STREAM_5 + * @arg @ref DDL_DMA_STREAM_6 + * @arg @ref DDL_DMA_STREAM_7 + * @retval None + */ +__STATIC_INLINE void DDL_DMA_DisableIT_TE(DMA_TypeDef *DMAx, uint32_t Stream) +{ + CLEAR_BIT(((DMA_Stream_TypeDef *)((uint32_t)((uint32_t)DMAx + STREAM_OFFSET_TAB[Stream])))->SCFG, DMA_SCFGx_TXEIEN); +} + +/** + * @brief Disable Transfer complete interrupt. + * @param DMAx DMAx Instance + * @param Stream This parameter can be one of the following values: + * @arg @ref DDL_DMA_STREAM_0 + * @arg @ref DDL_DMA_STREAM_1 + * @arg @ref DDL_DMA_STREAM_2 + * @arg @ref DDL_DMA_STREAM_3 + * @arg @ref DDL_DMA_STREAM_4 + * @arg @ref DDL_DMA_STREAM_5 + * @arg @ref DDL_DMA_STREAM_6 + * @arg @ref DDL_DMA_STREAM_7 + * @retval None + */ +__STATIC_INLINE void DDL_DMA_DisableIT_TC(DMA_TypeDef *DMAx, uint32_t Stream) +{ + CLEAR_BIT(((DMA_Stream_TypeDef *)((uint32_t)((uint32_t)DMAx + STREAM_OFFSET_TAB[Stream])))->SCFG, DMA_SCFGx_TXCIEN); +} + +/** + * @brief Disable Direct mode error interrupt. + * @param DMAx DMAx Instance + * @param Stream This parameter can be one of the following values: + * @arg @ref DDL_DMA_STREAM_0 + * @arg @ref DDL_DMA_STREAM_1 + * @arg @ref DDL_DMA_STREAM_2 + * @arg @ref DDL_DMA_STREAM_3 + * @arg @ref DDL_DMA_STREAM_4 + * @arg @ref DDL_DMA_STREAM_5 + * @arg @ref DDL_DMA_STREAM_6 + * @arg @ref DDL_DMA_STREAM_7 + * @retval None + */ +__STATIC_INLINE void DDL_DMA_DisableIT_DME(DMA_TypeDef *DMAx, uint32_t Stream) +{ + CLEAR_BIT(((DMA_Stream_TypeDef *)((uint32_t)((uint32_t)DMAx + STREAM_OFFSET_TAB[Stream])))->SCFG, DMA_SCFGx_DMEIEN); +} + +/** + * @brief Disable FIFO error interrupt. + * @param DMAx DMAx Instance + * @param Stream This parameter can be one of the following values: + * @arg @ref DDL_DMA_STREAM_0 + * @arg @ref DDL_DMA_STREAM_1 + * @arg @ref DDL_DMA_STREAM_2 + * @arg @ref DDL_DMA_STREAM_3 + * @arg @ref DDL_DMA_STREAM_4 + * @arg @ref DDL_DMA_STREAM_5 + * @arg @ref DDL_DMA_STREAM_6 + * @arg @ref DDL_DMA_STREAM_7 + * @retval None + */ +__STATIC_INLINE void DDL_DMA_DisableIT_FE(DMA_TypeDef *DMAx, uint32_t Stream) +{ + CLEAR_BIT(((DMA_Stream_TypeDef *)((uint32_t)((uint32_t)DMAx + STREAM_OFFSET_TAB[Stream])))->FCTRL, DMA_FCTRLx_FEIEN); +} + +/** + * @brief Check if Half transfer interrupt is enabled. + * @param DMAx DMAx Instance + * @param Stream This parameter can be one of the following values: + * @arg @ref DDL_DMA_STREAM_0 + * @arg @ref DDL_DMA_STREAM_1 + * @arg @ref DDL_DMA_STREAM_2 + * @arg @ref DDL_DMA_STREAM_3 + * @arg @ref DDL_DMA_STREAM_4 + * @arg @ref DDL_DMA_STREAM_5 + * @arg @ref DDL_DMA_STREAM_6 + * @arg @ref DDL_DMA_STREAM_7 + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_DMA_IsEnabledIT_HT(DMA_TypeDef *DMAx, uint32_t Stream) +{ + return (READ_BIT(((DMA_Stream_TypeDef*)((uint32_t)((uint32_t)DMAx + STREAM_OFFSET_TAB[Stream])))->SCFG, DMA_SCFGx_HTXIEN) == DMA_SCFGx_HTXIEN); +} + +/** + * @brief Check if Transfer error nterrup is enabled. + * @param DMAx DMAx Instance + * @param Stream This parameter can be one of the following values: + * @arg @ref DDL_DMA_STREAM_0 + * @arg @ref DDL_DMA_STREAM_1 + * @arg @ref DDL_DMA_STREAM_2 + * @arg @ref DDL_DMA_STREAM_3 + * @arg @ref DDL_DMA_STREAM_4 + * @arg @ref DDL_DMA_STREAM_5 + * @arg @ref DDL_DMA_STREAM_6 + * @arg @ref DDL_DMA_STREAM_7 + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_DMA_IsEnabledIT_TE(DMA_TypeDef *DMAx, uint32_t Stream) +{ + return (READ_BIT(((DMA_Stream_TypeDef*)((uint32_t)((uint32_t)DMAx + STREAM_OFFSET_TAB[Stream])))->SCFG, DMA_SCFGx_TXEIEN) == DMA_SCFGx_TXEIEN); +} + +/** + * @brief Check if Transfer complete interrupt is enabled. + * @param DMAx DMAx Instance + * @param Stream This parameter can be one of the following values: + * @arg @ref DDL_DMA_STREAM_0 + * @arg @ref DDL_DMA_STREAM_1 + * @arg @ref DDL_DMA_STREAM_2 + * @arg @ref DDL_DMA_STREAM_3 + * @arg @ref DDL_DMA_STREAM_4 + * @arg @ref DDL_DMA_STREAM_5 + * @arg @ref DDL_DMA_STREAM_6 + * @arg @ref DDL_DMA_STREAM_7 + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_DMA_IsEnabledIT_TC(DMA_TypeDef *DMAx, uint32_t Stream) +{ + return (READ_BIT(((DMA_Stream_TypeDef*)((uint32_t)((uint32_t)DMAx + STREAM_OFFSET_TAB[Stream])))->SCFG, DMA_SCFGx_TXCIEN) == DMA_SCFGx_TXCIEN); +} + +/** + * @brief Check if Direct mode error interrupt is enabled. + * @param DMAx DMAx Instance + * @param Stream This parameter can be one of the following values: + * @arg @ref DDL_DMA_STREAM_0 + * @arg @ref DDL_DMA_STREAM_1 + * @arg @ref DDL_DMA_STREAM_2 + * @arg @ref DDL_DMA_STREAM_3 + * @arg @ref DDL_DMA_STREAM_4 + * @arg @ref DDL_DMA_STREAM_5 + * @arg @ref DDL_DMA_STREAM_6 + * @arg @ref DDL_DMA_STREAM_7 + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_DMA_IsEnabledIT_DME(DMA_TypeDef *DMAx, uint32_t Stream) +{ + return (READ_BIT(((DMA_Stream_TypeDef*)((uint32_t)((uint32_t)DMAx + STREAM_OFFSET_TAB[Stream])))->SCFG, DMA_SCFGx_DMEIEN) == DMA_SCFGx_DMEIEN); +} + +/** + * @brief Check if FIFO error interrupt is enabled. + * @param DMAx DMAx Instance + * @param Stream This parameter can be one of the following values: + * @arg @ref DDL_DMA_STREAM_0 + * @arg @ref DDL_DMA_STREAM_1 + * @arg @ref DDL_DMA_STREAM_2 + * @arg @ref DDL_DMA_STREAM_3 + * @arg @ref DDL_DMA_STREAM_4 + * @arg @ref DDL_DMA_STREAM_5 + * @arg @ref DDL_DMA_STREAM_6 + * @arg @ref DDL_DMA_STREAM_7 + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_DMA_IsEnabledIT_FE(DMA_TypeDef *DMAx, uint32_t Stream) +{ + return (READ_BIT(((DMA_Stream_TypeDef*)((uint32_t)((uint32_t)DMAx + STREAM_OFFSET_TAB[Stream])))->FCTRL, DMA_FCTRLx_FEIEN) == DMA_FCTRLx_FEIEN); +} + +/** + * @} + */ + +#if defined(USE_FULL_DDL_DRIVER) +/** @defgroup DMA_DDL_EF_Init Initialization and de-initialization functions + * @{ + */ + +uint32_t DDL_DMA_Init(DMA_TypeDef *DMAx, uint32_t Stream, DDL_DMA_InitTypeDef *DMA_InitStruct); +uint32_t DDL_DMA_DeInit(DMA_TypeDef *DMAx, uint32_t Stream); +void DDL_DMA_StructInit(DDL_DMA_InitTypeDef *DMA_InitStruct); + +/** + * @} + */ +#endif /* USE_FULL_DDL_DRIVER */ + +/** + * @} + */ + +/** + * @} + */ + +#endif /* DMA1 || DMA2 */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* APM32F4xx_DDL_DMA_H */ + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_dmc.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_dmc.h new file mode 100644 index 0000000000..8cfd74aaf3 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_dmc.h @@ -0,0 +1,610 @@ +/** + * + * @file apm32f4xx_ddl_dmc.h + * @brief Header file of DMC DDL module. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef APM32F4xx_DDL_DMC_H +#define APM32F4xx_DDL_DMC_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal_def.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @addtogroup DMC_DDL + * @{ + */ + +/** @addtogroup DMC_DDL_Private_Macros + * @{ + */ + +#if defined(DMC) + +#define DMC_TIMEOUT_VALUE 100U + +#define IS_DMC_SDRAM_DEVICE(__INSTANCE__) ((__INSTANCE__) == DMC_SDRAM_DEVICE) + +#define IS_DMC_BANK_WIDTH(__WIDTH__) (((__WIDTH__) == DMC_SDRAM_BANK_WIDTH_BITS_NUM_1) || \ + ((__WIDTH__) == DMC_SDRAM_BANK_WIDTH_BITS_NUM_2)) + +#define IS_DMC_COLUMNBITS_NUMBER(__COLUMN__) (((__COLUMN__) == DMC_SDRAM_COLUMN_BITS_NUM_8) || \ + ((__COLUMN__) == DMC_SDRAM_COLUMN_BITS_NUM_9) || \ + ((__COLUMN__) == DMC_SDRAM_COLUMN_BITS_NUM_10) || \ + ((__COLUMN__) == DMC_SDRAM_COLUMN_BITS_NUM_11) || \ + ((__COLUMN__) == DMC_SDRAM_COLUMN_BITS_NUM_12) || \ + ((__COLUMN__) == DMC_SDRAM_COLUMN_BITS_NUM_13) || \ + ((__COLUMN__) == DMC_SDRAM_COLUMN_BITS_NUM_14) || \ + ((__COLUMN__) == DMC_SDRAM_COLUMN_BITS_NUM_15)) + +#define IS_DMC_ROWBITS_NUMBER(__ROW__) (((__ROW__) == DMC_SDRAM_ROW_BITS_NUM_11) || \ + ((__ROW__) == DMC_SDRAM_ROW_BITS_NUM_12) || \ + ((__ROW__) == DMC_SDRAM_ROW_BITS_NUM_13) || \ + ((__ROW__) == DMC_SDRAM_ROW_BITS_NUM_14) || \ + ((__ROW__) == DMC_SDRAM_ROW_BITS_NUM_15) || \ + ((__ROW__) == DMC_SDRAM_ROW_BITS_NUM_16)) +#define IS_DMC_MEMORY_WIDTH(__WIDTH__) (((__WIDTH__) == DMC_SDRAM_MEM_BUS_WIDTH_16)) + +#define IS_DMC_CLK_PHASE(__PHASE__) (((__PHASE__) == DMC_SDRAM_CLK_PHASE_NORMAL) || \ + ((__PHASE__) == DMC_SDRAM_CLK_PHASE_REVERSE)) + +#define IS_DMC_RD_DELAY(__STATUS__) (((__STATUS__) == DMC_SDRAM_RD_DELAY_ENABLE) || \ + ((__STATUS__) == DMC_SDRAM_RD_DELAY_DISABLE)) + +#define IS_DMC_RD_DELAY_CLK(__VALUE__) ((__VALUE__) <= 7U) + +#define IS_DMC_WRITE_PIPE(__STATUS__) (((__STATUS__) == DMC_SDRAM_WRITE_PIPE_ENABLE) || \ + ((__STATUS__) == DMC_SDRAM_WRITE_PIPE_DISABLE)) + +#define IS_DMC_ACCELERATE_MODE(__STATUS__) (((__STATUS__) == DMC_SDRAM_ACCELERATE_MODE_ENABLE) || \ + ((__STATUS__) == DMC_SDRAM_ACCELERATE_MODE_DISABLE)) + +#define IS_DMC_WRAP_BURST(__INC__) (((__INC__) == DMC_SDRAM_WRAP_BURST_INC4) || \ + ((__INC__) == DMC_SDRAM_WRAP_BURST_INC8)) + +#define IS_DMC_CAS_LATENCY(__LATENCY__) (((__LATENCY__) == DMC_SDRAM_CAS_LATENCY_1) || \ + ((__LATENCY__) == DMC_SDRAM_CAS_LATENCY_2) || \ + ((__LATENCY__) == DMC_SDRAM_CAS_LATENCY_3) || \ + ((__LATENCY__) == DMC_SDRAM_CAS_LATENCY_4) || \ + ((__LATENCY__) == DMC_SDRAM_CAS_LATENCY_5) || \ + ((__LATENCY__) == DMC_SDRAM_CAS_LATENCY_6) || \ + ((__LATENCY__) == DMC_SDRAM_CAS_LATENCY_7) || \ + ((__LATENCY__) == DMC_SDRAM_CAS_LATENCY_8)) + +#define IS_DMC_RAS_TIME(__TIME__) (((__TIME__) > 0U) && ((__TIME__) <= 16U)) +#define IS_DMC_RAS_TO_CAS_DELAY(__DELAY__) (((__DELAY__) > 0U) && ((__DELAY__) <= 8U)) +#define IS_DMC_PRECHARGE_PERIOD(__PERIOD__) (((__PERIOD__) > 0U) && ((__PERIOD__) <= 8U)) +#define IS_DMC_AUTO_REFRESH_TIME(__TIME__) (((__TIME__) > 0U) && ((__TIME__) <= 16U)) +#define IS_DMC_WRITE_RECOVERY_TIME(__TIME__) (((__TIME__) > 0U) && ((__TIME__) <= 4U)) +#define IS_DMC_XSR_TIME(__TIME__) ((__TIME__) <= 0x1FFU) +#define IS_DMC_ACTIVE_COMMAND_TIME(__TIME__) (((__TIME__) > 0U) && ((__TIME__) <= 16U)) +#define IS_DMC_REFRESH_PERIOD(__PERIOD__) ((__PERIOD__) <= 0xFFFFU) +#define IS_DMC_STABLE_TIME(__TIME__) ((__TIME__) <= 0xFFFFU) + +#define IS_DMC_POWER_DOWN_MODE(__MODE__) (((__MODE__) == DMC_SDRAM_POWER_DOWN_ENABLE) || \ + ((__MODE__) == DMC_SDRAM_POWER_DOWN_DISABLE)) + +#define IS_DMC_SELF_REFRESH_MODE(__MODE__) (((__MODE__) == DMC_SDRAM_SELF_REFRESH_ENABLE) || \ + ((__MODE__) == DMC_SDRAM_SELF_REFRESH_DISABLE)) + +#define IS_DMC_REFRESH_TYPE(__TYPE__) (((__TYPE__) == DMC_SDRAM_REFRESH_TYPE_ROW_ONE) || \ + ((__TYPE__) == DMC_SDRAM_REFRESH_TYPE_ROW_ALL)) + +#define IS_DMC_PRECHARGE_MODE(__MODE__) (((__MODE__) == DMC_SDRAM_PRECHARGE_MODE_IM) || \ + ((__MODE__) == DMC_SDRAM_PRECHARGE_MODE_DELAY)) + +#define IS_DMC_REG_INSERT_NUMBER(__NUMBER__) ((__NUMBER__) <= 0x7U) + +#define IS_DMC_OPEN_BANK_NUMBER(__NUMBER__) (((__NUMBER__) > 0U) && ((__NUMBER__) <= 16U)) + +#endif /* DMC */ + +/** + * @} + */ + +/* Exported typedef ----------------------------------------------------------*/ + +/** @defgroup DMC_DDL_Exported_typedef DMC Low Layer Exported Types + * @{ + */ + +#if defined(DMC) +#define DMC_SDRAM_TypeDef DMC_TypeDef +#endif /* DMC */ + +#if defined(DMC) +#define DMC_SDRAM_DEVICE DMC +#endif /* DMC */ + +#if defined(DMC) +/** + * @brief DMC SDRAM Configuration Structure definition + */ +typedef struct +{ + uint32_t BankWidth; /*!< Defines the number of bits of bank width. + This parameter can be a value of @ref DMC_SDRAM_Bank_Width_Bits_number. */ + + uint32_t ColumnBitsNumber; /*!< Defines the number of bits of column address. + This parameter can be a value of @ref DMC_SDRAM_Column_Bits_number. */ + + uint32_t RowBitsNumber; /*!< Defines the number of bits of column address. + This parameter can be a value of @ref DMC_SDRAM_Row_Bits_number. */ + + uint32_t MemoryDataWidth; /*!< Defines the memory device width. + This parameter can be a value of @ref DMC_SDRAM_Memory_Bus_Width. */ + + uint32_t ClockPhase; /*!< Defines the clock phase. + This parameter can be a value of @ref DMC_SDRAM_Clock_Phase. */ + + uint32_t RDDelay; /*!< Defines the RD delay enable status. + This parameter can be a value of @ref DMC_SDRAM_RD_Delay_Enable. */ + + uint32_t RDDelayClk; /*!< Defines the RD delay clock. + This parameter can be a value between Min_Data = 0 and Max_Data = 7 */ + + uint32_t WritePipe; /*!< Defines the Write pipe enable status. + This parameter can be a value of @ref DMC_SDRAM_Write_Pipe_Enable. */ + + uint32_t AccelerateMode; /*!< Defines the DMC accelerate mode. + This parameter can be a value of @ref DMC_SDRAM_Accelerate_Mode. */ + + uint32_t WRAPBurstType; /*!< Defines the DMC WRAP burst type. + This parameter can be a value of @ref DMC_SDRAM_WRAP_Burst_Type. */ + + uint32_t SelfRefreshMode; /*!< Defines the DMC Self refresh mode. + This parameter can be a value of @ref DMC_SDRAM_Self_Refresh_Mode. */ + + uint32_t PowerDownMode; /*!< Defines the DMC Power down mode. + This parameter can be a value of @ref DMC_SDRAM_Power_Down_Mode. */ + + uint32_t RefreshTypeEnterSelfRefresh; /*!< Defines the DMC refresh type before entering self-refresh mode. + This parameter can be a value of @ref DMC_SDRAM_Refresh_Type. */ + + uint32_t RefreshTypeExitSelfRefresh; /*!< Defines the DMC refresh type after exit self-refresh mode. + This parameter can be a value of @ref DMC_SDRAM_Refresh_Type. */ + + uint32_t RegisterInsertNumber; /*!< Defines the number of registers inserted in read data path. + This parameter can be a value between Min_Data = 0 and Max_Data = 7 */ + + uint32_t OpenBankNumber; /*!< Defines the number of open banks. + This parameter can be a value between Min_Data = 1 and Max_Data = 16 */ +} DMC_SDRAM_InitTypeDef; + +/** + * @brief DMC SDRAM Timing parameters structure definition + */ +typedef struct +{ + uint32_t CASLatency; /*!< Defines the SDRAM CAS latency in number of memory clock cycles. + This parameter can be a value of @ref DMC_SDRAM_CAS_Latency. */ + + uint32_t RASTime; /*!< Defines the minimum RAS time in number of memory clock cycles. + This parameter can be a value between Min_Data = 1 and Max_Data = 16 */ + + uint32_t RASToCASDelay; /*!< Defines the delay between RAS and CAS in number of memory clock cycles. + This parameter can be a value between Min_Data = 1 and Max_Data = 8 */ + + uint32_t PrechargeMode; /*!< Defines the SDRAM Precharge mode. + This parameter can be a value of @ref DMC_SDRAM_Precharge_Mode. */ + + uint32_t PrechargePeriod; /*!< Defines the period for precharge. + This parameter can be a value between Min_Data = 1 and Max_Data = 8 */ + + uint32_t AutoRefreshTime; /*!< Defines the Auto Refresh period in number of memory clock cycles. + This parameter can be a value between Min_Data = 1 and Max_Data = 16 */ + + uint32_t AutoRefreshNumber; /*!< Defines the Auto Refresh number. + This parameter can be a value between Min_Data = 1 and Max_Data = 16 */ + + uint32_t WriteRecoveryTime; /*!< Defines the Write recovery Time in number of memory clock cycles. + This parameter can be a value between Min_Data = 1 and Max_Data = 4 */ + + uint32_t XSRTime; /*!< Defines the delay between a Active Command and time of exit self refresh + in number of memory clock cycles. + This parameter can be a value between Min_Data = 0x000 and Max_Data = 0x1FF */ + + uint32_t ActiveCommandPeriod; /*!< Defines the period for active command. + This parameter can be a value between Min_Data = 1 and Max_Data = 16 */ + + uint32_t RefreshPeriod; /*!< Defines the period between two continuous refresh in number of memory clock + cycles. + This parameter can be a value between Min_Data = 0x0000 and Max_Data = 0xFFFF */ + + uint32_t StableTime; /*!< Defines the stable time in number of memory clock cycles. + This parameter can be a value between Min_Data = 0x0000 and Max_Data = 0xFFFF */ +} DMC_SDRAM_TimingTypeDef; + +#endif /* DMC */ +/** + * @} + */ + +/* Exported constants --------------------------------------------------------*/ +/** @addtogroup DMC_DDL_Exported_Constants DMC Low Layer Exported Constants + * @{ + */ + +#if defined(DMC) +/** @defgroup DMC_DDL_SDRAM_Controller DMC SDRAM Controller + * @{ + */ + +/** @defgroup DMC_SDRAM_Bank_Width_Bits_number DMC SDRAM Bank Width Bits number + * @{ + */ +#define DMC_SDRAM_BANK_WIDTH_BITS_NUM_1 (0x00UL << DMC_CFG_BAWCFG_Pos) +#define DMC_SDRAM_BANK_WIDTH_BITS_NUM_2 (0x01UL << DMC_CFG_BAWCFG_Pos) + + +/** @defgroup DMC_SDRAM_Row_Bits_number DMC SDRAM Row Bits number + * @{ + */ +#define DMC_SDRAM_ROW_BITS_NUM_11 (0x0AUL << DMC_CFG_RAWCFG_Pos) +#define DMC_SDRAM_ROW_BITS_NUM_12 (0x0BUL << DMC_CFG_RAWCFG_Pos) +#define DMC_SDRAM_ROW_BITS_NUM_13 (0x0CUL << DMC_CFG_RAWCFG_Pos) +#define DMC_SDRAM_ROW_BITS_NUM_14 (0x0DUL << DMC_CFG_RAWCFG_Pos) +#define DMC_SDRAM_ROW_BITS_NUM_15 (0x0EUL << DMC_CFG_RAWCFG_Pos) +#define DMC_SDRAM_ROW_BITS_NUM_16 (0x0FUL << DMC_CFG_RAWCFG_Pos) +/** + * @} + */ + +/** @defgroup DMC_SDRAM_Column_Bits_number DMC SDRAM Column Bits number + * @{ + */ +#define DMC_SDRAM_COLUMN_BITS_NUM_8 (0x07UL << DMC_CFG_CAWCFG_Pos) +#define DMC_SDRAM_COLUMN_BITS_NUM_9 (0x08UL << DMC_CFG_CAWCFG_Pos) +#define DMC_SDRAM_COLUMN_BITS_NUM_10 (0x09UL << DMC_CFG_CAWCFG_Pos) +#define DMC_SDRAM_COLUMN_BITS_NUM_11 (0x0AUL << DMC_CFG_CAWCFG_Pos) +#define DMC_SDRAM_COLUMN_BITS_NUM_12 (0x0BUL << DMC_CFG_CAWCFG_Pos) +#define DMC_SDRAM_COLUMN_BITS_NUM_13 (0x0CUL << DMC_CFG_CAWCFG_Pos) +#define DMC_SDRAM_COLUMN_BITS_NUM_14 (0x0DUL << DMC_CFG_CAWCFG_Pos) +#define DMC_SDRAM_COLUMN_BITS_NUM_15 (0x0EUL << DMC_CFG_CAWCFG_Pos) +/** + * @} + */ + +/** @defgroup DMC_SDRAM_Memory_Bus_Width DMC SDRAM Memory Bus Width + * @{ + */ +#define DMC_SDRAM_MEM_BUS_WIDTH_16 (0x00UL << DMC_CFG_DWCFG_Pos) +/** + * @} + */ + +/** @defgroup DMC_SDRAM_Clock_Phase DMC SDRAM Clock Phase + * @{ + */ +#define DMC_SDRAM_CLK_PHASE_NORMAL (0x00000000U) +#define DMC_SDRAM_CLK_PHASE_REVERSE (0x00000001U) +/** + * @} + */ + +/** @defgroup DMC_SDRAM_RD_Delay_Enable DMC SDRAM RD Delay Enable + * @{ + */ +#define DMC_SDRAM_RD_DELAY_ENABLE (0x00000000U) +#define DMC_SDRAM_RD_DELAY_DISABLE (0x00000002U) +/** + * @} + */ + +/** @defgroup DMC_SDRAM_Write_Pipe_Enable DMC SDRAM Write Pipe Enable + * @{ + */ +#define DMC_SDRAM_WRITE_PIPE_ENABLE (0x00000020U) +#define DMC_SDRAM_WRITE_PIPE_DISABLE (0x00000000U) +/** + * @} + */ + +/** @defgroup DMC_SDRAM_Accelerate_Mode DMC SDRAM Accelerate Mode + * @{ + */ +#define DMC_SDRAM_ACCELERATE_MODE_ENABLE (0x00000040U) +#define DMC_SDRAM_ACCELERATE_MODE_DISABLE (0x00000000U) +/** + * @} + */ + +/** @defgroup DMC_SDRAM_WRAP_Burst_Type DMC SDRAM WRAP Burst Type + * @{ + */ +#define DMC_SDRAM_WRAP_BURST_INC4 (0x00000000U) +#define DMC_SDRAM_WRAP_BURST_INC8 (0x00000080U) +/** + * @} + */ + +/** @defgroup DMC_SDRAM_CAS_Latency DMC SDRAM CAS Latency + * @{ + */ +#define DMC_SDRAM_CAS_LATENCY_1 (0x00000000U) +#define DMC_SDRAM_CAS_LATENCY_2 (0x00000001U) +#define DMC_SDRAM_CAS_LATENCY_3 (0x00000002U) +#define DMC_SDRAM_CAS_LATENCY_4 (0x00000003U) +#define DMC_SDRAM_CAS_LATENCY_5 (0x00000004U) +#define DMC_SDRAM_CAS_LATENCY_6 (0x00000005U) +#define DMC_SDRAM_CAS_LATENCY_7 (0x00000006U) +#define DMC_SDRAM_CAS_LATENCY_8 (0x00000007U) +/** + * @} + */ + +/** @defgroup DMC_SDRAM_Precharge_Mode DMC SDRAM Precharge Mode + * @{ + */ +#define DMC_SDRAM_PRECHARGE_MODE_IM (0x00000000U) +#define DMC_SDRAM_PRECHARGE_MODE_DELAY (0x00000008U) +/** + * @} + */ + +/** @defgroup DMC_SDRAM_Self_Refresh_Mode DMC SDRAM Self Refresh Mode + * @{ + */ +#define DMC_SDRAM_SELF_REFRESH_ENABLE (0x00000002U) +#define DMC_SDRAM_SELF_REFRESH_DISABLE (0x00000000U) +/** + * @} + */ + +/** @defgroup DMC_SDRAM_Power_Down_Mode DMC SDRAM Power Down Mode + * @{ + */ +#define DMC_SDRAM_POWER_DOWN_ENABLE (0x00000004U) +#define DMC_SDRAM_POWER_DOWN_DISABLE (0x00000000U) +/** + * @} + */ + +/** @defgroup DMC_SDRAM_Refresh_Type DMC SDRAM Refresh Type + * @{ + */ +#define DMC_SDRAM_REFRESH_TYPE_ROW_ONE (0x00000000U) +#define DMC_SDRAM_REFRESH_TYPE_ROW_ALL (0x00000001U) +/** + * @} + */ + +/** @defgroup DMC_SDRAM_Mode_Status DMC SDRAM Mode Status + * @{ + */ +#define DMC_SDRAM_NORMAL_MODE (0x00000000U) +#define DMC_SDRAM_SELF_REFRESH_MODE (0x00000001U) +#define DMC_SDRAM_POWER_DOWN_MODE (0x00000002U) +/** + * @} + */ + +/** + * @} + */ + +#endif /* DMC */ + +/** @defgroup DMC_DDL_Interrupt_definition DMC Low Layer Interrupt definition + * @{ + */ + +/** @defgroup DMC_Flag_definition DMC Flag definition + * @{ + */ +#define DMC_SDRAM_FLAG_SELF_REFRESH ((uint32_t)DMC_CTRL1_SRMFLG) + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +/* Private macro -------------------------------------------------------------*/ +/** @defgroup DMC_DDL_Private_Macros DMC_DDL Private Macros + * @{ + */ + +#if defined(DMC) + +/** @defgroup DMC_DDL_NOR_Macros DMC SDRAM Macros + * @brief macros to handle SDRAM device switch operations + * @{ + */ + +/** + * @brief Switch to the DMC Controller. + * @param __INSTANCE__ DMC_SDRAM Instance + * @retval None + */ +#define __DMC_SDRAM_ENABLE(__INSTANCE__) ((__INSTANCE__)->SW |= DMC_SW_MCSW) + +/** + * @brief Switch to the SMC Controller. + * @param __INSTANCE__ DMC_SDRAM Instance + * @retval None + */ +#define __DMC_SDRAM_DISABLE(__INSTANCE__) ((__INSTANCE__)->SW &= ~DMC_SW_MCSW) + +/** + * @} + */ + +/** @defgroup DMC_DDL_NOR_Macros DMC SDRAM Macros + * @brief macros to handle SDRAM device control operations + * @{ + */ + +/** + * @brief Update the SDRAM Mode Setup. + * @param __INSTANCE__ DMC_SDRAM Instance + * @retval None + */ +#define __DMC_SDRAM_UPDATE_MODE_SETUP(__INSTANCE__) ((__INSTANCE__)->CTRL1 |= DMC_CTRL1_MODESET) + +/** + * @brief Enable SDRAM self-refresh mode. + * @param __INSTANCE__ DMC_SDRAM Instance + * @retval None + */ +#define __DMC_SDRAM_SELF_REFRESH_MODE_ENABLE(__INSTANCE__) ((__INSTANCE__)->CTRL1 |= DMC_CTRL1_SRMEN) + +/** + * @brief Disable SDRAM self-refresh mode. + * @param __INSTANCE__ DMC_SDRAM Instance + * @retval None + */ +#define __DMC_SDRAM_SELF_REFRESH_MODE_DISABLE(__INSTANCE__) ((__INSTANCE__)->CTRL1 &= ~DMC_CTRL1_SRMEN) + +/** + * @brief Enable SDRAM power down mode. + * @param __INSTANCE__ DMC_SDRAM Instance + * @retval None + */ +#define __DMC_SDRAM_POWER_DOWN_MODE_ENABLE(__INSTANCE__) ((__INSTANCE__)->CTRL1 |= DMC_CTRL1_PDMEN) + +/** + * @brief Disable SDRAM power down mode. + * @param __INSTANCE__ DMC_SDRAM Instance + * @retval None + */ +#define __DMC_SDRAM_POWER_DOWN_MODE_DISABLE(__INSTANCE__) ((__INSTANCE__)->CTRL1 &= ~DMC_CTRL1_PDMEN) + +/** + * @} + */ + +/** @defgroup DMC_DDL_SDRAM_Interrupt DMC SDRAM Interrupt + * @brief macros to handle SDRAM interrupts + * @{ + */ + +/** + * @brief Get flag status of the SDRAM device. + * @param __INSTANCE__ DMC_SDRAM instance + * @param __FLAG__ DMC_SDRAM flag + * This parameter can be any combination of the following values: + * @arg DMC_SDRAM_FLAG_SELF_REFRESH: Self-refresh mode flag. + * @retval The state of FLAG (SET or RESET). + */ +#define __FMC_SDRAM_GET_FLAG(__INSTANCE__, __FLAG__) (((__INSTANCE__)->CTRL1 & (__FLAG__)) == (__FLAG__)) + + +/** + * @} + */ +#endif /* DMC */ +/** + * @} + */ + +/** + * @} + */ + +/* Private functions ---------------------------------------------------------*/ +/** @defgroup DMC_DDL_Private_Functions DMC DDL Private Functions + * @{ + */ + +#if defined(DMC) +/** @defgroup DMC_DDL_SDRAM SDRAM + * @{ + */ +/** @defgroup DMC_DDL_SDRAM_Private_Functions_Group1 SDRAM Initialization/de-initialization functions + * @{ + */ +DAL_StatusTypeDef DMC_SDRAM_Init(DMC_SDRAM_TypeDef *Device, DMC_SDRAM_InitTypeDef *Init); +DAL_StatusTypeDef DMC_SDRAM_Timing_Init(DMC_SDRAM_TypeDef *Device, + DMC_SDRAM_TimingTypeDef *Timing); +DAL_StatusTypeDef DMC_SDRAM_DeInit(DMC_SDRAM_TypeDef *Device); +/** + * @} + */ + +/** @defgroup DMC_DDL_SDRAM_Private_Functions_Group2 SDRAM Control functions + * @{ + */ +DAL_StatusTypeDef DMC_SDRAM_ProgramRefreshPeriod(DMC_SDRAM_TypeDef *Device, uint32_t RefreshPeriod); +DAL_StatusTypeDef DMC_SDRAM_SetOpenBankNumber(DMC_SDRAM_TypeDef *Device, uint32_t OpenBankNumber); +uint32_t DMC_SDRAM_GetModeStatus(DMC_SDRAM_TypeDef *Device); +/** + * @} + */ +/** + * @} + */ +#endif /* DMC */ + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* APM32F4xx_DDL_DMC_H */ diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_eint.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_eint.h new file mode 100644 index 0000000000..0b3ae21001 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_eint.h @@ -0,0 +1,963 @@ +/** + * + * @file apm32f4xx_ddl_eint.h + * @brief Header file of EINT DDL module. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS.Clause + * + * + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef APM32F4xx_DDL_EINT_H +#define APM32F4xx_DDL_EINT_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx.h" + +/** @addtogroup APM32F4xx_DDL_Driver + * @{ + */ + +#if defined (EINT) + +/** @defgroup EINT_DDL EINT + * @{ + */ + +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/* Private Macros ------------------------------------------------------------*/ +#if defined(USE_FULL_DDL_DRIVER) +/** @defgroup EINT_DDL_Private_Macros EINT Private Macros + * @{ + */ +/** + * @} + */ +#endif /*USE_FULL_DDL_DRIVER*/ +/* Exported types ------------------------------------------------------------*/ +#if defined(USE_FULL_DDL_DRIVER) +/** @defgroup EINT_DDL_ES_INIT EINT Exported Init structure + * @{ + */ +typedef struct +{ + + uint32_t Line_0_31; /*!< Specifies the EINT lines to be enabled or disabled for Lines in range 0 to 31 + This parameter can be any combination of @ref EINT_DDL_EC_LINE */ + + FunctionalState LineCommand; /*!< Specifies the new state of the selected EINT lines. + This parameter can be set either to ENABLE or DISABLE */ + + uint8_t Mode; /*!< Specifies the mode for the EINT lines. + This parameter can be a value of @ref EINT_DDL_EC_MODE. */ + + uint8_t Trigger; /*!< Specifies the trigger signal active edge for the EINT lines. + This parameter can be a value of @ref EINT_DDL_EC_TRIGGER. */ +} DDL_EINT_InitTypeDef; + +/** + * @} + */ +#endif /*USE_FULL_DDL_DRIVER*/ + +/* Exported constants --------------------------------------------------------*/ +/** @defgroup EINT_DDL_Exported_Constants EINT Exported Constants + * @{ + */ + +/** @defgroup EINT_DDL_EC_LINE LINE + * @{ + */ +#define DDL_EINT_LINE_0 EINT_IMASK_IM0 /*!< Extended line 0 */ +#define DDL_EINT_LINE_1 EINT_IMASK_IM1 /*!< Extended line 1 */ +#define DDL_EINT_LINE_2 EINT_IMASK_IM2 /*!< Extended line 2 */ +#define DDL_EINT_LINE_3 EINT_IMASK_IM3 /*!< Extended line 3 */ +#define DDL_EINT_LINE_4 EINT_IMASK_IM4 /*!< Extended line 4 */ +#define DDL_EINT_LINE_5 EINT_IMASK_IM5 /*!< Extended line 5 */ +#define DDL_EINT_LINE_6 EINT_IMASK_IM6 /*!< Extended line 6 */ +#define DDL_EINT_LINE_7 EINT_IMASK_IM7 /*!< Extended line 7 */ +#define DDL_EINT_LINE_8 EINT_IMASK_IM8 /*!< Extended line 8 */ +#define DDL_EINT_LINE_9 EINT_IMASK_IM9 /*!< Extended line 9 */ +#define DDL_EINT_LINE_10 EINT_IMASK_IM10 /*!< Extended line 10 */ +#define DDL_EINT_LINE_11 EINT_IMASK_IM11 /*!< Extended line 11 */ +#define DDL_EINT_LINE_12 EINT_IMASK_IM12 /*!< Extended line 12 */ +#define DDL_EINT_LINE_13 EINT_IMASK_IM13 /*!< Extended line 13 */ +#define DDL_EINT_LINE_14 EINT_IMASK_IM14 /*!< Extended line 14 */ +#define DDL_EINT_LINE_15 EINT_IMASK_IM15 /*!< Extended line 15 */ +#if defined(EINT_IMASK_IM16) +#define DDL_EINT_LINE_16 EINT_IMASK_IM16 /*!< Extended line 16 */ +#endif +#define DDL_EINT_LINE_17 EINT_IMASK_IM17 /*!< Extended line 17 */ +#if defined(EINT_IMASK_IM18) +#define DDL_EINT_LINE_18 EINT_IMASK_IM18 /*!< Extended line 18 */ +#endif +#define DDL_EINT_LINE_19 EINT_IMASK_IM19 /*!< Extended line 19 */ +#if defined(EINT_IMASK_IM20) +#define DDL_EINT_LINE_20 EINT_IMASK_IM20 /*!< Extended line 20 */ +#endif +#if defined(EINT_IMASK_IM21) +#define DDL_EINT_LINE_21 EINT_IMASK_IM21 /*!< Extended line 21 */ +#endif +#if defined(EINT_IMASK_IM22) +#define DDL_EINT_LINE_22 EINT_IMASK_IM22 /*!< Extended line 22 */ +#endif +#if defined(EINT_IMASK_IM23) +#define DDL_EINT_LINE_23 EINT_IMASK_IM23 /*!< Extended line 23 */ +#endif +#if defined(EINT_IMASK_IM24) +#define DDL_EINT_LINE_24 EINT_IMASK_IM24 /*!< Extended line 24 */ +#endif +#if defined(EINT_IMASK_IM25) +#define DDL_EINT_LINE_25 EINT_IMASK_IM25 /*!< Extended line 25 */ +#endif +#if defined(EINT_IMASK_IM26) +#define DDL_EINT_LINE_26 EINT_IMASK_IM26 /*!< Extended line 26 */ +#endif +#if defined(EINT_IMASK_IM27) +#define DDL_EINT_LINE_27 EINT_IMASK_IM27 /*!< Extended line 27 */ +#endif +#if defined(EINT_IMASK_IM28) +#define DDL_EINT_LINE_28 EINT_IMASK_IM28 /*!< Extended line 28 */ +#endif +#if defined(EINT_IMASK_IM29) +#define DDL_EINT_LINE_29 EINT_IMASK_IM29 /*!< Extended line 29 */ +#endif +#if defined(EINT_IMASK_IM30) +#define DDL_EINT_LINE_30 EINT_IMASK_IM30 /*!< Extended line 30 */ +#endif +#if defined(EINT_IMASK_IM31) +#define DDL_EINT_LINE_31 EINT_IMASK_IM31 /*!< Extended line 31 */ +#endif +#define DDL_EINT_LINE_ALL_0_31 EINT_IMASK_IM /*!< All Extended line not reserved*/ + + +#define DDL_EINT_LINE_ALL ((uint32_t)0xFFFFFFFFU) /*!< All Extended line */ + +#if defined(USE_FULL_DDL_DRIVER) +#define DDL_EINT_LINE_NONE ((uint32_t)0x00000000U) /*!< None Extended line */ +#endif /*USE_FULL_DDL_DRIVER*/ + +/** + * @} + */ +#if defined(USE_FULL_DDL_DRIVER) + +/** @defgroup EINT_DDL_EC_MODE Mode + * @{ + */ +#define DDL_EINT_MODE_IT ((uint8_t)0x00U) /*!< Interrupt Mode */ +#define DDL_EINT_MODE_EVENT ((uint8_t)0x01U) /*!< Event Mode */ +#define DDL_EINT_MODE_IT_EVENT ((uint8_t)0x02U) /*!< Interrupt & Event Mode */ +/** + * @} + */ + +/** @defgroup EINT_DDL_EC_TRIGGER Edge Trigger + * @{ + */ +#define DDL_EINT_TRIGGER_NONE ((uint8_t)0x00U) /*!< No Trigger Mode */ +#define DDL_EINT_TRIGGER_RISING ((uint8_t)0x01U) /*!< Trigger Rising Mode */ +#define DDL_EINT_TRIGGER_FALLING ((uint8_t)0x02U) /*!< Trigger Falling Mode */ +#define DDL_EINT_TRIGGER_RISING_FALLING ((uint8_t)0x03U) /*!< Trigger Rising & Falling Mode */ + +/** + * @} + */ + + +#endif /*USE_FULL_DDL_DRIVER*/ + + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ +/** @defgroup EINT_DDL_Exported_Macros EINT Exported Macros + * @{ + */ + +/** @defgroup EINT_DDL_EM_WRITE_READ Common Write and read registers Macros + * @{ + */ + +/** + * @brief Write a value in EINT register + * @param __REG__ Register to be written + * @param __VALUE__ Value to be written in the register + * @retval None + */ +#define DDL_EINT_WriteReg(__REG__, __VALUE__) WRITE_REG(EINT->__REG__, (__VALUE__)) + +/** + * @brief Read a value in EINT register + * @param __REG__ Register to be read + * @retval Register value + */ +#define DDL_EINT_ReadReg(__REG__) READ_REG(EINT->__REG__) +/** + * @} + */ + + +/** + * @} + */ + + + +/* Exported functions --------------------------------------------------------*/ +/** @defgroup EINT_DDL_Exported_Functions EINT Exported Functions + * @{ + */ +/** @defgroup EINT_DDL_EF_IT_Management IT_Management + * @{ + */ + +/** + * @brief Enable EintLine Interrupt request for Lines in range 0 to 31 + * @note The reset value for the direct or internal lines (see RM) + * is set to 1 in order to enable the interrupt by default. + * Bits are set automatically at Power on. + * @param EintLine This parameter can be one of the following values: + * @arg @ref DDL_EINT_LINE_0 + * @arg @ref DDL_EINT_LINE_1 + * @arg @ref DDL_EINT_LINE_2 + * @arg @ref DDL_EINT_LINE_3 + * @arg @ref DDL_EINT_LINE_4 + * @arg @ref DDL_EINT_LINE_5 + * @arg @ref DDL_EINT_LINE_6 + * @arg @ref DDL_EINT_LINE_7 + * @arg @ref DDL_EINT_LINE_8 + * @arg @ref DDL_EINT_LINE_9 + * @arg @ref DDL_EINT_LINE_10 + * @arg @ref DDL_EINT_LINE_11 + * @arg @ref DDL_EINT_LINE_12 + * @arg @ref DDL_EINT_LINE_13 + * @arg @ref DDL_EINT_LINE_14 + * @arg @ref DDL_EINT_LINE_15 + * @arg @ref DDL_EINT_LINE_16 + * @arg @ref DDL_EINT_LINE_17 + * @arg @ref DDL_EINT_LINE_18 + * @arg @ref DDL_EINT_LINE_19(*) + * @arg @ref DDL_EINT_LINE_20(*) + * @arg @ref DDL_EINT_LINE_21 + * @arg @ref DDL_EINT_LINE_22 + * @arg @ref DDL_EINT_LINE_23(*) + * @arg @ref DDL_EINT_LINE_ALL_0_31 + * @note (*): Available in some devices + * @note Please check each device line mapping for EINT Line availability + * @retval None + */ +__STATIC_INLINE void DDL_EINT_EnableIT_0_31(uint32_t EintLine) +{ + SET_BIT(EINT->IMASK, EintLine); +} + +/** + * @brief Disable EintLine Interrupt request for Lines in range 0 to 31 + * @note The reset value for the direct or internal lines (see RM) + * is set to 1 in order to enable the interrupt by default. + * Bits are set automatically at Power on. + * @param EintLine This parameter can be one of the following values: + * @arg @ref DDL_EINT_LINE_0 + * @arg @ref DDL_EINT_LINE_1 + * @arg @ref DDL_EINT_LINE_2 + * @arg @ref DDL_EINT_LINE_3 + * @arg @ref DDL_EINT_LINE_4 + * @arg @ref DDL_EINT_LINE_5 + * @arg @ref DDL_EINT_LINE_6 + * @arg @ref DDL_EINT_LINE_7 + * @arg @ref DDL_EINT_LINE_8 + * @arg @ref DDL_EINT_LINE_9 + * @arg @ref DDL_EINT_LINE_10 + * @arg @ref DDL_EINT_LINE_11 + * @arg @ref DDL_EINT_LINE_12 + * @arg @ref DDL_EINT_LINE_13 + * @arg @ref DDL_EINT_LINE_14 + * @arg @ref DDL_EINT_LINE_15 + * @arg @ref DDL_EINT_LINE_16 + * @arg @ref DDL_EINT_LINE_17 + * @arg @ref DDL_EINT_LINE_18 + * @arg @ref DDL_EINT_LINE_19(*) + * @arg @ref DDL_EINT_LINE_20(*) + * @arg @ref DDL_EINT_LINE_21 + * @arg @ref DDL_EINT_LINE_22 + * @arg @ref DDL_EINT_LINE_23(*) + * @arg @ref DDL_EINT_LINE_ALL_0_31 + * @note (*): Available in some devices + * @note Please check each device line mapping for EINT Line availability + * @retval None + */ +__STATIC_INLINE void DDL_EINT_DisableIT_0_31(uint32_t EintLine) +{ + CLEAR_BIT(EINT->IMASK, EintLine); +} + + +/** + * @brief Indicate if EintLine Interrupt request is enabled for Lines in range 0 to 31 + * @note The reset value for the direct or internal lines (see RM) + * is set to 1 in order to enable the interrupt by default. + * Bits are set automatically at Power on. + * @param EintLine This parameter can be one of the following values: + * @arg @ref DDL_EINT_LINE_0 + * @arg @ref DDL_EINT_LINE_1 + * @arg @ref DDL_EINT_LINE_2 + * @arg @ref DDL_EINT_LINE_3 + * @arg @ref DDL_EINT_LINE_4 + * @arg @ref DDL_EINT_LINE_5 + * @arg @ref DDL_EINT_LINE_6 + * @arg @ref DDL_EINT_LINE_7 + * @arg @ref DDL_EINT_LINE_8 + * @arg @ref DDL_EINT_LINE_9 + * @arg @ref DDL_EINT_LINE_10 + * @arg @ref DDL_EINT_LINE_11 + * @arg @ref DDL_EINT_LINE_12 + * @arg @ref DDL_EINT_LINE_13 + * @arg @ref DDL_EINT_LINE_14 + * @arg @ref DDL_EINT_LINE_15 + * @arg @ref DDL_EINT_LINE_16 + * @arg @ref DDL_EINT_LINE_17 + * @arg @ref DDL_EINT_LINE_18 + * @arg @ref DDL_EINT_LINE_19(*) + * @arg @ref DDL_EINT_LINE_20(*) + * @arg @ref DDL_EINT_LINE_21 + * @arg @ref DDL_EINT_LINE_22 + * @arg @ref DDL_EINT_LINE_23(*) + * @arg @ref DDL_EINT_LINE_ALL_0_31 + * @note (*): Available in some devices + * @note Please check each device line mapping for EINT Line availability + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_EINT_IsEnabledIT_0_31(uint32_t EintLine) +{ + return (READ_BIT(EINT->IMASK, EintLine) == (EintLine)); +} + + +/** + * @} + */ + +/** @defgroup EINT_DDL_EF_Event_Management Event_Management + * @{ + */ + +/** + * @brief Enable EintLine Event request for Lines in range 0 to 31 + * @param EintLine This parameter can be one of the following values: + * @arg @ref DDL_EINT_LINE_0 + * @arg @ref DDL_EINT_LINE_1 + * @arg @ref DDL_EINT_LINE_2 + * @arg @ref DDL_EINT_LINE_3 + * @arg @ref DDL_EINT_LINE_4 + * @arg @ref DDL_EINT_LINE_5 + * @arg @ref DDL_EINT_LINE_6 + * @arg @ref DDL_EINT_LINE_7 + * @arg @ref DDL_EINT_LINE_8 + * @arg @ref DDL_EINT_LINE_9 + * @arg @ref DDL_EINT_LINE_10 + * @arg @ref DDL_EINT_LINE_11 + * @arg @ref DDL_EINT_LINE_12 + * @arg @ref DDL_EINT_LINE_13 + * @arg @ref DDL_EINT_LINE_14 + * @arg @ref DDL_EINT_LINE_15 + * @arg @ref DDL_EINT_LINE_16 + * @arg @ref DDL_EINT_LINE_17 + * @arg @ref DDL_EINT_LINE_18 + * @arg @ref DDL_EINT_LINE_19(*) + * @arg @ref DDL_EINT_LINE_20(*) + * @arg @ref DDL_EINT_LINE_21 + * @arg @ref DDL_EINT_LINE_22 + * @arg @ref DDL_EINT_LINE_23(*) + * @arg @ref DDL_EINT_LINE_ALL_0_31 + * @note (*): Available in some devices + * @note Please check each device line mapping for EINT Line availability + * @retval None + */ +__STATIC_INLINE void DDL_EINT_EnableEvent_0_31(uint32_t EintLine) +{ + SET_BIT(EINT->EMASK, EintLine); + +} + + +/** + * @brief Disable EintLine Event request for Lines in range 0 to 31 + * @param EintLine This parameter can be one of the following values: + * @arg @ref DDL_EINT_LINE_0 + * @arg @ref DDL_EINT_LINE_1 + * @arg @ref DDL_EINT_LINE_2 + * @arg @ref DDL_EINT_LINE_3 + * @arg @ref DDL_EINT_LINE_4 + * @arg @ref DDL_EINT_LINE_5 + * @arg @ref DDL_EINT_LINE_6 + * @arg @ref DDL_EINT_LINE_7 + * @arg @ref DDL_EINT_LINE_8 + * @arg @ref DDL_EINT_LINE_9 + * @arg @ref DDL_EINT_LINE_10 + * @arg @ref DDL_EINT_LINE_11 + * @arg @ref DDL_EINT_LINE_12 + * @arg @ref DDL_EINT_LINE_13 + * @arg @ref DDL_EINT_LINE_14 + * @arg @ref DDL_EINT_LINE_15 + * @arg @ref DDL_EINT_LINE_16 + * @arg @ref DDL_EINT_LINE_17 + * @arg @ref DDL_EINT_LINE_18 + * @arg @ref DDL_EINT_LINE_19(*) + * @arg @ref DDL_EINT_LINE_20(*) + * @arg @ref DDL_EINT_LINE_21 + * @arg @ref DDL_EINT_LINE_22 + * @arg @ref DDL_EINT_LINE_23(*) + * @arg @ref DDL_EINT_LINE_ALL_0_31 + * @note (*): Available in some devices + * @note Please check each device line mapping for EINT Line availability + * @retval None + */ +__STATIC_INLINE void DDL_EINT_DisableEvent_0_31(uint32_t EintLine) +{ + CLEAR_BIT(EINT->EMASK, EintLine); +} + + +/** + * @brief Indicate if EintLine Event request is enabled for Lines in range 0 to 31 + * @param EintLine This parameter can be one of the following values: + * @arg @ref DDL_EINT_LINE_0 + * @arg @ref DDL_EINT_LINE_1 + * @arg @ref DDL_EINT_LINE_2 + * @arg @ref DDL_EINT_LINE_3 + * @arg @ref DDL_EINT_LINE_4 + * @arg @ref DDL_EINT_LINE_5 + * @arg @ref DDL_EINT_LINE_6 + * @arg @ref DDL_EINT_LINE_7 + * @arg @ref DDL_EINT_LINE_8 + * @arg @ref DDL_EINT_LINE_9 + * @arg @ref DDL_EINT_LINE_10 + * @arg @ref DDL_EINT_LINE_11 + * @arg @ref DDL_EINT_LINE_12 + * @arg @ref DDL_EINT_LINE_13 + * @arg @ref DDL_EINT_LINE_14 + * @arg @ref DDL_EINT_LINE_15 + * @arg @ref DDL_EINT_LINE_16 + * @arg @ref DDL_EINT_LINE_17 + * @arg @ref DDL_EINT_LINE_18 + * @arg @ref DDL_EINT_LINE_19(*) + * @arg @ref DDL_EINT_LINE_20(*) + * @arg @ref DDL_EINT_LINE_21 + * @arg @ref DDL_EINT_LINE_22 + * @arg @ref DDL_EINT_LINE_23(*) + * @arg @ref DDL_EINT_LINE_ALL_0_31 + * @note (*): Available in some devices + * @note Please check each device line mapping for EINT Line availability + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_EINT_IsEnabledEvent_0_31(uint32_t EintLine) +{ + return (READ_BIT(EINT->EMASK, EintLine) == (EintLine)); + +} + + +/** + * @} + */ + +/** @defgroup EINT_DDL_EF_Rising_Trigger_Management Rising_Trigger_Management + * @{ + */ + +/** + * @brief Enable EintLine Rising Edge Trigger for Lines in range 0 to 31 + * @note The configurable wakeup lines are edge-triggered. No glitch must be + * generated on these lines. If a rising edge on a configurable interrupt + * line occurs during a write operation in the EINT_RTEN register, the + * pending bit is not set. + * Rising and falling edge triggers can be set for + * the same interrupt line. In this case, both generate a trigger + * condition. + * @param EintLine This parameter can be a combination of the following values: + * @arg @ref DDL_EINT_LINE_0 + * @arg @ref DDL_EINT_LINE_1 + * @arg @ref DDL_EINT_LINE_2 + * @arg @ref DDL_EINT_LINE_3 + * @arg @ref DDL_EINT_LINE_4 + * @arg @ref DDL_EINT_LINE_5 + * @arg @ref DDL_EINT_LINE_6 + * @arg @ref DDL_EINT_LINE_7 + * @arg @ref DDL_EINT_LINE_8 + * @arg @ref DDL_EINT_LINE_9 + * @arg @ref DDL_EINT_LINE_10 + * @arg @ref DDL_EINT_LINE_11 + * @arg @ref DDL_EINT_LINE_12 + * @arg @ref DDL_EINT_LINE_13 + * @arg @ref DDL_EINT_LINE_14 + * @arg @ref DDL_EINT_LINE_15 + * @arg @ref DDL_EINT_LINE_16 + * @arg @ref DDL_EINT_LINE_18 + * @arg @ref DDL_EINT_LINE_19(*) + * @arg @ref DDL_EINT_LINE_20(*) + * @arg @ref DDL_EINT_LINE_21 + * @arg @ref DDL_EINT_LINE_22 + * @note (*): Available in some devices + * @note Please check each device line mapping for EINT Line availability + * @retval None + */ +__STATIC_INLINE void DDL_EINT_EnableRisingTrig_0_31(uint32_t EintLine) +{ + SET_BIT(EINT->RTEN, EintLine); + +} + + +/** + * @brief Disable EintLine Rising Edge Trigger for Lines in range 0 to 31 + * @note The configurable wakeup lines are edge-triggered. No glitch must be + * generated on these lines. If a rising edge on a configurable interrupt + * line occurs during a write operation in the EINT_RTEN register, the + * pending bit is not set. + * Rising and falling edge triggers can be set for + * the same interrupt line. In this case, both generate a trigger + * condition. + * @param EintLine This parameter can be a combination of the following values: + * @arg @ref DDL_EINT_LINE_0 + * @arg @ref DDL_EINT_LINE_1 + * @arg @ref DDL_EINT_LINE_2 + * @arg @ref DDL_EINT_LINE_3 + * @arg @ref DDL_EINT_LINE_4 + * @arg @ref DDL_EINT_LINE_5 + * @arg @ref DDL_EINT_LINE_6 + * @arg @ref DDL_EINT_LINE_7 + * @arg @ref DDL_EINT_LINE_8 + * @arg @ref DDL_EINT_LINE_9 + * @arg @ref DDL_EINT_LINE_10 + * @arg @ref DDL_EINT_LINE_11 + * @arg @ref DDL_EINT_LINE_12 + * @arg @ref DDL_EINT_LINE_13 + * @arg @ref DDL_EINT_LINE_14 + * @arg @ref DDL_EINT_LINE_15 + * @arg @ref DDL_EINT_LINE_16 + * @arg @ref DDL_EINT_LINE_18 + * @arg @ref DDL_EINT_LINE_19(*) + * @arg @ref DDL_EINT_LINE_20(*) + * @arg @ref DDL_EINT_LINE_21 + * @arg @ref DDL_EINT_LINE_22 + * @note (*): Available in some devices + * @note Please check each device line mapping for EINT Line availability + * @retval None + */ +__STATIC_INLINE void DDL_EINT_DisableRisingTrig_0_31(uint32_t EintLine) +{ + CLEAR_BIT(EINT->RTEN, EintLine); + +} + + +/** + * @brief Check if rising edge trigger is enabled for Lines in range 0 to 31 + * @param EintLine This parameter can be a combination of the following values: + * @arg @ref DDL_EINT_LINE_0 + * @arg @ref DDL_EINT_LINE_1 + * @arg @ref DDL_EINT_LINE_2 + * @arg @ref DDL_EINT_LINE_3 + * @arg @ref DDL_EINT_LINE_4 + * @arg @ref DDL_EINT_LINE_5 + * @arg @ref DDL_EINT_LINE_6 + * @arg @ref DDL_EINT_LINE_7 + * @arg @ref DDL_EINT_LINE_8 + * @arg @ref DDL_EINT_LINE_9 + * @arg @ref DDL_EINT_LINE_10 + * @arg @ref DDL_EINT_LINE_11 + * @arg @ref DDL_EINT_LINE_12 + * @arg @ref DDL_EINT_LINE_13 + * @arg @ref DDL_EINT_LINE_14 + * @arg @ref DDL_EINT_LINE_15 + * @arg @ref DDL_EINT_LINE_16 + * @arg @ref DDL_EINT_LINE_18 + * @arg @ref DDL_EINT_LINE_19(*) + * @arg @ref DDL_EINT_LINE_20(*) + * @arg @ref DDL_EINT_LINE_21 + * @arg @ref DDL_EINT_LINE_22 + * @note (*): Available in some devices + * @note Please check each device line mapping for EINT Line availability + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_EINT_IsEnabledRisingTrig_0_31(uint32_t EintLine) +{ + return (READ_BIT(EINT->RTEN, EintLine) == (EintLine)); +} + + +/** + * @} + */ + +/** @defgroup EINT_DDL_EF_Falling_Trigger_Management Falling_Trigger_Management + * @{ + */ + +/** + * @brief Enable EintLine Falling Edge Trigger for Lines in range 0 to 31 + * @note The configurable wakeup lines are edge-triggered. No glitch must be + * generated on these lines. If a falling edge on a configurable interrupt + * line occurs during a write operation in the EINT_FTEN register, the + * pending bit is not set. + * Rising and falling edge triggers can be set for + * the same interrupt line. In this case, both generate a trigger + * condition. + * @param EintLine This parameter can be a combination of the following values: + * @arg @ref DDL_EINT_LINE_0 + * @arg @ref DDL_EINT_LINE_1 + * @arg @ref DDL_EINT_LINE_2 + * @arg @ref DDL_EINT_LINE_3 + * @arg @ref DDL_EINT_LINE_4 + * @arg @ref DDL_EINT_LINE_5 + * @arg @ref DDL_EINT_LINE_6 + * @arg @ref DDL_EINT_LINE_7 + * @arg @ref DDL_EINT_LINE_8 + * @arg @ref DDL_EINT_LINE_9 + * @arg @ref DDL_EINT_LINE_10 + * @arg @ref DDL_EINT_LINE_11 + * @arg @ref DDL_EINT_LINE_12 + * @arg @ref DDL_EINT_LINE_13 + * @arg @ref DDL_EINT_LINE_14 + * @arg @ref DDL_EINT_LINE_15 + * @arg @ref DDL_EINT_LINE_16 + * @arg @ref DDL_EINT_LINE_18 + * @arg @ref DDL_EINT_LINE_19(*) + * @arg @ref DDL_EINT_LINE_20(*) + * @arg @ref DDL_EINT_LINE_21 + * @arg @ref DDL_EINT_LINE_22 + * @note (*): Available in some devices + * @note Please check each device line mapping for EINT Line availability + * @retval None + */ +__STATIC_INLINE void DDL_EINT_EnableFallingTrig_0_31(uint32_t EintLine) +{ + SET_BIT(EINT->FTEN, EintLine); +} + + +/** + * @brief Disable EintLine Falling Edge Trigger for Lines in range 0 to 31 + * @note The configurable wakeup lines are edge-triggered. No glitch must be + * generated on these lines. If a Falling edge on a configurable interrupt + * line occurs during a write operation in the EINT_FTEN register, the + * pending bit is not set. + * Rising and falling edge triggers can be set for the same interrupt line. + * In this case, both generate a trigger condition. + * @param EintLine This parameter can be a combination of the following values: + * @arg @ref DDL_EINT_LINE_0 + * @arg @ref DDL_EINT_LINE_1 + * @arg @ref DDL_EINT_LINE_2 + * @arg @ref DDL_EINT_LINE_3 + * @arg @ref DDL_EINT_LINE_4 + * @arg @ref DDL_EINT_LINE_5 + * @arg @ref DDL_EINT_LINE_6 + * @arg @ref DDL_EINT_LINE_7 + * @arg @ref DDL_EINT_LINE_8 + * @arg @ref DDL_EINT_LINE_9 + * @arg @ref DDL_EINT_LINE_10 + * @arg @ref DDL_EINT_LINE_11 + * @arg @ref DDL_EINT_LINE_12 + * @arg @ref DDL_EINT_LINE_13 + * @arg @ref DDL_EINT_LINE_14 + * @arg @ref DDL_EINT_LINE_15 + * @arg @ref DDL_EINT_LINE_16 + * @arg @ref DDL_EINT_LINE_18 + * @arg @ref DDL_EINT_LINE_19(*) + * @arg @ref DDL_EINT_LINE_20(*) + * @arg @ref DDL_EINT_LINE_21 + * @arg @ref DDL_EINT_LINE_22 + * @note (*): Available in some devices + * @note Please check each device line mapping for EINT Line availability + * @retval None + */ +__STATIC_INLINE void DDL_EINT_DisableFallingTrig_0_31(uint32_t EintLine) +{ + CLEAR_BIT(EINT->FTEN, EintLine); +} + + +/** + * @brief Check if falling edge trigger is enabled for Lines in range 0 to 31 + * @param EintLine This parameter can be a combination of the following values: + * @arg @ref DDL_EINT_LINE_0 + * @arg @ref DDL_EINT_LINE_1 + * @arg @ref DDL_EINT_LINE_2 + * @arg @ref DDL_EINT_LINE_3 + * @arg @ref DDL_EINT_LINE_4 + * @arg @ref DDL_EINT_LINE_5 + * @arg @ref DDL_EINT_LINE_6 + * @arg @ref DDL_EINT_LINE_7 + * @arg @ref DDL_EINT_LINE_8 + * @arg @ref DDL_EINT_LINE_9 + * @arg @ref DDL_EINT_LINE_10 + * @arg @ref DDL_EINT_LINE_11 + * @arg @ref DDL_EINT_LINE_12 + * @arg @ref DDL_EINT_LINE_13 + * @arg @ref DDL_EINT_LINE_14 + * @arg @ref DDL_EINT_LINE_15 + * @arg @ref DDL_EINT_LINE_16 + * @arg @ref DDL_EINT_LINE_18 + * @arg @ref DDL_EINT_LINE_19(*) + * @arg @ref DDL_EINT_LINE_20(*) + * @arg @ref DDL_EINT_LINE_21 + * @arg @ref DDL_EINT_LINE_22 + * @note (*): Available in some devices + * @note Please check each device line mapping for EINT Line availability + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_EINT_IsEnabledFallingTrig_0_31(uint32_t EintLine) +{ + return (READ_BIT(EINT->FTEN, EintLine) == (EintLine)); +} + + +/** + * @} + */ + +/** @defgroup EINT_DDL_EF_Software_Interrupt_Management Software_Interrupt_Management + * @{ + */ + +/** + * @brief Generate a software Interrupt Event for Lines in range 0 to 31 + * @note If the interrupt is enabled on this line in the EINT_IMASK, writing a 1 to + * this bit when it is at '0' sets the corresponding pending bit in EINT_IPEND + * resulting in an interrupt request generation. + * This bit is cleared by clearing the corresponding bit in the EINT_IPEND + * register (by writing a 1 into the bit) + * @param EintLine This parameter can be a combination of the following values: + * @arg @ref DDL_EINT_LINE_0 + * @arg @ref DDL_EINT_LINE_1 + * @arg @ref DDL_EINT_LINE_2 + * @arg @ref DDL_EINT_LINE_3 + * @arg @ref DDL_EINT_LINE_4 + * @arg @ref DDL_EINT_LINE_5 + * @arg @ref DDL_EINT_LINE_6 + * @arg @ref DDL_EINT_LINE_7 + * @arg @ref DDL_EINT_LINE_8 + * @arg @ref DDL_EINT_LINE_9 + * @arg @ref DDL_EINT_LINE_10 + * @arg @ref DDL_EINT_LINE_11 + * @arg @ref DDL_EINT_LINE_12 + * @arg @ref DDL_EINT_LINE_13 + * @arg @ref DDL_EINT_LINE_14 + * @arg @ref DDL_EINT_LINE_15 + * @arg @ref DDL_EINT_LINE_16 + * @arg @ref DDL_EINT_LINE_18 + * @arg @ref DDL_EINT_LINE_19(*) + * @arg @ref DDL_EINT_LINE_20(*) + * @arg @ref DDL_EINT_LINE_21 + * @arg @ref DDL_EINT_LINE_22 + * @note (*): Available in some devices + * @note Please check each device line mapping for EINT Line availability + * @retval None + */ +__STATIC_INLINE void DDL_EINT_GenerateSWI_0_31(uint32_t EintLine) +{ + SET_BIT(EINT->SWINTE, EintLine); +} + + +/** + * @} + */ + +/** @defgroup EINT_DDL_EF_Flag_Management Flag_Management + * @{ + */ + +/** + * @brief Check if the ExtLine Flag is set or not for Lines in range 0 to 31 + * @note This bit is set when the selected edge event arrives on the interrupt + * line. This bit is cleared by writing a 1 to the bit. + * @param EintLine This parameter can be a combination of the following values: + * @arg @ref DDL_EINT_LINE_0 + * @arg @ref DDL_EINT_LINE_1 + * @arg @ref DDL_EINT_LINE_2 + * @arg @ref DDL_EINT_LINE_3 + * @arg @ref DDL_EINT_LINE_4 + * @arg @ref DDL_EINT_LINE_5 + * @arg @ref DDL_EINT_LINE_6 + * @arg @ref DDL_EINT_LINE_7 + * @arg @ref DDL_EINT_LINE_8 + * @arg @ref DDL_EINT_LINE_9 + * @arg @ref DDL_EINT_LINE_10 + * @arg @ref DDL_EINT_LINE_11 + * @arg @ref DDL_EINT_LINE_12 + * @arg @ref DDL_EINT_LINE_13 + * @arg @ref DDL_EINT_LINE_14 + * @arg @ref DDL_EINT_LINE_15 + * @arg @ref DDL_EINT_LINE_16 + * @arg @ref DDL_EINT_LINE_18 + * @arg @ref DDL_EINT_LINE_19(*) + * @arg @ref DDL_EINT_LINE_20(*) + * @arg @ref DDL_EINT_LINE_21 + * @arg @ref DDL_EINT_LINE_22 + * @note (*): Available in some devices + * @note Please check each device line mapping for EINT Line availability + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_EINT_IsActiveFlag_0_31(uint32_t EintLine) +{ + return (READ_BIT(EINT->IPEND, EintLine) == (EintLine)); +} + + +/** + * @brief Read ExtLine Combination Flag for Lines in range 0 to 31 + * @note This bit is set when the selected edge event arrives on the interrupt + * line. This bit is cleared by writing a 1 to the bit. + * @param EintLine This parameter can be a combination of the following values: + * @arg @ref DDL_EINT_LINE_0 + * @arg @ref DDL_EINT_LINE_1 + * @arg @ref DDL_EINT_LINE_2 + * @arg @ref DDL_EINT_LINE_3 + * @arg @ref DDL_EINT_LINE_4 + * @arg @ref DDL_EINT_LINE_5 + * @arg @ref DDL_EINT_LINE_6 + * @arg @ref DDL_EINT_LINE_7 + * @arg @ref DDL_EINT_LINE_8 + * @arg @ref DDL_EINT_LINE_9 + * @arg @ref DDL_EINT_LINE_10 + * @arg @ref DDL_EINT_LINE_11 + * @arg @ref DDL_EINT_LINE_12 + * @arg @ref DDL_EINT_LINE_13 + * @arg @ref DDL_EINT_LINE_14 + * @arg @ref DDL_EINT_LINE_15 + * @arg @ref DDL_EINT_LINE_16 + * @arg @ref DDL_EINT_LINE_18 + * @arg @ref DDL_EINT_LINE_19(*) + * @arg @ref DDL_EINT_LINE_20(*) + * @arg @ref DDL_EINT_LINE_21 + * @arg @ref DDL_EINT_LINE_22 + * @note (*): Available in some devices + * @note Please check each device line mapping for EINT Line availability + * @retval @note This bit is set when the selected edge event arrives on the interrupt + */ +__STATIC_INLINE uint32_t DDL_EINT_ReadFlag_0_31(uint32_t EintLine) +{ + return (uint32_t)(READ_BIT(EINT->IPEND, EintLine)); +} + + +/** + * @brief Clear ExtLine Flags for Lines in range 0 to 31 + * @note This bit is set when the selected edge event arrives on the interrupt + * line. This bit is cleared by writing a 1 to the bit. + * @param EintLine This parameter can be a combination of the following values: + * @arg @ref DDL_EINT_LINE_0 + * @arg @ref DDL_EINT_LINE_1 + * @arg @ref DDL_EINT_LINE_2 + * @arg @ref DDL_EINT_LINE_3 + * @arg @ref DDL_EINT_LINE_4 + * @arg @ref DDL_EINT_LINE_5 + * @arg @ref DDL_EINT_LINE_6 + * @arg @ref DDL_EINT_LINE_7 + * @arg @ref DDL_EINT_LINE_8 + * @arg @ref DDL_EINT_LINE_9 + * @arg @ref DDL_EINT_LINE_10 + * @arg @ref DDL_EINT_LINE_11 + * @arg @ref DDL_EINT_LINE_12 + * @arg @ref DDL_EINT_LINE_13 + * @arg @ref DDL_EINT_LINE_14 + * @arg @ref DDL_EINT_LINE_15 + * @arg @ref DDL_EINT_LINE_16 + * @arg @ref DDL_EINT_LINE_18 + * @arg @ref DDL_EINT_LINE_19(*) + * @arg @ref DDL_EINT_LINE_20(*) + * @arg @ref DDL_EINT_LINE_21 + * @arg @ref DDL_EINT_LINE_22 + * @note (*): Available in some devices + * @note Please check each device line mapping for EINT Line availability + * @retval None + */ +__STATIC_INLINE void DDL_EINT_ClearFlag_0_31(uint32_t EintLine) +{ + WRITE_REG(EINT->IPEND, EintLine); +} + + +/** + * @} + */ + +#if defined(USE_FULL_DDL_DRIVER) +/** @defgroup EINT_DDL_EF_Init Initialization and de-initialization functions + * @{ + */ + +uint32_t DDL_EINT_Init(DDL_EINT_InitTypeDef *EINT_InitStruct); +uint32_t DDL_EINT_DeInit(void); +void DDL_EINT_StructInit(DDL_EINT_InitTypeDef *EINT_InitStruct); + + +/** + * @} + */ +#endif /* USE_FULL_DDL_DRIVER */ + +/** + * @} + */ + +/** + * @} + */ + +#endif /* EINT */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* APM32F4xx_DDL_EINT_H */ + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_gpio.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_gpio.h new file mode 100644 index 0000000000..e7788d4ef7 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_gpio.h @@ -0,0 +1,982 @@ +/** + * + * @file apm32f4xx_ddl_gpio.h + * @brief Header file of GPIO DDL module. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2017 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef APM32F4xx_DDL_GPIO_H +#define APM32F4xx_DDL_GPIO_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx.h" + +/** @addtogroup APM32F4xx_DDL_Driver + * @{ + */ + +#if defined (GPIOA) || defined (GPIOB) || defined (GPIOC) || defined (GPIOD) || defined (GPIOE) || defined (GPIOF) || defined (GPIOG) || defined (GPIOH) || defined (GPIOI) || defined (GPIOJ) || defined (GPIOK) + +/** @defgroup GPIO_DDL GPIO + * @{ + */ + +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/* Private macros ------------------------------------------------------------*/ +#if defined(USE_FULL_DDL_DRIVER) +/** @defgroup GPIO_DDL_Private_Macros GPIO Private Macros + * @{ + */ + +/** + * @} + */ +#endif /*USE_FULL_DDL_DRIVER*/ + +/* Exported types ------------------------------------------------------------*/ +#if defined(USE_FULL_DDL_DRIVER) +/** @defgroup GPIO_DDL_ES_INIT GPIO Exported Init structures + * @{ + */ + +/** + * @brief LL GPIO Init Structure definition + */ +typedef struct +{ + uint32_t Pin; /*!< Specifies the GPIO pins to be configured. + This parameter can be any value of @ref GPIO_DDL_EC_PIN */ + + uint32_t Mode; /*!< Specifies the operating mode for the selected pins. + This parameter can be a value of @ref GPIO_DDL_EC_MODE. + + GPIO HW configuration can be modified afterwards using unitary function @ref DDL_GPIO_SetPinMode().*/ + + uint32_t Speed; /*!< Specifies the speed for the selected pins. + This parameter can be a value of @ref GPIO_DDL_EC_SPEED. + + GPIO HW configuration can be modified afterwards using unitary function @ref DDL_GPIO_SetPinSpeed().*/ + + uint32_t OutputType; /*!< Specifies the operating output type for the selected pins. + This parameter can be a value of @ref GPIO_DDL_EC_OUTPUT. + + GPIO HW configuration can be modified afterwards using unitary function @ref DDL_GPIO_SetPinOutputType().*/ + + uint32_t Pull; /*!< Specifies the operating Pull-up/Pull down for the selected pins. + This parameter can be a value of @ref GPIO_DDL_EC_PULL. + + GPIO HW configuration can be modified afterwards using unitary function @ref DDL_GPIO_SetPinPull().*/ + + uint32_t Alternate; /*!< Specifies the Peripheral to be connected to the selected pins. + This parameter can be a value of @ref GPIO_DDL_EC_AF. + + GPIO HW configuration can be modified afterwards using unitary function @ref DDL_GPIO_SetAFPin_0_7() and DDL_GPIO_SetAFPin_8_15().*/ +} DDL_GPIO_InitTypeDef; + +/** + * @} + */ +#endif /* USE_FULL_DDL_DRIVER */ + +/* Exported constants --------------------------------------------------------*/ +/** @defgroup GPIO_DDL_Exported_Constants GPIO Exported Constants + * @{ + */ + +/** @defgroup GPIO_DDL_EC_PIN PIN + * @{ + */ +#define DDL_GPIO_PIN_0 GPIO_BSC_BS_0 /*!< Select pin 0 */ +#define DDL_GPIO_PIN_1 GPIO_BSC_BS_1 /*!< Select pin 1 */ +#define DDL_GPIO_PIN_2 GPIO_BSC_BS_2 /*!< Select pin 2 */ +#define DDL_GPIO_PIN_3 GPIO_BSC_BS_3 /*!< Select pin 3 */ +#define DDL_GPIO_PIN_4 GPIO_BSC_BS_4 /*!< Select pin 4 */ +#define DDL_GPIO_PIN_5 GPIO_BSC_BS_5 /*!< Select pin 5 */ +#define DDL_GPIO_PIN_6 GPIO_BSC_BS_6 /*!< Select pin 6 */ +#define DDL_GPIO_PIN_7 GPIO_BSC_BS_7 /*!< Select pin 7 */ +#define DDL_GPIO_PIN_8 GPIO_BSC_BS_8 /*!< Select pin 8 */ +#define DDL_GPIO_PIN_9 GPIO_BSC_BS_9 /*!< Select pin 9 */ +#define DDL_GPIO_PIN_10 GPIO_BSC_BS_10 /*!< Select pin 10 */ +#define DDL_GPIO_PIN_11 GPIO_BSC_BS_11 /*!< Select pin 11 */ +#define DDL_GPIO_PIN_12 GPIO_BSC_BS_12 /*!< Select pin 12 */ +#define DDL_GPIO_PIN_13 GPIO_BSC_BS_13 /*!< Select pin 13 */ +#define DDL_GPIO_PIN_14 GPIO_BSC_BS_14 /*!< Select pin 14 */ +#define DDL_GPIO_PIN_15 GPIO_BSC_BS_15 /*!< Select pin 15 */ +#define DDL_GPIO_PIN_ALL (GPIO_BSC_BS_0 | GPIO_BSC_BS_1 | GPIO_BSC_BS_2 | \ + GPIO_BSC_BS_3 | GPIO_BSC_BS_4 | GPIO_BSC_BS_5 | \ + GPIO_BSC_BS_6 | GPIO_BSC_BS_7 | GPIO_BSC_BS_8 | \ + GPIO_BSC_BS_9 | GPIO_BSC_BS_10 | GPIO_BSC_BS_11 | \ + GPIO_BSC_BS_12 | GPIO_BSC_BS_13 | GPIO_BSC_BS_14 | \ + GPIO_BSC_BS_15) /*!< Select all pins */ +/** + * @} + */ + +/** @defgroup GPIO_DDL_EC_MODE Mode + * @{ + */ +#define DDL_GPIO_MODE_INPUT (0x00000000U) /*!< Select input mode */ +#define DDL_GPIO_MODE_OUTPUT GPIO_MODE_MODE0_0 /*!< Select output mode */ +#define DDL_GPIO_MODE_ALTERNATE GPIO_MODE_MODE0_1 /*!< Select alternate function mode */ +#define DDL_GPIO_MODE_ANALOG GPIO_MODE_MODE0 /*!< Select analog mode */ +/** + * @} + */ + +/** @defgroup GPIO_DDL_EC_OUTPUT Output Type + * @{ + */ +#define DDL_GPIO_OUTPUT_PUSHPULL (0x00000000U) /*!< Select push-pull as output type */ +#define DDL_GPIO_OUTPUT_OPENDRAIN GPIO_OMODE_OT_0 /*!< Select open-drain as output type */ +/** + * @} + */ + +/** @defgroup GPIO_DDL_EC_SPEED Output Speed + * @{ + */ +#define DDL_GPIO_SPEED_FREQ_LOW (0x00000000U) /*!< Select I/O low output speed */ +#define DDL_GPIO_SPEED_FREQ_MEDIUM GPIO_OSPEEDER_OSPEEDR0_0 /*!< Select I/O medium output speed */ +#define DDL_GPIO_SPEED_FREQ_HIGH GPIO_OSPEEDER_OSPEEDR0_1 /*!< Select I/O fast output speed */ +#define DDL_GPIO_SPEED_FREQ_VERY_HIGH GPIO_OSPEEDER_OSPEEDR0 /*!< Select I/O high output speed */ +/** + * @} + */ + +/** @defgroup GPIO_DDL_EC_PULL Pull Up Pull Down + * @{ + */ +#define DDL_GPIO_PULL_NO (0x00000000U) /*!< Select I/O no pull */ +#define DDL_GPIO_PULL_UP GPIO_PUPD_PUPDR0_0 /*!< Select I/O pull up */ +#define DDL_GPIO_PULL_DOWN GPIO_PUPD_PUPDR0_1 /*!< Select I/O pull down */ +/** + * @} + */ + +/** @defgroup GPIO_DDL_EC_AF Alternate Function + * @{ + */ +#define DDL_GPIO_AF_0 (0x0000000U) /*!< Select alternate function 0 */ +#define DDL_GPIO_AF_1 (0x0000001U) /*!< Select alternate function 1 */ +#define DDL_GPIO_AF_2 (0x0000002U) /*!< Select alternate function 2 */ +#define DDL_GPIO_AF_3 (0x0000003U) /*!< Select alternate function 3 */ +#define DDL_GPIO_AF_4 (0x0000004U) /*!< Select alternate function 4 */ +#define DDL_GPIO_AF_5 (0x0000005U) /*!< Select alternate function 5 */ +#define DDL_GPIO_AF_6 (0x0000006U) /*!< Select alternate function 6 */ +#define DDL_GPIO_AF_7 (0x0000007U) /*!< Select alternate function 7 */ +#define DDL_GPIO_AF_8 (0x0000008U) /*!< Select alternate function 8 */ +#define DDL_GPIO_AF_9 (0x0000009U) /*!< Select alternate function 9 */ +#define DDL_GPIO_AF_10 (0x000000AU) /*!< Select alternate function 10 */ +#define DDL_GPIO_AF_11 (0x000000BU) /*!< Select alternate function 11 */ +#define DDL_GPIO_AF_12 (0x000000CU) /*!< Select alternate function 12 */ +#define DDL_GPIO_AF_13 (0x000000DU) /*!< Select alternate function 13 */ +#define DDL_GPIO_AF_14 (0x000000EU) /*!< Select alternate function 14 */ +#define DDL_GPIO_AF_15 (0x000000FU) /*!< Select alternate function 15 */ +/** + * @} + */ + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ +/** @defgroup GPIO_DDL_Exported_Macros GPIO Exported Macros + * @{ + */ + +/** @defgroup GPIO_DDL_EM_WRITE_READ Common Write and read registers Macros + * @{ + */ + +/** + * @brief Write a value in GPIO register + * @param __INSTANCE__ GPIO Instance + * @param __REG__ Register to be written + * @param __VALUE__ Value to be written in the register + * @retval None + */ +#define DDL_GPIO_WriteReg(__INSTANCE__, __REG__, __VALUE__) WRITE_REG(__INSTANCE__->__REG__, (__VALUE__)) + +/** + * @brief Read a value in GPIO register + * @param __INSTANCE__ GPIO Instance + * @param __REG__ Register to be read + * @retval Register value + */ +#define DDL_GPIO_ReadReg(__INSTANCE__, __REG__) READ_REG(__INSTANCE__->__REG__) +/** + * @} + */ + +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +/** @defgroup GPIO_DDL_Exported_Functions GPIO Exported Functions + * @{ + */ + +/** @defgroup GPIO_DDL_EF_Port_Configuration Port Configuration + * @{ + */ + +/** + * @brief Configure gpio mode for a dedicated pin on dedicated port. + * @note I/O mode can be Input mode, General purpose output, Alternate function mode or Analog. + * @note Warning: only one pin can be passed as parameter. + * @param GPIOx GPIO Port + * @param Pin This parameter can be one of the following values: + * @arg @ref DDL_GPIO_PIN_0 + * @arg @ref DDL_GPIO_PIN_1 + * @arg @ref DDL_GPIO_PIN_2 + * @arg @ref DDL_GPIO_PIN_3 + * @arg @ref DDL_GPIO_PIN_4 + * @arg @ref DDL_GPIO_PIN_5 + * @arg @ref DDL_GPIO_PIN_6 + * @arg @ref DDL_GPIO_PIN_7 + * @arg @ref DDL_GPIO_PIN_8 + * @arg @ref DDL_GPIO_PIN_9 + * @arg @ref DDL_GPIO_PIN_10 + * @arg @ref DDL_GPIO_PIN_11 + * @arg @ref DDL_GPIO_PIN_12 + * @arg @ref DDL_GPIO_PIN_13 + * @arg @ref DDL_GPIO_PIN_14 + * @arg @ref DDL_GPIO_PIN_15 + * @param Mode This parameter can be one of the following values: + * @arg @ref DDL_GPIO_MODE_INPUT + * @arg @ref DDL_GPIO_MODE_OUTPUT + * @arg @ref DDL_GPIO_MODE_ALTERNATE + * @arg @ref DDL_GPIO_MODE_ANALOG + * @retval None + */ +__STATIC_INLINE void DDL_GPIO_SetPinMode(GPIO_TypeDef *GPIOx, uint32_t Pin, uint32_t Mode) +{ + MODIFY_REG(GPIOx->MODE, (GPIO_MODE_MODE0 << (POSITION_VAL(Pin) * 2U)), (Mode << (POSITION_VAL(Pin) * 2U))); +} + +/** + * @brief Return gpio mode for a dedicated pin on dedicated port. + * @note I/O mode can be Input mode, General purpose output, Alternate function mode or Analog. + * @note Warning: only one pin can be passed as parameter. + * @param GPIOx GPIO Port + * @param Pin This parameter can be one of the following values: + * @arg @ref DDL_GPIO_PIN_0 + * @arg @ref DDL_GPIO_PIN_1 + * @arg @ref DDL_GPIO_PIN_2 + * @arg @ref DDL_GPIO_PIN_3 + * @arg @ref DDL_GPIO_PIN_4 + * @arg @ref DDL_GPIO_PIN_5 + * @arg @ref DDL_GPIO_PIN_6 + * @arg @ref DDL_GPIO_PIN_7 + * @arg @ref DDL_GPIO_PIN_8 + * @arg @ref DDL_GPIO_PIN_9 + * @arg @ref DDL_GPIO_PIN_10 + * @arg @ref DDL_GPIO_PIN_11 + * @arg @ref DDL_GPIO_PIN_12 + * @arg @ref DDL_GPIO_PIN_13 + * @arg @ref DDL_GPIO_PIN_14 + * @arg @ref DDL_GPIO_PIN_15 + * @retval Returned value can be one of the following values: + * @arg @ref DDL_GPIO_MODE_INPUT + * @arg @ref DDL_GPIO_MODE_OUTPUT + * @arg @ref DDL_GPIO_MODE_ALTERNATE + * @arg @ref DDL_GPIO_MODE_ANALOG + */ +__STATIC_INLINE uint32_t DDL_GPIO_GetPinMode(GPIO_TypeDef *GPIOx, uint32_t Pin) +{ + return (uint32_t)(READ_BIT(GPIOx->MODE, + (GPIO_MODE_MODE0 << (POSITION_VAL(Pin) * 2U))) >> (POSITION_VAL(Pin) * 2U)); +} + +/** + * @brief Configure gpio output type for several pins on dedicated port. + * @note Output type as to be set when gpio pin is in output or + * alternate modes. Possible type are Push-pull or Open-drain. + * @param GPIOx GPIO Port + * @param PinMask This parameter can be a combination of the following values: + * @arg @ref DDL_GPIO_PIN_0 + * @arg @ref DDL_GPIO_PIN_1 + * @arg @ref DDL_GPIO_PIN_2 + * @arg @ref DDL_GPIO_PIN_3 + * @arg @ref DDL_GPIO_PIN_4 + * @arg @ref DDL_GPIO_PIN_5 + * @arg @ref DDL_GPIO_PIN_6 + * @arg @ref DDL_GPIO_PIN_7 + * @arg @ref DDL_GPIO_PIN_8 + * @arg @ref DDL_GPIO_PIN_9 + * @arg @ref DDL_GPIO_PIN_10 + * @arg @ref DDL_GPIO_PIN_11 + * @arg @ref DDL_GPIO_PIN_12 + * @arg @ref DDL_GPIO_PIN_13 + * @arg @ref DDL_GPIO_PIN_14 + * @arg @ref DDL_GPIO_PIN_15 + * @arg @ref DDL_GPIO_PIN_ALL + * @param OutputType This parameter can be one of the following values: + * @arg @ref DDL_GPIO_OUTPUT_PUSHPULL + * @arg @ref DDL_GPIO_OUTPUT_OPENDRAIN + * @retval None + */ +__STATIC_INLINE void DDL_GPIO_SetPinOutputType(GPIO_TypeDef *GPIOx, uint32_t PinMask, uint32_t OutputType) +{ + MODIFY_REG(GPIOx->OMODE, PinMask, (PinMask * OutputType)); +} + +/** + * @brief Return gpio output type for several pins on dedicated port. + * @note Output type as to be set when gpio pin is in output or + * alternate modes. Possible type are Push-pull or Open-drain. + * @note Warning: only one pin can be passed as parameter. + * @param GPIOx GPIO Port + * @param Pin This parameter can be one of the following values: + * @arg @ref DDL_GPIO_PIN_0 + * @arg @ref DDL_GPIO_PIN_1 + * @arg @ref DDL_GPIO_PIN_2 + * @arg @ref DDL_GPIO_PIN_3 + * @arg @ref DDL_GPIO_PIN_4 + * @arg @ref DDL_GPIO_PIN_5 + * @arg @ref DDL_GPIO_PIN_6 + * @arg @ref DDL_GPIO_PIN_7 + * @arg @ref DDL_GPIO_PIN_8 + * @arg @ref DDL_GPIO_PIN_9 + * @arg @ref DDL_GPIO_PIN_10 + * @arg @ref DDL_GPIO_PIN_11 + * @arg @ref DDL_GPIO_PIN_12 + * @arg @ref DDL_GPIO_PIN_13 + * @arg @ref DDL_GPIO_PIN_14 + * @arg @ref DDL_GPIO_PIN_15 + * @arg @ref DDL_GPIO_PIN_ALL + * @retval Returned value can be one of the following values: + * @arg @ref DDL_GPIO_OUTPUT_PUSHPULL + * @arg @ref DDL_GPIO_OUTPUT_OPENDRAIN + */ +__STATIC_INLINE uint32_t DDL_GPIO_GetPinOutputType(GPIO_TypeDef *GPIOx, uint32_t Pin) +{ + return (uint32_t)(READ_BIT(GPIOx->OMODE, Pin) >> POSITION_VAL(Pin)); +} + +/** + * @brief Configure gpio speed for a dedicated pin on dedicated port. + * @note I/O speed can be Low, Medium, Fast or High speed. + * @note Warning: only one pin can be passed as parameter. + * @note Refer to datasheet for frequency specifications and the power + * supply and load conditions for each speed. + * @param GPIOx GPIO Port + * @param Pin This parameter can be one of the following values: + * @arg @ref DDL_GPIO_PIN_0 + * @arg @ref DDL_GPIO_PIN_1 + * @arg @ref DDL_GPIO_PIN_2 + * @arg @ref DDL_GPIO_PIN_3 + * @arg @ref DDL_GPIO_PIN_4 + * @arg @ref DDL_GPIO_PIN_5 + * @arg @ref DDL_GPIO_PIN_6 + * @arg @ref DDL_GPIO_PIN_7 + * @arg @ref DDL_GPIO_PIN_8 + * @arg @ref DDL_GPIO_PIN_9 + * @arg @ref DDL_GPIO_PIN_10 + * @arg @ref DDL_GPIO_PIN_11 + * @arg @ref DDL_GPIO_PIN_12 + * @arg @ref DDL_GPIO_PIN_13 + * @arg @ref DDL_GPIO_PIN_14 + * @arg @ref DDL_GPIO_PIN_15 + * @param Speed This parameter can be one of the following values: + * @arg @ref DDL_GPIO_SPEED_FREQ_LOW + * @arg @ref DDL_GPIO_SPEED_FREQ_MEDIUM + * @arg @ref DDL_GPIO_SPEED_FREQ_HIGH + * @arg @ref DDL_GPIO_SPEED_FREQ_VERY_HIGH + * @retval None + */ +__STATIC_INLINE void DDL_GPIO_SetPinSpeed(GPIO_TypeDef *GPIOx, uint32_t Pin, uint32_t Speed) +{ + MODIFY_REG(GPIOx->OSSEL, (GPIO_OSPEEDER_OSPEEDR0 << (POSITION_VAL(Pin) * 2U)), + (Speed << (POSITION_VAL(Pin) * 2U))); +} + +/** + * @brief Return gpio speed for a dedicated pin on dedicated port. + * @note I/O speed can be Low, Medium, Fast or High speed. + * @note Warning: only one pin can be passed as parameter. + * @note Refer to datasheet for frequency specifications and the power + * supply and load conditions for each speed. + * @param GPIOx GPIO Port + * @param Pin This parameter can be one of the following values: + * @arg @ref DDL_GPIO_PIN_0 + * @arg @ref DDL_GPIO_PIN_1 + * @arg @ref DDL_GPIO_PIN_2 + * @arg @ref DDL_GPIO_PIN_3 + * @arg @ref DDL_GPIO_PIN_4 + * @arg @ref DDL_GPIO_PIN_5 + * @arg @ref DDL_GPIO_PIN_6 + * @arg @ref DDL_GPIO_PIN_7 + * @arg @ref DDL_GPIO_PIN_8 + * @arg @ref DDL_GPIO_PIN_9 + * @arg @ref DDL_GPIO_PIN_10 + * @arg @ref DDL_GPIO_PIN_11 + * @arg @ref DDL_GPIO_PIN_12 + * @arg @ref DDL_GPIO_PIN_13 + * @arg @ref DDL_GPIO_PIN_14 + * @arg @ref DDL_GPIO_PIN_15 + * @retval Returned value can be one of the following values: + * @arg @ref DDL_GPIO_SPEED_FREQ_LOW + * @arg @ref DDL_GPIO_SPEED_FREQ_MEDIUM + * @arg @ref DDL_GPIO_SPEED_FREQ_HIGH + * @arg @ref DDL_GPIO_SPEED_FREQ_VERY_HIGH + */ +__STATIC_INLINE uint32_t DDL_GPIO_GetPinSpeed(GPIO_TypeDef *GPIOx, uint32_t Pin) +{ + return (uint32_t)(READ_BIT(GPIOx->OSSEL, + (GPIO_OSPEEDER_OSPEEDR0 << (POSITION_VAL(Pin) * 2U))) >> (POSITION_VAL(Pin) * 2U)); +} + +/** + * @brief Configure gpio pull-up or pull-down for a dedicated pin on a dedicated port. + * @note Warning: only one pin can be passed as parameter. + * @param GPIOx GPIO Port + * @param Pin This parameter can be one of the following values: + * @arg @ref DDL_GPIO_PIN_0 + * @arg @ref DDL_GPIO_PIN_1 + * @arg @ref DDL_GPIO_PIN_2 + * @arg @ref DDL_GPIO_PIN_3 + * @arg @ref DDL_GPIO_PIN_4 + * @arg @ref DDL_GPIO_PIN_5 + * @arg @ref DDL_GPIO_PIN_6 + * @arg @ref DDL_GPIO_PIN_7 + * @arg @ref DDL_GPIO_PIN_8 + * @arg @ref DDL_GPIO_PIN_9 + * @arg @ref DDL_GPIO_PIN_10 + * @arg @ref DDL_GPIO_PIN_11 + * @arg @ref DDL_GPIO_PIN_12 + * @arg @ref DDL_GPIO_PIN_13 + * @arg @ref DDL_GPIO_PIN_14 + * @arg @ref DDL_GPIO_PIN_15 + * @param Pull This parameter can be one of the following values: + * @arg @ref DDL_GPIO_PULL_NO + * @arg @ref DDL_GPIO_PULL_UP + * @arg @ref DDL_GPIO_PULL_DOWN + * @retval None + */ +__STATIC_INLINE void DDL_GPIO_SetPinPull(GPIO_TypeDef *GPIOx, uint32_t Pin, uint32_t Pull) +{ + MODIFY_REG(GPIOx->PUPD, (GPIO_PUPD_PUPDR0 << (POSITION_VAL(Pin) * 2U)), (Pull << (POSITION_VAL(Pin) * 2U))); +} + +/** + * @brief Return gpio pull-up or pull-down for a dedicated pin on a dedicated port + * @note Warning: only one pin can be passed as parameter. + * @param GPIOx GPIO Port + * @param Pin This parameter can be one of the following values: + * @arg @ref DDL_GPIO_PIN_0 + * @arg @ref DDL_GPIO_PIN_1 + * @arg @ref DDL_GPIO_PIN_2 + * @arg @ref DDL_GPIO_PIN_3 + * @arg @ref DDL_GPIO_PIN_4 + * @arg @ref DDL_GPIO_PIN_5 + * @arg @ref DDL_GPIO_PIN_6 + * @arg @ref DDL_GPIO_PIN_7 + * @arg @ref DDL_GPIO_PIN_8 + * @arg @ref DDL_GPIO_PIN_9 + * @arg @ref DDL_GPIO_PIN_10 + * @arg @ref DDL_GPIO_PIN_11 + * @arg @ref DDL_GPIO_PIN_12 + * @arg @ref DDL_GPIO_PIN_13 + * @arg @ref DDL_GPIO_PIN_14 + * @arg @ref DDL_GPIO_PIN_15 + * @retval Returned value can be one of the following values: + * @arg @ref DDL_GPIO_PULL_NO + * @arg @ref DDL_GPIO_PULL_UP + * @arg @ref DDL_GPIO_PULL_DOWN + */ +__STATIC_INLINE uint32_t DDL_GPIO_GetPinPull(GPIO_TypeDef *GPIOx, uint32_t Pin) +{ + return (uint32_t)(READ_BIT(GPIOx->PUPD, + (GPIO_PUPD_PUPDR0 << (POSITION_VAL(Pin) * 2U))) >> (POSITION_VAL(Pin) * 2U)); +} + +/** + * @brief Configure gpio alternate function of a dedicated pin from 0 to 7 for a dedicated port. + * @note Possible values are from AF0 to AF15 depending on target. + * @note Warning: only one pin can be passed as parameter. + * @param GPIOx GPIO Port + * @param Pin This parameter can be one of the following values: + * @arg @ref DDL_GPIO_PIN_0 + * @arg @ref DDL_GPIO_PIN_1 + * @arg @ref DDL_GPIO_PIN_2 + * @arg @ref DDL_GPIO_PIN_3 + * @arg @ref DDL_GPIO_PIN_4 + * @arg @ref DDL_GPIO_PIN_5 + * @arg @ref DDL_GPIO_PIN_6 + * @arg @ref DDL_GPIO_PIN_7 + * @param Alternate This parameter can be one of the following values: + * @arg @ref DDL_GPIO_AF_0 + * @arg @ref DDL_GPIO_AF_1 + * @arg @ref DDL_GPIO_AF_2 + * @arg @ref DDL_GPIO_AF_3 + * @arg @ref DDL_GPIO_AF_4 + * @arg @ref DDL_GPIO_AF_5 + * @arg @ref DDL_GPIO_AF_6 + * @arg @ref DDL_GPIO_AF_7 + * @arg @ref DDL_GPIO_AF_8 + * @arg @ref DDL_GPIO_AF_9 + * @arg @ref DDL_GPIO_AF_10 + * @arg @ref DDL_GPIO_AF_11 + * @arg @ref DDL_GPIO_AF_12 + * @arg @ref DDL_GPIO_AF_13 + * @arg @ref DDL_GPIO_AF_14 + * @arg @ref DDL_GPIO_AF_15 + * @retval None + */ +__STATIC_INLINE void DDL_GPIO_SetAFPin_0_7(GPIO_TypeDef *GPIOx, uint32_t Pin, uint32_t Alternate) +{ + MODIFY_REG(GPIOx->ALF[0], (GPIO_ALFL_ALFSEL0 << (POSITION_VAL(Pin) * 4U)), + (Alternate << (POSITION_VAL(Pin) * 4U))); +} + +/** + * @brief Return gpio alternate function of a dedicated pin from 0 to 7 for a dedicated port. + * @param GPIOx GPIO Port + * @param Pin This parameter can be one of the following values: + * @arg @ref DDL_GPIO_PIN_0 + * @arg @ref DDL_GPIO_PIN_1 + * @arg @ref DDL_GPIO_PIN_2 + * @arg @ref DDL_GPIO_PIN_3 + * @arg @ref DDL_GPIO_PIN_4 + * @arg @ref DDL_GPIO_PIN_5 + * @arg @ref DDL_GPIO_PIN_6 + * @arg @ref DDL_GPIO_PIN_7 + * @retval Returned value can be one of the following values: + * @arg @ref DDL_GPIO_AF_0 + * @arg @ref DDL_GPIO_AF_1 + * @arg @ref DDL_GPIO_AF_2 + * @arg @ref DDL_GPIO_AF_3 + * @arg @ref DDL_GPIO_AF_4 + * @arg @ref DDL_GPIO_AF_5 + * @arg @ref DDL_GPIO_AF_6 + * @arg @ref DDL_GPIO_AF_7 + * @arg @ref DDL_GPIO_AF_8 + * @arg @ref DDL_GPIO_AF_9 + * @arg @ref DDL_GPIO_AF_10 + * @arg @ref DDL_GPIO_AF_11 + * @arg @ref DDL_GPIO_AF_12 + * @arg @ref DDL_GPIO_AF_13 + * @arg @ref DDL_GPIO_AF_14 + * @arg @ref DDL_GPIO_AF_15 + */ +__STATIC_INLINE uint32_t DDL_GPIO_GetAFPin_0_7(GPIO_TypeDef *GPIOx, uint32_t Pin) +{ + return (uint32_t)(READ_BIT(GPIOx->ALF[0], + (GPIO_ALFL_ALFSEL0 << (POSITION_VAL(Pin) * 4U))) >> (POSITION_VAL(Pin) * 4U)); +} + +/** + * @brief Configure gpio alternate function of a dedicated pin from 8 to 15 for a dedicated port. + * @note Possible values are from AF0 to AF15 depending on target. + * @note Warning: only one pin can be passed as parameter. + * @param GPIOx GPIO Port + * @param Pin This parameter can be one of the following values: + * @arg @ref DDL_GPIO_PIN_8 + * @arg @ref DDL_GPIO_PIN_9 + * @arg @ref DDL_GPIO_PIN_10 + * @arg @ref DDL_GPIO_PIN_11 + * @arg @ref DDL_GPIO_PIN_12 + * @arg @ref DDL_GPIO_PIN_13 + * @arg @ref DDL_GPIO_PIN_14 + * @arg @ref DDL_GPIO_PIN_15 + * @param Alternate This parameter can be one of the following values: + * @arg @ref DDL_GPIO_AF_0 + * @arg @ref DDL_GPIO_AF_1 + * @arg @ref DDL_GPIO_AF_2 + * @arg @ref DDL_GPIO_AF_3 + * @arg @ref DDL_GPIO_AF_4 + * @arg @ref DDL_GPIO_AF_5 + * @arg @ref DDL_GPIO_AF_6 + * @arg @ref DDL_GPIO_AF_7 + * @arg @ref DDL_GPIO_AF_8 + * @arg @ref DDL_GPIO_AF_9 + * @arg @ref DDL_GPIO_AF_10 + * @arg @ref DDL_GPIO_AF_11 + * @arg @ref DDL_GPIO_AF_12 + * @arg @ref DDL_GPIO_AF_13 + * @arg @ref DDL_GPIO_AF_14 + * @arg @ref DDL_GPIO_AF_15 + * @retval None + */ +__STATIC_INLINE void DDL_GPIO_SetAFPin_8_15(GPIO_TypeDef *GPIOx, uint32_t Pin, uint32_t Alternate) +{ + MODIFY_REG(GPIOx->ALF[1], (GPIO_ALFH_ALFSEL8 << (POSITION_VAL(Pin >> 8U) * 4U)), + (Alternate << (POSITION_VAL(Pin >> 8U) * 4U))); +} + +/** + * @brief Return gpio alternate function of a dedicated pin from 8 to 15 for a dedicated port. + * @note Possible values are from AF0 to AF15 depending on target. + * @param GPIOx GPIO Port + * @param Pin This parameter can be one of the following values: + * @arg @ref DDL_GPIO_PIN_8 + * @arg @ref DDL_GPIO_PIN_9 + * @arg @ref DDL_GPIO_PIN_10 + * @arg @ref DDL_GPIO_PIN_11 + * @arg @ref DDL_GPIO_PIN_12 + * @arg @ref DDL_GPIO_PIN_13 + * @arg @ref DDL_GPIO_PIN_14 + * @arg @ref DDL_GPIO_PIN_15 + * @retval Returned value can be one of the following values: + * @arg @ref DDL_GPIO_AF_0 + * @arg @ref DDL_GPIO_AF_1 + * @arg @ref DDL_GPIO_AF_2 + * @arg @ref DDL_GPIO_AF_3 + * @arg @ref DDL_GPIO_AF_4 + * @arg @ref DDL_GPIO_AF_5 + * @arg @ref DDL_GPIO_AF_6 + * @arg @ref DDL_GPIO_AF_7 + * @arg @ref DDL_GPIO_AF_8 + * @arg @ref DDL_GPIO_AF_9 + * @arg @ref DDL_GPIO_AF_10 + * @arg @ref DDL_GPIO_AF_11 + * @arg @ref DDL_GPIO_AF_12 + * @arg @ref DDL_GPIO_AF_13 + * @arg @ref DDL_GPIO_AF_14 + * @arg @ref DDL_GPIO_AF_15 + */ +__STATIC_INLINE uint32_t DDL_GPIO_GetAFPin_8_15(GPIO_TypeDef *GPIOx, uint32_t Pin) +{ + return (uint32_t)(READ_BIT(GPIOx->ALF[1], + (GPIO_ALFH_ALFSEL8 << (POSITION_VAL(Pin >> 8U) * 4U))) >> (POSITION_VAL(Pin >> 8U) * 4U)); +} + + +/** + * @brief Lock configuration of several pins for a dedicated port. + * @note When the lock sequence has been applied on a port bit, the + * value of this port bit can no longer be modified until the + * next reset. + * @note Each lock bit freezes a specific configuration register + * (control and alternate function registers). + * @param GPIOx GPIO Port + * @param PinMask This parameter can be a combination of the following values: + * @arg @ref DDL_GPIO_PIN_0 + * @arg @ref DDL_GPIO_PIN_1 + * @arg @ref DDL_GPIO_PIN_2 + * @arg @ref DDL_GPIO_PIN_3 + * @arg @ref DDL_GPIO_PIN_4 + * @arg @ref DDL_GPIO_PIN_5 + * @arg @ref DDL_GPIO_PIN_6 + * @arg @ref DDL_GPIO_PIN_7 + * @arg @ref DDL_GPIO_PIN_8 + * @arg @ref DDL_GPIO_PIN_9 + * @arg @ref DDL_GPIO_PIN_10 + * @arg @ref DDL_GPIO_PIN_11 + * @arg @ref DDL_GPIO_PIN_12 + * @arg @ref DDL_GPIO_PIN_13 + * @arg @ref DDL_GPIO_PIN_14 + * @arg @ref DDL_GPIO_PIN_15 + * @arg @ref DDL_GPIO_PIN_ALL + * @retval None + */ +__STATIC_INLINE void DDL_GPIO_LockPin(GPIO_TypeDef *GPIOx, uint32_t PinMask) +{ + __IO uint32_t temp; + WRITE_REG(GPIOx->LOCK, GPIO_LOCK_LOCKKEY | PinMask); + WRITE_REG(GPIOx->LOCK, PinMask); + WRITE_REG(GPIOx->LOCK, GPIO_LOCK_LOCKKEY | PinMask); + temp = READ_REG(GPIOx->LOCK); + (void) temp; +} + +/** + * @brief Return 1 if all pins passed as parameter, of a dedicated port, are locked. else Return 0. + * @param GPIOx GPIO Port + * @param PinMask This parameter can be a combination of the following values: + * @arg @ref DDL_GPIO_PIN_0 + * @arg @ref DDL_GPIO_PIN_1 + * @arg @ref DDL_GPIO_PIN_2 + * @arg @ref DDL_GPIO_PIN_3 + * @arg @ref DDL_GPIO_PIN_4 + * @arg @ref DDL_GPIO_PIN_5 + * @arg @ref DDL_GPIO_PIN_6 + * @arg @ref DDL_GPIO_PIN_7 + * @arg @ref DDL_GPIO_PIN_8 + * @arg @ref DDL_GPIO_PIN_9 + * @arg @ref DDL_GPIO_PIN_10 + * @arg @ref DDL_GPIO_PIN_11 + * @arg @ref DDL_GPIO_PIN_12 + * @arg @ref DDL_GPIO_PIN_13 + * @arg @ref DDL_GPIO_PIN_14 + * @arg @ref DDL_GPIO_PIN_15 + * @arg @ref DDL_GPIO_PIN_ALL + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_GPIO_IsPinLocked(GPIO_TypeDef *GPIOx, uint32_t PinMask) +{ + return (READ_BIT(GPIOx->LOCK, PinMask) == (PinMask)); +} + +/** + * @brief Return 1 if one of the pin of a dedicated port is locked. else return 0. + * @param GPIOx GPIO Port + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_GPIO_IsAnyPinLocked(GPIO_TypeDef *GPIOx) +{ + return (READ_BIT(GPIOx->LOCK, GPIO_LOCK_LOCKKEY) == (GPIO_LOCK_LOCKKEY)); +} + +/** + * @} + */ + +/** @defgroup GPIO_DDL_EF_Data_Access Data Access + * @{ + */ + +/** + * @brief Return full input data register value for a dedicated port. + * @param GPIOx GPIO Port + * @retval Input data register value of port + */ +__STATIC_INLINE uint32_t DDL_GPIO_ReadInputPort(GPIO_TypeDef *GPIOx) +{ + return (uint32_t)(READ_REG(GPIOx->IDATA)); +} + +/** + * @brief Return if input data level for several pins of dedicated port is high or low. + * @param GPIOx GPIO Port + * @param PinMask This parameter can be a combination of the following values: + * @arg @ref DDL_GPIO_PIN_0 + * @arg @ref DDL_GPIO_PIN_1 + * @arg @ref DDL_GPIO_PIN_2 + * @arg @ref DDL_GPIO_PIN_3 + * @arg @ref DDL_GPIO_PIN_4 + * @arg @ref DDL_GPIO_PIN_5 + * @arg @ref DDL_GPIO_PIN_6 + * @arg @ref DDL_GPIO_PIN_7 + * @arg @ref DDL_GPIO_PIN_8 + * @arg @ref DDL_GPIO_PIN_9 + * @arg @ref DDL_GPIO_PIN_10 + * @arg @ref DDL_GPIO_PIN_11 + * @arg @ref DDL_GPIO_PIN_12 + * @arg @ref DDL_GPIO_PIN_13 + * @arg @ref DDL_GPIO_PIN_14 + * @arg @ref DDL_GPIO_PIN_15 + * @arg @ref DDL_GPIO_PIN_ALL + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_GPIO_IsInputPinSet(GPIO_TypeDef *GPIOx, uint32_t PinMask) +{ + return (READ_BIT(GPIOx->IDATA, PinMask) == (PinMask)); +} + +/** + * @brief Write output data register for the port. + * @param GPIOx GPIO Port + * @param PortValue Level value for each pin of the port + * @retval None + */ +__STATIC_INLINE void DDL_GPIO_WriteOutputPort(GPIO_TypeDef *GPIOx, uint32_t PortValue) +{ + WRITE_REG(GPIOx->ODATA, PortValue); +} + +/** + * @brief Return full output data register value for a dedicated port. + * @param GPIOx GPIO Port + * @retval Output data register value of port + */ +__STATIC_INLINE uint32_t DDL_GPIO_ReadOutputPort(GPIO_TypeDef *GPIOx) +{ + return (uint32_t)(READ_REG(GPIOx->ODATA)); +} + +/** + * @brief Return if input data level for several pins of dedicated port is high or low. + * @param GPIOx GPIO Port + * @param PinMask This parameter can be a combination of the following values: + * @arg @ref DDL_GPIO_PIN_0 + * @arg @ref DDL_GPIO_PIN_1 + * @arg @ref DDL_GPIO_PIN_2 + * @arg @ref DDL_GPIO_PIN_3 + * @arg @ref DDL_GPIO_PIN_4 + * @arg @ref DDL_GPIO_PIN_5 + * @arg @ref DDL_GPIO_PIN_6 + * @arg @ref DDL_GPIO_PIN_7 + * @arg @ref DDL_GPIO_PIN_8 + * @arg @ref DDL_GPIO_PIN_9 + * @arg @ref DDL_GPIO_PIN_10 + * @arg @ref DDL_GPIO_PIN_11 + * @arg @ref DDL_GPIO_PIN_12 + * @arg @ref DDL_GPIO_PIN_13 + * @arg @ref DDL_GPIO_PIN_14 + * @arg @ref DDL_GPIO_PIN_15 + * @arg @ref DDL_GPIO_PIN_ALL + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_GPIO_IsOutputPinSet(GPIO_TypeDef *GPIOx, uint32_t PinMask) +{ + return (READ_BIT(GPIOx->ODATA, PinMask) == (PinMask)); +} + +/** + * @brief Set several pins to high level on dedicated gpio port. + * @param GPIOx GPIO Port + * @param PinMask This parameter can be a combination of the following values: + * @arg @ref DDL_GPIO_PIN_0 + * @arg @ref DDL_GPIO_PIN_1 + * @arg @ref DDL_GPIO_PIN_2 + * @arg @ref DDL_GPIO_PIN_3 + * @arg @ref DDL_GPIO_PIN_4 + * @arg @ref DDL_GPIO_PIN_5 + * @arg @ref DDL_GPIO_PIN_6 + * @arg @ref DDL_GPIO_PIN_7 + * @arg @ref DDL_GPIO_PIN_8 + * @arg @ref DDL_GPIO_PIN_9 + * @arg @ref DDL_GPIO_PIN_10 + * @arg @ref DDL_GPIO_PIN_11 + * @arg @ref DDL_GPIO_PIN_12 + * @arg @ref DDL_GPIO_PIN_13 + * @arg @ref DDL_GPIO_PIN_14 + * @arg @ref DDL_GPIO_PIN_15 + * @arg @ref DDL_GPIO_PIN_ALL + * @retval None + */ +__STATIC_INLINE void DDL_GPIO_SetOutputPin(GPIO_TypeDef *GPIOx, uint32_t PinMask) +{ + WRITE_REG(GPIOx->BSC, PinMask); +} + +/** + * @brief Set several pins to low level on dedicated gpio port. + * @param GPIOx GPIO Port + * @param PinMask This parameter can be a combination of the following values: + * @arg @ref DDL_GPIO_PIN_0 + * @arg @ref DDL_GPIO_PIN_1 + * @arg @ref DDL_GPIO_PIN_2 + * @arg @ref DDL_GPIO_PIN_3 + * @arg @ref DDL_GPIO_PIN_4 + * @arg @ref DDL_GPIO_PIN_5 + * @arg @ref DDL_GPIO_PIN_6 + * @arg @ref DDL_GPIO_PIN_7 + * @arg @ref DDL_GPIO_PIN_8 + * @arg @ref DDL_GPIO_PIN_9 + * @arg @ref DDL_GPIO_PIN_10 + * @arg @ref DDL_GPIO_PIN_11 + * @arg @ref DDL_GPIO_PIN_12 + * @arg @ref DDL_GPIO_PIN_13 + * @arg @ref DDL_GPIO_PIN_14 + * @arg @ref DDL_GPIO_PIN_15 + * @arg @ref DDL_GPIO_PIN_ALL + * @retval None + */ +__STATIC_INLINE void DDL_GPIO_ResetOutputPin(GPIO_TypeDef *GPIOx, uint32_t PinMask) +{ + WRITE_REG(GPIOx->BSC, (PinMask << 16)); +} + +/** + * @brief Toggle data value for several pin of dedicated port. + * @param GPIOx GPIO Port + * @param PinMask This parameter can be a combination of the following values: + * @arg @ref DDL_GPIO_PIN_0 + * @arg @ref DDL_GPIO_PIN_1 + * @arg @ref DDL_GPIO_PIN_2 + * @arg @ref DDL_GPIO_PIN_3 + * @arg @ref DDL_GPIO_PIN_4 + * @arg @ref DDL_GPIO_PIN_5 + * @arg @ref DDL_GPIO_PIN_6 + * @arg @ref DDL_GPIO_PIN_7 + * @arg @ref DDL_GPIO_PIN_8 + * @arg @ref DDL_GPIO_PIN_9 + * @arg @ref DDL_GPIO_PIN_10 + * @arg @ref DDL_GPIO_PIN_11 + * @arg @ref DDL_GPIO_PIN_12 + * @arg @ref DDL_GPIO_PIN_13 + * @arg @ref DDL_GPIO_PIN_14 + * @arg @ref DDL_GPIO_PIN_15 + * @arg @ref DDL_GPIO_PIN_ALL + * @retval None + */ +__STATIC_INLINE void DDL_GPIO_TogglePin(GPIO_TypeDef *GPIOx, uint32_t PinMask) +{ + uint32_t odr = READ_REG(GPIOx->ODATA); + WRITE_REG(GPIOx->BSC, ((odr & PinMask) << 16u) | (~odr & PinMask)); +} + +/** + * @} + */ + +#if defined(USE_FULL_DDL_DRIVER) +/** @defgroup GPIO_DDL_EF_Init Initialization and de-initialization functions + * @{ + */ + +ErrorStatus DDL_GPIO_DeInit(GPIO_TypeDef *GPIOx); +ErrorStatus DDL_GPIO_Init(GPIO_TypeDef *GPIOx, DDL_GPIO_InitTypeDef *GPIO_InitStruct); +void DDL_GPIO_StructInit(DDL_GPIO_InitTypeDef *GPIO_InitStruct); + +/** + * @} + */ +#endif /* USE_FULL_DDL_DRIVER */ + +/** + * @} + */ + +/** + * @} + */ + +#endif /* defined (GPIOA) || defined (GPIOB) || defined (GPIOC) || defined (GPIOD) || defined (GPIOE) || defined (GPIOF) || defined (GPIOG) || defined (GPIOH) || defined (GPIOI) || defined (GPIOJ) || defined (GPIOK) */ +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* APM32F4xx_DDL_GPIO_H */ + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_i2c.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_i2c.h new file mode 100644 index 0000000000..f880ed1e80 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_i2c.h @@ -0,0 +1,1786 @@ +/** + * + * @file apm32f4xx_ddl_i2c.h + * @brief Header file of I2C DDL module. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef APM32F4xx_DDL_I2C_H +#define APM32F4xx_DDL_I2C_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx.h" + +/** @addtogroup APM32F4xx_DDL_Driver + * @{ + */ + +#if defined (I2C1) || defined (I2C2) || defined (I2C3) + +/** @defgroup I2C_DDL I2C + * @{ + */ + +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ + +/* Private constants ---------------------------------------------------------*/ +/** @defgroup I2C_DDL_Private_Constants I2C Private Constants + * @{ + */ + +/* Defines used to perform compute and check in the macros */ +#define DDL_I2C_MAX_SPEED_STANDARD 100000U +#define DDL_I2C_MAX_SPEED_FAST 400000U +/** + * @} + */ + +/* Private macros ------------------------------------------------------------*/ +#if defined(USE_FULL_DDL_DRIVER) +/** @defgroup I2C_DDL_Private_Macros I2C Private Macros + * @{ + */ +/** + * @} + */ +#endif /*USE_FULL_DDL_DRIVER*/ + +/* Exported types ------------------------------------------------------------*/ +#if defined(USE_FULL_DDL_DRIVER) +/** @defgroup I2C_DDL_ES_INIT I2C Exported Init structure + * @{ + */ +typedef struct +{ + uint32_t PeripheralMode; /*!< Specifies the peripheral mode. + This parameter can be a value of @ref I2C_DDL_EC_PERIPHERAL_MODE + + This feature can be modified afterwards using unitary function @ref DDL_I2C_SetMode(). */ + + uint32_t ClockSpeed; /*!< Specifies the clock frequency. + This parameter must be set to a value lower than 400kHz (in Hz) + + This feature can be modified afterwards using unitary function @ref DDL_I2C_SetClockPeriod() + or @ref DDL_I2C_SetDutyCycle() or @ref DDL_I2C_SetClockSpeedMode() or @ref DDL_I2C_ConfigSpeed(). */ + + uint32_t DutyCycle; /*!< Specifies the I2C fast mode duty cycle. + This parameter can be a value of @ref I2C_DDL_EC_DUTYCYCLE + + This feature can be modified afterwards using unitary function @ref DDL_I2C_SetDutyCycle(). */ + +#if defined(I2C_FILTER_ANFDIS) && defined(I2C_FILTER_DNFCFG) + uint32_t AnalogFilter; /*!< Enables or disables analog noise filter. + This parameter can be a value of @ref I2C_DDL_EC_ANALOGFILTER_SELECTION + + This feature can be modified afterwards using unitary functions @ref DDL_I2C_EnableAnalogFilter() or DDL_I2C_DisableAnalogFilter(). */ + + uint32_t DigitalFilter; /*!< Configures the digital noise filter. + This parameter can be a number between Min_Data = 0x00 and Max_Data = 0x0F + + This feature can be modified afterwards using unitary function @ref DDL_I2C_SetDigitalFilter(). */ + +#endif /* I2C_FILTER_ANFDIS && I2C_FILTER_DNFCFG */ + uint32_t OwnAddress1; /*!< Specifies the device own address 1. + This parameter must be a value between Min_Data = 0x00 and Max_Data = 0x3FF + + This feature can be modified afterwards using unitary function @ref DDL_I2C_SetOwnAddress1(). */ + + uint32_t TypeAcknowledge; /*!< Specifies the ACKnowledge or Non ACKnowledge condition after the address receive match code or next received byte. + This parameter can be a value of @ref I2C_DDL_EC_I2C_ACKNOWLEDGE + + This feature can be modified afterwards using unitary function @ref DDL_I2C_AcknowledgeNextData(). */ + + uint32_t OwnAddrSize; /*!< Specifies the device own address 1 size (7-bit or 10-bit). + This parameter can be a value of @ref I2C_DDL_EC_OWNADDRESS1 + + This feature can be modified afterwards using unitary function @ref DDL_I2C_SetOwnAddress1(). */ +} DDL_I2C_InitTypeDef; +/** + * @} + */ +#endif /*USE_FULL_DDL_DRIVER*/ + +/* Exported constants --------------------------------------------------------*/ +/** @defgroup I2C_DDL_Exported_Constants I2C Exported Constants + * @{ + */ + +/** @defgroup I2C_DDL_EC_GET_FLAG Get Flags Defines + * @brief Flags defines which can be used with DDL_I2C_ReadReg function + * @{ + */ +#define DDL_I2C_STS1_STARTFLG I2C_STS1_STARTFLG /*!< Start Bit (master mode) */ +#define DDL_I2C_STS1_ADDRFLG I2C_STS1_ADDRFLG /*!< Address sent (master mode) or + Address matched flag (slave mode) */ +#define DDL_I2C_STS1_BTCFLG I2C_STS1_BTCFLG /*!< Byte Transfer Finished flag */ +#define DDL_I2C_STS1_ADDR10FLG I2C_STS1_ADDR10FLG /*!< 10-bit header sent (master mode) */ +#define DDL_I2C_STS1_STOPFLG I2C_STS1_STOPFLG /*!< Stop detection flag (slave mode) */ +#define DDL_I2C_STS1_RXBNEFLG I2C_STS1_RXBNEFLG /*!< Data register not empty (receivers) */ +#define DDL_I2C_STS1_TXBEFLG I2C_STS1_TXBEFLG /*!< Data register empty (transmitters) */ +#define DDL_I2C_STS1_BERRFLG I2C_STS1_BERRFLG /*!< Bus error */ +#define DDL_I2C_STS1_ALFLG I2C_STS1_ALFLG /*!< Arbitration lost */ +#define DDL_I2C_STS1_AEFLG I2C_STS1_AEFLG /*!< Acknowledge failure flag */ +#define DDL_I2C_STS1_OVRURFLG I2C_STS1_OVRURFLG /*!< Overrun/Underrun */ +#define DDL_I2C_STS1_PECEFLG I2C_ISR_PECERR /*!< PEC Error in reception (SMBus mode) */ +#define DDL_I2C_STS1_TTEFLG I2C_ISR_TIMEOUT /*!< Timeout detection flag (SMBus mode) */ +#define DDL_I2C_STS1_SMALERT I2C_ISR_SMALERT /*!< SMBus alert (SMBus mode) */ +#define DDL_I2C_STS2_MSFLG I2C_STS2_MSFLG /*!< Master/Slave flag */ +#define DDL_I2C_STS2_BUSBSYFLG I2C_STS2_BUSBSYFLG /*!< Bus busy flag */ +#define DDL_I2C_STS2_TRFLG I2C_STS2_TRFLG /*!< Transmitter/receiver direction */ +#define DDL_I2C_STS2_GENCALLFLG I2C_STS2_GENCALLFLG /*!< General call address (Slave mode) */ +#define DDL_I2C_STS2_SMBDADDRFLG I2C_STS2_SMBDADDRFLG /*!< SMBus Device default address (Slave mode) */ +#define DDL_I2C_STS2_SMMHADDR I2C_STS2_SMMHADDR /*!< SMBus Host address (Slave mode) */ +#define DDL_I2C_STS2_DUALADDRFLG I2C_STS2_DUALADDRFLG /*!< Dual flag (Slave mode) */ +/** + * @} + */ + +/** @defgroup I2C_DDL_EC_IT IT Defines + * @brief IT defines which can be used with DDL_I2C_ReadReg and DDL_I2C_WriteReg functions + * @{ + */ +#define DDL_I2C_CTRL2_EVIEN I2C_CTRL2_EVIEN /*!< Events interrupts enable */ +#define DDL_I2C_CTRL2_BUFIEN I2C_CTRL2_BUFIEN /*!< Buffer interrupts enable */ +#define DDL_I2C_CTRL2_ERRIEN I2C_CTRL2_ERRIEN /*!< Error interrupts enable */ +/** + * @} + */ + +#if defined(I2C_FILTER_ANFDIS) +/** @defgroup I2C_DDL_EC_ANALOGFILTER_SELECTION Analog Filter Selection + * @{ + */ +#define DDL_I2C_ANALOGFILTER_ENABLE 0x00000000U /*!< Analog filter is enabled. */ +#define DDL_I2C_ANALOGFILTER_DISABLE I2C_FILTER_ANFDIS /*!< Analog filter is disabled.*/ +/** + * @} + */ + +#endif +/** @defgroup I2C_DDL_EC_OWNADDRESS1 Own Address 1 Length + * @{ + */ +#define DDL_I2C_OWNADDRESS1_7BIT 0x00004000U /*!< Own address 1 is a 7-bit address. */ +#define DDL_I2C_OWNADDRESS1_10BIT (uint32_t)(I2C_SADDR1_ADDRLEN | 0x00004000U) /*!< Own address 1 is a 10-bit address. */ +/** + * @} + */ + +/** @defgroup I2C_DDL_EC_DUTYCYCLE Fast Mode Duty Cycle + * @{ + */ +#define DDL_I2C_DUTYCYCLE_2 0x00000000U /*!< I2C fast mode Tlow/Thigh = 2 */ +#define DDL_I2C_DUTYCYCLE_16_9 I2C_CLKCTRL_FDUTYCFG /*!< I2C fast mode Tlow/Thigh = 16/9 */ +/** + * @} + */ + +/** @defgroup I2C_DDL_EC_CLOCK_SPEED_MODE Master Clock Speed Mode + * @{ + */ +#define DDL_I2C_CLOCK_SPEED_STANDARD_MODE 0x00000000U /*!< Master clock speed range is standard mode */ +#define DDL_I2C_CLOCK_SPEED_FAST_MODE I2C_CLKCTRL_SPEEDCFG /*!< Master clock speed range is fast mode */ +/** + * @} + */ + +/** @defgroup I2C_DDL_EC_PERIPHERAL_MODE Peripheral Mode + * @{ + */ +#define DDL_I2C_MODE_I2C 0x00000000U /*!< I2C Master or Slave mode */ +#define DDL_I2C_MODE_SMBUS_HOST (uint32_t)(I2C_CTRL1_SMBEN | I2C_CTRL1_SMBTCFG | I2C_CTRL1_ARPEN) /*!< SMBus Host address acknowledge */ +#define DDL_I2C_MODE_SMBUS_DEVICE I2C_CTRL1_SMBEN /*!< SMBus Device default mode (Default address not acknowledge) */ +#define DDL_I2C_MODE_SMBUS_DEVICE_ARP (uint32_t)(I2C_CTRL1_SMBEN | I2C_CTRL1_ARPEN) /*!< SMBus Device Default address acknowledge */ +/** + * @} + */ + +/** @defgroup I2C_DDL_EC_I2C_ACKNOWLEDGE Acknowledge Generation + * @{ + */ +#define DDL_I2C_ACK I2C_CTRL1_ACKEN /*!< ACK is sent after current received byte. */ +#define DDL_I2C_NACK 0x00000000U /*!< NACK is sent after current received byte.*/ +/** + * @} + */ + +/** @defgroup I2C_DDL_EC_DIRECTION Read Write Direction + * @{ + */ +#define DDL_I2C_DIRECTION_WRITE I2C_STS2_TRFLG /*!< Bus is in write transfer */ +#define DDL_I2C_DIRECTION_READ 0x00000000U /*!< Bus is in read transfer */ +/** + * @} + */ + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ +/** @defgroup I2C_DDL_Exported_Macros I2C Exported Macros + * @{ + */ + +/** @defgroup I2C_DDL_EM_WRITE_READ Common Write and read registers Macros + * @{ + */ + +/** + * @brief Write a value in I2C register + * @param __INSTANCE__ I2C Instance + * @param __REG__ Register to be written + * @param __VALUE__ Value to be written in the register + * @retval None + */ +#define DDL_I2C_WriteReg(__INSTANCE__, __REG__, __VALUE__) WRITE_REG(__INSTANCE__->__REG__, (__VALUE__)) + +/** + * @brief Read a value in I2C register + * @param __INSTANCE__ I2C Instance + * @param __REG__ Register to be read + * @retval Register value + */ +#define DDL_I2C_ReadReg(__INSTANCE__, __REG__) READ_REG(__INSTANCE__->__REG__) +/** + * @} + */ + +/** @defgroup I2C_DDL_EM_Exported_Macros_Helper Exported_Macros_Helper + * @{ + */ + +/** + * @brief Convert Peripheral Clock Frequency in Mhz. + * @param __PCLK__ This parameter must be a value of peripheral clock (in Hz). + * @retval Value of peripheral clock (in Mhz) + */ +#define __DDL_I2C_FREQ_HZ_TO_MHZ(__PCLK__) (uint32_t)((__PCLK__)/1000000U) + +/** + * @brief Convert Peripheral Clock Frequency in Hz. + * @param __PCLK__ This parameter must be a value of peripheral clock (in Mhz). + * @retval Value of peripheral clock (in Hz) + */ +#define __DDL_I2C_FREQ_MHZ_TO_HZ(__PCLK__) (uint32_t)((__PCLK__)*1000000U) + +/** + * @brief Compute I2C Clock rising time. + * @param __FREQRANGE__ This parameter must be a value of peripheral clock (in Mhz). + * @param __SPEED__ This parameter must be a value lower than 400kHz (in Hz). + * @retval Value between Min_Data=0x02 and Max_Data=0x3F + */ +#define __DDL_I2C_RISE_TIME(__FREQRANGE__, __SPEED__) (uint32_t)(((__SPEED__) <= DDL_I2C_MAX_SPEED_STANDARD) ? ((__FREQRANGE__) + 1U) : ((((__FREQRANGE__) * 300U) / 1000U) + 1U)) + +/** + * @brief Compute Speed clock range to a Clock Control Register (I2C_CLKCTRL_CLKS) value. + * @param __PCLK__ This parameter must be a value of peripheral clock (in Hz). + * @param __SPEED__ This parameter must be a value lower than 400kHz (in Hz). + * @param __DUTYCYCLE__ This parameter can be one of the following values: + * @arg @ref DDL_I2C_DUTYCYCLE_2 + * @arg @ref DDL_I2C_DUTYCYCLE_16_9 + * @retval Value between Min_Data=0x004 and Max_Data=0xFFF, except in FAST DUTY mode where Min_Data=0x001. + */ +#define __DDL_I2C_SPEED_TO_CCR(__PCLK__, __SPEED__, __DUTYCYCLE__) (uint32_t)(((__SPEED__) <= DDL_I2C_MAX_SPEED_STANDARD)? \ + (__DDL_I2C_SPEED_STANDARD_TO_CCR((__PCLK__), (__SPEED__))) : \ + (__DDL_I2C_SPEED_FAST_TO_CCR((__PCLK__), (__SPEED__), (__DUTYCYCLE__)))) + +/** + * @brief Compute Speed Standard clock range to a Clock Control Register (I2C_CLKCTRL_CLKS) value. + * @param __PCLK__ This parameter must be a value of peripheral clock (in Hz). + * @param __SPEED__ This parameter must be a value lower than 100kHz (in Hz). + * @retval Value between Min_Data=0x004 and Max_Data=0xFFF. + */ +#define __DDL_I2C_SPEED_STANDARD_TO_CCR(__PCLK__, __SPEED__) (uint32_t)(((((__PCLK__)/((__SPEED__) << 1U)) & I2C_CLKCTRL_CLKS) < 4U)? 4U:((__PCLK__) / ((__SPEED__) << 1U))) + +/** + * @brief Compute Speed Fast clock range to a Clock Control Register (I2C_CLKCTRL_CLKS) value. + * @param __PCLK__ This parameter must be a value of peripheral clock (in Hz). + * @param __SPEED__ This parameter must be a value between Min_Data=100Khz and Max_Data=400Khz (in Hz). + * @param __DUTYCYCLE__ This parameter can be one of the following values: + * @arg @ref DDL_I2C_DUTYCYCLE_2 + * @arg @ref DDL_I2C_DUTYCYCLE_16_9 + * @retval Value between Min_Data=0x001 and Max_Data=0xFFF + */ +#define __DDL_I2C_SPEED_FAST_TO_CCR(__PCLK__, __SPEED__, __DUTYCYCLE__) (uint32_t)(((__DUTYCYCLE__) == DDL_I2C_DUTYCYCLE_2)? \ + (((((__PCLK__) / ((__SPEED__) * 3U)) & I2C_CLKCTRL_CLKS) == 0U)? 1U:((__PCLK__) / ((__SPEED__) * 3U))) : \ + (((((__PCLK__) / ((__SPEED__) * 25U)) & I2C_CLKCTRL_CLKS) == 0U)? 1U:((__PCLK__) / ((__SPEED__) * 25U)))) + +/** + * @brief Get the Least significant bits of a 10-Bits address. + * @param __ADDRESS__ This parameter must be a value of a 10-Bits slave address. + * @retval Value between Min_Data=0x00 and Max_Data=0xFF + */ +#define __DDL_I2C_10BIT_ADDRESS(__ADDRESS__) ((uint8_t)((uint16_t)((__ADDRESS__) & (uint16_t)(0x00FF)))) + +/** + * @brief Convert a 10-Bits address to a 10-Bits header with Write direction. + * @param __ADDRESS__ This parameter must be a value of a 10-Bits slave address. + * @retval Value between Min_Data=0xF0 and Max_Data=0xF6 + */ +#define __DDL_I2C_10BIT_HEADER_WRITE(__ADDRESS__) ((uint8_t)((uint16_t)((uint16_t)(((uint16_t)((__ADDRESS__) & (uint16_t)(0x0300))) >> 7) | (uint16_t)(0xF0)))) + +/** + * @brief Convert a 10-Bits address to a 10-Bits header with Read direction. + * @param __ADDRESS__ This parameter must be a value of a 10-Bits slave address. + * @retval Value between Min_Data=0xF1 and Max_Data=0xF7 + */ +#define __DDL_I2C_10BIT_HEADER_READ(__ADDRESS__) ((uint8_t)((uint16_t)((uint16_t)(((uint16_t)((__ADDRESS__) & (uint16_t)(0x0300))) >> 7) | (uint16_t)(0xF1)))) + +/** + * @} + */ + +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ + +/** @defgroup I2C_DDL_Exported_Functions I2C Exported Functions + * @{ + */ + +/** @defgroup I2C_DDL_EF_Configuration Configuration + * @{ + */ + +/** + * @brief Enable I2C peripheral (PE = 1). + * @param I2Cx I2C Instance. + * @retval None + */ +__STATIC_INLINE void DDL_I2C_Enable(I2C_TypeDef *I2Cx) +{ + SET_BIT(I2Cx->CTRL1, I2C_CTRL1_I2CEN); +} + +/** + * @brief Disable I2C peripheral (PE = 0). + * @param I2Cx I2C Instance. + * @retval None + */ +__STATIC_INLINE void DDL_I2C_Disable(I2C_TypeDef *I2Cx) +{ + CLEAR_BIT(I2Cx->CTRL1, I2C_CTRL1_I2CEN); +} + +/** + * @brief Check if the I2C peripheral is enabled or disabled. + * @param I2Cx I2C Instance. + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_I2C_IsEnabled(I2C_TypeDef *I2Cx) +{ + return (READ_BIT(I2Cx->CTRL1, I2C_CTRL1_I2CEN) == (I2C_CTRL1_I2CEN)); +} + +#if defined(I2C_FILTER_ANFDIS) && defined(I2C_FILTER_DNFCFG) +/** + * @brief Configure Noise Filters (Analog and Digital). + * @note If the analog filter is also enabled, the digital filter is added to analog filter. + * The filters can only be programmed when the I2C is disabled (PE = 0). + * @param I2Cx I2C Instance. + * @param AnalogFilter This parameter can be one of the following values: + * @arg @ref DDL_I2C_ANALOGFILTER_ENABLE + * @arg @ref DDL_I2C_ANALOGFILTER_DISABLE + * @param DigitalFilter This parameter must be a value between Min_Data=0x00 (Digital filter disabled) and Max_Data=0x0F (Digital filter enabled and filtering capability up to 15*TPCLK1) + * This parameter is used to configure the digital noise filter on SDA and SCL input. The digital filter will suppress the spikes with a length of up to DNF[3:0]*TPCLK1. + * @retval None + */ +__STATIC_INLINE void DDL_I2C_ConfigFilters(I2C_TypeDef *I2Cx, uint32_t AnalogFilter, uint32_t DigitalFilter) +{ + MODIFY_REG(I2Cx->FILTER, I2C_FILTER_ANFDIS | I2C_FILTER_DNFCFG, AnalogFilter | DigitalFilter); +} +#endif /* I2C_FILTER_ANFDIS && I2C_FILTER_DNFCFG */ +#if defined(I2C_FILTER_DNFCFG) + +/** + * @brief Configure Digital Noise Filter. + * @note If the analog filter is also enabled, the digital filter is added to analog filter. + * This filter can only be programmed when the I2C is disabled (PE = 0). + * @param I2Cx I2C Instance. + * @param DigitalFilter This parameter must be a value between Min_Data=0x00 (Digital filter disabled) and Max_Data=0x0F (Digital filter enabled and filtering capability up to 15*TPCLK1) + * This parameter is used to configure the digital noise filter on SDA and SCL input. The digital filter will suppress the spikes with a length of up to DNF[3:0]*TPCLK1. + * @retval None + */ +__STATIC_INLINE void DDL_I2C_SetDigitalFilter(I2C_TypeDef *I2Cx, uint32_t DigitalFilter) +{ + MODIFY_REG(I2Cx->FILTER, I2C_FILTER_DNFCFG, DigitalFilter); +} + +/** + * @brief Get the current Digital Noise Filter configuration. + * @param I2Cx I2C Instance. + * @retval Value between Min_Data=0x0 and Max_Data=0xF + */ +__STATIC_INLINE uint32_t DDL_I2C_GetDigitalFilter(I2C_TypeDef *I2Cx) +{ + return (uint32_t)(READ_BIT(I2Cx->FILTER, I2C_FILTER_DNFCFG)); +} +#endif /* I2C_FILTER_DNFCFG */ +#if defined(I2C_FILTER_ANFDIS) + +/** + * @brief Enable Analog Noise Filter. + * @note This filter can only be programmed when the I2C is disabled (PE = 0). + * @param I2Cx I2C Instance. + * @retval None + */ +__STATIC_INLINE void DDL_I2C_EnableAnalogFilter(I2C_TypeDef *I2Cx) +{ + CLEAR_BIT(I2Cx->FILTER, I2C_FILTER_ANFDIS); +} + +/** + * @brief Disable Analog Noise Filter. + * @note This filter can only be programmed when the I2C is disabled (PE = 0). + * @param I2Cx I2C Instance. + * @retval None + */ +__STATIC_INLINE void DDL_I2C_DisableAnalogFilter(I2C_TypeDef *I2Cx) +{ + SET_BIT(I2Cx->FILTER, I2C_FILTER_ANFDIS); +} + +/** + * @brief Check if Analog Noise Filter is enabled or disabled. + * @param I2Cx I2C Instance. + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_I2C_IsEnabledAnalogFilter(I2C_TypeDef *I2Cx) +{ + return (READ_BIT(I2Cx->FILTER, I2C_FILTER_ANFDIS) == (I2C_FILTER_ANFDIS)); +} +#endif /* I2C_FILTER_ANFDIS */ + +/** + * @brief Enable DMA transmission requests. + * @param I2Cx I2C Instance. + * @retval None + */ +__STATIC_INLINE void DDL_I2C_EnableDMAReq_TX(I2C_TypeDef *I2Cx) +{ + SET_BIT(I2Cx->CTRL2, I2C_CTRL2_DMAEN); +} + +/** + * @brief Disable DMA transmission requests. + * @param I2Cx I2C Instance. + * @retval None + */ +__STATIC_INLINE void DDL_I2C_DisableDMAReq_TX(I2C_TypeDef *I2Cx) +{ + CLEAR_BIT(I2Cx->CTRL2, I2C_CTRL2_DMAEN); +} + +/** + * @brief Check if DMA transmission requests are enabled or disabled. + * @param I2Cx I2C Instance. + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_I2C_IsEnabledDMAReq_TX(I2C_TypeDef *I2Cx) +{ + return (READ_BIT(I2Cx->CTRL2, I2C_CTRL2_DMAEN) == (I2C_CTRL2_DMAEN)); +} + +/** + * @brief Enable DMA reception requests. + * @param I2Cx I2C Instance. + * @retval None + */ +__STATIC_INLINE void DDL_I2C_EnableDMAReq_RX(I2C_TypeDef *I2Cx) +{ + SET_BIT(I2Cx->CTRL2, I2C_CTRL2_DMAEN); +} + +/** + * @brief Disable DMA reception requests. + * @param I2Cx I2C Instance. + * @retval None + */ +__STATIC_INLINE void DDL_I2C_DisableDMAReq_RX(I2C_TypeDef *I2Cx) +{ + CLEAR_BIT(I2Cx->CTRL2, I2C_CTRL2_DMAEN); +} + +/** + * @brief Check if DMA reception requests are enabled or disabled. + * @param I2Cx I2C Instance. + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_I2C_IsEnabledDMAReq_RX(I2C_TypeDef *I2Cx) +{ + return (READ_BIT(I2Cx->CTRL2, I2C_CTRL2_DMAEN) == (I2C_CTRL2_DMAEN)); +} + +/** + * @brief Get the data register address used for DMA transfer. + * @param I2Cx I2C Instance. + * @retval Address of data register + */ +__STATIC_INLINE uint32_t DDL_I2C_DMA_GetRegAddr(I2C_TypeDef *I2Cx) +{ + return (uint32_t) & (I2Cx->DATA); +} + +/** + * @brief Enable Clock stretching. + * @note This bit can only be programmed when the I2C is disabled (PE = 0). + * @param I2Cx I2C Instance. + * @retval None + */ +__STATIC_INLINE void DDL_I2C_EnableClockStretching(I2C_TypeDef *I2Cx) +{ + CLEAR_BIT(I2Cx->CTRL1, I2C_CTRL1_CLKSTRETCHD); +} + +/** + * @brief Disable Clock stretching. + * @note This bit can only be programmed when the I2C is disabled (PE = 0). + * @param I2Cx I2C Instance. + * @retval None + */ +__STATIC_INLINE void DDL_I2C_DisableClockStretching(I2C_TypeDef *I2Cx) +{ + SET_BIT(I2Cx->CTRL1, I2C_CTRL1_CLKSTRETCHD); +} + +/** + * @brief Check if Clock stretching is enabled or disabled. + * @param I2Cx I2C Instance. + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_I2C_IsEnabledClockStretching(I2C_TypeDef *I2Cx) +{ + return (READ_BIT(I2Cx->CTRL1, I2C_CTRL1_CLKSTRETCHD) != (I2C_CTRL1_CLKSTRETCHD)); +} + +/** + * @brief Enable General Call. + * @note When enabled the Address 0x00 is ACKed. + * @param I2Cx I2C Instance. + * @retval None + */ +__STATIC_INLINE void DDL_I2C_EnableGeneralCall(I2C_TypeDef *I2Cx) +{ + SET_BIT(I2Cx->CTRL1, I2C_CTRL1_SRBEN); +} + +/** + * @brief Disable General Call. + * @note When disabled the Address 0x00 is NACKed. + * @param I2Cx I2C Instance. + * @retval None + */ +__STATIC_INLINE void DDL_I2C_DisableGeneralCall(I2C_TypeDef *I2Cx) +{ + CLEAR_BIT(I2Cx->CTRL1, I2C_CTRL1_SRBEN); +} + +/** + * @brief Check if General Call is enabled or disabled. + * @param I2Cx I2C Instance. + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_I2C_IsEnabledGeneralCall(I2C_TypeDef *I2Cx) +{ + return (READ_BIT(I2Cx->CTRL1, I2C_CTRL1_SRBEN) == (I2C_CTRL1_SRBEN)); +} + +/** + * @brief Set the Own Address1. + * @param I2Cx I2C Instance. + * @param OwnAddress1 This parameter must be a value between Min_Data=0 and Max_Data=0x3FF. + * @param OwnAddrSize This parameter can be one of the following values: + * @arg @ref DDL_I2C_OWNADDRESS1_7BIT + * @arg @ref DDL_I2C_OWNADDRESS1_10BIT + * @retval None + */ +__STATIC_INLINE void DDL_I2C_SetOwnAddress1(I2C_TypeDef *I2Cx, uint32_t OwnAddress1, uint32_t OwnAddrSize) +{ + MODIFY_REG(I2Cx->SADDR1, I2C_SADDR1_ADDR0 | I2C_SADDR1_ADDR1_7 | I2C_SADDR1_ADDR8_9 | I2C_SADDR1_ADDRLEN, OwnAddress1 | OwnAddrSize); +} + +/** + * @brief Set the 7bits Own Address2. + * @note This action has no effect if own address2 is enabled. + * @param I2Cx I2C Instance. + * @param OwnAddress2 This parameter must be a value between Min_Data=0 and Max_Data=0x7F. + * @retval None + */ +__STATIC_INLINE void DDL_I2C_SetOwnAddress2(I2C_TypeDef *I2Cx, uint32_t OwnAddress2) +{ + MODIFY_REG(I2Cx->SADDR2, I2C_SADDR2_ADDR2, OwnAddress2); +} + +/** + * @brief Enable acknowledge on Own Address2 match address. + * @param I2Cx I2C Instance. + * @retval None + */ +__STATIC_INLINE void DDL_I2C_EnableOwnAddress2(I2C_TypeDef *I2Cx) +{ + SET_BIT(I2Cx->SADDR2, I2C_SADDR2_ADDRNUM); +} + +/** + * @brief Disable acknowledge on Own Address2 match address. + * @param I2Cx I2C Instance. + * @retval None + */ +__STATIC_INLINE void DDL_I2C_DisableOwnAddress2(I2C_TypeDef *I2Cx) +{ + CLEAR_BIT(I2Cx->SADDR2, I2C_SADDR2_ADDRNUM); +} + +/** + * @brief Check if Own Address1 acknowledge is enabled or disabled. + * @param I2Cx I2C Instance. + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_I2C_IsEnabledOwnAddress2(I2C_TypeDef *I2Cx) +{ + return (READ_BIT(I2Cx->SADDR2, I2C_SADDR2_ADDRNUM) == (I2C_SADDR2_ADDRNUM)); +} + +/** + * @brief Configure the Peripheral clock frequency. + * @param I2Cx I2C Instance. + * @param PeriphClock Peripheral Clock (in Hz) + * @retval None + */ +__STATIC_INLINE void DDL_I2C_SetPeriphClock(I2C_TypeDef *I2Cx, uint32_t PeriphClock) +{ + MODIFY_REG(I2Cx->CTRL2, I2C_CTRL2_CLKFCFG, __DDL_I2C_FREQ_HZ_TO_MHZ(PeriphClock)); +} + +/** + * @brief Get the Peripheral clock frequency. + * @param I2Cx I2C Instance. + * @retval Value of Peripheral Clock (in Hz) + */ +__STATIC_INLINE uint32_t DDL_I2C_GetPeriphClock(I2C_TypeDef *I2Cx) +{ + return (uint32_t)(__DDL_I2C_FREQ_MHZ_TO_HZ(READ_BIT(I2Cx->CTRL2, I2C_CTRL2_CLKFCFG))); +} + +/** + * @brief Configure the Duty cycle (Fast mode only). + * @param I2Cx I2C Instance. + * @param DutyCycle This parameter can be one of the following values: + * @arg @ref DDL_I2C_DUTYCYCLE_2 + * @arg @ref DDL_I2C_DUTYCYCLE_16_9 + * @retval None + */ +__STATIC_INLINE void DDL_I2C_SetDutyCycle(I2C_TypeDef *I2Cx, uint32_t DutyCycle) +{ + MODIFY_REG(I2Cx->CLKCTRL, I2C_CLKCTRL_FDUTYCFG, DutyCycle); +} + +/** + * @brief Get the Duty cycle (Fast mode only). + * @param I2Cx I2C Instance. + * @retval Returned value can be one of the following values: + * @arg @ref DDL_I2C_DUTYCYCLE_2 + * @arg @ref DDL_I2C_DUTYCYCLE_16_9 + */ +__STATIC_INLINE uint32_t DDL_I2C_GetDutyCycle(I2C_TypeDef *I2Cx) +{ + return (uint32_t)(READ_BIT(I2Cx->CLKCTRL, I2C_CLKCTRL_FDUTYCFG)); +} + +/** + * @brief Configure the I2C master clock speed mode. + * @param I2Cx I2C Instance. + * @param ClockSpeedMode This parameter can be one of the following values: + * @arg @ref DDL_I2C_CLOCK_SPEED_STANDARD_MODE + * @arg @ref DDL_I2C_CLOCK_SPEED_FAST_MODE + * @retval None + */ +__STATIC_INLINE void DDL_I2C_SetClockSpeedMode(I2C_TypeDef *I2Cx, uint32_t ClockSpeedMode) +{ + MODIFY_REG(I2Cx->CLKCTRL, I2C_CLKCTRL_SPEEDCFG, ClockSpeedMode); +} + +/** + * @brief Get the the I2C master speed mode. + * @param I2Cx I2C Instance. + * @retval Returned value can be one of the following values: + * @arg @ref DDL_I2C_CLOCK_SPEED_STANDARD_MODE + * @arg @ref DDL_I2C_CLOCK_SPEED_FAST_MODE + */ +__STATIC_INLINE uint32_t DDL_I2C_GetClockSpeedMode(I2C_TypeDef *I2Cx) +{ + return (uint32_t)(READ_BIT(I2Cx->CLKCTRL, I2C_CLKCTRL_SPEEDCFG)); +} + +/** + * @brief Configure the SCL, SDA rising time. + * @note This bit can only be programmed when the I2C is disabled (PE = 0). + * @param I2Cx I2C Instance. + * @param RiseTime This parameter must be a value between Min_Data=0x02 and Max_Data=0x3F. + * @retval None + */ +__STATIC_INLINE void DDL_I2C_SetRiseTime(I2C_TypeDef *I2Cx, uint32_t RiseTime) +{ + MODIFY_REG(I2Cx->RISETMAX, I2C_RISETMAX_RISETMAX, RiseTime); +} + +/** + * @brief Get the SCL, SDA rising time. + * @param I2Cx I2C Instance. + * @retval Value between Min_Data=0x02 and Max_Data=0x3F + */ +__STATIC_INLINE uint32_t DDL_I2C_GetRiseTime(I2C_TypeDef *I2Cx) +{ + return (uint32_t)(READ_BIT(I2Cx->RISETMAX, I2C_RISETMAX_RISETMAX)); +} + +/** + * @brief Configure the SCL high and low period. + * @note This bit can only be programmed when the I2C is disabled (PE = 0). + * @param I2Cx I2C Instance. + * @param ClockPeriod This parameter must be a value between Min_Data=0x004 and Max_Data=0xFFF, except in FAST DUTY mode where Min_Data=0x001. + * @retval None + */ +__STATIC_INLINE void DDL_I2C_SetClockPeriod(I2C_TypeDef *I2Cx, uint32_t ClockPeriod) +{ + MODIFY_REG(I2Cx->CLKCTRL, I2C_CLKCTRL_CLKS, ClockPeriod); +} + +/** + * @brief Get the SCL high and low period. + * @param I2Cx I2C Instance. + * @retval Value between Min_Data=0x004 and Max_Data=0xFFF, except in FAST DUTY mode where Min_Data=0x001. + */ +__STATIC_INLINE uint32_t DDL_I2C_GetClockPeriod(I2C_TypeDef *I2Cx) +{ + return (uint32_t)(READ_BIT(I2Cx->CLKCTRL, I2C_CLKCTRL_CLKS)); +} + +/** + * @brief Configure the SCL speed. + * @note This bit can only be programmed when the I2C is disabled (PE = 0). + * @param I2Cx I2C Instance. + * @param PeriphClock Peripheral Clock (in Hz) + * @param ClockSpeed This parameter must be a value lower than 400kHz (in Hz). + * @param DutyCycle This parameter can be one of the following values: + * @arg @ref DDL_I2C_DUTYCYCLE_2 + * @arg @ref DDL_I2C_DUTYCYCLE_16_9 + * @retval None + */ +__STATIC_INLINE void DDL_I2C_ConfigSpeed(I2C_TypeDef *I2Cx, uint32_t PeriphClock, uint32_t ClockSpeed, + uint32_t DutyCycle) +{ + uint32_t freqrange = 0x0U; + uint32_t clockconfig = 0x0U; + + /* Compute frequency range */ + freqrange = __DDL_I2C_FREQ_HZ_TO_MHZ(PeriphClock); + + /* Configure I2Cx: Frequency range register */ + MODIFY_REG(I2Cx->CTRL2, I2C_CTRL2_CLKFCFG, freqrange); + + /* Configure I2Cx: Rise Time register */ + MODIFY_REG(I2Cx->RISETMAX, I2C_RISETMAX_RISETMAX, __DDL_I2C_RISE_TIME(freqrange, ClockSpeed)); + + /* Configure Speed mode, Duty Cycle and Clock control register value */ + if (ClockSpeed > DDL_I2C_MAX_SPEED_STANDARD) + { + /* Set Speed mode at fast and duty cycle for Clock Speed request in fast clock range */ + clockconfig = DDL_I2C_CLOCK_SPEED_FAST_MODE | \ + __DDL_I2C_SPEED_FAST_TO_CCR(PeriphClock, ClockSpeed, DutyCycle) | \ + DutyCycle; + } + else + { + /* Set Speed mode at standard for Clock Speed request in standard clock range */ + clockconfig = DDL_I2C_CLOCK_SPEED_STANDARD_MODE | \ + __DDL_I2C_SPEED_STANDARD_TO_CCR(PeriphClock, ClockSpeed); + } + + /* Configure I2Cx: Clock control register */ + MODIFY_REG(I2Cx->CLKCTRL, (I2C_CLKCTRL_SPEEDCFG | I2C_CLKCTRL_FDUTYCFG | I2C_CLKCTRL_CLKS), clockconfig); +} + +/** + * @brief Configure peripheral mode. + * @note Macro @ref IS_SMBUS_ALL_INSTANCE(I2Cx) can be used to check whether or not + * SMBus feature is supported by the I2Cx Instance. + * @param I2Cx I2C Instance. + * @param PeripheralMode This parameter can be one of the following values: + * @arg @ref DDL_I2C_MODE_I2C + * @arg @ref DDL_I2C_MODE_SMBUS_HOST + * @arg @ref DDL_I2C_MODE_SMBUS_DEVICE + * @arg @ref DDL_I2C_MODE_SMBUS_DEVICE_ARP + * @retval None + */ +__STATIC_INLINE void DDL_I2C_SetMode(I2C_TypeDef *I2Cx, uint32_t PeripheralMode) +{ + MODIFY_REG(I2Cx->CTRL1, I2C_CTRL1_SMBEN | I2C_CTRL1_SMBTCFG | I2C_CTRL1_ARPEN, PeripheralMode); +} + +/** + * @brief Get peripheral mode. + * @note Macro @ref IS_SMBUS_ALL_INSTANCE(I2Cx) can be used to check whether or not + * SMBus feature is supported by the I2Cx Instance. + * @param I2Cx I2C Instance. + * @retval Returned value can be one of the following values: + * @arg @ref DDL_I2C_MODE_I2C + * @arg @ref DDL_I2C_MODE_SMBUS_HOST + * @arg @ref DDL_I2C_MODE_SMBUS_DEVICE + * @arg @ref DDL_I2C_MODE_SMBUS_DEVICE_ARP + */ +__STATIC_INLINE uint32_t DDL_I2C_GetMode(I2C_TypeDef *I2Cx) +{ + return (uint32_t)(READ_BIT(I2Cx->CTRL1, I2C_CTRL1_SMBEN | I2C_CTRL1_SMBTCFG | I2C_CTRL1_ARPEN)); +} + +/** + * @brief Enable SMBus alert (Host or Device mode) + * @note Macro @ref IS_SMBUS_ALL_INSTANCE(I2Cx) can be used to check whether or not + * SMBus feature is supported by the I2Cx Instance. + * @note SMBus Device mode: + * - SMBus Alert pin is drived low and + * Alert Response Address Header acknowledge is enabled. + * SMBus Host mode: + * - SMBus Alert pin management is supported. + * @param I2Cx I2C Instance. + * @retval None + */ +__STATIC_INLINE void DDL_I2C_EnableSMBusAlert(I2C_TypeDef *I2Cx) +{ + SET_BIT(I2Cx->CTRL1, I2C_CTRL1_ALERTEN); +} + +/** + * @brief Disable SMBus alert (Host or Device mode) + * @note Macro @ref IS_SMBUS_ALL_INSTANCE(I2Cx) can be used to check whether or not + * SMBus feature is supported by the I2Cx Instance. + * @note SMBus Device mode: + * - SMBus Alert pin is not drived (can be used as a standard GPIO) and + * Alert Response Address Header acknowledge is disabled. + * SMBus Host mode: + * - SMBus Alert pin management is not supported. + * @param I2Cx I2C Instance. + * @retval None + */ +__STATIC_INLINE void DDL_I2C_DisableSMBusAlert(I2C_TypeDef *I2Cx) +{ + CLEAR_BIT(I2Cx->CTRL1, I2C_CTRL1_ALERTEN); +} + +/** + * @brief Check if SMBus alert (Host or Device mode) is enabled or disabled. + * @note Macro @ref IS_SMBUS_ALL_INSTANCE(I2Cx) can be used to check whether or not + * SMBus feature is supported by the I2Cx Instance. + * @param I2Cx I2C Instance. + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_I2C_IsEnabledSMBusAlert(I2C_TypeDef *I2Cx) +{ + return (READ_BIT(I2Cx->CTRL1, I2C_CTRL1_ALERTEN) == (I2C_CTRL1_ALERTEN)); +} + +/** + * @brief Enable SMBus Packet Error Calculation (PEC). + * @note Macro @ref IS_SMBUS_ALL_INSTANCE(I2Cx) can be used to check whether or not + * SMBus feature is supported by the I2Cx Instance. + * @param I2Cx I2C Instance. + * @retval None + */ +__STATIC_INLINE void DDL_I2C_EnableSMBusPEC(I2C_TypeDef *I2Cx) +{ + SET_BIT(I2Cx->CTRL1, I2C_CTRL1_PECEN); +} + +/** + * @brief Disable SMBus Packet Error Calculation (PEC). + * @note Macro @ref IS_SMBUS_ALL_INSTANCE(I2Cx) can be used to check whether or not + * SMBus feature is supported by the I2Cx Instance. + * @param I2Cx I2C Instance. + * @retval None + */ +__STATIC_INLINE void DDL_I2C_DisableSMBusPEC(I2C_TypeDef *I2Cx) +{ + CLEAR_BIT(I2Cx->CTRL1, I2C_CTRL1_PECEN); +} + +/** + * @brief Check if SMBus Packet Error Calculation (PEC) is enabled or disabled. + * @note Macro @ref IS_SMBUS_ALL_INSTANCE(I2Cx) can be used to check whether or not + * SMBus feature is supported by the I2Cx Instance. + * @param I2Cx I2C Instance. + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_I2C_IsEnabledSMBusPEC(I2C_TypeDef *I2Cx) +{ + return (READ_BIT(I2Cx->CTRL1, I2C_CTRL1_PECEN) == (I2C_CTRL1_PECEN)); +} + +/** + * @} + */ + +/** @defgroup I2C_DDL_EF_IT_Management IT_Management + * @{ + */ + +/** + * @brief Enable TXE interrupt. + * @param I2Cx I2C Instance. + * @retval None + */ +__STATIC_INLINE void DDL_I2C_EnableIT_TX(I2C_TypeDef *I2Cx) +{ + SET_BIT(I2Cx->CTRL2, I2C_CTRL2_EVIEN | I2C_CTRL2_BUFIEN); +} + +/** + * @brief Disable TXE interrupt. + * @param I2Cx I2C Instance. + * @retval None + */ +__STATIC_INLINE void DDL_I2C_DisableIT_TX(I2C_TypeDef *I2Cx) +{ + CLEAR_BIT(I2Cx->CTRL2, I2C_CTRL2_EVIEN | I2C_CTRL2_BUFIEN); +} + +/** + * @brief Check if the TXE Interrupt is enabled or disabled. + * @param I2Cx I2C Instance. + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_I2C_IsEnabledIT_TX(I2C_TypeDef *I2Cx) +{ + return (READ_BIT(I2Cx->CTRL2, I2C_CTRL2_EVIEN | I2C_CTRL2_BUFIEN) == (I2C_CTRL2_EVIEN | I2C_CTRL2_BUFIEN)); +} + +/** + * @brief Enable RXNE interrupt. + * @param I2Cx I2C Instance. + * @retval None + */ +__STATIC_INLINE void DDL_I2C_EnableIT_RX(I2C_TypeDef *I2Cx) +{ + SET_BIT(I2Cx->CTRL2, I2C_CTRL2_EVIEN | I2C_CTRL2_BUFIEN); +} + +/** + * @brief Disable RXNE interrupt. + * @param I2Cx I2C Instance. + * @retval None + */ +__STATIC_INLINE void DDL_I2C_DisableIT_RX(I2C_TypeDef *I2Cx) +{ + CLEAR_BIT(I2Cx->CTRL2, I2C_CTRL2_EVIEN | I2C_CTRL2_BUFIEN); +} + +/** + * @brief Check if the RXNE Interrupt is enabled or disabled. + * @param I2Cx I2C Instance. + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_I2C_IsEnabledIT_RX(I2C_TypeDef *I2Cx) +{ + return (READ_BIT(I2Cx->CTRL2, I2C_CTRL2_EVIEN | I2C_CTRL2_BUFIEN) == (I2C_CTRL2_EVIEN | I2C_CTRL2_BUFIEN)); +} + +/** + * @brief Enable Events interrupts. + * @note Any of these events will generate interrupt : + * Start Bit (SB) + * Address sent, Address matched (ADDR) + * 10-bit header sent (ADD10) + * Stop detection (STOPF) + * Byte transfer finished (BTF) + * + * @note Any of these events will generate interrupt if Buffer interrupts are enabled too(using unitary function @ref DDL_I2C_EnableIT_BUF()) : + * Receive buffer not empty (RXNE) + * Transmit buffer empty (TXE) + * @param I2Cx I2C Instance. + * @retval None + */ +__STATIC_INLINE void DDL_I2C_EnableIT_EVT(I2C_TypeDef *I2Cx) +{ + SET_BIT(I2Cx->CTRL2, I2C_CTRL2_EVIEN); +} + +/** + * @brief Disable Events interrupts. + * @note Any of these events will generate interrupt : + * Start Bit (SB) + * Address sent, Address matched (ADDR) + * 10-bit header sent (ADD10) + * Stop detection (STOPF) + * Byte transfer finished (BTF) + * Receive buffer not empty (RXNE) + * Transmit buffer empty (TXE) + * @param I2Cx I2C Instance. + * @retval None + */ +__STATIC_INLINE void DDL_I2C_DisableIT_EVT(I2C_TypeDef *I2Cx) +{ + CLEAR_BIT(I2Cx->CTRL2, I2C_CTRL2_EVIEN); +} + +/** + * @brief Check if Events interrupts are enabled or disabled. + * @param I2Cx I2C Instance. + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_I2C_IsEnabledIT_EVT(I2C_TypeDef *I2Cx) +{ + return (READ_BIT(I2Cx->CTRL2, I2C_CTRL2_EVIEN) == (I2C_CTRL2_EVIEN)); +} + +/** + * @brief Enable Buffer interrupts. + * @note Any of these Buffer events will generate interrupt if Events interrupts are enabled too(using unitary function @ref DDL_I2C_EnableIT_EVT()) : + * Receive buffer not empty (RXNE) + * Transmit buffer empty (TXE) + * @param I2Cx I2C Instance. + * @retval None + */ +__STATIC_INLINE void DDL_I2C_EnableIT_BUF(I2C_TypeDef *I2Cx) +{ + SET_BIT(I2Cx->CTRL2, I2C_CTRL2_BUFIEN); +} + +/** + * @brief Disable Buffer interrupts. + * @note Any of these Buffer events will generate interrupt : + * Receive buffer not empty (RXNE) + * Transmit buffer empty (TXE) + * @param I2Cx I2C Instance. + * @retval None + */ +__STATIC_INLINE void DDL_I2C_DisableIT_BUF(I2C_TypeDef *I2Cx) +{ + CLEAR_BIT(I2Cx->CTRL2, I2C_CTRL2_BUFIEN); +} + +/** + * @brief Check if Buffer interrupts are enabled or disabled. + * @param I2Cx I2C Instance. + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_I2C_IsEnabledIT_BUF(I2C_TypeDef *I2Cx) +{ + return (READ_BIT(I2Cx->CTRL2, I2C_CTRL2_BUFIEN) == (I2C_CTRL2_BUFIEN)); +} + +/** + * @brief Enable Error interrupts. + * @note Macro @ref IS_SMBUS_ALL_INSTANCE(I2Cx) can be used to check whether or not + * SMBus feature is supported by the I2Cx Instance. + * @note Any of these errors will generate interrupt : + * Bus Error detection (BERR) + * Arbitration Loss (ARLO) + * Acknowledge Failure(AF) + * Overrun/Underrun (OVR) + * SMBus Timeout detection (TIMEOUT) + * SMBus PEC error detection (PECERR) + * SMBus Alert pin event detection (SMBALERT) + * @param I2Cx I2C Instance. + * @retval None + */ +__STATIC_INLINE void DDL_I2C_EnableIT_ERR(I2C_TypeDef *I2Cx) +{ + SET_BIT(I2Cx->CTRL2, I2C_CTRL2_ERRIEN); +} + +/** + * @brief Disable Error interrupts. + * @note Macro @ref IS_SMBUS_ALL_INSTANCE(I2Cx) can be used to check whether or not + * SMBus feature is supported by the I2Cx Instance. + * @note Any of these errors will generate interrupt : + * Bus Error detection (BERR) + * Arbitration Loss (ARLO) + * Acknowledge Failure(AF) + * Overrun/Underrun (OVR) + * SMBus Timeout detection (TIMEOUT) + * SMBus PEC error detection (PECERR) + * SMBus Alert pin event detection (SMBALERT) + * @param I2Cx I2C Instance. + * @retval None + */ +__STATIC_INLINE void DDL_I2C_DisableIT_ERR(I2C_TypeDef *I2Cx) +{ + CLEAR_BIT(I2Cx->CTRL2, I2C_CTRL2_ERRIEN); +} + +/** + * @brief Check if Error interrupts are enabled or disabled. + * @param I2Cx I2C Instance. + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_I2C_IsEnabledIT_ERR(I2C_TypeDef *I2Cx) +{ + return (READ_BIT(I2Cx->CTRL2, I2C_CTRL2_ERRIEN) == (I2C_CTRL2_ERRIEN)); +} + +/** + * @} + */ + +/** @defgroup I2C_DDL_EF_FLAG_management FLAG_management + * @{ + */ + +/** + * @brief Indicate the status of Transmit data register empty flag. + * @note RESET: When next data is written in Transmit data register. + * SET: When Transmit data register is empty. + * @param I2Cx I2C Instance. + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_I2C_IsActiveFlag_TXE(I2C_TypeDef *I2Cx) +{ + return (READ_BIT(I2Cx->STS1, I2C_STS1_TXBEFLG) == (I2C_STS1_TXBEFLG)); +} + +/** + * @brief Indicate the status of Byte Transfer Finished flag. + * RESET: When Data byte transfer not done. + * SET: When Data byte transfer succeeded. + * @param I2Cx I2C Instance. + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_I2C_IsActiveFlag_BTF(I2C_TypeDef *I2Cx) +{ + return (READ_BIT(I2Cx->STS1, I2C_STS1_BTCFLG) == (I2C_STS1_BTCFLG)); +} + +/** + * @brief Indicate the status of Receive data register not empty flag. + * @note RESET: When Receive data register is read. + * SET: When the received data is copied in Receive data register. + * @param I2Cx I2C Instance. + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_I2C_IsActiveFlag_RXNE(I2C_TypeDef *I2Cx) +{ + return (READ_BIT(I2Cx->STS1, I2C_STS1_RXBNEFLG) == (I2C_STS1_RXBNEFLG)); +} + +/** + * @brief Indicate the status of Start Bit (master mode). + * @note RESET: When No Start condition. + * SET: When Start condition is generated. + * @param I2Cx I2C Instance. + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_I2C_IsActiveFlag_SB(I2C_TypeDef *I2Cx) +{ + return (READ_BIT(I2Cx->STS1, I2C_STS1_STARTFLG) == (I2C_STS1_STARTFLG)); +} + +/** + * @brief Indicate the status of Address sent (master mode) or Address matched flag (slave mode). + * @note RESET: Clear default value. + * SET: When the address is fully sent (master mode) or when the received slave address matched with one of the enabled slave address (slave mode). + * @param I2Cx I2C Instance. + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_I2C_IsActiveFlag_ADDR(I2C_TypeDef *I2Cx) +{ + return (READ_BIT(I2Cx->STS1, I2C_STS1_ADDRFLG) == (I2C_STS1_ADDRFLG)); +} + +/** + * @brief Indicate the status of 10-bit header sent (master mode). + * @note RESET: When no ADD10 event occurred. + * SET: When the master has sent the first address byte (header). + * @param I2Cx I2C Instance. + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_I2C_IsActiveFlag_ADD10(I2C_TypeDef *I2Cx) +{ + return (READ_BIT(I2Cx->STS1, I2C_STS1_ADDR10FLG) == (I2C_STS1_ADDR10FLG)); +} + +/** + * @brief Indicate the status of Acknowledge failure flag. + * @note RESET: No acknowledge failure. + * SET: When an acknowledge failure is received after a byte transmission. + * @param I2Cx I2C Instance. + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_I2C_IsActiveFlag_AF(I2C_TypeDef *I2Cx) +{ + return (READ_BIT(I2Cx->STS1, I2C_STS1_AEFLG) == (I2C_STS1_AEFLG)); +} + +/** + * @brief Indicate the status of Stop detection flag (slave mode). + * @note RESET: Clear default value. + * SET: When a Stop condition is detected. + * @param I2Cx I2C Instance. + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_I2C_IsActiveFlag_STOP(I2C_TypeDef *I2Cx) +{ + return (READ_BIT(I2Cx->STS1, I2C_STS1_STOPFLG) == (I2C_STS1_STOPFLG)); +} + +/** + * @brief Indicate the status of Bus error flag. + * @note RESET: Clear default value. + * SET: When a misplaced Start or Stop condition is detected. + * @param I2Cx I2C Instance. + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_I2C_IsActiveFlag_BERR(I2C_TypeDef *I2Cx) +{ + return (READ_BIT(I2Cx->STS1, I2C_STS1_BERRFLG) == (I2C_STS1_BERRFLG)); +} + +/** + * @brief Indicate the status of Arbitration lost flag. + * @note RESET: Clear default value. + * SET: When arbitration lost. + * @param I2Cx I2C Instance. + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_I2C_IsActiveFlag_ARLO(I2C_TypeDef *I2Cx) +{ + return (READ_BIT(I2Cx->STS1, I2C_STS1_ALFLG) == (I2C_STS1_ALFLG)); +} + +/** + * @brief Indicate the status of Overrun/Underrun flag. + * @note RESET: Clear default value. + * SET: When an overrun/underrun error occurs (Clock Stretching Disabled). + * @param I2Cx I2C Instance. + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_I2C_IsActiveFlag_OVR(I2C_TypeDef *I2Cx) +{ + return (READ_BIT(I2Cx->STS1, I2C_STS1_OVRURFLG) == (I2C_STS1_OVRURFLG)); +} + +/** + * @brief Indicate the status of SMBus PEC error flag in reception. + * @note Macro @ref IS_SMBUS_ALL_INSTANCE(I2Cx) can be used to check whether or not + * SMBus feature is supported by the I2Cx Instance. + * @param I2Cx I2C Instance. + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_I2C_IsActiveSMBusFlag_PECERR(I2C_TypeDef *I2Cx) +{ + return (READ_BIT(I2Cx->STS1, I2C_STS1_PECEFLG) == (I2C_STS1_PECEFLG)); +} + +/** + * @brief Indicate the status of SMBus Timeout detection flag. + * @note Macro @ref IS_SMBUS_ALL_INSTANCE(I2Cx) can be used to check whether or not + * SMBus feature is supported by the I2Cx Instance. + * @param I2Cx I2C Instance. + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_I2C_IsActiveSMBusFlag_TIMEOUT(I2C_TypeDef *I2Cx) +{ + return (READ_BIT(I2Cx->STS1, I2C_STS1_TTEFLG) == (I2C_STS1_TTEFLG)); +} + +/** + * @brief Indicate the status of SMBus alert flag. + * @note Macro @ref IS_SMBUS_ALL_INSTANCE(I2Cx) can be used to check whether or not + * SMBus feature is supported by the I2Cx Instance. + * @param I2Cx I2C Instance. + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_I2C_IsActiveSMBusFlag_ALERT(I2C_TypeDef *I2Cx) +{ + return (READ_BIT(I2Cx->STS1, I2C_STS1_SMBALTFLG) == (I2C_STS1_SMBALTFLG)); +} + +/** + * @brief Indicate the status of Bus Busy flag. + * @note RESET: Clear default value. + * SET: When a Start condition is detected. + * @param I2Cx I2C Instance. + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_I2C_IsActiveFlag_BUSY(I2C_TypeDef *I2Cx) +{ + return (READ_BIT(I2Cx->STS2, I2C_STS2_BUSBSYFLG) == (I2C_STS2_BUSBSYFLG)); +} + +/** + * @brief Indicate the status of Dual flag. + * @note RESET: Received address matched with OAR1. + * SET: Received address matched with OAR2. + * @param I2Cx I2C Instance. + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_I2C_IsActiveFlag_DUAL(I2C_TypeDef *I2Cx) +{ + return (READ_BIT(I2Cx->STS2, I2C_STS2_DUALADDRFLG) == (I2C_STS2_DUALADDRFLG)); +} + +/** + * @brief Indicate the status of SMBus Host address reception (Slave mode). + * @note Macro @ref IS_SMBUS_ALL_INSTANCE(I2Cx) can be used to check whether or not + * SMBus feature is supported by the I2Cx Instance. + * @note RESET: No SMBus Host address + * SET: SMBus Host address received. + * @note This status is cleared by hardware after a STOP condition or repeated START condition. + * @param I2Cx I2C Instance. + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_I2C_IsActiveSMBusFlag_SMBHOST(I2C_TypeDef *I2Cx) +{ + return (READ_BIT(I2Cx->STS2, I2C_STS2_SMMHADDR) == (I2C_STS2_SMMHADDR)); +} + +/** + * @brief Indicate the status of SMBus Device default address reception (Slave mode). + * @note Macro @ref IS_SMBUS_ALL_INSTANCE(I2Cx) can be used to check whether or not + * SMBus feature is supported by the I2Cx Instance. + * @note RESET: No SMBus Device default address + * SET: SMBus Device default address received. + * @note This status is cleared by hardware after a STOP condition or repeated START condition. + * @param I2Cx I2C Instance. + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_I2C_IsActiveSMBusFlag_SMBDEFAULT(I2C_TypeDef *I2Cx) +{ + return (READ_BIT(I2Cx->STS2, I2C_STS2_SMBDADDRFLG) == (I2C_STS2_SMBDADDRFLG)); +} + +/** + * @brief Indicate the status of General call address reception (Slave mode). + * @note RESET: No General call address + * SET: General call address received. + * @note This status is cleared by hardware after a STOP condition or repeated START condition. + * @param I2Cx I2C Instance. + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_I2C_IsActiveFlag_GENCALL(I2C_TypeDef *I2Cx) +{ + return (READ_BIT(I2Cx->STS2, I2C_STS2_GENCALLFLG) == (I2C_STS2_GENCALLFLG)); +} + +/** + * @brief Indicate the status of Master/Slave flag. + * @note RESET: Slave Mode. + * SET: Master Mode. + * @param I2Cx I2C Instance. + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_I2C_IsActiveFlag_MSL(I2C_TypeDef *I2Cx) +{ + return (READ_BIT(I2Cx->STS2, I2C_STS2_MSFLG) == (I2C_STS2_MSFLG)); +} + +/** + * @brief Clear Address Matched flag. + * @note Clearing this flag is done by a read access to the I2Cx_SR1 + * register followed by a read access to the I2Cx_SR2 register. + * @param I2Cx I2C Instance. + * @retval None + */ +__STATIC_INLINE void DDL_I2C_ClearFlag_ADDR(I2C_TypeDef *I2Cx) +{ + __IO uint32_t tmpreg; + tmpreg = I2Cx->STS1; + (void) tmpreg; + tmpreg = I2Cx->STS2; + (void) tmpreg; +} + +/** + * @brief Clear Acknowledge failure flag. + * @param I2Cx I2C Instance. + * @retval None + */ +__STATIC_INLINE void DDL_I2C_ClearFlag_AF(I2C_TypeDef *I2Cx) +{ + CLEAR_BIT(I2Cx->STS1, I2C_STS1_AEFLG); +} + +/** + * @brief Clear Stop detection flag. + * @note Clearing this flag is done by a read access to the I2Cx_SR1 + * register followed by a write access to I2Cx_CTRL1 register. + * @param I2Cx I2C Instance. + * @retval None + */ +__STATIC_INLINE void DDL_I2C_ClearFlag_STOP(I2C_TypeDef *I2Cx) +{ + __IO uint32_t tmpreg; + tmpreg = I2Cx->STS1; + (void) tmpreg; + SET_BIT(I2Cx->CTRL1, I2C_CTRL1_I2CEN); +} + +/** + * @brief Clear Bus error flag. + * @param I2Cx I2C Instance. + * @retval None + */ +__STATIC_INLINE void DDL_I2C_ClearFlag_BERR(I2C_TypeDef *I2Cx) +{ + CLEAR_BIT(I2Cx->STS1, I2C_STS1_BERRFLG); +} + +/** + * @brief Clear Arbitration lost flag. + * @param I2Cx I2C Instance. + * @retval None + */ +__STATIC_INLINE void DDL_I2C_ClearFlag_ARLO(I2C_TypeDef *I2Cx) +{ + CLEAR_BIT(I2Cx->STS1, I2C_STS1_ALFLG); +} + +/** + * @brief Clear Overrun/Underrun flag. + * @param I2Cx I2C Instance. + * @retval None + */ +__STATIC_INLINE void DDL_I2C_ClearFlag_OVR(I2C_TypeDef *I2Cx) +{ + CLEAR_BIT(I2Cx->STS1, I2C_STS1_OVRURFLG); +} + +/** + * @brief Clear SMBus PEC error flag. + * @param I2Cx I2C Instance. + * @retval None + */ +__STATIC_INLINE void DDL_I2C_ClearSMBusFlag_PECERR(I2C_TypeDef *I2Cx) +{ + CLEAR_BIT(I2Cx->STS1, I2C_STS1_PECEFLG); +} + +/** + * @brief Clear SMBus Timeout detection flag. + * @note Macro @ref IS_SMBUS_ALL_INSTANCE(I2Cx) can be used to check whether or not + * SMBus feature is supported by the I2Cx Instance. + * @param I2Cx I2C Instance. + * @retval None + */ +__STATIC_INLINE void DDL_I2C_ClearSMBusFlag_TIMEOUT(I2C_TypeDef *I2Cx) +{ + CLEAR_BIT(I2Cx->STS1, I2C_STS1_TTEFLG); +} + +/** + * @brief Clear SMBus Alert flag. + * @note Macro @ref IS_SMBUS_ALL_INSTANCE(I2Cx) can be used to check whether or not + * SMBus feature is supported by the I2Cx Instance. + * @param I2Cx I2C Instance. + * @retval None + */ +__STATIC_INLINE void DDL_I2C_ClearSMBusFlag_ALERT(I2C_TypeDef *I2Cx) +{ + CLEAR_BIT(I2Cx->STS1, I2C_STS1_SMBALTFLG); +} + +/** + * @} + */ + +/** @defgroup I2C_DDL_EF_Data_Management Data_Management + * @{ + */ + +/** + * @brief Enable Reset of I2C peripheral. + * @param I2Cx I2C Instance. + * @retval None + */ +__STATIC_INLINE void DDL_I2C_EnableReset(I2C_TypeDef *I2Cx) +{ + SET_BIT(I2Cx->CTRL1, I2C_CTRL1_SWRST); +} + +/** + * @brief Disable Reset of I2C peripheral. + * @param I2Cx I2C Instance. + * @retval None + */ +__STATIC_INLINE void DDL_I2C_DisableReset(I2C_TypeDef *I2Cx) +{ + CLEAR_BIT(I2Cx->CTRL1, I2C_CTRL1_SWRST); +} + +/** + * @brief Check if the I2C peripheral is under reset state or not. + * @param I2Cx I2C Instance. + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_I2C_IsResetEnabled(I2C_TypeDef *I2Cx) +{ + return (READ_BIT(I2Cx->CTRL1, I2C_CTRL1_SWRST) == (I2C_CTRL1_SWRST)); +} + +/** + * @brief Prepare the generation of a ACKnowledge or Non ACKnowledge condition after the address receive match code or next received byte. + * @note Usage in Slave or Master mode. + * @param I2Cx I2C Instance. + * @param TypeAcknowledge This parameter can be one of the following values: + * @arg @ref DDL_I2C_ACK + * @arg @ref DDL_I2C_NACK + * @retval None + */ +__STATIC_INLINE void DDL_I2C_AcknowledgeNextData(I2C_TypeDef *I2Cx, uint32_t TypeAcknowledge) +{ + MODIFY_REG(I2Cx->CTRL1, I2C_CTRL1_ACKEN, TypeAcknowledge); +} + +/** + * @brief Generate a START or RESTART condition + * @note The START bit can be set even if bus is BUSY or I2C is in slave mode. + * This action has no effect when RELOAD is set. + * @param I2Cx I2C Instance. + * @retval None + */ +__STATIC_INLINE void DDL_I2C_GenerateStartCondition(I2C_TypeDef *I2Cx) +{ + SET_BIT(I2Cx->CTRL1, I2C_CTRL1_START); +} + +/** + * @brief Generate a STOP condition after the current byte transfer (master mode). + * @param I2Cx I2C Instance. + * @retval None + */ +__STATIC_INLINE void DDL_I2C_GenerateStopCondition(I2C_TypeDef *I2Cx) +{ + SET_BIT(I2Cx->CTRL1, I2C_CTRL1_STOP); +} + +/** + * @brief Enable bit POS (master/host mode). + * @note In that case, the ACK bit controls the (N)ACK of the next byte received or the PEC bit indicates that the next byte in shift register is a PEC. + * @param I2Cx I2C Instance. + * @retval None + */ +__STATIC_INLINE void DDL_I2C_EnableBitPOS(I2C_TypeDef *I2Cx) +{ + SET_BIT(I2Cx->CTRL1, I2C_CTRL1_ACKPOS); +} + +/** + * @brief Disable bit POS (master/host mode). + * @note In that case, the ACK bit controls the (N)ACK of the current byte received or the PEC bit indicates that the current byte in shift register is a PEC. + * @param I2Cx I2C Instance. + * @retval None + */ +__STATIC_INLINE void DDL_I2C_DisableBitPOS(I2C_TypeDef *I2Cx) +{ + CLEAR_BIT(I2Cx->CTRL1, I2C_CTRL1_ACKPOS); +} + +/** + * @brief Check if bit POS is enabled or disabled. + * @param I2Cx I2C Instance. + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_I2C_IsEnabledBitPOS(I2C_TypeDef *I2Cx) +{ + return (READ_BIT(I2Cx->CTRL1, I2C_CTRL1_ACKPOS) == (I2C_CTRL1_ACKPOS)); +} + +/** + * @brief Indicate the value of transfer direction. + * @note RESET: Bus is in read transfer (peripheral point of view). + * SET: Bus is in write transfer (peripheral point of view). + * @param I2Cx I2C Instance. + * @retval Returned value can be one of the following values: + * @arg @ref DDL_I2C_DIRECTION_WRITE + * @arg @ref DDL_I2C_DIRECTION_READ + */ +__STATIC_INLINE uint32_t DDL_I2C_GetTransferDirection(I2C_TypeDef *I2Cx) +{ + return (uint32_t)(READ_BIT(I2Cx->STS2, I2C_STS2_TRFLG)); +} + +/** + * @brief Enable DMA last transfer. + * @note This action mean that next DMA EOT is the last transfer. + * @param I2Cx I2C Instance. + * @retval None + */ +__STATIC_INLINE void DDL_I2C_EnableLastDMA(I2C_TypeDef *I2Cx) +{ + SET_BIT(I2Cx->CTRL2, I2C_CTRL2_LTCFG); +} + +/** + * @brief Disable DMA last transfer. + * @note This action mean that next DMA EOT is not the last transfer. + * @param I2Cx I2C Instance. + * @retval None + */ +__STATIC_INLINE void DDL_I2C_DisableLastDMA(I2C_TypeDef *I2Cx) +{ + CLEAR_BIT(I2Cx->CTRL2, I2C_CTRL2_LTCFG); +} + +/** + * @brief Check if DMA last transfer is enabled or disabled. + * @param I2Cx I2C Instance. + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_I2C_IsEnabledLastDMA(I2C_TypeDef *I2Cx) +{ + return (READ_BIT(I2Cx->CTRL2, I2C_CTRL2_LTCFG) == (I2C_CTRL2_LTCFG)); +} + +/** + * @brief Enable transfer or internal comparison of the SMBus Packet Error byte (transmission or reception mode). + * @note Macro @ref IS_SMBUS_ALL_INSTANCE(I2Cx) can be used to check whether or not + * SMBus feature is supported by the I2Cx Instance. + * @note This feature is cleared by hardware when the PEC byte is transferred or compared, + * or by a START or STOP condition, it is also cleared by software. + * @param I2Cx I2C Instance. + * @retval None + */ +__STATIC_INLINE void DDL_I2C_EnableSMBusPECCompare(I2C_TypeDef *I2Cx) +{ + SET_BIT(I2Cx->CTRL1, I2C_CTRL1_PEC); +} + +/** + * @brief Disable transfer or internal comparison of the SMBus Packet Error byte (transmission or reception mode). + * @note Macro @ref IS_SMBUS_ALL_INSTANCE(I2Cx) can be used to check whether or not + * SMBus feature is supported by the I2Cx Instance. + * @param I2Cx I2C Instance. + * @retval None + */ +__STATIC_INLINE void DDL_I2C_DisableSMBusPECCompare(I2C_TypeDef *I2Cx) +{ + CLEAR_BIT(I2Cx->CTRL1, I2C_CTRL1_PEC); +} + +/** + * @brief Check if the SMBus Packet Error byte transfer or internal comparison is requested or not. + * @note Macro @ref IS_SMBUS_ALL_INSTANCE(I2Cx) can be used to check whether or not + * SMBus feature is supported by the I2Cx Instance. + * @param I2Cx I2C Instance. + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_I2C_IsEnabledSMBusPECCompare(I2C_TypeDef *I2Cx) +{ + return (READ_BIT(I2Cx->CTRL1, I2C_CTRL1_PEC) == (I2C_CTRL1_PEC)); +} + +/** + * @brief Get the SMBus Packet Error byte calculated. + * @note Macro @ref IS_SMBUS_ALL_INSTANCE(I2Cx) can be used to check whether or not + * SMBus feature is supported by the I2Cx Instance. + * @param I2Cx I2C Instance. + * @retval Value between Min_Data=0x00 and Max_Data=0xFF + */ +__STATIC_INLINE uint32_t DDL_I2C_GetSMBusPEC(I2C_TypeDef *I2Cx) +{ + return (uint32_t)(READ_BIT(I2Cx->STS2, I2C_STS2_PECVALUE) >> I2C_STS2_PECVALUE_Pos); +} + +/** + * @brief Read Receive Data register. + * @param I2Cx I2C Instance. + * @retval Value between Min_Data=0x0 and Max_Data=0xFF + */ +__STATIC_INLINE uint8_t DDL_I2C_ReceiveData8(I2C_TypeDef *I2Cx) +{ + return (uint8_t)(READ_BIT(I2Cx->DATA, I2C_DATA_DATA)); +} + +/** + * @brief Write in Transmit Data Register . + * @param I2Cx I2C Instance. + * @param Data Value between Min_Data=0x0 and Max_Data=0xFF + * @retval None + */ +__STATIC_INLINE void DDL_I2C_TransmitData8(I2C_TypeDef *I2Cx, uint8_t Data) +{ + MODIFY_REG(I2Cx->DATA, I2C_DATA_DATA, Data); +} + +/** + * @} + */ + +#if defined(USE_FULL_DDL_DRIVER) +/** @defgroup I2C_DDL_EF_Init Initialization and de-initialization functions + * @{ + */ + +uint32_t DDL_I2C_Init(I2C_TypeDef *I2Cx, DDL_I2C_InitTypeDef *I2C_InitStruct); +uint32_t DDL_I2C_DeInit(I2C_TypeDef *I2Cx); +void DDL_I2C_StructInit(DDL_I2C_InitTypeDef *I2C_InitStruct); + + +/** + * @} + */ +#endif /* USE_FULL_DDL_DRIVER */ + +/** + * @} + */ + +/** + * @} + */ + +#endif /* I2C1 || I2C2 || I2C3 */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* APM32F4xx_DDL_I2C_H */ + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_iwdt.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_iwdt.h new file mode 100644 index 0000000000..55848f02a8 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_iwdt.h @@ -0,0 +1,314 @@ +/** + * + * @file apm32f4xx_ddl_iwdt.h + * @brief Header file of IWDT DDL module. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef APM32F4xx_DDL_IWDT_H +#define APM32F4xx_DDL_IWDT_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx.h" + +/** @addtogroup APM32F4xx_DDL_Driver + * @{ + */ + +#if defined(IWDT) + +/** @defgroup IWDT_DDL IWDT + * @{ + */ + +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ + +/* Private constants ---------------------------------------------------------*/ +/** @defgroup IWDT_DDL_Private_Constants IWDT Private Constants + * @{ + */ +#define DDL_IWDT_KEY_RELOAD 0x0000AAAAU /*!< IWDT Reload Counter Enable */ +#define DDL_IWDT_KEY_ENABLE 0x0000CCCCU /*!< IWDT Peripheral Enable */ +#define DDL_IWDT_KEY_WR_ACCESS_ENABLE 0x00005555U /*!< IWDT KR Write Access Enable */ +#define DDL_IWDT_KEY_WR_ACCESS_DISABLE 0x00000000U /*!< IWDT KR Write Access Disable */ +/** + * @} + */ + +/* Private macros ------------------------------------------------------------*/ + +/* Exported types ------------------------------------------------------------*/ +/* Exported constants --------------------------------------------------------*/ +/** @defgroup IWDT_DDL_Exported_Constants IWDT Exported Constants + * @{ + */ + +/** @defgroup IWDT_DDL_EC_GET_FLAG Get Flags Defines + * @brief Flags defines which can be used with DDL_IWDT_ReadReg function + * @{ + */ +#define DDL_IWDT_STS_PSCUFLG IWDT_STS_PSCUFLG /*!< Watchdog prescaler value update */ +#define DDL_IWDT_STS_CNTUFLG IWDT_STS_CNTUFLG /*!< Watchdog counter reload value update */ +/** + * @} + */ + +/** @defgroup IWDT_DDL_EC_PRESCALER Prescaler Divider + * @{ + */ +#define DDL_IWDT_PSC_4 0x00000000U /*!< Divider by 4 */ +#define DDL_IWDT_PSC_8 (IWDT_PSC_PSC_0) /*!< Divider by 8 */ +#define DDL_IWDT_PSC_16 (IWDT_PSC_PSC_1) /*!< Divider by 16 */ +#define DDL_IWDT_PSC_32 (IWDT_PSC_PSC_1 | IWDT_PSC_PSC_0) /*!< Divider by 32 */ +#define DDL_IWDT_PSC_64 (IWDT_PSC_PSC_2) /*!< Divider by 64 */ +#define DDL_IWDT_PSC_128 (IWDT_PSC_PSC_2 | IWDT_PSC_PSC_0) /*!< Divider by 128 */ +#define DDL_IWDT_PSC_256 (IWDT_PSC_PSC_2 | IWDT_PSC_PSC_1) /*!< Divider by 256 */ +/** + * @} + */ + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ +/** @defgroup IWDT_DDL_Exported_Macros IWDT Exported Macros + * @{ + */ + +/** @defgroup IWDT_DDL_EM_WRITE_READ Common Write and read registers Macros + * @{ + */ + +/** + * @brief Write a value in IWDT register + * @param __INSTANCE__ IWDT Instance + * @param __REG__ Register to be written + * @param __VALUE__ Value to be written in the register + * @retval None + */ +#define DDL_IWDT_WriteReg(__INSTANCE__, __REG__, __VALUE__) WRITE_REG(__INSTANCE__->__REG__, (__VALUE__)) + +/** + * @brief Read a value in IWDT register + * @param __INSTANCE__ IWDT Instance + * @param __REG__ Register to be read + * @retval Register value + */ +#define DDL_IWDT_ReadReg(__INSTANCE__, __REG__) READ_REG(__INSTANCE__->__REG__) +/** + * @} + */ + +/** + * @} + */ + + +/* Exported functions --------------------------------------------------------*/ +/** @defgroup IWDT_DDL_Exported_Functions IWDT Exported Functions + * @{ + */ +/** @defgroup IWDT_DDL_EF_Configuration Configuration + * @{ + */ + +/** + * @brief Start the Independent Watchdog + * @note Except if the hardware watchdog option is selected + * @param IWDTx IWDT Instance + * @retval None + */ +__STATIC_INLINE void DDL_IWDT_Enable(IWDT_TypeDef *IWDTx) +{ + WRITE_REG(IWDTx->KEY, DDL_IWDT_KEY_ENABLE); +} + +/** + * @brief Reloads IWDT counter with value defined in the reload register + * @param IWDTx IWDT Instance + * @retval None + */ +__STATIC_INLINE void DDL_IWDT_ReloadCounter(IWDT_TypeDef *IWDTx) +{ + WRITE_REG(IWDTx->KEY, DDL_IWDT_KEY_RELOAD); +} + +/** + * @brief Enable write access to IWDT_PR, IWDT_RLR and IWDT_WINR registers + * @param IWDTx IWDT Instance + * @retval None + */ +__STATIC_INLINE void DDL_IWDT_EnableWriteAccess(IWDT_TypeDef *IWDTx) +{ + WRITE_REG(IWDTx->KEY, DDL_IWDT_KEY_WR_ACCESS_ENABLE); +} + +/** + * @brief Disable write access to IWDT_PR, IWDT_RLR and IWDT_WINR registers + * @param IWDTx IWDT Instance + * @retval None + */ +__STATIC_INLINE void DDL_IWDT_DisableWriteAccess(IWDT_TypeDef *IWDTx) +{ + WRITE_REG(IWDTx->KEY, DDL_IWDT_KEY_WR_ACCESS_DISABLE); +} + +/** + * @brief Select the prescaler of the IWDT + * @param IWDTx IWDT Instance + * @param Prescaler This parameter can be one of the following values: + * @arg @ref DDL_IWDT_PSC_4 + * @arg @ref DDL_IWDT_PSC_8 + * @arg @ref DDL_IWDT_PSC_16 + * @arg @ref DDL_IWDT_PSC_32 + * @arg @ref DDL_IWDT_PSC_64 + * @arg @ref DDL_IWDT_PSC_128 + * @arg @ref DDL_IWDT_PSC_256 + * @retval None + */ +__STATIC_INLINE void DDL_IWDT_SetPrescaler(IWDT_TypeDef *IWDTx, uint32_t Prescaler) +{ + WRITE_REG(IWDTx->PSC, IWDT_PSC_PSC & Prescaler); +} + +/** + * @brief Get the selected prescaler of the IWDT + * @param IWDTx IWDT Instance + * @retval Returned value can be one of the following values: + * @arg @ref DDL_IWDT_PSC_4 + * @arg @ref DDL_IWDT_PSC_8 + * @arg @ref DDL_IWDT_PSC_16 + * @arg @ref DDL_IWDT_PSC_32 + * @arg @ref DDL_IWDT_PSC_64 + * @arg @ref DDL_IWDT_PSC_128 + * @arg @ref DDL_IWDT_PSC_256 + */ +__STATIC_INLINE uint32_t DDL_IWDT_GetPrescaler(IWDT_TypeDef *IWDTx) +{ + return (READ_REG(IWDTx->PSC)); +} + +/** + * @brief Specify the IWDT down-counter reload value + * @param IWDTx IWDT Instance + * @param Counter Value between Min_Data=0 and Max_Data=0x0FFF + * @retval None + */ +__STATIC_INLINE void DDL_IWDT_SetReloadCounter(IWDT_TypeDef *IWDTx, uint32_t Counter) +{ + WRITE_REG(IWDTx->CNTRLD, IWDT_CNTRLD_CNTRLD & Counter); +} + +/** + * @brief Get the specified IWDT down-counter reload value + * @param IWDTx IWDT Instance + * @retval Value between Min_Data=0 and Max_Data=0x0FFF + */ +__STATIC_INLINE uint32_t DDL_IWDT_GetReloadCounter(IWDT_TypeDef *IWDTx) +{ + return (READ_REG(IWDTx->CNTRLD)); +} + +/** + * @} + */ + +/** @defgroup IWDT_DDL_EF_FLAG_Management FLAG_Management + * @{ + */ + +/** + * @brief Check if flag Prescaler Value Update is set or not + * @param IWDTx IWDT Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_IWDT_IsActiveFlag_PVU(IWDT_TypeDef *IWDTx) +{ + return ((READ_BIT(IWDTx->STS, IWDT_STS_PSCUFLG) == (IWDT_STS_PSCUFLG)) ? 1UL : 0UL); +} + +/** + * @brief Check if flag Reload Value Update is set or not + * @param IWDTx IWDT Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_IWDT_IsActiveFlag_RVU(IWDT_TypeDef *IWDTx) +{ + return ((READ_BIT(IWDTx->STS, IWDT_STS_CNTUFLG) == (IWDT_STS_CNTUFLG)) ? 1UL : 0UL); +} + +/** + * @brief Check if flags Prescaler & Reload Value Update are reset or not + * @param IWDTx IWDT Instance + * @retval State of bits (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_IWDT_IsReady(IWDT_TypeDef *IWDTx) +{ + return ((READ_BIT(IWDTx->STS, IWDT_STS_PSCUFLG | IWDT_STS_CNTUFLG) == 0U) ? 1UL : 0UL); +} + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#endif /* IWDT */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* APM32F4xx_DDL_IWDT_H */ diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_pmu.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_pmu.h new file mode 100644 index 0000000000..de9e403c1f --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_pmu.h @@ -0,0 +1,924 @@ +/** + * + * @file apm32f4xx_ddl_pmu.h + * @brief Header file of PMU DDL module. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2017 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file in + * the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef APM32F4xx_DDL_PMU_H +#define APM32F4xx_DDL_PMU_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx.h" + +/** @addtogroup APM32F4xx_DDL_Driver + * @{ + */ + +#if defined(PMU) + +/** @defgroup PMU_DDL PMU + * @{ + */ + +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/* Private macros ------------------------------------------------------------*/ +/* Exported types ------------------------------------------------------------*/ +/* Exported constants --------------------------------------------------------*/ +/** @defgroup PMU_DDL_Exported_Constants PMU Exported Constants + * @{ + */ + +/** @defgroup PMU_DDL_EC_CLEAR_FLAG Clear Flags Defines + * @brief Flags defines which can be used with DDL_PMU_WriteReg function + * @{ + */ +#define DDL_PMU_CTRL_SBFLGCLR PMU_CTRL_SBFLGCLR /*!< Clear standby flag */ +#define DDL_PMU_CTRL_WUFLGCLR PMU_CTRL_WUFLGCLR /*!< Clear wakeup flag */ +/** + * @} + */ + +/** @defgroup PMU_DDL_EC_GET_FLAG Get Flags Defines + * @brief Flags defines which can be used with DDL_PMU_ReadReg function + * @{ + */ +#define DDL_PMU_CSTS_WUEFLG PMU_CSTS_WUEFLG /*!< Wakeup flag */ +#define DDL_PMU_CSTS_SBFLG PMU_CSTS_SBFLG /*!< Standby flag */ +#define DDL_PMU_CSTS_PVDOFLG PMU_CSTS_PVDOFLG /*!< Power voltage detector output flag */ +#define DDL_PMU_CSTS_VOS PMU_CSTS_VOSRFLG /*!< Voltage scaling select flag */ +#if defined(PMU_CSTS_WKUPCFG) +#define DDL_PMU_CSTS_WKUPCFG1 PMU_CSTS_WKUPCFG /*!< Enable WKUP pin */ +#elif defined(PMU_CSTS_WKUPCFG1) +#define DDL_PMU_CSTS_WKUPCFG1 PMU_CSTS_WKUPCFG1 /*!< Enable WKUP pin 1 */ +#endif /* PMU_CSTS_WKUPCFG */ +#if defined(PMU_CSTS_WKUPCFG2) +#define DDL_PMU_CSTS_WKUPCFG2 PMU_CSTS_WKUPCFG2 /*!< Enable WKUP pin 2 */ +#endif /* PMU_CSTS_WKUPCFG2 */ +#if defined(PMU_CSTS_WKUPCFG3) +#define DDL_PMU_CSTS_WKUPCFG3 PMU_CSTS_WKUPCFG3 /*!< Enable WKUP pin 3 */ +#endif /* PMU_CSTS_WKUPCFG3 */ +/** + * @} + */ + +/** @defgroup PMU_DDL_EC_REGU_VOLTAGE Regulator Voltage + * @{ + */ +#if defined(PMU_CTRL_VOSSEL_0) +#define DDL_PMU_REGU_VOLTAGE_SCALE3 (PMU_CTRL_VOSSEL_0) +#define DDL_PMU_REGU_VOLTAGE_SCALE2 (PMU_CTRL_VOSSEL_1) +#define DDL_PMU_REGU_VOLTAGE_SCALE1 (PMU_CTRL_VOSSEL_0 | PMU_CTRL_VOSSEL_1) +#else +#define DDL_PMU_REGU_VOLTAGE_SCALE1 (PMU_CTRL_VOSSEL) +#define DDL_PMU_REGU_VOLTAGE_SCALE2 0x00000000U +#endif /* PMU_CTRL_VOSSEL_0 */ +/** + * @} + */ + +/** @defgroup PMU_DDL_EC_MODE_PMU Mode Power + * @{ + */ +#define DDL_PMU_MODE_STOP_MAINREGU 0x00000000U /*!< Enter Stop mode when the CPU enters deepsleep */ +#define DDL_PMU_MODE_STOP_LPREGU (PMU_CTRL_LPDSCFG) /*!< Enter Stop mode (with low power Regulator ON) when the CPU enters deepsleep */ +#if defined(PMU_CTRL_MRUDS) && defined(PMU_CTRL_LPUDS) && defined(PMU_CTRL_FPDSM) +#define DDL_PMU_MODE_STOP_MAINREGU_UNDERDRIVE (PMU_CTRL_MRUDS | PMU_CTRL_FPDSM) /*!< Enter Stop mode (with main Regulator in under-drive mode) when the CPU enters deepsleep */ +#define DDL_PMU_MODE_STOP_LPREGU_UNDERDRIVE (PMU_CTRL_LPDSCFG | PMU_CTRL_LPUDS | PMU_CTRL_FPDSM) /*!< Enter Stop mode (with low power Regulator in under-drive mode) when the CPU enters deepsleep */ +#endif /* PMU_CTRL_MRUDS && PMU_CTRL_LPUDS && PMU_CTRL_FPDSM */ +#if defined(PMU_CTRL_MRLV) && defined(PMU_CTRL_LPRLV) && defined(PMU_CTRL_FPDSM) +#define DDL_PMU_MODE_STOP_MAINREGU_DEEPSLEEP (PMU_CTRL_MRLV | PMU_CTRL_FPDSM) /*!< Enter Stop mode (with main Regulator in Deep Sleep mode) when the CPU enters deepsleep */ +#define DDL_PMU_MODE_STOP_LPREGU_DEEPSLEEP (PMU_CTRL_LPDSCFG | PMU_CTRL_LPRLV | PMU_CTRL_FPDSM) /*!< Enter Stop mode (with low power Regulator in Deep Sleep mode) when the CPU enters deepsleep */ +#endif /* PMU_CTRL_MRLV && PMU_CTRL_LPRLV && PMU_CTRL_FPDSM */ +#define DDL_PMU_MODE_STANDBY (PMU_CTRL_PDDSCFG) /*!< Enter Standby mode when the CPU enters deepsleep */ +/** + * @} + */ + +/** @defgroup PMU_DDL_EC_REGU_MODE_DS_MODE Regulator Mode In Deep Sleep Mode + * @{ + */ +#define DDL_PMU_REGU_DSMODE_MAIN 0x00000000U /*!< Voltage Regulator in main mode during deepsleep mode */ +#define DDL_PMU_REGU_DSMODE_LOW_POWER (PMU_CTRL_LPDSCFG) /*!< Voltage Regulator in low-power mode during deepsleep mode */ +/** + * @} + */ + +/** @defgroup PMU_DDL_EC_PVDLEVEL Power Voltage Detector Level + * @{ + */ +#define DDL_PMU_PVDLEVEL_0 (PMU_CTRL_PLSEL_LEV0) /*!< Voltage threshold detected by PVD 2.2 V */ +#define DDL_PMU_PVDLEVEL_1 (PMU_CTRL_PLSEL_LEV1) /*!< Voltage threshold detected by PVD 2.3 V */ +#define DDL_PMU_PVDLEVEL_2 (PMU_CTRL_PLSEL_LEV2) /*!< Voltage threshold detected by PVD 2.4 V */ +#define DDL_PMU_PVDLEVEL_3 (PMU_CTRL_PLSEL_LEV3) /*!< Voltage threshold detected by PVD 2.5 V */ +#define DDL_PMU_PVDLEVEL_4 (PMU_CTRL_PLSEL_LEV4) /*!< Voltage threshold detected by PVD 2.6 V */ +#define DDL_PMU_PVDLEVEL_5 (PMU_CTRL_PLSEL_LEV5) /*!< Voltage threshold detected by PVD 2.7 V */ +#define DDL_PMU_PVDLEVEL_6 (PMU_CTRL_PLSEL_LEV6) /*!< Voltage threshold detected by PVD 2.8 V */ +#define DDL_PMU_PVDLEVEL_7 (PMU_CTRL_PLSEL_LEV7) /*!< Voltage threshold detected by PVD 2.9 V */ +/** + * @} + */ +/** @defgroup PMU_DDL_EC_WAKEUP_PIN Wakeup Pins + * @{ + */ +#if defined(PMU_CSTS_WKUPCFG) +#define DDL_PMU_WAKEUP_PIN1 (PMU_CSTS_WKUPCFG) /*!< WKUP pin : PA0 */ +#endif /* PMU_CSTS_WKUPCFG */ +#if defined(PMU_CSTS_WKUPCFG1) +#define DDL_PMU_WAKEUP_PIN1 (PMU_CSTS_WKUPCFG1) /*!< WKUP pin 1 : PA0 */ +#endif /* PMU_CSTS_WKUPCFG1 */ +#if defined(PMU_CSTS_WKUPCFG2) +#define DDL_PMU_WAKEUP_PIN2 (PMU_CSTS_WKUPCFG2) /*!< WKUP pin 2 : PC0 or PC13 according to device */ +#endif /* PMU_CSTS_WKUPCFG2 */ +#if defined(PMU_CSTS_WKUPCFG3) +#define DDL_PMU_WAKEUP_PIN3 (PMU_CSTS_WKUPCFG3) /*!< WKUP pin 3 : PC1 */ +#endif /* PMU_CSTS_WKUPCFG3 */ +/** + * @} + */ + +/** + * @} + */ + + +/* Exported macro ------------------------------------------------------------*/ +/** @defgroup PMU_DDL_Exported_Macros PMU Exported Macros + * @{ + */ + +/** @defgroup PMU_DDL_EM_WRITE_READ Common write and read registers Macros + * @{ + */ + +/** + * @brief Write a value in PMU register + * @param __REG__ Register to be written + * @param __VALUE__ Value to be written in the register + * @retval None + */ +#define DDL_PMU_WriteReg(__REG__, __VALUE__) WRITE_REG(PMU->__REG__, (__VALUE__)) + +/** + * @brief Read a value in PMU register + * @param __REG__ Register to be read + * @retval Register value + */ +#define DDL_PMU_ReadReg(__REG__) READ_REG(PMU->__REG__) +/** + * @} + */ + +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +/** @defgroup PMU_DDL_Exported_Functions PMU Exported Functions + * @{ + */ + +/** @defgroup PMU_DDL_EF_Configuration Configuration + * @{ + */ +#if defined(PMU_CTRL_FLASHEN) +/** + * @brief Enable FLASH interface STOP while system Run is ON + * @note This mode is enabled only with STOP low power mode. + * @retval None + */ +__STATIC_INLINE void DDL_PMU_EnableFLASHInterfaceSTOP(void) +{ + SET_BIT(PMU->CTRL, PMU_CTRL_FLASHEN); +} + +/** + * @brief Disable FLASH Interface STOP while system Run is ON + * @retval None + */ +__STATIC_INLINE void DDL_PMU_DisableFLASHInterfaceSTOP(void) +{ + CLEAR_BIT(PMU->CTRL, PMU_CTRL_FLASHEN); +} + +/** + * @brief Check if FLASH Interface STOP while system Run feature is enabled + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_PMU_IsEnabledFLASHInterfaceSTOP(void) +{ + return (READ_BIT(PMU->CTRL, PMU_CTRL_FLASHEN) == (PMU_CTRL_FLASHEN)); +} +#endif /* PMU_CTRL_FLASHEN */ + +#if defined(PMU_CTRL_FSMODE) +/** + * @brief Enable FLASH Memory STOP while system Run is ON + * @note This mode is enabled only with STOP low power mode. + * @retval None + */ +__STATIC_INLINE void DDL_PMU_EnableFLASHMemorySTOP(void) +{ + SET_BIT(PMU->CTRL, PMU_CTRL_FSMODE); +} + +/** + * @brief Disable FLASH Memory STOP while system Run is ON + * @retval None + */ +__STATIC_INLINE void DDL_PMU_DisableFLASHMemorySTOP(void) +{ + CLEAR_BIT(PMU->CTRL, PMU_CTRL_FSMODE); +} + +/** + * @brief Check if FLASH Memory STOP while system Run feature is enabled + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_PMU_IsEnabledFLASHMemorySTOP(void) +{ + return (READ_BIT(PMU->CTRL, PMU_CTRL_FSMODE) == (PMU_CTRL_FSMODE)); +} +#endif /* PMU_CTRL_FSMODE */ +#if defined(PMU_CTRL_UDEN) +/** + * @brief Enable Under Drive Mode + * @note This mode is enabled only with STOP low power mode. + * In this mode, the 1.2V domain is preserved in reduced leakage mode. This + * mode is only available when the main Regulator or the low power Regulator + * is in low voltage mode. + * @note If the Under-drive mode was enabled, it is automatically disabled after + * exiting Stop mode. + * When the voltage Regulator operates in Under-drive mode, an additional + * startup delay is induced when waking up from Stop mode. + * @retval None + */ +__STATIC_INLINE void DDL_PMU_EnableUnderDriveMode(void) +{ + SET_BIT(PMU->CTRL, PMU_CTRL_UDEN); +} + +/** + * @brief Disable Under Drive Mode + * @retval None + */ +__STATIC_INLINE void DDL_PMU_DisableUnderDriveMode(void) +{ + CLEAR_BIT(PMU->CTRL, PMU_CTRL_UDEN); +} + +/** + * @brief Check if Under Drive Mode is enabled + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_PMU_IsEnabledUnderDriveMode(void) +{ + return (READ_BIT(PMU->CTRL, PMU_CTRL_UDEN) == (PMU_CTRL_UDEN)); +} +#endif /* PMU_CTRL_UDEN */ + +#if defined(PMU_CTRL_ODSWEN) +/** + * @brief Enable Over drive switching + * @retval None + */ +__STATIC_INLINE void DDL_PMU_EnableOverDriveSwitching(void) +{ + SET_BIT(PMU->CTRL, PMU_CTRL_ODSWEN); +} + +/** + * @brief Disable Over drive switching + * @retval None + */ +__STATIC_INLINE void DDL_PMU_DisableOverDriveSwitching(void) +{ + CLEAR_BIT(PMU->CTRL, PMU_CTRL_ODSWEN); +} + +/** + * @brief Check if Over drive switching is enabled + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_PMU_IsEnabledOverDriveSwitching(void) +{ + return (READ_BIT(PMU->CTRL, PMU_CTRL_ODSWEN) == (PMU_CTRL_ODSWEN)); +} +#endif /* PMU_CTRL_ODSWEN */ +#if defined(PMU_CTRL_ODEN) +/** + * @brief Enable Over drive Mode + * @retval None + */ +__STATIC_INLINE void DDL_PMU_EnableOverDriveMode(void) +{ + SET_BIT(PMU->CTRL, PMU_CTRL_ODEN); +} + +/** + * @brief Disable Over drive Mode + * @retval None + */ +__STATIC_INLINE void DDL_PMU_DisableOverDriveMode(void) +{ + CLEAR_BIT(PMU->CTRL, PMU_CTRL_ODEN); +} + +/** + * @brief Check if Over drive switching is enabled + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_PMU_IsEnabledOverDriveMode(void) +{ + return (READ_BIT(PMU->CTRL, PMU_CTRL_ODEN) == (PMU_CTRL_ODEN)); +} +#endif /* PMU_CTRL_ODEN */ +#if defined(PMU_CTRL_MRUDS) +/** + * @brief Enable Main Regulator in deepsleep under-drive Mode + * @retval None + */ +__STATIC_INLINE void DDL_PMU_EnableMainRegulatorDeepSleepUDMode(void) +{ + SET_BIT(PMU->CTRL, PMU_CTRL_MRUDS); +} + +/** + * @brief Disable Main Regulator in deepsleep under-drive Mode + * @retval None + */ +__STATIC_INLINE void DDL_PMU_DisableMainRegulatorDeepSleepUDMode(void) +{ + CLEAR_BIT(PMU->CTRL, PMU_CTRL_MRUDS); +} + +/** + * @brief Check if Main Regulator in deepsleep under-drive Mode is enabled + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_PMU_IsEnabledMainRegulatorDeepSleepUDMode(void) +{ + return (READ_BIT(PMU->CTRL, PMU_CTRL_MRUDS) == (PMU_CTRL_MRUDS)); +} +#endif /* PMU_CTRL_MRUDS */ + +#if defined(PMU_CTRL_LPUDS) +/** + * @brief Enable Low Power Regulator in deepsleep under-drive Mode + * @retval None + */ +__STATIC_INLINE void DDL_PMU_EnableLowPowerRegulatorDeepSleepUDMode(void) +{ + SET_BIT(PMU->CTRL, PMU_CTRL_LPUDS); +} + +/** + * @brief Disable Low Power Regulator in deepsleep under-drive Mode + * @retval None + */ +__STATIC_INLINE void DDL_PMU_DisableLowPowerRegulatorDeepSleepUDMode(void) +{ + CLEAR_BIT(PMU->CTRL, PMU_CTRL_LPUDS); +} + +/** + * @brief Check if Low Power Regulator in deepsleep under-drive Mode is enabled + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_PMU_IsEnabledLowPowerRegulatorDeepSleepUDMode(void) +{ + return (READ_BIT(PMU->CTRL, PMU_CTRL_LPUDS) == (PMU_CTRL_LPUDS)); +} +#endif /* PMU_CTRL_LPUDS */ + +#if defined(PMU_CTRL_MRLV) +/** + * @brief Enable Main Regulator low voltage Mode + * @retval None + */ +__STATIC_INLINE void DDL_PMU_EnableMainRegulatorLowVoltageMode(void) +{ + SET_BIT(PMU->CTRL, PMU_CTRL_MRLV); +} + +/** + * @brief Disable Main Regulator low voltage Mode + * @retval None + */ +__STATIC_INLINE void DDL_PMU_DisableMainRegulatorLowVoltageMode(void) +{ + CLEAR_BIT(PMU->CTRL, PMU_CTRL_MRLV); +} + +/** + * @brief Check if Main Regulator low voltage Mode is enabled + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_PMU_IsEnabledMainRegulatorLowVoltageMode(void) +{ + return (READ_BIT(PMU->CTRL, PMU_CTRL_MRLV) == (PMU_CTRL_MRLV)); +} +#endif /* PMU_CTRL_MRLV */ + +#if defined(PMU_CTRL_LPRLV) +/** + * @brief Enable Low Power Regulator low voltage Mode + * @retval None + */ +__STATIC_INLINE void DDL_PMU_EnableLowPowerRegulatorLowVoltageMode(void) +{ + SET_BIT(PMU->CTRL, PMU_CTRL_LPRLV); +} + +/** + * @brief Disable Low Power Regulator low voltage Mode + * @retval None + */ +__STATIC_INLINE void DDL_PMU_DisableLowPowerRegulatorLowVoltageMode(void) +{ + CLEAR_BIT(PMU->CTRL, PMU_CTRL_LPRLV); +} + +/** + * @brief Check if Low Power Regulator low voltage Mode is enabled + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_PMU_IsEnabledLowPowerRegulatorLowVoltageMode(void) +{ + return (READ_BIT(PMU->CTRL, PMU_CTRL_LPRLV) == (PMU_CTRL_LPRLV)); +} +#endif /* PMU_CTRL_LPRLV */ +/** + * @brief Set the main internal Regulator output voltage + * @param VoltageScaling This parameter can be one of the following values: + * @arg @ref DDL_PMU_REGU_VOLTAGE_SCALE1 (*) + * @arg @ref DDL_PMU_REGU_VOLTAGE_SCALE2 + * @arg @ref DDL_PMU_REGU_VOLTAGE_SCALE3 + * @retval None + */ +__STATIC_INLINE void DDL_PMU_SetRegulVoltageScaling(uint32_t VoltageScaling) +{ + MODIFY_REG(PMU->CTRL, PMU_CTRL_VOSSEL, VoltageScaling); +} + +/** + * @brief Get the main internal Regulator output voltage + * @retval Returned value can be one of the following values: + * @arg @ref DDL_PMU_REGU_VOLTAGE_SCALE1 (*) + * @arg @ref DDL_PMU_REGU_VOLTAGE_SCALE2 + * @arg @ref DDL_PMU_REGU_VOLTAGE_SCALE3 + */ +__STATIC_INLINE uint32_t DDL_PMU_GetRegulVoltageScaling(void) +{ + return (uint32_t)(READ_BIT(PMU->CTRL, PMU_CTRL_VOSSEL)); +} +/** + * @brief Enable the Flash Power Down in Stop Mode + * @retval None + */ +__STATIC_INLINE void DDL_PMU_EnableFlashPowerDown(void) +{ + SET_BIT(PMU->CTRL, PMU_CTRL_FPDSM); +} + +/** + * @brief Disable the Flash Power Down in Stop Mode + * @retval None + */ +__STATIC_INLINE void DDL_PMU_DisableFlashPowerDown(void) +{ + CLEAR_BIT(PMU->CTRL, PMU_CTRL_FPDSM); +} + +/** + * @brief Check if the Flash Power Down in Stop Mode is enabled + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_PMU_IsEnabledFlashPowerDown(void) +{ + return (READ_BIT(PMU->CTRL, PMU_CTRL_FPDSM) == (PMU_CTRL_FPDSM)); +} + +/** + * @brief Enable access to the backup domain + * @retval None + */ +__STATIC_INLINE void DDL_PMU_EnableBkUpAccess(void) +{ + SET_BIT(PMU->CTRL, PMU_CTRL_BPWEN); +} + +/** + * @brief Disable access to the backup domain + * @retval None + */ +__STATIC_INLINE void DDL_PMU_DisableBkUpAccess(void) +{ + CLEAR_BIT(PMU->CTRL, PMU_CTRL_BPWEN); +} + +/** + * @brief Check if the backup domain is enabled + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_PMU_IsEnabledBkUpAccess(void) +{ + return (READ_BIT(PMU->CTRL, PMU_CTRL_BPWEN) == (PMU_CTRL_BPWEN)); +} +/** + * @brief Enable the backup Regulator + * @note The BRE bit of the PMU_CSTS register is protected against parasitic write access. + * The DDL_PMU_EnableBkUpAccess() must be called before using this API. + * @retval None + */ +__STATIC_INLINE void DDL_PMU_EnableBkUpRegulator(void) +{ + SET_BIT(PMU->CSTS, PMU_CSTS_BKPREN); +} + +/** + * @brief Disable the backup Regulator + * @note The BRE bit of the PMU_CSTS register is protected against parasitic write access. + * The DDL_PMU_EnableBkUpAccess() must be called before using this API. + * @retval None + */ +__STATIC_INLINE void DDL_PMU_DisableBkUpRegulator(void) +{ + CLEAR_BIT(PMU->CSTS, PMU_CSTS_BKPREN); +} + +/** + * @brief Check if the backup Regulator is enabled + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_PMU_IsEnabledBkUpRegulator(void) +{ + return (READ_BIT(PMU->CSTS, PMU_CSTS_BKPREN) == (PMU_CSTS_BKPREN)); +} + +/** + * @brief Set voltage Regulator mode during deep sleep mode + * @param RegulMode This parameter can be one of the following values: + * @arg @ref DDL_PMU_REGU_DSMODE_MAIN + * @arg @ref DDL_PMU_REGU_DSMODE_LOW_POWER + * @retval None + */ +__STATIC_INLINE void DDL_PMU_SetRegulModeDS(uint32_t RegulMode) +{ + MODIFY_REG(PMU->CTRL, PMU_CTRL_LPDSCFG, RegulMode); +} + +/** + * @brief Get voltage Regulator mode during deep sleep mode + * @retval Returned value can be one of the following values: + * @arg @ref DDL_PMU_REGU_DSMODE_MAIN + * @arg @ref DDL_PMU_REGU_DSMODE_LOW_POWER + */ +__STATIC_INLINE uint32_t DDL_PMU_GetRegulModeDS(void) +{ + return (uint32_t)(READ_BIT(PMU->CTRL, PMU_CTRL_LPDSCFG)); +} + +/** + * @brief Set Power Down mode when CPU enters deepsleep + * @param PDMode This parameter can be one of the following values: + * @arg @ref DDL_PMU_MODE_STOP_MAINREGU + * @arg @ref DDL_PMU_MODE_STOP_LPREGU + * @arg @ref DDL_PMU_MODE_STOP_MAINREGU_UNDERDRIVE (*) + * @arg @ref DDL_PMU_MODE_STOP_LPREGU_UNDERDRIVE (*) + * @arg @ref DDL_PMU_MODE_STOP_MAINREGU_DEEPSLEEP (*) + * @arg @ref DDL_PMU_MODE_STOP_LPREGU_DEEPSLEEP (*) + * + * (*) not available on all devices + * @arg @ref DDL_PMU_MODE_STANDBY + * @retval None + */ +__STATIC_INLINE void DDL_PMU_SetPowerMode(uint32_t PDMode) +{ +#if defined(PMU_CTRL_MRUDS) && defined(PMU_CTRL_LPUDS) && defined(PMU_CTRL_FPDSM) + MODIFY_REG(PMU->CTRL, (PMU_CTRL_PDDSCFG | PMU_CTRL_LPDSCFG | PMU_CTRL_FPDSM | PMU_CTRL_LPUDS | PMU_CTRL_MRUDS), PDMode); +#elif defined(PMU_CTRL_MRLV) && defined(PMU_CTRL_LPRLV) && defined(PMU_CTRL_FPDSM) + MODIFY_REG(PMU->CTRL, (PMU_CTRL_PDDSCFG | PMU_CTRL_LPDSCFG | PMU_CTRL_FPDSM | PMU_CTRL_LPRLV | PMU_CTRL_MRLV), PDMode); +#else + MODIFY_REG(PMU->CTRL, (PMU_CTRL_PDDSCFG| PMU_CTRL_LPDSCFG), PDMode); +#endif /* PMU_CTRL_MRUDS && PMU_CTRL_LPUDS && PMU_CTRL_FPDSM */ +} + +/** + * @brief Get Power Down mode when CPU enters deepsleep + * @retval Returned value can be one of the following values: + * @arg @ref DDL_PMU_MODE_STOP_MAINREGU + * @arg @ref DDL_PMU_MODE_STOP_LPREGU + * @arg @ref DDL_PMU_MODE_STOP_MAINREGU_UNDERDRIVE (*) + * @arg @ref DDL_PMU_MODE_STOP_LPREGU_UNDERDRIVE (*) + * @arg @ref DDL_PMU_MODE_STOP_MAINREGU_DEEPSLEEP (*) + * @arg @ref DDL_PMU_MODE_STOP_LPREGU_DEEPSLEEP (*) + * + * (*) not available on all devices + * @arg @ref DDL_PMU_MODE_STANDBY + */ +__STATIC_INLINE uint32_t DDL_PMU_GetPowerMode(void) +{ +#if defined(PMU_CTRL_MRUDS) && defined(PMU_CTRL_LPUDS) && defined(PMU_CTRL_FPDSM) + return (uint32_t)(READ_BIT(PMU->CTRL, (PMU_CTRL_PDDSCFG | PMU_CTRL_LPDSCFG | PMU_CTRL_FPDSM | PMU_CTRL_LPUDS | PMU_CTRL_MRUDS))); +#elif defined(PMU_CTRL_MRLV) && defined(PMU_CTRL_LPRLV) && defined(PMU_CTRL_FPDSM) + return (uint32_t)(READ_BIT(PMU->CTRL, (PMU_CTRL_PDDSCFG | PMU_CTRL_LPDSCFG | PMU_CTRL_FPDSM | PMU_CTRL_LPRLV | PMU_CTRL_MRLV))); +#else + return (uint32_t)(READ_BIT(PMU->CTRL, (PMU_CTRL_PDDSCFG| PMU_CTRL_LPDSCFG))); +#endif /* PMU_CTRL_MRUDS && PMU_CTRL_LPUDS && PMU_CTRL_FPDSM */ +} + +/** + * @brief Configure the voltage threshold detected by the Power Voltage Detector + * @param PVDLevel This parameter can be one of the following values: + * @arg @ref DDL_PMU_PVDLEVEL_0 + * @arg @ref DDL_PMU_PVDLEVEL_1 + * @arg @ref DDL_PMU_PVDLEVEL_2 + * @arg @ref DDL_PMU_PVDLEVEL_3 + * @arg @ref DDL_PMU_PVDLEVEL_4 + * @arg @ref DDL_PMU_PVDLEVEL_5 + * @arg @ref DDL_PMU_PVDLEVEL_6 + * @arg @ref DDL_PMU_PVDLEVEL_7 + * @retval None + */ +__STATIC_INLINE void DDL_PMU_SetPVDLevel(uint32_t PVDLevel) +{ + MODIFY_REG(PMU->CTRL, PMU_CTRL_PLSEL, PVDLevel); +} + +/** + * @brief Get the voltage threshold detection + * @retval Returned value can be one of the following values: + * @arg @ref DDL_PMU_PVDLEVEL_0 + * @arg @ref DDL_PMU_PVDLEVEL_1 + * @arg @ref DDL_PMU_PVDLEVEL_2 + * @arg @ref DDL_PMU_PVDLEVEL_3 + * @arg @ref DDL_PMU_PVDLEVEL_4 + * @arg @ref DDL_PMU_PVDLEVEL_5 + * @arg @ref DDL_PMU_PVDLEVEL_6 + * @arg @ref DDL_PMU_PVDLEVEL_7 + */ +__STATIC_INLINE uint32_t DDL_PMU_GetPVDLevel(void) +{ + return (uint32_t)(READ_BIT(PMU->CTRL, PMU_CTRL_PLSEL)); +} + +/** + * @brief Enable Power Voltage Detector + * @retval None + */ +__STATIC_INLINE void DDL_PMU_EnablePVD(void) +{ + SET_BIT(PMU->CTRL, PMU_CTRL_PVDEN); +} + +/** + * @brief Disable Power Voltage Detector + * @retval None + */ +__STATIC_INLINE void DDL_PMU_DisablePVD(void) +{ + CLEAR_BIT(PMU->CTRL, PMU_CTRL_PVDEN); +} + +/** + * @brief Check if Power Voltage Detector is enabled + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_PMU_IsEnabledPVD(void) +{ + return (READ_BIT(PMU->CTRL, PMU_CTRL_PVDEN) == (PMU_CTRL_PVDEN)); +} + +/** + * @brief Enable the WakeUp PINx functionality + * @param WakeUpPin This parameter can be one of the following values: + * @arg @ref DDL_PMU_WAKEUP_PIN1 + * @arg @ref DDL_PMU_WAKEUP_PIN2 (*) + * @arg @ref DDL_PMU_WAKEUP_PIN3 (*) + * + * (*) not available on all devices + * @retval None + */ +__STATIC_INLINE void DDL_PMU_EnableWakeUpPin(uint32_t WakeUpPin) +{ + SET_BIT(PMU->CSTS, WakeUpPin); +} + +/** + * @brief Disable the WakeUp PINx functionality + * @param WakeUpPin This parameter can be one of the following values: + * @arg @ref DDL_PMU_WAKEUP_PIN1 + * @arg @ref DDL_PMU_WAKEUP_PIN2 (*) + * @arg @ref DDL_PMU_WAKEUP_PIN3 (*) + * + * (*) not available on all devices + * @retval None + */ +__STATIC_INLINE void DDL_PMU_DisableWakeUpPin(uint32_t WakeUpPin) +{ + CLEAR_BIT(PMU->CSTS, WakeUpPin); +} + +/** + * @brief Check if the WakeUp PINx functionality is enabled + * @param WakeUpPin This parameter can be one of the following values: + * @arg @ref DDL_PMU_WAKEUP_PIN1 + * @arg @ref DDL_PMU_WAKEUP_PIN2 (*) + * @arg @ref DDL_PMU_WAKEUP_PIN3 (*) + * + * (*) not available on all devices + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_PMU_IsEnabledWakeUpPin(uint32_t WakeUpPin) +{ + return (READ_BIT(PMU->CSTS, WakeUpPin) == (WakeUpPin)); +} + + +/** + * @} + */ + +/** @defgroup PMU_DDL_EF_FLAG_Management FLAG_Management + * @{ + */ + +/** + * @brief Get Wake-up Flag + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_PMU_IsActiveFlag_WU(void) +{ + return (READ_BIT(PMU->CSTS, PMU_CSTS_WUEFLG) == (PMU_CSTS_WUEFLG)); +} + +/** + * @brief Get Standby Flag + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_PMU_IsActiveFlag_SB(void) +{ + return (READ_BIT(PMU->CSTS, PMU_CSTS_SBFLG) == (PMU_CSTS_SBFLG)); +} + +/** + * @brief Get Backup Regulator ready Flag + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_PMU_IsActiveFlag_BRR(void) +{ + return (READ_BIT(PMU->CSTS, PMU_CSTS_BKPRFLG) == (PMU_CSTS_BKPRFLG)); +} +/** + * @brief Indicate whether VDD voltage is below the selected PVD threshold + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_PMU_IsActiveFlag_PVDO(void) +{ + return (READ_BIT(PMU->CSTS, PMU_CSTS_PVDOFLG) == (PMU_CSTS_PVDOFLG)); +} + +/** + * @brief Indicate whether the Regulator is ready in the selected voltage range or if its output voltage is still changing to the required voltage level + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_PMU_IsActiveFlag_VOS(void) +{ + return (READ_BIT(PMU->CSTS, DDL_PMU_CSTS_VOS) == (DDL_PMU_CSTS_VOS)); +} +#if defined(PMU_CTRL_ODEN) +/** + * @brief Indicate whether the Over-Drive mode is ready or not + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_PMU_IsActiveFlag_OD(void) +{ + return (READ_BIT(PMU->CSTS, PMU_CSTS_ODRDY) == (PMU_CSTS_ODRDY)); +} +#endif /* PMU_CTRL_ODEN */ + +#if defined(PMU_CTRL_ODSWEN) +/** + * @brief Indicate whether the Over-Drive mode switching is ready or not + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_PMU_IsActiveFlag_ODSW(void) +{ + return (READ_BIT(PMU->CSTS, PMU_CSTS_ODSWRDY) == (PMU_CSTS_ODSWRDY)); +} +#endif /* PMU_CTRL_ODSWEN */ + +#if defined(PMU_CTRL_UDEN) +/** + * @brief Indicate whether the Under-Drive mode is ready or not + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_PMU_IsActiveFlag_UD(void) +{ + return (READ_BIT(PMU->CSTS, PMU_CSTS_UDRDY) == (PMU_CSTS_UDRDY)); +} +#endif /* PMU_CTRL_UDEN */ +/** + * @brief Clear Standby Flag + * @retval None + */ +__STATIC_INLINE void DDL_PMU_ClearFlag_SB(void) +{ + SET_BIT(PMU->CTRL, PMU_CTRL_SBFLGCLR); +} + +/** + * @brief Clear Wake-up Flags + * @retval None + */ +__STATIC_INLINE void DDL_PMU_ClearFlag_WU(void) +{ + SET_BIT(PMU->CTRL, PMU_CTRL_WUFLGCLR); +} +#if defined(PMU_CSTS_UDRDY) +/** + * @brief Clear Under-Drive ready Flag + * @retval None + */ +__STATIC_INLINE void DDL_PMU_ClearFlag_UD(void) +{ + WRITE_REG(PMU->CSTS, PMU_CSTS_UDRDY); +} +#endif /* PMU_CSTS_UDRDY */ + +/** + * @} + */ + +#if defined(USE_FULL_DDL_DRIVER) +/** @defgroup PMU_DDL_EF_Init De-initialization function + * @{ + */ +ErrorStatus DDL_PMU_DeInit(void); +/** + * @} + */ +#endif /* USE_FULL_DDL_DRIVER */ + +/** + * @} + */ + +/** + * @} + */ + +#endif /* defined(PMU) */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* APM32F4xx_DDL_PMU_H */ diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_rcm.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_rcm.h new file mode 100644 index 0000000000..349fb70fb9 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_rcm.h @@ -0,0 +1,2900 @@ +/** + * + * @file apm32f4xx_ddl_rcm.h + * @brief Header file of RCM DDL module. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2017 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file in + * the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef APM32F4xx_DDL_RCM_H +#define APM32F4xx_DDL_RCM_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx.h" + +/** @addtogroup APM32F4xx_DDL_Driver + * @{ + */ + +#if defined(RCM) + +/** @defgroup RCM_DDL RCM + * @{ + */ + +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/** @defgroup RCM_DDL_Private_Variables RCM Private Variables + * @{ + */ + +/** + * @} + */ +/* Private constants ---------------------------------------------------------*/ +/* Private macros ------------------------------------------------------------*/ +#if defined(USE_FULL_DDL_DRIVER) +/** @defgroup RCM_DDL_Private_Macros RCM Private Macros + * @{ + */ +/** + * @} + */ +#endif /*USE_FULL_DDL_DRIVER*/ +/* Exported types ------------------------------------------------------------*/ +#if defined(USE_FULL_DDL_DRIVER) +/** @defgroup RCM_DDL_Exported_Types RCM Exported Types + * @{ + */ + +/** @defgroup DDL_ES_CLOCK_FREQ Clocks Frequency Structure + * @{ + */ + +/** + * @brief RCM Clocks Frequency Structure + */ +typedef struct +{ + uint32_t SYSCLK_Frequency; /*!< SYSCLK clock frequency */ + uint32_t HCLK_Frequency; /*!< HCLK clock frequency */ + uint32_t PCLK1_Frequency; /*!< PCLK1 clock frequency */ + uint32_t PCLK2_Frequency; /*!< PCLK2 clock frequency */ +} DDL_RCM_ClocksTypeDef; + +/** + * @} + */ + +/** + * @} + */ +#endif /* USE_FULL_DDL_DRIVER */ + +/* Exported constants --------------------------------------------------------*/ +/** @defgroup RCM_DDL_Exported_Constants RCM Exported Constants + * @{ + */ + +/** @defgroup RCM_DDL_EC_OSC_VALUES Oscillator Values adaptation + * @brief Defines used to adapt values of different oscillators + * @note These values could be modified in the user environment according to + * HW set-up. + * @{ + */ +#if !defined (HSE_VALUE) +#define HSE_VALUE 25000000U /*!< Value of the HSE oscillator in Hz */ +#endif /* HSE_VALUE */ + +#if !defined (HSI_VALUE) +#define HSI_VALUE 16000000U /*!< Value of the HSI oscillator in Hz */ +#endif /* HSI_VALUE */ + +#if !defined (LSE_VALUE) +#define LSE_VALUE 32768U /*!< Value of the LSE oscillator in Hz */ +#endif /* LSE_VALUE */ + +#if !defined (LSI_VALUE) +#define LSI_VALUE 32000U /*!< Value of the LSI oscillator in Hz */ +#endif /* LSI_VALUE */ + +#if !defined (EXTERNAL_CLOCK_VALUE) +#define EXTERNAL_CLOCK_VALUE 12288000U /*!< Value of the I2S_CKIN external oscillator in Hz */ +#endif /* EXTERNAL_CLOCK_VALUE */ +/** + * @} + */ + +/** @defgroup RCM_DDL_EC_CLEAR_FLAG Clear Flags Defines + * @brief Flags defines which can be used with DDL_RCM_WriteReg function + * @{ + */ +#define DDL_RCM_INT_LSIRDYCLR RCM_INT_LSIRDYCLR /*!< LSI Ready Interrupt Clear */ +#define DDL_RCM_INT_LSERDYCLR RCM_INT_LSERDYCLR /*!< LSE Ready Interrupt Clear */ +#define DDL_RCM_INT_HSIRDYCLR RCM_INT_HSIRDYCLR /*!< HSI Ready Interrupt Clear */ +#define DDL_RCM_INT_HSERDYCLR RCM_INT_HSERDYCLR /*!< HSE Ready Interrupt Clear */ +#define DDL_RCM_INT_PLL1RDYCLR RCM_INT_PLL1RDYCLR /*!< PLL Ready Interrupt Clear */ +#if defined(RCM_PLLI2S_SUPPORT) +#define DDL_RCM_INT_PLL2RDYCLR RCM_INT_PLL2RDYCLR /*!< PLLI2S Ready Interrupt Clear */ +#endif /* RCM_PLLI2S_SUPPORT */ +#define DDL_RCM_INT_CSSCLR RCM_INT_CSSCLR /*!< Clock Security System Interrupt Clear */ +/** + * @} + */ + +/** @defgroup RCM_DDL_EC_GET_FLAG Get Flags Defines + * @brief Flags defines which can be used with DDL_RCM_ReadReg function + * @{ + */ +#define DDL_RCM_INT_LSIRDYFLG RCM_INT_LSIRDYFLG /*!< LSI Ready Interrupt flag */ +#define DDL_RCM_INT_LSERDYFLG RCM_INT_LSERDYFLG /*!< LSE Ready Interrupt flag */ +#define DDL_RCM_INT_HSIRDYFLG RCM_INT_HSIRDYFLG /*!< HSI Ready Interrupt flag */ +#define DDL_RCM_INT_HSERDYFLG RCM_INT_HSERDYFLG /*!< HSE Ready Interrupt flag */ +#define DDL_RCM_INT_PLL1RDYFLG RCM_INT_PLL1RDYFLG /*!< PLL Ready Interrupt flag */ +#if defined(RCM_PLLI2S_SUPPORT) +#define DDL_RCM_INT_PLL2RDYFLG RCM_INT_PLL2RDYFLG /*!< PLLI2S Ready Interrupt flag */ +#endif /* RCM_PLLI2S_SUPPORT */ +#define DDL_RCM_INT_CSSFLG RCM_INT_CSSFLG /*!< Clock Security System Interrupt flag */ +#define DDL_RCM_CSTS_LPWRRSTFLG RCM_CSTS_LPWRRSTFLG /*!< Low-Power reset flag */ +#define DDL_RCM_CSTS_PINRSTFLG RCM_CSTS_PINRSTFLG /*!< PIN reset flag */ +#define DDL_RCM_CSTS_PODRSTFLG RCM_CSTS_PODRSTFLG /*!< POR/PDR reset flag */ +#define DDL_RCM_CSTS_SWRSTFLG RCM_CSTS_SWRSTFLG /*!< Software Reset flag */ +#define DDL_RCM_CSTS_IWDTRSTFLG RCM_CSTS_IWDTRSTFLG /*!< Independent Watchdog reset flag */ +#define DDL_RCM_CSTS_WWDTRSTFLG RCM_CSTS_WWDTRSTFLG /*!< Window watchdog reset flag */ +#if defined(RCM_CSTS_BORRSTFLG) +#define DDL_RCM_CSTS_BORRSTFLG RCM_CSTS_BORRSTFLG /*!< BOR reset flag */ +#endif /* RCM_CSTS_BORRSTFLG */ +/** + * @} + */ + +/** @defgroup RCM_DDL_EC_IT IT Defines + * @brief IT defines which can be used with DDL_RCM_ReadReg and DDL_RCM_WriteReg functions + * @{ + */ +#define DDL_RCM_INT_LSIRDYEN RCM_INT_LSIRDYEN /*!< LSI Ready Interrupt Enable */ +#define DDL_RCM_INT_LSERDYEN RCM_INT_LSERDYEN /*!< LSE Ready Interrupt Enable */ +#define DDL_RCM_INT_HSIRDYEN RCM_INT_HSIRDYEN /*!< HSI Ready Interrupt Enable */ +#define DDL_RCM_INT_HSERDYEN RCM_INT_HSERDYEN /*!< HSE Ready Interrupt Enable */ +#define DDL_RCM_INT_PLL1RDYEN RCM_INT_PLL1RDYEN /*!< PLL Ready Interrupt Enable */ +#if defined(RCM_PLLI2S_SUPPORT) +#define DDL_RCM_INT_PLL2RDYEN RCM_INT_PLL2RDYEN /*!< PLLI2S Ready Interrupt Enable */ +#endif /* RCM_PLLI2S_SUPPORT */ +/** + * @} + */ + +/** @defgroup RCM_DDL_EC_SYS_CLKSOURCE System clock switch + * @{ + */ +#define DDL_RCM_SYS_CLKSOURCE_HSI RCM_CFG_SCLKSEL_HSI /*!< HSI selection as system clock */ +#define DDL_RCM_SYS_CLKSOURCE_HSE RCM_CFG_SCLKSEL_HSE /*!< HSE selection as system clock */ +#define DDL_RCM_SYS_CLKSOURCE_PLL RCM_CFG_SCLKSEL_PLL /*!< PLL selection as system clock */ +/** + * @} + */ + +/** @defgroup RCM_DDL_EC_SYS_CLKSOURCE_STATUS System clock switch status + * @{ + */ +#define DDL_RCM_SYS_CLKSOURCE_STATUS_HSI RCM_CFG_SCLKSWSTS_HSI /*!< HSI used as system clock */ +#define DDL_RCM_SYS_CLKSOURCE_STATUS_HSE RCM_CFG_SCLKSWSTS_HSE /*!< HSE used as system clock */ +#define DDL_RCM_SYS_CLKSOURCE_STATUS_PLL RCM_CFG_SCLKSWSTS_PLL /*!< PLL used as system clock */ +/** + * @} + */ + +/** @defgroup RCM_DDL_EC_SYSCLK_DIV AHB prescaler + * @{ + */ +#define DDL_RCM_SYSCLK_DIV_1 RCM_CFG_AHBPSC_DIV1 /*!< SYSCLK not divided */ +#define DDL_RCM_SYSCLK_DIV_2 RCM_CFG_AHBPSC_DIV2 /*!< SYSCLK divided by 2 */ +#define DDL_RCM_SYSCLK_DIV_4 RCM_CFG_AHBPSC_DIV4 /*!< SYSCLK divided by 4 */ +#define DDL_RCM_SYSCLK_DIV_8 RCM_CFG_AHBPSC_DIV8 /*!< SYSCLK divided by 8 */ +#define DDL_RCM_SYSCLK_DIV_16 RCM_CFG_AHBPSC_DIV16 /*!< SYSCLK divided by 16 */ +#define DDL_RCM_SYSCLK_DIV_64 RCM_CFG_AHBPSC_DIV64 /*!< SYSCLK divided by 64 */ +#define DDL_RCM_SYSCLK_DIV_128 RCM_CFG_AHBPSC_DIV128 /*!< SYSCLK divided by 128 */ +#define DDL_RCM_SYSCLK_DIV_256 RCM_CFG_AHBPSC_DIV256 /*!< SYSCLK divided by 256 */ +#define DDL_RCM_SYSCLK_DIV_512 RCM_CFG_AHBPSC_DIV512 /*!< SYSCLK divided by 512 */ +/** + * @} + */ + +/** @defgroup RCM_DDL_EC_APB1_DIV APB low-speed prescaler (APB1) + * @{ + */ +#define DDL_RCM_APB1_DIV_1 RCM_CFG_APB1PSC_DIV1 /*!< HCLK not divided */ +#define DDL_RCM_APB1_DIV_2 RCM_CFG_APB1PSC_DIV2 /*!< HCLK divided by 2 */ +#define DDL_RCM_APB1_DIV_4 RCM_CFG_APB1PSC_DIV4 /*!< HCLK divided by 4 */ +#define DDL_RCM_APB1_DIV_8 RCM_CFG_APB1PSC_DIV8 /*!< HCLK divided by 8 */ +#define DDL_RCM_APB1_DIV_16 RCM_CFG_APB1PSC_DIV16 /*!< HCLK divided by 16 */ +/** + * @} + */ + +/** @defgroup RCM_DDL_EC_APB2_DIV APB high-speed prescaler (APB2) + * @{ + */ +#define DDL_RCM_APB2_DIV_1 RCM_CFG_APB2PSC_DIV1 /*!< HCLK not divided */ +#define DDL_RCM_APB2_DIV_2 RCM_CFG_APB2PSC_DIV2 /*!< HCLK divided by 2 */ +#define DDL_RCM_APB2_DIV_4 RCM_CFG_APB2PSC_DIV4 /*!< HCLK divided by 4 */ +#define DDL_RCM_APB2_DIV_8 RCM_CFG_APB2PSC_DIV8 /*!< HCLK divided by 8 */ +#define DDL_RCM_APB2_DIV_16 RCM_CFG_APB2PSC_DIV16 /*!< HCLK divided by 16 */ +/** + * @} + */ + +/** @defgroup RCM_DDL_EC_MCOxSOURCE MCO source selection + * @{ + */ +#define DDL_RCM_MCO1SOURCE_HSI (uint32_t)(RCM_CFG_MCO1SEL|0x00000000U) /*!< HSI selection as MCO1 source */ +#define DDL_RCM_MCO1SOURCE_LSE (uint32_t)(RCM_CFG_MCO1SEL|(RCM_CFG_MCO1SEL_0 >> 16U)) /*!< LSE selection as MCO1 source */ +#define DDL_RCM_MCO1SOURCE_HSE (uint32_t)(RCM_CFG_MCO1SEL|(RCM_CFG_MCO1SEL_1 >> 16U)) /*!< HSE selection as MCO1 source */ +#define DDL_RCM_MCO1SOURCE_PLLCLK (uint32_t)(RCM_CFG_MCO1SEL|((RCM_CFG_MCO1SEL_1|RCM_CFG_MCO1SEL_0) >> 16U)) /*!< PLLCLK selection as MCO1 source */ +#if defined(RCM_CFG_MCO2SEL) +#define DDL_RCM_MCO2SOURCE_SYSCLK (uint32_t)(RCM_CFG_MCO2SEL|0x00000000U) /*!< SYSCLK selection as MCO2 source */ +#define DDL_RCM_MCO2SOURCE_PLLI2S (uint32_t)(RCM_CFG_MCO2SEL|(RCM_CFG_MCO2SEL_0 >> 16U)) /*!< PLLI2S selection as MCO2 source */ +#define DDL_RCM_MCO2SOURCE_HSE (uint32_t)(RCM_CFG_MCO2SEL|(RCM_CFG_MCO2SEL_1 >> 16U)) /*!< HSE selection as MCO2 source */ +#define DDL_RCM_MCO2SOURCE_PLLCLK (uint32_t)(RCM_CFG_MCO2SEL|((RCM_CFG_MCO2SEL_1|RCM_CFG_MCO2SEL_0) >> 16U)) /*!< PLLCLK selection as MCO2 source */ +#endif /* RCM_CFG_MCO2SEL */ +/** + * @} + */ + +/** @defgroup RCM_DDL_EC_MCOx_DIV MCO prescaler + * @{ + */ +#define DDL_RCM_MCO1_DIV_1 (uint32_t)(RCM_CFG_MCO1PSC|0x00000000U) /*!< MCO1 not divided */ +#define DDL_RCM_MCO1_DIV_2 (uint32_t)(RCM_CFG_MCO1PSC|(RCM_CFG_MCO1PSC_2 >> 16U)) /*!< MCO1 divided by 2 */ +#define DDL_RCM_MCO1_DIV_3 (uint32_t)(RCM_CFG_MCO1PSC|((RCM_CFG_MCO1PSC_2|RCM_CFG_MCO1PSC_0) >> 16U)) /*!< MCO1 divided by 3 */ +#define DDL_RCM_MCO1_DIV_4 (uint32_t)(RCM_CFG_MCO1PSC|((RCM_CFG_MCO1PSC_2|RCM_CFG_MCO1PSC_1) >> 16U)) /*!< MCO1 divided by 4 */ +#define DDL_RCM_MCO1_DIV_5 (uint32_t)(RCM_CFG_MCO1PSC|(RCM_CFG_MCO1PSC >> 16U)) /*!< MCO1 divided by 5 */ +#if defined(RCM_CFG_MCO2PSC) +#define DDL_RCM_MCO2_DIV_1 (uint32_t)(RCM_CFG_MCO2PSC|0x00000000U) /*!< MCO2 not divided */ +#define DDL_RCM_MCO2_DIV_2 (uint32_t)(RCM_CFG_MCO2PSC|(RCM_CFG_MCO2PSC_2 >> 16U)) /*!< MCO2 divided by 2 */ +#define DDL_RCM_MCO2_DIV_3 (uint32_t)(RCM_CFG_MCO2PSC|((RCM_CFG_MCO2PSC_2|RCM_CFG_MCO2PSC_0) >> 16U)) /*!< MCO2 divided by 3 */ +#define DDL_RCM_MCO2_DIV_4 (uint32_t)(RCM_CFG_MCO2PSC|((RCM_CFG_MCO2PSC_2|RCM_CFG_MCO2PSC_1) >> 16U)) /*!< MCO2 divided by 4 */ +#define DDL_RCM_MCO2_DIV_5 (uint32_t)(RCM_CFG_MCO2PSC|(RCM_CFG_MCO2PSC >> 16U)) /*!< MCO2 divided by 5 */ +#endif /* RCM_CFG_MCO2PSC */ +/** + * @} + */ + +/** @defgroup RCM_DDL_EC_RTC_HSEDIV HSE prescaler for RTC clock + * @{ + */ +#define DDL_RCM_RTC_NOCLOCK 0x00000000U /*!< HSE not divided */ +#define DDL_RCM_RTC_HSE_DIV_2 RCM_CFG_RTCPSC_1 /*!< HSE clock divided by 2 */ +#define DDL_RCM_RTC_HSE_DIV_3 (RCM_CFG_RTCPSC_1|RCM_CFG_RTCPSC_0) /*!< HSE clock divided by 3 */ +#define DDL_RCM_RTC_HSE_DIV_4 RCM_CFG_RTCPSC_2 /*!< HSE clock divided by 4 */ +#define DDL_RCM_RTC_HSE_DIV_5 (RCM_CFG_RTCPSC_2|RCM_CFG_RTCPSC_0) /*!< HSE clock divided by 5 */ +#define DDL_RCM_RTC_HSE_DIV_6 (RCM_CFG_RTCPSC_2|RCM_CFG_RTCPSC_1) /*!< HSE clock divided by 6 */ +#define DDL_RCM_RTC_HSE_DIV_7 (RCM_CFG_RTCPSC_2|RCM_CFG_RTCPSC_1|RCM_CFG_RTCPSC_0) /*!< HSE clock divided by 7 */ +#define DDL_RCM_RTC_HSE_DIV_8 RCM_CFG_RTCPSC_3 /*!< HSE clock divided by 8 */ +#define DDL_RCM_RTC_HSE_DIV_9 (RCM_CFG_RTCPSC_3|RCM_CFG_RTCPSC_0) /*!< HSE clock divided by 9 */ +#define DDL_RCM_RTC_HSE_DIV_10 (RCM_CFG_RTCPSC_3|RCM_CFG_RTCPSC_1) /*!< HSE clock divided by 10 */ +#define DDL_RCM_RTC_HSE_DIV_11 (RCM_CFG_RTCPSC_3|RCM_CFG_RTCPSC_1|RCM_CFG_RTCPSC_0) /*!< HSE clock divided by 11 */ +#define DDL_RCM_RTC_HSE_DIV_12 (RCM_CFG_RTCPSC_3|RCM_CFG_RTCPSC_2) /*!< HSE clock divided by 12 */ +#define DDL_RCM_RTC_HSE_DIV_13 (RCM_CFG_RTCPSC_3|RCM_CFG_RTCPSC_2|RCM_CFG_RTCPSC_0) /*!< HSE clock divided by 13 */ +#define DDL_RCM_RTC_HSE_DIV_14 (RCM_CFG_RTCPSC_3|RCM_CFG_RTCPSC_2|RCM_CFG_RTCPSC_1) /*!< HSE clock divided by 14 */ +#define DDL_RCM_RTC_HSE_DIV_15 (RCM_CFG_RTCPSC_3|RCM_CFG_RTCPSC_2|RCM_CFG_RTCPSC_1|RCM_CFG_RTCPSC_0) /*!< HSE clock divided by 15 */ +#define DDL_RCM_RTC_HSE_DIV_16 RCM_CFG_RTCPSC_4 /*!< HSE clock divided by 16 */ +#define DDL_RCM_RTC_HSE_DIV_17 (RCM_CFG_RTCPSC_4|RCM_CFG_RTCPSC_0) /*!< HSE clock divided by 17 */ +#define DDL_RCM_RTC_HSE_DIV_18 (RCM_CFG_RTCPSC_4|RCM_CFG_RTCPSC_1) /*!< HSE clock divided by 18 */ +#define DDL_RCM_RTC_HSE_DIV_19 (RCM_CFG_RTCPSC_4|RCM_CFG_RTCPSC_1|RCM_CFG_RTCPSC_0) /*!< HSE clock divided by 19 */ +#define DDL_RCM_RTC_HSE_DIV_20 (RCM_CFG_RTCPSC_4|RCM_CFG_RTCPSC_2) /*!< HSE clock divided by 20 */ +#define DDL_RCM_RTC_HSE_DIV_21 (RCM_CFG_RTCPSC_4|RCM_CFG_RTCPSC_2|RCM_CFG_RTCPSC_0) /*!< HSE clock divided by 21 */ +#define DDL_RCM_RTC_HSE_DIV_22 (RCM_CFG_RTCPSC_4|RCM_CFG_RTCPSC_2|RCM_CFG_RTCPSC_1) /*!< HSE clock divided by 22 */ +#define DDL_RCM_RTC_HSE_DIV_23 (RCM_CFG_RTCPSC_4|RCM_CFG_RTCPSC_2|RCM_CFG_RTCPSC_1|RCM_CFG_RTCPSC_0) /*!< HSE clock divided by 23 */ +#define DDL_RCM_RTC_HSE_DIV_24 (RCM_CFG_RTCPSC_4|RCM_CFG_RTCPSC_3) /*!< HSE clock divided by 24 */ +#define DDL_RCM_RTC_HSE_DIV_25 (RCM_CFG_RTCPSC_4|RCM_CFG_RTCPSC_3|RCM_CFG_RTCPSC_0) /*!< HSE clock divided by 25 */ +#define DDL_RCM_RTC_HSE_DIV_26 (RCM_CFG_RTCPSC_4|RCM_CFG_RTCPSC_3|RCM_CFG_RTCPSC_1) /*!< HSE clock divided by 26 */ +#define DDL_RCM_RTC_HSE_DIV_27 (RCM_CFG_RTCPSC_4|RCM_CFG_RTCPSC_3|RCM_CFG_RTCPSC_1|RCM_CFG_RTCPSC_0) /*!< HSE clock divided by 27 */ +#define DDL_RCM_RTC_HSE_DIV_28 (RCM_CFG_RTCPSC_4|RCM_CFG_RTCPSC_3|RCM_CFG_RTCPSC_2) /*!< HSE clock divided by 28 */ +#define DDL_RCM_RTC_HSE_DIV_29 (RCM_CFG_RTCPSC_4|RCM_CFG_RTCPSC_3|RCM_CFG_RTCPSC_2|RCM_CFG_RTCPSC_0) /*!< HSE clock divided by 29 */ +#define DDL_RCM_RTC_HSE_DIV_30 (RCM_CFG_RTCPSC_4|RCM_CFG_RTCPSC_3|RCM_CFG_RTCPSC_2|RCM_CFG_RTCPSC_1) /*!< HSE clock divided by 30 */ +#define DDL_RCM_RTC_HSE_DIV_31 (RCM_CFG_RTCPSC_4|RCM_CFG_RTCPSC_3|RCM_CFG_RTCPSC_2|RCM_CFG_RTCPSC_1|RCM_CFG_RTCPSC_0) /*!< HSE clock divided by 31 */ +/** + * @} + */ + +#if defined(USE_FULL_DDL_DRIVER) +/** @defgroup RCM_DDL_EC_PERIPH_FREQUENCY Peripheral clock frequency + * @{ + */ +#define DDL_RCM_PERIPH_FREQUENCY_NO 0x00000000U /*!< No clock enabled for the peripheral */ +#define DDL_RCM_PERIPH_FREQUENCY_NA 0xFFFFFFFFU /*!< Frequency cannot be provided as external clock */ +/** + * @} + */ +#endif /* USE_FULL_DDL_DRIVER */ + +/** @defgroup RCM_DDL_EC_I2S1_CLKSOURCE Peripheral I2S clock source selection + * @{ + */ +#if defined(RCM_CFG_I2SSEL) +#define DDL_RCM_I2S1_CLKSOURCE_PLLI2S 0x00000000U /*!< I2S oscillator clock used as I2S1 clock */ +#define DDL_RCM_I2S1_CLKSOURCE_PIN RCM_CFG_I2SSEL /*!< External pin clock used as I2S1 clock */ +#endif /* RCM_CFG_I2SSEL */ +/** + * @} + */ + +#if defined(SDIO) +/** @defgroup RCM_DDL_EC_SDIOx Peripheral SDIO get clock source + * @{ + */ +#if defined(RCM_DCKCFGR_SDIOSEL) +#define DDL_RCM_SDIO_CLKSOURCE RCM_DCKCFGR_SDIOSEL /*!< SDIO Clock source selection */ +#elif defined(RCM_DCKCFGR2_SDIOSEL) +#define DDL_RCM_SDIO_CLKSOURCE RCM_DCKCFGR2_SDIOSEL /*!< SDIO Clock source selection */ +#else +#define DDL_RCM_SDIO_CLKSOURCE RCM_PLL1CFG_PLLD /*!< SDIO Clock source selection */ +#endif +/** + * @} + */ +#endif /* SDIO */ + +#if defined(RNG) +/** @defgroup RCM_DDL_EC_RNG Peripheral RNG get clock source + * @{ + */ +#if defined(RCM_DCKCFGR_CK48MSEL) || defined(RCM_DCKCFGR2_CK48MSEL) +#define DDL_RCM_RNG_CLKSOURCE DDL_RCM_CK48M_CLKSOURCE /*!< RNG Clock source selection */ +#else +#define DDL_RCM_RNG_CLKSOURCE RCM_PLL1CFG_PLLD /*!< RNG Clock source selection */ +#endif /* RCM_DCKCFGR_CK48MSEL || RCM_DCKCFGR2_CK48MSEL */ +/** + * @} + */ +#endif /* RNG */ + +#if defined(USB_OTG_FS) || defined(USB_OTG_HS) +/** @defgroup RCM_DDL_EC_USB Peripheral USB get clock source + * @{ + */ +#if defined(RCM_DCKCFGR_CK48MSEL) || defined(RCM_DCKCFGR2_CK48MSEL) +#define DDL_RCM_USB_CLKSOURCE DDL_RCM_CK48M_CLKSOURCE /*!< USB Clock source selection */ +#else +#define DDL_RCM_USB_CLKSOURCE RCM_PLL1CFG_PLLD /*!< USB Clock source selection */ +#endif /* RCM_DCKCFGR_CK48MSEL || RCM_DCKCFGR2_CK48MSEL */ +/** + * @} + */ +#endif /* USB_OTG_FS || USB_OTG_HS */ + + +/** @defgroup RCM_DDL_EC_I2S1 Peripheral I2S get clock source + * @{ + */ +#if defined(RCM_CFG_I2SSEL) +#define DDL_RCM_I2S1_CLKSOURCE RCM_CFG_I2SSEL /*!< I2S1 Clock source selection */ +#endif /* RCM_CFG_I2SSEL */ +/** + * @} + */ + + +/** @defgroup RCM_DDL_EC_RTC_CLKSOURCE RTC clock source selection + * @{ + */ +#define DDL_RCM_RTC_CLKSOURCE_NONE 0x00000000U /*!< No clock used as RTC clock */ +#define DDL_RCM_RTC_CLKSOURCE_LSE RCM_BDCTRL_RTCSRCSEL_0 /*!< LSE oscillator clock used as RTC clock */ +#define DDL_RCM_RTC_CLKSOURCE_LSI RCM_BDCTRL_RTCSRCSEL_1 /*!< LSI oscillator clock used as RTC clock */ +#define DDL_RCM_RTC_CLKSOURCE_HSE RCM_BDCTRL_RTCSRCSEL /*!< HSE oscillator clock divided by HSE prescaler used as RTC clock */ +/** + * @} + */ + +#if defined(RCM_CFGSEL_CLKPSEL) +/** @defgroup RCM_DDL_EC_TMR_CLKPRESCALER Timers clocks prescalers selection + * @{ + */ +#define DDL_RCM_TMR_PRESCALER_TWICE 0x00000000U /*!< Timers clock to twice PCLK */ +#define DDL_RCM_TMR_PRESCALER_FOUR_TIMES RCM_CFGSEL_CLKPSEL /*!< Timers clock to four time PCLK */ +/** + * @} + */ +#endif /* RCM_CFGSEL_CLKPSEL */ + +/** @defgroup RCM_DDL_EC_PLLSOURCE PLL, PLLI2S and PLLSAI entry clock source + * @{ + */ +#define DDL_RCM_PLLSOURCE_HSI RCM_PLL1CFG_PLL1CLKS_HSI /*!< HSI16 clock selected as PLL entry clock source */ +#define DDL_RCM_PLLSOURCE_HSE RCM_PLL1CFG_PLL1CLKS_HSE /*!< HSE clock selected as PLL entry clock source */ +/** + * @} + */ + +/** @defgroup RCM_DDL_EC_PLLB_DIV PLL, PLLI2S and PLLSAI division factor + * @{ + */ +#define DDL_RCM_PLLB_DIV_2 (RCM_PLL1CFG_PLLB_1) /*!< PLL, PLLI2S and PLLSAI division factor by 2 */ +#define DDL_RCM_PLLB_DIV_3 (RCM_PLL1CFG_PLLB_1 | RCM_PLL1CFG_PLLB_0) /*!< PLL, PLLI2S and PLLSAI division factor by 3 */ +#define DDL_RCM_PLLB_DIV_4 (RCM_PLL1CFG_PLLB_2) /*!< PLL, PLLI2S and PLLSAI division factor by 4 */ +#define DDL_RCM_PLLB_DIV_5 (RCM_PLL1CFG_PLLB_2 | RCM_PLL1CFG_PLLB_0) /*!< PLL, PLLI2S and PLLSAI division factor by 5 */ +#define DDL_RCM_PLLB_DIV_6 (RCM_PLL1CFG_PLLB_2 | RCM_PLL1CFG_PLLB_1) /*!< PLL, PLLI2S and PLLSAI division factor by 6 */ +#define DDL_RCM_PLLB_DIV_7 (RCM_PLL1CFG_PLLB_2 | RCM_PLL1CFG_PLLB_1 | RCM_PLL1CFG_PLLB_0) /*!< PLL, PLLI2S and PLLSAI division factor by 7 */ +#define DDL_RCM_PLLB_DIV_8 (RCM_PLL1CFG_PLLB_3) /*!< PLL, PLLI2S and PLLSAI division factor by 8 */ +#define DDL_RCM_PLLB_DIV_9 (RCM_PLL1CFG_PLLB_3 | RCM_PLL1CFG_PLLB_0) /*!< PLL, PLLI2S and PLLSAI division factor by 9 */ +#define DDL_RCM_PLLB_DIV_10 (RCM_PLL1CFG_PLLB_3 | RCM_PLL1CFG_PLLB_1) /*!< PLL, PLLI2S and PLLSAI division factor by 10 */ +#define DDL_RCM_PLLB_DIV_11 (RCM_PLL1CFG_PLLB_3 | RCM_PLL1CFG_PLLB_1 | RCM_PLL1CFG_PLLB_0) /*!< PLL, PLLI2S and PLLSAI division factor by 11 */ +#define DDL_RCM_PLLB_DIV_12 (RCM_PLL1CFG_PLLB_3 | RCM_PLL1CFG_PLLB_2) /*!< PLL, PLLI2S and PLLSAI division factor by 12 */ +#define DDL_RCM_PLLB_DIV_13 (RCM_PLL1CFG_PLLB_3 | RCM_PLL1CFG_PLLB_2 | RCM_PLL1CFG_PLLB_0) /*!< PLL, PLLI2S and PLLSAI division factor by 13 */ +#define DDL_RCM_PLLB_DIV_14 (RCM_PLL1CFG_PLLB_3 | RCM_PLL1CFG_PLLB_2 | RCM_PLL1CFG_PLLB_1) /*!< PLL, PLLI2S and PLLSAI division factor by 14 */ +#define DDL_RCM_PLLB_DIV_15 (RCM_PLL1CFG_PLLB_3 | RCM_PLL1CFG_PLLB_2 | RCM_PLL1CFG_PLLB_1 | RCM_PLL1CFG_PLLB_0) /*!< PLL, PLLI2S and PLLSAI division factor by 15 */ +#define DDL_RCM_PLLB_DIV_16 (RCM_PLL1CFG_PLLB_4) /*!< PLL, PLLI2S and PLLSAI division factor by 16 */ +#define DDL_RCM_PLLB_DIV_17 (RCM_PLL1CFG_PLLB_4 | RCM_PLL1CFG_PLLB_0) /*!< PLL, PLLI2S and PLLSAI division factor by 17 */ +#define DDL_RCM_PLLB_DIV_18 (RCM_PLL1CFG_PLLB_4 | RCM_PLL1CFG_PLLB_1) /*!< PLL, PLLI2S and PLLSAI division factor by 18 */ +#define DDL_RCM_PLLB_DIV_19 (RCM_PLL1CFG_PLLB_4 | RCM_PLL1CFG_PLLB_1 | RCM_PLL1CFG_PLLB_0) /*!< PLL, PLLI2S and PLLSAI division factor by 19 */ +#define DDL_RCM_PLLB_DIV_20 (RCM_PLL1CFG_PLLB_4 | RCM_PLL1CFG_PLLB_2) /*!< PLL, PLLI2S and PLLSAI division factor by 20 */ +#define DDL_RCM_PLLB_DIV_21 (RCM_PLL1CFG_PLLB_4 | RCM_PLL1CFG_PLLB_2 | RCM_PLL1CFG_PLLB_0) /*!< PLL, PLLI2S and PLLSAI division factor by 21 */ +#define DDL_RCM_PLLB_DIV_22 (RCM_PLL1CFG_PLLB_4 | RCM_PLL1CFG_PLLB_2 | RCM_PLL1CFG_PLLB_1) /*!< PLL, PLLI2S and PLLSAI division factor by 22 */ +#define DDL_RCM_PLLB_DIV_23 (RCM_PLL1CFG_PLLB_4 | RCM_PLL1CFG_PLLB_2 | RCM_PLL1CFG_PLLB_1 | RCM_PLL1CFG_PLLB_0) /*!< PLL, PLLI2S and PLLSAI division factor by 23 */ +#define DDL_RCM_PLLB_DIV_24 (RCM_PLL1CFG_PLLB_4 | RCM_PLL1CFG_PLLB_3) /*!< PLL, PLLI2S and PLLSAI division factor by 24 */ +#define DDL_RCM_PLLB_DIV_25 (RCM_PLL1CFG_PLLB_4 | RCM_PLL1CFG_PLLB_3 | RCM_PLL1CFG_PLLB_0) /*!< PLL, PLLI2S and PLLSAI division factor by 25 */ +#define DDL_RCM_PLLB_DIV_26 (RCM_PLL1CFG_PLLB_4 | RCM_PLL1CFG_PLLB_3 | RCM_PLL1CFG_PLLB_1) /*!< PLL, PLLI2S and PLLSAI division factor by 26 */ +#define DDL_RCM_PLLB_DIV_27 (RCM_PLL1CFG_PLLB_4 | RCM_PLL1CFG_PLLB_3 | RCM_PLL1CFG_PLLB_1 | RCM_PLL1CFG_PLLB_0) /*!< PLL, PLLI2S and PLLSAI division factor by 27 */ +#define DDL_RCM_PLLB_DIV_28 (RCM_PLL1CFG_PLLB_4 | RCM_PLL1CFG_PLLB_3 | RCM_PLL1CFG_PLLB_2) /*!< PLL, PLLI2S and PLLSAI division factor by 28 */ +#define DDL_RCM_PLLB_DIV_29 (RCM_PLL1CFG_PLLB_4 | RCM_PLL1CFG_PLLB_3 | RCM_PLL1CFG_PLLB_2 | RCM_PLL1CFG_PLLB_0) /*!< PLL, PLLI2S and PLLSAI division factor by 29 */ +#define DDL_RCM_PLLB_DIV_30 (RCM_PLL1CFG_PLLB_4 | RCM_PLL1CFG_PLLB_3 | RCM_PLL1CFG_PLLB_2 | RCM_PLL1CFG_PLLB_1) /*!< PLL, PLLI2S and PLLSAI division factor by 30 */ +#define DDL_RCM_PLLB_DIV_31 (RCM_PLL1CFG_PLLB_4 | RCM_PLL1CFG_PLLB_3 | RCM_PLL1CFG_PLLB_2 | RCM_PLL1CFG_PLLB_1 | RCM_PLL1CFG_PLLB_0) /*!< PLL, PLLI2S and PLLSAI division factor by 31 */ +#define DDL_RCM_PLLB_DIV_32 (RCM_PLL1CFG_PLLB_5) /*!< PLL, PLLI2S and PLLSAI division factor by 32 */ +#define DDL_RCM_PLLB_DIV_33 (RCM_PLL1CFG_PLLB_5 | RCM_PLL1CFG_PLLB_0) /*!< PLL, PLLI2S and PLLSAI division factor by 33 */ +#define DDL_RCM_PLLB_DIV_34 (RCM_PLL1CFG_PLLB_5 | RCM_PLL1CFG_PLLB_1) /*!< PLL, PLLI2S and PLLSAI division factor by 34 */ +#define DDL_RCM_PLLB_DIV_35 (RCM_PLL1CFG_PLLB_5 | RCM_PLL1CFG_PLLB_1 | RCM_PLL1CFG_PLLB_0) /*!< PLL, PLLI2S and PLLSAI division factor by 35 */ +#define DDL_RCM_PLLB_DIV_36 (RCM_PLL1CFG_PLLB_5 | RCM_PLL1CFG_PLLB_2) /*!< PLL, PLLI2S and PLLSAI division factor by 36 */ +#define DDL_RCM_PLLB_DIV_37 (RCM_PLL1CFG_PLLB_5 | RCM_PLL1CFG_PLLB_2 | RCM_PLL1CFG_PLLB_0) /*!< PLL, PLLI2S and PLLSAI division factor by 37 */ +#define DDL_RCM_PLLB_DIV_38 (RCM_PLL1CFG_PLLB_5 | RCM_PLL1CFG_PLLB_2 | RCM_PLL1CFG_PLLB_1) /*!< PLL, PLLI2S and PLLSAI division factor by 38 */ +#define DDL_RCM_PLLB_DIV_39 (RCM_PLL1CFG_PLLB_5 | RCM_PLL1CFG_PLLB_2 | RCM_PLL1CFG_PLLB_1 | RCM_PLL1CFG_PLLB_0) /*!< PLL, PLLI2S and PLLSAI division factor by 39 */ +#define DDL_RCM_PLLB_DIV_40 (RCM_PLL1CFG_PLLB_5 | RCM_PLL1CFG_PLLB_3) /*!< PLL, PLLI2S and PLLSAI division factor by 40 */ +#define DDL_RCM_PLLB_DIV_41 (RCM_PLL1CFG_PLLB_5 | RCM_PLL1CFG_PLLB_3 | RCM_PLL1CFG_PLLB_0) /*!< PLL, PLLI2S and PLLSAI division factor by 41 */ +#define DDL_RCM_PLLB_DIV_42 (RCM_PLL1CFG_PLLB_5 | RCM_PLL1CFG_PLLB_3 | RCM_PLL1CFG_PLLB_1) /*!< PLL, PLLI2S and PLLSAI division factor by 42 */ +#define DDL_RCM_PLLB_DIV_43 (RCM_PLL1CFG_PLLB_5 | RCM_PLL1CFG_PLLB_3 | RCM_PLL1CFG_PLLB_1 | RCM_PLL1CFG_PLLB_0) /*!< PLL, PLLI2S and PLLSAI division factor by 43 */ +#define DDL_RCM_PLLB_DIV_44 (RCM_PLL1CFG_PLLB_5 | RCM_PLL1CFG_PLLB_3 | RCM_PLL1CFG_PLLB_2) /*!< PLL, PLLI2S and PLLSAI division factor by 44 */ +#define DDL_RCM_PLLB_DIV_45 (RCM_PLL1CFG_PLLB_5 | RCM_PLL1CFG_PLLB_3 | RCM_PLL1CFG_PLLB_2 | RCM_PLL1CFG_PLLB_0) /*!< PLL, PLLI2S and PLLSAI division factor by 45 */ +#define DDL_RCM_PLLB_DIV_46 (RCM_PLL1CFG_PLLB_5 | RCM_PLL1CFG_PLLB_3 | RCM_PLL1CFG_PLLB_2 | RCM_PLL1CFG_PLLB_1) /*!< PLL, PLLI2S and PLLSAI division factor by 46 */ +#define DDL_RCM_PLLB_DIV_47 (RCM_PLL1CFG_PLLB_5 | RCM_PLL1CFG_PLLB_3 | RCM_PLL1CFG_PLLB_2 | RCM_PLL1CFG_PLLB_1 | RCM_PLL1CFG_PLLB_0) /*!< PLL, PLLI2S and PLLSAI division factor by 47 */ +#define DDL_RCM_PLLB_DIV_48 (RCM_PLL1CFG_PLLB_5 | RCM_PLL1CFG_PLLB_4) /*!< PLL, PLLI2S and PLLSAI division factor by 48 */ +#define DDL_RCM_PLLB_DIV_49 (RCM_PLL1CFG_PLLB_5 | RCM_PLL1CFG_PLLB_4 | RCM_PLL1CFG_PLLB_0) /*!< PLL, PLLI2S and PLLSAI division factor by 49 */ +#define DDL_RCM_PLLB_DIV_50 (RCM_PLL1CFG_PLLB_5 | RCM_PLL1CFG_PLLB_4 | RCM_PLL1CFG_PLLB_1) /*!< PLL, PLLI2S and PLLSAI division factor by 50 */ +#define DDL_RCM_PLLB_DIV_51 (RCM_PLL1CFG_PLLB_5 | RCM_PLL1CFG_PLLB_4 | RCM_PLL1CFG_PLLB_1 | RCM_PLL1CFG_PLLB_0) /*!< PLL, PLLI2S and PLLSAI division factor by 51 */ +#define DDL_RCM_PLLB_DIV_52 (RCM_PLL1CFG_PLLB_5 | RCM_PLL1CFG_PLLB_4 | RCM_PLL1CFG_PLLB_2) /*!< PLL, PLLI2S and PLLSAI division factor by 52 */ +#define DDL_RCM_PLLB_DIV_53 (RCM_PLL1CFG_PLLB_5 | RCM_PLL1CFG_PLLB_4 | RCM_PLL1CFG_PLLB_2 | RCM_PLL1CFG_PLLB_0) /*!< PLL, PLLI2S and PLLSAI division factor by 53 */ +#define DDL_RCM_PLLB_DIV_54 (RCM_PLL1CFG_PLLB_5 | RCM_PLL1CFG_PLLB_4 | RCM_PLL1CFG_PLLB_2 | RCM_PLL1CFG_PLLB_1) /*!< PLL, PLLI2S and PLLSAI division factor by 54 */ +#define DDL_RCM_PLLB_DIV_55 (RCM_PLL1CFG_PLLB_5 | RCM_PLL1CFG_PLLB_4 | RCM_PLL1CFG_PLLB_2 | RCM_PLL1CFG_PLLB_1 | RCM_PLL1CFG_PLLB_0) /*!< PLL, PLLI2S and PLLSAI division factor by 55 */ +#define DDL_RCM_PLLB_DIV_56 (RCM_PLL1CFG_PLLB_5 | RCM_PLL1CFG_PLLB_4 | RCM_PLL1CFG_PLLB_3) /*!< PLL, PLLI2S and PLLSAI division factor by 56 */ +#define DDL_RCM_PLLB_DIV_57 (RCM_PLL1CFG_PLLB_5 | RCM_PLL1CFG_PLLB_4 | RCM_PLL1CFG_PLLB_3 | RCM_PLL1CFG_PLLB_0) /*!< PLL, PLLI2S and PLLSAI division factor by 57 */ +#define DDL_RCM_PLLB_DIV_58 (RCM_PLL1CFG_PLLB_5 | RCM_PLL1CFG_PLLB_4 | RCM_PLL1CFG_PLLB_3 | RCM_PLL1CFG_PLLB_1) /*!< PLL, PLLI2S and PLLSAI division factor by 58 */ +#define DDL_RCM_PLLB_DIV_59 (RCM_PLL1CFG_PLLB_5 | RCM_PLL1CFG_PLLB_4 | RCM_PLL1CFG_PLLB_3 | RCM_PLL1CFG_PLLB_1 | RCM_PLL1CFG_PLLB_0) /*!< PLL, PLLI2S and PLLSAI division factor by 59 */ +#define DDL_RCM_PLLB_DIV_60 (RCM_PLL1CFG_PLLB_5 | RCM_PLL1CFG_PLLB_4 | RCM_PLL1CFG_PLLB_3 | RCM_PLL1CFG_PLLB_2) /*!< PLL, PLLI2S and PLLSAI division factor by 60 */ +#define DDL_RCM_PLLB_DIV_61 (RCM_PLL1CFG_PLLB_5 | RCM_PLL1CFG_PLLB_4 | RCM_PLL1CFG_PLLB_3 | RCM_PLL1CFG_PLLB_2 | RCM_PLL1CFG_PLLB_0) /*!< PLL, PLLI2S and PLLSAI division factor by 61 */ +#define DDL_RCM_PLLB_DIV_62 (RCM_PLL1CFG_PLLB_5 | RCM_PLL1CFG_PLLB_4 | RCM_PLL1CFG_PLLB_3 | RCM_PLL1CFG_PLLB_2 | RCM_PLL1CFG_PLLB_1) /*!< PLL, PLLI2S and PLLSAI division factor by 62 */ +#define DDL_RCM_PLLB_DIV_63 (RCM_PLL1CFG_PLLB_5 | RCM_PLL1CFG_PLLB_4 | RCM_PLL1CFG_PLLB_3 | RCM_PLL1CFG_PLLB_2 | RCM_PLL1CFG_PLLB_1 | RCM_PLL1CFG_PLLB_0) /*!< PLL, PLLI2S and PLLSAI division factor by 63 */ +/** + * @} + */ + +/** @defgroup RCM_DDL_EC_PLL1C_DIV PLL division factor (PLL1C) + * @{ + */ +#define DDL_RCM_PLL1C_DIV_2 0x00000000U /*!< Main PLL division factor for PLL1C output by 2 */ +#define DDL_RCM_PLL1C_DIV_4 RCM_PLL1CFG_PLL1C_0 /*!< Main PLL division factor for PLL1C output by 4 */ +#define DDL_RCM_PLL1C_DIV_6 RCM_PLL1CFG_PLL1C_1 /*!< Main PLL division factor for PLL1C output by 6 */ +#define DDL_RCM_PLL1C_DIV_8 (RCM_PLL1CFG_PLL1C_1 | RCM_PLL1CFG_PLL1C_0) /*!< Main PLL division factor for PLL1C output by 8 */ +/** + * @} + */ + +/** @defgroup RCM_DDL_EC_PLLD_DIV PLL division factor (PLLD) + * @{ + */ +#define DDL_RCM_PLLD_DIV_2 RCM_PLL1CFG_PLLD_1 /*!< Main PLL division factor for PLLD output by 2 */ +#define DDL_RCM_PLLD_DIV_3 (RCM_PLL1CFG_PLLD_1|RCM_PLL1CFG_PLLD_0) /*!< Main PLL division factor for PLLD output by 3 */ +#define DDL_RCM_PLLD_DIV_4 RCM_PLL1CFG_PLLD_2 /*!< Main PLL division factor for PLLD output by 4 */ +#define DDL_RCM_PLLD_DIV_5 (RCM_PLL1CFG_PLLD_2|RCM_PLL1CFG_PLLD_0) /*!< Main PLL division factor for PLLD output by 5 */ +#define DDL_RCM_PLLD_DIV_6 (RCM_PLL1CFG_PLLD_2|RCM_PLL1CFG_PLLD_1) /*!< Main PLL division factor for PLLD output by 6 */ +#define DDL_RCM_PLLD_DIV_7 (RCM_PLL1CFG_PLLD_2|RCM_PLL1CFG_PLLD_1|RCM_PLL1CFG_PLLD_0) /*!< Main PLL division factor for PLLD output by 7 */ +#define DDL_RCM_PLLD_DIV_8 RCM_PLL1CFG_PLLD_3 /*!< Main PLL division factor for PLLD output by 8 */ +#define DDL_RCM_PLLD_DIV_9 (RCM_PLL1CFG_PLLD_3|RCM_PLL1CFG_PLLD_0) /*!< Main PLL division factor for PLLD output by 9 */ +#define DDL_RCM_PLLD_DIV_10 (RCM_PLL1CFG_PLLD_3|RCM_PLL1CFG_PLLD_1) /*!< Main PLL division factor for PLLD output by 10 */ +#define DDL_RCM_PLLD_DIV_11 (RCM_PLL1CFG_PLLD_3|RCM_PLL1CFG_PLLD_1|RCM_PLL1CFG_PLLD_0) /*!< Main PLL division factor for PLLD output by 11 */ +#define DDL_RCM_PLLD_DIV_12 (RCM_PLL1CFG_PLLD_3|RCM_PLL1CFG_PLLD_2) /*!< Main PLL division factor for PLLD output by 12 */ +#define DDL_RCM_PLLD_DIV_13 (RCM_PLL1CFG_PLLD_3|RCM_PLL1CFG_PLLD_2|RCM_PLL1CFG_PLLD_0) /*!< Main PLL division factor for PLLD output by 13 */ +#define DDL_RCM_PLLD_DIV_14 (RCM_PLL1CFG_PLLD_3|RCM_PLL1CFG_PLLD_2|RCM_PLL1CFG_PLLD_1) /*!< Main PLL division factor for PLLD output by 14 */ +#define DDL_RCM_PLLD_DIV_15 (RCM_PLL1CFG_PLLD_3|RCM_PLL1CFG_PLLD_2|RCM_PLL1CFG_PLLD_1|RCM_PLL1CFG_PLLD_0) /*!< Main PLL division factor for PLLD output by 15 */ +/** + * @} + */ + +/** @defgroup RCM_DDL_EC_PLL_SPRE_SEL PLL Spread Spectrum Selection + * @{ + */ +#define DDL_RCM_SPREAD_SELECT_CENTER 0x00000000U /*!< PLL center spread spectrum selection */ +#define DDL_RCM_SPREAD_SELECT_DOWN RCM_SSCCFG_SSSEL /*!< PLL down spread spectrum selection */ +/** + * @} + */ + +#if defined(RCM_PLLI2S_SUPPORT) +/** @defgroup RCM_DDL_EC_PLL2B PLL2B division factor (PLL2B) + * @{ + */ +#if defined(RCM_PLL2CFG_PLL2B) +#define DDL_RCM_PLL2B_DIV_2 (RCM_PLL2CFG_PLL2B_1) /*!< PLLI2S division factor for PLL2B output by 2 */ +#define DDL_RCM_PLL2B_DIV_3 (RCM_PLL2CFG_PLL2B_1 | RCM_PLL2CFG_PLL2B_0) /*!< PLLI2S division factor for PLL2B output by 3 */ +#define DDL_RCM_PLL2B_DIV_4 (RCM_PLL2CFG_PLL2B_2) /*!< PLLI2S division factor for PLL2B output by 4 */ +#define DDL_RCM_PLL2B_DIV_5 (RCM_PLL2CFG_PLL2B_2 | RCM_PLL2CFG_PLL2B_0) /*!< PLLI2S division factor for PLL2B output by 5 */ +#define DDL_RCM_PLL2B_DIV_6 (RCM_PLL2CFG_PLL2B_2 | RCM_PLL2CFG_PLL2B_1) /*!< PLLI2S division factor for PLL2B output by 6 */ +#define DDL_RCM_PLL2B_DIV_7 (RCM_PLL2CFG_PLL2B_2 | RCM_PLL2CFG_PLL2B_1 | RCM_PLL2CFG_PLL2B_0) /*!< PLLI2S division factor for PLL2B output by 7 */ +#define DDL_RCM_PLL2B_DIV_8 (RCM_PLL2CFG_PLL2B_3) /*!< PLLI2S division factor for PLL2B output by 8 */ +#define DDL_RCM_PLL2B_DIV_9 (RCM_PLL2CFG_PLL2B_3 | RCM_PLL2CFG_PLL2B_0) /*!< PLLI2S division factor for PLL2B output by 9 */ +#define DDL_RCM_PLL2B_DIV_10 (RCM_PLL2CFG_PLL2B_3 | RCM_PLL2CFG_PLL2B_1) /*!< PLLI2S division factor for PLL2B output by 10 */ +#define DDL_RCM_PLL2B_DIV_11 (RCM_PLL2CFG_PLL2B_3 | RCM_PLL2CFG_PLL2B_1 | RCM_PLL2CFG_PLL2B_0) /*!< PLLI2S division factor for PLL2B output by 11 */ +#define DDL_RCM_PLL2B_DIV_12 (RCM_PLL2CFG_PLL2B_3 | RCM_PLL2CFG_PLL2B_2) /*!< PLLI2S division factor for PLL2B output by 12 */ +#define DDL_RCM_PLL2B_DIV_13 (RCM_PLL2CFG_PLL2B_3 | RCM_PLL2CFG_PLL2B_2 | RCM_PLL2CFG_PLL2B_0) /*!< PLLI2S division factor for PLL2B output by 13 */ +#define DDL_RCM_PLL2B_DIV_14 (RCM_PLL2CFG_PLL2B_3 | RCM_PLL2CFG_PLL2B_2 | RCM_PLL2CFG_PLL2B_1) /*!< PLLI2S division factor for PLL2B output by 14 */ +#define DDL_RCM_PLL2B_DIV_15 (RCM_PLL2CFG_PLL2B_3 | RCM_PLL2CFG_PLL2B_2 | RCM_PLL2CFG_PLL2B_1 | RCM_PLL2CFG_PLL2B_0) /*!< PLLI2S division factor for PLL2B output by 15 */ +#define DDL_RCM_PLL2B_DIV_16 (RCM_PLL2CFG_PLL2B_4) /*!< PLLI2S division factor for PLL2B output by 16 */ +#define DDL_RCM_PLL2B_DIV_17 (RCM_PLL2CFG_PLL2B_4 | RCM_PLL2CFG_PLL2B_0) /*!< PLLI2S division factor for PLL2B output by 17 */ +#define DDL_RCM_PLL2B_DIV_18 (RCM_PLL2CFG_PLL2B_4 | RCM_PLL2CFG_PLL2B_1) /*!< PLLI2S division factor for PLL2B output by 18 */ +#define DDL_RCM_PLL2B_DIV_19 (RCM_PLL2CFG_PLL2B_4 | RCM_PLL2CFG_PLL2B_1 | RCM_PLL2CFG_PLL2B_0) /*!< PLLI2S division factor for PLL2B output by 19 */ +#define DDL_RCM_PLL2B_DIV_20 (RCM_PLL2CFG_PLL2B_4 | RCM_PLL2CFG_PLL2B_2) /*!< PLLI2S division factor for PLL2B output by 20 */ +#define DDL_RCM_PLL2B_DIV_21 (RCM_PLL2CFG_PLL2B_4 | RCM_PLL2CFG_PLL2B_2 | RCM_PLL2CFG_PLL2B_0) /*!< PLLI2S division factor for PLL2B output by 21 */ +#define DDL_RCM_PLL2B_DIV_22 (RCM_PLL2CFG_PLL2B_4 | RCM_PLL2CFG_PLL2B_2 | RCM_PLL2CFG_PLL2B_1) /*!< PLLI2S division factor for PLL2B output by 22 */ +#define DDL_RCM_PLL2B_DIV_23 (RCM_PLL2CFG_PLL2B_4 | RCM_PLL2CFG_PLL2B_2 | RCM_PLL2CFG_PLL2B_1 | RCM_PLL2CFG_PLL2B_0) /*!< PLLI2S division factor for PLL2B output by 23 */ +#define DDL_RCM_PLL2B_DIV_24 (RCM_PLL2CFG_PLL2B_4 | RCM_PLL2CFG_PLL2B_3) /*!< PLLI2S division factor for PLL2B output by 24 */ +#define DDL_RCM_PLL2B_DIV_25 (RCM_PLL2CFG_PLL2B_4 | RCM_PLL2CFG_PLL2B_3 | RCM_PLL2CFG_PLL2B_0) /*!< PLLI2S division factor for PLL2B output by 25 */ +#define DDL_RCM_PLL2B_DIV_26 (RCM_PLL2CFG_PLL2B_4 | RCM_PLL2CFG_PLL2B_3 | RCM_PLL2CFG_PLL2B_1) /*!< PLLI2S division factor for PLL2B output by 26 */ +#define DDL_RCM_PLL2B_DIV_27 (RCM_PLL2CFG_PLL2B_4 | RCM_PLL2CFG_PLL2B_3 | RCM_PLL2CFG_PLL2B_1 | RCM_PLL2CFG_PLL2B_0) /*!< PLLI2S division factor for PLL2B output by 27 */ +#define DDL_RCM_PLL2B_DIV_28 (RCM_PLL2CFG_PLL2B_4 | RCM_PLL2CFG_PLL2B_3 | RCM_PLL2CFG_PLL2B_2) /*!< PLLI2S division factor for PLL2B output by 28 */ +#define DDL_RCM_PLL2B_DIV_29 (RCM_PLL2CFG_PLL2B_4 | RCM_PLL2CFG_PLL2B_3 | RCM_PLL2CFG_PLL2B_2 | RCM_PLL2CFG_PLL2B_0) /*!< PLLI2S division factor for PLL2B output by 29 */ +#define DDL_RCM_PLL2B_DIV_30 (RCM_PLL2CFG_PLL2B_4 | RCM_PLL2CFG_PLL2B_3 | RCM_PLL2CFG_PLL2B_2 | RCM_PLL2CFG_PLL2B_1) /*!< PLLI2S division factor for PLL2B output by 30 */ +#define DDL_RCM_PLL2B_DIV_31 (RCM_PLL2CFG_PLL2B_4 | RCM_PLL2CFG_PLL2B_3 | RCM_PLL2CFG_PLL2B_2 | RCM_PLL2CFG_PLL2B_1 | RCM_PLL2CFG_PLL2B_0) /*!< PLLI2S division factor for PLL2B output by 31 */ +#define DDL_RCM_PLL2B_DIV_32 (RCM_PLL2CFG_PLL2B_5) /*!< PLLI2S division factor for PLL2B output by 32 */ +#define DDL_RCM_PLL2B_DIV_33 (RCM_PLL2CFG_PLL2B_5 | RCM_PLL2CFG_PLL2B_0) /*!< PLLI2S division factor for PLL2B output by 33 */ +#define DDL_RCM_PLL2B_DIV_34 (RCM_PLL2CFG_PLL2B_5 | RCM_PLL2CFG_PLL2B_1) /*!< PLLI2S division factor for PLL2B output by 34 */ +#define DDL_RCM_PLL2B_DIV_35 (RCM_PLL2CFG_PLL2B_5 | RCM_PLL2CFG_PLL2B_1 | RCM_PLL2CFG_PLL2B_0) /*!< PLLI2S division factor for PLL2B output by 35 */ +#define DDL_RCM_PLL2B_DIV_36 (RCM_PLL2CFG_PLL2B_5 | RCM_PLL2CFG_PLL2B_2) /*!< PLLI2S division factor for PLL2B output by 36 */ +#define DDL_RCM_PLL2B_DIV_37 (RCM_PLL2CFG_PLL2B_5 | RCM_PLL2CFG_PLL2B_2 | RCM_PLL2CFG_PLL2B_0) /*!< PLLI2S division factor for PLL2B output by 37 */ +#define DDL_RCM_PLL2B_DIV_38 (RCM_PLL2CFG_PLL2B_5 | RCM_PLL2CFG_PLL2B_2 | RCM_PLL2CFG_PLL2B_1) /*!< PLLI2S division factor for PLL2B output by 38 */ +#define DDL_RCM_PLL2B_DIV_39 (RCM_PLL2CFG_PLL2B_5 | RCM_PLL2CFG_PLL2B_2 | RCM_PLL2CFG_PLL2B_1 | RCM_PLL2CFG_PLL2B_0) /*!< PLLI2S division factor for PLL2B output by 39 */ +#define DDL_RCM_PLL2B_DIV_40 (RCM_PLL2CFG_PLL2B_5 | RCM_PLL2CFG_PLL2B_3) /*!< PLLI2S division factor for PLL2B output by 40 */ +#define DDL_RCM_PLL2B_DIV_41 (RCM_PLL2CFG_PLL2B_5 | RCM_PLL2CFG_PLL2B_3 | RCM_PLL2CFG_PLL2B_0) /*!< PLLI2S division factor for PLL2B output by 41 */ +#define DDL_RCM_PLL2B_DIV_42 (RCM_PLL2CFG_PLL2B_5 | RCM_PLL2CFG_PLL2B_3 | RCM_PLL2CFG_PLL2B_1) /*!< PLLI2S division factor for PLL2B output by 42 */ +#define DDL_RCM_PLL2B_DIV_43 (RCM_PLL2CFG_PLL2B_5 | RCM_PLL2CFG_PLL2B_3 | RCM_PLL2CFG_PLL2B_1 | RCM_PLL2CFG_PLL2B_0) /*!< PLLI2S division factor for PLL2B output by 43 */ +#define DDL_RCM_PLL2B_DIV_44 (RCM_PLL2CFG_PLL2B_5 | RCM_PLL2CFG_PLL2B_3 | RCM_PLL2CFG_PLL2B_2) /*!< PLLI2S division factor for PLL2B output by 44 */ +#define DDL_RCM_PLL2B_DIV_45 (RCM_PLL2CFG_PLL2B_5 | RCM_PLL2CFG_PLL2B_3 | RCM_PLL2CFG_PLL2B_2 | RCM_PLL2CFG_PLL2B_0) /*!< PLLI2S division factor for PLL2B output by 45 */ +#define DDL_RCM_PLL2B_DIV_46 (RCM_PLL2CFG_PLL2B_5 | RCM_PLL2CFG_PLL2B_3 | RCM_PLL2CFG_PLL2B_2 | RCM_PLL2CFG_PLL2B_1) /*!< PLLI2S division factor for PLL2B output by 46 */ +#define DDL_RCM_PLL2B_DIV_47 (RCM_PLL2CFG_PLL2B_5 | RCM_PLL2CFG_PLL2B_3 | RCM_PLL2CFG_PLL2B_2 | RCM_PLL2CFG_PLL2B_1 | RCM_PLL2CFG_PLL2B_0) /*!< PLLI2S division factor for PLL2B output by 47 */ +#define DDL_RCM_PLL2B_DIV_48 (RCM_PLL2CFG_PLL2B_5 | RCM_PLL2CFG_PLL2B_4) /*!< PLLI2S division factor for PLL2B output by 48 */ +#define DDL_RCM_PLL2B_DIV_49 (RCM_PLL2CFG_PLL2B_5 | RCM_PLL2CFG_PLL2B_4 | RCM_PLL2CFG_PLL2B_0) /*!< PLLI2S division factor for PLL2B output by 49 */ +#define DDL_RCM_PLL2B_DIV_50 (RCM_PLL2CFG_PLL2B_5 | RCM_PLL2CFG_PLL2B_4 | RCM_PLL2CFG_PLL2B_1) /*!< PLLI2S division factor for PLL2B output by 50 */ +#define DDL_RCM_PLL2B_DIV_51 (RCM_PLL2CFG_PLL2B_5 | RCM_PLL2CFG_PLL2B_4 | RCM_PLL2CFG_PLL2B_1 | RCM_PLL2CFG_PLL2B_0) /*!< PLLI2S division factor for PLL2B output by 51 */ +#define DDL_RCM_PLL2B_DIV_52 (RCM_PLL2CFG_PLL2B_5 | RCM_PLL2CFG_PLL2B_4 | RCM_PLL2CFG_PLL2B_2) /*!< PLLI2S division factor for PLL2B output by 52 */ +#define DDL_RCM_PLL2B_DIV_53 (RCM_PLL2CFG_PLL2B_5 | RCM_PLL2CFG_PLL2B_4 | RCM_PLL2CFG_PLL2B_2 | RCM_PLL2CFG_PLL2B_0) /*!< PLLI2S division factor for PLL2B output by 53 */ +#define DDL_RCM_PLL2B_DIV_54 (RCM_PLL2CFG_PLL2B_5 | RCM_PLL2CFG_PLL2B_4 | RCM_PLL2CFG_PLL2B_2 | RCM_PLL2CFG_PLL2B_1) /*!< PLLI2S division factor for PLL2B output by 54 */ +#define DDL_RCM_PLL2B_DIV_55 (RCM_PLL2CFG_PLL2B_5 | RCM_PLL2CFG_PLL2B_4 | RCM_PLL2CFG_PLL2B_2 | RCM_PLL2CFG_PLL2B_1 | RCM_PLL2CFG_PLL2B_0) /*!< PLLI2S division factor for PLL2B output by 55 */ +#define DDL_RCM_PLL2B_DIV_56 (RCM_PLL2CFG_PLL2B_5 | RCM_PLL2CFG_PLL2B_4 | RCM_PLL2CFG_PLL2B_3) /*!< PLLI2S division factor for PLL2B output by 56 */ +#define DDL_RCM_PLL2B_DIV_57 (RCM_PLL2CFG_PLL2B_5 | RCM_PLL2CFG_PLL2B_4 | RCM_PLL2CFG_PLL2B_3 | RCM_PLL2CFG_PLL2B_0) /*!< PLLI2S division factor for PLL2B output by 57 */ +#define DDL_RCM_PLL2B_DIV_58 (RCM_PLL2CFG_PLL2B_5 | RCM_PLL2CFG_PLL2B_4 | RCM_PLL2CFG_PLL2B_3 | RCM_PLL2CFG_PLL2B_1) /*!< PLLI2S division factor for PLL2B output by 58 */ +#define DDL_RCM_PLL2B_DIV_59 (RCM_PLL2CFG_PLL2B_5 | RCM_PLL2CFG_PLL2B_4 | RCM_PLL2CFG_PLL2B_3 | RCM_PLL2CFG_PLL2B_1 | RCM_PLL2CFG_PLL2B_0) /*!< PLLI2S division factor for PLL2B output by 59 */ +#define DDL_RCM_PLL2B_DIV_60 (RCM_PLL2CFG_PLL2B_5 | RCM_PLL2CFG_PLL2B_4 | RCM_PLL2CFG_PLL2B_3 | RCM_PLL2CFG_PLL2B_2) /*!< PLLI2S division factor for PLL2B output by 60 */ +#define DDL_RCM_PLL2B_DIV_61 (RCM_PLL2CFG_PLL2B_5 | RCM_PLL2CFG_PLL2B_4 | RCM_PLL2CFG_PLL2B_3 | RCM_PLL2CFG_PLL2B_2 | RCM_PLL2CFG_PLL2B_0) /*!< PLLI2S division factor for PLL2B output by 61 */ +#define DDL_RCM_PLL2B_DIV_62 (RCM_PLL2CFG_PLL2B_5 | RCM_PLL2CFG_PLL2B_4 | RCM_PLL2CFG_PLL2B_3 | RCM_PLL2CFG_PLL2B_2 | RCM_PLL2CFG_PLL2B_1) /*!< PLLI2S division factor for PLL2B output by 62 */ +#define DDL_RCM_PLL2B_DIV_63 (RCM_PLL2CFG_PLL2B_5 | RCM_PLL2CFG_PLL2B_4 | RCM_PLL2CFG_PLL2B_3 | RCM_PLL2CFG_PLL2B_2 | RCM_PLL2CFG_PLL2B_1 | RCM_PLL2CFG_PLL2B_0) /*!< PLLI2S division factor for PLL2B output by 63 */ +#else +#define DDL_RCM_PLL2B_DIV_2 DDL_RCM_PLLB_DIV_2 /*!< PLLI2S division factor for PLL2B output by 2 */ +#define DDL_RCM_PLL2B_DIV_3 DDL_RCM_PLLB_DIV_3 /*!< PLLI2S division factor for PLL2B output by 3 */ +#define DDL_RCM_PLL2B_DIV_4 DDL_RCM_PLLB_DIV_4 /*!< PLLI2S division factor for PLL2B output by 4 */ +#define DDL_RCM_PLL2B_DIV_5 DDL_RCM_PLLB_DIV_5 /*!< PLLI2S division factor for PLL2B output by 5 */ +#define DDL_RCM_PLL2B_DIV_6 DDL_RCM_PLLB_DIV_6 /*!< PLLI2S division factor for PLL2B output by 6 */ +#define DDL_RCM_PLL2B_DIV_7 DDL_RCM_PLLB_DIV_7 /*!< PLLI2S division factor for PLL2B output by 7 */ +#define DDL_RCM_PLL2B_DIV_8 DDL_RCM_PLLB_DIV_8 /*!< PLLI2S division factor for PLL2B output by 8 */ +#define DDL_RCM_PLL2B_DIV_9 DDL_RCM_PLLB_DIV_9 /*!< PLLI2S division factor for PLL2B output by 9 */ +#define DDL_RCM_PLL2B_DIV_10 DDL_RCM_PLLB_DIV_10 /*!< PLLI2S division factor for PLL2B output by 10 */ +#define DDL_RCM_PLL2B_DIV_11 DDL_RCM_PLLB_DIV_11 /*!< PLLI2S division factor for PLL2B output by 11 */ +#define DDL_RCM_PLL2B_DIV_12 DDL_RCM_PLLB_DIV_12 /*!< PLLI2S division factor for PLL2B output by 12 */ +#define DDL_RCM_PLL2B_DIV_13 DDL_RCM_PLLB_DIV_13 /*!< PLLI2S division factor for PLL2B output by 13 */ +#define DDL_RCM_PLL2B_DIV_14 DDL_RCM_PLLB_DIV_14 /*!< PLLI2S division factor for PLL2B output by 14 */ +#define DDL_RCM_PLL2B_DIV_15 DDL_RCM_PLLB_DIV_15 /*!< PLLI2S division factor for PLL2B output by 15 */ +#define DDL_RCM_PLL2B_DIV_16 DDL_RCM_PLLB_DIV_16 /*!< PLLI2S division factor for PLL2B output by 16 */ +#define DDL_RCM_PLL2B_DIV_17 DDL_RCM_PLLB_DIV_17 /*!< PLLI2S division factor for PLL2B output by 17 */ +#define DDL_RCM_PLL2B_DIV_18 DDL_RCM_PLLB_DIV_18 /*!< PLLI2S division factor for PLL2B output by 18 */ +#define DDL_RCM_PLL2B_DIV_19 DDL_RCM_PLLB_DIV_19 /*!< PLLI2S division factor for PLL2B output by 19 */ +#define DDL_RCM_PLL2B_DIV_20 DDL_RCM_PLLB_DIV_20 /*!< PLLI2S division factor for PLL2B output by 20 */ +#define DDL_RCM_PLL2B_DIV_21 DDL_RCM_PLLB_DIV_21 /*!< PLLI2S division factor for PLL2B output by 21 */ +#define DDL_RCM_PLL2B_DIV_22 DDL_RCM_PLLB_DIV_22 /*!< PLLI2S division factor for PLL2B output by 22 */ +#define DDL_RCM_PLL2B_DIV_23 DDL_RCM_PLLB_DIV_23 /*!< PLLI2S division factor for PLL2B output by 23 */ +#define DDL_RCM_PLL2B_DIV_24 DDL_RCM_PLLB_DIV_24 /*!< PLLI2S division factor for PLL2B output by 24 */ +#define DDL_RCM_PLL2B_DIV_25 DDL_RCM_PLLB_DIV_25 /*!< PLLI2S division factor for PLL2B output by 25 */ +#define DDL_RCM_PLL2B_DIV_26 DDL_RCM_PLLB_DIV_26 /*!< PLLI2S division factor for PLL2B output by 26 */ +#define DDL_RCM_PLL2B_DIV_27 DDL_RCM_PLLB_DIV_27 /*!< PLLI2S division factor for PLL2B output by 27 */ +#define DDL_RCM_PLL2B_DIV_28 DDL_RCM_PLLB_DIV_28 /*!< PLLI2S division factor for PLL2B output by 28 */ +#define DDL_RCM_PLL2B_DIV_29 DDL_RCM_PLLB_DIV_29 /*!< PLLI2S division factor for PLL2B output by 29 */ +#define DDL_RCM_PLL2B_DIV_30 DDL_RCM_PLLB_DIV_30 /*!< PLLI2S division factor for PLL2B output by 30 */ +#define DDL_RCM_PLL2B_DIV_31 DDL_RCM_PLLB_DIV_31 /*!< PLLI2S division factor for PLL2B output by 31 */ +#define DDL_RCM_PLL2B_DIV_32 DDL_RCM_PLLB_DIV_32 /*!< PLLI2S division factor for PLL2B output by 32 */ +#define DDL_RCM_PLL2B_DIV_33 DDL_RCM_PLLB_DIV_33 /*!< PLLI2S division factor for PLL2B output by 33 */ +#define DDL_RCM_PLL2B_DIV_34 DDL_RCM_PLLB_DIV_34 /*!< PLLI2S division factor for PLL2B output by 34 */ +#define DDL_RCM_PLL2B_DIV_35 DDL_RCM_PLLB_DIV_35 /*!< PLLI2S division factor for PLL2B output by 35 */ +#define DDL_RCM_PLL2B_DIV_36 DDL_RCM_PLLB_DIV_36 /*!< PLLI2S division factor for PLL2B output by 36 */ +#define DDL_RCM_PLL2B_DIV_37 DDL_RCM_PLLB_DIV_37 /*!< PLLI2S division factor for PLL2B output by 37 */ +#define DDL_RCM_PLL2B_DIV_38 DDL_RCM_PLLB_DIV_38 /*!< PLLI2S division factor for PLL2B output by 38 */ +#define DDL_RCM_PLL2B_DIV_39 DDL_RCM_PLLB_DIV_39 /*!< PLLI2S division factor for PLL2B output by 39 */ +#define DDL_RCM_PLL2B_DIV_40 DDL_RCM_PLLB_DIV_40 /*!< PLLI2S division factor for PLL2B output by 40 */ +#define DDL_RCM_PLL2B_DIV_41 DDL_RCM_PLLB_DIV_41 /*!< PLLI2S division factor for PLL2B output by 41 */ +#define DDL_RCM_PLL2B_DIV_42 DDL_RCM_PLLB_DIV_42 /*!< PLLI2S division factor for PLL2B output by 42 */ +#define DDL_RCM_PLL2B_DIV_43 DDL_RCM_PLLB_DIV_43 /*!< PLLI2S division factor for PLL2B output by 43 */ +#define DDL_RCM_PLL2B_DIV_44 DDL_RCM_PLLB_DIV_44 /*!< PLLI2S division factor for PLL2B output by 44 */ +#define DDL_RCM_PLL2B_DIV_45 DDL_RCM_PLLB_DIV_45 /*!< PLLI2S division factor for PLL2B output by 45 */ +#define DDL_RCM_PLL2B_DIV_46 DDL_RCM_PLLB_DIV_46 /*!< PLLI2S division factor for PLL2B output by 46 */ +#define DDL_RCM_PLL2B_DIV_47 DDL_RCM_PLLB_DIV_47 /*!< PLLI2S division factor for PLL2B output by 47 */ +#define DDL_RCM_PLL2B_DIV_48 DDL_RCM_PLLB_DIV_48 /*!< PLLI2S division factor for PLL2B output by 48 */ +#define DDL_RCM_PLL2B_DIV_49 DDL_RCM_PLLB_DIV_49 /*!< PLLI2S division factor for PLL2B output by 49 */ +#define DDL_RCM_PLL2B_DIV_50 DDL_RCM_PLLB_DIV_50 /*!< PLLI2S division factor for PLL2B output by 50 */ +#define DDL_RCM_PLL2B_DIV_51 DDL_RCM_PLLB_DIV_51 /*!< PLLI2S division factor for PLL2B output by 51 */ +#define DDL_RCM_PLL2B_DIV_52 DDL_RCM_PLLB_DIV_52 /*!< PLLI2S division factor for PLL2B output by 52 */ +#define DDL_RCM_PLL2B_DIV_53 DDL_RCM_PLLB_DIV_53 /*!< PLLI2S division factor for PLL2B output by 53 */ +#define DDL_RCM_PLL2B_DIV_54 DDL_RCM_PLLB_DIV_54 /*!< PLLI2S division factor for PLL2B output by 54 */ +#define DDL_RCM_PLL2B_DIV_55 DDL_RCM_PLLB_DIV_55 /*!< PLLI2S division factor for PLL2B output by 55 */ +#define DDL_RCM_PLL2B_DIV_56 DDL_RCM_PLLB_DIV_56 /*!< PLLI2S division factor for PLL2B output by 56 */ +#define DDL_RCM_PLL2B_DIV_57 DDL_RCM_PLLB_DIV_57 /*!< PLLI2S division factor for PLL2B output by 57 */ +#define DDL_RCM_PLL2B_DIV_58 DDL_RCM_PLLB_DIV_58 /*!< PLLI2S division factor for PLL2B output by 58 */ +#define DDL_RCM_PLL2B_DIV_59 DDL_RCM_PLLB_DIV_59 /*!< PLLI2S division factor for PLL2B output by 59 */ +#define DDL_RCM_PLL2B_DIV_60 DDL_RCM_PLLB_DIV_60 /*!< PLLI2S division factor for PLL2B output by 60 */ +#define DDL_RCM_PLL2B_DIV_61 DDL_RCM_PLLB_DIV_61 /*!< PLLI2S division factor for PLL2B output by 61 */ +#define DDL_RCM_PLL2B_DIV_62 DDL_RCM_PLLB_DIV_62 /*!< PLLI2S division factor for PLL2B output by 62 */ +#define DDL_RCM_PLL2B_DIV_63 DDL_RCM_PLLB_DIV_63 /*!< PLLI2S division factor for PLL2B output by 63 */ +#endif /* RCM_PLL2CFG_PLL2B */ +/** + * @} + */ + +/** @defgroup RCM_DDL_EC_PLL2C PLL2C division factor (PLL2C) + * @{ + */ +#define DDL_RCM_PLL2C_DIV_2 RCM_PLL2CFG_PLL2C_1 /*!< PLLI2S division factor for PLL2C output by 2 */ +#define DDL_RCM_PLL2C_DIV_3 (RCM_PLL2CFG_PLL2C_1 | RCM_PLL2CFG_PLL2C_0) /*!< PLLI2S division factor for PLL2C output by 3 */ +#define DDL_RCM_PLL2C_DIV_4 RCM_PLL2CFG_PLL2C_2 /*!< PLLI2S division factor for PLL2C output by 4 */ +#define DDL_RCM_PLL2C_DIV_5 (RCM_PLL2CFG_PLL2C_2 | RCM_PLL2CFG_PLL2C_0) /*!< PLLI2S division factor for PLL2C output by 5 */ +#define DDL_RCM_PLL2C_DIV_6 (RCM_PLL2CFG_PLL2C_2 | RCM_PLL2CFG_PLL2C_1) /*!< PLLI2S division factor for PLL2C output by 6 */ +#define DDL_RCM_PLL2C_DIV_7 (RCM_PLL2CFG_PLL2C_2 | RCM_PLL2CFG_PLL2C_1 | RCM_PLL2CFG_PLL2C_0) /*!< PLLI2S division factor for PLL2C output by 7 */ +/** + * @} + */ + +#endif /* RCM_PLLI2S_SUPPORT */ + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ +/** @defgroup RCM_DDL_Exported_Macros RCM Exported Macros + * @{ + */ + +/** @defgroup RCM_DDL_EM_WRITE_READ Common Write and read registers Macros + * @{ + */ + +/** + * @brief Write a value in RCM register + * @param __REG__ Register to be written + * @param __VALUE__ Value to be written in the register + * @retval None + */ +#define DDL_RCM_WriteReg(__REG__, __VALUE__) WRITE_REG(RCM->__REG__, (__VALUE__)) + +/** + * @brief Read a value in RCM register + * @param __REG__ Register to be read + * @retval Register value + */ +#define DDL_RCM_ReadReg(__REG__) READ_REG(RCM->__REG__) +/** + * @} + */ + +/** @defgroup RCM_DDL_EM_CALC_FREQ Calculate frequencies + * @{ + */ + +/** + * @brief Helper macro to calculate the PLLCLK frequency on system domain + * @note ex: @ref __DDL_RCM_CALC_PLLCLK_FREQ (HSE_VALUE,@ref DDL_RCM_PLL_GetDivider (), + * @ref DDL_RCM_PLL_GetN (), @ref DDL_RCM_PLL_GetP ()); + * @param __INPUTFREQ__ PLL Input frequency (based on HSE/HSI) + * @param __PLLB__ This parameter can be one of the following values: + * @arg @ref DDL_RCM_PLLB_DIV_2 + * @arg @ref DDL_RCM_PLLB_DIV_3 + * @arg @ref DDL_RCM_PLLB_DIV_4 + * @arg @ref DDL_RCM_PLLB_DIV_5 + * @arg @ref DDL_RCM_PLLB_DIV_6 + * @arg @ref DDL_RCM_PLLB_DIV_7 + * @arg @ref DDL_RCM_PLLB_DIV_8 + * @arg @ref DDL_RCM_PLLB_DIV_9 + * @arg @ref DDL_RCM_PLLB_DIV_10 + * @arg @ref DDL_RCM_PLLB_DIV_11 + * @arg @ref DDL_RCM_PLLB_DIV_12 + * @arg @ref DDL_RCM_PLLB_DIV_13 + * @arg @ref DDL_RCM_PLLB_DIV_14 + * @arg @ref DDL_RCM_PLLB_DIV_15 + * @arg @ref DDL_RCM_PLLB_DIV_16 + * @arg @ref DDL_RCM_PLLB_DIV_17 + * @arg @ref DDL_RCM_PLLB_DIV_18 + * @arg @ref DDL_RCM_PLLB_DIV_19 + * @arg @ref DDL_RCM_PLLB_DIV_20 + * @arg @ref DDL_RCM_PLLB_DIV_21 + * @arg @ref DDL_RCM_PLLB_DIV_22 + * @arg @ref DDL_RCM_PLLB_DIV_23 + * @arg @ref DDL_RCM_PLLB_DIV_24 + * @arg @ref DDL_RCM_PLLB_DIV_25 + * @arg @ref DDL_RCM_PLLB_DIV_26 + * @arg @ref DDL_RCM_PLLB_DIV_27 + * @arg @ref DDL_RCM_PLLB_DIV_28 + * @arg @ref DDL_RCM_PLLB_DIV_29 + * @arg @ref DDL_RCM_PLLB_DIV_30 + * @arg @ref DDL_RCM_PLLB_DIV_31 + * @arg @ref DDL_RCM_PLLB_DIV_32 + * @arg @ref DDL_RCM_PLLB_DIV_33 + * @arg @ref DDL_RCM_PLLB_DIV_34 + * @arg @ref DDL_RCM_PLLB_DIV_35 + * @arg @ref DDL_RCM_PLLB_DIV_36 + * @arg @ref DDL_RCM_PLLB_DIV_37 + * @arg @ref DDL_RCM_PLLB_DIV_38 + * @arg @ref DDL_RCM_PLLB_DIV_39 + * @arg @ref DDL_RCM_PLLB_DIV_40 + * @arg @ref DDL_RCM_PLLB_DIV_41 + * @arg @ref DDL_RCM_PLLB_DIV_42 + * @arg @ref DDL_RCM_PLLB_DIV_43 + * @arg @ref DDL_RCM_PLLB_DIV_44 + * @arg @ref DDL_RCM_PLLB_DIV_45 + * @arg @ref DDL_RCM_PLLB_DIV_46 + * @arg @ref DDL_RCM_PLLB_DIV_47 + * @arg @ref DDL_RCM_PLLB_DIV_48 + * @arg @ref DDL_RCM_PLLB_DIV_49 + * @arg @ref DDL_RCM_PLLB_DIV_50 + * @arg @ref DDL_RCM_PLLB_DIV_51 + * @arg @ref DDL_RCM_PLLB_DIV_52 + * @arg @ref DDL_RCM_PLLB_DIV_53 + * @arg @ref DDL_RCM_PLLB_DIV_54 + * @arg @ref DDL_RCM_PLLB_DIV_55 + * @arg @ref DDL_RCM_PLLB_DIV_56 + * @arg @ref DDL_RCM_PLLB_DIV_57 + * @arg @ref DDL_RCM_PLLB_DIV_58 + * @arg @ref DDL_RCM_PLLB_DIV_59 + * @arg @ref DDL_RCM_PLLB_DIV_60 + * @arg @ref DDL_RCM_PLLB_DIV_61 + * @arg @ref DDL_RCM_PLLB_DIV_62 + * @arg @ref DDL_RCM_PLLB_DIV_63 + * @param __PLL1A__ Between 50/192(*) and 432 + * + * (*) value not defined in all devices. + * @param __PLL1C__ This parameter can be one of the following values: + * @arg @ref DDL_RCM_PLL1C_DIV_2 + * @arg @ref DDL_RCM_PLL1C_DIV_4 + * @arg @ref DDL_RCM_PLL1C_DIV_6 + * @arg @ref DDL_RCM_PLL1C_DIV_8 + * @retval PLL clock frequency (in Hz) + */ +#define __DDL_RCM_CALC_PLLCLK_FREQ(__INPUTFREQ__, __PLLB__, __PLL1A__, __PLL1C__) ((__INPUTFREQ__) / (__PLLB__) * (__PLL1A__) / \ + ((((__PLL1C__) >> RCM_PLL1CFG_PLL1C_Pos ) + 1U) * 2U)) + +/** + * @brief Helper macro to calculate the PLLCLK frequency used on 48M domain + * @note ex: @ref __DDL_RCM_CALC_PLLCLK_48M_FREQ (HSE_VALUE,@ref DDL_RCM_PLL_GetDivider (), + * @ref DDL_RCM_PLL_GetN (), @ref DDL_RCM_PLL_GetQ ()); + * @param __INPUTFREQ__ PLL Input frequency (based on HSE/HSI) + * @param __PLLB__ This parameter can be one of the following values: + * @arg @ref DDL_RCM_PLLB_DIV_2 + * @arg @ref DDL_RCM_PLLB_DIV_3 + * @arg @ref DDL_RCM_PLLB_DIV_4 + * @arg @ref DDL_RCM_PLLB_DIV_5 + * @arg @ref DDL_RCM_PLLB_DIV_6 + * @arg @ref DDL_RCM_PLLB_DIV_7 + * @arg @ref DDL_RCM_PLLB_DIV_8 + * @arg @ref DDL_RCM_PLLB_DIV_9 + * @arg @ref DDL_RCM_PLLB_DIV_10 + * @arg @ref DDL_RCM_PLLB_DIV_11 + * @arg @ref DDL_RCM_PLLB_DIV_12 + * @arg @ref DDL_RCM_PLLB_DIV_13 + * @arg @ref DDL_RCM_PLLB_DIV_14 + * @arg @ref DDL_RCM_PLLB_DIV_15 + * @arg @ref DDL_RCM_PLLB_DIV_16 + * @arg @ref DDL_RCM_PLLB_DIV_17 + * @arg @ref DDL_RCM_PLLB_DIV_18 + * @arg @ref DDL_RCM_PLLB_DIV_19 + * @arg @ref DDL_RCM_PLLB_DIV_20 + * @arg @ref DDL_RCM_PLLB_DIV_21 + * @arg @ref DDL_RCM_PLLB_DIV_22 + * @arg @ref DDL_RCM_PLLB_DIV_23 + * @arg @ref DDL_RCM_PLLB_DIV_24 + * @arg @ref DDL_RCM_PLLB_DIV_25 + * @arg @ref DDL_RCM_PLLB_DIV_26 + * @arg @ref DDL_RCM_PLLB_DIV_27 + * @arg @ref DDL_RCM_PLLB_DIV_28 + * @arg @ref DDL_RCM_PLLB_DIV_29 + * @arg @ref DDL_RCM_PLLB_DIV_30 + * @arg @ref DDL_RCM_PLLB_DIV_31 + * @arg @ref DDL_RCM_PLLB_DIV_32 + * @arg @ref DDL_RCM_PLLB_DIV_33 + * @arg @ref DDL_RCM_PLLB_DIV_34 + * @arg @ref DDL_RCM_PLLB_DIV_35 + * @arg @ref DDL_RCM_PLLB_DIV_36 + * @arg @ref DDL_RCM_PLLB_DIV_37 + * @arg @ref DDL_RCM_PLLB_DIV_38 + * @arg @ref DDL_RCM_PLLB_DIV_39 + * @arg @ref DDL_RCM_PLLB_DIV_40 + * @arg @ref DDL_RCM_PLLB_DIV_41 + * @arg @ref DDL_RCM_PLLB_DIV_42 + * @arg @ref DDL_RCM_PLLB_DIV_43 + * @arg @ref DDL_RCM_PLLB_DIV_44 + * @arg @ref DDL_RCM_PLLB_DIV_45 + * @arg @ref DDL_RCM_PLLB_DIV_46 + * @arg @ref DDL_RCM_PLLB_DIV_47 + * @arg @ref DDL_RCM_PLLB_DIV_48 + * @arg @ref DDL_RCM_PLLB_DIV_49 + * @arg @ref DDL_RCM_PLLB_DIV_50 + * @arg @ref DDL_RCM_PLLB_DIV_51 + * @arg @ref DDL_RCM_PLLB_DIV_52 + * @arg @ref DDL_RCM_PLLB_DIV_53 + * @arg @ref DDL_RCM_PLLB_DIV_54 + * @arg @ref DDL_RCM_PLLB_DIV_55 + * @arg @ref DDL_RCM_PLLB_DIV_56 + * @arg @ref DDL_RCM_PLLB_DIV_57 + * @arg @ref DDL_RCM_PLLB_DIV_58 + * @arg @ref DDL_RCM_PLLB_DIV_59 + * @arg @ref DDL_RCM_PLLB_DIV_60 + * @arg @ref DDL_RCM_PLLB_DIV_61 + * @arg @ref DDL_RCM_PLLB_DIV_62 + * @arg @ref DDL_RCM_PLLB_DIV_63 + * @param __PLL1A__ Between 50/192(*) and 432 + * + * (*) value not defined in all devices. + * @param __PLLD__ This parameter can be one of the following values: + * @arg @ref DDL_RCM_PLLD_DIV_2 + * @arg @ref DDL_RCM_PLLD_DIV_3 + * @arg @ref DDL_RCM_PLLD_DIV_4 + * @arg @ref DDL_RCM_PLLD_DIV_5 + * @arg @ref DDL_RCM_PLLD_DIV_6 + * @arg @ref DDL_RCM_PLLD_DIV_7 + * @arg @ref DDL_RCM_PLLD_DIV_8 + * @arg @ref DDL_RCM_PLLD_DIV_9 + * @arg @ref DDL_RCM_PLLD_DIV_10 + * @arg @ref DDL_RCM_PLLD_DIV_11 + * @arg @ref DDL_RCM_PLLD_DIV_12 + * @arg @ref DDL_RCM_PLLD_DIV_13 + * @arg @ref DDL_RCM_PLLD_DIV_14 + * @arg @ref DDL_RCM_PLLD_DIV_15 + * @retval PLL clock frequency (in Hz) + */ +#define __DDL_RCM_CALC_PLLCLK_48M_FREQ(__INPUTFREQ__, __PLLB__, __PLL1A__, __PLLD__) ((__INPUTFREQ__) / (__PLLB__) * (__PLL1A__) / \ + ((__PLLD__) >> RCM_PLL1CFG_PLLD_Pos )) + + +#if defined(RCM_PLLI2S_SUPPORT) +/** + * @brief Helper macro to calculate the PLLI2S frequency used for I2S domain + * @note ex: @ref __DDL_RCM_CALC_PLLI2S_I2S_FREQ (HSE_VALUE,@ref DDL_RCM_PLLI2S_GetDivider (), + * @ref DDL_RCM_PLLI2S_GetN (), @ref DDL_RCM_PLLI2S_GetR ()); + * @param __INPUTFREQ__ PLL Input frequency (based on HSE/HSI) + * @param __PLLB__ This parameter can be one of the following values: + * @arg @ref DDL_RCM_PLL2B_DIV_2 + * @arg @ref DDL_RCM_PLL2B_DIV_3 + * @arg @ref DDL_RCM_PLL2B_DIV_4 + * @arg @ref DDL_RCM_PLL2B_DIV_5 + * @arg @ref DDL_RCM_PLL2B_DIV_6 + * @arg @ref DDL_RCM_PLL2B_DIV_7 + * @arg @ref DDL_RCM_PLL2B_DIV_8 + * @arg @ref DDL_RCM_PLL2B_DIV_9 + * @arg @ref DDL_RCM_PLL2B_DIV_10 + * @arg @ref DDL_RCM_PLL2B_DIV_11 + * @arg @ref DDL_RCM_PLL2B_DIV_12 + * @arg @ref DDL_RCM_PLL2B_DIV_13 + * @arg @ref DDL_RCM_PLL2B_DIV_14 + * @arg @ref DDL_RCM_PLL2B_DIV_15 + * @arg @ref DDL_RCM_PLL2B_DIV_16 + * @arg @ref DDL_RCM_PLL2B_DIV_17 + * @arg @ref DDL_RCM_PLL2B_DIV_18 + * @arg @ref DDL_RCM_PLL2B_DIV_19 + * @arg @ref DDL_RCM_PLL2B_DIV_20 + * @arg @ref DDL_RCM_PLL2B_DIV_21 + * @arg @ref DDL_RCM_PLL2B_DIV_22 + * @arg @ref DDL_RCM_PLL2B_DIV_23 + * @arg @ref DDL_RCM_PLL2B_DIV_24 + * @arg @ref DDL_RCM_PLL2B_DIV_25 + * @arg @ref DDL_RCM_PLL2B_DIV_26 + * @arg @ref DDL_RCM_PLL2B_DIV_27 + * @arg @ref DDL_RCM_PLL2B_DIV_28 + * @arg @ref DDL_RCM_PLL2B_DIV_29 + * @arg @ref DDL_RCM_PLL2B_DIV_30 + * @arg @ref DDL_RCM_PLL2B_DIV_31 + * @arg @ref DDL_RCM_PLL2B_DIV_32 + * @arg @ref DDL_RCM_PLL2B_DIV_33 + * @arg @ref DDL_RCM_PLL2B_DIV_34 + * @arg @ref DDL_RCM_PLL2B_DIV_35 + * @arg @ref DDL_RCM_PLL2B_DIV_36 + * @arg @ref DDL_RCM_PLL2B_DIV_37 + * @arg @ref DDL_RCM_PLL2B_DIV_38 + * @arg @ref DDL_RCM_PLL2B_DIV_39 + * @arg @ref DDL_RCM_PLL2B_DIV_40 + * @arg @ref DDL_RCM_PLL2B_DIV_41 + * @arg @ref DDL_RCM_PLL2B_DIV_42 + * @arg @ref DDL_RCM_PLL2B_DIV_43 + * @arg @ref DDL_RCM_PLL2B_DIV_44 + * @arg @ref DDL_RCM_PLL2B_DIV_45 + * @arg @ref DDL_RCM_PLL2B_DIV_46 + * @arg @ref DDL_RCM_PLL2B_DIV_47 + * @arg @ref DDL_RCM_PLL2B_DIV_48 + * @arg @ref DDL_RCM_PLL2B_DIV_49 + * @arg @ref DDL_RCM_PLL2B_DIV_50 + * @arg @ref DDL_RCM_PLL2B_DIV_51 + * @arg @ref DDL_RCM_PLL2B_DIV_52 + * @arg @ref DDL_RCM_PLL2B_DIV_53 + * @arg @ref DDL_RCM_PLL2B_DIV_54 + * @arg @ref DDL_RCM_PLL2B_DIV_55 + * @arg @ref DDL_RCM_PLL2B_DIV_56 + * @arg @ref DDL_RCM_PLL2B_DIV_57 + * @arg @ref DDL_RCM_PLL2B_DIV_58 + * @arg @ref DDL_RCM_PLL2B_DIV_59 + * @arg @ref DDL_RCM_PLL2B_DIV_60 + * @arg @ref DDL_RCM_PLL2B_DIV_61 + * @arg @ref DDL_RCM_PLL2B_DIV_62 + * @arg @ref DDL_RCM_PLL2B_DIV_63 + * @param __PLL2A__ Between 50/192(*) and 432 + * + * (*) value not defined in all devices. + * @param __PLL2C__ This parameter can be one of the following values: + * @arg @ref DDL_RCM_PLL2C_DIV_2 + * @arg @ref DDL_RCM_PLL2C_DIV_3 + * @arg @ref DDL_RCM_PLL2C_DIV_4 + * @arg @ref DDL_RCM_PLL2C_DIV_5 + * @arg @ref DDL_RCM_PLL2C_DIV_6 + * @arg @ref DDL_RCM_PLL2C_DIV_7 + * @retval PLLI2S clock frequency (in Hz) + */ +#define __DDL_RCM_CALC_PLLI2S_I2S_FREQ(__INPUTFREQ__, __PLLB__, __PLL2A__, __PLL2C__) (((__INPUTFREQ__) / (__PLLB__)) * (__PLL2A__) / \ + ((__PLL2C__) >> RCM_PLL2CFG_PLL2C_Pos)) +#endif /* RCM_PLLI2S_SUPPORT */ + +/** + * @brief Helper macro to calculate the HCLK frequency + * @param __SYSCLKFREQ__ SYSCLK frequency (based on HSE/HSI/PLLCLK) + * @param __AHBPRESCALER__ This parameter can be one of the following values: + * @arg @ref DDL_RCM_SYSCLK_DIV_1 + * @arg @ref DDL_RCM_SYSCLK_DIV_2 + * @arg @ref DDL_RCM_SYSCLK_DIV_4 + * @arg @ref DDL_RCM_SYSCLK_DIV_8 + * @arg @ref DDL_RCM_SYSCLK_DIV_16 + * @arg @ref DDL_RCM_SYSCLK_DIV_64 + * @arg @ref DDL_RCM_SYSCLK_DIV_128 + * @arg @ref DDL_RCM_SYSCLK_DIV_256 + * @arg @ref DDL_RCM_SYSCLK_DIV_512 + * @retval HCLK clock frequency (in Hz) + */ +#define __DDL_RCM_CALC_HCLK_FREQ(__SYSCLKFREQ__, __AHBPRESCALER__) ((__SYSCLKFREQ__) >> AHBPrescTable[((__AHBPRESCALER__) & RCM_CFG_AHBPSC) >> RCM_CFG_AHBPSC_Pos]) + +/** + * @brief Helper macro to calculate the PCLK1 frequency (ABP1) + * @param __HCLKFREQ__ HCLK frequency + * @param __APB1PRESCALER__ This parameter can be one of the following values: + * @arg @ref DDL_RCM_APB1_DIV_1 + * @arg @ref DDL_RCM_APB1_DIV_2 + * @arg @ref DDL_RCM_APB1_DIV_4 + * @arg @ref DDL_RCM_APB1_DIV_8 + * @arg @ref DDL_RCM_APB1_DIV_16 + * @retval PCLK1 clock frequency (in Hz) + */ +#define __DDL_RCM_CALC_PCLK1_FREQ(__HCLKFREQ__, __APB1PRESCALER__) ((__HCLKFREQ__) >> APBPrescTable[(__APB1PRESCALER__) >> RCM_CFG_APB1PSC_Pos]) + +/** + * @brief Helper macro to calculate the PCLK2 frequency (ABP2) + * @param __HCLKFREQ__ HCLK frequency + * @param __APB2PRESCALER__ This parameter can be one of the following values: + * @arg @ref DDL_RCM_APB2_DIV_1 + * @arg @ref DDL_RCM_APB2_DIV_2 + * @arg @ref DDL_RCM_APB2_DIV_4 + * @arg @ref DDL_RCM_APB2_DIV_8 + * @arg @ref DDL_RCM_APB2_DIV_16 + * @retval PCLK2 clock frequency (in Hz) + */ +#define __DDL_RCM_CALC_PCLK2_FREQ(__HCLKFREQ__, __APB2PRESCALER__) ((__HCLKFREQ__) >> APBPrescTable[(__APB2PRESCALER__) >> RCM_CFG_APB2PSC_Pos]) + +/** + * @} + */ + +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +/** @defgroup RCM_DDL_Exported_Functions RCM Exported Functions + * @{ + */ + +/** @defgroup RCM_DDL_EF_HSE HSE + * @{ + */ + +/** + * @brief Enable the Clock Security System. + * @retval None + */ +__STATIC_INLINE void DDL_RCM_HSE_EnableCSS(void) +{ + SET_BIT(RCM->CTRL, RCM_CTRL_CSSEN); +} + +/** + * @brief Enable HSE external oscillator (HSE Bypass) + * @retval None + */ +__STATIC_INLINE void DDL_RCM_HSE_EnableBypass(void) +{ + SET_BIT(RCM->CTRL, RCM_CTRL_HSEBCFG); +} + +/** + * @brief Disable HSE external oscillator (HSE Bypass) + * @retval None + */ +__STATIC_INLINE void DDL_RCM_HSE_DisableBypass(void) +{ + CLEAR_BIT(RCM->CTRL, RCM_CTRL_HSEBCFG); +} + +/** + * @brief Enable HSE crystal oscillator (HSE ON) + * @retval None + */ +__STATIC_INLINE void DDL_RCM_HSE_Enable(void) +{ + SET_BIT(RCM->CTRL, RCM_CTRL_HSEEN); +} + +/** + * @brief Disable HSE crystal oscillator (HSE ON) + * @retval None + */ +__STATIC_INLINE void DDL_RCM_HSE_Disable(void) +{ + CLEAR_BIT(RCM->CTRL, RCM_CTRL_HSEEN); +} + +/** + * @brief Check if HSE oscillator Ready + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_RCM_HSE_IsReady(void) +{ + return (READ_BIT(RCM->CTRL, RCM_CTRL_HSERDYFLG) == (RCM_CTRL_HSERDYFLG)); +} + +/** + * @} + */ + +/** @defgroup RCM_DDL_EF_HSI HSI + * @{ + */ + +/** + * @brief Enable HSI oscillator + * @retval None + */ +__STATIC_INLINE void DDL_RCM_HSI_Enable(void) +{ + SET_BIT(RCM->CTRL, RCM_CTRL_HSIEN); +} + +/** + * @brief Disable HSI oscillator + * @retval None + */ +__STATIC_INLINE void DDL_RCM_HSI_Disable(void) +{ + CLEAR_BIT(RCM->CTRL, RCM_CTRL_HSIEN); +} + +/** + * @brief Check if HSI clock is ready + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_RCM_HSI_IsReady(void) +{ + return (READ_BIT(RCM->CTRL, RCM_CTRL_HSIRDYFLG) == (RCM_CTRL_HSIRDYFLG)); +} + +/** + * @brief Get HSI Calibration value + * @note When HSITRIM is written, HSICAL is updated with the sum of + * HSITRIM and the factory trim value + * @retval Between Min_Data = 0x00 and Max_Data = 0xFF + */ +__STATIC_INLINE uint32_t DDL_RCM_HSI_GetCalibration(void) +{ + return (uint32_t)(READ_BIT(RCM->CTRL, RCM_CTRL_HSICAL) >> RCM_CTRL_HSICAL_Pos); +} + +/** + * @brief Set HSI Calibration trimming + * @note user-programmable trimming value that is added to the HSICAL + * @note Default value is 16, which, when added to the HSICAL value, + * should trim the HSI to 16 MHz +/- 1 % + * @param Value Between Min_Data = 0 and Max_Data = 31 + * @retval None + */ +__STATIC_INLINE void DDL_RCM_HSI_SetCalibTrimming(uint32_t Value) +{ + MODIFY_REG(RCM->CTRL, RCM_CTRL_HSITRM, Value << RCM_CTRL_HSITRM_Pos); +} + +/** + * @brief Get HSI Calibration trimming + * @retval Between Min_Data = 0 and Max_Data = 31 + */ +__STATIC_INLINE uint32_t DDL_RCM_HSI_GetCalibTrimming(void) +{ + return (uint32_t)(READ_BIT(RCM->CTRL, RCM_CTRL_HSITRM) >> RCM_CTRL_HSITRM_Pos); +} + +/** + * @} + */ + +/** @defgroup RCM_DDL_EF_LSE LSE + * @{ + */ + +/** + * @brief Enable Low Speed External (LSE) crystal. + * @retval None + */ +__STATIC_INLINE void DDL_RCM_LSE_Enable(void) +{ + SET_BIT(RCM->BDCTRL, RCM_BDCTRL_LSEEN); +} + +/** + * @brief Disable Low Speed External (LSE) crystal. + * @retval None + */ +__STATIC_INLINE void DDL_RCM_LSE_Disable(void) +{ + CLEAR_BIT(RCM->BDCTRL, RCM_BDCTRL_LSEEN); +} + +/** + * @brief Enable external clock source (LSE bypass). + * @retval None + */ +__STATIC_INLINE void DDL_RCM_LSE_EnableBypass(void) +{ + SET_BIT(RCM->BDCTRL, RCM_BDCTRL_LSEBCFG); +} + +/** + * @brief Disable external clock source (LSE bypass). + * @retval None + */ +__STATIC_INLINE void DDL_RCM_LSE_DisableBypass(void) +{ + CLEAR_BIT(RCM->BDCTRL, RCM_BDCTRL_LSEBCFG); +} + +/** + * @brief Check if LSE oscillator Ready + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_RCM_LSE_IsReady(void) +{ + return (READ_BIT(RCM->BDCTRL, RCM_BDCTRL_LSERDYFLG) == (RCM_BDCTRL_LSERDYFLG)); +} + +#if defined(RCM_BDCTRL_LSEMOD) +/** + * @brief Enable LSE high drive mode. + * @note LSE high drive mode can be enabled only when the LSE clock is disabled + * @retval None + */ +__STATIC_INLINE void DDL_RCM_LSE_EnableHighDriveMode(void) +{ + SET_BIT(RCM->BDCTRL, RCM_BDCTRL_LSEMOD); +} + +/** + * @brief Disable LSE high drive mode. + * @note LSE high drive mode can be disabled only when the LSE clock is disabled + * @retval None + */ +__STATIC_INLINE void DDL_RCM_LSE_DisableHighDriveMode(void) +{ + CLEAR_BIT(RCM->BDCTRL, RCM_BDCTRL_LSEMOD); +} +#endif /* RCM_BDCTRL_LSEMOD */ + +/** + * @} + */ + +/** @defgroup RCM_DDL_EF_LSI LSI + * @{ + */ + +/** + * @brief Enable LSI Oscillator + * @retval None + */ +__STATIC_INLINE void DDL_RCM_LSI_Enable(void) +{ + SET_BIT(RCM->CSTS, RCM_CSTS_LSIEN); +} + +/** + * @brief Disable LSI Oscillator + * @retval None + */ +__STATIC_INLINE void DDL_RCM_LSI_Disable(void) +{ + CLEAR_BIT(RCM->CSTS, RCM_CSTS_LSIEN); +} + +/** + * @brief Check if LSI is Ready + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_RCM_LSI_IsReady(void) +{ + return (READ_BIT(RCM->CSTS, RCM_CSTS_LSIRDYFLG) == (RCM_CSTS_LSIRDYFLG)); +} + +/** + * @} + */ + +/** @defgroup RCM_DDL_EF_System System + * @{ + */ + +/** + * @brief Configure the system clock source + * @param Source This parameter can be one of the following values: + * @arg @ref DDL_RCM_SYS_CLKSOURCE_HSI + * @arg @ref DDL_RCM_SYS_CLKSOURCE_HSE + * @arg @ref DDL_RCM_SYS_CLKSOURCE_PLL + * @arg @ref DDL_RCM_SYS_CLKSOURCE_PLLR (*) + * + * (*) value not defined in all devices. + * @retval None + */ +__STATIC_INLINE void DDL_RCM_SetSysClkSource(uint32_t Source) +{ + MODIFY_REG(RCM->CFG, RCM_CFG_SCLKSEL, Source); +} + +/** + * @brief Get the system clock source + * @retval Returned value can be one of the following values: + * @arg @ref DDL_RCM_SYS_CLKSOURCE_STATUS_HSI + * @arg @ref DDL_RCM_SYS_CLKSOURCE_STATUS_HSE + * @arg @ref DDL_RCM_SYS_CLKSOURCE_STATUS_PLL + * @arg @ref DDL_RCM_SYS_CLKSOURCE_STATUS_PLLR (*) + * + * (*) value not defined in all devices. + */ +__STATIC_INLINE uint32_t DDL_RCM_GetSysClkSource(void) +{ + return (uint32_t)(READ_BIT(RCM->CFG, RCM_CFG_SCLKSWSTS)); +} + +/** + * @brief Set AHB prescaler + * @param Prescaler This parameter can be one of the following values: + * @arg @ref DDL_RCM_SYSCLK_DIV_1 + * @arg @ref DDL_RCM_SYSCLK_DIV_2 + * @arg @ref DDL_RCM_SYSCLK_DIV_4 + * @arg @ref DDL_RCM_SYSCLK_DIV_8 + * @arg @ref DDL_RCM_SYSCLK_DIV_16 + * @arg @ref DDL_RCM_SYSCLK_DIV_64 + * @arg @ref DDL_RCM_SYSCLK_DIV_128 + * @arg @ref DDL_RCM_SYSCLK_DIV_256 + * @arg @ref DDL_RCM_SYSCLK_DIV_512 + * @retval None + */ +__STATIC_INLINE void DDL_RCM_SetAHBPrescaler(uint32_t Prescaler) +{ + MODIFY_REG(RCM->CFG, RCM_CFG_AHBPSC, Prescaler); +} + +/** + * @brief Set APB1 prescaler + * @param Prescaler This parameter can be one of the following values: + * @arg @ref DDL_RCM_APB1_DIV_1 + * @arg @ref DDL_RCM_APB1_DIV_2 + * @arg @ref DDL_RCM_APB1_DIV_4 + * @arg @ref DDL_RCM_APB1_DIV_8 + * @arg @ref DDL_RCM_APB1_DIV_16 + * @retval None + */ +__STATIC_INLINE void DDL_RCM_SetAPB1Prescaler(uint32_t Prescaler) +{ + MODIFY_REG(RCM->CFG, RCM_CFG_APB1PSC, Prescaler); +} + +/** + * @brief Set APB2 prescaler + * @param Prescaler This parameter can be one of the following values: + * @arg @ref DDL_RCM_APB2_DIV_1 + * @arg @ref DDL_RCM_APB2_DIV_2 + * @arg @ref DDL_RCM_APB2_DIV_4 + * @arg @ref DDL_RCM_APB2_DIV_8 + * @arg @ref DDL_RCM_APB2_DIV_16 + * @retval None + */ +__STATIC_INLINE void DDL_RCM_SetAPB2Prescaler(uint32_t Prescaler) +{ + MODIFY_REG(RCM->CFG, RCM_CFG_APB2PSC, Prescaler); +} + +/** + * @brief Get AHB prescaler + * @retval Returned value can be one of the following values: + * @arg @ref DDL_RCM_SYSCLK_DIV_1 + * @arg @ref DDL_RCM_SYSCLK_DIV_2 + * @arg @ref DDL_RCM_SYSCLK_DIV_4 + * @arg @ref DDL_RCM_SYSCLK_DIV_8 + * @arg @ref DDL_RCM_SYSCLK_DIV_16 + * @arg @ref DDL_RCM_SYSCLK_DIV_64 + * @arg @ref DDL_RCM_SYSCLK_DIV_128 + * @arg @ref DDL_RCM_SYSCLK_DIV_256 + * @arg @ref DDL_RCM_SYSCLK_DIV_512 + */ +__STATIC_INLINE uint32_t DDL_RCM_GetAHBPrescaler(void) +{ + return (uint32_t)(READ_BIT(RCM->CFG, RCM_CFG_AHBPSC)); +} + +/** + * @brief Get APB1 prescaler + * @retval Returned value can be one of the following values: + * @arg @ref DDL_RCM_APB1_DIV_1 + * @arg @ref DDL_RCM_APB1_DIV_2 + * @arg @ref DDL_RCM_APB1_DIV_4 + * @arg @ref DDL_RCM_APB1_DIV_8 + * @arg @ref DDL_RCM_APB1_DIV_16 + */ +__STATIC_INLINE uint32_t DDL_RCM_GetAPB1Prescaler(void) +{ + return (uint32_t)(READ_BIT(RCM->CFG, RCM_CFG_APB1PSC)); +} + +/** + * @brief Get APB2 prescaler + * @retval Returned value can be one of the following values: + * @arg @ref DDL_RCM_APB2_DIV_1 + * @arg @ref DDL_RCM_APB2_DIV_2 + * @arg @ref DDL_RCM_APB2_DIV_4 + * @arg @ref DDL_RCM_APB2_DIV_8 + * @arg @ref DDL_RCM_APB2_DIV_16 + */ +__STATIC_INLINE uint32_t DDL_RCM_GetAPB2Prescaler(void) +{ + return (uint32_t)(READ_BIT(RCM->CFG, RCM_CFG_APB2PSC)); +} + +/** + * @} + */ + +/** @defgroup RCM_DDL_EF_MCO MCO + * @{ + */ + +#if defined(RCM_CFG_MCO1EN) +/** + * @brief Enable MCO1 output + * @retval None + */ +__STATIC_INLINE void DDL_RCM_MCO1_Enable(void) +{ + SET_BIT(RCM->CFG, RCM_CFG_MCO1EN); +} + +/** + * @brief Disable MCO1 output + * @retval None + */ +__STATIC_INLINE void DDL_RCM_MCO1_Disable(void) +{ + CLEAR_BIT(RCM->CFG, RCM_CFG_MCO1EN); +} +#endif /* RCM_CFG_MCO1EN */ + +#if defined(RCM_CFG_MCO2EN) +/** + * @brief Enable MCO2 output + * @retval None + */ +__STATIC_INLINE void DDL_RCM_MCO2_Enable(void) +{ + SET_BIT(RCM->CFG, RCM_CFG_MCO2EN); +} + +/** + * @brief Disable MCO2 output + * @retval None + */ +__STATIC_INLINE void DDL_RCM_MCO2_Disable(void) +{ + CLEAR_BIT(RCM->CFG, RCM_CFG_MCO2EN); +} +#endif /* RCM_CFG_MCO2EN */ + +/** + * @brief Configure MCOx + * @param MCOxSource This parameter can be one of the following values: + * @arg @ref DDL_RCM_MCO1SOURCE_HSI + * @arg @ref DDL_RCM_MCO1SOURCE_LSE + * @arg @ref DDL_RCM_MCO1SOURCE_HSE + * @arg @ref DDL_RCM_MCO1SOURCE_PLLCLK + * @arg @ref DDL_RCM_MCO2SOURCE_SYSCLK + * @arg @ref DDL_RCM_MCO2SOURCE_PLLI2S + * @arg @ref DDL_RCM_MCO2SOURCE_HSE + * @arg @ref DDL_RCM_MCO2SOURCE_PLLCLK + * @param MCOxPrescaler This parameter can be one of the following values: + * @arg @ref DDL_RCM_MCO1_DIV_1 + * @arg @ref DDL_RCM_MCO1_DIV_2 + * @arg @ref DDL_RCM_MCO1_DIV_3 + * @arg @ref DDL_RCM_MCO1_DIV_4 + * @arg @ref DDL_RCM_MCO1_DIV_5 + * @arg @ref DDL_RCM_MCO2_DIV_1 + * @arg @ref DDL_RCM_MCO2_DIV_2 + * @arg @ref DDL_RCM_MCO2_DIV_3 + * @arg @ref DDL_RCM_MCO2_DIV_4 + * @arg @ref DDL_RCM_MCO2_DIV_5 + * @retval None + */ +__STATIC_INLINE void DDL_RCM_ConfigMCO(uint32_t MCOxSource, uint32_t MCOxPrescaler) +{ + MODIFY_REG(RCM->CFG, (MCOxSource & 0xFFFF0000U) | (MCOxPrescaler & 0xFFFF0000U), (MCOxSource << 16U) | (MCOxPrescaler << 16U)); +} + +/** + * @} + */ + +/** @defgroup RCM_DDL_EF_Peripheral_Clock_Source Peripheral Clock Source + * @{ + */ + +/** + * @brief Configure I2S clock source + * @param Source This parameter can be one of the following values: + * @arg @ref DDL_RCM_I2S1_CLKSOURCE_PLLI2S (*) + * @arg @ref DDL_RCM_I2S1_CLKSOURCE_PIN + * @arg @ref DDL_RCM_I2S1_CLKSOURCE_PLL (*) + * @arg @ref DDL_RCM_I2S1_CLKSOURCE_PLLSRC (*) + * @arg @ref DDL_RCM_I2S2_CLKSOURCE_PLLI2S (*) + * @arg @ref DDL_RCM_I2S2_CLKSOURCE_PIN (*) + * @arg @ref DDL_RCM_I2S2_CLKSOURCE_PLL (*) + * @arg @ref DDL_RCM_I2S2_CLKSOURCE_PLLSRC (*) + * + * (*) value not defined in all devices. + * @retval None + */ +__STATIC_INLINE void DDL_RCM_SetI2SClockSource(uint32_t Source) +{ +#if defined(RCM_CFG_I2SSEL) + MODIFY_REG(RCM->CFG, RCM_CFG_I2SSEL, Source); +#else + MODIFY_REG(RCM->DCKCFGR, (Source & 0xFFFF0000U), (Source << 16U)); +#endif /* RCM_CFG_I2SSEL */ +} + +/** + * @brief Get I2S Clock Source + * @param I2Sx This parameter can be one of the following values: + * @arg @ref DDL_RCM_I2S1_CLKSOURCE + * @arg @ref DDL_RCM_I2S2_CLKSOURCE (*) + * @retval Returned value can be one of the following values: + * @arg @ref DDL_RCM_I2S1_CLKSOURCE_PLLI2S (*) + * @arg @ref DDL_RCM_I2S1_CLKSOURCE_PIN + * @arg @ref DDL_RCM_I2S1_CLKSOURCE_PLL (*) + * @arg @ref DDL_RCM_I2S1_CLKSOURCE_PLLSRC (*) + * @arg @ref DDL_RCM_I2S2_CLKSOURCE_PLLI2S (*) + * @arg @ref DDL_RCM_I2S2_CLKSOURCE_PIN (*) + * @arg @ref DDL_RCM_I2S2_CLKSOURCE_PLL (*) + * @arg @ref DDL_RCM_I2S2_CLKSOURCE_PLLSRC (*) + * + * (*) value not defined in all devices. + */ +__STATIC_INLINE uint32_t DDL_RCM_GetI2SClockSource(uint32_t I2Sx) +{ +#if defined(RCM_CFG_I2SSEL) + return (uint32_t)(READ_BIT(RCM->CFG, I2Sx)); +#else + return (uint32_t)(READ_BIT(RCM->DCKCFGR, I2Sx) >> 16U | I2Sx); +#endif /* RCM_CFG_I2SSEL */ +} + +/** + * @} + */ + +/** @defgroup RCM_DDL_EF_RTC RTC + * @{ + */ + +/** + * @brief Set RTC Clock Source + * @note Once the RTC clock source has been selected, it cannot be changed anymore unless + * the Backup domain is reset, or unless a failure is detected on LSE (LSECSSD is + * set). The BDRST bit can be used to reset them. + * @param Source This parameter can be one of the following values: + * @arg @ref DDL_RCM_RTC_CLKSOURCE_NONE + * @arg @ref DDL_RCM_RTC_CLKSOURCE_LSE + * @arg @ref DDL_RCM_RTC_CLKSOURCE_LSI + * @arg @ref DDL_RCM_RTC_CLKSOURCE_HSE + * @retval None + */ +__STATIC_INLINE void DDL_RCM_SetRTCClockSource(uint32_t Source) +{ + MODIFY_REG(RCM->BDCTRL, RCM_BDCTRL_RTCSRCSEL, Source); +} + +/** + * @brief Get RTC Clock Source + * @retval Returned value can be one of the following values: + * @arg @ref DDL_RCM_RTC_CLKSOURCE_NONE + * @arg @ref DDL_RCM_RTC_CLKSOURCE_LSE + * @arg @ref DDL_RCM_RTC_CLKSOURCE_LSI + * @arg @ref DDL_RCM_RTC_CLKSOURCE_HSE + */ +__STATIC_INLINE uint32_t DDL_RCM_GetRTCClockSource(void) +{ + return (uint32_t)(READ_BIT(RCM->BDCTRL, RCM_BDCTRL_RTCSRCSEL)); +} + +/** + * @brief Enable RTC + * @retval None + */ +__STATIC_INLINE void DDL_RCM_EnableRTC(void) +{ + SET_BIT(RCM->BDCTRL, RCM_BDCTRL_RTCCLKEN); +} + +/** + * @brief Disable RTC + * @retval None + */ +__STATIC_INLINE void DDL_RCM_DisableRTC(void) +{ + CLEAR_BIT(RCM->BDCTRL, RCM_BDCTRL_RTCCLKEN); +} + +/** + * @brief Check if RTC has been enabled or not + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_RCM_IsEnabledRTC(void) +{ + return (READ_BIT(RCM->BDCTRL, RCM_BDCTRL_RTCCLKEN) == (RCM_BDCTRL_RTCCLKEN)); +} + +/** + * @brief Force the Backup domain reset + * @retval None + */ +__STATIC_INLINE void DDL_RCM_ForceBackupDomainReset(void) +{ + SET_BIT(RCM->BDCTRL, RCM_BDCTRL_BDRST); +} + +/** + * @brief Release the Backup domain reset + * @retval None + */ +__STATIC_INLINE void DDL_RCM_ReleaseBackupDomainReset(void) +{ + CLEAR_BIT(RCM->BDCTRL, RCM_BDCTRL_BDRST); +} + +/** + * @brief Set HSE Prescalers for RTC Clock + * @param Prescaler This parameter can be one of the following values: + * @arg @ref DDL_RCM_RTC_NOCLOCK + * @arg @ref DDL_RCM_RTC_HSE_DIV_2 + * @arg @ref DDL_RCM_RTC_HSE_DIV_3 + * @arg @ref DDL_RCM_RTC_HSE_DIV_4 + * @arg @ref DDL_RCM_RTC_HSE_DIV_5 + * @arg @ref DDL_RCM_RTC_HSE_DIV_6 + * @arg @ref DDL_RCM_RTC_HSE_DIV_7 + * @arg @ref DDL_RCM_RTC_HSE_DIV_8 + * @arg @ref DDL_RCM_RTC_HSE_DIV_9 + * @arg @ref DDL_RCM_RTC_HSE_DIV_10 + * @arg @ref DDL_RCM_RTC_HSE_DIV_11 + * @arg @ref DDL_RCM_RTC_HSE_DIV_12 + * @arg @ref DDL_RCM_RTC_HSE_DIV_13 + * @arg @ref DDL_RCM_RTC_HSE_DIV_14 + * @arg @ref DDL_RCM_RTC_HSE_DIV_15 + * @arg @ref DDL_RCM_RTC_HSE_DIV_16 + * @arg @ref DDL_RCM_RTC_HSE_DIV_17 + * @arg @ref DDL_RCM_RTC_HSE_DIV_18 + * @arg @ref DDL_RCM_RTC_HSE_DIV_19 + * @arg @ref DDL_RCM_RTC_HSE_DIV_20 + * @arg @ref DDL_RCM_RTC_HSE_DIV_21 + * @arg @ref DDL_RCM_RTC_HSE_DIV_22 + * @arg @ref DDL_RCM_RTC_HSE_DIV_23 + * @arg @ref DDL_RCM_RTC_HSE_DIV_24 + * @arg @ref DDL_RCM_RTC_HSE_DIV_25 + * @arg @ref DDL_RCM_RTC_HSE_DIV_26 + * @arg @ref DDL_RCM_RTC_HSE_DIV_27 + * @arg @ref DDL_RCM_RTC_HSE_DIV_28 + * @arg @ref DDL_RCM_RTC_HSE_DIV_29 + * @arg @ref DDL_RCM_RTC_HSE_DIV_30 + * @arg @ref DDL_RCM_RTC_HSE_DIV_31 + * @retval None + */ +__STATIC_INLINE void DDL_RCM_SetRTC_HSEPrescaler(uint32_t Prescaler) +{ + MODIFY_REG(RCM->CFG, RCM_CFG_RTCPSC, Prescaler); +} + +/** + * @brief Get HSE Prescalers for RTC Clock + * @retval Returned value can be one of the following values: + * @arg @ref DDL_RCM_RTC_NOCLOCK + * @arg @ref DDL_RCM_RTC_HSE_DIV_2 + * @arg @ref DDL_RCM_RTC_HSE_DIV_3 + * @arg @ref DDL_RCM_RTC_HSE_DIV_4 + * @arg @ref DDL_RCM_RTC_HSE_DIV_5 + * @arg @ref DDL_RCM_RTC_HSE_DIV_6 + * @arg @ref DDL_RCM_RTC_HSE_DIV_7 + * @arg @ref DDL_RCM_RTC_HSE_DIV_8 + * @arg @ref DDL_RCM_RTC_HSE_DIV_9 + * @arg @ref DDL_RCM_RTC_HSE_DIV_10 + * @arg @ref DDL_RCM_RTC_HSE_DIV_11 + * @arg @ref DDL_RCM_RTC_HSE_DIV_12 + * @arg @ref DDL_RCM_RTC_HSE_DIV_13 + * @arg @ref DDL_RCM_RTC_HSE_DIV_14 + * @arg @ref DDL_RCM_RTC_HSE_DIV_15 + * @arg @ref DDL_RCM_RTC_HSE_DIV_16 + * @arg @ref DDL_RCM_RTC_HSE_DIV_17 + * @arg @ref DDL_RCM_RTC_HSE_DIV_18 + * @arg @ref DDL_RCM_RTC_HSE_DIV_19 + * @arg @ref DDL_RCM_RTC_HSE_DIV_20 + * @arg @ref DDL_RCM_RTC_HSE_DIV_21 + * @arg @ref DDL_RCM_RTC_HSE_DIV_22 + * @arg @ref DDL_RCM_RTC_HSE_DIV_23 + * @arg @ref DDL_RCM_RTC_HSE_DIV_24 + * @arg @ref DDL_RCM_RTC_HSE_DIV_25 + * @arg @ref DDL_RCM_RTC_HSE_DIV_26 + * @arg @ref DDL_RCM_RTC_HSE_DIV_27 + * @arg @ref DDL_RCM_RTC_HSE_DIV_28 + * @arg @ref DDL_RCM_RTC_HSE_DIV_29 + * @arg @ref DDL_RCM_RTC_HSE_DIV_30 + * @arg @ref DDL_RCM_RTC_HSE_DIV_31 + */ +__STATIC_INLINE uint32_t DDL_RCM_GetRTC_HSEPrescaler(void) +{ + return (uint32_t)(READ_BIT(RCM->CFG, RCM_CFG_RTCPSC)); +} + +/** + * @} + */ + +#if defined(RCM_CFGSEL_CLKPSEL) +/** @defgroup RCM_DDL_EF_TMR_CLOCK_PRESCALER TMR + * @{ + */ + +/** + * @brief Set Timers Clock Prescalers + * @param Prescaler This parameter can be one of the following values: + * @arg @ref DDL_RCM_TMR_PRESCALER_TWICE + * @arg @ref DDL_RCM_TMR_PRESCALER_FOUR_TIMES + * @retval None + */ +__STATIC_INLINE void DDL_RCM_SetTMRPrescaler(uint32_t Prescaler) +{ + MODIFY_REG(RCM->CFGSEL, RCM_CFGSEL_CLKPSEL, Prescaler); +} + +/** + * @brief Get Timers Clock Prescalers + * @retval Returned value can be one of the following values: + * @arg @ref DDL_RCM_TMR_PRESCALER_TWICE + * @arg @ref DDL_RCM_TMR_PRESCALER_FOUR_TIMES + */ +__STATIC_INLINE uint32_t DDL_RCM_GetTMRPrescaler(void) +{ + return (uint32_t)(READ_BIT(RCM->CFGSEL, RCM_CFGSEL_CLKPSEL)); +} + +/** + * @} + */ +#endif /* RCM_CFGSEL_CLKPSEL */ + +/** @defgroup RCM_DDL_EF_PLL PLL + * @{ + */ + +/** + * @brief Enable PLL + * @retval None + */ +__STATIC_INLINE void DDL_RCM_PLL_Enable(void) +{ + SET_BIT(RCM->CTRL, RCM_CTRL_PLL1EN); +} + +/** + * @brief Disable PLL + * @note Cannot be disabled if the PLL clock is used as the system clock + * @retval None + */ +__STATIC_INLINE void DDL_RCM_PLL_Disable(void) +{ + CLEAR_BIT(RCM->CTRL, RCM_CTRL_PLL1EN); +} + +/** + * @brief Check if PLL Ready + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_RCM_PLL_IsReady(void) +{ + return (READ_BIT(RCM->CTRL, RCM_CTRL_PLL1RDYFLG) == (RCM_CTRL_PLL1RDYFLG)); +} + +/** + * @brief Configure PLL used for SYSCLK Domain + * @note PLL Source and PLLB Divider can be written only when PLL, + * PLLI2S and PLLSAI(*) are disabled + * @note PLL1A/PLL1C can be written only when PLL is disabled + * @param Source This parameter can be one of the following values: + * @arg @ref DDL_RCM_PLLSOURCE_HSI + * @arg @ref DDL_RCM_PLLSOURCE_HSE + * @param PLLB This parameter can be one of the following values: + * @arg @ref DDL_RCM_PLLB_DIV_2 + * @arg @ref DDL_RCM_PLLB_DIV_3 + * @arg @ref DDL_RCM_PLLB_DIV_4 + * @arg @ref DDL_RCM_PLLB_DIV_5 + * @arg @ref DDL_RCM_PLLB_DIV_6 + * @arg @ref DDL_RCM_PLLB_DIV_7 + * @arg @ref DDL_RCM_PLLB_DIV_8 + * @arg @ref DDL_RCM_PLLB_DIV_9 + * @arg @ref DDL_RCM_PLLB_DIV_10 + * @arg @ref DDL_RCM_PLLB_DIV_11 + * @arg @ref DDL_RCM_PLLB_DIV_12 + * @arg @ref DDL_RCM_PLLB_DIV_13 + * @arg @ref DDL_RCM_PLLB_DIV_14 + * @arg @ref DDL_RCM_PLLB_DIV_15 + * @arg @ref DDL_RCM_PLLB_DIV_16 + * @arg @ref DDL_RCM_PLLB_DIV_17 + * @arg @ref DDL_RCM_PLLB_DIV_18 + * @arg @ref DDL_RCM_PLLB_DIV_19 + * @arg @ref DDL_RCM_PLLB_DIV_20 + * @arg @ref DDL_RCM_PLLB_DIV_21 + * @arg @ref DDL_RCM_PLLB_DIV_22 + * @arg @ref DDL_RCM_PLLB_DIV_23 + * @arg @ref DDL_RCM_PLLB_DIV_24 + * @arg @ref DDL_RCM_PLLB_DIV_25 + * @arg @ref DDL_RCM_PLLB_DIV_26 + * @arg @ref DDL_RCM_PLLB_DIV_27 + * @arg @ref DDL_RCM_PLLB_DIV_28 + * @arg @ref DDL_RCM_PLLB_DIV_29 + * @arg @ref DDL_RCM_PLLB_DIV_30 + * @arg @ref DDL_RCM_PLLB_DIV_31 + * @arg @ref DDL_RCM_PLLB_DIV_32 + * @arg @ref DDL_RCM_PLLB_DIV_33 + * @arg @ref DDL_RCM_PLLB_DIV_34 + * @arg @ref DDL_RCM_PLLB_DIV_35 + * @arg @ref DDL_RCM_PLLB_DIV_36 + * @arg @ref DDL_RCM_PLLB_DIV_37 + * @arg @ref DDL_RCM_PLLB_DIV_38 + * @arg @ref DDL_RCM_PLLB_DIV_39 + * @arg @ref DDL_RCM_PLLB_DIV_40 + * @arg @ref DDL_RCM_PLLB_DIV_41 + * @arg @ref DDL_RCM_PLLB_DIV_42 + * @arg @ref DDL_RCM_PLLB_DIV_43 + * @arg @ref DDL_RCM_PLLB_DIV_44 + * @arg @ref DDL_RCM_PLLB_DIV_45 + * @arg @ref DDL_RCM_PLLB_DIV_46 + * @arg @ref DDL_RCM_PLLB_DIV_47 + * @arg @ref DDL_RCM_PLLB_DIV_48 + * @arg @ref DDL_RCM_PLLB_DIV_49 + * @arg @ref DDL_RCM_PLLB_DIV_50 + * @arg @ref DDL_RCM_PLLB_DIV_51 + * @arg @ref DDL_RCM_PLLB_DIV_52 + * @arg @ref DDL_RCM_PLLB_DIV_53 + * @arg @ref DDL_RCM_PLLB_DIV_54 + * @arg @ref DDL_RCM_PLLB_DIV_55 + * @arg @ref DDL_RCM_PLLB_DIV_56 + * @arg @ref DDL_RCM_PLLB_DIV_57 + * @arg @ref DDL_RCM_PLLB_DIV_58 + * @arg @ref DDL_RCM_PLLB_DIV_59 + * @arg @ref DDL_RCM_PLLB_DIV_60 + * @arg @ref DDL_RCM_PLLB_DIV_61 + * @arg @ref DDL_RCM_PLLB_DIV_62 + * @arg @ref DDL_RCM_PLLB_DIV_63 + * @param PLL1A Between 50/192(*) and 432 + * + * (*) value not defined in all devices. + * @param PLL1C_R This parameter can be one of the following values: + * @arg @ref DDL_RCM_PLL1C_DIV_2 + * @arg @ref DDL_RCM_PLL1C_DIV_4 + * @arg @ref DDL_RCM_PLL1C_DIV_6 + * @arg @ref DDL_RCM_PLL1C_DIV_8 + * @arg @ref DDL_RCM_PLLR_DIV_2 (*) + * @arg @ref DDL_RCM_PLLR_DIV_3 (*) + * @arg @ref DDL_RCM_PLLR_DIV_4 (*) + * @arg @ref DDL_RCM_PLLR_DIV_5 (*) + * @arg @ref DDL_RCM_PLLR_DIV_6 (*) + * @arg @ref DDL_RCM_PLLR_DIV_7 (*) + * + * (*) value not defined in all devices. + * @retval None + */ +__STATIC_INLINE void DDL_RCM_PLL_ConfigDomain_SYS(uint32_t Source, uint32_t PLLB, uint32_t PLL1A, uint32_t PLL1C_R) +{ + MODIFY_REG(RCM->PLL1CFG, RCM_PLL1CFG_PLL1CLKS | RCM_PLL1CFG_PLLB | RCM_PLL1CFG_PLL1A, + Source | PLLB | PLL1A << RCM_PLL1CFG_PLL1A_Pos); + MODIFY_REG(RCM->PLL1CFG, RCM_PLL1CFG_PLL1C, PLL1C_R); +#if defined(RCM_PLLR_SYSCLK_SUPPORT) + MODIFY_REG(RCM->PLL1CFG, RCM_PLL1CFG_PLLR, PLL1C_R); +#endif /* RCM_PLLR_SYSCLK_SUPPORT */ +} + +/** + * @brief Configure PLL used for 48Mhz domain clock + * @note PLL Source and PLLB Divider can be written only when PLL, + * PLLI2S and PLLSAI(*) are disabled + * @note PLL1A/PLLD can be written only when PLL is disabled + * @note This can be selected for USB, RNG, SDIO + * @param Source This parameter can be one of the following values: + * @arg @ref DDL_RCM_PLLSOURCE_HSI + * @arg @ref DDL_RCM_PLLSOURCE_HSE + * @param PLLB This parameter can be one of the following values: + * @arg @ref DDL_RCM_PLLB_DIV_2 + * @arg @ref DDL_RCM_PLLB_DIV_3 + * @arg @ref DDL_RCM_PLLB_DIV_4 + * @arg @ref DDL_RCM_PLLB_DIV_5 + * @arg @ref DDL_RCM_PLLB_DIV_6 + * @arg @ref DDL_RCM_PLLB_DIV_7 + * @arg @ref DDL_RCM_PLLB_DIV_8 + * @arg @ref DDL_RCM_PLLB_DIV_9 + * @arg @ref DDL_RCM_PLLB_DIV_10 + * @arg @ref DDL_RCM_PLLB_DIV_11 + * @arg @ref DDL_RCM_PLLB_DIV_12 + * @arg @ref DDL_RCM_PLLB_DIV_13 + * @arg @ref DDL_RCM_PLLB_DIV_14 + * @arg @ref DDL_RCM_PLLB_DIV_15 + * @arg @ref DDL_RCM_PLLB_DIV_16 + * @arg @ref DDL_RCM_PLLB_DIV_17 + * @arg @ref DDL_RCM_PLLB_DIV_18 + * @arg @ref DDL_RCM_PLLB_DIV_19 + * @arg @ref DDL_RCM_PLLB_DIV_20 + * @arg @ref DDL_RCM_PLLB_DIV_21 + * @arg @ref DDL_RCM_PLLB_DIV_22 + * @arg @ref DDL_RCM_PLLB_DIV_23 + * @arg @ref DDL_RCM_PLLB_DIV_24 + * @arg @ref DDL_RCM_PLLB_DIV_25 + * @arg @ref DDL_RCM_PLLB_DIV_26 + * @arg @ref DDL_RCM_PLLB_DIV_27 + * @arg @ref DDL_RCM_PLLB_DIV_28 + * @arg @ref DDL_RCM_PLLB_DIV_29 + * @arg @ref DDL_RCM_PLLB_DIV_30 + * @arg @ref DDL_RCM_PLLB_DIV_31 + * @arg @ref DDL_RCM_PLLB_DIV_32 + * @arg @ref DDL_RCM_PLLB_DIV_33 + * @arg @ref DDL_RCM_PLLB_DIV_34 + * @arg @ref DDL_RCM_PLLB_DIV_35 + * @arg @ref DDL_RCM_PLLB_DIV_36 + * @arg @ref DDL_RCM_PLLB_DIV_37 + * @arg @ref DDL_RCM_PLLB_DIV_38 + * @arg @ref DDL_RCM_PLLB_DIV_39 + * @arg @ref DDL_RCM_PLLB_DIV_40 + * @arg @ref DDL_RCM_PLLB_DIV_41 + * @arg @ref DDL_RCM_PLLB_DIV_42 + * @arg @ref DDL_RCM_PLLB_DIV_43 + * @arg @ref DDL_RCM_PLLB_DIV_44 + * @arg @ref DDL_RCM_PLLB_DIV_45 + * @arg @ref DDL_RCM_PLLB_DIV_46 + * @arg @ref DDL_RCM_PLLB_DIV_47 + * @arg @ref DDL_RCM_PLLB_DIV_48 + * @arg @ref DDL_RCM_PLLB_DIV_49 + * @arg @ref DDL_RCM_PLLB_DIV_50 + * @arg @ref DDL_RCM_PLLB_DIV_51 + * @arg @ref DDL_RCM_PLLB_DIV_52 + * @arg @ref DDL_RCM_PLLB_DIV_53 + * @arg @ref DDL_RCM_PLLB_DIV_54 + * @arg @ref DDL_RCM_PLLB_DIV_55 + * @arg @ref DDL_RCM_PLLB_DIV_56 + * @arg @ref DDL_RCM_PLLB_DIV_57 + * @arg @ref DDL_RCM_PLLB_DIV_58 + * @arg @ref DDL_RCM_PLLB_DIV_59 + * @arg @ref DDL_RCM_PLLB_DIV_60 + * @arg @ref DDL_RCM_PLLB_DIV_61 + * @arg @ref DDL_RCM_PLLB_DIV_62 + * @arg @ref DDL_RCM_PLLB_DIV_63 + * @param PLL1A Between 50/192(*) and 432 + * + * (*) value not defined in all devices. + * @param PLLD This parameter can be one of the following values: + * @arg @ref DDL_RCM_PLLD_DIV_2 + * @arg @ref DDL_RCM_PLLD_DIV_3 + * @arg @ref DDL_RCM_PLLD_DIV_4 + * @arg @ref DDL_RCM_PLLD_DIV_5 + * @arg @ref DDL_RCM_PLLD_DIV_6 + * @arg @ref DDL_RCM_PLLD_DIV_7 + * @arg @ref DDL_RCM_PLLD_DIV_8 + * @arg @ref DDL_RCM_PLLD_DIV_9 + * @arg @ref DDL_RCM_PLLD_DIV_10 + * @arg @ref DDL_RCM_PLLD_DIV_11 + * @arg @ref DDL_RCM_PLLD_DIV_12 + * @arg @ref DDL_RCM_PLLD_DIV_13 + * @arg @ref DDL_RCM_PLLD_DIV_14 + * @arg @ref DDL_RCM_PLLD_DIV_15 + * @retval None + */ +__STATIC_INLINE void DDL_RCM_PLL_ConfigDomain_48M(uint32_t Source, uint32_t PLLB, uint32_t PLL1A, uint32_t PLLD) +{ + MODIFY_REG(RCM->PLL1CFG, RCM_PLL1CFG_PLL1CLKS | RCM_PLL1CFG_PLLB | RCM_PLL1CFG_PLL1A | RCM_PLL1CFG_PLLD, + Source | PLLB | PLL1A << RCM_PLL1CFG_PLL1A_Pos | PLLD); +} + +/** + * @brief Configure PLL clock source + * @param PLLSource This parameter can be one of the following values: + * @arg @ref DDL_RCM_PLLSOURCE_HSI + * @arg @ref DDL_RCM_PLLSOURCE_HSE + * @retval None + */ +__STATIC_INLINE void DDL_RCM_PLL_SetMainSource(uint32_t PLLSource) +{ + MODIFY_REG(RCM->PLL1CFG, RCM_PLL1CFG_PLL1CLKS, PLLSource); +} + +/** + * @brief Get the oscillator used as PLL clock source. + * @retval Returned value can be one of the following values: + * @arg @ref DDL_RCM_PLLSOURCE_HSI + * @arg @ref DDL_RCM_PLLSOURCE_HSE + */ +__STATIC_INLINE uint32_t DDL_RCM_PLL_GetMainSource(void) +{ + return (uint32_t)(READ_BIT(RCM->PLL1CFG, RCM_PLL1CFG_PLL1CLKS)); +} + +/** + * @brief Get Main PLL multiplication factor for VCO + * @retval Between 50/192(*) and 432 + * + * (*) value not defined in all devices. + */ +__STATIC_INLINE uint32_t DDL_RCM_PLL_GetN(void) +{ + return (uint32_t)(READ_BIT(RCM->PLL1CFG, RCM_PLL1CFG_PLL1A) >> RCM_PLL1CFG_PLL1A_Pos); +} + +/** + * @brief Get Main PLL division factor for PLL1C + * @retval Returned value can be one of the following values: + * @arg @ref DDL_RCM_PLL1C_DIV_2 + * @arg @ref DDL_RCM_PLL1C_DIV_4 + * @arg @ref DDL_RCM_PLL1C_DIV_6 + * @arg @ref DDL_RCM_PLL1C_DIV_8 + */ +__STATIC_INLINE uint32_t DDL_RCM_PLL_GetP(void) +{ + return (uint32_t)(READ_BIT(RCM->PLL1CFG, RCM_PLL1CFG_PLL1C)); +} + +/** + * @brief Get Main PLL division factor for PLLD + * @note used for PLL48MCLK selected for USB, RNG, SDIO (48 MHz clock) + * @retval Returned value can be one of the following values: + * @arg @ref DDL_RCM_PLLD_DIV_2 + * @arg @ref DDL_RCM_PLLD_DIV_3 + * @arg @ref DDL_RCM_PLLD_DIV_4 + * @arg @ref DDL_RCM_PLLD_DIV_5 + * @arg @ref DDL_RCM_PLLD_DIV_6 + * @arg @ref DDL_RCM_PLLD_DIV_7 + * @arg @ref DDL_RCM_PLLD_DIV_8 + * @arg @ref DDL_RCM_PLLD_DIV_9 + * @arg @ref DDL_RCM_PLLD_DIV_10 + * @arg @ref DDL_RCM_PLLD_DIV_11 + * @arg @ref DDL_RCM_PLLD_DIV_12 + * @arg @ref DDL_RCM_PLLD_DIV_13 + * @arg @ref DDL_RCM_PLLD_DIV_14 + * @arg @ref DDL_RCM_PLLD_DIV_15 + */ +__STATIC_INLINE uint32_t DDL_RCM_PLL_GetQ(void) +{ + return (uint32_t)(READ_BIT(RCM->PLL1CFG, RCM_PLL1CFG_PLLD)); +} + +/** + * @brief Get Division factor for the main PLL and other PLL + * @retval Returned value can be one of the following values: + * @arg @ref DDL_RCM_PLLB_DIV_2 + * @arg @ref DDL_RCM_PLLB_DIV_3 + * @arg @ref DDL_RCM_PLLB_DIV_4 + * @arg @ref DDL_RCM_PLLB_DIV_5 + * @arg @ref DDL_RCM_PLLB_DIV_6 + * @arg @ref DDL_RCM_PLLB_DIV_7 + * @arg @ref DDL_RCM_PLLB_DIV_8 + * @arg @ref DDL_RCM_PLLB_DIV_9 + * @arg @ref DDL_RCM_PLLB_DIV_10 + * @arg @ref DDL_RCM_PLLB_DIV_11 + * @arg @ref DDL_RCM_PLLB_DIV_12 + * @arg @ref DDL_RCM_PLLB_DIV_13 + * @arg @ref DDL_RCM_PLLB_DIV_14 + * @arg @ref DDL_RCM_PLLB_DIV_15 + * @arg @ref DDL_RCM_PLLB_DIV_16 + * @arg @ref DDL_RCM_PLLB_DIV_17 + * @arg @ref DDL_RCM_PLLB_DIV_18 + * @arg @ref DDL_RCM_PLLB_DIV_19 + * @arg @ref DDL_RCM_PLLB_DIV_20 + * @arg @ref DDL_RCM_PLLB_DIV_21 + * @arg @ref DDL_RCM_PLLB_DIV_22 + * @arg @ref DDL_RCM_PLLB_DIV_23 + * @arg @ref DDL_RCM_PLLB_DIV_24 + * @arg @ref DDL_RCM_PLLB_DIV_25 + * @arg @ref DDL_RCM_PLLB_DIV_26 + * @arg @ref DDL_RCM_PLLB_DIV_27 + * @arg @ref DDL_RCM_PLLB_DIV_28 + * @arg @ref DDL_RCM_PLLB_DIV_29 + * @arg @ref DDL_RCM_PLLB_DIV_30 + * @arg @ref DDL_RCM_PLLB_DIV_31 + * @arg @ref DDL_RCM_PLLB_DIV_32 + * @arg @ref DDL_RCM_PLLB_DIV_33 + * @arg @ref DDL_RCM_PLLB_DIV_34 + * @arg @ref DDL_RCM_PLLB_DIV_35 + * @arg @ref DDL_RCM_PLLB_DIV_36 + * @arg @ref DDL_RCM_PLLB_DIV_37 + * @arg @ref DDL_RCM_PLLB_DIV_38 + * @arg @ref DDL_RCM_PLLB_DIV_39 + * @arg @ref DDL_RCM_PLLB_DIV_40 + * @arg @ref DDL_RCM_PLLB_DIV_41 + * @arg @ref DDL_RCM_PLLB_DIV_42 + * @arg @ref DDL_RCM_PLLB_DIV_43 + * @arg @ref DDL_RCM_PLLB_DIV_44 + * @arg @ref DDL_RCM_PLLB_DIV_45 + * @arg @ref DDL_RCM_PLLB_DIV_46 + * @arg @ref DDL_RCM_PLLB_DIV_47 + * @arg @ref DDL_RCM_PLLB_DIV_48 + * @arg @ref DDL_RCM_PLLB_DIV_49 + * @arg @ref DDL_RCM_PLLB_DIV_50 + * @arg @ref DDL_RCM_PLLB_DIV_51 + * @arg @ref DDL_RCM_PLLB_DIV_52 + * @arg @ref DDL_RCM_PLLB_DIV_53 + * @arg @ref DDL_RCM_PLLB_DIV_54 + * @arg @ref DDL_RCM_PLLB_DIV_55 + * @arg @ref DDL_RCM_PLLB_DIV_56 + * @arg @ref DDL_RCM_PLLB_DIV_57 + * @arg @ref DDL_RCM_PLLB_DIV_58 + * @arg @ref DDL_RCM_PLLB_DIV_59 + * @arg @ref DDL_RCM_PLLB_DIV_60 + * @arg @ref DDL_RCM_PLLB_DIV_61 + * @arg @ref DDL_RCM_PLLB_DIV_62 + * @arg @ref DDL_RCM_PLLB_DIV_63 + */ +__STATIC_INLINE uint32_t DDL_RCM_PLL_GetDivider(void) +{ + return (uint32_t)(READ_BIT(RCM->PLL1CFG, RCM_PLL1CFG_PLLB)); +} + +/** + * @brief Configure Spread Spectrum used for PLL + * @note These bits must be written before enabling PLL + * @param Mod Between Min_Data=0 and Max_Data=8191 + * @param Inc Between Min_Data=0 and Max_Data=32767 + * @param Sel This parameter can be one of the following values: + * @arg @ref DDL_RCM_SPREAD_SELECT_CENTER + * @arg @ref DDL_RCM_SPREAD_SELECT_DOWN + * @retval None + */ +__STATIC_INLINE void DDL_RCM_PLL_ConfigSpreadSpectrum(uint32_t Mod, uint32_t Inc, uint32_t Sel) +{ + MODIFY_REG(RCM->SSCCFG, RCM_SSCCFG_MODPCFG | RCM_SSCCFG_STEP | RCM_SSCCFG_SSSEL, Mod | (Inc << RCM_SSCCFG_STEP_Pos) | Sel); +} + +/** + * @brief Get Spread Spectrum Modulation Period for PLL + * @retval Between Min_Data=0 and Max_Data=8191 + */ +__STATIC_INLINE uint32_t DDL_RCM_PLL_GetPeriodModulation(void) +{ + return (uint32_t)(READ_BIT(RCM->SSCCFG, RCM_SSCCFG_MODPCFG)); +} + +/** + * @brief Get Spread Spectrum Incrementation Step for PLL + * @note Must be written before enabling PLL + * @retval Between Min_Data=0 and Max_Data=32767 + */ +__STATIC_INLINE uint32_t DDL_RCM_PLL_GetStepIncrementation(void) +{ + return (uint32_t)(READ_BIT(RCM->SSCCFG, RCM_SSCCFG_STEP) >> RCM_SSCCFG_STEP_Pos); +} + +/** + * @brief Get Spread Spectrum Selection for PLL + * @note Must be written before enabling PLL + * @retval Returned value can be one of the following values: + * @arg @ref DDL_RCM_SPREAD_SELECT_CENTER + * @arg @ref DDL_RCM_SPREAD_SELECT_DOWN + */ +__STATIC_INLINE uint32_t DDL_RCM_PLL_GetSpreadSelection(void) +{ + return (uint32_t)(READ_BIT(RCM->SSCCFG, RCM_SSCCFG_SSSEL)); +} + +/** + * @brief Enable Spread Spectrum for PLL. + * @retval None + */ +__STATIC_INLINE void DDL_RCM_PLL_SpreadSpectrum_Enable(void) +{ + SET_BIT(RCM->SSCCFG, RCM_SSCCFG_SSEN); +} + +/** + * @brief Disable Spread Spectrum for PLL. + * @retval None + */ +__STATIC_INLINE void DDL_RCM_PLL_SpreadSpectrum_Disable(void) +{ + CLEAR_BIT(RCM->SSCCFG, RCM_SSCCFG_SSEN); +} + +/** + * @} + */ + +#if defined(RCM_PLLI2S_SUPPORT) +/** @defgroup RCM_DDL_EF_PLLI2S PLLI2S + * @{ + */ + +/** + * @brief Enable PLLI2S + * @retval None + */ +__STATIC_INLINE void DDL_RCM_PLLI2S_Enable(void) +{ + SET_BIT(RCM->CTRL, RCM_CTRL_PLL2EN); +} + +/** + * @brief Disable PLLI2S + * @retval None + */ +__STATIC_INLINE void DDL_RCM_PLLI2S_Disable(void) +{ + CLEAR_BIT(RCM->CTRL, RCM_CTRL_PLL2EN); +} + +/** + * @brief Check if PLLI2S Ready + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_RCM_PLLI2S_IsReady(void) +{ + return (READ_BIT(RCM->CTRL, RCM_CTRL_PLL2RDYFLG) == (RCM_CTRL_PLL2RDYFLG)); +} + +/** + * @brief Configure PLLI2S used for I2S1 domain clock + * @note PLL Source and PLLB Divider can be written only when PLL, + * PLLI2S and PLLSAI(*) are disabled + * @note PLL1A/PLLR can be written only when PLLI2S is disabled + * @note This can be selected for I2S + * @param Source This parameter can be one of the following values: + * @arg @ref DDL_RCM_PLLSOURCE_HSI + * @arg @ref DDL_RCM_PLLSOURCE_HSE + * @arg @ref DDL_RCM_PLLI2SSOURCE_PIN (*) + * + * (*) value not defined in all devices. + * @param PLLB This parameter can be one of the following values: + * @arg @ref DDL_RCM_PLL2B_DIV_2 + * @arg @ref DDL_RCM_PLL2B_DIV_3 + * @arg @ref DDL_RCM_PLL2B_DIV_4 + * @arg @ref DDL_RCM_PLL2B_DIV_5 + * @arg @ref DDL_RCM_PLL2B_DIV_6 + * @arg @ref DDL_RCM_PLL2B_DIV_7 + * @arg @ref DDL_RCM_PLL2B_DIV_8 + * @arg @ref DDL_RCM_PLL2B_DIV_9 + * @arg @ref DDL_RCM_PLL2B_DIV_10 + * @arg @ref DDL_RCM_PLL2B_DIV_11 + * @arg @ref DDL_RCM_PLL2B_DIV_12 + * @arg @ref DDL_RCM_PLL2B_DIV_13 + * @arg @ref DDL_RCM_PLL2B_DIV_14 + * @arg @ref DDL_RCM_PLL2B_DIV_15 + * @arg @ref DDL_RCM_PLL2B_DIV_16 + * @arg @ref DDL_RCM_PLL2B_DIV_17 + * @arg @ref DDL_RCM_PLL2B_DIV_18 + * @arg @ref DDL_RCM_PLL2B_DIV_19 + * @arg @ref DDL_RCM_PLL2B_DIV_20 + * @arg @ref DDL_RCM_PLL2B_DIV_21 + * @arg @ref DDL_RCM_PLL2B_DIV_22 + * @arg @ref DDL_RCM_PLL2B_DIV_23 + * @arg @ref DDL_RCM_PLL2B_DIV_24 + * @arg @ref DDL_RCM_PLL2B_DIV_25 + * @arg @ref DDL_RCM_PLL2B_DIV_26 + * @arg @ref DDL_RCM_PLL2B_DIV_27 + * @arg @ref DDL_RCM_PLL2B_DIV_28 + * @arg @ref DDL_RCM_PLL2B_DIV_29 + * @arg @ref DDL_RCM_PLL2B_DIV_30 + * @arg @ref DDL_RCM_PLL2B_DIV_31 + * @arg @ref DDL_RCM_PLL2B_DIV_32 + * @arg @ref DDL_RCM_PLL2B_DIV_33 + * @arg @ref DDL_RCM_PLL2B_DIV_34 + * @arg @ref DDL_RCM_PLL2B_DIV_35 + * @arg @ref DDL_RCM_PLL2B_DIV_36 + * @arg @ref DDL_RCM_PLL2B_DIV_37 + * @arg @ref DDL_RCM_PLL2B_DIV_38 + * @arg @ref DDL_RCM_PLL2B_DIV_39 + * @arg @ref DDL_RCM_PLL2B_DIV_40 + * @arg @ref DDL_RCM_PLL2B_DIV_41 + * @arg @ref DDL_RCM_PLL2B_DIV_42 + * @arg @ref DDL_RCM_PLL2B_DIV_43 + * @arg @ref DDL_RCM_PLL2B_DIV_44 + * @arg @ref DDL_RCM_PLL2B_DIV_45 + * @arg @ref DDL_RCM_PLL2B_DIV_46 + * @arg @ref DDL_RCM_PLL2B_DIV_47 + * @arg @ref DDL_RCM_PLL2B_DIV_48 + * @arg @ref DDL_RCM_PLL2B_DIV_49 + * @arg @ref DDL_RCM_PLL2B_DIV_50 + * @arg @ref DDL_RCM_PLL2B_DIV_51 + * @arg @ref DDL_RCM_PLL2B_DIV_52 + * @arg @ref DDL_RCM_PLL2B_DIV_53 + * @arg @ref DDL_RCM_PLL2B_DIV_54 + * @arg @ref DDL_RCM_PLL2B_DIV_55 + * @arg @ref DDL_RCM_PLL2B_DIV_56 + * @arg @ref DDL_RCM_PLL2B_DIV_57 + * @arg @ref DDL_RCM_PLL2B_DIV_58 + * @arg @ref DDL_RCM_PLL2B_DIV_59 + * @arg @ref DDL_RCM_PLL2B_DIV_60 + * @arg @ref DDL_RCM_PLL2B_DIV_61 + * @arg @ref DDL_RCM_PLL2B_DIV_62 + * @arg @ref DDL_RCM_PLL2B_DIV_63 + * @param PLL1A Between 50/192(*) and 432 + * + * (*) value not defined in all devices. + * @param PLLR This parameter can be one of the following values: + * @arg @ref DDL_RCM_PLL2C_DIV_2 + * @arg @ref DDL_RCM_PLL2C_DIV_3 + * @arg @ref DDL_RCM_PLL2C_DIV_4 + * @arg @ref DDL_RCM_PLL2C_DIV_5 + * @arg @ref DDL_RCM_PLL2C_DIV_6 + * @arg @ref DDL_RCM_PLL2C_DIV_7 + * @retval None + */ +__STATIC_INLINE void DDL_RCM_PLLI2S_ConfigDomain_I2S(uint32_t Source, uint32_t PLLB, uint32_t PLL1A, uint32_t PLLR) +{ + __IO uint32_t *pReg = (__IO uint32_t *)((uint32_t)((uint32_t)(&RCM->PLL1CFG) + (Source & 0x80U))); + MODIFY_REG(*pReg, RCM_PLL1CFG_PLL1CLKS, (Source & (~0x80U))); +#if defined(RCM_PLL2CFG_PLL2B) + MODIFY_REG(RCM->PLL2CFG, RCM_PLL2CFG_PLL2B, PLLB); +#else + MODIFY_REG(RCM->PLL1CFG, RCM_PLL1CFG_PLLB, PLLB); +#endif /* RCM_PLL2CFG_PLL2B */ + MODIFY_REG(RCM->PLL2CFG, RCM_PLL2CFG_PLL2A | RCM_PLL2CFG_PLL2C, PLL1A << RCM_PLL2CFG_PLL2A_Pos | PLLR); +} + +/** + * @brief Get I2SPLL multiplication factor for VCO + * @retval Between 50/192(*) and 432 + * + * (*) value not defined in all devices. + */ +__STATIC_INLINE uint32_t DDL_RCM_PLLI2S_GetN(void) +{ + return (uint32_t)(READ_BIT(RCM->PLL2CFG, RCM_PLL2CFG_PLL2A) >> RCM_PLL2CFG_PLL2A_Pos); +} + +/** + * @brief Get I2SPLL division factor for PLL2C + * @note used for PLLI2SCLK (I2S clock) + * @retval Returned value can be one of the following values: + * @arg @ref DDL_RCM_PLL2C_DIV_2 + * @arg @ref DDL_RCM_PLL2C_DIV_3 + * @arg @ref DDL_RCM_PLL2C_DIV_4 + * @arg @ref DDL_RCM_PLL2C_DIV_5 + * @arg @ref DDL_RCM_PLL2C_DIV_6 + * @arg @ref DDL_RCM_PLL2C_DIV_7 + */ +__STATIC_INLINE uint32_t DDL_RCM_PLLI2S_GetR(void) +{ + return (uint32_t)(READ_BIT(RCM->PLL2CFG, RCM_PLL2CFG_PLL2C)); +} + +/** + * @brief Get division factor for PLLI2S input clock + * @retval Returned value can be one of the following values: + * @arg @ref DDL_RCM_PLL2B_DIV_2 + * @arg @ref DDL_RCM_PLL2B_DIV_3 + * @arg @ref DDL_RCM_PLL2B_DIV_4 + * @arg @ref DDL_RCM_PLL2B_DIV_5 + * @arg @ref DDL_RCM_PLL2B_DIV_6 + * @arg @ref DDL_RCM_PLL2B_DIV_7 + * @arg @ref DDL_RCM_PLL2B_DIV_8 + * @arg @ref DDL_RCM_PLL2B_DIV_9 + * @arg @ref DDL_RCM_PLL2B_DIV_10 + * @arg @ref DDL_RCM_PLL2B_DIV_11 + * @arg @ref DDL_RCM_PLL2B_DIV_12 + * @arg @ref DDL_RCM_PLL2B_DIV_13 + * @arg @ref DDL_RCM_PLL2B_DIV_14 + * @arg @ref DDL_RCM_PLL2B_DIV_15 + * @arg @ref DDL_RCM_PLL2B_DIV_16 + * @arg @ref DDL_RCM_PLL2B_DIV_17 + * @arg @ref DDL_RCM_PLL2B_DIV_18 + * @arg @ref DDL_RCM_PLL2B_DIV_19 + * @arg @ref DDL_RCM_PLL2B_DIV_20 + * @arg @ref DDL_RCM_PLL2B_DIV_21 + * @arg @ref DDL_RCM_PLL2B_DIV_22 + * @arg @ref DDL_RCM_PLL2B_DIV_23 + * @arg @ref DDL_RCM_PLL2B_DIV_24 + * @arg @ref DDL_RCM_PLL2B_DIV_25 + * @arg @ref DDL_RCM_PLL2B_DIV_26 + * @arg @ref DDL_RCM_PLL2B_DIV_27 + * @arg @ref DDL_RCM_PLL2B_DIV_28 + * @arg @ref DDL_RCM_PLL2B_DIV_29 + * @arg @ref DDL_RCM_PLL2B_DIV_30 + * @arg @ref DDL_RCM_PLL2B_DIV_31 + * @arg @ref DDL_RCM_PLL2B_DIV_32 + * @arg @ref DDL_RCM_PLL2B_DIV_33 + * @arg @ref DDL_RCM_PLL2B_DIV_34 + * @arg @ref DDL_RCM_PLL2B_DIV_35 + * @arg @ref DDL_RCM_PLL2B_DIV_36 + * @arg @ref DDL_RCM_PLL2B_DIV_37 + * @arg @ref DDL_RCM_PLL2B_DIV_38 + * @arg @ref DDL_RCM_PLL2B_DIV_39 + * @arg @ref DDL_RCM_PLL2B_DIV_40 + * @arg @ref DDL_RCM_PLL2B_DIV_41 + * @arg @ref DDL_RCM_PLL2B_DIV_42 + * @arg @ref DDL_RCM_PLL2B_DIV_43 + * @arg @ref DDL_RCM_PLL2B_DIV_44 + * @arg @ref DDL_RCM_PLL2B_DIV_45 + * @arg @ref DDL_RCM_PLL2B_DIV_46 + * @arg @ref DDL_RCM_PLL2B_DIV_47 + * @arg @ref DDL_RCM_PLL2B_DIV_48 + * @arg @ref DDL_RCM_PLL2B_DIV_49 + * @arg @ref DDL_RCM_PLL2B_DIV_50 + * @arg @ref DDL_RCM_PLL2B_DIV_51 + * @arg @ref DDL_RCM_PLL2B_DIV_52 + * @arg @ref DDL_RCM_PLL2B_DIV_53 + * @arg @ref DDL_RCM_PLL2B_DIV_54 + * @arg @ref DDL_RCM_PLL2B_DIV_55 + * @arg @ref DDL_RCM_PLL2B_DIV_56 + * @arg @ref DDL_RCM_PLL2B_DIV_57 + * @arg @ref DDL_RCM_PLL2B_DIV_58 + * @arg @ref DDL_RCM_PLL2B_DIV_59 + * @arg @ref DDL_RCM_PLL2B_DIV_60 + * @arg @ref DDL_RCM_PLL2B_DIV_61 + * @arg @ref DDL_RCM_PLL2B_DIV_62 + * @arg @ref DDL_RCM_PLL2B_DIV_63 + */ +__STATIC_INLINE uint32_t DDL_RCM_PLLI2S_GetDivider(void) +{ +#if defined(RCM_PLL2CFG_PLL2B) + return (uint32_t)(READ_BIT(RCM->PLL2CFG, RCM_PLL2CFG_PLL2B)); +#else + return (uint32_t)(READ_BIT(RCM->PLL1CFG, RCM_PLL1CFG_PLLB)); +#endif /* RCM_PLL2CFG_PLL2B */ +} + +/** + * @brief Get the oscillator used as PLL clock source. + * @retval Returned value can be one of the following values: + * @arg @ref DDL_RCM_PLLSOURCE_HSI + * @arg @ref DDL_RCM_PLLSOURCE_HSE + * @arg @ref DDL_RCM_PLLI2SSOURCE_PIN (*) + * + * (*) value not defined in all devices. + */ +__STATIC_INLINE uint32_t DDL_RCM_PLLI2S_GetMainSource(void) +{ +#if defined(RCM_PLL2CFG_PLLI2SSRC) + uint32_t pllsrc = READ_BIT(RCM->PLL1CFG, RCM_PLL1CFG_PLL1CLKS); + uint32_t plli2sssrc0 = READ_BIT(RCM->PLL2CFG, RCM_PLL2CFG_PLLI2SSRC); + uint32_t plli2sssrc1 = READ_BIT(RCM->PLL2CFG, RCM_PLL2CFG_PLLI2SSRC) >> 15U; + return (uint32_t)(pllsrc | plli2sssrc0 | plli2sssrc1); +#else + return (uint32_t)(READ_BIT(RCM->PLL1CFG, RCM_PLL1CFG_PLL1CLKS)); +#endif /* RCM_PLL2CFG_PLLI2SSRC */ +} + +/** + * @} + */ +#endif /* RCM_PLLI2S_SUPPORT */ + +/** @defgroup RCM_DDL_EF_FLAG_Management FLAG Management + * @{ + */ + +/** + * @brief Clear LSI ready interrupt flag + * @retval None + */ +__STATIC_INLINE void DDL_RCM_ClearFlag_LSIRDY(void) +{ + SET_BIT(RCM->INT, RCM_INT_LSIRDYCLR); +} + +/** + * @brief Clear LSE ready interrupt flag + * @retval None + */ +__STATIC_INLINE void DDL_RCM_ClearFlag_LSERDY(void) +{ + SET_BIT(RCM->INT, RCM_INT_LSERDYCLR); +} + +/** + * @brief Clear HSI ready interrupt flag + * @retval None + */ +__STATIC_INLINE void DDL_RCM_ClearFlag_HSIRDY(void) +{ + SET_BIT(RCM->INT, RCM_INT_HSIRDYCLR); +} + +/** + * @brief Clear HSE ready interrupt flag + * @retval None + */ +__STATIC_INLINE void DDL_RCM_ClearFlag_HSERDY(void) +{ + SET_BIT(RCM->INT, RCM_INT_HSERDYCLR); +} + +/** + * @brief Clear PLL ready interrupt flag + * @retval None + */ +__STATIC_INLINE void DDL_RCM_ClearFlag_PLLRDY(void) +{ + SET_BIT(RCM->INT, RCM_INT_PLL1RDYCLR); +} + +#if defined(RCM_PLLI2S_SUPPORT) +/** + * @brief Clear PLLI2S ready interrupt flag + * @retval None + */ +__STATIC_INLINE void DDL_RCM_ClearFlag_PLL2RDY(void) +{ + SET_BIT(RCM->INT, RCM_INT_PLL2RDYCLR); +} + +#endif /* RCM_PLLI2S_SUPPORT */ + +/** + * @brief Clear Clock security system interrupt flag + * @retval None + */ +__STATIC_INLINE void DDL_RCM_ClearFlag_HSECSS(void) +{ + SET_BIT(RCM->INT, RCM_INT_CSSCLR); +} + +/** + * @brief Check if LSI ready interrupt occurred or not + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_RCM_IsActiveFlag_LSIRDY(void) +{ + return (READ_BIT(RCM->INT, RCM_INT_LSIRDYFLG) == (RCM_INT_LSIRDYFLG)); +} + +/** + * @brief Check if LSE ready interrupt occurred or not + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_RCM_IsActiveFlag_LSERDY(void) +{ + return (READ_BIT(RCM->INT, RCM_INT_LSERDYFLG) == (RCM_INT_LSERDYFLG)); +} + +/** + * @brief Check if HSI ready interrupt occurred or not + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_RCM_IsActiveFlag_HSIRDY(void) +{ + return (READ_BIT(RCM->INT, RCM_INT_HSIRDYFLG) == (RCM_INT_HSIRDYFLG)); +} + +/** + * @brief Check if HSE ready interrupt occurred or not + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_RCM_IsActiveFlag_HSERDY(void) +{ + return (READ_BIT(RCM->INT, RCM_INT_HSERDYFLG) == (RCM_INT_HSERDYFLG)); +} + +/** + * @brief Check if PLL ready interrupt occurred or not + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_RCM_IsActiveFlag_PLLRDY(void) +{ + return (READ_BIT(RCM->INT, RCM_INT_PLL1RDYFLG) == (RCM_INT_PLL1RDYFLG)); +} + +#if defined(RCM_PLLI2S_SUPPORT) +/** + * @brief Check if PLLI2S ready interrupt occurred or not + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_RCM_IsActiveFlag_PLL2RDY(void) +{ + return (READ_BIT(RCM->INT, RCM_INT_PLL2RDYFLG) == (RCM_INT_PLL2RDYFLG)); +} +#endif /* RCM_PLLI2S_SUPPORT */ + +/** + * @brief Check if Clock security system interrupt occurred or not + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_RCM_IsActiveFlag_HSECSS(void) +{ + return (READ_BIT(RCM->INT, RCM_INT_CSSFLG) == (RCM_INT_CSSFLG)); +} + +/** + * @brief Check if RCM flag Independent Watchdog reset is set or not. + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_RCM_IsActiveFlag_IWDTRST(void) +{ + return (READ_BIT(RCM->CSTS, RCM_CSTS_IWDTRSTFLG) == (RCM_CSTS_IWDTRSTFLG)); +} + +/** + * @brief Check if RCM flag Low Power reset is set or not. + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_RCM_IsActiveFlag_LPWRRST(void) +{ + return (READ_BIT(RCM->CSTS, RCM_CSTS_LPWRRSTFLG) == (RCM_CSTS_LPWRRSTFLG)); +} + +/** + * @brief Check if RCM flag Pin reset is set or not. + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_RCM_IsActiveFlag_PINRST(void) +{ + return (READ_BIT(RCM->CSTS, RCM_CSTS_PINRSTFLG) == (RCM_CSTS_PINRSTFLG)); +} + +/** + * @brief Check if RCM flag POR/PDR reset is set or not. + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_RCM_IsActiveFlag_PORRST(void) +{ + return (READ_BIT(RCM->CSTS, RCM_CSTS_PODRSTFLG) == (RCM_CSTS_PODRSTFLG)); +} + +/** + * @brief Check if RCM flag Software reset is set or not. + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_RCM_IsActiveFlag_SFTRST(void) +{ + return (READ_BIT(RCM->CSTS, RCM_CSTS_SWRSTFLG) == (RCM_CSTS_SWRSTFLG)); +} + +/** + * @brief Check if RCM flag Window Watchdog reset is set or not. + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_RCM_IsActiveFlag_WWDTRST(void) +{ + return (READ_BIT(RCM->CSTS, RCM_CSTS_WWDTRSTFLG) == (RCM_CSTS_WWDTRSTFLG)); +} + +#if defined(RCM_CSTS_BORRSTFLG) +/** + * @brief Check if RCM flag BOR reset is set or not. + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_RCM_IsActiveFlag_BORRST(void) +{ + return (READ_BIT(RCM->CSTS, RCM_CSTS_BORRSTFLG) == (RCM_CSTS_BORRSTFLG)); +} +#endif /* RCM_CSTS_BORRSTFLG */ + +/** + * @brief Set RMVF bit to clear the reset flags. + * @retval None + */ +__STATIC_INLINE void DDL_RCM_ClearResetFlags(void) +{ + SET_BIT(RCM->CSTS, RCM_CSTS_RSTFLGCLR); +} + +/** + * @} + */ + +/** @defgroup RCM_DDL_EF_IT_Management IT Management + * @{ + */ + +/** + * @brief Enable LSI ready interrupt + * @retval None + */ +__STATIC_INLINE void DDL_RCM_EnableIT_LSIRDY(void) +{ + SET_BIT(RCM->INT, RCM_INT_LSIRDYEN); +} + +/** + * @brief Enable LSE ready interrupt + * @retval None + */ +__STATIC_INLINE void DDL_RCM_EnableIT_LSERDY(void) +{ + SET_BIT(RCM->INT, RCM_INT_LSERDYEN); +} + +/** + * @brief Enable HSI ready interrupt + * @retval None + */ +__STATIC_INLINE void DDL_RCM_EnableIT_HSIRDY(void) +{ + SET_BIT(RCM->INT, RCM_INT_HSIRDYEN); +} + +/** + * @brief Enable HSE ready interrupt + * @retval None + */ +__STATIC_INLINE void DDL_RCM_EnableIT_HSERDY(void) +{ + SET_BIT(RCM->INT, RCM_INT_HSERDYEN); +} + +/** + * @brief Enable PLL ready interrupt + * @retval None + */ +__STATIC_INLINE void DDL_RCM_EnableIT_PLLRDY(void) +{ + SET_BIT(RCM->INT, RCM_INT_PLL1RDYEN); +} + +#if defined(RCM_PLLI2S_SUPPORT) +/** + * @brief Enable PLLI2S ready interrupt + * @retval None + */ +__STATIC_INLINE void DDL_RCM_EnableIT_PLL2RDY(void) +{ + SET_BIT(RCM->INT, RCM_INT_PLL2RDYEN); +} +#endif /* RCM_PLLI2S_SUPPORT */ + +/** + * @brief Disable LSI ready interrupt + * @retval None + */ +__STATIC_INLINE void DDL_RCM_DisableIT_LSIRDY(void) +{ + CLEAR_BIT(RCM->INT, RCM_INT_LSIRDYEN); +} + +/** + * @brief Disable LSE ready interrupt + * @retval None + */ +__STATIC_INLINE void DDL_RCM_DisableIT_LSERDY(void) +{ + CLEAR_BIT(RCM->INT, RCM_INT_LSERDYEN); +} + +/** + * @brief Disable HSI ready interrupt + * @retval None + */ +__STATIC_INLINE void DDL_RCM_DisableIT_HSIRDY(void) +{ + CLEAR_BIT(RCM->INT, RCM_INT_HSIRDYEN); +} + +/** + * @brief Disable HSE ready interrupt + * @retval None + */ +__STATIC_INLINE void DDL_RCM_DisableIT_HSERDY(void) +{ + CLEAR_BIT(RCM->INT, RCM_INT_HSERDYEN); +} + +/** + * @brief Disable PLL ready interrupt + * @retval None + */ +__STATIC_INLINE void DDL_RCM_DisableIT_PLLRDY(void) +{ + CLEAR_BIT(RCM->INT, RCM_INT_PLL1RDYEN); +} + +#if defined(RCM_PLLI2S_SUPPORT) +/** + * @brief Disable PLLI2S ready interrupt + * @retval None + */ +__STATIC_INLINE void DDL_RCM_DisableIT_PLL2RDY(void) +{ + CLEAR_BIT(RCM->INT, RCM_INT_PLL2RDYEN); +} + +#endif /* RCM_PLLI2S_SUPPORT */ + +/** + * @brief Checks if LSI ready interrupt source is enabled or disabled. + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_RCM_IsEnabledIT_LSIRDY(void) +{ + return (READ_BIT(RCM->INT, RCM_INT_LSIRDYEN) == (RCM_INT_LSIRDYEN)); +} + +/** + * @brief Checks if LSE ready interrupt source is enabled or disabled. + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_RCM_IsEnabledIT_LSERDY(void) +{ + return (READ_BIT(RCM->INT, RCM_INT_LSERDYEN) == (RCM_INT_LSERDYEN)); +} + +/** + * @brief Checks if HSI ready interrupt source is enabled or disabled. + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_RCM_IsEnabledIT_HSIRDY(void) +{ + return (READ_BIT(RCM->INT, RCM_INT_HSIRDYEN) == (RCM_INT_HSIRDYEN)); +} + +/** + * @brief Checks if HSE ready interrupt source is enabled or disabled. + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_RCM_IsEnabledIT_HSERDY(void) +{ + return (READ_BIT(RCM->INT, RCM_INT_HSERDYEN) == (RCM_INT_HSERDYEN)); +} + +/** + * @brief Checks if PLL ready interrupt source is enabled or disabled. + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_RCM_IsEnabledIT_PLLRDY(void) +{ + return (READ_BIT(RCM->INT, RCM_INT_PLL1RDYEN) == (RCM_INT_PLL1RDYEN)); +} + +#if defined(RCM_PLLI2S_SUPPORT) +/** + * @brief Checks if PLLI2S ready interrupt source is enabled or disabled. + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_RCM_IsEnabledIT_PLL2RDY(void) +{ + return (READ_BIT(RCM->INT, RCM_INT_PLL2RDYEN) == (RCM_INT_PLL2RDYEN)); +} + +#endif /* RCM_PLLI2S_SUPPORT */ + +/** + * @} + */ + +#if defined(USE_FULL_DDL_DRIVER) +/** @defgroup RCM_DDL_EF_Init De-initialization function + * @{ + */ +ErrorStatus DDL_RCM_DeInit(void); +/** + * @} + */ + +/** @defgroup RCM_DDL_EF_Get_Freq Get system and peripherals clocks frequency functions + * @{ + */ +void DDL_RCM_GetSystemClocksFreq(DDL_RCM_ClocksTypeDef *RCM_Clocks); +#if defined(SDIO) +uint32_t DDL_RCM_GetSDIOClockFreq(uint32_t SDIOxSource); +#endif /* SDIO */ +#if defined(RNG) +uint32_t DDL_RCM_GetRNGClockFreq(uint32_t RNGxSource); +#endif /* RNG */ +#if defined(USB_OTG_FS) || defined(USB_OTG_HS) +uint32_t DDL_RCM_GetUSBClockFreq(uint32_t USBxSource); +#endif /* USB_OTG_FS || USB_OTG_HS */ +uint32_t DDL_RCM_GetI2SClockFreq(uint32_t I2SxSource); +/** + * @} + */ +#endif /* USE_FULL_DDL_DRIVER */ + +/** + * @} + */ + +/** + * @} + */ + +#endif /* defined(RCM) */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* APM32F4xx_DDL_RCM_H */ + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_rng.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_rng.h new file mode 100644 index 0000000000..2c5dd35997 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_rng.h @@ -0,0 +1,345 @@ +/** + * + * @file apm32f4xx_ddl_rng.h + * @brief Header file of RNG DDL module. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef APM32F4xx_DDL_RNG_H +#define APM32F4xx_DDL_RNG_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx.h" + +/** @addtogroup APM32F4xx_DDL_Driver + * @{ + */ + +#if defined (RNG) + +/** @defgroup RNG_DDL RNG + * @{ + */ + +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/* Private macros ------------------------------------------------------------*/ + +/* Exported types ------------------------------------------------------------*/ +/* Exported constants --------------------------------------------------------*/ +/** @defgroup RNG_DDL_Exported_Constants RNG Exported Constants + * @{ + */ + + +/** @defgroup RNG_DDL_EC_GET_FLAG Get Flags Defines + * @brief Flags defines which can be used with DDL_RNG_ReadReg function + * @{ + */ +#define DDL_RNG_STS_DATARDY RNG_STS_DATARDY /*!< Register contains valid random data */ +#define DDL_RNG_STS_CLKERCSTS RNG_STS_CLKERCSTS /*!< Clock error current status */ +#define DDL_RNG_STS_FSCSTS RNG_STS_FSCSTS /*!< Seed error current status */ +#define DDL_RNG_STS_CLKERINT RNG_STS_CLKERINT /*!< Clock error interrupt status */ +#define DDL_RNG_STS_FSINT RNG_STS_FSINT /*!< Seed error interrupt status */ +/** + * @} + */ + +/** @defgroup RNG_DDL_EC_IT IT Defines + * @brief IT defines which can be used with DDL_RNG_ReadReg and DDL_RNG_WriteReg macros + * @{ + */ +#define DDL_RNG_CTRL_INTEN RNG_CTRL_INTEN /*!< RNG Interrupt enable */ +/** + * @} + */ + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ +/** @defgroup RNG_DDL_Exported_Macros RNG Exported Macros + * @{ + */ + +/** @defgroup RNG_DDL_EM_WRITE_READ Common Write and read registers Macros + * @{ + */ + +/** + * @brief Write a value in RNG register + * @param __INSTANCE__ RNG Instance + * @param __REG__ Register to be written + * @param __VALUE__ Value to be written in the register + * @retval None + */ +#define DDL_RNG_WriteReg(__INSTANCE__, __REG__, __VALUE__) WRITE_REG(__INSTANCE__->__REG__, (__VALUE__)) + +/** + * @brief Read a value in RNG register + * @param __INSTANCE__ RNG Instance + * @param __REG__ Register to be read + * @retval Register value + */ +#define DDL_RNG_ReadReg(__INSTANCE__, __REG__) READ_REG(__INSTANCE__->__REG__) +/** + * @} + */ + +/** + * @} + */ + + +/* Exported functions --------------------------------------------------------*/ +/** @defgroup RNG_DDL_Exported_Functions RNG Exported Functions + * @{ + */ +/** @defgroup RNG_DDL_EF_Configuration RNG Configuration functions + * @{ + */ + +/** + * @brief Enable Random Number Generation + * @param RNGx RNG Instance + * @retval None + */ +__STATIC_INLINE void DDL_RNG_Enable(RNG_TypeDef *RNGx) +{ + SET_BIT(RNGx->CTRL, RNG_CTRL_RNGEN); +} + +/** + * @brief Disable Random Number Generation + * @param RNGx RNG Instance + * @retval None + */ +__STATIC_INLINE void DDL_RNG_Disable(RNG_TypeDef *RNGx) +{ + CLEAR_BIT(RNGx->CTRL, RNG_CTRL_RNGEN); +} + +/** + * @brief Check if Random Number Generator is enabled + * @param RNGx RNG Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_RNG_IsEnabled(RNG_TypeDef *RNGx) +{ + return ((READ_BIT(RNGx->CTRL, RNG_CTRL_RNGEN) == (RNG_CTRL_RNGEN)) ? 1UL : 0UL); +} + +/** + * @} + */ + +/** @defgroup RNG_DDL_EF_FLAG_Management FLAG Management + * @{ + */ + +/** + * @brief Indicate if the RNG Data ready Flag is set or not + * @param RNGx RNG Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_RNG_IsActiveFlag_DRDY(RNG_TypeDef *RNGx) +{ + return ((READ_BIT(RNGx->STS, RNG_STS_DATARDY) == (RNG_STS_DATARDY)) ? 1UL : 0UL); +} + +/** + * @brief Indicate if the Clock Error Current Status Flag is set or not + * @param RNGx RNG Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_RNG_IsActiveFlag_CECS(RNG_TypeDef *RNGx) +{ + return ((READ_BIT(RNGx->STS, RNG_STS_CLKERCSTS) == (RNG_STS_CLKERCSTS)) ? 1UL : 0UL); +} + +/** + * @brief Indicate if the Seed Error Current Status Flag is set or not + * @param RNGx RNG Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_RNG_IsActiveFlag_SECS(RNG_TypeDef *RNGx) +{ + return ((READ_BIT(RNGx->STS, RNG_STS_FSCSTS) == (RNG_STS_FSCSTS)) ? 1UL : 0UL); +} + +/** + * @brief Indicate if the Clock Error Interrupt Status Flag is set or not + * @param RNGx RNG Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_RNG_IsActiveFlag_CEIS(RNG_TypeDef *RNGx) +{ + return ((READ_BIT(RNGx->STS, RNG_STS_CLKERINT) == (RNG_STS_CLKERINT)) ? 1UL : 0UL); +} + +/** + * @brief Indicate if the Seed Error Interrupt Status Flag is set or not + * @param RNGx RNG Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_RNG_IsActiveFlag_SEIS(RNG_TypeDef *RNGx) +{ + return ((READ_BIT(RNGx->STS, RNG_STS_FSINT) == (RNG_STS_FSINT)) ? 1UL : 0UL); +} + +/** + * @brief Clear Clock Error interrupt Status (CEIS) Flag + * @param RNGx RNG Instance + * @retval None + */ +__STATIC_INLINE void DDL_RNG_ClearFlag_CEIS(RNG_TypeDef *RNGx) +{ + WRITE_REG(RNGx->STS, ~RNG_STS_CLKERINT); +} + +/** + * @brief Clear Seed Error interrupt Status (SEIS) Flag + * @param RNGx RNG Instance + * @retval None + */ +__STATIC_INLINE void DDL_RNG_ClearFlag_SEIS(RNG_TypeDef *RNGx) +{ + WRITE_REG(RNGx->STS, ~RNG_STS_FSINT); +} + +/** + * @} + */ + +/** @defgroup RNG_DDL_EF_IT_Management IT Management + * @{ + */ + +/** + * @brief Enable Random Number Generator Interrupt + * (applies for either Seed error, Clock Error or Data ready interrupts) + * @param RNGx RNG Instance + * @retval None + */ +__STATIC_INLINE void DDL_RNG_EnableIT(RNG_TypeDef *RNGx) +{ + SET_BIT(RNGx->CTRL, RNG_CTRL_INTEN); +} + +/** + * @brief Disable Random Number Generator Interrupt + * (applies for either Seed error, Clock Error or Data ready interrupts) + * @param RNGx RNG Instance + * @retval None + */ +__STATIC_INLINE void DDL_RNG_DisableIT(RNG_TypeDef *RNGx) +{ + CLEAR_BIT(RNGx->CTRL, RNG_CTRL_INTEN); +} + +/** + * @brief Check if Random Number Generator Interrupt is enabled + * (applies for either Seed error, Clock Error or Data ready interrupts) + * @param RNGx RNG Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_RNG_IsEnabledIT(RNG_TypeDef *RNGx) +{ + return ((READ_BIT(RNGx->CTRL, RNG_CTRL_INTEN) == (RNG_CTRL_INTEN)) ? 1UL : 0UL); +} + +/** + * @} + */ + +/** @defgroup RNG_DDL_EF_Data_Management Data Management + * @{ + */ + +/** + * @brief Return32-bit Random Number value + * @param RNGx RNG Instance + * @retval Generated 32-bit random value + */ +__STATIC_INLINE uint32_t DDL_RNG_ReadRandData32(RNG_TypeDef *RNGx) +{ + return (uint32_t)(READ_REG(RNGx->DATA)); +} + +/** + * @} + */ + +#if defined(USE_FULL_DDL_DRIVER) +/** @defgroup RNG_DDL_EF_Init Initialization and de-initialization functions + * @{ + */ +ErrorStatus DDL_RNG_DeInit(RNG_TypeDef *RNGx); + +/** + * @} + */ +#endif /* USE_FULL_DDL_DRIVER */ + +/** + * @} + */ + +/** + * @} + */ + +#endif /* RNG */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __APM32F4xx_DDL_RNG_H */ + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_rtc.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_rtc.h new file mode 100644 index 0000000000..7f520995ff --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_rtc.h @@ -0,0 +1,3390 @@ +/** + * + * @file apm32f4xx_ddl_rtc.h + * @brief Header file of RTC DDL module. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2017 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef APM32F4xx_DDL_RTC_H +#define APM32F4xx_DDL_RTC_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx.h" + +/** @addtogroup APM32F4xx_DDL_Driver + * @{ + */ + +#if defined(RTC) + +/** @defgroup RTC_DDL RTC + * @{ + */ + +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/** @defgroup RTC_DDL_Private_Constants RTC Private Constants + * @{ + */ +/* Masks Definition */ +#define RTC_INIT_MASK 0xFFFFFFFFU +#define RTC_RSF_MASK ((uint32_t)~(RTC_STS_INITEN | RTC_STS_RSFLG)) + +/* Write protection defines */ +#define RTC_WRITE_PROTECTION_DISABLE ((uint8_t)0xFFU) +#define RTC_WRITE_PROTECTION_ENABLE_1 ((uint8_t)0xCAU) +#define RTC_WRITE_PROTECTION_ENABLE_2 ((uint8_t)0x53U) + +/* Defines used to combine date & time */ +#define RTC_OFFSET_WEEKDAY 24U +#define RTC_OFFSET_DAY 16U +#define RTC_OFFSET_MONTH 8U +#define RTC_OFFSET_HOUR 16U +#define RTC_OFFSET_MINUTE 8U + +/** + * @} + */ + +/* Private macros ------------------------------------------------------------*/ +#if defined(USE_FULL_DDL_DRIVER) +/** @defgroup RTC_DDL_Private_Macros RTC Private Macros + * @{ + */ +/** + * @} + */ +#endif /*USE_FULL_DDL_DRIVER*/ + +/* Exported types ------------------------------------------------------------*/ +#if defined(USE_FULL_DDL_DRIVER) +/** @defgroup RTC_DDL_ES_INIT RTC Exported Init structure + * @{ + */ + +/** + * @brief RTC Init structures definition + */ +typedef struct +{ + uint32_t HourFormat; /*!< Specifies the RTC Hours Format. + This parameter can be a value of @ref RTC_DDL_EC_HOURFORMAT + + This feature can be modified afterwards using unitary function + @ref DDL_RTC_SetHourFormat(). */ + + uint32_t AsynchPrescaler; /*!< Specifies the RTC Asynchronous Predivider value. + This parameter must be a number between Min_Data = 0x00 and Max_Data = 0x7F + + This feature can be modified afterwards using unitary function + @ref DDL_RTC_SetAsynchPrescaler(). */ + + uint32_t SynchPrescaler; /*!< Specifies the RTC Synchronous Predivider value. + This parameter must be a number between Min_Data = 0x00 and Max_Data = 0x7FFF + + This feature can be modified afterwards using unitary function + @ref DDL_RTC_SetSynchPrescaler(). */ +} DDL_RTC_InitTypeDef; + +/** + * @brief RTC Time structure definition + */ +typedef struct +{ + uint32_t TimeFormat; /*!< Specifies the RTC AM/PM Time. + This parameter can be a value of @ref RTC_DDL_EC_TIME_FORMAT + + This feature can be modified afterwards using unitary function @ref DDL_RTC_TIME_SetFormat(). */ + + uint8_t Hours; /*!< Specifies the RTC Time Hours. + This parameter must be a number between Min_Data = 0 and Max_Data = 12 if the @ref DDL_RTC_TIME_FORMAT_PM is selected. + This parameter must be a number between Min_Data = 0 and Max_Data = 23 if the @ref DDL_RTC_TIME_FORMAT_AM_OR_24 is selected. + + This feature can be modified afterwards using unitary function @ref DDL_RTC_TIME_SetHour(). */ + + uint8_t Minutes; /*!< Specifies the RTC Time Minutes. + This parameter must be a number between Min_Data = 0 and Max_Data = 59 + + This feature can be modified afterwards using unitary function @ref DDL_RTC_TIME_SetMinute(). */ + + uint8_t Seconds; /*!< Specifies the RTC Time Seconds. + This parameter must be a number between Min_Data = 0 and Max_Data = 59 + + This feature can be modified afterwards using unitary function @ref DDL_RTC_TIME_SetSecond(). */ +} DDL_RTC_TimeTypeDef; + +/** + * @brief RTC Date structure definition + */ +typedef struct +{ + uint8_t WeekDay; /*!< Specifies the RTC Date WeekDay. + This parameter can be a value of @ref RTC_DDL_EC_WEEKDAY + + This feature can be modified afterwards using unitary function @ref DDL_RTC_DATE_SetWeekDay(). */ + + uint8_t Month; /*!< Specifies the RTC Date Month. + This parameter can be a value of @ref RTC_DDL_EC_MONTH + + This feature can be modified afterwards using unitary function @ref DDL_RTC_DATE_SetMonth(). */ + + uint8_t Day; /*!< Specifies the RTC Date Day. + This parameter must be a number between Min_Data = 1 and Max_Data = 31 + + This feature can be modified afterwards using unitary function @ref DDL_RTC_DATE_SetDay(). */ + + uint8_t Year; /*!< Specifies the RTC Date Year. + This parameter must be a number between Min_Data = 0 and Max_Data = 99 + + This feature can be modified afterwards using unitary function @ref DDL_RTC_DATE_SetYear(). */ +} DDL_RTC_DateTypeDef; + +/** + * @brief RTC Alarm structure definition + */ +typedef struct +{ + DDL_RTC_TimeTypeDef AlarmTime; /*!< Specifies the RTC Alarm Time members. */ + + uint32_t AlarmMask; /*!< Specifies the RTC Alarm Masks. + This parameter can be a value of @ref RTC_DDL_EC_ALMA_MASK for ALARM A or @ref RTC_DDL_EC_ALMB_MASK for ALARM B. + + This feature can be modified afterwards using unitary function @ref DDL_RTC_ALMA_SetMask() for ALARM A + or @ref DDL_RTC_ALMB_SetMask() for ALARM B. + */ + + uint32_t AlarmDateWeekDaySel; /*!< Specifies the RTC Alarm is on day or WeekDay. + This parameter can be a value of @ref RTC_DDL_EC_ALMA_WEEKDAY_SELECTION for ALARM A or @ref RTC_DDL_EC_ALMB_WEEKDAY_SELECTION for ALARM B + + This feature can be modified afterwards using unitary function @ref DDL_RTC_ALMA_EnableWeekday() or @ref DDL_RTC_ALMA_DisableWeekday() + for ALARM A or @ref DDL_RTC_ALMB_EnableWeekday() or @ref DDL_RTC_ALMB_DisableWeekday() for ALARM B + */ + + uint8_t AlarmDateWeekDay; /*!< Specifies the RTC Alarm Day/WeekDay. + If AlarmDateWeekDaySel set to day, this parameter must be a number between Min_Data = 1 and Max_Data = 31. + + This feature can be modified afterwards using unitary function @ref DDL_RTC_ALMA_SetDay() + for ALARM A or @ref DDL_RTC_ALMB_SetDay() for ALARM B. + + If AlarmDateWeekDaySel set to Weekday, this parameter can be a value of @ref RTC_DDL_EC_WEEKDAY. + + This feature can be modified afterwards using unitary function @ref DDL_RTC_ALMA_SetWeekDay() + for ALARM A or @ref DDL_RTC_ALMB_SetWeekDay() for ALARM B. + */ +} DDL_RTC_AlarmTypeDef; + +/** + * @} + */ +#endif /* USE_FULL_DDL_DRIVER */ + +/* Exported constants --------------------------------------------------------*/ +/** @defgroup RTC_DDL_Exported_Constants RTC Exported Constants + * @{ + */ + +#if defined(USE_FULL_DDL_DRIVER) +/** @defgroup RTC_DDL_EC_FORMAT FORMAT + * @{ + */ +#define DDL_RTC_FORMAT_BIN 0x00000000U /*!< Binary data format */ +#define DDL_RTC_FORMAT_BCD 0x00000001U /*!< BCD data format */ +/** + * @} + */ + +/** @defgroup RTC_DDL_EC_ALMA_WEEKDAY_SELECTION RTC Alarm A Date WeekDay + * @{ + */ +#define DDL_RTC_ALMA_DATEWEEKDAYSEL_DATE 0x00000000U /*!< Alarm A Date is selected */ +#define DDL_RTC_ALMA_DATEWEEKDAYSEL_WEEKDAY RTC_ALRMA_WEEKSEL /*!< Alarm A WeekDay is selected */ +/** + * @} + */ + +/** @defgroup RTC_DDL_EC_ALMB_WEEKDAY_SELECTION RTC Alarm B Date WeekDay + * @{ + */ +#define DDL_RTC_ALMB_DATEWEEKDAYSEL_DATE 0x00000000U /*!< Alarm B Date is selected */ +#define DDL_RTC_ALMB_DATEWEEKDAYSEL_WEEKDAY RTC_ALRMB_WEEKSEL /*!< Alarm B WeekDay is selected */ +/** + * @} + */ + +#endif /* USE_FULL_DDL_DRIVER */ + +/** @defgroup RTC_DDL_EC_GET_FLAG Get Flags Defines + * @brief Flags defines which can be used with DDL_RTC_ReadReg function + * @{ + */ +#define DDL_RTC_STS_RCALPFLG RTC_STS_RCALPFLG +#if defined(RTC_TAMPER2_SUPPORT) +#define DDL_RTC_STS_TP2FLG RTC_STS_TP2FLG +#endif /* RTC_TAMPER2_SUPPORT */ +#define DDL_RTC_STS_TP1FLG RTC_STS_TP1FLG +#define DDL_RTC_STS_TSOVRFLG RTC_STS_TSOVRFLG +#define DDL_RTC_STS_TSFLG RTC_STS_TSFLG +#define DDL_RTC_STS_WUTFLG RTC_STS_WUTFLG +#define DDL_RTC_STS_ALRBFLG RTC_STS_ALRBFLG +#define DDL_RTC_STS_ALRAFLG RTC_STS_ALRAFLG +#define DDL_RTC_STS_RINITFLG RTC_STS_RINITFLG +#define DDL_RTC_STS_RSFLG RTC_STS_RSFLG +#define DDL_RTC_STS_INITSFLG RTC_STS_INITSFLG +#define DDL_RTC_STS_SOPFLG RTC_STS_SOPFLG +#define DDL_RTC_STS_WUTWFLG RTC_STS_WUTWFLG +#define DDL_RTC_STS_ALRBWFLG RTC_STS_ALRBWFLG +#define DDL_RTC_STS_ALRAWFLG RTC_STS_ALRAWFLG +/** + * @} + */ + +/** @defgroup RTC_DDL_EC_IT IT Defines + * @brief IT defines which can be used with DDL_RTC_ReadReg and DDL_RTC_WriteReg functions + * @{ + */ +#define DDL_RTC_CTRL_TSIEN RTC_CTRL_TSIEN +#define DDL_RTC_CTRL_WUTIEN RTC_CTRL_WUTIEN +#define DDL_RTC_CTRL_ALRBIEN RTC_CTRL_ALRBIEN +#define DDL_RTC_CTRL_ALRAIEN RTC_CTRL_ALRAIEN +#define DDL_RTC_TACFG_TPIEN RTC_TACFG_TPIEN +/** + * @} + */ + +/** @defgroup RTC_DDL_EC_WEEKDAY WEEK DAY + * @{ + */ +#define DDL_RTC_WEEKDAY_MONDAY ((uint8_t)0x01U) /*!< Monday */ +#define DDL_RTC_WEEKDAY_TUESDAY ((uint8_t)0x02U) /*!< Tuesday */ +#define DDL_RTC_WEEKDAY_WEDNESDAY ((uint8_t)0x03U) /*!< Wednesday */ +#define DDL_RTC_WEEKDAY_THURSDAY ((uint8_t)0x04U) /*!< Thrusday */ +#define DDL_RTC_WEEKDAY_FRIDAY ((uint8_t)0x05U) /*!< Friday */ +#define DDL_RTC_WEEKDAY_SATURDAY ((uint8_t)0x06U) /*!< Saturday */ +#define DDL_RTC_WEEKDAY_SUNDAY ((uint8_t)0x07U) /*!< Sunday */ +/** + * @} + */ + +/** @defgroup RTC_DDL_EC_MONTH MONTH + * @{ + */ +#define DDL_RTC_MONTH_JANUARY ((uint8_t)0x01U) /*!< January */ +#define DDL_RTC_MONTH_FEBRUARY ((uint8_t)0x02U) /*!< February */ +#define DDL_RTC_MONTH_MARCH ((uint8_t)0x03U) /*!< March */ +#define DDL_RTC_MONTH_APRIL ((uint8_t)0x04U) /*!< April */ +#define DDL_RTC_MONTH_MAY ((uint8_t)0x05U) /*!< May */ +#define DDL_RTC_MONTH_JUNE ((uint8_t)0x06U) /*!< June */ +#define DDL_RTC_MONTH_JULY ((uint8_t)0x07U) /*!< July */ +#define DDL_RTC_MONTH_AUGUST ((uint8_t)0x08U) /*!< August */ +#define DDL_RTC_MONTH_SEPTEMBER ((uint8_t)0x09U) /*!< September */ +#define DDL_RTC_MONTH_OCTOBER ((uint8_t)0x10U) /*!< October */ +#define DDL_RTC_MONTH_NOVEMBER ((uint8_t)0x11U) /*!< November */ +#define DDL_RTC_MONTH_DECEMBER ((uint8_t)0x12U) /*!< December */ +/** + * @} + */ + +/** @defgroup RTC_DDL_EC_HOURFORMAT HOUR FORMAT + * @{ + */ +#define DDL_RTC_HOURFORMAT_24HOUR 0x00000000U /*!< 24 hour/day format */ +#define DDL_RTC_HOURFORMAT_AMPM RTC_CTRL_TIMEFCFG /*!< AM/PM hour format */ +/** + * @} + */ + +/** @defgroup RTC_DDL_EC_ALARMOUT ALARM OUTPUT + * @{ + */ +#define DDL_RTC_ALARMOUT_DISABLE 0x00000000U /*!< Output disabled */ +#define DDL_RTC_ALARMOUT_ALMA RTC_CTRL_OUTSEL_0 /*!< Alarm A output enabled */ +#define DDL_RTC_ALARMOUT_ALMB RTC_CTRL_OUTSEL_1 /*!< Alarm B output enabled */ +#define DDL_RTC_ALARMOUT_WAKEUP RTC_CTRL_OUTSEL /*!< Wakeup output enabled */ +/** + * @} + */ + +/** @defgroup RTC_DDL_EC_ALARM_OUTPUTTYPE ALARM OUTPUT TYPE + * @{ + */ +#define DDL_RTC_ALARM_OUTPUTTYPE_OPENDRAIN 0x00000000U /*!< RTC_ALARM, when mapped on PC13, is open-drain output */ +#define DDL_RTC_ALARM_OUTPUTTYPE_PUSHPULL RTC_TACFG_ALRMOT /*!< RTC_ALARM, when mapped on PC13, is push-pull output */ +/** + * @} + */ + +/** @defgroup RTC_DDL_EC_OUTPUTPOLARITY_PIN OUTPUT POLARITY PIN + * @{ + */ +#define DDL_RTC_OUTPUTPOLARITY_PIN_HIGH 0x00000000U /*!< Pin is high when ALRAF/ALRBF/WUTF is asserted (depending on OSEL)*/ +#define DDL_RTC_OUTPUTPOLARITY_PIN_LOW RTC_CTRL_POLCFG /*!< Pin is low when ALRAF/ALRBF/WUTF is asserted (depending on OSEL) */ +/** + * @} + */ + +/** @defgroup RTC_DDL_EC_TIME_FORMAT TIME FORMAT + * @{ + */ +#define DDL_RTC_TIME_FORMAT_AM_OR_24 0x00000000U /*!< AM or 24-hour format */ +#define DDL_RTC_TIME_FORMAT_PM RTC_TIME_TIMEFCFG /*!< PM */ +/** + * @} + */ + +/** @defgroup RTC_DDL_EC_SHIFT_SECOND SHIFT SECOND + * @{ + */ +#define DDL_RTC_SHIFT_SECOND_DELAY 0x00000000U /* Delay (seconds) = SUBFS / (PREDIV_S + 1) */ +#define DDL_RTC_SHIFT_SECOND_ADVANCE RTC_SHIFT_ADD1SECEN /* Advance (seconds) = (1 - (SUBFS / (PREDIV_S + 1))) */ +/** + * @} + */ + +/** @defgroup RTC_DDL_EC_ALMA_MASK ALARMA MASK + * @{ + */ +#define DDL_RTC_ALMA_MASK_NONE 0x00000000U /*!< No masks applied on Alarm A*/ +#define DDL_RTC_ALMA_MASK_DATEWEEKDAY RTC_ALRMA_DATEMEN /*!< Date/day do not care in Alarm A comparison */ +#define DDL_RTC_ALMA_MASK_HOURS RTC_ALRMA_HRMEN /*!< Hours do not care in Alarm A comparison */ +#define DDL_RTC_ALMA_MASK_MINUTES RTC_ALRMA_MINMEN /*!< Minutes do not care in Alarm A comparison */ +#define DDL_RTC_ALMA_MASK_SECONDS RTC_ALRMA_SECMEN /*!< Seconds do not care in Alarm A comparison */ +#define DDL_RTC_ALMA_MASK_ALL (RTC_ALRMA_DATEMEN | RTC_ALRMA_HRMEN | RTC_ALRMA_MINMEN | RTC_ALRMA_SECMEN) /*!< Masks all */ +/** + * @} + */ + +/** @defgroup RTC_DDL_EC_ALMA_TIME_FORMAT ALARMA TIME FORMAT + * @{ + */ +#define DDL_RTC_ALMA_TIME_FORMAT_AM 0x00000000U /*!< AM or 24-hour format */ +#define DDL_RTC_ALMA_TIME_FORMAT_PM RTC_ALRMA_TIMEFCFG /*!< PM */ +/** + * @} + */ + +/** @defgroup RTC_DDL_EC_ALMB_MASK ALARMB MASK + * @{ + */ +#define DDL_RTC_ALMB_MASK_NONE 0x00000000U /*!< No masks applied on Alarm B */ +#define DDL_RTC_ALMB_MASK_DATEWEEKDAY RTC_ALRMB_DATEMEN /*!< Date/day do not care in Alarm B comparison */ +#define DDL_RTC_ALMB_MASK_HOURS RTC_ALRMB_HRMEN /*!< Hours do not care in Alarm B comparison */ +#define DDL_RTC_ALMB_MASK_MINUTES RTC_ALRMB_MINMEN /*!< Minutes do not care in Alarm B comparison */ +#define DDL_RTC_ALMB_MASK_SECONDS RTC_ALRMB_SECMEN /*!< Seconds do not care in Alarm B comparison */ +#define DDL_RTC_ALMB_MASK_ALL (RTC_ALRMB_DATEMEN | RTC_ALRMB_HRMEN | RTC_ALRMB_MINMEN | RTC_ALRMB_SECMEN) /*!< Masks all */ +/** + * @} + */ + +/** @defgroup RTC_DDL_EC_ALMB_TIME_FORMAT ALARMB TIME FORMAT + * @{ + */ +#define DDL_RTC_ALMB_TIME_FORMAT_AM 0x00000000U /*!< AM or 24-hour format */ +#define DDL_RTC_ALMB_TIME_FORMAT_PM RTC_ALRMB_TIMEFCFG /*!< PM */ +/** + * @} + */ + +/** @defgroup RTC_DDL_EC_TIMESTAMP_EDGE TIMESTAMP EDGE + * @{ + */ +#define DDL_RTC_TIMESTAMP_EDGE_RISING 0x00000000U /*!< RTC_TS input rising edge generates a time-stamp event */ +#define DDL_RTC_TIMESTAMP_EDGE_FALLING RTC_CTRL_TSETECFG /*!< RTC_TS input falling edge generates a time-stamp even */ +/** + * @} + */ + +/** @defgroup RTC_DDL_EC_TS_TIME_FORMAT TIMESTAMP TIME FORMAT + * @{ + */ +#define DDL_RTC_TS_TIME_FORMAT_AM 0x00000000U /*!< AM or 24-hour format */ +#define DDL_RTC_TS_TIME_FORMAT_PM RTC_TSTIME_TIMEFCFG /*!< PM */ +/** + * @} + */ + +/** @defgroup RTC_DDL_EC_TAMPER TAMPER + * @{ + */ +#define DDL_RTC_TAMPER_1 RTC_TACFG_TP1EN /*!< RTC_TAMP1 input detection */ +#if defined(RTC_TAMPER2_SUPPORT) +#define DDL_RTC_TAMPER_2 RTC_TACFG_TP2EN /*!< RTC_TAMP2 input detection */ +#endif /* RTC_TAMPER2_SUPPORT */ +/** + * @} + */ + +/** @defgroup RTC_DDL_EC_TAMPER_DURATION TAMPER DURATION + * @{ + */ +#define DDL_RTC_TAMPER_DURATION_1RTCCLK 0x00000000U /*!< Tamper pins are pre-charged before sampling during 1 RTCCLK cycle */ +#define DDL_RTC_TAMPER_DURATION_2RTCCLK RTC_TACFG_TPPRDUSEL_0 /*!< Tamper pins are pre-charged before sampling during 2 RTCCLK cycles */ +#define DDL_RTC_TAMPER_DURATION_4RTCCLK RTC_TACFG_TPPRDUSEL_1 /*!< Tamper pins are pre-charged before sampling during 4 RTCCLK cycles */ +#define DDL_RTC_TAMPER_DURATION_8RTCCLK RTC_TACFG_TPPRDUSEL /*!< Tamper pins are pre-charged before sampling during 8 RTCCLK cycles */ +/** + * @} + */ + +/** @defgroup RTC_DDL_EC_TAMPER_FILTER TAMPER FILTER + * @{ + */ +#define DDL_RTC_TAMPER_FILTER_DISABLE 0x00000000U /*!< Tamper filter is disabled */ +#define DDL_RTC_TAMPER_FILTER_2SAMPLE RTC_TACFG_TPFCSEL_0 /*!< Tamper is activated after 2 consecutive samples at the active level */ +#define DDL_RTC_TAMPER_FILTER_4SAMPLE RTC_TACFG_TPFCSEL_1 /*!< Tamper is activated after 4 consecutive samples at the active level */ +#define DDL_RTC_TAMPER_FILTER_8SAMPLE RTC_TACFG_TPFCSEL /*!< Tamper is activated after 8 consecutive samples at the active level. */ +/** + * @} + */ + +/** @defgroup RTC_DDL_EC_TAMPER_SAMPLFREQDIV TAMPER SAMPLING FREQUENCY DIVIDER + * @{ + */ +#define DDL_RTC_TAMPER_SAMPLFREQDIV_32768 0x00000000U /*!< Each of the tamper inputs are sampled with a frequency = RTCCLK / 32768 */ +#define DDL_RTC_TAMPER_SAMPLFREQDIV_16384 RTC_TACFG_TPSFSEL_0 /*!< Each of the tamper inputs are sampled with a frequency = RTCCLK / 16384 */ +#define DDL_RTC_TAMPER_SAMPLFREQDIV_8192 RTC_TACFG_TPSFSEL_1 /*!< Each of the tamper inputs are sampled with a frequency = RTCCLK / 8192 */ +#define DDL_RTC_TAMPER_SAMPLFREQDIV_4096 (RTC_TACFG_TPSFSEL_1 | RTC_TACFG_TPSFSEL_0) /*!< Each of the tamper inputs are sampled with a frequency = RTCCLK / 4096 */ +#define DDL_RTC_TAMPER_SAMPLFREQDIV_2048 RTC_TACFG_TPSFSEL_2 /*!< Each of the tamper inputs are sampled with a frequency = RTCCLK / 2048 */ +#define DDL_RTC_TAMPER_SAMPLFREQDIV_1024 (RTC_TACFG_TPSFSEL_2 | RTC_TACFG_TPSFSEL_0) /*!< Each of the tamper inputs are sampled with a frequency = RTCCLK / 1024 */ +#define DDL_RTC_TAMPER_SAMPLFREQDIV_512 (RTC_TACFG_TPSFSEL_2 | RTC_TACFG_TPSFSEL_1) /*!< Each of the tamper inputs are sampled with a frequency = RTCCLK / 512 */ +#define DDL_RTC_TAMPER_SAMPLFREQDIV_256 RTC_TACFG_TPSFSEL /*!< Each of the tamper inputs are sampled with a frequency = RTCCLK / 256 */ +/** + * @} + */ + +/** @defgroup RTC_DDL_EC_TAMPER_ACTIVELEVEL TAMPER ACTIVE LEVEL + * @{ + */ +#define DDL_RTC_TAMPER_ACTIVELEVEL_TAMP1 RTC_TACFG_TP1ALCFG /*!< RTC_TAMP1 input falling edge (if TAMPFLT = 00) or staying high (if TAMPFLT != 00) triggers a tamper detection event */ +#if defined(RTC_TAMPER2_SUPPORT) +#define DDL_RTC_TAMPER_ACTIVELEVEL_TAMP2 RTC_TACFG_TP2ALCFG /*!< RTC_TAMP2 input falling edge (if TAMPFLT = 00) or staying high (if TAMPFLT != 00) triggers a tamper detection event */ +#endif /* RTC_TAMPER2_SUPPORT */ +/** + * @} + */ + +/** @defgroup RTC_DDL_EC_WAKEUPCLOCK_DIV WAKEUP CLOCK DIV + * @{ + */ +#define DDL_RTC_WAKEUPCLOCK_DIV_16 0x00000000U /*!< RTC/16 clock is selected */ +#define DDL_RTC_WAKEUPCLOCK_DIV_8 (RTC_CTRL_WUCLKSEL_0) /*!< RTC/8 clock is selected */ +#define DDL_RTC_WAKEUPCLOCK_DIV_4 (RTC_CTRL_WUCLKSEL_1) /*!< RTC/4 clock is selected */ +#define DDL_RTC_WAKEUPCLOCK_DIV_2 (RTC_CTRL_WUCLKSEL_1 | RTC_CTRL_WUCLKSEL_0) /*!< RTC/2 clock is selected */ +#define DDL_RTC_WAKEUPCLOCK_CKSPRE (RTC_CTRL_WUCLKSEL_2) /*!< ck_spre (usually 1 Hz) clock is selected */ +#define DDL_RTC_WAKEUPCLOCK_CKSPRE_WUT (RTC_CTRL_WUCLKSEL_2 | RTC_CTRL_WUCLKSEL_1) /*!< ck_spre (usually 1 Hz) clock is selected and 2exp16 is added to the WUT counter value*/ +/** + * @} + */ + +/** @defgroup RTC_DDL_EC_BKP BACKUP + * @{ + */ +#define DDL_RTC_BKP_DR0 0x00000000U +#define DDL_RTC_BKP_DR1 0x00000001U +#define DDL_RTC_BKP_DR2 0x00000002U +#define DDL_RTC_BKP_DR3 0x00000003U +#define DDL_RTC_BKP_DR4 0x00000004U +#define DDL_RTC_BKP_DR5 0x00000005U +#define DDL_RTC_BKP_DR6 0x00000006U +#define DDL_RTC_BKP_DR7 0x00000007U +#define DDL_RTC_BKP_DR8 0x00000008U +#define DDL_RTC_BKP_DR9 0x00000009U +#define DDL_RTC_BKP_DR10 0x0000000AU +#define DDL_RTC_BKP_DR11 0x0000000BU +#define DDL_RTC_BKP_DR12 0x0000000CU +#define DDL_RTC_BKP_DR13 0x0000000DU +#define DDL_RTC_BKP_DR14 0x0000000EU +#define DDL_RTC_BKP_DR15 0x0000000FU +#define DDL_RTC_BKP_DR16 0x00000010U +#define DDL_RTC_BKP_DR17 0x00000011U +#define DDL_RTC_BKP_DR18 0x00000012U +#define DDL_RTC_BKP_DR19 0x00000013U +/** + * @} + */ + +/** @defgroup RTC_DDL_EC_CALIB_OUTPUT Calibration output + * @{ + */ +#define DDL_RTC_CALIB_OUTPUT_NONE 0x00000000U /*!< Calibration output disabled */ +#define DDL_RTC_CALIB_OUTPUT_1HZ (RTC_CTRL_CALOEN | RTC_CTRL_CALOSEL) /*!< Calibration output is 1 Hz */ +#define DDL_RTC_CALIB_OUTPUT_512HZ (RTC_CTRL_CALOEN) /*!< Calibration output is 512 Hz */ +/** + * @} + */ + +/** @defgroup RTC_DDL_EC_CALIB_SIGN Coarse digital calibration sign + * @{ + */ +#define DDL_RTC_CALIB_SIGN_POSITIVE 0x00000000U /*!< Positive calibration: calendar update frequency is increased */ +#define DDL_RTC_CALIB_SIGN_NEGATIVE RTC_DCAL_DCALCFG /*!< Negative calibration: calendar update frequency is decreased */ +/** + * @} + */ + +/** @defgroup RTC_DDL_EC_CALIB_INSERTPULSE Calibration pulse insertion + * @{ + */ +#define DDL_RTC_CALIB_INSERTPULSE_NONE 0x00000000U /*!< No RTCCLK pulses are added */ +#define DDL_RTC_CALIB_INSERTPULSE_SET RTC_CAL_ICALFEN /*!< One RTCCLK pulse is effectively inserted every 2exp11 pulses (frequency increased by 488.5 ppm) */ +/** + * @} + */ + +/** @defgroup RTC_DDL_EC_CALIB_PERIOD Calibration period + * @{ + */ +#define DDL_RTC_CALIB_PERIOD_32SEC 0x00000000U /*!< Use a 32-second calibration cycle period */ +#define DDL_RTC_CALIB_PERIOD_16SEC RTC_CAL_CAL16CFG /*!< Use a 16-second calibration cycle period */ +#define DDL_RTC_CALIB_PERIOD_8SEC RTC_CAL_CAL8CFG /*!< Use a 8-second calibration cycle period */ +/** + * @} + */ + +/** @defgroup RTC_DDL_EC_TSINSEL TIMESTAMP mapping + * @{ + */ +#define DDL_RTC_TimeStampPin_Default 0x00000000U /*!< Use RTC_AF1 as TIMESTAMP */ +#if defined(RTC_AF2_SUPPORT) +#define DDL_RTC_TimeStampPin_Pos1 RTC_TACFG_TSMSEL /*!< Use RTC_AF2 as TIMESTAMP */ +#endif /* RTC_AF2_SUPPORT */ +/** + * @} + */ + +/** @defgroup RTC_DDL_EC_TAMP1INSEL TAMPER1 mapping + * @{ + */ +#define DDL_RTC_TamperPin_Default 0x00000000U /*!< Use RTC_AF1 as TAMPER1 */ +#if defined(RTC_AF2_SUPPORT) +#define DDL_RTC_TamperPin_Pos1 RTC_TACFG_TP1MSEL /*!< Use RTC_AF2 as TAMPER1 */ +#endif /* RTC_AF2_SUPPORT */ +/** + * @} + */ + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ +/** @defgroup RTC_DDL_Exported_Macros RTC Exported Macros + * @{ + */ + +/** @defgroup RTC_DDL_EM_WRITE_READ Common Write and read registers Macros + * @{ + */ + +/** + * @brief Write a value in RTC register + * @param __INSTANCE__ RTC Instance + * @param __REG__ Register to be written + * @param __VALUE__ Value to be written in the register + * @retval None + */ +#define DDL_RTC_WriteReg(__INSTANCE__, __REG__, __VALUE__) WRITE_REG(__INSTANCE__->__REG__, (__VALUE__)) + +/** + * @brief Read a value in RTC register + * @param __INSTANCE__ RTC Instance + * @param __REG__ Register to be read + * @retval Register value + */ +#define DDL_RTC_ReadReg(__INSTANCE__, __REG__) READ_REG(__INSTANCE__->__REG__) +/** + * @} + */ + +/** @defgroup RTC_DDL_EM_Convert Convert helper Macros + * @{ + */ + +/** + * @brief Helper macro to convert a value from 2 digit decimal format to BCD format + * @param __VALUE__ Byte to be converted + * @retval Converted byte + */ +#define __DDL_RTC_CONVERT_BIN2BCD(__VALUE__) (uint8_t)((((__VALUE__) / 10U) << 4U) | ((__VALUE__) % 10U)) + +/** + * @brief Helper macro to convert a value from BCD format to 2 digit decimal format + * @param __VALUE__ BCD value to be converted + * @retval Converted byte + */ +#define __DDL_RTC_CONVERT_BCD2BIN(__VALUE__) (uint8_t)(((uint8_t)((__VALUE__) & (uint8_t)0xF0U) >> (uint8_t)0x4U) * 10U + ((__VALUE__) & (uint8_t)0x0FU)) + +/** + * @} + */ + +/** @defgroup RTC_DDL_EM_Date Date helper Macros + * @{ + */ + +/** + * @brief Helper macro to retrieve weekday. + * @param __RTC_DATE__ Date returned by @ref DDL_RTC_DATE_Get function. + * @retval Returned value can be one of the following values: + * @arg @ref DDL_RTC_WEEKDAY_MONDAY + * @arg @ref DDL_RTC_WEEKDAY_TUESDAY + * @arg @ref DDL_RTC_WEEKDAY_WEDNESDAY + * @arg @ref DDL_RTC_WEEKDAY_THURSDAY + * @arg @ref DDL_RTC_WEEKDAY_FRIDAY + * @arg @ref DDL_RTC_WEEKDAY_SATURDAY + * @arg @ref DDL_RTC_WEEKDAY_SUNDAY + */ +#define __DDL_RTC_GET_WEEKDAY(__RTC_DATE__) (((__RTC_DATE__) >> RTC_OFFSET_WEEKDAY) & 0x000000FFU) + +/** + * @brief Helper macro to retrieve Year in BCD format + * @param __RTC_DATE__ Value returned by @ref DDL_RTC_DATE_Get + * @retval Year in BCD format (0x00 . . . 0x99) + */ +#define __DDL_RTC_GET_YEAR(__RTC_DATE__) ((__RTC_DATE__) & 0x000000FFU) + +/** + * @brief Helper macro to retrieve Month in BCD format + * @param __RTC_DATE__ Value returned by @ref DDL_RTC_DATE_Get + * @retval Returned value can be one of the following values: + * @arg @ref DDL_RTC_MONTH_JANUARY + * @arg @ref DDL_RTC_MONTH_FEBRUARY + * @arg @ref DDL_RTC_MONTH_MARCH + * @arg @ref DDL_RTC_MONTH_APRIL + * @arg @ref DDL_RTC_MONTH_MAY + * @arg @ref DDL_RTC_MONTH_JUNE + * @arg @ref DDL_RTC_MONTH_JULY + * @arg @ref DDL_RTC_MONTH_AUGUST + * @arg @ref DDL_RTC_MONTH_SEPTEMBER + * @arg @ref DDL_RTC_MONTH_OCTOBER + * @arg @ref DDL_RTC_MONTH_NOVEMBER + * @arg @ref DDL_RTC_MONTH_DECEMBER + */ +#define __DDL_RTC_GET_MONTH(__RTC_DATE__) (((__RTC_DATE__) >>RTC_OFFSET_MONTH) & 0x000000FFU) + +/** + * @brief Helper macro to retrieve Day in BCD format + * @param __RTC_DATE__ Value returned by @ref DDL_RTC_DATE_Get + * @retval Day in BCD format (0x01 . . . 0x31) + */ +#define __DDL_RTC_GET_DAY(__RTC_DATE__) (((__RTC_DATE__) >>RTC_OFFSET_DAY) & 0x000000FFU) + +/** + * @} + */ + +/** @defgroup RTC_DDL_EM_Time Time helper Macros + * @{ + */ + +/** + * @brief Helper macro to retrieve hour in BCD format + * @param __RTC_TIME__ RTC time returned by @ref DDL_RTC_TIME_Get function + * @retval Hours in BCD format (0x01. . .0x12 or between Min_Data=0x00 and Max_Data=0x23) + */ +#define __DDL_RTC_GET_HOUR(__RTC_TIME__) (((__RTC_TIME__) >> RTC_OFFSET_HOUR) & 0x000000FFU) + +/** + * @brief Helper macro to retrieve minute in BCD format + * @param __RTC_TIME__ RTC time returned by @ref DDL_RTC_TIME_Get function + * @retval Minutes in BCD format (0x00. . .0x59) + */ +#define __DDL_RTC_GET_MINUTE(__RTC_TIME__) (((__RTC_TIME__) >> RTC_OFFSET_MINUTE) & 0x000000FFU) + +/** + * @brief Helper macro to retrieve second in BCD format + * @param __RTC_TIME__ RTC time returned by @ref DDL_RTC_TIME_Get function + * @retval Seconds in format (0x00. . .0x59) + */ +#define __DDL_RTC_GET_SECOND(__RTC_TIME__) ((__RTC_TIME__) & 0x000000FFU) + +/** + * @} + */ + +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +/** @defgroup RTC_DDL_Exported_Functions RTC Exported Functions + * @{ + */ + +/** @defgroup RTC_DDL_EF_Configuration Configuration + * @{ + */ + +/** + * @brief Set Hours format (24 hour/day or AM/PM hour format) + * @note Bit is write-protected. @ref DDL_RTC_DisableWriteProtection function should be called before. + * @note It can be written in initialization mode only (@ref DDL_RTC_EnableInitMode function) + * @param RTCx RTC Instance + * @param HourFormat This parameter can be one of the following values: + * @arg @ref DDL_RTC_HOURFORMAT_24HOUR + * @arg @ref DDL_RTC_HOURFORMAT_AMPM + * @retval None + */ +__STATIC_INLINE void DDL_RTC_SetHourFormat(RTC_TypeDef *RTCx, uint32_t HourFormat) +{ + MODIFY_REG(RTCx->CTRL, RTC_CTRL_TIMEFCFG, HourFormat); +} + +/** + * @brief Get Hours format (24 hour/day or AM/PM hour format) + * @param RTCx RTC Instance + * @retval Returned value can be one of the following values: + * @arg @ref DDL_RTC_HOURFORMAT_24HOUR + * @arg @ref DDL_RTC_HOURFORMAT_AMPM + */ +__STATIC_INLINE uint32_t DDL_RTC_GetHourFormat(RTC_TypeDef *RTCx) +{ + return (uint32_t)(READ_BIT(RTCx->CTRL, RTC_CTRL_TIMEFCFG)); +} + +/** + * @brief Select the flag to be routed to RTC_ALARM output + * @note Bit is write-protected. @ref DDL_RTC_DisableWriteProtection function should be called before. + * @param RTCx RTC Instance + * @param AlarmOutput This parameter can be one of the following values: + * @arg @ref DDL_RTC_ALARMOUT_DISABLE + * @arg @ref DDL_RTC_ALARMOUT_ALMA + * @arg @ref DDL_RTC_ALARMOUT_ALMB + * @arg @ref DDL_RTC_ALARMOUT_WAKEUP + * @retval None + */ +__STATIC_INLINE void DDL_RTC_SetAlarmOutEvent(RTC_TypeDef *RTCx, uint32_t AlarmOutput) +{ + MODIFY_REG(RTCx->CTRL, RTC_CTRL_OUTSEL, AlarmOutput); +} + +/** + * @brief Get the flag to be routed to RTC_ALARM output + * @param RTCx RTC Instance + * @retval Returned value can be one of the following values: + * @arg @ref DDL_RTC_ALARMOUT_DISABLE + * @arg @ref DDL_RTC_ALARMOUT_ALMA + * @arg @ref DDL_RTC_ALARMOUT_ALMB + * @arg @ref DDL_RTC_ALARMOUT_WAKEUP + */ +__STATIC_INLINE uint32_t DDL_RTC_GetAlarmOutEvent(RTC_TypeDef *RTCx) +{ + return (uint32_t)(READ_BIT(RTCx->CTRL, RTC_CTRL_OUTSEL)); +} + +/** + * @brief Set RTC_ALARM output type (ALARM in push-pull or open-drain output) + * @note Used only when RTC_ALARM is mapped on PC13 + * @param RTCx RTC Instance + * @param Output This parameter can be one of the following values: + * @arg @ref DDL_RTC_ALARM_OUTPUTTYPE_OPENDRAIN + * @arg @ref DDL_RTC_ALARM_OUTPUTTYPE_PUSHPULL + * @retval None + */ +__STATIC_INLINE void DDL_RTC_SetAlarmOutputType(RTC_TypeDef *RTCx, uint32_t Output) +{ + MODIFY_REG(RTCx->TACFG, RTC_TACFG_ALRMOT, Output); +} + +/** + * @brief Get RTC_ALARM output type (ALARM in push-pull or open-drain output) + * @note used only when RTC_ALARM is mapped on PC13 + * @param RTCx RTC Instance + * @retval Returned value can be one of the following values: + * @arg @ref DDL_RTC_ALARM_OUTPUTTYPE_OPENDRAIN + * @arg @ref DDL_RTC_ALARM_OUTPUTTYPE_PUSHPULL + */ +__STATIC_INLINE uint32_t DDL_RTC_GetAlarmOutputType(RTC_TypeDef *RTCx) +{ + return (uint32_t)(READ_BIT(RTCx->TACFG, RTC_TACFG_ALRMOT)); +} + +/** + * @brief Enable initialization mode + * @note Initialization mode is used to program time and date register (RTC_TIME and RTC_DATE) + * and prescaler register (RTC_PSC). + * Counters are stopped and start counting from the new value when INIT is reset. + * @param RTCx RTC Instance + * @retval None + */ +__STATIC_INLINE void DDL_RTC_EnableInitMode(RTC_TypeDef *RTCx) +{ + /* Set the Initialization mode */ + WRITE_REG(RTCx->STS, RTC_INIT_MASK); +} + +/** + * @brief Disable initialization mode (Free running mode) + * @param RTCx RTC Instance + * @retval None + */ +__STATIC_INLINE void DDL_RTC_DisableInitMode(RTC_TypeDef *RTCx) +{ + /* Exit Initialization mode */ + WRITE_REG(RTCx->STS, (uint32_t)~RTC_STS_INITEN); +} + +/** + * @brief Set Output polarity (pin is low when ALRAF/ALRBF/WUTF is asserted) + * @note Bit is write-protected. @ref DDL_RTC_DisableWriteProtection function should be called before. + * @param RTCx RTC Instance + * @param Polarity This parameter can be one of the following values: + * @arg @ref DDL_RTC_OUTPUTPOLARITY_PIN_HIGH + * @arg @ref DDL_RTC_OUTPUTPOLARITY_PIN_LOW + * @retval None + */ +__STATIC_INLINE void DDL_RTC_SetOutputPolarity(RTC_TypeDef *RTCx, uint32_t Polarity) +{ + MODIFY_REG(RTCx->CTRL, RTC_CTRL_POLCFG, Polarity); +} + +/** + * @brief Get Output polarity + * @param RTCx RTC Instance + * @retval Returned value can be one of the following values: + * @arg @ref DDL_RTC_OUTPUTPOLARITY_PIN_HIGH + * @arg @ref DDL_RTC_OUTPUTPOLARITY_PIN_LOW + */ +__STATIC_INLINE uint32_t DDL_RTC_GetOutputPolarity(RTC_TypeDef *RTCx) +{ + return (uint32_t)(READ_BIT(RTCx->CTRL, RTC_CTRL_POLCFG)); +} + +/** + * @brief Enable Bypass the shadow registers + * @note Bit is write-protected. @ref DDL_RTC_DisableWriteProtection function should be called before. + * @param RTCx RTC Instance + * @retval None + */ +__STATIC_INLINE void DDL_RTC_EnableShadowRegBypass(RTC_TypeDef *RTCx) +{ + SET_BIT(RTCx->CTRL, RTC_CTRL_RCMCFG); +} + +/** + * @brief Disable Bypass the shadow registers + * @param RTCx RTC Instance + * @retval None + */ +__STATIC_INLINE void DDL_RTC_DisableShadowRegBypass(RTC_TypeDef *RTCx) +{ + CLEAR_BIT(RTCx->CTRL, RTC_CTRL_RCMCFG); +} + +/** + * @brief Check if Shadow registers bypass is enabled or not. + * @param RTCx RTC Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_RTC_IsShadowRegBypassEnabled(RTC_TypeDef *RTCx) +{ + return ((READ_BIT(RTCx->CTRL, RTC_CTRL_RCMCFG) == (RTC_CTRL_RCMCFG)) ? 1UL : 0UL); +} + +/** + * @brief Enable RTC_REFIN reference clock detection (50 or 60 Hz) + * @note Bit is write-protected. @ref DDL_RTC_DisableWriteProtection function should be called before. + * @note It can be written in initialization mode only (@ref DDL_RTC_EnableInitMode function) + * @param RTCx RTC Instance + * @retval None + */ +__STATIC_INLINE void DDL_RTC_EnableRefClock(RTC_TypeDef *RTCx) +{ + SET_BIT(RTCx->CTRL, RTC_CTRL_RCLKDEN); +} + +/** + * @brief Disable RTC_REFIN reference clock detection (50 or 60 Hz) + * @note Bit is write-protected. @ref DDL_RTC_DisableWriteProtection function should be called before. + * @note It can be written in initialization mode only (@ref DDL_RTC_EnableInitMode function) + * @param RTCx RTC Instance + * @retval None + */ +__STATIC_INLINE void DDL_RTC_DisableRefClock(RTC_TypeDef *RTCx) +{ + CLEAR_BIT(RTCx->CTRL, RTC_CTRL_RCLKDEN); +} + +/** + * @brief Set Asynchronous prescaler factor + * @param RTCx RTC Instance + * @param AsynchPrescaler Value between Min_Data = 0 and Max_Data = 0x7F + * @retval None + */ +__STATIC_INLINE void DDL_RTC_SetAsynchPrescaler(RTC_TypeDef *RTCx, uint32_t AsynchPrescaler) +{ + MODIFY_REG(RTCx->PSC, RTC_PSC_APSC, AsynchPrescaler << RTC_PSC_APSC_Pos); +} + +/** + * @brief Set Synchronous prescaler factor + * @param RTCx RTC Instance + * @param SynchPrescaler Value between Min_Data = 0 and Max_Data = 0x7FFF + * @retval None + */ +__STATIC_INLINE void DDL_RTC_SetSynchPrescaler(RTC_TypeDef *RTCx, uint32_t SynchPrescaler) +{ + MODIFY_REG(RTCx->PSC, RTC_PSC_SPSC, SynchPrescaler); +} + +/** + * @brief Get Asynchronous prescaler factor + * @param RTCx RTC Instance + * @retval Value between Min_Data = 0 and Max_Data = 0x7F + */ +__STATIC_INLINE uint32_t DDL_RTC_GetAsynchPrescaler(RTC_TypeDef *RTCx) +{ + return (uint32_t)(READ_BIT(RTCx->PSC, RTC_PSC_APSC) >> RTC_PSC_APSC_Pos); +} + +/** + * @brief Get Synchronous prescaler factor + * @param RTCx RTC Instance + * @retval Value between Min_Data = 0 and Max_Data = 0x7FFF + */ +__STATIC_INLINE uint32_t DDL_RTC_GetSynchPrescaler(RTC_TypeDef *RTCx) +{ + return (uint32_t)(READ_BIT(RTCx->PSC, RTC_PSC_SPSC)); +} + +/** + * @brief Enable the write protection for RTC registers. + * @param RTCx RTC Instance + * @retval None + */ +__STATIC_INLINE void DDL_RTC_EnableWriteProtection(RTC_TypeDef *RTCx) +{ + WRITE_REG(RTCx->WRPROT, RTC_WRITE_PROTECTION_DISABLE); +} + +/** + * @brief Disable the write protection for RTC registers. + * @param RTCx RTC Instance + * @retval None + */ +__STATIC_INLINE void DDL_RTC_DisableWriteProtection(RTC_TypeDef *RTCx) +{ + WRITE_REG(RTCx->WRPROT, RTC_WRITE_PROTECTION_ENABLE_1); + WRITE_REG(RTCx->WRPROT, RTC_WRITE_PROTECTION_ENABLE_2); +} + +/** + * @} + */ + +/** @defgroup RTC_DDL_EF_Time Time + * @{ + */ + +/** + * @brief Set time format (AM/24-hour or PM notation) + * @note Bit is write-protected. @ref DDL_RTC_DisableWriteProtection function should be called before. + * @note It can be written in initialization mode only (@ref DDL_RTC_EnableInitMode function) + * @param RTCx RTC Instance + * @param TimeFormat This parameter can be one of the following values: + * @arg @ref DDL_RTC_TIME_FORMAT_AM_OR_24 + * @arg @ref DDL_RTC_TIME_FORMAT_PM + * @retval None + */ +__STATIC_INLINE void DDL_RTC_TIME_SetFormat(RTC_TypeDef *RTCx, uint32_t TimeFormat) +{ + MODIFY_REG(RTCx->TIME, RTC_TIME_TIMEFCFG, TimeFormat); +} + +/** + * @brief Get time format (AM or PM notation) + * @note if shadow mode is disabled (BYPSHAD=0), need to check if RSF flag is set + * before reading this bit + * @note Read either RTC_SUBSEC or RTC_TIME locks the values in the higher-order calendar + * shadow registers until RTC_DATE is read (DDL_RTC_ReadReg(RTC, DR)). + * @param RTCx RTC Instance + * @retval Returned value can be one of the following values: + * @arg @ref DDL_RTC_TIME_FORMAT_AM_OR_24 + * @arg @ref DDL_RTC_TIME_FORMAT_PM + */ +__STATIC_INLINE uint32_t DDL_RTC_TIME_GetFormat(RTC_TypeDef *RTCx) +{ + return (uint32_t)(READ_BIT(RTCx->TIME, RTC_TIME_TIMEFCFG)); +} + +/** + * @brief Set Hours in BCD format + * @note Bit is write-protected. @ref DDL_RTC_DisableWriteProtection function should be called before. + * @note It can be written in initialization mode only (@ref DDL_RTC_EnableInitMode function) + * @note helper macro __DDL_RTC_CONVERT_BIN2BCD is available to convert hour from binary to BCD format + * @param RTCx RTC Instance + * @param Hours Value between Min_Data=0x01 and Max_Data=0x12 or between Min_Data=0x00 and Max_Data=0x23 + * @retval None + */ +__STATIC_INLINE void DDL_RTC_TIME_SetHour(RTC_TypeDef *RTCx, uint32_t Hours) +{ + MODIFY_REG(RTCx->TIME, (RTC_TIME_HRT | RTC_TIME_HRU), + (((Hours & 0xF0U) << (RTC_TIME_HRT_Pos - 4U)) | ((Hours & 0x0FU) << RTC_TIME_HRU_Pos))); +} + +/** + * @brief Get Hours in BCD format + * @note if shadow mode is disabled (BYPSHAD=0), need to check if RSF flag is set + * before reading this bit + * @note Read either RTC_SUBSEC or RTC_TIME locks the values in the higher-order calendar + * shadow registers until RTC_DATE is read (DDL_RTC_ReadReg(RTC, DR)). + * @note helper macro __DDL_RTC_CONVERT_BCD2BIN is available to convert hour from BCD to + * Binary format + * @param RTCx RTC Instance + * @retval Value between Min_Data=0x01 and Max_Data=0x12 or between Min_Data=0x00 and Max_Data=0x23 + */ +__STATIC_INLINE uint32_t DDL_RTC_TIME_GetHour(RTC_TypeDef *RTCx) +{ + return (uint32_t)((READ_BIT(RTCx->TIME, (RTC_TIME_HRT | RTC_TIME_HRU))) >> RTC_TIME_HRU_Pos); +} + +/** + * @brief Set Minutes in BCD format + * @note Bit is write-protected. @ref DDL_RTC_DisableWriteProtection function should be called before. + * @note It can be written in initialization mode only (@ref DDL_RTC_EnableInitMode function) + * @note helper macro __DDL_RTC_CONVERT_BIN2BCD is available to convert Minutes from binary to BCD format + * @param RTCx RTC Instance + * @param Minutes Value between Min_Data=0x00 and Max_Data=0x59 + * @retval None + */ +__STATIC_INLINE void DDL_RTC_TIME_SetMinute(RTC_TypeDef *RTCx, uint32_t Minutes) +{ + MODIFY_REG(RTCx->TIME, (RTC_TIME_MINT | RTC_TIME_MINU), + (((Minutes & 0xF0U) << (RTC_TIME_MINT_Pos - 4U)) | ((Minutes & 0x0FU) << RTC_TIME_MINU_Pos))); +} + +/** + * @brief Get Minutes in BCD format + * @note if shadow mode is disabled (BYPSHAD=0), need to check if RSF flag is set + * before reading this bit + * @note Read either RTC_SUBSEC or RTC_TIME locks the values in the higher-order calendar + * shadow registers until RTC_DATE is read (DDL_RTC_ReadReg(RTC, DR)). + * @note helper macro __DDL_RTC_CONVERT_BCD2BIN is available to convert minute from BCD + * to Binary format + * @param RTCx RTC Instance + * @retval Value between Min_Data=0x00 and Max_Data=0x59 + */ +__STATIC_INLINE uint32_t DDL_RTC_TIME_GetMinute(RTC_TypeDef *RTCx) +{ + return (uint32_t)(READ_BIT(RTCx->TIME, (RTC_TIME_MINT | RTC_TIME_MINU)) >> RTC_TIME_MINU_Pos); +} + +/** + * @brief Set Seconds in BCD format + * @note Bit is write-protected. @ref DDL_RTC_DisableWriteProtection function should be called before. + * @note It can be written in initialization mode only (@ref DDL_RTC_EnableInitMode function) + * @note helper macro __DDL_RTC_CONVERT_BIN2BCD is available to convert Seconds from binary to BCD format + * @param RTCx RTC Instance + * @param Seconds Value between Min_Data=0x00 and Max_Data=0x59 + * @retval None + */ +__STATIC_INLINE void DDL_RTC_TIME_SetSecond(RTC_TypeDef *RTCx, uint32_t Seconds) +{ + MODIFY_REG(RTCx->TIME, (RTC_TIME_SECT | RTC_TIME_SECU), + (((Seconds & 0xF0U) << (RTC_TIME_SECT_Pos - 4U)) | ((Seconds & 0x0FU) << RTC_TIME_SECU_Pos))); +} + +/** + * @brief Get Seconds in BCD format + * @note if shadow mode is disabled (BYPSHAD=0), need to check if RSF flag is set + * before reading this bit + * @note Read either RTC_SUBSEC or RTC_TIME locks the values in the higher-order calendar + * shadow registers until RTC_DATE is read (DDL_RTC_ReadReg(RTC, DR)). + * @note helper macro __DDL_RTC_CONVERT_BCD2BIN is available to convert Seconds from BCD + * to Binary format + * @param RTCx RTC Instance + * @retval Value between Min_Data=0x00 and Max_Data=0x59 + */ +__STATIC_INLINE uint32_t DDL_RTC_TIME_GetSecond(RTC_TypeDef *RTCx) +{ + return (uint32_t)(READ_BIT(RTCx->TIME, (RTC_TIME_SECT | RTC_TIME_SECU)) >> RTC_TIME_SECU_Pos); +} + +/** + * @brief Set time (hour, minute and second) in BCD format + * @note Bit is write-protected. @ref DDL_RTC_DisableWriteProtection function should be called before. + * @note It can be written in initialization mode only (@ref DDL_RTC_EnableInitMode function) + * @note TimeFormat and Hours should follow the same format + * @param RTCx RTC Instance + * @param Format12_24 This parameter can be one of the following values: + * @arg @ref DDL_RTC_TIME_FORMAT_AM_OR_24 + * @arg @ref DDL_RTC_TIME_FORMAT_PM + * @param Hours Value between Min_Data=0x01 and Max_Data=0x12 or between Min_Data=0x00 and Max_Data=0x23 + * @param Minutes Value between Min_Data=0x00 and Max_Data=0x59 + * @param Seconds Value between Min_Data=0x00 and Max_Data=0x59 + * @retval None + */ +__STATIC_INLINE void DDL_RTC_TIME_Config(RTC_TypeDef *RTCx, uint32_t Format12_24, uint32_t Hours, uint32_t Minutes, uint32_t Seconds) +{ + uint32_t temp; + + temp = Format12_24 | \ + (((Hours & 0xF0U) << (RTC_TIME_HRT_Pos - 4U)) | ((Hours & 0x0FU) << RTC_TIME_HRU_Pos)) | \ + (((Minutes & 0xF0U) << (RTC_TIME_MINT_Pos - 4U)) | ((Minutes & 0x0FU) << RTC_TIME_MINU_Pos)) | \ + (((Seconds & 0xF0U) << (RTC_TIME_SECT_Pos - 4U)) | ((Seconds & 0x0FU) << RTC_TIME_SECU_Pos)); + MODIFY_REG(RTCx->TIME, (RTC_TIME_TIMEFCFG | RTC_TIME_HRT | RTC_TIME_HRU | RTC_TIME_MINT | RTC_TIME_MINU | RTC_TIME_SECT | RTC_TIME_SECU), temp); +} + +/** + * @brief Get time (hour, minute and second) in BCD format + * @note if shadow mode is disabled (BYPSHAD=0), need to check if RSF flag is set + * before reading this bit + * @note Read either RTC_SUBSEC or RTC_TIME locks the values in the higher-order calendar + * shadow registers until RTC_DATE is read (DDL_RTC_ReadReg(RTC, DR)). + * @note helper macros __DDL_RTC_GET_HOUR, __DDL_RTC_GET_MINUTE and __DDL_RTC_GET_SECOND + * are available to get independently each parameter. + * @param RTCx RTC Instance + * @retval Combination of hours, minutes and seconds (Format: 0x00HHMMSS). + */ +__STATIC_INLINE uint32_t DDL_RTC_TIME_Get(RTC_TypeDef *RTCx) +{ + return (uint32_t)(READ_BIT(RTCx->TIME, (RTC_TIME_HRT | RTC_TIME_HRU | RTC_TIME_MINT | RTC_TIME_MINU | RTC_TIME_SECT | RTC_TIME_SECU))); +} + +/** + * @brief Memorize whether the daylight saving time change has been performed + * @note Bit is write-protected. @ref DDL_RTC_DisableWriteProtection function should be called before. + * @param RTCx RTC Instance + * @retval None + */ +__STATIC_INLINE void DDL_RTC_TIME_EnableDayLightStore(RTC_TypeDef *RTCx) +{ + SET_BIT(RTCx->CTRL, RTC_CTRL_BAKP); +} + +/** + * @brief Disable memorization whether the daylight saving time change has been performed. + * @note Bit is write-protected. @ref DDL_RTC_DisableWriteProtection function should be called before. + * @param RTCx RTC Instance + * @retval None + */ +__STATIC_INLINE void DDL_RTC_TIME_DisableDayLightStore(RTC_TypeDef *RTCx) +{ + CLEAR_BIT(RTCx->CTRL, RTC_CTRL_BAKP); +} + +/** + * @brief Check if RTC Day Light Saving stored operation has been enabled or not + * @param RTCx RTC Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_RTC_TIME_IsDayLightStoreEnabled(RTC_TypeDef *RTCx) +{ + return ((READ_BIT(RTCx->CTRL, RTC_CTRL_BAKP) == (RTC_CTRL_BAKP)) ? 1UL : 0UL); +} + +/** + * @brief Subtract 1 hour (winter time change) + * @note Bit is write-protected. @ref DDL_RTC_DisableWriteProtection function should be called before. + * @param RTCx RTC Instance + * @retval None + */ +__STATIC_INLINE void DDL_RTC_TIME_DecHour(RTC_TypeDef *RTCx) +{ + SET_BIT(RTCx->CTRL, RTC_CTRL_WTCCFG); +} + +/** + * @brief Add 1 hour (summer time change) + * @note Bit is write-protected. @ref DDL_RTC_DisableWriteProtection function should be called before. + * @param RTCx RTC Instance + * @retval None + */ +__STATIC_INLINE void DDL_RTC_TIME_IncHour(RTC_TypeDef *RTCx) +{ + SET_BIT(RTCx->CTRL, RTC_CTRL_STCCFG); +} + +/** + * @brief Get subseconds value in the synchronous prescaler counter. + * @note You can use both SubSeconds value and SecondFraction (PREDIV_S through + * DDL_RTC_GetSynchPrescaler function) terms returned to convert Calendar + * SubSeconds value in second fraction ratio with time unit following + * generic formula: + * ==> Seconds fraction ratio * time_unit = + * [(SecondFraction-SubSeconds)/(SecondFraction+1)] * time_unit + * This conversion can be performed only if no shift operation is pending + * (ie. SHFP=0) when PREDIV_S >= SS. + * @param RTCx RTC Instance + * @retval Subseconds value (number between 0 and 65535) + */ +__STATIC_INLINE uint32_t DDL_RTC_TIME_GetSubSecond(RTC_TypeDef *RTCx) +{ + return (uint32_t)(READ_BIT(RTCx->SUBSEC, RTC_SUBSEC_SUBSEC)); +} + +/** + * @brief Synchronize to a remote clock with a high degree of precision. + * @note This operation effectively subtracts from (delays) or advance the clock of a fraction of a second. + * @note Bit is write-protected. @ref DDL_RTC_DisableWriteProtection function should be called before. + * @note When REFCKON is set, firmware must not write to Shift control register. + * @param RTCx RTC Instance + * @param ShiftSecond This parameter can be one of the following values: + * @arg @ref DDL_RTC_SHIFT_SECOND_DELAY + * @arg @ref DDL_RTC_SHIFT_SECOND_ADVANCE + * @param Fraction Number of Seconds Fractions (any value from 0 to 0x7FFF) + * @retval None + */ +__STATIC_INLINE void DDL_RTC_TIME_Synchronize(RTC_TypeDef *RTCx, uint32_t ShiftSecond, uint32_t Fraction) +{ + WRITE_REG(RTCx->SHIFT, ShiftSecond | Fraction); +} + +/** + * @} + */ + +/** @defgroup RTC_DDL_EF_Date Date + * @{ + */ + +/** + * @brief Set Year in BCD format + * @note helper macro __DDL_RTC_CONVERT_BIN2BCD is available to convert Year from binary to BCD format + * @param RTCx RTC Instance + * @param Year Value between Min_Data=0x00 and Max_Data=0x99 + * @retval None + */ +__STATIC_INLINE void DDL_RTC_DATE_SetYear(RTC_TypeDef *RTCx, uint32_t Year) +{ + MODIFY_REG(RTCx->DATE, (RTC_DATE_YRT | RTC_DATE_YRU), + (((Year & 0xF0U) << (RTC_DATE_YRT_Pos - 4U)) | ((Year & 0x0FU) << RTC_DATE_YRU_Pos))); +} + +/** + * @brief Get Year in BCD format + * @note if shadow mode is disabled (BYPSHAD=0), need to check if RSF flag is set + * before reading this bit + * @note helper macro __DDL_RTC_CONVERT_BCD2BIN is available to convert Year from BCD to Binary format + * @param RTCx RTC Instance + * @retval Value between Min_Data=0x00 and Max_Data=0x99 + */ +__STATIC_INLINE uint32_t DDL_RTC_DATE_GetYear(RTC_TypeDef *RTCx) +{ + return (uint32_t)((READ_BIT(RTCx->DATE, (RTC_DATE_YRT | RTC_DATE_YRU))) >> RTC_DATE_YRU_Pos); +} + +/** + * @brief Set Week day + * @param RTCx RTC Instance + * @param WeekDay This parameter can be one of the following values: + * @arg @ref DDL_RTC_WEEKDAY_MONDAY + * @arg @ref DDL_RTC_WEEKDAY_TUESDAY + * @arg @ref DDL_RTC_WEEKDAY_WEDNESDAY + * @arg @ref DDL_RTC_WEEKDAY_THURSDAY + * @arg @ref DDL_RTC_WEEKDAY_FRIDAY + * @arg @ref DDL_RTC_WEEKDAY_SATURDAY + * @arg @ref DDL_RTC_WEEKDAY_SUNDAY + * @retval None + */ +__STATIC_INLINE void DDL_RTC_DATE_SetWeekDay(RTC_TypeDef *RTCx, uint32_t WeekDay) +{ + MODIFY_REG(RTCx->DATE, RTC_DATE_WEEKSEL, WeekDay << RTC_DATE_WEEKSEL_Pos); +} + +/** + * @brief Get Week day + * @note if shadow mode is disabled (BYPSHAD=0), need to check if RSF flag is set + * before reading this bit + * @param RTCx RTC Instance + * @retval Returned value can be one of the following values: + * @arg @ref DDL_RTC_WEEKDAY_MONDAY + * @arg @ref DDL_RTC_WEEKDAY_TUESDAY + * @arg @ref DDL_RTC_WEEKDAY_WEDNESDAY + * @arg @ref DDL_RTC_WEEKDAY_THURSDAY + * @arg @ref DDL_RTC_WEEKDAY_FRIDAY + * @arg @ref DDL_RTC_WEEKDAY_SATURDAY + * @arg @ref DDL_RTC_WEEKDAY_SUNDAY + */ +__STATIC_INLINE uint32_t DDL_RTC_DATE_GetWeekDay(RTC_TypeDef *RTCx) +{ + return (uint32_t)(READ_BIT(RTCx->DATE, RTC_DATE_WEEKSEL) >> RTC_DATE_WEEKSEL_Pos); +} + +/** + * @brief Set Month in BCD format + * @note helper macro __DDL_RTC_CONVERT_BIN2BCD is available to convert Month from binary to BCD format + * @param RTCx RTC Instance + * @param Month This parameter can be one of the following values: + * @arg @ref DDL_RTC_MONTH_JANUARY + * @arg @ref DDL_RTC_MONTH_FEBRUARY + * @arg @ref DDL_RTC_MONTH_MARCH + * @arg @ref DDL_RTC_MONTH_APRIL + * @arg @ref DDL_RTC_MONTH_MAY + * @arg @ref DDL_RTC_MONTH_JUNE + * @arg @ref DDL_RTC_MONTH_JULY + * @arg @ref DDL_RTC_MONTH_AUGUST + * @arg @ref DDL_RTC_MONTH_SEPTEMBER + * @arg @ref DDL_RTC_MONTH_OCTOBER + * @arg @ref DDL_RTC_MONTH_NOVEMBER + * @arg @ref DDL_RTC_MONTH_DECEMBER + * @retval None + */ +__STATIC_INLINE void DDL_RTC_DATE_SetMonth(RTC_TypeDef *RTCx, uint32_t Month) +{ + MODIFY_REG(RTCx->DATE, (RTC_DATE_MONT | RTC_DATE_MONU), + (((Month & 0xF0U) << (RTC_DATE_MONT_Pos - 4U)) | ((Month & 0x0FU) << RTC_DATE_MONU_Pos))); +} + +/** + * @brief Get Month in BCD format + * @note if shadow mode is disabled (BYPSHAD=0), need to check if RSF flag is set + * before reading this bit + * @note helper macro __DDL_RTC_CONVERT_BCD2BIN is available to convert Month from BCD to Binary format + * @param RTCx RTC Instance + * @retval Returned value can be one of the following values: + * @arg @ref DDL_RTC_MONTH_JANUARY + * @arg @ref DDL_RTC_MONTH_FEBRUARY + * @arg @ref DDL_RTC_MONTH_MARCH + * @arg @ref DDL_RTC_MONTH_APRIL + * @arg @ref DDL_RTC_MONTH_MAY + * @arg @ref DDL_RTC_MONTH_JUNE + * @arg @ref DDL_RTC_MONTH_JULY + * @arg @ref DDL_RTC_MONTH_AUGUST + * @arg @ref DDL_RTC_MONTH_SEPTEMBER + * @arg @ref DDL_RTC_MONTH_OCTOBER + * @arg @ref DDL_RTC_MONTH_NOVEMBER + * @arg @ref DDL_RTC_MONTH_DECEMBER + */ +__STATIC_INLINE uint32_t DDL_RTC_DATE_GetMonth(RTC_TypeDef *RTCx) +{ + return (uint32_t)((READ_BIT(RTCx->DATE, (RTC_DATE_MONT | RTC_DATE_MONU))) >> RTC_DATE_MONU_Pos); +} + +/** + * @brief Set Day in BCD format + * @note helper macro __DDL_RTC_CONVERT_BIN2BCD is available to convert Day from binary to BCD format + * @param RTCx RTC Instance + * @param Day Value between Min_Data=0x01 and Max_Data=0x31 + * @retval None + */ +__STATIC_INLINE void DDL_RTC_DATE_SetDay(RTC_TypeDef *RTCx, uint32_t Day) +{ + MODIFY_REG(RTCx->DATE, (RTC_DATE_DAYT | RTC_DATE_DAYU), + (((Day & 0xF0U) << (RTC_DATE_DAYT_Pos - 4U)) | ((Day & 0x0FU) << RTC_DATE_DAYU_Pos))); +} + +/** + * @brief Get Day in BCD format + * @note if shadow mode is disabled (BYPSHAD=0), need to check if RSF flag is set + * before reading this bit + * @note helper macro __DDL_RTC_CONVERT_BCD2BIN is available to convert Day from BCD to Binary format + * @param RTCx RTC Instance + * @retval Value between Min_Data=0x01 and Max_Data=0x31 + */ +__STATIC_INLINE uint32_t DDL_RTC_DATE_GetDay(RTC_TypeDef *RTCx) +{ + return (uint32_t)((READ_BIT(RTCx->DATE, (RTC_DATE_DAYT | RTC_DATE_DAYU))) >> RTC_DATE_DAYU_Pos); +} + +/** + * @brief Set date (WeekDay, Day, Month and Year) in BCD format + * @param RTCx RTC Instance + * @param WeekDay This parameter can be one of the following values: + * @arg @ref DDL_RTC_WEEKDAY_MONDAY + * @arg @ref DDL_RTC_WEEKDAY_TUESDAY + * @arg @ref DDL_RTC_WEEKDAY_WEDNESDAY + * @arg @ref DDL_RTC_WEEKDAY_THURSDAY + * @arg @ref DDL_RTC_WEEKDAY_FRIDAY + * @arg @ref DDL_RTC_WEEKDAY_SATURDAY + * @arg @ref DDL_RTC_WEEKDAY_SUNDAY + * @param Day Value between Min_Data=0x01 and Max_Data=0x31 + * @param Month This parameter can be one of the following values: + * @arg @ref DDL_RTC_MONTH_JANUARY + * @arg @ref DDL_RTC_MONTH_FEBRUARY + * @arg @ref DDL_RTC_MONTH_MARCH + * @arg @ref DDL_RTC_MONTH_APRIL + * @arg @ref DDL_RTC_MONTH_MAY + * @arg @ref DDL_RTC_MONTH_JUNE + * @arg @ref DDL_RTC_MONTH_JULY + * @arg @ref DDL_RTC_MONTH_AUGUST + * @arg @ref DDL_RTC_MONTH_SEPTEMBER + * @arg @ref DDL_RTC_MONTH_OCTOBER + * @arg @ref DDL_RTC_MONTH_NOVEMBER + * @arg @ref DDL_RTC_MONTH_DECEMBER + * @param Year Value between Min_Data=0x00 and Max_Data=0x99 + * @retval None + */ +__STATIC_INLINE void DDL_RTC_DATE_Config(RTC_TypeDef *RTCx, uint32_t WeekDay, uint32_t Day, uint32_t Month, uint32_t Year) +{ + uint32_t temp; + + temp = ( WeekDay << RTC_DATE_WEEKSEL_Pos) | \ + (((Year & 0xF0U) << (RTC_DATE_YRT_Pos - 4U)) | ((Year & 0x0FU) << RTC_DATE_YRU_Pos)) | \ + (((Month & 0xF0U) << (RTC_DATE_MONT_Pos - 4U)) | ((Month & 0x0FU) << RTC_DATE_MONU_Pos)) | \ + (((Day & 0xF0U) << (RTC_DATE_DAYT_Pos - 4U)) | ((Day & 0x0FU) << RTC_DATE_DAYU_Pos)); + + MODIFY_REG(RTCx->DATE, (RTC_DATE_WEEKSEL | RTC_DATE_MONT | RTC_DATE_MONU | RTC_DATE_DAYT | RTC_DATE_DAYU | RTC_DATE_YRT | RTC_DATE_YRU), temp); +} + +/** + * @brief Get date (WeekDay, Day, Month and Year) in BCD format + * @note if shadow mode is disabled (BYPSHAD=0), need to check if RSF flag is set + * before reading this bit + * @note helper macros __DDL_RTC_GET_WEEKDAY, __DDL_RTC_GET_YEAR, __DDL_RTC_GET_MONTH, + * and __DDL_RTC_GET_DAY are available to get independently each parameter. + * @param RTCx RTC Instance + * @retval Combination of WeekDay, Day, Month and Year (Format: 0xWWDDMMYY). + */ +__STATIC_INLINE uint32_t DDL_RTC_DATE_Get(RTC_TypeDef *RTCx) +{ + uint32_t temp; + + temp = READ_BIT(RTCx->DATE, (RTC_DATE_WEEKSEL | RTC_DATE_MONT | RTC_DATE_MONU | RTC_DATE_DAYT | RTC_DATE_DAYU | RTC_DATE_YRT | RTC_DATE_YRU)); + + return (uint32_t)((((temp & RTC_DATE_WEEKSEL) >> RTC_DATE_WEEKSEL_Pos) << RTC_OFFSET_WEEKDAY) | \ + (((temp & (RTC_DATE_DAYT | RTC_DATE_DAYU)) >> RTC_DATE_DAYU_Pos) << RTC_OFFSET_DAY) | \ + (((temp & (RTC_DATE_MONT | RTC_DATE_MONU)) >> RTC_DATE_MONU_Pos) << RTC_OFFSET_MONTH) | \ + ((temp & (RTC_DATE_YRT | RTC_DATE_YRU)) >> RTC_DATE_YRU_Pos)); +} + +/** + * @} + */ + +/** @defgroup RTC_DDL_EF_ALARMA ALARMA + * @{ + */ + +/** + * @brief Enable Alarm A + * @note Bit is write-protected. @ref DDL_RTC_DisableWriteProtection function should be called before. + * @param RTCx RTC Instance + * @retval None + */ +__STATIC_INLINE void DDL_RTC_ALMA_Enable(RTC_TypeDef *RTCx) +{ + SET_BIT(RTCx->CTRL, RTC_CTRL_ALRAEN); +} + +/** + * @brief Disable Alarm A + * @note Bit is write-protected. @ref DDL_RTC_DisableWriteProtection function should be called before. + * @param RTCx RTC Instance + * @retval None + */ +__STATIC_INLINE void DDL_RTC_ALMA_Disable(RTC_TypeDef *RTCx) +{ + CLEAR_BIT(RTCx->CTRL, RTC_CTRL_ALRAEN); +} + +/** + * @brief Specify the Alarm A masks. + * @param RTCx RTC Instance + * @param Mask This parameter can be a combination of the following values: + * @arg @ref DDL_RTC_ALMA_MASK_NONE + * @arg @ref DDL_RTC_ALMA_MASK_DATEWEEKDAY + * @arg @ref DDL_RTC_ALMA_MASK_HOURS + * @arg @ref DDL_RTC_ALMA_MASK_MINUTES + * @arg @ref DDL_RTC_ALMA_MASK_SECONDS + * @arg @ref DDL_RTC_ALMA_MASK_ALL + * @retval None + */ +__STATIC_INLINE void DDL_RTC_ALMA_SetMask(RTC_TypeDef *RTCx, uint32_t Mask) +{ + MODIFY_REG(RTCx->ALRMA, RTC_ALRMA_DATEMEN | RTC_ALRMA_HRMEN | RTC_ALRMA_MINMEN | RTC_ALRMA_SECMEN, Mask); +} + +/** + * @brief Get the Alarm A masks. + * @param RTCx RTC Instance + * @retval Returned value can be can be a combination of the following values: + * @arg @ref DDL_RTC_ALMA_MASK_NONE + * @arg @ref DDL_RTC_ALMA_MASK_DATEWEEKDAY + * @arg @ref DDL_RTC_ALMA_MASK_HOURS + * @arg @ref DDL_RTC_ALMA_MASK_MINUTES + * @arg @ref DDL_RTC_ALMA_MASK_SECONDS + * @arg @ref DDL_RTC_ALMA_MASK_ALL + */ +__STATIC_INLINE uint32_t DDL_RTC_ALMA_GetMask(RTC_TypeDef *RTCx) +{ + return (uint32_t)(READ_BIT(RTCx->ALRMA, RTC_ALRMA_DATEMEN | RTC_ALRMA_HRMEN | RTC_ALRMA_MINMEN | RTC_ALRMA_SECMEN)); +} + +/** + * @brief Enable AlarmA Week day selection (DU[3:0] represents the week day. DT[1:0] is do not care) + * @param RTCx RTC Instance + * @retval None + */ +__STATIC_INLINE void DDL_RTC_ALMA_EnableWeekday(RTC_TypeDef *RTCx) +{ + SET_BIT(RTCx->ALRMA, RTC_ALRMA_WEEKSEL); +} + +/** + * @brief Disable AlarmA Week day selection (DU[3:0] represents the date ) + * @param RTCx RTC Instance + * @retval None + */ +__STATIC_INLINE void DDL_RTC_ALMA_DisableWeekday(RTC_TypeDef *RTCx) +{ + CLEAR_BIT(RTCx->ALRMA, RTC_ALRMA_WEEKSEL); +} + +/** + * @brief Set ALARM A Day in BCD format + * @note helper macro __DDL_RTC_CONVERT_BIN2BCD is available to convert Day from binary to BCD format + * @param RTCx RTC Instance + * @param Day Value between Min_Data=0x01 and Max_Data=0x31 + * @retval None + */ +__STATIC_INLINE void DDL_RTC_ALMA_SetDay(RTC_TypeDef *RTCx, uint32_t Day) +{ + MODIFY_REG(RTCx->ALRMA, (RTC_ALRMA_DAYT | RTC_ALRMA_DAYU), + (((Day & 0xF0U) << (RTC_ALRMA_DAYT_Pos - 4U)) | ((Day & 0x0FU) << RTC_ALRMA_DAYU_Pos))); +} + +/** + * @brief Get ALARM A Day in BCD format + * @note helper macro __DDL_RTC_CONVERT_BCD2BIN is available to convert Day from BCD to Binary format + * @param RTCx RTC Instance + * @retval Value between Min_Data=0x01 and Max_Data=0x31 + */ +__STATIC_INLINE uint32_t DDL_RTC_ALMA_GetDay(RTC_TypeDef *RTCx) +{ + return (uint32_t)((READ_BIT(RTCx->ALRMA, (RTC_ALRMA_DAYT | RTC_ALRMA_DAYU))) >> RTC_ALRMA_DAYU_Pos); +} + +/** + * @brief Set ALARM A Weekday + * @param RTCx RTC Instance + * @param WeekDay This parameter can be one of the following values: + * @arg @ref DDL_RTC_WEEKDAY_MONDAY + * @arg @ref DDL_RTC_WEEKDAY_TUESDAY + * @arg @ref DDL_RTC_WEEKDAY_WEDNESDAY + * @arg @ref DDL_RTC_WEEKDAY_THURSDAY + * @arg @ref DDL_RTC_WEEKDAY_FRIDAY + * @arg @ref DDL_RTC_WEEKDAY_SATURDAY + * @arg @ref DDL_RTC_WEEKDAY_SUNDAY + * @retval None + */ +__STATIC_INLINE void DDL_RTC_ALMA_SetWeekDay(RTC_TypeDef *RTCx, uint32_t WeekDay) +{ + MODIFY_REG(RTCx->ALRMA, RTC_ALRMA_DAYU, WeekDay << RTC_ALRMA_DAYU_Pos); +} + +/** + * @brief Get ALARM A Weekday + * @param RTCx RTC Instance + * @retval Returned value can be one of the following values: + * @arg @ref DDL_RTC_WEEKDAY_MONDAY + * @arg @ref DDL_RTC_WEEKDAY_TUESDAY + * @arg @ref DDL_RTC_WEEKDAY_WEDNESDAY + * @arg @ref DDL_RTC_WEEKDAY_THURSDAY + * @arg @ref DDL_RTC_WEEKDAY_FRIDAY + * @arg @ref DDL_RTC_WEEKDAY_SATURDAY + * @arg @ref DDL_RTC_WEEKDAY_SUNDAY + */ +__STATIC_INLINE uint32_t DDL_RTC_ALMA_GetWeekDay(RTC_TypeDef *RTCx) +{ + return (uint32_t)(READ_BIT(RTCx->ALRMA, RTC_ALRMA_DAYU) >> RTC_ALRMA_DAYU_Pos); +} + +/** + * @brief Set Alarm A time format (AM/24-hour or PM notation) + * @param RTCx RTC Instance + * @param TimeFormat This parameter can be one of the following values: + * @arg @ref DDL_RTC_ALMA_TIME_FORMAT_AM + * @arg @ref DDL_RTC_ALMA_TIME_FORMAT_PM + * @retval None + */ +__STATIC_INLINE void DDL_RTC_ALMA_SetTimeFormat(RTC_TypeDef *RTCx, uint32_t TimeFormat) +{ + MODIFY_REG(RTCx->ALRMA, RTC_ALRMA_TIMEFCFG, TimeFormat); +} + +/** + * @brief Get Alarm A time format (AM or PM notation) + * @param RTCx RTC Instance + * @retval Returned value can be one of the following values: + * @arg @ref DDL_RTC_ALMA_TIME_FORMAT_AM + * @arg @ref DDL_RTC_ALMA_TIME_FORMAT_PM + */ +__STATIC_INLINE uint32_t DDL_RTC_ALMA_GetTimeFormat(RTC_TypeDef *RTCx) +{ + return (uint32_t)(READ_BIT(RTCx->ALRMA, RTC_ALRMA_TIMEFCFG)); +} + +/** + * @brief Set ALARM A Hours in BCD format + * @note helper macro __DDL_RTC_CONVERT_BIN2BCD is available to convert Hours from binary to BCD format + * @param RTCx RTC Instance + * @param Hours Value between Min_Data=0x01 and Max_Data=0x12 or between Min_Data=0x00 and Max_Data=0x23 + * @retval None + */ +__STATIC_INLINE void DDL_RTC_ALMA_SetHour(RTC_TypeDef *RTCx, uint32_t Hours) +{ + MODIFY_REG(RTCx->ALRMA, (RTC_ALRMA_HRT | RTC_ALRMA_HRU), + (((Hours & 0xF0U) << (RTC_ALRMA_HRT_Pos - 4U)) | ((Hours & 0x0FU) << RTC_ALRMA_HRU_Pos))); +} + +/** + * @brief Get ALARM A Hours in BCD format + * @note helper macro __DDL_RTC_CONVERT_BCD2BIN is available to convert Hours from BCD to Binary format + * @param RTCx RTC Instance + * @retval Value between Min_Data=0x01 and Max_Data=0x12 or between Min_Data=0x00 and Max_Data=0x23 + */ +__STATIC_INLINE uint32_t DDL_RTC_ALMA_GetHour(RTC_TypeDef *RTCx) +{ + return (uint32_t)((READ_BIT(RTCx->ALRMA, (RTC_ALRMA_HRT | RTC_ALRMA_HRU))) >> RTC_ALRMA_HRU_Pos); +} + +/** + * @brief Set ALARM A Minutes in BCD format + * @note helper macro __DDL_RTC_CONVERT_BIN2BCD is available to convert Minutes from binary to BCD format + * @param RTCx RTC Instance + * @param Minutes Value between Min_Data=0x00 and Max_Data=0x59 + * @retval None + */ +__STATIC_INLINE void DDL_RTC_ALMA_SetMinute(RTC_TypeDef *RTCx, uint32_t Minutes) +{ + MODIFY_REG(RTCx->ALRMA, (RTC_ALRMA_MINT | RTC_ALRMA_MINU), + (((Minutes & 0xF0U) << (RTC_ALRMA_MINT_Pos - 4U)) | ((Minutes & 0x0FU) << RTC_ALRMA_MINU_Pos))); +} + +/** + * @brief Get ALARM A Minutes in BCD format + * @note helper macro __DDL_RTC_CONVERT_BCD2BIN is available to convert Minutes from BCD to Binary format + * @param RTCx RTC Instance + * @retval Value between Min_Data=0x00 and Max_Data=0x59 + */ +__STATIC_INLINE uint32_t DDL_RTC_ALMA_GetMinute(RTC_TypeDef *RTCx) +{ + return (uint32_t)((READ_BIT(RTCx->ALRMA, (RTC_ALRMA_MINT | RTC_ALRMA_MINU))) >> RTC_ALRMA_MINU_Pos); +} + +/** + * @brief Set ALARM A Seconds in BCD format + * @note helper macro __DDL_RTC_CONVERT_BIN2BCD is available to convert Seconds from binary to BCD format + * @param RTCx RTC Instance + * @param Seconds Value between Min_Data=0x00 and Max_Data=0x59 + * @retval None + */ +__STATIC_INLINE void DDL_RTC_ALMA_SetSecond(RTC_TypeDef *RTCx, uint32_t Seconds) +{ + MODIFY_REG(RTCx->ALRMA, (RTC_ALRMA_SECT | RTC_ALRMA_SECU), + (((Seconds & 0xF0U) << (RTC_ALRMA_SECT_Pos - 4U)) | ((Seconds & 0x0FU) << RTC_ALRMA_SECU_Pos))); +} + +/** + * @brief Get ALARM A Seconds in BCD format + * @note helper macro __DDL_RTC_CONVERT_BCD2BIN is available to convert Seconds from BCD to Binary format + * @param RTCx RTC Instance + * @retval Value between Min_Data=0x00 and Max_Data=0x59 + */ +__STATIC_INLINE uint32_t DDL_RTC_ALMA_GetSecond(RTC_TypeDef *RTCx) +{ + return (uint32_t)((READ_BIT(RTCx->ALRMA, (RTC_ALRMA_SECT | RTC_ALRMA_SECU))) >> RTC_ALRMA_SECU_Pos); +} + +/** + * @brief Set Alarm A Time (hour, minute and second) in BCD format + * @param RTCx RTC Instance + * @param Format12_24 This parameter can be one of the following values: + * @arg @ref DDL_RTC_ALMA_TIME_FORMAT_AM + * @arg @ref DDL_RTC_ALMA_TIME_FORMAT_PM + * @param Hours Value between Min_Data=0x01 and Max_Data=0x12 or between Min_Data=0x00 and Max_Data=0x23 + * @param Minutes Value between Min_Data=0x00 and Max_Data=0x59 + * @param Seconds Value between Min_Data=0x00 and Max_Data=0x59 + * @retval None + */ +__STATIC_INLINE void DDL_RTC_ALMA_ConfigTime(RTC_TypeDef *RTCx, uint32_t Format12_24, uint32_t Hours, uint32_t Minutes, uint32_t Seconds) +{ + uint32_t temp; + + temp = Format12_24 | \ + (((Hours & 0xF0U) << (RTC_ALRMA_HRT_Pos - 4U)) | ((Hours & 0x0FU) << RTC_ALRMA_HRU_Pos)) | \ + (((Minutes & 0xF0U) << (RTC_ALRMA_MINT_Pos - 4U)) | ((Minutes & 0x0FU) << RTC_ALRMA_MINU_Pos)) | \ + (((Seconds & 0xF0U) << (RTC_ALRMA_SECT_Pos - 4U)) | ((Seconds & 0x0FU) << RTC_ALRMA_SECU_Pos)); + + MODIFY_REG(RTCx->ALRMA, RTC_ALRMA_TIMEFCFG | RTC_ALRMA_HRT | RTC_ALRMA_HRU | RTC_ALRMA_MINT | RTC_ALRMA_MINU | RTC_ALRMA_SECT | RTC_ALRMA_SECU, temp); +} + +/** + * @brief Get Alarm B Time (hour, minute and second) in BCD format + * @note helper macros __DDL_RTC_GET_HOUR, __DDL_RTC_GET_MINUTE and __DDL_RTC_GET_SECOND + * are available to get independently each parameter. + * @param RTCx RTC Instance + * @retval Combination of hours, minutes and seconds. + */ +__STATIC_INLINE uint32_t DDL_RTC_ALMA_GetTime(RTC_TypeDef *RTCx) +{ + return (uint32_t)((DDL_RTC_ALMA_GetHour(RTCx) << RTC_OFFSET_HOUR) | (DDL_RTC_ALMA_GetMinute(RTCx) << RTC_OFFSET_MINUTE) | DDL_RTC_ALMA_GetSecond(RTCx)); +} + +/** + * @brief Mask the most-significant bits of the subseconds field starting from + * the bit specified in parameter Mask + * @note This register can be written only when ALRAE is reset in RTC_CTRL register, + * or in initialization mode. + * @param RTCx RTC Instance + * @param Mask Value between Min_Data=0x00 and Max_Data=0xF + * @retval None + */ +__STATIC_INLINE void DDL_RTC_ALMA_SetSubSecondMask(RTC_TypeDef *RTCx, uint32_t Mask) +{ + MODIFY_REG(RTCx->ALRMASS, RTC_ALRMASS_MASKSEL, Mask << RTC_ALRMASS_MASKSEL_Pos); +} + +/** + * @brief Get Alarm A subseconds mask + * @param RTCx RTC Instance + * @retval Value between Min_Data=0x00 and Max_Data=0xF + */ +__STATIC_INLINE uint32_t DDL_RTC_ALMA_GetSubSecondMask(RTC_TypeDef *RTCx) +{ + return (uint32_t)(READ_BIT(RTCx->ALRMASS, RTC_ALRMASS_MASKSEL) >> RTC_ALRMASS_MASKSEL_Pos); +} + +/** + * @brief Set Alarm A subseconds value + * @param RTCx RTC Instance + * @param Subsecond Value between Min_Data=0x00 and Max_Data=0x7FFF + * @retval None + */ +__STATIC_INLINE void DDL_RTC_ALMA_SetSubSecond(RTC_TypeDef *RTCx, uint32_t Subsecond) +{ + MODIFY_REG(RTCx->ALRMASS, RTC_ALRMASS_SUBSEC, Subsecond); +} + +/** + * @brief Get Alarm A subseconds value + * @param RTCx RTC Instance + * @retval Value between Min_Data=0x00 and Max_Data=0x7FFF + */ +__STATIC_INLINE uint32_t DDL_RTC_ALMA_GetSubSecond(RTC_TypeDef *RTCx) +{ + return (uint32_t)(READ_BIT(RTCx->ALRMASS, RTC_ALRMASS_SUBSEC)); +} + +/** + * @} + */ + +/** @defgroup RTC_DDL_EF_ALARMB ALARMB + * @{ + */ + +/** + * @brief Enable Alarm B + * @note Bit is write-protected. @ref DDL_RTC_DisableWriteProtection function should be called before. + * @param RTCx RTC Instance + * @retval None + */ +__STATIC_INLINE void DDL_RTC_ALMB_Enable(RTC_TypeDef *RTCx) +{ + SET_BIT(RTCx->CTRL, RTC_CTRL_ALRBEN); +} + +/** + * @brief Disable Alarm B + * @note Bit is write-protected. @ref DDL_RTC_DisableWriteProtection function should be called before. + * @param RTCx RTC Instance + * @retval None + */ +__STATIC_INLINE void DDL_RTC_ALMB_Disable(RTC_TypeDef *RTCx) +{ + CLEAR_BIT(RTCx->CTRL, RTC_CTRL_ALRBEN); +} + +/** + * @brief Specify the Alarm B masks. + * @param RTCx RTC Instance + * @param Mask This parameter can be a combination of the following values: + * @arg @ref DDL_RTC_ALMB_MASK_NONE + * @arg @ref DDL_RTC_ALMB_MASK_DATEWEEKDAY + * @arg @ref DDL_RTC_ALMB_MASK_HOURS + * @arg @ref DDL_RTC_ALMB_MASK_MINUTES + * @arg @ref DDL_RTC_ALMB_MASK_SECONDS + * @arg @ref DDL_RTC_ALMB_MASK_ALL + * @retval None + */ +__STATIC_INLINE void DDL_RTC_ALMB_SetMask(RTC_TypeDef *RTCx, uint32_t Mask) +{ + MODIFY_REG(RTCx->ALRMB, RTC_ALRMB_DATEMEN | RTC_ALRMB_HRMEN | RTC_ALRMB_MINMEN | RTC_ALRMB_SECMEN, Mask); +} + +/** + * @brief Get the Alarm B masks. + * @param RTCx RTC Instance + * @retval Returned value can be can be a combination of the following values: + * @arg @ref DDL_RTC_ALMB_MASK_NONE + * @arg @ref DDL_RTC_ALMB_MASK_DATEWEEKDAY + * @arg @ref DDL_RTC_ALMB_MASK_HOURS + * @arg @ref DDL_RTC_ALMB_MASK_MINUTES + * @arg @ref DDL_RTC_ALMB_MASK_SECONDS + * @arg @ref DDL_RTC_ALMB_MASK_ALL + */ +__STATIC_INLINE uint32_t DDL_RTC_ALMB_GetMask(RTC_TypeDef *RTCx) +{ + return (uint32_t)(READ_BIT(RTCx->ALRMB, RTC_ALRMB_DATEMEN | RTC_ALRMB_HRMEN | RTC_ALRMB_MINMEN | RTC_ALRMB_SECMEN)); +} + +/** + * @brief Enable AlarmB Week day selection (DU[3:0] represents the week day. DT[1:0] is do not care) + * @param RTCx RTC Instance + * @retval None + */ +__STATIC_INLINE void DDL_RTC_ALMB_EnableWeekday(RTC_TypeDef *RTCx) +{ + SET_BIT(RTCx->ALRMB, RTC_ALRMB_WEEKSEL); +} + +/** + * @brief Disable AlarmB Week day selection (DU[3:0] represents the date ) + * @param RTCx RTC Instance + * @retval None + */ +__STATIC_INLINE void DDL_RTC_ALMB_DisableWeekday(RTC_TypeDef *RTCx) +{ + CLEAR_BIT(RTCx->ALRMB, RTC_ALRMB_WEEKSEL); +} + +/** + * @brief Set ALARM B Day in BCD format + * @note helper macro __DDL_RTC_CONVERT_BIN2BCD is available to convert Day from binary to BCD format + * @param RTCx RTC Instance + * @param Day Value between Min_Data=0x01 and Max_Data=0x31 + * @retval None + */ +__STATIC_INLINE void DDL_RTC_ALMB_SetDay(RTC_TypeDef *RTCx, uint32_t Day) +{ + MODIFY_REG(RTCx->ALRMB, (RTC_ALRMB_DAYT | RTC_ALRMB_DAYU), + (((Day & 0xF0U) << (RTC_ALRMB_DAYT_Pos - 4U)) | ((Day & 0x0FU) << RTC_ALRMB_DAYU_Pos))); +} + +/** + * @brief Get ALARM B Day in BCD format + * @note helper macro __DDL_RTC_CONVERT_BCD2BIN is available to convert Day from BCD to Binary format + * @param RTCx RTC Instance + * @retval Value between Min_Data=0x01 and Max_Data=0x31 + */ +__STATIC_INLINE uint32_t DDL_RTC_ALMB_GetDay(RTC_TypeDef *RTCx) +{ + return (uint32_t)((READ_BIT(RTCx->ALRMB, (RTC_ALRMB_DAYT | RTC_ALRMB_DAYU))) >> RTC_ALRMB_DAYU_Pos); +} + +/** + * @brief Set ALARM B Weekday + * @param RTCx RTC Instance + * @param WeekDay This parameter can be one of the following values: + * @arg @ref DDL_RTC_WEEKDAY_MONDAY + * @arg @ref DDL_RTC_WEEKDAY_TUESDAY + * @arg @ref DDL_RTC_WEEKDAY_WEDNESDAY + * @arg @ref DDL_RTC_WEEKDAY_THURSDAY + * @arg @ref DDL_RTC_WEEKDAY_FRIDAY + * @arg @ref DDL_RTC_WEEKDAY_SATURDAY + * @arg @ref DDL_RTC_WEEKDAY_SUNDAY + * @retval None + */ +__STATIC_INLINE void DDL_RTC_ALMB_SetWeekDay(RTC_TypeDef *RTCx, uint32_t WeekDay) +{ + MODIFY_REG(RTCx->ALRMB, RTC_ALRMB_DAYU, WeekDay << RTC_ALRMB_DAYU_Pos); +} + +/** + * @brief Get ALARM B Weekday + * @param RTCx RTC Instance + * @retval Returned value can be one of the following values: + * @arg @ref DDL_RTC_WEEKDAY_MONDAY + * @arg @ref DDL_RTC_WEEKDAY_TUESDAY + * @arg @ref DDL_RTC_WEEKDAY_WEDNESDAY + * @arg @ref DDL_RTC_WEEKDAY_THURSDAY + * @arg @ref DDL_RTC_WEEKDAY_FRIDAY + * @arg @ref DDL_RTC_WEEKDAY_SATURDAY + * @arg @ref DDL_RTC_WEEKDAY_SUNDAY + */ +__STATIC_INLINE uint32_t DDL_RTC_ALMB_GetWeekDay(RTC_TypeDef *RTCx) +{ + return (uint32_t)(READ_BIT(RTCx->ALRMB, RTC_ALRMB_DAYU) >> RTC_ALRMB_DAYU_Pos); +} + +/** + * @brief Set ALARM B time format (AM/24-hour or PM notation) + * @param RTCx RTC Instance + * @param TimeFormat This parameter can be one of the following values: + * @arg @ref DDL_RTC_ALMB_TIME_FORMAT_AM + * @arg @ref DDL_RTC_ALMB_TIME_FORMAT_PM + * @retval None + */ +__STATIC_INLINE void DDL_RTC_ALMB_SetTimeFormat(RTC_TypeDef *RTCx, uint32_t TimeFormat) +{ + MODIFY_REG(RTCx->ALRMB, RTC_ALRMB_TIMEFCFG, TimeFormat); +} + +/** + * @brief Get ALARM B time format (AM or PM notation) + * @param RTCx RTC Instance + * @retval Returned value can be one of the following values: + * @arg @ref DDL_RTC_ALMB_TIME_FORMAT_AM + * @arg @ref DDL_RTC_ALMB_TIME_FORMAT_PM + */ +__STATIC_INLINE uint32_t DDL_RTC_ALMB_GetTimeFormat(RTC_TypeDef *RTCx) +{ + return (uint32_t)(READ_BIT(RTCx->ALRMB, RTC_ALRMB_TIMEFCFG)); +} + +/** + * @brief Set ALARM B Hours in BCD format + * @note helper macro __DDL_RTC_CONVERT_BIN2BCD is available to convert Hours from binary to BCD format + * @param RTCx RTC Instance + * @param Hours Value between Min_Data=0x01 and Max_Data=0x12 or between Min_Data=0x00 and Max_Data=0x23 + * @retval None + */ +__STATIC_INLINE void DDL_RTC_ALMB_SetHour(RTC_TypeDef *RTCx, uint32_t Hours) +{ + MODIFY_REG(RTCx->ALRMB, (RTC_ALRMB_HRT | RTC_ALRMB_HRU), + (((Hours & 0xF0U) << (RTC_ALRMB_HRT_Pos - 4U)) | ((Hours & 0x0FU) << RTC_ALRMB_HRU_Pos))); +} + +/** + * @brief Get ALARM B Hours in BCD format + * @note helper macro __DDL_RTC_CONVERT_BCD2BIN is available to convert Hours from BCD to Binary format + * @param RTCx RTC Instance + * @retval Value between Min_Data=0x01 and Max_Data=0x12 or between Min_Data=0x00 and Max_Data=0x23 + */ +__STATIC_INLINE uint32_t DDL_RTC_ALMB_GetHour(RTC_TypeDef *RTCx) +{ + return (uint32_t)((READ_BIT(RTCx->ALRMB, (RTC_ALRMB_HRT | RTC_ALRMB_HRU))) >> RTC_ALRMB_HRU_Pos); +} + +/** + * @brief Set ALARM B Minutes in BCD format + * @note helper macro __DDL_RTC_CONVERT_BIN2BCD is available to convert Minutes from binary to BCD format + * @param RTCx RTC Instance + * @param Minutes between Min_Data=0x00 and Max_Data=0x59 + * @retval None + */ +__STATIC_INLINE void DDL_RTC_ALMB_SetMinute(RTC_TypeDef *RTCx, uint32_t Minutes) +{ + MODIFY_REG(RTCx->ALRMB, (RTC_ALRMB_MINT | RTC_ALRMB_MINU), + (((Minutes & 0xF0U) << (RTC_ALRMB_MINT_Pos - 4U)) | ((Minutes & 0x0FU) << RTC_ALRMB_MINU_Pos))); +} + +/** + * @brief Get ALARM B Minutes in BCD format + * @note helper macro __DDL_RTC_CONVERT_BCD2BIN is available to convert Minutes from BCD to Binary format + * @param RTCx RTC Instance + * @retval Value between Min_Data=0x00 and Max_Data=0x59 + */ +__STATIC_INLINE uint32_t DDL_RTC_ALMB_GetMinute(RTC_TypeDef *RTCx) +{ + return (uint32_t)((READ_BIT(RTCx->ALRMB, (RTC_ALRMB_MINT | RTC_ALRMB_MINU))) >> RTC_ALRMB_MINU_Pos); +} + +/** + * @brief Set ALARM B Seconds in BCD format + * @note helper macro __DDL_RTC_CONVERT_BIN2BCD is available to convert Seconds from binary to BCD format + * @param RTCx RTC Instance + * @param Seconds Value between Min_Data=0x00 and Max_Data=0x59 + * @retval None + */ +__STATIC_INLINE void DDL_RTC_ALMB_SetSecond(RTC_TypeDef *RTCx, uint32_t Seconds) +{ + MODIFY_REG(RTCx->ALRMB, (RTC_ALRMB_SECT | RTC_ALRMB_SECU), + (((Seconds & 0xF0U) << (RTC_ALRMB_SECT_Pos - 4U)) | ((Seconds & 0x0FU) << RTC_ALRMB_SECU_Pos))); +} + +/** + * @brief Get ALARM B Seconds in BCD format + * @note helper macro __DDL_RTC_CONVERT_BCD2BIN is available to convert Seconds from BCD to Binary format + * @param RTCx RTC Instance + * @retval Value between Min_Data=0x00 and Max_Data=0x59 + */ +__STATIC_INLINE uint32_t DDL_RTC_ALMB_GetSecond(RTC_TypeDef *RTCx) +{ + return (uint32_t)((READ_BIT(RTCx->ALRMB, (RTC_ALRMB_SECT | RTC_ALRMB_SECU))) >> RTC_ALRMB_SECU_Pos); +} + +/** + * @brief Set Alarm B Time (hour, minute and second) in BCD format + * @param RTCx RTC Instance + * @param Format12_24 This parameter can be one of the following values: + * @arg @ref DDL_RTC_ALMB_TIME_FORMAT_AM + * @arg @ref DDL_RTC_ALMB_TIME_FORMAT_PM + * @param Hours Value between Min_Data=0x01 and Max_Data=0x12 or between Min_Data=0x00 and Max_Data=0x23 + * @param Minutes Value between Min_Data=0x00 and Max_Data=0x59 + * @param Seconds Value between Min_Data=0x00 and Max_Data=0x59 + * @retval None + */ +__STATIC_INLINE void DDL_RTC_ALMB_ConfigTime(RTC_TypeDef *RTCx, uint32_t Format12_24, uint32_t Hours, uint32_t Minutes, uint32_t Seconds) +{ + uint32_t temp; + + temp = Format12_24 | \ + (((Hours & 0xF0U) << (RTC_ALRMB_HRT_Pos - 4U)) | ((Hours & 0x0FU) << RTC_ALRMB_HRU_Pos)) | \ + (((Minutes & 0xF0U) << (RTC_ALRMB_MINT_Pos - 4U)) | ((Minutes & 0x0FU) << RTC_ALRMB_MINU_Pos)) | \ + (((Seconds & 0xF0U) << (RTC_ALRMB_SECT_Pos - 4U)) | ((Seconds & 0x0FU) << RTC_ALRMB_SECU_Pos)); + + MODIFY_REG(RTCx->ALRMB, RTC_ALRMB_TIMEFCFG | RTC_ALRMB_HRT | RTC_ALRMB_HRU | RTC_ALRMB_MINT | RTC_ALRMB_MINU | RTC_ALRMB_SECT | RTC_ALRMB_SECU, temp); +} + +/** + * @brief Get Alarm B Time (hour, minute and second) in BCD format + * @note helper macros __DDL_RTC_GET_HOUR, __DDL_RTC_GET_MINUTE and __DDL_RTC_GET_SECOND + * are available to get independently each parameter. + * @param RTCx RTC Instance + * @retval Combination of hours, minutes and seconds. + */ +__STATIC_INLINE uint32_t DDL_RTC_ALMB_GetTime(RTC_TypeDef *RTCx) +{ + return (uint32_t)((DDL_RTC_ALMB_GetHour(RTCx) << RTC_OFFSET_HOUR) | (DDL_RTC_ALMB_GetMinute(RTCx) << RTC_OFFSET_MINUTE) | DDL_RTC_ALMB_GetSecond(RTCx)); +} + +/** + * @brief Mask the most-significant bits of the subseconds field starting from + * the bit specified in parameter Mask + * @note This register can be written only when ALRBE is reset in RTC_CTRL register, + * or in initialization mode. + * @param RTCx RTC Instance + * @param Mask Value between Min_Data=0x00 and Max_Data=0xF + * @retval None + */ +__STATIC_INLINE void DDL_RTC_ALMB_SetSubSecondMask(RTC_TypeDef *RTCx, uint32_t Mask) +{ + MODIFY_REG(RTCx->ALRMBSS, RTC_ALRMBSS_MASKSEL, Mask << RTC_ALRMBSS_MASKSEL_Pos); +} + +/** + * @brief Get Alarm B subseconds mask + * @param RTCx RTC Instance + * @retval Value between Min_Data=0x00 and Max_Data=0xF + */ +__STATIC_INLINE uint32_t DDL_RTC_ALMB_GetSubSecondMask(RTC_TypeDef *RTCx) +{ + return (uint32_t)(READ_BIT(RTCx->ALRMBSS, RTC_ALRMBSS_MASKSEL) >> RTC_ALRMBSS_MASKSEL_Pos); +} + +/** + * @brief Set Alarm B subseconds value + * @param RTCx RTC Instance + * @param Subsecond Value between Min_Data=0x00 and Max_Data=0x7FFF + * @retval None + */ +__STATIC_INLINE void DDL_RTC_ALMB_SetSubSecond(RTC_TypeDef *RTCx, uint32_t Subsecond) +{ + MODIFY_REG(RTCx->ALRMBSS, RTC_ALRMBSS_SUBSEC, Subsecond); +} + +/** + * @brief Get Alarm B subseconds value + * @param RTCx RTC Instance + * @retval Value between Min_Data=0x00 and Max_Data=0x7FFF + */ +__STATIC_INLINE uint32_t DDL_RTC_ALMB_GetSubSecond(RTC_TypeDef *RTCx) +{ + return (uint32_t)(READ_BIT(RTCx->ALRMBSS, RTC_ALRMBSS_SUBSEC)); +} + +/** + * @} + */ + +/** @defgroup RTC_DDL_EF_Timestamp Timestamp + * @{ + */ + +/** + * @brief Enable Timestamp + * @note Bit is write-protected. @ref DDL_RTC_DisableWriteProtection function should be called before. + * @param RTCx RTC Instance + * @retval None + */ +__STATIC_INLINE void DDL_RTC_TS_Enable(RTC_TypeDef *RTCx) +{ + SET_BIT(RTCx->CTRL, RTC_CTRL_TSEN); +} + +/** + * @brief Disable Timestamp + * @note Bit is write-protected. @ref DDL_RTC_DisableWriteProtection function should be called before. + * @param RTCx RTC Instance + * @retval None + */ +__STATIC_INLINE void DDL_RTC_TS_Disable(RTC_TypeDef *RTCx) +{ + CLEAR_BIT(RTCx->CTRL, RTC_CTRL_TSEN); +} + +/** + * @brief Set Time-stamp event active edge + * @note Bit is write-protected. @ref DDL_RTC_DisableWriteProtection function should be called before. + * @note TSE must be reset when TSEDGE is changed to avoid unwanted TSF setting + * @param RTCx RTC Instance + * @param Edge This parameter can be one of the following values: + * @arg @ref DDL_RTC_TIMESTAMP_EDGE_RISING + * @arg @ref DDL_RTC_TIMESTAMP_EDGE_FALLING + * @retval None + */ +__STATIC_INLINE void DDL_RTC_TS_SetActiveEdge(RTC_TypeDef *RTCx, uint32_t Edge) +{ + MODIFY_REG(RTCx->CTRL, RTC_CTRL_TSETECFG, Edge); +} + +/** + * @brief Get Time-stamp event active edge + * @note Bit is write-protected. @ref DDL_RTC_DisableWriteProtection function should be called before. + * @param RTCx RTC Instance + * @retval Returned value can be one of the following values: + * @arg @ref DDL_RTC_TIMESTAMP_EDGE_RISING + * @arg @ref DDL_RTC_TIMESTAMP_EDGE_FALLING + */ +__STATIC_INLINE uint32_t DDL_RTC_TS_GetActiveEdge(RTC_TypeDef *RTCx) +{ + return (uint32_t)(READ_BIT(RTCx->CTRL, RTC_CTRL_TSETECFG)); +} + +/** + * @brief Get Timestamp AM/PM notation (AM or 24-hour format) + * @param RTCx RTC Instance + * @retval Returned value can be one of the following values: + * @arg @ref DDL_RTC_TS_TIME_FORMAT_AM + * @arg @ref DDL_RTC_TS_TIME_FORMAT_PM + */ +__STATIC_INLINE uint32_t DDL_RTC_TS_GetTimeFormat(RTC_TypeDef *RTCx) +{ + return (uint32_t)(READ_BIT(RTCx->TSTIME, RTC_TSTIME_TIMEFCFG)); +} + +/** + * @brief Get Timestamp Hours in BCD format + * @note helper macro __DDL_RTC_CONVERT_BCD2BIN is available to convert Hours from BCD to Binary format + * @param RTCx RTC Instance + * @retval Value between Min_Data=0x01 and Max_Data=0x12 or between Min_Data=0x00 and Max_Data=0x23 + */ +__STATIC_INLINE uint32_t DDL_RTC_TS_GetHour(RTC_TypeDef *RTCx) +{ + return (uint32_t)(READ_BIT(RTCx->TSTIME, RTC_TSTIME_HRT | RTC_TSTIME_HRU) >> RTC_TSTIME_HRU_Pos); +} + +/** + * @brief Get Timestamp Minutes in BCD format + * @note helper macro __DDL_RTC_CONVERT_BCD2BIN is available to convert Minutes from BCD to Binary format + * @param RTCx RTC Instance + * @retval Value between Min_Data=0x00 and Max_Data=0x59 + */ +__STATIC_INLINE uint32_t DDL_RTC_TS_GetMinute(RTC_TypeDef *RTCx) +{ + return (uint32_t)(READ_BIT(RTCx->TSTIME, RTC_TSTIME_MINT | RTC_TSTIME_MINU) >> RTC_TSTIME_MINU_Pos); +} + +/** + * @brief Get Timestamp Seconds in BCD format + * @note helper macro __DDL_RTC_CONVERT_BCD2BIN is available to convert Seconds from BCD to Binary format + * @param RTCx RTC Instance + * @retval Value between Min_Data=0x00 and Max_Data=0x59 + */ +__STATIC_INLINE uint32_t DDL_RTC_TS_GetSecond(RTC_TypeDef *RTCx) +{ + return (uint32_t)(READ_BIT(RTCx->TSTIME, RTC_TSTIME_SECT | RTC_TSTIME_SECU)); +} + +/** + * @brief Get Timestamp time (hour, minute and second) in BCD format + * @note helper macros __DDL_RTC_GET_HOUR, __DDL_RTC_GET_MINUTE and __DDL_RTC_GET_SECOND + * are available to get independently each parameter. + * @param RTCx RTC Instance + * @retval Combination of hours, minutes and seconds. + */ +__STATIC_INLINE uint32_t DDL_RTC_TS_GetTime(RTC_TypeDef *RTCx) +{ + return (uint32_t)(READ_BIT(RTCx->TSTIME, + RTC_TSTIME_HRT | RTC_TSTIME_HRU | RTC_TSTIME_MINT | RTC_TSTIME_MINU | RTC_TSTIME_SECT | RTC_TSTIME_SECU)); +} + +/** + * @brief Get Timestamp Week day + * @param RTCx RTC Instance + * @retval Returned value can be one of the following values: + * @arg @ref DDL_RTC_WEEKDAY_MONDAY + * @arg @ref DDL_RTC_WEEKDAY_TUESDAY + * @arg @ref DDL_RTC_WEEKDAY_WEDNESDAY + * @arg @ref DDL_RTC_WEEKDAY_THURSDAY + * @arg @ref DDL_RTC_WEEKDAY_FRIDAY + * @arg @ref DDL_RTC_WEEKDAY_SATURDAY + * @arg @ref DDL_RTC_WEEKDAY_SUNDAY + */ +__STATIC_INLINE uint32_t DDL_RTC_TS_GetWeekDay(RTC_TypeDef *RTCx) +{ + return (uint32_t)(READ_BIT(RTCx->TSDATE, RTC_TSDATE_WEEKSEL) >> RTC_TSDATE_WEEKSEL_Pos); +} + +/** + * @brief Get Timestamp Month in BCD format + * @note helper macro __DDL_RTC_CONVERT_BCD2BIN is available to convert Month from BCD to Binary format + * @param RTCx RTC Instance + * @retval Returned value can be one of the following values: + * @arg @ref DDL_RTC_MONTH_JANUARY + * @arg @ref DDL_RTC_MONTH_FEBRUARY + * @arg @ref DDL_RTC_MONTH_MARCH + * @arg @ref DDL_RTC_MONTH_APRIL + * @arg @ref DDL_RTC_MONTH_MAY + * @arg @ref DDL_RTC_MONTH_JUNE + * @arg @ref DDL_RTC_MONTH_JULY + * @arg @ref DDL_RTC_MONTH_AUGUST + * @arg @ref DDL_RTC_MONTH_SEPTEMBER + * @arg @ref DDL_RTC_MONTH_OCTOBER + * @arg @ref DDL_RTC_MONTH_NOVEMBER + * @arg @ref DDL_RTC_MONTH_DECEMBER + */ +__STATIC_INLINE uint32_t DDL_RTC_TS_GetMonth(RTC_TypeDef *RTCx) +{ + return (uint32_t)(READ_BIT(RTCx->TSDATE, RTC_TSDATE_MONT | RTC_TSDATE_MONU) >> RTC_TSDATE_MONU_Pos); +} + +/** + * @brief Get Timestamp Day in BCD format + * @note helper macro __DDL_RTC_CONVERT_BCD2BIN is available to convert Day from BCD to Binary format + * @param RTCx RTC Instance + * @retval Value between Min_Data=0x01 and Max_Data=0x31 + */ +__STATIC_INLINE uint32_t DDL_RTC_TS_GetDay(RTC_TypeDef *RTCx) +{ + return (uint32_t)(READ_BIT(RTCx->TSDATE, RTC_TSDATE_DAYT | RTC_TSDATE_DAYU)); +} + +/** + * @brief Get Timestamp date (WeekDay, Day and Month) in BCD format + * @note helper macros __DDL_RTC_GET_WEEKDAY, __DDL_RTC_GET_MONTH, + * and __DDL_RTC_GET_DAY are available to get independently each parameter. + * @param RTCx RTC Instance + * @retval Combination of Weekday, Day and Month + */ +__STATIC_INLINE uint32_t DDL_RTC_TS_GetDate(RTC_TypeDef *RTCx) +{ + return (uint32_t)(READ_BIT(RTCx->TSDATE, RTC_TSDATE_WEEKSEL | RTC_TSDATE_MONT | RTC_TSDATE_MONU | RTC_TSDATE_DAYT | RTC_TSDATE_DAYU)); +} + +/** + * @brief Get time-stamp subseconds value + * @param RTCx RTC Instance + * @retval Value between Min_Data=0x00 and Max_Data=0xFFFF + */ +__STATIC_INLINE uint32_t DDL_RTC_TS_GetSubSecond(RTC_TypeDef *RTCx) +{ + return (uint32_t)(READ_BIT(RTCx->TSSUBSEC, RTC_TSSUBSEC_SUBSE)); +} + +#if defined(RTC_TACFG_TPTSEN) +/** + * @brief Activate timestamp on tamper detection event + * @param RTCx RTC Instance + * @retval None + */ +__STATIC_INLINE void DDL_RTC_TS_EnableOnTamper(RTC_TypeDef *RTCx) +{ + SET_BIT(RTCx->TACFG, RTC_TACFG_TPTSEN); +} + +/** + * @brief Disable timestamp on tamper detection event + * @param RTCx RTC Instance + * @retval None + */ +__STATIC_INLINE void DDL_RTC_TS_DisableOnTamper(RTC_TypeDef *RTCx) +{ + CLEAR_BIT(RTCx->TACFG, RTC_TACFG_TPTSEN); +} +#endif /* RTC_TACFG_TPTSEN */ + +/** + * @brief Set timestamp Pin + * @param RTCx RTC Instance + * @param TSPin specifies the RTC Timestamp Pin. + * This parameter can be one of the following values: + * @arg DDL_RTC_TimeStampPin_Default: RTC_AF1 is used as RTC Timestamp Pin. + * @arg DDL_RTC_TimeStampPin_Pos1: RTC_AF2 is used as RTC Timestamp Pin. (*) + * + * (*) value not applicable to all devices. + * @retval None + */ +__STATIC_INLINE void DDL_RTC_TS_SetPin(RTC_TypeDef *RTCx, uint32_t TSPin) +{ + MODIFY_REG(RTCx->TACFG, RTC_TACFG_TSMSEL, TSPin); +} + +/** + * @brief Get timestamp Pin + * @param RTCx RTC Instance + * @retval Returned value can be one of the following values: + * @arg DDL_RTC_TimeStampPin_Default: RTC_AF1 is used as RTC Timestamp Pin. + * @arg DDL_RTC_TimeStampPin_Pos1: RTC_AF2 is used as RTC Timestamp Pin. (*) + * + * (*) value not applicable to all devices. + * @retval None + */ +__STATIC_INLINE uint32_t DDL_RTC_TS_GetPin(RTC_TypeDef *RTCx) +{ + return (uint32_t)(READ_BIT(RTCx->TACFG, RTC_TACFG_TSMSEL)); +} + +/** + * @} + */ + +/** @defgroup RTC_DDL_EF_Tamper Tamper + * @{ + */ + +/** + * @brief Enable RTC_TAMPx input detection + * @param RTCx RTC Instance + * @param Tamper This parameter can be a combination of the following values: + * @arg @ref DDL_RTC_TAMPER_1 + * @arg @ref DDL_RTC_TAMPER_2 (*) + * + * (*) value not applicable to all devices. + * @retval None + */ +__STATIC_INLINE void DDL_RTC_TAMPER_Enable(RTC_TypeDef *RTCx, uint32_t Tamper) +{ + SET_BIT(RTCx->TACFG, Tamper); +} + +/** + * @brief Clear RTC_TAMPx input detection + * @param RTCx RTC Instance + * @param Tamper This parameter can be a combination of the following values: + * @arg @ref DDL_RTC_TAMPER_1 + * @arg @ref DDL_RTC_TAMPER_2 (*) + * + * (*) value not applicable to all devices. + * @retval None + */ +__STATIC_INLINE void DDL_RTC_TAMPER_Disable(RTC_TypeDef *RTCx, uint32_t Tamper) +{ + CLEAR_BIT(RTCx->TACFG, Tamper); +} + +/** + * @brief Disable RTC_TAMPx pull-up disable (Disable precharge of RTC_TAMPx pins) + * @param RTCx RTC Instance + * @retval None + */ +__STATIC_INLINE void DDL_RTC_TAMPER_DisablePullUp(RTC_TypeDef *RTCx) +{ + SET_BIT(RTCx->TACFG, RTC_TACFG_TPPUDIS); +} + +/** + * @brief Enable RTC_TAMPx pull-up disable ( Precharge RTC_TAMPx pins before sampling) + * @param RTCx RTC Instance + * @retval None + */ +__STATIC_INLINE void DDL_RTC_TAMPER_EnablePullUp(RTC_TypeDef *RTCx) +{ + CLEAR_BIT(RTCx->TACFG, RTC_TACFG_TPPUDIS); +} + +/** + * @brief Set RTC_TAMPx precharge duration + * @param RTCx RTC Instance + * @param Duration This parameter can be one of the following values: + * @arg @ref DDL_RTC_TAMPER_DURATION_1RTCCLK + * @arg @ref DDL_RTC_TAMPER_DURATION_2RTCCLK + * @arg @ref DDL_RTC_TAMPER_DURATION_4RTCCLK + * @arg @ref DDL_RTC_TAMPER_DURATION_8RTCCLK + * @retval None + */ +__STATIC_INLINE void DDL_RTC_TAMPER_SetPrecharge(RTC_TypeDef *RTCx, uint32_t Duration) +{ + MODIFY_REG(RTCx->TACFG, RTC_TACFG_TPPRDUSEL, Duration); +} + +/** + * @brief Get RTC_TAMPx precharge duration + * @param RTCx RTC Instance + * @retval Returned value can be one of the following values: + * @arg @ref DDL_RTC_TAMPER_DURATION_1RTCCLK + * @arg @ref DDL_RTC_TAMPER_DURATION_2RTCCLK + * @arg @ref DDL_RTC_TAMPER_DURATION_4RTCCLK + * @arg @ref DDL_RTC_TAMPER_DURATION_8RTCCLK + */ +__STATIC_INLINE uint32_t DDL_RTC_TAMPER_GetPrecharge(RTC_TypeDef *RTCx) +{ + return (uint32_t)(READ_BIT(RTCx->TACFG, RTC_TACFG_TPPRDUSEL)); +} + +/** + * @brief Set RTC_TAMPx filter count + * @param RTCx RTC Instance + * @param FilterCount This parameter can be one of the following values: + * @arg @ref DDL_RTC_TAMPER_FILTER_DISABLE + * @arg @ref DDL_RTC_TAMPER_FILTER_2SAMPLE + * @arg @ref DDL_RTC_TAMPER_FILTER_4SAMPLE + * @arg @ref DDL_RTC_TAMPER_FILTER_8SAMPLE + * @retval None + */ +__STATIC_INLINE void DDL_RTC_TAMPER_SetFilterCount(RTC_TypeDef *RTCx, uint32_t FilterCount) +{ + MODIFY_REG(RTCx->TACFG, RTC_TACFG_TPFCSEL, FilterCount); +} + +/** + * @brief Get RTC_TAMPx filter count + * @param RTCx RTC Instance + * @retval Returned value can be one of the following values: + * @arg @ref DDL_RTC_TAMPER_FILTER_DISABLE + * @arg @ref DDL_RTC_TAMPER_FILTER_2SAMPLE + * @arg @ref DDL_RTC_TAMPER_FILTER_4SAMPLE + * @arg @ref DDL_RTC_TAMPER_FILTER_8SAMPLE + */ +__STATIC_INLINE uint32_t DDL_RTC_TAMPER_GetFilterCount(RTC_TypeDef *RTCx) +{ + return (uint32_t)(READ_BIT(RTCx->TACFG, RTC_TACFG_TPFCSEL)); +} + +/** + * @brief Set Tamper sampling frequency + * @param RTCx RTC Instance + * @param SamplingFreq This parameter can be one of the following values: + * @arg @ref DDL_RTC_TAMPER_SAMPLFREQDIV_32768 + * @arg @ref DDL_RTC_TAMPER_SAMPLFREQDIV_16384 + * @arg @ref DDL_RTC_TAMPER_SAMPLFREQDIV_8192 + * @arg @ref DDL_RTC_TAMPER_SAMPLFREQDIV_4096 + * @arg @ref DDL_RTC_TAMPER_SAMPLFREQDIV_2048 + * @arg @ref DDL_RTC_TAMPER_SAMPLFREQDIV_1024 + * @arg @ref DDL_RTC_TAMPER_SAMPLFREQDIV_512 + * @arg @ref DDL_RTC_TAMPER_SAMPLFREQDIV_256 + * @retval None + */ +__STATIC_INLINE void DDL_RTC_TAMPER_SetSamplingFreq(RTC_TypeDef *RTCx, uint32_t SamplingFreq) +{ + MODIFY_REG(RTCx->TACFG, RTC_TACFG_TPSFSEL, SamplingFreq); +} + +/** + * @brief Get Tamper sampling frequency + * @param RTCx RTC Instance + * @retval Returned value can be one of the following values: + * @arg @ref DDL_RTC_TAMPER_SAMPLFREQDIV_32768 + * @arg @ref DDL_RTC_TAMPER_SAMPLFREQDIV_16384 + * @arg @ref DDL_RTC_TAMPER_SAMPLFREQDIV_8192 + * @arg @ref DDL_RTC_TAMPER_SAMPLFREQDIV_4096 + * @arg @ref DDL_RTC_TAMPER_SAMPLFREQDIV_2048 + * @arg @ref DDL_RTC_TAMPER_SAMPLFREQDIV_1024 + * @arg @ref DDL_RTC_TAMPER_SAMPLFREQDIV_512 + * @arg @ref DDL_RTC_TAMPER_SAMPLFREQDIV_256 + */ +__STATIC_INLINE uint32_t DDL_RTC_TAMPER_GetSamplingFreq(RTC_TypeDef *RTCx) +{ + return (uint32_t)(READ_BIT(RTCx->TACFG, RTC_TACFG_TPSFSEL)); +} + +/** + * @brief Enable Active level for Tamper input + * @param RTCx RTC Instance + * @param Tamper This parameter can be a combination of the following values: + * @arg @ref DDL_RTC_TAMPER_ACTIVELEVEL_TAMP1 + * @arg @ref DDL_RTC_TAMPER_ACTIVELEVEL_TAMP2 (*) + * + * (*) value not applicable to all devices. + * @retval None + */ +__STATIC_INLINE void DDL_RTC_TAMPER_EnableActiveLevel(RTC_TypeDef *RTCx, uint32_t Tamper) +{ + SET_BIT(RTCx->TACFG, Tamper); +} + +/** + * @brief Disable Active level for Tamper input + * @param RTCx RTC Instance + * @param Tamper This parameter can be a combination of the following values: + * @arg @ref DDL_RTC_TAMPER_ACTIVELEVEL_TAMP1 + * @arg @ref DDL_RTC_TAMPER_ACTIVELEVEL_TAMP2 (*) + * + * (*) value not applicable to all devices. + * @retval None + */ +__STATIC_INLINE void DDL_RTC_TAMPER_DisableActiveLevel(RTC_TypeDef *RTCx, uint32_t Tamper) +{ + CLEAR_BIT(RTCx->TACFG, Tamper); +} + +/** + * @brief Set Tamper Pin + * @param RTCx RTC Instance + * @param TamperPin specifies the RTC Tamper Pin. + * This parameter can be one of the following values: + * @arg DDL_RTC_TamperPin_Default: RTC_AF1 is used as RTC Tamper Pin. + * @arg DDL_RTC_TamperPin_Pos1: RTC_AF2 is used as RTC Tamper Pin. (*) + * + * (*) value not applicable to all devices. + * @retval None + */ +__STATIC_INLINE void DDL_RTC_TAMPER_SetPin(RTC_TypeDef *RTCx, uint32_t TamperPin) +{ + MODIFY_REG(RTCx->TACFG, RTC_TACFG_TP1MSEL, TamperPin); +} + +/** + * @brief Get Tamper Pin + * @param RTCx RTC Instance + * @retval Returned value can be one of the following values: + * @arg DDL_RTC_TamperPin_Default: RTC_AF1 is used as RTC Tamper Pin. + * @arg DDL_RTC_TamperPin_Pos1: RTC_AF2 is selected as RTC Tamper Pin. (*) + * + * (*) value not applicable to all devices. + * @retval None + */ + +__STATIC_INLINE uint32_t DDL_RTC_TAMPER_GetPin(RTC_TypeDef *RTCx) +{ + return (uint32_t)(READ_BIT(RTCx->TACFG, RTC_TACFG_TP1MSEL)); +} + +/** + * @} + */ + +/** @defgroup RTC_DDL_EF_Wakeup Wakeup + * @{ + */ + +/** + * @brief Enable Wakeup timer + * @note Bit is write-protected. @ref DDL_RTC_DisableWriteProtection function should be called before. + * @param RTCx RTC Instance + * @retval None + */ +__STATIC_INLINE void DDL_RTC_WAKEUP_Enable(RTC_TypeDef *RTCx) +{ + SET_BIT(RTCx->CTRL, RTC_CTRL_WUTEN); +} + +/** + * @brief Disable Wakeup timer + * @note Bit is write-protected. @ref DDL_RTC_DisableWriteProtection function should be called before. + * @param RTCx RTC Instance + * @retval None + */ +__STATIC_INLINE void DDL_RTC_WAKEUP_Disable(RTC_TypeDef *RTCx) +{ + CLEAR_BIT(RTCx->CTRL, RTC_CTRL_WUTEN); +} + +/** + * @brief Check if Wakeup timer is enabled or not + * @param RTCx RTC Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_RTC_WAKEUP_IsEnabled(RTC_TypeDef *RTCx) +{ + return ((READ_BIT(RTCx->CTRL, RTC_CTRL_WUTEN) == (RTC_CTRL_WUTEN)) ? 1UL : 0UL); +} + +/** + * @brief Select Wakeup clock + * @note Bit is write-protected. @ref DDL_RTC_DisableWriteProtection function should be called before. + * @note Bit can be written only when RTC_CTRL WUTE bit = 0 and RTC_STS WUTWF bit = 1 + * @param RTCx RTC Instance + * @param WakeupClock This parameter can be one of the following values: + * @arg @ref DDL_RTC_WAKEUPCLOCK_DIV_16 + * @arg @ref DDL_RTC_WAKEUPCLOCK_DIV_8 + * @arg @ref DDL_RTC_WAKEUPCLOCK_DIV_4 + * @arg @ref DDL_RTC_WAKEUPCLOCK_DIV_2 + * @arg @ref DDL_RTC_WAKEUPCLOCK_CKSPRE + * @arg @ref DDL_RTC_WAKEUPCLOCK_CKSPRE_WUT + * @retval None + */ +__STATIC_INLINE void DDL_RTC_WAKEUP_SetClock(RTC_TypeDef *RTCx, uint32_t WakeupClock) +{ + MODIFY_REG(RTCx->CTRL, RTC_CTRL_WUCLKSEL, WakeupClock); +} + +/** + * @brief Get Wakeup clock + * @param RTCx RTC Instance + * @retval Returned value can be one of the following values: + * @arg @ref DDL_RTC_WAKEUPCLOCK_DIV_16 + * @arg @ref DDL_RTC_WAKEUPCLOCK_DIV_8 + * @arg @ref DDL_RTC_WAKEUPCLOCK_DIV_4 + * @arg @ref DDL_RTC_WAKEUPCLOCK_DIV_2 + * @arg @ref DDL_RTC_WAKEUPCLOCK_CKSPRE + * @arg @ref DDL_RTC_WAKEUPCLOCK_CKSPRE_WUT + */ +__STATIC_INLINE uint32_t DDL_RTC_WAKEUP_GetClock(RTC_TypeDef *RTCx) +{ + return (uint32_t)(READ_BIT(RTCx->CTRL, RTC_CTRL_WUCLKSEL)); +} + +/** + * @brief Set Wakeup auto-reload value + * @note Bit can be written only when WUTWF is set to 1 in RTC_STS + * @param RTCx RTC Instance + * @param Value Value between Min_Data=0x00 and Max_Data=0xFFFF + * @retval None + */ +__STATIC_INLINE void DDL_RTC_WAKEUP_SetAutoReload(RTC_TypeDef *RTCx, uint32_t Value) +{ + MODIFY_REG(RTCx->AUTORLD, RTC_AUTORLD_WUAUTORE, Value); +} + +/** + * @brief Get Wakeup auto-reload value + * @param RTCx RTC Instance + * @retval Value between Min_Data=0x00 and Max_Data=0xFFFF + */ +__STATIC_INLINE uint32_t DDL_RTC_WAKEUP_GetAutoReload(RTC_TypeDef *RTCx) +{ + return (uint32_t)(READ_BIT(RTCx->AUTORLD, RTC_AUTORLD_WUAUTORE)); +} + +/** + * @} + */ + +/** @defgroup RTC_DDL_EF_Backup_Registers Backup_Registers + * @{ + */ + +/** + * @brief Writes a data in a specified RTC Backup data register. + * @param RTCx RTC Instance + * @param BackupRegister This parameter can be one of the following values: + * @arg @ref DDL_RTC_BKP_DR0 + * @arg @ref DDL_RTC_BKP_DR1 + * @arg @ref DDL_RTC_BKP_DR2 + * @arg @ref DDL_RTC_BKP_DR3 + * @arg @ref DDL_RTC_BKP_DR4 + * @arg @ref DDL_RTC_BKP_DR5 + * @arg @ref DDL_RTC_BKP_DR6 + * @arg @ref DDL_RTC_BKP_DR7 + * @arg @ref DDL_RTC_BKP_DR8 + * @arg @ref DDL_RTC_BKP_DR9 + * @arg @ref DDL_RTC_BKP_DR10 + * @arg @ref DDL_RTC_BKP_DR11 + * @arg @ref DDL_RTC_BKP_DR12 + * @arg @ref DDL_RTC_BKP_DR13 + * @arg @ref DDL_RTC_BKP_DR14 + * @arg @ref DDL_RTC_BKP_DR15 + * @arg @ref DDL_RTC_BKP_DR16 + * @arg @ref DDL_RTC_BKP_DR17 + * @arg @ref DDL_RTC_BKP_DR18 + * @arg @ref DDL_RTC_BKP_DR19 + * @param Data Value between Min_Data=0x00 and Max_Data=0xFFFFFFFF + * @retval None + */ +__STATIC_INLINE void DDL_RTC_BAK_SetRegister(RTC_TypeDef *RTCx, uint32_t BackupRegister, uint32_t Data) +{ + uint32_t temp; + + temp = (uint32_t)(&(RTCx->BAKP0)); + temp += (BackupRegister * 4U); + + /* Write the specified register */ + *(__IO uint32_t *)temp = (uint32_t)Data; +} + +/** + * @brief Reads data from the specified RTC Backup data Register. + * @param RTCx RTC Instance + * @param BackupRegister This parameter can be one of the following values: + * @arg @ref DDL_RTC_BKP_DR0 + * @arg @ref DDL_RTC_BKP_DR1 + * @arg @ref DDL_RTC_BKP_DR2 + * @arg @ref DDL_RTC_BKP_DR3 + * @arg @ref DDL_RTC_BKP_DR4 + * @arg @ref DDL_RTC_BKP_DR5 + * @arg @ref DDL_RTC_BKP_DR6 + * @arg @ref DDL_RTC_BKP_DR7 + * @arg @ref DDL_RTC_BKP_DR8 + * @arg @ref DDL_RTC_BKP_DR9 + * @arg @ref DDL_RTC_BKP_DR10 + * @arg @ref DDL_RTC_BKP_DR11 + * @arg @ref DDL_RTC_BKP_DR12 + * @arg @ref DDL_RTC_BKP_DR13 + * @arg @ref DDL_RTC_BKP_DR14 + * @arg @ref DDL_RTC_BKP_DR15 + * @arg @ref DDL_RTC_BKP_DR16 + * @arg @ref DDL_RTC_BKP_DR17 + * @arg @ref DDL_RTC_BKP_DR18 + * @arg @ref DDL_RTC_BKP_DR19 + * @retval Value between Min_Data=0x00 and Max_Data=0xFFFFFFFF + */ +__STATIC_INLINE uint32_t DDL_RTC_BAK_GetRegister(RTC_TypeDef *RTCx, uint32_t BackupRegister) +{ + uint32_t temp; + + temp = (uint32_t)(&(RTCx->BAKP0)); + temp += (BackupRegister * 4U); + + /* Read the specified register */ + return (*(__IO uint32_t *)temp); +} + +/** + * @} + */ + +/** @defgroup RTC_DDL_EF_Calibration Calibration + * @{ + */ + +/** + * @brief Set Calibration output frequency (1 Hz or 512 Hz) + * @note Bits are write-protected. @ref DDL_RTC_DisableWriteProtection function should be called before. + * @param RTCx RTC Instance + * @param Frequency This parameter can be one of the following values: + * @arg @ref DDL_RTC_CALIB_OUTPUT_NONE + * @arg @ref DDL_RTC_CALIB_OUTPUT_1HZ + * @arg @ref DDL_RTC_CALIB_OUTPUT_512HZ + * + * @retval None + */ +__STATIC_INLINE void DDL_RTC_CAL_SetOutputFreq(RTC_TypeDef *RTCx, uint32_t Frequency) +{ + MODIFY_REG(RTCx->CTRL, RTC_CTRL_CALOEN | RTC_CTRL_CALOSEL, Frequency); +} + +/** + * @brief Get Calibration output frequency (1 Hz or 512 Hz) + * @param RTCx RTC Instance + * @retval Returned value can be one of the following values: + * @arg @ref DDL_RTC_CALIB_OUTPUT_NONE + * @arg @ref DDL_RTC_CALIB_OUTPUT_1HZ + * @arg @ref DDL_RTC_CALIB_OUTPUT_512HZ + * + */ +__STATIC_INLINE uint32_t DDL_RTC_CAL_GetOutputFreq(RTC_TypeDef *RTCx) +{ + return (uint32_t)(READ_BIT(RTCx->CTRL, RTC_CTRL_CALOEN | RTC_CTRL_CALOSEL)); +} + +/** + * @brief Enable Coarse digital calibration + * @note Bit is write-protected. @ref DDL_RTC_DisableWriteProtection function should be called before. + * @note It can be written in initialization mode only (@ref DDL_RTC_EnableInitMode function) + * @param RTCx RTC Instance + * @retval None + */ +__STATIC_INLINE void DDL_RTC_CAL_EnableCoarseDigital(RTC_TypeDef *RTCx) +{ + SET_BIT(RTCx->CTRL, RTC_CTRL_DCALEN); +} + +/** + * @brief Disable Coarse digital calibration + * @note Bit is write-protected. @ref DDL_RTC_DisableWriteProtection function should be called before. + * @note It can be written in initialization mode only (@ref DDL_RTC_EnableInitMode function) + * @param RTCx RTC Instance + * @retval None + */ +__STATIC_INLINE void DDL_RTC_CAL_DisableCoarseDigital(RTC_TypeDef *RTCx) +{ + CLEAR_BIT(RTCx->CTRL, RTC_CTRL_DCALEN); +} + +/** + * @brief Set the coarse digital calibration + * @note Bit is write-protected. @ref DDL_RTC_DisableWriteProtection function should be called before. + * @note It can be written in initialization mode only (@ref DDL_RTC_EnableInitMode function) + * @param RTCx RTC Instance + * @param Sign This parameter can be one of the following values: + * @arg @ref DDL_RTC_CALIB_SIGN_POSITIVE + * @arg @ref DDL_RTC_CALIB_SIGN_NEGATIVE + * @param Value value of coarse calibration expressed in ppm (coded on 5 bits) + * @note This Calibration value should be between 0 and 63 when using negative sign with a 2-ppm step. + * @note This Calibration value should be between 0 and 126 when using positive sign with a 4-ppm step. + * @retval None + */ +__STATIC_INLINE void DDL_RTC_CAL_ConfigCoarseDigital(RTC_TypeDef *RTCx, uint32_t Sign, uint32_t Value) +{ + MODIFY_REG(RTCx->DCAL, RTC_DCAL_DCALCFG | RTC_DCAL_DCAL, Sign | Value); +} + +/** + * @brief Get the coarse digital calibration value + * @param RTCx RTC Instance + * @retval value of coarse calibration expressed in ppm (coded on 5 bits) + */ +__STATIC_INLINE uint32_t DDL_RTC_CAL_GetCoarseDigitalValue(RTC_TypeDef *RTCx) +{ + return (uint32_t)(READ_BIT(RTCx->DCAL, RTC_DCAL_DCAL)); +} + +/** + * @brief Get the coarse digital calibration sign + * @param RTCx RTC Instance + * @retval Returned value can be one of the following values: + * @arg @ref DDL_RTC_CALIB_SIGN_POSITIVE + * @arg @ref DDL_RTC_CALIB_SIGN_NEGATIVE + */ +__STATIC_INLINE uint32_t DDL_RTC_CAL_GetCoarseDigitalSign(RTC_TypeDef *RTCx) +{ + return (uint32_t)(READ_BIT(RTCx->DCAL, RTC_DCAL_DCALCFG)); +} + +/** + * @brief Insert or not One RTCCLK pulse every 2exp11 pulses (frequency increased by 488.5 ppm) + * @note Bit is write-protected. @ref DDL_RTC_DisableWriteProtection function should be called before. + * @note Bit can be written only when RECALPF is set to 0 in RTC_STS + * @param RTCx RTC Instance + * @param Pulse This parameter can be one of the following values: + * @arg @ref DDL_RTC_CALIB_INSERTPULSE_NONE + * @arg @ref DDL_RTC_CALIB_INSERTPULSE_SET + * @retval None + */ +__STATIC_INLINE void DDL_RTC_CAL_SetPulse(RTC_TypeDef *RTCx, uint32_t Pulse) +{ + MODIFY_REG(RTCx->CAL, RTC_CAL_ICALFEN, Pulse); +} + +/** + * @brief Check if one RTCCLK has been inserted or not every 2exp11 pulses (frequency increased by 488.5 ppm) + * @param RTCx RTC Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_RTC_CAL_IsPulseInserted(RTC_TypeDef *RTCx) +{ + return ((READ_BIT(RTCx->CAL, RTC_CAL_ICALFEN) == (RTC_CAL_ICALFEN)) ? 1UL : 0UL); +} + +/** + * @brief Set smooth calibration cycle period + * @note Bit is write-protected. @ref DDL_RTC_DisableWriteProtection function should be called before. + * @note Bit can be written only when RECALPF is set to 0 in RTC_STS + * @param RTCx RTC Instance + * @param Period This parameter can be one of the following values: + * @arg @ref DDL_RTC_CALIB_PERIOD_32SEC + * @arg @ref DDL_RTC_CALIB_PERIOD_16SEC + * @arg @ref DDL_RTC_CALIB_PERIOD_8SEC + * @retval None + */ +__STATIC_INLINE void DDL_RTC_CAL_SetPeriod(RTC_TypeDef *RTCx, uint32_t Period) +{ + MODIFY_REG(RTCx->CAL, RTC_CAL_CAL8CFG | RTC_CAL_CAL16CFG, Period); +} + +/** + * @brief Get smooth calibration cycle period + * @param RTCx RTC Instance + * @retval Returned value can be one of the following values: + * @arg @ref DDL_RTC_CALIB_PERIOD_32SEC + * @arg @ref DDL_RTC_CALIB_PERIOD_16SEC + * @arg @ref DDL_RTC_CALIB_PERIOD_8SEC + */ +__STATIC_INLINE uint32_t DDL_RTC_CAL_GetPeriod(RTC_TypeDef *RTCx) +{ + return (uint32_t)(READ_BIT(RTCx->CAL, RTC_CAL_CAL8CFG | RTC_CAL_CAL16CFG)); +} + +/** + * @brief Set smooth Calibration minus + * @note Bit is write-protected. @ref DDL_RTC_DisableWriteProtection function should be called before. + * @note Bit can be written only when RECALPF is set to 0 in RTC_STS + * @param RTCx RTC Instance + * @param CalibMinus Value between Min_Data=0x00 and Max_Data=0x1FF + * @retval None + */ +__STATIC_INLINE void DDL_RTC_CAL_SetMinus(RTC_TypeDef *RTCx, uint32_t CalibMinus) +{ + MODIFY_REG(RTCx->CAL, RTC_CAL_RECALF, CalibMinus); +} + +/** + * @brief Get smooth Calibration minus + * @param RTCx RTC Instance + * @retval Value between Min_Data=0x00 and Max_Data= 0x1FF + */ +__STATIC_INLINE uint32_t DDL_RTC_CAL_GetMinus(RTC_TypeDef *RTCx) +{ + return (uint32_t)(READ_BIT(RTCx->CAL, RTC_CAL_RECALF)); +} + +/** + * @} + */ + +/** @defgroup RTC_DDL_EF_FLAG_Management FLAG_Management + * @{ + */ + +/** + * @brief Get Recalibration pending Flag + * @param RTCx RTC Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_RTC_IsActiveFlag_RECALP(RTC_TypeDef *RTCx) +{ + return ((READ_BIT(RTCx->STS, RTC_STS_RCALPFLG) == (RTC_STS_RCALPFLG)) ? 1UL : 0UL); +} + +#if defined(RTC_TAMPER2_SUPPORT) +/** + * @brief Get RTC_TAMP2 detection flag + * @param RTCx RTC Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_RTC_IsActiveFlag_TAMP2(RTC_TypeDef *RTCx) +{ + return ((READ_BIT(RTCx->STS, RTC_STS_TP2FLG) == (RTC_STS_TP2FLG)) ? 1UL : 0UL); +} +#endif /* RTC_TAMPER2_SUPPORT */ + +/** + * @brief Get RTC_TAMP1 detection flag + * @param RTCx RTC Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_RTC_IsActiveFlag_TAMP1(RTC_TypeDef *RTCx) +{ + return ((READ_BIT(RTCx->STS, RTC_STS_TP1FLG) == (RTC_STS_TP1FLG)) ? 1UL : 0UL); +} + +/** + * @brief Get Time-stamp overflow flag + * @param RTCx RTC Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_RTC_IsActiveFlag_TSOV(RTC_TypeDef *RTCx) +{ + return ((READ_BIT(RTCx->STS, RTC_STS_TSOVRFLG) == (RTC_STS_TSOVRFLG)) ? 1UL : 0UL); +} + +/** + * @brief Get Time-stamp flag + * @param RTCx RTC Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_RTC_IsActiveFlag_TS(RTC_TypeDef *RTCx) +{ + return ((READ_BIT(RTCx->STS, RTC_STS_TSFLG) == (RTC_STS_TSFLG)) ? 1UL : 0UL); +} + +/** + * @brief Get Wakeup timer flag + * @param RTCx RTC Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_RTC_IsActiveFlag_WUT(RTC_TypeDef *RTCx) +{ + return ((READ_BIT(RTCx->STS, RTC_STS_WUTFLG) == (RTC_STS_WUTFLG)) ? 1UL : 0UL); +} + +/** + * @brief Get Alarm B flag + * @param RTCx RTC Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_RTC_IsActiveFlag_ALRB(RTC_TypeDef *RTCx) +{ + return ((READ_BIT(RTCx->STS, RTC_STS_ALRBFLG) == (RTC_STS_ALRBFLG)) ? 1UL : 0UL); +} + +/** + * @brief Get Alarm A flag + * @param RTCx RTC Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_RTC_IsActiveFlag_ALRA(RTC_TypeDef *RTCx) +{ + return ((READ_BIT(RTCx->STS, RTC_STS_ALRAFLG) == (RTC_STS_ALRAFLG)) ? 1UL : 0UL); +} + +#if defined(RTC_TAMPER2_SUPPORT) +/** + * @brief Clear RTC_TAMP2 detection flag + * @param RTCx RTC Instance + * @retval None + */ +__STATIC_INLINE void DDL_RTC_ClearFlag_TAMP2(RTC_TypeDef *RTCx) +{ + WRITE_REG(RTCx->STS, (~((RTC_STS_TP2FLG | RTC_STS_INITEN) & 0x0000FFFFU) | (RTCx->STS & RTC_STS_INITEN))); +} +#endif /* RTC_TAMPER2_SUPPORT */ + +/** + * @brief Clear RTC_TAMP1 detection flag + * @param RTCx RTC Instance + * @retval None + */ +__STATIC_INLINE void DDL_RTC_ClearFlag_TAMP1(RTC_TypeDef *RTCx) +{ + WRITE_REG(RTCx->STS, (~((RTC_STS_TP1FLG | RTC_STS_INITEN) & 0x0000FFFFU) | (RTCx->STS & RTC_STS_INITEN))); +} + +/** + * @brief Clear Time-stamp overflow flag + * @param RTCx RTC Instance + * @retval None + */ +__STATIC_INLINE void DDL_RTC_ClearFlag_TSOV(RTC_TypeDef *RTCx) +{ + WRITE_REG(RTCx->STS, (~((RTC_STS_TSOVRFLG | RTC_STS_INITEN) & 0x0000FFFFU) | (RTCx->STS & RTC_STS_INITEN))); +} + +/** + * @brief Clear Time-stamp flag + * @param RTCx RTC Instance + * @retval None + */ +__STATIC_INLINE void DDL_RTC_ClearFlag_TS(RTC_TypeDef *RTCx) +{ + WRITE_REG(RTCx->STS, (~((RTC_STS_TSFLG | RTC_STS_INITEN) & 0x0000FFFFU) | (RTCx->STS & RTC_STS_INITEN))); +} + +/** + * @brief Clear Wakeup timer flag + * @param RTCx RTC Instance + * @retval None + */ +__STATIC_INLINE void DDL_RTC_ClearFlag_WUT(RTC_TypeDef *RTCx) +{ + WRITE_REG(RTCx->STS, (~((RTC_STS_WUTFLG | RTC_STS_INITEN) & 0x0000FFFFU) | (RTCx->STS & RTC_STS_INITEN))); +} + +/** + * @brief Clear Alarm B flag + * @param RTCx RTC Instance + * @retval None + */ +__STATIC_INLINE void DDL_RTC_ClearFlag_ALRB(RTC_TypeDef *RTCx) +{ + WRITE_REG(RTCx->STS, (~((RTC_STS_ALRBFLG | RTC_STS_INITEN) & 0x0000FFFFU) | (RTCx->STS & RTC_STS_INITEN))); +} + +/** + * @brief Clear Alarm A flag + * @param RTCx RTC Instance + * @retval None + */ +__STATIC_INLINE void DDL_RTC_ClearFlag_ALRA(RTC_TypeDef *RTCx) +{ + WRITE_REG(RTCx->STS, (~((RTC_STS_ALRAFLG | RTC_STS_INITEN) & 0x0000FFFFU) | (RTCx->STS & RTC_STS_INITEN))); +} + +/** + * @brief Get Initialization flag + * @param RTCx RTC Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_RTC_IsActiveFlag_INIT(RTC_TypeDef *RTCx) +{ + return ((READ_BIT(RTCx->STS, RTC_STS_RINITFLG) == (RTC_STS_RINITFLG)) ? 1UL : 0UL); +} + +/** + * @brief Get Registers synchronization flag + * @param RTCx RTC Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_RTC_IsActiveFlag_RS(RTC_TypeDef *RTCx) +{ + return ((READ_BIT(RTCx->STS, RTC_STS_RSFLG) == (RTC_STS_RSFLG)) ? 1UL : 0UL); +} + +/** + * @brief Clear Registers synchronization flag + * @param RTCx RTC Instance + * @retval None + */ +__STATIC_INLINE void DDL_RTC_ClearFlag_RS(RTC_TypeDef *RTCx) +{ + WRITE_REG(RTCx->STS, (~((RTC_STS_RSFLG | RTC_STS_INITEN) & 0x0000FFFFU) | (RTCx->STS & RTC_STS_INITEN))); +} + +/** + * @brief Get Initialization status flag + * @param RTCx RTC Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_RTC_IsActiveFlag_INITS(RTC_TypeDef *RTCx) +{ + return ((READ_BIT(RTCx->STS, RTC_STS_INITSFLG) == (RTC_STS_INITSFLG)) ? 1UL : 0UL); +} + +/** + * @brief Get Shift operation pending flag + * @param RTCx RTC Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_RTC_IsActiveFlag_SHP(RTC_TypeDef *RTCx) +{ + return ((READ_BIT(RTCx->STS, RTC_STS_SOPFLG) == (RTC_STS_SOPFLG)) ? 1UL : 0UL); +} + +/** + * @brief Get Wakeup timer write flag + * @param RTCx RTC Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_RTC_IsActiveFlag_WUTW(RTC_TypeDef *RTCx) +{ + return ((READ_BIT(RTCx->STS, RTC_STS_WUTWFLG) == (RTC_STS_WUTWFLG)) ? 1UL : 0UL); +} + +/** + * @brief Get Alarm B write flag + * @param RTCx RTC Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_RTC_IsActiveFlag_ALRBW(RTC_TypeDef *RTCx) +{ + return ((READ_BIT(RTCx->STS, RTC_STS_ALRBWFLG) == (RTC_STS_ALRBWFLG)) ? 1UL : 0UL); +} + +/** + * @brief Get Alarm A write flag + * @param RTCx RTC Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_RTC_IsActiveFlag_ALRAW(RTC_TypeDef *RTCx) +{ + return ((READ_BIT(RTCx->STS, RTC_STS_ALRAWFLG) == (RTC_STS_ALRAWFLG)) ? 1UL : 0UL); +} + +/** + * @} + */ + +/** @defgroup RTC_DDL_EF_IT_Management IT_Management + * @{ + */ + +/** + * @brief Enable Time-stamp interrupt + * @note Bit is write-protected. @ref DDL_RTC_DisableWriteProtection function should be called before. + * @param RTCx RTC Instance + * @retval None + */ +__STATIC_INLINE void DDL_RTC_EnableIT_TS(RTC_TypeDef *RTCx) +{ + SET_BIT(RTCx->CTRL, RTC_CTRL_TSIEN); +} + +/** + * @brief Disable Time-stamp interrupt + * @note Bit is write-protected. @ref DDL_RTC_DisableWriteProtection function should be called before. + * @param RTCx RTC Instance + * @retval None + */ +__STATIC_INLINE void DDL_RTC_DisableIT_TS(RTC_TypeDef *RTCx) +{ + CLEAR_BIT(RTCx->CTRL, RTC_CTRL_TSIEN); +} + +/** + * @brief Enable Wakeup timer interrupt + * @note Bit is write-protected. @ref DDL_RTC_DisableWriteProtection function should be called before. + * @param RTCx RTC Instance + * @retval None + */ +__STATIC_INLINE void DDL_RTC_EnableIT_WUT(RTC_TypeDef *RTCx) +{ + SET_BIT(RTCx->CTRL, RTC_CTRL_WUTIEN); +} + +/** + * @brief Disable Wakeup timer interrupt + * @note Bit is write-protected. @ref DDL_RTC_DisableWriteProtection function should be called before. + * @param RTCx RTC Instance + * @retval None + */ +__STATIC_INLINE void DDL_RTC_DisableIT_WUT(RTC_TypeDef *RTCx) +{ + CLEAR_BIT(RTCx->CTRL, RTC_CTRL_WUTIEN); +} + +/** + * @brief Enable Alarm B interrupt + * @note Bit is write-protected. @ref DDL_RTC_DisableWriteProtection function should be called before. + * @param RTCx RTC Instance + * @retval None + */ +__STATIC_INLINE void DDL_RTC_EnableIT_ALRB(RTC_TypeDef *RTCx) +{ + SET_BIT(RTCx->CTRL, RTC_CTRL_ALRBIEN); +} + +/** + * @brief Disable Alarm B interrupt + * @note Bit is write-protected. @ref DDL_RTC_DisableWriteProtection function should be called before. + * @param RTCx RTC Instance + * @retval None + */ +__STATIC_INLINE void DDL_RTC_DisableIT_ALRB(RTC_TypeDef *RTCx) +{ + CLEAR_BIT(RTCx->CTRL, RTC_CTRL_ALRBIEN); +} + +/** + * @brief Enable Alarm A interrupt + * @note Bit is write-protected. @ref DDL_RTC_DisableWriteProtection function should be called before. + * @param RTCx RTC Instance + * @retval None + */ +__STATIC_INLINE void DDL_RTC_EnableIT_ALRA(RTC_TypeDef *RTCx) +{ + SET_BIT(RTCx->CTRL, RTC_CTRL_ALRAIEN); +} + +/** + * @brief Disable Alarm A interrupt + * @note Bit is write-protected. @ref DDL_RTC_DisableWriteProtection function should be called before. + * @param RTCx RTC Instance + * @retval None + */ +__STATIC_INLINE void DDL_RTC_DisableIT_ALRA(RTC_TypeDef *RTCx) +{ + CLEAR_BIT(RTCx->CTRL, RTC_CTRL_ALRAIEN); +} + +/** + * @brief Enable all Tamper Interrupt + * @param RTCx RTC Instance + * @retval None + */ +__STATIC_INLINE void DDL_RTC_EnableIT_TAMP(RTC_TypeDef *RTCx) +{ + SET_BIT(RTCx->TACFG, RTC_TACFG_TPIEN); +} + +/** + * @brief Disable all Tamper Interrupt + * @param RTCx RTC Instance + * @retval None + */ +__STATIC_INLINE void DDL_RTC_DisableIT_TAMP(RTC_TypeDef *RTCx) +{ + CLEAR_BIT(RTCx->TACFG, RTC_TACFG_TPIEN); +} + +/** + * @brief Check if Time-stamp interrupt is enabled or not + * @param RTCx RTC Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_RTC_IsEnabledIT_TS(RTC_TypeDef *RTCx) +{ + return ((READ_BIT(RTCx->CTRL, RTC_CTRL_TSIEN) == (RTC_CTRL_TSIEN)) ? 1UL : 0UL); +} + +/** + * @brief Check if Wakeup timer interrupt is enabled or not + * @param RTCx RTC Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_RTC_IsEnabledIT_WUT(RTC_TypeDef *RTCx) +{ + return ((READ_BIT(RTCx->CTRL, RTC_CTRL_WUTIEN) == (RTC_CTRL_WUTIEN)) ? 1UL : 0UL); +} + +/** + * @brief Check if Alarm B interrupt is enabled or not + * @param RTCx RTC Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_RTC_IsEnabledIT_ALRB(RTC_TypeDef *RTCx) +{ + return ((READ_BIT(RTCx->CTRL, RTC_CTRL_ALRBIEN) == (RTC_CTRL_ALRBIEN)) ? 1UL : 0UL); +} + +/** + * @brief Check if Alarm A interrupt is enabled or not + * @param RTCx RTC Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_RTC_IsEnabledIT_ALRA(RTC_TypeDef *RTCx) +{ + return ((READ_BIT(RTCx->CTRL, RTC_CTRL_ALRAIEN) == (RTC_CTRL_ALRAIEN)) ? 1UL : 0UL); +} + +/** + * @brief Check if all the TAMPER interrupts are enabled or not + * @param RTCx RTC Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_RTC_IsEnabledIT_TAMP(RTC_TypeDef *RTCx) +{ + return ((READ_BIT(RTCx->TACFG, + RTC_TACFG_TPIEN) == (RTC_TACFG_TPIEN)) ? 1UL : 0UL); +} + +/** + * @} + */ + +#if defined(USE_FULL_DDL_DRIVER) +/** @defgroup RTC_DDL_EF_Init Initialization and de-initialization functions + * @{ + */ + +ErrorStatus DDL_RTC_DeInit(RTC_TypeDef *RTCx); +ErrorStatus DDL_RTC_Init(RTC_TypeDef *RTCx, DDL_RTC_InitTypeDef *RTC_InitStruct); +void DDL_RTC_StructInit(DDL_RTC_InitTypeDef *RTC_InitStruct); +ErrorStatus DDL_RTC_TIME_Init(RTC_TypeDef *RTCx, uint32_t RTC_Format, DDL_RTC_TimeTypeDef *RTC_TimeStruct); +void DDL_RTC_TIME_StructInit(DDL_RTC_TimeTypeDef *RTC_TimeStruct); +ErrorStatus DDL_RTC_DATE_Init(RTC_TypeDef *RTCx, uint32_t RTC_Format, DDL_RTC_DateTypeDef *RTC_DateStruct); +void DDL_RTC_DATE_StructInit(DDL_RTC_DateTypeDef *RTC_DateStruct); +ErrorStatus DDL_RTC_ALMA_Init(RTC_TypeDef *RTCx, uint32_t RTC_Format, DDL_RTC_AlarmTypeDef *RTC_AlarmStruct); +ErrorStatus DDL_RTC_ALMB_Init(RTC_TypeDef *RTCx, uint32_t RTC_Format, DDL_RTC_AlarmTypeDef *RTC_AlarmStruct); +void DDL_RTC_ALMA_StructInit(DDL_RTC_AlarmTypeDef *RTC_AlarmStruct); +void DDL_RTC_ALMB_StructInit(DDL_RTC_AlarmTypeDef *RTC_AlarmStruct); +ErrorStatus DDL_RTC_EnterInitMode(RTC_TypeDef *RTCx); +ErrorStatus DDL_RTC_ExitInitMode(RTC_TypeDef *RTCx); +ErrorStatus DDL_RTC_WaitForSynchro(RTC_TypeDef *RTCx); + +/** + * @} + */ +#endif /* USE_FULL_DDL_DRIVER */ + +/** + * @} + */ + +/** + * @} + */ + +#endif /* defined(RTC) */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* APM32F4xx_DDL_RTC_H */ diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_sdmmc.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_sdmmc.h new file mode 100644 index 0000000000..1216cf5253 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_sdmmc.h @@ -0,0 +1,1165 @@ +/** + * + * @file apm32f4xx_ddl_sdmmc.h + * @brief Header file of SDMMC DDL module. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef APM32F4xx_DDL_SDMMC_H +#define APM32F4xx_DDL_SDMMC_H + +#ifdef __cplusplus + extern "C" { +#endif + +#if defined(SDIO) + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal_def.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @addtogroup SDMMC_DDL + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ +/** @defgroup SDMMC_DDL_Exported_Types SDMMC_DDL Exported Types + * @{ + */ + +/** + * @brief SDMMC Configuration Structure definition + */ +typedef struct +{ + uint32_t ClockEdge; /*!< Specifies the clock transition on which the bit capture is made. + This parameter can be a value of @ref SDMMC_DDL_Clock_Edge */ + + uint32_t ClockBypass; /*!< Specifies whether the SDMMC Clock divider bypass is + enabled or disabled. + This parameter can be a value of @ref SDMMC_DDL_Clock_Bypass */ + + uint32_t ClockPowerSave; /*!< Specifies whether SDMMC Clock output is enabled or + disabled when the bus is idle. + This parameter can be a value of @ref SDMMC_DDL_Clock_Power_Save */ + + uint32_t BusWide; /*!< Specifies the SDMMC bus width. + This parameter can be a value of @ref SDMMC_DDL_Bus_Wide */ + + uint32_t HardwareFlowControl; /*!< Specifies whether the SDMMC hardware flow control is enabled or disabled. + This parameter can be a value of @ref SDMMC_DDL_Hardware_Flow_Control */ + + uint32_t ClockDiv; /*!< Specifies the clock frequency of the SDMMC controller. + This parameter can be a value between Min_Data = 0 and Max_Data = 255 */ + +}SDIO_InitTypeDef; + + +/** + * @brief SDMMC Command Control structure + */ +typedef struct +{ + uint32_t Argument; /*!< Specifies the SDMMC command argument which is sent + to a card as part of a command message. If a command + contains an argument, it must be loaded into this register + before writing the command to the command register. */ + + uint32_t CmdIndex; /*!< Specifies the SDMMC command index. It must be Min_Data = 0 and + Max_Data = 64 */ + + uint32_t Response; /*!< Specifies the SDMMC response type. + This parameter can be a value of @ref SDMMC_DDL_Response_Type */ + + uint32_t WaitForInterrupt; /*!< Specifies whether SDMMC wait for interrupt request is + enabled or disabled. + This parameter can be a value of @ref SDMMC_DDL_Wait_Interrupt_State */ + + uint32_t CPSM; /*!< Specifies whether SDMMC Command path state machine (CPSM) + is enabled or disabled. + This parameter can be a value of @ref SDMMC_DDL_CPSM_State */ +}SDIO_CmdInitTypeDef; + + +/** + * @brief SDMMC Data Control structure + */ +typedef struct +{ + uint32_t DataTimeOut; /*!< Specifies the data timeout period in card bus clock periods. */ + + uint32_t DataLength; /*!< Specifies the number of data bytes to be transferred. */ + + uint32_t DataBlockSize; /*!< Specifies the data block size for block transfer. + This parameter can be a value of @ref SDMMC_DDL_Data_Block_Size */ + + uint32_t TransferDir; /*!< Specifies the data transfer direction, whether the transfer + is a read or write. + This parameter can be a value of @ref SDMMC_DDL_Transfer_Direction */ + + uint32_t TransferMode; /*!< Specifies whether data transfer is in stream or block mode. + This parameter can be a value of @ref SDMMC_DDL_Transfer_Type */ + + uint32_t DPSM; /*!< Specifies whether SDMMC Data path state machine (DPSM) + is enabled or disabled. + This parameter can be a value of @ref SDMMC_DDL_DPSM_State */ +}SDIO_DataInitTypeDef; + +/** + * @} + */ + +/* Exported constants --------------------------------------------------------*/ +/** @defgroup SDMMC_DDL_Exported_Constants SDMMC_LL Exported Constants + * @{ + */ +#define SDMMC_ERROR_NONE 0x00000000U /*!< No error */ +#define SDMMC_ERROR_CMD_CRC_FAIL 0x00000001U /*!< Command response received (but CRC check failed) */ +#define SDMMC_ERROR_DATA_CRC_FAIL 0x00000002U /*!< Data block sent/received (CRC check failed) */ +#define SDMMC_ERROR_CMD_RSP_TIMEOUT 0x00000004U /*!< Command response timeout */ +#define SDMMC_ERROR_DATA_TIMEOUT 0x00000008U /*!< Data timeout */ +#define SDMMC_ERROR_TX_UNDERRUN 0x00000010U /*!< Transmit FIFO underrun */ +#define SDMMC_ERROR_RX_OVERRUN 0x00000020U /*!< Receive FIFO overrun */ +#define SDMMC_ERROR_ADDR_MISALIGNED 0x00000040U /*!< Misaligned address */ +#define SDMMC_ERROR_BLOCK_LEN_ERR 0x00000080U /*!< Transferred block length is not allowed for the card or the + number of transferred bytes does not match the block length */ +#define SDMMC_ERROR_ERASE_SEQ_ERR 0x00000100U /*!< An error in the sequence of erase command occurs */ +#define SDMMC_ERROR_BAD_ERASE_PARAM 0x00000200U /*!< An invalid selection for erase groups */ +#define SDMMC_ERROR_WRITE_PROT_VIOLATION 0x00000400U /*!< Attempt to program a write protect block */ +#define SDMMC_ERROR_LOCK_UNLOCK_FAILED 0x00000800U /*!< Sequence or password error has been detected in unlock + command or if there was an attempt to access a locked card */ +#define SDMMC_ERROR_COM_CRC_FAILED 0x00001000U /*!< CRC check of the previous command failed */ +#define SDMMC_ERROR_ILLEGAL_CMD 0x00002000U /*!< Command is not legal for the card state */ +#define SDMMC_ERROR_CARD_ECC_FAILED 0x00004000U /*!< Card internal ECC was applied but failed to correct the data */ +#define SDMMC_ERROR_CC_ERR 0x00008000U /*!< Internal card controller error */ +#define SDMMC_ERROR_GENERAL_UNKNOWN_ERR 0x00010000U /*!< General or unknown error */ +#define SDMMC_ERROR_STREAM_READ_UNDERRUN 0x00020000U /*!< The card could not sustain data reading in stream rmode */ +#define SDMMC_ERROR_STREAM_WRITE_OVERRUN 0x00040000U /*!< The card could not sustain data programming in stream mode */ +#define SDMMC_ERROR_CID_CSD_OVERWRITE 0x00080000U /*!< CID/CSD overwrite error */ +#define SDMMC_ERROR_WP_ERASE_SKIP 0x00100000U /*!< Only partial address space was erased */ +#define SDMMC_ERROR_CARD_ECC_DISABLED 0x00200000U /*!< Command has been executed without using internal ECC */ +#define SDMMC_ERROR_ERASE_RESET 0x00400000U /*!< Erase sequence was cleared before executing because an out + of erase sequence command was received */ +#define SDMMC_ERROR_AKE_SEQ_ERR 0x00800000U /*!< Error in sequence of authentication */ +#define SDMMC_ERROR_INVALID_VOLTRANGE 0x01000000U /*!< Error in case of invalid voltage range */ +#define SDMMC_ERROR_ADDR_OUT_OF_RANGE 0x02000000U /*!< Error when addressed block is out of range */ +#define SDMMC_ERROR_REQUEST_NOT_APPLICABLE 0x04000000U /*!< Error when command request is not applicable */ +#define SDMMC_ERROR_INVALID_PARAMETER 0x08000000U /*!< the used parameter is not valid */ +#define SDMMC_ERROR_UNSUPPORTED_FEATURE 0x10000000U /*!< Error when feature is not insupported */ +#define SDMMC_ERROR_BUSY 0x20000000U /*!< Error when transfer process is busy */ +#define SDMMC_ERROR_DMA 0x40000000U /*!< Error while DMA transfer */ +#define SDMMC_ERROR_TIMEOUT 0x80000000U /*!< Timeout error */ + +/** + * @brief SDMMC Commands Index + */ +#define SDMMC_CMD_GO_IDLE_STATE 0U /*!< Resets the SD memory card. */ +#define SDMMC_CMD_SEND_OP_COND 1U /*!< Sends host capacity support information and activates the card's initialization process. */ +#define SDMMC_CMD_ALL_SEND_CID 2U /*!< Asks any card connected to the host to send the CID numbers on the CMD line. */ +#define SDMMC_CMD_SET_REL_ADDR 3U /*!< Asks the card to publish a new relative address (RCA). */ +#define SDMMC_CMD_SET_DSR 4U /*!< Programs the DSR of all cards. */ +#define SDMMC_CMD_SDMMC_SEN_OP_COND 5U /*!< Sends host capacity support information (HCS) and asks the accessed card to send its + operating condition register (OCR) content in the response on the CMD line. */ +#define SDMMC_CMD_HS_SWITCH 6U /*!< Checks switchable function (mode 0) and switch card function (mode 1). */ +#define SDMMC_CMD_SEL_DESEL_CARD 7U /*!< Selects the card by its own relative address and gets deselected by any other address */ +#define SDMMC_CMD_HS_SEND_EXT_CSD 8U /*!< Sends SD Memory Card interface condition, which includes host supply voltage information + and asks the card whether card supports voltage. */ +#define SDMMC_CMD_SEND_CSD 9U /*!< Addressed card sends its card specific data (CSD) on the CMD line. */ +#define SDMMC_CMD_SEND_CID 10U /*!< Addressed card sends its card identification (CID) on the CMD line. */ +#define SDMMC_CMD_READ_DAT_UNTIL_STOP 11U /*!< SD card doesn't support it. */ +#define SDMMC_CMD_STOP_TRANSMISSION 12U /*!< Forces the card to stop transmission. */ +#define SDMMC_CMD_SEND_STATUS 13U /*!< Addressed card sends its status register. */ +#define SDMMC_CMD_HS_BUSTEST_READ 14U /*!< Reserved */ +#define SDMMC_CMD_GO_INACTIVE_STATE 15U /*!< Sends an addressed card into the inactive state. */ +#define SDMMC_CMD_SET_BLOCKLEN 16U /*!< Sets the block length (in bytes for SDSC) for all following block commands + (read, write, lock). Default block length is fixed to 512 Bytes. Not effective + for SDHS and SDXC. */ +#define SDMMC_CMD_READ_SINGLE_BLOCK 17U /*!< Reads single block of size selected by SET_BLOCKLEN in case of SDSC, and a block of + fixed 512 bytes in case of SDHC and SDXC. */ +#define SDMMC_CMD_READ_MULT_BLOCK 18U /*!< Continuously transfers data blocks from card to host until interrupted by + STOP_TRANSMISSION command. */ +#define SDMMC_CMD_HS_BUSTEST_WRITE 19U /*!< 64 bytes tuning pattern is sent for SDR50 and SDR104. */ +#define SDMMC_CMD_WRITE_DAT_UNTIL_STOP 20U /*!< Speed class control command. */ +#define SDMMC_CMD_SET_BLOCK_COUNT 23U /*!< Specify block count for CMD18 and CMD25. */ +#define SDMMC_CMD_WRITE_SINGLE_BLOCK 24U /*!< Writes single block of size selected by SET_BLOCKLEN in case of SDSC, and a block of + fixed 512 bytes in case of SDHC and SDXC. */ +#define SDMMC_CMD_WRITE_MULT_BLOCK 25U /*!< Continuously writes blocks of data until a STOP_TRANSMISSION follows. */ +#define SDMMC_CMD_PROG_CID 26U /*!< Reserved for manufacturers. */ +#define SDMMC_CMD_PROG_CSD 27U /*!< Programming of the programmable bits of the CSD. */ +#define SDMMC_CMD_SET_WRITE_PROT 28U /*!< Sets the write protection bit of the addressed group. */ +#define SDMMC_CMD_CLR_WRITE_PROT 29U /*!< Clears the write protection bit of the addressed group. */ +#define SDMMC_CMD_SEND_WRITE_PROT 30U /*!< Asks the card to send the status of the write protection bits. */ +#define SDMMC_CMD_SD_ERASE_GRP_START 32U /*!< Sets the address of the first write block to be erased. (For SD card only). */ +#define SDMMC_CMD_SD_ERASE_GRP_END 33U /*!< Sets the address of the last write block of the continuous range to be erased. */ +#define SDMMC_CMD_ERASE_GRP_START 35U /*!< Sets the address of the first write block to be erased. Reserved for each command + system set by switch function command (CMD6). */ +#define SDMMC_CMD_ERASE_GRP_END 36U /*!< Sets the address of the last write block of the continuous range to be erased. + Reserved for each command system set by switch function command (CMD6). */ +#define SDMMC_CMD_ERASE 38U /*!< Reserved for SD security applications. */ +#define SDMMC_CMD_FAST_IO 39U /*!< SD card doesn't support it (Reserved). */ +#define SDMMC_CMD_GO_IRQ_STATE 40U /*!< SD card doesn't support it (Reserved). */ +#define SDMMC_CMD_LOCK_UNLOCK 42U /*!< Sets/resets the password or lock/unlock the card. The size of the data block is set by + the SET_BLOCK_LEN command. */ +#define SDMMC_CMD_APP_CMD 55U /*!< Indicates to the card that the next command is an application specific command rather + than a standard command. */ +#define SDMMC_CMD_GEN_CMD 56U /*!< Used either to transfer a data block to the card or to get a data block from the card + for general purpose/application specific commands. */ +#define SDMMC_CMD_NO_CMD 64U /*!< No command */ + +/** + * @brief Following commands are SD Card Specific commands. + * SDMMC_APP_CMD should be sent before sending these commands. + */ +#define SDMMC_CMD_APP_SD_SET_BUSWIDTH 6U /*!< (ACMD6) Defines the data bus width to be used for data transfer. The allowed data bus + widths are given in SCR register. */ +#define SDMMC_CMD_SD_APP_STATUS 13U /*!< (ACMD13) Sends the SD status. */ +#define SDMMC_CMD_SD_APP_SEND_NUM_WRITE_BLOCKS 22U /*!< (ACMD22) Sends the number of the written (without errors) write blocks. Responds with + 32bit+CRC data block. */ +#define SDMMC_CMD_SD_APP_OP_COND 41U /*!< (ACMD41) Sends host capacity support information (HCS) and asks the accessed card to + send its operating condition register (OCR) content in the response on the CMD line. */ +#define SDMMC_CMD_SD_APP_SET_CLR_CARD_DETECT 42U /*!< (ACMD42) Connect/Disconnect the 50 KOhm pull-up resistor on CD/DAT3 (pin 1) of the card */ +#define SDMMC_CMD_SD_APP_SEND_SCR 51U /*!< Reads the SD Configuration Register (SCR). */ +#define SDMMC_CMD_SDMMC_RW_DIRECT 52U /*!< For SD I/O card only, reserved for security specification. */ +#define SDMMC_CMD_SDMMC_RW_EXTENDED 53U /*!< For SD I/O card only, reserved for security specification. */ + +/** + * @brief Following commands are SD Card Specific security commands. + * SDMMC_CMD_APP_CMD should be sent before sending these commands. + */ +#define SDMMC_CMD_SD_APP_GET_MKB 43U +#define SDMMC_CMD_SD_APP_GET_MID 44U +#define SDMMC_CMD_SD_APP_SET_CER_RN1 45U +#define SDMMC_CMD_SD_APP_GET_CER_RN2 46U +#define SDMMC_CMD_SD_APP_SET_CER_RES2 47U +#define SDMMC_CMD_SD_APP_GET_CER_RES1 48U +#define SDMMC_CMD_SD_APP_SECURE_READ_MULTIPLE_BLOCK 18U +#define SDMMC_CMD_SD_APP_SECURE_WRITE_MULTIPLE_BLOCK 25U +#define SDMMC_CMD_SD_APP_SECURE_ERASE 38U +#define SDMMC_CMD_SD_APP_CHANGE_SECURE_AREA 49U +#define SDMMC_CMD_SD_APP_SECURE_WRITE_MKB 48U + +/** + * @brief Masks for errors Card Status R1 (OCR Register) + */ +#define SDMMC_OCR_ADDR_OUT_OF_RANGE 0x80000000U +#define SDMMC_OCR_ADDR_MISALIGNED 0x40000000U +#define SDMMC_OCR_BLOCK_LEN_ERR 0x20000000U +#define SDMMC_OCR_ERASE_SEQ_ERR 0x10000000U +#define SDMMC_OCR_BAD_ERASE_PARAM 0x08000000U +#define SDMMC_OCR_WRITE_PROT_VIOLATION 0x04000000U +#define SDMMC_OCR_LOCK_UNLOCK_FAILED 0x01000000U +#define SDMMC_OCR_COM_CRC_FAILED 0x00800000U +#define SDMMC_OCR_ILLEGAL_CMD 0x00400000U +#define SDMMC_OCR_CARD_ECC_FAILED 0x00200000U +#define SDMMC_OCR_CC_ERROR 0x00100000U +#define SDMMC_OCR_GENERAL_UNKNOWN_ERROR 0x00080000U +#define SDMMC_OCR_STREAM_READ_UNDERRUN 0x00040000U +#define SDMMC_OCR_STREAM_WRITE_OVERRUN 0x00020000U +#define SDMMC_OCR_CID_CSD_OVERWRITE 0x00010000U +#define SDMMC_OCR_WP_ERASE_SKIP 0x00008000U +#define SDMMC_OCR_CARD_ECC_DISABLED 0x00004000U +#define SDMMC_OCR_ERASE_RESET 0x00002000U +#define SDMMC_OCR_AKE_SEQ_ERROR 0x00000008U +#define SDMMC_OCR_ERRORBITS 0xFDFFE008U + +/** + * @brief Masks for R6 Response + */ +#define SDMMC_R6_GENERAL_UNKNOWN_ERROR 0x00002000U +#define SDMMC_R6_ILLEGAL_CMD 0x00004000U +#define SDMMC_R6_COM_CRC_FAILED 0x00008000U + +#define SDMMC_VOLTAGE_WINDOW_SD 0x80100000U +#define SDMMC_HIGH_CAPACITY 0x40000000U +#define SDMMC_STD_CAPACITY 0x00000000U +#define SDMMC_CHECK_PATTERN 0x000001AAU +#define SD_SWITCH_1_8V_CAPACITY 0x01000000U + +#define SDMMC_MAX_VOLT_TRIAL 0x0000FFFFU + +#define SDMMC_MAX_TRIAL 0x0000FFFFU + +#define SDMMC_ALLZERO 0x00000000U + +#define SDMMC_WIDE_BUS_SUPPORT 0x00040000U +#define SDMMC_SINGLE_BUS_SUPPORT 0x00010000U +#define SDMMC_CARD_LOCKED 0x02000000U + +#ifndef SDMMC_DATATIMEOUT +#define SDMMC_DATATIMEOUT 0xFFFFFFFFU +#endif /* SDMMC_DATATIMEOUT */ + +#define SDMMC_0TO7BITS 0x000000FFU +#define SDMMC_8TO15BITS 0x0000FF00U +#define SDMMC_16TO23BITS 0x00FF0000U +#define SDMMC_24TO31BITS 0xFF000000U +#define SDMMC_MAX_DATA_LENGTH 0x01FFFFFFU + +#define SDMMC_HALFFIFO 0x00000008U +#define SDMMC_HALFFIFOBYTES 0x00000020U + +/** + * @brief Command Class supported + */ +#define SDIO_CCCC_ERASE 0x00000020U + +#define SDIO_CMDTIMEOUT 5000U /* Command send and response timeout */ +#define SDIO_MAXERASETIMEOUT 63000U /* Max erase Timeout 63 s */ +#define SDIO_STOPTRANSFERTIMEOUT 100000000U /* Timeout for STOP TRANSMISSION command */ + +/** @defgroup SDIO_DDL_Clock_Edge Clock Edge + * @{ + */ +#define SDIO_CLOCK_EDGE_RISING 0x00000000U +#define SDIO_CLOCK_EDGE_FALLING SDIO_CLKCTRL_DEPSEL + +#define IS_SDIO_CLOCK_EDGE(EDGE) (((EDGE) == SDIO_CLOCK_EDGE_RISING) || \ + ((EDGE) == SDIO_CLOCK_EDGE_FALLING)) +/** + * @} + */ + +/** @defgroup SDIO_DDL_Clock_Bypass Clock Bypass + * @{ + */ +#define SDIO_CLOCK_BYPASS_DISABLE 0x00000000U +#define SDIO_CLOCK_BYPASS_ENABLE SDIO_CLKCTRL_BYPASSEN + +#define IS_SDIO_CLOCK_BYPASS(BYPASS) (((BYPASS) == SDIO_CLOCK_BYPASS_DISABLE) || \ + ((BYPASS) == SDIO_CLOCK_BYPASS_ENABLE)) +/** + * @} + */ + +/** @defgroup SDIO_DDL_Clock_Power_Save Clock Power Saving + * @{ + */ +#define SDIO_CLOCK_POWER_SAVE_DISABLE 0x00000000U +#define SDIO_CLOCK_POWER_SAVE_ENABLE SDIO_CLKCTRL_PWRSAV + +#define IS_SDIO_CLOCK_POWER_SAVE(SAVE) (((SAVE) == SDIO_CLOCK_POWER_SAVE_DISABLE) || \ + ((SAVE) == SDIO_CLOCK_POWER_SAVE_ENABLE)) +/** + * @} + */ + +/** @defgroup SDIO_DDL_Bus_Wide Bus Width + * @{ + */ +#define SDIO_BUS_WIDE_1B 0x00000000U +#define SDIO_BUS_WIDE_4B SDIO_CLKCTRL_WBSEL_0 +#define SDIO_BUS_WIDE_8B SDIO_CLKCTRL_WBSEL_1 + +#define IS_SDIO_BUS_WIDE(WIDE) (((WIDE) == SDIO_BUS_WIDE_1B) || \ + ((WIDE) == SDIO_BUS_WIDE_4B) || \ + ((WIDE) == SDIO_BUS_WIDE_8B)) +/** + * @} + */ + +/** @defgroup SDIO_DDL_Hardware_Flow_Control Hardware Flow Control + * @{ + */ +#define SDIO_HARDWARE_FLOW_CONTROL_DISABLE 0x00000000U +#define SDIO_HARDWARE_FLOW_CONTROL_ENABLE SDIO_CLKCTRL_HFCEN_EN + +#define IS_SDIO_HARDWARE_FLOW_CONTROL(CONTROL) (((CONTROL) == SDIO_HARDWARE_FLOW_CONTROL_DISABLE) || \ + ((CONTROL) == SDIO_HARDWARE_FLOW_CONTROL_ENABLE)) +/** + * @} + */ + +/** @defgroup SDIO_DDL_Clock_Division Clock Division + * @{ + */ +#define IS_SDIO_CLKDIV(DIV) ((DIV) <= 0xFFU) +/** + * @} + */ + +/** @defgroup SDIO_DDL_Command_Index Command Index + * @{ + */ +#define IS_SDIO_CMD_INDEX(INDEX) ((INDEX) < 0x40U) +/** + * @} + */ + +/** @defgroup SDIO_DDL_Response_Type Response Type + * @{ + */ +#define SDIO_RESPONSE_NO 0x00000000U +#define SDIO_RESPONSE_SHORT SDIO_CMD_WAITRES_0 +#define SDIO_RESPONSE_LONG SDIO_CMD_WAITRES + +#define IS_SDIO_RESPONSE(RESPONSE) (((RESPONSE) == SDIO_RESPONSE_NO) || \ + ((RESPONSE) == SDIO_RESPONSE_SHORT) || \ + ((RESPONSE) == SDIO_RESPONSE_LONG)) +/** + * @} + */ + +/** @defgroup SDIO_DDL_Wait_Interrupt_State Wait Interrupt + * @{ + */ +#define SDIO_WAIT_NO 0x00000000U +#define SDIO_WAIT_IT SDIO_CMD_WAITINT +#define SDIO_WAIT_PEND SDIO_CMD_WENDDATA + +#define IS_SDIO_WAIT(WAIT) (((WAIT) == SDIO_WAIT_NO) || \ + ((WAIT) == SDIO_WAIT_IT) || \ + ((WAIT) == SDIO_WAIT_PEND)) +/** + * @} + */ + +/** @defgroup SDIO_DDL_CPSM_State CPSM State + * @{ + */ +#define SDIO_CPSM_DISABLE 0x00000000U +#define SDIO_CPSM_ENABLE SDIO_CMD_CPSMEN + +#define IS_SDIO_CPSM(CPSM) (((CPSM) == SDIO_CPSM_DISABLE) || \ + ((CPSM) == SDIO_CPSM_ENABLE)) +/** + * @} + */ + +/** @defgroup SDIO_DDL_Response_Registers Response Register + * @{ + */ +#define SDIO_RES1 0x00000000U +#define SDIO_RES2 0x00000004U +#define SDIO_RES3 0x00000008U +#define SDIO_RES4 0x0000000CU + +#define IS_SDIO_RESP(RESP) (((RESP) == SDIO_RES1) || \ + ((RESP) == SDIO_RES2) || \ + ((RESP) == SDIO_RES3) || \ + ((RESP) == SDIO_RES4)) +/** + * @} + */ + +/** @defgroup SDIO_DDL_Data_Length Data Length + * @{ + */ +#define IS_SDIO_DATA_LENGTH(LENGTH) ((LENGTH) <= 0x01FFFFFFU) +/** + * @} + */ + +/** @defgroup SDIO_DDL_Data_Block_Size Data Block Size + * @{ + */ +#define SDIO_DATABLOCK_SIZE_1B 0x00000000U +#define SDIO_DATABLOCK_SIZE_2B SDIO_DCTRL_DBSIZE_0 +#define SDIO_DATABLOCK_SIZE_4B SDIO_DCTRL_DBSIZE_1 +#define SDIO_DATABLOCK_SIZE_8B (SDIO_DCTRL_DBSIZE_0|SDIO_DCTRL_DBSIZE_1) +#define SDIO_DATABLOCK_SIZE_16B SDIO_DCTRL_DBSIZE_2 +#define SDIO_DATABLOCK_SIZE_32B (SDIO_DCTRL_DBSIZE_0|SDIO_DCTRL_DBSIZE_2) +#define SDIO_DATABLOCK_SIZE_64B (SDIO_DCTRL_DBSIZE_1|SDIO_DCTRL_DBSIZE_2) +#define SDIO_DATABLOCK_SIZE_128B (SDIO_DCTRL_DBSIZE_0|SDIO_DCTRL_DBSIZE_1|SDIO_DCTRL_DBSIZE_2) +#define SDIO_DATABLOCK_SIZE_256B SDIO_DCTRL_DBSIZE_3 +#define SDIO_DATABLOCK_SIZE_512B (SDIO_DCTRL_DBSIZE_0|SDIO_DCTRL_DBSIZE_3) +#define SDIO_DATABLOCK_SIZE_1024B (SDIO_DCTRL_DBSIZE_1|SDIO_DCTRL_DBSIZE_3) +#define SDIO_DATABLOCK_SIZE_2048B (SDIO_DCTRL_DBSIZE_0|SDIO_DCTRL_DBSIZE_1|SDIO_DCTRL_DBSIZE_3) +#define SDIO_DATABLOCK_SIZE_4096B (SDIO_DCTRL_DBSIZE_2|SDIO_DCTRL_DBSIZE_3) +#define SDIO_DATABLOCK_SIZE_8192B (SDIO_DCTRL_DBSIZE_0|SDIO_DCTRL_DBSIZE_2|SDIO_DCTRL_DBSIZE_3) +#define SDIO_DATABLOCK_SIZE_16384B (SDIO_DCTRL_DBSIZE_1|SDIO_DCTRL_DBSIZE_2|SDIO_DCTRL_DBSIZE_3) + +#define IS_SDIO_BLOCK_SIZE(SIZE) (((SIZE) == SDIO_DATABLOCK_SIZE_1B) || \ + ((SIZE) == SDIO_DATABLOCK_SIZE_2B) || \ + ((SIZE) == SDIO_DATABLOCK_SIZE_4B) || \ + ((SIZE) == SDIO_DATABLOCK_SIZE_8B) || \ + ((SIZE) == SDIO_DATABLOCK_SIZE_16B) || \ + ((SIZE) == SDIO_DATABLOCK_SIZE_32B) || \ + ((SIZE) == SDIO_DATABLOCK_SIZE_64B) || \ + ((SIZE) == SDIO_DATABLOCK_SIZE_128B) || \ + ((SIZE) == SDIO_DATABLOCK_SIZE_256B) || \ + ((SIZE) == SDIO_DATABLOCK_SIZE_512B) || \ + ((SIZE) == SDIO_DATABLOCK_SIZE_1024B) || \ + ((SIZE) == SDIO_DATABLOCK_SIZE_2048B) || \ + ((SIZE) == SDIO_DATABLOCK_SIZE_4096B) || \ + ((SIZE) == SDIO_DATABLOCK_SIZE_8192B) || \ + ((SIZE) == SDIO_DATABLOCK_SIZE_16384B)) +/** + * @} + */ + +/** @defgroup SDIO_DDL_Transfer_Direction Transfer Direction + * @{ + */ +#define SDIO_TRANSFER_DIR_TO_CARD 0x00000000U +#define SDIO_TRANSFER_DIR_TO_SDIO SDIO_DCTRL_DTDRCFG + +#define IS_SDIO_TRANSFER_DIR(DIR) (((DIR) == SDIO_TRANSFER_DIR_TO_CARD) || \ + ((DIR) == SDIO_TRANSFER_DIR_TO_SDIO)) +/** + * @} + */ + +/** @defgroup SDIO_DDL_Transfer_Type Transfer Type + * @{ + */ +#define SDIO_TRANSFER_MODE_BLOCK 0x00000000U +#define SDIO_TRANSFER_MODE_STREAM SDIO_DCTRL_DTSEL + +#define IS_SDIO_TRANSFER_MODE(MODE) (((MODE) == SDIO_TRANSFER_MODE_BLOCK) || \ + ((MODE) == SDIO_TRANSFER_MODE_STREAM)) +/** + * @} + */ + +/** @defgroup SDIO_DDL_DPSM_State DPSM State + * @{ + */ +#define SDIO_DPSM_DISABLE 0x00000000U +#define SDIO_DPSM_ENABLE SDIO_DCTRL_DTEN + +#define IS_SDIO_DPSM(DPSM) (((DPSM) == SDIO_DPSM_DISABLE) ||\ + ((DPSM) == SDIO_DPSM_ENABLE)) +/** + * @} + */ + +/** @defgroup SDIO_DDL_Read_Wait_Mode Read Wait Mode + * @{ + */ +#define SDIO_READ_WAIT_MODE_DATA2 0x00000000U +#define SDIO_READ_WAIT_MODE_CLK (SDIO_DCTRL_RDWAIT) + +#define IS_SDIO_READWAIT_MODE(MODE) (((MODE) == SDIO_READ_WAIT_MODE_CLK) || \ + ((MODE) == SDIO_READ_WAIT_MODE_DATA2)) +/** + * @} + */ + +/** @defgroup SDIO_DDL_Interrupt_sources Interrupt Sources + * @{ + */ +#define SDIO_IT_CCRCFAIL SDIO_MASK_CCRCFAIL +#define SDIO_IT_DCRCFAIL SDIO_MASK_DCRCFAIL +#define SDIO_IT_CTIMEOUT SDIO_MASK_CMDTO +#define SDIO_IT_DTIMEOUT SDIO_MASK_DATATO +#define SDIO_IT_TXUNDERR SDIO_MASK_TXURER +#define SDIO_IT_RXOVERR SDIO_MASK_RXORER +#define SDIO_IT_CMDREND SDIO_MASK_CMDRESRC +#define SDIO_IT_CMDSENT SDIO_MASK_CMDSENT +#define SDIO_IT_DATAEND SDIO_MASK_DATAEND +#if defined(SDIO_STS_SBE) +#define SDIO_IT_STBITERR SDIO_MASK_STRTER +#endif +#define SDIO_IT_DBCKEND SDIO_MASK_DBEND +#define SDIO_IT_CMDACT SDIO_MASK_CMDACT +#define SDIO_IT_TXACT SDIO_MASK_TXACT +#define SDIO_IT_RXACT SDIO_MASK_RXACT +#define SDIO_IT_TXFIFOHE SDIO_MASK_TXHFERT +#define SDIO_IT_RXFIFOHF SDIO_MASK_RXHFFUL +#define SDIO_IT_TXFIFOF SDIO_MASK_TXFUL +#define SDIO_IT_RXFIFOF SDIO_MASK_RXFUL +#define SDIO_IT_TXFIFOE SDIO_MASK_TXEPT +#define SDIO_IT_RXFIFOE SDIO_MASK_RXFEIE +#define SDIO_IT_TXDAVL SDIO_MASK_TXDAVB +#define SDIO_IT_RXDAVL SDIO_MASK_RXDAVB +#define SDIO_IT_SDIOIT SDIO_MASK_SDIOINTREC +#if defined(SDIO_CMD_ATACMD) +#define SDIO_IT_CEATAEND SDIO_MASK_ATACLPREC +#endif +/** + * @} + */ + +/** @defgroup SDIO_DDL_Flags Flags + * @{ + */ +#define SDIO_FLAG_CCRCFAIL SDIO_STS_COMRESP +#define SDIO_FLAG_DCRCFAIL SDIO_STS_DBDR +#define SDIO_FLAG_CTIMEOUT SDIO_STS_CMDRESTO +#define SDIO_FLAG_DTIMEOUT SDIO_STS_DATATO +#define SDIO_FLAG_TXUNDERR SDIO_STS_TXUDRER +#define SDIO_FLAG_RXOVERR SDIO_STS_RXOVRER +#define SDIO_FLAG_CMDREND SDIO_STS_CMDRES +#define SDIO_FLAG_CMDSENT SDIO_STS_CMDSENT +#define SDIO_FLAG_DATAEND SDIO_STS_DATAEND +#if defined(SDIO_STS_SBE) +#define SDIO_FLAG_STBITERR SDIO_STS_SBE +#endif +#define SDIO_FLAG_DBCKEND SDIO_STS_DBCP +#define SDIO_FLAG_CMDACT SDIO_STS_CMDACT +#define SDIO_FLAG_TXACT SDIO_STS_TXACT +#define SDIO_FLAG_RXACT SDIO_STS_RXACT +#define SDIO_FLAG_TXFIFOHE SDIO_STS_TXFHF +#define SDIO_FLAG_RXFIFOHF SDIO_STS_RXFHF +#define SDIO_FLAG_TXFIFOF SDIO_STS_TXFF +#define SDIO_FLAG_RXFIFOF SDIO_STS_RXFF +#define SDIO_FLAG_TXFIFOE SDIO_STS_TXFE +#define SDIO_FLAG_RXFIFOE SDIO_STS_RXFE +#define SDIO_FLAG_TXDAVL SDIO_STS_TXDA +#define SDIO_FLAG_RXDAVL SDIO_STS_RXDA +#define SDIO_FLAG_SDIOIT SDIO_STS_SDIOINT +#if defined(SDIO_CMD_ATACMD) +#define SDIO_FLAG_CEATAEND SDIO_STS_ATAEND +#endif +#define SDIO_STATIC_FLAGS ((uint32_t)(SDIO_FLAG_CCRCFAIL | SDIO_FLAG_DCRCFAIL | SDIO_FLAG_CTIMEOUT |\ + SDIO_FLAG_DTIMEOUT | SDIO_FLAG_TXUNDERR | SDIO_FLAG_RXOVERR |\ + SDIO_FLAG_CMDREND | SDIO_FLAG_CMDSENT | SDIO_FLAG_DATAEND |\ + SDIO_FLAG_DBCKEND | SDIO_FLAG_SDIOIT)) + +#define SDIO_STATIC_CMD_FLAGS ((uint32_t)(SDIO_FLAG_CCRCFAIL | SDIO_FLAG_CTIMEOUT | SDIO_FLAG_CMDREND |\ + SDIO_FLAG_CMDSENT)) + +#define SDIO_STATIC_DATA_FLAGS ((uint32_t)(SDIO_FLAG_DCRCFAIL | SDIO_FLAG_DTIMEOUT | SDIO_FLAG_TXUNDERR |\ + SDIO_FLAG_RXOVERR | SDIO_FLAG_DATAEND | SDIO_FLAG_DBCKEND)) +/** + * @} + */ + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ +/** @defgroup SDIO_DDL_Exported_macros SDIO_LL Exported Macros + * @{ + */ + +/** @defgroup SDMMC_DDL_Alias_Region Bit Address in the alias region + * @{ + */ +/* ------------ SDIO registers bit address in the alias region -------------- */ +#define SDIO_OFFSET (SDIO_BASE - PERIPH_BASE) + +/* --- CLKCR Register ---*/ +/* Alias word address of CLKEN bit */ +#define CLKCTRL_OFFSET (SDIO_OFFSET + 0x04U) +#define CLKEN_BITNUMBER 0x08U +#define CLKCTRL_CLKEN_BB (PERIPH_BB_BASE + (CLKCTRL_OFFSET * 32U) + (CLKEN_BITNUMBER * 4U)) + +/* --- CMD Register ---*/ +/* Alias word address of SDIOSUSPEND bit */ +#define CMD_OFFSET (SDIO_OFFSET + 0x0CU) +#define SDIOSUSPEND_BITNUMBER 0x0BU +#define CMD_SDIOSUSPEND_BB (PERIPH_BB_BASE + (CMD_OFFSET * 32U) + (SDIOSUSPEND_BITNUMBER * 4U)) + +/* Alias word address of ENCMDCOMPL bit */ +#define ENCMDCOMPL_BITNUMBER 0x0CU +#define CMD_ENCMDCOMPL_BB (PERIPH_BB_BASE + (CMD_OFFSET * 32U) + (ENCMDCOMPL_BITNUMBER * 4U)) + +/* Alias word address of NIEN bit */ +#define NIEN_BITNUMBER 0x0DU +#define CMD_NIEN_BB (PERIPH_BB_BASE + (CMD_OFFSET * 32U) + (NIEN_BITNUMBER * 4U)) + +/* Alias word address of ATACMD bit */ +#define ATACMD_BITNUMBER 0x0EU +#define CMD_ATACMD_BB (PERIPH_BB_BASE + (CMD_OFFSET * 32U) + (ATACMD_BITNUMBER * 4U)) + +/* --- DCTRL Register ---*/ +/* Alias word address of DMAEN bit */ +#define DCTRL_OFFSET (SDIO_OFFSET + 0x2CU) +#define DMAEN_BITNUMBER 0x03U +#define DCTRL_DMAEN_BB (PERIPH_BB_BASE + (DCTRL_OFFSET * 32U) + (DMAEN_BITNUMBER * 4U)) + +/* Alias word address of RWSTART bit */ +#define RWSTART_BITNUMBER 0x08U +#define DCTRL_RWSTART_BB (PERIPH_BB_BASE + (DCTRL_OFFSET * 32U) + (RWSTART_BITNUMBER * 4U)) + +/* Alias word address of RWSTOP bit */ +#define RWSTOP_BITNUMBER 0x09U +#define DCTRL_RWSTOP_BB (PERIPH_BB_BASE + (DCTRL_OFFSET * 32U) + (RWSTOP_BITNUMBER * 4U)) + +/* Alias word address of RWMOD bit */ +#define RWMOD_BITNUMBER 0x0AU +#define DCTRL_RWMOD_BB (PERIPH_BB_BASE + (DCTRL_OFFSET * 32U) + (RWMOD_BITNUMBER * 4U)) + +/* Alias word address of SDIOEN bit */ +#define SDIOEN_BITNUMBER 0x0BU +#define DCTRL_SDIOEN_BB (PERIPH_BB_BASE + (DCTRL_OFFSET * 32U) + (SDIOEN_BITNUMBER * 4U)) +/** + * @} + */ + +/** @defgroup SDIO_DDL_Register Bits And Addresses Definitions + * @brief SDIO_LL registers bit address in the alias region + * @{ + */ +/* ---------------------- SDIO registers bit mask --------------------------- */ +/* --- CLKCTRL Register ---*/ +/* CLKCTRL register clear mask */ +#define CLKCTRL_CLEAR_MASK ((uint32_t)(SDIO_CLKCTRL_CLKDIV | SDIO_CLKCTRL_PWRSAV |\ + SDIO_CLKCTRL_BYPASSEN | SDIO_CLKCTRL_WBSEL |\ + SDIO_CLKCTRL_DEPSEL | SDIO_CLKCTRL_HFCEN_EN)) + +/* --- DCTRL Register ---*/ +/* SDIO DCTRL Clear Mask */ +#define DCTRL_CLEAR_MASK ((uint32_t)(SDIO_DCTRL_DTEN | SDIO_DCTRL_DTDRCFG |\ + SDIO_DCTRL_DTSEL | SDIO_DCTRL_DBSIZE)) + +/* --- CMD Register ---*/ +/* CMD Register clear mask */ +#define CMD_CLEAR_MASK ((uint32_t)(SDIO_CMD_CMDINDEX | SDIO_CMD_WAITRES |\ + SDIO_CMD_WAITINT | SDIO_CMD_WENDDATA |\ + SDIO_CMD_CPSMEN | SDIO_CMD_SDIOSC)) + +/* SDIO Initialization Frequency (400KHz max) */ +#define SDIO_INIT_CLK_DIV ((uint8_t)0x76) /* 48MHz / (SDMMC_INIT_CLK_DIV + 2) < 400KHz */ + +/* SDIO Data Transfer Frequency (25MHz max) */ +#define SDIO_TRANSFER_CLK_DIV ((uint8_t)0x0) /* 48MHz / (SDMMC_TRANSFER_CLK_DIV + 2) < 25MHz */ +/** + * @} + */ + +/** @defgroup SDIO_DDL_Interrupt_Clock Interrupt And Clock Configuration + * @brief macros to handle interrupts and specific clock configurations + * @{ + */ + +/** + * @brief Enable the SDIO device. + * @param __INSTANCE__: SDIO Instance + * @retval None + */ +#define __SDIO_ENABLE(__INSTANCE__) (*(__IO uint32_t *)CLKCTRL_CLKEN_BB = ENABLE) + +/** + * @brief Disable the SDIO device. + * @param __INSTANCE__: SDIO Instance + * @retval None + */ +#define __SDIO_DISABLE(__INSTANCE__) (*(__IO uint32_t *)CLKCTRL_CLKEN_BB = DISABLE) + +/** + * @brief Enable the SDIO DMA transfer. + * @param __INSTANCE__: SDIO Instance + * @retval None + */ +#define __SDIO_DMA_ENABLE(__INSTANCE__) (*(__IO uint32_t *)DCTRL_DMAEN_BB = ENABLE) + +/** + * @brief Disable the SDIO DMA transfer. + * @param __INSTANCE__: SDIO Instance + * @retval None + */ +#define __SDIO_DMA_DISABLE(__INSTANCE__) (*(__IO uint32_t *)DCTRL_DMAEN_BB = DISABLE) + +/** + * @brief Enable the SDIO device interrupt. + * @param __INSTANCE__ : Pointer to SDIO register base + * @param __INTERRUPT__ : specifies the SDIO interrupt sources to be enabled. + * This parameter can be one or a combination of the following values: + * @arg SDIO_IT_CCRCFAIL: Command response received (CRC check failed) interrupt + * @arg SDIO_IT_DCRCFAIL: Data block sent/received (CRC check failed) interrupt + * @arg SDIO_IT_CTIMEOUT: Command response timeout interrupt + * @arg SDIO_IT_DTIMEOUT: Data timeout interrupt + * @arg SDIO_IT_TXUNDERR: Transmit FIFO underrun error interrupt + * @arg SDIO_IT_RXOVERR: Received FIFO overrun error interrupt + * @arg SDIO_IT_CMDREND: Command response received (CRC check passed) interrupt + * @arg SDIO_IT_CMDSENT: Command sent (no response required) interrupt + * @arg SDIO_IT_DATAEND: Data end (data counter, DATACOUNT, is zero) interrupt + * @arg SDIO_IT_DBCKEND: Data block sent/received (CRC check passed) interrupt + * @arg SDIO_IT_CMDACT: Command transfer in progress interrupt + * @arg SDIO_IT_TXACT: Data transmit in progress interrupt + * @arg SDIO_IT_RXACT: Data receive in progress interrupt + * @arg SDIO_IT_TXFIFOHE: Transmit FIFO Half Empty interrupt + * @arg SDIO_IT_RXFIFOHF: Receive FIFO Half Full interrupt + * @arg SDIO_IT_TXFIFOF: Transmit FIFO full interrupt + * @arg SDIO_IT_RXFIFOF: Receive FIFO full interrupt + * @arg SDIO_IT_TXFIFOE: Transmit FIFO empty interrupt + * @arg SDIO_IT_RXFIFOE: Receive FIFO empty interrupt + * @arg SDIO_IT_TXDAVL: Data available in transmit FIFO interrupt + * @arg SDIO_IT_RXDAVL: Data available in receive FIFO interrupt + * @arg SDIO_IT_SDIOIT: SDIO interrupt received interrupt + * @retval None + */ +#define __SDIO_ENABLE_IT(__INSTANCE__, __INTERRUPT__) ((__INSTANCE__)->MASK |= (__INTERRUPT__)) + +/** + * @brief Disable the SDIO device interrupt. + * @param __INSTANCE__ : Pointer to SDIO register base + * @param __INTERRUPT__ : specifies the SDIO interrupt sources to be disabled. + * This parameter can be one or a combination of the following values: + * @arg SDIO_IT_CCRCFAIL: Command response received (CRC check failed) interrupt + * @arg SDIO_IT_DCRCFAIL: Data block sent/received (CRC check failed) interrupt + * @arg SDIO_IT_CTIMEOUT: Command response timeout interrupt + * @arg SDIO_IT_DTIMEOUT: Data timeout interrupt + * @arg SDIO_IT_TXUNDERR: Transmit FIFO underrun error interrupt + * @arg SDIO_IT_RXOVERR: Received FIFO overrun error interrupt + * @arg SDIO_IT_CMDREND: Command response received (CRC check passed) interrupt + * @arg SDIO_IT_CMDSENT: Command sent (no response required) interrupt + * @arg SDIO_IT_DATAEND: Data end (data counter, DATACOUNT, is zero) interrupt + * @arg SDIO_IT_DBCKEND: Data block sent/received (CRC check passed) interrupt + * @arg SDIO_IT_CMDACT: Command transfer in progress interrupt + * @arg SDIO_IT_TXACT: Data transmit in progress interrupt + * @arg SDIO_IT_RXACT: Data receive in progress interrupt + * @arg SDIO_IT_TXFIFOHE: Transmit FIFO Half Empty interrupt + * @arg SDIO_IT_RXFIFOHF: Receive FIFO Half Full interrupt + * @arg SDIO_IT_TXFIFOF: Transmit FIFO full interrupt + * @arg SDIO_IT_RXFIFOF: Receive FIFO full interrupt + * @arg SDIO_IT_TXFIFOE: Transmit FIFO empty interrupt + * @arg SDIO_IT_RXFIFOE: Receive FIFO empty interrupt + * @arg SDIO_IT_TXDAVL: Data available in transmit FIFO interrupt + * @arg SDIO_IT_RXDAVL: Data available in receive FIFO interrupt + * @arg SDIO_IT_SDIOIT: SDIO interrupt received interrupt + * @retval None + */ +#define __SDIO_DISABLE_IT(__INSTANCE__, __INTERRUPT__) ((__INSTANCE__)->MASK &= ~(__INTERRUPT__)) + +/** + * @brief Checks whether the specified SDIO flag is set or not. + * @param __INSTANCE__ : Pointer to SDIO register base + * @param __FLAG__: specifies the flag to check. + * This parameter can be one of the following values: + * @arg SDIO_FLAG_CCRCFAIL: Command response received (CRC check failed) + * @arg SDIO_FLAG_DCRCFAIL: Data block sent/received (CRC check failed) + * @arg SDIO_FLAG_CTIMEOUT: Command response timeout + * @arg SDIO_FLAG_DTIMEOUT: Data timeout + * @arg SDIO_FLAG_TXUNDERR: Transmit FIFO underrun error + * @arg SDIO_FLAG_RXOVERR: Received FIFO overrun error + * @arg SDIO_FLAG_CMDREND: Command response received (CRC check passed) + * @arg SDIO_FLAG_CMDSENT: Command sent (no response required) + * @arg SDIO_FLAG_DATAEND: Data end (data counter, DATACOUNT, is zero) + * @arg SDIO_FLAG_DBCKEND: Data block sent/received (CRC check passed) + * @arg SDIO_FLAG_CMDACT: Command transfer in progress + * @arg SDIO_FLAG_TXACT: Data transmit in progress + * @arg SDIO_FLAG_RXACT: Data receive in progress + * @arg SDIO_FLAG_TXFIFOHE: Transmit FIFO Half Empty + * @arg SDIO_FLAG_RXFIFOHF: Receive FIFO Half Full + * @arg SDIO_FLAG_TXFIFOF: Transmit FIFO full + * @arg SDIO_FLAG_RXFIFOF: Receive FIFO full + * @arg SDIO_FLAG_TXFIFOE: Transmit FIFO empty + * @arg SDIO_FLAG_RXFIFOE: Receive FIFO empty + * @arg SDIO_FLAG_TXDAVL: Data available in transmit FIFO + * @arg SDIO_FLAG_RXDAVL: Data available in receive FIFO + * @arg SDIO_FLAG_SDIOIT: SDIO interrupt received + * @retval The new state of SDIO_FLAG (SET or RESET). + */ +#define __SDIO_GET_FLAG(__INSTANCE__, __FLAG__) (((__INSTANCE__)->STS &(__FLAG__)) != 0U) + + +/** + * @brief Clears the SDIO pending flags. + * @param __INSTANCE__ : Pointer to SDIO register base + * @param __FLAG__: specifies the flag to clear. + * This parameter can be one or a combination of the following values: + * @arg SDIO_FLAG_CCRCFAIL: Command response received (CRC check failed) + * @arg SDIO_FLAG_DCRCFAIL: Data block sent/received (CRC check failed) + * @arg SDIO_FLAG_CTIMEOUT: Command response timeout + * @arg SDIO_FLAG_DTIMEOUT: Data timeout + * @arg SDIO_FLAG_TXUNDERR: Transmit FIFO underrun error + * @arg SDIO_FLAG_RXOVERR: Received FIFO overrun error + * @arg SDIO_FLAG_CMDREND: Command response received (CRC check passed) + * @arg SDIO_FLAG_CMDSENT: Command sent (no response required) + * @arg SDIO_FLAG_DATAEND: Data end (data counter, DATACOUNT, is zero) + * @arg SDIO_FLAG_DBCKEND: Data block sent/received (CRC check passed) + * @arg SDIO_FLAG_SDIOIT: SDIO interrupt received + * @retval None + */ +#define __SDIO_CLEAR_FLAG(__INSTANCE__, __FLAG__) ((__INSTANCE__)->ICF = (__FLAG__)) + +/** + * @brief Checks whether the specified SDIO interrupt has occurred or not. + * @param __INSTANCE__ : Pointer to SDIO register base + * @param __INTERRUPT__: specifies the SDIO interrupt source to check. + * This parameter can be one of the following values: + * @arg SDIO_IT_CCRCFAIL: Command response received (CRC check failed) interrupt + * @arg SDIO_IT_DCRCFAIL: Data block sent/received (CRC check failed) interrupt + * @arg SDIO_IT_CTIMEOUT: Command response timeout interrupt + * @arg SDIO_IT_DTIMEOUT: Data timeout interrupt + * @arg SDIO_IT_TXUNDERR: Transmit FIFO underrun error interrupt + * @arg SDIO_IT_RXOVERR: Received FIFO overrun error interrupt + * @arg SDIO_IT_CMDREND: Command response received (CRC check passed) interrupt + * @arg SDIO_IT_CMDSENT: Command sent (no response required) interrupt + * @arg SDIO_IT_DATAEND: Data end (data counter, DATACOUNT, is zero) interrupt + * @arg SDIO_IT_DBCKEND: Data block sent/received (CRC check passed) interrupt + * @arg SDIO_IT_CMDACT: Command transfer in progress interrupt + * @arg SDIO_IT_TXACT: Data transmit in progress interrupt + * @arg SDIO_IT_RXACT: Data receive in progress interrupt + * @arg SDIO_IT_TXFIFOHE: Transmit FIFO Half Empty interrupt + * @arg SDIO_IT_RXFIFOHF: Receive FIFO Half Full interrupt + * @arg SDIO_IT_TXFIFOF: Transmit FIFO full interrupt + * @arg SDIO_IT_RXFIFOF: Receive FIFO full interrupt + * @arg SDIO_IT_TXFIFOE: Transmit FIFO empty interrupt + * @arg SDIO_IT_RXFIFOE: Receive FIFO empty interrupt + * @arg SDIO_IT_TXDAVL: Data available in transmit FIFO interrupt + * @arg SDIO_IT_RXDAVL: Data available in receive FIFO interrupt + * @arg SDIO_IT_SDIOIT: SDIO interrupt received interrupt + * @retval The new state of SDIO_IT (SET or RESET). + */ +#define __SDIO_GET_IT(__INSTANCE__, __INTERRUPT__) (((__INSTANCE__)->STS &(__INTERRUPT__)) == (__INTERRUPT__)) + +/** + * @brief Clears the SDIO's interrupt pending bits. + * @param __INSTANCE__ : Pointer to SDIO register base + * @param __INTERRUPT__: specifies the interrupt pending bit to clear. + * This parameter can be one or a combination of the following values: + * @arg SDIO_IT_CCRCFAIL: Command response received (CRC check failed) interrupt + * @arg SDIO_IT_DCRCFAIL: Data block sent/received (CRC check failed) interrupt + * @arg SDIO_IT_CTIMEOUT: Command response timeout interrupt + * @arg SDIO_IT_DTIMEOUT: Data timeout interrupt + * @arg SDIO_IT_TXUNDERR: Transmit FIFO underrun error interrupt + * @arg SDIO_IT_RXOVERR: Received FIFO overrun error interrupt + * @arg SDIO_IT_CMDREND: Command response received (CRC check passed) interrupt + * @arg SDIO_IT_CMDSENT: Command sent (no response required) interrupt + * @arg SDIO_IT_DATAEND: Data end (data counter, DATACOUNT, is zero) interrupt + * @arg SDIO_IT_SDIOIT: SDIO interrupt received interrupt + * @retval None + */ +#define __SDIO_CLEAR_IT(__INSTANCE__, __INTERRUPT__) ((__INSTANCE__)->ICF = (__INTERRUPT__)) + +/** + * @brief Enable Start the SD I/O Read Wait operation. + * @param __INSTANCE__ : Pointer to SDIO register base + * @retval None + */ +#define __SDIO_START_READWAIT_ENABLE(__INSTANCE__) (*(__IO uint32_t *) DCTRL_RWSTART_BB = ENABLE) + +/** + * @brief Disable Start the SD I/O Read Wait operations. + * @param __INSTANCE__ : Pointer to SDIO register base + * @retval None + */ +#define __SDIO_START_READWAIT_DISABLE(__INSTANCE__) (*(__IO uint32_t *) DCTRL_RWSTART_BB = DISABLE) + +/** + * @brief Enable Start the SD I/O Read Wait operation. + * @param __INSTANCE__ : Pointer to SDIO register base + * @retval None + */ +#define __SDIO_STOP_READWAIT_ENABLE(__INSTANCE__) (*(__IO uint32_t *) DCTRL_RWSTOP_BB = ENABLE) + +/** + * @brief Disable Stop the SD I/O Read Wait operations. + * @param __INSTANCE__ : Pointer to SDIO register base + * @retval None + */ +#define __SDIO_STOP_READWAIT_DISABLE(__INSTANCE__) (*(__IO uint32_t *) DCTRL_RWSTOP_BB = DISABLE) + +/** + * @brief Enable the SD I/O Mode Operation. + * @param __INSTANCE__ : Pointer to SDIO register base + * @retval None + */ +#define __SDIO_OPERATION_ENABLE(__INSTANCE__) (*(__IO uint32_t *) DCTRL_SDIOEN_BB = ENABLE) + +/** + * @brief Disable the SD I/O Mode Operation. + * @param __INSTANCE__ : Pointer to SDIO register base + * @retval None + */ +#define __SDIO_OPERATION_DISABLE(__INSTANCE__) (*(__IO uint32_t *) DCTRL_SDIOEN_BB = DISABLE) + +/** + * @brief Enable the SD I/O Suspend command sending. + * @param __INSTANCE__ : Pointer to SDIO register base + * @retval None + */ +#define __SDIO_SUSPEND_CMD_ENABLE(__INSTANCE__) (*(__IO uint32_t *) CMD_SDIOSUSPEND_BB = ENABLE) + +/** + * @brief Disable the SD I/O Suspend command sending. + * @param __INSTANCE__ : Pointer to SDIO register base + * @retval None + */ +#define __SDIO_SUSPEND_CMD_DISABLE(__INSTANCE__) (*(__IO uint32_t *) CMD_SDIOSUSPEND_BB = DISABLE) + +#if defined(SDIO_CMD_ATACMD) +/** + * @brief Enable the command completion signal. + * @retval None + */ +#define __SDIO_CEATA_CMD_COMPLETION_ENABLE() (*(__IO uint32_t *) CMD_ENCMDCOMPL_BB = ENABLE) + +/** + * @brief Disable the command completion signal. + * @retval None + */ +#define __SDIO_CEATA_CMD_COMPLETION_DISABLE() (*(__IO uint32_t *) CMD_ENCMDCOMPL_BB = DISABLE) + +/** + * @brief Enable the CE-ATA interrupt. + * @retval None + */ +#define __SDIO_CEATA_ENABLE_IT() (*(__IO uint32_t *) CMD_NIEN_BB = (uint32_t)0U) + +/** + * @brief Disable the CE-ATA interrupt. + * @retval None + */ +#define __SDIO_CEATA_DISABLE_IT() (*(__IO uint32_t *) CMD_NIEN_BB = (uint32_t)1U) + +/** + * @brief Enable send CE-ATA command (CMD61). + * @retval None + */ +#define __SDIO_CEATA_SENDCMD_ENABLE() (*(__IO uint32_t *) CMD_ATACMD_BB = ENABLE) + +/** + * @brief Disable send CE-ATA command (CMD61). + * @retval None + */ +#define __SDIO_CEATA_SENDCMD_DISABLE() (*(__IO uint32_t *) CMD_ATACMD_BB = DISABLE) + +#endif +/** + * @} + */ + +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup SDMMC_DDL_Exported_Functions + * @{ + */ + +/* Initialization/de-initialization functions **********************************/ +/** @addtogroup DAL_SDMMC_DDL_Group1 + * @{ + */ +DAL_StatusTypeDef SDIO_Init(SDIO_TypeDef *SDIOx, SDIO_InitTypeDef Init); +/** + * @} + */ + +/* I/O operation functions *****************************************************/ +/** @addtogroup DAL_SDMMC_DDL_Group2 + * @{ + */ +uint32_t SDIO_ReadFIFO(SDIO_TypeDef *SDIOx); +DAL_StatusTypeDef SDIO_WriteFIFO(SDIO_TypeDef *SDIOx, uint32_t *pWriteData); +/** + * @} + */ + +/* Peripheral Control functions ************************************************/ +/** @addtogroup DAL_SDMMC_DDL_Group3 + * @{ + */ +DAL_StatusTypeDef SDIO_PowerState_ON(SDIO_TypeDef *SDIOx); +DAL_StatusTypeDef SDIO_PowerState_OFF(SDIO_TypeDef *SDIOx); +uint32_t SDIO_GetPowerState(SDIO_TypeDef *SDIOx); + +/* Command path state machine (CPSM) management functions */ +DAL_StatusTypeDef SDIO_SendCommand(SDIO_TypeDef *SDIOx, SDIO_CmdInitTypeDef *Command); +uint8_t SDIO_GetCommandResponse(SDIO_TypeDef *SDIOx); +uint32_t SDIO_GetResponse(SDIO_TypeDef *SDIOx, uint32_t Response); + +/* Data path state machine (DPSM) management functions */ +DAL_StatusTypeDef SDIO_ConfigData(SDIO_TypeDef *SDIOx, SDIO_DataInitTypeDef* Data); +uint32_t SDIO_GetDataCounter(SDIO_TypeDef *SDIOx); +uint32_t SDIO_GetFIFOCount(SDIO_TypeDef *SDIOx); + +/* SDMMC Cards mode management functions */ +DAL_StatusTypeDef SDIO_SetSDMMCReadWaitMode(SDIO_TypeDef *SDIOx, uint32_t SDIO_ReadWaitMode); +/** + * @} + */ + +/* SDMMC Commands management functions */ +/** @addtogroup DAL_SDMMC_DDL_Group4 + * @{ + */ +uint32_t SDMMC_CmdBlockLength(SDIO_TypeDef *SDIOx, uint32_t BlockSize); +uint32_t SDMMC_CmdReadSingleBlock(SDIO_TypeDef *SDIOx, uint32_t ReadAdd); +uint32_t SDMMC_CmdReadMultiBlock(SDIO_TypeDef *SDIOx, uint32_t ReadAdd); +uint32_t SDMMC_CmdWriteSingleBlock(SDIO_TypeDef *SDIOx, uint32_t WriteAdd); +uint32_t SDMMC_CmdWriteMultiBlock(SDIO_TypeDef *SDIOx, uint32_t WriteAdd); +uint32_t SDMMC_CmdEraseStartAdd(SDIO_TypeDef *SDIOx, uint32_t StartAdd); +uint32_t SDMMC_CmdSDEraseStartAdd(SDIO_TypeDef *SDIOx, uint32_t StartAdd); +uint32_t SDMMC_CmdEraseEndAdd(SDIO_TypeDef *SDIOx, uint32_t EndAdd); +uint32_t SDMMC_CmdSDEraseEndAdd(SDIO_TypeDef *SDIOx, uint32_t EndAdd); +uint32_t SDMMC_CmdErase(SDIO_TypeDef *SDIOx); +uint32_t SDMMC_CmdStopTransfer(SDIO_TypeDef *SDIOx); +uint32_t SDMMC_CmdSelDesel(SDIO_TypeDef *SDIOx, uint64_t Addr); +uint32_t SDMMC_CmdGoIdleState(SDIO_TypeDef *SDIOx); +uint32_t SDMMC_CmdOperCond(SDIO_TypeDef *SDIOx); +uint32_t SDMMC_CmdAppCommand(SDIO_TypeDef *SDIOx, uint32_t Argument); +uint32_t SDMMC_CmdAppOperCommand(SDIO_TypeDef *SDIOx, uint32_t Argument); +uint32_t SDMMC_CmdBusWidth(SDIO_TypeDef *SDIOx, uint32_t BusWidth); +uint32_t SDMMC_CmdSendSCR(SDIO_TypeDef *SDIOx); +uint32_t SDMMC_CmdSendCID(SDIO_TypeDef *SDIOx); +uint32_t SDMMC_CmdSendCSD(SDIO_TypeDef *SDIOx, uint32_t Argument); +uint32_t SDMMC_CmdSetRelAdd(SDIO_TypeDef *SDIOx, uint16_t *pRCA); +uint32_t SDMMC_CmdSetRelAddMmc(SDIO_TypeDef *SDIOx, uint16_t RCA); +uint32_t SDMMC_CmdSendStatus(SDIO_TypeDef *SDIOx, uint32_t Argument); +uint32_t SDMMC_CmdStatusRegister(SDIO_TypeDef *SDIOx); +uint32_t SDMMC_CmdOpCondition(SDIO_TypeDef *SDIOx, uint32_t Argument); +uint32_t SDMMC_CmdSwitch(SDIO_TypeDef *SDIOx, uint32_t Argument); +uint32_t SDMMC_CmdSendEXTCSD(SDIO_TypeDef *SDIOx, uint32_t Argument); +/** + * @} + */ + +/* SDMMC Responses management functions *****************************************/ +/** @addtogroup DAL_SDMMC_DDL_Group5 + * @{ + */ +uint32_t SDMMC_GetCmdResp1(SDIO_TypeDef *SDIOx, uint8_t SD_CMD, uint32_t Timeout); +uint32_t SDMMC_GetCmdResp2(SDIO_TypeDef *SDIOx); +uint32_t SDMMC_GetCmdResp3(SDIO_TypeDef *SDIOx); +uint32_t SDMMC_GetCmdResp6(SDIO_TypeDef *SDIOx, uint8_t SD_CMD, uint16_t *pRCA); +uint32_t SDMMC_GetCmdResp7(SDIO_TypeDef *SDIOx); +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#endif /* SDIO */ + +#ifdef __cplusplus +} +#endif + +#endif /* APM32F4xx_DDL_SDMMC_H */ diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_smc.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_smc.h new file mode 100644 index 0000000000..49972edbdc --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_smc.h @@ -0,0 +1,1110 @@ +/** + * + * @file apm32f4xx_ddl_smc.h + * @brief Header file of SMC DDL module. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef APM32F4xx_DDL_SMC_H +#define APM32F4xx_DDL_SMC_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal_def.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @addtogroup SMC_DDL + * @{ + */ + +/** @addtogroup SMC_DDL_Private_Macros + * @{ + */ +#if defined(SMC_Bank1) + +#define IS_SMC_NORSRAM_BANK(__BANK__) (((__BANK__) == SMC_NORSRAM_BANK1) || \ + ((__BANK__) == SMC_NORSRAM_BANK2) || \ + ((__BANK__) == SMC_NORSRAM_BANK3) || \ + ((__BANK__) == SMC_NORSRAM_BANK4)) +#define IS_SMC_MUX(__MUX__) (((__MUX__) == SMC_DATA_ADDRESS_MUX_DISABLE) || \ + ((__MUX__) == SMC_DATA_ADDRESS_MUX_ENABLE)) +#define IS_SMC_MEMORY(__MEMORY__) (((__MEMORY__) == SMC_MEMORY_TYPE_SRAM) || \ + ((__MEMORY__) == SMC_MEMORY_TYPE_PSRAM)|| \ + ((__MEMORY__) == SMC_MEMORY_TYPE_NOR)) +#define IS_SMC_NORSRAM_MEMORY_WIDTH(__WIDTH__) (((__WIDTH__) == SMC_NORSRAM_MEM_BUS_WIDTH_8) || \ + ((__WIDTH__) == SMC_NORSRAM_MEM_BUS_WIDTH_16) || \ + ((__WIDTH__) == SMC_NORSRAM_MEM_BUS_WIDTH_32)) +#define IS_SMC_PAGESIZE(__SIZE__) (((__SIZE__) == SMC_PAGE_SIZE_NONE) || \ + ((__SIZE__) == SMC_PAGE_SIZE_128) || \ + ((__SIZE__) == SMC_PAGE_SIZE_256) || \ + ((__SIZE__) == SMC_PAGE_SIZE_512) || \ + ((__SIZE__) == SMC_PAGE_SIZE_1024)) +#if defined(SMC_CSCTRL1_WFDIS) +#define IS_SMC_WRITE_FIFO(__FIFO__) (((__FIFO__) == SMC_WRITE_FIFO_DISABLE) || \ + ((__FIFO__) == SMC_WRITE_FIFO_ENABLE)) +#endif /* SMC_CSCTRL1_WFDIS */ +#define IS_SMC_ACCESS_MODE(__MODE__) (((__MODE__) == SMC_ACCESS_MODE_A) || \ + ((__MODE__) == SMC_ACCESS_MODE_B) || \ + ((__MODE__) == SMC_ACCESS_MODE_C) || \ + ((__MODE__) == SMC_ACCESS_MODE_D)) +#define IS_SMC_BURSTMODE(__STATE__) (((__STATE__) == SMC_BURST_ACCESS_MODE_DISABLE) || \ + ((__STATE__) == SMC_BURST_ACCESS_MODE_ENABLE)) +#define IS_SMC_WAIT_POLARITY(__POLARITY__) (((__POLARITY__) == SMC_WAIT_SIGNAL_POLARITY_LOW) || \ + ((__POLARITY__) == SMC_WAIT_SIGNAL_POLARITY_HIGH)) +#define IS_SMC_WRAP_MODE(__MODE__) (((__MODE__) == SMC_WRAP_MODE_DISABLE) || \ + ((__MODE__) == SMC_WRAP_MODE_ENABLE)) +#define IS_SMC_WAIT_SIGNAL_ACTIVE(__ACTIVE__) (((__ACTIVE__) == SMC_WAIT_TIMING_BEFORE_WS) || \ + ((__ACTIVE__) == SMC_WAIT_TIMING_DURING_WS)) +#define IS_SMC_WRITE_OPERATION(__OPERATION__) (((__OPERATION__) == SMC_WRITE_OPERATION_DISABLE) || \ + ((__OPERATION__) == SMC_WRITE_OPERATION_ENABLE)) +#define IS_SMC_WAITE_SIGNAL(__SIGNAL__) (((__SIGNAL__) == SMC_WAIT_SIGNAL_DISABLE) || \ + ((__SIGNAL__) == SMC_WAIT_SIGNAL_ENABLE)) +#define IS_SMC_EXTENDED_MODE(__MODE__) (((__MODE__) == SMC_EXTENDED_MODE_DISABLE) || \ + ((__MODE__) == SMC_EXTENDED_MODE_ENABLE)) +#define IS_SMC_ASYNWAIT(__STATE__) (((__STATE__) == SMC_ASYNCHRONOUS_WAIT_DISABLE) || \ + ((__STATE__) == SMC_ASYNCHRONOUS_WAIT_ENABLE)) +#define IS_SMC_DATA_LATENCY(__LATENCY__) (((__LATENCY__) > 1U) && ((__LATENCY__) <= 17U)) +#define IS_SMC_WRITE_BURST(__BURST__) (((__BURST__) == SMC_WRITE_BURST_DISABLE) || \ + ((__BURST__) == SMC_WRITE_BURST_ENABLE)) +#define IS_SMC_CONTINOUS_CLOCK(__CCLOCK__) (((__CCLOCK__) == SMC_CONTINUOUS_CLOCK_SYNC_ONLY) || \ + ((__CCLOCK__) == SMC_CONTINUOUS_CLOCK_SYNC_ASYNC)) +#define IS_SMC_ADDRESS_SETUP_TIME(__TIME__) ((__TIME__) <= 15U) +#define IS_SMC_ADDRESS_HOLD_TIME(__TIME__) (((__TIME__) > 0U) && ((__TIME__) <= 15U)) +#define IS_SMC_DATASETUP_TIME(__TIME__) (((__TIME__) > 0U) && ((__TIME__) <= 255U)) +#define IS_SMC_DATAHOLD_DURATION(__DATAHOLD__) ((__DATAHOLD__) <= 3U) +#define IS_SMC_TURNAROUND_TIME(__TIME__) ((__TIME__) <= 15U) +#define IS_SMC_CLK_DIV(__DIV__) (((__DIV__) > 1U) && ((__DIV__) <= 16U)) +#define IS_SMC_NORSRAM_DEVICE(__INSTANCE__) ((__INSTANCE__) == SMC_NORSRAM_DEVICE) +#define IS_SMC_NORSRAM_EXTENDED_DEVICE(__INSTANCE__) ((__INSTANCE__) == SMC_NORSRAM_EXTENDED_DEVICE) + +#endif /* SMC_Bank1 */ +#if defined(SMC_Bank2_3) + +#define IS_SMC_NAND_BANK(__BANK__) (((__BANK__) == SMC_NAND_BANK2) || \ + ((__BANK__) == SMC_NAND_BANK3)) +#define IS_SMC_WAIT_FEATURE(__FEATURE__) (((__FEATURE__) == SMC_NAND_PCC_WAIT_FEATURE_DISABLE) || \ + ((__FEATURE__) == SMC_NAND_PCC_WAIT_FEATURE_ENABLE)) +#define IS_SMC_NAND_MEMORY_WIDTH(__WIDTH__) (((__WIDTH__) == SMC_NAND_PCC_MEM_BUS_WIDTH_8) || \ + ((__WIDTH__) == SMC_NAND_PCC_MEM_BUS_WIDTH_16)) +#define IS_SMC_ECC_STATE(__STATE__) (((__STATE__) == SMC_NAND_ECC_DISABLE) || \ + ((__STATE__) == SMC_NAND_ECC_ENABLE)) + +#define IS_SMC_ECCPAGE_SIZE(__SIZE__) (((__SIZE__) == SMC_NAND_ECC_PAGE_SIZE_256BYTE) || \ + ((__SIZE__) == SMC_NAND_ECC_PAGE_SIZE_512BYTE) || \ + ((__SIZE__) == SMC_NAND_ECC_PAGE_SIZE_1024BYTE) || \ + ((__SIZE__) == SMC_NAND_ECC_PAGE_SIZE_2048BYTE) || \ + ((__SIZE__) == SMC_NAND_ECC_PAGE_SIZE_4096BYTE) || \ + ((__SIZE__) == SMC_NAND_ECC_PAGE_SIZE_8192BYTE)) +#define IS_SMC_TCLR_TIME(__TIME__) ((__TIME__) <= 255U) +#define IS_SMC_TAR_TIME(__TIME__) ((__TIME__) <= 255U) +#define IS_SMC_SETUP_TIME(__TIME__) ((__TIME__) <= 254U) +#define IS_SMC_WAIT_TIME(__TIME__) ((__TIME__) <= 254U) +#define IS_SMC_HOLD_TIME(__TIME__) ((__TIME__) <= 254U) +#define IS_SMC_HIZ_TIME(__TIME__) ((__TIME__) <= 254U) +#define IS_SMC_NAND_DEVICE(__INSTANCE__) ((__INSTANCE__) == SMC_NAND_DEVICE) + +#endif /* SMC_Bank2_3 */ +#if defined(SMC_Bank4) +#define IS_SMC_PCCARD_DEVICE(__INSTANCE__) ((__INSTANCE__) == SMC_PCCARD_DEVICE) + +#endif /* SMC_Bank4 */ + +/** + * @} + */ + +/* Exported typedef ----------------------------------------------------------*/ + +/** @defgroup SMC_DDL_Exported_typedef SMC Low Layer Exported Types + * @{ + */ + +#if defined(SMC_Bank1) +#define SMC_NORSRAM_TypeDef SMC_Bank1_TypeDef +#define SMC_NORSRAM_EXTENDED_TypeDef SMC_Bank1E_TypeDef +#endif /* SMC_Bank1 */ +#if defined(SMC_Bank2_3) +#define SMC_NAND_TypeDef SMC_Bank2_3_TypeDef +#endif /* SMC_Bank2_3 */ +#if defined(SMC_Bank4) +#define SMC_PCCARD_TypeDef SMC_Bank4_TypeDef +#endif /* SMC_Bank4 */ + +#if defined(SMC_Bank1) +#define SMC_NORSRAM_DEVICE SMC_Bank1 +#define SMC_NORSRAM_EXTENDED_DEVICE SMC_Bank1E +#endif /* SMC_Bank1 */ +#if defined(SMC_Bank2_3) +#define SMC_NAND_DEVICE SMC_Bank2_3 +#endif /* SMC_Bank2_3 */ +#if defined(SMC_Bank4) +#define SMC_PCCARD_DEVICE SMC_Bank4 +#endif /* SMC_Bank4 */ + +#if defined(SMC_Bank1) +/** + * @brief SMC NORSRAM Configuration Structure definition + */ +typedef struct +{ + uint32_t NSBank; /*!< Specifies the NORSRAM memory device that will be used. + This parameter can be a value of @ref SMC_NORSRAM_Bank */ + + uint32_t DataAddressMux; /*!< Specifies whether the address and data values are + multiplexed on the data bus or not. + This parameter can be a value of @ref SMC_Data_Address_Bus_Multiplexing */ + + uint32_t MemoryType; /*!< Specifies the type of external memory attached to + the corresponding memory device. + This parameter can be a value of @ref SMC_Memory_Type */ + + uint32_t MemoryDataWidth; /*!< Specifies the external memory device width. + This parameter can be a value of @ref SMC_NORSRAM_Data_Width */ + + uint32_t BurstAccessMode; /*!< Enables or disables the burst access mode for Flash memory, + valid only with synchronous burst Flash memories. + This parameter can be a value of @ref SMC_Burst_Access_Mode */ + + uint32_t WaitSignalPolarity; /*!< Specifies the wait signal polarity, valid only when accessing + the Flash memory in burst mode. + This parameter can be a value of @ref SMC_Wait_Signal_Polarity */ + + uint32_t WrapMode; /*!< Enables or disables the Wrapped burst access mode for Flash + memory, valid only when accessing Flash memories in burst mode. + This parameter can be a value of @ref SMC_Wrap_Mode + This mode is available only for the APM32F405/407/417xx devices */ + + uint32_t WaitSignalActive; /*!< Specifies if the wait signal is asserted by the memory one + clock cycle before the wait state or during the wait state, + valid only when accessing memories in burst mode. + This parameter can be a value of @ref SMC_Wait_Timing */ + + uint32_t WriteOperation; /*!< Enables or disables the write operation in the selected device by the SMC. + This parameter can be a value of @ref SMC_Write_Operation */ + + uint32_t WaitSignal; /*!< Enables or disables the wait state insertion via wait + signal, valid for Flash memory access in burst mode. + This parameter can be a value of @ref SMC_Wait_Signal */ + + uint32_t ExtendedMode; /*!< Enables or disables the extended mode. + This parameter can be a value of @ref SMC_Extended_Mode */ + + uint32_t AsynchronousWait; /*!< Enables or disables wait signal during asynchronous transfers, + valid only with asynchronous Flash memories. + This parameter can be a value of @ref SMC_AsynchronousWait */ + + uint32_t WriteBurst; /*!< Enables or disables the write burst operation. + This parameter can be a value of @ref SMC_Write_Burst */ + + uint32_t ContinuousClock; /*!< Enables or disables the SMC clock output to external memory devices. + This parameter is only enabled through the SMC_CSCTRL1 register, + and don't care through SMC_CSCTRL2..4 registers. + This parameter can be a value of @ref SMC_Continous_Clock + This mode is available only for the APM32F412Vx/Zx/Rx devices */ + + uint32_t WriteFifo; /*!< Enables or disables the write FIFO used by the SMC controller. + This parameter is only enabled through the SMC_CSCTRL1 register, + and don't care through SMC_CSCTRL2..4 registers. + This parameter can be a value of @ref SMC_Write_FIFO + This mode is available only for the APM32F412Vx/Vx devices */ + + uint32_t PageSize; /*!< Specifies the memory page size. + This parameter can be a value of @ref SMC_Page_Size */ +} SMC_NORSRAM_InitTypeDef; + +/** + * @brief SMC NORSRAM Timing parameters structure definition + */ +typedef struct +{ + uint32_t AddressSetupTime; /*!< Defines the number of HCLK cycles to configure + the duration of the address setup time. + This parameter can be a value between Min_Data = 0 and Max_Data = 15. + @note This parameter is not used with synchronous NOR Flash memories. */ + + uint32_t AddressHoldTime; /*!< Defines the number of HCLK cycles to configure + the duration of the address hold time. + This parameter can be a value between Min_Data = 1 and Max_Data = 15. + @note This parameter is not used with synchronous NOR Flash memories. */ + + uint32_t DataSetupTime; /*!< Defines the number of HCLK cycles to configure + the duration of the data setup time. + This parameter can be a value between Min_Data = 1 and Max_Data = 255. + @note This parameter is used for SRAMs, ROMs and asynchronous multiplexed + NOR Flash memories. */ + + uint32_t BusTurnAroundDuration; /*!< Defines the number of HCLK cycles to configure + the duration of the bus turnaround. + This parameter can be a value between Min_Data = 0 and Max_Data = 15. + @note This parameter is only used for multiplexed NOR Flash memories. */ + + uint32_t CLKDivision; /*!< Defines the period of CLK clock output signal, expressed in number of + HCLK cycles. This parameter can be a value between Min_Data = 2 and + Max_Data = 16. + @note This parameter is not used for asynchronous NOR Flash, SRAM or ROM + accesses. */ + + uint32_t DataLatency; /*!< Defines the number of memory clock cycles to issue + to the memory before getting the first data. + The parameter value depends on the memory type as shown below: + - It must be set to 0 in case of a CRAM + - It is don't care in asynchronous NOR, SRAM or ROM accesses + - It may assume a value between Min_Data = 2 and Max_Data = 17 + in NOR Flash memories with synchronous burst mode enable */ + + uint32_t AccessMode; /*!< Specifies the asynchronous access mode. + This parameter can be a value of @ref SMC_Access_Mode */ +} SMC_NORSRAM_TimingTypeDef; +#endif /* SMC_Bank1 */ + +#if defined(SMC_Bank2_3) +/** + * @brief SMC NAND Configuration Structure definition + */ +typedef struct +{ + uint32_t NandBank; /*!< Specifies the NAND memory device that will be used. + This parameter can be a value of @ref SMC_NAND_Bank */ + + uint32_t Waitfeature; /*!< Enables or disables the Wait feature for the NAND Memory device. + This parameter can be any value of @ref SMC_Wait_feature */ + + uint32_t MemoryDataWidth; /*!< Specifies the external memory device width. + This parameter can be any value of @ref SMC_NAND_Data_Width */ + + uint32_t EccComputation; /*!< Enables or disables the ECC computation. + This parameter can be any value of @ref SMC_ECC */ + + uint32_t ECCPageSize; /*!< Defines the page size for the extended ECC. + This parameter can be any value of @ref SMC_ECC_Page_Size */ + + uint32_t TCLRSetupTime; /*!< Defines the number of HCLK cycles to configure the + delay between CLE low and RE low. + This parameter can be a value between Min_Data = 0 and Max_Data = 255 */ + + uint32_t TARSetupTime; /*!< Defines the number of HCLK cycles to configure the + delay between ALE low and RE low. + This parameter can be a number between Min_Data = 0 and Max_Data = 255 */ +} SMC_NAND_InitTypeDef; +#endif + +#if defined(SMC_Bank2_3) || defined(SMC_Bank4) +/** + * @brief SMC NAND Timing parameters structure definition + */ +typedef struct +{ + uint32_t SetupTime; /*!< Defines the number of HCLK cycles to setup address before + the command assertion for NAND-Flash read or write access + to common/Attribute or I/O memory space (depending on + the memory space timing to be configured). + This parameter can be a value between Min_Data = 0 and Max_Data = 254 */ + + uint32_t WaitSetupTime; /*!< Defines the minimum number of HCLK cycles to assert the + command for NAND-Flash read or write access to + common/Attribute or I/O memory space (depending on the + memory space timing to be configured). + This parameter can be a number between Min_Data = 0 and Max_Data = 254 */ + + uint32_t HoldSetupTime; /*!< Defines the number of HCLK clock cycles to hold address + (and data for write access) after the command de-assertion + for NAND-Flash read or write access to common/Attribute + or I/O memory space (depending on the memory space timing + to be configured). + This parameter can be a number between Min_Data = 0 and Max_Data = 254 */ + + uint32_t HiZSetupTime; /*!< Defines the number of HCLK clock cycles during which the + data bus is kept in HiZ after the start of a NAND-Flash + write access to common/Attribute or I/O memory space (depending + on the memory space timing to be configured). + This parameter can be a number between Min_Data = 0 and Max_Data = 254 */ +} SMC_NAND_PCC_TimingTypeDef; +#endif /* SMC_Bank2_3 */ + +#if defined(SMC_Bank4) +/** + * @brief SMC PCCARD Configuration Structure definition + */ +typedef struct +{ + uint32_t Waitfeature; /*!< Enables or disables the Wait feature for the PCCARD Memory device. + This parameter can be any value of @ref SMC_Wait_feature */ + + uint32_t TCLRSetupTime; /*!< Defines the number of HCLK cycles to configure the + delay between CLE low and RE low. + This parameter can be a value between Min_Data = 0 and Max_Data = 255 */ + + uint32_t TARSetupTime; /*!< Defines the number of HCLK cycles to configure the + delay between ALE low and RE low. + This parameter can be a number between Min_Data = 0 and Max_Data = 255 */ +}SMC_PCCARD_InitTypeDef; +#endif /* SMC_Bank4 */ + +/** + * @} + */ + +/* Exported constants --------------------------------------------------------*/ +/** @addtogroup SMC_DDL_Exported_Constants SMC Low Layer Exported Constants + * @{ + */ +#if defined(SMC_Bank1) + +/** @defgroup SMC_DDL_NOR_SRAM_Controller SMC NOR/SRAM Controller + * @{ + */ + +/** @defgroup SMC_NORSRAM_Bank SMC NOR/SRAM Bank + * @{ + */ +#define SMC_NORSRAM_BANK1 (0x00000000U) +#define SMC_NORSRAM_BANK2 (0x00000002U) +#define SMC_NORSRAM_BANK3 (0x00000004U) +#define SMC_NORSRAM_BANK4 (0x00000006U) +/** + * @} + */ + +/** @defgroup SMC_Data_Address_Bus_Multiplexing SMC Data Address Bus Multiplexing + * @{ + */ +#define SMC_DATA_ADDRESS_MUX_DISABLE (0x00000000U) +#define SMC_DATA_ADDRESS_MUX_ENABLE (0x00000002U) +/** + * @} + */ + +/** @defgroup SMC_Memory_Type SMC Memory Type + * @{ + */ +#define SMC_MEMORY_TYPE_SRAM (0x00000000U) +#define SMC_MEMORY_TYPE_PSRAM (0x00000004U) +#define SMC_MEMORY_TYPE_NOR (0x00000008U) +/** + * @} + */ + +/** @defgroup SMC_NORSRAM_Data_Width SMC NORSRAM Data Width + * @{ + */ +#define SMC_NORSRAM_MEM_BUS_WIDTH_8 (0x00000000U) +#define SMC_NORSRAM_MEM_BUS_WIDTH_16 (0x00000010U) +#define SMC_NORSRAM_MEM_BUS_WIDTH_32 (0x00000020U) +/** + * @} + */ + +/** @defgroup SMC_NORSRAM_Flash_Access SMC NOR/SRAM Flash Access + * @{ + */ +#define SMC_NORSRAM_FLASH_ACCESS_ENABLE (0x00000040U) +#define SMC_NORSRAM_FLASH_ACCESS_DISABLE (0x00000000U) +/** + * @} + */ + +/** @defgroup SMC_Burst_Access_Mode SMC Burst Access Mode + * @{ + */ +#define SMC_BURST_ACCESS_MODE_DISABLE (0x00000000U) +#define SMC_BURST_ACCESS_MODE_ENABLE (0x00000100U) +/** + * @} + */ + +/** @defgroup SMC_Wait_Signal_Polarity SMC Wait Signal Polarity + * @{ + */ +#define SMC_WAIT_SIGNAL_POLARITY_LOW (0x00000000U) +#define SMC_WAIT_SIGNAL_POLARITY_HIGH (0x00000200U) +/** + * @} + */ + +/** @defgroup SMC_Wrap_Mode SMC Wrap Mode + * @note These values are available only for the APM32F405/407/417xx devices. + * @{ + */ +#define SMC_WRAP_MODE_DISABLE (0x00000000U) +#define SMC_WRAP_MODE_ENABLE (0x00000400U) +/** + * @} + */ + +/** @defgroup SMC_Wait_Timing SMC Wait Timing + * @{ + */ +#define SMC_WAIT_TIMING_BEFORE_WS (0x00000000U) +#define SMC_WAIT_TIMING_DURING_WS (0x00000800U) +/** + * @} + */ + +/** @defgroup SMC_Write_Operation SMC Write Operation + * @{ + */ +#define SMC_WRITE_OPERATION_DISABLE (0x00000000U) +#define SMC_WRITE_OPERATION_ENABLE (0x00001000U) +/** + * @} + */ + +/** @defgroup SMC_Wait_Signal SMC Wait Signal + * @{ + */ +#define SMC_WAIT_SIGNAL_DISABLE (0x00000000U) +#define SMC_WAIT_SIGNAL_ENABLE (0x00002000U) +/** + * @} + */ + +/** @defgroup SMC_Extended_Mode SMC Extended Mode + * @{ + */ +#define SMC_EXTENDED_MODE_DISABLE (0x00000000U) +#define SMC_EXTENDED_MODE_ENABLE (0x00004000U) +/** + * @} + */ + +/** @defgroup SMC_AsynchronousWait SMC Asynchronous Wait + * @{ + */ +#define SMC_ASYNCHRONOUS_WAIT_DISABLE (0x00000000U) +#define SMC_ASYNCHRONOUS_WAIT_ENABLE (0x00008000U) +/** + * @} + */ + +/** @defgroup SMC_Page_Size SMC Page Size + * @{ + */ +#define SMC_PAGE_SIZE_NONE (0x00000000U) +#define SMC_PAGE_SIZE_128 SMC_CSCTRL1_CRAMPSIZECFG_0 +#define SMC_PAGE_SIZE_256 SMC_CSCTRL1_CRAMPSIZECFG_1 +#define SMC_PAGE_SIZE_512 (SMC_CSCTRL1_CRAMPSIZECFG_0\ + | SMC_CSCTRL1_CRAMPSIZECFG_1) +#define SMC_PAGE_SIZE_1024 SMC_CSCTRL1_CRAMPSIZECFG_2 +/** + * @} + */ + +/** @defgroup SMC_Write_Burst SMC Write Burst + * @{ + */ +#define SMC_WRITE_BURST_DISABLE (0x00000000U) +#define SMC_WRITE_BURST_ENABLE (0x00080000U) +/** + * @} + */ + +/** @defgroup SMC_Continous_Clock SMC Continuous Clock + * @note These values are available only for the APM32F412Vx/Zx/Rx devices. + * @{ + */ +#define SMC_CONTINUOUS_CLOCK_SYNC_ONLY (0x00000000U) +#define SMC_CONTINUOUS_CLOCK_SYNC_ASYNC (0x00100000U) +/** + * @} + */ + +#if defined(SMC_CSCTRL1_WFDIS) +/** @defgroup SMC_Write_FIFO SMC Write FIFO + * @note These values are available only for the APM32F412Vx/Zx/Rx devices. + * @{ + */ +#define SMC_WRITE_FIFO_DISABLE SMC_CSCTRL1_WFDIS +#define SMC_WRITE_FIFO_ENABLE (0x00000000U) +#endif /* SMC_CSCTRL1_WFDIS */ +/** + * @} + */ + +/** @defgroup SMC_Access_Mode SMC Access Mode + * @{ + */ +#define SMC_ACCESS_MODE_A (0x00000000U) +#define SMC_ACCESS_MODE_B (0x10000000U) +#define SMC_ACCESS_MODE_C (0x20000000U) +#define SMC_ACCESS_MODE_D (0x30000000U) +/** + * @} + */ + +/** + * @} + */ +#endif /* SMC_Bank1 */ + +#if defined(SMC_Bank2_3) || defined(SMC_Bank4) + +/** @defgroup SMC_DDL_NAND_Controller SMC NAND Controller + * @{ + */ +/** @defgroup SMC_NAND_Bank SMC NAND Bank + * @{ + */ +#if defined(SMC_Bank2_3) +#define SMC_NAND_BANK2 (0x00000010U) +#endif +#define SMC_NAND_BANK3 (0x00000100U) +/** + * @} + */ + +/** @defgroup SMC_Wait_feature SMC Wait feature + * @{ + */ +#define SMC_NAND_PCC_WAIT_FEATURE_DISABLE (0x00000000U) +#define SMC_NAND_PCC_WAIT_FEATURE_ENABLE (0x00000002U) +/** + * @} + */ + +/** @defgroup SMC_PCR_Memory_Type SMC PCR Memory Type + * @{ + */ +#if defined(SMC_Bank4) +#define SMC_PCR_MEMORY_TYPE_PCCARD (0x00000000U) +#endif /* SMC_Bank4 */ +#define SMC_PCR_MEMORY_TYPE_NAND (0x00000008U) +/** + * @} + */ + +/** @defgroup SMC_NAND_Data_Width SMC NAND Data Width + * @{ + */ +#define SMC_NAND_PCC_MEM_BUS_WIDTH_8 (0x00000000U) +#define SMC_NAND_PCC_MEM_BUS_WIDTH_16 (0x00000010U) +/** + * @} + */ + +/** @defgroup SMC_ECC SMC ECC + * @{ + */ +#define SMC_NAND_ECC_DISABLE (0x00000000U) +#define SMC_NAND_ECC_ENABLE (0x00000040U) +/** + * @} + */ + +/** @defgroup SMC_ECC_Page_Size SMC ECC Page Size + * @{ + */ +#define SMC_NAND_ECC_PAGE_SIZE_256BYTE (0x00000000U) +#define SMC_NAND_ECC_PAGE_SIZE_512BYTE (0x00020000U) +#define SMC_NAND_ECC_PAGE_SIZE_1024BYTE (0x00040000U) +#define SMC_NAND_ECC_PAGE_SIZE_2048BYTE (0x00060000U) +#define SMC_NAND_ECC_PAGE_SIZE_4096BYTE (0x00080000U) +#define SMC_NAND_ECC_PAGE_SIZE_8192BYTE (0x000A0000U) +/** + * @} + */ + +/** + * @} + */ +#endif /* SMC_Bank2_3 || SMC_Bank4 */ + + +/** @defgroup SMC_DDL_Interrupt_definition SMC Low Layer Interrupt definition + * @{ + */ +#if defined(SMC_Bank2_3) || defined(SMC_Bank4) +#define SMC_IT_RISING_EDGE (0x00000008U) +#define SMC_IT_LEVEL (0x00000010U) +#define SMC_IT_FALLING_EDGE (0x00000020U) +#endif /* SMC_Bank2_3 || SMC_Bank4 */ +/** + * @} + */ + +/** @defgroup SMC_DDL_Flag_definition SMC Low Layer Flag definition + * @{ + */ +#if defined(SMC_Bank2_3) || defined(SMC_Bank4) +#define SMC_FLAG_RISING_EDGE (0x00000001U) +#define SMC_FLAG_LEVEL (0x00000002U) +#define SMC_FLAG_FALLING_EDGE (0x00000004U) +#define SMC_FLAG_FEMPT (0x00000040U) +#endif /* SMC_Bank2_3 || SMC_Bank4 */ +/** + * @} + */ + +/** @defgroup SMC_DDL_Alias_definition SMC Alias definition + * @{ + */ +#define FMC_WRITE_OPERATION_DISABLE SMC_WRITE_OPERATION_DISABLE +#define FMC_WRITE_OPERATION_ENABLE SMC_WRITE_OPERATION_ENABLE + +#define FMC_NORSRAM_MEM_BUS_WIDTH_8 SMC_NORSRAM_MEM_BUS_WIDTH_8 +#define FMC_NORSRAM_MEM_BUS_WIDTH_16 SMC_NORSRAM_MEM_BUS_WIDTH_16 +#define FMC_NORSRAM_MEM_BUS_WIDTH_32 SMC_NORSRAM_MEM_BUS_WIDTH_32 + +#define FMC_NORSRAM_TypeDef SMC_NORSRAM_TypeDef +#define FMC_NORSRAM_EXTENDED_TypeDef SMC_NORSRAM_EXTENDED_TypeDef +#define FMC_NORSRAM_InitTypeDef SMC_NORSRAM_InitTypeDef +#define FMC_NORSRAM_TimingTypeDef SMC_NORSRAM_TimingTypeDef + +#define FMC_NORSRAM_Init SMC_NORSRAM_Init +#define FMC_NORSRAM_Timing_Init SMC_NORSRAM_Timing_Init +#define FMC_NORSRAM_Extended_Timing_Init SMC_NORSRAM_Extended_Timing_Init +#define FMC_NORSRAM_DeInit SMC_NORSRAM_DeInit +#define FMC_NORSRAM_WriteOperation_Enable SMC_NORSRAM_WriteOperation_Enable +#define FMC_NORSRAM_WriteOperation_Disable SMC_NORSRAM_WriteOperation_Disable + +#define __FMC_NORSRAM_ENABLE __SMC_NORSRAM_ENABLE +#define __FMC_NORSRAM_DISABLE __SMC_NORSRAM_DISABLE + +#if defined(APM32F405xx) || defined(APM32F407xx) || defined(APM32F417xx) || defined(APM32F465xx) || defined(APM32F411xx) +#define FMC_NAND_InitTypeDef SMC_NAND_InitTypeDef +#define FMC_PCCARD_InitTypeDef SMC_PCCARD_InitTypeDef +#define FMC_NAND_PCC_TimingTypeDef SMC_NAND_PCC_TimingTypeDef + +#define FMC_NAND_Init SMC_NAND_Init +#define FMC_NAND_CommonSpace_Timing_Init SMC_NAND_CommonSpace_Timing_Init +#define FMC_NAND_AttributeSpace_Timing_Init SMC_NAND_AttributeSpace_Timing_Init +#define FMC_NAND_DeInit SMC_NAND_DeInit +#define FMC_NAND_ECC_Enable SMC_NAND_ECC_Enable +#define FMC_NAND_ECC_Disable SMC_NAND_ECC_Disable +#define FMC_NAND_GetECC SMC_NAND_GetECC +#define FMC_PCCARD_Init SMC_PCCARD_Init +#define FMC_PCCARD_CommonSpace_Timing_Init SMC_PCCARD_CommonSpace_Timing_Init +#define FMC_PCCARD_AttributeSpace_Timing_Init SMC_PCCARD_AttributeSpace_Timing_Init +#define FMC_PCCARD_IOSpace_Timing_Init SMC_PCCARD_IOSpace_Timing_Init +#define FMC_PCCARD_DeInit SMC_PCCARD_DeInit + +#define __FMC_NAND_ENABLE __SMC_NAND_ENABLE +#define __FMC_NAND_DISABLE __SMC_NAND_DISABLE +#define __FMC_PCCARD_ENABLE __SMC_PCCARD_ENABLE +#define __FMC_PCCARD_DISABLE __SMC_PCCARD_DISABLE +#define __FMC_NAND_ENABLE_IT __SMC_NAND_ENABLE_IT +#define __FMC_NAND_DISABLE_IT __SMC_NAND_DISABLE_IT +#define __FMC_NAND_GET_FLAG __SMC_NAND_GET_FLAG +#define __FMC_NAND_CLEAR_FLAG __SMC_NAND_CLEAR_FLAG +#define __FMC_PCCARD_ENABLE_IT __SMC_PCCARD_ENABLE_IT +#define __FMC_PCCARD_DISABLE_IT __SMC_PCCARD_DISABLE_IT +#define __FMC_PCCARD_GET_FLAG __SMC_PCCARD_GET_FLAG +#define __FMC_PCCARD_CLEAR_FLAG __SMC_PCCARD_CLEAR_FLAG +#endif /* APM32F405xx || APM32F407xx || APM32F417xx || APM32F465xx || APM32F411xx */ + +#define FMC_NORSRAM_TypeDef SMC_NORSRAM_TypeDef +#define FMC_NORSRAM_EXTENDED_TypeDef SMC_NORSRAM_EXTENDED_TypeDef +#if defined(APM32F405xx) || defined(APM32F407xx) || defined(APM32F417xx) || defined(APM32F465xx) || defined(APM32F411xx) +#define FMC_NAND_TypeDef SMC_NAND_TypeDef +#define FMC_PCCARD_TypeDef SMC_PCCARD_TypeDef +#endif /* APM32F405xx || APM32F407xx || APM32F417xx || APM32F465xx || APM32F411xx */ + +#define FMC_NORSRAM_DEVICE SMC_NORSRAM_DEVICE +#define FMC_NORSRAM_EXTENDED_DEVICE SMC_NORSRAM_EXTENDED_DEVICE +#if defined(APM32F405xx) || defined(APM32F407xx) || defined(APM32F417xx) || defined(APM32F465xx) || defined(APM32F411xx) +#define FMC_NAND_DEVICE SMC_NAND_DEVICE +#define FMC_PCCARD_DEVICE SMC_PCCARD_DEVICE + +#define FMC_NAND_BANK2 SMC_NAND_BANK2 +#endif /* APM32F405xx || APM32F407xx || APM32F417xx || APM32F465xx || APM32F411xx */ + +#define FMC_NORSRAM_BANK1 SMC_NORSRAM_BANK1 +#define FMC_NORSRAM_BANK2 SMC_NORSRAM_BANK2 +#define FMC_NORSRAM_BANK3 SMC_NORSRAM_BANK3 + +#define FMC_IT_RISING_EDGE SMC_IT_RISING_EDGE +#define FMC_IT_LEVEL SMC_IT_LEVEL +#define FMC_IT_FALLING_EDGE SMC_IT_FALLING_EDGE +#define FMC_IT_REFRESH_ERROR SMC_IT_REFRESH_ERROR + +#define FMC_FLAG_RISING_EDGE SMC_FLAG_RISING_EDGE +#define FMC_FLAG_LEVEL SMC_FLAG_LEVEL +#define FMC_FLAG_FALLING_EDGE SMC_FLAG_FALLING_EDGE +#define FMC_FLAG_FEMPT SMC_FLAG_FEMPT +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +/* Private macro -------------------------------------------------------------*/ +/** @defgroup SMC_DDL_Private_Macros SMC_DDL Private Macros + * @{ + */ +#if defined(SMC_Bank1) +/** @defgroup SMC_DDL_NOR_Macros SMC NOR/SRAM Macros + * @brief macros to handle NOR device enable/disable and read/write operations + * @{ + */ + +/** + * @brief Enable the NORSRAM device access. + * @param __INSTANCE__ SMC_NORSRAM Instance + * @param __BANK__ SMC_NORSRAM Bank + * @retval None + */ +#define __SMC_NORSRAM_ENABLE(__INSTANCE__, __BANK__) ((__INSTANCE__)->CSTR[(__BANK__)]\ + |= SMC_CSCTRL1_MBKEN) + +/** + * @brief Disable the NORSRAM device access. + * @param __INSTANCE__ SMC_NORSRAM Instance + * @param __BANK__ SMC_NORSRAM Bank + * @retval None + */ +#define __SMC_NORSRAM_DISABLE(__INSTANCE__, __BANK__) ((__INSTANCE__)->CSTR[(__BANK__)]\ + &= ~SMC_CSCTRL1_MBKEN) + +/** + * @} + */ +#endif /* SMC_Bank1 */ + +#if defined(SMC_Bank2_3) +/** @defgroup SMC_DDL_NAND_Macros SMC NAND Macros + * @brief macros to handle NAND device enable/disable + * @{ + */ + +/** + * @brief Enable the NAND device access. + * @param __INSTANCE__ SMC_NAND Instance + * @param __BANK__ SMC_NAND Bank + * @retval None + */ +#define __SMC_NAND_ENABLE(__INSTANCE__, __BANK__) (((__BANK__) == SMC_NAND_BANK2)? ((__INSTANCE__)->CTRL2 |= SMC_CTRL2_MBKEN): \ + ((__INSTANCE__)->CTRL3 |= SMC_CTRL3_MBKEN)) + +/** + * @brief Disable the NAND device access. + * @param __INSTANCE__ SMC_NAND Instance + * @param __BANK__ SMC_NAND Bank + * @retval None + */ +#define __SMC_NAND_DISABLE(__INSTANCE__, __BANK__) (((__BANK__) == SMC_NAND_BANK2)? CLEAR_BIT((__INSTANCE__)->CTRL2, SMC_CTRL2_MBKEN): \ + CLEAR_BIT((__INSTANCE__)->CTRL3, SMC_CTRL3_MBKEN)) + +/** + * @} + */ +#endif /* SMC_Bank2_3 */ + +#if defined(SMC_Bank4) +/** @defgroup SMC_DDL_PCCARD_Macros FMC PCCARD Macros + * @brief macros to handle PCCARD read/write operations + * @{ + */ +/** + * @brief Enable the PCCARD device access. + * @param __INSTANCE__ SMC_PCCARD Instance + * @retval None + */ +#define __SMC_PCCARD_ENABLE(__INSTANCE__) ((__INSTANCE__)->CTRL4 |= SMC_CTRL4_MBKEN) + +/** + * @brief Disable the PCCARD device access. + * @param __INSTANCE__ SMC_PCCARD Instance + * @retval None + */ +#define __SMC_PCCARD_DISABLE(__INSTANCE__) ((__INSTANCE__)->CTRL4 &= ~SMC_CTRL4_MBKEN) +/** + * @} + */ + +#endif +#if defined(SMC_Bank2_3) +/** @defgroup SMC_DDL_NAND_Interrupt SMC NAND Interrupt + * @brief macros to handle NAND interrupts + * @{ + */ + +/** + * @brief Enable the NAND device interrupt. + * @param __INSTANCE__ SMC_NAND instance + * @param __BANK__ SMC_NAND Bank + * @param __INTERRUPT__ SMC_NAND interrupt + * This parameter can be any combination of the following values: + * @arg SMC_IT_RISING_EDGE: Interrupt rising edge. + * @arg SMC_IT_LEVEL: Interrupt level. + * @arg SMC_IT_FALLING_EDGE: Interrupt falling edge. + * @retval None + */ +#define __SMC_NAND_ENABLE_IT(__INSTANCE__, __BANK__, __INTERRUPT__) (((__BANK__) == SMC_NAND_BANK2)? ((__INSTANCE__)->STSINT2 |= (__INTERRUPT__)): \ + ((__INSTANCE__)->STSINT3 |= (__INTERRUPT__))) + +/** + * @brief Disable the NAND device interrupt. + * @param __INSTANCE__ SMC_NAND Instance + * @param __BANK__ SMC_NAND Bank + * @param __INTERRUPT__ SMC_NAND interrupt + * This parameter can be any combination of the following values: + * @arg SMC_IT_RISING_EDGE: Interrupt rising edge. + * @arg SMC_IT_LEVEL: Interrupt level. + * @arg SMC_IT_FALLING_EDGE: Interrupt falling edge. + * @retval None + */ +#define __SMC_NAND_DISABLE_IT(__INSTANCE__, __BANK__, __INTERRUPT__) (((__BANK__) == SMC_NAND_BANK2)? ((__INSTANCE__)->STSINT2 &= ~(__INTERRUPT__)): \ + ((__INSTANCE__)->STSINT3 &= ~(__INTERRUPT__))) + +/** + * @brief Get flag status of the NAND device. + * @param __INSTANCE__ SMC_NAND Instance + * @param __BANK__ SMC_NAND Bank + * @param __FLAG__ SMC_NAND flag + * This parameter can be any combination of the following values: + * @arg SMC_FLAG_RISING_EDGE: Interrupt rising edge flag. + * @arg SMC_FLAG_LEVEL: Interrupt level edge flag. + * @arg SMC_FLAG_FALLING_EDGE: Interrupt falling edge flag. + * @arg SMC_FLAG_FEMPT: FIFO empty flag. + * @retval The state of FLAG (SET or RESET). + */ +#define __SMC_NAND_GET_FLAG(__INSTANCE__, __BANK__, __FLAG__) (((__BANK__) == SMC_NAND_BANK2)? (((__INSTANCE__)->STSINT2 &(__FLAG__)) == (__FLAG__)): \ + (((__INSTANCE__)->STSINT3 &(__FLAG__)) == (__FLAG__))) + +/** + * @brief Clear flag status of the NAND device. + * @param __INSTANCE__ SMC_NAND Instance + * @param __BANK__ SMC_NAND Bank + * @param __FLAG__ SMC_NAND flag + * This parameter can be any combination of the following values: + * @arg SMC_FLAG_RISING_EDGE: Interrupt rising edge flag. + * @arg SMC_FLAG_LEVEL: Interrupt level edge flag. + * @arg SMC_FLAG_FALLING_EDGE: Interrupt falling edge flag. + * @arg SMC_FLAG_FEMPT: FIFO empty flag. + * @retval None + */ +#define __SMC_NAND_CLEAR_FLAG(__INSTANCE__, __BANK__, __FLAG__) (((__BANK__) == SMC_NAND_BANK2)? ((__INSTANCE__)->STSINT2 &= ~(__FLAG__)): \ + ((__INSTANCE__)->STSINT3 &= ~(__FLAG__))) + +/** + * @} + */ +#endif /* SMC_Bank2_3 */ + +#if defined(SMC_Bank4) +/** @defgroup SMC_DDL_PCCARD_Interrupt SMC PCCARD Interrupt + * @brief macros to handle PCCARD interrupts + * @{ + */ + +/** + * @brief Enable the PCCARD device interrupt. + * @param __INSTANCE__ SMC_PCCARD instance + * @param __INTERRUPT__ SMC_PCCARD interrupt + * This parameter can be any combination of the following values: + * @arg SMC_IT_RISING_EDGE: Interrupt rising edge. + * @arg SMC_IT_LEVEL: Interrupt level. + * @arg SMC_IT_FALLING_EDGE: Interrupt falling edge. + * @retval None + */ +#define __SMC_PCCARD_ENABLE_IT(__INSTANCE__, __INTERRUPT__) ((__INSTANCE__)->STSINT4 |= (__INTERRUPT__)) + +/** + * @brief Disable the PCCARD device interrupt. + * @param __INSTANCE__ SMC_PCCARD instance + * @param __INTERRUPT__ SMC_PCCARD interrupt + * This parameter can be any combination of the following values: + * @arg SMC_IT_RISING_EDGE: Interrupt rising edge. + * @arg SMC_IT_LEVEL: Interrupt level. + * @arg SMC_IT_FALLING_EDGE: Interrupt falling edge. + * @retval None + */ +#define __SMC_PCCARD_DISABLE_IT(__INSTANCE__, __INTERRUPT__) ((__INSTANCE__)->STSINT4 &= ~(__INTERRUPT__)) + +/** + * @brief Get flag status of the PCCARD device. + * @param __INSTANCE__ SMC_PCCARD instance + * @param __FLAG__ SMC_PCCARD flag + * This parameter can be any combination of the following values: + * @arg SMC_FLAG_RISING_EDGE: Interrupt rising edge flag. + * @arg SMC_FLAG_LEVEL: Interrupt level edge flag. + * @arg SMC_FLAG_FALLING_EDGE: Interrupt falling edge flag. + * @arg SMC_FLAG_FEMPT: FIFO empty flag. + * @retval The state of FLAG (SET or RESET). + */ +#define __SMC_PCCARD_GET_FLAG(__INSTANCE__, __FLAG__) (((__INSTANCE__)->STSINT4 &(__FLAG__)) == (__FLAG__)) + +/** + * @brief Clear flag status of the PCCARD device. + * @param __INSTANCE__ SMC_PCCARD instance + * @param __FLAG__ SMC_PCCARD flag + * This parameter can be any combination of the following values: + * @arg SMC_FLAG_RISING_EDGE: Interrupt rising edge flag. + * @arg SMC_FLAG_LEVEL: Interrupt level edge flag. + * @arg SMC_FLAG_FALLING_EDGE: Interrupt falling edge flag. + * @arg SMC_FLAG_FEMPT: FIFO empty flag. + * @retval None + */ +#define __SMC_PCCARD_CLEAR_FLAG(__INSTANCE__, __FLAG__) ((__INSTANCE__)->STSINT4 &= ~(__FLAG__)) + +/** + * @} + */ +#endif + +/** + * @} + */ + +/** + * @} + */ + +/* Private functions ---------------------------------------------------------*/ +/** @defgroup SMC_DDL_Private_Functions SMC DDL Private Functions + * @{ + */ + +#if defined(SMC_Bank1) +/** @defgroup SMC_DDL_NORSRAM NOR SRAM + * @{ + */ +/** @defgroup SMC_DDL_NORSRAM_Private_Functions_Group1 NOR SRAM Initialization/de-initialization functions + * @{ + */ +DAL_StatusTypeDef SMC_NORSRAM_Init(SMC_NORSRAM_TypeDef *Device, + SMC_NORSRAM_InitTypeDef *Init); +DAL_StatusTypeDef SMC_NORSRAM_Timing_Init(SMC_NORSRAM_TypeDef *Device, + SMC_NORSRAM_TimingTypeDef *Timing, uint32_t Bank); +DAL_StatusTypeDef SMC_NORSRAM_Extended_Timing_Init(SMC_NORSRAM_EXTENDED_TypeDef *Device, + SMC_NORSRAM_TimingTypeDef *Timing, uint32_t Bank, + uint32_t ExtendedMode); +DAL_StatusTypeDef SMC_NORSRAM_DeInit(SMC_NORSRAM_TypeDef *Device, + SMC_NORSRAM_EXTENDED_TypeDef *ExDevice, uint32_t Bank); +/** + * @} + */ + +/** @defgroup SMC_DDL_NORSRAM_Private_Functions_Group2 NOR SRAM Control functions + * @{ + */ +DAL_StatusTypeDef SMC_NORSRAM_WriteOperation_Enable(SMC_NORSRAM_TypeDef *Device, uint32_t Bank); +DAL_StatusTypeDef SMC_NORSRAM_WriteOperation_Disable(SMC_NORSRAM_TypeDef *Device, uint32_t Bank); +/** + * @} + */ +/** + * @} + */ +#endif /* SMC_Bank1 */ + +#if defined(SMC_Bank2_3) +/** @defgroup SMC_DDL_NAND NAND + * @{ + */ +/** @defgroup SMC_DDL_NAND_Private_Functions_Group1 NAND Initialization/de-initialization functions + * @{ + */ +DAL_StatusTypeDef SMC_NAND_Init(SMC_NAND_TypeDef *Device, SMC_NAND_InitTypeDef *Init); +DAL_StatusTypeDef SMC_NAND_CommonSpace_Timing_Init(SMC_NAND_TypeDef *Device, + SMC_NAND_PCC_TimingTypeDef *Timing, uint32_t Bank); +DAL_StatusTypeDef SMC_NAND_AttributeSpace_Timing_Init(SMC_NAND_TypeDef *Device, + SMC_NAND_PCC_TimingTypeDef *Timing, uint32_t Bank); +DAL_StatusTypeDef SMC_NAND_DeInit(SMC_NAND_TypeDef *Device, uint32_t Bank); +/** + * @} + */ + +/** @defgroup SMC_DDL_NAND_Private_Functions_Group2 NAND Control functions + * @{ + */ +DAL_StatusTypeDef SMC_NAND_ECC_Enable(SMC_NAND_TypeDef *Device, uint32_t Bank); +DAL_StatusTypeDef SMC_NAND_ECC_Disable(SMC_NAND_TypeDef *Device, uint32_t Bank); +DAL_StatusTypeDef SMC_NAND_GetECC(SMC_NAND_TypeDef *Device, uint32_t *ECCval, uint32_t Bank, + uint32_t Timeout); +/** + * @} + */ +/** + * @} + */ +#endif /* SMC_Bank2_3 */ + +#if defined(SMC_Bank4) +/** @defgroup SMC_DDL_PCCARD PCCARD + * @{ + */ +/** @defgroup SMC_DDL_PCCARD_Private_Functions_Group1 PCCARD Initialization/de-initialization functions + * @{ + */ +DAL_StatusTypeDef SMC_PCCARD_Init(SMC_PCCARD_TypeDef *Device, SMC_PCCARD_InitTypeDef *Init); +DAL_StatusTypeDef SMC_PCCARD_CommonSpace_Timing_Init(SMC_PCCARD_TypeDef *Device, + SMC_NAND_PCC_TimingTypeDef *Timing); +DAL_StatusTypeDef SMC_PCCARD_AttributeSpace_Timing_Init(SMC_PCCARD_TypeDef *Device, + SMC_NAND_PCC_TimingTypeDef *Timing); +DAL_StatusTypeDef SMC_PCCARD_IOSpace_Timing_Init(SMC_PCCARD_TypeDef *Device, + SMC_NAND_PCC_TimingTypeDef *Timing); +DAL_StatusTypeDef SMC_PCCARD_DeInit(SMC_PCCARD_TypeDef *Device); +/** + * @} + */ +/** + * @} + */ +#endif /* SMC_Bank4 */ + + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* APM32F4xx_DDL_SMC_H */ diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_spi.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_spi.h new file mode 100644 index 0000000000..dec24be09f --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_spi.h @@ -0,0 +1,1930 @@ +/** + * + * @file apm32f4xx_ddl_spi.h + * @brief Header file of SPI DDL module. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef APM32F4xx_DDL_SPI_H +#define APM32F4xx_DDL_SPI_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx.h" + +/** @addtogroup APM32F4xx_DDL_Driver + * @{ + */ + +#if defined (SPI1) || defined (SPI2) || defined (SPI3) || defined (SPI4) || defined (SPI5) || defined(SPI6) + +/** @defgroup SPI_DDL SPI + * @{ + */ + +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private macros ------------------------------------------------------------*/ + +/* Exported types ------------------------------------------------------------*/ +#if defined(USE_FULL_DDL_DRIVER) +/** @defgroup SPI_DDL_ES_INIT SPI Exported Init structure + * @{ + */ + +/** + * @brief SPI Init structures definition + */ +typedef struct +{ + uint32_t TransferDirection; /*!< Specifies the SPI unidirectional or bidirectional data mode. + This parameter can be a value of @ref SPI_DDL_EC_TRANSFER_MODE. + + This feature can be modified afterwards using unitary function @ref DDL_SPI_SetTransferDirection().*/ + + uint32_t Mode; /*!< Specifies the SPI mode (Master/Slave). + This parameter can be a value of @ref SPI_DDL_EC_MODE. + + This feature can be modified afterwards using unitary function @ref DDL_SPI_SetMode().*/ + + uint32_t DataWidth; /*!< Specifies the SPI data width. + This parameter can be a value of @ref SPI_DDL_EC_DATAWIDTH. + + This feature can be modified afterwards using unitary function @ref DDL_SPI_SetDataWidth().*/ + + uint32_t ClockPolarity; /*!< Specifies the serial clock steady state. + This parameter can be a value of @ref SPI_DDL_EC_POLARITY. + + This feature can be modified afterwards using unitary function @ref DDL_SPI_SetClockPolarity().*/ + + uint32_t ClockPhase; /*!< Specifies the clock active edge for the bit capture. + This parameter can be a value of @ref SPI_DDL_EC_PHASE. + + This feature can be modified afterwards using unitary function @ref DDL_SPI_SetClockPhase().*/ + + uint32_t NSS; /*!< Specifies whether the NSS signal is managed by hardware (NSS pin) or by software using the SSI bit. + This parameter can be a value of @ref SPI_DDL_EC_NSS_MODE. + + This feature can be modified afterwards using unitary function @ref DDL_SPI_SetNSSMode().*/ + + uint32_t BaudRate; /*!< Specifies the BaudRate prescaler value which will be used to configure the transmit and receive SCK clock. + This parameter can be a value of @ref SPI_DDL_EC_BAUDRATEPRESCALER. + @note The communication clock is derived from the master clock. The slave clock does not need to be set. + + This feature can be modified afterwards using unitary function @ref DDL_SPI_SetBaudRatePrescaler().*/ + + uint32_t BitOrder; /*!< Specifies whether data transfers start from MSB or LSB bit. + This parameter can be a value of @ref SPI_DDL_EC_BIT_ORDER. + + This feature can be modified afterwards using unitary function @ref DDL_SPI_SetTransferBitOrder().*/ + + uint32_t CRCCalculation; /*!< Specifies if the CRC calculation is enabled or not. + This parameter can be a value of @ref SPI_DDL_EC_CRC_CALCULATION. + + This feature can be modified afterwards using unitary functions @ref DDL_SPI_EnableCRC() and @ref DDL_SPI_DisableCRC().*/ + + uint32_t CRCPoly; /*!< Specifies the polynomial used for the CRC calculation. + This parameter must be a number between Min_Data = 0x00 and Max_Data = 0xFFFF. + + This feature can be modified afterwards using unitary function @ref DDL_SPI_SetCRCPolynomial().*/ + +} DDL_SPI_InitTypeDef; + +/** + * @} + */ +#endif /* USE_FULL_DDL_DRIVER */ + +/* Exported constants --------------------------------------------------------*/ +/** @defgroup SPI_DDL_Exported_Constants SPI Exported Constants + * @{ + */ + +/** @defgroup SPI_DDL_EC_GET_FLAG Get Flags Defines + * @brief Flags defines which can be used with DDL_SPI_ReadReg function + * @{ + */ +#define DDL_SPI_STS_RXBNEFLG SPI_STS_RXBNEFLG /*!< Rx buffer not empty flag */ +#define DDL_SPI_STS_TXBEFLG SPI_STS_TXBEFLG /*!< Tx buffer empty flag */ +#define DDL_SPI_STS_BSYFLG SPI_STS_BSYFLG /*!< Busy flag */ +#define DDL_SPI_STS_CRCEFLG SPI_STS_CRCEFLG /*!< CRC error flag */ +#define DDL_SPI_STS_MEFLG SPI_STS_MEFLG /*!< Mode fault flag */ +#define DDL_SPI_STS_OVRFLG SPI_STS_OVRFLG /*!< Overrun flag */ +#define DDL_SPI_STS_FFERR SPI_STS_FFERR /*!< TI mode frame format error flag */ +/** + * @} + */ + +/** @defgroup SPI_DDL_EC_IT IT Defines + * @brief IT defines which can be used with DDL_SPI_ReadReg and DDL_SPI_WriteReg functions + * @{ + */ +#define DDL_SPI_CTRL2_RXBNEIEN SPI_CTRL2_RXBNEIEN /*!< Rx buffer not empty interrupt enable */ +#define DDL_SPI_CTRL2_TXBEIEN SPI_CTRL2_TXBEIEN /*!< Tx buffer empty interrupt enable */ +#define DDL_SPI_CTRL2_ERRIEN SPI_CTRL2_ERRIEN /*!< Error interrupt enable */ +/** + * @} + */ + +/** @defgroup SPI_DDL_EC_MODE Operation Mode + * @{ + */ +#define DDL_SPI_MODE_MASTER (SPI_CTRL1_MSMCFG | SPI_CTRL1_ISSEL) /*!< Master configuration */ +#define DDL_SPI_MODE_SLAVE 0x00000000U /*!< Slave configuration */ +/** + * @} + */ + +/** @defgroup SPI_DDL_EC_PROTOCOL Serial Protocol + * @{ + */ +#define DDL_SPI_PROTOCOL_MOTOROLA 0x00000000U /*!< Motorola mode. Used as default value */ +#define DDL_SPI_PROTOCOL_TI (SPI_CTRL2_FRFCFG) /*!< TI mode */ +/** + * @} + */ + +/** @defgroup SPI_DDL_EC_PHASE Clock Phase + * @{ + */ +#define DDL_SPI_PHASE_1EDGE 0x00000000U /*!< First clock transition is the first data capture edge */ +#define DDL_SPI_PHASE_2EDGE (SPI_CTRL1_CPHA) /*!< Second clock transition is the first data capture edge */ +/** + * @} + */ + +/** @defgroup SPI_DDL_EC_POLARITY Clock Polarity + * @{ + */ +#define DDL_SPI_POLARITY_LOW 0x00000000U /*!< Clock to 0 when idle */ +#define DDL_SPI_POLARITY_HIGH (SPI_CTRL1_CPOL) /*!< Clock to 1 when idle */ +/** + * @} + */ + +/** @defgroup SPI_DDL_EC_BAUDRATEPRESCALER Baud Rate Prescaler + * @{ + */ +#define DDL_SPI_BAUDRATEPRESCALER_DIV2 0x00000000U /*!< BaudRate control equal to fPCLK/2 */ +#define DDL_SPI_BAUDRATEPRESCALER_DIV4 (SPI_CTRL1_BRSEL_0) /*!< BaudRate control equal to fPCLK/4 */ +#define DDL_SPI_BAUDRATEPRESCALER_DIV8 (SPI_CTRL1_BRSEL_1) /*!< BaudRate control equal to fPCLK/8 */ +#define DDL_SPI_BAUDRATEPRESCALER_DIV16 (SPI_CTRL1_BRSEL_1 | SPI_CTRL1_BRSEL_0) /*!< BaudRate control equal to fPCLK/16 */ +#define DDL_SPI_BAUDRATEPRESCALER_DIV32 (SPI_CTRL1_BRSEL_2) /*!< BaudRate control equal to fPCLK/32 */ +#define DDL_SPI_BAUDRATEPRESCALER_DIV64 (SPI_CTRL1_BRSEL_2 | SPI_CTRL1_BRSEL_0) /*!< BaudRate control equal to fPCLK/64 */ +#define DDL_SPI_BAUDRATEPRESCALER_DIV128 (SPI_CTRL1_BRSEL_2 | SPI_CTRL1_BRSEL_1) /*!< BaudRate control equal to fPCLK/128 */ +#define DDL_SPI_BAUDRATEPRESCALER_DIV256 (SPI_CTRL1_BRSEL_2 | SPI_CTRL1_BRSEL_1 | SPI_CTRL1_BRSEL_0) /*!< BaudRate control equal to fPCLK/256 */ +/** + * @} + */ + +/** @defgroup SPI_DDL_EC_BIT_ORDER Transmission Bit Order + * @{ + */ +#define DDL_SPI_LSB_FIRST (SPI_CTRL1_LSBSEL) /*!< Data is transmitted/received with the LSB first */ +#define DDL_SPI_MSB_FIRST 0x00000000U /*!< Data is transmitted/received with the MSB first */ +/** + * @} + */ + +/** @defgroup SPI_DDL_EC_TRANSFER_MODE Transfer Mode + * @{ + */ +#define DDL_SPI_FULL_DUPLEX 0x00000000U /*!< Full-Duplex mode. Rx and Tx transfer on 2 lines */ +#define DDL_SPI_SIMPLEX_RX (SPI_CTRL1_RXOMEN) /*!< Simplex Rx mode. Rx transfer only on 1 line */ +#define DDL_SPI_HALF_DUPLEX_RX (SPI_CTRL1_BMEN) /*!< Half-Duplex Rx mode. Rx transfer on 1 line */ +#define DDL_SPI_HALF_DUPLEX_TX (SPI_CTRL1_BMEN | SPI_CTRL1_BMOEN) /*!< Half-Duplex Tx mode. Tx transfer on 1 line */ +/** + * @} + */ + +/** @defgroup SPI_DDL_EC_NSS_MODE Slave Select Pin Mode + * @{ + */ +#define DDL_SPI_NSS_SOFT (SPI_CTRL1_SSEN) /*!< NSS managed internally. NSS pin not used and free */ +#define DDL_SPI_NSS_HARD_INPUT 0x00000000U /*!< NSS pin used in Input. Only used in Master mode */ +#define DDL_SPI_NSS_HARD_OUTPUT (((uint32_t)SPI_CTRL2_SSOEN << 16U)) /*!< NSS pin used in Output. Only used in Slave mode as chip select */ +/** + * @} + */ + +/** @defgroup SPI_DDL_EC_DATAWIDTH Datawidth + * @{ + */ +#define DDL_SPI_DATAWIDTH_8BIT 0x00000000U /*!< Data length for SPI transfer: 8 bits */ +#define DDL_SPI_DATAWIDTH_16BIT (SPI_CTRL1_DFLSEL) /*!< Data length for SPI transfer: 16 bits */ +/** + * @} + */ +#if defined(USE_FULL_DDL_DRIVER) + +/** @defgroup SPI_DDL_EC_CRC_CALCULATION CRC Calculation + * @{ + */ +#define DDL_SPI_CRCCALCULATION_DISABLE 0x00000000U /*!< CRC calculation disabled */ +#define DDL_SPI_CRCCALCULATION_ENABLE (SPI_CTRL1_CRCEN) /*!< CRC calculation enabled */ +/** + * @} + */ +#endif /* USE_FULL_DDL_DRIVER */ + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ +/** @defgroup SPI_DDL_Exported_Macros SPI Exported Macros + * @{ + */ + +/** @defgroup SPI_DDL_EM_WRITE_READ Common Write and read registers Macros + * @{ + */ + +/** + * @brief Write a value in SPI register + * @param __INSTANCE__ SPI Instance + * @param __REG__ Register to be written + * @param __VALUE__ Value to be written in the register + * @retval None + */ +#define DDL_SPI_WriteReg(__INSTANCE__, __REG__, __VALUE__) WRITE_REG(__INSTANCE__->__REG__, (__VALUE__)) + +/** + * @brief Read a value in SPI register + * @param __INSTANCE__ SPI Instance + * @param __REG__ Register to be read + * @retval Register value + */ +#define DDL_SPI_ReadReg(__INSTANCE__, __REG__) READ_REG(__INSTANCE__->__REG__) +/** + * @} + */ + +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +/** @defgroup SPI_DDL_Exported_Functions SPI Exported Functions + * @{ + */ + +/** @defgroup SPI_DDL_EF_Configuration Configuration + * @{ + */ + +/** + * @brief Enable SPI peripheral + * @param SPIx SPI Instance + * @retval None + */ +__STATIC_INLINE void DDL_SPI_Enable(SPI_TypeDef *SPIx) +{ + SET_BIT(SPIx->CTRL1, SPI_CTRL1_SPIEN); +} + +/** + * @brief Disable SPI peripheral + * @note When disabling the SPI, follow the procedure described in the Reference Manual. + * @param SPIx SPI Instance + * @retval None + */ +__STATIC_INLINE void DDL_SPI_Disable(SPI_TypeDef *SPIx) +{ + CLEAR_BIT(SPIx->CTRL1, SPI_CTRL1_SPIEN); +} + +/** + * @brief Check if SPI peripheral is enabled + * @param SPIx SPI Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_SPI_IsEnabled(SPI_TypeDef *SPIx) +{ + return ((READ_BIT(SPIx->CTRL1, SPI_CTRL1_SPIEN) == (SPI_CTRL1_SPIEN)) ? 1UL : 0UL); +} + +/** + * @brief Set SPI operation mode to Master or Slave + * @note This bit should not be changed when communication is ongoing. + * @param SPIx SPI Instance + * @param Mode This parameter can be one of the following values: + * @arg @ref DDL_SPI_MODE_MASTER + * @arg @ref DDL_SPI_MODE_SLAVE + * @retval None + */ +__STATIC_INLINE void DDL_SPI_SetMode(SPI_TypeDef *SPIx, uint32_t Mode) +{ + MODIFY_REG(SPIx->CTRL1, SPI_CTRL1_MSMCFG | SPI_CTRL1_ISSEL, Mode); +} + +/** + * @brief Get SPI operation mode (Master or Slave) + * @param SPIx SPI Instance + * @retval Returned value can be one of the following values: + * @arg @ref DDL_SPI_MODE_MASTER + * @arg @ref DDL_SPI_MODE_SLAVE + */ +__STATIC_INLINE uint32_t DDL_SPI_GetMode(SPI_TypeDef *SPIx) +{ + return (uint32_t)(READ_BIT(SPIx->CTRL1, SPI_CTRL1_MSMCFG | SPI_CTRL1_ISSEL)); +} + +/** + * @brief Set serial protocol used + * @note This bit should be written only when SPI is disabled (SPE = 0) for correct operation. + * @param SPIx SPI Instance + * @param Standard This parameter can be one of the following values: + * @arg @ref DDL_SPI_PROTOCOL_MOTOROLA + * @arg @ref DDL_SPI_PROTOCOL_TI + * @retval None + */ +__STATIC_INLINE void DDL_SPI_SetStandard(SPI_TypeDef *SPIx, uint32_t Standard) +{ + MODIFY_REG(SPIx->CTRL2, SPI_CTRL2_FRFCFG, Standard); +} + +/** + * @brief Get serial protocol used + * @param SPIx SPI Instance + * @retval Returned value can be one of the following values: + * @arg @ref DDL_SPI_PROTOCOL_MOTOROLA + * @arg @ref DDL_SPI_PROTOCOL_TI + */ +__STATIC_INLINE uint32_t DDL_SPI_GetStandard(SPI_TypeDef *SPIx) +{ + return (uint32_t)(READ_BIT(SPIx->CTRL2, SPI_CTRL2_FRFCFG)); +} + +/** + * @brief Set clock phase + * @note This bit should not be changed when communication is ongoing. + * This bit is not used in SPI TI mode. + * @param SPIx SPI Instance + * @param ClockPhase This parameter can be one of the following values: + * @arg @ref DDL_SPI_PHASE_1EDGE + * @arg @ref DDL_SPI_PHASE_2EDGE + * @retval None + */ +__STATIC_INLINE void DDL_SPI_SetClockPhase(SPI_TypeDef *SPIx, uint32_t ClockPhase) +{ + MODIFY_REG(SPIx->CTRL1, SPI_CTRL1_CPHA, ClockPhase); +} + +/** + * @brief Get clock phase + * @param SPIx SPI Instance + * @retval Returned value can be one of the following values: + * @arg @ref DDL_SPI_PHASE_1EDGE + * @arg @ref DDL_SPI_PHASE_2EDGE + */ +__STATIC_INLINE uint32_t DDL_SPI_GetClockPhase(SPI_TypeDef *SPIx) +{ + return (uint32_t)(READ_BIT(SPIx->CTRL1, SPI_CTRL1_CPHA)); +} + +/** + * @brief Set clock polarity + * @note This bit should not be changed when communication is ongoing. + * This bit is not used in SPI TI mode. + * @param SPIx SPI Instance + * @param ClockPolarity This parameter can be one of the following values: + * @arg @ref DDL_SPI_POLARITY_LOW + * @arg @ref DDL_SPI_POLARITY_HIGH + * @retval None + */ +__STATIC_INLINE void DDL_SPI_SetClockPolarity(SPI_TypeDef *SPIx, uint32_t ClockPolarity) +{ + MODIFY_REG(SPIx->CTRL1, SPI_CTRL1_CPOL, ClockPolarity); +} + +/** + * @brief Get clock polarity + * @param SPIx SPI Instance + * @retval Returned value can be one of the following values: + * @arg @ref DDL_SPI_POLARITY_LOW + * @arg @ref DDL_SPI_POLARITY_HIGH + */ +__STATIC_INLINE uint32_t DDL_SPI_GetClockPolarity(SPI_TypeDef *SPIx) +{ + return (uint32_t)(READ_BIT(SPIx->CTRL1, SPI_CTRL1_CPOL)); +} + +/** + * @brief Set baud rate prescaler + * @note These bits should not be changed when communication is ongoing. SPI BaudRate = fPCLK/Prescaler. + * @param SPIx SPI Instance + * @param BaudRate This parameter can be one of the following values: + * @arg @ref DDL_SPI_BAUDRATEPRESCALER_DIV2 + * @arg @ref DDL_SPI_BAUDRATEPRESCALER_DIV4 + * @arg @ref DDL_SPI_BAUDRATEPRESCALER_DIV8 + * @arg @ref DDL_SPI_BAUDRATEPRESCALER_DIV16 + * @arg @ref DDL_SPI_BAUDRATEPRESCALER_DIV32 + * @arg @ref DDL_SPI_BAUDRATEPRESCALER_DIV64 + * @arg @ref DDL_SPI_BAUDRATEPRESCALER_DIV128 + * @arg @ref DDL_SPI_BAUDRATEPRESCALER_DIV256 + * @retval None + */ +__STATIC_INLINE void DDL_SPI_SetBaudRatePrescaler(SPI_TypeDef *SPIx, uint32_t BaudRate) +{ + MODIFY_REG(SPIx->CTRL1, SPI_CTRL1_BRSEL, BaudRate); +} + +/** + * @brief Get baud rate prescaler + * @param SPIx SPI Instance + * @retval Returned value can be one of the following values: + * @arg @ref DDL_SPI_BAUDRATEPRESCALER_DIV2 + * @arg @ref DDL_SPI_BAUDRATEPRESCALER_DIV4 + * @arg @ref DDL_SPI_BAUDRATEPRESCALER_DIV8 + * @arg @ref DDL_SPI_BAUDRATEPRESCALER_DIV16 + * @arg @ref DDL_SPI_BAUDRATEPRESCALER_DIV32 + * @arg @ref DDL_SPI_BAUDRATEPRESCALER_DIV64 + * @arg @ref DDL_SPI_BAUDRATEPRESCALER_DIV128 + * @arg @ref DDL_SPI_BAUDRATEPRESCALER_DIV256 + */ +__STATIC_INLINE uint32_t DDL_SPI_GetBaudRatePrescaler(SPI_TypeDef *SPIx) +{ + return (uint32_t)(READ_BIT(SPIx->CTRL1, SPI_CTRL1_BRSEL)); +} + +/** + * @brief Set transfer bit order + * @note This bit should not be changed when communication is ongoing. This bit is not used in SPI TI mode. + * @param SPIx SPI Instance + * @param BitOrder This parameter can be one of the following values: + * @arg @ref DDL_SPI_LSB_FIRST + * @arg @ref DDL_SPI_MSB_FIRST + * @retval None + */ +__STATIC_INLINE void DDL_SPI_SetTransferBitOrder(SPI_TypeDef *SPIx, uint32_t BitOrder) +{ + MODIFY_REG(SPIx->CTRL1, SPI_CTRL1_LSBSEL, BitOrder); +} + +/** + * @brief Get transfer bit order + * @param SPIx SPI Instance + * @retval Returned value can be one of the following values: + * @arg @ref DDL_SPI_LSB_FIRST + * @arg @ref DDL_SPI_MSB_FIRST + */ +__STATIC_INLINE uint32_t DDL_SPI_GetTransferBitOrder(SPI_TypeDef *SPIx) +{ + return (uint32_t)(READ_BIT(SPIx->CTRL1, SPI_CTRL1_LSBSEL)); +} + +/** + * @brief Set transfer direction mode + * @note For Half-Duplex mode, Rx Direction is set by default. + * In master mode, the MOSI pin is used and in slave mode, the MISO pin is used for Half-Duplex. + * @param SPIx SPI Instance + * @param TransferDirection This parameter can be one of the following values: + * @arg @ref DDL_SPI_FULL_DUPLEX + * @arg @ref DDL_SPI_SIMPLEX_RX + * @arg @ref DDL_SPI_HALF_DUPLEX_RX + * @arg @ref DDL_SPI_HALF_DUPLEX_TX + * @retval None + */ +__STATIC_INLINE void DDL_SPI_SetTransferDirection(SPI_TypeDef *SPIx, uint32_t TransferDirection) +{ + MODIFY_REG(SPIx->CTRL1, SPI_CTRL1_RXOMEN | SPI_CTRL1_BMEN | SPI_CTRL1_BMOEN, TransferDirection); +} + +/** + * @brief Get transfer direction mode + * @param SPIx SPI Instance + * @retval Returned value can be one of the following values: + * @arg @ref DDL_SPI_FULL_DUPLEX + * @arg @ref DDL_SPI_SIMPLEX_RX + * @arg @ref DDL_SPI_HALF_DUPLEX_RX + * @arg @ref DDL_SPI_HALF_DUPLEX_TX + */ +__STATIC_INLINE uint32_t DDL_SPI_GetTransferDirection(SPI_TypeDef *SPIx) +{ + return (uint32_t)(READ_BIT(SPIx->CTRL1, SPI_CTRL1_RXOMEN | SPI_CTRL1_BMEN | SPI_CTRL1_BMOEN)); +} + +/** + * @brief Set frame data width + * @param SPIx SPI Instance + * @param DataWidth This parameter can be one of the following values: + * @arg @ref DDL_SPI_DATAWIDTH_8BIT + * @arg @ref DDL_SPI_DATAWIDTH_16BIT + * @retval None + */ +__STATIC_INLINE void DDL_SPI_SetDataWidth(SPI_TypeDef *SPIx, uint32_t DataWidth) +{ + MODIFY_REG(SPIx->CTRL1, SPI_CTRL1_DFLSEL, DataWidth); +} + +/** + * @brief Get frame data width + * @param SPIx SPI Instance + * @retval Returned value can be one of the following values: + * @arg @ref DDL_SPI_DATAWIDTH_8BIT + * @arg @ref DDL_SPI_DATAWIDTH_16BIT + */ +__STATIC_INLINE uint32_t DDL_SPI_GetDataWidth(SPI_TypeDef *SPIx) +{ + return (uint32_t)(READ_BIT(SPIx->CTRL1, SPI_CTRL1_DFLSEL)); +} + +/** + * @} + */ + +/** @defgroup SPI_DDL_EF_CRC_Management CRC Management + * @{ + */ + +/** + * @brief Enable CRC + * @note This bit should be written only when SPI is disabled (SPE = 0) for correct operation. + * @param SPIx SPI Instance + * @retval None + */ +__STATIC_INLINE void DDL_SPI_EnableCRC(SPI_TypeDef *SPIx) +{ + SET_BIT(SPIx->CTRL1, SPI_CTRL1_CRCEN); +} + +/** + * @brief Disable CRC + * @note This bit should be written only when SPI is disabled (SPE = 0) for correct operation. + * @param SPIx SPI Instance + * @retval None + */ +__STATIC_INLINE void DDL_SPI_DisableCRC(SPI_TypeDef *SPIx) +{ + CLEAR_BIT(SPIx->CTRL1, SPI_CTRL1_CRCEN); +} + +/** + * @brief Check if CRC is enabled + * @note This bit should be written only when SPI is disabled (SPE = 0) for correct operation. + * @param SPIx SPI Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_SPI_IsEnabledCRC(SPI_TypeDef *SPIx) +{ + return ((READ_BIT(SPIx->CTRL1, SPI_CTRL1_CRCEN) == (SPI_CTRL1_CRCEN)) ? 1UL : 0UL); +} + +/** + * @brief Set CRCNext to transfer CRC on the line + * @note This bit has to be written as soon as the last data is written in the SPIx_DR register. + * @param SPIx SPI Instance + * @retval None + */ +__STATIC_INLINE void DDL_SPI_SetCRCNext(SPI_TypeDef *SPIx) +{ + SET_BIT(SPIx->CTRL1, SPI_CTRL1_CRCNXT); +} + +/** + * @brief Set polynomial for CRC calculation + * @param SPIx SPI Instance + * @param CRCPoly This parameter must be a number between Min_Data = 0x00 and Max_Data = 0xFFFF + * @retval None + */ +__STATIC_INLINE void DDL_SPI_SetCRCPolynomial(SPI_TypeDef *SPIx, uint32_t CRCPoly) +{ + WRITE_REG(SPIx->CRCPOLY, (uint16_t)CRCPoly); +} + +/** + * @brief Get polynomial for CRC calculation + * @param SPIx SPI Instance + * @retval Returned value is a number between Min_Data = 0x00 and Max_Data = 0xFFFF + */ +__STATIC_INLINE uint32_t DDL_SPI_GetCRCPolynomial(SPI_TypeDef *SPIx) +{ + return (uint32_t)(READ_REG(SPIx->CRCPOLY)); +} + +/** + * @brief Get Rx CRC + * @param SPIx SPI Instance + * @retval Returned value is a number between Min_Data = 0x00 and Max_Data = 0xFFFF + */ +__STATIC_INLINE uint32_t DDL_SPI_GetRxCRC(SPI_TypeDef *SPIx) +{ + return (uint32_t)(READ_REG(SPIx->RXCRC)); +} + +/** + * @brief Get Tx CRC + * @param SPIx SPI Instance + * @retval Returned value is a number between Min_Data = 0x00 and Max_Data = 0xFFFF + */ +__STATIC_INLINE uint32_t DDL_SPI_GetTxCRC(SPI_TypeDef *SPIx) +{ + return (uint32_t)(READ_REG(SPIx->TXCRC)); +} + +/** + * @} + */ + +/** @defgroup SPI_DDL_EF_NSS_Management Slave Select Pin Management + * @{ + */ + +/** + * @brief Set NSS mode + * @note DDL_SPI_NSS_SOFT Mode is not used in SPI TI mode. + * @param SPIx SPI Instance + * @param NSS This parameter can be one of the following values: + * @arg @ref DDL_SPI_NSS_SOFT + * @arg @ref DDL_SPI_NSS_HARD_INPUT + * @arg @ref DDL_SPI_NSS_HARD_OUTPUT + * @retval None + */ +__STATIC_INLINE void DDL_SPI_SetNSSMode(SPI_TypeDef *SPIx, uint32_t NSS) +{ + MODIFY_REG(SPIx->CTRL1, SPI_CTRL1_SSEN, NSS); + MODIFY_REG(SPIx->CTRL2, SPI_CTRL2_SSOEN, ((uint32_t)(NSS >> 16U))); +} + +/** + * @brief Get NSS mode + * @param SPIx SPI Instance + * @retval Returned value can be one of the following values: + * @arg @ref DDL_SPI_NSS_SOFT + * @arg @ref DDL_SPI_NSS_HARD_INPUT + * @arg @ref DDL_SPI_NSS_HARD_OUTPUT + */ +__STATIC_INLINE uint32_t DDL_SPI_GetNSSMode(SPI_TypeDef *SPIx) +{ + uint32_t Ssm = (READ_BIT(SPIx->CTRL1, SPI_CTRL1_SSEN)); + uint32_t Ssoe = (READ_BIT(SPIx->CTRL2, SPI_CTRL2_SSOEN) << 16U); + return (Ssm | Ssoe); +} + +/** + * @} + */ + +/** @defgroup SPI_DDL_EF_FLAG_Management FLAG Management + * @{ + */ + +/** + * @brief Check if Rx buffer is not empty + * @param SPIx SPI Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_SPI_IsActiveFlag_RXNE(SPI_TypeDef *SPIx) +{ + return ((READ_BIT(SPIx->STS, SPI_STS_RXBNEFLG) == (SPI_STS_RXBNEFLG)) ? 1UL : 0UL); +} + +/** + * @brief Check if Tx buffer is empty + * @param SPIx SPI Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_SPI_IsActiveFlag_TXE(SPI_TypeDef *SPIx) +{ + return ((READ_BIT(SPIx->STS, SPI_STS_TXBEFLG) == (SPI_STS_TXBEFLG)) ? 1UL : 0UL); +} + +/** + * @brief Get CRC error flag + * @param SPIx SPI Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_SPI_IsActiveFlag_CRCERR(SPI_TypeDef *SPIx) +{ + return ((READ_BIT(SPIx->STS, SPI_STS_CRCEFLG) == (SPI_STS_CRCEFLG)) ? 1UL : 0UL); +} + +/** + * @brief Get mode fault error flag + * @param SPIx SPI Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_SPI_IsActiveFlag_MODF(SPI_TypeDef *SPIx) +{ + return ((READ_BIT(SPIx->STS, SPI_STS_MEFLG) == (SPI_STS_MEFLG)) ? 1UL : 0UL); +} + +/** + * @brief Get overrun error flag + * @param SPIx SPI Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_SPI_IsActiveFlag_OVR(SPI_TypeDef *SPIx) +{ + return ((READ_BIT(SPIx->STS, SPI_STS_OVRFLG) == (SPI_STS_OVRFLG)) ? 1UL : 0UL); +} + +/** + * @brief Get busy flag + * @note The BSY flag is cleared under any one of the following conditions: + * -When the SPI is correctly disabled + * -When a fault is detected in Master mode (MODF bit set to 1) + * -In Master mode, when it finishes a data transmission and no new data is ready to be + * sent + * -In Slave mode, when the BSY flag is set to '0' for at least one SPI clock cycle between + * each data transfer. + * @param SPIx SPI Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_SPI_IsActiveFlag_BSY(SPI_TypeDef *SPIx) +{ + return ((READ_BIT(SPIx->STS, SPI_STS_BSYFLG) == (SPI_STS_BSYFLG)) ? 1UL : 0UL); +} + +/** + * @brief Get frame format error flag + * @param SPIx SPI Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_SPI_IsActiveFlag_FRE(SPI_TypeDef *SPIx) +{ + return ((READ_BIT(SPIx->STS, SPI_STS_FFERR) == (SPI_STS_FFERR)) ? 1UL : 0UL); +} + +/** + * @brief Clear CRC error flag + * @param SPIx SPI Instance + * @retval None + */ +__STATIC_INLINE void DDL_SPI_ClearFlag_CRCERR(SPI_TypeDef *SPIx) +{ + CLEAR_BIT(SPIx->STS, SPI_STS_CRCEFLG); +} + +/** + * @brief Clear mode fault error flag + * @note Clearing this flag is done by a read access to the SPIx_STS + * register followed by a write access to the SPIx_CTRL1 register + * @param SPIx SPI Instance + * @retval None + */ +__STATIC_INLINE void DDL_SPI_ClearFlag_MODF(SPI_TypeDef *SPIx) +{ + __IO uint32_t tmpreg_sr; + tmpreg_sr = SPIx->STS; + (void) tmpreg_sr; + CLEAR_BIT(SPIx->CTRL1, SPI_CTRL1_SPIEN); +} + +/** + * @brief Clear overrun error flag + * @note Clearing this flag is done by a read access to the SPIx_DATA + * register followed by a read access to the SPIx_SR register + * @param SPIx SPI Instance + * @retval None + */ +__STATIC_INLINE void DDL_SPI_ClearFlag_OVR(SPI_TypeDef *SPIx) +{ + __IO uint32_t tmpreg; + tmpreg = SPIx->DATA; + (void) tmpreg; + tmpreg = SPIx->STS; + (void) tmpreg; +} + +/** + * @brief Clear frame format error flag + * @note Clearing this flag is done by reading SPIx_STS register + * @param SPIx SPI Instance + * @retval None + */ +__STATIC_INLINE void DDL_SPI_ClearFlag_FRE(SPI_TypeDef *SPIx) +{ + __IO uint32_t tmpreg; + tmpreg = SPIx->STS; + (void) tmpreg; +} + +/** + * @} + */ + +/** @defgroup SPI_DDL_EF_IT_Management Interrupt Management + * @{ + */ + +/** + * @brief Enable error interrupt + * @note This bit controls the generation of an interrupt when an error condition occurs (CRCERR, OVR, MODF in SPI mode, FRE at TI mode). + * @param SPIx SPI Instance + * @retval None + */ +__STATIC_INLINE void DDL_SPI_EnableIT_ERR(SPI_TypeDef *SPIx) +{ + SET_BIT(SPIx->CTRL2, SPI_CTRL2_ERRIEN); +} + +/** + * @brief Enable Rx buffer not empty interrupt + * @param SPIx SPI Instance + * @retval None + */ +__STATIC_INLINE void DDL_SPI_EnableIT_RXNE(SPI_TypeDef *SPIx) +{ + SET_BIT(SPIx->CTRL2, SPI_CTRL2_RXBNEIEN); +} + +/** + * @brief Enable Tx buffer empty interrupt + * @param SPIx SPI Instance + * @retval None + */ +__STATIC_INLINE void DDL_SPI_EnableIT_TXE(SPI_TypeDef *SPIx) +{ + SET_BIT(SPIx->CTRL2, SPI_CTRL2_TXBEIEN); +} + +/** + * @brief Disable error interrupt + * @note This bit controls the generation of an interrupt when an error condition occurs (CRCERR, OVR, MODF in SPI mode, FRE at TI mode). + * @param SPIx SPI Instance + * @retval None + */ +__STATIC_INLINE void DDL_SPI_DisableIT_ERR(SPI_TypeDef *SPIx) +{ + CLEAR_BIT(SPIx->CTRL2, SPI_CTRL2_ERRIEN); +} + +/** + * @brief Disable Rx buffer not empty interrupt + * @param SPIx SPI Instance + * @retval None + */ +__STATIC_INLINE void DDL_SPI_DisableIT_RXNE(SPI_TypeDef *SPIx) +{ + CLEAR_BIT(SPIx->CTRL2, SPI_CTRL2_RXBNEIEN); +} + +/** + * @brief Disable Tx buffer empty interrupt + * @param SPIx SPI Instance + * @retval None + */ +__STATIC_INLINE void DDL_SPI_DisableIT_TXE(SPI_TypeDef *SPIx) +{ + CLEAR_BIT(SPIx->CTRL2, SPI_CTRL2_TXBEIEN); +} + +/** + * @brief Check if error interrupt is enabled + * @param SPIx SPI Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_SPI_IsEnabledIT_ERR(SPI_TypeDef *SPIx) +{ + return ((READ_BIT(SPIx->CTRL2, SPI_CTRL2_ERRIEN) == (SPI_CTRL2_ERRIEN)) ? 1UL : 0UL); +} + +/** + * @brief Check if Rx buffer not empty interrupt is enabled + * @param SPIx SPI Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_SPI_IsEnabledIT_RXNE(SPI_TypeDef *SPIx) +{ + return ((READ_BIT(SPIx->CTRL2, SPI_CTRL2_RXBNEIEN) == (SPI_CTRL2_RXBNEIEN)) ? 1UL : 0UL); +} + +/** + * @brief Check if Tx buffer empty interrupt + * @param SPIx SPI Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_SPI_IsEnabledIT_TXE(SPI_TypeDef *SPIx) +{ + return ((READ_BIT(SPIx->CTRL2, SPI_CTRL2_TXBEIEN) == (SPI_CTRL2_TXBEIEN)) ? 1UL : 0UL); +} + +/** + * @} + */ + +/** @defgroup SPI_DDL_EF_DMA_Management DMA Management + * @{ + */ + +/** + * @brief Enable DMA Rx + * @param SPIx SPI Instance + * @retval None + */ +__STATIC_INLINE void DDL_SPI_EnableDMAReq_RX(SPI_TypeDef *SPIx) +{ + SET_BIT(SPIx->CTRL2, SPI_CTRL2_RXDEN); +} + +/** + * @brief Disable DMA Rx + * @param SPIx SPI Instance + * @retval None + */ +__STATIC_INLINE void DDL_SPI_DisableDMAReq_RX(SPI_TypeDef *SPIx) +{ + CLEAR_BIT(SPIx->CTRL2, SPI_CTRL2_RXDEN); +} + +/** + * @brief Check if DMA Rx is enabled + * @param SPIx SPI Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_SPI_IsEnabledDMAReq_RX(SPI_TypeDef *SPIx) +{ + return ((READ_BIT(SPIx->CTRL2, SPI_CTRL2_RXDEN) == (SPI_CTRL2_RXDEN)) ? 1UL : 0UL); +} + +/** + * @brief Enable DMA Tx + * @param SPIx SPI Instance + * @retval None + */ +__STATIC_INLINE void DDL_SPI_EnableDMAReq_TX(SPI_TypeDef *SPIx) +{ + SET_BIT(SPIx->CTRL2, SPI_CTRL2_TXDEN); +} + +/** + * @brief Disable DMA Tx + * @param SPIx SPI Instance + * @retval None + */ +__STATIC_INLINE void DDL_SPI_DisableDMAReq_TX(SPI_TypeDef *SPIx) +{ + CLEAR_BIT(SPIx->CTRL2, SPI_CTRL2_TXDEN); +} + +/** + * @brief Check if DMA Tx is enabled + * @param SPIx SPI Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_SPI_IsEnabledDMAReq_TX(SPI_TypeDef *SPIx) +{ + return ((READ_BIT(SPIx->CTRL2, SPI_CTRL2_TXDEN) == (SPI_CTRL2_TXDEN)) ? 1UL : 0UL); +} + +/** + * @brief Get the data register address used for DMA transfer + * @param SPIx SPI Instance + * @retval Address of data register + */ +__STATIC_INLINE uint32_t DDL_SPI_DMA_GetRegAddr(SPI_TypeDef *SPIx) +{ + return (uint32_t) &(SPIx->DATA); +} + +/** + * @} + */ + +/** @defgroup SPI_DDL_EF_DATA_Management DATA Management + * @{ + */ + +/** + * @brief Read 8-Bits in the data register + * @param SPIx SPI Instance + * @retval RxData Value between Min_Data=0x00 and Max_Data=0xFF + */ +__STATIC_INLINE uint8_t DDL_SPI_ReceiveData8(SPI_TypeDef *SPIx) +{ + return (*((__IO uint8_t *)&SPIx->DATA)); +} + +/** + * @brief Read 16-Bits in the data register + * @param SPIx SPI Instance + * @retval RxData Value between Min_Data=0x00 and Max_Data=0xFFFF + */ +__STATIC_INLINE uint16_t DDL_SPI_ReceiveData16(SPI_TypeDef *SPIx) +{ + return (uint16_t)(READ_REG(SPIx->DATA)); +} + +/** + * @brief Write 8-Bits in the data register + * @param SPIx SPI Instance + * @param TxData Value between Min_Data=0x00 and Max_Data=0xFF + * @retval None + */ +__STATIC_INLINE void DDL_SPI_TransmitData8(SPI_TypeDef *SPIx, uint8_t TxData) +{ +#if defined (__GNUC__) + __IO uint8_t *spidr = ((__IO uint8_t *)&SPIx->DATA); + *spidr = TxData; +#else + *((__IO uint8_t *)&SPIx->DATA) = TxData; +#endif /* __GNUC__ */ +} + +/** + * @brief Write 16-Bits in the data register + * @param SPIx SPI Instance + * @param TxData Value between Min_Data=0x00 and Max_Data=0xFFFF + * @retval None + */ +__STATIC_INLINE void DDL_SPI_TransmitData16(SPI_TypeDef *SPIx, uint16_t TxData) +{ +#if defined (__GNUC__) + __IO uint16_t *spidr = ((__IO uint16_t *)&SPIx->DATA); + *spidr = TxData; +#else + SPIx->DATA = TxData; +#endif /* __GNUC__ */ +} + +/** + * @} + */ +#if defined(USE_FULL_DDL_DRIVER) +/** @defgroup SPI_DDL_EF_Init Initialization and de-initialization functions + * @{ + */ + +ErrorStatus DDL_SPI_DeInit(SPI_TypeDef *SPIx); +ErrorStatus DDL_SPI_Init(SPI_TypeDef *SPIx, DDL_SPI_InitTypeDef *SPI_InitStruct); +void DDL_SPI_StructInit(DDL_SPI_InitTypeDef *SPI_InitStruct); + +/** + * @} + */ +#endif /* USE_FULL_DDL_DRIVER */ +/** + * @} + */ + +/** + * @} + */ + +/** @defgroup I2S_DDL I2S + * @{ + */ + +/* Private variables ---------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/* Private macros ------------------------------------------------------------*/ + +/* Exported types ------------------------------------------------------------*/ +#if defined(USE_FULL_DDL_DRIVER) +/** @defgroup I2S_DDL_ES_INIT I2S Exported Init structure + * @{ + */ + +/** + * @brief I2S Init structure definition + */ + +typedef struct +{ + uint32_t Mode; /*!< Specifies the I2S operating mode. + This parameter can be a value of @ref I2S_DDL_EC_MODE + + This feature can be modified afterwards using unitary function @ref DDL_I2S_SetTransferMode().*/ + + uint32_t Standard; /*!< Specifies the standard used for the I2S communication. + This parameter can be a value of @ref I2S_DDL_EC_STANDARD + + This feature can be modified afterwards using unitary function @ref DDL_I2S_SetStandard().*/ + + + uint32_t DataFormat; /*!< Specifies the data format for the I2S communication. + This parameter can be a value of @ref I2S_DDL_EC_DATA_FORMAT + + This feature can be modified afterwards using unitary function @ref DDL_I2S_SetDataFormat().*/ + + + uint32_t MCLKOutput; /*!< Specifies whether the I2S MCLK output is enabled or not. + This parameter can be a value of @ref I2S_DDL_EC_MCLK_OUTPUT + + This feature can be modified afterwards using unitary functions @ref DDL_I2S_EnableMasterClock() or @ref DDL_I2S_DisableMasterClock.*/ + + + uint32_t AudioFreq; /*!< Specifies the frequency selected for the I2S communication. + This parameter can be a value of @ref I2S_DDL_EC_AUDIO_FREQ + + Audio Frequency can be modified afterwards using Reference manual formulas to calculate Prescaler Linear, Parity + and unitary functions @ref DDL_I2S_SetPrescalerLinear() and @ref DDL_I2S_SetPrescalerParity() to set it.*/ + + + uint32_t ClockPolarity; /*!< Specifies the idle state of the I2S clock. + This parameter can be a value of @ref I2S_DDL_EC_POLARITY + + This feature can be modified afterwards using unitary function @ref DDL_I2S_SetClockPolarity().*/ + +} DDL_I2S_InitTypeDef; + +/** + * @} + */ +#endif /*USE_FULL_DDL_DRIVER*/ + +/* Exported constants --------------------------------------------------------*/ +/** @defgroup I2S_DDL_Exported_Constants I2S Exported Constants + * @{ + */ + +/** @defgroup I2S_DDL_EC_GET_FLAG Get Flags Defines + * @brief Flags defines which can be used with DDL_I2S_ReadReg function + * @{ + */ +#define DDL_I2S_SR_RXNE DDL_SPI_STS_RXBNEFLG /*!< Rx buffer not empty flag */ +#define DDL_I2S_SR_TXE DDL_SPI_STS_TXBEFLG /*!< Tx buffer empty flag */ +#define DDL_I2S_SR_BSY DDL_SPI_STS_BSYFLG /*!< Busy flag */ +#define DDL_I2S_SR_UDR SPI_STS_UDRFLG /*!< Underrun flag */ +#define DDL_I2S_SR_OVR DDL_SPI_STS_OVRFLG /*!< Overrun flag */ +#define DDL_I2S_SR_FRE DDL_SPI_STS_FFERR /*!< TI mode frame format error flag */ +/** + * @} + */ + +/** @defgroup SPI_DDL_EC_IT IT Defines + * @brief IT defines which can be used with DDL_SPI_ReadReg and DDL_SPI_WriteReg functions + * @{ + */ +#define DDL_I2S_CTRL2_RXNEIE DDL_SPI_CTRL2_RXBNEIEN /*!< Rx buffer not empty interrupt enable */ +#define DDL_I2S_CTRL2_TXEIE DDL_SPI_CTRL2_TXBEIEN /*!< Tx buffer empty interrupt enable */ +#define DDL_I2S_CTRL2_ERRIE DDL_SPI_CTRL2_ERRIEN /*!< Error interrupt enable */ +/** + * @} + */ + +/** @defgroup I2S_DDL_EC_DATA_FORMAT Data format + * @{ + */ +#define DDL_I2S_DATAFORMAT_16B 0x00000000U /*!< Data length 16 bits, Channel length 16bit */ +#define DDL_I2S_DATAFORMAT_16B_EXTENDED (SPI_I2SCFG_CHLEN) /*!< Data length 16 bits, Channel length 32bit */ +#define DDL_I2S_DATAFORMAT_24B (SPI_I2SCFG_CHLEN | SPI_I2SCFG_DATALEN_0) /*!< Data length 24 bits, Channel length 32bit */ +#define DDL_I2S_DATAFORMAT_32B (SPI_I2SCFG_CHLEN | SPI_I2SCFG_DATALEN_1) /*!< Data length 16 bits, Channel length 32bit */ +/** + * @} + */ + +/** @defgroup I2S_DDL_EC_POLARITY Clock Polarity + * @{ + */ +#define DDL_I2S_POLARITY_LOW 0x00000000U /*!< Clock steady state is low level */ +#define DDL_I2S_POLARITY_HIGH (SPI_I2SCFG_CPOL) /*!< Clock steady state is high level */ +/** + * @} + */ + +/** @defgroup I2S_DDL_EC_STANDARD I2s Standard + * @{ + */ +#define DDL_I2S_STANDARD_PHILIPS 0x00000000U /*!< I2S standard philips */ +#define DDL_I2S_STANDARD_MSB (SPI_I2SCFG_I2SSSEL_0) /*!< MSB justified standard (left justified) */ +#define DDL_I2S_STANDARD_LSB (SPI_I2SCFG_I2SSSEL_1) /*!< LSB justified standard (right justified) */ +#define DDL_I2S_STANDARD_PCM_SHORT (SPI_I2SCFG_I2SSSEL_0 | SPI_I2SCFG_I2SSSEL_1) /*!< PCM standard, short frame synchronization */ +#define DDL_I2S_STANDARD_PCM_LONG (SPI_I2SCFG_I2SSSEL_0 | SPI_I2SCFG_I2SSSEL_1 | SPI_I2SCFG_PFSSEL) /*!< PCM standard, long frame synchronization */ +/** + * @} + */ + +/** @defgroup I2S_DDL_EC_MODE Operation Mode + * @{ + */ +#define DDL_I2S_MODE_SLAVE_TX 0x00000000U /*!< Slave Tx configuration */ +#define DDL_I2S_MODE_SLAVE_RX (SPI_I2SCFG_I2SMOD_0) /*!< Slave Rx configuration */ +#define DDL_I2S_MODE_MASTER_TX (SPI_I2SCFG_I2SMOD_1) /*!< Master Tx configuration */ +#define DDL_I2S_MODE_MASTER_RX (SPI_I2SCFG_I2SMOD_0 | SPI_I2SCFG_I2SMOD_1) /*!< Master Rx configuration */ +/** + * @} + */ + +/** @defgroup I2S_DDL_EC_PRESCALER_FACTOR Prescaler Factor + * @{ + */ +#define DDL_I2S_PRESCALER_PARITY_EVEN 0x00000000U /*!< Odd factor: Real divider value is = I2SDIV * 2 */ +#define DDL_I2S_PRESCALER_PARITY_ODD (SPI_I2SPSC_ODDPS >> 8U) /*!< Odd factor: Real divider value is = (I2SDIV * 2)+1 */ +/** + * @} + */ + +#if defined(USE_FULL_DDL_DRIVER) + +/** @defgroup I2S_DDL_EC_MCLK_OUTPUT MCLK Output + * @{ + */ +#define DDL_I2S_MCLK_OUTPUT_DISABLE 0x00000000U /*!< Master clock output is disabled */ +#define DDL_I2S_MCLK_OUTPUT_ENABLE (SPI_I2SPSC_MCOEN) /*!< Master clock output is enabled */ +/** + * @} + */ + +/** @defgroup I2S_DDL_EC_AUDIO_FREQ Audio Frequency + * @{ + */ + +#define DDL_I2S_AUDIOFREQ_192K 192000U /*!< Audio Frequency configuration 192000 Hz */ +#define DDL_I2S_AUDIOFREQ_96K 96000U /*!< Audio Frequency configuration 96000 Hz */ +#define DDL_I2S_AUDIOFREQ_48K 48000U /*!< Audio Frequency configuration 48000 Hz */ +#define DDL_I2S_AUDIOFREQ_44K 44100U /*!< Audio Frequency configuration 44100 Hz */ +#define DDL_I2S_AUDIOFREQ_32K 32000U /*!< Audio Frequency configuration 32000 Hz */ +#define DDL_I2S_AUDIOFREQ_22K 22050U /*!< Audio Frequency configuration 22050 Hz */ +#define DDL_I2S_AUDIOFREQ_16K 16000U /*!< Audio Frequency configuration 16000 Hz */ +#define DDL_I2S_AUDIOFREQ_11K 11025U /*!< Audio Frequency configuration 11025 Hz */ +#define DDL_I2S_AUDIOFREQ_8K 8000U /*!< Audio Frequency configuration 8000 Hz */ +#define DDL_I2S_AUDIOFREQ_DEFAULT 2U /*!< Audio Freq not specified. Register I2SDIV = 2 */ +/** + * @} + */ +#endif /* USE_FULL_DDL_DRIVER */ + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ +/** @defgroup I2S_DDL_Exported_Macros I2S Exported Macros + * @{ + */ + +/** @defgroup I2S_DDL_EM_WRITE_READ Common Write and read registers Macros + * @{ + */ + +/** + * @brief Write a value in I2S register + * @param __INSTANCE__ I2S Instance + * @param __REG__ Register to be written + * @param __VALUE__ Value to be written in the register + * @retval None + */ +#define DDL_I2S_WriteReg(__INSTANCE__, __REG__, __VALUE__) WRITE_REG(__INSTANCE__->__REG__, (__VALUE__)) + +/** + * @brief Read a value in I2S register + * @param __INSTANCE__ I2S Instance + * @param __REG__ Register to be read + * @retval Register value + */ +#define DDL_I2S_ReadReg(__INSTANCE__, __REG__) READ_REG(__INSTANCE__->__REG__) +/** + * @} + */ + +/** + * @} + */ + + +/* Exported functions --------------------------------------------------------*/ + +/** @defgroup I2S_DDL_Exported_Functions I2S Exported Functions + * @{ + */ + +/** @defgroup I2S_DDL_EF_Configuration Configuration + * @{ + */ + +/** + * @brief Select I2S mode and Enable I2S peripheral + * @param SPIx SPI Instance + * @retval None + */ +__STATIC_INLINE void DDL_I2S_Enable(SPI_TypeDef *SPIx) +{ + SET_BIT(SPIx->I2SCFG, SPI_I2SCFG_MODESEL | SPI_I2SCFG_I2SEN); +} + +/** + * @brief Disable I2S peripheral + * @param SPIx SPI Instance + * @retval None + */ +__STATIC_INLINE void DDL_I2S_Disable(SPI_TypeDef *SPIx) +{ + CLEAR_BIT(SPIx->I2SCFG, SPI_I2SCFG_MODESEL | SPI_I2SCFG_I2SEN); +} + +/** + * @brief Check if I2S peripheral is enabled + * @param SPIx SPI Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_I2S_IsEnabled(SPI_TypeDef *SPIx) +{ + return ((READ_BIT(SPIx->I2SCFG, SPI_I2SCFG_I2SEN) == (SPI_I2SCFG_I2SEN)) ? 1UL : 0UL); +} + +/** + * @brief Set I2S data frame length + * @param SPIx SPI Instance + * @param DataFormat This parameter can be one of the following values: + * @arg @ref DDL_I2S_DATAFORMAT_16B + * @arg @ref DDL_I2S_DATAFORMAT_16B_EXTENDED + * @arg @ref DDL_I2S_DATAFORMAT_24B + * @arg @ref DDL_I2S_DATAFORMAT_32B + * @retval None + */ +__STATIC_INLINE void DDL_I2S_SetDataFormat(SPI_TypeDef *SPIx, uint32_t DataFormat) +{ + MODIFY_REG(SPIx->I2SCFG, SPI_I2SCFG_DATALEN | SPI_I2SCFG_CHLEN, DataFormat); +} + +/** + * @brief Get I2S data frame length + * @param SPIx SPI Instance + * @retval Returned value can be one of the following values: + * @arg @ref DDL_I2S_DATAFORMAT_16B + * @arg @ref DDL_I2S_DATAFORMAT_16B_EXTENDED + * @arg @ref DDL_I2S_DATAFORMAT_24B + * @arg @ref DDL_I2S_DATAFORMAT_32B + */ +__STATIC_INLINE uint32_t DDL_I2S_GetDataFormat(SPI_TypeDef *SPIx) +{ + return (uint32_t)(READ_BIT(SPIx->I2SCFG, SPI_I2SCFG_DATALEN | SPI_I2SCFG_CHLEN)); +} + +/** + * @brief Set I2S clock polarity + * @param SPIx SPI Instance + * @param ClockPolarity This parameter can be one of the following values: + * @arg @ref DDL_I2S_POLARITY_LOW + * @arg @ref DDL_I2S_POLARITY_HIGH + * @retval None + */ +__STATIC_INLINE void DDL_I2S_SetClockPolarity(SPI_TypeDef *SPIx, uint32_t ClockPolarity) +{ + SET_BIT(SPIx->I2SCFG, ClockPolarity); +} + +/** + * @brief Get I2S clock polarity + * @param SPIx SPI Instance + * @retval Returned value can be one of the following values: + * @arg @ref DDL_I2S_POLARITY_LOW + * @arg @ref DDL_I2S_POLARITY_HIGH + */ +__STATIC_INLINE uint32_t DDL_I2S_GetClockPolarity(SPI_TypeDef *SPIx) +{ + return (uint32_t)(READ_BIT(SPIx->I2SCFG, SPI_I2SCFG_CPOL)); +} + +/** + * @brief Set I2S standard protocol + * @param SPIx SPI Instance + * @param Standard This parameter can be one of the following values: + * @arg @ref DDL_I2S_STANDARD_PHILIPS + * @arg @ref DDL_I2S_STANDARD_MSB + * @arg @ref DDL_I2S_STANDARD_LSB + * @arg @ref DDL_I2S_STANDARD_PCM_SHORT + * @arg @ref DDL_I2S_STANDARD_PCM_LONG + * @retval None + */ +__STATIC_INLINE void DDL_I2S_SetStandard(SPI_TypeDef *SPIx, uint32_t Standard) +{ + MODIFY_REG(SPIx->I2SCFG, SPI_I2SCFG_I2SSSEL | SPI_I2SCFG_PFSSEL, Standard); +} + +/** + * @brief Get I2S standard protocol + * @param SPIx SPI Instance + * @retval Returned value can be one of the following values: + * @arg @ref DDL_I2S_STANDARD_PHILIPS + * @arg @ref DDL_I2S_STANDARD_MSB + * @arg @ref DDL_I2S_STANDARD_LSB + * @arg @ref DDL_I2S_STANDARD_PCM_SHORT + * @arg @ref DDL_I2S_STANDARD_PCM_LONG + */ +__STATIC_INLINE uint32_t DDL_I2S_GetStandard(SPI_TypeDef *SPIx) +{ + return (uint32_t)(READ_BIT(SPIx->I2SCFG, SPI_I2SCFG_I2SSSEL | SPI_I2SCFG_PFSSEL)); +} + +/** + * @brief Set I2S transfer mode + * @param SPIx SPI Instance + * @param Mode This parameter can be one of the following values: + * @arg @ref DDL_I2S_MODE_SLAVE_TX + * @arg @ref DDL_I2S_MODE_SLAVE_RX + * @arg @ref DDL_I2S_MODE_MASTER_TX + * @arg @ref DDL_I2S_MODE_MASTER_RX + * @retval None + */ +__STATIC_INLINE void DDL_I2S_SetTransferMode(SPI_TypeDef *SPIx, uint32_t Mode) +{ + MODIFY_REG(SPIx->I2SCFG, SPI_I2SCFG_I2SMOD, Mode); +} + +/** + * @brief Get I2S transfer mode + * @param SPIx SPI Instance + * @retval Returned value can be one of the following values: + * @arg @ref DDL_I2S_MODE_SLAVE_TX + * @arg @ref DDL_I2S_MODE_SLAVE_RX + * @arg @ref DDL_I2S_MODE_MASTER_TX + * @arg @ref DDL_I2S_MODE_MASTER_RX + */ +__STATIC_INLINE uint32_t DDL_I2S_GetTransferMode(SPI_TypeDef *SPIx) +{ + return (uint32_t)(READ_BIT(SPIx->I2SCFG, SPI_I2SCFG_I2SMOD)); +} + +/** + * @brief Set I2S linear prescaler + * @param SPIx SPI Instance + * @param PrescalerLinear Value between Min_Data=0x02 and Max_Data=0xFF + * @retval None + */ +__STATIC_INLINE void DDL_I2S_SetPrescalerLinear(SPI_TypeDef *SPIx, uint8_t PrescalerLinear) +{ + MODIFY_REG(SPIx->I2SPSC, SPI_I2SPSC_I2SPSC, PrescalerLinear); +} + +/** + * @brief Get I2S linear prescaler + * @param SPIx SPI Instance + * @retval PrescalerLinear Value between Min_Data=0x02 and Max_Data=0xFF + */ +__STATIC_INLINE uint32_t DDL_I2S_GetPrescalerLinear(SPI_TypeDef *SPIx) +{ + return (uint32_t)(READ_BIT(SPIx->I2SPSC, SPI_I2SPSC_I2SPSC)); +} + +/** + * @brief Set I2S parity prescaler + * @param SPIx SPI Instance + * @param PrescalerParity This parameter can be one of the following values: + * @arg @ref DDL_I2S_PRESCALER_PARITY_EVEN + * @arg @ref DDL_I2S_PRESCALER_PARITY_ODD + * @retval None + */ +__STATIC_INLINE void DDL_I2S_SetPrescalerParity(SPI_TypeDef *SPIx, uint32_t PrescalerParity) +{ + MODIFY_REG(SPIx->I2SPSC, SPI_I2SPSC_ODDPS, PrescalerParity << 8U); +} + +/** + * @brief Get I2S parity prescaler + * @param SPIx SPI Instance + * @retval Returned value can be one of the following values: + * @arg @ref DDL_I2S_PRESCALER_PARITY_EVEN + * @arg @ref DDL_I2S_PRESCALER_PARITY_ODD + */ +__STATIC_INLINE uint32_t DDL_I2S_GetPrescalerParity(SPI_TypeDef *SPIx) +{ + return (uint32_t)(READ_BIT(SPIx->I2SPSC, SPI_I2SPSC_ODDPS) >> 8U); +} + +/** + * @brief Enable the master clock output (Pin MCK) + * @param SPIx SPI Instance + * @retval None + */ +__STATIC_INLINE void DDL_I2S_EnableMasterClock(SPI_TypeDef *SPIx) +{ + SET_BIT(SPIx->I2SPSC, SPI_I2SPSC_MCOEN); +} + +/** + * @brief Disable the master clock output (Pin MCK) + * @param SPIx SPI Instance + * @retval None + */ +__STATIC_INLINE void DDL_I2S_DisableMasterClock(SPI_TypeDef *SPIx) +{ + CLEAR_BIT(SPIx->I2SPSC, SPI_I2SPSC_MCOEN); +} + +/** + * @brief Check if the master clock output (Pin MCK) is enabled + * @param SPIx SPI Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_I2S_IsEnabledMasterClock(SPI_TypeDef *SPIx) +{ + return ((READ_BIT(SPIx->I2SPSC, SPI_I2SPSC_MCOEN) == (SPI_I2SPSC_MCOEN)) ? 1UL : 0UL); +} + +#if defined(SPI_I2SCFG_ASTRTEN) +/** + * @brief Enable asynchronous start + * @param SPIx SPI Instance + * @retval None + */ +__STATIC_INLINE void DDL_I2S_EnableAsyncStart(SPI_TypeDef *SPIx) +{ + SET_BIT(SPIx->I2SCFG, SPI_I2SCFG_ASTRTEN); +} + +/** + * @brief Disable asynchronous start + * @param SPIx SPI Instance + * @retval None + */ +__STATIC_INLINE void DDL_I2S_DisableAsyncStart(SPI_TypeDef *SPIx) +{ + CLEAR_BIT(SPIx->I2SCFG, SPI_I2SCFG_ASTRTEN); +} + +/** + * @brief Check if asynchronous start is enabled + * @param SPIx SPI Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_I2S_IsEnabledAsyncStart(SPI_TypeDef *SPIx) +{ + return ((READ_BIT(SPIx->I2SCFG, SPI_I2SCFG_ASTRTEN) == (SPI_I2SCFG_ASTRTEN)) ? 1UL : 0UL); +} +#endif /* SPI_I2SCFG_ASTRTEN */ + +/** + * @} + */ + +/** @defgroup I2S_DDL_EF_FLAG FLAG Management + * @{ + */ + +/** + * @brief Check if Rx buffer is not empty + * @param SPIx SPI Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_I2S_IsActiveFlag_RXNE(SPI_TypeDef *SPIx) +{ + return DDL_SPI_IsActiveFlag_RXNE(SPIx); +} + +/** + * @brief Check if Tx buffer is empty + * @param SPIx SPI Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_I2S_IsActiveFlag_TXE(SPI_TypeDef *SPIx) +{ + return DDL_SPI_IsActiveFlag_TXE(SPIx); +} + +/** + * @brief Get busy flag + * @param SPIx SPI Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_I2S_IsActiveFlag_BSY(SPI_TypeDef *SPIx) +{ + return DDL_SPI_IsActiveFlag_BSY(SPIx); +} + +/** + * @brief Get overrun error flag + * @param SPIx SPI Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_I2S_IsActiveFlag_OVR(SPI_TypeDef *SPIx) +{ + return DDL_SPI_IsActiveFlag_OVR(SPIx); +} + +/** + * @brief Get underrun error flag + * @param SPIx SPI Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_I2S_IsActiveFlag_UDR(SPI_TypeDef *SPIx) +{ + return ((READ_BIT(SPIx->STS, SPI_STS_UDRFLG) == (SPI_STS_UDRFLG)) ? 1UL : 0UL); +} + +/** + * @brief Get frame format error flag + * @param SPIx SPI Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_I2S_IsActiveFlag_FRE(SPI_TypeDef *SPIx) +{ + return DDL_SPI_IsActiveFlag_FRE(SPIx); +} + +/** + * @brief Get channel side flag. + * @note 0: Channel Left has to be transmitted or has been received\n + * 1: Channel Right has to be transmitted or has been received\n + * It has no significance in PCM mode. + * @param SPIx SPI Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_I2S_IsActiveFlag_CHSIDE(SPI_TypeDef *SPIx) +{ + return ((READ_BIT(SPIx->STS, SPI_STS_SCHDIR) == (SPI_STS_SCHDIR)) ? 1UL : 0UL); +} + +/** + * @brief Clear overrun error flag + * @param SPIx SPI Instance + * @retval None + */ +__STATIC_INLINE void DDL_I2S_ClearFlag_OVR(SPI_TypeDef *SPIx) +{ + DDL_SPI_ClearFlag_OVR(SPIx); +} + +/** + * @brief Clear underrun error flag + * @param SPIx SPI Instance + * @retval None + */ +__STATIC_INLINE void DDL_I2S_ClearFlag_UDR(SPI_TypeDef *SPIx) +{ + __IO uint32_t tmpreg; + tmpreg = SPIx->STS; + (void)tmpreg; +} + +/** + * @brief Clear frame format error flag + * @param SPIx SPI Instance + * @retval None + */ +__STATIC_INLINE void DDL_I2S_ClearFlag_FRE(SPI_TypeDef *SPIx) +{ + DDL_SPI_ClearFlag_FRE(SPIx); +} + +/** + * @} + */ + +/** @defgroup I2S_DDL_EF_IT Interrupt Management + * @{ + */ + +/** + * @brief Enable error IT + * @note This bit controls the generation of an interrupt when an error condition occurs (OVR, UDR and FRE in I2S mode). + * @param SPIx SPI Instance + * @retval None + */ +__STATIC_INLINE void DDL_I2S_EnableIT_ERR(SPI_TypeDef *SPIx) +{ + DDL_SPI_EnableIT_ERR(SPIx); +} + +/** + * @brief Enable Rx buffer not empty IT + * @param SPIx SPI Instance + * @retval None + */ +__STATIC_INLINE void DDL_I2S_EnableIT_RXNE(SPI_TypeDef *SPIx) +{ + DDL_SPI_EnableIT_RXNE(SPIx); +} + +/** + * @brief Enable Tx buffer empty IT + * @param SPIx SPI Instance + * @retval None + */ +__STATIC_INLINE void DDL_I2S_EnableIT_TXE(SPI_TypeDef *SPIx) +{ + DDL_SPI_EnableIT_TXE(SPIx); +} + +/** + * @brief Disable error IT + * @note This bit controls the generation of an interrupt when an error condition occurs (OVR, UDR and FRE in I2S mode). + * @param SPIx SPI Instance + * @retval None + */ +__STATIC_INLINE void DDL_I2S_DisableIT_ERR(SPI_TypeDef *SPIx) +{ + DDL_SPI_DisableIT_ERR(SPIx); +} + +/** + * @brief Disable Rx buffer not empty IT + * @param SPIx SPI Instance + * @retval None + */ +__STATIC_INLINE void DDL_I2S_DisableIT_RXNE(SPI_TypeDef *SPIx) +{ + DDL_SPI_DisableIT_RXNE(SPIx); +} + +/** + * @brief Disable Tx buffer empty IT + * @param SPIx SPI Instance + * @retval None + */ +__STATIC_INLINE void DDL_I2S_DisableIT_TXE(SPI_TypeDef *SPIx) +{ + DDL_SPI_DisableIT_TXE(SPIx); +} + +/** + * @brief Check if ERR IT is enabled + * @param SPIx SPI Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_I2S_IsEnabledIT_ERR(SPI_TypeDef *SPIx) +{ + return DDL_SPI_IsEnabledIT_ERR(SPIx); +} + +/** + * @brief Check if RXNE IT is enabled + * @param SPIx SPI Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_I2S_IsEnabledIT_RXNE(SPI_TypeDef *SPIx) +{ + return DDL_SPI_IsEnabledIT_RXNE(SPIx); +} + +/** + * @brief Check if TXE IT is enabled + * @param SPIx SPI Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_I2S_IsEnabledIT_TXE(SPI_TypeDef *SPIx) +{ + return DDL_SPI_IsEnabledIT_TXE(SPIx); +} + +/** + * @} + */ + +/** @defgroup I2S_DDL_EF_DMA DMA Management + * @{ + */ + +/** + * @brief Enable DMA Rx + * @param SPIx SPI Instance + * @retval None + */ +__STATIC_INLINE void DDL_I2S_EnableDMAReq_RX(SPI_TypeDef *SPIx) +{ + DDL_SPI_EnableDMAReq_RX(SPIx); +} + +/** + * @brief Disable DMA Rx + * @param SPIx SPI Instance + * @retval None + */ +__STATIC_INLINE void DDL_I2S_DisableDMAReq_RX(SPI_TypeDef *SPIx) +{ + DDL_SPI_DisableDMAReq_RX(SPIx); +} + +/** + * @brief Check if DMA Rx is enabled + * @param SPIx SPI Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_I2S_IsEnabledDMAReq_RX(SPI_TypeDef *SPIx) +{ + return DDL_SPI_IsEnabledDMAReq_RX(SPIx); +} + +/** + * @brief Enable DMA Tx + * @param SPIx SPI Instance + * @retval None + */ +__STATIC_INLINE void DDL_I2S_EnableDMAReq_TX(SPI_TypeDef *SPIx) +{ + DDL_SPI_EnableDMAReq_TX(SPIx); +} + +/** + * @brief Disable DMA Tx + * @param SPIx SPI Instance + * @retval None + */ +__STATIC_INLINE void DDL_I2S_DisableDMAReq_TX(SPI_TypeDef *SPIx) +{ + DDL_SPI_DisableDMAReq_TX(SPIx); +} + +/** + * @brief Check if DMA Tx is enabled + * @param SPIx SPI Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_I2S_IsEnabledDMAReq_TX(SPI_TypeDef *SPIx) +{ + return DDL_SPI_IsEnabledDMAReq_TX(SPIx); +} + +/** + * @} + */ + +/** @defgroup I2S_DDL_EF_DATA DATA Management + * @{ + */ + +/** + * @brief Read 16-Bits in data register + * @param SPIx SPI Instance + * @retval RxData Value between Min_Data=0x0000 and Max_Data=0xFFFF + */ +__STATIC_INLINE uint16_t DDL_I2S_ReceiveData16(SPI_TypeDef *SPIx) +{ + return DDL_SPI_ReceiveData16(SPIx); +} + +/** + * @brief Write 16-Bits in data register + * @param SPIx SPI Instance + * @param TxData Value between Min_Data=0x0000 and Max_Data=0xFFFF + * @retval None + */ +__STATIC_INLINE void DDL_I2S_TransmitData16(SPI_TypeDef *SPIx, uint16_t TxData) +{ + DDL_SPI_TransmitData16(SPIx, TxData); +} + +/** + * @} + */ + +#if defined(USE_FULL_DDL_DRIVER) +/** @defgroup I2S_DDL_EF_Init Initialization and de-initialization functions + * @{ + */ + +ErrorStatus DDL_I2S_DeInit(SPI_TypeDef *SPIx); +ErrorStatus DDL_I2S_Init(SPI_TypeDef *SPIx, DDL_I2S_InitTypeDef *I2S_InitStruct); +void DDL_I2S_StructInit(DDL_I2S_InitTypeDef *I2S_InitStruct); +void DDL_I2S_ConfigPrescaler(SPI_TypeDef *SPIx, uint32_t PrescalerLinear, uint32_t PrescalerParity); +#if defined (SPI_I2S_FULLDUPLEX_SUPPORT) +ErrorStatus DDL_I2S_InitFullDuplex(SPI_TypeDef *I2Sxext, DDL_I2S_InitTypeDef *I2S_InitStruct); +#endif /* SPI_I2S_FULLDUPLEX_SUPPORT */ + +/** + * @} + */ +#endif /* USE_FULL_DDL_DRIVER */ + +/** + * @} + */ + +/** + * @} + */ + +#endif /* defined (SPI1) || defined (SPI2) || defined (SPI3) || defined (SPI4) || defined (SPI5) || defined(SPI6) */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* APM32F4xx_DDL_SPI_H */ + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_system.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_system.h new file mode 100644 index 0000000000..fe02bdf929 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_system.h @@ -0,0 +1,931 @@ +/** + * + * @file apm32f4xx_ddl_system.h + * @brief Header file of SYSTEM DDL module. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2017 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + * + @verbatim + ============================================================================== + ##### How to use this driver ##### + ============================================================================== + [..] + The DDL SYSTEM driver contains a set of generic APIs that can be + used by user: + (+) Some of the FLASH features need to be handled in the SYSTEM file. + (+) Access to DBGCMU registers + (+) Access to SYSCFG registers + + @endverbatim + * + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef APM32F4xx_DDL_SYSTEM_H +#define APM32F4xx_DDL_SYSTEM_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx.h" + +/** @addtogroup APM32F4xx_DDL_Driver + * @{ + */ + +#if defined (FLASH) || defined (SYSCFG) || defined (DBGMCU) + +/** @defgroup SYSTEM_DDL SYSTEM + * @{ + */ + +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ + +/* Private constants ---------------------------------------------------------*/ +/** @defgroup SYSTEM_DDL_Private_Constants SYSTEM Private Constants + * @{ + */ + +/** + * @} + */ + +/* Private macros ------------------------------------------------------------*/ + +/* Exported types ------------------------------------------------------------*/ +/* Exported constants --------------------------------------------------------*/ +/** @defgroup SYSTEM_DDL_Exported_Constants SYSTEM Exported Constants + * @{ + */ + +/** @defgroup SYSTEM_DDL_EC_REMAP SYSCFG REMAP +* @{ +*/ +#define DDL_SYSCFG_REMAP_FLASH (uint32_t)0x00000000 /*!< Main Flash memory mapped at 0x00000000 */ +#define DDL_SYSCFG_REMAP_SYSTEMFLASH SYSCFG_MMSEL_MMSEL_0 /*!< System Flash memory mapped at 0x00000000 */ +#if defined(SMC_Bank1) +#define DDL_SYSCFG_REMAP_SMC SYSCFG_MMSEL_MMSEL_1 /*!< SMC(NOR/PSRAM 1 and 2) mapped at 0x00000000 */ +#endif /* SMC_Bank1 */ + +#define DDL_SYSCFG_REMAP_SRAM (SYSCFG_MMSEL_MMSEL_1 | SYSCFG_MMSEL_MMSEL_0) /*!< SRAM1 mapped at 0x00000000 */ + +/** + * @} + */ + +#if defined(SYSCFG_PMCFG_ENETSEL) + /** @defgroup SYSTEM_DDL_EC_PMC SYSCFG PMC +* @{ +*/ +#define DDL_SYSCFG_PMCFG_ETHMII (uint32_t)0x00000000 /*!< ETH Media MII interface */ +#define DDL_SYSCFG_PMCFG_ETHRMII (uint32_t)SYSCFG_PMCFG_ENETSEL /*!< ETH Media RMII interface */ + +/** + * @} + */ +#endif /* SYSCFG_PMCFG_ENETSEL */ + + + +#if defined(SYSCFG_MMSEL_UFB_MODE) +/** @defgroup SYSTEM_DDL_EC_BANKMODE SYSCFG BANK MODE + * @{ + */ +#define DDL_SYSCFG_BANKMODE_BANK1 (uint32_t)0x00000000 /*!< Flash Bank 1 base address mapped at 0x0800 0000 (AXI) and 0x0020 0000 (TCM) + and Flash Bank 2 base address mapped at 0x0810 0000 (AXI) and 0x0030 0000 (TCM)*/ +#define DDL_SYSCFG_BANKMODE_BANK2 SYSCFG_MMSEL_UFB_MODE /*!< Flash Bank 2 base address mapped at 0x0800 0000 (AXI) and 0x0020 0000(TCM) + and Flash Bank 1 base address mapped at 0x0810 0000 (AXI) and 0x0030 0000(TCM) */ +/** + * @} + */ +#endif /* SYSCFG_MMSEL_UFB_MODE */ +/** @defgroup SYSTEM_DDL_EC_I2C_FASTMODEPLUS SYSCFG I2C FASTMODEPLUS + * @{ + */ +#if defined(SYSCFG_CFGR_FMPI2C1_SCL) +#define DDL_SYSCFG_I2C_FASTMODEPLUS_SCL SYSCFG_CFGR_FMPI2C1_SCL /*!< Enable Fast Mode Plus on FMPI2C_SCL pin */ +#define DDL_SYSCFG_I2C_FASTMODEPLUS_SDA SYSCFG_CFGR_FMPI2C1_SDA /*!< Enable Fast Mode Plus on FMPI2C_SDA pin*/ +#endif /* SYSCFG_CFGR_FMPI2C1_SCL */ +/** + * @} + */ + +/** @defgroup SYSTEM_DDL_EC_EINT_PORT SYSCFG EINT PORT + * @{ + */ +#define DDL_SYSCFG_EINT_PORTA (uint32_t)0 /*!< EINT PORT A */ +#define DDL_SYSCFG_EINT_PORTB (uint32_t)1 /*!< EINT PORT B */ +#define DDL_SYSCFG_EINT_PORTC (uint32_t)2 /*!< EINT PORT C */ +#define DDL_SYSCFG_EINT_PORTD (uint32_t)3 /*!< EINT PORT D */ +#define DDL_SYSCFG_EINT_PORTE (uint32_t)4 /*!< EINT PORT E */ +#if defined(GPIOF) +#define DDL_SYSCFG_EINT_PORTF (uint32_t)5 /*!< EINT PORT F */ +#endif /* GPIOF */ +#if defined(GPIOG) +#define DDL_SYSCFG_EINT_PORTG (uint32_t)6 /*!< EINT PORT G */ +#endif /* GPIOG */ +#define DDL_SYSCFG_EINT_PORTH (uint32_t)7 /*!< EINT PORT H */ +#if defined(GPIOI) +#define DDL_SYSCFG_EINT_PORTI (uint32_t)8 /*!< EINT PORT I */ +#endif /* GPIOI */ +#if defined(GPIOJ) +#define DDL_SYSCFG_EINT_PORTJ (uint32_t)9 /*!< EINT PORT J */ +#endif /* GPIOJ */ +#if defined(GPIOK) +#define DDL_SYSCFG_EINT_PORTK (uint32_t)10 /*!< EINT PORT k */ +#endif /* GPIOK */ +/** + * @} + */ + +/** @defgroup SYSTEM_DDL_EC_EINT_LINE SYSCFG EINT LINE + * @{ + */ +#define DDL_SYSCFG_EINT_LINE0 (uint32_t)(0x000FU << 16 | 0) /*!< EINT_POSITION_0 | EINTCFG[0] */ +#define DDL_SYSCFG_EINT_LINE1 (uint32_t)(0x00F0U << 16 | 0) /*!< EINT_POSITION_4 | EINTCFG[0] */ +#define DDL_SYSCFG_EINT_LINE2 (uint32_t)(0x0F00U << 16 | 0) /*!< EINT_POSITION_8 | EINTCFG[0] */ +#define DDL_SYSCFG_EINT_LINE3 (uint32_t)(0xF000U << 16 | 0) /*!< EINT_POSITION_12 | EINTCFG[0] */ +#define DDL_SYSCFG_EINT_LINE4 (uint32_t)(0x000FU << 16 | 1) /*!< EINT_POSITION_0 | EINTCFG[1] */ +#define DDL_SYSCFG_EINT_LINE5 (uint32_t)(0x00F0U << 16 | 1) /*!< EINT_POSITION_4 | EINTCFG[1] */ +#define DDL_SYSCFG_EINT_LINE6 (uint32_t)(0x0F00U << 16 | 1) /*!< EINT_POSITION_8 | EINTCFG[1] */ +#define DDL_SYSCFG_EINT_LINE7 (uint32_t)(0xF000U << 16 | 1) /*!< EINT_POSITION_12 | EINTCFG[1] */ +#define DDL_SYSCFG_EINT_LINE8 (uint32_t)(0x000FU << 16 | 2) /*!< EINT_POSITION_0 | EINTCFG[2] */ +#define DDL_SYSCFG_EINT_LINE9 (uint32_t)(0x00F0U << 16 | 2) /*!< EINT_POSITION_4 | EINTCFG[2] */ +#define DDL_SYSCFG_EINT_LINE10 (uint32_t)(0x0F00U << 16 | 2) /*!< EINT_POSITION_8 | EINTCFG[2] */ +#define DDL_SYSCFG_EINT_LINE11 (uint32_t)(0xF000U << 16 | 2) /*!< EINT_POSITION_12 | EINTCFG[2] */ +#define DDL_SYSCFG_EINT_LINE12 (uint32_t)(0x000FU << 16 | 3) /*!< EINT_POSITION_0 | EINTCFG[3] */ +#define DDL_SYSCFG_EINT_LINE13 (uint32_t)(0x00F0U << 16 | 3) /*!< EINT_POSITION_4 | EINTCFG[3] */ +#define DDL_SYSCFG_EINT_LINE14 (uint32_t)(0x0F00U << 16 | 3) /*!< EINT_POSITION_8 | EINTCFG[3] */ +#define DDL_SYSCFG_EINT_LINE15 (uint32_t)(0xF000U << 16 | 3) /*!< EINT_POSITION_12 | EINTCFG[3] */ +/** + * @} + */ + +/** @defgroup SYSTEM_DDL_EC_TRACE DBGMCU TRACE Pin Assignment + * @{ + */ +#define DDL_DBGMCU_TRACE_NONE 0x00000000U /*!< TRACE pins not assigned (default state) */ +#define DDL_DBGMCU_TRACE_ASYNCH DBGMCU_CFG_TRACE_IOEN /*!< TRACE pin assignment for Asynchronous Mode */ +#define DDL_DBGMCU_TRACE_SYNCH_SIZE1 (DBGMCU_CFG_TRACE_IOEN | DBGMCU_CFG_TRACE_MODE_0) /*!< TRACE pin assignment for Synchronous Mode with a TRACEDATA size of 1 */ +#define DDL_DBGMCU_TRACE_SYNCH_SIZE2 (DBGMCU_CFG_TRACE_IOEN | DBGMCU_CFG_TRACE_MODE_1) /*!< TRACE pin assignment for Synchronous Mode with a TRACEDATA size of 2 */ +#define DDL_DBGMCU_TRACE_SYNCH_SIZE4 (DBGMCU_CFG_TRACE_IOEN | DBGMCU_CFG_TRACE_MODE) /*!< TRACE pin assignment for Synchronous Mode with a TRACEDATA size of 4 */ +/** + * @} + */ + +/** @defgroup SYSTEM_DDL_EC_APB1_GRP1_STOP_IP DBGMCU APB1 GRP1 STOP IP + * @{ + */ +#if defined(DBGMCU_APB1F_TMR2_STS) +#define DDL_DBGMCU_APB1_GRP1_TMR2_STOP DBGMCU_APB1F_TMR2_STS /*!< TMR2 counter stopped when core is halted */ +#endif /* DBGMCU_APB1F_TMR2_STS */ +#if defined(DBGMCU_APB1F_TMR3_STS) +#define DDL_DBGMCU_APB1_GRP1_TMR3_STOP DBGMCU_APB1F_TMR3_STS /*!< TMR3 counter stopped when core is halted */ +#endif /* DBGMCU_APB1F_TMR3_STS */ +#if defined(DBGMCU_APB1F_TMR4_STS) +#define DDL_DBGMCU_APB1_GRP1_TMR4_STOP DBGMCU_APB1F_TMR4_STS /*!< TMR4 counter stopped when core is halted */ +#endif /* DBGMCU_APB1F_TMR4_STS */ +#define DDL_DBGMCU_APB1_GRP1_TMR5_STOP DBGMCU_APB1F_TMR5_STS /*!< TMR5 counter stopped when core is halted */ +#if defined(DBGMCU_APB1F_TMR6_STS) +#define DDL_DBGMCU_APB1_GRP1_TMR6_STOP DBGMCU_APB1F_TMR6_STS /*!< TMR6 counter stopped when core is halted */ +#endif /* DBGMCU_APB1F_TMR6_STS */ +#if defined(DBGMCU_APB1F_TMR7_STS) +#define DDL_DBGMCU_APB1_GRP1_TMR7_STOP DBGMCU_APB1F_TMR7_STS /*!< TMR7 counter stopped when core is halted */ +#endif /* DBGMCU_APB1F_TMR7_STOP */ +#if defined(DBGMCU_APB1F_TMR12_STS) +#define DDL_DBGMCU_APB1_GRP1_TMR12_STOP DBGMCU_APB1F_TMR12_STS /*!< TMR12 counter stopped when core is halted */ +#endif /* DBGMCU_APB1F_TMR12_STS */ +#if defined(DBGMCU_APB1F_TMR13_STS) +#define DDL_DBGMCU_APB1_GRP1_TMR13_STOP DBGMCU_APB1F_TMR13_STS /*!< TMR13 counter stopped when core is halted */ +#endif /* DBGMCU_APB1F_TMR13_STS */ +#if defined(DBGMCU_APB1F_TMR14_STS) +#define DDL_DBGMCU_APB1_GRP1_TMR14_STOP DBGMCU_APB1F_TMR14_STS /*!< TMR14 counter stopped when core is halted */ +#endif /* DBGMCU_APB1F_TMR14_STS */ +#if defined(DBGMCU_APB1F_LPTIM_STOP) +#define DDL_DBGMCU_APB1_GRP1_LPTIM_STOP DBGMCU_APB1F_LPTIM_STOP /*!< LPTIM counter stopped when core is halted */ +#endif /* DBGMCU_APB1F_LPTIM_STOP */ +#define DDL_DBGMCU_APB1_GRP1_RTC_STOP DBGMCU_APB1F_RTC_STS /*!< RTC counter stopped when core is halted */ +#define DDL_DBGMCU_APB1_GRP1_WWDT_STOP DBGMCU_APB1F_WWDT_STS /*!< Debug Window Watchdog stopped when Core is halted */ +#define DDL_DBGMCU_APB1_GRP1_IWDT_STOP DBGMCU_APB1F_IWDT_STS /*!< Debug Independent Watchdog stopped when Core is halted */ +#define DDL_DBGMCU_APB1_GRP1_I2C1_STOP DBGMCU_APB1F_I2C1_SMBUS_TIMEOUT_STS /*!< I2C1 SMBUS timeout mode stopped when Core is halted */ +#define DDL_DBGMCU_APB1_GRP1_I2C2_STOP DBGMCU_APB1F_I2C2_SMBUS_TIMEOUT_STS /*!< I2C2 SMBUS timeout mode stopped when Core is halted */ +#if defined(DBGMCU_APB1F_I2C3_SMBUS_TIMEOUT_STS) +#define DDL_DBGMCU_APB1_GRP1_I2C3_STOP DBGMCU_APB1F_I2C3_SMBUS_TIMEOUT_STS /*!< I2C3 SMBUS timeout mode stopped when Core is halted */ +#endif /* DBGMCU_APB1F_I2C3_SMBUS_TIMEOUT_STS */ +#if defined(DBGMCU_APB1F_I2C4_SMBUS_TIMEOUT) +#define DDL_DBGMCU_APB1_GRP1_I2C4_STOP DBGMCU_APB1F_I2C4_SMBUS_TIMEOUT /*!< I2C4 SMBUS timeout mode stopped when Core is halted */ +#endif /* DBGMCU_APB1F_I2C4_SMBUS_TIMEOUT */ +#if defined(DBGMCU_APB1F_CAN1_STS) +#define DDL_DBGMCU_APB1_GRP1_CAN1_STOP DBGMCU_APB1F_CAN1_STS /*!< CAN1 debug stopped when Core is halted */ +#endif /* DBGMCU_APB1F_CAN1_STS */ +#if defined(DBGMCU_APB1F_CAN2_STS) +#define DDL_DBGMCU_APB1_GRP1_CAN2_STOP DBGMCU_APB1F_CAN2_STS /*!< CAN2 debug stopped when Core is halted */ +#endif /* DBGMCU_APB1F_CAN2_STS */ +#if defined(DBGMCU_APB1F_CAN3_STOP) +#define DDL_DBGMCU_APB1_GRP1_CAN3_STOP DBGMCU_APB1F_CAN3_STOP /*!< CAN3 debug stopped when Core is halted */ +#endif /* DBGMCU_APB1F_CAN3_STOP */ +/** + * @} + */ + +/** @defgroup SYSTEM_DDL_EC_APB2_GRP1_STOP_IP DBGMCU APB2 GRP1 STOP IP + * @{ + */ +#define DDL_DBGMCU_APB2_GRP1_TMR1_STOP DBGMCU_APB2F_TMR1_STS /*!< TMR1 counter stopped when core is halted */ +#if defined(DBGMCU_APB2F_TMR8_STS) +#define DDL_DBGMCU_APB2_GRP1_TMR8_STOP DBGMCU_APB2F_TMR8_STS /*!< TMR8 counter stopped when core is halted */ +#endif /* DBGMCU_APB2F_TMR8_STS */ +#define DDL_DBGMCU_APB2_GRP1_TMR9_STOP DBGMCU_APB2F_TMR9_STS /*!< TMR9 counter stopped when core is halted */ +#if defined(DBGMCU_APB2F_TMR10_STS) +#define DDL_DBGMCU_APB2_GRP1_TMR10_STOP DBGMCU_APB2F_TMR10_STS /*!< TMR10 counter stopped when core is halted */ +#endif /* DBGMCU_APB2F_TMR10_STS */ +#define DDL_DBGMCU_APB2_GRP1_TMR11_STOP DBGMCU_APB2F_TMR11_STS /*!< TMR11 counter stopped when core is halted */ +/** + * @} + */ + +/** @defgroup SYSTEM_DDL_EC_LATENCY FLASH LATENCY + * @{ + */ +#define DDL_FLASH_LATENCY_0 FLASH_ACCTRL_WAITP_0WS /*!< FLASH Zero wait state */ +#define DDL_FLASH_LATENCY_1 FLASH_ACCTRL_WAITP_1WS /*!< FLASH One wait state */ +#define DDL_FLASH_LATENCY_2 FLASH_ACCTRL_WAITP_2WS /*!< FLASH Two wait states */ +#define DDL_FLASH_LATENCY_3 FLASH_ACCTRL_WAITP_3WS /*!< FLASH Three wait states */ +#define DDL_FLASH_LATENCY_4 FLASH_ACCTRL_WAITP_4WS /*!< FLASH Four wait states */ +#define DDL_FLASH_LATENCY_5 FLASH_ACCTRL_WAITP_5WS /*!< FLASH five wait state */ +#define DDL_FLASH_LATENCY_6 FLASH_ACCTRL_WAITP_6WS /*!< FLASH six wait state */ +#define DDL_FLASH_LATENCY_7 FLASH_ACCTRL_WAITP_7WS /*!< FLASH seven wait states */ +#define DDL_FLASH_LATENCY_8 FLASH_ACCTRL_WAITP_8WS /*!< FLASH eight wait states */ +#define DDL_FLASH_LATENCY_9 FLASH_ACCTRL_WAITP_9WS /*!< FLASH nine wait states */ +#define DDL_FLASH_LATENCY_10 FLASH_ACCTRL_WAITP_10WS /*!< FLASH ten wait states */ +#define DDL_FLASH_LATENCY_11 FLASH_ACCTRL_WAITP_11WS /*!< FLASH eleven wait states */ +#define DDL_FLASH_LATENCY_12 FLASH_ACCTRL_WAITP_12WS /*!< FLASH twelve wait states */ +#define DDL_FLASH_LATENCY_13 FLASH_ACCTRL_WAITP_13WS /*!< FLASH thirteen wait states */ +#define DDL_FLASH_LATENCY_14 FLASH_ACCTRL_WAITP_14WS /*!< FLASH fourteen wait states */ +#define DDL_FLASH_LATENCY_15 FLASH_ACCTRL_WAITP_15WS /*!< FLASH fifteen wait states */ +/** + * @} + */ + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ + +/* Exported functions --------------------------------------------------------*/ +/** @defgroup SYSTEM_DDL_Exported_Functions SYSTEM Exported Functions + * @{ + */ + +/** @defgroup SYSTEM_DDL_EF_SYSCFG SYSCFG + * @{ + */ +/** + * @brief Set memory mapping at address 0x00000000 + * @param Memory This parameter can be one of the following values: + * @arg @ref DDL_SYSCFG_REMAP_FLASH + * @arg @ref DDL_SYSCFG_REMAP_SYSTEMFLASH + * @arg @ref DDL_SYSCFG_REMAP_SRAM + * @arg @ref DDL_SYSCFG_REMAP_SMC (*) + * @arg @ref DDL_SYSCFG_REMAP_FMC (*) + * @retval None + */ +__STATIC_INLINE void DDL_SYSCFG_SetRemapMemory(uint32_t Memory) +{ + MODIFY_REG(SYSCFG->MMSEL, SYSCFG_MMSEL_MMSEL, Memory); +} + +/** + * @brief Get memory mapping at address 0x00000000 + * @retval Returned value can be one of the following values: + * @arg @ref DDL_SYSCFG_REMAP_FLASH + * @arg @ref DDL_SYSCFG_REMAP_SYSTEMFLASH + * @arg @ref DDL_SYSCFG_REMAP_SRAM + * @arg @ref DDL_SYSCFG_REMAP_SMC (*) + * @arg @ref DDL_SYSCFG_REMAP_FMC (*) + */ +__STATIC_INLINE uint32_t DDL_SYSCFG_GetRemapMemory(void) +{ + return (uint32_t)(READ_BIT(SYSCFG->MMSEL, SYSCFG_MMSEL_MMSEL)); +} + +/** + * @brief Enables the Compensation cell Power Down + * @note The I/O compensation cell can be used only when the device supply + * voltage ranges from 2.4 to 3.6 V + * @retval None + */ +__STATIC_INLINE void DDL_SYSCFG_EnableCompensationCell(void) +{ + SET_BIT(SYSCFG->CCCTRL, SYSCFG_CCCTRL_CCPD); +} + +/** + * @brief Disables the Compensation cell Power Down + * @note The I/O compensation cell can be used only when the device supply + * voltage ranges from 2.4 to 3.6 V + * @retval None + */ +__STATIC_INLINE void DDL_SYSCFG_DisableCompensationCell(void) +{ + CLEAR_BIT(SYSCFG->CCCTRL, SYSCFG_CCCTRL_CCPD); +} + +/** + * @brief Get Compensation Cell ready Flag + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_SYSCFG_IsActiveFlag_CMPCR(void) +{ + return (READ_BIT(SYSCFG->CCCTRL, SYSCFG_CCCTRL_EDYFLG) == (SYSCFG_CCCTRL_EDYFLG)); +} + +#if defined(SYSCFG_PMCFG_ENETSEL) +/** + * @brief Select Ethernet PHY interface + * @param Interface This parameter can be one of the following values: + * @arg @ref DDL_SYSCFG_PMCFG_ETHMII + * @arg @ref DDL_SYSCFG_PMCFG_ETHRMII + * @retval None + */ +__STATIC_INLINE void DDL_SYSCFG_SetPHYInterface(uint32_t Interface) +{ + MODIFY_REG(SYSCFG->PMCFG, SYSCFG_PMCFG_ENETSEL, Interface); +} + +/** + * @brief Get Ethernet PHY interface + * @retval Returned value can be one of the following values: + * @arg @ref DDL_SYSCFG_PMCFG_ETHMII + * @arg @ref DDL_SYSCFG_PMCFG_ETHRMII + * @retval None + */ +__STATIC_INLINE uint32_t DDL_SYSCFG_GetPHYInterface(void) +{ + return (uint32_t)(READ_BIT(SYSCFG->PMCFG, SYSCFG_PMCFG_ENETSEL)); +} +#endif /* SYSCFG_PMCFG_ENETSEL */ + + + +#if defined(SYSCFG_MMSEL_UFB_MODE) +/** + * @brief Select Flash bank mode (Bank flashed at 0x08000000) + * @param Bank This parameter can be one of the following values: + * @arg @ref DDL_SYSCFG_BANKMODE_BANK1 + * @arg @ref DDL_SYSCFG_BANKMODE_BANK2 + * @retval None + */ +__STATIC_INLINE void DDL_SYSCFG_SetFlashBankMode(uint32_t Bank) +{ + MODIFY_REG(SYSCFG->MMSEL, SYSCFG_MMSEL_UFB_MODE, Bank); +} + +/** + * @brief Get Flash bank mode (Bank flashed at 0x08000000) + * @retval Returned value can be one of the following values: + * @arg @ref DDL_SYSCFG_BANKMODE_BANK1 + * @arg @ref DDL_SYSCFG_BANKMODE_BANK2 + */ +__STATIC_INLINE uint32_t DDL_SYSCFG_GetFlashBankMode(void) +{ + return (uint32_t)(READ_BIT(SYSCFG->MMSEL, SYSCFG_MMSEL_UFB_MODE)); +} +#endif /* SYSCFG_MMSEL_UFB_MODE */ + +#if defined(SYSCFG_CFGR_FMPI2C1_SCL) +/** + * @brief Enable the I2C fast mode plus driving capability. + * @param ConfigFastModePlus This parameter can be a combination of the following values: + * @arg @ref DDL_SYSCFG_I2C_FASTMODEPLUS_SCL + * @arg @ref DDL_SYSCFG_I2C_FASTMODEPLUS_SDA + * (*) value not defined in all devices + * @retval None + */ +__STATIC_INLINE void DDL_SYSCFG_EnableFastModePlus(uint32_t ConfigFastModePlus) +{ + SET_BIT(SYSCFG->CFGR, ConfigFastModePlus); +} + +/** + * @brief Disable the I2C fast mode plus driving capability. + * @param ConfigFastModePlus This parameter can be a combination of the following values: + * @arg @ref DDL_SYSCFG_I2C_FASTMODEPLUS_SCL + * @arg @ref DDL_SYSCFG_I2C_FASTMODEPLUS_SDA + * (*) value not defined in all devices + * @retval None + */ +__STATIC_INLINE void DDL_SYSCFG_DisableFastModePlus(uint32_t ConfigFastModePlus) +{ + CLEAR_BIT(SYSCFG->CFGR, ConfigFastModePlus); +} +#endif /* SYSCFG_CFGR_FMPI2C1_SCL */ + +/** + * @brief Configure source input for the EINT external interrupt. + * @param Port This parameter can be one of the following values: + * @arg @ref DDL_SYSCFG_EINT_PORTA + * @arg @ref DDL_SYSCFG_EINT_PORTB + * @arg @ref DDL_SYSCFG_EINT_PORTC + * @arg @ref DDL_SYSCFG_EINT_PORTD + * @arg @ref DDL_SYSCFG_EINT_PORTE + * @arg @ref DDL_SYSCFG_EINT_PORTF (*) + * @arg @ref DDL_SYSCFG_EINT_PORTG (*) + * @arg @ref DDL_SYSCFG_EINT_PORTH + * + * (*) value not defined in all devices + * @param Line This parameter can be one of the following values: + * @arg @ref DDL_SYSCFG_EINT_LINE0 + * @arg @ref DDL_SYSCFG_EINT_LINE1 + * @arg @ref DDL_SYSCFG_EINT_LINE2 + * @arg @ref DDL_SYSCFG_EINT_LINE3 + * @arg @ref DDL_SYSCFG_EINT_LINE4 + * @arg @ref DDL_SYSCFG_EINT_LINE5 + * @arg @ref DDL_SYSCFG_EINT_LINE6 + * @arg @ref DDL_SYSCFG_EINT_LINE7 + * @arg @ref DDL_SYSCFG_EINT_LINE8 + * @arg @ref DDL_SYSCFG_EINT_LINE9 + * @arg @ref DDL_SYSCFG_EINT_LINE10 + * @arg @ref DDL_SYSCFG_EINT_LINE11 + * @arg @ref DDL_SYSCFG_EINT_LINE12 + * @arg @ref DDL_SYSCFG_EINT_LINE13 + * @arg @ref DDL_SYSCFG_EINT_LINE14 + * @arg @ref DDL_SYSCFG_EINT_LINE15 + * @retval None + */ +__STATIC_INLINE void DDL_SYSCFG_SetEINTSource(uint32_t Port, uint32_t Line) +{ + MODIFY_REG(SYSCFG->EINTCFG[Line & 0xFF], (Line >> 16), Port << POSITION_VAL((Line >> 16))); +} + +/** + * @brief Get the configured defined for specific EINT Line + * @param Line This parameter can be one of the following values: + * @arg @ref DDL_SYSCFG_EINT_LINE0 + * @arg @ref DDL_SYSCFG_EINT_LINE1 + * @arg @ref DDL_SYSCFG_EINT_LINE2 + * @arg @ref DDL_SYSCFG_EINT_LINE3 + * @arg @ref DDL_SYSCFG_EINT_LINE4 + * @arg @ref DDL_SYSCFG_EINT_LINE5 + * @arg @ref DDL_SYSCFG_EINT_LINE6 + * @arg @ref DDL_SYSCFG_EINT_LINE7 + * @arg @ref DDL_SYSCFG_EINT_LINE8 + * @arg @ref DDL_SYSCFG_EINT_LINE9 + * @arg @ref DDL_SYSCFG_EINT_LINE10 + * @arg @ref DDL_SYSCFG_EINT_LINE11 + * @arg @ref DDL_SYSCFG_EINT_LINE12 + * @arg @ref DDL_SYSCFG_EINT_LINE13 + * @arg @ref DDL_SYSCFG_EINT_LINE14 + * @arg @ref DDL_SYSCFG_EINT_LINE15 + * @retval Returned value can be one of the following values: + * @arg @ref DDL_SYSCFG_EINT_PORTA + * @arg @ref DDL_SYSCFG_EINT_PORTB + * @arg @ref DDL_SYSCFG_EINT_PORTC + * @arg @ref DDL_SYSCFG_EINT_PORTD + * @arg @ref DDL_SYSCFG_EINT_PORTE + * @arg @ref DDL_SYSCFG_EINT_PORTF (*) + * @arg @ref DDL_SYSCFG_EINT_PORTG (*) + * @arg @ref DDL_SYSCFG_EINT_PORTH + * (*) value not defined in all devices + */ +__STATIC_INLINE uint32_t DDL_SYSCFG_GetEINTSource(uint32_t Line) +{ + return (uint32_t)(READ_BIT(SYSCFG->EINTCFG[Line & 0xFF], (Line >> 16)) >> POSITION_VAL(Line >> 16)); +} + +/** + * @} + */ + + +/** @defgroup SYSTEM_DDL_EF_DBGMCU DBGMCU + * @{ + */ + +/** + * @brief Return the device identifier + * @note For APM32F405/407xx and APM32F417xx devices, the device ID is 0x413 + * @note For APM32F411xx devices, the device ID is 0x431 + * @retval Values between Min_Data=0x00 and Max_Data=0xFFF + */ +__STATIC_INLINE uint32_t DDL_DBGMCU_GetDeviceID(void) +{ + return (uint32_t)(READ_BIT(DBGMCU->IDCODE, DBGMCU_IDCODE_EQR)); +} + +/** + * @brief Return the device revision identifier + * @note This field indicates the revision of the device. + For example, it is read as RevA -> 0x1000, Cat 2 revZ -> 0x1001, rev1 -> 0x1003, rev2 ->0x1007, revY -> 0x100F for APM32F405/407xx and APM32F417xx devices + For example, it is read as RevA -> 0x0015 for APM32F411xx devices + * @retval Values between Min_Data=0x00 and Max_Data=0xFFFF + */ +__STATIC_INLINE uint32_t DDL_DBGMCU_GetRevisionID(void) +{ + return (uint32_t)(READ_BIT(DBGMCU->IDCODE, DBGMCU_IDCODE_WVR) >> DBGMCU_IDCODE_WVR_Pos); +} + +/** + * @brief Enable the Debug Module during SLEEP mode + * @retval None + */ +__STATIC_INLINE void DDL_DBGMCU_EnableDBGSleepMode(void) +{ + SET_BIT(DBGMCU->CFG, DBGMCU_CFG_SLEEP_CLK_STS); +} + +/** + * @brief Disable the Debug Module during SLEEP mode + * @retval None + */ +__STATIC_INLINE void DDL_DBGMCU_DisableDBGSleepMode(void) +{ + CLEAR_BIT(DBGMCU->CFG, DBGMCU_CFG_SLEEP_CLK_STS); +} + +/** + * @brief Enable the Debug Module during STOP mode + * @retval None + */ +__STATIC_INLINE void DDL_DBGMCU_EnableDBGStopMode(void) +{ + SET_BIT(DBGMCU->CFG, DBGMCU_CFG_STOP_CLK_STS); +} + +/** + * @brief Disable the Debug Module during STOP mode + * @retval None + */ +__STATIC_INLINE void DDL_DBGMCU_DisableDBGStopMode(void) +{ + CLEAR_BIT(DBGMCU->CFG, DBGMCU_CFG_STOP_CLK_STS); +} + +/** + * @brief Enable the Debug Module during STANDBY mode + * @retval None + */ +__STATIC_INLINE void DDL_DBGMCU_EnableDBGStandbyMode(void) +{ + SET_BIT(DBGMCU->CFG, DBGMCU_CFG_STANDBY_CLK_STS); +} + +/** + * @brief Disable the Debug Module during STANDBY mode + * @retval None + */ +__STATIC_INLINE void DDL_DBGMCU_DisableDBGStandbyMode(void) +{ + CLEAR_BIT(DBGMCU->CFG, DBGMCU_CFG_STANDBY_CLK_STS); +} + +/** + * @brief Set Trace pin assignment control + * @param PinAssignment This parameter can be one of the following values: + * @arg @ref DDL_DBGMCU_TRACE_NONE + * @arg @ref DDL_DBGMCU_TRACE_ASYNCH + * @arg @ref DDL_DBGMCU_TRACE_SYNCH_SIZE1 + * @arg @ref DDL_DBGMCU_TRACE_SYNCH_SIZE2 + * @arg @ref DDL_DBGMCU_TRACE_SYNCH_SIZE4 + * @retval None + */ +__STATIC_INLINE void DDL_DBGMCU_SetTracePinAssignment(uint32_t PinAssignment) +{ + MODIFY_REG(DBGMCU->CFG, DBGMCU_CFG_TRACE_IOEN | DBGMCU_CFG_TRACE_MODE, PinAssignment); +} + +/** + * @brief Get Trace pin assignment control + * @retval Returned value can be one of the following values: + * @arg @ref DDL_DBGMCU_TRACE_NONE + * @arg @ref DDL_DBGMCU_TRACE_ASYNCH + * @arg @ref DDL_DBGMCU_TRACE_SYNCH_SIZE1 + * @arg @ref DDL_DBGMCU_TRACE_SYNCH_SIZE2 + * @arg @ref DDL_DBGMCU_TRACE_SYNCH_SIZE4 + */ +__STATIC_INLINE uint32_t DDL_DBGMCU_GetTracePinAssignment(void) +{ + return (uint32_t)(READ_BIT(DBGMCU->CFG, DBGMCU_CFG_TRACE_IOEN | DBGMCU_CFG_TRACE_MODE)); +} + +/** + * @brief Freeze APB1 peripherals (group1 peripherals) + * @param Periphs This parameter can be a combination of the following values: + * @arg @ref DDL_DBGMCU_APB1_GRP1_TMR2_STOP (*) + * @arg @ref DDL_DBGMCU_APB1_GRP1_TMR3_STOP (*) + * @arg @ref DDL_DBGMCU_APB1_GRP1_TMR4_STOP (*) + * @arg @ref DDL_DBGMCU_APB1_GRP1_TMR5_STOP + * @arg @ref DDL_DBGMCU_APB1_GRP1_TMR6_STOP (*) + * @arg @ref DDL_DBGMCU_APB1_GRP1_TMR7_STOP (*) + * @arg @ref DDL_DBGMCU_APB1_GRP1_TMR12_STOP (*) + * @arg @ref DDL_DBGMCU_APB1_GRP1_TMR13_STOP (*) + * @arg @ref DDL_DBGMCU_APB1_GRP1_TMR14_STOP (*) + * @arg @ref DDL_DBGMCU_APB1_GRP1_LPTIM_STOP (*) + * @arg @ref DDL_DBGMCU_APB1_GRP1_RTC_STOP + * @arg @ref DDL_DBGMCU_APB1_GRP1_WWDT_STOP + * @arg @ref DDL_DBGMCU_APB1_GRP1_IWDT_STOP + * @arg @ref DDL_DBGMCU_APB1_GRP1_I2C1_STOP + * @arg @ref DDL_DBGMCU_APB1_GRP1_I2C2_STOP + * @arg @ref DDL_DBGMCU_APB1_GRP1_I2C3_STOP (*) + * @arg @ref DDL_DBGMCU_APB1_GRP1_I2C4_STOP (*) + * @arg @ref DDL_DBGMCU_APB1_GRP1_CAN1_STOP (*) + * @arg @ref DDL_DBGMCU_APB1_GRP1_CAN2_STOP (*) + * @arg @ref DDL_DBGMCU_APB1_GRP1_CAN3_STOP (*) + * + * (*) value not defined in all devices. + * @retval None + */ +__STATIC_INLINE void DDL_DBGMCU_APB1_GRP1_FreezePeriph(uint32_t Periphs) +{ + SET_BIT(DBGMCU->APB1F, Periphs); +} + +/** + * @brief Unfreeze APB1 peripherals (group1 peripherals) + * @param Periphs This parameter can be a combination of the following values: + * @arg @ref DDL_DBGMCU_APB1_GRP1_TMR2_STOP (*) + * @arg @ref DDL_DBGMCU_APB1_GRP1_TMR3_STOP (*) + * @arg @ref DDL_DBGMCU_APB1_GRP1_TMR4_STOP (*) + * @arg @ref DDL_DBGMCU_APB1_GRP1_TMR5_STOP + * @arg @ref DDL_DBGMCU_APB1_GRP1_TMR6_STOP (*) + * @arg @ref DDL_DBGMCU_APB1_GRP1_TMR7_STOP (*) + * @arg @ref DDL_DBGMCU_APB1_GRP1_TMR12_STOP (*) + * @arg @ref DDL_DBGMCU_APB1_GRP1_TMR13_STOP (*) + * @arg @ref DDL_DBGMCU_APB1_GRP1_TMR14_STOP (*) + * @arg @ref DDL_DBGMCU_APB1_GRP1_LPTIM_STOP (*) + * @arg @ref DDL_DBGMCU_APB1_GRP1_RTC_STOP + * @arg @ref DDL_DBGMCU_APB1_GRP1_WWDT_STOP + * @arg @ref DDL_DBGMCU_APB1_GRP1_IWDT_STOP + * @arg @ref DDL_DBGMCU_APB1_GRP1_I2C1_STOP + * @arg @ref DDL_DBGMCU_APB1_GRP1_I2C2_STOP + * @arg @ref DDL_DBGMCU_APB1_GRP1_I2C3_STOP (*) + * @arg @ref DDL_DBGMCU_APB1_GRP1_I2C4_STOP (*) + * @arg @ref DDL_DBGMCU_APB1_GRP1_CAN1_STOP (*) + * @arg @ref DDL_DBGMCU_APB1_GRP1_CAN2_STOP (*) + * @arg @ref DDL_DBGMCU_APB1_GRP1_CAN3_STOP (*) + * + * (*) value not defined in all devices. + * @retval None + */ +__STATIC_INLINE void DDL_DBGMCU_APB1_GRP1_UnFreezePeriph(uint32_t Periphs) +{ + CLEAR_BIT(DBGMCU->APB1F, Periphs); +} + +/** + * @brief Freeze APB2 peripherals + * @param Periphs This parameter can be a combination of the following values: + * @arg @ref DDL_DBGMCU_APB2_GRP1_TMR1_STOP + * @arg @ref DDL_DBGMCU_APB2_GRP1_TMR8_STOP (*) + * @arg @ref DDL_DBGMCU_APB2_GRP1_TMR9_STOP (*) + * @arg @ref DDL_DBGMCU_APB2_GRP1_TMR10_STOP (*) + * @arg @ref DDL_DBGMCU_APB2_GRP1_TMR11_STOP (*) + * + * (*) value not defined in all devices. + * @retval None + */ +__STATIC_INLINE void DDL_DBGMCU_APB2_GRP1_FreezePeriph(uint32_t Periphs) +{ + SET_BIT(DBGMCU->APB2F, Periphs); +} + +/** + * @brief Unfreeze APB2 peripherals + * @param Periphs This parameter can be a combination of the following values: + * @arg @ref DDL_DBGMCU_APB2_GRP1_TMR1_STOP + * @arg @ref DDL_DBGMCU_APB2_GRP1_TMR8_STOP (*) + * @arg @ref DDL_DBGMCU_APB2_GRP1_TMR9_STOP (*) + * @arg @ref DDL_DBGMCU_APB2_GRP1_TMR10_STOP (*) + * @arg @ref DDL_DBGMCU_APB2_GRP1_TMR11_STOP (*) + * + * (*) value not defined in all devices. + * @retval None + */ +__STATIC_INLINE void DDL_DBGMCU_APB2_GRP1_UnFreezePeriph(uint32_t Periphs) +{ + CLEAR_BIT(DBGMCU->APB2F, Periphs); +} +/** + * @} + */ + +/** @defgroup SYSTEM_DDL_EF_FLASH FLASH + * @{ + */ + +/** + * @brief Set FLASH Latency + * @param Latency This parameter can be one of the following values: + * @arg @ref DDL_FLASH_LATENCY_0 + * @arg @ref DDL_FLASH_LATENCY_1 + * @arg @ref DDL_FLASH_LATENCY_2 + * @arg @ref DDL_FLASH_LATENCY_3 + * @arg @ref DDL_FLASH_LATENCY_4 + * @arg @ref DDL_FLASH_LATENCY_5 + * @arg @ref DDL_FLASH_LATENCY_6 + * @arg @ref DDL_FLASH_LATENCY_7 + * @arg @ref DDL_FLASH_LATENCY_8 + * @arg @ref DDL_FLASH_LATENCY_9 + * @arg @ref DDL_FLASH_LATENCY_10 + * @arg @ref DDL_FLASH_LATENCY_11 + * @arg @ref DDL_FLASH_LATENCY_12 + * @arg @ref DDL_FLASH_LATENCY_13 + * @arg @ref DDL_FLASH_LATENCY_14 + * @arg @ref DDL_FLASH_LATENCY_15 + * @retval None + */ +__STATIC_INLINE void DDL_FLASH_SetLatency(uint32_t Latency) +{ + MODIFY_REG(FLASH->ACCTRL, FLASH_ACCTRL_WAITP, Latency); +} + +/** + * @brief Get FLASH Latency + * @retval Returned value can be one of the following values: + * @arg @ref DDL_FLASH_LATENCY_0 + * @arg @ref DDL_FLASH_LATENCY_1 + * @arg @ref DDL_FLASH_LATENCY_2 + * @arg @ref DDL_FLASH_LATENCY_3 + * @arg @ref DDL_FLASH_LATENCY_4 + * @arg @ref DDL_FLASH_LATENCY_5 + * @arg @ref DDL_FLASH_LATENCY_6 + * @arg @ref DDL_FLASH_LATENCY_7 + * @arg @ref DDL_FLASH_LATENCY_8 + * @arg @ref DDL_FLASH_LATENCY_9 + * @arg @ref DDL_FLASH_LATENCY_10 + * @arg @ref DDL_FLASH_LATENCY_11 + * @arg @ref DDL_FLASH_LATENCY_12 + * @arg @ref DDL_FLASH_LATENCY_13 + * @arg @ref DDL_FLASH_LATENCY_14 + * @arg @ref DDL_FLASH_LATENCY_15 + */ +__STATIC_INLINE uint32_t DDL_FLASH_GetLatency(void) +{ + return (uint32_t)(READ_BIT(FLASH->ACCTRL, FLASH_ACCTRL_WAITP)); +} + +/** + * @brief Enable Prefetch + * @retval None + */ +__STATIC_INLINE void DDL_FLASH_EnablePrefetch(void) +{ + SET_BIT(FLASH->ACCTRL, FLASH_ACCTRL_PREFEN); +} + +/** + * @brief Disable Prefetch + * @retval None + */ +__STATIC_INLINE void DDL_FLASH_DisablePrefetch(void) +{ + CLEAR_BIT(FLASH->ACCTRL, FLASH_ACCTRL_PREFEN); +} + +/** + * @brief Check if Prefetch buffer is enabled + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_FLASH_IsPrefetchEnabled(void) +{ + return (READ_BIT(FLASH->ACCTRL, FLASH_ACCTRL_PREFEN) == (FLASH_ACCTRL_PREFEN)); +} + +/** + * @brief Enable Instruction cache + * @retval None + */ +__STATIC_INLINE void DDL_FLASH_EnableInstCache(void) +{ + SET_BIT(FLASH->ACCTRL, FLASH_ACCTRL_ICACHEEN); +} + +/** + * @brief Disable Instruction cache + * @retval None + */ +__STATIC_INLINE void DDL_FLASH_DisableInstCache(void) +{ + CLEAR_BIT(FLASH->ACCTRL, FLASH_ACCTRL_ICACHEEN); +} + +/** + * @brief Enable Data cache + * @retval None + */ +__STATIC_INLINE void DDL_FLASH_EnableDataCache(void) +{ + SET_BIT(FLASH->ACCTRL, FLASH_ACCTRL_DCACHEEN); +} + +/** + * @brief Disable Data cache + * @retval None + */ +__STATIC_INLINE void DDL_FLASH_DisableDataCache(void) +{ + CLEAR_BIT(FLASH->ACCTRL, FLASH_ACCTRL_DCACHEEN); +} + +/** + * @brief Enable Instruction cache reset + * @note bit can be written only when the instruction cache is disabled + * @retval None + */ +__STATIC_INLINE void DDL_FLASH_EnableInstCacheReset(void) +{ + SET_BIT(FLASH->ACCTRL, FLASH_ACCTRL_ICACHERST); +} + +/** + * @brief Disable Instruction cache reset + * @retval None + */ +__STATIC_INLINE void DDL_FLASH_DisableInstCacheReset(void) +{ + CLEAR_BIT(FLASH->ACCTRL, FLASH_ACCTRL_ICACHERST); +} + +/** + * @brief Enable Data cache reset + * @note bit can be written only when the data cache is disabled + * @retval None + */ +__STATIC_INLINE void DDL_FLASH_EnableDataCacheReset(void) +{ + SET_BIT(FLASH->ACCTRL, FLASH_ACCTRL_DCACHERST); +} + +/** + * @brief Disable Data cache reset + * @retval None + */ +__STATIC_INLINE void DDL_FLASH_DisableDataCacheReset(void) +{ + CLEAR_BIT(FLASH->ACCTRL, FLASH_ACCTRL_DCACHERST); +} + + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#endif /* defined (FLASH) || defined (SYSCFG) || defined (DBGMCU) */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* APM32F4xx_DDL_SYSTEM_H */ + + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_tmr.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_tmr.h new file mode 100644 index 0000000000..2039c48ed6 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_tmr.h @@ -0,0 +1,3790 @@ +/** + * + * @file apm32f4xx_ddl_tmr.h + * @brief Header file of TMR DDL module. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef APM32F4xx_DDL_TMR_H +#define APM32F4xx_DDL_TMR_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx.h" + +/** @addtogroup APM32F4xx_DDL_Driver + * @{ + */ + +#if defined (TMR1) || defined (TMR2) || defined (TMR3) || defined (TMR4) || defined (TMR5) || defined (TMR6) || defined (TMR7) || defined (TMR8) || defined (TMR9) || defined (TMR10) || defined (TMR11) || defined (TMR12) || defined (TMR13) || defined (TMR14) + +/** @defgroup TMR_DDL TMR + * @{ + */ + +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/** @defgroup TMR_DDL_Private_Variables TMR Private Variables + * @{ + */ +static const uint8_t OFFSET_TAB_CCMRx[] = +{ + 0x00U, /* 0: TMRx_CH1 */ + 0x00U, /* 1: TMRx_CH1N */ + 0x00U, /* 2: TMRx_CH2 */ + 0x00U, /* 3: TMRx_CH2N */ + 0x04U, /* 4: TMRx_CH3 */ + 0x04U, /* 5: TMRx_CH3N */ + 0x04U /* 6: TMRx_CH4 */ +}; + +static const uint8_t SHIFT_TAB_OCxx[] = +{ + 0U, /* 0: OC1M, OC1FE, OC1PE */ + 0U, /* 1: - NA */ + 8U, /* 2: OC2M, OC2FE, OC2PE */ + 0U, /* 3: - NA */ + 0U, /* 4: OC3M, OC3FE, OC3PE */ + 0U, /* 5: - NA */ + 8U /* 6: OC4M, OC4FE, OC4PE */ +}; + +static const uint8_t SHIFT_TAB_ICxx[] = +{ + 0U, /* 0: CC1S, IC1PSC, IC1F */ + 0U, /* 1: - NA */ + 8U, /* 2: CC2S, IC2PSC, IC2F */ + 0U, /* 3: - NA */ + 0U, /* 4: CC3S, IC3PSC, IC3F */ + 0U, /* 5: - NA */ + 8U /* 6: CC4S, IC4PSC, IC4F */ +}; + +static const uint8_t SHIFT_TAB_CCxP[] = +{ + 0U, /* 0: CC1P */ + 2U, /* 1: CC1NP */ + 4U, /* 2: CC2P */ + 6U, /* 3: CC2NP */ + 8U, /* 4: CC3P */ + 10U, /* 5: CC3NP */ + 12U /* 6: CC4P */ +}; + +static const uint8_t SHIFT_TAB_OISx[] = +{ + 0U, /* 0: OIS1 */ + 1U, /* 1: OIS1N */ + 2U, /* 2: OIS2 */ + 3U, /* 3: OIS2N */ + 4U, /* 4: OIS3 */ + 5U, /* 5: OIS3N */ + 6U /* 6: OIS4 */ +}; +/** + * @} + */ + +/* Private constants ---------------------------------------------------------*/ +/** @defgroup TMR_DDL_Private_Constants TMR Private Constants + * @{ + */ + + +/* Remap mask definitions */ +#define TMRx_OR_RMP_SHIFT 16U +#define TMRx_OR_RMP_MASK 0x0000FFFFU +#define TMR2_OR_RMP_MASK (TMR_OR_RMPSEL << TMRx_OR_RMP_SHIFT) +#define TMR5_OR_RMP_MASK (TMR_OR_TI4_RMPSEL << TMRx_OR_RMP_SHIFT) +#define TMR11_OR_RMP_MASK (TMR_OR_TI1_RMPSEL << TMRx_OR_RMP_SHIFT) + +/* Mask used to set the TDG[x:0] of the DTG bits of the TMRx_BDTR register */ +#define DT_DELAY_1 ((uint8_t)0x7F) +#define DT_DELAY_2 ((uint8_t)0x3F) +#define DT_DELAY_3 ((uint8_t)0x1F) +#define DT_DELAY_4 ((uint8_t)0x1F) + +/* Mask used to set the DTG[7:5] bits of the DTG bits of the TMRx_BDTR register */ +#define DT_RANGE_1 ((uint8_t)0x00) +#define DT_RANGE_2 ((uint8_t)0x80) +#define DT_RANGE_3 ((uint8_t)0xC0) +#define DT_RANGE_4 ((uint8_t)0xE0) + + +/** + * @} + */ + +/* Private macros ------------------------------------------------------------*/ +/** @defgroup TMR_DDL_Private_Macros TMR Private Macros + * @{ + */ +/** @brief Convert channel id into channel index. + * @param __CHANNEL__ This parameter can be one of the following values: + * @arg @ref DDL_TMR_CHANNEL_CH1 + * @arg @ref DDL_TMR_CHANNEL_CH1N + * @arg @ref DDL_TMR_CHANNEL_CH2 + * @arg @ref DDL_TMR_CHANNEL_CH2N + * @arg @ref DDL_TMR_CHANNEL_CH3 + * @arg @ref DDL_TMR_CHANNEL_CH3N + * @arg @ref DDL_TMR_CHANNEL_CH4 + * @retval none + */ +#define TMR_GET_CHANNEL_INDEX( __CHANNEL__) \ + (((__CHANNEL__) == DDL_TMR_CHANNEL_CH1) ? 0U :\ + ((__CHANNEL__) == DDL_TMR_CHANNEL_CH1N) ? 1U :\ + ((__CHANNEL__) == DDL_TMR_CHANNEL_CH2) ? 2U :\ + ((__CHANNEL__) == DDL_TMR_CHANNEL_CH2N) ? 3U :\ + ((__CHANNEL__) == DDL_TMR_CHANNEL_CH3) ? 4U :\ + ((__CHANNEL__) == DDL_TMR_CHANNEL_CH3N) ? 5U : 6U) + +/** @brief Calculate the deadtime sampling period(in ps). + * @param __TMRCLK__ timer input clock frequency (in Hz). + * @param __CKD__ This parameter can be one of the following values: + * @arg @ref DDL_TMR_CLOCKDIVISION_DIV1 + * @arg @ref DDL_TMR_CLOCKDIVISION_DIV2 + * @arg @ref DDL_TMR_CLOCKDIVISION_DIV4 + * @retval none + */ +#define TMR_CALC_DTS(__TMRCLK__, __CKD__) \ + (((__CKD__) == DDL_TMR_CLOCKDIVISION_DIV1) ? ((uint64_t)1000000000000U/(__TMRCLK__)) : \ + ((__CKD__) == DDL_TMR_CLOCKDIVISION_DIV2) ? ((uint64_t)1000000000000U/((__TMRCLK__) >> 1U)) : \ + ((uint64_t)1000000000000U/((__TMRCLK__) >> 2U))) +/** + * @} + */ + + +/* Exported types ------------------------------------------------------------*/ +#if defined(USE_FULL_DDL_DRIVER) +/** @defgroup TMR_DDL_ES_INIT TMR Exported Init structure + * @{ + */ + +/** + * @brief TMR Time Base configuration structure definition. + */ +typedef struct +{ + uint16_t Prescaler; /*!< Specifies the prescaler value used to divide the TMR clock. + This parameter can be a number between Min_Data=0x0000 and Max_Data=0xFFFF. + + This feature can be modified afterwards using unitary function + @ref DDL_TMR_SetPrescaler().*/ + + uint32_t CounterMode; /*!< Specifies the counter mode. + This parameter can be a value of @ref TMR_DDL_EC_COUNTERMODE. + + This feature can be modified afterwards using unitary function + @ref DDL_TMR_SetCounterMode().*/ + + uint32_t Autoreload; /*!< Specifies the auto reload value to be loaded into the active + Auto-Reload Register at the next update event. + This parameter must be a number between Min_Data=0x0000 and Max_Data=0xFFFF. + Some timer instances may support 32 bits counters. In that case this parameter must + be a number between 0x0000 and 0xFFFFFFFF. + + This feature can be modified afterwards using unitary function + @ref DDL_TMR_SetAutoReload().*/ + + uint32_t ClockDivision; /*!< Specifies the clock division. + This parameter can be a value of @ref TMR_DDL_EC_CLOCKDIVISION. + + This feature can be modified afterwards using unitary function + @ref DDL_TMR_SetClockDivision().*/ + + uint32_t RepetitionCounter; /*!< Specifies the repetition counter value. Each time the REPCNT downcounter + reaches zero, an update event is generated and counting restarts + from the REPCNT value (N). + This means in PWM mode that (N+1) corresponds to: + - the number of PWM periods in edge-aligned mode + - the number of half PWM period in center-aligned mode + GP timers: this parameter must be a number between Min_Data = 0x00 and + Max_Data = 0xFF. + Advanced timers: this parameter must be a number between Min_Data = 0x0000 and + Max_Data = 0xFFFF. + + This feature can be modified afterwards using unitary function + @ref DDL_TMR_SetRepetitionCounter().*/ +} DDL_TMR_InitTypeDef; + +/** + * @brief TMR Output Compare configuration structure definition. + */ +typedef struct +{ + uint32_t OCMode; /*!< Specifies the output mode. + This parameter can be a value of @ref TMR_DDL_EC_OCMODE. + + This feature can be modified afterwards using unitary function + @ref DDL_TMR_OC_SetMode().*/ + + uint32_t OCState; /*!< Specifies the TMR Output Compare state. + This parameter can be a value of @ref TMR_DDL_EC_OCSTATE. + + This feature can be modified afterwards using unitary functions + @ref DDL_TMR_CC_EnableChannel() or @ref DDL_TMR_CC_DisableChannel().*/ + + uint32_t OCNState; /*!< Specifies the TMR complementary Output Compare state. + This parameter can be a value of @ref TMR_DDL_EC_OCSTATE. + + This feature can be modified afterwards using unitary functions + @ref DDL_TMR_CC_EnableChannel() or @ref DDL_TMR_CC_DisableChannel().*/ + + uint32_t CompareValue; /*!< Specifies the Compare value to be loaded into the Capture Compare Register. + This parameter can be a number between Min_Data=0x0000 and Max_Data=0xFFFF. + + This feature can be modified afterwards using unitary function + DDL_TMR_OC_SetCompareCHx (x=1..6).*/ + + uint32_t OCPolarity; /*!< Specifies the output polarity. + This parameter can be a value of @ref TMR_DDL_EC_OCPOLARITY. + + This feature can be modified afterwards using unitary function + @ref DDL_TMR_OC_SetPolarity().*/ + + uint32_t OCNPolarity; /*!< Specifies the complementary output polarity. + This parameter can be a value of @ref TMR_DDL_EC_OCPOLARITY. + + This feature can be modified afterwards using unitary function + @ref DDL_TMR_OC_SetPolarity().*/ + + + uint32_t OCIdleState; /*!< Specifies the TMR Output Compare pin state during Idle state. + This parameter can be a value of @ref TMR_DDL_EC_OCIDLESTATE. + + This feature can be modified afterwards using unitary function + @ref DDL_TMR_OC_SetIdleState().*/ + + uint32_t OCNIdleState; /*!< Specifies the TMR Output Compare pin state during Idle state. + This parameter can be a value of @ref TMR_DDL_EC_OCIDLESTATE. + + This feature can be modified afterwards using unitary function + @ref DDL_TMR_OC_SetIdleState().*/ +} DDL_TMR_OC_InitTypeDef; + +/** + * @brief TMR Input Capture configuration structure definition. + */ + +typedef struct +{ + + uint32_t ICPolarity; /*!< Specifies the active edge of the input signal. + This parameter can be a value of @ref TMR_DDL_EC_IC_POLARITY. + + This feature can be modified afterwards using unitary function + @ref DDL_TMR_IC_SetPolarity().*/ + + uint32_t ICActiveInput; /*!< Specifies the input. + This parameter can be a value of @ref TMR_DDL_EC_ACTIVEINPUT. + + This feature can be modified afterwards using unitary function + @ref DDL_TMR_IC_SetActiveInput().*/ + + uint32_t ICPrescaler; /*!< Specifies the Input Capture Prescaler. + This parameter can be a value of @ref TMR_DDL_EC_ICPSC. + + This feature can be modified afterwards using unitary function + @ref DDL_TMR_IC_SetPrescaler().*/ + + uint32_t ICFilter; /*!< Specifies the input capture filter. + This parameter can be a value of @ref TMR_DDL_EC_IC_FILTER. + + This feature can be modified afterwards using unitary function + @ref DDL_TMR_IC_SetFilter().*/ +} DDL_TMR_IC_InitTypeDef; + + +/** + * @brief TMR Encoder interface configuration structure definition. + */ +typedef struct +{ + uint32_t EncoderMode; /*!< Specifies the encoder resolution (x2 or x4). + This parameter can be a value of @ref TMR_DDL_EC_ENCODERMODE. + + This feature can be modified afterwards using unitary function + @ref DDL_TMR_SetEncoderMode().*/ + + uint32_t IC1Polarity; /*!< Specifies the active edge of TI1 input. + This parameter can be a value of @ref TMR_DDL_EC_IC_POLARITY. + + This feature can be modified afterwards using unitary function + @ref DDL_TMR_IC_SetPolarity().*/ + + uint32_t IC1ActiveInput; /*!< Specifies the TI1 input source + This parameter can be a value of @ref TMR_DDL_EC_ACTIVEINPUT. + + This feature can be modified afterwards using unitary function + @ref DDL_TMR_IC_SetActiveInput().*/ + + uint32_t IC1Prescaler; /*!< Specifies the TI1 input prescaler value. + This parameter can be a value of @ref TMR_DDL_EC_ICPSC. + + This feature can be modified afterwards using unitary function + @ref DDL_TMR_IC_SetPrescaler().*/ + + uint32_t IC1Filter; /*!< Specifies the TI1 input filter. + This parameter can be a value of @ref TMR_DDL_EC_IC_FILTER. + + This feature can be modified afterwards using unitary function + @ref DDL_TMR_IC_SetFilter().*/ + + uint32_t IC2Polarity; /*!< Specifies the active edge of TI2 input. + This parameter can be a value of @ref TMR_DDL_EC_IC_POLARITY. + + This feature can be modified afterwards using unitary function + @ref DDL_TMR_IC_SetPolarity().*/ + + uint32_t IC2ActiveInput; /*!< Specifies the TI2 input source + This parameter can be a value of @ref TMR_DDL_EC_ACTIVEINPUT. + + This feature can be modified afterwards using unitary function + @ref DDL_TMR_IC_SetActiveInput().*/ + + uint32_t IC2Prescaler; /*!< Specifies the TI2 input prescaler value. + This parameter can be a value of @ref TMR_DDL_EC_ICPSC. + + This feature can be modified afterwards using unitary function + @ref DDL_TMR_IC_SetPrescaler().*/ + + uint32_t IC2Filter; /*!< Specifies the TI2 input filter. + This parameter can be a value of @ref TMR_DDL_EC_IC_FILTER. + + This feature can be modified afterwards using unitary function + @ref DDL_TMR_IC_SetFilter().*/ + +} DDL_TMR_ENCODER_InitTypeDef; + +/** + * @brief TMR Hall sensor interface configuration structure definition. + */ +typedef struct +{ + + uint32_t IC1Polarity; /*!< Specifies the active edge of TI1 input. + This parameter can be a value of @ref TMR_DDL_EC_IC_POLARITY. + + This feature can be modified afterwards using unitary function + @ref DDL_TMR_IC_SetPolarity().*/ + + uint32_t IC1Prescaler; /*!< Specifies the TI1 input prescaler value. + Prescaler must be set to get a maximum counter period longer than the + time interval between 2 consecutive changes on the Hall inputs. + This parameter can be a value of @ref TMR_DDL_EC_ICPSC. + + This feature can be modified afterwards using unitary function + @ref DDL_TMR_IC_SetPrescaler().*/ + + uint32_t IC1Filter; /*!< Specifies the TI1 input filter. + This parameter can be a value of + @ref TMR_DDL_EC_IC_FILTER. + + This feature can be modified afterwards using unitary function + @ref DDL_TMR_IC_SetFilter().*/ + + uint32_t CommutationDelay; /*!< Specifies the compare value to be loaded into the Capture Compare Register. + A positive pulse (TRGO event) is generated with a programmable delay every time + a change occurs on the Hall inputs. + This parameter can be a number between Min_Data = 0x0000 and Max_Data = 0xFFFF. + + This feature can be modified afterwards using unitary function + @ref DDL_TMR_OC_SetCompareCH2().*/ +} DDL_TMR_HALLSENSOR_InitTypeDef; + +/** + * @brief BDTR (Break and Dead Time) structure definition + */ +typedef struct +{ + uint32_t OSSRState; /*!< Specifies the Off-State selection used in Run mode. + This parameter can be a value of @ref TMR_DDL_EC_OSSR + + This feature can be modified afterwards using unitary function + @ref DDL_TMR_SetOffStates() + + @note This bit-field cannot be modified as long as LOCK level 2 has been + programmed. */ + + uint32_t OSSIState; /*!< Specifies the Off-State used in Idle state. + This parameter can be a value of @ref TMR_DDL_EC_OSSI + + This feature can be modified afterwards using unitary function + @ref DDL_TMR_SetOffStates() + + @note This bit-field cannot be modified as long as LOCK level 2 has been + programmed. */ + + uint32_t LockLevel; /*!< Specifies the LOCK level parameters. + This parameter can be a value of @ref TMR_DDL_EC_LOCKLEVEL + + @note The LOCK bits can be written only once after the reset. Once the TMRx_BDTR + register has been written, their content is frozen until the next reset.*/ + + uint8_t DeadTime; /*!< Specifies the delay time between the switching-off and the + switching-on of the outputs. + This parameter can be a number between Min_Data = 0x00 and Max_Data = 0xFF. + + This feature can be modified afterwards using unitary function + @ref DDL_TMR_OC_SetDeadTime() + + @note This bit-field can not be modified as long as LOCK level 1, 2 or 3 has been + programmed. */ + + uint16_t BreakState; /*!< Specifies whether the TMR Break input is enabled or not. + This parameter can be a value of @ref TMR_DDL_EC_BREAK_ENABLE + + This feature can be modified afterwards using unitary functions + @ref DDL_TMR_EnableBRK() or @ref DDL_TMR_DisableBRK() + + @note This bit-field can not be modified as long as LOCK level 1 has been + programmed. */ + + uint32_t BreakPolarity; /*!< Specifies the TMR Break Input pin polarity. + This parameter can be a value of @ref TMR_DDL_EC_BREAK_POLARITY + + This feature can be modified afterwards using unitary function + @ref DDL_TMR_ConfigBRK() + + @note This bit-field can not be modified as long as LOCK level 1 has been + programmed. */ + + uint32_t AutomaticOutput; /*!< Specifies whether the TMR Automatic Output feature is enabled or not. + This parameter can be a value of @ref TMR_DDL_EC_AUTOMATICOUTPUT_ENABLE + + This feature can be modified afterwards using unitary functions + @ref DDL_TMR_EnableAutomaticOutput() or @ref DDL_TMR_DisableAutomaticOutput() + + @note This bit-field can not be modified as long as LOCK level 1 has been + programmed. */ +} DDL_TMR_BDT_InitTypeDef; + +/** + * @} + */ +#endif /* USE_FULL_DDL_DRIVER */ + +/* Exported constants --------------------------------------------------------*/ +/** @defgroup TMR_DDL_Exported_Constants TMR Exported Constants + * @{ + */ + +/** @defgroup TMR_DDL_EC_GET_FLAG Get Flags Defines + * @brief Flags defines which can be used with DDL_TMR_ReadReg function. + * @{ + */ +#define DDL_TMR_STS_UIFLG TMR_STS_UIFLG /*!< Update interrupt flag */ +#define DDL_TMR_STS_CC1IFLG TMR_STS_CC1IFLG /*!< Capture/compare 1 interrupt flag */ +#define DDL_TMR_STS_CC2IFLG TMR_STS_CC2IFLG /*!< Capture/compare 2 interrupt flag */ +#define DDL_TMR_STS_CC3IFLG TMR_STS_CC3IFLG /*!< Capture/compare 3 interrupt flag */ +#define DDL_TMR_STS_CC4IFLG TMR_STS_CC4IFLG /*!< Capture/compare 4 interrupt flag */ +#define DDL_TMR_STS_COMIFLG TMR_STS_COMIFLG /*!< COM interrupt flag */ +#define DDL_TMR_STS_TRGIFLG TMR_STS_TRGIFLG /*!< Trigger interrupt flag */ +#define DDL_TMR_STS_BRKIFLG TMR_STS_BRKIFLG /*!< Break interrupt flag */ +#define DDL_TMR_STS_CC1RCFLG TMR_STS_CC1RCFLG /*!< Capture/Compare 1 overcapture flag */ +#define DDL_TMR_STS_CC2RCFLG TMR_STS_CC2RCFLG /*!< Capture/Compare 2 overcapture flag */ +#define DDL_TMR_STS_CC3RCFLG TMR_STS_CC3RCFLG /*!< Capture/Compare 3 overcapture flag */ +#define DDL_TMR_STS_CC4RCFLG TMR_STS_CC4RCFLG /*!< Capture/Compare 4 overcapture flag */ +/** + * @} + */ + +#if defined(USE_FULL_DDL_DRIVER) +/** @defgroup TMR_DDL_EC_BREAK_ENABLE Break Enable + * @{ + */ +#define DDL_TMR_BREAK_DISABLE 0x00000000U /*!< Break function disabled */ +#define DDL_TMR_BREAK_ENABLE TMR_BDT_BRKEN /*!< Break function enabled */ +/** + * @} + */ + +/** @defgroup TMR_DDL_EC_AUTOMATICOUTPUT_ENABLE Automatic output enable + * @{ + */ +#define DDL_TMR_AUTOMATICOUTPUT_DISABLE 0x00000000U /*!< MOE can be set only by software */ +#define DDL_TMR_AUTOMATICOUTPUT_ENABLE TMR_BDT_AOEN /*!< MOE can be set by software or automatically at the next update event */ +/** + * @} + */ +#endif /* USE_FULL_DDL_DRIVER */ + +/** @defgroup TMR_DDL_EC_IT IT Defines + * @brief IT defines which can be used with DDL_TMR_ReadReg and DDL_TMR_WriteReg functions. + * @{ + */ +#define DDL_TMR_DIEN_UIEN TMR_DIEN_UIEN /*!< Update interrupt enable */ +#define DDL_TMR_DIEN_CC1IEN TMR_DIEN_CC1IEN /*!< Capture/compare 1 interrupt enable */ +#define DDL_TMR_DIEN_CC2IEN TMR_DIEN_CC2IEN /*!< Capture/compare 2 interrupt enable */ +#define DDL_TMR_DIEN_CC3IEN TMR_DIEN_CC3IEN /*!< Capture/compare 3 interrupt enable */ +#define DDL_TMR_DIEN_CC4IEN TMR_DIEN_CC4IEN /*!< Capture/compare 4 interrupt enable */ +#define DDL_TMR_DIEN_COMIEN TMR_DIEN_COMIEN /*!< COM interrupt enable */ +#define DDL_TMR_DIEN_TRGIEN TMR_DIEN_TRGIEN /*!< Trigger interrupt enable */ +#define DDL_TMR_DIEN_BRKIEN TMR_DIEN_BRKIEN /*!< Break interrupt enable */ +/** + * @} + */ + +/** @defgroup TMR_DDL_EC_UPDATESOURCE Update Source + * @{ + */ +#define DDL_TMR_UPDATESOURCE_REGULAR 0x00000000U /*!< Counter overflow/underflow, Setting the UG bit or Update generation through the slave mode controller generates an update request */ +#define DDL_TMR_UPDATESOURCE_COUNTER TMR_CTRL1_URSSEL /*!< Only counter overflow/underflow generates an update request */ +/** + * @} + */ + +/** @defgroup TMR_DDL_EC_ONEPULSEMODE One Pulse Mode + * @{ + */ +#define DDL_TMR_ONEPULSEMODE_SINGLE TMR_CTRL1_SPMEN /*!< Counter stops counting at the next update event */ +#define DDL_TMR_ONEPULSEMODE_REPETITIVE 0x00000000U /*!< Counter is not stopped at update event */ +/** + * @} + */ + +/** @defgroup TMR_DDL_EC_COUNTERMODE Counter Mode + * @{ + */ +#define DDL_TMR_COUNTERMODE_UP 0x00000000U /*!TMRx_CCRy else active.*/ +#define DDL_TMR_OCMODE_PWM2 (TMR_CCM1_OC1MOD_2 | TMR_CCM1_OC1MOD_1 | TMR_CCM1_OC1MOD_0) /*!TMRx_CCRy else inactive*/ +/** + * @} + */ + +/** @defgroup TMR_DDL_EC_OCPOLARITY Output Configuration Polarity + * @{ + */ +#define DDL_TMR_OCPOLARITY_HIGH 0x00000000U /*!< OCxactive high*/ +#define DDL_TMR_OCPOLARITY_LOW TMR_CCEN_CC1POL /*!< OCxactive low*/ +/** + * @} + */ + +/** @defgroup TMR_DDL_EC_OCIDLESTATE Output Configuration Idle State + * @{ + */ +#define DDL_TMR_OCIDLESTATE_LOW 0x00000000U /*!__REG__, (__VALUE__)) + +/** + * @brief Read a value in TMR register. + * @param __INSTANCE__ TMR Instance + * @param __REG__ Register to be read + * @retval Register value + */ +#define DDL_TMR_ReadReg(__INSTANCE__, __REG__) READ_REG((__INSTANCE__)->__REG__) +/** + * @} + */ + +/** @defgroup TMR_DDL_EM_Exported_Macros Exported_Macros + * @{ + */ + +/** + * @brief HELPER macro calculating DTG[0:7] in the TMRx_BDTR register to achieve the requested dead time duration. + * @note ex: @ref __DDL_TMR_CALC_DEADTMRE (80000000, @ref DDL_TMR_GetClockDivision (), 120); + * @param __TMRCLK__ timer input clock frequency (in Hz) + * @param __CKD__ This parameter can be one of the following values: + * @arg @ref DDL_TMR_CLOCKDIVISION_DIV1 + * @arg @ref DDL_TMR_CLOCKDIVISION_DIV2 + * @arg @ref DDL_TMR_CLOCKDIVISION_DIV4 + * @param __DT__ deadtime duration (in ns) + * @retval DTG[0:7] + */ +#define __DDL_TMR_CALC_DEADTMRE(__TMRCLK__, __CKD__, __DT__) \ + ( (((uint64_t)((__DT__)*1000U)) < ((DT_DELAY_1+1U) * TMR_CALC_DTS((__TMRCLK__), (__CKD__)))) ? \ + (uint8_t)(((uint64_t)((__DT__)*1000U) / TMR_CALC_DTS((__TMRCLK__), (__CKD__))) & DT_DELAY_1) : \ + (((uint64_t)((__DT__)*1000U)) < ((64U + (DT_DELAY_2+1U)) * 2U * TMR_CALC_DTS((__TMRCLK__), (__CKD__)))) ? \ + (uint8_t)(DT_RANGE_2 | ((uint8_t)((uint8_t)((((uint64_t)((__DT__)*1000U))/ TMR_CALC_DTS((__TMRCLK__), \ + (__CKD__))) >> 1U) - (uint8_t) 64) & DT_DELAY_2)) :\ + (((uint64_t)((__DT__)*1000U)) < ((32U + (DT_DELAY_3+1U)) * 8U * TMR_CALC_DTS((__TMRCLK__), (__CKD__)))) ? \ + (uint8_t)(DT_RANGE_3 | ((uint8_t)((uint8_t)(((((uint64_t)(__DT__)*1000U))/ TMR_CALC_DTS((__TMRCLK__), \ + (__CKD__))) >> 3U) - (uint8_t) 32) & DT_DELAY_3)) :\ + (((uint64_t)((__DT__)*1000U)) < ((32U + (DT_DELAY_4+1U)) * 16U * TMR_CALC_DTS((__TMRCLK__), (__CKD__)))) ? \ + (uint8_t)(DT_RANGE_4 | ((uint8_t)((uint8_t)(((((uint64_t)(__DT__)*1000U))/ TMR_CALC_DTS((__TMRCLK__), \ + (__CKD__))) >> 4U) - (uint8_t) 32) & DT_DELAY_4)) :\ + 0U) + +/** + * @brief HELPER macro calculating the prescaler value to achieve the required counter clock frequency. + * @note ex: @ref __DDL_TMR_CALC_PSC (80000000, 1000000); + * @param __TMRCLK__ timer input clock frequency (in Hz) + * @param __CNTCLK__ counter clock frequency (in Hz) + * @retval Prescaler value (between Min_Data=0 and Max_Data=65535) + */ +#define __DDL_TMR_CALC_PSC(__TMRCLK__, __CNTCLK__) \ + (((__TMRCLK__) >= (__CNTCLK__)) ? (uint32_t)((((__TMRCLK__) + (__CNTCLK__)/2U)/(__CNTCLK__)) - 1U) : 0U) + +/** + * @brief HELPER macro calculating the auto-reload value to achieve the required output signal frequency. + * @note ex: @ref __DDL_TMR_CALC_ARR (1000000, @ref DDL_TMR_GetPrescaler (), 10000); + * @param __TMRCLK__ timer input clock frequency (in Hz) + * @param __PSC__ prescaler + * @param __FREQ__ output signal frequency (in Hz) + * @retval Auto-reload value (between Min_Data=0 and Max_Data=65535) + */ +#define __DDL_TMR_CALC_ARR(__TMRCLK__, __PSC__, __FREQ__) \ + ((((__TMRCLK__)/((__PSC__) + 1U)) >= (__FREQ__)) ? (((__TMRCLK__)/((__FREQ__) * ((__PSC__) + 1U))) - 1U) : 0U) + +/** + * @brief HELPER macro calculating the compare value required to achieve the required timer output compare + * active/inactive delay. + * @note ex: @ref __DDL_TMR_CALC_DELAY (1000000, @ref DDL_TMR_GetPrescaler (), 10); + * @param __TMRCLK__ timer input clock frequency (in Hz) + * @param __PSC__ prescaler + * @param __DELAY__ timer output compare active/inactive delay (in us) + * @retval Compare value (between Min_Data=0 and Max_Data=65535) + */ +#define __DDL_TMR_CALC_DELAY(__TMRCLK__, __PSC__, __DELAY__) \ + ((uint32_t)(((uint64_t)(__TMRCLK__) * (uint64_t)(__DELAY__)) \ + / ((uint64_t)1000000U * (uint64_t)((__PSC__) + 1U)))) + +/** + * @brief HELPER macro calculating the auto-reload value to achieve the required pulse duration + * (when the timer operates in one pulse mode). + * @note ex: @ref __DDL_TMR_CALC_PULSE (1000000, @ref DDL_TMR_GetPrescaler (), 10, 20); + * @param __TMRCLK__ timer input clock frequency (in Hz) + * @param __PSC__ prescaler + * @param __DELAY__ timer output compare active/inactive delay (in us) + * @param __PULSE__ pulse duration (in us) + * @retval Auto-reload value (between Min_Data=0 and Max_Data=65535) + */ +#define __DDL_TMR_CALC_PULSE(__TMRCLK__, __PSC__, __DELAY__, __PULSE__) \ + ((uint32_t)(__DDL_TMR_CALC_DELAY((__TMRCLK__), (__PSC__), (__PULSE__)) \ + + __DDL_TMR_CALC_DELAY((__TMRCLK__), (__PSC__), (__DELAY__)))) + +/** + * @brief HELPER macro retrieving the ratio of the input capture prescaler + * @note ex: @ref __DDL_TMR_GET_ICPSC_RATIO (@ref DDL_TMR_IC_GetPrescaler ()); + * @param __ICPSC__ This parameter can be one of the following values: + * @arg @ref DDL_TMR_ICPSC_DIV1 + * @arg @ref DDL_TMR_ICPSC_DIV2 + * @arg @ref DDL_TMR_ICPSC_DIV4 + * @arg @ref DDL_TMR_ICPSC_DIV8 + * @retval Input capture prescaler ratio (1, 2, 4 or 8) + */ +#define __DDL_TMR_GET_ICPSC_RATIO(__ICPSC__) \ + ((uint32_t)(0x01U << (((__ICPSC__) >> 16U) >> TMR_CCM1_IC1PSC_Pos))) + + +/** + * @} + */ + + +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +/** @defgroup TMR_DDL_Exported_Functions TMR Exported Functions + * @{ + */ + +/** @defgroup TMR_DDL_EF_Time_Base Time Base configuration + * @{ + */ +/** + * @brief Enable timer counter. + * @param TMRx Timer instance + * @retval None + */ +__STATIC_INLINE void DDL_TMR_EnableCounter(TMR_TypeDef *TMRx) +{ + SET_BIT(TMRx->CTRL1, TMR_CTRL1_CNTEN); +} + +/** + * @brief Disable timer counter. + * @param TMRx Timer instance + * @retval None + */ +__STATIC_INLINE void DDL_TMR_DisableCounter(TMR_TypeDef *TMRx) +{ + CLEAR_BIT(TMRx->CTRL1, TMR_CTRL1_CNTEN); +} + +/** + * @brief Indicates whether the timer counter is enabled. + * @param TMRx Timer instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_TMR_IsEnabledCounter(TMR_TypeDef *TMRx) +{ + return ((READ_BIT(TMRx->CTRL1, TMR_CTRL1_CNTEN) == (TMR_CTRL1_CNTEN)) ? 1UL : 0UL); +} + +/** + * @brief Enable update event generation. + * @param TMRx Timer instance + * @retval None + */ +__STATIC_INLINE void DDL_TMR_EnableUpdateEvent(TMR_TypeDef *TMRx) +{ + CLEAR_BIT(TMRx->CTRL1, TMR_CTRL1_UD); +} + +/** + * @brief Disable update event generation. + * @param TMRx Timer instance + * @retval None + */ +__STATIC_INLINE void DDL_TMR_DisableUpdateEvent(TMR_TypeDef *TMRx) +{ + SET_BIT(TMRx->CTRL1, TMR_CTRL1_UD); +} + +/** + * @brief Indicates whether update event generation is enabled. + * @param TMRx Timer instance + * @retval Inverted state of bit (0 or 1). + */ +__STATIC_INLINE uint32_t DDL_TMR_IsEnabledUpdateEvent(TMR_TypeDef *TMRx) +{ + return ((READ_BIT(TMRx->CTRL1, TMR_CTRL1_UD) == (uint32_t)RESET) ? 1UL : 0UL); +} + +/** + * @brief Set update event source + * @note Update event source set to DDL_TMR_UPDATESOURCE_REGULAR: any of the following events + * generate an update interrupt or DMA request if enabled: + * - Counter overflow/underflow + * - Setting the UG bit + * - Update generation through the slave mode controller + * @note Update event source set to DDL_TMR_UPDATESOURCE_COUNTER: only counter + * overflow/underflow generates an update interrupt or DMA request if enabled. + * @param TMRx Timer instance + * @param UpdateSource This parameter can be one of the following values: + * @arg @ref DDL_TMR_UPDATESOURCE_REGULAR + * @arg @ref DDL_TMR_UPDATESOURCE_COUNTER + * @retval None + */ +__STATIC_INLINE void DDL_TMR_SetUpdateSource(TMR_TypeDef *TMRx, uint32_t UpdateSource) +{ + MODIFY_REG(TMRx->CTRL1, TMR_CTRL1_URSSEL, UpdateSource); +} + +/** + * @brief Get actual event update source + * @param TMRx Timer instance + * @retval Returned value can be one of the following values: + * @arg @ref DDL_TMR_UPDATESOURCE_REGULAR + * @arg @ref DDL_TMR_UPDATESOURCE_COUNTER + */ +__STATIC_INLINE uint32_t DDL_TMR_GetUpdateSource(TMR_TypeDef *TMRx) +{ + return (uint32_t)(READ_BIT(TMRx->CTRL1, TMR_CTRL1_URSSEL)); +} + +/** + * @brief Set one pulse mode (one shot v.s. repetitive). + * @param TMRx Timer instance + * @param OnePulseMode This parameter can be one of the following values: + * @arg @ref DDL_TMR_ONEPULSEMODE_SINGLE + * @arg @ref DDL_TMR_ONEPULSEMODE_REPETITIVE + * @retval None + */ +__STATIC_INLINE void DDL_TMR_SetOnePulseMode(TMR_TypeDef *TMRx, uint32_t OnePulseMode) +{ + MODIFY_REG(TMRx->CTRL1, TMR_CTRL1_SPMEN, OnePulseMode); +} + +/** + * @brief Get actual one pulse mode. + * @param TMRx Timer instance + * @retval Returned value can be one of the following values: + * @arg @ref DDL_TMR_ONEPULSEMODE_SINGLE + * @arg @ref DDL_TMR_ONEPULSEMODE_REPETITIVE + */ +__STATIC_INLINE uint32_t DDL_TMR_GetOnePulseMode(TMR_TypeDef *TMRx) +{ + return (uint32_t)(READ_BIT(TMRx->CTRL1, TMR_CTRL1_SPMEN)); +} + +/** + * @brief Set the timer counter counting mode. + * @note Macro IS_TMR_COUNTER_MODE_SELECT_INSTANCE(TMRx) can be used to + * check whether or not the counter mode selection feature is supported + * by a timer instance. + * @note Switching from Center Aligned counter mode to Edge counter mode (or reverse) + * requires a timer reset to avoid unexpected direction + * due to DIR bit readonly in center aligned mode. + * @param TMRx Timer instance + * @param CounterMode This parameter can be one of the following values: + * @arg @ref DDL_TMR_COUNTERMODE_UP + * @arg @ref DDL_TMR_COUNTERMODE_DOWN + * @arg @ref DDL_TMR_COUNTERMODE_CENTER_UP + * @arg @ref DDL_TMR_COUNTERMODE_CENTER_DOWN + * @arg @ref DDL_TMR_COUNTERMODE_CENTER_UP_DOWN + * @retval None + */ +__STATIC_INLINE void DDL_TMR_SetCounterMode(TMR_TypeDef *TMRx, uint32_t CounterMode) +{ + MODIFY_REG(TMRx->CTRL1, (TMR_CTRL1_CNTDIR | TMR_CTRL1_CAMSEL), CounterMode); +} + +/** + * @brief Get actual counter mode. + * @note Macro IS_TMR_COUNTER_MODE_SELECT_INSTANCE(TMRx) can be used to + * check whether or not the counter mode selection feature is supported + * by a timer instance. + * @param TMRx Timer instance + * @retval Returned value can be one of the following values: + * @arg @ref DDL_TMR_COUNTERMODE_UP + * @arg @ref DDL_TMR_COUNTERMODE_DOWN + * @arg @ref DDL_TMR_COUNTERMODE_CENTER_UP + * @arg @ref DDL_TMR_COUNTERMODE_CENTER_DOWN + * @arg @ref DDL_TMR_COUNTERMODE_CENTER_UP_DOWN + */ +__STATIC_INLINE uint32_t DDL_TMR_GetCounterMode(TMR_TypeDef *TMRx) +{ + uint32_t counter_mode; + + counter_mode = (uint32_t)(READ_BIT(TMRx->CTRL1, TMR_CTRL1_CAMSEL)); + + if (counter_mode == 0U) + { + counter_mode = (uint32_t)(READ_BIT(TMRx->CTRL1, TMR_CTRL1_CNTDIR)); + } + + return counter_mode; +} + +/** + * @brief Enable auto-reload (ARR) preload. + * @param TMRx Timer instance + * @retval None + */ +__STATIC_INLINE void DDL_TMR_EnableARRPreload(TMR_TypeDef *TMRx) +{ + SET_BIT(TMRx->CTRL1, TMR_CTRL1_ARPEN); +} + +/** + * @brief Disable auto-reload (ARR) preload. + * @param TMRx Timer instance + * @retval None + */ +__STATIC_INLINE void DDL_TMR_DisableARRPreload(TMR_TypeDef *TMRx) +{ + CLEAR_BIT(TMRx->CTRL1, TMR_CTRL1_ARPEN); +} + +/** + * @brief Indicates whether auto-reload (ARR) preload is enabled. + * @param TMRx Timer instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_TMR_IsEnabledARRPreload(TMR_TypeDef *TMRx) +{ + return ((READ_BIT(TMRx->CTRL1, TMR_CTRL1_ARPEN) == (TMR_CTRL1_ARPEN)) ? 1UL : 0UL); +} + +/** + * @brief Set the division ratio between the timer clock and the sampling clock used by the dead-time generators + * (when supported) and the digital filters. + * @note Macro IS_TMR_CLOCK_DIVISION_INSTANCE(TMRx) can be used to check + * whether or not the clock division feature is supported by the timer + * instance. + * @param TMRx Timer instance + * @param ClockDivision This parameter can be one of the following values: + * @arg @ref DDL_TMR_CLOCKDIVISION_DIV1 + * @arg @ref DDL_TMR_CLOCKDIVISION_DIV2 + * @arg @ref DDL_TMR_CLOCKDIVISION_DIV4 + * @retval None + */ +__STATIC_INLINE void DDL_TMR_SetClockDivision(TMR_TypeDef *TMRx, uint32_t ClockDivision) +{ + MODIFY_REG(TMRx->CTRL1, TMR_CTRL1_CLKDIV, ClockDivision); +} + +/** + * @brief Get the actual division ratio between the timer clock and the sampling clock used by the dead-time + * generators (when supported) and the digital filters. + * @note Macro IS_TMR_CLOCK_DIVISION_INSTANCE(TMRx) can be used to check + * whether or not the clock division feature is supported by the timer + * instance. + * @param TMRx Timer instance + * @retval Returned value can be one of the following values: + * @arg @ref DDL_TMR_CLOCKDIVISION_DIV1 + * @arg @ref DDL_TMR_CLOCKDIVISION_DIV2 + * @arg @ref DDL_TMR_CLOCKDIVISION_DIV4 + */ +__STATIC_INLINE uint32_t DDL_TMR_GetClockDivision(TMR_TypeDef *TMRx) +{ + return (uint32_t)(READ_BIT(TMRx->CTRL1, TMR_CTRL1_CLKDIV)); +} + +/** + * @brief Set the counter value. + * @note Macro IS_TMR_32B_COUNTER_INSTANCE(TMRx) can be used to check + * whether or not a timer instance supports a 32 bits counter. + * @param TMRx Timer instance + * @param Counter Counter value (between Min_Data=0 and Max_Data=0xFFFF or 0xFFFFFFFF) + * @retval None + */ +__STATIC_INLINE void DDL_TMR_SetCounter(TMR_TypeDef *TMRx, uint32_t Counter) +{ + WRITE_REG(TMRx->CNT, Counter); +} + +/** + * @brief Get the counter value. + * @note Macro IS_TMR_32B_COUNTER_INSTANCE(TMRx) can be used to check + * whether or not a timer instance supports a 32 bits counter. + * @param TMRx Timer instance + * @retval Counter value (between Min_Data=0 and Max_Data=0xFFFF or 0xFFFFFFFF) + */ +__STATIC_INLINE uint32_t DDL_TMR_GetCounter(TMR_TypeDef *TMRx) +{ + return (uint32_t)(READ_REG(TMRx->CNT)); +} + +/** + * @brief Get the current direction of the counter + * @param TMRx Timer instance + * @retval Returned value can be one of the following values: + * @arg @ref DDL_TMR_COUNTERDIRECTION_UP + * @arg @ref DDL_TMR_COUNTERDIRECTION_DOWN + */ +__STATIC_INLINE uint32_t DDL_TMR_GetDirection(TMR_TypeDef *TMRx) +{ + return (uint32_t)(READ_BIT(TMRx->CTRL1, TMR_CTRL1_CNTDIR)); +} + +/** + * @brief Set the prescaler value. + * @note The counter clock frequency CK_CNT is equal to fCK_PSC / (PSC[15:0] + 1). + * @note The prescaler can be changed on the fly as this control register is buffered. The new + * prescaler ratio is taken into account at the next update event. + * @note Helper macro @ref __DDL_TMR_CALC_PSC can be used to calculate the Prescaler parameter + * @param TMRx Timer instance + * @param Prescaler between Min_Data=0 and Max_Data=65535 + * @retval None + */ +__STATIC_INLINE void DDL_TMR_SetPrescaler(TMR_TypeDef *TMRx, uint32_t Prescaler) +{ + WRITE_REG(TMRx->PSC, Prescaler); +} + +/** + * @brief Get the prescaler value. + * @param TMRx Timer instance + * @retval Prescaler value between Min_Data=0 and Max_Data=65535 + */ +__STATIC_INLINE uint32_t DDL_TMR_GetPrescaler(TMR_TypeDef *TMRx) +{ + return (uint32_t)(READ_REG(TMRx->PSC)); +} + +/** + * @brief Set the auto-reload value. + * @note The counter is blocked while the auto-reload value is null. + * @note Macro IS_TMR_32B_COUNTER_INSTANCE(TMRx) can be used to check + * whether or not a timer instance supports a 32 bits counter. + * @note Helper macro @ref __DDL_TMR_CALC_ARR can be used to calculate the AutoReload parameter + * @param TMRx Timer instance + * @param AutoReload between Min_Data=0 and Max_Data=65535 + * @retval None + */ +__STATIC_INLINE void DDL_TMR_SetAutoReload(TMR_TypeDef *TMRx, uint32_t AutoReload) +{ + WRITE_REG(TMRx->AUTORLD, AutoReload); +} + +/** + * @brief Get the auto-reload value. + * @note Macro IS_TMR_32B_COUNTER_INSTANCE(TMRx) can be used to check + * whether or not a timer instance supports a 32 bits counter. + * @param TMRx Timer instance + * @retval Auto-reload value + */ +__STATIC_INLINE uint32_t DDL_TMR_GetAutoReload(TMR_TypeDef *TMRx) +{ + return (uint32_t)(READ_REG(TMRx->AUTORLD)); +} + +/** + * @brief Set the repetition counter value. + * @note Macro IS_TMR_REPETITION_COUNTER_INSTANCE(TMRx) can be used to check + * whether or not a timer instance supports a repetition counter. + * @param TMRx Timer instance + * @param RepetitionCounter between Min_Data=0 and Max_Data=255 or 65535 for advanced timer. + * @retval None + */ +__STATIC_INLINE void DDL_TMR_SetRepetitionCounter(TMR_TypeDef *TMRx, uint32_t RepetitionCounter) +{ + WRITE_REG(TMRx->REPCNT, RepetitionCounter); +} + +/** + * @brief Get the repetition counter value. + * @note Macro IS_TMR_REPETITION_COUNTER_INSTANCE(TMRx) can be used to check + * whether or not a timer instance supports a repetition counter. + * @param TMRx Timer instance + * @retval Repetition counter value + */ +__STATIC_INLINE uint32_t DDL_TMR_GetRepetitionCounter(TMR_TypeDef *TMRx) +{ + return (uint32_t)(READ_REG(TMRx->REPCNT)); +} + +/** + * @} + */ + +/** @defgroup TMR_DDL_EF_Capture_Compare Capture Compare configuration + * @{ + */ +/** + * @brief Enable the capture/compare control bits (CCxE, CCxNE and OCxM) preload. + * @note CCxE, CCxNE and OCxM bits are preloaded, after having been written, + * they are updated only when a commutation event (COM) occurs. + * @note Only on channels that have a complementary output. + * @note Macro IS_TMR_COMMUTATION_EVENT_INSTANCE(TMRx) can be used to check + * whether or not a timer instance is able to generate a commutation event. + * @param TMRx Timer instance + * @retval None + */ +__STATIC_INLINE void DDL_TMR_CC_EnablePreload(TMR_TypeDef *TMRx) +{ + SET_BIT(TMRx->CTRL2, TMR_CTRL2_CCPEN); +} + +/** + * @brief Disable the capture/compare control bits (CCxE, CCxNE and OCxM) preload. + * @note Macro IS_TMR_COMMUTATION_EVENT_INSTANCE(TMRx) can be used to check + * whether or not a timer instance is able to generate a commutation event. + * @param TMRx Timer instance + * @retval None + */ +__STATIC_INLINE void DDL_TMR_CC_DisablePreload(TMR_TypeDef *TMRx) +{ + CLEAR_BIT(TMRx->CTRL2, TMR_CTRL2_CCPEN); +} + +/** + * @brief Set the updated source of the capture/compare control bits (CCxE, CCxNE and OCxM). + * @note Macro IS_TMR_COMMUTATION_EVENT_INSTANCE(TMRx) can be used to check + * whether or not a timer instance is able to generate a commutation event. + * @param TMRx Timer instance + * @param CCUpdateSource This parameter can be one of the following values: + * @arg @ref DDL_TMR_CCUPDATESOURCE_COMG_ONLY + * @arg @ref DDL_TMR_CCUPDATESOURCE_COMG_AND_TRGI + * @retval None + */ +__STATIC_INLINE void DDL_TMR_CC_SetUpdate(TMR_TypeDef *TMRx, uint32_t CCUpdateSource) +{ + MODIFY_REG(TMRx->CTRL2, TMR_CTRL2_CCUSEL, CCUpdateSource); +} + +/** + * @brief Set the trigger of the capture/compare DMA request. + * @param TMRx Timer instance + * @param DMAReqTrigger This parameter can be one of the following values: + * @arg @ref DDL_TMR_CCDMAREQUEST_CC + * @arg @ref DDL_TMR_CCDMAREQUEST_UPDATE + * @retval None + */ +__STATIC_INLINE void DDL_TMR_CC_SetDMAReqTrigger(TMR_TypeDef *TMRx, uint32_t DMAReqTrigger) +{ + MODIFY_REG(TMRx->CTRL2, TMR_CTRL2_CCDSEL, DMAReqTrigger); +} + +/** + * @brief Get actual trigger of the capture/compare DMA request. + * @param TMRx Timer instance + * @retval Returned value can be one of the following values: + * @arg @ref DDL_TMR_CCDMAREQUEST_CC + * @arg @ref DDL_TMR_CCDMAREQUEST_UPDATE + */ +__STATIC_INLINE uint32_t DDL_TMR_CC_GetDMAReqTrigger(TMR_TypeDef *TMRx) +{ + return (uint32_t)(READ_BIT(TMRx->CTRL2, TMR_CTRL2_CCDSEL)); +} + +/** + * @brief Set the lock level to freeze the + * configuration of several capture/compare parameters. + * @note Macro IS_TMR_BREAK_INSTANCE(TMRx) can be used to check whether or not + * the lock mechanism is supported by a timer instance. + * @param TMRx Timer instance + * @param LockLevel This parameter can be one of the following values: + * @arg @ref DDL_TMR_LOCKLEVEL_OFF + * @arg @ref DDL_TMR_LOCKLEVEL_1 + * @arg @ref DDL_TMR_LOCKLEVEL_2 + * @arg @ref DDL_TMR_LOCKLEVEL_3 + * @retval None + */ +__STATIC_INLINE void DDL_TMR_CC_SetLockLevel(TMR_TypeDef *TMRx, uint32_t LockLevel) +{ + MODIFY_REG(TMRx->BDT, TMR_BDT_LOCKCFG, LockLevel); +} + +/** + * @brief Enable capture/compare channels. + * @param TMRx Timer instance + * @param Channels This parameter can be a combination of the following values: + * @arg @ref DDL_TMR_CHANNEL_CH1 + * @arg @ref DDL_TMR_CHANNEL_CH1N + * @arg @ref DDL_TMR_CHANNEL_CH2 + * @arg @ref DDL_TMR_CHANNEL_CH2N + * @arg @ref DDL_TMR_CHANNEL_CH3 + * @arg @ref DDL_TMR_CHANNEL_CH3N + * @arg @ref DDL_TMR_CHANNEL_CH4 + * @retval None + */ +__STATIC_INLINE void DDL_TMR_CC_EnableChannel(TMR_TypeDef *TMRx, uint32_t Channels) +{ + SET_BIT(TMRx->CCEN, Channels); +} + +/** + * @brief Disable capture/compare channels. + * @param TMRx Timer instance + * @param Channels This parameter can be a combination of the following values: + * @arg @ref DDL_TMR_CHANNEL_CH1 + * @arg @ref DDL_TMR_CHANNEL_CH1N + * @arg @ref DDL_TMR_CHANNEL_CH2 + * @arg @ref DDL_TMR_CHANNEL_CH2N + * @arg @ref DDL_TMR_CHANNEL_CH3 + * @arg @ref DDL_TMR_CHANNEL_CH3N + * @arg @ref DDL_TMR_CHANNEL_CH4 + * @retval None + */ +__STATIC_INLINE void DDL_TMR_CC_DisableChannel(TMR_TypeDef *TMRx, uint32_t Channels) +{ + CLEAR_BIT(TMRx->CCEN, Channels); +} + +/** + * @brief Indicate whether channel(s) is(are) enabled. + * @param TMRx Timer instance + * @param Channels This parameter can be a combination of the following values: + * @arg @ref DDL_TMR_CHANNEL_CH1 + * @arg @ref DDL_TMR_CHANNEL_CH1N + * @arg @ref DDL_TMR_CHANNEL_CH2 + * @arg @ref DDL_TMR_CHANNEL_CH2N + * @arg @ref DDL_TMR_CHANNEL_CH3 + * @arg @ref DDL_TMR_CHANNEL_CH3N + * @arg @ref DDL_TMR_CHANNEL_CH4 + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_TMR_CC_IsEnabledChannel(TMR_TypeDef *TMRx, uint32_t Channels) +{ + return ((READ_BIT(TMRx->CCEN, Channels) == (Channels)) ? 1UL : 0UL); +} + +/** + * @} + */ + +/** @defgroup TMR_DDL_EF_Output_Channel Output channel configuration + * @{ + */ +/** + * @brief Configure an output channel. + * @param TMRx Timer instance + * @param Channel This parameter can be one of the following values: + * @arg @ref DDL_TMR_CHANNEL_CH1 + * @arg @ref DDL_TMR_CHANNEL_CH2 + * @arg @ref DDL_TMR_CHANNEL_CH3 + * @arg @ref DDL_TMR_CHANNEL_CH4 + * @param Configuration This parameter must be a combination of all the following values: + * @arg @ref DDL_TMR_OCPOLARITY_HIGH or @ref DDL_TMR_OCPOLARITY_LOW + * @arg @ref DDL_TMR_OCIDLESTATE_LOW or @ref DDL_TMR_OCIDLESTATE_HIGH + * @retval None + */ +__STATIC_INLINE void DDL_TMR_OC_ConfigOutput(TMR_TypeDef *TMRx, uint32_t Channel, uint32_t Configuration) +{ + uint8_t iChannel = TMR_GET_CHANNEL_INDEX(Channel); + __IO uint32_t *pReg = (__IO uint32_t *)((uint32_t)((uint32_t)(&TMRx->CCM1) + OFFSET_TAB_CCMRx[iChannel])); + CLEAR_BIT(*pReg, (TMR_CCM1_CC1SEL << SHIFT_TAB_OCxx[iChannel])); + MODIFY_REG(TMRx->CCEN, (TMR_CCEN_CC1POL << SHIFT_TAB_CCxP[iChannel]), + (Configuration & TMR_CCEN_CC1POL) << SHIFT_TAB_CCxP[iChannel]); + MODIFY_REG(TMRx->CTRL2, (TMR_CTRL2_OC1OIS << SHIFT_TAB_OISx[iChannel]), + (Configuration & TMR_CTRL2_OC1OIS) << SHIFT_TAB_OISx[iChannel]); +} + +/** + * @brief Define the behavior of the output reference signal OCxREF from which + * OCx and OCxN (when relevant) are derived. + * @param TMRx Timer instance + * @param Channel This parameter can be one of the following values: + * @arg @ref DDL_TMR_CHANNEL_CH1 + * @arg @ref DDL_TMR_CHANNEL_CH2 + * @arg @ref DDL_TMR_CHANNEL_CH3 + * @arg @ref DDL_TMR_CHANNEL_CH4 + * @param Mode This parameter can be one of the following values: + * @arg @ref DDL_TMR_OCMODE_FROZEN + * @arg @ref DDL_TMR_OCMODE_ACTIVE + * @arg @ref DDL_TMR_OCMODE_INACTIVE + * @arg @ref DDL_TMR_OCMODE_TOGGLE + * @arg @ref DDL_TMR_OCMODE_FORCED_INACTIVE + * @arg @ref DDL_TMR_OCMODE_FORCED_ACTIVE + * @arg @ref DDL_TMR_OCMODE_PWM1 + * @arg @ref DDL_TMR_OCMODE_PWM2 + * @retval None + */ +__STATIC_INLINE void DDL_TMR_OC_SetMode(TMR_TypeDef *TMRx, uint32_t Channel, uint32_t Mode) +{ + uint8_t iChannel = TMR_GET_CHANNEL_INDEX(Channel); + __IO uint32_t *pReg = (__IO uint32_t *)((uint32_t)((uint32_t)(&TMRx->CCM1) + OFFSET_TAB_CCMRx[iChannel])); + MODIFY_REG(*pReg, ((TMR_CCM1_OC1MOD | TMR_CCM1_CC1SEL) << SHIFT_TAB_OCxx[iChannel]), Mode << SHIFT_TAB_OCxx[iChannel]); +} + +/** + * @brief Get the output compare mode of an output channel. + * @param TMRx Timer instance + * @param Channel This parameter can be one of the following values: + * @arg @ref DDL_TMR_CHANNEL_CH1 + * @arg @ref DDL_TMR_CHANNEL_CH2 + * @arg @ref DDL_TMR_CHANNEL_CH3 + * @arg @ref DDL_TMR_CHANNEL_CH4 + * @retval Returned value can be one of the following values: + * @arg @ref DDL_TMR_OCMODE_FROZEN + * @arg @ref DDL_TMR_OCMODE_ACTIVE + * @arg @ref DDL_TMR_OCMODE_INACTIVE + * @arg @ref DDL_TMR_OCMODE_TOGGLE + * @arg @ref DDL_TMR_OCMODE_FORCED_INACTIVE + * @arg @ref DDL_TMR_OCMODE_FORCED_ACTIVE + * @arg @ref DDL_TMR_OCMODE_PWM1 + * @arg @ref DDL_TMR_OCMODE_PWM2 + */ +__STATIC_INLINE uint32_t DDL_TMR_OC_GetMode(TMR_TypeDef *TMRx, uint32_t Channel) +{ + uint8_t iChannel = TMR_GET_CHANNEL_INDEX(Channel); + const __IO uint32_t *pReg = (__IO uint32_t *)((uint32_t)((uint32_t)(&TMRx->CCM1) + OFFSET_TAB_CCMRx[iChannel])); + return (READ_BIT(*pReg, ((TMR_CCM1_OC1MOD | TMR_CCM1_CC1SEL) << SHIFT_TAB_OCxx[iChannel])) >> SHIFT_TAB_OCxx[iChannel]); +} + +/** + * @brief Set the polarity of an output channel. + * @param TMRx Timer instance + * @param Channel This parameter can be one of the following values: + * @arg @ref DDL_TMR_CHANNEL_CH1 + * @arg @ref DDL_TMR_CHANNEL_CH1N + * @arg @ref DDL_TMR_CHANNEL_CH2 + * @arg @ref DDL_TMR_CHANNEL_CH2N + * @arg @ref DDL_TMR_CHANNEL_CH3 + * @arg @ref DDL_TMR_CHANNEL_CH3N + * @arg @ref DDL_TMR_CHANNEL_CH4 + * @param Polarity This parameter can be one of the following values: + * @arg @ref DDL_TMR_OCPOLARITY_HIGH + * @arg @ref DDL_TMR_OCPOLARITY_LOW + * @retval None + */ +__STATIC_INLINE void DDL_TMR_OC_SetPolarity(TMR_TypeDef *TMRx, uint32_t Channel, uint32_t Polarity) +{ + uint8_t iChannel = TMR_GET_CHANNEL_INDEX(Channel); + MODIFY_REG(TMRx->CCEN, (TMR_CCEN_CC1POL << SHIFT_TAB_CCxP[iChannel]), Polarity << SHIFT_TAB_CCxP[iChannel]); +} + +/** + * @brief Get the polarity of an output channel. + * @param TMRx Timer instance + * @param Channel This parameter can be one of the following values: + * @arg @ref DDL_TMR_CHANNEL_CH1 + * @arg @ref DDL_TMR_CHANNEL_CH1N + * @arg @ref DDL_TMR_CHANNEL_CH2 + * @arg @ref DDL_TMR_CHANNEL_CH2N + * @arg @ref DDL_TMR_CHANNEL_CH3 + * @arg @ref DDL_TMR_CHANNEL_CH3N + * @arg @ref DDL_TMR_CHANNEL_CH4 + * @retval Returned value can be one of the following values: + * @arg @ref DDL_TMR_OCPOLARITY_HIGH + * @arg @ref DDL_TMR_OCPOLARITY_LOW + */ +__STATIC_INLINE uint32_t DDL_TMR_OC_GetPolarity(TMR_TypeDef *TMRx, uint32_t Channel) +{ + uint8_t iChannel = TMR_GET_CHANNEL_INDEX(Channel); + return (READ_BIT(TMRx->CCEN, (TMR_CCEN_CC1POL << SHIFT_TAB_CCxP[iChannel])) >> SHIFT_TAB_CCxP[iChannel]); +} + +/** + * @brief Set the IDLE state of an output channel + * @note This function is significant only for the timer instances + * supporting the break feature. Macro IS_TMR_BREAK_INSTANCE(TMRx) + * can be used to check whether or not a timer instance provides + * a break input. + * @param TMRx Timer instance + * @param Channel This parameter can be one of the following values: + * @arg @ref DDL_TMR_CHANNEL_CH1 + * @arg @ref DDL_TMR_CHANNEL_CH1N + * @arg @ref DDL_TMR_CHANNEL_CH2 + * @arg @ref DDL_TMR_CHANNEL_CH2N + * @arg @ref DDL_TMR_CHANNEL_CH3 + * @arg @ref DDL_TMR_CHANNEL_CH3N + * @arg @ref DDL_TMR_CHANNEL_CH4 + * @param IdleState This parameter can be one of the following values: + * @arg @ref DDL_TMR_OCIDLESTATE_LOW + * @arg @ref DDL_TMR_OCIDLESTATE_HIGH + * @retval None + */ +__STATIC_INLINE void DDL_TMR_OC_SetIdleState(TMR_TypeDef *TMRx, uint32_t Channel, uint32_t IdleState) +{ + uint8_t iChannel = TMR_GET_CHANNEL_INDEX(Channel); + MODIFY_REG(TMRx->CTRL2, (TMR_CTRL2_OC1OIS << SHIFT_TAB_OISx[iChannel]), IdleState << SHIFT_TAB_OISx[iChannel]); +} + +/** + * @brief Get the IDLE state of an output channel + * @param TMRx Timer instance + * @param Channel This parameter can be one of the following values: + * @arg @ref DDL_TMR_CHANNEL_CH1 + * @arg @ref DDL_TMR_CHANNEL_CH1N + * @arg @ref DDL_TMR_CHANNEL_CH2 + * @arg @ref DDL_TMR_CHANNEL_CH2N + * @arg @ref DDL_TMR_CHANNEL_CH3 + * @arg @ref DDL_TMR_CHANNEL_CH3N + * @arg @ref DDL_TMR_CHANNEL_CH4 + * @retval Returned value can be one of the following values: + * @arg @ref DDL_TMR_OCIDLESTATE_LOW + * @arg @ref DDL_TMR_OCIDLESTATE_HIGH + */ +__STATIC_INLINE uint32_t DDL_TMR_OC_GetIdleState(TMR_TypeDef *TMRx, uint32_t Channel) +{ + uint8_t iChannel = TMR_GET_CHANNEL_INDEX(Channel); + return (READ_BIT(TMRx->CTRL2, (TMR_CTRL2_OC1OIS << SHIFT_TAB_OISx[iChannel])) >> SHIFT_TAB_OISx[iChannel]); +} + +/** + * @brief Enable fast mode for the output channel. + * @note Acts only if the channel is configured in PWM1 or PWM2 mode. + * @param TMRx Timer instance + * @param Channel This parameter can be one of the following values: + * @arg @ref DDL_TMR_CHANNEL_CH1 + * @arg @ref DDL_TMR_CHANNEL_CH2 + * @arg @ref DDL_TMR_CHANNEL_CH3 + * @arg @ref DDL_TMR_CHANNEL_CH4 + * @retval None + */ +__STATIC_INLINE void DDL_TMR_OC_EnableFast(TMR_TypeDef *TMRx, uint32_t Channel) +{ + uint8_t iChannel = TMR_GET_CHANNEL_INDEX(Channel); + __IO uint32_t *pReg = (__IO uint32_t *)((uint32_t)((uint32_t)(&TMRx->CCM1) + OFFSET_TAB_CCMRx[iChannel])); + SET_BIT(*pReg, (TMR_CCM1_OC1FEN << SHIFT_TAB_OCxx[iChannel])); + +} + +/** + * @brief Disable fast mode for the output channel. + * @param TMRx Timer instance + * @param Channel This parameter can be one of the following values: + * @arg @ref DDL_TMR_CHANNEL_CH1 + * @arg @ref DDL_TMR_CHANNEL_CH2 + * @arg @ref DDL_TMR_CHANNEL_CH3 + * @arg @ref DDL_TMR_CHANNEL_CH4 + * @retval None + */ +__STATIC_INLINE void DDL_TMR_OC_DisableFast(TMR_TypeDef *TMRx, uint32_t Channel) +{ + uint8_t iChannel = TMR_GET_CHANNEL_INDEX(Channel); + __IO uint32_t *pReg = (__IO uint32_t *)((uint32_t)((uint32_t)(&TMRx->CCM1) + OFFSET_TAB_CCMRx[iChannel])); + CLEAR_BIT(*pReg, (TMR_CCM1_OC1FEN << SHIFT_TAB_OCxx[iChannel])); + +} + +/** + * @brief Indicates whether fast mode is enabled for the output channel. + * @param TMRx Timer instance + * @param Channel This parameter can be one of the following values: + * @arg @ref DDL_TMR_CHANNEL_CH1 + * @arg @ref DDL_TMR_CHANNEL_CH2 + * @arg @ref DDL_TMR_CHANNEL_CH3 + * @arg @ref DDL_TMR_CHANNEL_CH4 + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_TMR_OC_IsEnabledFast(TMR_TypeDef *TMRx, uint32_t Channel) +{ + uint8_t iChannel = TMR_GET_CHANNEL_INDEX(Channel); + const __IO uint32_t *pReg = (__IO uint32_t *)((uint32_t)((uint32_t)(&TMRx->CCM1) + OFFSET_TAB_CCMRx[iChannel])); + uint32_t bitfield = TMR_CCM1_OC1FEN << SHIFT_TAB_OCxx[iChannel]; + return ((READ_BIT(*pReg, bitfield) == bitfield) ? 1UL : 0UL); +} + +/** + * @brief Enable compare register (TMRx_CCx) preload for the output channel. + * @param TMRx Timer instance + * @param Channel This parameter can be one of the following values: + * @arg @ref DDL_TMR_CHANNEL_CH1 + * @arg @ref DDL_TMR_CHANNEL_CH2 + * @arg @ref DDL_TMR_CHANNEL_CH3 + * @arg @ref DDL_TMR_CHANNEL_CH4 + * @retval None + */ +__STATIC_INLINE void DDL_TMR_OC_EnablePreload(TMR_TypeDef *TMRx, uint32_t Channel) +{ + uint8_t iChannel = TMR_GET_CHANNEL_INDEX(Channel); + __IO uint32_t *pReg = (__IO uint32_t *)((uint32_t)((uint32_t)(&TMRx->CCM1) + OFFSET_TAB_CCMRx[iChannel])); + SET_BIT(*pReg, (TMR_CCM1_OC1PEN << SHIFT_TAB_OCxx[iChannel])); +} + +/** + * @brief Disable compare register (TMRx_CCx) preload for the output channel. + * @param TMRx Timer instance + * @param Channel This parameter can be one of the following values: + * @arg @ref DDL_TMR_CHANNEL_CH1 + * @arg @ref DDL_TMR_CHANNEL_CH2 + * @arg @ref DDL_TMR_CHANNEL_CH3 + * @arg @ref DDL_TMR_CHANNEL_CH4 + * @retval None + */ +__STATIC_INLINE void DDL_TMR_OC_DisablePreload(TMR_TypeDef *TMRx, uint32_t Channel) +{ + uint8_t iChannel = TMR_GET_CHANNEL_INDEX(Channel); + __IO uint32_t *pReg = (__IO uint32_t *)((uint32_t)((uint32_t)(&TMRx->CCM1) + OFFSET_TAB_CCMRx[iChannel])); + CLEAR_BIT(*pReg, (TMR_CCM1_OC1PEN << SHIFT_TAB_OCxx[iChannel])); +} + +/** + * @brief Indicates whether compare register (TMRx_CCx) preload is enabled for the output channel. + * @param TMRx Timer instance + * @param Channel This parameter can be one of the following values: + * @arg @ref DDL_TMR_CHANNEL_CH1 + * @arg @ref DDL_TMR_CHANNEL_CH2 + * @arg @ref DDL_TMR_CHANNEL_CH3 + * @arg @ref DDL_TMR_CHANNEL_CH4 + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_TMR_OC_IsEnabledPreload(TMR_TypeDef *TMRx, uint32_t Channel) +{ + uint8_t iChannel = TMR_GET_CHANNEL_INDEX(Channel); + const __IO uint32_t *pReg = (__IO uint32_t *)((uint32_t)((uint32_t)(&TMRx->CCM1) + OFFSET_TAB_CCMRx[iChannel])); + uint32_t bitfield = TMR_CCM1_OC1PEN << SHIFT_TAB_OCxx[iChannel]; + return ((READ_BIT(*pReg, bitfield) == bitfield) ? 1UL : 0UL); +} + +/** + * @brief Enable clearing the output channel on an external event. + * @note This function can only be used in Output compare and PWM modes. It does not work in Forced mode. + * @note Macro IS_TMR_OCXREF_CLEAR_INSTANCE(TMRx) can be used to check whether + * or not a timer instance can clear the OCxREF signal on an external event. + * @param TMRx Timer instance + * @param Channel This parameter can be one of the following values: + * @arg @ref DDL_TMR_CHANNEL_CH1 + * @arg @ref DDL_TMR_CHANNEL_CH2 + * @arg @ref DDL_TMR_CHANNEL_CH3 + * @arg @ref DDL_TMR_CHANNEL_CH4 + * @retval None + */ +__STATIC_INLINE void DDL_TMR_OC_EnableClear(TMR_TypeDef *TMRx, uint32_t Channel) +{ + uint8_t iChannel = TMR_GET_CHANNEL_INDEX(Channel); + __IO uint32_t *pReg = (__IO uint32_t *)((uint32_t)((uint32_t)(&TMRx->CCM1) + OFFSET_TAB_CCMRx[iChannel])); + SET_BIT(*pReg, (TMR_CCM1_OC1CEN << SHIFT_TAB_OCxx[iChannel])); +} + +/** + * @brief Disable clearing the output channel on an external event. + * @note Macro IS_TMR_OCXREF_CLEAR_INSTANCE(TMRx) can be used to check whether + * or not a timer instance can clear the OCxREF signal on an external event. + * @param TMRx Timer instance + * @param Channel This parameter can be one of the following values: + * @arg @ref DDL_TMR_CHANNEL_CH1 + * @arg @ref DDL_TMR_CHANNEL_CH2 + * @arg @ref DDL_TMR_CHANNEL_CH3 + * @arg @ref DDL_TMR_CHANNEL_CH4 + * @retval None + */ +__STATIC_INLINE void DDL_TMR_OC_DisableClear(TMR_TypeDef *TMRx, uint32_t Channel) +{ + uint8_t iChannel = TMR_GET_CHANNEL_INDEX(Channel); + __IO uint32_t *pReg = (__IO uint32_t *)((uint32_t)((uint32_t)(&TMRx->CCM1) + OFFSET_TAB_CCMRx[iChannel])); + CLEAR_BIT(*pReg, (TMR_CCM1_OC1CEN << SHIFT_TAB_OCxx[iChannel])); +} + +/** + * @brief Indicates clearing the output channel on an external event is enabled for the output channel. + * @note This function enables clearing the output channel on an external event. + * @note This function can only be used in Output compare and PWM modes. It does not work in Forced mode. + * @note Macro IS_TMR_OCXREF_CLEAR_INSTANCE(TMRx) can be used to check whether + * or not a timer instance can clear the OCxREF signal on an external event. + * @param TMRx Timer instance + * @param Channel This parameter can be one of the following values: + * @arg @ref DDL_TMR_CHANNEL_CH1 + * @arg @ref DDL_TMR_CHANNEL_CH2 + * @arg @ref DDL_TMR_CHANNEL_CH3 + * @arg @ref DDL_TMR_CHANNEL_CH4 + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_TMR_OC_IsEnabledClear(TMR_TypeDef *TMRx, uint32_t Channel) +{ + uint8_t iChannel = TMR_GET_CHANNEL_INDEX(Channel); + const __IO uint32_t *pReg = (__IO uint32_t *)((uint32_t)((uint32_t)(&TMRx->CCM1) + OFFSET_TAB_CCMRx[iChannel])); + uint32_t bitfield = TMR_CCM1_OC1CEN << SHIFT_TAB_OCxx[iChannel]; + return ((READ_BIT(*pReg, bitfield) == bitfield) ? 1UL : 0UL); +} + +/** + * @brief Set the dead-time delay (delay inserted between the rising edge of the OCxREF signal and the rising edge of + * the Ocx and OCxN signals). + * @note Macro IS_TMR_BREAK_INSTANCE(TMRx) can be used to check whether or not + * dead-time insertion feature is supported by a timer instance. + * @note Helper macro @ref __DDL_TMR_CALC_DEADTMRE can be used to calculate the DeadTime parameter + * @param TMRx Timer instance + * @param DeadTime between Min_Data=0 and Max_Data=255 + * @retval None + */ +__STATIC_INLINE void DDL_TMR_OC_SetDeadTime(TMR_TypeDef *TMRx, uint32_t DeadTime) +{ + MODIFY_REG(TMRx->BDT, TMR_BDT_DTS, DeadTime); +} + +/** + * @brief Set compare value for output channel 1 (TMRx_CC1). + * @note In 32-bit timer implementations compare value can be between 0x00000000 and 0xFFFFFFFF. + * @note Macro IS_TMR_32B_COUNTER_INSTANCE(TMRx) can be used to check + * whether or not a timer instance supports a 32 bits counter. + * @note Macro IS_TMR_CC1_INSTANCE(TMRx) can be used to check whether or not + * output channel 1 is supported by a timer instance. + * @param TMRx Timer instance + * @param CompareValue between Min_Data=0 and Max_Data=65535 + * @retval None + */ +__STATIC_INLINE void DDL_TMR_OC_SetCompareCH1(TMR_TypeDef *TMRx, uint32_t CompareValue) +{ + WRITE_REG(TMRx->CC1, CompareValue); +} + +/** + * @brief Set compare value for output channel 2 (TMRx_CC2). + * @note In 32-bit timer implementations compare value can be between 0x00000000 and 0xFFFFFFFF. + * @note Macro IS_TMR_32B_COUNTER_INSTANCE(TMRx) can be used to check + * whether or not a timer instance supports a 32 bits counter. + * @note Macro IS_TMR_CC2_INSTANCE(TMRx) can be used to check whether or not + * output channel 2 is supported by a timer instance. + * @param TMRx Timer instance + * @param CompareValue between Min_Data=0 and Max_Data=65535 + * @retval None + */ +__STATIC_INLINE void DDL_TMR_OC_SetCompareCH2(TMR_TypeDef *TMRx, uint32_t CompareValue) +{ + WRITE_REG(TMRx->CC2, CompareValue); +} + +/** + * @brief Set compare value for output channel 3 (TMRx_CC3). + * @note In 32-bit timer implementations compare value can be between 0x00000000 and 0xFFFFFFFF. + * @note Macro IS_TMR_32B_COUNTER_INSTANCE(TMRx) can be used to check + * whether or not a timer instance supports a 32 bits counter. + * @note Macro IS_TMR_CC3_INSTANCE(TMRx) can be used to check whether or not + * output channel is supported by a timer instance. + * @param TMRx Timer instance + * @param CompareValue between Min_Data=0 and Max_Data=65535 + * @retval None + */ +__STATIC_INLINE void DDL_TMR_OC_SetCompareCH3(TMR_TypeDef *TMRx, uint32_t CompareValue) +{ + WRITE_REG(TMRx->CC3, CompareValue); +} + +/** + * @brief Set compare value for output channel 4 (TMRx_CC4). + * @note In 32-bit timer implementations compare value can be between 0x00000000 and 0xFFFFFFFF. + * @note Macro IS_TMR_32B_COUNTER_INSTANCE(TMRx) can be used to check + * whether or not a timer instance supports a 32 bits counter. + * @note Macro IS_TMR_CC4_INSTANCE(TMRx) can be used to check whether or not + * output channel 4 is supported by a timer instance. + * @param TMRx Timer instance + * @param CompareValue between Min_Data=0 and Max_Data=65535 + * @retval None + */ +__STATIC_INLINE void DDL_TMR_OC_SetCompareCH4(TMR_TypeDef *TMRx, uint32_t CompareValue) +{ + WRITE_REG(TMRx->CC4, CompareValue); +} + +/** + * @brief Get compare value (TMRx_CC1) set for output channel 1. + * @note In 32-bit timer implementations returned compare value can be between 0x00000000 and 0xFFFFFFFF. + * @note Macro IS_TMR_32B_COUNTER_INSTANCE(TMRx) can be used to check + * whether or not a timer instance supports a 32 bits counter. + * @note Macro IS_TMR_CC1_INSTANCE(TMRx) can be used to check whether or not + * output channel 1 is supported by a timer instance. + * @param TMRx Timer instance + * @retval CompareValue (between Min_Data=0 and Max_Data=65535) + */ +__STATIC_INLINE uint32_t DDL_TMR_OC_GetCompareCH1(TMR_TypeDef *TMRx) +{ + return (uint32_t)(READ_REG(TMRx->CC1)); +} + +/** + * @brief Get compare value (TMRx_CC2) set for output channel 2. + * @note In 32-bit timer implementations returned compare value can be between 0x00000000 and 0xFFFFFFFF. + * @note Macro IS_TMR_32B_COUNTER_INSTANCE(TMRx) can be used to check + * whether or not a timer instance supports a 32 bits counter. + * @note Macro IS_TMR_CC2_INSTANCE(TMRx) can be used to check whether or not + * output channel 2 is supported by a timer instance. + * @param TMRx Timer instance + * @retval CompareValue (between Min_Data=0 and Max_Data=65535) + */ +__STATIC_INLINE uint32_t DDL_TMR_OC_GetCompareCH2(TMR_TypeDef *TMRx) +{ + return (uint32_t)(READ_REG(TMRx->CC2)); +} + +/** + * @brief Get compare value (TMRx_CC3) set for output channel 3. + * @note In 32-bit timer implementations returned compare value can be between 0x00000000 and 0xFFFFFFFF. + * @note Macro IS_TMR_32B_COUNTER_INSTANCE(TMRx) can be used to check + * whether or not a timer instance supports a 32 bits counter. + * @note Macro IS_TMR_CC3_INSTANCE(TMRx) can be used to check whether or not + * output channel 3 is supported by a timer instance. + * @param TMRx Timer instance + * @retval CompareValue (between Min_Data=0 and Max_Data=65535) + */ +__STATIC_INLINE uint32_t DDL_TMR_OC_GetCompareCH3(TMR_TypeDef *TMRx) +{ + return (uint32_t)(READ_REG(TMRx->CC3)); +} + +/** + * @brief Get compare value (TMRx_CC4) set for output channel 4. + * @note In 32-bit timer implementations returned compare value can be between 0x00000000 and 0xFFFFFFFF. + * @note Macro IS_TMR_32B_COUNTER_INSTANCE(TMRx) can be used to check + * whether or not a timer instance supports a 32 bits counter. + * @note Macro IS_TMR_CC4_INSTANCE(TMRx) can be used to check whether or not + * output channel 4 is supported by a timer instance. + * @param TMRx Timer instance + * @retval CompareValue (between Min_Data=0 and Max_Data=65535) + */ +__STATIC_INLINE uint32_t DDL_TMR_OC_GetCompareCH4(TMR_TypeDef *TMRx) +{ + return (uint32_t)(READ_REG(TMRx->CC4)); +} + +/** + * @} + */ + +/** @defgroup TMR_DDL_EF_Input_Channel Input channel configuration + * @{ + */ +/** + * @brief Configure input channel. + * @param TMRx Timer instance + * @param Channel This parameter can be one of the following values: + * @arg @ref DDL_TMR_CHANNEL_CH1 + * @arg @ref DDL_TMR_CHANNEL_CH2 + * @arg @ref DDL_TMR_CHANNEL_CH3 + * @arg @ref DDL_TMR_CHANNEL_CH4 + * @param Configuration This parameter must be a combination of all the following values: + * @arg @ref DDL_TMR_ACTIVEINPUT_DIRECTTI or @ref DDL_TMR_ACTIVEINPUT_INDIRECTTI or @ref DDL_TMR_ACTIVEINPUT_TRC + * @arg @ref DDL_TMR_ICPSC_DIV1 or ... or @ref DDL_TMR_ICPSC_DIV8 + * @arg @ref DDL_TMR_IC_FILTER_FDIV1 or ... or @ref DDL_TMR_IC_FILTER_FDIV32_N8 + * @arg @ref DDL_TMR_IC_POLARITY_RISING or @ref DDL_TMR_IC_POLARITY_FALLING or @ref DDL_TMR_IC_POLARITY_BOTHEDGE + * @retval None + */ +__STATIC_INLINE void DDL_TMR_IC_Config(TMR_TypeDef *TMRx, uint32_t Channel, uint32_t Configuration) +{ + uint8_t iChannel = TMR_GET_CHANNEL_INDEX(Channel); + __IO uint32_t *pReg = (__IO uint32_t *)((uint32_t)((uint32_t)(&TMRx->CCM1) + OFFSET_TAB_CCMRx[iChannel])); + MODIFY_REG(*pReg, ((TMR_CCM1_IC1F | TMR_CCM1_IC1PSC | TMR_CCM1_CC1SEL) << SHIFT_TAB_ICxx[iChannel]), + ((Configuration >> 16U) & (TMR_CCM1_IC1F | TMR_CCM1_IC1PSC | TMR_CCM1_CC1SEL)) \ + << SHIFT_TAB_ICxx[iChannel]); + MODIFY_REG(TMRx->CCEN, ((TMR_CCEN_CC1NPOL | TMR_CCEN_CC1POL) << SHIFT_TAB_CCxP[iChannel]), + (Configuration & (TMR_CCEN_CC1NPOL | TMR_CCEN_CC1POL)) << SHIFT_TAB_CCxP[iChannel]); +} + +/** + * @brief Set the active input. + * @param TMRx Timer instance + * @param Channel This parameter can be one of the following values: + * @arg @ref DDL_TMR_CHANNEL_CH1 + * @arg @ref DDL_TMR_CHANNEL_CH2 + * @arg @ref DDL_TMR_CHANNEL_CH3 + * @arg @ref DDL_TMR_CHANNEL_CH4 + * @param ICActiveInput This parameter can be one of the following values: + * @arg @ref DDL_TMR_ACTIVEINPUT_DIRECTTI + * @arg @ref DDL_TMR_ACTIVEINPUT_INDIRECTTI + * @arg @ref DDL_TMR_ACTIVEINPUT_TRC + * @retval None + */ +__STATIC_INLINE void DDL_TMR_IC_SetActiveInput(TMR_TypeDef *TMRx, uint32_t Channel, uint32_t ICActiveInput) +{ + uint8_t iChannel = TMR_GET_CHANNEL_INDEX(Channel); + __IO uint32_t *pReg = (__IO uint32_t *)((uint32_t)((uint32_t)(&TMRx->CCM1) + OFFSET_TAB_CCMRx[iChannel])); + MODIFY_REG(*pReg, ((TMR_CCM1_CC1SEL) << SHIFT_TAB_ICxx[iChannel]), (ICActiveInput >> 16U) << SHIFT_TAB_ICxx[iChannel]); +} + +/** + * @brief Get the current active input. + * @param TMRx Timer instance + * @param Channel This parameter can be one of the following values: + * @arg @ref DDL_TMR_CHANNEL_CH1 + * @arg @ref DDL_TMR_CHANNEL_CH2 + * @arg @ref DDL_TMR_CHANNEL_CH3 + * @arg @ref DDL_TMR_CHANNEL_CH4 + * @retval Returned value can be one of the following values: + * @arg @ref DDL_TMR_ACTIVEINPUT_DIRECTTI + * @arg @ref DDL_TMR_ACTIVEINPUT_INDIRECTTI + * @arg @ref DDL_TMR_ACTIVEINPUT_TRC + */ +__STATIC_INLINE uint32_t DDL_TMR_IC_GetActiveInput(TMR_TypeDef *TMRx, uint32_t Channel) +{ + uint8_t iChannel = TMR_GET_CHANNEL_INDEX(Channel); + const __IO uint32_t *pReg = (__IO uint32_t *)((uint32_t)((uint32_t)(&TMRx->CCM1) + OFFSET_TAB_CCMRx[iChannel])); + return ((READ_BIT(*pReg, ((TMR_CCM1_CC1SEL) << SHIFT_TAB_ICxx[iChannel])) >> SHIFT_TAB_ICxx[iChannel]) << 16U); +} + +/** + * @brief Set the prescaler of input channel. + * @param TMRx Timer instance + * @param Channel This parameter can be one of the following values: + * @arg @ref DDL_TMR_CHANNEL_CH1 + * @arg @ref DDL_TMR_CHANNEL_CH2 + * @arg @ref DDL_TMR_CHANNEL_CH3 + * @arg @ref DDL_TMR_CHANNEL_CH4 + * @param ICPrescaler This parameter can be one of the following values: + * @arg @ref DDL_TMR_ICPSC_DIV1 + * @arg @ref DDL_TMR_ICPSC_DIV2 + * @arg @ref DDL_TMR_ICPSC_DIV4 + * @arg @ref DDL_TMR_ICPSC_DIV8 + * @retval None + */ +__STATIC_INLINE void DDL_TMR_IC_SetPrescaler(TMR_TypeDef *TMRx, uint32_t Channel, uint32_t ICPrescaler) +{ + uint8_t iChannel = TMR_GET_CHANNEL_INDEX(Channel); + __IO uint32_t *pReg = (__IO uint32_t *)((uint32_t)((uint32_t)(&TMRx->CCM1) + OFFSET_TAB_CCMRx[iChannel])); + MODIFY_REG(*pReg, ((TMR_CCM1_IC1PSC) << SHIFT_TAB_ICxx[iChannel]), (ICPrescaler >> 16U) << SHIFT_TAB_ICxx[iChannel]); +} + +/** + * @brief Get the current prescaler value acting on an input channel. + * @param TMRx Timer instance + * @param Channel This parameter can be one of the following values: + * @arg @ref DDL_TMR_CHANNEL_CH1 + * @arg @ref DDL_TMR_CHANNEL_CH2 + * @arg @ref DDL_TMR_CHANNEL_CH3 + * @arg @ref DDL_TMR_CHANNEL_CH4 + * @retval Returned value can be one of the following values: + * @arg @ref DDL_TMR_ICPSC_DIV1 + * @arg @ref DDL_TMR_ICPSC_DIV2 + * @arg @ref DDL_TMR_ICPSC_DIV4 + * @arg @ref DDL_TMR_ICPSC_DIV8 + */ +__STATIC_INLINE uint32_t DDL_TMR_IC_GetPrescaler(TMR_TypeDef *TMRx, uint32_t Channel) +{ + uint8_t iChannel = TMR_GET_CHANNEL_INDEX(Channel); + const __IO uint32_t *pReg = (__IO uint32_t *)((uint32_t)((uint32_t)(&TMRx->CCM1) + OFFSET_TAB_CCMRx[iChannel])); + return ((READ_BIT(*pReg, ((TMR_CCM1_IC1PSC) << SHIFT_TAB_ICxx[iChannel])) >> SHIFT_TAB_ICxx[iChannel]) << 16U); +} + +/** + * @brief Set the input filter duration. + * @param TMRx Timer instance + * @param Channel This parameter can be one of the following values: + * @arg @ref DDL_TMR_CHANNEL_CH1 + * @arg @ref DDL_TMR_CHANNEL_CH2 + * @arg @ref DDL_TMR_CHANNEL_CH3 + * @arg @ref DDL_TMR_CHANNEL_CH4 + * @param ICFilter This parameter can be one of the following values: + * @arg @ref DDL_TMR_IC_FILTER_FDIV1 + * @arg @ref DDL_TMR_IC_FILTER_FDIV1_N2 + * @arg @ref DDL_TMR_IC_FILTER_FDIV1_N4 + * @arg @ref DDL_TMR_IC_FILTER_FDIV1_N8 + * @arg @ref DDL_TMR_IC_FILTER_FDIV2_N6 + * @arg @ref DDL_TMR_IC_FILTER_FDIV2_N8 + * @arg @ref DDL_TMR_IC_FILTER_FDIV4_N6 + * @arg @ref DDL_TMR_IC_FILTER_FDIV4_N8 + * @arg @ref DDL_TMR_IC_FILTER_FDIV8_N6 + * @arg @ref DDL_TMR_IC_FILTER_FDIV8_N8 + * @arg @ref DDL_TMR_IC_FILTER_FDIV16_N5 + * @arg @ref DDL_TMR_IC_FILTER_FDIV16_N6 + * @arg @ref DDL_TMR_IC_FILTER_FDIV16_N8 + * @arg @ref DDL_TMR_IC_FILTER_FDIV32_N5 + * @arg @ref DDL_TMR_IC_FILTER_FDIV32_N6 + * @arg @ref DDL_TMR_IC_FILTER_FDIV32_N8 + * @retval None + */ +__STATIC_INLINE void DDL_TMR_IC_SetFilter(TMR_TypeDef *TMRx, uint32_t Channel, uint32_t ICFilter) +{ + uint8_t iChannel = TMR_GET_CHANNEL_INDEX(Channel); + __IO uint32_t *pReg = (__IO uint32_t *)((uint32_t)((uint32_t)(&TMRx->CCM1) + OFFSET_TAB_CCMRx[iChannel])); + MODIFY_REG(*pReg, ((TMR_CCM1_IC1F) << SHIFT_TAB_ICxx[iChannel]), (ICFilter >> 16U) << SHIFT_TAB_ICxx[iChannel]); +} + +/** + * @brief Get the input filter duration. + * @param TMRx Timer instance + * @param Channel This parameter can be one of the following values: + * @arg @ref DDL_TMR_CHANNEL_CH1 + * @arg @ref DDL_TMR_CHANNEL_CH2 + * @arg @ref DDL_TMR_CHANNEL_CH3 + * @arg @ref DDL_TMR_CHANNEL_CH4 + * @retval Returned value can be one of the following values: + * @arg @ref DDL_TMR_IC_FILTER_FDIV1 + * @arg @ref DDL_TMR_IC_FILTER_FDIV1_N2 + * @arg @ref DDL_TMR_IC_FILTER_FDIV1_N4 + * @arg @ref DDL_TMR_IC_FILTER_FDIV1_N8 + * @arg @ref DDL_TMR_IC_FILTER_FDIV2_N6 + * @arg @ref DDL_TMR_IC_FILTER_FDIV2_N8 + * @arg @ref DDL_TMR_IC_FILTER_FDIV4_N6 + * @arg @ref DDL_TMR_IC_FILTER_FDIV4_N8 + * @arg @ref DDL_TMR_IC_FILTER_FDIV8_N6 + * @arg @ref DDL_TMR_IC_FILTER_FDIV8_N8 + * @arg @ref DDL_TMR_IC_FILTER_FDIV16_N5 + * @arg @ref DDL_TMR_IC_FILTER_FDIV16_N6 + * @arg @ref DDL_TMR_IC_FILTER_FDIV16_N8 + * @arg @ref DDL_TMR_IC_FILTER_FDIV32_N5 + * @arg @ref DDL_TMR_IC_FILTER_FDIV32_N6 + * @arg @ref DDL_TMR_IC_FILTER_FDIV32_N8 + */ +__STATIC_INLINE uint32_t DDL_TMR_IC_GetFilter(TMR_TypeDef *TMRx, uint32_t Channel) +{ + uint8_t iChannel = TMR_GET_CHANNEL_INDEX(Channel); + const __IO uint32_t *pReg = (__IO uint32_t *)((uint32_t)((uint32_t)(&TMRx->CCM1) + OFFSET_TAB_CCMRx[iChannel])); + return ((READ_BIT(*pReg, ((TMR_CCM1_IC1F) << SHIFT_TAB_ICxx[iChannel])) >> SHIFT_TAB_ICxx[iChannel]) << 16U); +} + +/** + * @brief Set the input channel polarity. + * @param TMRx Timer instance + * @param Channel This parameter can be one of the following values: + * @arg @ref DDL_TMR_CHANNEL_CH1 + * @arg @ref DDL_TMR_CHANNEL_CH2 + * @arg @ref DDL_TMR_CHANNEL_CH3 + * @arg @ref DDL_TMR_CHANNEL_CH4 + * @param ICPolarity This parameter can be one of the following values: + * @arg @ref DDL_TMR_IC_POLARITY_RISING + * @arg @ref DDL_TMR_IC_POLARITY_FALLING + * @arg @ref DDL_TMR_IC_POLARITY_BOTHEDGE + * @retval None + */ +__STATIC_INLINE void DDL_TMR_IC_SetPolarity(TMR_TypeDef *TMRx, uint32_t Channel, uint32_t ICPolarity) +{ + uint8_t iChannel = TMR_GET_CHANNEL_INDEX(Channel); + MODIFY_REG(TMRx->CCEN, ((TMR_CCEN_CC1NPOL | TMR_CCEN_CC1POL) << SHIFT_TAB_CCxP[iChannel]), + ICPolarity << SHIFT_TAB_CCxP[iChannel]); +} + +/** + * @brief Get the current input channel polarity. + * @param TMRx Timer instance + * @param Channel This parameter can be one of the following values: + * @arg @ref DDL_TMR_CHANNEL_CH1 + * @arg @ref DDL_TMR_CHANNEL_CH2 + * @arg @ref DDL_TMR_CHANNEL_CH3 + * @arg @ref DDL_TMR_CHANNEL_CH4 + * @retval Returned value can be one of the following values: + * @arg @ref DDL_TMR_IC_POLARITY_RISING + * @arg @ref DDL_TMR_IC_POLARITY_FALLING + * @arg @ref DDL_TMR_IC_POLARITY_BOTHEDGE + */ +__STATIC_INLINE uint32_t DDL_TMR_IC_GetPolarity(TMR_TypeDef *TMRx, uint32_t Channel) +{ + uint8_t iChannel = TMR_GET_CHANNEL_INDEX(Channel); + return (READ_BIT(TMRx->CCEN, ((TMR_CCEN_CC1NPOL | TMR_CCEN_CC1POL) << SHIFT_TAB_CCxP[iChannel])) >> + SHIFT_TAB_CCxP[iChannel]); +} + +/** + * @brief Connect the TMRx_CH1, CH2 and CH3 pins to the TI1 input (XOR combination). + * @note Macro IS_TMR_XOR_INSTANCE(TMRx) can be used to check whether or not + * a timer instance provides an XOR input. + * @param TMRx Timer instance + * @retval None + */ +__STATIC_INLINE void DDL_TMR_IC_EnableXORCombination(TMR_TypeDef *TMRx) +{ + SET_BIT(TMRx->CTRL2, TMR_CTRL2_TI1SEL); +} + +/** + * @brief Disconnect the TMRx_CH1, CH2 and CH3 pins from the TI1 input. + * @note Macro IS_TMR_XOR_INSTANCE(TMRx) can be used to check whether or not + * a timer instance provides an XOR input. + * @param TMRx Timer instance + * @retval None + */ +__STATIC_INLINE void DDL_TMR_IC_DisableXORCombination(TMR_TypeDef *TMRx) +{ + CLEAR_BIT(TMRx->CTRL2, TMR_CTRL2_TI1SEL); +} + +/** + * @brief Indicates whether the TMRx_CH1, CH2 and CH3 pins are connectected to the TI1 input. + * @note Macro IS_TMR_XOR_INSTANCE(TMRx) can be used to check whether or not + * a timer instance provides an XOR input. + * @param TMRx Timer instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_TMR_IC_IsEnabledXORCombination(TMR_TypeDef *TMRx) +{ + return ((READ_BIT(TMRx->CTRL2, TMR_CTRL2_TI1SEL) == (TMR_CTRL2_TI1SEL)) ? 1UL : 0UL); +} + +/** + * @brief Get captured value for input channel 1. + * @note In 32-bit timer implementations returned captured value can be between 0x00000000 and 0xFFFFFFFF. + * @note Macro IS_TMR_32B_COUNTER_INSTANCE(TMRx) can be used to check + * whether or not a timer instance supports a 32 bits counter. + * @note Macro IS_TMR_CC1_INSTANCE(TMRx) can be used to check whether or not + * input channel 1 is supported by a timer instance. + * @param TMRx Timer instance + * @retval CapturedValue (between Min_Data=0 and Max_Data=65535) + */ +__STATIC_INLINE uint32_t DDL_TMR_IC_GetCaptureCH1(TMR_TypeDef *TMRx) +{ + return (uint32_t)(READ_REG(TMRx->CC1)); +} + +/** + * @brief Get captured value for input channel 2. + * @note In 32-bit timer implementations returned captured value can be between 0x00000000 and 0xFFFFFFFF. + * @note Macro IS_TMR_32B_COUNTER_INSTANCE(TMRx) can be used to check + * whether or not a timer instance supports a 32 bits counter. + * @note Macro IS_TMR_CC2_INSTANCE(TMRx) can be used to check whether or not + * input channel 2 is supported by a timer instance. + * @param TMRx Timer instance + * @retval CapturedValue (between Min_Data=0 and Max_Data=65535) + */ +__STATIC_INLINE uint32_t DDL_TMR_IC_GetCaptureCH2(TMR_TypeDef *TMRx) +{ + return (uint32_t)(READ_REG(TMRx->CC2)); +} + +/** + * @brief Get captured value for input channel 3. + * @note In 32-bit timer implementations returned captured value can be between 0x00000000 and 0xFFFFFFFF. + * @note Macro IS_TMR_32B_COUNTER_INSTANCE(TMRx) can be used to check + * whether or not a timer instance supports a 32 bits counter. + * @note Macro IS_TMR_CC3_INSTANCE(TMRx) can be used to check whether or not + * input channel 3 is supported by a timer instance. + * @param TMRx Timer instance + * @retval CapturedValue (between Min_Data=0 and Max_Data=65535) + */ +__STATIC_INLINE uint32_t DDL_TMR_IC_GetCaptureCH3(TMR_TypeDef *TMRx) +{ + return (uint32_t)(READ_REG(TMRx->CC3)); +} + +/** + * @brief Get captured value for input channel 4. + * @note In 32-bit timer implementations returned captured value can be between 0x00000000 and 0xFFFFFFFF. + * @note Macro IS_TMR_32B_COUNTER_INSTANCE(TMRx) can be used to check + * whether or not a timer instance supports a 32 bits counter. + * @note Macro IS_TMR_CC4_INSTANCE(TMRx) can be used to check whether or not + * input channel 4 is supported by a timer instance. + * @param TMRx Timer instance + * @retval CapturedValue (between Min_Data=0 and Max_Data=65535) + */ +__STATIC_INLINE uint32_t DDL_TMR_IC_GetCaptureCH4(TMR_TypeDef *TMRx) +{ + return (uint32_t)(READ_REG(TMRx->CC4)); +} + +/** + * @} + */ + +/** @defgroup TMR_DDL_EF_Clock_Selection Counter clock selection + * @{ + */ +/** + * @brief Enable external clock mode 2. + * @note When external clock mode 2 is enabled the counter is clocked by any active edge on the ETRF signal. + * @note Macro IS_TMR_CLOCKSOURCE_ETRMODE2_INSTANCE(TMRx) can be used to check + * whether or not a timer instance supports external clock mode2. + * @param TMRx Timer instance + * @retval None + */ +__STATIC_INLINE void DDL_TMR_EnableExternalClock(TMR_TypeDef *TMRx) +{ + SET_BIT(TMRx->SMCTRL, TMR_SMCTRL_ECEN); +} + +/** + * @brief Disable external clock mode 2. + * @note Macro IS_TMR_CLOCKSOURCE_ETRMODE2_INSTANCE(TMRx) can be used to check + * whether or not a timer instance supports external clock mode2. + * @param TMRx Timer instance + * @retval None + */ +__STATIC_INLINE void DDL_TMR_DisableExternalClock(TMR_TypeDef *TMRx) +{ + CLEAR_BIT(TMRx->SMCTRL, TMR_SMCTRL_ECEN); +} + +/** + * @brief Indicate whether external clock mode 2 is enabled. + * @note Macro IS_TMR_CLOCKSOURCE_ETRMODE2_INSTANCE(TMRx) can be used to check + * whether or not a timer instance supports external clock mode2. + * @param TMRx Timer instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_TMR_IsEnabledExternalClock(TMR_TypeDef *TMRx) +{ + return ((READ_BIT(TMRx->SMCTRL, TMR_SMCTRL_ECEN) == (TMR_SMCTRL_ECEN)) ? 1UL : 0UL); +} + +/** + * @brief Set the clock source of the counter clock. + * @note when selected clock source is external clock mode 1, the timer input + * the external clock is applied is selected by calling the @ref DDL_TMR_SetTriggerInput() + * function. This timer input must be configured by calling + * the @ref DDL_TMR_IC_Config() function. + * @note Macro IS_TMR_CLOCKSOURCE_ETRMODE1_INSTANCE(TMRx) can be used to check + * whether or not a timer instance supports external clock mode1. + * @note Macro IS_TMR_CLOCKSOURCE_ETRMODE2_INSTANCE(TMRx) can be used to check + * whether or not a timer instance supports external clock mode2. + * @param TMRx Timer instance + * @param ClockSource This parameter can be one of the following values: + * @arg @ref DDL_TMR_CLOCKSOURCE_INTERNAL + * @arg @ref DDL_TMR_CLOCKSOURCE_EXT_MODE1 + * @arg @ref DDL_TMR_CLOCKSOURCE_EXT_MODE2 + * @retval None + */ +__STATIC_INLINE void DDL_TMR_SetClockSource(TMR_TypeDef *TMRx, uint32_t ClockSource) +{ + MODIFY_REG(TMRx->SMCTRL, TMR_SMCTRL_SMFSEL | TMR_SMCTRL_ECEN, ClockSource); +} + +/** + * @brief Set the encoder interface mode. + * @note Macro IS_TMR_ENCODER_INTERFACE_INSTANCE(TMRx) can be used to check + * whether or not a timer instance supports the encoder mode. + * @param TMRx Timer instance + * @param EncoderMode This parameter can be one of the following values: + * @arg @ref DDL_TMR_ENCODERMODE_X2_TI1 + * @arg @ref DDL_TMR_ENCODERMODE_X2_TI2 + * @arg @ref DDL_TMR_ENCODERMODE_X4_TI12 + * @retval None + */ +__STATIC_INLINE void DDL_TMR_SetEncoderMode(TMR_TypeDef *TMRx, uint32_t EncoderMode) +{ + MODIFY_REG(TMRx->SMCTRL, TMR_SMCTRL_SMFSEL, EncoderMode); +} + +/** + * @} + */ + +/** @defgroup TMR_DDL_EF_Timer_Synchronization Timer synchronisation configuration + * @{ + */ +/** + * @brief Set the trigger output (TRGO) used for timer synchronization . + * @note Macro IS_TMR_MASTER_INSTANCE(TMRx) can be used to check + * whether or not a timer instance can operate as a master timer. + * @param TMRx Timer instance + * @param TimerSynchronization This parameter can be one of the following values: + * @arg @ref DDL_TMR_TRGO_RESET + * @arg @ref DDL_TMR_TRGO_ENABLE + * @arg @ref DDL_TMR_TRGO_UPDATE + * @arg @ref DDL_TMR_TRGO_CC1IF + * @arg @ref DDL_TMR_TRGO_OC1REF + * @arg @ref DDL_TMR_TRGO_OC2REF + * @arg @ref DDL_TMR_TRGO_OC3REF + * @arg @ref DDL_TMR_TRGO_OC4REF + * @retval None + */ +__STATIC_INLINE void DDL_TMR_SetTriggerOutput(TMR_TypeDef *TMRx, uint32_t TimerSynchronization) +{ + MODIFY_REG(TMRx->CTRL2, TMR_CTRL2_MMSEL, TimerSynchronization); +} + +/** + * @brief Set the synchronization mode of a slave timer. + * @note Macro IS_TMR_SLAVE_INSTANCE(TMRx) can be used to check whether or not + * a timer instance can operate as a slave timer. + * @param TMRx Timer instance + * @param SlaveMode This parameter can be one of the following values: + * @arg @ref DDL_TMR_SLAVEMODE_DISABLED + * @arg @ref DDL_TMR_SLAVEMODE_RESET + * @arg @ref DDL_TMR_SLAVEMODE_GATED + * @arg @ref DDL_TMR_SLAVEMODE_TRIGGER + * @retval None + */ +__STATIC_INLINE void DDL_TMR_SetSlaveMode(TMR_TypeDef *TMRx, uint32_t SlaveMode) +{ + MODIFY_REG(TMRx->SMCTRL, TMR_SMCTRL_SMFSEL, SlaveMode); +} + +/** + * @brief Set the selects the trigger input to be used to synchronize the counter. + * @note Macro IS_TMR_SLAVE_INSTANCE(TMRx) can be used to check whether or not + * a timer instance can operate as a slave timer. + * @param TMRx Timer instance + * @param TriggerInput This parameter can be one of the following values: + * @arg @ref DDL_TMR_TS_ITR0 + * @arg @ref DDL_TMR_TS_ITR1 + * @arg @ref DDL_TMR_TS_ITR2 + * @arg @ref DDL_TMR_TS_ITR3 + * @arg @ref DDL_TMR_TS_TI1F_ED + * @arg @ref DDL_TMR_TS_TI1FP1 + * @arg @ref DDL_TMR_TS_TI2FP2 + * @arg @ref DDL_TMR_TS_ETRF + * @retval None + */ +__STATIC_INLINE void DDL_TMR_SetTriggerInput(TMR_TypeDef *TMRx, uint32_t TriggerInput) +{ + MODIFY_REG(TMRx->SMCTRL, TMR_SMCTRL_TRGSEL, TriggerInput); +} + +/** + * @brief Enable the Master/Slave mode. + * @note Macro IS_TMR_SLAVE_INSTANCE(TMRx) can be used to check whether or not + * a timer instance can operate as a slave timer. + * @param TMRx Timer instance + * @retval None + */ +__STATIC_INLINE void DDL_TMR_EnableMasterSlaveMode(TMR_TypeDef *TMRx) +{ + SET_BIT(TMRx->SMCTRL, TMR_SMCTRL_MSMEN); +} + +/** + * @brief Disable the Master/Slave mode. + * @note Macro IS_TMR_SLAVE_INSTANCE(TMRx) can be used to check whether or not + * a timer instance can operate as a slave timer. + * @param TMRx Timer instance + * @retval None + */ +__STATIC_INLINE void DDL_TMR_DisableMasterSlaveMode(TMR_TypeDef *TMRx) +{ + CLEAR_BIT(TMRx->SMCTRL, TMR_SMCTRL_MSMEN); +} + +/** + * @brief Indicates whether the Master/Slave mode is enabled. + * @note Macro IS_TMR_SLAVE_INSTANCE(TMRx) can be used to check whether or not + * a timer instance can operate as a slave timer. + * @param TMRx Timer instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_TMR_IsEnabledMasterSlaveMode(TMR_TypeDef *TMRx) +{ + return ((READ_BIT(TMRx->SMCTRL, TMR_SMCTRL_MSMEN) == (TMR_SMCTRL_MSMEN)) ? 1UL : 0UL); +} + +/** + * @brief Configure the external trigger (ETR) input. + * @note Macro IS_TMR_ETR_INSTANCE(TMRx) can be used to check whether or not + * a timer instance provides an external trigger input. + * @param TMRx Timer instance + * @param ETRPolarity This parameter can be one of the following values: + * @arg @ref DDL_TMR_ETR_POLARITY_NONINVERTED + * @arg @ref DDL_TMR_ETR_POLARITY_INVERTED + * @param ETRPrescaler This parameter can be one of the following values: + * @arg @ref DDL_TMR_ETR_PRESCALER_DIV1 + * @arg @ref DDL_TMR_ETR_PRESCALER_DIV2 + * @arg @ref DDL_TMR_ETR_PRESCALER_DIV4 + * @arg @ref DDL_TMR_ETR_PRESCALER_DIV8 + * @param ETRFilter This parameter can be one of the following values: + * @arg @ref DDL_TMR_ETR_FILTER_FDIV1 + * @arg @ref DDL_TMR_ETR_FILTER_FDIV1_N2 + * @arg @ref DDL_TMR_ETR_FILTER_FDIV1_N4 + * @arg @ref DDL_TMR_ETR_FILTER_FDIV1_N8 + * @arg @ref DDL_TMR_ETR_FILTER_FDIV2_N6 + * @arg @ref DDL_TMR_ETR_FILTER_FDIV2_N8 + * @arg @ref DDL_TMR_ETR_FILTER_FDIV4_N6 + * @arg @ref DDL_TMR_ETR_FILTER_FDIV4_N8 + * @arg @ref DDL_TMR_ETR_FILTER_FDIV8_N6 + * @arg @ref DDL_TMR_ETR_FILTER_FDIV8_N8 + * @arg @ref DDL_TMR_ETR_FILTER_FDIV16_N5 + * @arg @ref DDL_TMR_ETR_FILTER_FDIV16_N6 + * @arg @ref DDL_TMR_ETR_FILTER_FDIV16_N8 + * @arg @ref DDL_TMR_ETR_FILTER_FDIV32_N5 + * @arg @ref DDL_TMR_ETR_FILTER_FDIV32_N6 + * @arg @ref DDL_TMR_ETR_FILTER_FDIV32_N8 + * @retval None + */ +__STATIC_INLINE void DDL_TMR_ConfigETR(TMR_TypeDef *TMRx, uint32_t ETRPolarity, uint32_t ETRPrescaler, + uint32_t ETRFilter) +{ + MODIFY_REG(TMRx->SMCTRL, TMR_SMCTRL_ETPOL | TMR_SMCTRL_ETPCFG | TMR_SMCTRL_ETFCFG, ETRPolarity | ETRPrescaler | ETRFilter); +} + +/** + * @} + */ + +/** @defgroup TMR_DDL_EF_Break_Function Break function configuration + * @{ + */ +/** + * @brief Enable the break function. + * @note Macro IS_TMR_BREAK_INSTANCE(TMRx) can be used to check whether or not + * a timer instance provides a break input. + * @param TMRx Timer instance + * @retval None + */ +__STATIC_INLINE void DDL_TMR_EnableBRK(TMR_TypeDef *TMRx) +{ + __IO uint32_t tmpreg; + SET_BIT(TMRx->BDT, TMR_BDT_BRKEN); + /* Note: Any write operation to this bit takes a delay of 1 APB clock cycle to become effective. */ + tmpreg = READ_REG(TMRx->BDT); + (void)(tmpreg); +} + +/** + * @brief Disable the break function. + * @param TMRx Timer instance + * @note Macro IS_TMR_BREAK_INSTANCE(TMRx) can be used to check whether or not + * a timer instance provides a break input. + * @retval None + */ +__STATIC_INLINE void DDL_TMR_DisableBRK(TMR_TypeDef *TMRx) +{ + __IO uint32_t tmpreg; + CLEAR_BIT(TMRx->BDT, TMR_BDT_BRKEN); + /* Note: Any write operation to this bit takes a delay of 1 APB clock cycle to become effective. */ + tmpreg = READ_REG(TMRx->BDT); + (void)(tmpreg); +} + +/** + * @brief Configure the break input. + * @note Macro IS_TMR_BREAK_INSTANCE(TMRx) can be used to check whether or not + * a timer instance provides a break input. + * @param TMRx Timer instance + * @param BreakPolarity This parameter can be one of the following values: + * @arg @ref DDL_TMR_BREAK_POLARITY_LOW + * @arg @ref DDL_TMR_BREAK_POLARITY_HIGH + * @retval None + */ +__STATIC_INLINE void DDL_TMR_ConfigBRK(TMR_TypeDef *TMRx, uint32_t BreakPolarity) +{ + __IO uint32_t tmpreg; + MODIFY_REG(TMRx->BDT, TMR_BDT_BRKPOL, BreakPolarity); + /* Note: Any write operation to BKP bit takes a delay of 1 APB clock cycle to become effective. */ + tmpreg = READ_REG(TMRx->BDT); + (void)(tmpreg); +} + +/** + * @brief Select the outputs off state (enabled v.s. disabled) in Idle and Run modes. + * @note Macro IS_TMR_BREAK_INSTANCE(TMRx) can be used to check whether or not + * a timer instance provides a break input. + * @param TMRx Timer instance + * @param OffStateIdle This parameter can be one of the following values: + * @arg @ref DDL_TMR_OSSI_DISABLE + * @arg @ref DDL_TMR_OSSI_ENABLE + * @param OffStateRun This parameter can be one of the following values: + * @arg @ref DDL_TMR_OSSR_DISABLE + * @arg @ref DDL_TMR_OSSR_ENABLE + * @retval None + */ +__STATIC_INLINE void DDL_TMR_SetOffStates(TMR_TypeDef *TMRx, uint32_t OffStateIdle, uint32_t OffStateRun) +{ + MODIFY_REG(TMRx->BDT, TMR_BDT_IMOS | TMR_BDT_RMOS, OffStateIdle | OffStateRun); +} + +/** + * @brief Enable automatic output (MOE can be set by software or automatically when a break input is active). + * @note Macro IS_TMR_BREAK_INSTANCE(TMRx) can be used to check whether or not + * a timer instance provides a break input. + * @param TMRx Timer instance + * @retval None + */ +__STATIC_INLINE void DDL_TMR_EnableAutomaticOutput(TMR_TypeDef *TMRx) +{ + SET_BIT(TMRx->BDT, TMR_BDT_AOEN); +} + +/** + * @brief Disable automatic output (MOE can be set only by software). + * @note Macro IS_TMR_BREAK_INSTANCE(TMRx) can be used to check whether or not + * a timer instance provides a break input. + * @param TMRx Timer instance + * @retval None + */ +__STATIC_INLINE void DDL_TMR_DisableAutomaticOutput(TMR_TypeDef *TMRx) +{ + CLEAR_BIT(TMRx->BDT, TMR_BDT_AOEN); +} + +/** + * @brief Indicate whether automatic output is enabled. + * @note Macro IS_TMR_BREAK_INSTANCE(TMRx) can be used to check whether or not + * a timer instance provides a break input. + * @param TMRx Timer instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_TMR_IsEnabledAutomaticOutput(TMR_TypeDef *TMRx) +{ + return ((READ_BIT(TMRx->BDT, TMR_BDT_AOEN) == (TMR_BDT_AOEN)) ? 1UL : 0UL); +} + +/** + * @brief Enable the outputs (set the MOE bit in TMRx_BDTR register). + * @note The MOE bit in TMRx_BDTR register allows to enable /disable the outputs by + * software and is reset in case of break or break2 event + * @note Macro IS_TMR_BREAK_INSTANCE(TMRx) can be used to check whether or not + * a timer instance provides a break input. + * @param TMRx Timer instance + * @retval None + */ +__STATIC_INLINE void DDL_TMR_EnableAllOutputs(TMR_TypeDef *TMRx) +{ + SET_BIT(TMRx->BDT, TMR_BDT_MOEN); +} + +/** + * @brief Disable the outputs (reset the MOE bit in TMRx_BDTR register). + * @note The MOE bit in TMRx_BDTR register allows to enable /disable the outputs by + * software and is reset in case of break or break2 event. + * @note Macro IS_TMR_BREAK_INSTANCE(TMRx) can be used to check whether or not + * a timer instance provides a break input. + * @param TMRx Timer instance + * @retval None + */ +__STATIC_INLINE void DDL_TMR_DisableAllOutputs(TMR_TypeDef *TMRx) +{ + CLEAR_BIT(TMRx->BDT, TMR_BDT_MOEN); +} + +/** + * @brief Indicates whether outputs are enabled. + * @note Macro IS_TMR_BREAK_INSTANCE(TMRx) can be used to check whether or not + * a timer instance provides a break input. + * @param TMRx Timer instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_TMR_IsEnabledAllOutputs(TMR_TypeDef *TMRx) +{ + return ((READ_BIT(TMRx->BDT, TMR_BDT_MOEN) == (TMR_BDT_MOEN)) ? 1UL : 0UL); +} + +/** + * @} + */ + +/** @defgroup TMR_DDL_EF_DMA_Burst_Mode DMA burst mode configuration + * @{ + */ +/** + * @brief Configures the timer DMA burst feature. + * @note Macro IS_TMR_DMABURST_INSTANCE(TMRx) can be used to check whether or + * not a timer instance supports the DMA burst mode. + * @param TMRx Timer instance + * @param DMABurstBaseAddress This parameter can be one of the following values: + * @arg @ref DDL_TMR_DMABURST_BASEADDR_CTRL1 + * @arg @ref DDL_TMR_DMABURST_BASEADDR_CTRL2 + * @arg @ref DDL_TMR_DMABURST_BASEADDR_SMCTRL + * @arg @ref DDL_TMR_DMABURST_BASEADDR_DIEN + * @arg @ref DDL_TMR_DMABURST_BASEADDR_SR + * @arg @ref DDL_TMR_DMABURST_BASEADDR_EGR + * @arg @ref DDL_TMR_DMABURST_BASEADDR_CCM1 + * @arg @ref DDL_TMR_DMABURST_BASEADDR_CCM2 + * @arg @ref DDL_TMR_DMABURST_BASEADDR_CCEN + * @arg @ref DDL_TMR_DMABURST_BASEADDR_CNT + * @arg @ref DDL_TMR_DMABURST_BASEADDR_PSC + * @arg @ref DDL_TMR_DMABURST_BASEADDR_AUTORLD + * @arg @ref DDL_TMR_DMABURST_BASEADDR_REPCNT + * @arg @ref DDL_TMR_DMABURST_BASEADDR_CC1 + * @arg @ref DDL_TMR_DMABURST_BASEADDR_CC2 + * @arg @ref DDL_TMR_DMABURST_BASEADDR_CC3 + * @arg @ref DDL_TMR_DMABURST_BASEADDR_CC4 + * @arg @ref DDL_TMR_DMABURST_BASEADDR_BDT + * @param DMABurstLength This parameter can be one of the following values: + * @arg @ref DDL_TMR_DMABURST_LENGTH_1TRANSFER + * @arg @ref DDL_TMR_DMABURST_LENGTH_2TRANSFERS + * @arg @ref DDL_TMR_DMABURST_LENGTH_3TRANSFERS + * @arg @ref DDL_TMR_DMABURST_LENGTH_4TRANSFERS + * @arg @ref DDL_TMR_DMABURST_LENGTH_5TRANSFERS + * @arg @ref DDL_TMR_DMABURST_LENGTH_6TRANSFERS + * @arg @ref DDL_TMR_DMABURST_LENGTH_7TRANSFERS + * @arg @ref DDL_TMR_DMABURST_LENGTH_8TRANSFERS + * @arg @ref DDL_TMR_DMABURST_LENGTH_9TRANSFERS + * @arg @ref DDL_TMR_DMABURST_LENGTH_10TRANSFERS + * @arg @ref DDL_TMR_DMABURST_LENGTH_11TRANSFERS + * @arg @ref DDL_TMR_DMABURST_LENGTH_12TRANSFERS + * @arg @ref DDL_TMR_DMABURST_LENGTH_13TRANSFERS + * @arg @ref DDL_TMR_DMABURST_LENGTH_14TRANSFERS + * @arg @ref DDL_TMR_DMABURST_LENGTH_15TRANSFERS + * @arg @ref DDL_TMR_DMABURST_LENGTH_16TRANSFERS + * @arg @ref DDL_TMR_DMABURST_LENGTH_17TRANSFERS + * @arg @ref DDL_TMR_DMABURST_LENGTH_18TRANSFERS + * @retval None + */ +__STATIC_INLINE void DDL_TMR_ConfigDMABurst(TMR_TypeDef *TMRx, uint32_t DMABurstBaseAddress, uint32_t DMABurstLength) +{ + MODIFY_REG(TMRx->DCTRL, (TMR_DCTRL_DBLEN | TMR_DCTRL_DBADDR), (DMABurstBaseAddress | DMABurstLength)); +} + +/** + * @} + */ + +/** @defgroup TMR_DDL_EF_Timer_Inputs_Remapping Timer input remapping + * @{ + */ +/** + * @brief Remap TMR inputs (input channel, internal/external triggers). + * @note Macro IS_TMR_REMAP_INSTANCE(TMRx) can be used to check whether or not + * a some timer inputs can be remapped. + * @param TMRx Timer instance + * @param Remap Remap param depends on the TMRx. Description available only + * in CHM version of the User Manual (not in .pdf). + * Otherwise see Reference Manual description of OR registers. + * + * Below description summarizes "Timer Instance" and "Remap" param combinations: + * + * TMR1: one of the following values + * + * ITR2_RMP can be one of the following values + * @arg @ref DDL_TMR_TMR1_ITR2_RMP_TMR3_TRGO (*) + * @arg @ref DDL_TMR_TMR1_ITR2_RMP_LPTMR (*) + * + * TMR2: one of the following values + * + * ITR1_RMP can be one of the following values + * @arg @ref DDL_TMR_TMR2_ITR1_RMP_TMR8_TRGO + * @arg @ref DDL_TMR_TMR2_ITR1_RMP_OTG_FS_SOF + * @arg @ref DDL_TMR_TMR2_ITR1_RMP_OTG_HS_SOF + * + * TMR5: one of the following values + * + * @arg @ref DDL_TMR_TMR5_TI4_RMP_GPIO + * @arg @ref DDL_TMR_TMR5_TI4_RMP_LSI + * @arg @ref DDL_TMR_TMR5_TI4_RMP_LSE + * @arg @ref DDL_TMR_TMR5_TI4_RMP_RTC + * @arg @ref DDL_TMR_TMR5_ITR1_RMP_TMR3_TRGO (*) + * @arg @ref DDL_TMR_TMR5_ITR1_RMP_LPTMR (*) + * + * TMR9: one of the following values + * + * ITR1_RMP can be one of the following values + * @arg @ref DDL_TMR_TMR9_ITR1_RMP_TMR3_TRGO (*) + * @arg @ref DDL_TMR_TMR9_ITR1_RMP_LPTMR (*) + * + * TMR11: one of the following values + * + * @arg @ref DDL_TMR_TMR11_TI1_RMP_GPIO + * @arg @ref DDL_TMR_TMR11_TI1_RMP_GPIO1 (*) + * @arg @ref DDL_TMR_TMR11_TI1_RMP_HSE_RTC + * @arg @ref DDL_TMR_TMR11_TI1_RMP_GPIO2 + * @arg @ref DDL_TMR_TMR11_TI1_RMP_SPDIFRX (*) + * + * (*) Value not defined in all devices. \n + * + * @retval None + */ +__STATIC_INLINE void DDL_TMR_SetRemap(TMR_TypeDef *TMRx, uint32_t Remap) +{ +#if defined(LPTMR_OR_TMR1_ITR2_RMP) && defined(LPTMR_OR_TMR5_ITR1_RMP) && defined(LPTMR_OR_TMR9_ITR1_RMP) + if ((Remap & DDL_TMR_LPTMR_REMAP_MASK) == DDL_TMR_LPTMR_REMAP_MASK) + { + /* Connect TMRx internal trigger to LPTMR1 output */ + SET_BIT(RCC->APB1ENR, RCM_APB1ENR_LPTMR1EN); + MODIFY_REG(LPTMR1->OR, + (LPTMR_OR_TMR1_ITR2_RMP | LPTMR_OR_TMR5_ITR1_RMP | LPTMR_OR_TMR9_ITR1_RMP), + Remap & ~(DDL_TMR_LPTMR_REMAP_MASK)); + } + else + { + MODIFY_REG(TMRx->OR, (Remap >> TMRx_OR_RMP_SHIFT), (Remap & TMRx_OR_RMP_MASK)); + } +#else + MODIFY_REG(TMRx->OR, (Remap >> TMRx_OR_RMP_SHIFT), (Remap & TMRx_OR_RMP_MASK)); +#endif /* LPTMR_OR_TMR1_ITR2_RMP && LPTMR_OR_TMR5_ITR1_RMP && LPTMR_OR_TMR9_ITR1_RMP */ +} + +/** + * @} + */ + +/** @defgroup TMR_DDL_EF_FLAG_Management FLAG-Management + * @{ + */ +/** + * @brief Clear the update interrupt flag (UIF). + * @param TMRx Timer instance + * @retval None + */ +__STATIC_INLINE void DDL_TMR_ClearFlag_UPDATE(TMR_TypeDef *TMRx) +{ + WRITE_REG(TMRx->STS, ~(TMR_STS_UIFLG)); +} + +/** + * @brief Indicate whether update interrupt flag (UIF) is set (update interrupt is pending). + * @param TMRx Timer instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_TMR_IsActiveFlag_UPDATE(TMR_TypeDef *TMRx) +{ + return ((READ_BIT(TMRx->STS, TMR_STS_UIFLG) == (TMR_STS_UIFLG)) ? 1UL : 0UL); +} + +/** + * @brief Clear the Capture/Compare 1 interrupt flag (CC1F). + * @param TMRx Timer instance + * @retval None + */ +__STATIC_INLINE void DDL_TMR_ClearFlag_CC1(TMR_TypeDef *TMRx) +{ + WRITE_REG(TMRx->STS, ~(TMR_STS_CC1IFLG)); +} + +/** + * @brief Indicate whether Capture/Compare 1 interrupt flag (CC1F) is set (Capture/Compare 1 interrupt is pending). + * @param TMRx Timer instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_TMR_IsActiveFlag_CC1(TMR_TypeDef *TMRx) +{ + return ((READ_BIT(TMRx->STS, TMR_STS_CC1IFLG) == (TMR_STS_CC1IFLG)) ? 1UL : 0UL); +} + +/** + * @brief Clear the Capture/Compare 2 interrupt flag (CC2F). + * @param TMRx Timer instance + * @retval None + */ +__STATIC_INLINE void DDL_TMR_ClearFlag_CC2(TMR_TypeDef *TMRx) +{ + WRITE_REG(TMRx->STS, ~(TMR_STS_CC2IFLG)); +} + +/** + * @brief Indicate whether Capture/Compare 2 interrupt flag (CC2F) is set (Capture/Compare 2 interrupt is pending). + * @param TMRx Timer instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_TMR_IsActiveFlag_CC2(TMR_TypeDef *TMRx) +{ + return ((READ_BIT(TMRx->STS, TMR_STS_CC2IFLG) == (TMR_STS_CC2IFLG)) ? 1UL : 0UL); +} + +/** + * @brief Clear the Capture/Compare 3 interrupt flag (CC3F). + * @param TMRx Timer instance + * @retval None + */ +__STATIC_INLINE void DDL_TMR_ClearFlag_CC3(TMR_TypeDef *TMRx) +{ + WRITE_REG(TMRx->STS, ~(TMR_STS_CC3IFLG)); +} + +/** + * @brief Indicate whether Capture/Compare 3 interrupt flag (CC3F) is set (Capture/Compare 3 interrupt is pending). + * @param TMRx Timer instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_TMR_IsActiveFlag_CC3(TMR_TypeDef *TMRx) +{ + return ((READ_BIT(TMRx->STS, TMR_STS_CC3IFLG) == (TMR_STS_CC3IFLG)) ? 1UL : 0UL); +} + +/** + * @brief Clear the Capture/Compare 4 interrupt flag (CC4F). + * @param TMRx Timer instance + * @retval None + */ +__STATIC_INLINE void DDL_TMR_ClearFlag_CC4(TMR_TypeDef *TMRx) +{ + WRITE_REG(TMRx->STS, ~(TMR_STS_CC4IFLG)); +} + +/** + * @brief Indicate whether Capture/Compare 4 interrupt flag (CC4F) is set (Capture/Compare 4 interrupt is pending). + * @param TMRx Timer instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_TMR_IsActiveFlag_CC4(TMR_TypeDef *TMRx) +{ + return ((READ_BIT(TMRx->STS, TMR_STS_CC4IFLG) == (TMR_STS_CC4IFLG)) ? 1UL : 0UL); +} + +/** + * @brief Clear the commutation interrupt flag (COMIF). + * @param TMRx Timer instance + * @retval None + */ +__STATIC_INLINE void DDL_TMR_ClearFlag_COM(TMR_TypeDef *TMRx) +{ + WRITE_REG(TMRx->STS, ~(TMR_STS_COMIFLG)); +} + +/** + * @brief Indicate whether commutation interrupt flag (COMIF) is set (commutation interrupt is pending). + * @param TMRx Timer instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_TMR_IsActiveFlag_COM(TMR_TypeDef *TMRx) +{ + return ((READ_BIT(TMRx->STS, TMR_STS_COMIFLG) == (TMR_STS_COMIFLG)) ? 1UL : 0UL); +} + +/** + * @brief Clear the trigger interrupt flag (TIF). + * @param TMRx Timer instance + * @retval None + */ +__STATIC_INLINE void DDL_TMR_ClearFlag_TRIG(TMR_TypeDef *TMRx) +{ + WRITE_REG(TMRx->STS, ~(TMR_STS_TRGIFLG)); +} + +/** + * @brief Indicate whether trigger interrupt flag (TIF) is set (trigger interrupt is pending). + * @param TMRx Timer instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_TMR_IsActiveFlag_TRIG(TMR_TypeDef *TMRx) +{ + return ((READ_BIT(TMRx->STS, TMR_STS_TRGIFLG) == (TMR_STS_TRGIFLG)) ? 1UL : 0UL); +} + +/** + * @brief Clear the break interrupt flag (BIF). + * @param TMRx Timer instance + * @retval None + */ +__STATIC_INLINE void DDL_TMR_ClearFlag_BRK(TMR_TypeDef *TMRx) +{ + WRITE_REG(TMRx->STS, ~(TMR_STS_BRKIFLG)); +} + +/** + * @brief Indicate whether break interrupt flag (BIF) is set (break interrupt is pending). + * @param TMRx Timer instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_TMR_IsActiveFlag_BRK(TMR_TypeDef *TMRx) +{ + return ((READ_BIT(TMRx->STS, TMR_STS_BRKIFLG) == (TMR_STS_BRKIFLG)) ? 1UL : 0UL); +} + +/** + * @brief Clear the Capture/Compare 1 over-capture interrupt flag (CC1OF). + * @param TMRx Timer instance + * @retval None + */ +__STATIC_INLINE void DDL_TMR_ClearFlag_CC1OVR(TMR_TypeDef *TMRx) +{ + WRITE_REG(TMRx->STS, ~(TMR_STS_CC1RCFLG)); +} + +/** + * @brief Indicate whether Capture/Compare 1 over-capture interrupt flag (CC1OF) is set + * (Capture/Compare 1 interrupt is pending). + * @param TMRx Timer instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_TMR_IsActiveFlag_CC1OVR(TMR_TypeDef *TMRx) +{ + return ((READ_BIT(TMRx->STS, TMR_STS_CC1RCFLG) == (TMR_STS_CC1RCFLG)) ? 1UL : 0UL); +} + +/** + * @brief Clear the Capture/Compare 2 over-capture interrupt flag (CC2OF). + * @param TMRx Timer instance + * @retval None + */ +__STATIC_INLINE void DDL_TMR_ClearFlag_CC2OVR(TMR_TypeDef *TMRx) +{ + WRITE_REG(TMRx->STS, ~(TMR_STS_CC2RCFLG)); +} + +/** + * @brief Indicate whether Capture/Compare 2 over-capture interrupt flag (CC2OF) is set + * (Capture/Compare 2 over-capture interrupt is pending). + * @param TMRx Timer instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_TMR_IsActiveFlag_CC2OVR(TMR_TypeDef *TMRx) +{ + return ((READ_BIT(TMRx->STS, TMR_STS_CC2RCFLG) == (TMR_STS_CC2RCFLG)) ? 1UL : 0UL); +} + +/** + * @brief Clear the Capture/Compare 3 over-capture interrupt flag (CC3OF). + * @param TMRx Timer instance + * @retval None + */ +__STATIC_INLINE void DDL_TMR_ClearFlag_CC3OVR(TMR_TypeDef *TMRx) +{ + WRITE_REG(TMRx->STS, ~(TMR_STS_CC3RCFLG)); +} + +/** + * @brief Indicate whether Capture/Compare 3 over-capture interrupt flag (CC3OF) is set + * (Capture/Compare 3 over-capture interrupt is pending). + * @param TMRx Timer instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_TMR_IsActiveFlag_CC3OVR(TMR_TypeDef *TMRx) +{ + return ((READ_BIT(TMRx->STS, TMR_STS_CC3RCFLG) == (TMR_STS_CC3RCFLG)) ? 1UL : 0UL); +} + +/** + * @brief Clear the Capture/Compare 4 over-capture interrupt flag (CC4OF). + * @param TMRx Timer instance + * @retval None + */ +__STATIC_INLINE void DDL_TMR_ClearFlag_CC4OVR(TMR_TypeDef *TMRx) +{ + WRITE_REG(TMRx->STS, ~(TMR_STS_CC4RCFLG)); +} + +/** + * @brief Indicate whether Capture/Compare 4 over-capture interrupt flag (CC4OF) is set + * (Capture/Compare 4 over-capture interrupt is pending). + * @param TMRx Timer instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_TMR_IsActiveFlag_CC4OVR(TMR_TypeDef *TMRx) +{ + return ((READ_BIT(TMRx->STS, TMR_STS_CC4RCFLG) == (TMR_STS_CC4RCFLG)) ? 1UL : 0UL); +} + +/** + * @} + */ + +/** @defgroup TMR_DDL_EF_IT_Management IT-Management + * @{ + */ +/** + * @brief Enable update interrupt (UIE). + * @param TMRx Timer instance + * @retval None + */ +__STATIC_INLINE void DDL_TMR_EnableIT_UPDATE(TMR_TypeDef *TMRx) +{ + SET_BIT(TMRx->DIEN, TMR_DIEN_UIEN); +} + +/** + * @brief Disable update interrupt (UIE). + * @param TMRx Timer instance + * @retval None + */ +__STATIC_INLINE void DDL_TMR_DisableIT_UPDATE(TMR_TypeDef *TMRx) +{ + CLEAR_BIT(TMRx->DIEN, TMR_DIEN_UIEN); +} + +/** + * @brief Indicates whether the update interrupt (UIE) is enabled. + * @param TMRx Timer instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_TMR_IsEnabledIT_UPDATE(TMR_TypeDef *TMRx) +{ + return ((READ_BIT(TMRx->DIEN, TMR_DIEN_UIEN) == (TMR_DIEN_UIEN)) ? 1UL : 0UL); +} + +/** + * @brief Enable capture/compare 1 interrupt (CC1IE). + * @param TMRx Timer instance + * @retval None + */ +__STATIC_INLINE void DDL_TMR_EnableIT_CC1(TMR_TypeDef *TMRx) +{ + SET_BIT(TMRx->DIEN, TMR_DIEN_CC1IEN); +} + +/** + * @brief Disable capture/compare 1 interrupt (CC1IE). + * @param TMRx Timer instance + * @retval None + */ +__STATIC_INLINE void DDL_TMR_DisableIT_CC1(TMR_TypeDef *TMRx) +{ + CLEAR_BIT(TMRx->DIEN, TMR_DIEN_CC1IEN); +} + +/** + * @brief Indicates whether the capture/compare 1 interrupt (CC1IE) is enabled. + * @param TMRx Timer instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_TMR_IsEnabledIT_CC1(TMR_TypeDef *TMRx) +{ + return ((READ_BIT(TMRx->DIEN, TMR_DIEN_CC1IEN) == (TMR_DIEN_CC1IEN)) ? 1UL : 0UL); +} + +/** + * @brief Enable capture/compare 2 interrupt (CC2IE). + * @param TMRx Timer instance + * @retval None + */ +__STATIC_INLINE void DDL_TMR_EnableIT_CC2(TMR_TypeDef *TMRx) +{ + SET_BIT(TMRx->DIEN, TMR_DIEN_CC2IEN); +} + +/** + * @brief Disable capture/compare 2 interrupt (CC2IE). + * @param TMRx Timer instance + * @retval None + */ +__STATIC_INLINE void DDL_TMR_DisableIT_CC2(TMR_TypeDef *TMRx) +{ + CLEAR_BIT(TMRx->DIEN, TMR_DIEN_CC2IEN); +} + +/** + * @brief Indicates whether the capture/compare 2 interrupt (CC2IE) is enabled. + * @param TMRx Timer instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_TMR_IsEnabledIT_CC2(TMR_TypeDef *TMRx) +{ + return ((READ_BIT(TMRx->DIEN, TMR_DIEN_CC2IEN) == (TMR_DIEN_CC2IEN)) ? 1UL : 0UL); +} + +/** + * @brief Enable capture/compare 3 interrupt (CC3IE). + * @param TMRx Timer instance + * @retval None + */ +__STATIC_INLINE void DDL_TMR_EnableIT_CC3(TMR_TypeDef *TMRx) +{ + SET_BIT(TMRx->DIEN, TMR_DIEN_CC3IEN); +} + +/** + * @brief Disable capture/compare 3 interrupt (CC3IE). + * @param TMRx Timer instance + * @retval None + */ +__STATIC_INLINE void DDL_TMR_DisableIT_CC3(TMR_TypeDef *TMRx) +{ + CLEAR_BIT(TMRx->DIEN, TMR_DIEN_CC3IEN); +} + +/** + * @brief Indicates whether the capture/compare 3 interrupt (CC3IE) is enabled. + * @param TMRx Timer instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_TMR_IsEnabledIT_CC3(TMR_TypeDef *TMRx) +{ + return ((READ_BIT(TMRx->DIEN, TMR_DIEN_CC3IEN) == (TMR_DIEN_CC3IEN)) ? 1UL : 0UL); +} + +/** + * @brief Enable capture/compare 4 interrupt (CC4IE). + * @param TMRx Timer instance + * @retval None + */ +__STATIC_INLINE void DDL_TMR_EnableIT_CC4(TMR_TypeDef *TMRx) +{ + SET_BIT(TMRx->DIEN, TMR_DIEN_CC4IEN); +} + +/** + * @brief Disable capture/compare 4 interrupt (CC4IE). + * @param TMRx Timer instance + * @retval None + */ +__STATIC_INLINE void DDL_TMR_DisableIT_CC4(TMR_TypeDef *TMRx) +{ + CLEAR_BIT(TMRx->DIEN, TMR_DIEN_CC4IEN); +} + +/** + * @brief Indicates whether the capture/compare 4 interrupt (CC4IE) is enabled. + * @param TMRx Timer instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_TMR_IsEnabledIT_CC4(TMR_TypeDef *TMRx) +{ + return ((READ_BIT(TMRx->DIEN, TMR_DIEN_CC4IEN) == (TMR_DIEN_CC4IEN)) ? 1UL : 0UL); +} + +/** + * @brief Enable commutation interrupt (COMIE). + * @param TMRx Timer instance + * @retval None + */ +__STATIC_INLINE void DDL_TMR_EnableIT_COM(TMR_TypeDef *TMRx) +{ + SET_BIT(TMRx->DIEN, TMR_DIEN_COMIEN); +} + +/** + * @brief Disable commutation interrupt (COMIE). + * @param TMRx Timer instance + * @retval None + */ +__STATIC_INLINE void DDL_TMR_DisableIT_COM(TMR_TypeDef *TMRx) +{ + CLEAR_BIT(TMRx->DIEN, TMR_DIEN_COMIEN); +} + +/** + * @brief Indicates whether the commutation interrupt (COMIE) is enabled. + * @param TMRx Timer instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_TMR_IsEnabledIT_COM(TMR_TypeDef *TMRx) +{ + return ((READ_BIT(TMRx->DIEN, TMR_DIEN_COMIEN) == (TMR_DIEN_COMIEN)) ? 1UL : 0UL); +} + +/** + * @brief Enable trigger interrupt (TIE). + * @param TMRx Timer instance + * @retval None + */ +__STATIC_INLINE void DDL_TMR_EnableIT_TRIG(TMR_TypeDef *TMRx) +{ + SET_BIT(TMRx->DIEN, TMR_DIEN_TRGIEN); +} + +/** + * @brief Disable trigger interrupt (TIE). + * @param TMRx Timer instance + * @retval None + */ +__STATIC_INLINE void DDL_TMR_DisableIT_TRIG(TMR_TypeDef *TMRx) +{ + CLEAR_BIT(TMRx->DIEN, TMR_DIEN_TRGIEN); +} + +/** + * @brief Indicates whether the trigger interrupt (TIE) is enabled. + * @param TMRx Timer instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_TMR_IsEnabledIT_TRIG(TMR_TypeDef *TMRx) +{ + return ((READ_BIT(TMRx->DIEN, TMR_DIEN_TRGIEN) == (TMR_DIEN_TRGIEN)) ? 1UL : 0UL); +} + +/** + * @brief Enable break interrupt (BIE). + * @param TMRx Timer instance + * @retval None + */ +__STATIC_INLINE void DDL_TMR_EnableIT_BRK(TMR_TypeDef *TMRx) +{ + SET_BIT(TMRx->DIEN, TMR_DIEN_BRKIEN); +} + +/** + * @brief Disable break interrupt (BIE). + * @param TMRx Timer instance + * @retval None + */ +__STATIC_INLINE void DDL_TMR_DisableIT_BRK(TMR_TypeDef *TMRx) +{ + CLEAR_BIT(TMRx->DIEN, TMR_DIEN_BRKIEN); +} + +/** + * @brief Indicates whether the break interrupt (BIE) is enabled. + * @param TMRx Timer instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_TMR_IsEnabledIT_BRK(TMR_TypeDef *TMRx) +{ + return ((READ_BIT(TMRx->DIEN, TMR_DIEN_BRKIEN) == (TMR_DIEN_BRKIEN)) ? 1UL : 0UL); +} + +/** + * @} + */ + +/** @defgroup TMR_DDL_EF_DMA_Management DMA Management + * @{ + */ +/** + * @brief Enable update DMA request (UDE). + * @param TMRx Timer instance + * @retval None + */ +__STATIC_INLINE void DDL_TMR_EnableDMAReq_UPDATE(TMR_TypeDef *TMRx) +{ + SET_BIT(TMRx->DIEN, TMR_DIEN_UDIEN); +} + +/** + * @brief Disable update DMA request (UDE). + * @param TMRx Timer instance + * @retval None + */ +__STATIC_INLINE void DDL_TMR_DisableDMAReq_UPDATE(TMR_TypeDef *TMRx) +{ + CLEAR_BIT(TMRx->DIEN, TMR_DIEN_UDIEN); +} + +/** + * @brief Indicates whether the update DMA request (UDE) is enabled. + * @param TMRx Timer instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_TMR_IsEnabledDMAReq_UPDATE(TMR_TypeDef *TMRx) +{ + return ((READ_BIT(TMRx->DIEN, TMR_DIEN_UDIEN) == (TMR_DIEN_UDIEN)) ? 1UL : 0UL); +} + +/** + * @brief Enable capture/compare 1 DMA request (CC1DE). + * @param TMRx Timer instance + * @retval None + */ +__STATIC_INLINE void DDL_TMR_EnableDMAReq_CC1(TMR_TypeDef *TMRx) +{ + SET_BIT(TMRx->DIEN, TMR_DIEN_CC1DEN); +} + +/** + * @brief Disable capture/compare 1 DMA request (CC1DE). + * @param TMRx Timer instance + * @retval None + */ +__STATIC_INLINE void DDL_TMR_DisableDMAReq_CC1(TMR_TypeDef *TMRx) +{ + CLEAR_BIT(TMRx->DIEN, TMR_DIEN_CC1DEN); +} + +/** + * @brief Indicates whether the capture/compare 1 DMA request (CC1DE) is enabled. + * @param TMRx Timer instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_TMR_IsEnabledDMAReq_CC1(TMR_TypeDef *TMRx) +{ + return ((READ_BIT(TMRx->DIEN, TMR_DIEN_CC1DEN) == (TMR_DIEN_CC1DEN)) ? 1UL : 0UL); +} + +/** + * @brief Enable capture/compare 2 DMA request (CC2DE). + * @param TMRx Timer instance + * @retval None + */ +__STATIC_INLINE void DDL_TMR_EnableDMAReq_CC2(TMR_TypeDef *TMRx) +{ + SET_BIT(TMRx->DIEN, TMR_DIEN_CC2DEN); +} + +/** + * @brief Disable capture/compare 2 DMA request (CC2DE). + * @param TMRx Timer instance + * @retval None + */ +__STATIC_INLINE void DDL_TMR_DisableDMAReq_CC2(TMR_TypeDef *TMRx) +{ + CLEAR_BIT(TMRx->DIEN, TMR_DIEN_CC2DEN); +} + +/** + * @brief Indicates whether the capture/compare 2 DMA request (CC2DE) is enabled. + * @param TMRx Timer instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_TMR_IsEnabledDMAReq_CC2(TMR_TypeDef *TMRx) +{ + return ((READ_BIT(TMRx->DIEN, TMR_DIEN_CC2DEN) == (TMR_DIEN_CC2DEN)) ? 1UL : 0UL); +} + +/** + * @brief Enable capture/compare 3 DMA request (CC3DE). + * @param TMRx Timer instance + * @retval None + */ +__STATIC_INLINE void DDL_TMR_EnableDMAReq_CC3(TMR_TypeDef *TMRx) +{ + SET_BIT(TMRx->DIEN, TMR_DIEN_CC3DEN); +} + +/** + * @brief Disable capture/compare 3 DMA request (CC3DE). + * @param TMRx Timer instance + * @retval None + */ +__STATIC_INLINE void DDL_TMR_DisableDMAReq_CC3(TMR_TypeDef *TMRx) +{ + CLEAR_BIT(TMRx->DIEN, TMR_DIEN_CC3DEN); +} + +/** + * @brief Indicates whether the capture/compare 3 DMA request (CC3DE) is enabled. + * @param TMRx Timer instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_TMR_IsEnabledDMAReq_CC3(TMR_TypeDef *TMRx) +{ + return ((READ_BIT(TMRx->DIEN, TMR_DIEN_CC3DEN) == (TMR_DIEN_CC3DEN)) ? 1UL : 0UL); +} + +/** + * @brief Enable capture/compare 4 DMA request (CC4DE). + * @param TMRx Timer instance + * @retval None + */ +__STATIC_INLINE void DDL_TMR_EnableDMAReq_CC4(TMR_TypeDef *TMRx) +{ + SET_BIT(TMRx->DIEN, TMR_DIEN_CC4DEN); +} + +/** + * @brief Disable capture/compare 4 DMA request (CC4DE). + * @param TMRx Timer instance + * @retval None + */ +__STATIC_INLINE void DDL_TMR_DisableDMAReq_CC4(TMR_TypeDef *TMRx) +{ + CLEAR_BIT(TMRx->DIEN, TMR_DIEN_CC4DEN); +} + +/** + * @brief Indicates whether the capture/compare 4 DMA request (CC4DE) is enabled. + * @param TMRx Timer instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_TMR_IsEnabledDMAReq_CC4(TMR_TypeDef *TMRx) +{ + return ((READ_BIT(TMRx->DIEN, TMR_DIEN_CC4DEN) == (TMR_DIEN_CC4DEN)) ? 1UL : 0UL); +} + +/** + * @brief Enable commutation DMA request (COMDE). + * @param TMRx Timer instance + * @retval None + */ +__STATIC_INLINE void DDL_TMR_EnableDMAReq_COM(TMR_TypeDef *TMRx) +{ + SET_BIT(TMRx->DIEN, TMR_DIEN_COMDEN); +} + +/** + * @brief Disable commutation DMA request (COMDE). + * @param TMRx Timer instance + * @retval None + */ +__STATIC_INLINE void DDL_TMR_DisableDMAReq_COM(TMR_TypeDef *TMRx) +{ + CLEAR_BIT(TMRx->DIEN, TMR_DIEN_COMDEN); +} + +/** + * @brief Indicates whether the commutation DMA request (COMDE) is enabled. + * @param TMRx Timer instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_TMR_IsEnabledDMAReq_COM(TMR_TypeDef *TMRx) +{ + return ((READ_BIT(TMRx->DIEN, TMR_DIEN_COMDEN) == (TMR_DIEN_COMDEN)) ? 1UL : 0UL); +} + +/** + * @brief Enable trigger interrupt (TDE). + * @param TMRx Timer instance + * @retval None + */ +__STATIC_INLINE void DDL_TMR_EnableDMAReq_TRIG(TMR_TypeDef *TMRx) +{ + SET_BIT(TMRx->DIEN, TMR_DIEN_TRGDEN); +} + +/** + * @brief Disable trigger interrupt (TDE). + * @param TMRx Timer instance + * @retval None + */ +__STATIC_INLINE void DDL_TMR_DisableDMAReq_TRIG(TMR_TypeDef *TMRx) +{ + CLEAR_BIT(TMRx->DIEN, TMR_DIEN_TRGDEN); +} + +/** + * @brief Indicates whether the trigger interrupt (TDE) is enabled. + * @param TMRx Timer instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_TMR_IsEnabledDMAReq_TRIG(TMR_TypeDef *TMRx) +{ + return ((READ_BIT(TMRx->DIEN, TMR_DIEN_TRGDEN) == (TMR_DIEN_TRGDEN)) ? 1UL : 0UL); +} + +/** + * @} + */ + +/** @defgroup TMR_DDL_EF_EVENT_Management EVENT-Management + * @{ + */ +/** + * @brief Generate an update event. + * @param TMRx Timer instance + * @retval None + */ +__STATIC_INLINE void DDL_TMR_GenerateEvent_UPDATE(TMR_TypeDef *TMRx) +{ + SET_BIT(TMRx->CEG, TMR_CEG_UEG); +} + +/** + * @brief Generate Capture/Compare 1 event. + * @param TMRx Timer instance + * @retval None + */ +__STATIC_INLINE void DDL_TMR_GenerateEvent_CC1(TMR_TypeDef *TMRx) +{ + SET_BIT(TMRx->CEG, TMR_CEG_CC1EG); +} + +/** + * @brief Generate Capture/Compare 2 event. + * @param TMRx Timer instance + * @retval None + */ +__STATIC_INLINE void DDL_TMR_GenerateEvent_CC2(TMR_TypeDef *TMRx) +{ + SET_BIT(TMRx->CEG, TMR_CEG_CC2EG); +} + +/** + * @brief Generate Capture/Compare 3 event. + * @param TMRx Timer instance + * @retval None + */ +__STATIC_INLINE void DDL_TMR_GenerateEvent_CC3(TMR_TypeDef *TMRx) +{ + SET_BIT(TMRx->CEG, TMR_CEG_CC3EG); +} + +/** + * @brief Generate Capture/Compare 4 event. + * @param TMRx Timer instance + * @retval None + */ +__STATIC_INLINE void DDL_TMR_GenerateEvent_CC4(TMR_TypeDef *TMRx) +{ + SET_BIT(TMRx->CEG, TMR_CEG_CC4EG); +} + +/** + * @brief Generate commutation event. + * @param TMRx Timer instance + * @retval None + */ +__STATIC_INLINE void DDL_TMR_GenerateEvent_COM(TMR_TypeDef *TMRx) +{ + SET_BIT(TMRx->CEG, TMR_CEG_COMG); +} + +/** + * @brief Generate trigger event. + * @param TMRx Timer instance + * @retval None + */ +__STATIC_INLINE void DDL_TMR_GenerateEvent_TRIG(TMR_TypeDef *TMRx) +{ + SET_BIT(TMRx->CEG, TMR_CEG_TEG); +} + +/** + * @brief Generate break event. + * @param TMRx Timer instance + * @retval None + */ +__STATIC_INLINE void DDL_TMR_GenerateEvent_BRK(TMR_TypeDef *TMRx) +{ + SET_BIT(TMRx->CEG, TMR_CEG_BEG); +} + +/** + * @} + */ + +#if defined(USE_FULL_DDL_DRIVER) +/** @defgroup TMR_DDL_EF_Init Initialisation and deinitialisation functions + * @{ + */ + +ErrorStatus DDL_TMR_DeInit(TMR_TypeDef *TMRx); +void DDL_TMR_StructInit(DDL_TMR_InitTypeDef *TMR_InitStruct); +ErrorStatus DDL_TMR_Init(TMR_TypeDef *TMRx, DDL_TMR_InitTypeDef *TMR_InitStruct); +void DDL_TMR_OC_StructInit(DDL_TMR_OC_InitTypeDef *TMR_OC_InitStruct); +ErrorStatus DDL_TMR_OC_Init(TMR_TypeDef *TMRx, uint32_t Channel, DDL_TMR_OC_InitTypeDef *TMR_OC_InitStruct); +void DDL_TMR_IC_StructInit(DDL_TMR_IC_InitTypeDef *TMR_ICInitStruct); +ErrorStatus DDL_TMR_IC_Init(TMR_TypeDef *TMRx, uint32_t Channel, DDL_TMR_IC_InitTypeDef *TMR_IC_InitStruct); +void DDL_TMR_ENCODER_StructInit(DDL_TMR_ENCODER_InitTypeDef *TMR_EncoderInitStruct); +ErrorStatus DDL_TMR_ENCODER_Init(TMR_TypeDef *TMRx, DDL_TMR_ENCODER_InitTypeDef *TMR_EncoderInitStruct); +void DDL_TMR_HALLSENSOR_StructInit(DDL_TMR_HALLSENSOR_InitTypeDef *TMR_HallSensorInitStruct); +ErrorStatus DDL_TMR_HALLSENSOR_Init(TMR_TypeDef *TMRx, DDL_TMR_HALLSENSOR_InitTypeDef *TMR_HallSensorInitStruct); +void DDL_TMR_BDT_StructInit(DDL_TMR_BDT_InitTypeDef *TMR_BDTInitStruct); +ErrorStatus DDL_TMR_BDT_Init(TMR_TypeDef *TMRx, DDL_TMR_BDT_InitTypeDef *TMR_BDTInitStruct); +/** + * @} + */ +#endif /* USE_FULL_DDL_DRIVER */ + +/** + * @} + */ + +/** + * @} + */ + +#endif /* TMR1 || TMR2 || TMR3 || TMR4 || TMR5 || TMR6 || TMR7 || TMR8 || TMR9 || TMR10 || TMR11 || TMR12 || TMR13 || TMR14 */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* APM32F4xx_DDL_TMR_H */ diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_usart.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_usart.h new file mode 100644 index 0000000000..ce938771f6 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_usart.h @@ -0,0 +1,2370 @@ +/** + * + * @file apm32f4xx_ddl_usart.h + * @brief Header file of USART DDL module. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef APM32F4xx_DDL_USART_H +#define APM32F4xx_DDL_USART_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx.h" + +/** @addtogroup APM32F4xx_DDL_Driver + * @{ + */ + +#if defined (USART1) || defined (USART2) || defined (USART3) || defined (USART6) || defined (UART4) || defined (UART5) || defined (UART7) || defined (UART8) || defined (UART9) || defined (UART10) + +/** @defgroup USART_DDL USART + * @{ + */ + +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ + +/* Private constants ---------------------------------------------------------*/ +/** @defgroup USART_DDL_Private_Constants USART Private Constants + * @{ + */ + +/* Defines used for the bit position in the register and perform offsets*/ +#define USART_POSITION_GTPR_GT USART_GTPSC_GRDT_Pos +/** + * @} + */ + +/* Private macros ------------------------------------------------------------*/ +#if defined(USE_FULL_DDL_DRIVER) +/** @defgroup USART_DDL_Private_Macros USART Private Macros + * @{ + */ +/** + * @} + */ +#endif /*USE_FULL_DDL_DRIVER*/ + +/* Exported types ------------------------------------------------------------*/ +#if defined(USE_FULL_DDL_DRIVER) +/** @defgroup USART_DDL_ES_INIT USART Exported Init structures + * @{ + */ + +/** + * @brief LL USART Init Structure definition + */ +typedef struct +{ + uint32_t BaudRate; /*!< This field defines expected Usart communication baud rate. + + This feature can be modified afterwards using unitary function @ref DDL_USART_SetBaudRate().*/ + + uint32_t DataWidth; /*!< Specifies the number of data bits transmitted or received in a frame. + This parameter can be a value of @ref USART_DDL_EC_DATAWIDTH. + + This feature can be modified afterwards using unitary function @ref DDL_USART_SetDataWidth().*/ + + uint32_t StopBits; /*!< Specifies the number of stop bits transmitted. + This parameter can be a value of @ref USART_DDL_EC_STOPBITS. + + This feature can be modified afterwards using unitary function @ref DDL_USART_SetStopBitsLength().*/ + + uint32_t Parity; /*!< Specifies the parity mode. + This parameter can be a value of @ref USART_DDL_EC_PARITY. + + This feature can be modified afterwards using unitary function @ref DDL_USART_SetParity().*/ + + uint32_t TransferDirection; /*!< Specifies whether the Receive and/or Transmit mode is enabled or disabled. + This parameter can be a value of @ref USART_DDL_EC_DIRECTION. + + This feature can be modified afterwards using unitary function @ref DDL_USART_SetTransferDirection().*/ + + uint32_t HardwareFlowControl; /*!< Specifies whether the hardware flow control mode is enabled or disabled. + This parameter can be a value of @ref USART_DDL_EC_HWCONTROL. + + This feature can be modified afterwards using unitary function @ref DDL_USART_SetHWFlowCtrl().*/ + + uint32_t OverSampling; /*!< Specifies whether USART oversampling mode is 16 or 8. + This parameter can be a value of @ref USART_DDL_EC_OVERSAMPLING. + + This feature can be modified afterwards using unitary function @ref DDL_USART_SetOverSampling().*/ + +} DDL_USART_InitTypeDef; + +/** + * @brief LL USART Clock Init Structure definition + */ +typedef struct +{ + uint32_t ClockOutput; /*!< Specifies whether the USART clock is enabled or disabled. + This parameter can be a value of @ref USART_DDL_EC_CLOCK. + + USART HW configuration can be modified afterwards using unitary functions + @ref DDL_USART_EnableSCLKOutput() or @ref DDL_USART_DisableSCLKOutput(). + For more details, refer to description of this function. */ + + uint32_t ClockPolarity; /*!< Specifies the steady state of the serial clock. + This parameter can be a value of @ref USART_DDL_EC_POLARITY. + + USART HW configuration can be modified afterwards using unitary functions @ref DDL_USART_SetClockPolarity(). + For more details, refer to description of this function. */ + + uint32_t ClockPhase; /*!< Specifies the clock transition on which the bit capture is made. + This parameter can be a value of @ref USART_DDL_EC_PHASE. + + USART HW configuration can be modified afterwards using unitary functions @ref DDL_USART_SetClockPhase(). + For more details, refer to description of this function. */ + + uint32_t LastBitClockPulse; /*!< Specifies whether the clock pulse corresponding to the last transmitted + data bit (MSB) has to be output on the SCLK pin in synchronous mode. + This parameter can be a value of @ref USART_DDL_EC_LASTCLKPULSE. + + USART HW configuration can be modified afterwards using unitary functions @ref DDL_USART_SetLastClkPulseOutput(). + For more details, refer to description of this function. */ + +} DDL_USART_ClockInitTypeDef; + +/** + * @} + */ +#endif /* USE_FULL_DDL_DRIVER */ + +/* Exported constants --------------------------------------------------------*/ +/** @defgroup USART_DDL_Exported_Constants USART Exported Constants + * @{ + */ + +/** @defgroup USART_DDL_EC_GET_FLAG Get Flags Defines + * @brief Flags defines which can be used with DDL_USART_ReadReg function + * @{ + */ +#define DDL_USART_STS_PEFLG USART_STS_PEFLG /*!< Parity error flag */ +#define DDL_USART_STS_FEFLG USART_STS_FEFLG /*!< Framing error flag */ +#define DDL_USART_STS_NEFLG USART_STS_NEFLG /*!< Noise detected flag */ +#define DDL_USART_STS_OVREFLG USART_STS_OVREFLG /*!< Overrun error flag */ +#define DDL_USART_STS_IDLEFLG USART_STS_IDLEFLG /*!< Idle line detected flag */ +#define DDL_USART_STS_RXBNEFLG USART_STS_RXBNEFLG /*!< Read data register not empty flag */ +#define DDL_USART_STS_TXCFLG USART_STS_TXCFLG /*!< Transmission complete flag */ +#define DDL_USART_STS_TXBEFLG USART_STS_TXBEFLG /*!< Transmit data register empty flag */ +#define DDL_USART_STS_LBDFLG USART_STS_LBDFLG /*!< LIN break detection flag */ +#define DDL_USART_STS_CTSFLG USART_STS_CTSFLG /*!< CTS flag */ +/** + * @} + */ + +/** @defgroup USART_DDL_EC_IT IT Defines + * @brief IT defines which can be used with DDL_USART_ReadReg and DDL_USART_WriteReg functions + * @{ + */ +#define DDL_USART_CTRL1_IDLEIEN USART_CTRL1_IDLEIEN /*!< IDLE interrupt enable */ +#define DDL_USART_CTRL1_RXBNEIEN USART_CTRL1_RXBNEIEN /*!< Read data register not empty interrupt enable */ +#define DDL_USART_CTRL1_TXCIEN USART_CTRL1_TXCIEN /*!< Transmission complete interrupt enable */ +#define DDL_USART_CTRL1_TXBEIEN USART_CTRL1_TXBEIEN /*!< Transmit data register empty interrupt enable */ +#define DDL_USART_CTRL1_PEIEN USART_CTRL1_PEIEN /*!< Parity error */ +#define DDL_USART_CTRL2_LBDIEN USART_CTRL2_LBDIEN /*!< LIN break detection interrupt enable */ +#define DDL_USART_CTRL3_ERRIEN USART_CTRL3_ERRIEN /*!< Error interrupt enable */ +#define DDL_USART_CTRL3_CTSIEN USART_CTRL3_CTSIEN /*!< CTS interrupt enable */ +/** + * @} + */ + +/** @defgroup USART_DDL_EC_DIRECTION Communication Direction + * @{ + */ +#define DDL_USART_DIRECTION_NONE 0x00000000U /*!< Transmitter and Receiver are disabled */ +#define DDL_USART_DIRECTION_RX USART_CTRL1_RXEN /*!< Transmitter is disabled and Receiver is enabled */ +#define DDL_USART_DIRECTION_TX USART_CTRL1_TXEN /*!< Transmitter is enabled and Receiver is disabled */ +#define DDL_USART_DIRECTION_TX_RX (USART_CTRL1_TXEN |USART_CTRL1_RXEN) /*!< Transmitter and Receiver are enabled */ +/** + * @} + */ + +/** @defgroup USART_DDL_EC_PARITY Parity Control + * @{ + */ +#define DDL_USART_PARITY_NONE 0x00000000U /*!< Parity control disabled */ +#define DDL_USART_PARITY_EVEN USART_CTRL1_PCEN /*!< Parity control enabled and Even Parity is selected */ +#define DDL_USART_PARITY_ODD (USART_CTRL1_PCEN | USART_CTRL1_PCFG) /*!< Parity control enabled and Odd Parity is selected */ +/** + * @} + */ + +/** @defgroup USART_DDL_EC_WAKEUP Wakeup + * @{ + */ +#define DDL_USART_WAKEUP_IDLELINE 0x00000000U /*!< USART wake up from Mute mode on Idle Line */ +#define DDL_USART_WAKEUP_ADDRESSMARK USART_CTRL1_WUPMCFG /*!< USART wake up from Mute mode on Address Mark */ +/** + * @} + */ + +/** @defgroup USART_DDL_EC_DATAWIDTH Datawidth + * @{ + */ +#define DDL_USART_DATAWIDTH_8B 0x00000000U /*!< 8 bits word length : Start bit, 8 data bits, n stop bits */ +#define DDL_USART_DATAWIDTH_9B USART_CTRL1_DBLCFG /*!< 9 bits word length : Start bit, 9 data bits, n stop bits */ +/** + * @} + */ + +/** @defgroup USART_DDL_EC_OVERSAMPLING Oversampling + * @{ + */ +#define DDL_USART_OVERSAMPLING_16 0x00000000U /*!< Oversampling by 16 */ +#define DDL_USART_OVERSAMPLING_8 USART_CTRL1_OSMCFG /*!< Oversampling by 8 */ +/** + * @} + */ + +#if defined(USE_FULL_DDL_DRIVER) +/** @defgroup USART_DDL_EC_CLOCK Clock Signal + * @{ + */ + +#define DDL_USART_CLOCK_DISABLE 0x00000000U /*!< Clock signal not provided */ +#define DDL_USART_CLOCK_ENABLE USART_CTRL2_CLKEN /*!< Clock signal provided */ +/** + * @} + */ +#endif /*USE_FULL_DDL_DRIVER*/ + +/** @defgroup USART_DDL_EC_LASTCLKPULSE Last Clock Pulse + * @{ + */ +#define DDL_USART_LASTCLKPULSE_NO_OUTPUT 0x00000000U /*!< The clock pulse of the last data bit is not output to the SCLK pin */ +#define DDL_USART_LASTCLKPULSE_OUTPUT USART_CTRL2_LBCPOEN /*!< The clock pulse of the last data bit is output to the SCLK pin */ +/** + * @} + */ + +/** @defgroup USART_DDL_EC_PHASE Clock Phase + * @{ + */ +#define DDL_USART_PHASE_1EDGE 0x00000000U /*!< The first clock transition is the first data capture edge */ +#define DDL_USART_PHASE_2EDGE USART_CTRL2_CPHA /*!< The second clock transition is the first data capture edge */ +/** + * @} + */ + +/** @defgroup USART_DDL_EC_POLARITY Clock Polarity + * @{ + */ +#define DDL_USART_POLARITY_LOW 0x00000000U /*!< Steady low value on SCLK pin outside transmission window*/ +#define DDL_USART_POLARITY_HIGH USART_CTRL2_CPOL /*!< Steady high value on SCLK pin outside transmission window */ +/** + * @} + */ + +/** @defgroup USART_DDL_EC_STOPBITS Stop Bits + * @{ + */ +#define DDL_USART_STOPBITS_0_5 USART_CTRL2_STOPCFG_0 /*!< 0.5 stop bit */ +#define DDL_USART_STOPBITS_1 0x00000000U /*!< 1 stop bit */ +#define DDL_USART_STOPBITS_1_5 (USART_CTRL2_STOPCFG_0 | USART_CTRL2_STOPCFG_1) /*!< 1.5 stop bits */ +#define DDL_USART_STOPBITS_2 USART_CTRL2_STOPCFG_1 /*!< 2 stop bits */ +/** + * @} + */ + +/** @defgroup USART_DDL_EC_HWCONTROL Hardware Control + * @{ + */ +#define DDL_USART_HWCONTROL_NONE 0x00000000U /*!< CTS and RTS hardware flow control disabled */ +#define DDL_USART_HWCONTROL_RTS USART_CTRL3_RTSEN /*!< RTS output enabled, data is only requested when there is space in the receive buffer */ +#define DDL_USART_HWCONTROL_CTS USART_CTRL3_CTSEN /*!< CTS mode enabled, data is only transmitted when the nCTS input is asserted (tied to 0) */ +#define DDL_USART_HWCONTROL_RTS_CTS (USART_CTRL3_RTSEN | USART_CTRL3_CTSEN) /*!< CTS and RTS hardware flow control enabled */ +/** + * @} + */ + +/** @defgroup USART_DDL_EC_IRDA_POWER IrDA Power + * @{ + */ +#define DDL_USART_IRDA_POWER_NORMAL 0x00000000U /*!< IrDA normal power mode */ +#define DDL_USART_IRDA_POWER_LOW USART_CTRL3_IRLPEN /*!< IrDA low power mode */ +/** + * @} + */ + +/** @defgroup USART_DDL_EC_LINBREAK_DETECT LIN Break Detection Length + * @{ + */ +#define DDL_USART_LINBREAK_DETECT_10B 0x00000000U /*!< 10-bit break detection method selected */ +#define DDL_USART_LINBREAK_DETECT_11B USART_CTRL2_LBDLCFG /*!< 11-bit break detection method selected */ +/** + * @} + */ + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ +/** @defgroup USART_DDL_Exported_Macros USART Exported Macros + * @{ + */ + +/** @defgroup USART_DDL_EM_WRITE_READ Common Write and read registers Macros + * @{ + */ + +/** + * @brief Write a value in USART register + * @param __INSTANCE__ USART Instance + * @param __REG__ Register to be written + * @param __VALUE__ Value to be written in the register + * @retval None + */ +#define DDL_USART_WriteReg(__INSTANCE__, __REG__, __VALUE__) WRITE_REG(__INSTANCE__->__REG__, (__VALUE__)) + +/** + * @brief Read a value in USART register + * @param __INSTANCE__ USART Instance + * @param __REG__ Register to be read + * @retval Register value + */ +#define DDL_USART_ReadReg(__INSTANCE__, __REG__) READ_REG(__INSTANCE__->__REG__) +/** + * @} + */ + +/** @defgroup USART_DDL_EM_Exported_Macros_Helper Exported_Macros_Helper + * @{ + */ + +/** + * @brief Compute USARTDIV value according to Peripheral Clock and + * expected Baud Rate in 8 bits sampling mode (32 bits value of USARTDIV is returned) + * @param __PERIPHCLK__ Peripheral Clock frequency used for USART instance + * @param __BAUDRATE__ Baud rate value to achieve + * @retval USARTDIV value to be used for BRR register filling in OverSampling_8 case + */ +#define __DDL_USART_DIV_SAMPLING8_100(__PERIPHCLK__, __BAUDRATE__) ((uint32_t)((((uint64_t)(__PERIPHCLK__))*25)/(2*((uint64_t)(__BAUDRATE__))))) +#define __DDL_USART_DIVMANT_SAMPLING8(__PERIPHCLK__, __BAUDRATE__) (__DDL_USART_DIV_SAMPLING8_100((__PERIPHCLK__), (__BAUDRATE__))/100) +#define __DDL_USART_DIVFRAQ_SAMPLING8(__PERIPHCLK__, __BAUDRATE__) ((((__DDL_USART_DIV_SAMPLING8_100((__PERIPHCLK__), (__BAUDRATE__)) - (__DDL_USART_DIVMANT_SAMPLING8((__PERIPHCLK__), (__BAUDRATE__)) * 100)) * 8)\ + + 50) / 100) +/* UART BRR = mantissa + overflow + fraction + = (UART DIVMANT << 4) + ((UART DIVFRAQ & 0xF8) << 1) + (UART DIVFRAQ & 0x07) */ +#define __DDL_USART_DIV_SAMPLING8(__PERIPHCLK__, __BAUDRATE__) (((__DDL_USART_DIVMANT_SAMPLING8((__PERIPHCLK__), (__BAUDRATE__)) << 4) + \ + ((__DDL_USART_DIVFRAQ_SAMPLING8((__PERIPHCLK__), (__BAUDRATE__)) & 0xF8) << 1)) + \ + (__DDL_USART_DIVFRAQ_SAMPLING8((__PERIPHCLK__), (__BAUDRATE__)) & 0x07)) + +/** + * @brief Compute USARTDIV value according to Peripheral Clock and + * expected Baud Rate in 16 bits sampling mode (32 bits value of USARTDIV is returned) + * @param __PERIPHCLK__ Peripheral Clock frequency used for USART instance + * @param __BAUDRATE__ Baud rate value to achieve + * @retval USARTDIV value to be used for BRR register filling in OverSampling_16 case + */ +#define __DDL_USART_DIV_SAMPLING16_100(__PERIPHCLK__, __BAUDRATE__) ((uint32_t)((((uint64_t)(__PERIPHCLK__))*25)/(4*((uint64_t)(__BAUDRATE__))))) +#define __DDL_USART_DIVMANT_SAMPLING16(__PERIPHCLK__, __BAUDRATE__) (__DDL_USART_DIV_SAMPLING16_100((__PERIPHCLK__), (__BAUDRATE__))/100) +#define __DDL_USART_DIVFRAQ_SAMPLING16(__PERIPHCLK__, __BAUDRATE__) ((((__DDL_USART_DIV_SAMPLING16_100((__PERIPHCLK__), (__BAUDRATE__)) - (__DDL_USART_DIVMANT_SAMPLING16((__PERIPHCLK__), (__BAUDRATE__)) * 100)) * 16)\ + + 50) / 100) +/* USART BRR = mantissa + overflow + fraction + = (USART DIVMANT << 4) + (USART DIVFRAQ & 0xF0) + (USART DIVFRAQ & 0x0F) */ +#define __DDL_USART_DIV_SAMPLING16(__PERIPHCLK__, __BAUDRATE__) (((__DDL_USART_DIVMANT_SAMPLING16((__PERIPHCLK__), (__BAUDRATE__)) << 4) + \ + (__DDL_USART_DIVFRAQ_SAMPLING16((__PERIPHCLK__), (__BAUDRATE__)) & 0xF0)) + \ + (__DDL_USART_DIVFRAQ_SAMPLING16((__PERIPHCLK__), (__BAUDRATE__)) & 0x0F)) + +/** + * @} + */ + +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ + +/** @defgroup USART_DDL_Exported_Functions USART Exported Functions + * @{ + */ + +/** @defgroup USART_DDL_EF_Configuration Configuration functions + * @{ + */ + +/** + * @brief USART Enable + * @param USARTx USART Instance + * @retval None + */ +__STATIC_INLINE void DDL_USART_Enable(USART_TypeDef *USARTx) +{ + SET_BIT(USARTx->CTRL1, USART_CTRL1_UEN); +} + +/** + * @brief USART Disable (all USART prescalers and outputs are disabled) + * @note When USART is disabled, USART prescalers and outputs are stopped immediately, + * and current operations are discarded. The configuration of the USART is kept, but all the status + * flags, in the USARTx_SR are set to their default values. + * @param USARTx USART Instance + * @retval None + */ +__STATIC_INLINE void DDL_USART_Disable(USART_TypeDef *USARTx) +{ + CLEAR_BIT(USARTx->CTRL1, USART_CTRL1_UEN); +} + +/** + * @brief Indicate if USART is enabled + * @param USARTx USART Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_USART_IsEnabled(USART_TypeDef *USARTx) +{ + return (READ_BIT(USARTx->CTRL1, USART_CTRL1_UEN) == (USART_CTRL1_UEN)); +} + +/** + * @brief Receiver Enable (Receiver is enabled and begins searching for a start bit) + * @param USARTx USART Instance + * @retval None + */ +__STATIC_INLINE void DDL_USART_EnableDirectionRx(USART_TypeDef *USARTx) +{ + ATOMIC_SET_BIT(USARTx->CTRL1, USART_CTRL1_RXEN); +} + +/** + * @brief Receiver Disable + * @param USARTx USART Instance + * @retval None + */ +__STATIC_INLINE void DDL_USART_DisableDirectionRx(USART_TypeDef *USARTx) +{ + ATOMIC_CLEAR_BIT(USARTx->CTRL1, USART_CTRL1_RXEN); +} + +/** + * @brief Transmitter Enable + * @param USARTx USART Instance + * @retval None + */ +__STATIC_INLINE void DDL_USART_EnableDirectionTx(USART_TypeDef *USARTx) +{ + ATOMIC_SET_BIT(USARTx->CTRL1, USART_CTRL1_TXEN); +} + +/** + * @brief Transmitter Disable + * @param USARTx USART Instance + * @retval None + */ +__STATIC_INLINE void DDL_USART_DisableDirectionTx(USART_TypeDef *USARTx) +{ + ATOMIC_CLEAR_BIT(USARTx->CTRL1, USART_CTRL1_TXEN); +} + +/** + * @brief Configure simultaneously enabled/disabled states + * of Transmitter and Receiver + * @param USARTx USART Instance + * @param TransferDirection This parameter can be one of the following values: + * @arg @ref DDL_USART_DIRECTION_NONE + * @arg @ref DDL_USART_DIRECTION_RX + * @arg @ref DDL_USART_DIRECTION_TX + * @arg @ref DDL_USART_DIRECTION_TX_RX + * @retval None + */ +__STATIC_INLINE void DDL_USART_SetTransferDirection(USART_TypeDef *USARTx, uint32_t TransferDirection) +{ + ATOMIC_MODIFY_REG(USARTx->CTRL1, USART_CTRL1_RXEN | USART_CTRL1_TXEN, TransferDirection); +} + +/** + * @brief Return enabled/disabled states of Transmitter and Receiver + * @param USARTx USART Instance + * @retval Returned value can be one of the following values: + * @arg @ref DDL_USART_DIRECTION_NONE + * @arg @ref DDL_USART_DIRECTION_RX + * @arg @ref DDL_USART_DIRECTION_TX + * @arg @ref DDL_USART_DIRECTION_TX_RX + */ +__STATIC_INLINE uint32_t DDL_USART_GetTransferDirection(USART_TypeDef *USARTx) +{ + return (uint32_t)(READ_BIT(USARTx->CTRL1, USART_CTRL1_RXEN | USART_CTRL1_TXEN)); +} + +/** + * @brief Configure Parity (enabled/disabled and parity mode if enabled). + * @note This function selects if hardware parity control (generation and detection) is enabled or disabled. + * When the parity control is enabled (Odd or Even), computed parity bit is inserted at the MSB position + * (9th or 8th bit depending on data width) and parity is checked on the received data. + * @param USARTx USART Instance + * @param Parity This parameter can be one of the following values: + * @arg @ref DDL_USART_PARITY_NONE + * @arg @ref DDL_USART_PARITY_EVEN + * @arg @ref DDL_USART_PARITY_ODD + * @retval None + */ +__STATIC_INLINE void DDL_USART_SetParity(USART_TypeDef *USARTx, uint32_t Parity) +{ + MODIFY_REG(USARTx->CTRL1, USART_CTRL1_PCFG | USART_CTRL1_PCEN, Parity); +} + +/** + * @brief Return Parity configuration (enabled/disabled and parity mode if enabled) + * @param USARTx USART Instance + * @retval Returned value can be one of the following values: + * @arg @ref DDL_USART_PARITY_NONE + * @arg @ref DDL_USART_PARITY_EVEN + * @arg @ref DDL_USART_PARITY_ODD + */ +__STATIC_INLINE uint32_t DDL_USART_GetParity(USART_TypeDef *USARTx) +{ + return (uint32_t)(READ_BIT(USARTx->CTRL1, USART_CTRL1_PCFG | USART_CTRL1_PCEN)); +} + +/** + * @brief Set Receiver Wake Up method from Mute mode. + * @param USARTx USART Instance + * @param Method This parameter can be one of the following values: + * @arg @ref DDL_USART_WAKEUP_IDLELINE + * @arg @ref DDL_USART_WAKEUP_ADDRESSMARK + * @retval None + */ +__STATIC_INLINE void DDL_USART_SetWakeUpMethod(USART_TypeDef *USARTx, uint32_t Method) +{ + MODIFY_REG(USARTx->CTRL1, USART_CTRL1_WUPMCFG, Method); +} + +/** + * @brief Return Receiver Wake Up method from Mute mode + * @param USARTx USART Instance + * @retval Returned value can be one of the following values: + * @arg @ref DDL_USART_WAKEUP_IDLELINE + * @arg @ref DDL_USART_WAKEUP_ADDRESSMARK + */ +__STATIC_INLINE uint32_t DDL_USART_GetWakeUpMethod(USART_TypeDef *USARTx) +{ + return (uint32_t)(READ_BIT(USARTx->CTRL1, USART_CTRL1_WUPMCFG)); +} + +/** + * @brief Set Word length (i.e. nb of data bits, excluding start and stop bits) + * @param USARTx USART Instance + * @param DataWidth This parameter can be one of the following values: + * @arg @ref DDL_USART_DATAWIDTH_8B + * @arg @ref DDL_USART_DATAWIDTH_9B + * @retval None + */ +__STATIC_INLINE void DDL_USART_SetDataWidth(USART_TypeDef *USARTx, uint32_t DataWidth) +{ + MODIFY_REG(USARTx->CTRL1, USART_CTRL1_DBLCFG, DataWidth); +} + +/** + * @brief Return Word length (i.e. nb of data bits, excluding start and stop bits) + * @param USARTx USART Instance + * @retval Returned value can be one of the following values: + * @arg @ref DDL_USART_DATAWIDTH_8B + * @arg @ref DDL_USART_DATAWIDTH_9B + */ +__STATIC_INLINE uint32_t DDL_USART_GetDataWidth(USART_TypeDef *USARTx) +{ + return (uint32_t)(READ_BIT(USARTx->CTRL1, USART_CTRL1_DBLCFG)); +} + +/** + * @brief Set Oversampling to 8-bit or 16-bit mode + * @param USARTx USART Instance + * @param OverSampling This parameter can be one of the following values: + * @arg @ref DDL_USART_OVERSAMPLING_16 + * @arg @ref DDL_USART_OVERSAMPLING_8 + * @retval None + */ +__STATIC_INLINE void DDL_USART_SetOverSampling(USART_TypeDef *USARTx, uint32_t OverSampling) +{ + MODIFY_REG(USARTx->CTRL1, USART_CTRL1_OSMCFG, OverSampling); +} + +/** + * @brief Return Oversampling mode + * @param USARTx USART Instance + * @retval Returned value can be one of the following values: + * @arg @ref DDL_USART_OVERSAMPLING_16 + * @arg @ref DDL_USART_OVERSAMPLING_8 + */ +__STATIC_INLINE uint32_t DDL_USART_GetOverSampling(USART_TypeDef *USARTx) +{ + return (uint32_t)(READ_BIT(USARTx->CTRL1, USART_CTRL1_OSMCFG)); +} + +/** + * @brief Configure if Clock pulse of the last data bit is output to the SCLK pin or not + * @note Macro @ref IS_USART_INSTANCE(USARTx) can be used to check whether or not + * Synchronous mode is supported by the USARTx instance. + * @param USARTx USART Instance + * @param LastBitClockPulse This parameter can be one of the following values: + * @arg @ref DDL_USART_LASTCLKPULSE_NO_OUTPUT + * @arg @ref DDL_USART_LASTCLKPULSE_OUTPUT + * @retval None + */ +__STATIC_INLINE void DDL_USART_SetLastClkPulseOutput(USART_TypeDef *USARTx, uint32_t LastBitClockPulse) +{ + MODIFY_REG(USARTx->CTRL2, USART_CTRL2_LBCPOEN, LastBitClockPulse); +} + +/** + * @brief Retrieve Clock pulse of the last data bit output configuration + * (Last bit Clock pulse output to the SCLK pin or not) + * @note Macro @ref IS_USART_INSTANCE(USARTx) can be used to check whether or not + * Synchronous mode is supported by the USARTx instance. + * @param USARTx USART Instance + * @retval Returned value can be one of the following values: + * @arg @ref DDL_USART_LASTCLKPULSE_NO_OUTPUT + * @arg @ref DDL_USART_LASTCLKPULSE_OUTPUT + */ +__STATIC_INLINE uint32_t DDL_USART_GetLastClkPulseOutput(USART_TypeDef *USARTx) +{ + return (uint32_t)(READ_BIT(USARTx->CTRL2, USART_CTRL2_LBCPOEN)); +} + +/** + * @brief Select the phase of the clock output on the SCLK pin in synchronous mode + * @note Macro @ref IS_USART_INSTANCE(USARTx) can be used to check whether or not + * Synchronous mode is supported by the USARTx instance. + * @param USARTx USART Instance + * @param ClockPhase This parameter can be one of the following values: + * @arg @ref DDL_USART_PHASE_1EDGE + * @arg @ref DDL_USART_PHASE_2EDGE + * @retval None + */ +__STATIC_INLINE void DDL_USART_SetClockPhase(USART_TypeDef *USARTx, uint32_t ClockPhase) +{ + MODIFY_REG(USARTx->CTRL2, USART_CTRL2_CPHA, ClockPhase); +} + +/** + * @brief Return phase of the clock output on the SCLK pin in synchronous mode + * @note Macro @ref IS_USART_INSTANCE(USARTx) can be used to check whether or not + * Synchronous mode is supported by the USARTx instance. + * @param USARTx USART Instance + * @retval Returned value can be one of the following values: + * @arg @ref DDL_USART_PHASE_1EDGE + * @arg @ref DDL_USART_PHASE_2EDGE + */ +__STATIC_INLINE uint32_t DDL_USART_GetClockPhase(USART_TypeDef *USARTx) +{ + return (uint32_t)(READ_BIT(USARTx->CTRL2, USART_CTRL2_CPHA)); +} + +/** + * @brief Select the polarity of the clock output on the SCLK pin in synchronous mode + * @note Macro @ref IS_USART_INSTANCE(USARTx) can be used to check whether or not + * Synchronous mode is supported by the USARTx instance. + * @param USARTx USART Instance + * @param ClockPolarity This parameter can be one of the following values: + * @arg @ref DDL_USART_POLARITY_LOW + * @arg @ref DDL_USART_POLARITY_HIGH + * @retval None + */ +__STATIC_INLINE void DDL_USART_SetClockPolarity(USART_TypeDef *USARTx, uint32_t ClockPolarity) +{ + MODIFY_REG(USARTx->CTRL2, USART_CTRL2_CPOL, ClockPolarity); +} + +/** + * @brief Return polarity of the clock output on the SCLK pin in synchronous mode + * @note Macro @ref IS_USART_INSTANCE(USARTx) can be used to check whether or not + * Synchronous mode is supported by the USARTx instance. + * @param USARTx USART Instance + * @retval Returned value can be one of the following values: + * @arg @ref DDL_USART_POLARITY_LOW + * @arg @ref DDL_USART_POLARITY_HIGH + */ +__STATIC_INLINE uint32_t DDL_USART_GetClockPolarity(USART_TypeDef *USARTx) +{ + return (uint32_t)(READ_BIT(USARTx->CTRL2, USART_CTRL2_CPOL)); +} + +/** + * @brief Configure Clock signal format (Phase Polarity and choice about output of last bit clock pulse) + * @note Macro @ref IS_USART_INSTANCE(USARTx) can be used to check whether or not + * Synchronous mode is supported by the USARTx instance. + * @note Call of this function is equivalent to following function call sequence : + * - Clock Phase configuration using @ref DDL_USART_SetClockPhase() function + * - Clock Polarity configuration using @ref DDL_USART_SetClockPolarity() function + * - Output of Last bit Clock pulse configuration using @ref DDL_USART_SetLastClkPulseOutput() function + * @param USARTx USART Instance + * @param Phase This parameter can be one of the following values: + * @arg @ref DDL_USART_PHASE_1EDGE + * @arg @ref DDL_USART_PHASE_2EDGE + * @param Polarity This parameter can be one of the following values: + * @arg @ref DDL_USART_POLARITY_LOW + * @arg @ref DDL_USART_POLARITY_HIGH + * @param LBCPOutput This parameter can be one of the following values: + * @arg @ref DDL_USART_LASTCLKPULSE_NO_OUTPUT + * @arg @ref DDL_USART_LASTCLKPULSE_OUTPUT + * @retval None + */ +__STATIC_INLINE void DDL_USART_ConfigClock(USART_TypeDef *USARTx, uint32_t Phase, uint32_t Polarity, uint32_t LBCPOutput) +{ + MODIFY_REG(USARTx->CTRL2, USART_CTRL2_CPHA | USART_CTRL2_CPOL | USART_CTRL2_LBCPOEN, Phase | Polarity | LBCPOutput); +} + +/** + * @brief Enable Clock output on SCLK pin + * @note Macro @ref IS_USART_INSTANCE(USARTx) can be used to check whether or not + * Synchronous mode is supported by the USARTx instance. + * @param USARTx USART Instance + * @retval None + */ +__STATIC_INLINE void DDL_USART_EnableSCLKOutput(USART_TypeDef *USARTx) +{ + SET_BIT(USARTx->CTRL2, USART_CTRL2_CLKEN); +} + +/** + * @brief Disable Clock output on SCLK pin + * @note Macro @ref IS_USART_INSTANCE(USARTx) can be used to check whether or not + * Synchronous mode is supported by the USARTx instance. + * @param USARTx USART Instance + * @retval None + */ +__STATIC_INLINE void DDL_USART_DisableSCLKOutput(USART_TypeDef *USARTx) +{ + CLEAR_BIT(USARTx->CTRL2, USART_CTRL2_CLKEN); +} + +/** + * @brief Indicate if Clock output on SCLK pin is enabled + * @note Macro @ref IS_USART_INSTANCE(USARTx) can be used to check whether or not + * Synchronous mode is supported by the USARTx instance. + * @param USARTx USART Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_USART_IsEnabledSCLKOutput(USART_TypeDef *USARTx) +{ + return (READ_BIT(USARTx->CTRL2, USART_CTRL2_CLKEN) == (USART_CTRL2_CLKEN)); +} + +/** + * @brief Set the length of the stop bits + * @param USARTx USART Instance + * @param StopBits This parameter can be one of the following values: + * @arg @ref DDL_USART_STOPBITS_0_5 + * @arg @ref DDL_USART_STOPBITS_1 + * @arg @ref DDL_USART_STOPBITS_1_5 + * @arg @ref DDL_USART_STOPBITS_2 + * @retval None + */ +__STATIC_INLINE void DDL_USART_SetStopBitsLength(USART_TypeDef *USARTx, uint32_t StopBits) +{ + MODIFY_REG(USARTx->CTRL2, USART_CTRL2_STOPCFG, StopBits); +} + +/** + * @brief Retrieve the length of the stop bits + * @param USARTx USART Instance + * @retval Returned value can be one of the following values: + * @arg @ref DDL_USART_STOPBITS_0_5 + * @arg @ref DDL_USART_STOPBITS_1 + * @arg @ref DDL_USART_STOPBITS_1_5 + * @arg @ref DDL_USART_STOPBITS_2 + */ +__STATIC_INLINE uint32_t DDL_USART_GetStopBitsLength(USART_TypeDef *USARTx) +{ + return (uint32_t)(READ_BIT(USARTx->CTRL2, USART_CTRL2_STOPCFG)); +} + +/** + * @brief Configure Character frame format (Datawidth, Parity control, Stop Bits) + * @note Call of this function is equivalent to following function call sequence : + * - Data Width configuration using @ref DDL_USART_SetDataWidth() function + * - Parity Control and mode configuration using @ref DDL_USART_SetParity() function + * - Stop bits configuration using @ref DDL_USART_SetStopBitsLength() function + * @param USARTx USART Instance + * @param DataWidth This parameter can be one of the following values: + * @arg @ref DDL_USART_DATAWIDTH_8B + * @arg @ref DDL_USART_DATAWIDTH_9B + * @param Parity This parameter can be one of the following values: + * @arg @ref DDL_USART_PARITY_NONE + * @arg @ref DDL_USART_PARITY_EVEN + * @arg @ref DDL_USART_PARITY_ODD + * @param StopBits This parameter can be one of the following values: + * @arg @ref DDL_USART_STOPBITS_0_5 + * @arg @ref DDL_USART_STOPBITS_1 + * @arg @ref DDL_USART_STOPBITS_1_5 + * @arg @ref DDL_USART_STOPBITS_2 + * @retval None + */ +__STATIC_INLINE void DDL_USART_ConfigCharacter(USART_TypeDef *USARTx, uint32_t DataWidth, uint32_t Parity, + uint32_t StopBits) +{ + MODIFY_REG(USARTx->CTRL1, USART_CTRL1_PCFG | USART_CTRL1_PCEN | USART_CTRL1_DBLCFG, Parity | DataWidth); + MODIFY_REG(USARTx->CTRL2, USART_CTRL2_STOPCFG, StopBits); +} + +/** + * @brief Set Address of the USART node. + * @note This is used in multiprocessor communication during Mute mode or Stop mode, + * for wake up with address mark detection. + * @param USARTx USART Instance + * @param NodeAddress 4 bit Address of the USART node. + * @retval None + */ +__STATIC_INLINE void DDL_USART_SetNodeAddress(USART_TypeDef *USARTx, uint32_t NodeAddress) +{ + MODIFY_REG(USARTx->CTRL2, USART_CTRL2_ADDR, (NodeAddress & USART_CTRL2_ADDR)); +} + +/** + * @brief Return 4 bit Address of the USART node as set in ADD field of CTRL2. + * @note only 4bits (b3-b0) of returned value are relevant (b31-b4 are not relevant) + * @param USARTx USART Instance + * @retval Address of the USART node (Value between Min_Data=0 and Max_Data=255) + */ +__STATIC_INLINE uint32_t DDL_USART_GetNodeAddress(USART_TypeDef *USARTx) +{ + return (uint32_t)(READ_BIT(USARTx->CTRL2, USART_CTRL2_ADDR)); +} + +/** + * @brief Enable RTS HW Flow Control + * @note Macro @ref IS_UART_HWFLOW_INSTANCE(USARTx) can be used to check whether or not + * Hardware Flow control feature is supported by the USARTx instance. + * @param USARTx USART Instance + * @retval None + */ +__STATIC_INLINE void DDL_USART_EnableRTSHWFlowCtrl(USART_TypeDef *USARTx) +{ + SET_BIT(USARTx->CTRL3, USART_CTRL3_RTSEN); +} + +/** + * @brief Disable RTS HW Flow Control + * @note Macro @ref IS_UART_HWFLOW_INSTANCE(USARTx) can be used to check whether or not + * Hardware Flow control feature is supported by the USARTx instance. + * @param USARTx USART Instance + * @retval None + */ +__STATIC_INLINE void DDL_USART_DisableRTSHWFlowCtrl(USART_TypeDef *USARTx) +{ + CLEAR_BIT(USARTx->CTRL3, USART_CTRL3_RTSEN); +} + +/** + * @brief Enable CTS HW Flow Control + * @note Macro @ref IS_UART_HWFLOW_INSTANCE(USARTx) can be used to check whether or not + * Hardware Flow control feature is supported by the USARTx instance. + * @param USARTx USART Instance + * @retval None + */ +__STATIC_INLINE void DDL_USART_EnableCTSHWFlowCtrl(USART_TypeDef *USARTx) +{ + SET_BIT(USARTx->CTRL3, USART_CTRL3_CTSEN); +} + +/** + * @brief Disable CTS HW Flow Control + * @note Macro @ref IS_UART_HWFLOW_INSTANCE(USARTx) can be used to check whether or not + * Hardware Flow control feature is supported by the USARTx instance. + * @param USARTx USART Instance + * @retval None + */ +__STATIC_INLINE void DDL_USART_DisableCTSHWFlowCtrl(USART_TypeDef *USARTx) +{ + CLEAR_BIT(USARTx->CTRL3, USART_CTRL3_CTSEN); +} + +/** + * @brief Configure HW Flow Control mode (both CTS and RTS) + * @note Macro @ref IS_UART_HWFLOW_INSTANCE(USARTx) can be used to check whether or not + * Hardware Flow control feature is supported by the USARTx instance. + * @param USARTx USART Instance + * @param HardwareFlowControl This parameter can be one of the following values: + * @arg @ref DDL_USART_HWCONTROL_NONE + * @arg @ref DDL_USART_HWCONTROL_RTS + * @arg @ref DDL_USART_HWCONTROL_CTS + * @arg @ref DDL_USART_HWCONTROL_RTS_CTS + * @retval None + */ +__STATIC_INLINE void DDL_USART_SetHWFlowCtrl(USART_TypeDef *USARTx, uint32_t HardwareFlowControl) +{ + MODIFY_REG(USARTx->CTRL3, USART_CTRL3_RTSEN | USART_CTRL3_CTSEN, HardwareFlowControl); +} + +/** + * @brief Return HW Flow Control configuration (both CTS and RTS) + * @note Macro @ref IS_UART_HWFLOW_INSTANCE(USARTx) can be used to check whether or not + * Hardware Flow control feature is supported by the USARTx instance. + * @param USARTx USART Instance + * @retval Returned value can be one of the following values: + * @arg @ref DDL_USART_HWCONTROL_NONE + * @arg @ref DDL_USART_HWCONTROL_RTS + * @arg @ref DDL_USART_HWCONTROL_CTS + * @arg @ref DDL_USART_HWCONTROL_RTS_CTS + */ +__STATIC_INLINE uint32_t DDL_USART_GetHWFlowCtrl(USART_TypeDef *USARTx) +{ + return (uint32_t)(READ_BIT(USARTx->CTRL3, USART_CTRL3_RTSEN | USART_CTRL3_CTSEN)); +} + +/** + * @brief Enable One bit sampling method + * @param USARTx USART Instance + * @retval None + */ +__STATIC_INLINE void DDL_USART_EnableOneBitSamp(USART_TypeDef *USARTx) +{ + SET_BIT(USARTx->CTRL3, USART_CTRL3_SAMCFG); +} + +/** + * @brief Disable One bit sampling method + * @param USARTx USART Instance + * @retval None + */ +__STATIC_INLINE void DDL_USART_DisableOneBitSamp(USART_TypeDef *USARTx) +{ + CLEAR_BIT(USARTx->CTRL3, USART_CTRL3_SAMCFG); +} + +/** + * @brief Indicate if One bit sampling method is enabled + * @param USARTx USART Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_USART_IsEnabledOneBitSamp(USART_TypeDef *USARTx) +{ + return (READ_BIT(USARTx->CTRL3, USART_CTRL3_SAMCFG) == (USART_CTRL3_SAMCFG)); +} + +/** + * @brief Configure USART BRR register for achieving expected Baud Rate value. + * @note Compute and set USARTDIV value in BRR Register (full BRR content) + * according to used Peripheral Clock, Oversampling mode, and expected Baud Rate values + * @note Peripheral clock and Baud rate values provided as function parameters should be valid + * (Baud rate value != 0) + * @param USARTx USART Instance + * @param PeriphClk Peripheral Clock + * @param OverSampling This parameter can be one of the following values: + * @arg @ref DDL_USART_OVERSAMPLING_16 + * @arg @ref DDL_USART_OVERSAMPLING_8 + * @param BaudRate Baud Rate + * @retval None + */ +__STATIC_INLINE void DDL_USART_SetBaudRate(USART_TypeDef *USARTx, uint32_t PeriphClk, uint32_t OverSampling, + uint32_t BaudRate) +{ + if (OverSampling == DDL_USART_OVERSAMPLING_8) + { + USARTx->BR = (uint16_t)(__DDL_USART_DIV_SAMPLING8(PeriphClk, BaudRate)); + } + else + { + USARTx->BR = (uint16_t)(__DDL_USART_DIV_SAMPLING16(PeriphClk, BaudRate)); + } +} + +/** + * @brief Return current Baud Rate value, according to USARTDIV present in BRR register + * (full BRR content), and to used Peripheral Clock and Oversampling mode values + * @note In case of non-initialized or invalid value stored in BRR register, value 0 will be returned. + * @param USARTx USART Instance + * @param PeriphClk Peripheral Clock + * @param OverSampling This parameter can be one of the following values: + * @arg @ref DDL_USART_OVERSAMPLING_16 + * @arg @ref DDL_USART_OVERSAMPLING_8 + * @retval Baud Rate + */ +__STATIC_INLINE uint32_t DDL_USART_GetBaudRate(USART_TypeDef *USARTx, uint32_t PeriphClk, uint32_t OverSampling) +{ + uint32_t usartdiv = 0x0U; + uint32_t brrresult = 0x0U; + + usartdiv = USARTx->BR; + + if (OverSampling == DDL_USART_OVERSAMPLING_8) + { + if ((usartdiv & 0xFFF7U) != 0U) + { + usartdiv = (uint16_t)((usartdiv & 0xFFF0U) | ((usartdiv & 0x0007U) << 1U)) ; + brrresult = (PeriphClk * 2U) / usartdiv; + } + } + else + { + if ((usartdiv & 0xFFFFU) != 0U) + { + brrresult = PeriphClk / usartdiv; + } + } + return (brrresult); +} + +/** + * @} + */ + +/** @defgroup USART_DDL_EF_Configuration_IRDA Configuration functions related to Irda feature + * @{ + */ + +/** + * @brief Enable IrDA mode + * @note Macro @ref IS_IRDA_INSTANCE(USARTx) can be used to check whether or not + * IrDA feature is supported by the USARTx instance. + * @param USARTx USART Instance + * @retval None + */ +__STATIC_INLINE void DDL_USART_EnableIrda(USART_TypeDef *USARTx) +{ + SET_BIT(USARTx->CTRL3, USART_CTRL3_IREN); +} + +/** + * @brief Disable IrDA mode + * @note Macro @ref IS_IRDA_INSTANCE(USARTx) can be used to check whether or not + * IrDA feature is supported by the USARTx instance. + * @param USARTx USART Instance + * @retval None + */ +__STATIC_INLINE void DDL_USART_DisableIrda(USART_TypeDef *USARTx) +{ + CLEAR_BIT(USARTx->CTRL3, USART_CTRL3_IREN); +} + +/** + * @brief Indicate if IrDA mode is enabled + * @note Macro @ref IS_IRDA_INSTANCE(USARTx) can be used to check whether or not + * IrDA feature is supported by the USARTx instance. + * @param USARTx USART Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_USART_IsEnabledIrda(USART_TypeDef *USARTx) +{ + return (READ_BIT(USARTx->CTRL3, USART_CTRL3_IREN) == (USART_CTRL3_IREN)); +} + +/** + * @brief Configure IrDA Power Mode (Normal or Low Power) + * @note Macro @ref IS_IRDA_INSTANCE(USARTx) can be used to check whether or not + * IrDA feature is supported by the USARTx instance. + * @param USARTx USART Instance + * @param PowerMode This parameter can be one of the following values: + * @arg @ref DDL_USART_IRDA_POWER_NORMAL + * @arg @ref DDL_USART_IRDA_POWER_LOW + * @retval None + */ +__STATIC_INLINE void DDL_USART_SetIrdaPowerMode(USART_TypeDef *USARTx, uint32_t PowerMode) +{ + MODIFY_REG(USARTx->CTRL3, USART_CTRL3_IRLPEN, PowerMode); +} + +/** + * @brief Retrieve IrDA Power Mode configuration (Normal or Low Power) + * @note Macro @ref IS_IRDA_INSTANCE(USARTx) can be used to check whether or not + * IrDA feature is supported by the USARTx instance. + * @param USARTx USART Instance + * @retval Returned value can be one of the following values: + * @arg @ref DDL_USART_IRDA_POWER_NORMAL + * @arg @ref DDL_USART_PHASE_2EDGE + */ +__STATIC_INLINE uint32_t DDL_USART_GetIrdaPowerMode(USART_TypeDef *USARTx) +{ + return (uint32_t)(READ_BIT(USARTx->CTRL3, USART_CTRL3_IRLPEN)); +} + +/** + * @brief Set Irda prescaler value, used for dividing the USART clock source + * to achieve the Irda Low Power frequency (8 bits value) + * @note Macro @ref IS_IRDA_INSTANCE(USARTx) can be used to check whether or not + * IrDA feature is supported by the USARTx instance. + * @param USARTx USART Instance + * @param PrescalerValue Value between Min_Data=0x00 and Max_Data=0xFF + * @retval None + */ +__STATIC_INLINE void DDL_USART_SetIrdaPrescaler(USART_TypeDef *USARTx, uint32_t PrescalerValue) +{ + MODIFY_REG(USARTx->GTPSC, USART_GTPSC_PSC, PrescalerValue); +} + +/** + * @brief Return Irda prescaler value, used for dividing the USART clock source + * to achieve the Irda Low Power frequency (8 bits value) + * @note Macro @ref IS_IRDA_INSTANCE(USARTx) can be used to check whether or not + * IrDA feature is supported by the USARTx instance. + * @param USARTx USART Instance + * @retval Irda prescaler value (Value between Min_Data=0x00 and Max_Data=0xFF) + */ +__STATIC_INLINE uint32_t DDL_USART_GetIrdaPrescaler(USART_TypeDef *USARTx) +{ + return (uint32_t)(READ_BIT(USARTx->GTPSC, USART_GTPSC_PSC)); +} + +/** + * @} + */ + +/** @defgroup USART_DDL_EF_Configuration_Smartcard Configuration functions related to Smartcard feature + * @{ + */ + +/** + * @brief Enable Smartcard NACK transmission + * @note Macro @ref IS_SMARTCARD_INSTANCE(USARTx) can be used to check whether or not + * Smartcard feature is supported by the USARTx instance. + * @param USARTx USART Instance + * @retval None + */ +__STATIC_INLINE void DDL_USART_EnableSmartcardNACK(USART_TypeDef *USARTx) +{ + SET_BIT(USARTx->CTRL3, USART_CTRL3_SCNACKEN); +} + +/** + * @brief Disable Smartcard NACK transmission + * @note Macro @ref IS_SMARTCARD_INSTANCE(USARTx) can be used to check whether or not + * Smartcard feature is supported by the USARTx instance. + * @param USARTx USART Instance + * @retval None + */ +__STATIC_INLINE void DDL_USART_DisableSmartcardNACK(USART_TypeDef *USARTx) +{ + CLEAR_BIT(USARTx->CTRL3, USART_CTRL3_SCNACKEN); +} + +/** + * @brief Indicate if Smartcard NACK transmission is enabled + * @note Macro @ref IS_SMARTCARD_INSTANCE(USARTx) can be used to check whether or not + * Smartcard feature is supported by the USARTx instance. + * @param USARTx USART Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_USART_IsEnabledSmartcardNACK(USART_TypeDef *USARTx) +{ + return (READ_BIT(USARTx->CTRL3, USART_CTRL3_SCNACKEN) == (USART_CTRL3_SCNACKEN)); +} + +/** + * @brief Enable Smartcard mode + * @note Macro @ref IS_SMARTCARD_INSTANCE(USARTx) can be used to check whether or not + * Smartcard feature is supported by the USARTx instance. + * @param USARTx USART Instance + * @retval None + */ +__STATIC_INLINE void DDL_USART_EnableSmartcard(USART_TypeDef *USARTx) +{ + SET_BIT(USARTx->CTRL3, USART_CTRL3_SCEN); +} + +/** + * @brief Disable Smartcard mode + * @note Macro @ref IS_SMARTCARD_INSTANCE(USARTx) can be used to check whether or not + * Smartcard feature is supported by the USARTx instance. + * @param USARTx USART Instance + * @retval None + */ +__STATIC_INLINE void DDL_USART_DisableSmartcard(USART_TypeDef *USARTx) +{ + CLEAR_BIT(USARTx->CTRL3, USART_CTRL3_SCEN); +} + +/** + * @brief Indicate if Smartcard mode is enabled + * @note Macro @ref IS_SMARTCARD_INSTANCE(USARTx) can be used to check whether or not + * Smartcard feature is supported by the USARTx instance. + * @param USARTx USART Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_USART_IsEnabledSmartcard(USART_TypeDef *USARTx) +{ + return (READ_BIT(USARTx->CTRL3, USART_CTRL3_SCEN) == (USART_CTRL3_SCEN)); +} + +/** + * @brief Set Smartcard prescaler value, used for dividing the USART clock + * source to provide the SMARTCARD Clock (5 bits value) + * @note Macro @ref IS_SMARTCARD_INSTANCE(USARTx) can be used to check whether or not + * Smartcard feature is supported by the USARTx instance. + * @param USARTx USART Instance + * @param PrescalerValue Value between Min_Data=0 and Max_Data=31 + * @retval None + */ +__STATIC_INLINE void DDL_USART_SetSmartcardPrescaler(USART_TypeDef *USARTx, uint32_t PrescalerValue) +{ + MODIFY_REG(USARTx->GTPSC, USART_GTPSC_PSC, PrescalerValue); +} + +/** + * @brief Return Smartcard prescaler value, used for dividing the USART clock + * source to provide the SMARTCARD Clock (5 bits value) + * @note Macro @ref IS_SMARTCARD_INSTANCE(USARTx) can be used to check whether or not + * Smartcard feature is supported by the USARTx instance. + * @param USARTx USART Instance + * @retval Smartcard prescaler value (Value between Min_Data=0 and Max_Data=31) + */ +__STATIC_INLINE uint32_t DDL_USART_GetSmartcardPrescaler(USART_TypeDef *USARTx) +{ + return (uint32_t)(READ_BIT(USARTx->GTPSC, USART_GTPSC_PSC)); +} + +/** + * @brief Set Smartcard Guard time value, expressed in nb of baud clocks periods + * (GT[7:0] bits : Guard time value) + * @note Macro @ref IS_SMARTCARD_INSTANCE(USARTx) can be used to check whether or not + * Smartcard feature is supported by the USARTx instance. + * @param USARTx USART Instance + * @param GuardTime Value between Min_Data=0x00 and Max_Data=0xFF + * @retval None + */ +__STATIC_INLINE void DDL_USART_SetSmartcardGuardTime(USART_TypeDef *USARTx, uint32_t GuardTime) +{ + MODIFY_REG(USARTx->GTPSC, USART_GTPSC_GRDT, GuardTime << USART_POSITION_GTPR_GT); +} + +/** + * @brief Return Smartcard Guard time value, expressed in nb of baud clocks periods + * (GT[7:0] bits : Guard time value) + * @note Macro @ref IS_SMARTCARD_INSTANCE(USARTx) can be used to check whether or not + * Smartcard feature is supported by the USARTx instance. + * @param USARTx USART Instance + * @retval Smartcard Guard time value (Value between Min_Data=0x00 and Max_Data=0xFF) + */ +__STATIC_INLINE uint32_t DDL_USART_GetSmartcardGuardTime(USART_TypeDef *USARTx) +{ + return (uint32_t)(READ_BIT(USARTx->GTPSC, USART_GTPSC_GRDT) >> USART_POSITION_GTPR_GT); +} + +/** + * @} + */ + +/** @defgroup USART_DDL_EF_Configuration_HalfDuplex Configuration functions related to Half Duplex feature + * @{ + */ + +/** + * @brief Enable Single Wire Half-Duplex mode + * @note Macro @ref IS_UART_HALFDUPLEX_INSTANCE(USARTx) can be used to check whether or not + * Half-Duplex mode is supported by the USARTx instance. + * @param USARTx USART Instance + * @retval None + */ +__STATIC_INLINE void DDL_USART_EnableHalfDuplex(USART_TypeDef *USARTx) +{ + SET_BIT(USARTx->CTRL3, USART_CTRL3_HDEN); +} + +/** + * @brief Disable Single Wire Half-Duplex mode + * @note Macro @ref IS_UART_HALFDUPLEX_INSTANCE(USARTx) can be used to check whether or not + * Half-Duplex mode is supported by the USARTx instance. + * @param USARTx USART Instance + * @retval None + */ +__STATIC_INLINE void DDL_USART_DisableHalfDuplex(USART_TypeDef *USARTx) +{ + CLEAR_BIT(USARTx->CTRL3, USART_CTRL3_HDEN); +} + +/** + * @brief Indicate if Single Wire Half-Duplex mode is enabled + * @note Macro @ref IS_UART_HALFDUPLEX_INSTANCE(USARTx) can be used to check whether or not + * Half-Duplex mode is supported by the USARTx instance. + * @param USARTx USART Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_USART_IsEnabledHalfDuplex(USART_TypeDef *USARTx) +{ + return (READ_BIT(USARTx->CTRL3, USART_CTRL3_HDEN) == (USART_CTRL3_HDEN)); +} + +/** + * @} + */ + +/** @defgroup USART_DDL_EF_Configuration_LIN Configuration functions related to LIN feature + * @{ + */ + +/** + * @brief Set LIN Break Detection Length + * @note Macro @ref IS_UART_LIN_INSTANCE(USARTx) can be used to check whether or not + * LIN feature is supported by the USARTx instance. + * @param USARTx USART Instance + * @param LINBDLength This parameter can be one of the following values: + * @arg @ref DDL_USART_LINBREAK_DETECT_10B + * @arg @ref DDL_USART_LINBREAK_DETECT_11B + * @retval None + */ +__STATIC_INLINE void DDL_USART_SetLINBrkDetectionLen(USART_TypeDef *USARTx, uint32_t LINBDLength) +{ + MODIFY_REG(USARTx->CTRL2, USART_CTRL2_LBDLCFG, LINBDLength); +} + +/** + * @brief Return LIN Break Detection Length + * @note Macro @ref IS_UART_LIN_INSTANCE(USARTx) can be used to check whether or not + * LIN feature is supported by the USARTx instance. + * @param USARTx USART Instance + * @retval Returned value can be one of the following values: + * @arg @ref DDL_USART_LINBREAK_DETECT_10B + * @arg @ref DDL_USART_LINBREAK_DETECT_11B + */ +__STATIC_INLINE uint32_t DDL_USART_GetLINBrkDetectionLen(USART_TypeDef *USARTx) +{ + return (uint32_t)(READ_BIT(USARTx->CTRL2, USART_CTRL2_LBDLCFG)); +} + +/** + * @brief Enable LIN mode + * @note Macro @ref IS_UART_LIN_INSTANCE(USARTx) can be used to check whether or not + * LIN feature is supported by the USARTx instance. + * @param USARTx USART Instance + * @retval None + */ +__STATIC_INLINE void DDL_USART_EnableLIN(USART_TypeDef *USARTx) +{ + SET_BIT(USARTx->CTRL2, USART_CTRL2_LINMEN); +} + +/** + * @brief Disable LIN mode + * @note Macro @ref IS_UART_LIN_INSTANCE(USARTx) can be used to check whether or not + * LIN feature is supported by the USARTx instance. + * @param USARTx USART Instance + * @retval None + */ +__STATIC_INLINE void DDL_USART_DisableLIN(USART_TypeDef *USARTx) +{ + CLEAR_BIT(USARTx->CTRL2, USART_CTRL2_LINMEN); +} + +/** + * @brief Indicate if LIN mode is enabled + * @note Macro @ref IS_UART_LIN_INSTANCE(USARTx) can be used to check whether or not + * LIN feature is supported by the USARTx instance. + * @param USARTx USART Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_USART_IsEnabledLIN(USART_TypeDef *USARTx) +{ + return (READ_BIT(USARTx->CTRL2, USART_CTRL2_LINMEN) == (USART_CTRL2_LINMEN)); +} + +/** + * @} + */ + +/** @defgroup USART_DDL_EF_AdvancedConfiguration Advanced Configurations services + * @{ + */ + +/** + * @brief Perform basic configuration of USART for enabling use in Asynchronous Mode (UART) + * @note In UART mode, the following bits must be kept cleared: + * - LINEN bit in the USART_CTRL2 register, + * - CLKEN bit in the USART_CTRL2 register, + * - SCEN bit in the USART_CTRL3 register, + * - IREN bit in the USART_CTRL3 register, + * - HDSEL bit in the USART_CTRL3 register. + * @note Call of this function is equivalent to following function call sequence : + * - Clear LINEN in CTRL2 using @ref DDL_USART_DisableLIN() function + * - Clear CLKEN in CTRL2 using @ref DDL_USART_DisableSCLKOutput() function + * - Clear SCEN in CTRL3 using @ref DDL_USART_DisableSmartcard() function + * - Clear IREN in CTRL3 using @ref DDL_USART_DisableIrda() function + * - Clear HDSEL in CTRL3 using @ref DDL_USART_DisableHalfDuplex() function + * @note Other remaining configurations items related to Asynchronous Mode + * (as Baud Rate, Word length, Parity, ...) should be set using + * dedicated functions + * @param USARTx USART Instance + * @retval None + */ +__STATIC_INLINE void DDL_USART_ConfigAsyncMode(USART_TypeDef *USARTx) +{ + /* In Asynchronous mode, the following bits must be kept cleared: + - LINEN, CLKEN bits in the USART_CTRL2 register, + - SCEN, IREN and HDSEL bits in the USART_CTRL3 register.*/ + CLEAR_BIT(USARTx->CTRL2, (USART_CTRL2_LINMEN | USART_CTRL2_CLKEN)); + CLEAR_BIT(USARTx->CTRL3, (USART_CTRL3_SCEN | USART_CTRL3_IREN | USART_CTRL3_HDEN)); +} + +/** + * @brief Perform basic configuration of USART for enabling use in Synchronous Mode + * @note In Synchronous mode, the following bits must be kept cleared: + * - LINEN bit in the USART_CTRL2 register, + * - SCEN bit in the USART_CTRL3 register, + * - IREN bit in the USART_CTRL3 register, + * - HDSEL bit in the USART_CTRL3 register. + * This function also sets the USART in Synchronous mode. + * @note Macro @ref IS_USART_INSTANCE(USARTx) can be used to check whether or not + * Synchronous mode is supported by the USARTx instance. + * @note Call of this function is equivalent to following function call sequence : + * - Clear LINEN in CTRL2 using @ref DDL_USART_DisableLIN() function + * - Clear IREN in CTRL3 using @ref DDL_USART_DisableIrda() function + * - Clear SCEN in CTRL3 using @ref DDL_USART_DisableSmartcard() function + * - Clear HDSEL in CTRL3 using @ref DDL_USART_DisableHalfDuplex() function + * - Set CLKEN in CTRL2 using @ref DDL_USART_EnableSCLKOutput() function + * @note Other remaining configurations items related to Synchronous Mode + * (as Baud Rate, Word length, Parity, Clock Polarity, ...) should be set using + * dedicated functions + * @param USARTx USART Instance + * @retval None + */ +__STATIC_INLINE void DDL_USART_ConfigSyncMode(USART_TypeDef *USARTx) +{ + /* In Synchronous mode, the following bits must be kept cleared: + - LINEN bit in the USART_CTRL2 register, + - SCEN, IREN and HDSEL bits in the USART_CTRL3 register.*/ + CLEAR_BIT(USARTx->CTRL2, (USART_CTRL2_LINMEN)); + CLEAR_BIT(USARTx->CTRL3, (USART_CTRL3_SCEN | USART_CTRL3_IREN | USART_CTRL3_HDEN)); + /* set the UART/USART in Synchronous mode */ + SET_BIT(USARTx->CTRL2, USART_CTRL2_CLKEN); +} + +/** + * @brief Perform basic configuration of USART for enabling use in LIN Mode + * @note In LIN mode, the following bits must be kept cleared: + * - STOP and CLKEN bits in the USART_CTRL2 register, + * - SCEN bit in the USART_CTRL3 register, + * - IREN bit in the USART_CTRL3 register, + * - HDSEL bit in the USART_CTRL3 register. + * This function also set the UART/USART in LIN mode. + * @note Macro @ref IS_UART_LIN_INSTANCE(USARTx) can be used to check whether or not + * LIN feature is supported by the USARTx instance. + * @note Call of this function is equivalent to following function call sequence : + * - Clear CLKEN in CTRL2 using @ref DDL_USART_DisableSCLKOutput() function + * - Clear STOP in CTRL2 using @ref DDL_USART_SetStopBitsLength() function + * - Clear SCEN in CTRL3 using @ref DDL_USART_DisableSmartcard() function + * - Clear IREN in CTRL3 using @ref DDL_USART_DisableIrda() function + * - Clear HDSEL in CTRL3 using @ref DDL_USART_DisableHalfDuplex() function + * - Set LINEN in CTRL2 using @ref DDL_USART_EnableLIN() function + * @note Other remaining configurations items related to LIN Mode + * (as Baud Rate, Word length, LIN Break Detection Length, ...) should be set using + * dedicated functions + * @param USARTx USART Instance + * @retval None + */ +__STATIC_INLINE void DDL_USART_ConfigLINMode(USART_TypeDef *USARTx) +{ + /* In LIN mode, the following bits must be kept cleared: + - STOP and CLKEN bits in the USART_CTRL2 register, + - IREN, SCEN and HDSEL bits in the USART_CTRL3 register.*/ + CLEAR_BIT(USARTx->CTRL2, (USART_CTRL2_CLKEN | USART_CTRL2_STOPCFG)); + CLEAR_BIT(USARTx->CTRL3, (USART_CTRL3_IREN | USART_CTRL3_SCEN | USART_CTRL3_HDEN)); + /* Set the UART/USART in LIN mode */ + SET_BIT(USARTx->CTRL2, USART_CTRL2_LINMEN); +} + +/** + * @brief Perform basic configuration of USART for enabling use in Half Duplex Mode + * @note In Half Duplex mode, the following bits must be kept cleared: + * - LINEN bit in the USART_CTRL2 register, + * - CLKEN bit in the USART_CTRL2 register, + * - SCEN bit in the USART_CTRL3 register, + * - IREN bit in the USART_CTRL3 register, + * This function also sets the UART/USART in Half Duplex mode. + * @note Macro @ref IS_UART_HALFDUPLEX_INSTANCE(USARTx) can be used to check whether or not + * Half-Duplex mode is supported by the USARTx instance. + * @note Call of this function is equivalent to following function call sequence : + * - Clear LINEN in CTRL2 using @ref DDL_USART_DisableLIN() function + * - Clear CLKEN in CTRL2 using @ref DDL_USART_DisableSCLKOutput() function + * - Clear SCEN in CTRL3 using @ref DDL_USART_DisableSmartcard() function + * - Clear IREN in CTRL3 using @ref DDL_USART_DisableIrda() function + * - Set HDSEL in CTRL3 using @ref DDL_USART_EnableHalfDuplex() function + * @note Other remaining configurations items related to Half Duplex Mode + * (as Baud Rate, Word length, Parity, ...) should be set using + * dedicated functions + * @param USARTx USART Instance + * @retval None + */ +__STATIC_INLINE void DDL_USART_ConfigHalfDuplexMode(USART_TypeDef *USARTx) +{ + /* In Half Duplex mode, the following bits must be kept cleared: + - LINEN and CLKEN bits in the USART_CTRL2 register, + - SCEN and IREN bits in the USART_CTRL3 register.*/ + CLEAR_BIT(USARTx->CTRL2, (USART_CTRL2_LINMEN | USART_CTRL2_CLKEN)); + CLEAR_BIT(USARTx->CTRL3, (USART_CTRL3_SCEN | USART_CTRL3_IREN)); + /* set the UART/USART in Half Duplex mode */ + SET_BIT(USARTx->CTRL3, USART_CTRL3_HDEN); +} + +/** + * @brief Perform basic configuration of USART for enabling use in Smartcard Mode + * @note In Smartcard mode, the following bits must be kept cleared: + * - LINEN bit in the USART_CTRL2 register, + * - IREN bit in the USART_CTRL3 register, + * - HDSEL bit in the USART_CTRL3 register. + * This function also configures Stop bits to 1.5 bits and + * sets the USART in Smartcard mode (SCEN bit). + * Clock Output is also enabled (CLKEN). + * @note Macro @ref IS_SMARTCARD_INSTANCE(USARTx) can be used to check whether or not + * Smartcard feature is supported by the USARTx instance. + * @note Call of this function is equivalent to following function call sequence : + * - Clear LINEN in CTRL2 using @ref DDL_USART_DisableLIN() function + * - Clear IREN in CTRL3 using @ref DDL_USART_DisableIrda() function + * - Clear HDSEL in CTRL3 using @ref DDL_USART_DisableHalfDuplex() function + * - Configure STOP in CTRL2 using @ref DDL_USART_SetStopBitsLength() function + * - Set CLKEN in CTRL2 using @ref DDL_USART_EnableSCLKOutput() function + * - Set SCEN in CTRL3 using @ref DDL_USART_EnableSmartcard() function + * @note Other remaining configurations items related to Smartcard Mode + * (as Baud Rate, Word length, Parity, ...) should be set using + * dedicated functions + * @param USARTx USART Instance + * @retval None + */ +__STATIC_INLINE void DDL_USART_ConfigSmartcardMode(USART_TypeDef *USARTx) +{ + /* In Smartcard mode, the following bits must be kept cleared: + - LINEN bit in the USART_CTRL2 register, + - IREN and HDSEL bits in the USART_CTRL3 register.*/ + CLEAR_BIT(USARTx->CTRL2, (USART_CTRL2_LINMEN)); + CLEAR_BIT(USARTx->CTRL3, (USART_CTRL3_IREN | USART_CTRL3_HDEN)); + /* Configure Stop bits to 1.5 bits */ + /* Synchronous mode is activated by default */ + SET_BIT(USARTx->CTRL2, (USART_CTRL2_STOPCFG_0 | USART_CTRL2_STOPCFG_1 | USART_CTRL2_CLKEN)); + /* set the UART/USART in Smartcard mode */ + SET_BIT(USARTx->CTRL3, USART_CTRL3_SCEN); +} + +/** + * @brief Perform basic configuration of USART for enabling use in Irda Mode + * @note In IRDA mode, the following bits must be kept cleared: + * - LINEN bit in the USART_CTRL2 register, + * - STOP and CLKEN bits in the USART_CTRL2 register, + * - SCEN bit in the USART_CTRL3 register, + * - HDSEL bit in the USART_CTRL3 register. + * This function also sets the UART/USART in IRDA mode (IREN bit). + * @note Macro @ref IS_IRDA_INSTANCE(USARTx) can be used to check whether or not + * IrDA feature is supported by the USARTx instance. + * @note Call of this function is equivalent to following function call sequence : + * - Clear LINEN in CTRL2 using @ref DDL_USART_DisableLIN() function + * - Clear CLKEN in CTRL2 using @ref DDL_USART_DisableSCLKOutput() function + * - Clear SCEN in CTRL3 using @ref DDL_USART_DisableSmartcard() function + * - Clear HDSEL in CTRL3 using @ref DDL_USART_DisableHalfDuplex() function + * - Configure STOP in CTRL2 using @ref DDL_USART_SetStopBitsLength() function + * - Set IREN in CTRL3 using @ref DDL_USART_EnableIrda() function + * @note Other remaining configurations items related to Irda Mode + * (as Baud Rate, Word length, Power mode, ...) should be set using + * dedicated functions + * @param USARTx USART Instance + * @retval None + */ +__STATIC_INLINE void DDL_USART_ConfigIrdaMode(USART_TypeDef *USARTx) +{ + /* In IRDA mode, the following bits must be kept cleared: + - LINEN, STOP and CLKEN bits in the USART_CTRL2 register, + - SCEN and HDSEL bits in the USART_CTRL3 register.*/ + CLEAR_BIT(USARTx->CTRL2, (USART_CTRL2_LINMEN | USART_CTRL2_CLKEN | USART_CTRL2_STOPCFG)); + CLEAR_BIT(USARTx->CTRL3, (USART_CTRL3_SCEN | USART_CTRL3_HDEN)); + /* set the UART/USART in IRDA mode */ + SET_BIT(USARTx->CTRL3, USART_CTRL3_IREN); +} + +/** + * @brief Perform basic configuration of USART for enabling use in Multi processor Mode + * (several USARTs connected in a network, one of the USARTs can be the master, + * its TX output connected to the RX inputs of the other slaves USARTs). + * @note In MultiProcessor mode, the following bits must be kept cleared: + * - LINEN bit in the USART_CTRL2 register, + * - CLKEN bit in the USART_CTRL2 register, + * - SCEN bit in the USART_CTRL3 register, + * - IREN bit in the USART_CTRL3 register, + * - HDSEL bit in the USART_CTRL3 register. + * @note Call of this function is equivalent to following function call sequence : + * - Clear LINEN in CTRL2 using @ref DDL_USART_DisableLIN() function + * - Clear CLKEN in CTRL2 using @ref DDL_USART_DisableSCLKOutput() function + * - Clear SCEN in CTRL3 using @ref DDL_USART_DisableSmartcard() function + * - Clear IREN in CTRL3 using @ref DDL_USART_DisableIrda() function + * - Clear HDSEL in CTRL3 using @ref DDL_USART_DisableHalfDuplex() function + * @note Other remaining configurations items related to Multi processor Mode + * (as Baud Rate, Wake Up Method, Node address, ...) should be set using + * dedicated functions + * @param USARTx USART Instance + * @retval None + */ +__STATIC_INLINE void DDL_USART_ConfigMultiProcessMode(USART_TypeDef *USARTx) +{ + /* In Multi Processor mode, the following bits must be kept cleared: + - LINEN and CLKEN bits in the USART_CTRL2 register, + - IREN, SCEN and HDSEL bits in the USART_CTRL3 register.*/ + CLEAR_BIT(USARTx->CTRL2, (USART_CTRL2_LINMEN | USART_CTRL2_CLKEN)); + CLEAR_BIT(USARTx->CTRL3, (USART_CTRL3_SCEN | USART_CTRL3_HDEN | USART_CTRL3_IREN)); +} + +/** + * @} + */ + +/** @defgroup USART_DDL_EF_FLAG_Management FLAG_Management + * @{ + */ + +/** + * @brief Check if the USART Parity Error Flag is set or not + * @param USARTx USART Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_USART_IsActiveFlag_PE(USART_TypeDef *USARTx) +{ + return (READ_BIT(USARTx->STS, USART_STS_PEFLG) == (USART_STS_PEFLG)); +} + +/** + * @brief Check if the USART Framing Error Flag is set or not + * @param USARTx USART Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_USART_IsActiveFlag_FE(USART_TypeDef *USARTx) +{ + return (READ_BIT(USARTx->STS, USART_STS_FEFLG) == (USART_STS_FEFLG)); +} + +/** + * @brief Check if the USART Noise error detected Flag is set or not + * @param USARTx USART Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_USART_IsActiveFlag_NE(USART_TypeDef *USARTx) +{ + return (READ_BIT(USARTx->STS, USART_STS_NEFLG) == (USART_STS_NEFLG)); +} + +/** + * @brief Check if the USART OverRun Error Flag is set or not + * @param USARTx USART Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_USART_IsActiveFlag_ORE(USART_TypeDef *USARTx) +{ + return (READ_BIT(USARTx->STS, USART_STS_OVREFLG) == (USART_STS_OVREFLG)); +} + +/** + * @brief Check if the USART IDLE line detected Flag is set or not + * @param USARTx USART Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_USART_IsActiveFlag_IDLE(USART_TypeDef *USARTx) +{ + return (READ_BIT(USARTx->STS, USART_STS_IDLEFLG) == (USART_STS_IDLEFLG)); +} + +/** + * @brief Check if the USART Read Data Register Not Empty Flag is set or not + * @param USARTx USART Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_USART_IsActiveFlag_RXNE(USART_TypeDef *USARTx) +{ + return (READ_BIT(USARTx->STS, USART_STS_RXBNEFLG) == (USART_STS_RXBNEFLG)); +} + +/** + * @brief Check if the USART Transmission Complete Flag is set or not + * @param USARTx USART Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_USART_IsActiveFlag_TC(USART_TypeDef *USARTx) +{ + return (READ_BIT(USARTx->STS, USART_STS_TXCFLG) == (USART_STS_TXCFLG)); +} + +/** + * @brief Check if the USART Transmit Data Register Empty Flag is set or not + * @param USARTx USART Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_USART_IsActiveFlag_TXE(USART_TypeDef *USARTx) +{ + return (READ_BIT(USARTx->STS, USART_STS_TXBEFLG) == (USART_STS_TXBEFLG)); +} + +/** + * @brief Check if the USART LIN Break Detection Flag is set or not + * @note Macro @ref IS_UART_LIN_INSTANCE(USARTx) can be used to check whether or not + * LIN feature is supported by the USARTx instance. + * @param USARTx USART Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_USART_IsActiveFlag_LBD(USART_TypeDef *USARTx) +{ + return (READ_BIT(USARTx->STS, USART_STS_LBDFLG) == (USART_STS_LBDFLG)); +} + +/** + * @brief Check if the USART CTS Flag is set or not + * @note Macro @ref IS_UART_HWFLOW_INSTANCE(USARTx) can be used to check whether or not + * Hardware Flow control feature is supported by the USARTx instance. + * @param USARTx USART Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_USART_IsActiveFlag_nCTS(USART_TypeDef *USARTx) +{ + return (READ_BIT(USARTx->STS, USART_STS_CTSFLG) == (USART_STS_CTSFLG)); +} + +/** + * @brief Check if the USART Send Break Flag is set or not + * @param USARTx USART Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_USART_IsActiveFlag_SBK(USART_TypeDef *USARTx) +{ + return (READ_BIT(USARTx->CTRL1, USART_CTRL1_TXBF) == (USART_CTRL1_TXBF)); +} + +/** + * @brief Check if the USART Receive Wake Up from mute mode Flag is set or not + * @param USARTx USART Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_USART_IsActiveFlag_RWU(USART_TypeDef *USARTx) +{ + return (READ_BIT(USARTx->CTRL1, USART_CTRL1_RXMUTEEN) == (USART_CTRL1_RXMUTEEN)); +} + +/** + * @brief Clear Parity Error Flag + * @note Clearing this flag is done by a read access to the USARTx_SR + * register followed by a read access to the USARTx_DR register. + * @note Please also consider that when clearing this flag, other flags as + * NE, FE, ORE, IDLE would also be cleared. + * @param USARTx USART Instance + * @retval None + */ +__STATIC_INLINE void DDL_USART_ClearFlag_PE(USART_TypeDef *USARTx) +{ + __IO uint32_t tmpreg; + tmpreg = USARTx->STS; + (void) tmpreg; + tmpreg = USARTx->DATA; + (void) tmpreg; +} + +/** + * @brief Clear Framing Error Flag + * @note Clearing this flag is done by a read access to the USARTx_SR + * register followed by a read access to the USARTx_DR register. + * @note Please also consider that when clearing this flag, other flags as + * PE, NE, ORE, IDLE would also be cleared. + * @param USARTx USART Instance + * @retval None + */ +__STATIC_INLINE void DDL_USART_ClearFlag_FE(USART_TypeDef *USARTx) +{ + __IO uint32_t tmpreg; + tmpreg = USARTx->STS; + (void) tmpreg; + tmpreg = USARTx->DATA; + (void) tmpreg; +} + +/** + * @brief Clear Noise detected Flag + * @note Clearing this flag is done by a read access to the USARTx_SR + * register followed by a read access to the USARTx_DR register. + * @note Please also consider that when clearing this flag, other flags as + * PE, FE, ORE, IDLE would also be cleared. + * @param USARTx USART Instance + * @retval None + */ +__STATIC_INLINE void DDL_USART_ClearFlag_NE(USART_TypeDef *USARTx) +{ + __IO uint32_t tmpreg; + tmpreg = USARTx->STS; + (void) tmpreg; + tmpreg = USARTx->DATA; + (void) tmpreg; +} + +/** + * @brief Clear OverRun Error Flag + * @note Clearing this flag is done by a read access to the USARTx_SR + * register followed by a read access to the USARTx_DR register. + * @note Please also consider that when clearing this flag, other flags as + * PE, NE, FE, IDLE would also be cleared. + * @param USARTx USART Instance + * @retval None + */ +__STATIC_INLINE void DDL_USART_ClearFlag_ORE(USART_TypeDef *USARTx) +{ + __IO uint32_t tmpreg; + tmpreg = USARTx->STS; + (void) tmpreg; + tmpreg = USARTx->DATA; + (void) tmpreg; +} + +/** + * @brief Clear IDLE line detected Flag + * @note Clearing this flag is done by a read access to the USARTx_SR + * register followed by a read access to the USARTx_DR register. + * @note Please also consider that when clearing this flag, other flags as + * PE, NE, FE, ORE would also be cleared. + * @param USARTx USART Instance + * @retval None + */ +__STATIC_INLINE void DDL_USART_ClearFlag_IDLE(USART_TypeDef *USARTx) +{ + __IO uint32_t tmpreg; + tmpreg = USARTx->STS; + (void) tmpreg; + tmpreg = USARTx->DATA; + (void) tmpreg; +} + +/** + * @brief Clear Transmission Complete Flag + * @param USARTx USART Instance + * @retval None + */ +__STATIC_INLINE void DDL_USART_ClearFlag_TC(USART_TypeDef *USARTx) +{ + WRITE_REG(USARTx->STS, ~(USART_STS_TXCFLG)); +} + +/** + * @brief Clear RX Not Empty Flag + * @param USARTx USART Instance + * @retval None + */ +__STATIC_INLINE void DDL_USART_ClearFlag_RXNE(USART_TypeDef *USARTx) +{ + WRITE_REG(USARTx->STS, ~(USART_STS_RXBNEFLG)); +} + +/** + * @brief Clear LIN Break Detection Flag + * @note Macro @ref IS_UART_LIN_INSTANCE(USARTx) can be used to check whether or not + * LIN feature is supported by the USARTx instance. + * @param USARTx USART Instance + * @retval None + */ +__STATIC_INLINE void DDL_USART_ClearFlag_LBD(USART_TypeDef *USARTx) +{ + WRITE_REG(USARTx->STS, ~(USART_STS_LBDFLG)); +} + +/** + * @brief Clear CTS Interrupt Flag + * @note Macro @ref IS_UART_HWFLOW_INSTANCE(USARTx) can be used to check whether or not + * Hardware Flow control feature is supported by the USARTx instance. + * @param USARTx USART Instance + * @retval None + */ +__STATIC_INLINE void DDL_USART_ClearFlag_nCTS(USART_TypeDef *USARTx) +{ + WRITE_REG(USARTx->STS, ~(USART_STS_CTSFLG)); +} + +/** + * @} + */ + +/** @defgroup USART_DDL_EF_IT_Management IT_Management + * @{ + */ + +/** + * @brief Enable IDLE Interrupt + * @param USARTx USART Instance + * @retval None + */ +__STATIC_INLINE void DDL_USART_EnableIT_IDLE(USART_TypeDef *USARTx) +{ + ATOMIC_SET_BIT(USARTx->CTRL1, USART_CTRL1_IDLEIEN); +} + +/** + * @brief Enable RX Not Empty Interrupt + * @param USARTx USART Instance + * @retval None + */ +__STATIC_INLINE void DDL_USART_EnableIT_RXNE(USART_TypeDef *USARTx) +{ + ATOMIC_SET_BIT(USARTx->CTRL1, USART_CTRL1_RXBNEIEN); +} + +/** + * @brief Enable Transmission Complete Interrupt + * @param USARTx USART Instance + * @retval None + */ +__STATIC_INLINE void DDL_USART_EnableIT_TC(USART_TypeDef *USARTx) +{ + ATOMIC_SET_BIT(USARTx->CTRL1, USART_CTRL1_TXCIEN); +} + +/** + * @brief Enable TX Empty Interrupt + * @param USARTx USART Instance + * @retval None + */ +__STATIC_INLINE void DDL_USART_EnableIT_TXE(USART_TypeDef *USARTx) +{ + ATOMIC_SET_BIT(USARTx->CTRL1, USART_CTRL1_TXBEIEN); +} + +/** + * @brief Enable Parity Error Interrupt + * @param USARTx USART Instance + * @retval None + */ +__STATIC_INLINE void DDL_USART_EnableIT_PE(USART_TypeDef *USARTx) +{ + ATOMIC_SET_BIT(USARTx->CTRL1, USART_CTRL1_PEIEN); +} + +/** + * @brief Enable LIN Break Detection Interrupt + * @note Macro @ref IS_UART_LIN_INSTANCE(USARTx) can be used to check whether or not + * LIN feature is supported by the USARTx instance. + * @param USARTx USART Instance + * @retval None + */ +__STATIC_INLINE void DDL_USART_EnableIT_LBD(USART_TypeDef *USARTx) +{ + SET_BIT(USARTx->CTRL2, USART_CTRL2_LBDIEN); +} + +/** + * @brief Enable Error Interrupt + * @note When set, Error Interrupt Enable Bit is enabling interrupt generation in case of a framing + * error, overrun error or noise flag (FE=1 or ORE=1 or NF=1 in the USARTx_SR register). + * 0: Interrupt is inhibited + * 1: An interrupt is generated when FE=1 or ORE=1 or NF=1 in the USARTx_SR register. + * @param USARTx USART Instance + * @retval None + */ +__STATIC_INLINE void DDL_USART_EnableIT_ERROR(USART_TypeDef *USARTx) +{ + ATOMIC_SET_BIT(USARTx->CTRL3, USART_CTRL3_ERRIEN); +} + +/** + * @brief Enable CTS Interrupt + * @note Macro @ref IS_UART_HWFLOW_INSTANCE(USARTx) can be used to check whether or not + * Hardware Flow control feature is supported by the USARTx instance. + * @param USARTx USART Instance + * @retval None + */ +__STATIC_INLINE void DDL_USART_EnableIT_CTS(USART_TypeDef *USARTx) +{ + ATOMIC_SET_BIT(USARTx->CTRL3, USART_CTRL3_CTSIEN); +} + +/** + * @brief Disable IDLE Interrupt + * @param USARTx USART Instance + * @retval None + */ +__STATIC_INLINE void DDL_USART_DisableIT_IDLE(USART_TypeDef *USARTx) +{ + ATOMIC_CLEAR_BIT(USARTx->CTRL1, USART_CTRL1_IDLEIEN); +} + +/** + * @brief Disable RX Not Empty Interrupt + * @param USARTx USART Instance + * @retval None + */ +__STATIC_INLINE void DDL_USART_DisableIT_RXNE(USART_TypeDef *USARTx) +{ + ATOMIC_CLEAR_BIT(USARTx->CTRL1, USART_CTRL1_RXBNEIEN); +} + +/** + * @brief Disable Transmission Complete Interrupt + * @param USARTx USART Instance + * @retval None + */ +__STATIC_INLINE void DDL_USART_DisableIT_TC(USART_TypeDef *USARTx) +{ + ATOMIC_CLEAR_BIT(USARTx->CTRL1, USART_CTRL1_TXCIEN); +} + +/** + * @brief Disable TX Empty Interrupt + * @param USARTx USART Instance + * @retval None + */ +__STATIC_INLINE void DDL_USART_DisableIT_TXE(USART_TypeDef *USARTx) +{ + ATOMIC_CLEAR_BIT(USARTx->CTRL1, USART_CTRL1_TXBEIEN); +} + +/** + * @brief Disable Parity Error Interrupt + * @param USARTx USART Instance + * @retval None + */ +__STATIC_INLINE void DDL_USART_DisableIT_PE(USART_TypeDef *USARTx) +{ + ATOMIC_CLEAR_BIT(USARTx->CTRL1, USART_CTRL1_PEIEN); +} + +/** + * @brief Disable LIN Break Detection Interrupt + * @note Macro @ref IS_UART_LIN_INSTANCE(USARTx) can be used to check whether or not + * LIN feature is supported by the USARTx instance. + * @param USARTx USART Instance + * @retval None + */ +__STATIC_INLINE void DDL_USART_DisableIT_LBD(USART_TypeDef *USARTx) +{ + CLEAR_BIT(USARTx->CTRL2, USART_CTRL2_LBDIEN); +} + +/** + * @brief Disable Error Interrupt + * @note When set, Error Interrupt Enable Bit is enabling interrupt generation in case of a framing + * error, overrun error or noise flag (FE=1 or ORE=1 or NF=1 in the USARTx_SR register). + * 0: Interrupt is inhibited + * 1: An interrupt is generated when FE=1 or ORE=1 or NF=1 in the USARTx_SR register. + * @param USARTx USART Instance + * @retval None + */ +__STATIC_INLINE void DDL_USART_DisableIT_ERROR(USART_TypeDef *USARTx) +{ + ATOMIC_CLEAR_BIT(USARTx->CTRL3, USART_CTRL3_ERRIEN); +} + +/** + * @brief Disable CTS Interrupt + * @note Macro @ref IS_UART_HWFLOW_INSTANCE(USARTx) can be used to check whether or not + * Hardware Flow control feature is supported by the USARTx instance. + * @param USARTx USART Instance + * @retval None + */ +__STATIC_INLINE void DDL_USART_DisableIT_CTS(USART_TypeDef *USARTx) +{ + ATOMIC_CLEAR_BIT(USARTx->CTRL3, USART_CTRL3_CTSIEN); +} + +/** + * @brief Check if the USART IDLE Interrupt source is enabled or disabled. + * @param USARTx USART Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_USART_IsEnabledIT_IDLE(USART_TypeDef *USARTx) +{ + return (READ_BIT(USARTx->CTRL1, USART_CTRL1_IDLEIEN) == (USART_CTRL1_IDLEIEN)); +} + +/** + * @brief Check if the USART RX Not Empty Interrupt is enabled or disabled. + * @param USARTx USART Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_USART_IsEnabledIT_RXNE(USART_TypeDef *USARTx) +{ + return (READ_BIT(USARTx->CTRL1, USART_CTRL1_RXBNEIEN) == (USART_CTRL1_RXBNEIEN)); +} + +/** + * @brief Check if the USART Transmission Complete Interrupt is enabled or disabled. + * @param USARTx USART Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_USART_IsEnabledIT_TC(USART_TypeDef *USARTx) +{ + return (READ_BIT(USARTx->CTRL1, USART_CTRL1_TXCIEN) == (USART_CTRL1_TXCIEN)); +} + +/** + * @brief Check if the USART TX Empty Interrupt is enabled or disabled. + * @param USARTx USART Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_USART_IsEnabledIT_TXE(USART_TypeDef *USARTx) +{ + return (READ_BIT(USARTx->CTRL1, USART_CTRL1_TXBEIEN) == (USART_CTRL1_TXBEIEN)); +} + +/** + * @brief Check if the USART Parity Error Interrupt is enabled or disabled. + * @param USARTx USART Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_USART_IsEnabledIT_PE(USART_TypeDef *USARTx) +{ + return (READ_BIT(USARTx->CTRL1, USART_CTRL1_PEIEN) == (USART_CTRL1_PEIEN)); +} + +/** + * @brief Check if the USART LIN Break Detection Interrupt is enabled or disabled. + * @note Macro @ref IS_UART_LIN_INSTANCE(USARTx) can be used to check whether or not + * LIN feature is supported by the USARTx instance. + * @param USARTx USART Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_USART_IsEnabledIT_LBD(USART_TypeDef *USARTx) +{ + return (READ_BIT(USARTx->CTRL2, USART_CTRL2_LBDIEN) == (USART_CTRL2_LBDIEN)); +} + +/** + * @brief Check if the USART Error Interrupt is enabled or disabled. + * @param USARTx USART Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_USART_IsEnabledIT_ERROR(USART_TypeDef *USARTx) +{ + return (READ_BIT(USARTx->CTRL3, USART_CTRL3_ERRIEN) == (USART_CTRL3_ERRIEN)); +} + +/** + * @brief Check if the USART CTS Interrupt is enabled or disabled. + * @note Macro @ref IS_UART_HWFLOW_INSTANCE(USARTx) can be used to check whether or not + * Hardware Flow control feature is supported by the USARTx instance. + * @param USARTx USART Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_USART_IsEnabledIT_CTS(USART_TypeDef *USARTx) +{ + return (READ_BIT(USARTx->CTRL3, USART_CTRL3_CTSIEN) == (USART_CTRL3_CTSIEN)); +} + +/** + * @} + */ + +/** @defgroup USART_DDL_EF_DMA_Management DMA_Management + * @{ + */ + +/** + * @brief Enable DMA Mode for reception + * @param USARTx USART Instance + * @retval None + */ +__STATIC_INLINE void DDL_USART_EnableDMAReq_RX(USART_TypeDef *USARTx) +{ + ATOMIC_SET_BIT(USARTx->CTRL3, USART_CTRL3_DMARXEN); +} + +/** + * @brief Disable DMA Mode for reception + * @param USARTx USART Instance + * @retval None + */ +__STATIC_INLINE void DDL_USART_DisableDMAReq_RX(USART_TypeDef *USARTx) +{ + ATOMIC_CLEAR_BIT(USARTx->CTRL3, USART_CTRL3_DMARXEN); +} + +/** + * @brief Check if DMA Mode is enabled for reception + * @param USARTx USART Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_USART_IsEnabledDMAReq_RX(USART_TypeDef *USARTx) +{ + return (READ_BIT(USARTx->CTRL3, USART_CTRL3_DMARXEN) == (USART_CTRL3_DMARXEN)); +} + +/** + * @brief Enable DMA Mode for transmission + * @param USARTx USART Instance + * @retval None + */ +__STATIC_INLINE void DDL_USART_EnableDMAReq_TX(USART_TypeDef *USARTx) +{ + ATOMIC_SET_BIT(USARTx->CTRL3, USART_CTRL3_DMATXEN); +} + +/** + * @brief Disable DMA Mode for transmission + * @param USARTx USART Instance + * @retval None + */ +__STATIC_INLINE void DDL_USART_DisableDMAReq_TX(USART_TypeDef *USARTx) +{ + ATOMIC_CLEAR_BIT(USARTx->CTRL3, USART_CTRL3_DMATXEN); +} + +/** + * @brief Check if DMA Mode is enabled for transmission + * @param USARTx USART Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_USART_IsEnabledDMAReq_TX(USART_TypeDef *USARTx) +{ + return (READ_BIT(USARTx->CTRL3, USART_CTRL3_DMATXEN) == (USART_CTRL3_DMATXEN)); +} + +/** + * @brief Get the data register address used for DMA transfer + * @note Address of Data Register is valid for both Transmit and Receive transfers. + * @param USARTx USART Instance + * @retval Address of data register + */ +__STATIC_INLINE uint32_t DDL_USART_DMA_GetRegAddr(USART_TypeDef *USARTx) +{ + /* return address of DR register */ + return ((uint32_t) &(USARTx->DATA)); +} + +/** + * @} + */ + +/** @defgroup USART_DDL_EF_Data_Management Data_Management + * @{ + */ + +/** + * @brief Read Receiver Data register (Receive Data value, 8 bits) + * @param USARTx USART Instance + * @retval Value between Min_Data=0x00 and Max_Data=0xFF + */ +__STATIC_INLINE uint8_t DDL_USART_ReceiveData8(USART_TypeDef *USARTx) +{ + return (uint8_t)(READ_BIT(USARTx->DATA, USART_DATA_DATA)); +} + +/** + * @brief Read Receiver Data register (Receive Data value, 9 bits) + * @param USARTx USART Instance + * @retval Value between Min_Data=0x00 and Max_Data=0x1FF + */ +__STATIC_INLINE uint16_t DDL_USART_ReceiveData9(USART_TypeDef *USARTx) +{ + return (uint16_t)(READ_BIT(USARTx->DATA, USART_DATA_DATA)); +} + +/** + * @brief Write in Transmitter Data Register (Transmit Data value, 8 bits) + * @param USARTx USART Instance + * @param Value between Min_Data=0x00 and Max_Data=0xFF + * @retval None + */ +__STATIC_INLINE void DDL_USART_TransmitData8(USART_TypeDef *USARTx, uint8_t Value) +{ + USARTx->DATA = Value; +} + +/** + * @brief Write in Transmitter Data Register (Transmit Data value, 9 bits) + * @param USARTx USART Instance + * @param Value between Min_Data=0x00 and Max_Data=0x1FF + * @retval None + */ +__STATIC_INLINE void DDL_USART_TransmitData9(USART_TypeDef *USARTx, uint16_t Value) +{ + USARTx->DATA = Value & 0x1FFU; +} + +/** + * @} + */ + +/** @defgroup USART_DDL_EF_Execution Execution + * @{ + */ + +/** + * @brief Request Break sending + * @param USARTx USART Instance + * @retval None + */ +__STATIC_INLINE void DDL_USART_RequestBreakSending(USART_TypeDef *USARTx) +{ + SET_BIT(USARTx->CTRL1, USART_CTRL1_TXBF); +} + +/** + * @brief Put USART in Mute mode + * @param USARTx USART Instance + * @retval None + */ +__STATIC_INLINE void DDL_USART_RequestEnterMuteMode(USART_TypeDef *USARTx) +{ + SET_BIT(USARTx->CTRL1, USART_CTRL1_RXMUTEEN); +} + +/** + * @brief Put USART in Active mode + * @param USARTx USART Instance + * @retval None + */ +__STATIC_INLINE void DDL_USART_RequestExitMuteMode(USART_TypeDef *USARTx) +{ + CLEAR_BIT(USARTx->CTRL1, USART_CTRL1_RXMUTEEN); +} + +/** + * @} + */ + +#if defined(USE_FULL_DDL_DRIVER) +/** @defgroup USART_DDL_EF_Init Initialization and de-initialization functions + * @{ + */ +ErrorStatus DDL_USART_DeInit(USART_TypeDef *USARTx); +ErrorStatus DDL_USART_Init(USART_TypeDef *USARTx, DDL_USART_InitTypeDef *USART_InitStruct); +void DDL_USART_StructInit(DDL_USART_InitTypeDef *USART_InitStruct); +ErrorStatus DDL_USART_ClockInit(USART_TypeDef *USARTx, DDL_USART_ClockInitTypeDef *USART_ClockInitStruct); +void DDL_USART_ClockStructInit(DDL_USART_ClockInitTypeDef *USART_ClockInitStruct); +/** + * @} + */ +#endif /* USE_FULL_DDL_DRIVER */ + +/** + * @} + */ + +/** + * @} + */ + +#endif /* USART1 || USART2 || USART3 || USART6 || UART4 || UART5 || UART7 || UART8 || UART9 || UART10 */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* APM32F4xx_DDL_USART_H */ + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_usb.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_usb.h new file mode 100644 index 0000000000..5b29e4c17a --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_usb.h @@ -0,0 +1,631 @@ +/** + * + * @file apm32f4xx_ddl_usb.h + * @brief Header file of USB Low Layer DDL module. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef APM32F4xx_DDL_USB_H +#define APM32F4xx_DDL_USB_H + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal_def.h" + +#if defined (USB_OTG_FS) || defined (USB_OTG_HS) +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @addtogroup USB_DDL + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ + +/** + * @brief USB Mode definition + */ +#if defined (USB_OTG_FS) || defined (USB_OTG_HS) + +typedef enum +{ + USB_DEVICE_MODE = 0, + USB_HOST_MODE = 1, + USB_DRD_MODE = 2 +} USB_OTG_ModeTypeDef; + +/** + * @brief URB States definition + */ +typedef enum +{ + URB_IDLE = 0, + URB_DONE, + URB_NOTREADY, + URB_NYET, + URB_ERROR, + URB_STALL +} USB_OTG_URBStateTypeDef; + +/** + * @brief USB URB status + */ +typedef enum +{ + USB_URB_IDLE, + USB_URB_NOREADY, + USB_URB_STALL, + USB_URB_ERROR, + USB_URB_NYET, + USB_URB_OK, +} USB_OTG_URB_STA_T; + +/** + * @brief USB host PID type of data + */ +typedef enum +{ + USBH_PID_SETUP, + USBH_PID_DATA, +} USBH_PID_T; + +/** + * @brief USB host port speed type + */ +typedef enum +{ + USBH_PORT_SPEED_HS, + USBH_PORT_SPEED_FS, + USBH_PORT_SPEED_LS +} USBH_SPEED_TYPE_T; + +/** + * @brief Host channel States definition + */ +typedef enum +{ + HC_IDLE = 0, + HC_XFRC, + HC_HALTED, + HC_NAK, + HC_NYET, + HC_STALL, + HC_XACTERR, + HC_BBLERR, + HC_DATATGLERR +} USB_OTG_HCStateTypeDef; + +/** + * @brief USB endpoint type + */ +typedef enum +{ + EP_TYPE_CONTROL, + EP_TYPE_ISO, + EP_TYPE_BULK, + EP_TYPE_INTERRUPT +} USB_EP_TYPE_T; + +/** + * @brief USB endpoint direction + */ +typedef enum +{ + EP_DIR_OUT, + EP_DIR_IN +} USB_EP_DIR_T; + +/** + * @brief USB device endpoint id + */ +typedef enum +{ + USBD_EP_0, + USBD_EP_1, + USBD_EP_2, + USBD_EP_3, + USBD_EP_4, + USBD_EP_5, + USBD_EP_6, + USBD_EP_7, +} USBD_EP_ID_T; + +/** + * @brief USB Instance Initialization Structure definition + */ +typedef struct +{ + uint32_t dev_endpoints; /*!< Device Endpoints number. + This parameter depends on the used USB core. + This parameter must be a number between Min_Data = 1 and Max_Data = 15 */ + + uint32_t Host_channels; /*!< Host Channels number. + This parameter Depends on the used USB core. + This parameter must be a number between Min_Data = 1 and Max_Data = 15 */ + + uint32_t speed; /*!< USB Core speed. + This parameter can be any value of @ref PCD_Speed/HCD_Speed + (HCD_SPEED_xxx, HCD_SPEED_xxx) */ + + uint32_t dma_enable; /*!< Enable or disable of the USB embedded DMA used only for OTG HS. */ + + uint32_t ep0_mps; /*!< Set the Endpoint 0 Max Packet size. */ + + uint32_t phy_itface; /*!< Select the used PHY interface. + This parameter can be any value of @ref PCD_PHY_Module/HCD_PHY_Module */ + + uint32_t Sof_enable; /*!< Enable or disable the output of the SOF signal. */ + + uint32_t low_power_enable; /*!< Enable or disable the low power mode. */ + + uint32_t lpm_enable; /*!< Enable or disable Link Power Management. */ + + uint32_t battery_charging_enable; /*!< Enable or disable Battery charging. */ + + uint32_t vbus_sensing_enable; /*!< Enable or disable the VBUS Sensing feature. */ + + uint32_t use_dedicated_ep1; /*!< Enable or disable the use of the dedicated EP1 interrupt. */ + + uint32_t use_external_vbus; /*!< Enable or disable the use of the external VBUS. */ + +} USB_OTG_CfgTypeDef; + +typedef struct +{ + uint8_t num; /*!< Endpoint number + This parameter must be a number between Min_Data = 1 and Max_Data = 15 */ + + uint8_t is_in; /*!< Endpoint direction + This parameter must be a number between Min_Data = 0 and Max_Data = 1 */ + + uint8_t is_stall; /*!< Endpoint stall condition + This parameter must be a number between Min_Data = 0 and Max_Data = 1 */ + + uint8_t is_iso_incomplete; /*!< Endpoint isoc condition + This parameter must be a number between Min_Data = 0 and Max_Data = 1 */ + + uint8_t type; /*!< Endpoint type + This parameter can be any value of @ref USB_DDL_EP_Type */ + + uint8_t data_pid_start; /*!< Initial data PID + This parameter must be a number between Min_Data = 0 and Max_Data = 1 */ + + uint8_t even_odd_frame; /*!< IFrame parity + This parameter must be a number between Min_Data = 0 and Max_Data = 1 */ + + uint16_t tx_fifo_num; /*!< Transmission FIFO number + This parameter must be a number between Min_Data = 1 and Max_Data = 15 */ + + uint32_t maxpacket; /*!< Endpoint Max packet size + This parameter must be a number between Min_Data = 0 and Max_Data = 64KB */ + + uint8_t *xfer_buff; /*!< Pointer to transfer buffer */ + + uint32_t dma_addr; /*!< 32 bits aligned transfer buffer address */ + + uint32_t xfer_len; /*!< Current transfer length */ + + uint32_t xfer_size; /*!< requested transfer size */ + + uint32_t xfer_count; /*!< Partial transfer length in case of multi packet transfer */ +} USB_OTG_EPTypeDef; + +typedef struct +{ + uint8_t dev_addr; /*!< USB device address. + This parameter must be a number between Min_Data = 1 and Max_Data = 255 */ + + uint8_t ch_num; /*!< Host channel number. + This parameter must be a number between Min_Data = 1 and Max_Data = 15 */ + + uint8_t ep_num; /*!< Endpoint number. + This parameter must be a number between Min_Data = 1 and Max_Data = 15 */ + + uint8_t ep_is_in; /*!< Endpoint direction + This parameter must be a number between Min_Data = 0 and Max_Data = 1 */ + + uint8_t speed; /*!< USB Host Channel speed. + This parameter can be any value of @ref HCD_Device_Speed: + (HCD_DEVICE_SPEED_xxx) */ + + uint8_t do_ping; /*!< Enable or disable the use of the PING protocol for HS mode. */ + + uint8_t process_ping; /*!< Execute the PING protocol for HS mode. */ + + uint8_t ep_type; /*!< Endpoint Type. + This parameter can be any value of @ref USB_DDL_EP_Type */ + + uint16_t max_packet; /*!< Endpoint Max packet size. + This parameter must be a number between Min_Data = 0 and Max_Data = 64KB */ + + uint8_t data_pid; /*!< Initial data PID. + This parameter must be a number between Min_Data = 0 and Max_Data = 1 */ + + uint8_t *xfer_buff; /*!< Pointer to transfer buffer. */ + + uint32_t XferSize; /*!< OTG Channel transfer size. */ + + uint32_t xfer_len; /*!< Current transfer length. */ + + uint32_t xfer_count; /*!< Partial transfer length in case of multi packet transfer. */ + + uint8_t toggle_in; /*!< IN transfer current toggle flag. + This parameter must be a number between Min_Data = 0 and Max_Data = 1 */ + + uint8_t toggle_out; /*!< OUT transfer current toggle flag + This parameter must be a number between Min_Data = 0 and Max_Data = 1 */ + + uint32_t dma_addr; /*!< 32 bits aligned transfer buffer address. */ + + uint32_t ErrCnt; /*!< Host channel error count. */ + + USB_OTG_URBStateTypeDef urb_state; /*!< URB state. + This parameter can be any value of @ref USB_OTG_URBStateTypeDef */ + + USB_OTG_HCStateTypeDef state; /*!< Host Channel state. + This parameter can be any value of @ref USB_OTG_HCStateTypeDef */ +} USB_OTG_HCTypeDef; +#endif /* defined (USB_OTG_FS) || defined (USB_OTG_HS) */ + + +/* Exported constants --------------------------------------------------------*/ + +/** @defgroup PCD_Exported_Constants PCD Exported Constants + * @{ + */ + +#if defined (USB_OTG_FS) || defined (USB_OTG_HS) +/** @defgroup USB_OTG_CORE VERSION ID + * @{ + */ +#define USB_OTG_CORE_ID_300A 0x4F54300AU +#define USB_OTG_CORE_ID_310A 0x4F54310AU +/** + * @} + */ + +/** @defgroup USB_Core_Mode_ USB Core Mode + * @{ + */ +#define USB_OTG_MODE_DEVICE 0U +#define USB_OTG_MODE_HOST 1U +#define USB_OTG_MODE_DRD 2U +/** + * @} + */ + +/** @defgroup USB_LL Device Speed + * @{ + */ +#define USBD_HS_SPEED 0U +#define USBD_HSINFS_SPEED 1U +#define USBH_HS_SPEED 0U +#define USBD_FS_SPEED 2U +#define USBH_FSLS_SPEED 1U +/** + * @} + */ + +/** @defgroup USB_DDL_Core_Speed USB Low Layer Core Speed + * @{ + */ +#define USB_OTG_SPEED_HIGH 0U +#define USB_OTG_SPEED_HIGH_IN_FULL 1U +#define USB_OTG_SPEED_FULL 3U +/** + * @} + */ + +/** @defgroup USB_DDL_Core_PHY USB Low Layer Core PHY + * @{ + */ +#define USB_OTG_ULPI_PHY 1U +#define USB_OTG_EMBEDDED_PHY 2U +/** + * @} + */ + +/** @defgroup USB_DDL_Turnaround_Timeout Turnaround Timeout Value + * @{ + */ +#ifndef USBD_HS_TRDT_VALUE +#define USBD_HS_TRDT_VALUE 9U +#endif /* USBD_HS_TRDT_VALUE */ +#ifndef USBD_FS_TRDT_VALUE +#define USBD_FS_TRDT_VALUE 5U +#define USBD_DEFAULT_TRDT_VALUE 9U +#endif /* USBD_HS_TRDT_VALUE */ +/** + * @} + */ + +/** @defgroup USB_DDL_Core_MPS USB Low Layer Core MPS + * @{ + */ +#define USB_OTG_HS_MAX_PACKET_SIZE 512U +#define USB_OTG_FS_MAX_PACKET_SIZE 64U +#define USB_OTG_MAX_EP0_SIZE 64U +/** + * @} + */ + +/** @defgroup USB_DDL_Core_PHY_Frequency USB Low Layer Core PHY Frequency + * @{ + */ +#define DSTS_ENUMSPD_HS_PHY_30MHZ_OR_60MHZ (0U << 1) +#define DSTS_ENUMSPD_FS_PHY_30MHZ_OR_60MHZ (1U << 1) +#define DSTS_ENUMSPD_FS_PHY_48MHZ (3U << 1) +/** + * @} + */ + +/** @defgroup USB_DDL_CORE_Frame_Interval USB Low Layer Core Frame Interval + * @{ + */ +#define DCFG_FRAME_INTERVAL_80 0U +#define DCFG_FRAME_INTERVAL_85 1U +#define DCFG_FRAME_INTERVAL_90 2U +#define DCFG_FRAME_INTERVAL_95 3U +/** + * @} + */ + +/** @defgroup USB_DDL_EP0_MPS USB Low Layer EP0 MPS + * @{ + */ +#define EP_MPS_64 0U +#define EP_MPS_32 1U +#define EP_MPS_16 2U +#define EP_MPS_8 3U +/** + * @} + */ + +/** @defgroup USB_DDL_EP_Speed USB Low Layer EP Speed + * @{ + */ +#define EP_SPEED_LOW 0U +#define EP_SPEED_FULL 1U +#define EP_SPEED_HIGH 2U +/** + * @} + */ + +/** @defgroup USB_DDL_EP_Type USB Low Layer EP Type + * @{ + */ +#define EP_TYPE_CTRL 0U +#define EP_TYPE_ISOC 1U +#define EP_TYPE_BULK 2U +#define EP_TYPE_INTR 3U +#define EP_TYPE_MSK 3U +/** + * @} + */ + +/** @defgroup USB_DDL_STS_Defines USB Low Layer STS Defines + * @{ + */ +#define STS_GOUT_NAK 1U +#define STS_DATA_UPDT 2U +#define STS_XFER_COMP 3U +#define STS_SETUP_COMP 4U +#define STS_SETUP_UPDT 6U +/** + * @} + */ + +/** @defgroup USB_DDL_HCFG_SPEED_Defines USB Low Layer HCFG Speed Defines + * @{ + */ +#define HCFG_30_60_MHZ 0U +#define HCFG_48_MHZ 1U +#define HCFG_6_MHZ 2U +/** + * @} + */ + +/** @defgroup USB_DDL_HPRT0_PRTSPD_SPEED_Defines USB Low Layer HPRT0 PRTSPD Speed Defines + * @{ + */ +#define HPRT0_PRTSPD_HIGH_SPEED 0U +#define HPRT0_PRTSPD_FULL_SPEED 1U +#define HPRT0_PRTSPD_LOW_SPEED 2U +/** + * @} + */ + +#define HCCHAR_CTRL 0U +#define HCCHAR_ISOC 1U +#define HCCHAR_BULK 2U +#define HCCHAR_INTR 3U + +#define HC_PID_DATA0 0U +#define HC_PID_DATA2 1U +#define HC_PID_DATA1 2U +#define HC_PID_SETUP 3U + +#define GRXSTS_PKTSTS_IN 2U +#define GRXSTS_PKTSTS_IN_XFER_COMP 3U +#define GRXSTS_PKTSTS_DATA_TOGGLE_ERR 5U +#define GRXSTS_PKTSTS_CH_HALTED 7U + +#define TEST_J 1U +#define TEST_K 2U +#define TEST_SE0_NAK 3U +#define TEST_PACKET 4U +#define TEST_FORCE_EN 5U + +#define USBx_PCGCCTL *(__IO uint32_t *)((uint32_t)USBx_BASE + USB_OTG_PCGCCTL_BASE) +#define USBx_HPRT0 *(__IO uint32_t *)((uint32_t)USBx_BASE + USB_OTG_HOST_PORT_BASE) + +#define USBx_DEVICE ((USB_OTG_DeviceTypeDef *)(USBx_BASE + USB_OTG_DEVICE_BASE)) +#define USBx_INEP(i) ((USB_OTG_INEndpointTypeDef *)(USBx_BASE\ + + USB_OTG_IN_ENDPOINT_BASE + ((i) * USB_OTG_EP_REG_SIZE))) + +#define USBx_OUTEP(i) ((USB_OTG_OUTEndpointTypeDef *)(USBx_BASE\ + + USB_OTG_OUT_ENDPOINT_BASE + ((i) * USB_OTG_EP_REG_SIZE))) + +#define USBx_DFIFO(i) *(__IO uint32_t *)(USBx_BASE + USB_OTG_FIFO_BASE + ((i) * USB_OTG_FIFO_SIZE)) + +#define USBx_HOST ((USB_OTG_HostTypeDef *)(USBx_BASE + USB_OTG_HOST_BASE)) +#define USBx_HC(i) ((USB_OTG_HostChannelTypeDef *)(USBx_BASE\ + + USB_OTG_HOST_CHANNEL_BASE\ + + ((i) * USB_OTG_HOST_CHANNEL_SIZE))) + +#endif /* defined (USB_OTG_FS) || defined (USB_OTG_HS) */ + +#define EP_ADDR_MSK 0xFU + +#ifndef USE_USB_DOUBLE_BUFFER +#define USE_USB_DOUBLE_BUFFER 1U +#endif /* USE_USB_DOUBLE_BUFFER */ +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ +/** @defgroup USB_DDL_Exported_Macros USB Low Layer Exported Macros + * @{ + */ +#if defined (USB_OTG_FS) || defined (USB_OTG_HS) +#define USB_MASK_INTERRUPT(__INSTANCE__, __INTERRUPT__) ((__INSTANCE__)->GINTMASK &= ~(__INTERRUPT__)) +#define USB_UNMASK_INTERRUPT(__INSTANCE__, __INTERRUPT__) ((__INSTANCE__)->GINTMASK |= (__INTERRUPT__)) + +#define CLEAR_IN_EP_INTR(__EPNUM__, __INTERRUPT__) (USBx_INEP(__EPNUM__)->DIEPINT = (__INTERRUPT__)) +#define CLEAR_OUT_EP_INTR(__EPNUM__, __INTERRUPT__) (USBx_OUTEP(__EPNUM__)->DOEPINT = (__INTERRUPT__)) + +#if defined(APM32F405xx) || defined(APM32F407xx) || defined(APM32F417xx) +#define USB_HS2_POWER_CORE_ENABLE() (USB_OTG_HS2->POWERON_CORE |= USB_OTG_HS2_POWERON_CORE) +#endif /* APM32F405xx || APM32F407xx || APM32F417xx */ + +#endif /* defined (USB_OTG_FS) || defined (USB_OTG_HS) */ +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup USB_DDL_Exported_Functions USB Low Layer Exported Functions + * @{ + */ +#if defined (USB_OTG_FS) || defined (USB_OTG_HS) +DAL_StatusTypeDef USB_CoreInit(USB_OTG_GlobalTypeDef *USBx, USB_OTG_CfgTypeDef cfg); +DAL_StatusTypeDef USB_DevInit(USB_OTG_GlobalTypeDef *USBx, USB_OTG_CfgTypeDef cfg); +DAL_StatusTypeDef USB_EnableGlobalInt(USB_OTG_GlobalTypeDef *USBx); +DAL_StatusTypeDef USB_DisableGlobalInt(USB_OTG_GlobalTypeDef *USBx); +DAL_StatusTypeDef USB_SetTurnaroundTime(USB_OTG_GlobalTypeDef *USBx, uint32_t hclk, uint8_t speed); +DAL_StatusTypeDef USB_SetCurrentMode(USB_OTG_GlobalTypeDef *USBx, USB_OTG_ModeTypeDef mode); +DAL_StatusTypeDef USB_SetDevSpeed(USB_OTG_GlobalTypeDef *USBx, uint8_t speed); +DAL_StatusTypeDef USB_FlushRxFifo(USB_OTG_GlobalTypeDef *USBx); +DAL_StatusTypeDef USB_FlushTxFifo(USB_OTG_GlobalTypeDef *USBx, uint32_t num); +DAL_StatusTypeDef USB_ActivateEndpoint(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTypeDef *ep); +DAL_StatusTypeDef USB_DeactivateEndpoint(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTypeDef *ep); +DAL_StatusTypeDef USB_ActivateDedicatedEndpoint(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTypeDef *ep); +DAL_StatusTypeDef USB_DeactivateDedicatedEndpoint(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTypeDef *ep); +DAL_StatusTypeDef USB_EPStartXfer(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTypeDef *ep, uint8_t dma); +DAL_StatusTypeDef USB_EP0StartXfer(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTypeDef *ep, uint8_t dma); +DAL_StatusTypeDef USB_WritePacket(USB_OTG_GlobalTypeDef *USBx, uint8_t *src, + uint8_t ch_ep_num, uint16_t len, uint8_t dma); + +void *USB_ReadPacket(USB_OTG_GlobalTypeDef *USBx, uint8_t *dest, uint16_t len); +DAL_StatusTypeDef USB_EPSetStall(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTypeDef *ep); +DAL_StatusTypeDef USB_EPClearStall(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTypeDef *ep); +DAL_StatusTypeDef USB_EPStopXfer(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTypeDef *ep); +DAL_StatusTypeDef USB_SetDevAddress(USB_OTG_GlobalTypeDef *USBx, uint8_t address); +DAL_StatusTypeDef USB_DevConnect(USB_OTG_GlobalTypeDef *USBx); +DAL_StatusTypeDef USB_DevDisconnect(USB_OTG_GlobalTypeDef *USBx); +DAL_StatusTypeDef USB_StopDevice(USB_OTG_GlobalTypeDef *USBx); +DAL_StatusTypeDef USB_ActivateSetup(USB_OTG_GlobalTypeDef *USBx); +DAL_StatusTypeDef USB_EP0_OutStart(USB_OTG_GlobalTypeDef *USBx, uint8_t dma, uint8_t *psetup); +uint8_t USB_GetDevSpeed(USB_OTG_GlobalTypeDef *USBx); +uint32_t USB_GetMode(USB_OTG_GlobalTypeDef *USBx); +uint32_t USB_ReadInterrupts(USB_OTG_GlobalTypeDef *USBx); +uint32_t USB_ReadDevAllOutEpInterrupt(USB_OTG_GlobalTypeDef *USBx); +uint32_t USB_ReadDevOutEPInterrupt(USB_OTG_GlobalTypeDef *USBx, uint8_t epnum); +uint32_t USB_ReadDevAllInEpInterrupt(USB_OTG_GlobalTypeDef *USBx); +uint32_t USB_ReadDevInEPInterrupt(USB_OTG_GlobalTypeDef *USBx, uint8_t epnum); +void USB_ClearInterrupts(USB_OTG_GlobalTypeDef *USBx, uint32_t interrupt); + +DAL_StatusTypeDef USB_HostInit(USB_OTG_GlobalTypeDef *USBx, USB_OTG_CfgTypeDef cfg); +DAL_StatusTypeDef USB_InitFSLSPClkSel(USB_OTG_GlobalTypeDef *USBx, uint8_t freq); +DAL_StatusTypeDef USB_ResetPort(USB_OTG_GlobalTypeDef *USBx); +DAL_StatusTypeDef USB_DriveVbus(USB_OTG_GlobalTypeDef *USBx, uint8_t state); +uint32_t USB_GetHostSpeed(USB_OTG_GlobalTypeDef *USBx); +uint32_t USB_GetCurrentFrame(USB_OTG_GlobalTypeDef *USBx); +DAL_StatusTypeDef USB_HC_Init(USB_OTG_GlobalTypeDef *USBx, uint8_t ch_num, + uint8_t epnum, uint8_t dev_address, uint8_t speed, + uint8_t ep_type, uint16_t mps); +DAL_StatusTypeDef USB_HC_StartXfer(USB_OTG_GlobalTypeDef *USBx, + USB_OTG_HCTypeDef *hc, uint8_t dma); + +uint32_t USB_HC_ReadInterrupt(USB_OTG_GlobalTypeDef *USBx); +DAL_StatusTypeDef USB_HC_Halt(USB_OTG_GlobalTypeDef *USBx, uint8_t hc_num); +DAL_StatusTypeDef USB_DoPing(USB_OTG_GlobalTypeDef *USBx, uint8_t ch_num); +DAL_StatusTypeDef USB_StopHost(USB_OTG_GlobalTypeDef *USBx); +DAL_StatusTypeDef USB_ActivateRemoteWakeup(USB_OTG_GlobalTypeDef *USBx); +DAL_StatusTypeDef USB_DeActivateRemoteWakeup(USB_OTG_GlobalTypeDef *USBx); +#endif /* defined (USB_OTG_FS) || defined (USB_OTG_HS) */ + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ +#endif /* defined (USB_OTG_FS) || defined (USB_OTG_HS) */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + + +#endif /* APM32F4xx_DDL_USB_H */ diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_utils.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_utils.h new file mode 100644 index 0000000000..f422ca45e1 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_utils.h @@ -0,0 +1,331 @@ +/** + * + * @file apm32f4xx_ddl_utils.h + * @brief Header file of UTILS DDL module. + @verbatim + ============================================================================== + ##### How to use this driver ##### + ============================================================================== + [..] + The LL UTILS driver contains a set of generic APIs that can be + used by user: + (+) Device electronic signature + (+) Timing functions + (+) PLL configuration functions + + @endverbatim + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2017 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef APM32F4xx_DDL_UTILS_H +#define APM32F4xx_DDL_UTILS_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx.h" + +/** @addtogroup APM32F4xx_DDL_Driver + * @{ + */ + +/** @defgroup UTILS_DDL UTILS + * @{ + */ + +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ + +/* Private constants ---------------------------------------------------------*/ +/** @defgroup UTILS_DDL_Private_Constants UTILS Private Constants + * @{ + */ + +/* Max delay can be used in DDL_mDelay */ +#define DDL_MAX_DELAY 0xFFFFFFFFU + +/** + * @brief Unique device ID register base address + */ +#define UID_BASE_ADDRESS UID_BASE + +/** + * @brief Flash size data register base address + */ +#define FLASHSIZE_BASE_ADDRESS FLASHSIZE_BASE + +/** + * @brief Package data register base address + */ +#define PACKAGE_BASE_ADDRESS PACKAGE_BASE + +/** + * @} + */ + +/* Private macros ------------------------------------------------------------*/ +/** @defgroup UTILS_DDL_Private_Macros UTILS Private Macros + * @{ + */ +/** + * @} + */ +/* Exported types ------------------------------------------------------------*/ +/** @defgroup UTILS_DDL_ES_INIT UTILS Exported structures + * @{ + */ +/** + * @brief UTILS PLL structure definition + */ +typedef struct +{ + uint32_t PLLB; /*!< Division factor for PLL VCO input clock. + This parameter can be a value of @ref RCM_DDL_EC_PLLB_DIV + + This feature can be modified afterwards using unitary function + @ref DDL_RCM_PLL_ConfigDomain_SYS(). */ + + uint32_t PLL1A; /*!< Multiplication factor for PLL VCO output clock. + This parameter must be a number between Min_Data = @ref RCM_PLL1A_MIN_VALUE + and Max_Data = @ref RCM_PLL1A_MIN_VALUE + + This feature can be modified afterwards using unitary function + @ref DDL_RCM_PLL_ConfigDomain_SYS(). */ + + uint32_t PLL1C; /*!< Division for the main system clock. + This parameter can be a value of @ref RCM_DDL_EC_PLL1C_DIV + + This feature can be modified afterwards using unitary function + @ref DDL_RCM_PLL_ConfigDomain_SYS(). */ +} DDL_UTILS_PLLInitTypeDef; + +/** + * @brief UTILS System, AHB and APB buses clock configuration structure definition + */ +typedef struct +{ + uint32_t AHBCLKDivider; /*!< The AHB clock (HCLK) divider. This clock is derived from the system clock (SYSCLK). + This parameter can be a value of @ref RCM_DDL_EC_SYSCLK_DIV + + This feature can be modified afterwards using unitary function + @ref DDL_RCM_SetAHBPrescaler(). */ + + uint32_t APB1CLKDivider; /*!< The APB1 clock (PCLK1) divider. This clock is derived from the AHB clock (HCLK). + This parameter can be a value of @ref RCM_DDL_EC_APB1_DIV + + This feature can be modified afterwards using unitary function + @ref DDL_RCM_SetAPB1Prescaler(). */ + + uint32_t APB2CLKDivider; /*!< The APB2 clock (PCLK2) divider. This clock is derived from the AHB clock (HCLK). + This parameter can be a value of @ref RCM_DDL_EC_APB2_DIV + + This feature can be modified afterwards using unitary function + @ref DDL_RCM_SetAPB2Prescaler(). */ + +} DDL_UTILS_ClkInitTypeDef; + +/** + * @} + */ + +/* Exported constants --------------------------------------------------------*/ +/** @defgroup UTILS_DDL_Exported_Constants UTILS Exported Constants + * @{ + */ + +/** @defgroup UTILS_EC_HSE_BYPASS HSE Bypass activation + * @{ + */ +#define DDL_UTILS_HSEBYPASS_OFF 0x00000000U /*!< HSE Bypass is not enabled */ +#define DDL_UTILS_HSEBYPASS_ON 0x00000001U /*!< HSE Bypass is enabled */ +/** + * @} + */ + +/** @defgroup UTILS_EC_PACKAGETYPE PACKAGE TYPE + * @{ + */ +#define DDL_UTILS_PACKAGETYPE_WLCSP36_UFQFPN48_LQFP64 0x00000000U /*!< WLCSP36 or UFQFPN48 or LQFP64 package type */ +#define DDL_UTILS_PACKAGETYPE_WLCSP168_FBGA169_LQFP100_LQFP64_UFQFPN48 0x00000100U /*!< WLCSP168 or FBGA169 or LQFP100 or LQFP64 or UFQFPN48 package type */ +#define DDL_UTILS_PACKAGETYPE_WLCSP64_WLCSP81_LQFP176_UFBGA176 0x00000200U /*!< WLCSP64 or WLCSP81 or LQFP176 or UFBGA176 package type */ +#define DDL_UTILS_PACKAGETYPE_LQFP144_UFBGA144_UFBGA144_UFBGA100 0x00000300U /*!< LQFP144 or UFBGA144 or UFBGA144 or UFBGA100 package type */ +#define DDL_UTILS_PACKAGETYPE_LQFP100_LQFP208_TFBGA216 0x00000400U /*!< LQFP100 or LQFP208 or TFBGA216 package type */ +#define DDL_UTILS_PACKAGETYPE_LQFP208_TFBGA216 0x00000500U /*!< LQFP208 or TFBGA216 package type */ +#define DDL_UTILS_PACKAGETYPE_TQFP64_UFBGA144_LQFP144 0x00000700U /*!< TQFP64 or UFBGA144 or LQFP144 package type */ +/** + * @} + */ + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ + +/* Exported functions --------------------------------------------------------*/ +/** @defgroup UTILS_DDL_Exported_Functions UTILS Exported Functions + * @{ + */ + +/** @defgroup UTILS_EF_DEVICE_ELECTRONIC_SIGNATURE DEVICE ELECTRONIC SIGNATURE + * @{ + */ + +/** + * @brief Get Word0 of the unique device identifier (UID based on 96 bits) + * @retval UID[31:0] + */ +__STATIC_INLINE uint32_t DDL_GetUID_Word0(void) +{ + return (uint32_t)(READ_REG(*((uint32_t *)UID_BASE_ADDRESS))); +} + +/** + * @brief Get Word1 of the unique device identifier (UID based on 96 bits) + * @retval UID[63:32] + */ +__STATIC_INLINE uint32_t DDL_GetUID_Word1(void) +{ + return (uint32_t)(READ_REG(*((uint32_t *)(UID_BASE_ADDRESS + 4U)))); +} + +/** + * @brief Get Word2 of the unique device identifier (UID based on 96 bits) + * @retval UID[95:64] + */ +__STATIC_INLINE uint32_t DDL_GetUID_Word2(void) +{ + return (uint32_t)(READ_REG(*((uint32_t *)(UID_BASE_ADDRESS + 8U)))); +} + +/** + * @brief Get Flash memory size + * @note This bitfield indicates the size of the device Flash memory expressed in + * Kbytes. As an example, 0x040 corresponds to 64 Kbytes. + * @retval FLASH_SIZE[15:0]: Flash memory size + */ +__STATIC_INLINE uint32_t DDL_GetFlashSize(void) +{ + return (uint32_t)(READ_REG(*((uint32_t *)FLASHSIZE_BASE_ADDRESS)) & 0xFFFF); +} + +/** + * @brief Get Package type + * @retval Returned value can be one of the following values: + * @arg @ref DDL_UTILS_PACKAGETYPE_WLCSP36_UFQFPN48_LQFP64 (*) + * @arg @ref DDL_UTILS_PACKAGETYPE_WLCSP168_FBGA169_LQFP100_LQFP64_UFQFPN48 (*) + * @arg @ref DDL_UTILS_PACKAGETYPE_WLCSP64_WLCSP81_LQFP176_UFBGA176 (*) + * @arg @ref DDL_UTILS_PACKAGETYPE_LQFP144_UFBGA144_UFBGA144_UFBGA100 (*) + * @arg @ref DDL_UTILS_PACKAGETYPE_LQFP100_LQFP208_TFBGA216 (*) + * @arg @ref DDL_UTILS_PACKAGETYPE_LQFP208_TFBGA216 (*) + * @arg @ref DDL_UTILS_PACKAGETYPE_TQFP64_UFBGA144_LQFP144 (*) + * + * (*) value not defined in all devices. + */ +__STATIC_INLINE uint32_t DDL_GetPackageType(void) +{ + return (uint32_t)(READ_REG(*((uint32_t *)PACKAGE_BASE_ADDRESS)) & 0x0700U); +} + +/** + * @} + */ + +/** @defgroup UTILS_DDL_EF_DELAY DELAY + * @{ + */ + +/** + * @brief This function configures the Cortex-M SysTick source of the time base. + * @param HCLKFrequency HCLK frequency in Hz (can be calculated thanks to RCC helper macro) + * @note When a RTOS is used, it is recommended to avoid changing the SysTick + * configuration by calling this function, for a delay use rather osDelay RTOS service. + * @param Ticks Number of ticks + * @retval None + */ +__STATIC_INLINE void DDL_InitTick(uint32_t HCLKFrequency, uint32_t Ticks) +{ + /* Configure the SysTick to have interrupt in 1ms time base */ + SysTick->LOAD = (uint32_t)((HCLKFrequency / Ticks) - 1UL); /* set reload register */ + SysTick->VAL = 0UL; /* Load the SysTick Counter Value */ + SysTick->CTRL = SysTick_CTRL_CLKSOURCE_Msk | + SysTick_CTRL_ENABLE_Msk; /* Enable the Systick Timer */ +} + +void DDL_Init1msTick(uint32_t HCLKFrequency); +void DDL_mDelay(uint32_t Delay); + +/** + * @} + */ + +/** @defgroup UTILS_EF_SYSTEM SYSTEM + * @{ + */ + +void DDL_SetSystemCoreClock(uint32_t HCLKFrequency); +ErrorStatus DDL_SetFlashLatency(uint32_t HCLK_Frequency); +ErrorStatus DDL_PLL_ConfigSystemClock_HSI(DDL_UTILS_PLLInitTypeDef *UTILS_PLLInitStruct, + DDL_UTILS_ClkInitTypeDef *UTILS_ClkInitStruct); +ErrorStatus DDL_PLL_ConfigSystemClock_HSE(uint32_t HSEFrequency, uint32_t HSEBypass, + DDL_UTILS_PLLInitTypeDef *UTILS_PLLInitStruct, DDL_UTILS_ClkInitTypeDef *UTILS_ClkInitStruct); + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* APM32F4xx_DDL_UTILS_H */ diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_wwdt.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_wwdt.h new file mode 100644 index 0000000000..202ce19185 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_ddl_wwdt.h @@ -0,0 +1,328 @@ +/** + * + * @file apm32f4xx_ddl_wwdt.h + * @brief Header file of WWDT DDL module. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef APM32F4xx_DDL_WWDT_H +#define APM32F4xx_DDL_WWDT_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx.h" + +/** @addtogroup APM32F4xx_DDL_Driver + * @{ + */ + +#if defined (WWDT) + +/** @defgroup WWDT_DDL WWDT + * @{ + */ + +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/* Private macros ------------------------------------------------------------*/ +/* Exported types ------------------------------------------------------------*/ +/* Exported constants --------------------------------------------------------*/ +/** @defgroup WWDT_DDL_Exported_Constants WWDT Exported Constants + * @{ + */ + +/** @defgroup WWDT_DDL_EC_IT IT Defines + * @brief IT defines which can be used with DDL_WWDT_ReadReg and DDL_WWDT_WriteReg functions + * @{ + */ +#define DDL_WWDT_CFR_EWIEN WWDT_CFR_EWIEN +/** + * @} + */ + +/** @defgroup WWDT_DDL_EC_PRESCALER PRESCALER + * @{ + */ +#define DDL_WWDT_PRESCALER_1 0x00000000u /*!< WWDT counter clock = (PCLK1/4096)/1 */ +#define DDL_WWDT_PRESCALER_2 WWDT_CFR_TBPSC_0 /*!< WWDT counter clock = (PCLK1/4096)/2 */ +#define DDL_WWDT_PRESCALER_4 WWDT_CFR_TBPSC_1 /*!< WWDT counter clock = (PCLK1/4096)/4 */ +#define DDL_WWDT_PRESCALER_8 (WWDT_CFR_TBPSC_0 | WWDT_CFR_TBPSC_1) /*!< WWDT counter clock = (PCLK1/4096)/8 */ +/** + * @} + */ + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ +/** @defgroup WWDT_DDL_Exported_Macros WWDT Exported Macros + * @{ + */ +/** @defgroup WWDT_DDL_EM_WRITE_READ Common Write and read registers macros + * @{ + */ +/** + * @brief Write a value in WWDT register + * @param __INSTANCE__ WWDT Instance + * @param __REG__ Register to be written + * @param __VALUE__ Value to be written in the register + * @retval None + */ +#define DDL_WWDT_WriteReg(__INSTANCE__, __REG__, __VALUE__) WRITE_REG(__INSTANCE__->__REG__, (__VALUE__)) + +/** + * @brief Read a value in WWDT register + * @param __INSTANCE__ WWDT Instance + * @param __REG__ Register to be read + * @retval Register value + */ +#define DDL_WWDT_ReadReg(__INSTANCE__, __REG__) READ_REG(__INSTANCE__->__REG__) +/** + * @} + */ + +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +/** @defgroup WWDT_DDL_Exported_Functions WWDT Exported Functions + * @{ + */ + +/** @defgroup WWDT_DDL_EF_Configuration Configuration + * @{ + */ +/** + * @brief Enable Window Watchdog. The watchdog is always disabled after a reset. + * @note It is enabled by setting the WDGA bit in the WWDT_CTRL register, + * then it cannot be disabled again except by a reset. + * This bit is set by software and only cleared by hardware after a reset. + * When WDGA = 1, the watchdog can generate a reset. + * @param WWDTx WWDT Instance + * @retval None + */ +__STATIC_INLINE void DDL_WWDT_Enable(WWDT_TypeDef *WWDTx) +{ + SET_BIT(WWDTx->CTRL, WWDT_CTRL_WWDTEN); +} + +/** + * @brief Checks if Window Watchdog is enabled + * @param WWDTx WWDT Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_WWDT_IsEnabled(WWDT_TypeDef *WWDTx) +{ + return ((READ_BIT(WWDTx->CTRL, WWDT_CTRL_WWDTEN) == (WWDT_CTRL_WWDTEN)) ? 1UL : 0UL); +} + +/** + * @brief Set the Watchdog counter value to provided value (7-bits T[6:0]) + * @note When writing to the WWDT_CTRL register, always write 1 in the MSB b6 to avoid generating an immediate reset + * This counter is decremented every (4096 x 2expWDGTB) PCLK cycles + * A reset is produced when it rolls over from 0x40 to 0x3F (bit T6 becomes cleared) + * Setting the counter lower then 0x40 causes an immediate reset (if WWDT enabled) + * @param WWDTx WWDT Instance + * @param Counter 0..0x7F (7 bit counter value) + * @retval None + */ +__STATIC_INLINE void DDL_WWDT_SetCounter(WWDT_TypeDef *WWDTx, uint32_t Counter) +{ + MODIFY_REG(WWDTx->CTRL, WWDT_CTRL_CNT, Counter); +} + +/** + * @brief Return current Watchdog Counter Value (7 bits counter value) + * @param WWDTx WWDT Instance + * @retval 7 bit Watchdog Counter value + */ +__STATIC_INLINE uint32_t DDL_WWDT_GetCounter(WWDT_TypeDef *WWDTx) +{ + return (READ_BIT(WWDTx->CTRL, WWDT_CTRL_CNT)); +} + +/** + * @brief Set the time base of the prescaler (WDGTB). + * @note Prescaler is used to apply ratio on PCLK clock, so that Watchdog counter + * is decremented every (4096 x 2expWDGTB) PCLK cycles + * @param WWDTx WWDT Instance + * @param Prescaler This parameter can be one of the following values: + * @arg @ref DDL_WWDT_PRESCALER_1 + * @arg @ref DDL_WWDT_PRESCALER_2 + * @arg @ref DDL_WWDT_PRESCALER_4 + * @arg @ref DDL_WWDT_PRESCALER_8 + * @retval None + */ +__STATIC_INLINE void DDL_WWDT_SetPrescaler(WWDT_TypeDef *WWDTx, uint32_t Prescaler) +{ + MODIFY_REG(WWDTx->CFR, WWDT_CFR_TBPSC, Prescaler); +} + +/** + * @brief Return current Watchdog Prescaler Value + * @param WWDTx WWDT Instance + * @retval Returned value can be one of the following values: + * @arg @ref DDL_WWDT_PRESCALER_1 + * @arg @ref DDL_WWDT_PRESCALER_2 + * @arg @ref DDL_WWDT_PRESCALER_4 + * @arg @ref DDL_WWDT_PRESCALER_8 + */ +__STATIC_INLINE uint32_t DDL_WWDT_GetPrescaler(WWDT_TypeDef *WWDTx) +{ + return (READ_BIT(WWDTx->CFR, WWDT_CFR_TBPSC)); +} + +/** + * @brief Set the Watchdog Window value to be compared to the downcounter (7-bits W[6:0]). + * @note This window value defines when write in the WWDT_CTRL register + * to program Watchdog counter is allowed. + * Watchdog counter value update must occur only when the counter value + * is lower than the Watchdog window register value. + * Otherwise, a MCU reset is generated if the 7-bit Watchdog counter value + * (in the control register) is refreshed before the downcounter has reached + * the watchdog window register value. + * Physically is possible to set the Window lower then 0x40 but it is not recommended. + * To generate an immediate reset, it is possible to set the Counter lower than 0x40. + * @param WWDTx WWDT Instance + * @param Window 0x00..0x7F (7 bit Window value) + * @retval None + */ +__STATIC_INLINE void DDL_WWDT_SetWindow(WWDT_TypeDef *WWDTx, uint32_t Window) +{ + MODIFY_REG(WWDTx->CFR, WWDT_CFR_WIN, Window); +} + +/** + * @brief Return current Watchdog Window Value (7 bits value) + * @param WWDTx WWDT Instance + * @retval 7 bit Watchdog Window value + */ +__STATIC_INLINE uint32_t DDL_WWDT_GetWindow(WWDT_TypeDef *WWDTx) +{ + return (READ_BIT(WWDTx->CFR, WWDT_CFR_WIN)); +} + +/** + * @} + */ + +/** @defgroup WWDT_DDL_EF_FLAG_Management FLAG_Management + * @{ + */ +/** + * @brief Indicates if the WWDT Early Wakeup Interrupt Flag is set or not. + * @note This bit is set by hardware when the counter has reached the value 0x40. + * It must be cleared by software by writing 0. + * A write of 1 has no effect. This bit is also set if the interrupt is not enabled. + * @param WWDTx WWDT Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_WWDT_IsActiveFlag_EWKUP(WWDT_TypeDef *WWDTx) +{ + return ((READ_BIT(WWDTx->STS, WWDT_STS_EWIFLG) == (WWDT_STS_EWIFLG)) ? 1UL : 0UL); +} + +/** + * @brief Clear WWDT Early Wakeup Interrupt Flag (EWIF) + * @param WWDTx WWDT Instance + * @retval None + */ +__STATIC_INLINE void DDL_WWDT_ClearFlag_EWKUP(WWDT_TypeDef *WWDTx) +{ + WRITE_REG(WWDTx->STS, ~WWDT_STS_EWIFLG); +} + +/** + * @} + */ + +/** @defgroup WWDT_DDL_EF_IT_Management IT_Management + * @{ + */ +/** + * @brief Enable the Early Wakeup Interrupt. + * @note When set, an interrupt occurs whenever the counter reaches value 0x40. + * This interrupt is only cleared by hardware after a reset + * @param WWDTx WWDT Instance + * @retval None + */ +__STATIC_INLINE void DDL_WWDT_EnableIT_EWKUP(WWDT_TypeDef *WWDTx) +{ + SET_BIT(WWDTx->CFR, WWDT_CFR_EWIEN); +} + +/** + * @brief Check if Early Wakeup Interrupt is enabled + * @param WWDTx WWDT Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t DDL_WWDT_IsEnabledIT_EWKUP(WWDT_TypeDef *WWDTx) +{ + return ((READ_BIT(WWDTx->CFR, WWDT_CFR_EWIEN) == (WWDT_CFR_EWIEN)) ? 1UL : 0UL); +} + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#endif /* WWDT */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* APM32F4xx_DDL_WWDT_H */ diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_device_cfg_template.h b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_device_cfg_template.h new file mode 100644 index 0000000000..befe25d705 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Include/apm32f4xx_device_cfg_template.h @@ -0,0 +1,65 @@ +/** + * @file apm32f4xx_device_cfg.h + * + * @brief This file provides all configuration support for device + * + * @version V1.0.0 + * + * @date 2023-07-31 + * + * @attention + * + * Copyright (C) 2023 Geehy Semiconductor + * + * You may not use this file except in compliance with the + * GEEHY COPYRIGHT NOTICE (GEEHY SOFTWARE PACKAGE LICENSE). + * + * The program is only for reference, which is distributed in the hope + * that it will be useful and instructional for customers to develop + * their software. Unless required by applicable law or agreed to in + * writing, the program is distributed on an "AS IS" BASIS, WITHOUT + * ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied. + * See the GEEHY SOFTWARE PACKAGE LICENSE for the governing permissions + * and limitations under the License. + */ + +/* Define to prevent recursive inclusion */ +#ifndef APM32F4XX_DEVICE_CFG_H +#define APM32F4XX_DEVICE_CFG_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes */ +#include "apm32f4xx_dal.h" + +/** @addtogroup Config + @{ + */ + +/** @addtogroup Device_Config + @{ + */ + + +/** @defgroup Device_Config_Functions + @{ +*/ + +void DAL_DeviceConfig(void); +void DAL_SysClkConfig(void); +void DAL_RCM_PeripheralClkConfig(void); +void DAL_GPIO_Config(void); +void DAL_DMA_Config(void); +void DAL_NVIC_Config(void); + +/**@} end of group Device_Config_Functions */ +/**@} end of group Device_Config */ +/**@} end of group Config */ + +#ifdef __cplusplus +} +#endif + +#endif /* APM32F4XX_DEVICE_CFG_H */ diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/LICENSE.txt b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/LICENSE.txt new file mode 100644 index 0000000000..d7e42673ec --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/LICENSE.txt @@ -0,0 +1,29 @@ +This software component is provided to you as part of a software package and +applicable license terms are in the Package_license file. If you received this +software component outside of a package or without applicable license terms, +the terms of the BSD-3-Clause license shall apply. +You may obtain a copy of the BSD-3-Clause at: +https://opensource.org/licenses/BSD-3-Clause + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. +3. Neither the name of the copyright holder nor the names of its contributors + may be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, +INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE +OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED +OF THE POSSIBILITY OF SUCH DAMAGE. \ No newline at end of file diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal.c b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal.c new file mode 100644 index 0000000000..e2c4e8e314 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal.c @@ -0,0 +1,608 @@ +/** + * + * @file apm32f4xx_dal.c + * @brief DAL module driver. + * This is the common part of the DAL initialization + * + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2017 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + * + @verbatim + ============================================================================== + ##### How to use this driver ##### + ============================================================================== + [..] + The common DAL driver contains a set of generic and common APIs that can be + used by the PPP peripheral drivers and the user to start using the DAL. + [..] + The DAL contains two APIs' categories: + (+) Common DAL APIs + (+) Services DAL APIs + + @endverbatim + * + */ + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @defgroup DAL DAL + * @brief DAL module driver. + * @{ + */ + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/** @addtogroup DAL_Private_Constants + * @{ + */ +/** + * @brief APM32F4xx DAL Driver version number V1.1.2 + */ +#define __APM32F4xx_DAL_VERSION_MAIN (0x01U) /*!< [31:24] main version */ +#define __APM32F4xx_DAL_VERSION_SUB1 (0x01U) /*!< [23:16] sub1 version */ +#define __APM32F4xx_DAL_VERSION_SUB2 (0x02U) /*!< [15:8] sub2 version */ +#define __APM32F4xx_DAL_VERSION_RC (0x00U) /*!< [7:0] release candidate */ +#define __APM32F4xx_DAL_VERSION ((__APM32F4xx_DAL_VERSION_MAIN << 24U)\ + |(__APM32F4xx_DAL_VERSION_SUB1 << 16U)\ + |(__APM32F4xx_DAL_VERSION_SUB2 << 8U )\ + |(__APM32F4xx_DAL_VERSION_RC)) + +#define IDCODE_DEVID_MASK 0x00000FFFU + +/* ------------ RCM registers bit address in the alias region ----------- */ +#define SYSCFG_OFFSET (SYSCFG_BASE - PERIPH_BASE) +/* --- MEMRMP Register ---*/ +/* Alias word address of UFB_MODE bit */ +#define MEMRMP_OFFSET SYSCFG_OFFSET +#define UFB_MODE_BIT_NUMBER SYSCFG_MMSEL_UFB_MODE_Pos +#define UFB_MODE_BB (uint32_t)(PERIPH_BB_BASE + (MEMRMP_OFFSET * 32U) + (UFB_MODE_BIT_NUMBER * 4U)) + +/* --- CMPCR Register ---*/ +/* Alias word address of CMP_PD bit */ +#define CMPCR_OFFSET (SYSCFG_OFFSET + 0x20U) +#define CMP_PD_BIT_NUMBER SYSCFG_CCCTRL_CCPD_Pos +#define CMPCR_CMP_PD_BB (uint32_t)(PERIPH_BB_BASE + (CMPCR_OFFSET * 32U) + (CMP_PD_BIT_NUMBER * 4U)) + +/* --- MCHDLYCR Register ---*/ +/* Alias word address of BSCKSEL bit */ +#define MCHDLYCR_OFFSET (SYSCFG_OFFSET + 0x30U) +#define BSCKSEL_BIT_NUMBER SYSCFG_MCHDLYCR_BSCKSEL_Pos +#define MCHDLYCR_BSCKSEL_BB (uint32_t)(PERIPH_BB_BASE + (MCHDLYCR_OFFSET * 32U) + (BSCKSEL_BIT_NUMBER * 4U)) +/** + * @} + */ + +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/** @addtogroup DAL_Private_Variables + * @{ + */ +__IO uint32_t uwTick; +uint32_t uwTickPrio = (1UL << __NVIC_PRIO_BITS); /* Invalid PRIO */ +DAL_TickFreqTypeDef uwTickFreq = DAL_TICK_FREQ_DEFAULT; /* 1KHz */ +/** + * @} + */ +/* Private function prototypes -----------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ + +/** @defgroup DAL_Exported_Functions DAL Exported Functions + * @{ + */ + +/** @defgroup DAL_Exported_Functions_Group1 Initialization and de-initialization Functions + * @brief Initialization and de-initialization functions + * +@verbatim + =============================================================================== + ##### Initialization and Configuration functions ##### + =============================================================================== + [..] This section provides functions allowing to: + (+) Initializes the Flash interface the NVIC allocation and initial clock + configuration. It initializes the systick also when timeout is needed + and the backup domain when enabled. + (+) De-Initializes common part of the DAL. + (+) Configure the time base source to have 1ms time base with a dedicated + Tick interrupt priority. + (++) SysTick timer is used by default as source of time base, but user + can eventually implement his proper time base source (a general purpose + timer for example or other time source), keeping in mind that Time base + duration should be kept 1ms since PPP_TIMEOUT_VALUEs are defined and + handled in milliseconds basis. + (++) Time base configuration function (DAL_InitTick ()) is called automatically + at the beginning of the program after reset by DAL_Init() or at any time + when clock is configured, by DAL_RCM_ClockConfig(). + (++) Source of time base is configured to generate interrupts at regular + time intervals. Care must be taken if DAL_Delay() is called from a + peripheral ISR process, the Tick interrupt line must have higher priority + (numerically lower) than the peripheral interrupt. Otherwise the caller + ISR process will be blocked. + (++) functions affecting time base configurations are declared as __weak + to make override possible in case of other implementations in user file. +@endverbatim + * @{ + */ + +/** + * @brief This function is used to initialize the DAL Library; it must be the first + * instruction to be executed in the main program (before to call any other + * DAL function), it performs the following: + * Configure the Flash prefetch, instruction and Data caches. + * Configures the SysTick to generate an interrupt each 1 millisecond, + * which is clocked by the HSI (at this stage, the clock is not yet + * configured and thus the system is running from the internal HSI at 16 MHz). + * Set NVIC Group Priority to 4. + * Calls the DAL_MspInit() callback function defined in user file + * "apm32f4xx_dal_msp.c" to do the global low level hardware initialization + * + * @note SysTick is used as time base for the DAL_Delay() function, the application + * need to ensure that the SysTick time base is always set to 1 millisecond + * to have correct DAL operation. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_Init(void) +{ + /* Configure Flash prefetch, Instruction cache, Data cache */ +#if (INSTRUCTION_CACHE_ENABLE != 0U) + __DAL_FLASH_INSTRUCTION_CACHE_ENABLE(); +#endif /* INSTRUCTION_CACHE_ENABLE */ + +#if (DATA_CACHE_ENABLE != 0U) + __DAL_FLASH_DATA_CACHE_ENABLE(); +#endif /* DATA_CACHE_ENABLE */ + +#if (PREFETCH_ENABLE != 0U) + __DAL_FLASH_PREFETCH_BUFFER_ENABLE(); +#endif /* PREFETCH_ENABLE */ + + /* Set Interrupt Group Priority */ + DAL_NVIC_SetPriorityGrouping(NVIC_PRIORITYGROUP_4); + + /* Use systick as time base source and configure 1ms tick (default clock after Reset is HSI) */ + DAL_InitTick(TICK_INT_PRIORITY); + + /* Init the low level hardware */ + DAL_MspInit(); + + /* Return function status */ + return DAL_OK; +} + +/** + * @brief This function de-Initializes common part of the DAL and stops the systick. + * This function is optional. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_DeInit(void) +{ + /* Reset of all peripherals */ + __DAL_RCM_APB1_FORCE_RESET(); + __DAL_RCM_APB1_RELEASE_RESET(); + + __DAL_RCM_APB2_FORCE_RESET(); + __DAL_RCM_APB2_RELEASE_RESET(); + + __DAL_RCM_AHB1_FORCE_RESET(); + __DAL_RCM_AHB1_RELEASE_RESET(); + + __DAL_RCM_AHB2_FORCE_RESET(); + __DAL_RCM_AHB2_RELEASE_RESET(); + + __DAL_RCM_AHB3_FORCE_RESET(); + __DAL_RCM_AHB3_RELEASE_RESET(); + + /* De-Init the low level hardware */ + DAL_MspDeInit(); + + /* Return function status */ + return DAL_OK; +} + +/** + * @brief Initialize the MSP. + * @retval None + */ +__weak void DAL_MspInit(void) +{ + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_MspInit could be implemented in the user file + */ +} + +/** + * @brief DeInitializes the MSP. + * @retval None + */ +__weak void DAL_MspDeInit(void) +{ + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_MspDeInit could be implemented in the user file + */ +} + +/** + * @brief This function configures the source of the time base. + * The time source is configured to have 1ms time base with a dedicated + * Tick interrupt priority. + * @note This function is called automatically at the beginning of program after + * reset by DAL_Init() or at any time when clock is reconfigured by DAL_RCM_ClockConfig(). + * @note In the default implementation, SysTick timer is the source of time base. + * It is used to generate interrupts at regular time intervals. + * Care must be taken if DAL_Delay() is called from a peripheral ISR process, + * The SysTick interrupt must have higher priority (numerically lower) + * than the peripheral interrupt. Otherwise the caller ISR process will be blocked. + * The function is declared as __weak to be overwritten in case of other + * implementation in user file. + * @param TickPriority Tick interrupt priority. + * @retval DAL status + */ +__weak DAL_StatusTypeDef DAL_InitTick(uint32_t TickPriority) +{ + /* Configure the SysTick to have interrupt in 1ms time basis*/ + if (DAL_SYSTICK_Config(SystemCoreClock / (1000U / uwTickFreq)) > 0U) + { + return DAL_ERROR; + } + + /* Configure the SysTick IRQ priority */ + if (TickPriority < (1UL << __NVIC_PRIO_BITS)) + { + DAL_NVIC_SetPriority(SysTick_IRQn, TickPriority, 0U); + uwTickPrio = TickPriority; + } + else + { + return DAL_ERROR; + } + + /* Return function status */ + return DAL_OK; +} + +/** + * @} + */ + +/** @defgroup DAL_Exported_Functions_Group2 DAL Control functions + * @brief DAL Control functions + * +@verbatim + =============================================================================== + ##### DAL Control functions ##### + =============================================================================== + [..] This section provides functions allowing to: + (+) Provide a tick value in millisecond + (+) Provide a blocking delay in millisecond + (+) Suspend the time base source interrupt + (+) Resume the time base source interrupt + (+) Get the DAL API driver version + (+) Get the device identifier + (+) Get the device revision identifier + (+) Enable/Disable Debug module during SLEEP mode + (+) Enable/Disable Debug module during STOP mode + (+) Enable/Disable Debug module during STANDBY mode + +@endverbatim + * @{ + */ + +/** + * @brief This function is called to increment a global variable "uwTick" + * used as application time base. + * @note In the default implementation, this variable is incremented each 1ms + * in SysTick ISR. + * @note This function is declared as __weak to be overwritten in case of other + * implementations in user file. + * @retval None + */ +__weak void DAL_IncTick(void) +{ + uwTick += uwTickFreq; +} + +/** + * @brief Provides a tick value in millisecond. + * @note This function is declared as __weak to be overwritten in case of other + * implementations in user file. + * @retval tick value + */ +__weak uint32_t DAL_GetTick(void) +{ + return uwTick; +} + +/** + * @brief This function returns a tick priority. + * @retval tick priority + */ +uint32_t DAL_GetTickPrio(void) +{ + return uwTickPrio; +} + +/** + * @brief Set new tick Freq. + * @retval Status + */ +DAL_StatusTypeDef DAL_SetTickFreq(DAL_TickFreqTypeDef Freq) +{ + DAL_StatusTypeDef status = DAL_OK; + DAL_TickFreqTypeDef prevTickFreq; + + ASSERT_PARAM(IS_TICKFREQ(Freq)); + + if (uwTickFreq != Freq) + { + /* Back up uwTickFreq frequency */ + prevTickFreq = uwTickFreq; + + /* Update uwTickFreq global variable used by DAL_InitTick() */ + uwTickFreq = Freq; + + /* Apply the new tick Freq */ + status = DAL_InitTick(uwTickPrio); + + if (status != DAL_OK) + { + /* Restore previous tick frequency */ + uwTickFreq = prevTickFreq; + } + } + + return status; +} + +/** + * @brief Return tick frequency. + * @retval tick period in Hz + */ +DAL_TickFreqTypeDef DAL_GetTickFreq(void) +{ + return uwTickFreq; +} + +/** + * @brief This function provides minimum delay (in milliseconds) based + * on variable incremented. + * @note In the default implementation , SysTick timer is the source of time base. + * It is used to generate interrupts at regular time intervals where uwTick + * is incremented. + * @note This function is declared as __weak to be overwritten in case of other + * implementations in user file. + * @param Delay specifies the delay time length, in milliseconds. + * @retval None + */ +__weak void DAL_Delay(uint32_t Delay) +{ + uint32_t tickstart = DAL_GetTick(); + uint32_t wait = Delay; + + /* Add a freq to guarantee minimum wait */ + if (wait < DAL_MAX_DELAY) + { + wait += (uint32_t)(uwTickFreq); + } + + while((DAL_GetTick() - tickstart) < wait) + { + } +} + +/** + * @brief Suspend Tick increment. + * @note In the default implementation , SysTick timer is the source of time base. It is + * used to generate interrupts at regular time intervals. Once DAL_SuspendTick() + * is called, the SysTick interrupt will be disabled and so Tick increment + * is suspended. + * @note This function is declared as __weak to be overwritten in case of other + * implementations in user file. + * @retval None + */ +__weak void DAL_SuspendTick(void) +{ + /* Disable SysTick Interrupt */ + SysTick->CTRL &= ~SysTick_CTRL_TICKINT_Msk; +} + +/** + * @brief Resume Tick increment. + * @note In the default implementation , SysTick timer is the source of time base. It is + * used to generate interrupts at regular time intervals. Once DAL_ResumeTick() + * is called, the SysTick interrupt will be enabled and so Tick increment + * is resumed. + * @note This function is declared as __weak to be overwritten in case of other + * implementations in user file. + * @retval None + */ +__weak void DAL_ResumeTick(void) +{ + /* Enable SysTick Interrupt */ + SysTick->CTRL |= SysTick_CTRL_TICKINT_Msk; +} + +/** + * @brief Returns the DAL revision + * @retval version : 0xXYZR (8bits for each decimal, R for RC) + */ +uint32_t DAL_GetHalVersion(void) +{ + return __APM32F4xx_DAL_VERSION; +} + +/** + * @brief Returns the device revision identifier. + * @retval Device revision identifier + */ +uint32_t DAL_GetREVID(void) +{ + return((DBGMCU->IDCODE) >> 16U); +} + +/** + * @brief Returns the device identifier. + * @retval Device identifier + */ +uint32_t DAL_GetDEVID(void) +{ + return((DBGMCU->IDCODE) & IDCODE_DEVID_MASK); +} + +/** + * @brief Enable the Debug Module during SLEEP mode + * @retval None + */ +void DAL_DBGMCU_EnableDBGSleepMode(void) +{ + SET_BIT(DBGMCU->CFG, DBGMCU_CFG_SLEEP_CLK_STS); +} + +/** + * @brief Disable the Debug Module during SLEEP mode + * @retval None + */ +void DAL_DBGMCU_DisableDBGSleepMode(void) +{ + CLEAR_BIT(DBGMCU->CFG, DBGMCU_CFG_SLEEP_CLK_STS); +} + +/** + * @brief Enable the Debug Module during STOP mode + * @retval None + */ +void DAL_DBGMCU_EnableDBGStopMode(void) +{ + SET_BIT(DBGMCU->CFG, DBGMCU_CFG_STOP_CLK_STS); +} + +/** + * @brief Disable the Debug Module during STOP mode + * @retval None + */ +void DAL_DBGMCU_DisableDBGStopMode(void) +{ + CLEAR_BIT(DBGMCU->CFG, DBGMCU_CFG_STOP_CLK_STS); +} + +/** + * @brief Enable the Debug Module during STANDBY mode + * @retval None + */ +void DAL_DBGMCU_EnableDBGStandbyMode(void) +{ + SET_BIT(DBGMCU->CFG, DBGMCU_CFG_STANDBY_CLK_STS); +} + +/** + * @brief Disable the Debug Module during STANDBY mode + * @retval None + */ +void DAL_DBGMCU_DisableDBGStandbyMode(void) +{ + CLEAR_BIT(DBGMCU->CFG, DBGMCU_CFG_STANDBY_CLK_STS); +} + +/** + * @brief Enables the I/O Compensation Cell. + * @note The I/O compensation cell can be used only when the device supply + * voltage ranges from 2.4 to 3.6 V. + * @retval None + */ +void DAL_EnableCompensationCell(void) +{ + *(__IO uint32_t *)CMPCR_CMP_PD_BB = (uint32_t)ENABLE; +} + +/** + * @brief Power-down the I/O Compensation Cell. + * @note The I/O compensation cell can be used only when the device supply + * voltage ranges from 2.4 to 3.6 V. + * @retval None + */ +void DAL_DisableCompensationCell(void) +{ + *(__IO uint32_t *)CMPCR_CMP_PD_BB = (uint32_t)DISABLE; +} + +/** + * @brief Returns first word of the unique device identifier (UID based on 96 bits) + * @retval Device identifier + */ +uint32_t DAL_GetUIDw0(void) +{ + return (READ_REG(*((uint32_t *)UID_BASE))); +} + +/** + * @brief Returns second word of the unique device identifier (UID based on 96 bits) + * @retval Device identifier + */ +uint32_t DAL_GetUIDw1(void) +{ + return (READ_REG(*((uint32_t *)(UID_BASE + 4U)))); +} + +/** + * @brief Returns third word of the unique device identifier (UID based on 96 bits) + * @retval Device identifier + */ +uint32_t DAL_GetUIDw2(void) +{ + return (READ_REG(*((uint32_t *)(UID_BASE + 8U)))); +} + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_adc.c b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_adc.c new file mode 100644 index 0000000000..ee67ebe394 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_adc.c @@ -0,0 +1,2135 @@ +/** + * + * @file apm32f4xx_dal_adc.c + * @brief This file provides firmware functions to manage the following + * functionalities of the Analog to Digital Converter (ADC) peripheral: + * + Initialization and de-initialization functions + * + Peripheral Control functions + * + Peripheral State functions + * + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2017 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + * + @verbatim + ============================================================================== + ##### ADC Peripheral features ##### + ============================================================================== + [..] + (#) 12-bit, 10-bit, 8-bit or 6-bit configurable resolution. + (#) Interrupt generation at the end of conversion, end of injected conversion, + and in case of analog watchdog or overrun events + (#) Single and continuous conversion modes. + (#) Scan mode for automatic conversion of channel 0 to channel x. + (#) Data alignment with in-built data coherency. + (#) Channel-wise programmable sampling time. + (#) External trigger option with configurable polarity for both regular and + injected conversion. + (#) Dual/Triple mode (on devices with 2 ADCs or more). + (#) Configurable DMA data storage in Dual/Triple ADC mode. + (#) Configurable delay between conversions in Dual/Triple interleaved mode. + (#) ADC conversion type (refer to the datasheets). + (#) ADC supply requirements: 2.4 V to 3.6 V at full speed and down to 1.8 V at + slower speed. + (#) ADC input range: VREF(minus) = VIN = VREF(plus). + (#) DMA request generation during regular channel conversion. + + + ##### How to use this driver ##### + ============================================================================== + [..] + (#)Initialize the ADC low level resources by implementing the DAL_ADC_MspInit(): + (##) Enable the ADC interface clock using __DAL_RCM_ADC_CLK_ENABLE() + (##) ADC pins configuration + (+++) Enable the clock for the ADC GPIOs using the following function: + __DAL_RCM_GPIOx_CLK_ENABLE() + (+++) Configure these ADC pins in analog mode using DAL_GPIO_Init() + (##) In case of using interrupts (e.g. DAL_ADC_Start_IT()) + (+++) Configure the ADC interrupt priority using DAL_NVIC_SetPriority() + (+++) Enable the ADC IRQ handler using DAL_NVIC_EnableIRQ() + (+++) In ADC IRQ handler, call DAL_ADC_IRQHandler() + (##) In case of using DMA to control data transfer (e.g. DAL_ADC_Start_DMA()) + (+++) Enable the DMAx interface clock using __DAL_RCM_DMAx_CLK_ENABLE() + (+++) Configure and enable two DMA streams stream for managing data + transfer from peripheral to memory (output stream) + (+++) Associate the initialized DMA handle to the CRYP DMA handle + using __DAL_LINKDMA() + (+++) Configure the priority and enable the NVIC for the transfer complete + interrupt on the two DMA Streams. The output stream should have higher + priority than the input stream. + + *** Configuration of ADC, groups regular/injected, channels parameters *** + ============================================================================== + [..] + (#) Configure the ADC parameters (resolution, data alignment, ...) + and regular group parameters (conversion trigger, sequencer, ...) + using function DAL_ADC_Init(). + + (#) Configure the channels for regular group parameters (channel number, + channel rank into sequencer, ..., into regular group) + using function DAL_ADC_ConfigChannel(). + + (#) Optionally, configure the injected group parameters (conversion trigger, + sequencer, ..., of injected group) + and the channels for injected group parameters (channel number, + channel rank into sequencer, ..., into injected group) + using function DAL_ADCEx_InjectedConfigChannel(). + + (#) Optionally, configure the analog watchdog parameters (channels + monitored, thresholds, ...) using function DAL_ADC_AnalogWDGConfig(). + + (#) Optionally, for devices with several ADC instances: configure the + multimode parameters using function DAL_ADCEx_MultiModeConfigChannel(). + + *** Execution of ADC conversions *** + ============================================================================== + [..] + (#) ADC driver can be used among three modes: polling, interruption, + transfer by DMA. + + *** Polling mode IO operation *** + ================================= + [..] + (+) Start the ADC peripheral using DAL_ADC_Start() + (+) Wait for end of conversion using DAL_ADC_PollForConversion(), at this stage + user can specify the value of timeout according to his end application + (+) To read the ADC converted values, use the DAL_ADC_GetValue() function. + (+) Stop the ADC peripheral using DAL_ADC_Stop() + + *** Interrupt mode IO operation *** + =================================== + [..] + (+) Start the ADC peripheral using DAL_ADC_Start_IT() + (+) Use DAL_ADC_IRQHandler() called under ADC_IRQHandler() Interrupt subroutine + (+) At ADC end of conversion DAL_ADC_ConvCpltCallback() function is executed and user can + add his own code by customization of function pointer DAL_ADC_ConvCpltCallback + (+) In case of ADC Error, DAL_ADC_ErrorCallback() function is executed and user can + add his own code by customization of function pointer DAL_ADC_ErrorCallback + (+) Stop the ADC peripheral using DAL_ADC_Stop_IT() + + *** DMA mode IO operation *** + ============================== + [..] + (+) Start the ADC peripheral using DAL_ADC_Start_DMA(), at this stage the user specify the length + of data to be transferred at each end of conversion + (+) At The end of data transfer by DAL_ADC_ConvCpltCallback() function is executed and user can + add his own code by customization of function pointer DAL_ADC_ConvCpltCallback + (+) In case of transfer Error, DAL_ADC_ErrorCallback() function is executed and user can + add his own code by customization of function pointer DAL_ADC_ErrorCallback + (+) Stop the ADC peripheral using DAL_ADC_Stop_DMA() + + *** ADC DAL driver macros list *** + ============================================= + [..] + Below the list of most used macros in ADC DAL driver. + + (+) __DAL_ADC_ENABLE : Enable the ADC peripheral + (+) __DAL_ADC_DISABLE : Disable the ADC peripheral + (+) __DAL_ADC_ENABLE_IT: Enable the ADC end of conversion interrupt + (+) __DAL_ADC_DISABLE_IT: Disable the ADC end of conversion interrupt + (+) __DAL_ADC_GET_IT_SOURCE: Check if the specified ADC interrupt source is enabled or disabled + (+) __DAL_ADC_CLEAR_FLAG: Clear the ADC's pending flags + (+) __DAL_ADC_GET_FLAG: Get the selected ADC's flag status + (+) ADC_GET_RESOLUTION: Return resolution bits in CTRL1 register + + [..] + (@) You can refer to the ADC DAL driver header file for more useful macros + + *** Deinitialization of ADC *** + ============================================================================== + [..] + (#) Disable the ADC interface + (++) ADC clock can be hard reset and disabled at RCC top level. + (++) Hard reset of ADC peripherals + using macro __DAL_RCM_ADC_FORCE_RESET(), __DAL_RCM_ADC_RELEASE_RESET(). + (++) ADC clock disable using the equivalent macro/functions as configuration step. + (+++) Example: + Into DAL_ADC_MspDeInit() (recommended code location) or with + other device clock parameters configuration: + (+++) DAL_RCM_GetOscConfig(&RCM_OscInitStructure); + (+++) RCM_OscInitStructure.OscillatorType = RCM_OSCILLATORTYPE_HSI; + (+++) RCM_OscInitStructure.HSIState = RCM_HSI_OFF; (if not used for system clock) + (+++) DAL_RCM_OscConfig(&RCM_OscInitStructure); + + (#) ADC pins configuration + (++) Disable the clock for the ADC GPIOs using macro __DAL_RCM_GPIOx_CLK_DISABLE() + + (#) Optionally, in case of usage of ADC with interruptions: + (++) Disable the NVIC for ADC using function DAL_NVIC_DisableIRQ(ADCx_IRQn) + + (#) Optionally, in case of usage of DMA: + (++) Deinitialize the DMA using function DAL_DMA_DeInit(). + (++) Disable the NVIC for DMA using function DAL_NVIC_DisableIRQ(DMAx_Channelx_IRQn) + *** Callback registration *** + ============================================================================== + [..] + + The compilation flag USE_DAL_ADC_REGISTER_CALLBACKS, when set to 1, + allows the user to configure dynamically the driver callbacks. + Use Functions DAL_ADC_RegisterCallback() + to register an interrupt callback. + [..] + + Function DAL_ADC_RegisterCallback() allows to register following callbacks: + (+) ConvCpltCallback : ADC conversion complete callback + (+) ConvHalfCpltCallback : ADC conversion DMA half-transfer callback + (+) LevelOutOfWindowCallback : ADC analog watchdog 1 callback + (+) ErrorCallback : ADC error callback + (+) InjectedConvCpltCallback : ADC group injected conversion complete callback + (+) InjectedQueueOverflowCallback : ADC group injected context queue overflow callback + (+) LevelOutOfWindow2Callback : ADC analog watchdog 2 callback + (+) LevelOutOfWindow3Callback : ADC analog watchdog 3 callback + (+) EndOfSamplingCallback : ADC end of sampling callback + (+) MspInitCallback : ADC Msp Init callback + (+) MspDeInitCallback : ADC Msp DeInit callback + This function takes as parameters the DAL peripheral handle, the Callback ID + and a pointer to the user callback function. + [..] + + Use function DAL_ADC_UnRegisterCallback to reset a callback to the default + weak function. + [..] + + DAL_ADC_UnRegisterCallback takes as parameters the DAL peripheral handle, + and the Callback ID. + This function allows to reset following callbacks: + (+) ConvCpltCallback : ADC conversion complete callback + (+) ConvHalfCpltCallback : ADC conversion DMA half-transfer callback + (+) LevelOutOfWindowCallback : ADC analog watchdog 1 callback + (+) ErrorCallback : ADC error callback + (+) InjectedConvCpltCallback : ADC group injected conversion complete callback + (+) InjectedQueueOverflowCallback : ADC group injected context queue overflow callback + (+) LevelOutOfWindow2Callback : ADC analog watchdog 2 callback + (+) LevelOutOfWindow3Callback : ADC analog watchdog 3 callback + (+) EndOfSamplingCallback : ADC end of sampling callback + (+) MspInitCallback : ADC Msp Init callback + (+) MspDeInitCallback : ADC Msp DeInit callback + [..] + + By default, after the DAL_ADC_Init() and when the state is DAL_ADC_STATE_RESET + all callbacks are set to the corresponding weak functions: + examples DAL_ADC_ConvCpltCallback(), DAL_ADC_ErrorCallback(). + Exception done for MspInit and MspDeInit functions that are + reset to the legacy weak functions in the DAL_ADC_Init()/ DAL_ADC_DeInit() only when + these callbacks are null (not registered beforehand). + [..] + + If MspInit or MspDeInit are not null, the DAL_ADC_Init()/ DAL_ADC_DeInit() + keep and use the user MspInit/MspDeInit callbacks (registered beforehand) whatever the state. + [..] + + Callbacks can be registered/unregistered in DAL_ADC_STATE_READY state only. + Exception done MspInit/MspDeInit functions that can be registered/unregistered + in DAL_ADC_STATE_READY or DAL_ADC_STATE_RESET state, + thus registered (user) MspInit/DeInit callbacks can be used during the Init/DeInit. + [..] + + Then, the user first registers the MspInit/MspDeInit user callbacks + using DAL_ADC_RegisterCallback() before calling DAL_ADC_DeInit() + or DAL_ADC_Init() function. + [..] + + When the compilation flag USE_DAL_ADC_REGISTER_CALLBACKS is set to 0 or + not defined, the callback registration feature is not available and all callbacks + are set to the corresponding weak functions. + + @endverbatim + */ + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @defgroup ADC ADC + * @brief ADC driver modules + * @{ + */ + +#ifdef DAL_ADC_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/** @addtogroup ADC_Private_Functions + * @{ + */ +/* Private function prototypes -----------------------------------------------*/ +static void ADC_Init(ADC_HandleTypeDef* hadc); +static void ADC_DMAConvCplt(DMA_HandleTypeDef *hdma); +static void ADC_DMAError(DMA_HandleTypeDef *hdma); +static void ADC_DMAHalfConvCplt(DMA_HandleTypeDef *hdma); +/** + * @} + */ +/* Exported functions --------------------------------------------------------*/ +/** @defgroup ADC_Exported_Functions ADC Exported Functions + * @{ + */ + +/** @defgroup ADC_Exported_Functions_Group1 Initialization and de-initialization functions + * @brief Initialization and Configuration functions + * +@verbatim + =============================================================================== + ##### Initialization and de-initialization functions ##### + =============================================================================== + [..] This section provides functions allowing to: + (+) Initialize and configure the ADC. + (+) De-initialize the ADC. + +@endverbatim + * @{ + */ + +/** + * @brief Initializes the ADCx peripheral according to the specified parameters + * in the ADC_InitStruct and initializes the ADC MSP. + * + * @note This function is used to configure the global features of the ADC ( + * ClockPrescaler, Resolution, Data Alignment and number of conversion), however, + * the rest of the configuration parameters are specific to the regular + * channels group (scan mode activation, continuous mode activation, + * External trigger source and edge, DMA continuous request after the + * last transfer and End of conversion selection). + * + * @param hadc pointer to a ADC_HandleTypeDef structure that contains + * the configuration information for the specified ADC. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_ADC_Init(ADC_HandleTypeDef* hadc) +{ + DAL_StatusTypeDef tmp_dal_status = DAL_OK; + + /* Check ADC handle */ + if(hadc == NULL) + { + return DAL_ERROR; + } + + /* Check the parameters */ + ASSERT_PARAM(IS_ADC_ALL_INSTANCE(hadc->Instance)); + ASSERT_PARAM(IS_ADC_CLOCKPRESCALER(hadc->Init.ClockPrescaler)); + ASSERT_PARAM(IS_ADC_RESOLUTION(hadc->Init.Resolution)); + ASSERT_PARAM(IS_FUNCTIONAL_STATE(hadc->Init.ScanConvMode)); + ASSERT_PARAM(IS_FUNCTIONAL_STATE(hadc->Init.ContinuousConvMode)); + ASSERT_PARAM(IS_ADC_EXT_TRIG(hadc->Init.ExternalTrigConv)); + ASSERT_PARAM(IS_ADC_DATA_ALIGN(hadc->Init.DataAlign)); + ASSERT_PARAM(IS_ADC_REGULAR_LENGTH(hadc->Init.NbrOfConversion)); + ASSERT_PARAM(IS_FUNCTIONAL_STATE(hadc->Init.DMAContinuousRequests)); + ASSERT_PARAM(IS_ADC_EOCSelection(hadc->Init.EOCSelection)); + ASSERT_PARAM(IS_FUNCTIONAL_STATE(hadc->Init.DiscontinuousConvMode)); + + if(hadc->Init.ExternalTrigConv != ADC_SOFTWARE_START) + { + ASSERT_PARAM(IS_ADC_EXT_TRIG_EDGE(hadc->Init.ExternalTrigConvEdge)); + } + + if(hadc->State == DAL_ADC_STATE_RESET) + { +#if (USE_DAL_ADC_REGISTER_CALLBACKS == 1) + /* Init the ADC Callback settings */ + hadc->ConvCpltCallback = DAL_ADC_ConvCpltCallback; /* Legacy weak callback */ + hadc->ConvHalfCpltCallback = DAL_ADC_ConvHalfCpltCallback; /* Legacy weak callback */ + hadc->LevelOutOfWindowCallback = DAL_ADC_LevelOutOfWindowCallback; /* Legacy weak callback */ + hadc->ErrorCallback = DAL_ADC_ErrorCallback; /* Legacy weak callback */ + hadc->InjectedConvCpltCallback = DAL_ADCEx_InjectedConvCpltCallback; /* Legacy weak callback */ + if (hadc->MspInitCallback == NULL) + { + hadc->MspInitCallback = DAL_ADC_MspInit; /* Legacy weak MspInit */ + } + + /* Init the low level hardware */ + hadc->MspInitCallback(hadc); +#else + /* Init the low level hardware */ + DAL_ADC_MspInit(hadc); +#endif /* USE_DAL_ADC_REGISTER_CALLBACKS */ + + /* Initialize ADC error code */ + ADC_CLEAR_ERRORCODE(hadc); + + /* Allocate lock resource and initialize it */ + hadc->Lock = DAL_UNLOCKED; + } + + /* Configuration of ADC parameters if previous preliminary actions are */ + /* correctly completed. */ + if (DAL_IS_BIT_CLR(hadc->State, DAL_ADC_STATE_ERROR_INTERNAL)) + { + /* Set ADC state */ + ADC_STATE_CLR_SET(hadc->State, + DAL_ADC_STATE_REG_BUSY | DAL_ADC_STATE_INJ_BUSY, + DAL_ADC_STATE_BUSY_INTERNAL); + + /* Set ADC parameters */ + ADC_Init(hadc); + + /* Set ADC error code to none */ + ADC_CLEAR_ERRORCODE(hadc); + + /* Set the ADC state */ + ADC_STATE_CLR_SET(hadc->State, + DAL_ADC_STATE_BUSY_INTERNAL, + DAL_ADC_STATE_READY); + } + else + { + tmp_dal_status = DAL_ERROR; + } + + /* Release Lock */ + __DAL_UNLOCK(hadc); + + /* Return function status */ + return tmp_dal_status; +} + +/** + * @brief Deinitializes the ADCx peripheral registers to their default reset values. + * @param hadc pointer to a ADC_HandleTypeDef structure that contains + * the configuration information for the specified ADC. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_ADC_DeInit(ADC_HandleTypeDef* hadc) +{ + DAL_StatusTypeDef tmp_dal_status = DAL_OK; + + /* Check ADC handle */ + if(hadc == NULL) + { + return DAL_ERROR; + } + + /* Check the parameters */ + ASSERT_PARAM(IS_ADC_ALL_INSTANCE(hadc->Instance)); + + /* Set ADC state */ + SET_BIT(hadc->State, DAL_ADC_STATE_BUSY_INTERNAL); + + /* Stop potential conversion on going, on regular and injected groups */ + /* Disable ADC peripheral */ + __DAL_ADC_DISABLE(hadc); + + /* Configuration of ADC parameters if previous preliminary actions are */ + /* correctly completed. */ + if(DAL_IS_BIT_CLR(hadc->Instance->CTRL2, ADC_CTRL2_ADCEN)) + { +#if (USE_DAL_ADC_REGISTER_CALLBACKS == 1) + if (hadc->MspDeInitCallback == NULL) + { + hadc->MspDeInitCallback = DAL_ADC_MspDeInit; /* Legacy weak MspDeInit */ + } + + /* DeInit the low level hardware: RCC clock, NVIC */ + hadc->MspDeInitCallback(hadc); +#else + /* DeInit the low level hardware: RCC clock, NVIC */ + DAL_ADC_MspDeInit(hadc); +#endif /* USE_DAL_ADC_REGISTER_CALLBACKS */ + + /* Set ADC error code to none */ + ADC_CLEAR_ERRORCODE(hadc); + + /* Set ADC state */ + hadc->State = DAL_ADC_STATE_RESET; + } + + /* Process unlocked */ + __DAL_UNLOCK(hadc); + + /* Return function status */ + return tmp_dal_status; +} + +#if (USE_DAL_ADC_REGISTER_CALLBACKS == 1) +/** + * @brief Register a User ADC Callback + * To be used instead of the weak predefined callback + * @param hadc Pointer to a ADC_HandleTypeDef structure that contains + * the configuration information for the specified ADC. + * @param CallbackID ID of the callback to be registered + * This parameter can be one of the following values: + * @arg @ref DAL_ADC_CONVERSION_COMPLETE_CB_ID ADC conversion complete callback ID + * @arg @ref DAL_ADC_CONVERSION_HALF_CB_ID ADC conversion DMA half-transfer callback ID + * @arg @ref DAL_ADC_LEVEL_OUT_OF_WINDOW_1_CB_ID ADC analog watchdog 1 callback ID + * @arg @ref DAL_ADC_ERROR_CB_ID ADC error callback ID + * @arg @ref DAL_ADC_INJ_CONVERSION_COMPLETE_CB_ID ADC group injected conversion complete callback ID + * @arg @ref DAL_ADC_MSPINIT_CB_ID ADC Msp Init callback ID + * @arg @ref DAL_ADC_MSPDEINIT_CB_ID ADC Msp DeInit callback ID + * @param pCallback pointer to the Callback function + * @retval DAL status + */ +DAL_StatusTypeDef DAL_ADC_RegisterCallback(ADC_HandleTypeDef *hadc, DAL_ADC_CallbackIDTypeDef CallbackID, pADC_CallbackTypeDef pCallback) +{ + DAL_StatusTypeDef status = DAL_OK; + + if (pCallback == NULL) + { + /* Update the error code */ + hadc->ErrorCode |= DAL_ADC_ERROR_INVALID_CALLBACK; + + return DAL_ERROR; + } + + if ((hadc->State & DAL_ADC_STATE_READY) != 0UL) + { + switch (CallbackID) + { + case DAL_ADC_CONVERSION_COMPLETE_CB_ID : + hadc->ConvCpltCallback = pCallback; + break; + + case DAL_ADC_CONVERSION_HALF_CB_ID : + hadc->ConvHalfCpltCallback = pCallback; + break; + + case DAL_ADC_LEVEL_OUT_OF_WINDOW_1_CB_ID : + hadc->LevelOutOfWindowCallback = pCallback; + break; + + case DAL_ADC_ERROR_CB_ID : + hadc->ErrorCallback = pCallback; + break; + + case DAL_ADC_INJ_CONVERSION_COMPLETE_CB_ID : + hadc->InjectedConvCpltCallback = pCallback; + break; + + case DAL_ADC_MSPINIT_CB_ID : + hadc->MspInitCallback = pCallback; + break; + + case DAL_ADC_MSPDEINIT_CB_ID : + hadc->MspDeInitCallback = pCallback; + break; + + default : + /* Update the error code */ + hadc->ErrorCode |= DAL_ADC_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = DAL_ERROR; + break; + } + } + else if (DAL_ADC_STATE_RESET == hadc->State) + { + switch (CallbackID) + { + case DAL_ADC_MSPINIT_CB_ID : + hadc->MspInitCallback = pCallback; + break; + + case DAL_ADC_MSPDEINIT_CB_ID : + hadc->MspDeInitCallback = pCallback; + break; + + default : + /* Update the error code */ + hadc->ErrorCode |= DAL_ADC_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = DAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + hadc->ErrorCode |= DAL_ADC_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = DAL_ERROR; + } + + return status; +} + +/** + * @brief Unregister a ADC Callback + * ADC callback is redirected to the weak predefined callback + * @param hadc Pointer to a ADC_HandleTypeDef structure that contains + * the configuration information for the specified ADC. + * @param CallbackID ID of the callback to be unregistered + * This parameter can be one of the following values: + * @arg @ref DAL_ADC_CONVERSION_COMPLETE_CB_ID ADC conversion complete callback ID + * @arg @ref DAL_ADC_CONVERSION_HALF_CB_ID ADC conversion DMA half-transfer callback ID + * @arg @ref DAL_ADC_LEVEL_OUT_OF_WINDOW_1_CB_ID ADC analog watchdog 1 callback ID + * @arg @ref DAL_ADC_ERROR_CB_ID ADC error callback ID + * @arg @ref DAL_ADC_INJ_CONVERSION_COMPLETE_CB_ID ADC group injected conversion complete callback ID + * @arg @ref DAL_ADC_MSPINIT_CB_ID ADC Msp Init callback ID + * @arg @ref DAL_ADC_MSPDEINIT_CB_ID ADC Msp DeInit callback ID + * @retval DAL status + */ +DAL_StatusTypeDef DAL_ADC_UnRegisterCallback(ADC_HandleTypeDef *hadc, DAL_ADC_CallbackIDTypeDef CallbackID) +{ + DAL_StatusTypeDef status = DAL_OK; + + if ((hadc->State & DAL_ADC_STATE_READY) != 0UL) + { + switch (CallbackID) + { + case DAL_ADC_CONVERSION_COMPLETE_CB_ID : + hadc->ConvCpltCallback = DAL_ADC_ConvCpltCallback; + break; + + case DAL_ADC_CONVERSION_HALF_CB_ID : + hadc->ConvHalfCpltCallback = DAL_ADC_ConvHalfCpltCallback; + break; + + case DAL_ADC_LEVEL_OUT_OF_WINDOW_1_CB_ID : + hadc->LevelOutOfWindowCallback = DAL_ADC_LevelOutOfWindowCallback; + break; + + case DAL_ADC_ERROR_CB_ID : + hadc->ErrorCallback = DAL_ADC_ErrorCallback; + break; + + case DAL_ADC_INJ_CONVERSION_COMPLETE_CB_ID : + hadc->InjectedConvCpltCallback = DAL_ADCEx_InjectedConvCpltCallback; + break; + + case DAL_ADC_MSPINIT_CB_ID : + hadc->MspInitCallback = DAL_ADC_MspInit; /* Legacy weak MspInit */ + break; + + case DAL_ADC_MSPDEINIT_CB_ID : + hadc->MspDeInitCallback = DAL_ADC_MspDeInit; /* Legacy weak MspDeInit */ + break; + + default : + /* Update the error code */ + hadc->ErrorCode |= DAL_ADC_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = DAL_ERROR; + break; + } + } + else if (DAL_ADC_STATE_RESET == hadc->State) + { + switch (CallbackID) + { + case DAL_ADC_MSPINIT_CB_ID : + hadc->MspInitCallback = DAL_ADC_MspInit; /* Legacy weak MspInit */ + break; + + case DAL_ADC_MSPDEINIT_CB_ID : + hadc->MspDeInitCallback = DAL_ADC_MspDeInit; /* Legacy weak MspDeInit */ + break; + + default : + /* Update the error code */ + hadc->ErrorCode |= DAL_ADC_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = DAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + hadc->ErrorCode |= DAL_ADC_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = DAL_ERROR; + } + + return status; +} + +#endif /* USE_DAL_ADC_REGISTER_CALLBACKS */ + +/** + * @brief Initializes the ADC MSP. + * @param hadc pointer to a ADC_HandleTypeDef structure that contains + * the configuration information for the specified ADC. + * @retval None + */ +__weak void DAL_ADC_MspInit(ADC_HandleTypeDef* hadc) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hadc); + /* NOTE : This function Should not be modified, when the callback is needed, + the DAL_ADC_MspInit could be implemented in the user file + */ +} + +/** + * @brief DeInitializes the ADC MSP. + * @param hadc pointer to a ADC_HandleTypeDef structure that contains + * the configuration information for the specified ADC. + * @retval None + */ +__weak void DAL_ADC_MspDeInit(ADC_HandleTypeDef* hadc) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hadc); + /* NOTE : This function Should not be modified, when the callback is needed, + the DAL_ADC_MspDeInit could be implemented in the user file + */ +} + +/** + * @} + */ + +/** @defgroup ADC_Exported_Functions_Group2 IO operation functions + * @brief IO operation functions + * +@verbatim + =============================================================================== + ##### IO operation functions ##### + =============================================================================== + [..] This section provides functions allowing to: + (+) Start conversion of regular channel. + (+) Stop conversion of regular channel. + (+) Start conversion of regular channel and enable interrupt. + (+) Stop conversion of regular channel and disable interrupt. + (+) Start conversion of regular channel and enable DMA transfer. + (+) Stop conversion of regular channel and disable DMA transfer. + (+) Handle ADC interrupt request. + +@endverbatim + * @{ + */ + +/** + * @brief Enables ADC and starts conversion of the regular channels. + * @param hadc pointer to a ADC_HandleTypeDef structure that contains + * the configuration information for the specified ADC. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_ADC_Start(ADC_HandleTypeDef* hadc) +{ + __IO uint32_t counter = 0U; + ADC_Common_TypeDef *tmpADC_Common; + + /* Check the parameters */ + ASSERT_PARAM(IS_FUNCTIONAL_STATE(hadc->Init.ContinuousConvMode)); + ASSERT_PARAM(IS_ADC_EXT_TRIG_EDGE(hadc->Init.ExternalTrigConvEdge)); + + /* Process locked */ + __DAL_LOCK(hadc); + + /* Enable the ADC peripheral */ + /* Check if ADC peripheral is disabled in order to enable it and wait during + Tstab time the ADC's stabilization */ + if((hadc->Instance->CTRL2 & ADC_CTRL2_ADCEN) != ADC_CTRL2_ADCEN) + { + /* Enable the Peripheral */ + __DAL_ADC_ENABLE(hadc); + + /* Delay for ADC stabilization time */ + /* Compute number of CPU cycles to wait for */ + counter = (ADC_STAB_DELAY_US * (SystemCoreClock / 1000000U)); + while(counter != 0U) + { + counter--; + } + } + + /* Start conversion if ADC is effectively enabled */ + if(DAL_IS_BIT_SET(hadc->Instance->CTRL2, ADC_CTRL2_ADCEN)) + { + /* Set ADC state */ + /* - Clear state bitfield related to regular group conversion results */ + /* - Set state bitfield related to regular group operation */ + ADC_STATE_CLR_SET(hadc->State, + DAL_ADC_STATE_READY | DAL_ADC_STATE_REG_EOC | DAL_ADC_STATE_REG_OVR, + DAL_ADC_STATE_REG_BUSY); + + /* If conversions on group regular are also triggering group injected, */ + /* update ADC state. */ + if (READ_BIT(hadc->Instance->CTRL1, ADC_CTRL1_INJGACEN) != RESET) + { + ADC_STATE_CLR_SET(hadc->State, DAL_ADC_STATE_INJ_EOC, DAL_ADC_STATE_INJ_BUSY); + } + + /* State machine update: Check if an injected conversion is ongoing */ + if (DAL_IS_BIT_SET(hadc->State, DAL_ADC_STATE_INJ_BUSY)) + { + /* Reset ADC error code fields related to conversions on group regular */ + CLEAR_BIT(hadc->ErrorCode, (DAL_ADC_ERROR_OVR | DAL_ADC_ERROR_DMA)); + } + else + { + /* Reset ADC all error code fields */ + ADC_CLEAR_ERRORCODE(hadc); + } + + /* Process unlocked */ + /* Unlock before starting ADC conversions: in case of potential */ + /* interruption, to let the process to ADC IRQ Handler. */ + __DAL_UNLOCK(hadc); + + /* Pointer to the common control register to which is belonging hadc */ + /* (Depending on APM32F4 product, there may be up to 3 ADCs and 1 common */ + /* control register) */ + tmpADC_Common = ADC_COMMON_REGISTER(hadc); + + /* Clear regular group conversion flag and overrun flag */ + /* (To ensure of no unknown state from potential previous ADC operations) */ + __DAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_EOC | ADC_FLAG_OVR); + + /* Check if Multimode enabled */ + if(DAL_IS_BIT_CLR(tmpADC_Common->CCTRL, ADC_CCTRL_ADCMSEL)) + { +#if defined(ADC2) && defined(ADC3) + if((hadc->Instance == ADC1) || ((hadc->Instance == ADC2) && ((ADC->CCTRL & ADC_CCTRL_ADCMSEL_Msk) < ADC_CCTRL_ADCMSEL_0)) \ + || ((hadc->Instance == ADC3) && ((ADC->CCTRL & ADC_CCTRL_ADCMSEL_Msk) < ADC_CCTRL_ADCMSEL_4))) + { +#endif /* ADC2 || ADC3 */ + /* if no external trigger present enable software conversion of regular channels */ + if((hadc->Instance->CTRL2 & ADC_CTRL2_REGEXTTRGEN) == RESET) + { + /* Enable the selected ADC software conversion for regular group */ + hadc->Instance->CTRL2 |= (uint32_t)ADC_CTRL2_REGCHSC; + } +#if defined(ADC2) && defined(ADC3) + } +#endif /* ADC2 || ADC3 */ + } + else + { + /* if instance of handle correspond to ADC1 and no external trigger present enable software conversion of regular channels */ + if(((hadc->Instance == ADC1) || (hadc->Instance == ADC2)) && ((hadc->Instance->CTRL2 & ADC_CTRL2_REGEXTTRGEN) == RESET)) + { + /* Enable the selected ADC software conversion for regular group */ + hadc->Instance->CTRL2 |= (uint32_t)ADC_CTRL2_REGCHSC; + } + } + } + else + { + /* Update ADC state machine to error */ + SET_BIT(hadc->State, DAL_ADC_STATE_ERROR_INTERNAL); + + /* Set ADC error code to ADC IP internal error */ + SET_BIT(hadc->ErrorCode, DAL_ADC_ERROR_INTERNAL); + } + + /* Return function status */ + return DAL_OK; +} + +/** + * @brief Disables ADC and stop conversion of regular channels. + * + * @note Caution: This function will stop also injected channels. + * + * @param hadc pointer to a ADC_HandleTypeDef structure that contains + * the configuration information for the specified ADC. + * + * @retval DAL status. + */ +DAL_StatusTypeDef DAL_ADC_Stop(ADC_HandleTypeDef* hadc) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_ADC_ALL_INSTANCE(hadc->Instance)); + + /* Process locked */ + __DAL_LOCK(hadc); + + /* Stop potential conversion on going, on regular and injected groups */ + /* Disable ADC peripheral */ + __DAL_ADC_DISABLE(hadc); + + /* Check if ADC is effectively disabled */ + if(DAL_IS_BIT_CLR(hadc->Instance->CTRL2, ADC_CTRL2_ADCEN)) + { + /* Set ADC state */ + ADC_STATE_CLR_SET(hadc->State, + DAL_ADC_STATE_REG_BUSY | DAL_ADC_STATE_INJ_BUSY, + DAL_ADC_STATE_READY); + } + + /* Process unlocked */ + __DAL_UNLOCK(hadc); + + /* Return function status */ + return DAL_OK; +} + +/** + * @brief Poll for regular conversion complete + * @note ADC conversion flags EOS (end of sequence) and EOC (end of + * conversion) are cleared by this function. + * @note This function cannot be used in a particular setup: ADC configured + * in DMA mode and polling for end of each conversion (ADC init + * parameter "EOCSelection" set to ADC_EOC_SINGLE_CONV). + * In this case, DMA resets the flag EOC and polling cannot be + * performed on each conversion. Nevertheless, polling can still + * be performed on the complete sequence. + * @param hadc pointer to a ADC_HandleTypeDef structure that contains + * the configuration information for the specified ADC. + * @param Timeout Timeout value in millisecond. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_ADC_PollForConversion(ADC_HandleTypeDef* hadc, uint32_t Timeout) +{ + uint32_t tickstart = 0U; + + /* Verification that ADC configuration is compliant with polling for */ + /* each conversion: */ + /* Particular case is ADC configured in DMA mode and ADC sequencer with */ + /* several ranks and polling for end of each conversion. */ + /* For code simplicity sake, this particular case is generalized to */ + /* ADC configured in DMA mode and polling for end of each conversion. */ + if (DAL_IS_BIT_SET(hadc->Instance->CTRL2, ADC_CTRL2_EOCSEL) && + DAL_IS_BIT_SET(hadc->Instance->CTRL2, ADC_CTRL2_DMAEN) ) + { + /* Update ADC state machine to error */ + SET_BIT(hadc->State, DAL_ADC_STATE_ERROR_CONFIG); + + /* Process unlocked */ + __DAL_UNLOCK(hadc); + + return DAL_ERROR; + } + + /* Get tick */ + tickstart = DAL_GetTick(); + + /* Check End of conversion flag */ + while(!(__DAL_ADC_GET_FLAG(hadc, ADC_FLAG_EOC))) + { + /* Check if timeout is disabled (set to infinite wait) */ + if(Timeout != DAL_MAX_DELAY) + { + if((Timeout == 0U) || ((DAL_GetTick() - tickstart ) > Timeout)) + { + /* New check to avoid false timeout detection in case of preemption */ + if(!(__DAL_ADC_GET_FLAG(hadc, ADC_FLAG_EOC))) + { + /* Update ADC state machine to timeout */ + SET_BIT(hadc->State, DAL_ADC_STATE_TIMEOUT); + + /* Process unlocked */ + __DAL_UNLOCK(hadc); + + return DAL_TIMEOUT; + } + } + } + } + + /* Clear regular group conversion flag */ + __DAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_STRT | ADC_FLAG_EOC); + + /* Update ADC state machine */ + SET_BIT(hadc->State, DAL_ADC_STATE_REG_EOC); + + /* Determine whether any further conversion upcoming on group regular */ + /* by external trigger, continuous mode or scan sequence on going. */ + /* Note: On APM32F4, there is no independent flag of end of sequence. */ + /* The test of scan sequence on going is done either with scan */ + /* sequence disabled or with end of conversion flag set to */ + /* of end of sequence. */ + if(ADC_IS_SOFTWARE_START_REGULAR(hadc) && + (hadc->Init.ContinuousConvMode == DISABLE) && + (DAL_IS_BIT_CLR(hadc->Instance->REGSEQ1, ADC_REGSEQ1_REGSEQLEN) || + DAL_IS_BIT_CLR(hadc->Instance->CTRL2, ADC_CTRL2_EOCSEL) ) ) + { + /* Set ADC state */ + CLEAR_BIT(hadc->State, DAL_ADC_STATE_REG_BUSY); + + if (DAL_IS_BIT_CLR(hadc->State, DAL_ADC_STATE_INJ_BUSY)) + { + SET_BIT(hadc->State, DAL_ADC_STATE_READY); + } + } + + /* Return ADC state */ + return DAL_OK; +} + +/** + * @brief Poll for conversion event + * @param hadc pointer to a ADC_HandleTypeDef structure that contains + * the configuration information for the specified ADC. + * @param EventType the ADC event type. + * This parameter can be one of the following values: + * @arg ADC_AWD_EVENT: ADC Analog watch Dog event. + * @arg ADC_OVR_EVENT: ADC Overrun event. + * @param Timeout Timeout value in millisecond. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_ADC_PollForEvent(ADC_HandleTypeDef* hadc, uint32_t EventType, uint32_t Timeout) +{ + uint32_t tickstart = 0U; + + /* Check the parameters */ + ASSERT_PARAM(IS_ADC_ALL_INSTANCE(hadc->Instance)); + ASSERT_PARAM(IS_ADC_EVENT_TYPE(EventType)); + + /* Get tick */ + tickstart = DAL_GetTick(); + + /* Check selected event flag */ + while(!(__DAL_ADC_GET_FLAG(hadc,EventType))) + { + /* Check for the Timeout */ + if(Timeout != DAL_MAX_DELAY) + { + if((Timeout == 0U) || ((DAL_GetTick() - tickstart ) > Timeout)) + { + /* New check to avoid false timeout detection in case of preemption */ + if(!(__DAL_ADC_GET_FLAG(hadc,EventType))) + { + /* Update ADC state machine to timeout */ + SET_BIT(hadc->State, DAL_ADC_STATE_TIMEOUT); + + /* Process unlocked */ + __DAL_UNLOCK(hadc); + + return DAL_TIMEOUT; + } + } + } + } + + /* Analog watchdog (level out of window) event */ + if(EventType == ADC_AWD_EVENT) + { + /* Set ADC state */ + SET_BIT(hadc->State, DAL_ADC_STATE_AWD1); + + /* Clear ADC analog watchdog flag */ + __DAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_AWD); + } + /* Overrun event */ + else + { + /* Set ADC state */ + SET_BIT(hadc->State, DAL_ADC_STATE_REG_OVR); + /* Set ADC error code to overrun */ + SET_BIT(hadc->ErrorCode, DAL_ADC_ERROR_OVR); + + /* Clear ADC overrun flag */ + __DAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_OVR); + } + + /* Return ADC state */ + return DAL_OK; +} + + +/** + * @brief Enables the interrupt and starts ADC conversion of regular channels. + * @param hadc pointer to a ADC_HandleTypeDef structure that contains + * the configuration information for the specified ADC. + * @retval DAL status. + */ +DAL_StatusTypeDef DAL_ADC_Start_IT(ADC_HandleTypeDef* hadc) +{ + __IO uint32_t counter = 0U; + ADC_Common_TypeDef *tmpADC_Common; + + /* Check the parameters */ + ASSERT_PARAM(IS_FUNCTIONAL_STATE(hadc->Init.ContinuousConvMode)); + ASSERT_PARAM(IS_ADC_EXT_TRIG_EDGE(hadc->Init.ExternalTrigConvEdge)); + + /* Process locked */ + __DAL_LOCK(hadc); + + /* Enable the ADC peripheral */ + /* Check if ADC peripheral is disabled in order to enable it and wait during + Tstab time the ADC's stabilization */ + if((hadc->Instance->CTRL2 & ADC_CTRL2_ADCEN) != ADC_CTRL2_ADCEN) + { + /* Enable the Peripheral */ + __DAL_ADC_ENABLE(hadc); + + /* Delay for ADC stabilization time */ + /* Compute number of CPU cycles to wait for */ + counter = (ADC_STAB_DELAY_US * (SystemCoreClock / 1000000U)); + while(counter != 0U) + { + counter--; + } + } + + /* Start conversion if ADC is effectively enabled */ + if(DAL_IS_BIT_SET(hadc->Instance->CTRL2, ADC_CTRL2_ADCEN)) + { + /* Set ADC state */ + /* - Clear state bitfield related to regular group conversion results */ + /* - Set state bitfield related to regular group operation */ + ADC_STATE_CLR_SET(hadc->State, + DAL_ADC_STATE_READY | DAL_ADC_STATE_REG_EOC | DAL_ADC_STATE_REG_OVR, + DAL_ADC_STATE_REG_BUSY); + + /* If conversions on group regular are also triggering group injected, */ + /* update ADC state. */ + if (READ_BIT(hadc->Instance->CTRL1, ADC_CTRL1_INJGACEN) != RESET) + { + ADC_STATE_CLR_SET(hadc->State, DAL_ADC_STATE_INJ_EOC, DAL_ADC_STATE_INJ_BUSY); + } + + /* State machine update: Check if an injected conversion is ongoing */ + if (DAL_IS_BIT_SET(hadc->State, DAL_ADC_STATE_INJ_BUSY)) + { + /* Reset ADC error code fields related to conversions on group regular */ + CLEAR_BIT(hadc->ErrorCode, (DAL_ADC_ERROR_OVR | DAL_ADC_ERROR_DMA)); + } + else + { + /* Reset ADC all error code fields */ + ADC_CLEAR_ERRORCODE(hadc); + } + + /* Process unlocked */ + /* Unlock before starting ADC conversions: in case of potential */ + /* interruption, to let the process to ADC IRQ Handler. */ + __DAL_UNLOCK(hadc); + + /* Pointer to the common control register to which is belonging hadc */ + /* (Depending on APM32F4 product, there may be up to 3 ADCs and 1 common */ + /* control register) */ + tmpADC_Common = ADC_COMMON_REGISTER(hadc); + + /* Clear regular group conversion flag and overrun flag */ + /* (To ensure of no unknown state from potential previous ADC operations) */ + __DAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_EOC | ADC_FLAG_OVR); + + /* Enable end of conversion interrupt for regular group */ + __DAL_ADC_ENABLE_IT(hadc, (ADC_IT_EOC | ADC_IT_OVR)); + + /* Check if Multimode enabled */ + if(DAL_IS_BIT_CLR(tmpADC_Common->CCTRL, ADC_CCTRL_ADCMSEL)) + { +#if defined(ADC2) && defined(ADC3) + if((hadc->Instance == ADC1) || ((hadc->Instance == ADC2) && ((ADC->CCTRL & ADC_CCTRL_ADCMSEL_Msk) < ADC_CCTRL_ADCMSEL_0)) \ + || ((hadc->Instance == ADC3) && ((ADC->CCTRL & ADC_CCTRL_ADCMSEL_Msk) < ADC_CCTRL_ADCMSEL_4))) + { +#endif /* ADC2 || ADC3 */ + /* if no external trigger present enable software conversion of regular channels */ + if((hadc->Instance->CTRL2 & ADC_CTRL2_REGEXTTRGEN) == RESET) + { + /* Enable the selected ADC software conversion for regular group */ + hadc->Instance->CTRL2 |= (uint32_t)ADC_CTRL2_REGCHSC; + } +#if defined(ADC2) && defined(ADC3) + } +#endif /* ADC2 || ADC3 */ + } + else + { + /* if instance of handle correspond to ADC1 and no external trigger present enable software conversion of regular channels */ + if(((hadc->Instance == ADC1) || (hadc->Instance == ADC2)) && ((hadc->Instance->CTRL2 & ADC_CTRL2_REGEXTTRGEN) == RESET)) + { + /* Enable the selected ADC software conversion for regular group */ + hadc->Instance->CTRL2 |= (uint32_t)ADC_CTRL2_REGCHSC; + } + } + } + else + { + /* Update ADC state machine to error */ + SET_BIT(hadc->State, DAL_ADC_STATE_ERROR_INTERNAL); + + /* Set ADC error code to ADC IP internal error */ + SET_BIT(hadc->ErrorCode, DAL_ADC_ERROR_INTERNAL); + } + + /* Return function status */ + return DAL_OK; +} + +/** + * @brief Disables the interrupt and stop ADC conversion of regular channels. + * + * @note Caution: This function will stop also injected channels. + * + * @param hadc pointer to a ADC_HandleTypeDef structure that contains + * the configuration information for the specified ADC. + * @retval DAL status. + */ +DAL_StatusTypeDef DAL_ADC_Stop_IT(ADC_HandleTypeDef* hadc) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_ADC_ALL_INSTANCE(hadc->Instance)); + + /* Process locked */ + __DAL_LOCK(hadc); + + /* Stop potential conversion on going, on regular and injected groups */ + /* Disable ADC peripheral */ + __DAL_ADC_DISABLE(hadc); + + /* Check if ADC is effectively disabled */ + if(DAL_IS_BIT_CLR(hadc->Instance->CTRL2, ADC_CTRL2_ADCEN)) + { + /* Disable ADC end of conversion interrupt for regular group */ + __DAL_ADC_DISABLE_IT(hadc, (ADC_IT_EOC | ADC_IT_OVR)); + + /* Set ADC state */ + ADC_STATE_CLR_SET(hadc->State, + DAL_ADC_STATE_REG_BUSY | DAL_ADC_STATE_INJ_BUSY, + DAL_ADC_STATE_READY); + } + + /* Process unlocked */ + __DAL_UNLOCK(hadc); + + /* Return function status */ + return DAL_OK; +} + +/** + * @brief Handles ADC interrupt request + * @param hadc pointer to a ADC_HandleTypeDef structure that contains + * the configuration information for the specified ADC. + * @retval None + */ +void DAL_ADC_IRQHandler(ADC_HandleTypeDef* hadc) +{ + uint32_t tmp1 = 0U, tmp2 = 0U; + + uint32_t tmp_sr = hadc->Instance->STS; + uint32_t tmp_cr1 = hadc->Instance->CTRL1; + + /* Check the parameters */ + ASSERT_PARAM(IS_FUNCTIONAL_STATE(hadc->Init.ContinuousConvMode)); + ASSERT_PARAM(IS_ADC_REGULAR_LENGTH(hadc->Init.NbrOfConversion)); + ASSERT_PARAM(IS_ADC_EOCSelection(hadc->Init.EOCSelection)); + + tmp1 = tmp_sr & ADC_FLAG_EOC; + tmp2 = tmp_cr1 & ADC_IT_EOC; + /* Check End of conversion flag for regular channels */ + if(tmp1 && tmp2) + { + /* Update state machine on conversion status if not in error state */ + if (DAL_IS_BIT_CLR(hadc->State, DAL_ADC_STATE_ERROR_INTERNAL)) + { + /* Set ADC state */ + SET_BIT(hadc->State, DAL_ADC_STATE_REG_EOC); + } + + /* Determine whether any further conversion upcoming on group regular */ + /* by external trigger, continuous mode or scan sequence on going. */ + /* Note: On APM32F4, there is no independent flag of end of sequence. */ + /* The test of scan sequence on going is done either with scan */ + /* sequence disabled or with end of conversion flag set to */ + /* of end of sequence. */ + if(ADC_IS_SOFTWARE_START_REGULAR(hadc) && + (hadc->Init.ContinuousConvMode == DISABLE) && + (DAL_IS_BIT_CLR(hadc->Instance->REGSEQ1, ADC_REGSEQ1_REGSEQLEN) || + DAL_IS_BIT_CLR(hadc->Instance->CTRL2, ADC_CTRL2_EOCSEL) ) ) + { + /* Disable ADC end of single conversion interrupt on group regular */ + /* Note: Overrun interrupt was enabled with EOC interrupt in */ + /* DAL_ADC_Start_IT(), but is not disabled here because can be used */ + /* by overrun IRQ process below. */ + __DAL_ADC_DISABLE_IT(hadc, ADC_IT_EOC); + + /* Set ADC state */ + CLEAR_BIT(hadc->State, DAL_ADC_STATE_REG_BUSY); + + if (DAL_IS_BIT_CLR(hadc->State, DAL_ADC_STATE_INJ_BUSY)) + { + SET_BIT(hadc->State, DAL_ADC_STATE_READY); + } + } + + /* Conversion complete callback */ +#if (USE_DAL_ADC_REGISTER_CALLBACKS == 1) + hadc->ConvCpltCallback(hadc); +#else + DAL_ADC_ConvCpltCallback(hadc); +#endif /* USE_DAL_ADC_REGISTER_CALLBACKS */ + + /* Clear regular group conversion flag */ + __DAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_STRT | ADC_FLAG_EOC); + } + + tmp1 = tmp_sr & ADC_FLAG_JEOC; + tmp2 = tmp_cr1 & ADC_IT_JEOC; + /* Check End of conversion flag for injected channels */ + if(tmp1 && tmp2) + { + /* Update state machine on conversion status if not in error state */ + if (DAL_IS_BIT_CLR(hadc->State, DAL_ADC_STATE_ERROR_INTERNAL)) + { + /* Set ADC state */ + SET_BIT(hadc->State, DAL_ADC_STATE_INJ_EOC); + } + + /* Determine whether any further conversion upcoming on group injected */ + /* by external trigger, scan sequence on going or by automatic injected */ + /* conversion from group regular (same conditions as group regular */ + /* interruption disabling above). */ + if(ADC_IS_SOFTWARE_START_INJECTED(hadc) && + (DAL_IS_BIT_CLR(hadc->Instance->INJSEQ, ADC_INJSEQ_INJSEQLEN) || + DAL_IS_BIT_CLR(hadc->Instance->CTRL2, ADC_CTRL2_EOCSEL) ) && + (DAL_IS_BIT_CLR(hadc->Instance->CTRL1, ADC_CTRL1_INJGACEN) && + (ADC_IS_SOFTWARE_START_REGULAR(hadc) && + (hadc->Init.ContinuousConvMode == DISABLE) ) ) ) + { + /* Disable ADC end of single conversion interrupt on group injected */ + __DAL_ADC_DISABLE_IT(hadc, ADC_IT_JEOC); + + /* Set ADC state */ + CLEAR_BIT(hadc->State, DAL_ADC_STATE_INJ_BUSY); + + if (DAL_IS_BIT_CLR(hadc->State, DAL_ADC_STATE_REG_BUSY)) + { + SET_BIT(hadc->State, DAL_ADC_STATE_READY); + } + } + + /* Conversion complete callback */ + /* Conversion complete callback */ +#if (USE_DAL_ADC_REGISTER_CALLBACKS == 1) + hadc->InjectedConvCpltCallback(hadc); +#else + DAL_ADCEx_InjectedConvCpltCallback(hadc); +#endif /* USE_DAL_ADC_REGISTER_CALLBACKS */ + + /* Clear injected group conversion flag */ + __DAL_ADC_CLEAR_FLAG(hadc, (ADC_FLAG_JSTRT | ADC_FLAG_JEOC)); + } + + tmp1 = tmp_sr & ADC_FLAG_AWD; + tmp2 = tmp_cr1 & ADC_IT_AWD; + /* Check Analog watchdog flag */ + if(tmp1 && tmp2) + { + if(__DAL_ADC_GET_FLAG(hadc, ADC_FLAG_AWD)) + { + /* Set ADC state */ + SET_BIT(hadc->State, DAL_ADC_STATE_AWD1); + + /* Level out of window callback */ +#if (USE_DAL_ADC_REGISTER_CALLBACKS == 1) + hadc->LevelOutOfWindowCallback(hadc); +#else + DAL_ADC_LevelOutOfWindowCallback(hadc); +#endif /* USE_DAL_ADC_REGISTER_CALLBACKS */ + + /* Clear the ADC analog watchdog flag */ + __DAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_AWD); + } + } + + tmp1 = tmp_sr & ADC_FLAG_OVR; + tmp2 = tmp_cr1 & ADC_IT_OVR; + /* Check Overrun flag */ + if(tmp1 && tmp2) + { + /* Note: On APM32F4, ADC overrun can be set through other parameters */ + /* refer to description of parameter "EOCSelection" for more */ + /* details. */ + + /* Set ADC error code to overrun */ + SET_BIT(hadc->ErrorCode, DAL_ADC_ERROR_OVR); + + /* Clear ADC overrun flag */ + __DAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_OVR); + + /* Error callback */ +#if (USE_DAL_ADC_REGISTER_CALLBACKS == 1) + hadc->ErrorCallback(hadc); +#else + DAL_ADC_ErrorCallback(hadc); +#endif /* USE_DAL_ADC_REGISTER_CALLBACKS */ + + /* Clear the Overrun flag */ + __DAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_OVR); + } +} + +/** + * @brief Enables ADC DMA request after last transfer (Single-ADC mode) and enables ADC peripheral + * @param hadc pointer to a ADC_HandleTypeDef structure that contains + * the configuration information for the specified ADC. + * @param pData The destination Buffer address. + * @param Length The length of data to be transferred from ADC peripheral to memory. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_ADC_Start_DMA(ADC_HandleTypeDef* hadc, uint32_t* pData, uint32_t Length) +{ + __IO uint32_t counter = 0U; + ADC_Common_TypeDef *tmpADC_Common; + + /* Check the parameters */ + ASSERT_PARAM(IS_FUNCTIONAL_STATE(hadc->Init.ContinuousConvMode)); + ASSERT_PARAM(IS_ADC_EXT_TRIG_EDGE(hadc->Init.ExternalTrigConvEdge)); + + /* Process locked */ + __DAL_LOCK(hadc); + + /* Enable the ADC peripheral */ + /* Check if ADC peripheral is disabled in order to enable it and wait during + Tstab time the ADC's stabilization */ + if((hadc->Instance->CTRL2 & ADC_CTRL2_ADCEN) != ADC_CTRL2_ADCEN) + { + /* Enable the Peripheral */ + __DAL_ADC_ENABLE(hadc); + + /* Delay for ADC stabilization time */ + /* Compute number of CPU cycles to wait for */ + counter = (ADC_STAB_DELAY_US * (SystemCoreClock / 1000000U)); + while(counter != 0U) + { + counter--; + } + } + + /* Check ADC DMA Mode */ + /* - disable the DMA Mode if it is already enabled */ + if((hadc->Instance->CTRL2 & ADC_CTRL2_DMAEN) == ADC_CTRL2_DMAEN) + { + CLEAR_BIT(hadc->Instance->CTRL2, ADC_CTRL2_DMAEN); + } + + /* Start conversion if ADC is effectively enabled */ + if(DAL_IS_BIT_SET(hadc->Instance->CTRL2, ADC_CTRL2_ADCEN)) + { + /* Set ADC state */ + /* - Clear state bitfield related to regular group conversion results */ + /* - Set state bitfield related to regular group operation */ + ADC_STATE_CLR_SET(hadc->State, + DAL_ADC_STATE_READY | DAL_ADC_STATE_REG_EOC | DAL_ADC_STATE_REG_OVR, + DAL_ADC_STATE_REG_BUSY); + + /* If conversions on group regular are also triggering group injected, */ + /* update ADC state. */ + if (READ_BIT(hadc->Instance->CTRL1, ADC_CTRL1_INJGACEN) != RESET) + { + ADC_STATE_CLR_SET(hadc->State, DAL_ADC_STATE_INJ_EOC, DAL_ADC_STATE_INJ_BUSY); + } + + /* State machine update: Check if an injected conversion is ongoing */ + if (DAL_IS_BIT_SET(hadc->State, DAL_ADC_STATE_INJ_BUSY)) + { + /* Reset ADC error code fields related to conversions on group regular */ + CLEAR_BIT(hadc->ErrorCode, (DAL_ADC_ERROR_OVR | DAL_ADC_ERROR_DMA)); + } + else + { + /* Reset ADC all error code fields */ + ADC_CLEAR_ERRORCODE(hadc); + } + + /* Process unlocked */ + /* Unlock before starting ADC conversions: in case of potential */ + /* interruption, to let the process to ADC IRQ Handler. */ + __DAL_UNLOCK(hadc); + + /* Pointer to the common control register to which is belonging hadc */ + /* (Depending on APM32F4 product, there may be up to 3 ADCs and 1 common */ + /* control register) */ + tmpADC_Common = ADC_COMMON_REGISTER(hadc); + + /* Set the DMA transfer complete callback */ + hadc->DMA_Handle->XferCpltCallback = ADC_DMAConvCplt; + + /* Set the DMA half transfer complete callback */ + hadc->DMA_Handle->XferHalfCpltCallback = ADC_DMAHalfConvCplt; + + /* Set the DMA error callback */ + hadc->DMA_Handle->XferErrorCallback = ADC_DMAError; + + + /* Manage ADC and DMA start: ADC overrun interruption, DMA start, ADC */ + /* start (in case of SW start): */ + + /* Clear regular group conversion flag and overrun flag */ + /* (To ensure of no unknown state from potential previous ADC operations) */ + __DAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_EOC | ADC_FLAG_OVR); + + /* Enable ADC overrun interrupt */ + __DAL_ADC_ENABLE_IT(hadc, ADC_IT_OVR); + + /* Enable ADC DMA mode */ + hadc->Instance->CTRL2 |= ADC_CTRL2_DMAEN; + + /* Start the DMA channel */ + DAL_DMA_Start_IT(hadc->DMA_Handle, (uint32_t)&hadc->Instance->REGDATA, (uint32_t)pData, Length); + + /* Check if Multimode enabled */ + if(DAL_IS_BIT_CLR(tmpADC_Common->CCTRL, ADC_CCTRL_ADCMSEL)) + { +#if defined(ADC2) && defined(ADC3) + if((hadc->Instance == ADC1) || ((hadc->Instance == ADC2) && ((ADC->CCTRL & ADC_CCTRL_ADCMSEL_Msk) < ADC_CCTRL_ADCMSEL_0)) \ + || ((hadc->Instance == ADC3) && ((ADC->CCTRL & ADC_CCTRL_ADCMSEL_Msk) < ADC_CCTRL_ADCMSEL_4))) + { +#endif /* ADC2 || ADC3 */ + /* if no external trigger present enable software conversion of regular channels */ + if((hadc->Instance->CTRL2 & ADC_CTRL2_REGEXTTRGEN) == RESET) + { + /* Enable the selected ADC software conversion for regular group */ + hadc->Instance->CTRL2 |= (uint32_t)ADC_CTRL2_REGCHSC; + } +#if defined(ADC2) && defined(ADC3) + } +#endif /* ADC2 || ADC3 */ + } + else + { + /* if instance of handle correspond to ADC1 and no external trigger present enable software conversion of regular channels */ + if(((hadc->Instance == ADC1) || (hadc->Instance == ADC2)) && ((hadc->Instance->CTRL2 & ADC_CTRL2_REGEXTTRGEN) == RESET)) + { + /* Enable the selected ADC software conversion for regular group */ + hadc->Instance->CTRL2 |= (uint32_t)ADC_CTRL2_REGCHSC; + } + } + } + else + { + /* Update ADC state machine to error */ + SET_BIT(hadc->State, DAL_ADC_STATE_ERROR_INTERNAL); + + /* Set ADC error code to ADC IP internal error */ + SET_BIT(hadc->ErrorCode, DAL_ADC_ERROR_INTERNAL); + } + + /* Return function status */ + return DAL_OK; +} + +/** + * @brief Disables ADC DMA (Single-ADC mode) and disables ADC peripheral + * @param hadc pointer to a ADC_HandleTypeDef structure that contains + * the configuration information for the specified ADC. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_ADC_Stop_DMA(ADC_HandleTypeDef* hadc) +{ + DAL_StatusTypeDef tmp_dal_status = DAL_OK; + + /* Check the parameters */ + ASSERT_PARAM(IS_ADC_ALL_INSTANCE(hadc->Instance)); + + /* Process locked */ + __DAL_LOCK(hadc); + + /* Stop potential conversion on going, on regular and injected groups */ + /* Disable ADC peripheral */ + __DAL_ADC_DISABLE(hadc); + + /* Check if ADC is effectively disabled */ + if(DAL_IS_BIT_CLR(hadc->Instance->CTRL2, ADC_CTRL2_ADCEN)) + { + /* Disable the selected ADC DMA mode */ + hadc->Instance->CTRL2 &= ~ADC_CTRL2_DMAEN; + + /* Disable the DMA channel (in case of DMA in circular mode or stop while */ + /* DMA transfer is on going) */ + if (hadc->DMA_Handle->State == DAL_DMA_STATE_BUSY) + { + tmp_dal_status = DAL_DMA_Abort(hadc->DMA_Handle); + + /* Check if DMA channel effectively disabled */ + if (tmp_dal_status != DAL_OK) + { + /* Update ADC state machine to error */ + SET_BIT(hadc->State, DAL_ADC_STATE_ERROR_DMA); + } + } + + /* Disable ADC overrun interrupt */ + __DAL_ADC_DISABLE_IT(hadc, ADC_IT_OVR); + + /* Set ADC state */ + ADC_STATE_CLR_SET(hadc->State, + DAL_ADC_STATE_REG_BUSY | DAL_ADC_STATE_INJ_BUSY, + DAL_ADC_STATE_READY); + } + + /* Process unlocked */ + __DAL_UNLOCK(hadc); + + /* Return function status */ + return tmp_dal_status; +} + +/** + * @brief Gets the converted value from data register of regular channel. + * @param hadc pointer to a ADC_HandleTypeDef structure that contains + * the configuration information for the specified ADC. + * @retval Converted value + */ +uint32_t DAL_ADC_GetValue(ADC_HandleTypeDef* hadc) +{ + /* Return the selected ADC converted value */ + return hadc->Instance->REGDATA; +} + +/** + * @brief Regular conversion complete callback in non blocking mode + * @param hadc pointer to a ADC_HandleTypeDef structure that contains + * the configuration information for the specified ADC. + * @retval None + */ +__weak void DAL_ADC_ConvCpltCallback(ADC_HandleTypeDef* hadc) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hadc); + /* NOTE : This function Should not be modified, when the callback is needed, + the DAL_ADC_ConvCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Regular conversion half DMA transfer callback in non blocking mode + * @param hadc pointer to a ADC_HandleTypeDef structure that contains + * the configuration information for the specified ADC. + * @retval None + */ +__weak void DAL_ADC_ConvHalfCpltCallback(ADC_HandleTypeDef* hadc) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hadc); + /* NOTE : This function Should not be modified, when the callback is needed, + the DAL_ADC_ConvHalfCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Analog watchdog callback in non blocking mode + * @param hadc pointer to a ADC_HandleTypeDef structure that contains + * the configuration information for the specified ADC. + * @retval None + */ +__weak void DAL_ADC_LevelOutOfWindowCallback(ADC_HandleTypeDef* hadc) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hadc); + /* NOTE : This function Should not be modified, when the callback is needed, + the DAL_ADC_LevelOoutOfWindowCallback could be implemented in the user file + */ +} + +/** + * @brief Error ADC callback. + * @note In case of error due to overrun when using ADC with DMA transfer + * (DAL ADC handle parameter "ErrorCode" to state "DAL_ADC_ERROR_OVR"): + * - Reinitialize the DMA using function "DAL_ADC_Stop_DMA()". + * - If needed, restart a new ADC conversion using function + * "DAL_ADC_Start_DMA()" + * (this function is also clearing overrun flag) + * @param hadc pointer to a ADC_HandleTypeDef structure that contains + * the configuration information for the specified ADC. + * @retval None + */ +__weak void DAL_ADC_ErrorCallback(ADC_HandleTypeDef *hadc) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hadc); + /* NOTE : This function Should not be modified, when the callback is needed, + the DAL_ADC_ErrorCallback could be implemented in the user file + */ +} + +/** + * @} + */ + +/** @defgroup ADC_Exported_Functions_Group3 Peripheral Control functions + * @brief Peripheral Control functions + * +@verbatim + =============================================================================== + ##### Peripheral Control functions ##### + =============================================================================== + [..] This section provides functions allowing to: + (+) Configure regular channels. + (+) Configure injected channels. + (+) Configure multimode. + (+) Configure the analog watch dog. + +@endverbatim + * @{ + */ + + /** + * @brief Configures for the selected ADC regular channel its corresponding + * rank in the sequencer and its sample time. + * @param hadc pointer to a ADC_HandleTypeDef structure that contains + * the configuration information for the specified ADC. + * @param sConfig ADC configuration structure. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_ADC_ConfigChannel(ADC_HandleTypeDef* hadc, ADC_ChannelConfTypeDef* sConfig) +{ + __IO uint32_t counter = 0U; + ADC_Common_TypeDef *tmpADC_Common; + + /* Check the parameters */ + ASSERT_PARAM(IS_ADC_CHANNEL(sConfig->Channel)); + ASSERT_PARAM(IS_ADC_REGULAR_RANK(sConfig->Rank)); + ASSERT_PARAM(IS_ADC_SAMPLE_TIME(sConfig->SamplingTime)); + + /* Process locked */ + __DAL_LOCK(hadc); + + /* if ADC_Channel_10 ... ADC_Channel_18 is selected */ + if (sConfig->Channel > ADC_CHANNEL_9) + { + /* Clear the old sample time */ + hadc->Instance->SMPTIM1 &= ~ADC_SMPTIM1(ADC_SMPTIM1_SMPCYCCFG10, sConfig->Channel); + + /* Set the new sample time */ + hadc->Instance->SMPTIM1 |= ADC_SMPTIM1(sConfig->SamplingTime, sConfig->Channel); + } + else /* ADC_Channel include in ADC_Channel_[0..9] */ + { + /* Clear the old sample time */ + hadc->Instance->SMPTIM2 &= ~ADC_SMPTIM2(ADC_SMPTIM2_SMPCYCCFG0, sConfig->Channel); + + /* Set the new sample time */ + hadc->Instance->SMPTIM2 |= ADC_SMPTIM2(sConfig->SamplingTime, sConfig->Channel); + } + + /* For Rank 1 to 6 */ + if (sConfig->Rank < 7U) + { + /* Clear the old REGSEQCx bits for the selected rank */ + hadc->Instance->REGSEQ3 &= ~ADC_REGSEQ3_RK(ADC_REGSEQ3_REGSEQC1, sConfig->Rank); + + /* Set the REGSEQCx bits for the selected rank */ + hadc->Instance->REGSEQ3 |= ADC_REGSEQ3_RK(sConfig->Channel, sConfig->Rank); + } + /* For Rank 7 to 12 */ + else if (sConfig->Rank < 13U) + { + /* Clear the old REGSEQCx bits for the selected rank */ + hadc->Instance->REGSEQ2 &= ~ADC_REGSEQ2_RK(ADC_REGSEQ2_REGSEQC7, sConfig->Rank); + + /* Set the REGSEQCx bits for the selected rank */ + hadc->Instance->REGSEQ2 |= ADC_REGSEQ2_RK(sConfig->Channel, sConfig->Rank); + } + /* For Rank 13 to 16 */ + else + { + /* Clear the old REGSEQCx bits for the selected rank */ + hadc->Instance->REGSEQ1 &= ~ADC_REGSEQ1_RK(ADC_REGSEQ1_REGSEQC13, sConfig->Rank); + + /* Set the REGSEQCx bits for the selected rank */ + hadc->Instance->REGSEQ1 |= ADC_REGSEQ1_RK(sConfig->Channel, sConfig->Rank); + } + + /* Pointer to the common control register to which is belonging hadc */ + /* (Depending on APM32F4 product, there may be up to 3 ADCs and 1 common */ + /* control register) */ + tmpADC_Common = ADC_COMMON_REGISTER(hadc); + + /* if ADC1 Channel_18 is selected for VBAT Channel ennable VBATE */ + if ((hadc->Instance == ADC1) && (sConfig->Channel == ADC_CHANNEL_VBAT)) + { + /* Disable the TEMPSENSOR channel in case of using board with multiplixed ADC_CHANNEL_VBAT & ADC_CHANNEL_TEMPSENSOR*/ + if ((uint16_t)ADC_CHANNEL_TEMPSENSOR == (uint16_t)ADC_CHANNEL_VBAT) + { + tmpADC_Common->CCTRL &= ~ADC_CCTRL_TSVREFEN; + } + /* Enable the VBAT channel*/ + tmpADC_Common->CCTRL |= ADC_CCTRL_VBATEN; + } + + /* if ADC1 Channel_16 or Channel_18 is selected for Temperature sensor or + Channel_17 is selected for VREFINT enable TSVREFEN */ + if ((hadc->Instance == ADC1) && ((sConfig->Channel == ADC_CHANNEL_TEMPSENSOR) || (sConfig->Channel == ADC_CHANNEL_VREFINT))) + { + /* Disable the VBAT channel in case of using board with multiplixed ADC_CHANNEL_VBAT & ADC_CHANNEL_TEMPSENSOR*/ + if ((uint16_t)ADC_CHANNEL_TEMPSENSOR == (uint16_t)ADC_CHANNEL_VBAT) + { + tmpADC_Common->CCTRL &= ~ADC_CCTRL_VBATEN; + } + /* Enable the Temperature sensor and VREFINT channel*/ + tmpADC_Common->CCTRL |= ADC_CCTRL_TSVREFEN; + + if(sConfig->Channel == ADC_CHANNEL_TEMPSENSOR) + { + /* Delay for temperature sensor stabilization time */ + /* Compute number of CPU cycles to wait for */ + counter = (ADC_TEMPSENSOR_DELAY_US * (SystemCoreClock / 1000000U)); + while(counter != 0U) + { + counter--; + } + } + } + + /* Process unlocked */ + __DAL_UNLOCK(hadc); + + /* Return function status */ + return DAL_OK; +} + +/** + * @brief Configures the analog watchdog. + * @note Analog watchdog thresholds can be modified while ADC conversion + * is on going. + * In this case, some constraints must be taken into account: + * The programmed threshold values are effective from the next + * ADC EOC (end of unitary conversion). + * Considering that registers write delay may happen due to + * bus activity, this might cause an uncertainty on the + * effective timing of the new programmed threshold values. + * @param hadc pointer to a ADC_HandleTypeDef structure that contains + * the configuration information for the specified ADC. + * @param AnalogWDGConfig pointer to an ADC_AnalogWDGConfTypeDef structure + * that contains the configuration information of ADC analog watchdog. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_ADC_AnalogWDGConfig(ADC_HandleTypeDef* hadc, ADC_AnalogWDGConfTypeDef* AnalogWDGConfig) +{ +#if (USE_FULL_ASSERT == 1U) + uint32_t tmp = 0U; +#endif /* USE_FULL_ASSERT */ + + /* Check the parameters */ + ASSERT_PARAM(IS_ADC_ANALOG_WATCHDOG(AnalogWDGConfig->WatchdogMode)); + ASSERT_PARAM(IS_ADC_CHANNEL(AnalogWDGConfig->Channel)); + ASSERT_PARAM(IS_FUNCTIONAL_STATE(AnalogWDGConfig->ITMode)); + +#if (USE_FULL_ASSERT == 1U) + tmp = ADC_GET_RESOLUTION(hadc); + ASSERT_PARAM(IS_ADC_RANGE(tmp, AnalogWDGConfig->HighThreshold)); + ASSERT_PARAM(IS_ADC_RANGE(tmp, AnalogWDGConfig->LowThreshold)); +#endif /* USE_FULL_ASSERT */ + + /* Process locked */ + __DAL_LOCK(hadc); + + if(AnalogWDGConfig->ITMode == ENABLE) + { + /* Enable the ADC Analog watchdog interrupt */ + __DAL_ADC_ENABLE_IT(hadc, ADC_IT_AWD); + } + else + { + /* Disable the ADC Analog watchdog interrupt */ + __DAL_ADC_DISABLE_IT(hadc, ADC_IT_AWD); + } + + /* Clear REGAWDEN, INJAWDEN and AWDSGLEN bits */ + hadc->Instance->CTRL1 &= ~(ADC_CTRL1_AWDSGLEN | ADC_CTRL1_INJAWDEN | ADC_CTRL1_REGAWDEN); + + /* Set the analog watchdog enable mode */ + hadc->Instance->CTRL1 |= AnalogWDGConfig->WatchdogMode; + + /* Set the high threshold */ + hadc->Instance->AWDHT = AnalogWDGConfig->HighThreshold; + + /* Set the low threshold */ + hadc->Instance->AWDLT = AnalogWDGConfig->LowThreshold; + + /* Clear the Analog watchdog channel select bits */ + hadc->Instance->CTRL1 &= ~ADC_CTRL1_AWDCHSEL; + + /* Set the Analog watchdog channel */ + hadc->Instance->CTRL1 |= (uint32_t)((uint16_t)(AnalogWDGConfig->Channel)); + + /* Process unlocked */ + __DAL_UNLOCK(hadc); + + /* Return function status */ + return DAL_OK; +} + +/** + * @} + */ + +/** @defgroup ADC_Exported_Functions_Group4 ADC Peripheral State functions + * @brief ADC Peripheral State functions + * +@verbatim + =============================================================================== + ##### Peripheral State and errors functions ##### + =============================================================================== + [..] + This subsection provides functions allowing to + (+) Check the ADC state + (+) Check the ADC Error + +@endverbatim + * @{ + */ + +/** + * @brief return the ADC state + * @param hadc pointer to a ADC_HandleTypeDef structure that contains + * the configuration information for the specified ADC. + * @retval DAL state + */ +uint32_t DAL_ADC_GetState(ADC_HandleTypeDef* hadc) +{ + /* Return ADC state */ + return hadc->State; +} + +/** + * @brief Return the ADC error code + * @param hadc pointer to a ADC_HandleTypeDef structure that contains + * the configuration information for the specified ADC. + * @retval ADC Error Code + */ +uint32_t DAL_ADC_GetError(ADC_HandleTypeDef *hadc) +{ + return hadc->ErrorCode; +} + +/** + * @} + */ + +/** @addtogroup ADC_Private_Functions + * @{ + */ + +/** + * @brief Initializes the ADCx peripheral according to the specified parameters + * in the ADC_InitStruct without initializing the ADC MSP. + * @param hadc pointer to a ADC_HandleTypeDef structure that contains + * the configuration information for the specified ADC. + * @retval None + */ +static void ADC_Init(ADC_HandleTypeDef* hadc) +{ + ADC_Common_TypeDef *tmpADC_Common; + + /* Set ADC parameters */ + /* Pointer to the common control register to which is belonging hadc */ + /* (Depending on APM32F4 product, there may be up to 3 ADCs and 1 common */ + /* control register) */ + tmpADC_Common = ADC_COMMON_REGISTER(hadc); + + /* Set the ADC clock prescaler */ + tmpADC_Common->CCTRL &= ~(ADC_CCTRL_ADCPRE); + tmpADC_Common->CCTRL |= hadc->Init.ClockPrescaler; + + /* Set ADC scan mode */ + hadc->Instance->CTRL1 &= ~(ADC_CTRL1_SCANEN); + hadc->Instance->CTRL1 |= ADC_CTRL1_SCANENCONV(hadc->Init.ScanConvMode); + + /* Set ADC resolution */ + hadc->Instance->CTRL1 &= ~(ADC_CTRL1_RESSEL); + hadc->Instance->CTRL1 |= hadc->Init.Resolution; + + /* Set ADC data alignment */ + hadc->Instance->CTRL2 &= ~(ADC_CTRL2_DALIGNCFG); + hadc->Instance->CTRL2 |= hadc->Init.DataAlign; + + /* Enable external trigger if trigger selection is different of software */ + /* start. */ + /* Note: This configuration keeps the hardware feature of parameter */ + /* ExternalTrigConvEdge "trigger edge none" equivalent to */ + /* software start. */ + if(hadc->Init.ExternalTrigConv != ADC_SOFTWARE_START) + { + /* Select external trigger to start conversion */ + hadc->Instance->CTRL2 &= ~(ADC_CTRL2_REGEXTTRGSEL); + hadc->Instance->CTRL2 |= hadc->Init.ExternalTrigConv; + + /* Select external trigger polarity */ + hadc->Instance->CTRL2 &= ~(ADC_CTRL2_REGEXTTRGEN); + hadc->Instance->CTRL2 |= hadc->Init.ExternalTrigConvEdge; + } + else + { + /* Reset the external trigger */ + hadc->Instance->CTRL2 &= ~(ADC_CTRL2_REGEXTTRGSEL); + hadc->Instance->CTRL2 &= ~(ADC_CTRL2_REGEXTTRGEN); + } + + /* Enable or disable ADC continuous conversion mode */ + hadc->Instance->CTRL2 &= ~(ADC_CTRL2_CONTCEN); + hadc->Instance->CTRL2 |= ADC_CTRL2_CONTCENINUOUS((uint32_t)hadc->Init.ContinuousConvMode); + + if(hadc->Init.DiscontinuousConvMode != DISABLE) + { + ASSERT_PARAM(IS_ADC_REGULAR_DISC_NUMBER(hadc->Init.NbrOfDiscConversion)); + + /* Enable the selected ADC regular discontinuous mode */ + hadc->Instance->CTRL1 |= (uint32_t)ADC_CTRL1_REGDISCEN; + + /* Set the number of channels to be converted in discontinuous mode */ + hadc->Instance->CTRL1 &= ~(ADC_CTRL1_DISCNUMCFG); + hadc->Instance->CTRL1 |= ADC_CTRL1_DISCONTINUOUS(hadc->Init.NbrOfDiscConversion); + } + else + { + /* Disable the selected ADC regular discontinuous mode */ + hadc->Instance->CTRL1 &= ~(ADC_CTRL1_REGDISCEN); + } + + /* Set ADC number of conversion */ + hadc->Instance->REGSEQ1 &= ~(ADC_REGSEQ1_REGSEQLEN); + hadc->Instance->REGSEQ1 |= ADC_REGSEQ1(hadc->Init.NbrOfConversion); + + /* Enable or disable ADC DMA continuous request */ + hadc->Instance->CTRL2 &= ~(ADC_CTRL2_DMADISSEL); + hadc->Instance->CTRL2 |= ADC_CTRL2_DMAENContReq((uint32_t)hadc->Init.DMAContinuousRequests); + + /* Enable or disable ADC end of conversion selection */ + hadc->Instance->CTRL2 &= ~(ADC_CTRL2_EOCSEL); + hadc->Instance->CTRL2 |= ADC_CTRL2_EOCSELelection(hadc->Init.EOCSelection); +} + +/** + * @brief DMA transfer complete callback. + * @param hdma pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +static void ADC_DMAConvCplt(DMA_HandleTypeDef *hdma) +{ + /* Retrieve ADC handle corresponding to current DMA handle */ + ADC_HandleTypeDef* hadc = ( ADC_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + + /* Update state machine on conversion status if not in error state */ + if (DAL_IS_BIT_CLR(hadc->State, DAL_ADC_STATE_ERROR_INTERNAL | DAL_ADC_STATE_ERROR_DMA)) + { + /* Update ADC state machine */ + SET_BIT(hadc->State, DAL_ADC_STATE_REG_EOC); + + /* Determine whether any further conversion upcoming on group regular */ + /* by external trigger, continuous mode or scan sequence on going. */ + /* Note: On APM32F4, there is no independent flag of end of sequence. */ + /* The test of scan sequence on going is done either with scan */ + /* sequence disabled or with end of conversion flag set to */ + /* of end of sequence. */ + if(ADC_IS_SOFTWARE_START_REGULAR(hadc) && + (hadc->Init.ContinuousConvMode == DISABLE) && + (DAL_IS_BIT_CLR(hadc->Instance->REGSEQ1, ADC_REGSEQ1_REGSEQLEN) || + DAL_IS_BIT_CLR(hadc->Instance->CTRL2, ADC_CTRL2_EOCSEL) ) ) + { + /* Disable ADC end of single conversion interrupt on group regular */ + /* Note: Overrun interrupt was enabled with EOC interrupt in */ + /* DAL_ADC_Start_IT(), but is not disabled here because can be used */ + /* by overrun IRQ process below. */ + __DAL_ADC_DISABLE_IT(hadc, ADC_IT_EOC); + + /* Set ADC state */ + CLEAR_BIT(hadc->State, DAL_ADC_STATE_REG_BUSY); + + if (DAL_IS_BIT_CLR(hadc->State, DAL_ADC_STATE_INJ_BUSY)) + { + SET_BIT(hadc->State, DAL_ADC_STATE_READY); + } + } + + /* Conversion complete callback */ +#if (USE_DAL_ADC_REGISTER_CALLBACKS == 1) + hadc->ConvCpltCallback(hadc); +#else + DAL_ADC_ConvCpltCallback(hadc); +#endif /* USE_DAL_ADC_REGISTER_CALLBACKS */ + } + else /* DMA and-or internal error occurred */ + { + if ((hadc->State & DAL_ADC_STATE_ERROR_INTERNAL) != 0UL) + { + /* Call DAL ADC Error Callback function */ +#if (USE_DAL_ADC_REGISTER_CALLBACKS == 1) + hadc->ErrorCallback(hadc); +#else + DAL_ADC_ErrorCallback(hadc); +#endif /* USE_DAL_ADC_REGISTER_CALLBACKS */ + } + else + { + /* Call DMA error callback */ + hadc->DMA_Handle->XferErrorCallback(hdma); + } + } +} + +/** + * @brief DMA half transfer complete callback. + * @param hdma pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +static void ADC_DMAHalfConvCplt(DMA_HandleTypeDef *hdma) +{ + ADC_HandleTypeDef* hadc = ( ADC_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + /* Half conversion callback */ +#if (USE_DAL_ADC_REGISTER_CALLBACKS == 1) + hadc->ConvHalfCpltCallback(hadc); +#else + DAL_ADC_ConvHalfCpltCallback(hadc); +#endif /* USE_DAL_ADC_REGISTER_CALLBACKS */ +} + +/** + * @brief DMA error callback + * @param hdma pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +static void ADC_DMAError(DMA_HandleTypeDef *hdma) +{ + ADC_HandleTypeDef* hadc = ( ADC_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + hadc->State= DAL_ADC_STATE_ERROR_DMA; + /* Set ADC error code to DMA error */ + hadc->ErrorCode |= DAL_ADC_ERROR_DMA; + /* Error callback */ +#if (USE_DAL_ADC_REGISTER_CALLBACKS == 1) + hadc->ErrorCallback(hadc); +#else + DAL_ADC_ErrorCallback(hadc); +#endif /* USE_DAL_ADC_REGISTER_CALLBACKS */ +} + +/** + * @} + */ + +/** + * @} + */ + +#endif /* DAL_ADC_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_adc_ex.c b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_adc_ex.c new file mode 100644 index 0000000000..4bbf3d897c --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_adc_ex.c @@ -0,0 +1,1146 @@ +/** + * + * @file apm32f4xx_dal_adc_ex.c + * @brief This file provides firmware functions to manage the following + * functionalities of the ADC extension peripheral: + * + Extended features functions + * + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2017 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + * + @verbatim + ============================================================================== + ##### How to use this driver ##### + ============================================================================== + [..] + (#)Initialize the ADC low level resources by implementing the DAL_ADC_MspInit(): + (##) Enable the ADC interface clock using __DAL_RCM_ADC_CLK_ENABLE() + (##) ADC pins configuration + (+++) Enable the clock for the ADC GPIOs using the following function: + __DAL_RCM_GPIOx_CLK_ENABLE() + (+++) Configure these ADC pins in analog mode using DAL_GPIO_Init() + (##) In case of using interrupts (e.g. DAL_ADC_Start_IT()) + (+++) Configure the ADC interrupt priority using DAL_NVIC_SetPriority() + (+++) Enable the ADC IRQ handler using DAL_NVIC_EnableIRQ() + (+++) In ADC IRQ handler, call DAL_ADC_IRQHandler() + (##) In case of using DMA to control data transfer (e.g. DAL_ADC_Start_DMA()) + (+++) Enable the DMAx interface clock using __DAL_RCM_DMAx_CLK_ENABLE() + (+++) Configure and enable two DMA streams stream for managing data + transfer from peripheral to memory (output stream) + (+++) Associate the initialized DMA handle to the ADC DMA handle + using __DAL_LINKDMA() + (+++) Configure the priority and enable the NVIC for the transfer complete + interrupt on the two DMA Streams. The output stream should have higher + priority than the input stream. + (#) Configure the ADC Prescaler, conversion resolution and data alignment + using the DAL_ADC_Init() function. + + (#) Configure the ADC Injected channels group features, use DAL_ADC_Init() + and DAL_ADC_ConfigChannel() functions. + + (#) Three operation modes are available within this driver: + + *** Polling mode IO operation *** + ================================= + [..] + (+) Start the ADC peripheral using DAL_ADCEx_InjectedStart() + (+) Wait for end of conversion using DAL_ADC_PollForConversion(), at this stage + user can specify the value of timeout according to his end application + (+) To read the ADC converted values, use the DAL_ADCEx_InjectedGetValue() function. + (+) Stop the ADC peripheral using DAL_ADCEx_InjectedStop() + + *** Interrupt mode IO operation *** + =================================== + [..] + (+) Start the ADC peripheral using DAL_ADCEx_InjectedStart_IT() + (+) Use DAL_ADC_IRQHandler() called under ADC_IRQHandler() Interrupt subroutine + (+) At ADC end of conversion DAL_ADCEx_InjectedConvCpltCallback() function is executed and user can + add his own code by customization of function pointer DAL_ADCEx_InjectedConvCpltCallback + (+) In case of ADC Error, DAL_ADCEx_InjectedErrorCallback() function is executed and user can + add his own code by customization of function pointer DAL_ADCEx_InjectedErrorCallback + (+) Stop the ADC peripheral using DAL_ADCEx_InjectedStop_IT() + + *** Multi mode ADCs Regular channels configuration *** + ====================================================== + [..] + (+) Select the Multi mode ADC regular channels features (dual or triple mode) + and configure the DMA mode using DAL_ADCEx_MultiModeConfigChannel() functions. + (+) Start the ADC peripheral using DAL_ADCEx_MultiModeStart_DMA(), at this stage the user specify the length + of data to be transferred at each end of conversion + (+) Read the ADCs converted values using the DAL_ADCEx_MultiModeGetValue() function. + + + @endverbatim + */ + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @defgroup ADCEx ADCEx + * @brief ADC Extended driver modules + * @{ + */ + +#ifdef DAL_ADC_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/** @addtogroup ADCEx_Private_Functions + * @{ + */ +/* Private function prototypes -----------------------------------------------*/ +#if defined(ADC_MULTIMODE_SUPPORT) +static void ADC_MultiModeDMAConvCplt(DMA_HandleTypeDef *hdma); +static void ADC_MultiModeDMAError(DMA_HandleTypeDef *hdma); +static void ADC_MultiModeDMAHalfConvCplt(DMA_HandleTypeDef *hdma); +#endif /* ADC_MULTIMODE_SUPPORT */ +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +/** @defgroup ADCEx_Exported_Functions ADC Exported Functions + * @{ + */ + +/** @defgroup ADCEx_Exported_Functions_Group1 Extended features functions + * @brief Extended features functions + * +@verbatim + =============================================================================== + ##### Extended features functions ##### + =============================================================================== + [..] This section provides functions allowing to: + (+) Start conversion of injected channel. + (+) Stop conversion of injected channel. + (+) Start multimode and enable DMA transfer. + (+) Stop multimode and disable DMA transfer. + (+) Get result of injected channel conversion. + (+) Get result of multimode conversion. + (+) Configure injected channels. + (+) Configure multimode. + +@endverbatim + * @{ + */ + +/** + * @brief Enables the selected ADC software start conversion of the injected channels. + * @param hadc pointer to a ADC_HandleTypeDef structure that contains + * the configuration information for the specified ADC. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_ADCEx_InjectedStart(ADC_HandleTypeDef* hadc) +{ + __IO uint32_t counter = 0U; + uint32_t tmp1 = 0U, tmp2 = 0U; + ADC_Common_TypeDef *tmpADC_Common; + + /* Process locked */ + __DAL_LOCK(hadc); + + /* Enable the ADC peripheral */ + + /* Check if ADC peripheral is disabled in order to enable it and wait during + Tstab time the ADC's stabilization */ + if((hadc->Instance->CTRL2 & ADC_CTRL2_ADCEN) != ADC_CTRL2_ADCEN) + { + /* Enable the Peripheral */ + __DAL_ADC_ENABLE(hadc); + + /* Delay for ADC stabilization time */ + /* Compute number of CPU cycles to wait for */ + counter = (ADC_STAB_DELAY_US * (SystemCoreClock / 1000000U)); + while(counter != 0U) + { + counter--; + } + } + + /* Start conversion if ADC is effectively enabled */ + if(DAL_IS_BIT_SET(hadc->Instance->CTRL2, ADC_CTRL2_ADCEN)) + { + /* Set ADC state */ + /* - Clear state bitfield related to injected group conversion results */ + /* - Set state bitfield related to injected operation */ + ADC_STATE_CLR_SET(hadc->State, + DAL_ADC_STATE_READY | DAL_ADC_STATE_INJ_EOC, + DAL_ADC_STATE_INJ_BUSY); + + /* Check if a regular conversion is ongoing */ + /* Note: On this device, there is no ADC error code fields related to */ + /* conversions on group injected only. In case of conversion on */ + /* going on group regular, no error code is reset. */ + if (DAL_IS_BIT_CLR(hadc->State, DAL_ADC_STATE_REG_BUSY)) + { + /* Reset ADC all error code fields */ + ADC_CLEAR_ERRORCODE(hadc); + } + + /* Process unlocked */ + /* Unlock before starting ADC conversions: in case of potential */ + /* interruption, to let the process to ADC IRQ Handler. */ + __DAL_UNLOCK(hadc); + + /* Clear injected group conversion flag */ + /* (To ensure of no unknown state from potential previous ADC operations) */ + __DAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_JEOC); + + /* Pointer to the common control register to which is belonging hadc */ + /* (Depending on APM32F4 product, there may be up to 3 ADC and 1 common */ + /* control register) */ + tmpADC_Common = ADC_COMMON_REGISTER(hadc); + + /* Check if Multimode enabled */ + if(DAL_IS_BIT_CLR(tmpADC_Common->CCTRL, ADC_CCTRL_ADCMSEL)) + { + tmp1 = DAL_IS_BIT_CLR(hadc->Instance->CTRL2, ADC_CTRL2_INJEXTTRGEN); + tmp2 = DAL_IS_BIT_CLR(hadc->Instance->CTRL1, ADC_CTRL1_INJGACEN); + if(tmp1 && tmp2) + { + /* Enable the selected ADC software conversion for injected group */ + hadc->Instance->CTRL2 |= ADC_CTRL2_INJSWSC; + } + } + else + { + tmp1 = DAL_IS_BIT_CLR(hadc->Instance->CTRL2, ADC_CTRL2_INJEXTTRGEN); + tmp2 = DAL_IS_BIT_CLR(hadc->Instance->CTRL1, ADC_CTRL1_INJGACEN); + if(((hadc->Instance == ADC1) || (hadc->Instance == ADC2)) && tmp1 && tmp2) + { + /* Enable the selected ADC software conversion for injected group */ + hadc->Instance->CTRL2 |= ADC_CTRL2_INJSWSC; + } + } + } + else + { + /* Update ADC state machine to error */ + SET_BIT(hadc->State, DAL_ADC_STATE_ERROR_INTERNAL); + + /* Set ADC error code to ADC IP internal error */ + SET_BIT(hadc->ErrorCode, DAL_ADC_ERROR_INTERNAL); + } + + /* Return function status */ + return DAL_OK; +} + +/** + * @brief Enables the interrupt and starts ADC conversion of injected channels. + * @param hadc pointer to a ADC_HandleTypeDef structure that contains + * the configuration information for the specified ADC. + * + * @retval DAL status. + */ +DAL_StatusTypeDef DAL_ADCEx_InjectedStart_IT(ADC_HandleTypeDef* hadc) +{ + __IO uint32_t counter = 0U; + uint32_t tmp1 = 0U, tmp2 = 0U; + ADC_Common_TypeDef *tmpADC_Common; + + /* Process locked */ + __DAL_LOCK(hadc); + + /* Enable the ADC peripheral */ + + /* Check if ADC peripheral is disabled in order to enable it and wait during + Tstab time the ADC's stabilization */ + if((hadc->Instance->CTRL2 & ADC_CTRL2_ADCEN) != ADC_CTRL2_ADCEN) + { + /* Enable the Peripheral */ + __DAL_ADC_ENABLE(hadc); + + /* Delay for ADC stabilization time */ + /* Compute number of CPU cycles to wait for */ + counter = (ADC_STAB_DELAY_US * (SystemCoreClock / 1000000U)); + while(counter != 0U) + { + counter--; + } + } + + /* Start conversion if ADC is effectively enabled */ + if(DAL_IS_BIT_SET(hadc->Instance->CTRL2, ADC_CTRL2_ADCEN)) + { + /* Set ADC state */ + /* - Clear state bitfield related to injected group conversion results */ + /* - Set state bitfield related to injected operation */ + ADC_STATE_CLR_SET(hadc->State, + DAL_ADC_STATE_READY | DAL_ADC_STATE_INJ_EOC, + DAL_ADC_STATE_INJ_BUSY); + + /* Check if a regular conversion is ongoing */ + /* Note: On this device, there is no ADC error code fields related to */ + /* conversions on group injected only. In case of conversion on */ + /* going on group regular, no error code is reset. */ + if (DAL_IS_BIT_CLR(hadc->State, DAL_ADC_STATE_REG_BUSY)) + { + /* Reset ADC all error code fields */ + ADC_CLEAR_ERRORCODE(hadc); + } + + /* Process unlocked */ + /* Unlock before starting ADC conversions: in case of potential */ + /* interruption, to let the process to ADC IRQ Handler. */ + __DAL_UNLOCK(hadc); + + /* Clear injected group conversion flag */ + /* (To ensure of no unknown state from potential previous ADC operations) */ + __DAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_JEOC); + + /* Enable end of conversion interrupt for injected channels */ + __DAL_ADC_ENABLE_IT(hadc, ADC_IT_JEOC); + + /* Pointer to the common control register to which is belonging hadc */ + /* (Depending on APM32F4 product, there may be up to 3 ADC and 1 common */ + /* control register) */ + tmpADC_Common = ADC_COMMON_REGISTER(hadc); + + /* Check if Multimode enabled */ + if(DAL_IS_BIT_CLR(tmpADC_Common->CCTRL, ADC_CCTRL_ADCMSEL)) + { + tmp1 = DAL_IS_BIT_CLR(hadc->Instance->CTRL2, ADC_CTRL2_INJEXTTRGEN); + tmp2 = DAL_IS_BIT_CLR(hadc->Instance->CTRL1, ADC_CTRL1_INJGACEN); + if(tmp1 && tmp2) + { + /* Enable the selected ADC software conversion for injected group */ + hadc->Instance->CTRL2 |= ADC_CTRL2_INJSWSC; + } + } + else + { + tmp1 = DAL_IS_BIT_CLR(hadc->Instance->CTRL2, ADC_CTRL2_INJEXTTRGEN); + tmp2 = DAL_IS_BIT_CLR(hadc->Instance->CTRL1, ADC_CTRL1_INJGACEN); + if(((hadc->Instance == ADC1) || (hadc->Instance == ADC2)) && tmp1 && tmp2) + { + /* Enable the selected ADC software conversion for injected group */ + hadc->Instance->CTRL2 |= ADC_CTRL2_INJSWSC; + } + } + } + else + { + /* Update ADC state machine to error */ + SET_BIT(hadc->State, DAL_ADC_STATE_ERROR_INTERNAL); + + /* Set ADC error code to ADC IP internal error */ + SET_BIT(hadc->ErrorCode, DAL_ADC_ERROR_INTERNAL); + } + + /* Return function status */ + return DAL_OK; +} + +/** + * @brief Stop conversion of injected channels. Disable ADC peripheral if + * no regular conversion is on going. + * @note If ADC must be disabled and if conversion is on going on + * regular group, function DAL_ADC_Stop must be used to stop both + * injected and regular groups, and disable the ADC. + * @note If injected group mode auto-injection is enabled, + * function DAL_ADC_Stop must be used. + * @note In case of auto-injection mode, DAL_ADC_Stop must be used. + * @param hadc ADC handle + * @retval None + */ +DAL_StatusTypeDef DAL_ADCEx_InjectedStop(ADC_HandleTypeDef* hadc) +{ + DAL_StatusTypeDef tmp_dal_status = DAL_OK; + + /* Check the parameters */ + ASSERT_PARAM(IS_ADC_ALL_INSTANCE(hadc->Instance)); + + /* Process locked */ + __DAL_LOCK(hadc); + + /* Stop potential conversion and disable ADC peripheral */ + /* Conditioned to: */ + /* - No conversion on the other group (regular group) is intended to */ + /* continue (injected and regular groups stop conversion and ADC disable */ + /* are common) */ + /* - In case of auto-injection mode, DAL_ADC_Stop must be used. */ + if(((hadc->State & DAL_ADC_STATE_REG_BUSY) == RESET) && + DAL_IS_BIT_CLR(hadc->Instance->CTRL1, ADC_CTRL1_INJGACEN) ) + { + /* Stop potential conversion on going, on regular and injected groups */ + /* Disable ADC peripheral */ + __DAL_ADC_DISABLE(hadc); + + /* Check if ADC is effectively disabled */ + if(DAL_IS_BIT_CLR(hadc->Instance->CTRL2, ADC_CTRL2_ADCEN)) + { + /* Set ADC state */ + ADC_STATE_CLR_SET(hadc->State, + DAL_ADC_STATE_REG_BUSY | DAL_ADC_STATE_INJ_BUSY, + DAL_ADC_STATE_READY); + } + } + else + { + /* Update ADC state machine to error */ + SET_BIT(hadc->State, DAL_ADC_STATE_ERROR_CONFIG); + + tmp_dal_status = DAL_ERROR; + } + + /* Process unlocked */ + __DAL_UNLOCK(hadc); + + /* Return function status */ + return tmp_dal_status; +} + +/** + * @brief Poll for injected conversion complete + * @param hadc pointer to a ADC_HandleTypeDef structure that contains + * the configuration information for the specified ADC. + * @param Timeout Timeout value in millisecond. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_ADCEx_InjectedPollForConversion(ADC_HandleTypeDef* hadc, uint32_t Timeout) +{ + uint32_t tickstart = 0U; + + /* Get tick */ + tickstart = DAL_GetTick(); + + /* Check End of conversion flag */ + while(!(__DAL_ADC_GET_FLAG(hadc, ADC_FLAG_JEOC))) + { + /* Check for the Timeout */ + if(Timeout != DAL_MAX_DELAY) + { + if((Timeout == 0U)||((DAL_GetTick() - tickstart ) > Timeout)) + { + /* New check to avoid false timeout detection in case of preemption */ + if(!(__DAL_ADC_GET_FLAG(hadc, ADC_FLAG_JEOC))) + { + hadc->State= DAL_ADC_STATE_TIMEOUT; + /* Process unlocked */ + __DAL_UNLOCK(hadc); + return DAL_TIMEOUT; + } + } + } + } + + /* Clear injected group conversion flag */ + __DAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_JSTRT | ADC_FLAG_JEOC); + + /* Update ADC state machine */ + SET_BIT(hadc->State, DAL_ADC_STATE_INJ_EOC); + + /* Determine whether any further conversion upcoming on group injected */ + /* by external trigger, continuous mode or scan sequence on going. */ + /* Note: On APM32F4, there is no independent flag of end of sequence. */ + /* The test of scan sequence on going is done either with scan */ + /* sequence disabled or with end of conversion flag set to */ + /* of end of sequence. */ + if(ADC_IS_SOFTWARE_START_INJECTED(hadc) && + (DAL_IS_BIT_CLR(hadc->Instance->INJSEQ, ADC_INJSEQ_INJSEQLEN) || + DAL_IS_BIT_CLR(hadc->Instance->CTRL2, ADC_CTRL2_EOCSEL) ) && + (DAL_IS_BIT_CLR(hadc->Instance->CTRL1, ADC_CTRL1_INJGACEN) && + (ADC_IS_SOFTWARE_START_REGULAR(hadc) && + (hadc->Init.ContinuousConvMode == DISABLE) ) ) ) + { + /* Set ADC state */ + CLEAR_BIT(hadc->State, DAL_ADC_STATE_INJ_BUSY); + + if (DAL_IS_BIT_CLR(hadc->State, DAL_ADC_STATE_REG_BUSY)) + { + SET_BIT(hadc->State, DAL_ADC_STATE_READY); + } + } + + /* Return ADC state */ + return DAL_OK; +} + +/** + * @brief Stop conversion of injected channels, disable interruption of + * end-of-conversion. Disable ADC peripheral if no regular conversion + * is on going. + * @note If ADC must be disabled and if conversion is on going on + * regular group, function DAL_ADC_Stop must be used to stop both + * injected and regular groups, and disable the ADC. + * @note If injected group mode auto-injection is enabled, + * function DAL_ADC_Stop must be used. + * @param hadc ADC handle + * @retval None + */ +DAL_StatusTypeDef DAL_ADCEx_InjectedStop_IT(ADC_HandleTypeDef* hadc) +{ + DAL_StatusTypeDef tmp_dal_status = DAL_OK; + + /* Check the parameters */ + ASSERT_PARAM(IS_ADC_ALL_INSTANCE(hadc->Instance)); + + /* Process locked */ + __DAL_LOCK(hadc); + + /* Stop potential conversion and disable ADC peripheral */ + /* Conditioned to: */ + /* - No conversion on the other group (regular group) is intended to */ + /* continue (injected and regular groups stop conversion and ADC disable */ + /* are common) */ + /* - In case of auto-injection mode, DAL_ADC_Stop must be used. */ + if(((hadc->State & DAL_ADC_STATE_REG_BUSY) == RESET) && + DAL_IS_BIT_CLR(hadc->Instance->CTRL1, ADC_CTRL1_INJGACEN) ) + { + /* Stop potential conversion on going, on regular and injected groups */ + /* Disable ADC peripheral */ + __DAL_ADC_DISABLE(hadc); + + /* Check if ADC is effectively disabled */ + if(DAL_IS_BIT_CLR(hadc->Instance->CTRL2, ADC_CTRL2_ADCEN)) + { + /* Disable ADC end of conversion interrupt for injected channels */ + __DAL_ADC_DISABLE_IT(hadc, ADC_IT_JEOC); + + /* Set ADC state */ + ADC_STATE_CLR_SET(hadc->State, + DAL_ADC_STATE_REG_BUSY | DAL_ADC_STATE_INJ_BUSY, + DAL_ADC_STATE_READY); + } + } + else + { + /* Update ADC state machine to error */ + SET_BIT(hadc->State, DAL_ADC_STATE_ERROR_CONFIG); + + tmp_dal_status = DAL_ERROR; + } + + /* Process unlocked */ + __DAL_UNLOCK(hadc); + + /* Return function status */ + return tmp_dal_status; +} + +/** + * @brief Gets the converted value from data register of injected channel. + * @param hadc pointer to a ADC_HandleTypeDef structure that contains + * the configuration information for the specified ADC. + * @param InjectedRank the ADC injected rank. + * This parameter can be one of the following values: + * @arg ADC_INJECTED_RANK_1: Injected Channel1 selected + * @arg ADC_INJECTED_RANK_2: Injected Channel2 selected + * @arg ADC_INJECTED_RANK_3: Injected Channel3 selected + * @arg ADC_INJECTED_RANK_4: Injected Channel4 selected + * @retval None + */ +uint32_t DAL_ADCEx_InjectedGetValue(ADC_HandleTypeDef* hadc, uint32_t InjectedRank) +{ + __IO uint32_t tmp = 0U; + + /* Check the parameters */ + ASSERT_PARAM(IS_ADC_INJECTED_RANK(InjectedRank)); + + /* Clear injected group conversion flag to have similar behaviour as */ + /* regular group: reading data register also clears end of conversion flag. */ + __DAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_JEOC); + + /* Return the selected ADC converted value */ + switch(InjectedRank) + { + case ADC_INJECTED_RANK_4: + { + tmp = hadc->Instance->INJDATA4; + } + break; + case ADC_INJECTED_RANK_3: + { + tmp = hadc->Instance->INJDATA3; + } + break; + case ADC_INJECTED_RANK_2: + { + tmp = hadc->Instance->INJDATA2; + } + break; + case ADC_INJECTED_RANK_1: + { + tmp = hadc->Instance->INJDATA1; + } + break; + default: + break; + } + return tmp; +} + +#if defined(ADC_MULTIMODE_SUPPORT) +/** + * @brief Enables ADC DMA request after last transfer (Multi-ADC mode) and enables ADC peripheral + * + * @note Caution: This function must be used only with the ADC master. + * + * @param hadc pointer to a ADC_HandleTypeDef structure that contains + * the configuration information for the specified ADC. + * @param pData Pointer to buffer in which transferred from ADC peripheral to memory will be stored. + * @param Length The length of data to be transferred from ADC peripheral to memory. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_ADCEx_MultiModeStart_DMA(ADC_HandleTypeDef* hadc, uint32_t* pData, uint32_t Length) +{ + __IO uint32_t counter = 0U; + ADC_Common_TypeDef *tmpADC_Common; + + /* Check the parameters */ + ASSERT_PARAM(IS_FUNCTIONAL_STATE(hadc->Init.ContinuousConvMode)); + ASSERT_PARAM(IS_ADC_EXT_TRIG_EDGE(hadc->Init.ExternalTrigConvEdge)); + ASSERT_PARAM(IS_FUNCTIONAL_STATE(hadc->Init.DMAContinuousRequests)); + + /* Process locked */ + __DAL_LOCK(hadc); + + /* Check if ADC peripheral is disabled in order to enable it and wait during + Tstab time the ADC's stabilization */ + if((hadc->Instance->CTRL2 & ADC_CTRL2_ADCEN) != ADC_CTRL2_ADCEN) + { + /* Enable the Peripheral */ + __DAL_ADC_ENABLE(hadc); + + /* Delay for temperature sensor stabilization time */ + /* Compute number of CPU cycles to wait for */ + counter = (ADC_STAB_DELAY_US * (SystemCoreClock / 1000000U)); + while(counter != 0U) + { + counter--; + } + } + + /* Start conversion if ADC is effectively enabled */ + if(DAL_IS_BIT_SET(hadc->Instance->CTRL2, ADC_CTRL2_ADCEN)) + { + /* Set ADC state */ + /* - Clear state bitfield related to regular group conversion results */ + /* - Set state bitfield related to regular group operation */ + ADC_STATE_CLR_SET(hadc->State, + DAL_ADC_STATE_READY | DAL_ADC_STATE_REG_EOC | DAL_ADC_STATE_REG_OVR, + DAL_ADC_STATE_REG_BUSY); + + /* If conversions on group regular are also triggering group injected, */ + /* update ADC state. */ + if (READ_BIT(hadc->Instance->CTRL1, ADC_CTRL1_INJGACEN) != RESET) + { + ADC_STATE_CLR_SET(hadc->State, DAL_ADC_STATE_INJ_EOC, DAL_ADC_STATE_INJ_BUSY); + } + + /* State machine update: Check if an injected conversion is ongoing */ + if (DAL_IS_BIT_SET(hadc->State, DAL_ADC_STATE_INJ_BUSY)) + { + /* Reset ADC error code fields related to conversions on group regular */ + CLEAR_BIT(hadc->ErrorCode, (DAL_ADC_ERROR_OVR | DAL_ADC_ERROR_DMA)); + } + else + { + /* Reset ADC all error code fields */ + ADC_CLEAR_ERRORCODE(hadc); + } + + /* Process unlocked */ + /* Unlock before starting ADC conversions: in case of potential */ + /* interruption, to let the process to ADC IRQ Handler. */ + __DAL_UNLOCK(hadc); + + /* Set the DMA transfer complete callback */ + hadc->DMA_Handle->XferCpltCallback = ADC_MultiModeDMAConvCplt; + + /* Set the DMA half transfer complete callback */ + hadc->DMA_Handle->XferHalfCpltCallback = ADC_MultiModeDMAHalfConvCplt; + + /* Set the DMA error callback */ + hadc->DMA_Handle->XferErrorCallback = ADC_MultiModeDMAError ; + + /* Manage ADC and DMA start: ADC overrun interruption, DMA start, ADC */ + /* start (in case of SW start): */ + + /* Clear regular group conversion flag and overrun flag */ + /* (To ensure of no unknown state from potential previous ADC operations) */ + __DAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_EOC); + + /* Enable ADC overrun interrupt */ + __DAL_ADC_ENABLE_IT(hadc, ADC_IT_OVR); + + /* Pointer to the common control register to which is belonging hadc */ + /* (Depending on APM32F4 product, there may be up to 3 ADC and 1 common */ + /* control register) */ + tmpADC_Common = ADC_COMMON_REGISTER(hadc); + + if (hadc->Init.DMAContinuousRequests != DISABLE) + { + /* Enable the selected ADC DMA request after last transfer */ + tmpADC_Common->CCTRL |= ADC_CCTRL_DMAMODEDISSEL; + } + else + { + /* Disable the selected ADC EOC rising on each regular channel conversion */ + tmpADC_Common->CCTRL &= ~ADC_CCTRL_DMAMODEDISSEL; + } + + /* Enable the DMA Stream */ + DAL_DMA_Start_IT(hadc->DMA_Handle, (uint32_t)&tmpADC_Common->CDATA, (uint32_t)pData, Length); + + /* if no external trigger present enable software conversion of regular channels */ + if((hadc->Instance->CTRL2 & ADC_CTRL2_REGEXTTRGEN) == RESET) + { + /* Enable the selected ADC software conversion for regular group */ + hadc->Instance->CTRL2 |= (uint32_t)ADC_CTRL2_REGCHSC; + } + } + else + { + /* Update ADC state machine to error */ + SET_BIT(hadc->State, DAL_ADC_STATE_ERROR_INTERNAL); + + /* Set ADC error code to ADC IP internal error */ + SET_BIT(hadc->ErrorCode, DAL_ADC_ERROR_INTERNAL); + } + + /* Return function status */ + return DAL_OK; +} + +/** + * @brief Disables ADC DMA (multi-ADC mode) and disables ADC peripheral + * @param hadc pointer to a ADC_HandleTypeDef structure that contains + * the configuration information for the specified ADC. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_ADCEx_MultiModeStop_DMA(ADC_HandleTypeDef* hadc) +{ + DAL_StatusTypeDef tmp_dal_status = DAL_OK; + ADC_Common_TypeDef *tmpADC_Common; + + /* Check the parameters */ + ASSERT_PARAM(IS_ADC_ALL_INSTANCE(hadc->Instance)); + + /* Process locked */ + __DAL_LOCK(hadc); + + /* Stop potential conversion on going, on regular and injected groups */ + /* Disable ADC peripheral */ + __DAL_ADC_DISABLE(hadc); + + /* Pointer to the common control register to which is belonging hadc */ + /* (Depending on APM32F4 product, there may be up to 3 ADC and 1 common */ + /* control register) */ + tmpADC_Common = ADC_COMMON_REGISTER(hadc); + + /* Check if ADC is effectively disabled */ + if(DAL_IS_BIT_CLR(hadc->Instance->CTRL2, ADC_CTRL2_ADCEN)) + { + /* Disable the selected ADC DMA mode for multimode */ + tmpADC_Common->CCTRL &= ~ADC_CCTRL_DMAMODEDISSEL; + + /* Disable the DMA channel (in case of DMA in circular mode or stop while */ + /* DMA transfer is on going) */ + tmp_dal_status = DAL_DMA_Abort(hadc->DMA_Handle); + + /* Disable ADC overrun interrupt */ + __DAL_ADC_DISABLE_IT(hadc, ADC_IT_OVR); + + /* Set ADC state */ + ADC_STATE_CLR_SET(hadc->State, + DAL_ADC_STATE_REG_BUSY | DAL_ADC_STATE_INJ_BUSY, + DAL_ADC_STATE_READY); + } + + /* Process unlocked */ + __DAL_UNLOCK(hadc); + + /* Return function status */ + return tmp_dal_status; +} + +/** + * @brief Returns the last ADC1, ADC2 and ADC3 regular conversions results + * data in the selected multi mode. + * @param hadc pointer to a ADC_HandleTypeDef structure that contains + * the configuration information for the specified ADC. + * @retval The converted data value. + */ +uint32_t DAL_ADCEx_MultiModeGetValue(ADC_HandleTypeDef* hadc) +{ + ADC_Common_TypeDef *tmpADC_Common; + + UNUSED(hadc); + + /* Pointer to the common control register to which is belonging hadc */ + /* (Depending on APM32F4 product, there may be up to 3 ADC and 1 common */ + /* control register) */ + tmpADC_Common = ADC_COMMON_REGISTER(hadc); + + /* Return the multi mode conversion value */ + return tmpADC_Common->CDATA; +} +#endif /* ADC_MULTIMODE_SUPPORT */ + +/** + * @brief Injected conversion complete callback in non blocking mode + * @param hadc pointer to a ADC_HandleTypeDef structure that contains + * the configuration information for the specified ADC. + * @retval None + */ +__weak void DAL_ADCEx_InjectedConvCpltCallback(ADC_HandleTypeDef* hadc) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hadc); + /* NOTE : This function Should not be modified, when the callback is needed, + the DAL_ADC_InjectedConvCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Configures for the selected ADC injected channel its corresponding + * rank in the sequencer and its sample time. + * @param hadc pointer to a ADC_HandleTypeDef structure that contains + * the configuration information for the specified ADC. + * @param sConfigInjected ADC configuration structure for injected channel. + * @retval None + */ +DAL_StatusTypeDef DAL_ADCEx_InjectedConfigChannel(ADC_HandleTypeDef* hadc, ADC_InjectionConfTypeDef* sConfigInjected) +{ + +#if (USE_FULL_ASSERT == 1U) + uint32_t tmp = 0U; + +#endif /* USE_FULL_ASSERT */ + + ADC_Common_TypeDef *tmpADC_Common; + + /* Check the parameters */ + ASSERT_PARAM(IS_ADC_CHANNEL(sConfigInjected->InjectedChannel)); + ASSERT_PARAM(IS_ADC_INJECTED_RANK(sConfigInjected->InjectedRank)); + ASSERT_PARAM(IS_ADC_SAMPLE_TIME(sConfigInjected->InjectedSamplingTime)); + ASSERT_PARAM(IS_ADC_EXT_INJEC_TRIG(sConfigInjected->ExternalTrigInjecConv)); + ASSERT_PARAM(IS_ADC_INJECTED_LENGTH(sConfigInjected->InjectedNbrOfConversion)); + ASSERT_PARAM(IS_FUNCTIONAL_STATE(sConfigInjected->AutoInjectedConv)); + ASSERT_PARAM(IS_FUNCTIONAL_STATE(sConfigInjected->InjectedDiscontinuousConvMode)); + +#if (USE_FULL_ASSERT == 1U) + tmp = ADC_GET_RESOLUTION(hadc); + ASSERT_PARAM(IS_ADC_RANGE(tmp, sConfigInjected->InjectedOffset)); +#endif /* USE_FULL_ASSERT */ + + if(sConfigInjected->ExternalTrigInjecConv != ADC_INJECTED_SOFTWARE_START) + { + ASSERT_PARAM(IS_ADC_EXT_INJEC_TRIG_EDGE(sConfigInjected->ExternalTrigInjecConvEdge)); + } + + /* Process locked */ + __DAL_LOCK(hadc); + + /* if ADC_Channel_10 ... ADC_Channel_18 is selected */ + if (sConfigInjected->InjectedChannel > ADC_CHANNEL_9) + { + /* Clear the old sample time */ + hadc->Instance->SMPTIM1 &= ~ADC_SMPTIM1(ADC_SMPTIM1_SMPCYCCFG10, sConfigInjected->InjectedChannel); + + /* Set the new sample time */ + hadc->Instance->SMPTIM1 |= ADC_SMPTIM1(sConfigInjected->InjectedSamplingTime, sConfigInjected->InjectedChannel); + } + else /* ADC_Channel include in ADC_Channel_[0..9] */ + { + /* Clear the old sample time */ + hadc->Instance->SMPTIM2 &= ~ADC_SMPTIM2(ADC_SMPTIM2_SMPCYCCFG0, sConfigInjected->InjectedChannel); + + /* Set the new sample time */ + hadc->Instance->SMPTIM2 |= ADC_SMPTIM2(sConfigInjected->InjectedSamplingTime, sConfigInjected->InjectedChannel); + } + + /*---------------------------- ADCx JSQR Configuration -----------------*/ + hadc->Instance->INJSEQ &= ~(ADC_INJSEQ_INJSEQLEN); + hadc->Instance->INJSEQ |= ADC_REGSEQ1(sConfigInjected->InjectedNbrOfConversion); + + /* Rank configuration */ + + /* Clear the old SQx bits for the selected rank */ + hadc->Instance->INJSEQ &= ~ADC_INJSEQ(ADC_INJSEQ_INJSEQC1, sConfigInjected->InjectedRank,sConfigInjected->InjectedNbrOfConversion); + + /* Set the SQx bits for the selected rank */ + hadc->Instance->INJSEQ |= ADC_INJSEQ(sConfigInjected->InjectedChannel, sConfigInjected->InjectedRank,sConfigInjected->InjectedNbrOfConversion); + + /* Enable external trigger if trigger selection is different of software */ + /* start. */ + /* Note: This configuration keeps the hardware feature of parameter */ + /* ExternalTrigConvEdge "trigger edge none" equivalent to */ + /* software start. */ + if(sConfigInjected->ExternalTrigInjecConv != ADC_INJECTED_SOFTWARE_START) + { + /* Select external trigger to start conversion */ + hadc->Instance->CTRL2 &= ~(ADC_CTRL2_INJGEXTTRGSEL); + hadc->Instance->CTRL2 |= sConfigInjected->ExternalTrigInjecConv; + + /* Select external trigger polarity */ + hadc->Instance->CTRL2 &= ~(ADC_CTRL2_INJEXTTRGEN); + hadc->Instance->CTRL2 |= sConfigInjected->ExternalTrigInjecConvEdge; + } + else + { + /* Reset the external trigger */ + hadc->Instance->CTRL2 &= ~(ADC_CTRL2_INJGEXTTRGSEL); + hadc->Instance->CTRL2 &= ~(ADC_CTRL2_INJEXTTRGEN); + } + + if (sConfigInjected->AutoInjectedConv != DISABLE) + { + /* Enable the selected ADC automatic injected group conversion */ + hadc->Instance->CTRL1 |= ADC_CTRL1_INJGACEN; + } + else + { + /* Disable the selected ADC automatic injected group conversion */ + hadc->Instance->CTRL1 &= ~(ADC_CTRL1_INJGACEN); + } + + if (sConfigInjected->InjectedDiscontinuousConvMode != DISABLE) + { + /* Enable the selected ADC injected discontinuous mode */ + hadc->Instance->CTRL1 |= ADC_CTRL1_INJDISCEN; + } + else + { + /* Disable the selected ADC injected discontinuous mode */ + hadc->Instance->CTRL1 &= ~(ADC_CTRL1_INJDISCEN); + } + + switch(sConfigInjected->InjectedRank) + { + case 1U: + /* Set injected channel 1 offset */ + hadc->Instance->INJDOF1 &= ~(ADC_INJDOF1_INJDOF1); + hadc->Instance->INJDOF1 |= sConfigInjected->InjectedOffset; + break; + case 2U: + /* Set injected channel 2 offset */ + hadc->Instance->INJDOF2 &= ~(ADC_INJDOF2_INJDOF2); + hadc->Instance->INJDOF2 |= sConfigInjected->InjectedOffset; + break; + case 3U: + /* Set injected channel 3 offset */ + hadc->Instance->INJDOF3 &= ~(ADC_INJDOF3_INJDOF3); + hadc->Instance->INJDOF3 |= sConfigInjected->InjectedOffset; + break; + default: + /* Set injected channel 4 offset */ + hadc->Instance->INJDOF4 &= ~(ADC_INJDOF4_INJDOF4); + hadc->Instance->INJDOF4 |= sConfigInjected->InjectedOffset; + break; + } + + /* Pointer to the common control register to which is belonging hadc */ + /* (Depending on APM32F4 product, there may be up to 3 ADC and 1 common */ + /* control register) */ + tmpADC_Common = ADC_COMMON_REGISTER(hadc); + + /* if ADC1 Channel_18 is selected enable VBAT Channel */ + if ((hadc->Instance == ADC1) && (sConfigInjected->InjectedChannel == ADC_CHANNEL_VBAT)) + { + /* Enable the VBAT channel*/ + tmpADC_Common->CCTRL |= ADC_CCTRL_VBATEN; + } + + /* if ADC1 Channel_16 or Channel_17 is selected enable TSVREFEN Channel(Temperature sensor and VREFINT) */ + if ((hadc->Instance == ADC1) && ((sConfigInjected->InjectedChannel == ADC_CHANNEL_TEMPSENSOR) || (sConfigInjected->InjectedChannel == ADC_CHANNEL_VREFINT))) + { + /* Enable the TSVREFEN channel*/ + tmpADC_Common->CCTRL |= ADC_CCTRL_TSVREFEN; + } + + /* Process unlocked */ + __DAL_UNLOCK(hadc); + + /* Return function status */ + return DAL_OK; +} + +#if defined(ADC_MULTIMODE_SUPPORT) +/** + * @brief Configures the ADC multi-mode + * @param hadc pointer to a ADC_HandleTypeDef structure that contains + * the configuration information for the specified ADC. + * @param multimode pointer to an ADC_MultiModeTypeDef structure that contains + * the configuration information for multimode. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_ADCEx_MultiModeConfigChannel(ADC_HandleTypeDef* hadc, ADC_MultiModeTypeDef* multimode) +{ + + ADC_Common_TypeDef *tmpADC_Common; + + /* Check the parameters */ + ASSERT_PARAM(IS_ADC_MODE(multimode->Mode)); + ASSERT_PARAM(IS_ADC_DMA_ACCESS_MODE(multimode->DMAAccessMode)); + ASSERT_PARAM(IS_ADC_SAMPLING_DELAY(multimode->TwoSamplingDelay)); + + /* Process locked */ + __DAL_LOCK(hadc); + + /* Pointer to the common control register to which is belonging hadc */ + /* (Depending on APM32F4 product, there may be up to 3 ADC and 1 common */ + /* control register) */ + tmpADC_Common = ADC_COMMON_REGISTER(hadc); + + /* Set ADC mode */ + tmpADC_Common->CCTRL &= ~(ADC_CCTRL_ADCMSEL); + tmpADC_Common->CCTRL |= multimode->Mode; + + /* Set the ADC DMA access mode */ + tmpADC_Common->CCTRL &= ~(ADC_CCTRL_DMAMODE); + tmpADC_Common->CCTRL |= multimode->DMAAccessMode; + + /* Set delay between two sampling phases */ + tmpADC_Common->CCTRL &= ~(ADC_CCTRL_SMPDEL2); + tmpADC_Common->CCTRL |= multimode->TwoSamplingDelay; + + /* Process unlocked */ + __DAL_UNLOCK(hadc); + + /* Return function status */ + return DAL_OK; +} +#endif /* ADC_MULTIMODE_SUPPORT */ + +/** + * @} + */ + +#if defined(ADC_MULTIMODE_SUPPORT) +/** + * @brief DMA transfer complete callback. + * @param hdma pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +static void ADC_MultiModeDMAConvCplt(DMA_HandleTypeDef *hdma) +{ + /* Retrieve ADC handle corresponding to current DMA handle */ + ADC_HandleTypeDef* hadc = ( ADC_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + + /* Update state machine on conversion status if not in error state */ + if (DAL_IS_BIT_CLR(hadc->State, DAL_ADC_STATE_ERROR_INTERNAL | DAL_ADC_STATE_ERROR_DMA)) + { + /* Update ADC state machine */ + SET_BIT(hadc->State, DAL_ADC_STATE_REG_EOC); + + /* Determine whether any further conversion upcoming on group regular */ + /* by external trigger, continuous mode or scan sequence on going. */ + /* Note: On APM32F4, there is no independent flag of end of sequence. */ + /* The test of scan sequence on going is done either with scan */ + /* sequence disabled or with end of conversion flag set to */ + /* of end of sequence. */ + if(ADC_IS_SOFTWARE_START_REGULAR(hadc) && + (hadc->Init.ContinuousConvMode == DISABLE) && + (DAL_IS_BIT_CLR(hadc->Instance->REGSEQ1, ADC_REGSEQ1_REGSEQLEN) || + DAL_IS_BIT_CLR(hadc->Instance->CTRL2, ADC_CTRL2_EOCSEL) ) ) + { + /* Disable ADC end of single conversion interrupt on group regular */ + /* Note: Overrun interrupt was enabled with EOC interrupt in */ + /* DAL_ADC_Start_IT(), but is not disabled here because can be used */ + /* by overrun IRQ process below. */ + __DAL_ADC_DISABLE_IT(hadc, ADC_IT_EOC); + + /* Set ADC state */ + CLEAR_BIT(hadc->State, DAL_ADC_STATE_REG_BUSY); + + if (DAL_IS_BIT_CLR(hadc->State, DAL_ADC_STATE_INJ_BUSY)) + { + SET_BIT(hadc->State, DAL_ADC_STATE_READY); + } + } + + /* Conversion complete callback */ + DAL_ADC_ConvCpltCallback(hadc); + } + else + { + /* Call DMA error callback */ + hadc->DMA_Handle->XferErrorCallback(hdma); + } +} + +/** + * @brief DMA half transfer complete callback. + * @param hdma pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +static void ADC_MultiModeDMAHalfConvCplt(DMA_HandleTypeDef *hdma) +{ + ADC_HandleTypeDef* hadc = ( ADC_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + /* Conversion complete callback */ + DAL_ADC_ConvHalfCpltCallback(hadc); +} + +/** + * @brief DMA error callback + * @param hdma pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +static void ADC_MultiModeDMAError(DMA_HandleTypeDef *hdma) +{ + ADC_HandleTypeDef* hadc = ( ADC_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + hadc->State= DAL_ADC_STATE_ERROR_DMA; + /* Set ADC error code to DMA error */ + hadc->ErrorCode |= DAL_ADC_ERROR_DMA; + DAL_ADC_ErrorCallback(hadc); +} +#endif /* ADC_MULTIMODE_SUPPORT */ +/** + * @} + */ + +#endif /* DAL_ADC_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_can.c b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_can.c new file mode 100644 index 0000000000..fb46d4cd3c --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_can.c @@ -0,0 +1,2487 @@ +/** + * + * @file apm32f4xx_dal_can.c + * @brief CAN DAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the Controller Area Network (CAN) peripheral: + * + Initialization and de-initialization functions + * + Configuration functions + * + Control functions + * + Interrupts management + * + Callbacks functions + * + Peripheral State and Error functions + * + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + * + @verbatim + ============================================================================== + ##### How to use this driver ##### + ============================================================================== + [..] + (#) Initialize the CAN low level resources by implementing the + DAL_CAN_MspInit(): + (++) Enable the CAN interface clock using __DAL_RCM_CANx_CLK_ENABLE() + (++) Configure CAN pins + (+++) Enable the clock for the CAN GPIOs + (+++) Configure CAN pins as alternate function open-drain + (++) In case of using interrupts (e.g. DAL_CAN_ActivateNotification()) + (+++) Configure the CAN interrupt priority using + DAL_NVIC_SetPriority() + (+++) Enable the CAN IRQ handler using DAL_NVIC_EnableIRQ() + (+++) In CAN IRQ handler, call DAL_CAN_IRQHandler() + + (#) Initialize the CAN peripheral using DAL_CAN_Init() function. This + function resorts to DAL_CAN_MspInit() for low-level initialization. + + (#) Configure the reception filters using the following configuration + functions: + (++) DAL_CAN_ConfigFilter() + + (#) Start the CAN module using DAL_CAN_Start() function. At this level + the node is active on the bus: it receive messages, and can send + messages. + + (#) To manage messages transmission, the following Tx control functions + can be used: + (++) DAL_CAN_AddTxMessage() to request transmission of a new + message. + (++) DAL_CAN_AbortTxRequest() to abort transmission of a pending + message. + (++) DAL_CAN_GetTxMailboxesFreeLevel() to get the number of free Tx + mailboxes. + (++) DAL_CAN_IsTxMessagePending() to check if a message is pending + in a Tx mailbox. + (++) DAL_CAN_GetTxTimestamp() to get the timestamp of Tx message + sent, if time triggered communication mode is enabled. + + (#) When a message is received into the CAN Rx FIFOs, it can be retrieved + using the DAL_CAN_GetRxMessage() function. The function + DAL_CAN_GetRxFifoFillLevel() allows to know how many Rx message are + stored in the Rx Fifo. + + (#) Calling the DAL_CAN_Stop() function stops the CAN module. + + (#) The deinitialization is achieved with DAL_CAN_DeInit() function. + + + *** Polling mode operation *** + ============================== + [..] + (#) Reception: + (++) Monitor reception of message using DAL_CAN_GetRxFifoFillLevel() + until at least one message is received. + (++) Then get the message using DAL_CAN_GetRxMessage(). + + (#) Transmission: + (++) Monitor the Tx mailboxes availability until at least one Tx + mailbox is free, using DAL_CAN_GetTxMailboxesFreeLevel(). + (++) Then request transmission of a message using + DAL_CAN_AddTxMessage(). + + + *** Interrupt mode operation *** + ================================ + [..] + (#) Notifications are activated using DAL_CAN_ActivateNotification() + function. Then, the process can be controlled through the + available user callbacks: DAL_CAN_xxxCallback(), using same APIs + DAL_CAN_GetRxMessage() and DAL_CAN_AddTxMessage(). + + (#) Notifications can be deactivated using + DAL_CAN_DeactivateNotification() function. + + (#) Special care should be taken for CAN_IT_RX_FIFO0_MSG_PENDING and + CAN_IT_RX_FIFO1_MSG_PENDING notifications. These notifications trig + the callbacks DAL_CAN_RxFIFO0MsgPendingCallback() and + DAL_CAN_RxFIFO1MsgPendingCallback(). User has two possible options + here. + (++) Directly get the Rx message in the callback, using + DAL_CAN_GetRxMessage(). + (++) Or deactivate the notification in the callback without + getting the Rx message. The Rx message can then be got later + using DAL_CAN_GetRxMessage(). Once the Rx message have been + read, the notification can be activated again. + + + *** Sleep mode *** + ================== + [..] + (#) The CAN peripheral can be put in sleep mode (low power), using + DAL_CAN_RequestSleep(). The sleep mode will be entered as soon as the + current CAN activity (transmission or reception of a CAN frame) will + be completed. + + (#) A notification can be activated to be informed when the sleep mode + will be entered. + + (#) It can be checked if the sleep mode is entered using + DAL_CAN_IsSleepActive(). + Note that the CAN state (accessible from the API DAL_CAN_GetState()) + is DAL_CAN_STATE_SLEEP_PENDING as soon as the sleep mode request is + submitted (the sleep mode is not yet entered), and become + DAL_CAN_STATE_SLEEP_ACTIVE when the sleep mode is effective. + + (#) The wake-up from sleep mode can be triggered by two ways: + (++) Using DAL_CAN_WakeUp(). When returning from this function, + the sleep mode is exited (if return status is DAL_OK). + (++) When a start of Rx CAN frame is detected by the CAN peripheral, + if automatic wake up mode is enabled. + + *** Callback registration *** + ============================================= + + The compilation define USE_DAL_CAN_REGISTER_CALLBACKS when set to 1 + allows the user to configure dynamically the driver callbacks. + Use Function DAL_CAN_RegisterCallback() to register an interrupt callback. + + Function DAL_CAN_RegisterCallback() allows to register following callbacks: + (+) TxMailbox0CompleteCallback : Tx Mailbox 0 Complete Callback. + (+) TxMailbox1CompleteCallback : Tx Mailbox 1 Complete Callback. + (+) TxMailbox2CompleteCallback : Tx Mailbox 2 Complete Callback. + (+) TxMailbox0AbortCallback : Tx Mailbox 0 Abort Callback. + (+) TxMailbox1AbortCallback : Tx Mailbox 1 Abort Callback. + (+) TxMailbox2AbortCallback : Tx Mailbox 2 Abort Callback. + (+) RxFifo0MsgPendingCallback : Rx Fifo 0 Message Pending Callback. + (+) RxFifo0FullCallback : Rx Fifo 0 Full Callback. + (+) RxFifo1MsgPendingCallback : Rx Fifo 1 Message Pending Callback. + (+) RxFifo1FullCallback : Rx Fifo 1 Full Callback. + (+) SleepCallback : Sleep Callback. + (+) WakeUpFromRxMsgCallback : Wake Up From Rx Message Callback. + (+) ErrorCallback : Error Callback. + (+) MspInitCallback : CAN MspInit. + (+) MspDeInitCallback : CAN MspDeInit. + This function takes as parameters the DAL peripheral handle, the Callback ID + and a pointer to the user callback function. + + Use function DAL_CAN_UnRegisterCallback() to reset a callback to the default + weak function. + DAL_CAN_UnRegisterCallback takes as parameters the DAL peripheral handle, + and the Callback ID. + This function allows to reset following callbacks: + (+) TxMailbox0CompleteCallback : Tx Mailbox 0 Complete Callback. + (+) TxMailbox1CompleteCallback : Tx Mailbox 1 Complete Callback. + (+) TxMailbox2CompleteCallback : Tx Mailbox 2 Complete Callback. + (+) TxMailbox0AbortCallback : Tx Mailbox 0 Abort Callback. + (+) TxMailbox1AbortCallback : Tx Mailbox 1 Abort Callback. + (+) TxMailbox2AbortCallback : Tx Mailbox 2 Abort Callback. + (+) RxFifo0MsgPendingCallback : Rx Fifo 0 Message Pending Callback. + (+) RxFifo0FullCallback : Rx Fifo 0 Full Callback. + (+) RxFifo1MsgPendingCallback : Rx Fifo 1 Message Pending Callback. + (+) RxFifo1FullCallback : Rx Fifo 1 Full Callback. + (+) SleepCallback : Sleep Callback. + (+) WakeUpFromRxMsgCallback : Wake Up From Rx Message Callback. + (+) ErrorCallback : Error Callback. + (+) MspInitCallback : CAN MspInit. + (+) MspDeInitCallback : CAN MspDeInit. + + By default, after the DAL_CAN_Init() and when the state is DAL_CAN_STATE_RESET, + all callbacks are set to the corresponding weak functions: + example DAL_CAN_ErrorCallback(). + Exception done for MspInit and MspDeInit functions that are + reset to the legacy weak function in the DAL_CAN_Init()/ DAL_CAN_DeInit() only when + these callbacks are null (not registered beforehand). + if not, MspInit or MspDeInit are not null, the DAL_CAN_Init()/ DAL_CAN_DeInit() + keep and use the user MspInit/MspDeInit callbacks (registered beforehand) + + Callbacks can be registered/unregistered in DAL_CAN_STATE_READY state only. + Exception done MspInit/MspDeInit that can be registered/unregistered + in DAL_CAN_STATE_READY or DAL_CAN_STATE_RESET state, + thus registered (user) MspInit/DeInit callbacks can be used during the Init/DeInit. + In that case first register the MspInit/MspDeInit user callbacks + using DAL_CAN_RegisterCallback() before calling DAL_CAN_DeInit() + or DAL_CAN_Init() function. + + When The compilation define USE_DAL_CAN_REGISTER_CALLBACKS is set to 0 or + not defined, the callback registration feature is not available and all callbacks + are set to the corresponding weak functions. + + @endverbatim + * + */ + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +#if defined(CAN1) + +/** @defgroup CAN CAN + * @brief CAN driver modules + * @{ + */ + +#ifdef DAL_CAN_MODULE_ENABLED + +#ifdef DAL_CAN_LEGACY_MODULE_ENABLED + #error "The CAN driver cannot be used with its legacy, Please enable only one CAN module at once" +#endif + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/** @defgroup CAN_Private_Constants CAN Private Constants + * @{ + */ +#define CAN_TIMEOUT_VALUE 10U +/** + * @} + */ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Exported functions --------------------------------------------------------*/ + +/** @defgroup CAN_Exported_Functions CAN Exported Functions + * @{ + */ + +/** @defgroup CAN_Exported_Functions_Group1 Initialization and de-initialization functions + * @brief Initialization and Configuration functions + * +@verbatim + ============================================================================== + ##### Initialization and de-initialization functions ##### + ============================================================================== + [..] This section provides functions allowing to: + (+) DAL_CAN_Init : Initialize and configure the CAN. + (+) DAL_CAN_DeInit : De-initialize the CAN. + (+) DAL_CAN_MspInit : Initialize the CAN MSP. + (+) DAL_CAN_MspDeInit : DeInitialize the CAN MSP. + +@endverbatim + * @{ + */ + +/** + * @brief Initializes the CAN peripheral according to the specified + * parameters in the CAN_InitStruct. + * @param hcan pointer to a CAN_HandleTypeDef structure that contains + * the configuration information for the specified CAN. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_CAN_Init(CAN_HandleTypeDef *hcan) +{ + uint32_t tickstart; + + /* Check CAN handle */ + if (hcan == NULL) + { + return DAL_ERROR; + } + + /* Check the parameters */ + ASSERT_PARAM(IS_CAN_ALL_INSTANCE(hcan->Instance)); + ASSERT_PARAM(IS_FUNCTIONAL_STATE(hcan->Init.TimeTriggeredMode)); + ASSERT_PARAM(IS_FUNCTIONAL_STATE(hcan->Init.AutoBusOff)); + ASSERT_PARAM(IS_FUNCTIONAL_STATE(hcan->Init.AutoWakeUp)); + ASSERT_PARAM(IS_FUNCTIONAL_STATE(hcan->Init.AutoRetransmission)); + ASSERT_PARAM(IS_FUNCTIONAL_STATE(hcan->Init.ReceiveFifoLocked)); + ASSERT_PARAM(IS_FUNCTIONAL_STATE(hcan->Init.TransmitFifoPriority)); + ASSERT_PARAM(IS_CAN_MODE(hcan->Init.Mode)); + ASSERT_PARAM(IS_CAN_SJW(hcan->Init.SyncJumpWidth)); + ASSERT_PARAM(IS_CAN_BS1(hcan->Init.TimeSeg1)); + ASSERT_PARAM(IS_CAN_BS2(hcan->Init.TimeSeg2)); + ASSERT_PARAM(IS_CAN_PRESCALER(hcan->Init.Prescaler)); + +#if USE_DAL_CAN_REGISTER_CALLBACKS == 1 + if (hcan->State == DAL_CAN_STATE_RESET) + { + /* Reset callbacks to legacy functions */ + hcan->RxFifo0MsgPendingCallback = DAL_CAN_RxFifo0MsgPendingCallback; /* Legacy weak RxFifo0MsgPendingCallback */ + hcan->RxFifo0FullCallback = DAL_CAN_RxFifo0FullCallback; /* Legacy weak RxFifo0FullCallback */ + hcan->RxFifo1MsgPendingCallback = DAL_CAN_RxFifo1MsgPendingCallback; /* Legacy weak RxFifo1MsgPendingCallback */ + hcan->RxFifo1FullCallback = DAL_CAN_RxFifo1FullCallback; /* Legacy weak RxFifo1FullCallback */ + hcan->TxMailbox0CompleteCallback = DAL_CAN_TxMailbox0CompleteCallback; /* Legacy weak TxMailbox0CompleteCallback */ + hcan->TxMailbox1CompleteCallback = DAL_CAN_TxMailbox1CompleteCallback; /* Legacy weak TxMailbox1CompleteCallback */ + hcan->TxMailbox2CompleteCallback = DAL_CAN_TxMailbox2CompleteCallback; /* Legacy weak TxMailbox2CompleteCallback */ + hcan->TxMailbox0AbortCallback = DAL_CAN_TxMailbox0AbortCallback; /* Legacy weak TxMailbox0AbortCallback */ + hcan->TxMailbox1AbortCallback = DAL_CAN_TxMailbox1AbortCallback; /* Legacy weak TxMailbox1AbortCallback */ + hcan->TxMailbox2AbortCallback = DAL_CAN_TxMailbox2AbortCallback; /* Legacy weak TxMailbox2AbortCallback */ + hcan->SleepCallback = DAL_CAN_SleepCallback; /* Legacy weak SleepCallback */ + hcan->WakeUpFromRxMsgCallback = DAL_CAN_WakeUpFromRxMsgCallback; /* Legacy weak WakeUpFromRxMsgCallback */ + hcan->ErrorCallback = DAL_CAN_ErrorCallback; /* Legacy weak ErrorCallback */ + + if (hcan->MspInitCallback == NULL) + { + hcan->MspInitCallback = DAL_CAN_MspInit; /* Legacy weak MspInit */ + } + + /* Init the low level hardware: CLOCK, NVIC */ + hcan->MspInitCallback(hcan); + } + +#else + if (hcan->State == DAL_CAN_STATE_RESET) + { + /* Init the low level hardware: CLOCK, NVIC */ + DAL_CAN_MspInit(hcan); + } +#endif /* (USE_DAL_CAN_REGISTER_CALLBACKS) */ + + /* Request initialisation */ + SET_BIT(hcan->Instance->MCTRL, CAN_MCTRL_INITREQ); + + /* Get tick */ + tickstart = DAL_GetTick(); + + /* Wait initialisation acknowledge */ + while ((hcan->Instance->MSTS & CAN_MSTS_INITFLG) == 0U) + { + if ((DAL_GetTick() - tickstart) > CAN_TIMEOUT_VALUE) + { + /* Update error code */ + hcan->ErrorCode |= DAL_CAN_ERROR_TIMEOUT; + + /* Change CAN state */ + hcan->State = DAL_CAN_STATE_ERROR; + + return DAL_ERROR; + } + } + + /* Exit from sleep mode */ + CLEAR_BIT(hcan->Instance->MCTRL, CAN_MCTRL_SLEEPREQ); + + /* Get tick */ + tickstart = DAL_GetTick(); + + /* Check Sleep mode leave acknowledge */ + while ((hcan->Instance->MSTS & CAN_MSTS_SLEEPFLG) != 0U) + { + if ((DAL_GetTick() - tickstart) > CAN_TIMEOUT_VALUE) + { + /* Update error code */ + hcan->ErrorCode |= DAL_CAN_ERROR_TIMEOUT; + + /* Change CAN state */ + hcan->State = DAL_CAN_STATE_ERROR; + + return DAL_ERROR; + } + } + + /* Set the time triggered communication mode */ + if (hcan->Init.TimeTriggeredMode == ENABLE) + { + SET_BIT(hcan->Instance->MCTRL, CAN_MCTRL_TTCM); + } + else + { + CLEAR_BIT(hcan->Instance->MCTRL, CAN_MCTRL_TTCM); + } + + /* Set the automatic bus-off management */ + if (hcan->Init.AutoBusOff == ENABLE) + { + SET_BIT(hcan->Instance->MCTRL, CAN_MCTRL_ALBOFFM); + } + else + { + CLEAR_BIT(hcan->Instance->MCTRL, CAN_MCTRL_ALBOFFM); + } + + /* Set the automatic wake-up mode */ + if (hcan->Init.AutoWakeUp == ENABLE) + { + SET_BIT(hcan->Instance->MCTRL, CAN_MCTRL_AWUPCFG); + } + else + { + CLEAR_BIT(hcan->Instance->MCTRL, CAN_MCTRL_AWUPCFG); + } + + /* Set the automatic retransmission */ + if (hcan->Init.AutoRetransmission == ENABLE) + { + CLEAR_BIT(hcan->Instance->MCTRL, CAN_MCTRL_ARTXMD); + } + else + { + SET_BIT(hcan->Instance->MCTRL, CAN_MCTRL_ARTXMD); + } + + /* Set the receive FIFO locked mode */ + if (hcan->Init.ReceiveFifoLocked == ENABLE) + { + SET_BIT(hcan->Instance->MCTRL, CAN_MCTRL_RXFLOCK); + } + else + { + CLEAR_BIT(hcan->Instance->MCTRL, CAN_MCTRL_RXFLOCK); + } + + /* Set the transmit FIFO priority */ + if (hcan->Init.TransmitFifoPriority == ENABLE) + { + SET_BIT(hcan->Instance->MCTRL, CAN_MCTRL_TXFPCFG); + } + else + { + CLEAR_BIT(hcan->Instance->MCTRL, CAN_MCTRL_TXFPCFG); + } + + /* Set the bit timing register */ + WRITE_REG(hcan->Instance->BITTIM, (uint32_t)(hcan->Init.Mode | + hcan->Init.SyncJumpWidth | + hcan->Init.TimeSeg1 | + hcan->Init.TimeSeg2 | + (hcan->Init.Prescaler - 1U))); + + /* Initialize the error code */ + hcan->ErrorCode = DAL_CAN_ERROR_NONE; + + /* Initialize the CAN state */ + hcan->State = DAL_CAN_STATE_READY; + + /* Return function status */ + return DAL_OK; +} + +/** + * @brief Deinitializes the CAN peripheral registers to their default + * reset values. + * @param hcan pointer to a CAN_HandleTypeDef structure that contains + * the configuration information for the specified CAN. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_CAN_DeInit(CAN_HandleTypeDef *hcan) +{ + /* Check CAN handle */ + if (hcan == NULL) + { + return DAL_ERROR; + } + + /* Check the parameters */ + ASSERT_PARAM(IS_CAN_ALL_INSTANCE(hcan->Instance)); + + /* Stop the CAN module */ + (void)DAL_CAN_Stop(hcan); + +#if USE_DAL_CAN_REGISTER_CALLBACKS == 1 + if (hcan->MspDeInitCallback == NULL) + { + hcan->MspDeInitCallback = DAL_CAN_MspDeInit; /* Legacy weak MspDeInit */ + } + + /* DeInit the low level hardware: CLOCK, NVIC */ + hcan->MspDeInitCallback(hcan); + +#else + /* DeInit the low level hardware: CLOCK, NVIC */ + DAL_CAN_MspDeInit(hcan); +#endif /* (USE_DAL_CAN_REGISTER_CALLBACKS) */ + + /* Reset the CAN peripheral */ + SET_BIT(hcan->Instance->MCTRL, CAN_MCTRL_SWRST); + + /* Reset the CAN ErrorCode */ + hcan->ErrorCode = DAL_CAN_ERROR_NONE; + + /* Change CAN state */ + hcan->State = DAL_CAN_STATE_RESET; + + /* Return function status */ + return DAL_OK; +} + +/** + * @brief Initializes the CAN MSP. + * @param hcan pointer to a CAN_HandleTypeDef structure that contains + * the configuration information for the specified CAN. + * @retval None + */ +__weak void DAL_CAN_MspInit(CAN_HandleTypeDef *hcan) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hcan); + + /* NOTE : This function Should not be modified, when the callback is needed, + the DAL_CAN_MspInit could be implemented in the user file + */ +} + +/** + * @brief DeInitializes the CAN MSP. + * @param hcan pointer to a CAN_HandleTypeDef structure that contains + * the configuration information for the specified CAN. + * @retval None + */ +__weak void DAL_CAN_MspDeInit(CAN_HandleTypeDef *hcan) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hcan); + + /* NOTE : This function Should not be modified, when the callback is needed, + the DAL_CAN_MspDeInit could be implemented in the user file + */ +} + +#if USE_DAL_CAN_REGISTER_CALLBACKS == 1 +/** + * @brief Register a CAN CallBack. + * To be used instead of the weak predefined callback + * @param hcan pointer to a CAN_HandleTypeDef structure that contains + * the configuration information for CAN module + * @param CallbackID ID of the callback to be registered + * This parameter can be one of the following values: + * @arg @ref DAL_CAN_TX_MAILBOX0_COMPLETE_CB_ID Tx Mailbox 0 Complete callback ID + * @arg @ref DAL_CAN_TX_MAILBOX1_COMPLETE_CB_ID Tx Mailbox 1 Complete callback ID + * @arg @ref DAL_CAN_TX_MAILBOX2_COMPLETE_CB_ID Tx Mailbox 2 Complete callback ID + * @arg @ref DAL_CAN_TX_MAILBOX0_ABORT_CB_ID Tx Mailbox 0 Abort callback ID + * @arg @ref DAL_CAN_TX_MAILBOX1_ABORT_CB_ID Tx Mailbox 1 Abort callback ID + * @arg @ref DAL_CAN_TX_MAILBOX2_ABORT_CB_ID Tx Mailbox 2 Abort callback ID + * @arg @ref DAL_CAN_RX_FIFO0_MSG_PENDING_CB_ID Rx Fifo 0 message pending callback ID + * @arg @ref DAL_CAN_RX_FIFO0_FULL_CB_ID Rx Fifo 0 full callback ID + * @arg @ref DAL_CAN_RX_FIFO1_MSG_PENDING_CB_ID Rx Fifo 1 message pending callback ID + * @arg @ref DAL_CAN_RX_FIFO1_FULL_CB_ID Rx Fifo 1 full callback ID + * @arg @ref DAL_CAN_SLEEP_CB_ID Sleep callback ID + * @arg @ref DAL_CAN_WAKEUP_FROM_RX_MSG_CB_ID Wake Up from Rx message callback ID + * @arg @ref DAL_CAN_ERROR_CB_ID Error callback ID + * @arg @ref DAL_CAN_MSPINIT_CB_ID MspInit callback ID + * @arg @ref DAL_CAN_MSPDEINIT_CB_ID MspDeInit callback ID + * @param pCallback pointer to the Callback function + * @retval DAL status + */ +DAL_StatusTypeDef DAL_CAN_RegisterCallback(CAN_HandleTypeDef *hcan, DAL_CAN_CallbackIDTypeDef CallbackID, void (* pCallback)(CAN_HandleTypeDef *_hcan)) +{ + DAL_StatusTypeDef status = DAL_OK; + + if (pCallback == NULL) + { + /* Update the error code */ + hcan->ErrorCode |= DAL_CAN_ERROR_INVALID_CALLBACK; + + return DAL_ERROR; + } + + if (hcan->State == DAL_CAN_STATE_READY) + { + switch (CallbackID) + { + case DAL_CAN_TX_MAILBOX0_COMPLETE_CB_ID : + hcan->TxMailbox0CompleteCallback = pCallback; + break; + + case DAL_CAN_TX_MAILBOX1_COMPLETE_CB_ID : + hcan->TxMailbox1CompleteCallback = pCallback; + break; + + case DAL_CAN_TX_MAILBOX2_COMPLETE_CB_ID : + hcan->TxMailbox2CompleteCallback = pCallback; + break; + + case DAL_CAN_TX_MAILBOX0_ABORT_CB_ID : + hcan->TxMailbox0AbortCallback = pCallback; + break; + + case DAL_CAN_TX_MAILBOX1_ABORT_CB_ID : + hcan->TxMailbox1AbortCallback = pCallback; + break; + + case DAL_CAN_TX_MAILBOX2_ABORT_CB_ID : + hcan->TxMailbox2AbortCallback = pCallback; + break; + + case DAL_CAN_RX_FIFO0_MSG_PENDING_CB_ID : + hcan->RxFifo0MsgPendingCallback = pCallback; + break; + + case DAL_CAN_RX_FIFO0_FULL_CB_ID : + hcan->RxFifo0FullCallback = pCallback; + break; + + case DAL_CAN_RX_FIFO1_MSG_PENDING_CB_ID : + hcan->RxFifo1MsgPendingCallback = pCallback; + break; + + case DAL_CAN_RX_FIFO1_FULL_CB_ID : + hcan->RxFifo1FullCallback = pCallback; + break; + + case DAL_CAN_SLEEP_CB_ID : + hcan->SleepCallback = pCallback; + break; + + case DAL_CAN_WAKEUP_FROM_RX_MSG_CB_ID : + hcan->WakeUpFromRxMsgCallback = pCallback; + break; + + case DAL_CAN_ERROR_CB_ID : + hcan->ErrorCallback = pCallback; + break; + + case DAL_CAN_MSPINIT_CB_ID : + hcan->MspInitCallback = pCallback; + break; + + case DAL_CAN_MSPDEINIT_CB_ID : + hcan->MspDeInitCallback = pCallback; + break; + + default : + /* Update the error code */ + hcan->ErrorCode |= DAL_CAN_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = DAL_ERROR; + break; + } + } + else if (hcan->State == DAL_CAN_STATE_RESET) + { + switch (CallbackID) + { + case DAL_CAN_MSPINIT_CB_ID : + hcan->MspInitCallback = pCallback; + break; + + case DAL_CAN_MSPDEINIT_CB_ID : + hcan->MspDeInitCallback = pCallback; + break; + + default : + /* Update the error code */ + hcan->ErrorCode |= DAL_CAN_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = DAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + hcan->ErrorCode |= DAL_CAN_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = DAL_ERROR; + } + + return status; +} + +/** + * @brief Unregister a CAN CallBack. + * CAN callback is redirected to the weak predefined callback + * @param hcan pointer to a CAN_HandleTypeDef structure that contains + * the configuration information for CAN module + * @param CallbackID ID of the callback to be unregistered + * This parameter can be one of the following values: + * @arg @ref DAL_CAN_TX_MAILBOX0_COMPLETE_CB_ID Tx Mailbox 0 Complete callback ID + * @arg @ref DAL_CAN_TX_MAILBOX1_COMPLETE_CB_ID Tx Mailbox 1 Complete callback ID + * @arg @ref DAL_CAN_TX_MAILBOX2_COMPLETE_CB_ID Tx Mailbox 2 Complete callback ID + * @arg @ref DAL_CAN_TX_MAILBOX0_ABORT_CB_ID Tx Mailbox 0 Abort callback ID + * @arg @ref DAL_CAN_TX_MAILBOX1_ABORT_CB_ID Tx Mailbox 1 Abort callback ID + * @arg @ref DAL_CAN_TX_MAILBOX2_ABORT_CB_ID Tx Mailbox 2 Abort callback ID + * @arg @ref DAL_CAN_RX_FIFO0_MSG_PENDING_CB_ID Rx Fifo 0 message pending callback ID + * @arg @ref DAL_CAN_RX_FIFO0_FULL_CB_ID Rx Fifo 0 full callback ID + * @arg @ref DAL_CAN_RX_FIFO1_MSG_PENDING_CB_ID Rx Fifo 1 message pending callback ID + * @arg @ref DAL_CAN_RX_FIFO1_FULL_CB_ID Rx Fifo 1 full callback ID + * @arg @ref DAL_CAN_SLEEP_CB_ID Sleep callback ID + * @arg @ref DAL_CAN_WAKEUP_FROM_RX_MSG_CB_ID Wake Up from Rx message callback ID + * @arg @ref DAL_CAN_ERROR_CB_ID Error callback ID + * @arg @ref DAL_CAN_MSPINIT_CB_ID MspInit callback ID + * @arg @ref DAL_CAN_MSPDEINIT_CB_ID MspDeInit callback ID + * @retval DAL status + */ +DAL_StatusTypeDef DAL_CAN_UnRegisterCallback(CAN_HandleTypeDef *hcan, DAL_CAN_CallbackIDTypeDef CallbackID) +{ + DAL_StatusTypeDef status = DAL_OK; + + if (hcan->State == DAL_CAN_STATE_READY) + { + switch (CallbackID) + { + case DAL_CAN_TX_MAILBOX0_COMPLETE_CB_ID : + hcan->TxMailbox0CompleteCallback = DAL_CAN_TxMailbox0CompleteCallback; + break; + + case DAL_CAN_TX_MAILBOX1_COMPLETE_CB_ID : + hcan->TxMailbox1CompleteCallback = DAL_CAN_TxMailbox1CompleteCallback; + break; + + case DAL_CAN_TX_MAILBOX2_COMPLETE_CB_ID : + hcan->TxMailbox2CompleteCallback = DAL_CAN_TxMailbox2CompleteCallback; + break; + + case DAL_CAN_TX_MAILBOX0_ABORT_CB_ID : + hcan->TxMailbox0AbortCallback = DAL_CAN_TxMailbox0AbortCallback; + break; + + case DAL_CAN_TX_MAILBOX1_ABORT_CB_ID : + hcan->TxMailbox1AbortCallback = DAL_CAN_TxMailbox1AbortCallback; + break; + + case DAL_CAN_TX_MAILBOX2_ABORT_CB_ID : + hcan->TxMailbox2AbortCallback = DAL_CAN_TxMailbox2AbortCallback; + break; + + case DAL_CAN_RX_FIFO0_MSG_PENDING_CB_ID : + hcan->RxFifo0MsgPendingCallback = DAL_CAN_RxFifo0MsgPendingCallback; + break; + + case DAL_CAN_RX_FIFO0_FULL_CB_ID : + hcan->RxFifo0FullCallback = DAL_CAN_RxFifo0FullCallback; + break; + + case DAL_CAN_RX_FIFO1_MSG_PENDING_CB_ID : + hcan->RxFifo1MsgPendingCallback = DAL_CAN_RxFifo1MsgPendingCallback; + break; + + case DAL_CAN_RX_FIFO1_FULL_CB_ID : + hcan->RxFifo1FullCallback = DAL_CAN_RxFifo1FullCallback; + break; + + case DAL_CAN_SLEEP_CB_ID : + hcan->SleepCallback = DAL_CAN_SleepCallback; + break; + + case DAL_CAN_WAKEUP_FROM_RX_MSG_CB_ID : + hcan->WakeUpFromRxMsgCallback = DAL_CAN_WakeUpFromRxMsgCallback; + break; + + case DAL_CAN_ERROR_CB_ID : + hcan->ErrorCallback = DAL_CAN_ErrorCallback; + break; + + case DAL_CAN_MSPINIT_CB_ID : + hcan->MspInitCallback = DAL_CAN_MspInit; + break; + + case DAL_CAN_MSPDEINIT_CB_ID : + hcan->MspDeInitCallback = DAL_CAN_MspDeInit; + break; + + default : + /* Update the error code */ + hcan->ErrorCode |= DAL_CAN_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = DAL_ERROR; + break; + } + } + else if (hcan->State == DAL_CAN_STATE_RESET) + { + switch (CallbackID) + { + case DAL_CAN_MSPINIT_CB_ID : + hcan->MspInitCallback = DAL_CAN_MspInit; + break; + + case DAL_CAN_MSPDEINIT_CB_ID : + hcan->MspDeInitCallback = DAL_CAN_MspDeInit; + break; + + default : + /* Update the error code */ + hcan->ErrorCode |= DAL_CAN_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = DAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + hcan->ErrorCode |= DAL_CAN_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = DAL_ERROR; + } + + return status; +} +#endif /* USE_DAL_CAN_REGISTER_CALLBACKS */ + +/** + * @} + */ + +/** @defgroup CAN_Exported_Functions_Group2 Configuration functions + * @brief Configuration functions. + * +@verbatim + ============================================================================== + ##### Configuration functions ##### + ============================================================================== + [..] This section provides functions allowing to: + (+) DAL_CAN_ConfigFilter : Configure the CAN reception filters + +@endverbatim + * @{ + */ + +/** + * @brief Configures the CAN reception filter according to the specified + * parameters in the CAN_FilterInitStruct. + * @param hcan pointer to a CAN_HandleTypeDef structure that contains + * the configuration information for the specified CAN. + * @param sFilterConfig pointer to a CAN_FilterTypeDef structure that + * contains the filter configuration information. + * @retval None + */ +DAL_StatusTypeDef DAL_CAN_ConfigFilter(CAN_HandleTypeDef *hcan, CAN_FilterTypeDef *sFilterConfig) +{ + uint32_t filternbrbitpos; + CAN_TypeDef *can_ip = hcan->Instance; + DAL_CAN_StateTypeDef state = hcan->State; + + if ((state == DAL_CAN_STATE_READY) || + (state == DAL_CAN_STATE_LISTENING)) + { + /* Check the parameters */ + ASSERT_PARAM(IS_CAN_FILTER_ID_HALFWORD(sFilterConfig->FilterIdHigh)); + ASSERT_PARAM(IS_CAN_FILTER_ID_HALFWORD(sFilterConfig->FilterIdLow)); + ASSERT_PARAM(IS_CAN_FILTER_ID_HALFWORD(sFilterConfig->FilterMaskIdHigh)); + ASSERT_PARAM(IS_CAN_FILTER_ID_HALFWORD(sFilterConfig->FilterMaskIdLow)); + ASSERT_PARAM(IS_CAN_FILTER_MODE(sFilterConfig->FilterMode)); + ASSERT_PARAM(IS_CAN_FILTER_SCALE(sFilterConfig->FilterScale)); + ASSERT_PARAM(IS_CAN_FILTER_FIFO(sFilterConfig->FilterFIFOAssignment)); + ASSERT_PARAM(IS_CAN_FILTER_ACTIVATION(sFilterConfig->FilterActivation)); + +#if defined(CAN3) + /* Check the CAN instance */ + if (hcan->Instance == CAN3) + { + /* CAN3 is single instance with 14 dedicated filters banks */ + + /* Check the parameters */ + ASSERT_PARAM(IS_CAN_FILTER_BANK_SINGLE(sFilterConfig->FilterBank)); + } + else + { + /* CAN1 and CAN2 are dual instances with 28 common filters banks */ + /* Select master instance to access the filter banks */ + can_ip = CAN1; + + /* Check the parameters */ + ASSERT_PARAM(IS_CAN_FILTER_BANK_DUAL(sFilterConfig->FilterBank)); + ASSERT_PARAM(IS_CAN_FILTER_BANK_DUAL(sFilterConfig->SlaveStartFilterBank)); + } +#elif defined(CAN2) + /* CAN1 and CAN2 are dual instances with 28 common filters banks */ + /* Select master instance to access the filter banks */ + can_ip = CAN1; + + /* Check the parameters */ + ASSERT_PARAM(IS_CAN_FILTER_BANK_DUAL(sFilterConfig->FilterBank)); + ASSERT_PARAM(IS_CAN_FILTER_BANK_DUAL(sFilterConfig->SlaveStartFilterBank)); +#else + /* CAN1 is single instance with 14 dedicated filters banks */ + + /* Check the parameters */ + ASSERT_PARAM(IS_CAN_FILTER_BANK_SINGLE(sFilterConfig->FilterBank)); +#endif + + /* Initialisation mode for the filter */ + SET_BIT(can_ip->FCTRL, CAN_FCTRL_FINIT); + +#if defined(CAN3) + /* Check the CAN instance */ + if (can_ip == CAN1) + { + /* Select the start filter number of CAN2 slave instance */ + CLEAR_BIT(can_ip->FCTRL, CAN_FCTRL_CAN2SB); + SET_BIT(can_ip->FCTRL, sFilterConfig->SlaveStartFilterBank << CAN_FCTRL_CAN2SB_Pos); + } + +#elif defined(CAN2) + /* Select the start filter number of CAN2 slave instance */ + CLEAR_BIT(can_ip->FCTRL, CAN_FCTRL_CAN2SB); + SET_BIT(can_ip->FCTRL, sFilterConfig->SlaveStartFilterBank << CAN_FCTRL_CAN2SB_Pos); + +#endif + /* Convert filter number into bit position */ + filternbrbitpos = (uint32_t)1 << (sFilterConfig->FilterBank & 0x1FU); + + /* Filter Deactivation */ + CLEAR_BIT(can_ip->FACT, filternbrbitpos); + + /* Filter Scale */ + if (sFilterConfig->FilterScale == CAN_FILTERSCALE_16BIT) + { + /* 16-bit scale for the filter */ + CLEAR_BIT(can_ip->FSCFG, filternbrbitpos); + + /* First 16-bit identifier and First 16-bit mask */ + /* Or First 16-bit identifier and Second 16-bit identifier */ + can_ip->sFilterRegister[sFilterConfig->FilterBank].FBANK1 = + ((0x0000FFFFU & (uint32_t)sFilterConfig->FilterMaskIdLow) << 16U) | + (0x0000FFFFU & (uint32_t)sFilterConfig->FilterIdLow); + + /* Second 16-bit identifier and Second 16-bit mask */ + /* Or Third 16-bit identifier and Fourth 16-bit identifier */ + can_ip->sFilterRegister[sFilterConfig->FilterBank].FBANK2 = + ((0x0000FFFFU & (uint32_t)sFilterConfig->FilterMaskIdHigh) << 16U) | + (0x0000FFFFU & (uint32_t)sFilterConfig->FilterIdHigh); + } + + if (sFilterConfig->FilterScale == CAN_FILTERSCALE_32BIT) + { + /* 32-bit scale for the filter */ + SET_BIT(can_ip->FSCFG, filternbrbitpos); + + /* 32-bit identifier or First 32-bit identifier */ + can_ip->sFilterRegister[sFilterConfig->FilterBank].FBANK1 = + ((0x0000FFFFU & (uint32_t)sFilterConfig->FilterIdHigh) << 16U) | + (0x0000FFFFU & (uint32_t)sFilterConfig->FilterIdLow); + + /* 32-bit mask or Second 32-bit identifier */ + can_ip->sFilterRegister[sFilterConfig->FilterBank].FBANK2 = + ((0x0000FFFFU & (uint32_t)sFilterConfig->FilterMaskIdHigh) << 16U) | + (0x0000FFFFU & (uint32_t)sFilterConfig->FilterMaskIdLow); + } + + /* Filter Mode */ + if (sFilterConfig->FilterMode == CAN_FILTERMODE_IDMASK) + { + /* Id/Mask mode for the filter*/ + CLEAR_BIT(can_ip->FMCFG, filternbrbitpos); + } + else /* CAN_FilterInitStruct->CAN_FilterMode == CAN_FilterMode_IdList */ + { + /* Identifier list mode for the filter*/ + SET_BIT(can_ip->FMCFG, filternbrbitpos); + } + + /* Filter FIFO assignment */ + if (sFilterConfig->FilterFIFOAssignment == CAN_FILTER_FIFO0) + { + /* FIFO 0 assignation for the filter */ + CLEAR_BIT(can_ip->FFASS, filternbrbitpos); + } + else + { + /* FIFO 1 assignation for the filter */ + SET_BIT(can_ip->FFASS, filternbrbitpos); + } + + /* Filter activation */ + if (sFilterConfig->FilterActivation == CAN_FILTER_ENABLE) + { + SET_BIT(can_ip->FACT, filternbrbitpos); + } + + /* Leave the initialisation mode for the filter */ + CLEAR_BIT(can_ip->FCTRL, CAN_FCTRL_FINIT); + + /* Return function status */ + return DAL_OK; + } + else + { + /* Update error code */ + hcan->ErrorCode |= DAL_CAN_ERROR_NOT_INITIALIZED; + + return DAL_ERROR; + } +} + +/** + * @} + */ + +/** @defgroup CAN_Exported_Functions_Group3 Control functions + * @brief Control functions + * +@verbatim + ============================================================================== + ##### Control functions ##### + ============================================================================== + [..] This section provides functions allowing to: + (+) DAL_CAN_Start : Start the CAN module + (+) DAL_CAN_Stop : Stop the CAN module + (+) DAL_CAN_RequestSleep : Request sleep mode entry. + (+) DAL_CAN_WakeUp : Wake up from sleep mode. + (+) DAL_CAN_IsSleepActive : Check is sleep mode is active. + (+) DAL_CAN_AddTxMessage : Add a message to the Tx mailboxes + and activate the corresponding + transmission request + (+) DAL_CAN_AbortTxRequest : Abort transmission request + (+) DAL_CAN_GetTxMailboxesFreeLevel : Return Tx mailboxes free level + (+) DAL_CAN_IsTxMessagePending : Check if a transmission request is + pending on the selected Tx mailbox + (+) DAL_CAN_GetRxMessage : Get a CAN frame from the Rx FIFO + (+) DAL_CAN_GetRxFifoFillLevel : Return Rx FIFO fill level + +@endverbatim + * @{ + */ + +/** + * @brief Start the CAN module. + * @param hcan pointer to an CAN_HandleTypeDef structure that contains + * the configuration information for the specified CAN. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_CAN_Start(CAN_HandleTypeDef *hcan) +{ + uint32_t tickstart; + + if (hcan->State == DAL_CAN_STATE_READY) + { + /* Change CAN peripheral state */ + hcan->State = DAL_CAN_STATE_LISTENING; + + /* Request leave initialisation */ + CLEAR_BIT(hcan->Instance->MCTRL, CAN_MCTRL_INITREQ); + + /* Get tick */ + tickstart = DAL_GetTick(); + + /* Wait the acknowledge */ + while ((hcan->Instance->MSTS & CAN_MSTS_INITFLG) != 0U) + { + /* Check for the Timeout */ + if ((DAL_GetTick() - tickstart) > CAN_TIMEOUT_VALUE) + { + /* Update error code */ + hcan->ErrorCode |= DAL_CAN_ERROR_TIMEOUT; + + /* Change CAN state */ + hcan->State = DAL_CAN_STATE_ERROR; + + return DAL_ERROR; + } + } + + /* Reset the CAN ErrorCode */ + hcan->ErrorCode = DAL_CAN_ERROR_NONE; + + /* Return function status */ + return DAL_OK; + } + else + { + /* Update error code */ + hcan->ErrorCode |= DAL_CAN_ERROR_NOT_READY; + + return DAL_ERROR; + } +} + +/** + * @brief Stop the CAN module and enable access to configuration registers. + * @param hcan pointer to an CAN_HandleTypeDef structure that contains + * the configuration information for the specified CAN. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_CAN_Stop(CAN_HandleTypeDef *hcan) +{ + uint32_t tickstart; + + if (hcan->State == DAL_CAN_STATE_LISTENING) + { + /* Request initialisation */ + SET_BIT(hcan->Instance->MCTRL, CAN_MCTRL_INITREQ); + + /* Get tick */ + tickstart = DAL_GetTick(); + + /* Wait the acknowledge */ + while ((hcan->Instance->MSTS & CAN_MSTS_INITFLG) == 0U) + { + /* Check for the Timeout */ + if ((DAL_GetTick() - tickstart) > CAN_TIMEOUT_VALUE) + { + /* Update error code */ + hcan->ErrorCode |= DAL_CAN_ERROR_TIMEOUT; + + /* Change CAN state */ + hcan->State = DAL_CAN_STATE_ERROR; + + return DAL_ERROR; + } + } + + /* Exit from sleep mode */ + CLEAR_BIT(hcan->Instance->MCTRL, CAN_MCTRL_SLEEPREQ); + + /* Change CAN peripheral state */ + hcan->State = DAL_CAN_STATE_READY; + + /* Return function status */ + return DAL_OK; + } + else + { + /* Update error code */ + hcan->ErrorCode |= DAL_CAN_ERROR_NOT_STARTED; + + return DAL_ERROR; + } +} + +/** + * @brief Request the sleep mode (low power) entry. + * When returning from this function, Sleep mode will be entered + * as soon as the current CAN activity (transmission or reception + * of a CAN frame) has been completed. + * @param hcan pointer to a CAN_HandleTypeDef structure that contains + * the configuration information for the specified CAN. + * @retval DAL status. + */ +DAL_StatusTypeDef DAL_CAN_RequestSleep(CAN_HandleTypeDef *hcan) +{ + DAL_CAN_StateTypeDef state = hcan->State; + + if ((state == DAL_CAN_STATE_READY) || + (state == DAL_CAN_STATE_LISTENING)) + { + /* Request Sleep mode */ + SET_BIT(hcan->Instance->MCTRL, CAN_MCTRL_SLEEPREQ); + + /* Return function status */ + return DAL_OK; + } + else + { + /* Update error code */ + hcan->ErrorCode |= DAL_CAN_ERROR_NOT_INITIALIZED; + + /* Return function status */ + return DAL_ERROR; + } +} + +/** + * @brief Wake up from sleep mode. + * When returning with DAL_OK status from this function, Sleep mode + * is exited. + * @param hcan pointer to a CAN_HandleTypeDef structure that contains + * the configuration information for the specified CAN. + * @retval DAL status. + */ +DAL_StatusTypeDef DAL_CAN_WakeUp(CAN_HandleTypeDef *hcan) +{ + __IO uint32_t count = 0; + uint32_t timeout = 1000000U; + DAL_CAN_StateTypeDef state = hcan->State; + + if ((state == DAL_CAN_STATE_READY) || + (state == DAL_CAN_STATE_LISTENING)) + { + /* Wake up request */ + CLEAR_BIT(hcan->Instance->MCTRL, CAN_MCTRL_SLEEPREQ); + + /* Wait sleep mode is exited */ + do + { + /* Increment counter */ + count++; + + /* Check if timeout is reached */ + if (count > timeout) + { + /* Update error code */ + hcan->ErrorCode |= DAL_CAN_ERROR_TIMEOUT; + + return DAL_ERROR; + } + } + while ((hcan->Instance->MSTS & CAN_MSTS_SLEEPFLG) != 0U); + + /* Return function status */ + return DAL_OK; + } + else + { + /* Update error code */ + hcan->ErrorCode |= DAL_CAN_ERROR_NOT_INITIALIZED; + + return DAL_ERROR; + } +} + +/** + * @brief Check is sleep mode is active. + * @param hcan pointer to a CAN_HandleTypeDef structure that contains + * the configuration information for the specified CAN. + * @retval Status + * - 0 : Sleep mode is not active. + * - 1 : Sleep mode is active. + */ +uint32_t DAL_CAN_IsSleepActive(CAN_HandleTypeDef *hcan) +{ + uint32_t status = 0U; + DAL_CAN_StateTypeDef state = hcan->State; + + if ((state == DAL_CAN_STATE_READY) || + (state == DAL_CAN_STATE_LISTENING)) + { + /* Check Sleep mode */ + if ((hcan->Instance->MSTS & CAN_MSTS_SLEEPFLG) != 0U) + { + status = 1U; + } + } + + /* Return function status */ + return status; +} + +/** + * @brief Add a message to the first free Tx mailbox and activate the + * corresponding transmission request. + * @param hcan pointer to a CAN_HandleTypeDef structure that contains + * the configuration information for the specified CAN. + * @param pHeader pointer to a CAN_TxHeaderTypeDef structure. + * @param aData array containing the payload of the Tx frame. + * @param pTxMailbox pointer to a variable where the function will return + * the TxMailbox used to store the Tx message. + * This parameter can be a value of @arg CAN_Tx_Mailboxes. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_CAN_AddTxMessage(CAN_HandleTypeDef *hcan, CAN_TxHeaderTypeDef *pHeader, uint8_t aData[], uint32_t *pTxMailbox) +{ + uint32_t transmitmailbox; + DAL_CAN_StateTypeDef state = hcan->State; + uint32_t TXSTS = READ_REG(hcan->Instance->TXSTS); + + /* Check the parameters */ + ASSERT_PARAM(IS_CAN_IDTYPE(pHeader->IDE)); + ASSERT_PARAM(IS_CAN_RTR(pHeader->RTR)); + ASSERT_PARAM(IS_CAN_DLC(pHeader->DLC)); + if (pHeader->IDE == CAN_ID_STD) + { + ASSERT_PARAM(IS_CAN_STDID(pHeader->StdId)); + } + else + { + ASSERT_PARAM(IS_CAN_EXTID(pHeader->ExtId)); + } + ASSERT_PARAM(IS_FUNCTIONAL_STATE(pHeader->TransmitGlobalTime)); + + if ((state == DAL_CAN_STATE_READY) || + (state == DAL_CAN_STATE_LISTENING)) + { + /* Check that all the Tx mailboxes are not full */ + if (((TXSTS & CAN_TXSTS_TXMEFLG0) != 0U) || + ((TXSTS & CAN_TXSTS_TXMEFLG1) != 0U) || + ((TXSTS & CAN_TXSTS_TXMEFLG2) != 0U)) + { + /* Select an empty transmit mailbox */ + transmitmailbox = (TXSTS & CAN_TXSTS_EMNUM) >> CAN_TXSTS_EMNUM_Pos; + + /* Check transmit mailbox value */ + if (transmitmailbox > 2U) + { + /* Update error code */ + hcan->ErrorCode |= DAL_CAN_ERROR_INTERNAL; + + return DAL_ERROR; + } + + /* Store the Tx mailbox */ + *pTxMailbox = (uint32_t)1 << transmitmailbox; + + /* Set up the Id */ + if (pHeader->IDE == CAN_ID_STD) + { + hcan->Instance->sTxMailBox[transmitmailbox].TXMID = ((pHeader->StdId << CAN_TXMID0_STDID_Pos) | + pHeader->RTR); + } + else + { + hcan->Instance->sTxMailBox[transmitmailbox].TXMID = ((pHeader->ExtId << CAN_TXMID0_EXTID_Pos) | + pHeader->IDE | + pHeader->RTR); + } + + /* Set up the DLC */ + hcan->Instance->sTxMailBox[transmitmailbox].TXDLEN = (pHeader->DLC); + + /* Set up the Transmit Global Time mode */ + if (pHeader->TransmitGlobalTime == ENABLE) + { + SET_BIT(hcan->Instance->sTxMailBox[transmitmailbox].TXDLEN, CAN_TXDLEN0_TXTS); + } + + /* Set up the data field */ + WRITE_REG(hcan->Instance->sTxMailBox[transmitmailbox].TXMDH, + ((uint32_t)aData[7] << CAN_TXMDH0_DATABYTE7_Pos) | + ((uint32_t)aData[6] << CAN_TXMDH0_DATABYTE6_Pos) | + ((uint32_t)aData[5] << CAN_TXMDH0_DATABYTE5_Pos) | + ((uint32_t)aData[4] << CAN_TXMDH0_DATABYTE4_Pos)); + WRITE_REG(hcan->Instance->sTxMailBox[transmitmailbox].TXMDL, + ((uint32_t)aData[3] << CAN_TXMDL0_DATABYTE3_Pos) | + ((uint32_t)aData[2] << CAN_TXMDL0_DATABYTE2_Pos) | + ((uint32_t)aData[1] << CAN_TXMDL0_DATABYTE1_Pos) | + ((uint32_t)aData[0] << CAN_TXMDL0_DATABYTE0_Pos)); + + /* Request transmission */ + SET_BIT(hcan->Instance->sTxMailBox[transmitmailbox].TXMID, CAN_TXMID0_TXMREQ); + + /* Return function status */ + return DAL_OK; + } + else + { + /* Update error code */ + hcan->ErrorCode |= DAL_CAN_ERROR_PARAM; + + return DAL_ERROR; + } + } + else + { + /* Update error code */ + hcan->ErrorCode |= DAL_CAN_ERROR_NOT_INITIALIZED; + + return DAL_ERROR; + } +} + +/** + * @brief Abort transmission requests + * @param hcan pointer to an CAN_HandleTypeDef structure that contains + * the configuration information for the specified CAN. + * @param TxMailboxes List of the Tx Mailboxes to abort. + * This parameter can be any combination of @arg CAN_Tx_Mailboxes. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_CAN_AbortTxRequest(CAN_HandleTypeDef *hcan, uint32_t TxMailboxes) +{ + DAL_CAN_StateTypeDef state = hcan->State; + + /* Check function parameters */ + ASSERT_PARAM(IS_CAN_TX_MAILBOX_LIST(TxMailboxes)); + + if ((state == DAL_CAN_STATE_READY) || + (state == DAL_CAN_STATE_LISTENING)) + { + /* Check Tx Mailbox 0 */ + if ((TxMailboxes & CAN_TX_MAILBOX0) != 0U) + { + /* Add cancellation request for Tx Mailbox 0 */ + SET_BIT(hcan->Instance->TXSTS, CAN_TXSTS_ABREQFLG0); + } + + /* Check Tx Mailbox 1 */ + if ((TxMailboxes & CAN_TX_MAILBOX1) != 0U) + { + /* Add cancellation request for Tx Mailbox 1 */ + SET_BIT(hcan->Instance->TXSTS, CAN_TXSTS_ABREQFLG1); + } + + /* Check Tx Mailbox 2 */ + if ((TxMailboxes & CAN_TX_MAILBOX2) != 0U) + { + /* Add cancellation request for Tx Mailbox 2 */ + SET_BIT(hcan->Instance->TXSTS, CAN_TXSTS_ABREQFLG2); + } + + /* Return function status */ + return DAL_OK; + } + else + { + /* Update error code */ + hcan->ErrorCode |= DAL_CAN_ERROR_NOT_INITIALIZED; + + return DAL_ERROR; + } +} + +/** + * @brief Return Tx Mailboxes free level: number of free Tx Mailboxes. + * @param hcan pointer to a CAN_HandleTypeDef structure that contains + * the configuration information for the specified CAN. + * @retval Number of free Tx Mailboxes. + */ +uint32_t DAL_CAN_GetTxMailboxesFreeLevel(CAN_HandleTypeDef *hcan) +{ + uint32_t freelevel = 0U; + DAL_CAN_StateTypeDef state = hcan->State; + + if ((state == DAL_CAN_STATE_READY) || + (state == DAL_CAN_STATE_LISTENING)) + { + /* Check Tx Mailbox 0 status */ + if ((hcan->Instance->TXSTS & CAN_TXSTS_TXMEFLG0) != 0U) + { + freelevel++; + } + + /* Check Tx Mailbox 1 status */ + if ((hcan->Instance->TXSTS & CAN_TXSTS_TXMEFLG1) != 0U) + { + freelevel++; + } + + /* Check Tx Mailbox 2 status */ + if ((hcan->Instance->TXSTS & CAN_TXSTS_TXMEFLG2) != 0U) + { + freelevel++; + } + } + + /* Return Tx Mailboxes free level */ + return freelevel; +} + +/** + * @brief Check if a transmission request is pending on the selected Tx + * Mailboxes. + * @param hcan pointer to an CAN_HandleTypeDef structure that contains + * the configuration information for the specified CAN. + * @param TxMailboxes List of Tx Mailboxes to check. + * This parameter can be any combination of @arg CAN_Tx_Mailboxes. + * @retval Status + * - 0 : No pending transmission request on any selected Tx Mailboxes. + * - 1 : Pending transmission request on at least one of the selected + * Tx Mailbox. + */ +uint32_t DAL_CAN_IsTxMessagePending(CAN_HandleTypeDef *hcan, uint32_t TxMailboxes) +{ + uint32_t status = 0U; + DAL_CAN_StateTypeDef state = hcan->State; + + /* Check function parameters */ + ASSERT_PARAM(IS_CAN_TX_MAILBOX_LIST(TxMailboxes)); + + if ((state == DAL_CAN_STATE_READY) || + (state == DAL_CAN_STATE_LISTENING)) + { + /* Check pending transmission request on the selected Tx Mailboxes */ + if ((hcan->Instance->TXSTS & (TxMailboxes << CAN_TXSTS_TXMEFLG0_Pos)) != (TxMailboxes << CAN_TXSTS_TXMEFLG0_Pos)) + { + status = 1U; + } + } + + /* Return status */ + return status; +} + +/** + * @brief Return timestamp of Tx message sent, if time triggered communication + mode is enabled. + * @param hcan pointer to a CAN_HandleTypeDef structure that contains + * the configuration information for the specified CAN. + * @param TxMailbox Tx Mailbox where the timestamp of message sent will be + * read. + * This parameter can be one value of @arg CAN_Tx_Mailboxes. + * @retval Timestamp of message sent from Tx Mailbox. + */ +uint32_t DAL_CAN_GetTxTimestamp(CAN_HandleTypeDef *hcan, uint32_t TxMailbox) +{ + uint32_t timestamp = 0U; + uint32_t transmitmailbox; + DAL_CAN_StateTypeDef state = hcan->State; + + /* Check function parameters */ + ASSERT_PARAM(IS_CAN_TX_MAILBOX(TxMailbox)); + + if ((state == DAL_CAN_STATE_READY) || + (state == DAL_CAN_STATE_LISTENING)) + { + /* Select the Tx mailbox */ + transmitmailbox = POSITION_VAL(TxMailbox); + + /* Get timestamp */ + timestamp = (hcan->Instance->sTxMailBox[transmitmailbox].TXDLEN & CAN_TXDLEN0_MTS) >> CAN_TXDLEN0_MTS_Pos; + } + + /* Return the timestamp */ + return timestamp; +} + +/** + * @brief Get an CAN frame from the Rx FIFO zone into the message RAM. + * @param hcan pointer to an CAN_HandleTypeDef structure that contains + * the configuration information for the specified CAN. + * @param RxFifo Fifo number of the received message to be read. + * This parameter can be a value of @arg CAN_receive_FIFO_number. + * @param pHeader pointer to a CAN_RxHeaderTypeDef structure where the header + * of the Rx frame will be stored. + * @param aData array where the payload of the Rx frame will be stored. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_CAN_GetRxMessage(CAN_HandleTypeDef *hcan, uint32_t RxFifo, CAN_RxHeaderTypeDef *pHeader, uint8_t aData[]) +{ + DAL_CAN_StateTypeDef state = hcan->State; + + ASSERT_PARAM(IS_CAN_RX_FIFO(RxFifo)); + + if ((state == DAL_CAN_STATE_READY) || + (state == DAL_CAN_STATE_LISTENING)) + { + /* Check the Rx FIFO */ + if (RxFifo == CAN_RX_FIFO0) /* Rx element is assigned to Rx FIFO 0 */ + { + /* Check that the Rx FIFO 0 is not empty */ + if ((hcan->Instance->RXF0 & CAN_RXF0_FMNUM0) == 0U) + { + /* Update error code */ + hcan->ErrorCode |= DAL_CAN_ERROR_PARAM; + + return DAL_ERROR; + } + } + else /* Rx element is assigned to Rx FIFO 1 */ + { + /* Check that the Rx FIFO 1 is not empty */ + if ((hcan->Instance->RXF1 & CAN_RXF1_FMNUM1) == 0U) + { + /* Update error code */ + hcan->ErrorCode |= DAL_CAN_ERROR_PARAM; + + return DAL_ERROR; + } + } + + /* Get the header */ + pHeader->IDE = CAN_RXMID0_IDTYPESEL & hcan->Instance->sFIFOMailBox[RxFifo].RXMID; + if (pHeader->IDE == CAN_ID_STD) + { + pHeader->StdId = (CAN_RXMID0_STDID & hcan->Instance->sFIFOMailBox[RxFifo].RXMID) >> CAN_TXMID0_STDID_Pos; + } + else + { + pHeader->ExtId = ((CAN_RXMID0_EXTID | CAN_RXMID0_STDID) & hcan->Instance->sFIFOMailBox[RxFifo].RXMID) >> CAN_RXMID0_EXTID_Pos; + } + pHeader->RTR = (CAN_RXMID0_RFTXREQ & hcan->Instance->sFIFOMailBox[RxFifo].RXMID); + pHeader->DLC = (CAN_RXDLEN0_DLCODE & hcan->Instance->sFIFOMailBox[RxFifo].RXDLEN) >> CAN_RXDLEN0_DLCODE_Pos; + pHeader->FilterMatchIndex = (CAN_RXDLEN0_FMIDX & hcan->Instance->sFIFOMailBox[RxFifo].RXDLEN) >> CAN_RXDLEN0_FMIDX_Pos; + pHeader->Timestamp = (CAN_RXDLEN0_MTS & hcan->Instance->sFIFOMailBox[RxFifo].RXDLEN) >> CAN_RXDLEN0_MTS_Pos; + + /* Get the data */ + aData[0] = (uint8_t)((CAN_RXMDL0_DATABYTE0 & hcan->Instance->sFIFOMailBox[RxFifo].RXMDL) >> CAN_RXMDL0_DATABYTE0_Pos); + aData[1] = (uint8_t)((CAN_RXMDL0_DATABYTE1 & hcan->Instance->sFIFOMailBox[RxFifo].RXMDL) >> CAN_RXMDL0_DATABYTE1_Pos); + aData[2] = (uint8_t)((CAN_RXMDL0_DATABYTE2 & hcan->Instance->sFIFOMailBox[RxFifo].RXMDL) >> CAN_RXMDL0_DATABYTE2_Pos); + aData[3] = (uint8_t)((CAN_RXMDL0_DATABYTE3 & hcan->Instance->sFIFOMailBox[RxFifo].RXMDL) >> CAN_RXMDL0_DATABYTE3_Pos); + aData[4] = (uint8_t)((CAN_RXMDH0_DATABYTE4 & hcan->Instance->sFIFOMailBox[RxFifo].RXMDH) >> CAN_RXMDH0_DATABYTE4_Pos); + aData[5] = (uint8_t)((CAN_RXMDH0_DATABYTE5 & hcan->Instance->sFIFOMailBox[RxFifo].RXMDH) >> CAN_RXMDH0_DATABYTE5_Pos); + aData[6] = (uint8_t)((CAN_RXMDH0_DATABYTE6 & hcan->Instance->sFIFOMailBox[RxFifo].RXMDH) >> CAN_RXMDH0_DATABYTE6_Pos); + aData[7] = (uint8_t)((CAN_RXMDH0_DATABYTE7 & hcan->Instance->sFIFOMailBox[RxFifo].RXMDH) >> CAN_RXMDH0_DATABYTE7_Pos); + + /* Release the FIFO */ + if (RxFifo == CAN_RX_FIFO0) /* Rx element is assigned to Rx FIFO 0 */ + { + /* Release RX FIFO 0 */ + SET_BIT(hcan->Instance->RXF0, CAN_RXF0_RFOM0); + } + else /* Rx element is assigned to Rx FIFO 1 */ + { + /* Release RX FIFO 1 */ + SET_BIT(hcan->Instance->RXF1, CAN_RXF1_RFOM1); + } + + /* Return function status */ + return DAL_OK; + } + else + { + /* Update error code */ + hcan->ErrorCode |= DAL_CAN_ERROR_NOT_INITIALIZED; + + return DAL_ERROR; + } +} + +/** + * @brief Return Rx FIFO fill level. + * @param hcan pointer to an CAN_HandleTypeDef structure that contains + * the configuration information for the specified CAN. + * @param RxFifo Rx FIFO. + * This parameter can be a value of @arg CAN_receive_FIFO_number. + * @retval Number of messages available in Rx FIFO. + */ +uint32_t DAL_CAN_GetRxFifoFillLevel(CAN_HandleTypeDef *hcan, uint32_t RxFifo) +{ + uint32_t filllevel = 0U; + DAL_CAN_StateTypeDef state = hcan->State; + + /* Check function parameters */ + ASSERT_PARAM(IS_CAN_RX_FIFO(RxFifo)); + + if ((state == DAL_CAN_STATE_READY) || + (state == DAL_CAN_STATE_LISTENING)) + { + if (RxFifo == CAN_RX_FIFO0) + { + filllevel = hcan->Instance->RXF0 & CAN_RXF0_FMNUM0; + } + else /* RxFifo == CAN_RX_FIFO1 */ + { + filllevel = hcan->Instance->RXF1 & CAN_RXF1_FMNUM1; + } + } + + /* Return Rx FIFO fill level */ + return filllevel; +} + +/** + * @} + */ + +/** @defgroup CAN_Exported_Functions_Group4 Interrupts management + * @brief Interrupts management + * +@verbatim + ============================================================================== + ##### Interrupts management ##### + ============================================================================== + [..] This section provides functions allowing to: + (+) DAL_CAN_ActivateNotification : Enable interrupts + (+) DAL_CAN_DeactivateNotification : Disable interrupts + (+) DAL_CAN_IRQHandler : Handles CAN interrupt request + +@endverbatim + * @{ + */ + +/** + * @brief Enable interrupts. + * @param hcan pointer to an CAN_HandleTypeDef structure that contains + * the configuration information for the specified CAN. + * @param ActiveITs indicates which interrupts will be enabled. + * This parameter can be any combination of @arg CAN_Interrupts. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_CAN_ActivateNotification(CAN_HandleTypeDef *hcan, uint32_t ActiveITs) +{ + DAL_CAN_StateTypeDef state = hcan->State; + + /* Check function parameters */ + ASSERT_PARAM(IS_CAN_IT(ActiveITs)); + + if ((state == DAL_CAN_STATE_READY) || + (state == DAL_CAN_STATE_LISTENING)) + { + /* Enable the selected interrupts */ + __DAL_CAN_ENABLE_IT(hcan, ActiveITs); + + /* Return function status */ + return DAL_OK; + } + else + { + /* Update error code */ + hcan->ErrorCode |= DAL_CAN_ERROR_NOT_INITIALIZED; + + return DAL_ERROR; + } +} + +/** + * @brief Disable interrupts. + * @param hcan pointer to an CAN_HandleTypeDef structure that contains + * the configuration information for the specified CAN. + * @param InactiveITs indicates which interrupts will be disabled. + * This parameter can be any combination of @arg CAN_Interrupts. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_CAN_DeactivateNotification(CAN_HandleTypeDef *hcan, uint32_t InactiveITs) +{ + DAL_CAN_StateTypeDef state = hcan->State; + + /* Check function parameters */ + ASSERT_PARAM(IS_CAN_IT(InactiveITs)); + + if ((state == DAL_CAN_STATE_READY) || + (state == DAL_CAN_STATE_LISTENING)) + { + /* Disable the selected interrupts */ + __DAL_CAN_DISABLE_IT(hcan, InactiveITs); + + /* Return function status */ + return DAL_OK; + } + else + { + /* Update error code */ + hcan->ErrorCode |= DAL_CAN_ERROR_NOT_INITIALIZED; + + return DAL_ERROR; + } +} + +/** + * @brief Handles CAN interrupt request + * @param hcan pointer to a CAN_HandleTypeDef structure that contains + * the configuration information for the specified CAN. + * @retval None + */ +void DAL_CAN_IRQHandler(CAN_HandleTypeDef *hcan) +{ + uint32_t errorcode = DAL_CAN_ERROR_NONE; + uint32_t interrupts = READ_REG(hcan->Instance->INTEN); + uint32_t MSTSflags = READ_REG(hcan->Instance->MSTS); + uint32_t TXSTSflags = READ_REG(hcan->Instance->TXSTS); + uint32_t RXF0flags = READ_REG(hcan->Instance->RXF0); + uint32_t RXF1flags = READ_REG(hcan->Instance->RXF1); + uint32_t esrflags = READ_REG(hcan->Instance->ERRSTS); + + /* Transmit Mailbox empty interrupt management *****************************/ + if ((interrupts & CAN_IT_TX_MAILBOX_EMPTY) != 0U) + { + /* Transmit Mailbox 0 management *****************************************/ + if ((TXSTSflags & CAN_TXSTS_REQCFLG0) != 0U) + { + /* Clear the Transmission Complete flag (and TXOK0,ALST0,TERR0 bits) */ + __DAL_CAN_CLEAR_FLAG(hcan, CAN_FLAG_RQCP0); + + if ((TXSTSflags & CAN_TXSTS_TXSUSFLG0) != 0U) + { + /* Transmission Mailbox 0 complete callback */ +#if USE_DAL_CAN_REGISTER_CALLBACKS == 1 + /* Call registered callback*/ + hcan->TxMailbox0CompleteCallback(hcan); +#else + /* Call weak (surcharged) callback */ + DAL_CAN_TxMailbox0CompleteCallback(hcan); +#endif /* USE_DAL_CAN_REGISTER_CALLBACKS */ + } + else + { + if ((TXSTSflags & CAN_TXSTS_ARBLSTFLG0) != 0U) + { + /* Update error code */ + errorcode |= DAL_CAN_ERROR_TX_ALST0; + } + else if ((TXSTSflags & CAN_TXSTS_TXERRFLG0) != 0U) + { + /* Update error code */ + errorcode |= DAL_CAN_ERROR_TX_TERR0; + } + else + { + /* Transmission Mailbox 0 abort callback */ +#if USE_DAL_CAN_REGISTER_CALLBACKS == 1 + /* Call registered callback*/ + hcan->TxMailbox0AbortCallback(hcan); +#else + /* Call weak (surcharged) callback */ + DAL_CAN_TxMailbox0AbortCallback(hcan); +#endif /* USE_DAL_CAN_REGISTER_CALLBACKS */ + } + } + } + + /* Transmit Mailbox 1 management *****************************************/ + if ((TXSTSflags & CAN_TXSTS_REQCFLG1) != 0U) + { + /* Clear the Transmission Complete flag (and TXOK1,ALST1,TERR1 bits) */ + __DAL_CAN_CLEAR_FLAG(hcan, CAN_FLAG_RQCP1); + + if ((TXSTSflags & CAN_TXSTS_TXSUSFLG1) != 0U) + { + /* Transmission Mailbox 1 complete callback */ +#if USE_DAL_CAN_REGISTER_CALLBACKS == 1 + /* Call registered callback*/ + hcan->TxMailbox1CompleteCallback(hcan); +#else + /* Call weak (surcharged) callback */ + DAL_CAN_TxMailbox1CompleteCallback(hcan); +#endif /* USE_DAL_CAN_REGISTER_CALLBACKS */ + } + else + { + if ((TXSTSflags & CAN_TXSTS_ARBLSTFLG1) != 0U) + { + /* Update error code */ + errorcode |= DAL_CAN_ERROR_TX_ALST1; + } + else if ((TXSTSflags & CAN_TXSTS_TXERRFLG1) != 0U) + { + /* Update error code */ + errorcode |= DAL_CAN_ERROR_TX_TERR1; + } + else + { + /* Transmission Mailbox 1 abort callback */ +#if USE_DAL_CAN_REGISTER_CALLBACKS == 1 + /* Call registered callback*/ + hcan->TxMailbox1AbortCallback(hcan); +#else + /* Call weak (surcharged) callback */ + DAL_CAN_TxMailbox1AbortCallback(hcan); +#endif /* USE_DAL_CAN_REGISTER_CALLBACKS */ + } + } + } + + /* Transmit Mailbox 2 management *****************************************/ + if ((TXSTSflags & CAN_TXSTS_REQCFLG2) != 0U) + { + /* Clear the Transmission Complete flag (and TXOK2,ALST2,TERR2 bits) */ + __DAL_CAN_CLEAR_FLAG(hcan, CAN_FLAG_RQCP2); + + if ((TXSTSflags & CAN_TXSTS_TXSUSFLG2) != 0U) + { + /* Transmission Mailbox 2 complete callback */ +#if USE_DAL_CAN_REGISTER_CALLBACKS == 1 + /* Call registered callback*/ + hcan->TxMailbox2CompleteCallback(hcan); +#else + /* Call weak (surcharged) callback */ + DAL_CAN_TxMailbox2CompleteCallback(hcan); +#endif /* USE_DAL_CAN_REGISTER_CALLBACKS */ + } + else + { + if ((TXSTSflags & CAN_TXSTS_ARBLSTFLG2) != 0U) + { + /* Update error code */ + errorcode |= DAL_CAN_ERROR_TX_ALST2; + } + else if ((TXSTSflags & CAN_TXSTS_TXERRFLG2) != 0U) + { + /* Update error code */ + errorcode |= DAL_CAN_ERROR_TX_TERR2; + } + else + { + /* Transmission Mailbox 2 abort callback */ +#if USE_DAL_CAN_REGISTER_CALLBACKS == 1 + /* Call registered callback*/ + hcan->TxMailbox2AbortCallback(hcan); +#else + /* Call weak (surcharged) callback */ + DAL_CAN_TxMailbox2AbortCallback(hcan); +#endif /* USE_DAL_CAN_REGISTER_CALLBACKS */ + } + } + } + } + + /* Receive FIFO 0 overrun interrupt management *****************************/ + if ((interrupts & CAN_IT_RX_FIFO0_OVERRUN) != 0U) + { + if ((RXF0flags & CAN_RXF0_FOVRFLG0) != 0U) + { + /* Set CAN error code to Rx Fifo 0 overrun error */ + errorcode |= DAL_CAN_ERROR_RX_FOV0; + + /* Clear FIFO0 Overrun Flag */ + __DAL_CAN_CLEAR_FLAG(hcan, CAN_FLAG_FOV0); + } + } + + /* Receive FIFO 0 full interrupt management ********************************/ + if ((interrupts & CAN_IT_RX_FIFO0_FULL) != 0U) + { + if ((RXF0flags & CAN_RXF0_FFULLFLG0) != 0U) + { + /* Clear FIFO 0 full Flag */ + __DAL_CAN_CLEAR_FLAG(hcan, CAN_FLAG_FF0); + + /* Receive FIFO 0 full Callback */ +#if USE_DAL_CAN_REGISTER_CALLBACKS == 1 + /* Call registered callback*/ + hcan->RxFifo0FullCallback(hcan); +#else + /* Call weak (surcharged) callback */ + DAL_CAN_RxFifo0FullCallback(hcan); +#endif /* USE_DAL_CAN_REGISTER_CALLBACKS */ + } + } + + /* Receive FIFO 0 message pending interrupt management *********************/ + if ((interrupts & CAN_IT_RX_FIFO0_MSG_PENDING) != 0U) + { + /* Check if message is still pending */ + if ((hcan->Instance->RXF0 & CAN_RXF0_FMNUM0) != 0U) + { + /* Receive FIFO 0 message pending Callback */ +#if USE_DAL_CAN_REGISTER_CALLBACKS == 1 + /* Call registered callback*/ + hcan->RxFifo0MsgPendingCallback(hcan); +#else + /* Call weak (surcharged) callback */ + DAL_CAN_RxFifo0MsgPendingCallback(hcan); +#endif /* USE_DAL_CAN_REGISTER_CALLBACKS */ + } + } + + /* Receive FIFO 1 overrun interrupt management *****************************/ + if ((interrupts & CAN_IT_RX_FIFO1_OVERRUN) != 0U) + { + if ((RXF1flags & CAN_RXF1_FOVRFLG1) != 0U) + { + /* Set CAN error code to Rx Fifo 1 overrun error */ + errorcode |= DAL_CAN_ERROR_RX_FOV1; + + /* Clear FIFO1 Overrun Flag */ + __DAL_CAN_CLEAR_FLAG(hcan, CAN_FLAG_FOV1); + } + } + + /* Receive FIFO 1 full interrupt management ********************************/ + if ((interrupts & CAN_IT_RX_FIFO1_FULL) != 0U) + { + if ((RXF1flags & CAN_RXF1_FFULLFLG1) != 0U) + { + /* Clear FIFO 1 full Flag */ + __DAL_CAN_CLEAR_FLAG(hcan, CAN_FLAG_FF1); + + /* Receive FIFO 1 full Callback */ +#if USE_DAL_CAN_REGISTER_CALLBACKS == 1 + /* Call registered callback*/ + hcan->RxFifo1FullCallback(hcan); +#else + /* Call weak (surcharged) callback */ + DAL_CAN_RxFifo1FullCallback(hcan); +#endif /* USE_DAL_CAN_REGISTER_CALLBACKS */ + } + } + + /* Receive FIFO 1 message pending interrupt management *********************/ + if ((interrupts & CAN_IT_RX_FIFO1_MSG_PENDING) != 0U) + { + /* Check if message is still pending */ + if ((hcan->Instance->RXF1 & CAN_RXF1_FMNUM1) != 0U) + { + /* Receive FIFO 1 message pending Callback */ +#if USE_DAL_CAN_REGISTER_CALLBACKS == 1 + /* Call registered callback*/ + hcan->RxFifo1MsgPendingCallback(hcan); +#else + /* Call weak (surcharged) callback */ + DAL_CAN_RxFifo1MsgPendingCallback(hcan); +#endif /* USE_DAL_CAN_REGISTER_CALLBACKS */ + } + } + + /* Sleep interrupt management *********************************************/ + if ((interrupts & CAN_IT_SLEEP_ACK) != 0U) + { + if ((MSTSflags & CAN_MSTS_SLEEPIFLG) != 0U) + { + /* Clear Sleep interrupt Flag */ + __DAL_CAN_CLEAR_FLAG(hcan, CAN_FLAG_SLAKI); + + /* Sleep Callback */ +#if USE_DAL_CAN_REGISTER_CALLBACKS == 1 + /* Call registered callback*/ + hcan->SleepCallback(hcan); +#else + /* Call weak (surcharged) callback */ + DAL_CAN_SleepCallback(hcan); +#endif /* USE_DAL_CAN_REGISTER_CALLBACKS */ + } + } + + /* WakeUp interrupt management *********************************************/ + if ((interrupts & CAN_IT_WAKEUP) != 0U) + { + if ((MSTSflags & CAN_MSTS_WUPIFLG) != 0U) + { + /* Clear WakeUp Flag */ + __DAL_CAN_CLEAR_FLAG(hcan, CAN_FLAG_WKU); + + /* WakeUp Callback */ +#if USE_DAL_CAN_REGISTER_CALLBACKS == 1 + /* Call registered callback*/ + hcan->WakeUpFromRxMsgCallback(hcan); +#else + /* Call weak (surcharged) callback */ + DAL_CAN_WakeUpFromRxMsgCallback(hcan); +#endif /* USE_DAL_CAN_REGISTER_CALLBACKS */ + } + } + + /* Error interrupts management *********************************************/ + if ((interrupts & CAN_IT_ERROR) != 0U) + { + if ((MSTSflags & CAN_MSTS_ERRIFLG) != 0U) + { + /* Check Error Warning Flag */ + if (((interrupts & CAN_IT_ERROR_WARNING) != 0U) && + ((esrflags & CAN_ERRSTS_ERRWFLG) != 0U)) + { + /* Set CAN error code to Error Warning */ + errorcode |= DAL_CAN_ERROR_EWG; + + /* No need for clear of Error Warning Flag as read-only */ + } + + /* Check Error Passive Flag */ + if (((interrupts & CAN_IT_ERROR_PASSIVE) != 0U) && + ((esrflags & CAN_ERRSTS_ERRPFLG) != 0U)) + { + /* Set CAN error code to Error Passive */ + errorcode |= DAL_CAN_ERROR_EPV; + + /* No need for clear of Error Passive Flag as read-only */ + } + + /* Check Bus-off Flag */ + if (((interrupts & CAN_IT_BUSOFF) != 0U) && + ((esrflags & CAN_ERRSTS_BOFLG) != 0U)) + { + /* Set CAN error code to Bus-Off */ + errorcode |= DAL_CAN_ERROR_BOF; + + /* No need for clear of Error Bus-Off as read-only */ + } + + /* Check Last Error Code Flag */ + if (((interrupts & CAN_IT_LAST_ERROR_CODE) != 0U) && + ((esrflags & CAN_ERRSTS_LERRC) != 0U)) + { + switch (esrflags & CAN_ERRSTS_LERRC) + { + case (CAN_ERRSTS_LERRC_0): + /* Set CAN error code to Stuff error */ + errorcode |= DAL_CAN_ERROR_STF; + break; + case (CAN_ERRSTS_LERRC_1): + /* Set CAN error code to Form error */ + errorcode |= DAL_CAN_ERROR_FOR; + break; + case (CAN_ERRSTS_LERRC_1 | CAN_ERRSTS_LERRC_0): + /* Set CAN error code to Acknowledgement error */ + errorcode |= DAL_CAN_ERROR_ACK; + break; + case (CAN_ERRSTS_LERRC_2): + /* Set CAN error code to Bit recessive error */ + errorcode |= DAL_CAN_ERROR_BR; + break; + case (CAN_ERRSTS_LERRC_2 | CAN_ERRSTS_LERRC_0): + /* Set CAN error code to Bit Dominant error */ + errorcode |= DAL_CAN_ERROR_BD; + break; + case (CAN_ERRSTS_LERRC_2 | CAN_ERRSTS_LERRC_1): + /* Set CAN error code to CRC error */ + errorcode |= DAL_CAN_ERROR_CRC; + break; + default: + break; + } + + /* Clear Last error code Flag */ + CLEAR_BIT(hcan->Instance->ERRSTS, CAN_ERRSTS_LERRC); + } + } + + /* Clear ERRI Flag */ + __DAL_CAN_CLEAR_FLAG(hcan, CAN_FLAG_ERRI); + } + + /* Call the Error call Back in case of Errors */ + if (errorcode != DAL_CAN_ERROR_NONE) + { + /* Update error code in handle */ + hcan->ErrorCode |= errorcode; + + /* Call Error callback function */ +#if USE_DAL_CAN_REGISTER_CALLBACKS == 1 + /* Call registered callback*/ + hcan->ErrorCallback(hcan); +#else + /* Call weak (surcharged) callback */ + DAL_CAN_ErrorCallback(hcan); +#endif /* USE_DAL_CAN_REGISTER_CALLBACKS */ + } +} + +/** + * @} + */ + +/** @defgroup CAN_Exported_Functions_Group5 Callback functions + * @brief CAN Callback functions + * +@verbatim + ============================================================================== + ##### Callback functions ##### + ============================================================================== + [..] + This subsection provides the following callback functions: + (+) DAL_CAN_TxMailbox0CompleteCallback + (+) DAL_CAN_TxMailbox1CompleteCallback + (+) DAL_CAN_TxMailbox2CompleteCallback + (+) DAL_CAN_TxMailbox0AbortCallback + (+) DAL_CAN_TxMailbox1AbortCallback + (+) DAL_CAN_TxMailbox2AbortCallback + (+) DAL_CAN_RxFifo0MsgPendingCallback + (+) DAL_CAN_RxFifo0FullCallback + (+) DAL_CAN_RxFifo1MsgPendingCallback + (+) DAL_CAN_RxFifo1FullCallback + (+) DAL_CAN_SleepCallback + (+) DAL_CAN_WakeUpFromRxMsgCallback + (+) DAL_CAN_ErrorCallback + +@endverbatim + * @{ + */ + +/** + * @brief Transmission Mailbox 0 complete callback. + * @param hcan pointer to a CAN_HandleTypeDef structure that contains + * the configuration information for the specified CAN. + * @retval None + */ +__weak void DAL_CAN_TxMailbox0CompleteCallback(CAN_HandleTypeDef *hcan) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hcan); + + /* NOTE : This function Should not be modified, when the callback is needed, + the DAL_CAN_TxMailbox0CompleteCallback could be implemented in the + user file + */ +} + +/** + * @brief Transmission Mailbox 1 complete callback. + * @param hcan pointer to a CAN_HandleTypeDef structure that contains + * the configuration information for the specified CAN. + * @retval None + */ +__weak void DAL_CAN_TxMailbox1CompleteCallback(CAN_HandleTypeDef *hcan) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hcan); + + /* NOTE : This function Should not be modified, when the callback is needed, + the DAL_CAN_TxMailbox1CompleteCallback could be implemented in the + user file + */ +} + +/** + * @brief Transmission Mailbox 2 complete callback. + * @param hcan pointer to a CAN_HandleTypeDef structure that contains + * the configuration information for the specified CAN. + * @retval None + */ +__weak void DAL_CAN_TxMailbox2CompleteCallback(CAN_HandleTypeDef *hcan) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hcan); + + /* NOTE : This function Should not be modified, when the callback is needed, + the DAL_CAN_TxMailbox2CompleteCallback could be implemented in the + user file + */ +} + +/** + * @brief Transmission Mailbox 0 Cancellation callback. + * @param hcan pointer to an CAN_HandleTypeDef structure that contains + * the configuration information for the specified CAN. + * @retval None + */ +__weak void DAL_CAN_TxMailbox0AbortCallback(CAN_HandleTypeDef *hcan) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hcan); + + /* NOTE : This function Should not be modified, when the callback is needed, + the DAL_CAN_TxMailbox0AbortCallback could be implemented in the + user file + */ +} + +/** + * @brief Transmission Mailbox 1 Cancellation callback. + * @param hcan pointer to an CAN_HandleTypeDef structure that contains + * the configuration information for the specified CAN. + * @retval None + */ +__weak void DAL_CAN_TxMailbox1AbortCallback(CAN_HandleTypeDef *hcan) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hcan); + + /* NOTE : This function Should not be modified, when the callback is needed, + the DAL_CAN_TxMailbox1AbortCallback could be implemented in the + user file + */ +} + +/** + * @brief Transmission Mailbox 2 Cancellation callback. + * @param hcan pointer to an CAN_HandleTypeDef structure that contains + * the configuration information for the specified CAN. + * @retval None + */ +__weak void DAL_CAN_TxMailbox2AbortCallback(CAN_HandleTypeDef *hcan) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hcan); + + /* NOTE : This function Should not be modified, when the callback is needed, + the DAL_CAN_TxMailbox2AbortCallback could be implemented in the + user file + */ +} + +/** + * @brief Rx FIFO 0 message pending callback. + * @param hcan pointer to a CAN_HandleTypeDef structure that contains + * the configuration information for the specified CAN. + * @retval None + */ +__weak void DAL_CAN_RxFifo0MsgPendingCallback(CAN_HandleTypeDef *hcan) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hcan); + + /* NOTE : This function Should not be modified, when the callback is needed, + the DAL_CAN_RxFifo0MsgPendingCallback could be implemented in the + user file + */ +} + +/** + * @brief Rx FIFO 0 full callback. + * @param hcan pointer to a CAN_HandleTypeDef structure that contains + * the configuration information for the specified CAN. + * @retval None + */ +__weak void DAL_CAN_RxFifo0FullCallback(CAN_HandleTypeDef *hcan) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hcan); + + /* NOTE : This function Should not be modified, when the callback is needed, + the DAL_CAN_RxFifo0FullCallback could be implemented in the user + file + */ +} + +/** + * @brief Rx FIFO 1 message pending callback. + * @param hcan pointer to a CAN_HandleTypeDef structure that contains + * the configuration information for the specified CAN. + * @retval None + */ +__weak void DAL_CAN_RxFifo1MsgPendingCallback(CAN_HandleTypeDef *hcan) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hcan); + + /* NOTE : This function Should not be modified, when the callback is needed, + the DAL_CAN_RxFifo1MsgPendingCallback could be implemented in the + user file + */ +} + +/** + * @brief Rx FIFO 1 full callback. + * @param hcan pointer to a CAN_HandleTypeDef structure that contains + * the configuration information for the specified CAN. + * @retval None + */ +__weak void DAL_CAN_RxFifo1FullCallback(CAN_HandleTypeDef *hcan) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hcan); + + /* NOTE : This function Should not be modified, when the callback is needed, + the DAL_CAN_RxFifo1FullCallback could be implemented in the user + file + */ +} + +/** + * @brief Sleep callback. + * @param hcan pointer to a CAN_HandleTypeDef structure that contains + * the configuration information for the specified CAN. + * @retval None + */ +__weak void DAL_CAN_SleepCallback(CAN_HandleTypeDef *hcan) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hcan); + + /* NOTE : This function Should not be modified, when the callback is needed, + the DAL_CAN_SleepCallback could be implemented in the user file + */ +} + +/** + * @brief WakeUp from Rx message callback. + * @param hcan pointer to a CAN_HandleTypeDef structure that contains + * the configuration information for the specified CAN. + * @retval None + */ +__weak void DAL_CAN_WakeUpFromRxMsgCallback(CAN_HandleTypeDef *hcan) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hcan); + + /* NOTE : This function Should not be modified, when the callback is needed, + the DAL_CAN_WakeUpFromRxMsgCallback could be implemented in the + user file + */ +} + +/** + * @brief Error CAN callback. + * @param hcan pointer to a CAN_HandleTypeDef structure that contains + * the configuration information for the specified CAN. + * @retval None + */ +__weak void DAL_CAN_ErrorCallback(CAN_HandleTypeDef *hcan) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hcan); + + /* NOTE : This function Should not be modified, when the callback is needed, + the DAL_CAN_ErrorCallback could be implemented in the user file + */ +} + +/** + * @} + */ + +/** @defgroup CAN_Exported_Functions_Group6 Peripheral State and Error functions + * @brief CAN Peripheral State functions + * +@verbatim + ============================================================================== + ##### Peripheral State and Error functions ##### + ============================================================================== + [..] + This subsection provides functions allowing to : + (+) DAL_CAN_GetState() : Return the CAN state. + (+) DAL_CAN_GetError() : Return the CAN error codes if any. + (+) DAL_CAN_ResetError(): Reset the CAN error codes if any. + +@endverbatim + * @{ + */ + +/** + * @brief Return the CAN state. + * @param hcan pointer to a CAN_HandleTypeDef structure that contains + * the configuration information for the specified CAN. + * @retval DAL state + */ +DAL_CAN_StateTypeDef DAL_CAN_GetState(CAN_HandleTypeDef *hcan) +{ + DAL_CAN_StateTypeDef state = hcan->State; + + if ((state == DAL_CAN_STATE_READY) || + (state == DAL_CAN_STATE_LISTENING)) + { + /* Check sleep mode acknowledge flag */ + if ((hcan->Instance->MSTS & CAN_MSTS_SLEEPFLG) != 0U) + { + /* Sleep mode is active */ + state = DAL_CAN_STATE_SLEEP_ACTIVE; + } + /* Check sleep mode request flag */ + else if ((hcan->Instance->MCTRL & CAN_MCTRL_SLEEPREQ) != 0U) + { + /* Sleep mode request is pending */ + state = DAL_CAN_STATE_SLEEP_PENDING; + } + else + { + /* Neither sleep mode request nor sleep mode acknowledge */ + } + } + + /* Return CAN state */ + return state; +} + +/** + * @brief Return the CAN error code. + * @param hcan pointer to a CAN_HandleTypeDef structure that contains + * the configuration information for the specified CAN. + * @retval CAN Error Code + */ +uint32_t DAL_CAN_GetError(CAN_HandleTypeDef *hcan) +{ + /* Return CAN error code */ + return hcan->ErrorCode; +} + +/** + * @brief Reset the CAN error code. + * @param hcan pointer to a CAN_HandleTypeDef structure that contains + * the configuration information for the specified CAN. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_CAN_ResetError(CAN_HandleTypeDef *hcan) +{ + DAL_StatusTypeDef status = DAL_OK; + DAL_CAN_StateTypeDef state = hcan->State; + + if ((state == DAL_CAN_STATE_READY) || + (state == DAL_CAN_STATE_LISTENING)) + { + /* Reset CAN error code */ + hcan->ErrorCode = 0U; + } + else + { + /* Update error code */ + hcan->ErrorCode |= DAL_CAN_ERROR_NOT_INITIALIZED; + + status = DAL_ERROR; + } + + /* Return the status */ + return status; +} + +/** + * @} + */ + +/** + * @} + */ + +#endif /* DAL_CAN_MODULE_ENABLED */ + +/** + * @} + */ + +#endif /* CAN1 */ + +/** + * @} + */ diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_comp.c b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_comp.c new file mode 100644 index 0000000000..8fdb533f90 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_comp.c @@ -0,0 +1,843 @@ +/** + * + * @file apm32f4xx_dal_comp.c + * @brief COMP DAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the COMP peripheral: + * + Initialization and de-initialization functions + * + Peripheral Control functions + * + Peripheral State functions + * + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2017 STMicroelectronics. + * Copyright (C) 2023-2024 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + * + @verbatim + =============================================================================== + ##### COMP Peripheral features ##### + =============================================================================== + + [..] + The APM32F411xx integrates 2 analog comparators COMP1 and COMP2: + (#) The COMP input minus (inverting input) and input plus (non inverting input) + can be set to internal references or to GPIO pins + + (#) The COMP output is available using DAL_COMP_GetOutputLevel(). + + (#) The COMP output can be redirected to embedded timers (TMR1, TMR8, TMR2, TMR3, TMR4) + + (#) Paris of comparators instances can be combined in window mode. + + ##### How to use this driver ##### +=============================================================================== +[..] + This driver provides functions to configure and program the Comparators of + APM32F411xx devices. + + To use the comparator, perform the following steps: + + (#) Initialize the COMP low level resources by implementing the DAL_COMP_MspInit(): + (##) Enable the COMP interface clock using __DAL_RCC_SYSCFG_CLK_ENABLE() function. + (##) Configure the GPIO connected to comparator inputs plus and minus in analog mode + using DAL_GPIO_Init(). + + (#) Configuration the COMP peripheral using DAL_COMP_Init() function: + (##) Select the window mode (Available only on COMP1 instance) + (##) Select the speed mode (Available only on COMP2 instance) + (##) Select the input minus (inverting input) + (##) Select the input plus (non-inverting input) + (##) Select the output polarity + (##) Select the output redirection + + (#) Enable the comparator using DAL_COMP_Start() function + + (#) Use DAL_COMP_GetOutputLevel() function to get the output level (high or low). + + (#) Disable the comparator using DAL_COMP_Stop() function + + (#) De-initialize the comparator using DAL_COMP_DeInit() function. + + (#) For safety purpose, use DAL_COMP_Lock() function to lock the whole + configuration of the comparator unit and the CSTS registers. + Then, no further change of the comparator unit configuration can be done + until the next reset. + + (#) Reset the comparator only by system reset. + + (#) If needed, reinitialize the comparator using DAL_COMP_Init() function. + + *** Callback registration *** + ============================================= + [..] + + The compilation define USE_DAL_COMP_REGISTER_CALLBACKS when set to 1, + allows the user to configure dynamically the driver callbacks. + Use Functions @ref DAL_COMP_RegisterCallback() to register an callback. + [..] + + Function @ref DAL_COMP_RegisterCallback() allows to register following callbacks: + (+) MspInitCallback : COMP MspInit. + (+) MspDeInitCallback : COMP MspDeInit. + This function takes as parameters the DAL peripheral handle, the Callback ID + and a pointer to the user callback function. + [..] + + Use function @ref DAL_COMP_UnRegisterCallback() to reset a callback to the default + weak function. + [..] + + @ref DAL_COMP_UnRegisterCallback() takes as parameters the DAL peripheral handle, + and the Callback ID. + This function allows to reset following callbacks: + (+) MspInitCallback : COMP MspInit. + (+) MspDeInitCallback : COMP MspDeInit. + [..] + + By default, after the @ref DAL_COMP_Init() and if the state is DAL_COMP_STATE_RESET + all callbacks are reset to the corresponding legacy weak functions. + Exception done for MspInit and MspDeInit functions that are respectively + reset to the legacy weak functions in the @ref DAL_COMP_Init() and @ref DAL_COMP_DeInit() only when + these callbacks are null (not registered beforehand). + [..] + + If MspInit or MspDeInit are not null, the @ref DAL_COMP_Init() and @ref DAL_COMP_DeInit() + keep and use the user MspInit/MspDeInit callbacks (registered beforehand) whatever the state. + [..] + + Callbacks can be registered/unregistered in DAL_COMP_STATE_READY state only. + Exception done MspInit/MspDeInit functions that can be registered/unregistered + in DAL_COMP_STATE_READY or DAL_COMP_STATE_RESET state, + thus registered (user) MspInit/DeInit callbacks can be used during the Init/DeInit. + [..] + + Then, the user first registers the MspInit/MspDeInit user callbacks + using @ref DAL_COMP_RegisterCallback() before calling @ref DAL_COMP_DeInit() + or @ref DAL_COMP_Init() function. + [..] + + When the compilation define USE_DAL_COMP_REGISTER_CALLBACKS is set to 0 or + not defined, the callback registration feature is not available and all callbacks + are set to the corresponding legacy weak functions. + + @endverbatim + ****************************************************************************** + + Table 1. COMP inputs for APM32F411xx devices + +---------------------------------------------------------+ + | | | COMP1 | COMP2 | + |----------------|----------------|-----------|-----------| + | | | PC0 | PC2 | + | Input Plus | GPIO | PC2 | PC2 | + | | | | | + |----------------|----------------|-----------|-----------| + | | VREFINT | Available | Available | + | | PC1 | Available | | + | | PC3 | | Available | + | Input Minus | 1/4 VREFINT | | Available | + | | 1/2 VREFINT | | Available | + | | 3/4 VREFINT | | Available | + | | | | | + +---------------------------------------------------------+ + | | TMR1 BK IN | Available | Available | + | | TMR1 IC1 | Available | Available | + | | TMR1 ETRF | Available | Available | + | | TMR8 BK IN | Available | Available | + | | TMR8 IC1 | Available | Available | + | Output | TMR8 ETRF | Available | Available | + | | TMR2 IC4 | Available | Available | + | | TMR2 ETRF | Available | Available | + | | TMR3 IC1 | Available | Available | + | | TMR3 ETRF | Available | Available | + | | TMR4 IC1 | Available | Available | + | | | | | + +---------------------------------------------------------+ + + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @defgroup COMP COMP + * @brief COMP DAL driver modules + * @{ + */ + +#ifdef DAL_COMP_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/** @defgroup COMP_Private_Constants COMP Private Constants + * @{ + */ + +/* Delay for COMP startup time. */ +#define COMP_DELAY_STARTUP_US (80UL) /*!< Delay for COMP startup time. */ + +/** + * @} + */ + +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Exported functions --------------------------------------------------------*/ + +/** @defgroup COMP_Exported_Functions COMP Exported Functions + * @{ + */ + +/** @defgroup COMP_Exported_Functions_Group1 Initialization and de-initialization functions + * @brief Initialization and Configuration functions + * + * @verbatim + * =============================================================================== + * ##### Initialization and Configuration functions ##### + * =============================================================================== + * [..] This section provides functions allowing to: + * (+) Initialize and configure the COMP. + * (+) De-initialize the COMP. + * + * @endverbatim + * @{ + */ + +/** + * @brief Initialize the COMP according to the specified parameters + * in the COMP_InitTypeDef and initialize the associated handle. + * @note If the selected comparator is locked, initialization cannot be performed. + * To unlock the configuration, perform a system reset. + * @param hcomp COMP handle + * @retval DAL status + */ +DAL_StatusTypeDef DAL_COMP_Init(COMP_HandleTypeDef *hcomp) +{ + DAL_StatusTypeDef status = DAL_OK; + uint32_t temp; + + /* Check the COMP handle allocation */ + if (hcomp == NULL) + { + status = DAL_ERROR; + } + else if (__DAL_COMP_IS_LOCKED(hcomp)) + { + status = DAL_ERROR; + } + else + { + /* Check the parameters */ + ASSERT_PARAM(IS_COMP_ALL_INSTANCE(hcomp->Instance)); + if (hcomp->Instance == COMP1) + { + ASSERT_PARAM(IS_COMP_WINDOWMODE(hcomp->Init.WindowMode)); + ASSERT_PARAM(IS_COMP1_INVERTINGINPUT(hcomp->Init.InvertingInput)); + } + else + { + ASSERT_PARAM(IS_COMP_SPEEDMODE(hcomp->Init.SpeedMode)); + ASSERT_PARAM(IS_COMP2_INVERTINGINPUT(hcomp->Init.InvertingInput)); + ASSERT_PARAM(IS_COMP_NONINVERTINGINPUT(hcomp->Init.NonInvertingInput)); + } + ASSERT_PARAM(IS_COMP_OUTPUT(hcomp->Init.Output)); + ASSERT_PARAM(IS_COMP_OUTPUTPOL(hcomp->Init.OutputPol)); + + if (hcomp->State == DAL_COMP_STATE_RESET) + { + /* Allocate lock resource and initialize it */ + hcomp->Lock = DAL_UNLOCKED; + + /* Set COMP error code to none */ + COMP_CLEAR_ERRORCODE(hcomp); + +#if (USE_DAL_COMP_REGISTER_CALLBACKS == 1) + /* Init the COMP Callback settings */ + if (hcomp->MspInitCallback == NULL) + { + hcomp->MspInitCallback = DAL_COMP_MspInit; /* Legacy weak MspInit */ + } + + /* Init the low level hardware */ + hcomp->MspInitCallback(hcomp); +#else + /* Init the low level hardware */ + DAL_COMP_MspInit(hcomp); +#endif /* USE_DAL_COMP_REGISTER_CALLBACKS */ + } + + /* Set COMP1 parameters */ + if (hcomp->Instance == COMP1) + { + temp = (hcomp->Init.WindowMode | \ + hcomp->Init.InvertingInput | \ + hcomp->Init.OutputPol | \ + hcomp->Init.Output); + + /* Set parameters in COMP_CSTS register */ + MODIFY_REG(hcomp->Instance->CSTS, + COMP_CSTS_WMODESEL | COMP_CSTS_INMCCFG | COMP_CSTS_POLCFG | COMP_CSTS_OUTSEL, + temp); + } + /* Set COMP2 parameters */ + else + { + temp = (hcomp->Init.Mode | \ + hcomp->Init.InvertingInput | \ + hcomp->Init.NonInvertingInput | \ + hcomp->Init.OutputPol | \ + hcomp->Init.Output); + + /* Set parameters in COMP_CSTS register */ + MODIFY_REG(hcomp->Instance->CSTS, + COMP_CSTS_SPEEDM | COMP_CSTS_INMCCFG | COMP_CSTS_INPCCFG | COMP_CSTS_POLCFG | COMP_CSTS_OUTSEL, + temp); + } + + /* Set DAL COMP handle state */ + if (hcomp->State == DAL_COMP_STATE_RESET) + { + hcomp->State = DAL_COMP_STATE_READY; + } + } + + return status; +} + +/** + * @brief DeInitialize the COMP peripheral. + * @param hcomp COMP handle + * @retval DAL status + */ +DAL_StatusTypeDef DAL_COMP_DeInit(COMP_HandleTypeDef *hcomp) +{ + DAL_StatusTypeDef status = DAL_OK; + + /* Check the COMP handle allocation */ + if (hcomp == NULL) + { + status = DAL_ERROR; + } + else if (__DAL_COMP_IS_LOCKED(hcomp)) + { + status = DAL_ERROR; + } + else + { + /* Check the parameters */ + ASSERT_PARAM(IS_COMP_ALL_INSTANCE(hcomp->Instance)); + + /* Set COMP_CSTS register to reset value */ + WRITE_REG(hcomp->Instance->CSTS, 0x00000000UL); + +#if (USE_DAL_COMP_REGISTER_CALLBACKS == 1) + if (hcomp->MspDeInitCallback == NULL) + { + hcomp->MspDeInitCallback = DAL_COMP_MspDeInit; /* Legacy weak MspDeInit */ + } + + /* DeInit the low level hardware */ + hcomp->MspDeInitCallback(hcomp); +#else + /* DeInit the low level hardware */ + DAL_COMP_MspDeInit(hcomp); +#endif /* USE_DAL_COMP_REGISTER_CALLBACKS */ + + /* Set DAL COMP handle state */ + hcomp->State = DAL_COMP_STATE_RESET; + + /* Release Lock */ + __DAL_UNLOCK(hcomp); + } + + return status; +} + +/** + * @brief Initialize the COMP MSP. + * @param hcomp COMP handle + * @retval None + */ +__WEAK void DAL_COMP_MspInit(COMP_HandleTypeDef *hcomp) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hcomp); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_COMP_MspInit could be implemented in the user file + */ +} + +/** + * @brief DeInitialize COMP MSP. + * @param hcomp COMP handle + * @retval None + */ +__WEAK void DAL_COMP_MspDeInit(COMP_HandleTypeDef *hcomp) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hcomp); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_COMP_MspDeInit could be implemented in the user file + */ +} + +#if (USE_DAL_COMP_REGISTER_CALLBACKS == 1) +/** + * @brief Register a User COMP Callback + * To be used instead of the weak predefined callback + * @param hcomp COMP handle + * @param CallbackID ID of the callback to be registered + * This parameter can be one of the following values: + * @arg @ref DAL_COMP_MSPINIT_CB_ID COMP MspInit callback ID + * @arg @ref DAL_COMP_MSPDEINIT_CB_ID COMP MspDeInit callback ID + * @param pCallback pointer to the Callback function + * @retval DAL status + */ +DAL_StatusTypeDef DAL_COMP_RegisterCallback(COMP_HandleTypeDef *hcomp, DAL_COMP_CallbackIDTypeDef CallbackID, pCOMP_CallbackTypeDef pCallback) +{ + DAL_StatusTypeDef status = DAL_OK; + + if (pCallback == NULL) + { + /* Update the error code */ + hcomp->ErrorCode |= DAL_COMP_ERROR_INVALID_CALLBACK; + + return DAL_ERROR; + } + + if (DAL_COMP_STATE_READY == hcomp->State) + { + switch (CallbackID) + { + case DAL_COMP_MSPINIT_CB_ID: + hcomp->MspInitCallback = pCallback; + break; + + case DAL_COMP_MSPDEINIT_CB_ID: + hcomp->MspDeInitCallback = pCallback; + break; + + default: + /* Update the error code */ + hcomp->ErrorCode |= DAL_COMP_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = DAL_ERROR; + break; + } + } + else if (DAL_COMP_STATE_RESET == hcomp->State) + { + switch (CallbackID) + { + case DAL_COMP_MSPINIT_CB_ID: + hcomp->MspInitCallback = pCallback; + break; + + case DAL_COMP_MSPDEINIT_CB_ID: + hcomp->MspDeInitCallback = pCallback; + break; + + default: + /* Update the error code */ + hcomp->ErrorCode |= DAL_COMP_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = DAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + hcomp->ErrorCode |= DAL_COMP_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = DAL_ERROR; + } + + return status; +} + +/** + * @brief Unregister an COMP Callback + * COMP callback is redirected to the weak predefined callback + * @param hcomp COMP handle + * @param CallbackID ID of the callback to be unregistered + * This parameter can be one of the following values: + * @arg @ref DAL_COMP_MSPINIT_CB_ID COMP MspInit callback ID + * @arg @ref DAL_COMP_MSPDEINIT_CB_ID COMP MspDeInit callback ID + * @retval DAL status + */ +DAL_StatusTypeDef DAL_COMP_UnRegisterCallback(COMP_HandleTypeDef *hcomp, DAL_COMP_CallbackIDTypeDef CallbackID) +{ + DAL_StatusTypeDef status = DAL_OK; + + if (DAL_COMP_STATE_READY == hcomp->State) + { + switch (CallbackID) + { + case DAL_COMP_MSPINIT_CB_ID: + hcomp->MspInitCallback = DAL_COMP_MspInit; /* Legacy weak MspInit */ + break; + + case DAL_COMP_MSPDEINIT_CB_ID: + hcomp->MspDeInitCallback = DAL_COMP_MspDeInit; /* Legacy weak MspDeInit */ + break; + + default: + /* Update the error code */ + hcomp->ErrorCode |= DAL_COMP_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = DAL_ERROR; + break; + } + } + else if (DAL_COMP_STATE_RESET == hcomp->State) + { + switch (CallbackID) + { + case DAL_COMP_MSPINIT_CB_ID: + hcomp->MspInitCallback = DAL_COMP_MspInit; /* Legacy weak MspInit */ + break; + + case DAL_COMP_MSPDEINIT_CB_ID: + hcomp->MspDeInitCallback = DAL_COMP_MspDeInit; /* Legacy weak MspDeInit */ + break; + + default: + /* Update the error code */ + hcomp->ErrorCode |= DAL_COMP_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = DAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + hcomp->ErrorCode |= DAL_COMP_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = DAL_ERROR; + } + + return status; +} + +#endif /* USE_DAL_COMP_REGISTER_CALLBACKS */ +/** + * @} + */ + +/** @defgroup COMP_Exported_Functions_Group2 Start-Stop operation functions + * @brief Start-Stop operation functions. + * + * @verbatim + * =============================================================================== + * ##### IO operation functions ##### + * =============================================================================== + * [..] This section provides functions allowing to: + * (+) Start the comparator. + * (+) Stop the comparator. + * + * @endverbatim + * @{ + */ + +/** + * @brief Start the comparator. + * @param hcomp COMP handle + * @retval DAL status + */ +DAL_StatusTypeDef DAL_COMP_Start(COMP_HandleTypeDef *hcomp) +{ + DAL_StatusTypeDef status = DAL_OK; + uint32_t time_delay = 0UL; + + /* Check the COMP handle allocation */ + if (hcomp == NULL) + { + status = DAL_ERROR; + } + else if (__DAL_COMP_IS_LOCKED(hcomp)) + { + status = DAL_ERROR; + } + else + { + /* Check the parameters */ + ASSERT_PARAM(IS_COMP_ALL_INSTANCE(hcomp->Instance)); + + if (hcomp->State == DAL_COMP_STATE_READY) + { + /* Enable the selected comparator */ + SET_BIT(hcomp->Instance->CSTS, COMP_CSTS_EN); + + /* Set COMP state */ + hcomp->State = DAL_COMP_STATE_BUSY; + + /* Delay for COMP startup time */ + time_delay = ((COMP_DELAY_STARTUP_US / 10UL) * ((SystemCoreClock / (1000000UL * 2UL)) + 1UL)); + while (time_delay != 0UL) + { + time_delay--; + } + } + else + { + status = DAL_ERROR; + } + } + + return status; +} + +/** + * @brief Stop the comparator. + * @param hcomp COMP handle + * @retval DAL status + */ +DAL_StatusTypeDef DAL_COMP_Stop(COMP_HandleTypeDef *hcomp) +{ + DAL_StatusTypeDef status = DAL_OK; + + /* Check the COMP handle allocation */ + if (hcomp == NULL) + { + status = DAL_ERROR; + } + else if (__DAL_COMP_IS_LOCKED(hcomp)) + { + status = DAL_ERROR; + } + else + { + /* Check the parameters */ + ASSERT_PARAM(IS_COMP_ALL_INSTANCE(hcomp->Instance)); + + if (hcomp->State == DAL_COMP_STATE_RESET) + { + /* Disable the selected comparator */ + CLEAR_BIT(hcomp->Instance->CSTS, COMP_CSTS_EN); + + /* Set COMP state */ + hcomp->State = DAL_COMP_STATE_READY; + } + else + { + status = DAL_ERROR; + } + } + + return status; +} + +/** + * @} + */ + +/** @defgroup COMP_Exported_Functions_Group3 Peripheral Control functions + * @brief Peripheral Control functions + * + * @verbatim + * =============================================================================== + * ##### Peripheral Control functions ##### + * =============================================================================== + * [..] This section provides functions allowing to: + * (+) Lock the selected comparator configuration. + * + * @endverbatim + * @{ + */ + +/** + * @brief Lock the selected comparator configuration. + * @note A system reset is required to unlock the comparator configuration. + * @param hcomp COMP handle + * @retval DAL status + */ +DAL_StatusTypeDef DAL_COMP_Lock(COMP_HandleTypeDef *hcomp) +{ + DAL_StatusTypeDef status = DAL_OK; + + /* Check the COMP handle allocation */ + if (hcomp == NULL) + { + status = DAL_ERROR; + } + else if (__DAL_COMP_IS_LOCKED(hcomp)) + { + status = DAL_ERROR; + } + else + { + /* Check the parameters */ + ASSERT_PARAM(IS_COMP_ALL_INSTANCE(hcomp->Instance)); + + /* Set lock flag on state */ + switch(hcomp->State) + { + case DAL_COMP_STATE_READY: + hcomp->State = DAL_COMP_STATE_READY_LOCKED; + break; + + case DAL_COMP_STATE_RESET: + hcomp->State = DAL_COMP_STATE_RESET_LOCKED; + break; + + default: + hcomp->State = DAL_COMP_STATE_BUSY_LOCKED; + break; + } + } + + if (status == DAL_OK) + { + /* Set lock flag on handle */ + __DAL_COMP_LOCK(hcomp); + } + + return status; +} + +/** + * @brief Return the output level (high or low) of the selected comparator. + * @param hcomp COMP handle + * @retval Returns the selected comparator output level: + * @note The output level depends on the selected polarity. + * If the polarity is not inverted: + * - Comparator output is low when the non-inverting input is at a lower + * voltage than the inverting input + * - Comparator output is high when the non-inverting input is at a higher + * voltage than the inverting input + * If the polarity is inverted: + * - Comparator output is high when the non-inverting input is at a lower + * voltage than the inverting input + * - Comparator output is low when the non-inverting input is at a higher + * voltage than the inverting input + */ +uint32_t DAL_COMP_GetOutputLevel(COMP_HandleTypeDef *hcomp) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_COMP_ALL_INSTANCE(hcomp->Instance)); + + /* Return the selected comparator output level */ + return (uint32_t)(READ_BIT(hcomp->Instance->CSTS, COMP_CSTS_OUTVAL)); +} + +/** + * @} + */ + +/** @defgroup COMP_Exported_Functions_Group4 Peripheral State functions + * @brief Peripheral State functions + * + * @verbatim + * =============================================================================== + * ##### Peripheral State functions ##### + * =============================================================================== + * [..] This section provides functions allowing to: + * + * @endverbatim + * @{ + */ + +/** + * @brief Return the COMP state. + * @param hcomp COMP handle + * @retval DAL state + */ +DAL_COMP_StateTypeDef DAL_COMP_GetState(COMP_HandleTypeDef *hcomp) +{ + /* Check the COMP handle allocation */ + if (hcomp == NULL) + { + return DAL_COMP_STATE_RESET; + } + + /* Check the parameter */ + ASSERT_PARAM(IS_COMP_ALL_INSTANCE(hcomp->Instance)); + + /* Return DAL COMP state */ + return hcomp->State; +} + +/** + * @brief Return the COMP error code. + * @param hcomp COMP handle + * @retval COMP error code + */ +uint32_t DAL_COMP_GetError(COMP_HandleTypeDef *hcomp) +{ + /* Check the COMP handle allocation */ + if (hcomp == NULL) + { + return 0UL; + } + + /* Check the parameter */ + ASSERT_PARAM(IS_COMP_ALL_INSTANCE(hcomp->Instance)); + + /* Return DAL COMP error code */ + return hcomp->ErrorCode; +} + +/** + * @} + */ + +/** + * @} + */ + +#endif /* DAL_COMP_MODULE_ENABLED */ + +/** + * @} + */ + +/** + * @} + */ + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_cortex.c b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_cortex.c new file mode 100644 index 0000000000..edbe098b2b --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_cortex.c @@ -0,0 +1,527 @@ +/** + * + * @file apm32f4xx_dal_cortex.c + * @brief CORTEX DAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the CORTEX: + * + Initialization and de-initialization functions + * + Peripheral Control functions + * + @verbatim + ============================================================================== + ##### How to use this driver ##### + ============================================================================== + + [..] + *** How to configure Interrupts using CORTEX DAL driver *** + =========================================================== + [..] + This section provides functions allowing to configure the NVIC interrupts (IRQ). + The Cortex-M4 exceptions are managed by CMSIS functions. + + (#) Configure the NVIC Priority Grouping using DAL_NVIC_SetPriorityGrouping() + function according to the following table. + (#) Configure the priority of the selected IRQ Channels using DAL_NVIC_SetPriority(). + (#) Enable the selected IRQ Channels using DAL_NVIC_EnableIRQ(). + (#) please refer to programming manual for details in how to configure priority. + + -@- When the NVIC_PRIORITYGROUP_0 is selected, IRQ preemption is no more possible. + The pending IRQ priority will be managed only by the sub priority. + + -@- IRQ priority order (sorted by highest to lowest priority): + (+@) Lowest preemption priority + (+@) Lowest sub priority + (+@) Lowest hardware priority (IRQ number) + + [..] + *** How to configure Systick using CORTEX DAL driver *** + ======================================================== + [..] + Setup SysTick Timer for time base. + + (+) The DAL_SYSTICK_Config() function calls the SysTick_Config() function which + is a CMSIS function that: + (++) Configures the SysTick Reload register with value passed as function parameter. + (++) Configures the SysTick IRQ priority to the lowest value 0x0F. + (++) Resets the SysTick Counter register. + (++) Configures the SysTick Counter clock source to be Core Clock Source (HCLK). + (++) Enables the SysTick Interrupt. + (++) Starts the SysTick Counter. + + (+) You can change the SysTick Clock source to be HCLK_Div8 by calling the macro + __DAL_CORTEX_SYSTICKCLK_CONFIG(SYSTICK_CLKSOURCE_HCLK_DIV8) just after the + DAL_SYSTICK_Config() function call. The __DAL_CORTEX_SYSTICKCLK_CONFIG() macro is defined + inside the apm32f4xx_dal_cortex.h file. + + (+) You can change the SysTick IRQ priority by calling the + DAL_NVIC_SetPriority(SysTick_IRQn,...) function just after the DAL_SYSTICK_Config() function + call. The DAL_NVIC_SetPriority() call the NVIC_SetPriority() function which is a CMSIS function. + + (+) To adjust the SysTick time base, use the following formula: + + Reload Value = SysTick Counter Clock (Hz) x Desired Time base (s) + (++) Reload Value is the parameter to be passed for DAL_SYSTICK_Config() function + (++) Reload Value should not exceed 0xFFFFFF + + @endverbatim + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2017 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file in + * the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + */ + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @defgroup CORTEX CORTEX + * @brief CORTEX DAL module driver + * @{ + */ + +#ifdef DAL_CORTEX_MODULE_ENABLED + +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/* Private macros ------------------------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ +/* Exported functions --------------------------------------------------------*/ + +/** @defgroup CORTEX_Exported_Functions CORTEX Exported Functions + * @{ + */ + + +/** @defgroup CORTEX_Exported_Functions_Group1 Initialization and de-initialization functions + * @brief Initialization and Configuration functions + * +@verbatim + ============================================================================== + ##### Initialization and de-initialization functions ##### + ============================================================================== + [..] + This section provides the CORTEX DAL driver functions allowing to configure Interrupts + Systick functionalities + +@endverbatim + * @{ + */ + + +/** + * @brief Sets the priority grouping field (preemption priority and subpriority) + * using the required unlock sequence. + * @param PriorityGroup The priority grouping bits length. + * This parameter can be one of the following values: + * @arg NVIC_PRIORITYGROUP_0: 0 bits for preemption priority + * 4 bits for subpriority + * @arg NVIC_PRIORITYGROUP_1: 1 bits for preemption priority + * 3 bits for subpriority + * @arg NVIC_PRIORITYGROUP_2: 2 bits for preemption priority + * 2 bits for subpriority + * @arg NVIC_PRIORITYGROUP_3: 3 bits for preemption priority + * 1 bits for subpriority + * @arg NVIC_PRIORITYGROUP_4: 4 bits for preemption priority + * 0 bits for subpriority + * @note When the NVIC_PriorityGroup_0 is selected, IRQ preemption is no more possible. + * The pending IRQ priority will be managed only by the subpriority. + * @retval None + */ +void DAL_NVIC_SetPriorityGrouping(uint32_t PriorityGroup) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_NVIC_PRIORITY_GROUP(PriorityGroup)); + + /* Set the PRIGROUP[10:8] bits according to the PriorityGroup parameter value */ + NVIC_SetPriorityGrouping(PriorityGroup); +} + +/** + * @brief Sets the priority of an interrupt. + * @param IRQn External interrupt number. + * This parameter can be an enumerator of IRQn_Type enumeration + * (For the complete APM32 Devices IRQ Channels list, please refer to the appropriate CMSIS device file (apm32f4xxxx.h)) + * @param PreemptPriority The preemption priority for the IRQn channel. + * This parameter can be a value between 0 and 15 + * A lower priority value indicates a higher priority + * @param SubPriority the subpriority level for the IRQ channel. + * This parameter can be a value between 0 and 15 + * A lower priority value indicates a higher priority. + * @retval None + */ +void DAL_NVIC_SetPriority(IRQn_Type IRQn, uint32_t PreemptPriority, uint32_t SubPriority) +{ + uint32_t prioritygroup = 0x00U; + + /* Check the parameters */ + ASSERT_PARAM(IS_NVIC_SUB_PRIORITY(SubPriority)); + ASSERT_PARAM(IS_NVIC_PREEMPTION_PRIORITY(PreemptPriority)); + + prioritygroup = NVIC_GetPriorityGrouping(); + + NVIC_SetPriority(IRQn, NVIC_EncodePriority(prioritygroup, PreemptPriority, SubPriority)); +} + +/** + * @brief Enables a device specific interrupt in the NVIC interrupt controller. + * @note To configure interrupts priority correctly, the NVIC_PriorityGroupConfig() + * function should be called before. + * @param IRQn External interrupt number. + * This parameter can be an enumerator of IRQn_Type enumeration + * (For the complete APM32 Devices IRQ Channels list, please refer to the appropriate CMSIS device file (apm32f4xxxx.h)) + * @retval None + */ +void DAL_NVIC_EnableIRQ(IRQn_Type IRQn) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_NVIC_DEVICE_IRQ(IRQn)); + + /* Enable interrupt */ + NVIC_EnableIRQ(IRQn); +} + +/** + * @brief Disables a device specific interrupt in the NVIC interrupt controller. + * @param IRQn External interrupt number. + * This parameter can be an enumerator of IRQn_Type enumeration + * (For the complete APM32 Devices IRQ Channels list, please refer to the appropriate CMSIS device file (apm32f4xxxx.h)) + * @retval None + */ +void DAL_NVIC_DisableIRQ(IRQn_Type IRQn) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_NVIC_DEVICE_IRQ(IRQn)); + + /* Disable interrupt */ + NVIC_DisableIRQ(IRQn); +} + +/** + * @brief Initiates a system reset request to reset the MCU. + * @retval None + */ +void DAL_NVIC_SystemReset(void) +{ + /* System Reset */ + NVIC_SystemReset(); +} + +/** + * @brief Initializes the System Timer and its interrupt, and starts the System Tick Timer. + * Counter is in free running mode to generate periodic interrupts. + * @param TicksNumb Specifies the ticks Number of ticks between two interrupts. + * @retval status: - 0 Function succeeded. + * - 1 Function failed. + */ +uint32_t DAL_SYSTICK_Config(uint32_t TicksNumb) +{ + return SysTick_Config(TicksNumb); +} +/** + * @} + */ + +/** @defgroup CORTEX_Exported_Functions_Group2 Peripheral Control functions + * @brief Cortex control functions + * +@verbatim + ============================================================================== + ##### Peripheral Control functions ##### + ============================================================================== + [..] + This subsection provides a set of functions allowing to control the CORTEX + (NVIC, SYSTICK, MPU) functionalities. + + +@endverbatim + * @{ + */ + +#if (__MPU_PRESENT == 1U) +/** + * @brief Disables the MPU + * @retval None + */ +void DAL_MPU_Disable(void) +{ + /* Make sure outstanding transfers are done */ + __DMB(); + + /* Disable fault exceptions */ + SCB->SHCSR &= ~SCB_SHCSR_MEMFAULTENA_Msk; + + /* Disable the MPU and clear the control register*/ + MPU->CTRL = 0U; +} + +/** + * @brief Enable the MPU. + * @param MPU_Control Specifies the control mode of the MPU during hard fault, + * NMI, FAULTMASK and privileged access to the default memory + * This parameter can be one of the following values: + * @arg MPU_HFNMI_PRIVDEF_NONE + * @arg MPU_HARDFAULT_NMI + * @arg MPU_PRIVILEGED_DEFAULT + * @arg MPU_HFNMI_PRIVDEF + * @retval None + */ +void DAL_MPU_Enable(uint32_t MPU_Control) +{ + /* Enable the MPU */ + MPU->CTRL = MPU_Control | MPU_CTRL_ENABLE_Msk; + + /* Enable fault exceptions */ + SCB->SHCSR |= SCB_SHCSR_MEMFAULTENA_Msk; + + /* Ensure MPU setting take effects */ + __DSB(); + __ISB(); +} + +/** + * @brief Initializes and configures the Region and the memory to be protected. + * @param MPU_Init Pointer to a MPU_Region_InitTypeDef structure that contains + * the initialization and configuration information. + * @retval None + */ +void DAL_MPU_ConfigRegion(MPU_Region_InitTypeDef *MPU_Init) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_MPU_REGION_NUMBER(MPU_Init->Number)); + ASSERT_PARAM(IS_MPU_REGION_ENABLE(MPU_Init->Enable)); + + /* Set the Region number */ + MPU->RNR = MPU_Init->Number; + + if ((MPU_Init->Enable) != RESET) + { + /* Check the parameters */ + ASSERT_PARAM(IS_MPU_INSTRUCTION_ACCESS(MPU_Init->DisableExec)); + ASSERT_PARAM(IS_MPU_REGION_PERMISSION_ATTRIBUTE(MPU_Init->AccessPermission)); + ASSERT_PARAM(IS_MPU_TEX_LEVEL(MPU_Init->TypeExtField)); + ASSERT_PARAM(IS_MPU_ACCESS_SHAREABLE(MPU_Init->IsShareable)); + ASSERT_PARAM(IS_MPU_ACCESS_CACHEABLE(MPU_Init->IsCacheable)); + ASSERT_PARAM(IS_MPU_ACCESS_BUFFERABLE(MPU_Init->IsBufferable)); + ASSERT_PARAM(IS_MPU_SUB_REGION_DISABLE(MPU_Init->SubRegionDisable)); + ASSERT_PARAM(IS_MPU_REGION_SIZE(MPU_Init->Size)); + + MPU->RBAR = MPU_Init->BaseAddress; + MPU->RASR = ((uint32_t)MPU_Init->DisableExec << MPU_RASR_XN_Pos) | + ((uint32_t)MPU_Init->AccessPermission << MPU_RASR_AP_Pos) | + ((uint32_t)MPU_Init->TypeExtField << MPU_RASR_TEX_Pos) | + ((uint32_t)MPU_Init->IsShareable << MPU_RASR_S_Pos) | + ((uint32_t)MPU_Init->IsCacheable << MPU_RASR_C_Pos) | + ((uint32_t)MPU_Init->IsBufferable << MPU_RASR_B_Pos) | + ((uint32_t)MPU_Init->SubRegionDisable << MPU_RASR_SRD_Pos) | + ((uint32_t)MPU_Init->Size << MPU_RASR_SIZE_Pos) | + ((uint32_t)MPU_Init->Enable << MPU_RASR_ENABLE_Pos); + } + else + { + MPU->RBAR = 0x00U; + MPU->RASR = 0x00U; + } +} +#endif /* __MPU_PRESENT */ + +/** + * @brief Gets the priority grouping field from the NVIC Interrupt Controller. + * @retval Priority grouping field (SCB->AIRCR [10:8] PRIGROUP field) + */ +uint32_t DAL_NVIC_GetPriorityGrouping(void) +{ + /* Get the PRIGROUP[10:8] field value */ + return NVIC_GetPriorityGrouping(); +} + +/** + * @brief Gets the priority of an interrupt. + * @param IRQn External interrupt number. + * This parameter can be an enumerator of IRQn_Type enumeration + * (For the complete APM32 Devices IRQ Channels list, please refer to the appropriate CMSIS device file (apm32f4xxxx.h)) + * @param PriorityGroup the priority grouping bits length. + * This parameter can be one of the following values: + * @arg NVIC_PRIORITYGROUP_0: 0 bits for preemption priority + * 4 bits for subpriority + * @arg NVIC_PRIORITYGROUP_1: 1 bits for preemption priority + * 3 bits for subpriority + * @arg NVIC_PRIORITYGROUP_2: 2 bits for preemption priority + * 2 bits for subpriority + * @arg NVIC_PRIORITYGROUP_3: 3 bits for preemption priority + * 1 bits for subpriority + * @arg NVIC_PRIORITYGROUP_4: 4 bits for preemption priority + * 0 bits for subpriority + * @param pPreemptPriority Pointer on the Preemptive priority value (starting from 0). + * @param pSubPriority Pointer on the Subpriority value (starting from 0). + * @retval None + */ +void DAL_NVIC_GetPriority(IRQn_Type IRQn, uint32_t PriorityGroup, uint32_t *pPreemptPriority, uint32_t *pSubPriority) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_NVIC_PRIORITY_GROUP(PriorityGroup)); + /* Get priority for Cortex-M system or device specific interrupts */ + NVIC_DecodePriority(NVIC_GetPriority(IRQn), PriorityGroup, pPreemptPriority, pSubPriority); +} + +/** + * @brief Sets Pending bit of an external interrupt. + * @param IRQn External interrupt number + * This parameter can be an enumerator of IRQn_Type enumeration + * (For the complete APM32 Devices IRQ Channels list, please refer to the appropriate CMSIS device file (apm32f4xxxx.h)) + * @retval None + */ +void DAL_NVIC_SetPendingIRQ(IRQn_Type IRQn) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_NVIC_DEVICE_IRQ(IRQn)); + + /* Set interrupt pending */ + NVIC_SetPendingIRQ(IRQn); +} + +/** + * @brief Gets Pending Interrupt (reads the pending register in the NVIC + * and returns the pending bit for the specified interrupt). + * @param IRQn External interrupt number. + * This parameter can be an enumerator of IRQn_Type enumeration + * (For the complete APM32 Devices IRQ Channels list, please refer to the appropriate CMSIS device file (apm32f4xxxx.h)) + * @retval status: - 0 Interrupt status is not pending. + * - 1 Interrupt status is pending. + */ +uint32_t DAL_NVIC_GetPendingIRQ(IRQn_Type IRQn) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_NVIC_DEVICE_IRQ(IRQn)); + + /* Return 1 if pending else 0 */ + return NVIC_GetPendingIRQ(IRQn); +} + +/** + * @brief Clears the pending bit of an external interrupt. + * @param IRQn External interrupt number. + * This parameter can be an enumerator of IRQn_Type enumeration + * (For the complete APM32 Devices IRQ Channels list, please refer to the appropriate CMSIS device file (apm32f4xxxx.h)) + * @retval None + */ +void DAL_NVIC_ClearPendingIRQ(IRQn_Type IRQn) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_NVIC_DEVICE_IRQ(IRQn)); + + /* Clear pending interrupt */ + NVIC_ClearPendingIRQ(IRQn); +} + +/** + * @brief Gets active interrupt ( reads the active register in NVIC and returns the active bit). + * @param IRQn External interrupt number + * This parameter can be an enumerator of IRQn_Type enumeration + * (For the complete APM32 Devices IRQ Channels list, please refer to the appropriate CMSIS device file (apm32f4xxxx.h)) + * @retval status: - 0 Interrupt status is not pending. + * - 1 Interrupt status is pending. + */ +uint32_t DAL_NVIC_GetActive(IRQn_Type IRQn) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_NVIC_DEVICE_IRQ(IRQn)); + + /* Return 1 if active else 0 */ + return NVIC_GetActive(IRQn); +} + +/** + * @brief Configures the SysTick clock source. + * @param CLKSource specifies the SysTick clock source. + * This parameter can be one of the following values: + * @arg SYSTICK_CLKSOURCE_HCLK_DIV8: AHB clock divided by 8 selected as SysTick clock source. + * @arg SYSTICK_CLKSOURCE_HCLK: AHB clock selected as SysTick clock source. + * @retval None + */ +void DAL_SYSTICK_CLKSourceConfig(uint32_t CLKSource) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_SYSTICK_CLK_SOURCE(CLKSource)); + if (CLKSource == SYSTICK_CLKSOURCE_HCLK) + { + SysTick->CTRL |= SYSTICK_CLKSOURCE_HCLK; + } + else + { + SysTick->CTRL &= ~SYSTICK_CLKSOURCE_HCLK; + } +} + +/** + * @brief This function handles SYSTICK interrupt request. + * @retval None + */ +void DAL_SYSTICK_IRQHandler(void) +{ + DAL_SYSTICK_Callback(); +} + +/** + * @brief SYSTICK callback. + * @retval None + */ +__weak void DAL_SYSTICK_Callback(void) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the DAL_SYSTICK_Callback could be implemented in the user file + */ +} + +/** + * @} + */ + +/** + * @} + */ + +#endif /* DAL_CORTEX_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_crc.c b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_crc.c new file mode 100644 index 0000000000..b664238bc0 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_crc.c @@ -0,0 +1,353 @@ +/** + * + * @file apm32f4xx_dal_crc.c + * @brief CRC DAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the Cyclic Redundancy Check (CRC) peripheral: + * + Initialization and de-initialization functions + * + Peripheral Control functions + * + Peripheral State functions + * + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + * + @verbatim + =============================================================================== + ##### How to use this driver ##### + =============================================================================== + [..] + (+) Enable CRC AHB clock using __DAL_RCM_CRC_CLK_ENABLE(); + (+) Initialize CRC calculator + (++) specify generating polynomial (peripheral default or non-default one) + (++) specify initialization value (peripheral default or non-default one) + (++) specify input data format + (++) specify input or output data inversion mode if any + (+) Use DAL_CRC_Accumulate() function to compute the CRC value of the + input data buffer starting with the previously computed CRC as + initialization value + (+) Use DAL_CRC_Calculate() function to compute the CRC value of the + input data buffer starting with the defined initialization value + (default or non-default) to initiate CRC calculation + + @endverbatim + * + */ + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @defgroup CRC CRC + * @brief CRC DAL module driver. + * @{ + */ + +#ifdef DAL_CRC_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ + +/* Exported functions --------------------------------------------------------*/ + +/** @defgroup CRC_Exported_Functions CRC Exported Functions + * @{ + */ + +/** @defgroup CRC_Exported_Functions_Group1 Initialization and de-initialization functions + * @brief Initialization and Configuration functions. + * +@verbatim + =============================================================================== + ##### Initialization and de-initialization functions ##### + =============================================================================== + [..] This section provides functions allowing to: + (+) Initialize the CRC according to the specified parameters + in the CRC_InitTypeDef and create the associated handle + (+) DeInitialize the CRC peripheral + (+) Initialize the CRC MSP (MCU Specific Package) + (+) DeInitialize the CRC MSP + +@endverbatim + * @{ + */ + +/** + * @brief Initialize the CRC according to the specified + * parameters in the CRC_InitTypeDef and create the associated handle. + * @param hcrc CRC handle + * @retval DAL status + */ +DAL_StatusTypeDef DAL_CRC_Init(CRC_HandleTypeDef *hcrc) +{ + /* Check the CRC handle allocation */ + if (hcrc == NULL) + { + return DAL_ERROR; + } + + /* Check the parameters */ + ASSERT_PARAM(IS_CRC_ALL_INSTANCE(hcrc->Instance)); + + if (hcrc->State == DAL_CRC_STATE_RESET) + { + /* Allocate lock resource and initialize it */ + hcrc->Lock = DAL_UNLOCKED; + /* Init the low level hardware */ + DAL_CRC_MspInit(hcrc); + } + + /* Change CRC peripheral state */ + hcrc->State = DAL_CRC_STATE_READY; + + /* Return function status */ + return DAL_OK; +} + +/** + * @brief DeInitialize the CRC peripheral. + * @param hcrc CRC handle + * @retval DAL status + */ +DAL_StatusTypeDef DAL_CRC_DeInit(CRC_HandleTypeDef *hcrc) +{ + /* Check the CRC handle allocation */ + if (hcrc == NULL) + { + return DAL_ERROR; + } + + /* Check the parameters */ + ASSERT_PARAM(IS_CRC_ALL_INSTANCE(hcrc->Instance)); + + /* Check the CRC peripheral state */ + if (hcrc->State == DAL_CRC_STATE_BUSY) + { + return DAL_BUSY; + } + + /* Change CRC peripheral state */ + hcrc->State = DAL_CRC_STATE_BUSY; + + /* Reset CRC calculation unit */ + __DAL_CRC_DATA_RESET(hcrc); + + /* Reset IDR register content */ + CLEAR_BIT(hcrc->Instance->INDATA, CRC_INDATA_INDATA); + + /* DeInit the low level hardware */ + DAL_CRC_MspDeInit(hcrc); + + /* Change CRC peripheral state */ + hcrc->State = DAL_CRC_STATE_RESET; + + /* Process unlocked */ + __DAL_UNLOCK(hcrc); + + /* Return function status */ + return DAL_OK; +} + +/** + * @brief Initializes the CRC MSP. + * @param hcrc CRC handle + * @retval None + */ +__weak void DAL_CRC_MspInit(CRC_HandleTypeDef *hcrc) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hcrc); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_CRC_MspInit can be implemented in the user file + */ +} + +/** + * @brief DeInitialize the CRC MSP. + * @param hcrc CRC handle + * @retval None + */ +__weak void DAL_CRC_MspDeInit(CRC_HandleTypeDef *hcrc) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hcrc); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_CRC_MspDeInit can be implemented in the user file + */ +} + +/** + * @} + */ + +/** @defgroup CRC_Exported_Functions_Group2 Peripheral Control functions + * @brief management functions. + * +@verbatim + =============================================================================== + ##### Peripheral Control functions ##### + =============================================================================== + [..] This section provides functions allowing to: + (+) compute the 32-bit CRC value of a 32-bit data buffer + using combination of the previous CRC value and the new one. + + [..] or + + (+) compute the 32-bit CRC value of a 32-bit data buffer + independently of the previous CRC value. + +@endverbatim + * @{ + */ + +/** + * @brief Compute the 32-bit CRC value of a 32-bit data buffer + * starting with the previously computed CRC as initialization value. + * @param hcrc CRC handle + * @param pBuffer pointer to the input data buffer. + * @param BufferLength input data buffer length (number of uint32_t words). + * @retval uint32_t CRC (returned value LSBs for CRC shorter than 32 bits) + */ +uint32_t DAL_CRC_Accumulate(CRC_HandleTypeDef *hcrc, uint32_t pBuffer[], uint32_t BufferLength) +{ + uint32_t index; /* CRC input data buffer index */ + uint32_t temp = 0U; /* CRC output (read from hcrc->Instance->DATA register) */ + + /* Change CRC peripheral state */ + hcrc->State = DAL_CRC_STATE_BUSY; + + /* Enter Data to the CRC calculator */ + for (index = 0U; index < BufferLength; index++) + { + hcrc->Instance->DATA = pBuffer[index]; + } + temp = hcrc->Instance->DATA; + + /* Change CRC peripheral state */ + hcrc->State = DAL_CRC_STATE_READY; + + /* Return the CRC computed value */ + return temp; +} + +/** + * @brief Compute the 32-bit CRC value of a 32-bit data buffer + * starting with hcrc->Instance->INIT as initialization value. + * @param hcrc CRC handle + * @param pBuffer pointer to the input data buffer. + * @param BufferLength input data buffer length (number of uint32_t words). + * @retval uint32_t CRC (returned value LSBs for CRC shorter than 32 bits) + */ +uint32_t DAL_CRC_Calculate(CRC_HandleTypeDef *hcrc, uint32_t pBuffer[], uint32_t BufferLength) +{ + uint32_t index; /* CRC input data buffer index */ + uint32_t temp = 0U; /* CRC output (read from hcrc->Instance->DATA register) */ + + /* Change CRC peripheral state */ + hcrc->State = DAL_CRC_STATE_BUSY; + + /* Reset CRC Calculation Unit (hcrc->Instance->INIT is + * written in hcrc->Instance->DATA) */ + __DAL_CRC_DATA_RESET(hcrc); + + /* Enter 32-bit input data to the CRC calculator */ + for (index = 0U; index < BufferLength; index++) + { + hcrc->Instance->DATA = pBuffer[index]; + } + temp = hcrc->Instance->DATA; + + /* Change CRC peripheral state */ + hcrc->State = DAL_CRC_STATE_READY; + + /* Return the CRC computed value */ + return temp; +} + +/** + * @} + */ + +/** @defgroup CRC_Exported_Functions_Group3 Peripheral State functions + * @brief Peripheral State functions. + * +@verbatim + =============================================================================== + ##### Peripheral State functions ##### + =============================================================================== + [..] + This subsection permits to get in run-time the status of the peripheral. + +@endverbatim + * @{ + */ + +/** + * @brief Return the CRC handle state. + * @param hcrc CRC handle + * @retval DAL state + */ +DAL_CRC_StateTypeDef DAL_CRC_GetState(CRC_HandleTypeDef *hcrc) +{ + /* Return CRC handle state */ + return hcrc->State; +} + +/** + * @} + */ + +/** + * @} + */ + + +#endif /* DAL_CRC_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_cryp.c b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_cryp.c new file mode 100644 index 0000000000..adce4f9395 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_cryp.c @@ -0,0 +1,7157 @@ +/** + * + * @file apm32f4xx_dal_cryp.c + * @brief CRYP DAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the Cryptography (CRYP) peripheral: + * + Initialization, de-initialization, set config and get config functions + * + DES/TDES, AES processing functions + * + DMA callback functions + * + CRYP IRQ handler management + * + Peripheral State functions + * + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + * + @verbatim + ============================================================================== + ##### How to use this driver ##### + ============================================================================== + [..] + The CRYP DAL driver can be used in CRYP or TinyAES IP as follows: + + (#)Initialize the CRYP low level resources by implementing the DAL_CRYP_MspInit(): + (##) Enable the CRYP interface clock using __DAL_RCM_CRYP_CLK_ENABLE()or __DAL_RCM_AES_CLK_ENABLE for TinyAES IP + (##) In case of using interrupts (e.g. DAL_CRYP_Encrypt_IT()) + (+++) Configure the CRYP interrupt priority using DAL_NVIC_SetPriority() + (+++) Enable the CRYP IRQ handler using DAL_NVIC_EnableIRQ() + (+++) In CRYP IRQ handler, call DAL_CRYP_IRQHandler() + (##) In case of using DMA to control data transfer (e.g. DAL_CRYP_Encrypt_DMA()) + (+++) Enable the DMAx interface clock using __RCM_DMAx_CLK_ENABLE() + (+++) Configure and enable two DMA streams one for managing data transfer from + memory to peripheral (input stream) and another stream for managing data + transfer from peripheral to memory (output stream) + (+++) Associate the initialized DMA handle to the CRYP DMA handle + using __DAL_LINKDMA() + (+++) Configure the priority and enable the NVIC for the transfer complete + interrupt on the two DMA Streams. The output stream should have higher + priority than the input stream DAL_NVIC_SetPriority() and DAL_NVIC_EnableIRQ() + + (#)Initialize the CRYP according to the specified parameters : + (##) The data type: 1-bit, 8-bit, 16-bit or 32-bit. + (##) The key size: 128, 192 or 256. + (##) The AlgoMode DES/ TDES Algorithm ECB/CBC or AES Algorithm ECB/CBC/CTR/GCM or CCM. + (##) The initialization vector (counter). It is not used in ECB mode. + (##) The key buffer used for encryption/decryption. + (##) The Header used only in AES GCM and CCM Algorithm for authentication. + (##) The HeaderSize The size of header buffer in word. + (##) The B0 block is the first authentication block used only in AES CCM mode. + + (#)Three processing (encryption/decryption) functions are available: + (##) Polling mode: encryption and decryption APIs are blocking functions + i.e. they process the data and wait till the processing is finished, + e.g. DAL_CRYP_Encrypt & DAL_CRYP_Decrypt + (##) Interrupt mode: encryption and decryption APIs are not blocking functions + i.e. they process the data under interrupt, + e.g. DAL_CRYP_Encrypt_IT & DAL_CRYP_Decrypt_IT + (##) DMA mode: encryption and decryption APIs are not blocking functions + i.e. the data transfer is ensured by DMA, + e.g. DAL_CRYP_Encrypt_DMA & DAL_CRYP_Decrypt_DMA + + (#)When the processing function is called at first time after DAL_CRYP_Init() + the CRYP peripheral is configured and processes the buffer in input. + At second call, no need to Initialize the CRYP, user have to get current configuration via + DAL_CRYP_GetConfig() API, then only DAL_CRYP_SetConfig() is requested to set + new parametres, finally user can start encryption/decryption. + + (#)Call DAL_CRYP_DeInit() to deinitialize the CRYP peripheral. + + (#)To process a single message with consecutive calls to DAL_CRYP_Encrypt() or DAL_CRYP_Decrypt() + without having to configure again the Key or the Initialization Vector between each API call, + the field KeyIVConfigSkip of the initialization structure must be set to CRYP_KEYIVCONFIG_ONCE. + Same is true for consecutive calls of DAL_CRYP_Encrypt_IT(), DAL_CRYP_Decrypt_IT(), DAL_CRYP_Encrypt_DMA() + or DAL_CRYP_Decrypt_DMA(). + + [..] + The cryptographic processor supports following standards: + (#) The data encryption standard (DES) and Triple-DES (TDES) supported only by CRYP1 IP: + (##)64-bit data block processing + (##) chaining modes supported : + (+++) Electronic Code Book(ECB) + (+++) Cipher Block Chaining (CBC) + (##) keys length supported :64-bit, 128-bit and 192-bit. + (#) The advanced encryption standard (AES) supported by CRYP1 & TinyAES IP: + (##)128-bit data block processing + (##) chaining modes supported : + (+++) Electronic Code Book(ECB) + (+++) Cipher Block Chaining (CBC) + (+++) Counter mode (CTR) + (+++) Galois/counter mode (GCM/GMAC) + (+++) Counter with Cipher Block Chaining-Message(CCM) + (##) keys length Supported : + (+++) for CRYP1 IP: 128-bit, 192-bit and 256-bit. + (+++) for TinyAES IP: 128-bit and 256-bit + + [..] This section describes the AES Galois/counter mode (GCM) supported by both CRYP1 IP: + (#) Algorithm supported : + (##) Galois/counter mode (GCM) + (##) Galois message authentication code (GMAC) :is exactly the same as + GCM algorithm composed only by an header. + (#) Four phases are performed in GCM : + (##) Init phase: IP prepares the GCM hash subkey (H) and do the IV processing + (##) Header phase: IP processes the Additional Authenticated Data (AAD), with hash + computation only. + (##) Payload phase: IP processes the plaintext (P) with hash computation + keystream + encryption + data XORing. It works in a similar way for ciphertext (C). + (##) Final phase: IP generates the authenticated tag (T) using the last block of data. + (#) structure of message construction in GCM is defined as below : + (##) 16 bytes Initial Counter Block (ICB)composed of IV and counter + (##) The authenticated header A (also knows as Additional Authentication Data AAD) + this part of the message is only authenticated, not encrypted. + (##) The plaintext message P is both authenticated and encrypted as ciphertext. + GCM standard specifies that ciphertext has same bit length as the plaintext. + (##) The last block is composed of the length of A (on 64 bits) and the length of ciphertext + (on 64 bits) + + [..] This section describe The AES Counter with Cipher Block Chaining-Message + Authentication Code (CCM) supported by both CRYP1 IP: + (#) Specific parameters for CCM : + + (##) B0 block : According to NIST Special Publication 800-38C, + The first block B0 is formatted as follows, where l(m) is encoded in + most-significant-byte first order(see below table 3) + + (+++) Q: a bit string representation of the octet length of P (plaintext) + (+++) q The octet length of the binary representation of the octet length of the payload + (+++) A nonce (N), n The octet length of the where n+q=15. + (+++) Flags: most significant octet containing four flags for control information, + (+++) t The octet length of the MAC. + (##) B1 block (header) : associated data length(a) concatenated with Associated Data (A) + the associated data length expressed in bytes (a) defined as below: + (+++) If 0 < a < 216-28, then it is encoded as [a]16, i.e. two octets + (+++) If 216-28 < a < 232, then it is encoded as 0xff || 0xfe || [a]32, i.e. six octets + (+++) If 232 < a < 264, then it is encoded as 0xff || 0xff || [a]64, i.e. ten octets + (##) CTRx block : control blocks + (+++) Generation of CTR1 from first block B0 information : + equal to B0 with first 5 bits zeroed and most significant bits storing octet + length of P also zeroed, then incremented by one ( see below Table 4) + (+++) Generation of CTR0: same as CTR1 with bit[0] set to zero. + + (#) Four phases are performed in CCM for CRYP1 IP: + (##) Init phase: IP prepares the GCM hash subkey (H) and do the IV processing + (##) Header phase: IP processes the Additional Authenticated Data (AAD), with hash + computation only. + (##) Payload phase: IP processes the plaintext (P) with hash computation + keystream + encryption + data XORing. It works in a similar way for ciphertext (C). + (##) Final phase: IP generates the authenticated tag (T) using the last block of data. + + *** Callback registration *** + ============================================= + + The compilation define USE_DAL_CRYP_REGISTER_CALLBACKS when set to 1 + allows the user to configure dynamically the driver callbacks. + Use Functions DAL_CRYP_RegisterCallback() or DAL_CRYP_RegisterXXXCallback() + to register an interrupt callback. + + Function DAL_CRYP_RegisterCallback() allows to register following callbacks: + (+) InCpltCallback : Input FIFO transfer completed callback. + (+) OutCpltCallback : Output FIFO transfer completed callback. + (+) ErrorCallback : callback for error detection. + (+) MspInitCallback : CRYP MspInit. + (+) MspDeInitCallback : CRYP MspDeInit. + This function takes as parameters the DAL peripheral handle, the Callback ID + and a pointer to the user callback function. + + Use function DAL_CRYP_UnRegisterCallback() to reset a callback to the default + weak function. + DAL_CRYP_UnRegisterCallback() takes as parameters the DAL peripheral handle, + and the Callback ID. + This function allows to reset following callbacks: + (+) InCpltCallback : Input FIFO transfer completed callback. + (+) OutCpltCallback : Output FIFO transfer completed callback. + (+) ErrorCallback : callback for error detection. + (+) MspInitCallback : CRYP MspInit. + (+) MspDeInitCallback : CRYP MspDeInit. + + By default, after the DAL_CRYP_Init() and when the state is DAL_CRYP_STATE_RESET + all callbacks are set to the corresponding weak functions : + examples DAL_CRYP_InCpltCallback() , DAL_CRYP_OutCpltCallback(). + Exception done for MspInit and MspDeInit functions that are + reset to the legacy weak function in the DAL_CRYP_Init()/ DAL_CRYP_DeInit() only when + these callbacks are null (not registered beforehand). + if not, MspInit or MspDeInit are not null, the DAL_CRYP_Init() / DAL_CRYP_DeInit() + keep and use the user MspInit/MspDeInit functions (registered beforehand) + + Callbacks can be registered/unregistered in DAL_CRYP_STATE_READY state only. + Exception done MspInit/MspDeInit callbacks that can be registered/unregistered + in DAL_CRYP_STATE_READY or DAL_CRYP_STATE_RESET state, + thus registered (user) MspInit/DeInit callbacks can be used during the Init/DeInit. + In that case first register the MspInit/MspDeInit user callbacks + using DAL_CRYP_RegisterCallback() before calling DAL_CRYP_DeInit() + or DAL_CRYP_Init() function. + + When The compilation define USE_DAL_CRYP_REGISTER_CALLBACKS is set to 0 or + not defined, the callback registration feature is not available and all callbacks + are set to the corresponding weak functions. + + Table 1. Initial Counter Block (ICB) + +-------------------------------------------------------+ + | Initialization vector (IV) | Counter | + |----------------|----------------|-----------|---------| + 127 95 63 31 0 + + + Bit Number Register Contents + ---------- --------------- ----------- + 127 ...96 CRYP_IV1R[31:0] ICB[127:96] + 95 ...64 CRYP_IV1L[31:0] B0[95:64] + 63 ... 32 CRYP_IV0R[31:0] ICB[63:32] + 31 ... 0 CRYP_IV0L[31:0] ICB[31:0], where 32-bit counter= 0x2 + + Table 2. GCM last block definition + + +-------------------------------------------------------------------+ + | Bit[0] | Bit[32] | Bit[64] | Bit[96] | + |-----------|--------------------|-----------|----------------------| + | 0x0 | Header length[31:0]| 0x0 | Payload length[31:0] | + |-----------|--------------------|-----------|----------------------| + + Table 3. B0 block + Octet Number Contents + ------------ --------- + 0 Flags + 1 ... 15-q Nonce N + 16-q ... 15 Q + + the Flags field is formatted as follows: + + Bit Number Contents + ---------- ---------------------- + 7 Reserved (always zero) + 6 Adata + 5 ... 3 (t-2)/2 + 2 ... 0 [q-1]3 + + Table 4. CTRx block + Bit Number Register Contents + ---------- --------------- ----------- + 127 ...96 CRYP_IV1R[31:0] B0[127:96], where Q length bits are set to 0, except for + bit 0 that is set to 1 + 95 ...64 CRYP_IV1L[31:0] B0[95:64] + 63 ... 32 CRYP_IV0R[31:0] B0[63:32] + 31 ... 0 CRYP_IV0L[31:0] B0[31:0], where flag bits set to 0 + + @endverbatim + * + */ + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +#if defined (AES) || defined (CRYP) + +/** @defgroup CRYP CRYP + * @brief CRYP DAL module driver. + * @{ + */ + + +#ifdef DAL_CRYP_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/** @addtogroup CRYP_Private_Defines + * @{ + */ +#define CRYP_TIMEOUT_KEYPREPARATION 82U /*The latency of key preparation operation is 82 clock cycles.*/ +#define CRYP_TIMEOUT_GCMCCMINITPHASE 299U /* The latency of GCM/CCM init phase to prepare hash subkey is 299 clock cycles.*/ +#define CRYP_TIMEOUT_GCMCCMHEADERPHASE 290U /* The latency of GCM/CCM header phase is 290 clock cycles.*/ + +#define CRYP_PHASE_READY 0x00000001U /*!< CRYP peripheral is ready for initialization. */ +#define CRYP_PHASE_PROCESS 0x00000002U /*!< CRYP peripheral is in processing phase */ + +#if defined(AES) +#define CRYP_OPERATINGMODE_ENCRYPT 0x00000000U /*!< Encryption mode(Mode 1) */ +#define CRYP_OPERATINGMODE_KEYDERIVATION AES_CR_MODE_0 /*!< Key derivation mode only used when performing ECB and CBC decryptions (Mode 2) */ +#define CRYP_OPERATINGMODE_DECRYPT AES_CR_MODE_1 /*!< Decryption (Mode 3) */ +#define CRYP_OPERATINGMODE_KEYDERIVATION_DECRYPT AES_CR_MODE /*!< Key derivation and decryption only used when performing ECB and CBC decryptions (Mode 4) */ +#define CRYP_PHASE_INIT 0x00000000U /*!< GCM/GMAC (or CCM) init phase */ +#define CRYP_PHASE_HEADER AES_CR_GCMPH_0 /*!< GCM/GMAC or CCM header phase */ +#define CRYP_PHASE_PAYLOAD AES_CR_GCMPH_1 /*!< GCM(/CCM) payload phase */ +#define CRYP_PHASE_FINAL AES_CR_GCMPH /*!< GCM/GMAC or CCM final phase */ +#else /* CRYP */ +#define CRYP_PHASE_INIT 0x00000000U /*!< GCM/GMAC (or CCM) init phase */ +#define CRYP_PHASE_HEADER CRYP_CTRL_GCM_CCMPH_0 /*!< GCM/GMAC or CCM header phase */ +#define CRYP_PHASE_PAYLOAD CRYP_CTRL_GCM_CCMPH_1 /*!< GCM(/CCM) payload phase */ +#define CRYP_PHASE_FINAL CRYP_CTRL_GCM_CCMPH /*!< GCM/GMAC or CCM final phase */ +#define CRYP_OPERATINGMODE_ENCRYPT 0x00000000U /*!< Encryption mode */ +#define CRYP_OPERATINGMODE_DECRYPT CRYP_CTRL_ALGODIRSEL /*!< Decryption */ +#endif /* End CRYP or AES */ + +/* CTR1 information to use in CCM algorithm */ +#define CRYP_CCM_CTR1_0 0x07FFFFFFU +#define CRYP_CCM_CTR1_1 0xFFFFFF00U +#define CRYP_CCM_CTR1_2 0x00000001U + + +/** + * @} + */ + + +/* Private macro -------------------------------------------------------------*/ +/** @addtogroup CRYP_Private_Macros + * @{ + */ + +#if defined(CRYP) + +#define CRYP_SET_PHASE(__HANDLE__, __PHASE__) do{(__HANDLE__)->Instance->CTRL &= (uint32_t)(~CRYP_CTRL_GCM_CCMPH);\ + (__HANDLE__)->Instance->CTRL |= (uint32_t)(__PHASE__);\ + }while(0) + +#define DAL_CRYP_FIFO_FLUSH(__HANDLE__) ((__HANDLE__)->Instance->CTRL |= CRYP_CTRL_FFLUSH) + +#else /*AES*/ +#define CRYP_SET_PHASE(__HANDLE__, __PHASE__) do{(__HANDLE__)->Instance->CTRL &= (uint32_t)(~AES_CR_GCMPH);\ + (__HANDLE__)->Instance->CTRL |= (uint32_t)(__PHASE__);\ + }while(0) +#endif /* End AES or CRYP*/ + + +/** + * @} + */ + +/* Private struct -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/** @addtogroup CRYP_Private_Functions_prototypes + * @{ + */ + +static void CRYP_SetDMAConfig(CRYP_HandleTypeDef *hcryp, uint32_t inputaddr, uint16_t Size, uint32_t outputaddr); +static void CRYP_DMAInCplt(DMA_HandleTypeDef *hdma); +static void CRYP_DMAOutCplt(DMA_HandleTypeDef *hdma); +static void CRYP_DMAError(DMA_HandleTypeDef *hdma); +static void CRYP_SetKey(CRYP_HandleTypeDef *hcryp, uint32_t KeySize); +static void CRYP_AES_IT(CRYP_HandleTypeDef *hcryp); +#if defined (CRYP_CTRL_ALGOMSEL_AES_GCM)|| defined (AES) +static DAL_StatusTypeDef CRYP_GCMCCM_SetHeaderPhase(CRYP_HandleTypeDef *hcryp, uint32_t Timeout); +static void CRYP_GCMCCM_SetPayloadPhase_IT(CRYP_HandleTypeDef *hcryp); +static void CRYP_GCMCCM_SetHeaderPhase_IT(CRYP_HandleTypeDef *hcryp); +static DAL_StatusTypeDef CRYP_GCMCCM_SetHeaderPhase_DMA(CRYP_HandleTypeDef *hcryp); +static void CRYP_Workaround(CRYP_HandleTypeDef *hcryp, uint32_t Timeout); +static DAL_StatusTypeDef CRYP_AESGCM_Process_DMA(CRYP_HandleTypeDef *hcryp); +static DAL_StatusTypeDef CRYP_AESGCM_Process_IT(CRYP_HandleTypeDef *hcryp); +static DAL_StatusTypeDef CRYP_AESGCM_Process(CRYP_HandleTypeDef *hcryp, uint32_t Timeout); +static DAL_StatusTypeDef CRYP_AESCCM_Process(CRYP_HandleTypeDef *hcryp, uint32_t Timeout); +static DAL_StatusTypeDef CRYP_AESCCM_Process_IT(CRYP_HandleTypeDef *hcryp); +static DAL_StatusTypeDef CRYP_AESCCM_Process_DMA(CRYP_HandleTypeDef *hcryp); +#endif /* AES or GCM CCM defined*/ +static void CRYP_AES_ProcessData(CRYP_HandleTypeDef *hcrypt, uint32_t Timeout); +static DAL_StatusTypeDef CRYP_AES_Encrypt(CRYP_HandleTypeDef *hcryp, uint32_t Timeout); +static DAL_StatusTypeDef CRYP_AES_Decrypt(CRYP_HandleTypeDef *hcryp, uint32_t Timeout); +static DAL_StatusTypeDef CRYP_AES_Decrypt_IT(CRYP_HandleTypeDef *hcryp); +static DAL_StatusTypeDef CRYP_AES_Encrypt_IT(CRYP_HandleTypeDef *hcryp); +static DAL_StatusTypeDef CRYP_AES_Decrypt_DMA(CRYP_HandleTypeDef *hcryp); +#if defined (CRYP) +static void CRYP_TDES_IT(CRYP_HandleTypeDef *hcryp); +#if defined (CRYP_CTRL_ALGOMSEL_AES_GCM) +static DAL_StatusTypeDef CRYP_WaitOnIFEMFlag(CRYP_HandleTypeDef *hcryp, uint32_t Timeout); +#endif /* GCM CCM defined*/ +static DAL_StatusTypeDef CRYP_WaitOnBUSYFlag(CRYP_HandleTypeDef *hcryp, uint32_t Timeout); +static DAL_StatusTypeDef CRYP_WaitOnOFNEFlag(CRYP_HandleTypeDef *hcryp, uint32_t Timeout); +static DAL_StatusTypeDef CRYP_TDES_Process(CRYP_HandleTypeDef *hcryp, uint32_t Timeout); +#else /*AES*/ +static DAL_StatusTypeDef CRYP_WaitOnCCFlag(CRYP_HandleTypeDef *hcryp, uint32_t Timeout); +#endif /* End CRYP or AES */ + +/** + * @} + */ + +/* Exported functions ---------------------------------------------------------*/ + +/** @defgroup CRYP_Exported_Functions CRYP Exported Functions + * @{ + */ + + +/** @defgroup CRYP_Exported_Functions_Group1 Initialization and de-initialization functions + * @brief Initialization and Configuration functions. + * +@verbatim + ======================================================================================== + ##### Initialization, de-initialization and Set and Get configuration functions ##### + ======================================================================================== + [..] This section provides functions allowing to: + (+) Initialize the CRYP + (+) DeInitialize the CRYP + (+) Initialize the CRYP MSP + (+) DeInitialize the CRYP MSP + (+) configure CRYP (DAL_CRYP_SetConfig) with the specified parameters in the CRYP_ConfigTypeDef + Parameters which are configured in This section are : + (+) Key size + (+) Data Type : 32,16, 8 or 1bit + (+) AlgoMode : + - for CRYP1 IP : + ECB and CBC in DES/TDES Standard + ECB,CBC,CTR,GCM/GMAC and CCM in AES Standard. + - for TinyAES2 IP, only ECB,CBC,CTR,GCM/GMAC and CCM in AES Standard are supported. + (+) Get CRYP configuration (DAL_CRYP_GetConfig) from the specified parameters in the CRYP_HandleTypeDef + + +@endverbatim + * @{ + */ + + +/** + * @brief Initializes the CRYP according to the specified + * parameters in the CRYP_ConfigTypeDef and creates the associated handle. + * @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains + * the configuration information for CRYP module + * @retval DAL status + */ +DAL_StatusTypeDef DAL_CRYP_Init(CRYP_HandleTypeDef *hcryp) +{ + /* Check the CRYP handle allocation */ + if (hcryp == NULL) + { + return DAL_ERROR; + } + + /* Check parameters */ + ASSERT_PARAM(IS_CRYP_KEYSIZE(hcryp->Init.KeySize)); + ASSERT_PARAM(IS_CRYP_DATATYPE(hcryp->Init.DataType)); + ASSERT_PARAM(IS_CRYP_ALGORITHM(hcryp->Init.Algorithm)); + ASSERT_PARAM(IS_CRYP_INIT(hcryp->Init.KeyIVConfigSkip)); + +#if (USE_DAL_CRYP_REGISTER_CALLBACKS == 1) + if (hcryp->State == DAL_CRYP_STATE_RESET) + { + /* Allocate lock resource and initialize it */ + hcryp->Lock = DAL_UNLOCKED; + + hcryp->InCpltCallback = DAL_CRYP_InCpltCallback; /* Legacy weak InCpltCallback */ + hcryp->OutCpltCallback = DAL_CRYP_OutCpltCallback; /* Legacy weak OutCpltCallback */ + hcryp->ErrorCallback = DAL_CRYP_ErrorCallback; /* Legacy weak ErrorCallback */ + + if (hcryp->MspInitCallback == NULL) + { + hcryp->MspInitCallback = DAL_CRYP_MspInit; /* Legacy weak MspInit */ + } + + /* Init the low level hardware */ + hcryp->MspInitCallback(hcryp); + } +#else + if (hcryp->State == DAL_CRYP_STATE_RESET) + { + /* Allocate lock resource and initialize it */ + hcryp->Lock = DAL_UNLOCKED; + + /* Init the low level hardware */ + DAL_CRYP_MspInit(hcryp); + } +#endif /* (USE_DAL_CRYP_REGISTER_CALLBACKS) */ + + /* Set the key size(This bit field is don't care in the DES or TDES modes) data type and Algorithm */ +#if defined (CRYP) + + MODIFY_REG(hcryp->Instance->CTRL, CRYP_CTRL_DTSEL | CRYP_CTRL_KSIZESEL | CRYP_CTRL_ALGOMSEL, + hcryp->Init.DataType | hcryp->Init.KeySize | hcryp->Init.Algorithm); + +#else /*AES*/ + + MODIFY_REG(hcryp->Instance->CTRL, AES_CR_DATATYPE | AES_CR_KEYSIZE | AES_CR_CHMOD, + hcryp->Init.DataType | hcryp->Init.KeySize | hcryp->Init.Algorithm); + +#endif /* End AES or CRYP*/ + + /* Reset Error Code field */ + hcryp->ErrorCode = DAL_CRYP_ERROR_NONE; + + /* Change the CRYP state */ + hcryp->State = DAL_CRYP_STATE_READY; + + /* Set the default CRYP phase */ + hcryp->Phase = CRYP_PHASE_READY; + + /* Return function status */ + return DAL_OK; +} + +/** + * @brief De-Initializes the CRYP peripheral. + * @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains + * the configuration information for CRYP module + * @retval DAL status + */ +DAL_StatusTypeDef DAL_CRYP_DeInit(CRYP_HandleTypeDef *hcryp) +{ + /* Check the CRYP handle allocation */ + if (hcryp == NULL) + { + return DAL_ERROR; + } + + /* Set the default CRYP phase */ + hcryp->Phase = CRYP_PHASE_READY; + + /* Reset CrypInCount and CrypOutCount */ + hcryp->CrypInCount = 0; + hcryp->CrypOutCount = 0; + hcryp->CrypHeaderCount = 0; + + /* Disable the CRYP peripheral clock */ + __DAL_CRYP_DISABLE(hcryp); + +#if (USE_DAL_CRYP_REGISTER_CALLBACKS == 1) + + if (hcryp->MspDeInitCallback == NULL) + { + hcryp->MspDeInitCallback = DAL_CRYP_MspDeInit; /* Legacy weak MspDeInit */ + } + /* DeInit the low level hardware */ + hcryp->MspDeInitCallback(hcryp); + +#else + + /* DeInit the low level hardware: CLOCK, NVIC.*/ + DAL_CRYP_MspDeInit(hcryp); + +#endif /* USE_DAL_CRYP_REGISTER_CALLBACKS */ + + /* Change the CRYP state */ + hcryp->State = DAL_CRYP_STATE_RESET; + + /* Release Lock */ + __DAL_UNLOCK(hcryp); + + /* Return function status */ + return DAL_OK; +} + +/** + * @brief Configure the CRYP according to the specified + * parameters in the CRYP_ConfigTypeDef + * @param hcryp: pointer to a CRYP_HandleTypeDef structure + * @param pConf: pointer to a CRYP_ConfigTypeDef structure that contains + * the configuration information for CRYP module + * @retval DAL status + */ +DAL_StatusTypeDef DAL_CRYP_SetConfig(CRYP_HandleTypeDef *hcryp, CRYP_ConfigTypeDef *pConf) +{ + /* Check the CRYP handle allocation */ + if ((hcryp == NULL) || (pConf == NULL)) + { + return DAL_ERROR; + } + + /* Check parameters */ + ASSERT_PARAM(IS_CRYP_KEYSIZE(pConf->KeySize)); + ASSERT_PARAM(IS_CRYP_DATATYPE(pConf->DataType)); + ASSERT_PARAM(IS_CRYP_ALGORITHM(pConf->Algorithm)); + + if (hcryp->State == DAL_CRYP_STATE_READY) + { + /* Change the CRYP state */ + hcryp->State = DAL_CRYP_STATE_BUSY; + + /* Process locked */ + __DAL_LOCK(hcryp); + + /* Set CRYP parameters */ + hcryp->Init.DataType = pConf->DataType; + hcryp->Init.pKey = pConf->pKey; + hcryp->Init.Algorithm = pConf->Algorithm; + hcryp->Init.KeySize = pConf->KeySize; + hcryp->Init.pInitVect = pConf->pInitVect; + hcryp->Init.Header = pConf->Header; + hcryp->Init.HeaderSize = pConf->HeaderSize; + hcryp->Init.B0 = pConf->B0; + hcryp->Init.DataWidthUnit = pConf->DataWidthUnit; + hcryp->Init.KeyIVConfigSkip = pConf->KeyIVConfigSkip; + hcryp->Init.HeaderWidthUnit = pConf->HeaderWidthUnit; + + /* Set the key size(This bit field is don't care in the DES or TDES modes) data type, AlgoMode and operating mode*/ +#if defined (CRYP) + + MODIFY_REG(hcryp->Instance->CTRL, CRYP_CTRL_DTSEL | CRYP_CTRL_KSIZESEL | CRYP_CTRL_ALGOMSEL, + hcryp->Init.DataType | hcryp->Init.KeySize | hcryp->Init.Algorithm); + +#else /*AES*/ + MODIFY_REG(hcryp->Instance->CTRL, AES_CR_DATATYPE | AES_CR_KEYSIZE | AES_CR_CHMOD, + hcryp->Init.DataType | hcryp->Init.KeySize | hcryp->Init.Algorithm); + + /*clear error flags*/ + __DAL_CRYP_CLEAR_FLAG(hcryp, CRYP_ERR_CLEAR); + +#endif /* End AES or CRYP */ + + /* Process Unlocked */ + __DAL_UNLOCK(hcryp); + + /* Reset Error Code field */ + hcryp->ErrorCode = DAL_CRYP_ERROR_NONE; + + /* Change the CRYP state */ + hcryp->State = DAL_CRYP_STATE_READY; + + /* Set the default CRYP phase */ + hcryp->Phase = CRYP_PHASE_READY; + + /* Return function status */ + return DAL_OK; + } + else + { + /* Process Unlocked */ + __DAL_UNLOCK(hcryp); + + /* Busy error code field */ + hcryp->ErrorCode |= DAL_CRYP_ERROR_BUSY; + return DAL_ERROR; + } +} + +/** + * @brief Get CRYP Configuration parameters in associated handle. + * @param pConf: pointer to a CRYP_ConfigTypeDef structure + * @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains + * the configuration information for CRYP module + * @retval DAL status + */ +DAL_StatusTypeDef DAL_CRYP_GetConfig(CRYP_HandleTypeDef *hcryp, CRYP_ConfigTypeDef *pConf) +{ + /* Check the CRYP handle allocation */ + if ((hcryp == NULL) || (pConf == NULL)) + { + return DAL_ERROR; + } + + if (hcryp->State == DAL_CRYP_STATE_READY) + { + /* Change the CRYP state */ + hcryp->State = DAL_CRYP_STATE_BUSY; + + /* Process locked */ + __DAL_LOCK(hcryp); + + /* Get CRYP parameters */ + pConf->DataType = hcryp->Init.DataType; + pConf->pKey = hcryp->Init.pKey; + pConf->Algorithm = hcryp->Init.Algorithm; + pConf->KeySize = hcryp->Init.KeySize ; + pConf->pInitVect = hcryp->Init.pInitVect; + pConf->Header = hcryp->Init.Header ; + pConf->HeaderSize = hcryp->Init.HeaderSize; + pConf->B0 = hcryp->Init.B0; + pConf->DataWidthUnit = hcryp->Init.DataWidthUnit; + pConf->KeyIVConfigSkip = hcryp->Init.KeyIVConfigSkip; + pConf->HeaderWidthUnit = hcryp->Init.HeaderWidthUnit; + + /* Process Unlocked */ + __DAL_UNLOCK(hcryp); + + /* Change the CRYP state */ + hcryp->State = DAL_CRYP_STATE_READY; + + /* Return function status */ + return DAL_OK; + } + else + { + /* Process Unlocked */ + __DAL_UNLOCK(hcryp); + + /* Busy error code field */ + hcryp->ErrorCode |= DAL_CRYP_ERROR_BUSY; + return DAL_ERROR; + } +} +/** + * @brief Initializes the CRYP MSP. + * @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains + * the configuration information for CRYP module + * @retval None + */ +__weak void DAL_CRYP_MspInit(CRYP_HandleTypeDef *hcryp) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hcryp); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_CRYP_MspInit can be implemented in the user file + */ +} + +/** + * @brief DeInitializes CRYP MSP. + * @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains + * the configuration information for CRYP module + * @retval None + */ +__weak void DAL_CRYP_MspDeInit(CRYP_HandleTypeDef *hcryp) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hcryp); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_CRYP_MspDeInit can be implemented in the user file + */ +} + +#if (USE_DAL_CRYP_REGISTER_CALLBACKS == 1) +/** + * @brief Register a User CRYP Callback + * To be used instead of the weak predefined callback + * @param hcryp cryp handle + * @param CallbackID ID of the callback to be registered + * This parameter can be one of the following values: + * @arg @ref DAL_CRYP_INPUT_COMPLETE_CB_ID Input FIFO transfer completed callback ID + * @arg @ref DAL_CRYP_OUTPUT_COMPLETE_CB_ID Output FIFO transfer completed callback ID + * @arg @ref DAL_CRYP_ERROR_CB_ID Error callback ID + * @arg @ref DAL_CRYP_MSPINIT_CB_ID MspInit callback ID + * @arg @ref DAL_CRYP_MSPDEINIT_CB_ID MspDeInit callback ID + * @param pCallback pointer to the Callback function + * @retval status + */ +DAL_StatusTypeDef DAL_CRYP_RegisterCallback(CRYP_HandleTypeDef *hcryp, DAL_CRYP_CallbackIDTypeDef CallbackID, + pCRYP_CallbackTypeDef pCallback) +{ + DAL_StatusTypeDef status = DAL_OK; + + if (pCallback == NULL) + { + /* Update the error code */ + hcryp->ErrorCode |= DAL_CRYP_ERROR_INVALID_CALLBACK; + + return DAL_ERROR; + } + /* Process locked */ + __DAL_LOCK(hcryp); + + if (hcryp->State == DAL_CRYP_STATE_READY) + { + switch (CallbackID) + { + case DAL_CRYP_INPUT_COMPLETE_CB_ID : + hcryp->InCpltCallback = pCallback; + break; + + case DAL_CRYP_OUTPUT_COMPLETE_CB_ID : + hcryp->OutCpltCallback = pCallback; + break; + + case DAL_CRYP_ERROR_CB_ID : + hcryp->ErrorCallback = pCallback; + break; + + case DAL_CRYP_MSPINIT_CB_ID : + hcryp->MspInitCallback = pCallback; + break; + + case DAL_CRYP_MSPDEINIT_CB_ID : + hcryp->MspDeInitCallback = pCallback; + break; + + default : + /* Update the error code */ + hcryp->ErrorCode |= DAL_CRYP_ERROR_INVALID_CALLBACK; + /* Return error status */ + status = DAL_ERROR; + break; + } + } + else if (hcryp->State == DAL_CRYP_STATE_RESET) + { + switch (CallbackID) + { + case DAL_CRYP_MSPINIT_CB_ID : + hcryp->MspInitCallback = pCallback; + break; + + case DAL_CRYP_MSPDEINIT_CB_ID : + hcryp->MspDeInitCallback = pCallback; + break; + + default : + /* Update the error code */ + hcryp->ErrorCode |= DAL_CRYP_ERROR_INVALID_CALLBACK; + /* Return error status */ + status = DAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + hcryp->ErrorCode |= DAL_CRYP_ERROR_INVALID_CALLBACK; + /* Return error status */ + status = DAL_ERROR; + } + + /* Release Lock */ + __DAL_UNLOCK(hcryp); + + return status; +} + +/** + * @brief Unregister an CRYP Callback + * CRYP callback is redirected to the weak predefined callback + * @param hcryp cryp handle + * @param CallbackID ID of the callback to be unregistered + * This parameter can be one of the following values: + * @arg @ref DAL_CRYP_INPUT_COMPLETE_CB_ID Input FIFO transfer completed callback ID + * @arg @ref DAL_CRYP_OUTPUT_COMPLETE_CB_ID Output FIFO transfer completed callback ID + * @arg @ref DAL_CRYP_ERROR_CB_ID Error callback ID + * @arg @ref DAL_CRYP_MSPINIT_CB_ID MspInit callback ID + * @arg @ref DAL_CRYP_MSPDEINIT_CB_ID MspDeInit callback ID + * @retval status + */ +DAL_StatusTypeDef DAL_CRYP_UnRegisterCallback(CRYP_HandleTypeDef *hcryp, DAL_CRYP_CallbackIDTypeDef CallbackID) +{ + DAL_StatusTypeDef status = DAL_OK; + + /* Process locked */ + __DAL_LOCK(hcryp); + + if (hcryp->State == DAL_CRYP_STATE_READY) + { + switch (CallbackID) + { + case DAL_CRYP_INPUT_COMPLETE_CB_ID : + hcryp->InCpltCallback = DAL_CRYP_InCpltCallback; /* Legacy weak InCpltCallback */ + break; + + case DAL_CRYP_OUTPUT_COMPLETE_CB_ID : + hcryp->OutCpltCallback = DAL_CRYP_OutCpltCallback; /* Legacy weak OutCpltCallback */ + break; + + case DAL_CRYP_ERROR_CB_ID : + hcryp->ErrorCallback = DAL_CRYP_ErrorCallback; /* Legacy weak ErrorCallback */ + break; + + case DAL_CRYP_MSPINIT_CB_ID : + hcryp->MspInitCallback = DAL_CRYP_MspInit; + break; + + case DAL_CRYP_MSPDEINIT_CB_ID : + hcryp->MspDeInitCallback = DAL_CRYP_MspDeInit; + break; + + default : + /* Update the error code */ + hcryp->ErrorCode |= DAL_CRYP_ERROR_INVALID_CALLBACK; + /* Return error status */ + status = DAL_ERROR; + break; + } + } + else if (hcryp->State == DAL_CRYP_STATE_RESET) + { + switch (CallbackID) + { + case DAL_CRYP_MSPINIT_CB_ID : + hcryp->MspInitCallback = DAL_CRYP_MspInit; + break; + + case DAL_CRYP_MSPDEINIT_CB_ID : + hcryp->MspDeInitCallback = DAL_CRYP_MspDeInit; + break; + + default : + /* Update the error code */ + hcryp->ErrorCode |= DAL_CRYP_ERROR_INVALID_CALLBACK; + /* Return error status */ + status = DAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + hcryp->ErrorCode |= DAL_CRYP_ERROR_INVALID_CALLBACK; + /* Return error status */ + status = DAL_ERROR; + } + + /* Release Lock */ + __DAL_UNLOCK(hcryp); + + return status; +} +#endif /* USE_DAL_UART_REGISTER_CALLBACKS */ +/** + * @} + */ + +/** @defgroup CRYP_Exported_Functions_Group2 Encrypt Decrypt functions + * @brief processing functions. + * +@verbatim + ============================================================================== + ##### Encrypt Decrypt functions ##### + ============================================================================== + [..] This section provides API allowing to Encrypt/Decrypt Data following + Standard DES/TDES or AES, and Algorithm configured by the user: + (+) Standard DES/TDES only supported by CRYP1 IP, below list of Algorithm supported : + - Electronic Code Book(ECB) + - Cipher Block Chaining (CBC) + (+) Standard AES supported by CRYP1 IP & TinyAES, list of Algorithm supported: + - Electronic Code Book(ECB) + - Cipher Block Chaining (CBC) + - Counter mode (CTR) + - Cipher Block Chaining (CBC) + - Counter mode (CTR) + - Galois/counter mode (GCM) + - Counter with Cipher Block Chaining-Message(CCM) + [..] Three processing functions are available: + (+) Polling mode : DAL_CRYP_Encrypt & DAL_CRYP_Decrypt + (+) Interrupt mode : DAL_CRYP_Encrypt_IT & DAL_CRYP_Decrypt_IT + (+) DMA mode : DAL_CRYP_Encrypt_DMA & DAL_CRYP_Decrypt_DMA + +@endverbatim + * @{ + */ + + +/** + * @brief Encryption mode. + * @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains + * the configuration information for CRYP module + * @param Input: Pointer to the input buffer (plaintext) + * @param Size: Length of the plaintext buffer in word. + * @param Output: Pointer to the output buffer(ciphertext) + * @param Timeout: Specify Timeout value + * @retval DAL status + */ +DAL_StatusTypeDef DAL_CRYP_Encrypt(CRYP_HandleTypeDef *hcryp, uint32_t *Input, uint16_t Size, uint32_t *Output, + uint32_t Timeout) +{ + uint32_t algo; + DAL_StatusTypeDef status; + + if (hcryp->State == DAL_CRYP_STATE_READY) + { + /* Change state Busy */ + hcryp->State = DAL_CRYP_STATE_BUSY; + + /* Process locked */ + __DAL_LOCK(hcryp); + + /* Reset CrypInCount, CrypOutCount and Initialize pCrypInBuffPtr and pCrypOutBuffPtr parameters*/ + hcryp->CrypInCount = 0U; + hcryp->CrypOutCount = 0U; + hcryp->pCrypInBuffPtr = Input; + hcryp->pCrypOutBuffPtr = Output; + + /* Calculate Size parameter in Byte*/ + if (hcryp->Init.DataWidthUnit == CRYP_DATAWIDTHUNIT_WORD) + { + hcryp->Size = Size * 4U; + } + else + { + hcryp->Size = Size; + } + +#if defined (CRYP) + /* Set Encryption operating mode*/ + MODIFY_REG(hcryp->Instance->CTRL, CRYP_CTRL_ALGODIRSEL, CRYP_OPERATINGMODE_ENCRYPT); + + /* algo get algorithm selected */ + algo = hcryp->Instance->CTRL & CRYP_CTRL_ALGOMSEL; + + switch (algo) + { + case CRYP_DES_ECB: + case CRYP_DES_CBC: + case CRYP_TDES_ECB: + case CRYP_TDES_CBC: + + /*Set Key */ + hcryp->Instance->K1L = *(uint32_t *)(hcryp->Init.pKey); + hcryp->Instance->K1R = *(uint32_t *)(hcryp->Init.pKey + 1); + if ((hcryp->Init.Algorithm == CRYP_TDES_ECB) || (hcryp->Init.Algorithm == CRYP_TDES_CBC)) + { + hcryp->Instance->K2L = *(uint32_t *)(hcryp->Init.pKey + 2); + hcryp->Instance->K2R = *(uint32_t *)(hcryp->Init.pKey + 3); + hcryp->Instance->K3L = *(uint32_t *)(hcryp->Init.pKey + 4); + hcryp->Instance->K3R = *(uint32_t *)(hcryp->Init.pKey + 5); + } + + /*Set Initialization Vector (IV)*/ + if ((hcryp->Init.Algorithm == CRYP_DES_CBC) || (hcryp->Init.Algorithm == CRYP_TDES_CBC)) + { + hcryp->Instance->IV0L = *(uint32_t *)(hcryp->Init.pInitVect); + hcryp->Instance->IV0R = *(uint32_t *)(hcryp->Init.pInitVect + 1); + } + + /* Flush FIFO */ + DAL_CRYP_FIFO_FLUSH(hcryp); + + /* Set the phase */ + hcryp->Phase = CRYP_PHASE_PROCESS; + + /* Statrt DES/TDES encryption process */ + status = CRYP_TDES_Process(hcryp, Timeout); + break; + + case CRYP_AES_ECB: + case CRYP_AES_CBC: + case CRYP_AES_CTR: + + /* AES encryption */ + status = CRYP_AES_Encrypt(hcryp, Timeout); + break; + #if defined (CRYP_CTRL_ALGOMSEL_AES_GCM) + case CRYP_AES_GCM: + + /* AES GCM encryption */ + status = CRYP_AESGCM_Process(hcryp, Timeout); + + break; + + case CRYP_AES_CCM: + + /* AES CCM encryption */ + status = CRYP_AESCCM_Process(hcryp, Timeout); + break; + #endif /* GCM CCM defined*/ + default: + hcryp->ErrorCode |= DAL_CRYP_ERROR_NOT_SUPPORTED; + /* Change the CRYP peripheral state */ + hcryp->State = DAL_CRYP_STATE_READY; + /* Process unlocked */ + __DAL_UNLOCK(hcryp); + return DAL_ERROR; + } + +#else /*AES*/ + + /* Set the operating mode*/ + MODIFY_REG(hcryp->Instance->CTRL, AES_CR_MODE, CRYP_OPERATINGMODE_ENCRYPT); + + /* algo get algorithm selected */ + algo = hcryp->Instance->CTRL & AES_CR_CHMOD; + + switch (algo) + { + + case CRYP_AES_ECB: + case CRYP_AES_CBC: + case CRYP_AES_CTR: + + /* AES encryption */ + status = CRYP_AES_Encrypt(hcryp, Timeout); + break; + + case CRYP_AES_GCM_GMAC: + + /* AES GCM encryption */ + status = CRYP_AESGCM_Process(hcryp, Timeout) ; + break; + + case CRYP_AES_CCM: + + /* AES CCM encryption */ + status = CRYP_AESCCM_Process(hcryp, Timeout); + break; + + default: + hcryp->ErrorCode |= DAL_CRYP_ERROR_NOT_SUPPORTED; + /* Change the CRYP peripheral state */ + hcryp->State = DAL_CRYP_STATE_READY; + /* Process unlocked */ + __DAL_UNLOCK(hcryp); + return DAL_ERROR; + } +#endif /*end AES or CRYP */ + + if (status == DAL_OK) + { + /* Change the CRYP peripheral state */ + hcryp->State = DAL_CRYP_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hcryp); + } + } + else + { + /* Busy error code field */ + hcryp->ErrorCode |= DAL_CRYP_ERROR_BUSY; + return DAL_ERROR; + } + + /* Return function status */ + return DAL_OK; +} + +/** + * @brief Decryption mode. + * @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains + * the configuration information for CRYP module + * @param Input: Pointer to the input buffer (ciphertext ) + * @param Size: Length of the plaintext buffer in word. + * @param Output: Pointer to the output buffer(plaintext) + * @param Timeout: Specify Timeout value + * @retval DAL status + */ +DAL_StatusTypeDef DAL_CRYP_Decrypt(CRYP_HandleTypeDef *hcryp, uint32_t *Input, uint16_t Size, uint32_t *Output, + uint32_t Timeout) +{ + DAL_StatusTypeDef status; + uint32_t algo; + + if (hcryp->State == DAL_CRYP_STATE_READY) + { + /* Change state Busy */ + hcryp->State = DAL_CRYP_STATE_BUSY; + + /* Process locked */ + __DAL_LOCK(hcryp); + + /* Reset CrypInCount, CrypOutCount and Initialize pCrypInBuffPtr and pCrypOutBuffPtr parameters*/ + hcryp->CrypInCount = 0U; + hcryp->CrypOutCount = 0U; + hcryp->pCrypInBuffPtr = Input; + hcryp->pCrypOutBuffPtr = Output; + + /* Calculate Size parameter in Byte*/ + if (hcryp->Init.DataWidthUnit == CRYP_DATAWIDTHUNIT_WORD) + { + hcryp->Size = Size * 4U; + } + else + { + hcryp->Size = Size; + } + +#if defined (CRYP) + + /* Set Decryption operating mode*/ + MODIFY_REG(hcryp->Instance->CTRL, CRYP_CTRL_ALGODIRSEL, CRYP_OPERATINGMODE_DECRYPT); + + /* algo get algorithm selected */ + algo = hcryp->Instance->CTRL & CRYP_CTRL_ALGOMSEL; + + switch (algo) + { + case CRYP_DES_ECB: + case CRYP_DES_CBC: + case CRYP_TDES_ECB: + case CRYP_TDES_CBC: + + /*Set Key */ + hcryp->Instance->K1L = *(uint32_t *)(hcryp->Init.pKey); + hcryp->Instance->K1R = *(uint32_t *)(hcryp->Init.pKey + 1); + if ((hcryp->Init.Algorithm == CRYP_TDES_ECB) || (hcryp->Init.Algorithm == CRYP_TDES_CBC)) + { + hcryp->Instance->K2L = *(uint32_t *)(hcryp->Init.pKey + 2); + hcryp->Instance->K2R = *(uint32_t *)(hcryp->Init.pKey + 3); + hcryp->Instance->K3L = *(uint32_t *)(hcryp->Init.pKey + 4); + hcryp->Instance->K3R = *(uint32_t *)(hcryp->Init.pKey + 5); + } + + /*Set Initialization Vector (IV)*/ + if ((hcryp->Init.Algorithm == CRYP_DES_CBC) || (hcryp->Init.Algorithm == CRYP_TDES_CBC)) + { + hcryp->Instance->IV0L = *(uint32_t *)(hcryp->Init.pInitVect); + hcryp->Instance->IV0R = *(uint32_t *)(hcryp->Init.pInitVect + 1); + } + + /* Flush FIFO */ + DAL_CRYP_FIFO_FLUSH(hcryp); + + /* Set the phase */ + hcryp->Phase = CRYP_PHASE_PROCESS; + + /* Start DES/TDES decryption process */ + status = CRYP_TDES_Process(hcryp, Timeout); + + break; + + case CRYP_AES_ECB: + case CRYP_AES_CBC: + case CRYP_AES_CTR: + + /* AES decryption */ + status = CRYP_AES_Decrypt(hcryp, Timeout); + break; + #if defined (CRYP_CTRL_ALGOMSEL_AES_GCM) + case CRYP_AES_GCM: + + /* AES GCM decryption */ + status = CRYP_AESGCM_Process(hcryp, Timeout) ; + break; + + case CRYP_AES_CCM: + + /* AES CCM decryption */ + status = CRYP_AESCCM_Process(hcryp, Timeout); + break; + #endif /* GCM CCM defined*/ + default: + hcryp->ErrorCode |= DAL_CRYP_ERROR_NOT_SUPPORTED; + /* Change the CRYP peripheral state */ + hcryp->State = DAL_CRYP_STATE_READY; + /* Process unlocked */ + __DAL_UNLOCK(hcryp); + return DAL_ERROR; + } + +#else /*AES*/ + + /* Set Decryption operating mode*/ + MODIFY_REG(hcryp->Instance->CTRL, AES_CR_MODE, CRYP_OPERATINGMODE_DECRYPT); + + /* algo get algorithm selected */ + algo = hcryp->Instance->CTRL & AES_CR_CHMOD; + + switch (algo) + { + + case CRYP_AES_ECB: + case CRYP_AES_CBC: + case CRYP_AES_CTR: + + /* AES decryption */ + status = CRYP_AES_Decrypt(hcryp, Timeout); + break; + + case CRYP_AES_GCM_GMAC: + + /* AES GCM decryption */ + status = CRYP_AESGCM_Process(hcryp, Timeout) ; + break; + + case CRYP_AES_CCM: + + /* AES CCM decryption */ + status = CRYP_AESCCM_Process(hcryp, Timeout); + break; + + default: + hcryp->ErrorCode |= DAL_CRYP_ERROR_NOT_SUPPORTED; + /* Change the CRYP peripheral state */ + hcryp->State = DAL_CRYP_STATE_READY; + /* Process unlocked */ + __DAL_UNLOCK(hcryp); + return DAL_ERROR; + } +#endif /* End AES or CRYP */ + + if (status == DAL_OK) + { + /* Change the CRYP peripheral state */ + hcryp->State = DAL_CRYP_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hcryp); + } + } + else + { + /* Busy error code field */ + hcryp->ErrorCode |= DAL_CRYP_ERROR_BUSY; + return DAL_ERROR; + } + + /* Return function status */ + return DAL_OK; +} + +/** + * @brief Encryption in interrupt mode. + * @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains + * the configuration information for CRYP module + * @param Input: Pointer to the input buffer (plaintext) + * @param Size: Length of the plaintext buffer in word + * @param Output: Pointer to the output buffer(ciphertext) + * @retval DAL status + */ +DAL_StatusTypeDef DAL_CRYP_Encrypt_IT(CRYP_HandleTypeDef *hcryp, uint32_t *Input, uint16_t Size, uint32_t *Output) +{ + uint32_t algo; + DAL_StatusTypeDef status = DAL_OK; + + if (hcryp->State == DAL_CRYP_STATE_READY) + { + /* Change state Busy */ + hcryp->State = DAL_CRYP_STATE_BUSY; + + /* Process locked */ + __DAL_LOCK(hcryp); + + /* Reset CrypInCount, CrypOutCount and Initialize pCrypInBuffPtr and pCrypOutBuffPtr parameters*/ + hcryp->CrypInCount = 0U; + hcryp->CrypOutCount = 0U; + hcryp->pCrypInBuffPtr = Input; + hcryp->pCrypOutBuffPtr = Output; + + /* Calculate Size parameter in Byte*/ + if (hcryp->Init.DataWidthUnit == CRYP_DATAWIDTHUNIT_WORD) + { + hcryp->Size = Size * 4U; + } + else + { + hcryp->Size = Size; + } + +#if defined (CRYP) + + /* Set encryption operating mode*/ + MODIFY_REG(hcryp->Instance->CTRL, CRYP_CTRL_ALGODIRSEL, CRYP_OPERATINGMODE_ENCRYPT); + + /* algo get algorithm selected */ + algo = (hcryp->Instance->CTRL & CRYP_CTRL_ALGOMSEL); + + switch (algo) + { + case CRYP_DES_ECB: + case CRYP_DES_CBC: + case CRYP_TDES_ECB: + case CRYP_TDES_CBC: + + /*Set Key */ + hcryp->Instance->K1L = *(uint32_t *)(hcryp->Init.pKey); + hcryp->Instance->K1R = *(uint32_t *)(hcryp->Init.pKey + 1); + if ((hcryp->Init.Algorithm == CRYP_TDES_ECB) || (hcryp->Init.Algorithm == CRYP_TDES_CBC)) + { + hcryp->Instance->K2L = *(uint32_t *)(hcryp->Init.pKey + 2); + hcryp->Instance->K2R = *(uint32_t *)(hcryp->Init.pKey + 3); + hcryp->Instance->K3L = *(uint32_t *)(hcryp->Init.pKey + 4); + hcryp->Instance->K3R = *(uint32_t *)(hcryp->Init.pKey + 5); + } + /* Set the Initialization Vector*/ + if ((hcryp->Init.Algorithm == CRYP_DES_CBC) || (hcryp->Init.Algorithm == CRYP_TDES_CBC)) + { + hcryp->Instance->IV0L = *(uint32_t *)(hcryp->Init.pInitVect); + hcryp->Instance->IV0R = *(uint32_t *)(hcryp->Init.pInitVect + 1); + } + + /* Flush FIFO */ + DAL_CRYP_FIFO_FLUSH(hcryp); + + /* Set the phase */ + hcryp->Phase = CRYP_PHASE_PROCESS; + + /* Enable interrupts */ + __DAL_CRYP_ENABLE_IT(hcryp, CRYP_IT_INI | CRYP_IT_OUTI); + + /* Enable CRYP to start DES/TDES process*/ + __DAL_CRYP_ENABLE(hcryp); + break; + + case CRYP_AES_ECB: + case CRYP_AES_CBC: + case CRYP_AES_CTR: + + status = CRYP_AES_Encrypt_IT(hcryp); + break; + #if defined (CRYP_CTRL_ALGOMSEL_AES_GCM) + case CRYP_AES_GCM: + + status = CRYP_AESGCM_Process_IT(hcryp) ; + break; + + case CRYP_AES_CCM: + + status = CRYP_AESCCM_Process_IT(hcryp); + break; + #endif /* GCM CCM defined*/ + default: + hcryp->ErrorCode |= DAL_CRYP_ERROR_NOT_SUPPORTED; + /* Change the CRYP peripheral state */ + hcryp->State = DAL_CRYP_STATE_READY; + /* Process unlocked */ + __DAL_UNLOCK(hcryp); + status = DAL_ERROR; + break; + } + +#else /* AES */ + + /* Set encryption operating mode*/ + MODIFY_REG(hcryp->Instance->CTRL, AES_CR_MODE, CRYP_OPERATINGMODE_ENCRYPT); + + /* algo get algorithm selected */ + algo = hcryp->Instance->CTRL & AES_CR_CHMOD; + + switch (algo) + { + case CRYP_AES_ECB: + case CRYP_AES_CBC: + case CRYP_AES_CTR: + + /* AES encryption */ + status = CRYP_AES_Encrypt_IT(hcryp); + break; + + case CRYP_AES_GCM_GMAC: + + /* AES GCM encryption */ + status = CRYP_AESGCM_Process_IT(hcryp) ; + break; + + case CRYP_AES_CCM: + + /* AES CCM encryption */ + status = CRYP_AESCCM_Process_IT(hcryp); + break; + + default: + hcryp->ErrorCode |= DAL_CRYP_ERROR_NOT_SUPPORTED; + /* Change the CRYP peripheral state */ + hcryp->State = DAL_CRYP_STATE_READY; + /* Process unlocked */ + __DAL_UNLOCK(hcryp); + status = DAL_ERROR; + break; + } +#endif /*end AES or CRYP*/ + + } + else + { + /* Busy error code field */ + hcryp->ErrorCode |= DAL_CRYP_ERROR_BUSY; + status = DAL_ERROR; + } + + /* Return function status */ + return status; +} + +/** + * @brief Decryption in itnterrupt mode. + * @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains + * the configuration information for CRYP module + * @param Input: Pointer to the input buffer (ciphertext ) + * @param Size: Length of the plaintext buffer in word. + * @param Output: Pointer to the output buffer(plaintext) + * @retval DAL status + */ +DAL_StatusTypeDef DAL_CRYP_Decrypt_IT(CRYP_HandleTypeDef *hcryp, uint32_t *Input, uint16_t Size, uint32_t *Output) +{ + uint32_t algo; + DAL_StatusTypeDef status = DAL_OK; + + if (hcryp->State == DAL_CRYP_STATE_READY) + { + /* Change state Busy */ + hcryp->State = DAL_CRYP_STATE_BUSY; + + /* Process locked */ + __DAL_LOCK(hcryp); + + /* Reset CrypInCount, CrypOutCount and Initialize pCrypInBuffPtr and pCrypOutBuffPtr parameters*/ + hcryp->CrypInCount = 0U; + hcryp->CrypOutCount = 0U; + hcryp->pCrypInBuffPtr = Input; + hcryp->pCrypOutBuffPtr = Output; + + /* Calculate Size parameter in Byte*/ + if (hcryp->Init.DataWidthUnit == CRYP_DATAWIDTHUNIT_WORD) + { + hcryp->Size = Size * 4U; + } + else + { + hcryp->Size = Size; + } + +#if defined (CRYP) + + /* Set decryption operating mode*/ + MODIFY_REG(hcryp->Instance->CTRL, CRYP_CTRL_ALGODIRSEL, CRYP_OPERATINGMODE_DECRYPT); + + /* algo get algorithm selected */ + algo = hcryp->Instance->CTRL & CRYP_CTRL_ALGOMSEL; + + switch (algo) + { + case CRYP_DES_ECB: + case CRYP_DES_CBC: + case CRYP_TDES_ECB: + case CRYP_TDES_CBC: + + /*Set Key */ + hcryp->Instance->K1L = *(uint32_t *)(hcryp->Init.pKey); + hcryp->Instance->K1R = *(uint32_t *)(hcryp->Init.pKey + 1); + if ((hcryp->Init.Algorithm == CRYP_TDES_ECB) || (hcryp->Init.Algorithm == CRYP_TDES_CBC)) + { + hcryp->Instance->K2L = *(uint32_t *)(hcryp->Init.pKey + 2); + hcryp->Instance->K2R = *(uint32_t *)(hcryp->Init.pKey + 3); + hcryp->Instance->K3L = *(uint32_t *)(hcryp->Init.pKey + 4); + hcryp->Instance->K3R = *(uint32_t *)(hcryp->Init.pKey + 5); + } + + /* Set the Initialization Vector*/ + if ((hcryp->Init.Algorithm == CRYP_DES_CBC) || (hcryp->Init.Algorithm == CRYP_TDES_CBC)) + { + hcryp->Instance->IV0L = *(uint32_t *)(hcryp->Init.pInitVect); + hcryp->Instance->IV0R = *(uint32_t *)(hcryp->Init.pInitVect + 1); + } + /* Flush FIFO */ + DAL_CRYP_FIFO_FLUSH(hcryp); + + /* Set the phase */ + hcryp->Phase = CRYP_PHASE_PROCESS; + + /* Enable interrupts */ + __DAL_CRYP_ENABLE_IT(hcryp, CRYP_IT_INI | CRYP_IT_OUTI); + + /* Enable CRYP and start DES/TDES process*/ + __DAL_CRYP_ENABLE(hcryp); + + break; + + case CRYP_AES_ECB: + case CRYP_AES_CBC: + case CRYP_AES_CTR: + + /* AES decryption */ + status = CRYP_AES_Decrypt_IT(hcryp); + break; + #if defined (CRYP_CTRL_ALGOMSEL_AES_GCM) + case CRYP_AES_GCM: + + /* AES GCM decryption */ + status = CRYP_AESGCM_Process_IT(hcryp) ; + break; + + case CRYP_AES_CCM: + + /* AES CCMdecryption */ + status = CRYP_AESCCM_Process_IT(hcryp); + break; + #endif /* GCM CCM defined*/ + default: + hcryp->ErrorCode |= DAL_CRYP_ERROR_NOT_SUPPORTED; + /* Change the CRYP peripheral state */ + hcryp->State = DAL_CRYP_STATE_READY; + /* Process unlocked */ + __DAL_UNLOCK(hcryp); + status = DAL_ERROR; + break; + } + +#else /*AES*/ + + /* Set decryption operating mode*/ + MODIFY_REG(hcryp->Instance->CTRL, AES_CR_MODE, CRYP_OPERATINGMODE_DECRYPT); + + /* algo get algorithm selected */ + algo = hcryp->Instance->CTRL & AES_CR_CHMOD; + + switch (algo) + { + case CRYP_AES_ECB: + case CRYP_AES_CBC: + case CRYP_AES_CTR: + + /* AES decryption */ + status = CRYP_AES_Decrypt_IT(hcryp); + break; + + case CRYP_AES_GCM_GMAC: + + /* AES GCM decryption */ + status = CRYP_AESGCM_Process_IT(hcryp) ; + break; + + case CRYP_AES_CCM: + + /* AES CCM decryption */ + status = CRYP_AESCCM_Process_IT(hcryp); + break; + + default: + hcryp->ErrorCode |= DAL_CRYP_ERROR_NOT_SUPPORTED; + /* Change the CRYP peripheral state */ + hcryp->State = DAL_CRYP_STATE_READY; + /* Process unlocked */ + __DAL_UNLOCK(hcryp); + status = DAL_ERROR; + break; + } +#endif /* End AES or CRYP */ + + } + else + { + /* Busy error code field */ + hcryp->ErrorCode |= DAL_CRYP_ERROR_BUSY; + status = DAL_ERROR; + } + + /* Return function status */ + return status; +} + +/** + * @brief Encryption in DMA mode. + * @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains + * the configuration information for CRYP module + * @param Input: Pointer to the input buffer (plaintext) + * @param Size: Length of the plaintext buffer in word. + * @param Output: Pointer to the output buffer(ciphertext) + * @retval DAL status + */ +DAL_StatusTypeDef DAL_CRYP_Encrypt_DMA(CRYP_HandleTypeDef *hcryp, uint32_t *Input, uint16_t Size, uint32_t *Output) +{ + uint32_t algo; + DAL_StatusTypeDef status = DAL_OK; + uint32_t DoKeyIVConfig = 1U; /* By default, carry out peripheral Key and IV configuration */ + + if (hcryp->State == DAL_CRYP_STATE_READY) + { + /* Change state Busy */ + hcryp->State = DAL_CRYP_STATE_BUSY; + + /* Process locked */ + __DAL_LOCK(hcryp); + + /* Reset CrypInCount, CrypOutCount and Initialize pCrypInBuffPtr and pCrypOutBuffPtr parameters*/ + hcryp->CrypInCount = 0U; + hcryp->CrypOutCount = 0U; + hcryp->pCrypInBuffPtr = Input; + hcryp->pCrypOutBuffPtr = Output; + + /* Calculate Size parameter in Byte*/ + if (hcryp->Init.DataWidthUnit == CRYP_DATAWIDTHUNIT_WORD) + { + hcryp->Size = Size * 4U; + } + else + { + hcryp->Size = Size; + } + +#if defined (CRYP) + + /* Set encryption operating mode*/ + MODIFY_REG(hcryp->Instance->CTRL, CRYP_CTRL_ALGODIRSEL, CRYP_OPERATINGMODE_ENCRYPT); + + /* algo get algorithm selected */ + algo = hcryp->Instance->CTRL & CRYP_CTRL_ALGOMSEL; + + switch (algo) + { + case CRYP_DES_ECB: + case CRYP_DES_CBC: + case CRYP_TDES_ECB: + case CRYP_TDES_CBC: + + /*Set Key */ + hcryp->Instance->K1L = *(uint32_t *)(hcryp->Init.pKey); + hcryp->Instance->K1R = *(uint32_t *)(hcryp->Init.pKey + 1); + if ((hcryp->Init.Algorithm == CRYP_TDES_ECB) || (hcryp->Init.Algorithm == CRYP_TDES_CBC)) + { + hcryp->Instance->K2L = *(uint32_t *)(hcryp->Init.pKey + 2); + hcryp->Instance->K2R = *(uint32_t *)(hcryp->Init.pKey + 3); + hcryp->Instance->K3L = *(uint32_t *)(hcryp->Init.pKey + 4); + hcryp->Instance->K3R = *(uint32_t *)(hcryp->Init.pKey + 5); + } + + /* Set the Initialization Vector*/ + if ((hcryp->Init.Algorithm == CRYP_DES_CBC) || (hcryp->Init.Algorithm == CRYP_TDES_CBC)) + { + hcryp->Instance->IV0L = *(uint32_t *)(hcryp->Init.pInitVect); + hcryp->Instance->IV0R = *(uint32_t *)(hcryp->Init.pInitVect + 1); + } + + /* Flush FIFO */ + DAL_CRYP_FIFO_FLUSH(hcryp); + + /* Set the phase */ + hcryp->Phase = CRYP_PHASE_PROCESS; + + /* Start DMA process transfer for DES/TDES */ + CRYP_SetDMAConfig(hcryp, (uint32_t)(hcryp->pCrypInBuffPtr), ((uint16_t)(hcryp->Size) / 4U), + (uint32_t)(hcryp->pCrypOutBuffPtr)); + break; + + case CRYP_AES_ECB: + case CRYP_AES_CBC: + case CRYP_AES_CTR: + + if (hcryp->Init.KeyIVConfigSkip == CRYP_KEYIVCONFIG_ONCE) + { + if (hcryp->KeyIVConfig == 1U) + { + /* If the Key and IV configuration has to be done only once + and if it has already been done, skip it */ + DoKeyIVConfig = 0U; + } + else + { + /* If the Key and IV configuration has to be done only once + and if it has not been done already, do it and set KeyIVConfig + to keep track it won't have to be done again next time */ + hcryp->KeyIVConfig = 1U; + } + } + + if (DoKeyIVConfig == 1U) + { + /* Set the Key*/ + CRYP_SetKey(hcryp, hcryp->Init.KeySize); + + /* Set the Initialization Vector*/ + if (hcryp->Init.Algorithm != CRYP_AES_ECB) + { + hcryp->Instance->IV0L = *(uint32_t *)(hcryp->Init.pInitVect); + hcryp->Instance->IV0R = *(uint32_t *)(hcryp->Init.pInitVect + 1U); + hcryp->Instance->IV1L = *(uint32_t *)(hcryp->Init.pInitVect + 2U); + hcryp->Instance->IV1R = *(uint32_t *)(hcryp->Init.pInitVect + 3U); + } + } /* if (DoKeyIVConfig == 1U) */ + + /* Set the phase */ + hcryp->Phase = CRYP_PHASE_PROCESS; + + /* Start DMA process transfer for AES */ + CRYP_SetDMAConfig(hcryp, (uint32_t)(hcryp->pCrypInBuffPtr), ((uint16_t)(hcryp->Size) / 4U), + (uint32_t)(hcryp->pCrypOutBuffPtr)); + break; + #if defined (CRYP_CTRL_ALGOMSEL_AES_GCM) + case CRYP_AES_GCM: + /* AES GCM encryption */ + status = CRYP_AESGCM_Process_DMA(hcryp) ; + break; + + case CRYP_AES_CCM: + /* AES CCM encryption */ + status = CRYP_AESCCM_Process_DMA(hcryp); + break; + #endif /* GCM CCM defined*/ + default: + hcryp->ErrorCode |= DAL_CRYP_ERROR_NOT_SUPPORTED; + /* Change the CRYP peripheral state */ + hcryp->State = DAL_CRYP_STATE_READY; + /* Process unlocked */ + __DAL_UNLOCK(hcryp); + status = DAL_ERROR; + break; + } + +#else /*AES*/ + /* Set encryption operating mode*/ + MODIFY_REG(hcryp->Instance->CTRL, AES_CR_MODE, CRYP_OPERATINGMODE_ENCRYPT); + + /* algo get algorithm selected */ + algo = hcryp->Instance->CTRL & AES_CR_CHMOD; + + switch (algo) + { + + case CRYP_AES_ECB: + case CRYP_AES_CBC: + case CRYP_AES_CTR: + + if (hcryp->Init.KeyIVConfigSkip == CRYP_KEYIVCONFIG_ONCE) + { + if (hcryp->KeyIVConfig == 1U) + { + /* If the Key and IV configuration has to be done only once + and if it has already been done, skip it */ + DoKeyIVConfig = 0U; + } + else + { + /* If the Key and IV configuration has to be done only once + and if it has not been done already, do it and set KeyIVConfig + to keep track it won't have to be done again next time */ + hcryp->KeyIVConfig = 1U; + } + } + + if (DoKeyIVConfig == 1U) + { + /* Set the Key*/ + CRYP_SetKey(hcryp, hcryp->Init.KeySize); + + /* Set the Initialization Vector*/ + if (hcryp->Init.Algorithm != CRYP_AES_ECB) + { + hcryp->Instance->IVR3 = *(uint32_t *)(hcryp->Init.pInitVect); + hcryp->Instance->IVR2 = *(uint32_t *)(hcryp->Init.pInitVect + 1); + hcryp->Instance->IVR1 = *(uint32_t *)(hcryp->Init.pInitVect + 2); + hcryp->Instance->IVR0 = *(uint32_t *)(hcryp->Init.pInitVect + 3); + } + } /* if (DoKeyIVConfig == 1U) */ + /* Set the phase */ + hcryp->Phase = CRYP_PHASE_PROCESS; + + /* Start DMA process transfer for AES */ + CRYP_SetDMAConfig(hcryp, (uint32_t)(hcryp->pCrypInBuffPtr), (hcryp->Size / 4U), (uint32_t)(hcryp->pCrypOutBuffPtr)); + break; + + case CRYP_AES_GCM_GMAC: + /* AES GCM encryption */ + status = CRYP_AESGCM_Process_DMA(hcryp) ; + break; + + case CRYP_AES_CCM: + /* AES CCM encryption */ + status = CRYP_AESCCM_Process_DMA(hcryp); + break; + + default: + hcryp->ErrorCode |= DAL_CRYP_ERROR_NOT_SUPPORTED; + /* Change the CRYP peripheral state */ + hcryp->State = DAL_CRYP_STATE_READY; + /* Process unlocked */ + __DAL_UNLOCK(hcryp); + status = DAL_ERROR; + break; + } +#endif /* End AES or CRYP */ + + } + else + { + /* Busy error code field */ + hcryp->ErrorCode |= DAL_CRYP_ERROR_BUSY; + status = DAL_ERROR; + } + + /* Return function status */ + return status; +} + +/** + * @brief Decryption in DMA mode. + * @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains + * the configuration information for CRYP module + * @param Input: Pointer to the input buffer (ciphertext ) + * @param Size: Length of the plaintext buffer in word + * @param Output: Pointer to the output buffer(plaintext) + * @retval DAL status + */ +DAL_StatusTypeDef DAL_CRYP_Decrypt_DMA(CRYP_HandleTypeDef *hcryp, uint32_t *Input, uint16_t Size, uint32_t *Output) +{ + uint32_t algo; + DAL_StatusTypeDef status = DAL_OK; + + if (hcryp->State == DAL_CRYP_STATE_READY) + { + + /* Change state Busy */ + hcryp->State = DAL_CRYP_STATE_BUSY; + + /* Process locked */ + __DAL_LOCK(hcryp); + + /* Reset CrypInCount, CrypOutCount and Initialize pCrypInBuffPtr, pCrypOutBuffPtr and Size parameters*/ + hcryp->CrypInCount = 0U; + hcryp->CrypOutCount = 0U; + hcryp->pCrypInBuffPtr = Input; + hcryp->pCrypOutBuffPtr = Output; + + /* Calculate Size parameter in Byte*/ + if (hcryp->Init.DataWidthUnit == CRYP_DATAWIDTHUNIT_WORD) + { + hcryp->Size = Size * 4U; + } + else + { + hcryp->Size = Size; + } + +#if defined (CRYP) + + /* Set decryption operating mode*/ + MODIFY_REG(hcryp->Instance->CTRL, CRYP_CTRL_ALGODIRSEL, CRYP_OPERATINGMODE_DECRYPT); + + /* algo get algorithm selected */ + algo = hcryp->Instance->CTRL & CRYP_CTRL_ALGOMSEL; + + switch (algo) + { + case CRYP_DES_ECB: + case CRYP_DES_CBC: + case CRYP_TDES_ECB: + case CRYP_TDES_CBC: + + /*Set Key */ + hcryp->Instance->K1L = *(uint32_t *)(hcryp->Init.pKey); + hcryp->Instance->K1R = *(uint32_t *)(hcryp->Init.pKey + 1); + if ((hcryp->Init.Algorithm == CRYP_TDES_ECB) || (hcryp->Init.Algorithm == CRYP_TDES_CBC)) + { + hcryp->Instance->K2L = *(uint32_t *)(hcryp->Init.pKey + 2); + hcryp->Instance->K2R = *(uint32_t *)(hcryp->Init.pKey + 3); + hcryp->Instance->K3L = *(uint32_t *)(hcryp->Init.pKey + 4); + hcryp->Instance->K3R = *(uint32_t *)(hcryp->Init.pKey + 5); + } + + /* Set the Initialization Vector*/ + if ((hcryp->Init.Algorithm == CRYP_DES_CBC) || (hcryp->Init.Algorithm == CRYP_TDES_CBC)) + { + hcryp->Instance->IV0L = *(uint32_t *)(hcryp->Init.pInitVect); + hcryp->Instance->IV0R = *(uint32_t *)(hcryp->Init.pInitVect + 1); + } + + /* Flush FIFO */ + DAL_CRYP_FIFO_FLUSH(hcryp); + + /* Set the phase */ + hcryp->Phase = CRYP_PHASE_PROCESS; + + /* Start DMA process transfer for DES/TDES */ + CRYP_SetDMAConfig(hcryp, (uint32_t)(hcryp->pCrypInBuffPtr), ((uint16_t)(hcryp->Size) / 4U), + (uint32_t)(hcryp->pCrypOutBuffPtr)); + break; + + case CRYP_AES_ECB: + case CRYP_AES_CBC: + case CRYP_AES_CTR: + + /* AES decryption */ + status = CRYP_AES_Decrypt_DMA(hcryp); + break; + #if defined (CRYP_CTRL_ALGOMSEL_AES_GCM) + case CRYP_AES_GCM: + /* AES GCM decryption */ + status = CRYP_AESGCM_Process_DMA(hcryp) ; + break; + + case CRYP_AES_CCM: + /* AES CCM decryption */ + status = CRYP_AESCCM_Process_DMA(hcryp); + break; + #endif /* GCM CCM defined*/ + default: + hcryp->ErrorCode |= DAL_CRYP_ERROR_NOT_SUPPORTED; + /* Change the CRYP peripheral state */ + hcryp->State = DAL_CRYP_STATE_READY; + /* Process unlocked */ + __DAL_UNLOCK(hcryp); + status = DAL_ERROR; + break; + } + +#else /*AES*/ + + /* Set decryption operating mode*/ + MODIFY_REG(hcryp->Instance->CTRL, AES_CR_MODE, CRYP_OPERATINGMODE_DECRYPT); + + /* algo get algorithm selected */ + algo = hcryp->Instance->CTRL & AES_CR_CHMOD; + + switch (algo) + { + + case CRYP_AES_ECB: + case CRYP_AES_CBC: + case CRYP_AES_CTR: + + /* AES decryption */ + status = CRYP_AES_Decrypt_DMA(hcryp); + break; + + case CRYP_AES_GCM_GMAC: + /* AES GCM decryption */ + status = CRYP_AESGCM_Process_DMA(hcryp) ; + break; + + case CRYP_AES_CCM: + /* AES CCM decryption */ + status = CRYP_AESCCM_Process_DMA(hcryp); + break; + + default: + hcryp->ErrorCode |= DAL_CRYP_ERROR_NOT_SUPPORTED; + /* Change the CRYP peripheral state */ + hcryp->State = DAL_CRYP_STATE_READY; + /* Process unlocked */ + __DAL_UNLOCK(hcryp); + status = DAL_ERROR; + break; + } +#endif /* End AES or CRYP */ + } + else + { + /* Busy error code field */ + hcryp->ErrorCode |= DAL_CRYP_ERROR_BUSY; + status = DAL_ERROR; + } + + /* Return function status */ + return status; +} + +/** + * @} + */ + +/** @defgroup CRYP_Exported_Functions_Group3 CRYP IRQ handler management + * @brief CRYP IRQ handler. + * +@verbatim + ============================================================================== + ##### CRYP IRQ handler management ##### + ============================================================================== +[..] This section provides CRYP IRQ handler and callback functions. + (+) DAL_CRYP_IRQHandler CRYP interrupt request + (+) DAL_CRYP_InCpltCallback input data transfer complete callback + (+) DAL_CRYP_OutCpltCallback output data transfer complete callback + (+) DAL_CRYP_ErrorCallback CRYP error callback + (+) DAL_CRYP_GetState return the CRYP state + (+) DAL_CRYP_GetError return the CRYP error code +@endverbatim + * @{ + */ + +/** + * @brief This function handles cryptographic interrupt request. + * @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains + * the configuration information for CRYP module + * @retval None + */ +void DAL_CRYP_IRQHandler(CRYP_HandleTypeDef *hcryp) +{ + +#if defined (CRYP) + + uint32_t itstatus = hcryp->Instance->MINTSTS; + + if ((itstatus & (CRYP_IT_INI | CRYP_IT_OUTI)) != 0U) + { + if ((hcryp->Init.Algorithm == CRYP_DES_ECB) || (hcryp->Init.Algorithm == CRYP_DES_CBC) + || (hcryp->Init.Algorithm == CRYP_TDES_ECB) || (hcryp->Init.Algorithm == CRYP_TDES_CBC)) + { + CRYP_TDES_IT(hcryp); /* DES or TDES*/ + } + else if ((hcryp->Init.Algorithm == CRYP_AES_ECB) || (hcryp->Init.Algorithm == CRYP_AES_CBC) + || (hcryp->Init.Algorithm == CRYP_AES_CTR)) + { + CRYP_AES_IT(hcryp); /*AES*/ + } + #if defined (CRYP_CTRL_ALGOMSEL_AES_GCM) + else if ((hcryp->Init.Algorithm == CRYP_AES_GCM) || (hcryp->Init.Algorithm == CRYP_CTRL_ALGOMSEL_AES_CCM)) + { + /* if header phase */ + if ((hcryp->Instance->CTRL & CRYP_PHASE_HEADER) == CRYP_PHASE_HEADER) + { + CRYP_GCMCCM_SetHeaderPhase_IT(hcryp); + } + else /* if payload phase */ + { + CRYP_GCMCCM_SetPayloadPhase_IT(hcryp); + } + } + #endif /* GCM CCM defined*/ + else + { + /* Nothing to do */ + } + } + +#else /*AES*/ + if (__DAL_CRYP_GET_FLAG(hcryp, CRYP_IT_CCF) != RESET) + { + if (__DAL_CRYP_GET_IT_SOURCE(hcryp, CRYP_IT_CCFIE) != RESET) + { + + /* Clear computation complete flag */ + __DAL_CRYP_CLEAR_FLAG(hcryp, CRYP_CCF_CLEAR); + + if (hcryp->Init.Algorithm == CRYP_AES_GCM_GMAC) + { + + /* if header phase */ + if ((hcryp->Instance->CTRL & CRYP_PHASE_HEADER) == CRYP_PHASE_HEADER) + { + CRYP_GCMCCM_SetHeaderPhase_IT(hcryp); + } + else /* if payload phase */ + { + CRYP_GCMCCM_SetPayloadPhase_IT(hcryp); + } + } + else if (hcryp->Init.Algorithm == CRYP_AES_CCM) + { + /* if header phase */ + if (hcryp->Init.HeaderSize >= hcryp->CrypHeaderCount) + { + CRYP_GCMCCM_SetHeaderPhase_IT(hcryp); + } + else /* if payload phase */ + { + CRYP_GCMCCM_SetPayloadPhase_IT(hcryp); + } + } + else /* AES Algorithm ECB,CBC or CTR*/ + { + CRYP_AES_IT(hcryp); + } + } + } + /* Check if error occurred */ + if (__DAL_CRYP_GET_IT_SOURCE(hcryp, CRYP_IT_ERRIE) != RESET) + { + /* If write Error occurred */ + if (__DAL_CRYP_GET_FLAG(hcryp, CRYP_IT_WRERR) != RESET) + { + hcryp->ErrorCode |= DAL_CRYP_ERROR_WRITE; + } + /* If read Error occurred */ + if (__DAL_CRYP_GET_FLAG(hcryp, CRYP_IT_RDERR) != RESET) + { + hcryp->ErrorCode |= DAL_CRYP_ERROR_READ; + } + } +#endif /* End AES or CRYP */ +} + +/** + * @brief Return the CRYP error code. + * @param hcryp : pointer to a CRYP_HandleTypeDef structure that contains + * the configuration information for the CRYP IP + * @retval CRYP error code + */ +uint32_t DAL_CRYP_GetError(CRYP_HandleTypeDef *hcryp) +{ + return hcryp->ErrorCode; +} + +/** + * @brief Returns the CRYP state. + * @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains + * the configuration information for CRYP module. + * @retval DAL state + */ +DAL_CRYP_STATETypeDef DAL_CRYP_GetState(CRYP_HandleTypeDef *hcryp) +{ + return hcryp->State; +} + +/** + * @brief Input FIFO transfer completed callback. + * @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains + * the configuration information for CRYP module. + * @retval None + */ +__weak void DAL_CRYP_InCpltCallback(CRYP_HandleTypeDef *hcryp) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hcryp); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_CRYP_InCpltCallback can be implemented in the user file + */ +} + +/** + * @brief Output FIFO transfer completed callback. + * @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains + * the configuration information for CRYP module. + * @retval None + */ +__weak void DAL_CRYP_OutCpltCallback(CRYP_HandleTypeDef *hcryp) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hcryp); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_CRYP_OutCpltCallback can be implemented in the user file + */ +} + +/** + * @brief CRYP error callback. + * @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains + * the configuration information for CRYP module. + * @retval None + */ +__weak void DAL_CRYP_ErrorCallback(CRYP_HandleTypeDef *hcryp) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hcryp); + + /* NOTE : This function Should not be modified, when the callback is needed, + the DAL_CRYP_ErrorCallback could be implemented in the user file + */ +} +/** + * @} + */ + +/* Private functions ---------------------------------------------------------*/ +/** @addtogroup CRYP_Private_Functions + * @{ + */ + +#if defined (CRYP) + +/** + * @brief Encryption in ECB/CBC Algorithm with DES/TDES standard. + * @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains + * the configuration information for CRYP module + * @param Timeout: specify Timeout value + * @retval DAL status + */ +static DAL_StatusTypeDef CRYP_TDES_Process(CRYP_HandleTypeDef *hcryp, uint32_t Timeout) +{ + uint32_t temp[2]; /* Temporary CrypOutBuff */ + uint16_t incount; /* Temporary CrypInCount Value */ + uint16_t outcount; /* Temporary CrypOutCount Value */ + uint32_t i; + + /* Enable CRYP */ + __DAL_CRYP_ENABLE(hcryp); + /*Temporary CrypOutCount Value*/ + outcount = hcryp->CrypOutCount; + + /*Start processing*/ + while ((hcryp->CrypInCount < (hcryp->Size / 4U)) && (outcount < (hcryp->Size / 4U))) + { + /* Temporary CrypInCount Value */ + incount = hcryp->CrypInCount; + /* Write plain data and get cipher data */ + if (((hcryp->Instance->STS & CRYP_FLAG_IFNF) != 0x0U) && (incount < (hcryp->Size / 4U))) + { + /* Write the input block in the IN FIFO */ + hcryp->Instance->DATAIN = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount); + hcryp->CrypInCount++; + hcryp->Instance->DATAIN = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount); + hcryp->CrypInCount++; + } + + /* Wait for OFNE flag to be raised */ + if (CRYP_WaitOnOFNEFlag(hcryp, Timeout) != DAL_OK) + { + /* Disable the CRYP peripheral clock */ + __DAL_CRYP_DISABLE(hcryp); + + /* Change state & errorCode*/ + hcryp->ErrorCode |= DAL_CRYP_ERROR_TIMEOUT; + hcryp->State = DAL_CRYP_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hcryp); +#if (USE_DAL_CRYP_REGISTER_CALLBACKS == 1) + /*Call registered error callback*/ + hcryp->ErrorCallback(hcryp); +#else + /*Call legacy weak error callback*/ + DAL_CRYP_ErrorCallback(hcryp); +#endif /* USE_DAL_CRYP_REGISTER_CALLBACKS */ + } + + /*Temporary CrypOutCount Value*/ + outcount = hcryp->CrypOutCount; + + if (((hcryp->Instance->STS & CRYP_FLAG_OFNE) != 0x0U) && (outcount < (hcryp->Size / 4U))) + { + /* Read the output block from the Output FIFO and put them in temporary Buffer then get CrypOutBuff from temporary buffer */ + for (i = 0U; i < 2U; i++) + { + temp[i] = hcryp->Instance->DATAOUT; + } + i = 0U; + while (((hcryp->CrypOutCount < ((hcryp->Size) / 4U))) && (i < 2U)) + { + *(uint32_t *)(hcryp->pCrypOutBuffPtr + hcryp->CrypOutCount) = temp[i]; + hcryp->CrypOutCount++; + i++; + } + } + /*Temporary CrypOutCount Value*/ + outcount = hcryp->CrypOutCount; + } + /* Disable CRYP */ + __DAL_CRYP_DISABLE(hcryp); + /* Change the CRYP state */ + hcryp->State = DAL_CRYP_STATE_READY; + + /* Return function status */ + return DAL_OK; +} + +/** + * @brief CRYP block input/output data handling under interruption with DES/TDES standard. + * @note The function is called under interruption only, once + * interruptions have been enabled by CRYP_Decrypt_IT() and CRYP_Encrypt_IT(). + * @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains + * the configuration information for CRYP module. + * @retval none + */ +static void CRYP_TDES_IT(CRYP_HandleTypeDef *hcryp) +{ + uint32_t temp[2]; /* Temporary CrypOutBuff */ + uint32_t i; + + if (hcryp->State == DAL_CRYP_STATE_BUSY) + { + if (__DAL_CRYP_GET_IT(hcryp, CRYP_IT_INI) != 0x0U) + { + if (__DAL_CRYP_GET_FLAG(hcryp, CRYP_FLAG_INRIS) != 0x0U) + { + /* Write input block in the IN FIFO */ + hcryp->Instance->DATAIN = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount); + hcryp->CrypInCount++; + hcryp->Instance->DATAIN = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount); + hcryp->CrypInCount++; + + if (hcryp->CrypInCount == ((uint16_t)(hcryp->Size) / 4U)) + { + /* Disable interruption */ + __DAL_CRYP_DISABLE_IT(hcryp, CRYP_IT_INI); + /* Call the input data transfer complete callback */ +#if (USE_DAL_CRYP_REGISTER_CALLBACKS == 1U) + /*Call registered Input complete callback*/ + hcryp->InCpltCallback(hcryp); +#else + /*Call legacy weak Input complete callback*/ + DAL_CRYP_InCpltCallback(hcryp); +#endif /* USE_DAL_CRYP_REGISTER_CALLBACKS */ + } + } + } + if (__DAL_CRYP_GET_IT(hcryp, CRYP_IT_OUTI) != 0x0U) + { + if (__DAL_CRYP_GET_FLAG(hcryp, CRYP_FLAG_OUTRIS) != 0x0U) + { + /* Read the output block from the Output FIFO and put them in temporary Buffer then get CrypOutBuff from temporary buffer */ + for (i = 0U; i < 2U; i++) + { + temp[i] = hcryp->Instance->DATAOUT; + } + i = 0U; + while (((hcryp->CrypOutCount < ((hcryp->Size) / 4U))) && (i < 2U)) + { + *(uint32_t *)(hcryp->pCrypOutBuffPtr + hcryp->CrypOutCount) = temp[i]; + hcryp->CrypOutCount++; + i++; + } + if (hcryp->CrypOutCount == ((uint16_t)(hcryp->Size) / 4U)) + { + /* Disable interruption */ + __DAL_CRYP_DISABLE_IT(hcryp, CRYP_IT_OUTI); + + /* Disable CRYP */ + __DAL_CRYP_DISABLE(hcryp); + + /* Process unlocked */ + __DAL_UNLOCK(hcryp); + + /* Change the CRYP state */ + hcryp->State = DAL_CRYP_STATE_READY; + /* Call output transfer complete callback */ +#if (USE_DAL_CRYP_REGISTER_CALLBACKS == 1) + /*Call registered Output complete callback*/ + hcryp->OutCpltCallback(hcryp); +#else + /*Call legacy weak Output complete callback*/ + DAL_CRYP_OutCpltCallback(hcryp); +#endif /* USE_DAL_CRYP_REGISTER_CALLBACKS */ + } + } + } + } + else + { + /* Process unlocked */ + __DAL_UNLOCK(hcryp); + /* Busy error code field */ + hcryp->ErrorCode |= DAL_CRYP_ERROR_BUSY; +#if (USE_DAL_CRYP_REGISTER_CALLBACKS == 1) + /*Call registered error callback*/ + hcryp->ErrorCallback(hcryp); +#else + /*Call legacy weak error callback*/ + DAL_CRYP_ErrorCallback(hcryp); +#endif /* USE_DAL_CRYP_REGISTER_CALLBACKS */ + } +} + +#endif /* CRYP */ + +/** + * @brief Encryption in ECB/CBC & CTR Algorithm with AES Standard + * @param hcryp: pointer to a CRYP_HandleTypeDef structure + * @param Timeout: specify Timeout value + * @retval DAL status + */ +static DAL_StatusTypeDef CRYP_AES_Encrypt(CRYP_HandleTypeDef *hcryp, uint32_t Timeout) +{ + uint16_t outcount; /* Temporary CrypOutCount Value */ + uint32_t DoKeyIVConfig = 1U; /* By default, carry out peripheral Key and IV configuration */ + + if (hcryp->Init.KeyIVConfigSkip == CRYP_KEYIVCONFIG_ONCE) + { + if (hcryp->KeyIVConfig == 1U) + { + /* If the Key and IV configuration has to be done only once + and if it has already been done, skip it */ + DoKeyIVConfig = 0U; + } + else + { + /* If the Key and IV configuration has to be done only once + and if it has not been done already, do it and set KeyIVConfig + to keep track it won't have to be done again next time */ + hcryp->KeyIVConfig = 1U; + } + } + + if (DoKeyIVConfig == 1U) + { + + /* Set the Key*/ + CRYP_SetKey(hcryp, hcryp->Init.KeySize); + + if (hcryp->Init.Algorithm != CRYP_AES_ECB) + { + /* Set the Initialization Vector*/ +#if defined (AES) + hcryp->Instance->IVR3 = *(uint32_t *)(hcryp->Init.pInitVect); + hcryp->Instance->IVR2 = *(uint32_t *)(hcryp->Init.pInitVect + 1); + hcryp->Instance->IVR1 = *(uint32_t *)(hcryp->Init.pInitVect + 2); + hcryp->Instance->IVR0 = *(uint32_t *)(hcryp->Init.pInitVect + 3); +#else /* CRYP */ + hcryp->Instance->IV0L = *(uint32_t *)(hcryp->Init.pInitVect); + hcryp->Instance->IV0R = *(uint32_t *)(hcryp->Init.pInitVect + 1); + hcryp->Instance->IV1L = *(uint32_t *)(hcryp->Init.pInitVect + 2); + hcryp->Instance->IV1R = *(uint32_t *)(hcryp->Init.pInitVect + 3); +#endif /* End AES or CRYP */ + } + } /* if (DoKeyIVConfig == 1U) */ + + /* Set the phase */ + hcryp->Phase = CRYP_PHASE_PROCESS; + + /* Enable CRYP */ + __DAL_CRYP_ENABLE(hcryp); + + /*Temporary CrypOutCount Value*/ + outcount = hcryp->CrypOutCount; + + while ((hcryp->CrypInCount < (hcryp->Size / 4U)) && (outcount < (hcryp->Size / 4U))) + { + /* Write plain Ddta and get cipher data */ + CRYP_AES_ProcessData(hcryp, Timeout); + /*Temporary CrypOutCount Value*/ + outcount = hcryp->CrypOutCount; + } + + /* Disable CRYP */ + __DAL_CRYP_DISABLE(hcryp); + + /* Change the CRYP state */ + hcryp->State = DAL_CRYP_STATE_READY; + + /* Return function status */ + return DAL_OK; +} + +/** + * @brief Encryption in ECB/CBC & CTR mode with AES Standard using interrupt mode + * @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains + * the configuration information for CRYP module + * @retval DAL status + */ +static DAL_StatusTypeDef CRYP_AES_Encrypt_IT(CRYP_HandleTypeDef *hcryp) +{ + uint32_t DoKeyIVConfig = 1U; /* By default, carry out peripheral Key and IV configuration */ + + if (hcryp->Init.KeyIVConfigSkip == CRYP_KEYIVCONFIG_ONCE) + { + if (hcryp->KeyIVConfig == 1U) + { + /* If the Key and IV configuration has to be done only once + and if it has already been done, skip it */ + DoKeyIVConfig = 0U; + } + else + { + /* If the Key and IV configuration has to be done only once + and if it has not been done already, do it and set KeyIVConfig + to keep track it won't have to be done again next time */ + hcryp->KeyIVConfig = 1U; + } + } + + if (DoKeyIVConfig == 1U) + { + /* Set the Key*/ + CRYP_SetKey(hcryp, hcryp->Init.KeySize); + + if (hcryp->Init.Algorithm != CRYP_AES_ECB) + { + /* Set the Initialization Vector*/ +#if defined (AES) + hcryp->Instance->IVR3 = *(uint32_t *)(hcryp->Init.pInitVect); + hcryp->Instance->IVR2 = *(uint32_t *)(hcryp->Init.pInitVect + 1); + hcryp->Instance->IVR1 = *(uint32_t *)(hcryp->Init.pInitVect + 2); + hcryp->Instance->IVR0 = *(uint32_t *)(hcryp->Init.pInitVect + 3); + +#else /* CRYP */ + hcryp->Instance->IV0L = *(uint32_t *)(hcryp->Init.pInitVect); + hcryp->Instance->IV0R = *(uint32_t *)(hcryp->Init.pInitVect + 1); + hcryp->Instance->IV1L = *(uint32_t *)(hcryp->Init.pInitVect + 2); + hcryp->Instance->IV1R = *(uint32_t *)(hcryp->Init.pInitVect + 3); +#endif /* End AES or CRYP */ + } + } /* if (DoKeyIVConfig == 1U) */ + + /* Set the phase */ + hcryp->Phase = CRYP_PHASE_PROCESS; + + if (hcryp->Size != 0U) + { +#if defined (AES) + + /* Enable computation complete flag and error interrupts */ + __DAL_CRYP_ENABLE_IT(hcryp, CRYP_IT_CCFIE | CRYP_IT_ERRIE); + + /* Enable CRYP */ + __DAL_CRYP_ENABLE(hcryp); + + /* Write the input block in the IN FIFO */ + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount); + hcryp->CrypInCount++; + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount); + hcryp->CrypInCount++; + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount); + hcryp->CrypInCount++; + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount); + hcryp->CrypInCount++; + +#else /* CRYP */ + + /* Enable interrupts */ + __DAL_CRYP_ENABLE_IT(hcryp, CRYP_IT_INI | CRYP_IT_OUTI); + + /* Enable CRYP */ + __DAL_CRYP_ENABLE(hcryp); + +#endif /* End AES or CRYP */ + } + else + { + /* Change the CRYP state */ + hcryp->State = DAL_CRYP_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hcryp); + } + + /* Return function status */ + return DAL_OK; +} + +/** + * @brief Decryption in ECB/CBC & CTR mode with AES Standard + * @param hcryp: pointer to a CRYP_HandleTypeDef structure + * @param Timeout: Specify Timeout value + * @retval DAL status + */ +static DAL_StatusTypeDef CRYP_AES_Decrypt(CRYP_HandleTypeDef *hcryp, uint32_t Timeout) +{ + uint16_t outcount; /* Temporary CrypOutCount Value */ + uint32_t DoKeyIVConfig = 1U; /* By default, carry out peripheral Key and IV configuration */ + + if (hcryp->Init.KeyIVConfigSkip == CRYP_KEYIVCONFIG_ONCE) + { + if (hcryp->KeyIVConfig == 1U) + { + /* If the Key and IV configuration has to be done only once + and if it has already been done, skip it */ + DoKeyIVConfig = 0U; + } + else + { + /* If the Key and IV configuration has to be done only once + and if it has not been done already, do it and set KeyIVConfig + to keep track it won't have to be done again next time */ + hcryp->KeyIVConfig = 1U; + } + } + + if (DoKeyIVConfig == 1U) + { + /* Key preparation for ECB/CBC */ + if (hcryp->Init.Algorithm != CRYP_AES_CTR) + { +#if defined (AES) + if (hcryp->AutoKeyDerivation == DISABLE)/*Mode 2 Key preparation*/ + { + /* Set key preparation for decryption operating mode*/ + MODIFY_REG(hcryp->Instance->CTRL, AES_CR_MODE, CRYP_OPERATINGMODE_KEYDERIVATION); + + /* Set the Key*/ + CRYP_SetKey(hcryp, hcryp->Init.KeySize); + + /* Enable CRYP */ + __DAL_CRYP_ENABLE(hcryp); + + /* Wait for CCF flag to be raised */ + if (CRYP_WaitOnCCFlag(hcryp, Timeout) != DAL_OK) + { + /* Disable the CRYP peripheral clock */ + __DAL_CRYP_DISABLE(hcryp); + + /* Change state & error code*/ + hcryp->ErrorCode |= DAL_CRYP_ERROR_TIMEOUT; + hcryp->State = DAL_CRYP_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hcryp); + return DAL_ERROR; + } + /* Clear CCF Flag */ + __DAL_CRYP_CLEAR_FLAG(hcryp, CRYP_CCF_CLEAR); + + /* Return to decryption operating mode(Mode 3)*/ + MODIFY_REG(hcryp->Instance->CTRL, AES_CR_MODE, CRYP_OPERATINGMODE_DECRYPT); + } + else /*Mode 4 : decryption & Key preparation*/ + { + /* Set the Key*/ + CRYP_SetKey(hcryp, hcryp->Init.KeySize); + + /* Set decryption & Key preparation operating mode*/ + MODIFY_REG(hcryp->Instance->CTRL, AES_CR_MODE, CRYP_OPERATINGMODE_KEYDERIVATION_DECRYPT); + } +#else /* CRYP */ + /* change ALGOMODE to key preparation for decryption*/ + MODIFY_REG(hcryp->Instance->CTRL, CRYP_CTRL_ALGOMSEL, CRYP_CTRL_ALGOMSEL_AES_KEY); + + /* Set the Key*/ + CRYP_SetKey(hcryp, hcryp->Init.KeySize); + + /* Enable CRYP */ + __DAL_CRYP_ENABLE(hcryp); + + /* Wait for BUSY flag to be raised */ + if (CRYP_WaitOnBUSYFlag(hcryp, Timeout) != DAL_OK) + { + /* Disable the CRYP peripheral clock */ + __DAL_CRYP_DISABLE(hcryp); + + /* Change state */ + hcryp->ErrorCode |= DAL_CRYP_ERROR_TIMEOUT; + hcryp->State = DAL_CRYP_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hcryp); + return DAL_ERROR; + } + /* Turn back to ALGOMODE of the configuration */ + MODIFY_REG(hcryp->Instance->CTRL, CRYP_CTRL_ALGOMSEL, hcryp->Init.Algorithm); + +#endif /* End AES or CRYP */ + } + else /*Algorithm CTR */ + { + /* Set the Key*/ + CRYP_SetKey(hcryp, hcryp->Init.KeySize); + } + + /* Set IV */ + if (hcryp->Init.Algorithm != CRYP_AES_ECB) + { + /* Set the Initialization Vector*/ +#if defined (AES) + hcryp->Instance->IVR3 = *(uint32_t *)(hcryp->Init.pInitVect); + hcryp->Instance->IVR2 = *(uint32_t *)(hcryp->Init.pInitVect + 1); + hcryp->Instance->IVR1 = *(uint32_t *)(hcryp->Init.pInitVect + 2); + hcryp->Instance->IVR0 = *(uint32_t *)(hcryp->Init.pInitVect + 3); +#else /* CRYP */ + hcryp->Instance->IV0L = *(uint32_t *)(hcryp->Init.pInitVect); + hcryp->Instance->IV0R = *(uint32_t *)(hcryp->Init.pInitVect + 1); + hcryp->Instance->IV1L = *(uint32_t *)(hcryp->Init.pInitVect + 2); + hcryp->Instance->IV1R = *(uint32_t *)(hcryp->Init.pInitVect + 3); +#endif /* End AES or CRYP */ + } + } /* if (DoKeyIVConfig == 1U) */ + /* Set the phase */ + hcryp->Phase = CRYP_PHASE_PROCESS; + + /* Enable CRYP */ + __DAL_CRYP_ENABLE(hcryp); + + /*Temporary CrypOutCount Value*/ + outcount = hcryp->CrypOutCount; + + while ((hcryp->CrypInCount < (hcryp->Size / 4U)) && (outcount < (hcryp->Size / 4U))) + { + /* Write plain data and get cipher data */ + CRYP_AES_ProcessData(hcryp, Timeout); + /*Temporary CrypOutCount Value*/ + outcount = hcryp->CrypOutCount; + } + + /* Disable CRYP */ + __DAL_CRYP_DISABLE(hcryp); + + /* Change the CRYP state */ + hcryp->State = DAL_CRYP_STATE_READY; + + /* Return function status */ + return DAL_OK; +} +/** + * @brief Decryption in ECB/CBC & CTR mode with AES Standard using interrupt mode + * @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains + * the configuration information for CRYP module + * @retval DAL status + */ +static DAL_StatusTypeDef CRYP_AES_Decrypt_IT(CRYP_HandleTypeDef *hcryp) +{ + __IO uint32_t count = 0U; + uint32_t DoKeyIVConfig = 1U; /* By default, carry out peripheral Key and IV configuration */ + + if (hcryp->Init.KeyIVConfigSkip == CRYP_KEYIVCONFIG_ONCE) + { + if (hcryp->KeyIVConfig == 1U) + { + /* If the Key and IV configuration has to be done only once + and if it has already been done, skip it */ + DoKeyIVConfig = 0U; + } + else + { + /* If the Key and IV configuration has to be done only once + and if it has not been done already, do it and set KeyIVConfig + to keep track it won't have to be done again next time */ + hcryp->KeyIVConfig = 1U; + } + } + + if (DoKeyIVConfig == 1U) + { + /* Key preparation for ECB/CBC */ + if (hcryp->Init.Algorithm != CRYP_AES_CTR) + { +#if defined (AES) + if (hcryp->AutoKeyDerivation == DISABLE)/*Mode 2 Key preparation*/ + { + /* Set key preparation for decryption operating mode*/ + MODIFY_REG(hcryp->Instance->CTRL, AES_CR_MODE, CRYP_OPERATINGMODE_KEYDERIVATION); + + /* Set the Key*/ + CRYP_SetKey(hcryp, hcryp->Init.KeySize); + + /* Enable CRYP */ + __DAL_CRYP_ENABLE(hcryp); + + /* Wait for CCF flag to be raised */ + count = CRYP_TIMEOUT_KEYPREPARATION; + do + { + count-- ; + if (count == 0U) + { + /* Disable the CRYP peripheral clock */ + __DAL_CRYP_DISABLE(hcryp); + + /* Change state */ + hcryp->ErrorCode |= DAL_CRYP_ERROR_TIMEOUT; + hcryp->State = DAL_CRYP_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hcryp); + return DAL_ERROR; + } + } while (DAL_IS_BIT_CLR(hcryp->Instance->STS, AES_SR_CCF)); + + /* Clear CCF Flag */ + __DAL_CRYP_CLEAR_FLAG(hcryp, CRYP_CCF_CLEAR); + + /* Return to decryption operating mode(Mode 3)*/ + MODIFY_REG(hcryp->Instance->CTRL, AES_CR_MODE, CRYP_OPERATINGMODE_DECRYPT); + } + else /*Mode 4 : decryption & key preparation*/ + { + /* Set the Key*/ + CRYP_SetKey(hcryp, hcryp->Init.KeySize); + + /* Set decryption & key preparation operating mode*/ + MODIFY_REG(hcryp->Instance->CTRL, AES_CR_MODE, CRYP_OPERATINGMODE_KEYDERIVATION_DECRYPT); + } +#else /* CRYP */ + + /* change ALGOMODE to key preparation for decryption*/ + MODIFY_REG(hcryp->Instance->CTRL, CRYP_CTRL_ALGOMSEL, CRYP_CTRL_ALGOMSEL_AES_KEY); + + /* Set the Key*/ + CRYP_SetKey(hcryp, hcryp->Init.KeySize); + + /* Enable CRYP */ + __DAL_CRYP_ENABLE(hcryp); + + /* Wait for BUSY flag to be raised */ + count = CRYP_TIMEOUT_KEYPREPARATION; + do + { + count-- ; + if (count == 0U) + { + /* Change state */ + hcryp->ErrorCode |= DAL_CRYP_ERROR_TIMEOUT; + hcryp->State = DAL_CRYP_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hcryp); + return DAL_ERROR; + } + } while (DAL_IS_BIT_SET(hcryp->Instance->STS, CRYP_FLAG_BUSY)); + + /* Turn back to ALGOMODE of the configuration */ + MODIFY_REG(hcryp->Instance->CTRL, CRYP_CTRL_ALGOMSEL, hcryp->Init.Algorithm); + +#endif /* End AES or CRYP */ + } + + else /*Algorithm CTR */ + { + /* Set the Key*/ + CRYP_SetKey(hcryp, hcryp->Init.KeySize); + } + + /* Set IV */ + if (hcryp->Init.Algorithm != CRYP_AES_ECB) + { + /* Set the Initialization Vector*/ +#if defined (AES) + hcryp->Instance->IVR3 = *(uint32_t *)(hcryp->Init.pInitVect); + hcryp->Instance->IVR2 = *(uint32_t *)(hcryp->Init.pInitVect + 1); + hcryp->Instance->IVR1 = *(uint32_t *)(hcryp->Init.pInitVect + 2); + hcryp->Instance->IVR0 = *(uint32_t *)(hcryp->Init.pInitVect + 3); +#else /* CRYP */ + hcryp->Instance->IV0L = *(uint32_t *)(hcryp->Init.pInitVect); + hcryp->Instance->IV0R = *(uint32_t *)(hcryp->Init.pInitVect + 1); + hcryp->Instance->IV1L = *(uint32_t *)(hcryp->Init.pInitVect + 2); + hcryp->Instance->IV1R = *(uint32_t *)(hcryp->Init.pInitVect + 3); +#endif /* End AES or CRYP */ + } + } /* if (DoKeyIVConfig == 1U) */ + + /* Set the phase */ + hcryp->Phase = CRYP_PHASE_PROCESS; + if (hcryp->Size != 0U) + { + +#if defined (AES) + + /* Enable computation complete flag and error interrupts */ + __DAL_CRYP_ENABLE_IT(hcryp, CRYP_IT_CCFIE | CRYP_IT_ERRIE); + + /* Enable CRYP */ + __DAL_CRYP_ENABLE(hcryp); + + /* Write the input block in the IN FIFO */ + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount); + hcryp->CrypInCount++; + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount); + hcryp->CrypInCount++; + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount); + hcryp->CrypInCount++; + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount); + hcryp->CrypInCount++; + +#else /* CRYP */ + + /* Enable interrupts */ + __DAL_CRYP_ENABLE_IT(hcryp, CRYP_IT_INI | CRYP_IT_OUTI); + + /* Enable CRYP */ + __DAL_CRYP_ENABLE(hcryp); + +#endif /* End AES or CRYP */ + } + else + { + /* Process locked */ + __DAL_UNLOCK(hcryp); + + /* Change the CRYP state */ + hcryp->State = DAL_CRYP_STATE_READY; + } + + /* Return function status */ + return DAL_OK; +} +/** + * @brief Decryption in ECB/CBC & CTR mode with AES Standard using DMA mode + * @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains + * the configuration information for CRYP module + * @retval DAL status + */ +static DAL_StatusTypeDef CRYP_AES_Decrypt_DMA(CRYP_HandleTypeDef *hcryp) +{ + __IO uint32_t count = 0U; + uint32_t DoKeyIVConfig = 1U; /* By default, carry out peripheral Key and IV configuration */ + + if (hcryp->Init.KeyIVConfigSkip == CRYP_KEYIVCONFIG_ONCE) + { + if (hcryp->KeyIVConfig == 1U) + { + /* If the Key and IV configuration has to be done only once + and if it has already been done, skip it */ + DoKeyIVConfig = 0U; + } + else + { + /* If the Key and IV configuration has to be done only once + and if it has not been done already, do it and set KeyIVConfig + to keep track it won't have to be done again next time */ + hcryp->KeyIVConfig = 1U; + } + } + if (DoKeyIVConfig == 1U) + { + /* Key preparation for ECB/CBC */ + if (hcryp->Init.Algorithm != CRYP_AES_CTR) + { +#if defined (AES) + if (hcryp->AutoKeyDerivation == DISABLE)/*Mode 2 key preparation*/ + { + /* Set key preparation for decryption operating mode*/ + MODIFY_REG(hcryp->Instance->CTRL, AES_CR_MODE, CRYP_OPERATINGMODE_KEYDERIVATION); + + /* Set the Key*/ + CRYP_SetKey(hcryp, hcryp->Init.KeySize); + + /* Enable CRYP */ + __DAL_CRYP_ENABLE(hcryp); + + /* Wait for CCF flag to be raised */ + count = CRYP_TIMEOUT_KEYPREPARATION; + do + { + count-- ; + if (count == 0U) + { + /* Disable the CRYP peripheral clock */ + __DAL_CRYP_DISABLE(hcryp); + + /* Change state */ + hcryp->ErrorCode |= DAL_CRYP_ERROR_TIMEOUT; + hcryp->State = DAL_CRYP_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hcryp); + return DAL_ERROR; + } + } while (DAL_IS_BIT_CLR(hcryp->Instance->STS, AES_SR_CCF)); + + /* Clear CCF Flag */ + __DAL_CRYP_CLEAR_FLAG(hcryp, CRYP_CCF_CLEAR); + + /* Return to decryption operating mode(Mode 3)*/ + MODIFY_REG(hcryp->Instance->CTRL, AES_CR_MODE, CRYP_OPERATINGMODE_DECRYPT); + } + else /*Mode 4 : decryption & key preparation*/ + { + /* Set the Key*/ + CRYP_SetKey(hcryp, hcryp->Init.KeySize); + + /* Set decryption & Key preparation operating mode*/ + MODIFY_REG(hcryp->Instance->CTRL, AES_CR_MODE, CRYP_OPERATINGMODE_KEYDERIVATION_DECRYPT); + } +#else /* CRYP */ + /* change ALGOMODE to key preparation for decryption*/ + MODIFY_REG(hcryp->Instance->CTRL, CRYP_CTRL_ALGOMSEL, CRYP_CTRL_ALGOMSEL_AES_KEY); + + /* Set the Key*/ + CRYP_SetKey(hcryp, hcryp->Init.KeySize); + + /* Enable CRYP */ + __DAL_CRYP_ENABLE(hcryp); + + /* Wait for BUSY flag to be raised */ + count = CRYP_TIMEOUT_KEYPREPARATION; + do + { + count-- ; + if (count == 0U) + { + /* Disable the CRYP peripheral clock */ + __DAL_CRYP_DISABLE(hcryp); + + /* Change state */ + hcryp->ErrorCode |= DAL_CRYP_ERROR_TIMEOUT; + hcryp->State = DAL_CRYP_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hcryp); + return DAL_ERROR; + } + } while (DAL_IS_BIT_SET(hcryp->Instance->STS, CRYP_FLAG_BUSY)); + + /* Turn back to ALGOMODE of the configuration */ + MODIFY_REG(hcryp->Instance->CTRL, CRYP_CTRL_ALGOMSEL, hcryp->Init.Algorithm); + +#endif /* End AES or CRYP */ + } + else /*Algorithm CTR */ + { + /* Set the Key*/ + CRYP_SetKey(hcryp, hcryp->Init.KeySize); + } + + if (hcryp->Init.Algorithm != CRYP_AES_ECB) + { + /* Set the Initialization Vector*/ +#if defined (AES) + hcryp->Instance->IVR3 = *(uint32_t *)(hcryp->Init.pInitVect); + hcryp->Instance->IVR2 = *(uint32_t *)(hcryp->Init.pInitVect + 1); + hcryp->Instance->IVR1 = *(uint32_t *)(hcryp->Init.pInitVect + 2); + hcryp->Instance->IVR0 = *(uint32_t *)(hcryp->Init.pInitVect + 3); +#else /* CRYP */ + hcryp->Instance->IV0L = *(uint32_t *)(hcryp->Init.pInitVect); + hcryp->Instance->IV0R = *(uint32_t *)(hcryp->Init.pInitVect + 1); + hcryp->Instance->IV1L = *(uint32_t *)(hcryp->Init.pInitVect + 2); + hcryp->Instance->IV1R = *(uint32_t *)(hcryp->Init.pInitVect + 3); +#endif /* End AES or CRYP */ + } + } /* if (DoKeyIVConfig == 1U) */ + + /* Set the phase */ + hcryp->Phase = CRYP_PHASE_PROCESS; + + if (hcryp->Size != 0U) + { + /* Set the input and output addresses and start DMA transfer */ + CRYP_SetDMAConfig(hcryp, (uint32_t)(hcryp->pCrypInBuffPtr), (hcryp->Size / 4U), (uint32_t)(hcryp->pCrypOutBuffPtr)); + } + else + { + /* Process unlocked */ + __DAL_UNLOCK(hcryp); + + /* Change the CRYP state */ + hcryp->State = DAL_CRYP_STATE_READY; + } + + /* Return function status */ + return DAL_OK; +} + + +/** + * @brief DMA CRYP input data process complete callback. + * @param hdma: DMA handle + * @retval None + */ +static void CRYP_DMAInCplt(DMA_HandleTypeDef *hdma) +{ + CRYP_HandleTypeDef *hcryp = (CRYP_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + + /* Disable the DMA transfer for input FIFO request by resetting the DIEN bit + in the DMACR register */ +#if defined (CRYP) + hcryp->Instance->DMACTRL &= (uint32_t)(~CRYP_DMACTRL_INEN); + +#else /* AES */ + CLEAR_BIT(hcryp->Instance->CTRL, AES_CR_DMAINEN); + + /* TinyAES2, No output on CCM AES, unlock should be done when input data process complete */ + if ((hcryp->Init.Algorithm & CRYP_AES_CCM) == CRYP_AES_CCM) + { + /* Clear CCF flag */ + __DAL_CRYP_CLEAR_FLAG(hcryp, CRYP_CCF_CLEAR); + + /* Change the CRYP state to ready */ + hcryp->State = DAL_CRYP_STATE_READY; + + /* Process Unlocked */ + __DAL_UNLOCK(hcryp); + } +#endif /* End AES or CRYP */ + + /* Call input data transfer complete callback */ +#if (USE_DAL_CRYP_REGISTER_CALLBACKS == 1) + /*Call registered Input complete callback*/ + hcryp->InCpltCallback(hcryp); +#else + /*Call legacy weak Input complete callback*/ + DAL_CRYP_InCpltCallback(hcryp); +#endif /* USE_DAL_CRYP_REGISTER_CALLBACKS */ +} + +/** + * @brief DMA CRYP output data process complete callback. + * @param hdma: DMA handle + * @retval None + */ +static void CRYP_DMAOutCplt(DMA_HandleTypeDef *hdma) +{ + CRYP_HandleTypeDef *hcryp = (CRYP_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + + /* Disable the DMA transfer for output FIFO request by resetting + the DOEN bit in the DMACR register */ + +#if defined (CRYP) + + hcryp->Instance->DMACTRL &= (uint32_t)(~CRYP_DMACTRL_OUTEN); + #if defined (CRYP_CTRL_ALGOMSEL_AES_GCM) + if ((hcryp->Init.Algorithm & CRYP_AES_GCM) != CRYP_AES_GCM) + { + /* Disable CRYP (not allowed in GCM)*/ + __DAL_CRYP_DISABLE(hcryp); + } + + #else /*NO GCM CCM */ + /* Disable CRYP */ + __DAL_CRYP_DISABLE(hcryp); + #endif /* GCM CCM defined*/ +#else /* AES */ + + CLEAR_BIT(hcryp->Instance->CTRL, AES_CR_DMAOUTEN); + + /* Clear CCF flag */ + __DAL_CRYP_CLEAR_FLAG(hcryp, CRYP_CCF_CLEAR); + + if ((hcryp->Init.Algorithm & CRYP_AES_GCM_GMAC) != CRYP_AES_GCM_GMAC) + { + /* Disable CRYP (not allowed in GCM)*/ + __DAL_CRYP_DISABLE(hcryp); + } +#endif /* End AES or CRYP */ + + /* Change the CRYP state to ready */ + hcryp->State = DAL_CRYP_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hcryp); + /* Call output data transfer complete callback */ +#if (USE_DAL_CRYP_REGISTER_CALLBACKS == 1) + /*Call registered Output complete callback*/ + hcryp->OutCpltCallback(hcryp); +#else + /*Call legacy weak Output complete callback*/ + DAL_CRYP_OutCpltCallback(hcryp); +#endif /* USE_DAL_CRYP_REGISTER_CALLBACKS */ +} + +/** + * @brief DMA CRYP communication error callback. + * @param hdma: DMA handle + * @retval None + */ +static void CRYP_DMAError(DMA_HandleTypeDef *hdma) +{ + CRYP_HandleTypeDef *hcryp = (CRYP_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + + /* Change the CRYP peripheral state */ + hcryp->State = DAL_CRYP_STATE_READY; + + /* DMA error code field */ + hcryp->ErrorCode |= DAL_CRYP_ERROR_DMA; + +#if defined (AES) + + /* Clear CCF flag */ + __DAL_CRYP_CLEAR_FLAG(hcryp, CRYP_CCF_CLEAR); + +#endif /* AES */ + + /* Call error callback */ +#if (USE_DAL_CRYP_REGISTER_CALLBACKS == 1) + /*Call registered error callback*/ + hcryp->ErrorCallback(hcryp); +#else + /*Call legacy weak error callback*/ + DAL_CRYP_ErrorCallback(hcryp); +#endif /* USE_DAL_CRYP_REGISTER_CALLBACKS */ +} + +/** + * @brief Set the DMA configuration and start the DMA transfer + * @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains + * the configuration information for CRYP module + * @param inputaddr: address of the input buffer + * @param Size: size of the input buffer, must be a multiple of 16. + * @param outputaddr: address of the output buffer + * @retval None + */ +static void CRYP_SetDMAConfig(CRYP_HandleTypeDef *hcryp, uint32_t inputaddr, uint16_t Size, uint32_t outputaddr) +{ + /* Set the CRYP DMA transfer complete callback */ + hcryp->hdmain->XferCpltCallback = CRYP_DMAInCplt; + + /* Set the DMA input error callback */ + hcryp->hdmain->XferErrorCallback = CRYP_DMAError; + + /* Set the CRYP DMA transfer complete callback */ + hcryp->hdmaout->XferCpltCallback = CRYP_DMAOutCplt; + + /* Set the DMA output error callback */ + hcryp->hdmaout->XferErrorCallback = CRYP_DMAError; + +#if defined (CRYP) + + /* Enable CRYP */ + __DAL_CRYP_ENABLE(hcryp); + + /* Enable the input DMA Stream */ + if (DAL_DMA_Start_IT(hcryp->hdmain, inputaddr, (uint32_t)&hcryp->Instance->DATAIN, Size) != DAL_OK) + { + /* DMA error code field */ + hcryp->ErrorCode |= DAL_CRYP_ERROR_DMA; + + /* Call error callback */ +#if (USE_DAL_CRYP_REGISTER_CALLBACKS == 1) + /*Call registered error callback*/ + hcryp->ErrorCallback(hcryp); +#else + /*Call legacy weak error callback*/ + DAL_CRYP_ErrorCallback(hcryp); +#endif /* USE_DAL_CRYP_REGISTER_CALLBACKS */ + } + /* Enable the output DMA Stream */ + if (DAL_DMA_Start_IT(hcryp->hdmaout, (uint32_t)&hcryp->Instance->DATAOUT, outputaddr, Size) != DAL_OK) + { + /* DMA error code field */ + hcryp->ErrorCode |= DAL_CRYP_ERROR_DMA; + + /* Call error callback */ +#if (USE_DAL_CRYP_REGISTER_CALLBACKS == 1) + /*Call registered error callback*/ + hcryp->ErrorCallback(hcryp); +#else + /*Call legacy weak error callback*/ + DAL_CRYP_ErrorCallback(hcryp); +#endif /* USE_DAL_CRYP_REGISTER_CALLBACKS */ + } + /* Enable In/Out DMA request */ + hcryp->Instance->DMACTRL = CRYP_DMACTRL_OUTEN | CRYP_DMACTRL_INEN; + +#else /* AES */ + + if (((hcryp->Init.Algorithm & CRYP_AES_GCM_GMAC) != CRYP_AES_GCM_GMAC) + && ((hcryp->Init.Algorithm & CRYP_AES_CCM) != CRYP_AES_CCM)) + { + /* Enable CRYP (not allowed in GCM & CCM)*/ + __DAL_CRYP_ENABLE(hcryp); + } + + /* Enable the DMA input stream */ + if (DAL_DMA_Start_IT(hcryp->hdmain, inputaddr, (uint32_t)&hcryp->Instance->DATAINR, Size) != DAL_OK) + { + /* DMA error code field */ + hcryp->ErrorCode |= DAL_CRYP_ERROR_DMA; + + /* Call error callback */ +#if (USE_DAL_CRYP_REGISTER_CALLBACKS == 1) + /*Call registered error callback*/ + hcryp->ErrorCallback(hcryp); +#else + /*Call legacy weak error callback*/ + DAL_CRYP_ErrorCallback(hcryp); +#endif /* USE_DAL_CRYP_REGISTER_CALLBACKS */ + } + /* Enable the DMA output stream */ + if (DAL_DMA_Start_IT(hcryp->hdmaout, (uint32_t)&hcryp->Instance->DATAOUTR, outputaddr, Size) != DAL_OK) + { + /* DMA error code field */ + hcryp->ErrorCode |= DAL_CRYP_ERROR_DMA; + + /* Call error callback */ +#if (USE_DAL_CRYP_REGISTER_CALLBACKS == 1) + /*Call registered error callback*/ + hcryp->ErrorCallback(hcryp); +#else + /*Call legacy weak error callback*/ + DAL_CRYP_ErrorCallback(hcryp); +#endif /* USE_DAL_CRYP_REGISTER_CALLBACKS */ + } + /*AES2v1.1.1 : CCM authentication : no init phase, only header and final phase */ + /* Enable In and Out DMA requests */ + if ((hcryp->Init.Algorithm & CRYP_AES_CCM) == CRYP_AES_CCM) + { + /* Enable only In DMA requests for CCM*/ + SET_BIT(hcryp->Instance->CTRL, (AES_CR_DMAINEN)); + } + else + { + /* Enable In and Out DMA requests */ + SET_BIT(hcryp->Instance->CTRL, (AES_CR_DMAINEN | AES_CR_DMAOUTEN)); + } +#endif /* End AES or CRYP */ +} + +/** + * @brief Process Data: Write Input data in polling mode and used in AES functions. + * @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains + * the configuration information for CRYP module + * @param Timeout: Specify Timeout value + * @retval None + */ +static void CRYP_AES_ProcessData(CRYP_HandleTypeDef *hcryp, uint32_t Timeout) +{ + + uint32_t temp[4]; /* Temporary CrypOutBuff */ + uint32_t i; +#if defined (CRYP) + uint16_t incount; /* Temporary CrypInCount Value */ + uint16_t outcount; /* Temporary CrypOutCount Value */ +#endif + +#if defined (CRYP) + + /*Temporary CrypOutCount Value*/ + incount = hcryp->CrypInCount; + + if (((hcryp->Instance->STS & CRYP_FLAG_IFNF) != 0x0U) && (incount < (hcryp->Size / 4U))) + { + /* Write the input block in the IN FIFO */ + hcryp->Instance->DATAIN = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount); + hcryp->CrypInCount++; + hcryp->Instance->DATAIN = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount); + hcryp->CrypInCount++; + hcryp->Instance->DATAIN = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount); + hcryp->CrypInCount++; + hcryp->Instance->DATAIN = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount); + hcryp->CrypInCount++; + } + + /* Wait for OFNE flag to be raised */ + if (CRYP_WaitOnOFNEFlag(hcryp, Timeout) != DAL_OK) + { + /* Disable the CRYP peripheral clock */ + __DAL_CRYP_DISABLE(hcryp); + + /* Change state & error code*/ + hcryp->ErrorCode |= DAL_CRYP_ERROR_TIMEOUT; + hcryp->State = DAL_CRYP_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hcryp); +#if (USE_DAL_CRYP_REGISTER_CALLBACKS == 1) + /*Call registered error callback*/ + hcryp->ErrorCallback(hcryp); +#else + /*Call legacy weak error callback*/ + DAL_CRYP_ErrorCallback(hcryp); +#endif /* USE_DAL_CRYP_REGISTER_CALLBACKS */ + } + + /*Temporary CrypOutCount Value*/ + outcount = hcryp->CrypOutCount; + + if (((hcryp->Instance->STS & CRYP_FLAG_OFNE) != 0x0U) && (outcount < (hcryp->Size / 4U))) + { + /* Read the output block from the Output FIFO and put them in temporary buffer then get CrypOutBuff from temporary buffer */ + for (i = 0U; i < 4U; i++) + { + temp[i] = hcryp->Instance->DATAOUT; + } + i = 0U; + while (((hcryp->CrypOutCount < ((hcryp->Size) / 4U))) && (i < 4U)) + { + *(uint32_t *)(hcryp->pCrypOutBuffPtr + hcryp->CrypOutCount) = temp[i]; + hcryp->CrypOutCount++; + i++; + } + } + +#else /* AES */ + + /* Write the input block in the IN FIFO */ + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount); + hcryp->CrypInCount++; + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount); + hcryp->CrypInCount++; + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount); + hcryp->CrypInCount++; + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount); + hcryp->CrypInCount++; + + /* Wait for CCF flag to be raised */ + if (CRYP_WaitOnCCFlag(hcryp, Timeout) != DAL_OK) + { + /* Disable the CRYP peripheral clock */ + __DAL_CRYP_DISABLE(hcryp); + + /* Change state */ + hcryp->ErrorCode |= DAL_CRYP_ERROR_TIMEOUT; + hcryp->State = DAL_CRYP_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hcryp); +#if (USE_DAL_CRYP_REGISTER_CALLBACKS == 1) + /*Call registered error callback*/ + hcryp->ErrorCallback(hcryp); +#else + /*Call legacy weak error callback*/ + DAL_CRYP_ErrorCallback(hcryp); +#endif /* USE_DAL_CRYP_REGISTER_CALLBACKS */ + } + + /* Clear CCF Flag */ + __DAL_CRYP_CLEAR_FLAG(hcryp, CRYP_CCF_CLEAR); + + /* Read the output block from the output FIFO and put them in temporary buffer then get CrypOutBuff from temporary buffer*/ + for (i = 0U; i < 4U; i++) + { + temp[i] = hcryp->Instance->DATAOUTR; + } + i = 0U; + while ((hcryp->CrypOutCount < ((hcryp->Size + 3U) / 4U)) && (i < 4U)) + { + *(uint32_t *)(hcryp->pCrypOutBuffPtr + hcryp->CrypOutCount) = temp[i]; + hcryp->CrypOutCount++; + i++; + } +#endif /* End AES or CRYP */ +} + +/** + * @brief Handle CRYP block input/output data handling under interruption. + * @note The function is called under interruption only, once + * interruptions have been enabled by DAL_CRYP_Encrypt_IT or DAL_CRYP_Decrypt_IT. + * @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains + * the configuration information for CRYP module. + * @retval DAL status + */ +static void CRYP_AES_IT(CRYP_HandleTypeDef *hcryp) +{ + uint32_t temp[4]; /* Temporary CrypOutBuff */ + uint32_t i; +#if defined (CRYP) + uint16_t incount; /* Temporary CrypInCount Value */ + uint16_t outcount; /* Temporary CrypOutCount Value */ +#endif + + if (hcryp->State == DAL_CRYP_STATE_BUSY) + { +#if defined (CRYP) + + /*Temporary CrypOutCount Value*/ + incount = hcryp->CrypInCount; + if (((hcryp->Instance->STS & CRYP_FLAG_IFNF) != 0x0U) && (incount < (hcryp->Size / 4U))) + { + /* Write the input block in the IN FIFO */ + hcryp->Instance->DATAIN = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount); + hcryp->CrypInCount++; + hcryp->Instance->DATAIN = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount); + hcryp->CrypInCount++; + hcryp->Instance->DATAIN = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount); + hcryp->CrypInCount++; + hcryp->Instance->DATAIN = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount); + hcryp->CrypInCount++; + if (hcryp->CrypInCount == ((uint16_t)(hcryp->Size) / 4U)) + { + /* Disable interrupts */ + __DAL_CRYP_DISABLE_IT(hcryp, CRYP_IT_INI); + + /* Call the input data transfer complete callback */ +#if (USE_DAL_CRYP_REGISTER_CALLBACKS == 1) + /*Call registered Input complete callback*/ + hcryp->InCpltCallback(hcryp); +#else + /*Call legacy weak Input complete callback*/ + DAL_CRYP_InCpltCallback(hcryp); +#endif /* USE_DAL_CRYP_REGISTER_CALLBACKS */ + } + } + /*Temporary CrypOutCount Value*/ + outcount = hcryp->CrypOutCount; + + if (((hcryp->Instance->STS & CRYP_FLAG_OFNE) != 0x0U) && (outcount < (hcryp->Size / 4U))) + { + /* Read the output block from the output FIFO and put them in temporary buffer then get CrypOutBuff from temporary buffer */ + for (i = 0U; i < 4U; i++) + { + temp[i] = hcryp->Instance->DATAOUT; + } + i = 0U; + while (((hcryp->CrypOutCount < ((hcryp->Size) / 4U))) && (i < 4U)) + { + *(uint32_t *)(hcryp->pCrypOutBuffPtr + hcryp->CrypOutCount) = temp[i]; + hcryp->CrypOutCount++; + i++; + } + if (hcryp->CrypOutCount == ((uint16_t)(hcryp->Size) / 4U)) + { + /* Disable interrupts */ + __DAL_CRYP_DISABLE_IT(hcryp, CRYP_IT_OUTI); + + /* Change the CRYP state */ + hcryp->State = DAL_CRYP_STATE_READY; + + /* Disable CRYP */ + __DAL_CRYP_DISABLE(hcryp); + + /* Process unlocked */ + __DAL_UNLOCK(hcryp); + + /* Call Output transfer complete callback */ +#if (USE_DAL_CRYP_REGISTER_CALLBACKS == 1) + /*Call registered Output complete callback*/ + hcryp->OutCpltCallback(hcryp); +#else + /*Call legacy weak Output complete callback*/ + DAL_CRYP_OutCpltCallback(hcryp); +#endif /* USE_DAL_CRYP_REGISTER_CALLBACKS */ + } + } + +#else /*AES*/ + + /* Read the output block from the output FIFO and put them in temporary buffer then get CrypOutBuff from temporary buffer*/ + for (i = 0U; i < 4U; i++) + { + temp[i] = hcryp->Instance->DATAOUTR; + } + i = 0U; + while ((hcryp->CrypOutCount < ((hcryp->Size + 3U) / 4U)) && (i < 4U)) + { + *(uint32_t *)(hcryp->pCrypOutBuffPtr + hcryp->CrypOutCount) = temp[i]; + hcryp->CrypOutCount++; + i++; + } + + if (hcryp->CrypOutCount == (hcryp->Size / 4U)) + { + /* Disable Computation Complete flag and errors interrupts */ + __DAL_CRYP_DISABLE_IT(hcryp, CRYP_IT_CCFIE | CRYP_IT_ERRIE); + + /* Change the CRYP state */ + hcryp->State = DAL_CRYP_STATE_READY; + + /* Disable CRYP */ + __DAL_CRYP_DISABLE(hcryp); + + /* Process Unlocked */ + __DAL_UNLOCK(hcryp); + + /* Call Output transfer complete callback */ +#if (USE_DAL_CRYP_REGISTER_CALLBACKS == 1) + /*Call registered Output complete callback*/ + hcryp->OutCpltCallback(hcryp); +#else + /*Call legacy weak Output complete callback*/ + DAL_CRYP_OutCpltCallback(hcryp); +#endif /* USE_DAL_CRYP_REGISTER_CALLBACKS */ + } + else + { + /* Write the input block in the IN FIFO */ + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount); + hcryp->CrypInCount++; + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount); + hcryp->CrypInCount++; + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount); + hcryp->CrypInCount++; + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount); + hcryp->CrypInCount++; + + if (hcryp->CrypInCount == (hcryp->Size / 4U)) + { + /* Call Input transfer complete callback */ +#if (USE_DAL_CRYP_REGISTER_CALLBACKS == 1U) + /*Call registered Input complete callback*/ + hcryp->InCpltCallback(hcryp); +#else + /*Call legacy weak Input complete callback*/ + DAL_CRYP_InCpltCallback(hcryp); +#endif /* USE_DAL_CRYP_REGISTER_CALLBACKS */ + } + } +#endif /* End AES or CRYP */ + + } + else + { + /* Busy error code field */ + hcryp->ErrorCode |= DAL_CRYP_ERROR_BUSY; +#if (USE_DAL_CRYP_REGISTER_CALLBACKS == 1) + /*Call registered error callback*/ + hcryp->ErrorCallback(hcryp); +#else + /*Call legacy weak error callback*/ + DAL_CRYP_ErrorCallback(hcryp); +#endif /* USE_DAL_CRYP_REGISTER_CALLBACKS */ + } +} + +/** + * @brief Writes Key in Key registers. + * @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains + * the configuration information for CRYP module + * @param KeySize: Size of Key + * @retval None + */ +static void CRYP_SetKey(CRYP_HandleTypeDef *hcryp, uint32_t KeySize) +{ +#if defined (CRYP) + + switch (KeySize) + { + case CRYP_KEYSIZE_256B: + hcryp->Instance->K0L = *(uint32_t *)(hcryp->Init.pKey); + hcryp->Instance->K0R = *(uint32_t *)(hcryp->Init.pKey + 1); + hcryp->Instance->K1L = *(uint32_t *)(hcryp->Init.pKey + 2); + hcryp->Instance->K1R = *(uint32_t *)(hcryp->Init.pKey + 3); + hcryp->Instance->K2L = *(uint32_t *)(hcryp->Init.pKey + 4); + hcryp->Instance->K2R = *(uint32_t *)(hcryp->Init.pKey + 5); + hcryp->Instance->K3L = *(uint32_t *)(hcryp->Init.pKey + 6); + hcryp->Instance->K3R = *(uint32_t *)(hcryp->Init.pKey + 7); + break; + case CRYP_KEYSIZE_192B: + hcryp->Instance->K1L = *(uint32_t *)(hcryp->Init.pKey); + hcryp->Instance->K1R = *(uint32_t *)(hcryp->Init.pKey + 1); + hcryp->Instance->K2L = *(uint32_t *)(hcryp->Init.pKey + 2); + hcryp->Instance->K2R = *(uint32_t *)(hcryp->Init.pKey + 3); + hcryp->Instance->K3L = *(uint32_t *)(hcryp->Init.pKey + 4); + hcryp->Instance->K3R = *(uint32_t *)(hcryp->Init.pKey + 5); + break; + case CRYP_KEYSIZE_128B: + hcryp->Instance->K2L = *(uint32_t *)(hcryp->Init.pKey); + hcryp->Instance->K2R = *(uint32_t *)(hcryp->Init.pKey + 1); + hcryp->Instance->K3L = *(uint32_t *)(hcryp->Init.pKey + 2); + hcryp->Instance->K3R = *(uint32_t *)(hcryp->Init.pKey + 3); + + break; + default: + break; + } +#else /*AES*/ + switch (KeySize) + { + case CRYP_KEYSIZE_256B: + hcryp->Instance->KEYR7 = *(uint32_t *)(hcryp->Init.pKey); + hcryp->Instance->KEYR6 = *(uint32_t *)(hcryp->Init.pKey + 1); + hcryp->Instance->KEYR5 = *(uint32_t *)(hcryp->Init.pKey + 2); + hcryp->Instance->KEYR4 = *(uint32_t *)(hcryp->Init.pKey + 3); + hcryp->Instance->KEYR3 = *(uint32_t *)(hcryp->Init.pKey + 4); + hcryp->Instance->KEYR2 = *(uint32_t *)(hcryp->Init.pKey + 5); + hcryp->Instance->KEYR1 = *(uint32_t *)(hcryp->Init.pKey + 6); + hcryp->Instance->KEYR0 = *(uint32_t *)(hcryp->Init.pKey + 7); + break; + case CRYP_KEYSIZE_128B: + hcryp->Instance->KEYR3 = *(uint32_t *)(hcryp->Init.pKey); + hcryp->Instance->KEYR2 = *(uint32_t *)(hcryp->Init.pKey + 1); + hcryp->Instance->KEYR1 = *(uint32_t *)(hcryp->Init.pKey + 2); + hcryp->Instance->KEYR0 = *(uint32_t *)(hcryp->Init.pKey + 3); + + break; + default: + break; + } +#endif /* End AES or CRYP */ +} + +#if defined (CRYP_CTRL_ALGOMSEL_AES_GCM)|| defined (AES) +/** + * @brief Encryption/Decryption process in AES GCM mode and prepare the authentication TAG + * @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains + * the configuration information for CRYP module + * @param Timeout: Timeout duration + * @retval DAL status + */ +static DAL_StatusTypeDef CRYP_AESGCM_Process(CRYP_HandleTypeDef *hcryp, uint32_t Timeout) +{ + uint32_t tickstart; + uint32_t wordsize = (uint32_t)(hcryp->Size) / 4U ; + uint16_t outcount; /* Temporary CrypOutCount Value */ + uint32_t DoKeyIVConfig = 1U; /* By default, carry out peripheral Key and IV configuration */ + + if (hcryp->Init.KeyIVConfigSkip == CRYP_KEYIVCONFIG_ONCE) + { + if (hcryp->KeyIVConfig == 1U) + { + /* If the Key and IV configuration has to be done only once + and if it has already been done, skip it */ + DoKeyIVConfig = 0U; + hcryp->SizesSum += hcryp->Size; /* Compute message total payload length */ + } + else + { + /* If the Key and IV configuration has to be done only once + and if it has not been done already, do it and set KeyIVConfig + to keep track it won't have to be done again next time */ + hcryp->KeyIVConfig = 1U; + hcryp->SizesSum = hcryp->Size; /* Merely store payload length */ + } + } + else + { + hcryp->SizesSum = hcryp->Size; + } + + if (DoKeyIVConfig == 1U) + { + /* Reset CrypHeaderCount */ + hcryp->CrypHeaderCount = 0U; + + /****************************** Init phase **********************************/ + + CRYP_SET_PHASE(hcryp, CRYP_PHASE_INIT); + + /* Set the key */ + CRYP_SetKey(hcryp, hcryp->Init.KeySize); + +#if defined(CRYP) + + /* Set the initialization vector and the counter : Initial Counter Block (ICB)*/ + hcryp->Instance->IV0L = *(uint32_t *)(hcryp->Init.pInitVect); + hcryp->Instance->IV0R = *(uint32_t *)(hcryp->Init.pInitVect + 1); + hcryp->Instance->IV1L = *(uint32_t *)(hcryp->Init.pInitVect + 2); + hcryp->Instance->IV1R = *(uint32_t *)(hcryp->Init.pInitVect + 3); + + /* Enable the CRYP peripheral */ + __DAL_CRYP_ENABLE(hcryp); + + /* Get tick */ + tickstart = DAL_GetTick(); + + /*Wait for the CRYPEN bit to be cleared*/ + while ((hcryp->Instance->CTRL & CRYP_CTRL_CRYPEN) == CRYP_CTRL_CRYPEN) + { + /* Check for the Timeout */ + if (Timeout != DAL_MAX_DELAY) + { + if (((DAL_GetTick() - tickstart) > Timeout) || (Timeout == 0U)) + { + /* Disable the CRYP peripheral clock */ + __DAL_CRYP_DISABLE(hcryp); + + /* Change state */ + hcryp->ErrorCode |= DAL_CRYP_ERROR_TIMEOUT; + hcryp->State = DAL_CRYP_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hcryp); + return DAL_ERROR; + } + } + } + +#else /* AES */ + /* Workaround 1 : only AES. + Datatype configuration must be 32 bits during Init phase. Only, after Init, and before re + enabling the IP, datatype different from 32 bits can be configured.*/ + /* Select DATATYPE 32 */ + MODIFY_REG(hcryp->Instance->CTRL, AES_CR_DATATYPE, CRYP_DATATYPE_32B); + + /* Set the initialization vector and the counter : Initial Counter Block (ICB)*/ + hcryp->Instance->IVR3 = *(uint32_t *)(hcryp->Init.pInitVect); + hcryp->Instance->IVR2 = *(uint32_t *)(hcryp->Init.pInitVect + 1); + hcryp->Instance->IVR1 = *(uint32_t *)(hcryp->Init.pInitVect + 2); + hcryp->Instance->IVR0 = *(uint32_t *)(hcryp->Init.pInitVect + 3); + + /* Enable the CRYP peripheral */ + __DAL_CRYP_ENABLE(hcryp); + + /* just wait for hash computation */ + if (CRYP_WaitOnCCFlag(hcryp, Timeout) != DAL_OK) + { + /* Change state */ + hcryp->ErrorCode |= DAL_CRYP_ERROR_TIMEOUT; + hcryp->State = DAL_CRYP_STATE_READY; + + /* Process unlocked & return error */ + __DAL_UNLOCK(hcryp); + return DAL_ERROR; + } + /* Clear CCF flag */ + __DAL_CRYP_CLEAR_FLAG(hcryp, CRYP_CCF_CLEAR); + +#endif /* End AES or CRYP */ + + /************************ Header phase *************************************/ + + if (CRYP_GCMCCM_SetHeaderPhase(hcryp, Timeout) != DAL_OK) + { + return DAL_ERROR; + } + + /*************************Payload phase ************************************/ + + /* Set the phase */ + hcryp->Phase = CRYP_PHASE_PROCESS; + +#if defined(CRYP) + + /* Disable the CRYP peripheral */ + __DAL_CRYP_DISABLE(hcryp); + + /* Select payload phase once the header phase is performed */ + CRYP_SET_PHASE(hcryp, CRYP_PHASE_PAYLOAD); + + /* Enable the CRYP peripheral */ + __DAL_CRYP_ENABLE(hcryp); + +#else /* AES */ + + /* Select payload phase once the header phase is performed */ + CRYP_SET_PHASE(hcryp, CRYP_PHASE_PAYLOAD); + +#endif /* End AES or CRYP */ + } /* if (DoKeyIVConfig == 1U) */ + + if ((hcryp->Size % 16U) != 0U) + { + /* recalculate wordsize */ + wordsize = ((wordsize / 4U) * 4U) ; + } + + /* Get tick */ + tickstart = DAL_GetTick(); + /*Temporary CrypOutCount Value*/ + outcount = hcryp->CrypOutCount; + + /* Write input data and get output Data */ + while ((hcryp->CrypInCount < wordsize) && (outcount < wordsize)) + { + /* Write plain data and get cipher data */ + CRYP_AES_ProcessData(hcryp, Timeout); + + /*Temporary CrypOutCount Value*/ + outcount = hcryp->CrypOutCount; + + /* Check for the Timeout */ + if (Timeout != DAL_MAX_DELAY) + { + if (((DAL_GetTick() - tickstart) > Timeout) || (Timeout == 0U)) + { + /* Disable the CRYP peripheral clock */ + __DAL_CRYP_DISABLE(hcryp); + + /* Change state & error code */ + hcryp->ErrorCode |= DAL_CRYP_ERROR_TIMEOUT; + hcryp->State = DAL_CRYP_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hcryp); + return DAL_ERROR; + } + } + } + + if ((hcryp->Size % 16U) != 0U) + { + /* Workaround 2 : CRYP1 & AES generates correct TAG for GCM mode only when input block size is multiple of + 128 bits. If lthe size of the last block of payload is inferior to 128 bits, when GCM encryption + is selected, then the TAG message will be wrong.*/ + CRYP_Workaround(hcryp, Timeout); + } + + /* Return function status */ + return DAL_OK; +} + +/** + * @brief Encryption/Decryption process in AES GCM mode and prepare the authentication TAG in interrupt mode + * @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains + * the configuration information for CRYP module + * @retval DAL status + */ +static DAL_StatusTypeDef CRYP_AESGCM_Process_IT(CRYP_HandleTypeDef *hcryp) +{ + __IO uint32_t count = 0U; + uint32_t DoKeyIVConfig = 1U; /* By default, carry out peripheral Key and IV configuration */ +#if defined(AES) + uint32_t loopcounter; + uint32_t lastwordsize; + uint32_t npblb; +#endif /* AES */ + + if (hcryp->Init.KeyIVConfigSkip == CRYP_KEYIVCONFIG_ONCE) + { + if (hcryp->KeyIVConfig == 1U) + { + /* If the Key and IV configuration has to be done only once + and if it has already been done, skip it */ + DoKeyIVConfig = 0U; + hcryp->SizesSum += hcryp->Size; /* Compute message total payload length */ + } + else + { + /* If the Key and IV configuration has to be done only once + and if it has not been done already, do it and set KeyIVConfig + to keep track it won't have to be done again next time */ + hcryp->KeyIVConfig = 1U; + hcryp->SizesSum = hcryp->Size; /* Merely store payload length */ + } + } + else + { + hcryp->SizesSum = hcryp->Size; + } + + /* Configure Key, IV and process message (header and payload) */ + if (DoKeyIVConfig == 1U) + { + /* Reset CrypHeaderCount */ + hcryp->CrypHeaderCount = 0U; + + /******************************* Init phase *********************************/ + + CRYP_SET_PHASE(hcryp, CRYP_PHASE_INIT); + + /* Set the key */ + CRYP_SetKey(hcryp, hcryp->Init.KeySize); + +#if defined(CRYP) + /* Set the initialization vector and the counter : Initial Counter Block (ICB)*/ + hcryp->Instance->IV0L = *(uint32_t *)(hcryp->Init.pInitVect); + hcryp->Instance->IV0R = *(uint32_t *)(hcryp->Init.pInitVect + 1); + hcryp->Instance->IV1L = *(uint32_t *)(hcryp->Init.pInitVect + 2); + hcryp->Instance->IV1R = *(uint32_t *)(hcryp->Init.pInitVect + 3); + + /* Enable the CRYP peripheral */ + __DAL_CRYP_ENABLE(hcryp); + + /*Wait for the CRYPEN bit to be cleared*/ + count = CRYP_TIMEOUT_GCMCCMINITPHASE; + do + { + count-- ; + if (count == 0U) + { + /* Disable the CRYP peripheral clock */ + __DAL_CRYP_DISABLE(hcryp); + + /* Change state */ + hcryp->ErrorCode |= DAL_CRYP_ERROR_TIMEOUT; + hcryp->State = DAL_CRYP_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hcryp); + return DAL_ERROR; + } + } while ((hcryp->Instance->CTRL & CRYP_CTRL_CRYPEN) == CRYP_CTRL_CRYPEN); + +#else /* AES */ + + /* Workaround 1 : only AES + Datatype configuration must be 32 bits during INIT phase. Only, after INIT, and before re + enabling the IP, datatype different from 32 bits can be configured.*/ + /* Select DATATYPE 32 */ + MODIFY_REG(hcryp->Instance->CTRL, AES_CR_DATATYPE, CRYP_DATATYPE_32B); + + /* Set the initialization vector and the counter : Initial Counter Block (ICB)*/ + hcryp->Instance->IVR3 = *(uint32_t *)(hcryp->Init.pInitVect); + hcryp->Instance->IVR2 = *(uint32_t *)(hcryp->Init.pInitVect + 1); + hcryp->Instance->IVR1 = *(uint32_t *)(hcryp->Init.pInitVect + 2); + hcryp->Instance->IVR0 = *(uint32_t *)(hcryp->Init.pInitVect + 3); + + /* Enable the CRYP peripheral */ + __DAL_CRYP_ENABLE(hcryp); + + /* just wait for hash computation */ + count = CRYP_TIMEOUT_GCMCCMINITPHASE; + do + { + count-- ; + if (count == 0U) + { + /* Disable the CRYP peripheral clock */ + __DAL_CRYP_DISABLE(hcryp); + + /* Change state */ + hcryp->ErrorCode |= DAL_CRYP_ERROR_TIMEOUT; + hcryp->State = DAL_CRYP_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hcryp); + return DAL_ERROR; + } + } while (DAL_IS_BIT_CLR(hcryp->Instance->STS, AES_SR_CCF)); + + /* Clear CCF flag */ + __DAL_CRYP_CLEAR_FLAG(hcryp, CRYP_CCF_CLEAR); + +#endif /* End AES or CRYP */ + + /***************************** Header phase *********************************/ + +#if defined(CRYP) + + /* Select header phase */ + CRYP_SET_PHASE(hcryp, CRYP_PHASE_HEADER); + + /* Enable interrupts */ + __DAL_CRYP_ENABLE_IT(hcryp, CRYP_IT_INI); + + /* Enable CRYP */ + __DAL_CRYP_ENABLE(hcryp); + +#else /* AES */ + + /* Workaround 1: only AES , before re-enabling the IP, datatype can be configured*/ + MODIFY_REG(hcryp->Instance->CTRL, AES_CR_DATATYPE, hcryp->Init.DataType); + + /* Select header phase */ + CRYP_SET_PHASE(hcryp, CRYP_PHASE_HEADER); + + /* Enable computation complete flag and error interrupts */ + __DAL_CRYP_ENABLE_IT(hcryp, CRYP_IT_CCFIE | CRYP_IT_ERRIE); + + /* Enable the CRYP peripheral */ + __DAL_CRYP_ENABLE(hcryp); + + if (hcryp->Init.HeaderSize == 0U) /*header phase is skipped*/ + { + /* Set the phase */ + hcryp->Phase = CRYP_PHASE_PROCESS; + + /* Select payload phase once the header phase is performed */ + MODIFY_REG(hcryp->Instance->CTRL, AES_CR_GCMPH, CRYP_PHASE_PAYLOAD); + + /* Write the payload Input block in the IN FIFO */ + if (hcryp->Size == 0U) + { + /* Disable interrupts */ + __DAL_CRYP_DISABLE_IT(hcryp, CRYP_IT_CCFIE | CRYP_IT_ERRIE); + + /* Change the CRYP state */ + hcryp->State = DAL_CRYP_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hcryp); + } + else if (hcryp->Size >= 16U) + { + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount); + hcryp->CrypInCount++; + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount); + hcryp->CrypInCount++; + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount); + hcryp->CrypInCount++; + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount); + hcryp->CrypInCount++; + if (hcryp->CrypInCount == (hcryp->Size / 4U)) + { + /* Call Input transfer complete callback */ +#if (USE_DAL_CRYP_REGISTER_CALLBACKS == 1) + /*Call registered Input complete callback*/ + hcryp->InCpltCallback(hcryp); +#else + /*Call legacy weak Input complete callback*/ + DAL_CRYP_InCpltCallback(hcryp); +#endif /* USE_DAL_CRYP_REGISTER_CALLBACKS */ + } + } + else /* Size < 16Bytes : first block is the last block*/ + { + /* Workaround not implemented*/ + /* Size should be %4 otherwise Tag will be incorrectly generated for GCM Encryption: + Workaround is implemented in polling mode, so if last block of + payload <128bit don't use CRYP_Encrypt_IT otherwise TAG is incorrectly generated for GCM Encryption. */ + + /* Compute the number of padding bytes in last block of payload */ + npblb = 16U - (uint32_t)(hcryp->Size); + + /* Number of valid words (lastwordsize) in last block */ + if ((npblb % 4U) == 0U) + { + lastwordsize = (16U - npblb) / 4U; + } + else + { + lastwordsize = ((16U - npblb) / 4U) + 1U; + } + + /* last block optionally pad the data with zeros*/ + for (loopcounter = 0U; loopcounter < lastwordsize ; loopcounter++) + { + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount); + hcryp->CrypInCount++; + } + while (loopcounter < 4U) + { + /* pad the data with zeros to have a complete block */ + hcryp->Instance->DATAINR = 0x0U; + loopcounter++; + } + } + } + else if ((hcryp->Init.HeaderSize) < 4U) + { + for (loopcounter = 0U; loopcounter < hcryp->Init.HeaderSize ; loopcounter++) + { + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount); + hcryp->CrypHeaderCount++ ; + } + while (loopcounter < 4U) + { + /* pad the data with zeros to have a complete block */ + hcryp->Instance->DATAINR = 0x0U; + loopcounter++; + } + /* Set the phase */ + hcryp->Phase = CRYP_PHASE_PROCESS; + + /* Select payload phase once the header phase is performed */ + CRYP_SET_PHASE(hcryp, CRYP_PHASE_PAYLOAD); + + /* Call Input transfer complete callback */ +#if (USE_DAL_CRYP_REGISTER_CALLBACKS == 1) + /*Call registered Input complete callback*/ + hcryp->InCpltCallback(hcryp); +#else + /*Call legacy weak Input complete callback*/ + DAL_CRYP_InCpltCallback(hcryp); +#endif /* USE_DAL_CRYP_REGISTER_CALLBACKS */ + } + else if ((hcryp->Init.HeaderSize) >= 4U) + { + /* Write the input block in the IN FIFO */ + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount); + hcryp->CrypHeaderCount++; + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount); + hcryp->CrypHeaderCount++; + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount); + hcryp->CrypHeaderCount++; + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount); + hcryp->CrypHeaderCount++; + } + else + { + /* Nothing to do */ + } + +#endif /* End AES or CRYP */ + } /* end of if (DoKeyIVConfig == 1U) */ + + /* Return function status */ + return DAL_OK; +} + + +/** + * @brief Encryption/Decryption process in AES GCM mode and prepare the authentication TAG using DMA + * @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains + * the configuration information for CRYP module + * @retval DAL status + */ +static DAL_StatusTypeDef CRYP_AESGCM_Process_DMA(CRYP_HandleTypeDef *hcryp) +{ + __IO uint32_t count = 0U; + uint32_t wordsize; + uint32_t DoKeyIVConfig = 1U; /* By default, carry out peripheral Key and IV configuration */ + + if (hcryp->Init.KeyIVConfigSkip == CRYP_KEYIVCONFIG_ONCE) + { + if (hcryp->KeyIVConfig == 1U) + { + /* If the Key and IV configuration has to be done only once + and if it has already been done, skip it */ + DoKeyIVConfig = 0U; + hcryp->SizesSum += hcryp->Size; /* Compute message total payload length */ + } + else + { + /* If the Key and IV configuration has to be done only once + and if it has not been done already, do it and set KeyIVConfig + to keep track it won't have to be done again next time */ + hcryp->KeyIVConfig = 1U; + hcryp->SizesSum = hcryp->Size; /* Merely store payload length */ + } + } + else + { + hcryp->SizesSum = hcryp->Size; + } + + if (DoKeyIVConfig == 1U) + { + /* Reset CrypHeaderCount */ + hcryp->CrypHeaderCount = 0U; + + /*************************** Init phase ************************************/ + + CRYP_SET_PHASE(hcryp, CRYP_PHASE_INIT); + + /* Set the key */ + CRYP_SetKey(hcryp, hcryp->Init.KeySize); + +#if defined(CRYP) + /* Set the initialization vector and the counter : Initial Counter Block (ICB)*/ + hcryp->Instance->IV0L = *(uint32_t *)(hcryp->Init.pInitVect); + hcryp->Instance->IV0R = *(uint32_t *)(hcryp->Init.pInitVect + 1); + hcryp->Instance->IV1L = *(uint32_t *)(hcryp->Init.pInitVect + 2); + hcryp->Instance->IV1R = *(uint32_t *)(hcryp->Init.pInitVect + 3); + + /* Enable the CRYP peripheral */ + __DAL_CRYP_ENABLE(hcryp); + + /*Wait for the CRYPEN bit to be cleared*/ + count = CRYP_TIMEOUT_GCMCCMINITPHASE; + do + { + count-- ; + if (count == 0U) + { + /* Disable the CRYP peripheral clock */ + __DAL_CRYP_DISABLE(hcryp); + + /* Change state */ + hcryp->ErrorCode |= DAL_CRYP_ERROR_TIMEOUT; + hcryp->State = DAL_CRYP_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hcryp); + return DAL_ERROR; + } + } while ((hcryp->Instance->CTRL & CRYP_CTRL_CRYPEN) == CRYP_CTRL_CRYPEN); + +#else /* AES */ + + /*Workaround 1 : only AES + Datatype configuration must be 32 bits during Init phase. Only, after Init, and before re + enabling the IP, datatype different from 32 bits can be configured.*/ + /* Select DATATYPE 32 */ + MODIFY_REG(hcryp->Instance->CTRL, AES_CR_DATATYPE, CRYP_DATATYPE_32B); + + /* Set the initialization vector and the counter : Initial Counter Block (ICB)*/ + hcryp->Instance->IVR3 = *(uint32_t *)(hcryp->Init.pInitVect); + hcryp->Instance->IVR2 = *(uint32_t *)(hcryp->Init.pInitVect + 1); + hcryp->Instance->IVR1 = *(uint32_t *)(hcryp->Init.pInitVect + 2); + hcryp->Instance->IVR0 = *(uint32_t *)(hcryp->Init.pInitVect + 3); + + /* Enable the CRYP peripheral */ + __DAL_CRYP_ENABLE(hcryp); + + /* just wait for hash computation */ + count = CRYP_TIMEOUT_GCMCCMINITPHASE; + do + { + count-- ; + if (count == 0U) + { + /* Disable the CRYP peripheral clock */ + __DAL_CRYP_DISABLE(hcryp); + + /* Change state */ + hcryp->ErrorCode |= DAL_CRYP_ERROR_TIMEOUT; + hcryp->State = DAL_CRYP_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hcryp); + return DAL_ERROR; + } + } while (DAL_IS_BIT_CLR(hcryp->Instance->STS, AES_SR_CCF)); + + /* Clear CCF flag */ + __DAL_CRYP_CLEAR_FLAG(hcryp, CRYP_CCF_CLEAR); + +#endif /* End AES or CRYP */ + + /************************ Header phase *************************************/ + + if (CRYP_GCMCCM_SetHeaderPhase_DMA(hcryp) != DAL_OK) + { + return DAL_ERROR; + } + + /************************ Payload phase ************************************/ + + /* Set the phase */ + hcryp->Phase = CRYP_PHASE_PROCESS; + +#if defined(CRYP) + + /* Disable the CRYP peripheral */ + __DAL_CRYP_DISABLE(hcryp); + +#endif /* CRYP */ + + /* Select payload phase once the header phase is performed */ + CRYP_SET_PHASE(hcryp, CRYP_PHASE_PAYLOAD); + + } /* if (DoKeyIVConfig == 1U) */ + + if (hcryp->Size != 0U) + { + /* CRYP1 IP V < 2.2.1 Size should be %4 otherwise Tag will be incorrectly generated for GCM Encryption: + Workaround is implemented in polling mode, so if last block of + payload <128bit don't use DMA mode otherwise TAG is incorrectly generated . */ + /* Set the input and output addresses and start DMA transfer */ + if ((hcryp->Size % 16U) == 0U) + { + CRYP_SetDMAConfig(hcryp, (uint32_t)(hcryp->pCrypInBuffPtr), (hcryp->Size / 4U), (uint32_t)(hcryp->pCrypOutBuffPtr)); + } + else /*to compute last word<128bits, otherwise it will not be encrypted/decrypted */ + { + wordsize = (uint32_t)(hcryp->Size) + (16U - ((uint32_t)(hcryp->Size) % 16U)) ; + + /* Set the input and output addresses and start DMA transfer, pCrypOutBuffPtr size should be %4 */ + CRYP_SetDMAConfig(hcryp, (uint32_t)(hcryp->pCrypInBuffPtr), ((uint16_t)wordsize / 4U), + (uint32_t)(hcryp->pCrypOutBuffPtr)); + } + } + else + { + /* Process unLocked */ + __DAL_UNLOCK(hcryp); + + /* Change the CRYP state and phase */ + hcryp->State = DAL_CRYP_STATE_READY; + } + + /* Return function status */ + return DAL_OK; +} + + +/** + * @brief AES CCM encryption/decryption processing in polling mode + * for TinyAES IP, no encrypt/decrypt performed, only authentication preparation. + * @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains + * the configuration information for CRYP module + * @param Timeout: Timeout duration + * @retval DAL status + */ +static DAL_StatusTypeDef CRYP_AESCCM_Process(CRYP_HandleTypeDef *hcryp, uint32_t Timeout) +{ + uint32_t tickstart; + uint32_t wordsize = (uint32_t)(hcryp->Size) / 4U; + uint16_t outcount; /* Temporary CrypOutCount Value */ + uint32_t DoKeyIVConfig = 1U; /* By default, carry out peripheral Key and IV configuration */ +#if defined(AES) + uint32_t loopcounter; + uint32_t npblb; + uint32_t lastwordsize; +#endif /* AES */ + + if (hcryp->Init.KeyIVConfigSkip == CRYP_KEYIVCONFIG_ONCE) + { + if (hcryp->KeyIVConfig == 1U) + { + /* If the Key and IV configuration has to be done only once + and if it has already been done, skip it */ + DoKeyIVConfig = 0U; + hcryp->SizesSum += hcryp->Size; /* Compute message total payload length */ + } + else + { + /* If the Key and IV configuration has to be done only once + and if it has not been done already, do it and set KeyIVConfig + to keep track it won't have to be done again next time */ + hcryp->KeyIVConfig = 1U; + hcryp->SizesSum = hcryp->Size; /* Merely store payload length */ + } + } + else + { + hcryp->SizesSum = hcryp->Size; + } + + if (DoKeyIVConfig == 1U) + { + + /* Reset CrypHeaderCount */ + hcryp->CrypHeaderCount = 0U; + +#if defined(CRYP) + + /********************** Init phase ******************************************/ + + CRYP_SET_PHASE(hcryp, CRYP_PHASE_INIT); + + /* Set the key */ + CRYP_SetKey(hcryp, hcryp->Init.KeySize); + + /* Set the initialization vector (IV) with CTR1 information */ + hcryp->Instance->IV0L = (hcryp->Init.B0[0]) & CRYP_CCM_CTR1_0; + hcryp->Instance->IV0R = hcryp->Init.B0[1]; + hcryp->Instance->IV1L = hcryp->Init.B0[2]; + hcryp->Instance->IV1R = (hcryp->Init.B0[3] & CRYP_CCM_CTR1_1) | CRYP_CCM_CTR1_2; + + + /* Enable the CRYP peripheral */ + __DAL_CRYP_ENABLE(hcryp); + + /*Write B0 packet into CRYP_DATAIN Register*/ + if (hcryp->Init.DataType == CRYP_DATATYPE_8B) + { + hcryp->Instance->DATAIN = __REV(*(uint32_t *)(hcryp->Init.B0)); + hcryp->Instance->DATAIN = __REV(*(uint32_t *)(hcryp->Init.B0 + 1)); + hcryp->Instance->DATAIN = __REV(*(uint32_t *)(hcryp->Init.B0 + 2)); + hcryp->Instance->DATAIN = __REV(*(uint32_t *)(hcryp->Init.B0 + 3)); + } + else if (hcryp->Init.DataType == CRYP_DATATYPE_16B) + { + hcryp->Instance->DATAIN = __ROR(*(uint32_t *)(hcryp->Init.B0), 16); + hcryp->Instance->DATAIN = __ROR(*(uint32_t *)(hcryp->Init.B0 + 1), 16); + hcryp->Instance->DATAIN = __ROR(*(uint32_t *)(hcryp->Init.B0 + 2), 16); + hcryp->Instance->DATAIN = __ROR(*(uint32_t *)(hcryp->Init.B0 + 3), 16); + } + else if (hcryp->Init.DataType == CRYP_DATATYPE_1B) + { + hcryp->Instance->DATAIN = __RBIT(*(uint32_t *)(hcryp->Init.B0)); + hcryp->Instance->DATAIN = __RBIT(*(uint32_t *)(hcryp->Init.B0 + 1)); + hcryp->Instance->DATAIN = __RBIT(*(uint32_t *)(hcryp->Init.B0 + 2)); + hcryp->Instance->DATAIN = __RBIT(*(uint32_t *)(hcryp->Init.B0 + 3)); + } + else + { + hcryp->Instance->DATAIN = *(uint32_t *)(hcryp->Init.B0); + hcryp->Instance->DATAIN = *(uint32_t *)(hcryp->Init.B0 + 1); + hcryp->Instance->DATAIN = *(uint32_t *)(hcryp->Init.B0 + 2); + hcryp->Instance->DATAIN = *(uint32_t *)(hcryp->Init.B0 + 3); + } + /* Get tick */ + tickstart = DAL_GetTick(); + + /*Wait for the CRYPEN bit to be cleared*/ + while ((hcryp->Instance->CTRL & CRYP_CTRL_CRYPEN) == CRYP_CTRL_CRYPEN) + { + /* Check for the Timeout */ + if (Timeout != DAL_MAX_DELAY) + { + if (((DAL_GetTick() - tickstart) > Timeout) || (Timeout == 0U)) + { + /* Disable the CRYP peripheral clock */ + __DAL_CRYP_DISABLE(hcryp); + + /* Change state */ + hcryp->ErrorCode |= DAL_CRYP_ERROR_TIMEOUT; + hcryp->State = DAL_CRYP_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hcryp); + return DAL_ERROR; + } + } + } +#else /* AES */ + /*AES2v1.1.1 : CCM authentication : no init phase, only header and final phase */ + /* Select header phase */ + CRYP_SET_PHASE(hcryp, CRYP_PHASE_HEADER); + + /* configured encryption mode */ + MODIFY_REG(hcryp->Instance->CTRL, AES_CR_MODE, CRYP_OPERATINGMODE_ENCRYPT); + + /* Set the key */ + CRYP_SetKey(hcryp, hcryp->Init.KeySize); + + /* Set the initialization vector with zero values*/ + hcryp->Instance->IVR3 = 0U; + hcryp->Instance->IVR2 = 0U; + hcryp->Instance->IVR1 = 0U; + hcryp->Instance->IVR0 = 0U; + + /* Enable the CRYP peripheral */ + __DAL_CRYP_ENABLE(hcryp); + + /*Write the B0 packet into CRYP_DATAIN*/ + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->Init.B0); + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->Init.B0 + 1); + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->Init.B0 + 2); + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->Init.B0 + 3); + + /* wait until the end of computation */ + if (CRYP_WaitOnCCFlag(hcryp, Timeout) != DAL_OK) + { + /* Change state */ + hcryp->ErrorCode |= DAL_CRYP_ERROR_TIMEOUT; + hcryp->State = DAL_CRYP_STATE_READY; + + /* Process unlocked & return error */ + __DAL_UNLOCK(hcryp); + return DAL_ERROR; + } + /* Clear CCF flag */ + __DAL_CRYP_CLEAR_FLAG(hcryp, CRYP_CCF_CLEAR); + + /* Set the phase */ + hcryp->Phase = CRYP_PHASE_PROCESS; + + /* From that point the whole message must be processed, first the Header then the payload. + First the Header block(B1) : associated data length expressed in bytes concatenated with Associated Data (A)*/ + + if (hcryp->Init.HeaderSize != 0U) + { + if ((hcryp->Init.HeaderSize % 4U) == 0U) + { + /* HeaderSize %4, no padding */ + for (loopcounter = 0U; (loopcounter < hcryp->Init.HeaderSize); loopcounter += 4U) + { + /* Write the Input block in the Data Input register */ + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount); + hcryp->CrypHeaderCount++ ; + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount); + hcryp->CrypHeaderCount++ ; + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount); + hcryp->CrypHeaderCount++ ; + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount); + hcryp->CrypHeaderCount++ ; + + if (CRYP_WaitOnCCFlag(hcryp, Timeout) != DAL_OK) + { + /* Disable the CRYP peripheral clock */ + __DAL_CRYP_DISABLE(hcryp); + + /* Change state */ + hcryp->ErrorCode |= DAL_CRYP_ERROR_TIMEOUT; + hcryp->State = DAL_CRYP_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hcryp); + return DAL_ERROR; + } + /* Clear CCF Flag */ + __DAL_CRYP_CLEAR_FLAG(hcryp, CRYP_CCF_CLEAR); + } + } + else + { + /*Write Header block in the IN FIFO without last block */ + for (loopcounter = 0U; (loopcounter < ((hcryp->Init.HeaderSize) - (hcryp->Init.HeaderSize % 4U))); loopcounter += 4U) + { + /* Write the input block in the data input register */ + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount); + hcryp->CrypHeaderCount++ ; + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount); + hcryp->CrypHeaderCount++ ; + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount); + hcryp->CrypHeaderCount++ ; + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount); + hcryp->CrypHeaderCount++ ; + + if (CRYP_WaitOnCCFlag(hcryp, Timeout) != DAL_OK) + { + /* Disable the CRYP peripheral clock */ + __DAL_CRYP_DISABLE(hcryp); + + /* Change state */ + hcryp->ErrorCode |= DAL_CRYP_ERROR_TIMEOUT; + hcryp->State = DAL_CRYP_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hcryp); + return DAL_ERROR; + } + /* Clear CCF Flag */ + __DAL_CRYP_CLEAR_FLAG(hcryp, CRYP_CCF_CLEAR); + } + /* Last block optionally pad the data with zeros*/ + for (loopcounter = 0U; (loopcounter < (hcryp->Init.HeaderSize % 4U)); loopcounter++) + { + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount); + hcryp->CrypHeaderCount++ ; + } + while (loopcounter < 4U) + { + /* Pad the data with zeros to have a complete block */ + hcryp->Instance->DATAINR = 0x0U; + loopcounter++; + } + + if (CRYP_WaitOnCCFlag(hcryp, Timeout) != DAL_OK) + { + /* Disable the CRYP peripheral clock */ + __DAL_CRYP_DISABLE(hcryp); + + /* Change state */ + hcryp->ErrorCode |= DAL_CRYP_ERROR_TIMEOUT; + hcryp->State = DAL_CRYP_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hcryp); + return DAL_ERROR; + } + /* Clear CCF flag */ + __DAL_CRYP_CLEAR_FLAG(hcryp, CRYP_CCF_CLEAR); + } + } + } /* if (DoKeyIVConfig == 1U) */ + /* Then the payload: cleartext payload (not the ciphertext payload). + Write input Data, no output Data to get */ + if (hcryp->Size != 0U) + { + if ((hcryp->Size % 16U) != 0U) + { + /* recalculate wordsize */ + wordsize = ((wordsize / 4U) * 4U) ; + } + + /* Get tick */ + tickstart = DAL_GetTick(); + /*Temporary CrypOutCount Value*/ + outcount = hcryp->CrypOutCount; + + while ((hcryp->CrypInCount < wordsize) && (outcount < wordsize)) + { + /* Write plain data and get cipher data */ + CRYP_AES_ProcessData(hcryp, Timeout); + + /*Temporary CrypOutCount Value*/ + outcount = hcryp->CrypOutCount; + + /* Check for the Timeout */ + if (Timeout != DAL_MAX_DELAY) + { + if (((DAL_GetTick() - tickstart) > Timeout) || (Timeout == 0U)) + { + /* Disable the CRYP peripheral clock */ + __DAL_CRYP_DISABLE(hcryp); + + /* Change state */ + hcryp->ErrorCode |= DAL_CRYP_ERROR_TIMEOUT; + hcryp->State = DAL_CRYP_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hcryp); + return DAL_ERROR; + } + } + } + + if ((hcryp->Size % 16U) != 0U) + { + /* Compute the number of padding bytes in last block of payload */ + npblb = ((((uint32_t)(hcryp->Size) / 16U) + 1U) * 16U) - (uint32_t)(hcryp->Size); + + /* Number of valid words (lastwordsize) in last block */ + if ((npblb % 4U) == 0U) + { + lastwordsize = (16U - npblb) / 4U; + } + else + { + lastwordsize = ((16U - npblb) / 4U) + 1U; + } + /* Last block optionally pad the data with zeros*/ + for (loopcounter = 0U; loopcounter < lastwordsize; loopcounter ++) + { + /* Write the last input block in the IN FIFO */ + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount); + hcryp->CrypInCount++; + } + while (loopcounter < 4U) + { + /* Pad the data with zeros to have a complete block */ + hcryp->Instance->DATAINR = 0U; + loopcounter++; + } + /* Wait for CCF flag to be raised */ + if (CRYP_WaitOnCCFlag(hcryp, Timeout) != DAL_OK) + { + /* Disable the CRYP peripheral clock */ + __DAL_CRYP_DISABLE(hcryp); + + /* Change state */ + hcryp->ErrorCode |= DAL_CRYP_ERROR_TIMEOUT; + hcryp->State = DAL_CRYP_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hcryp); + return DAL_ERROR; + } + /* Clear CCF flag */ + __DAL_CRYP_CLEAR_FLAG(hcryp, CRYP_CCF_CLEAR); + + } + } +#endif /* End AES or CRYP */ + +#if defined(CRYP) + + /************************* Header phase *************************************/ + /* Header block(B1) : associated data length expressed in bytes concatenated + with Associated Data (A)*/ + + if (CRYP_GCMCCM_SetHeaderPhase(hcryp, Timeout) != DAL_OK) + { + return DAL_ERROR; + } + + /********************** Payload phase ***************************************/ + + /* Set the phase */ + hcryp->Phase = CRYP_PHASE_PROCESS; + + /* Disable the CRYP peripheral */ + __DAL_CRYP_DISABLE(hcryp); + + /* Select payload phase once the header phase is performed */ + CRYP_SET_PHASE(hcryp, CRYP_PHASE_PAYLOAD); + + /* Enable the CRYP peripheral */ + __DAL_CRYP_ENABLE(hcryp); + + } /* if (DoKeyIVConfig == 1U) */ + + if ((hcryp->Size % 16U) != 0U) + { + /* recalculate wordsize */ + wordsize = ((wordsize / 4U) * 4U) ; + } + /* Get tick */ + tickstart = DAL_GetTick(); + /*Temporary CrypOutCount Value*/ + outcount = hcryp->CrypOutCount; + + /* Write input data and get output data */ + while ((hcryp->CrypInCount < wordsize) && (outcount < wordsize)) + { + /* Write plain data and get cipher data */ + CRYP_AES_ProcessData(hcryp, Timeout); + + /* Check for the Timeout */ + if (Timeout != DAL_MAX_DELAY) + { + if (((DAL_GetTick() - tickstart) > Timeout) || (Timeout == 0U)) + { + /* Disable the CRYP peripheral clock */ + __DAL_CRYP_DISABLE(hcryp); + + /* Change state */ + hcryp->ErrorCode |= DAL_CRYP_ERROR_TIMEOUT; + hcryp->State = DAL_CRYP_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hcryp); + return DAL_ERROR; + } + } + } + + if ((hcryp->Size % 16U) != 0U) + { + /* CRYP Workaround : CRYP1 generates correct TAG during CCM decryption only when ciphertext blocks size is multiple of + 128 bits. If lthe size of the last block of payload is inferior to 128 bits, when CCM decryption + is selected, then the TAG message will be wrong.*/ + CRYP_Workaround(hcryp, Timeout); + } +#endif /* CRYP */ + + /* Return function status */ + return DAL_OK; +} + +/** + * @brief AES CCM encryption/decryption process in interrupt mode + * for TinyAES IP, no encrypt/decrypt performed, only authentication preparation. + * @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains + * the configuration information for CRYP module + * @retval DAL status + */ +static DAL_StatusTypeDef CRYP_AESCCM_Process_IT(CRYP_HandleTypeDef *hcryp) +{ + uint32_t DoKeyIVConfig = 1U; /* By default, carry out peripheral Key and IV configuration */ +#if defined(CRYP) + __IO uint32_t count = 0U; +#endif /* CRYP */ + + if (hcryp->Init.KeyIVConfigSkip == CRYP_KEYIVCONFIG_ONCE) + { + if (hcryp->KeyIVConfig == 1U) + { + /* If the Key and IV configuration has to be done only once + and if it has already been done, skip it */ + DoKeyIVConfig = 0U; + hcryp->SizesSum += hcryp->Size; /* Compute message total payload length */ + } + else + { + /* If the Key and IV configuration has to be done only once + and if it has not been done already, do it and set KeyIVConfig + to keep track it won't have to be done again next time */ + hcryp->KeyIVConfig = 1U; + hcryp->SizesSum = hcryp->Size; /* Merely store payload length */ + } + } + else + { + hcryp->SizesSum = hcryp->Size; + } + + /* Configure Key, IV and process message (header and payload) */ + if (DoKeyIVConfig == 1U) + { + /* Reset CrypHeaderCount */ + hcryp->CrypHeaderCount = 0U; + +#if defined(CRYP) + + /************ Init phase ************/ + + CRYP_SET_PHASE(hcryp, CRYP_PHASE_INIT); + + /* Set the key */ + CRYP_SetKey(hcryp, hcryp->Init.KeySize); + + /* Set the initialization vector (IV) with CTR1 information */ + hcryp->Instance->IV0L = (hcryp->Init.B0[0]) & CRYP_CCM_CTR1_0; + hcryp->Instance->IV0R = hcryp->Init.B0[1]; + hcryp->Instance->IV1L = hcryp->Init.B0[2]; + hcryp->Instance->IV1R = (hcryp->Init.B0[3] & CRYP_CCM_CTR1_1) | CRYP_CCM_CTR1_2; + + /* Enable the CRYP peripheral */ + __DAL_CRYP_ENABLE(hcryp); + + /*Write the B0 packet into CRYP_DATAIN Register*/ + if (hcryp->Init.DataType == CRYP_DATATYPE_8B) + { + hcryp->Instance->DATAIN = __REV(*(uint32_t *)(hcryp->Init.B0)); + hcryp->Instance->DATAIN = __REV(*(uint32_t *)(hcryp->Init.B0 + 1)); + hcryp->Instance->DATAIN = __REV(*(uint32_t *)(hcryp->Init.B0 + 2)); + hcryp->Instance->DATAIN = __REV(*(uint32_t *)(hcryp->Init.B0 + 3)); + } + else if (hcryp->Init.DataType == CRYP_DATATYPE_16B) + { + hcryp->Instance->DATAIN = __ROR(*(uint32_t *)(hcryp->Init.B0), 16); + hcryp->Instance->DATAIN = __ROR(*(uint32_t *)(hcryp->Init.B0 + 1), 16); + hcryp->Instance->DATAIN = __ROR(*(uint32_t *)(hcryp->Init.B0 + 2), 16); + hcryp->Instance->DATAIN = __ROR(*(uint32_t *)(hcryp->Init.B0 + 3), 16); + } + else if (hcryp->Init.DataType == CRYP_DATATYPE_1B) + { + hcryp->Instance->DATAIN = __RBIT(*(uint32_t *)(hcryp->Init.B0)); + hcryp->Instance->DATAIN = __RBIT(*(uint32_t *)(hcryp->Init.B0 + 1)); + hcryp->Instance->DATAIN = __RBIT(*(uint32_t *)(hcryp->Init.B0 + 2)); + hcryp->Instance->DATAIN = __RBIT(*(uint32_t *)(hcryp->Init.B0 + 3)); + } + else + { + hcryp->Instance->DATAIN = *(uint32_t *)(hcryp->Init.B0); + hcryp->Instance->DATAIN = *(uint32_t *)(hcryp->Init.B0 + 1); + hcryp->Instance->DATAIN = *(uint32_t *)(hcryp->Init.B0 + 2); + hcryp->Instance->DATAIN = *(uint32_t *)(hcryp->Init.B0 + 3); + } + /*Wait for the CRYPEN bit to be cleared*/ + count = CRYP_TIMEOUT_GCMCCMINITPHASE; + do + { + count-- ; + if (count == 0U) + { + /* Disable the CRYP peripheral clock */ + __DAL_CRYP_DISABLE(hcryp); + + /* Change state */ + hcryp->ErrorCode |= DAL_CRYP_ERROR_TIMEOUT; + hcryp->State = DAL_CRYP_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hcryp); + return DAL_ERROR; + } + } while ((hcryp->Instance->CTRL & CRYP_CTRL_CRYPEN) == CRYP_CTRL_CRYPEN); + + /* Select header phase */ + CRYP_SET_PHASE(hcryp, CRYP_PHASE_HEADER); + + } /* end of if (DoKeyIVConfig == 1U) */ + + /* Enable interrupts */ + __DAL_CRYP_ENABLE_IT(hcryp, CRYP_IT_INI); + + /* Enable CRYP */ + __DAL_CRYP_ENABLE(hcryp); + +#else /* AES */ + + /*AES2v1.1.1 : CCM authentication : no init phase, only header and final phase */ + /* Select header phase */ + CRYP_SET_PHASE(hcryp, CRYP_PHASE_HEADER); + + /* configured mode and encryption mode */ + MODIFY_REG(hcryp->Instance->CTRL, AES_CR_MODE, CRYP_OPERATINGMODE_ENCRYPT); + + /* Set the key */ + CRYP_SetKey(hcryp, hcryp->Init.KeySize); + + /* Set the initialization vector with zero values*/ + hcryp->Instance->IVR3 = 0U; + hcryp->Instance->IVR2 = 0U; + hcryp->Instance->IVR1 = 0U; + hcryp->Instance->IVR0 = 0U; + + /* Enable interrupts */ + __DAL_CRYP_ENABLE_IT(hcryp, CRYP_IT_CCFIE | CRYP_IT_ERRIE); + /* Enable the CRYP peripheral */ + __DAL_CRYP_ENABLE(hcryp); + + /*Write the B0 packet into CRYP_DATAIN*/ + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->Init.B0); + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->Init.B0 + 1); + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->Init.B0 + 2); + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->Init.B0 + 3); + + } /* end of if (DoKeyIVConfig == 1U) */ +#endif /* End AES or CRYP */ + + /* Return function status */ + return DAL_OK; +} +/** + * @brief AES CCM encryption/decryption process in DMA mode + * for TinyAES IP, no encrypt/decrypt performed, only authentication preparation. + * @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains + * the configuration information for CRYP module + * @retval DAL status + */ +static DAL_StatusTypeDef CRYP_AESCCM_Process_DMA(CRYP_HandleTypeDef *hcryp) +{ + uint32_t wordsize; + __IO uint32_t count = 0U; + uint32_t DoKeyIVConfig = 1U; /* By default, carry out peripheral Key and IV configuration */ +#if defined(AES) + uint32_t loopcounter; + uint32_t npblb; + uint32_t lastwordsize; +#endif + + if (hcryp->Init.KeyIVConfigSkip == CRYP_KEYIVCONFIG_ONCE) + { + if (hcryp->KeyIVConfig == 1U) + { + /* If the Key and IV configuration has to be done only once + and if it has already been done, skip it */ + DoKeyIVConfig = 0U; + hcryp->SizesSum += hcryp->Size; /* Compute message total payload length */ + } + else + { + /* If the Key and IV configuration has to be done only once + and if it has not been done already, do it and set KeyIVConfig + to keep track it won't have to be done again next time */ + hcryp->KeyIVConfig = 1U; + hcryp->SizesSum = hcryp->Size; /* Merely store payload length */ + } + } + else + { + hcryp->SizesSum = hcryp->Size; + } + + if (DoKeyIVConfig == 1U) + { + + /* Reset CrypHeaderCount */ + hcryp->CrypHeaderCount = 0U; + +#if defined(CRYP) + + /************************** Init phase **************************************/ + + CRYP_SET_PHASE(hcryp, CRYP_PHASE_INIT); + + /* Set the key */ + CRYP_SetKey(hcryp, hcryp->Init.KeySize); + + /* Set the initialization vector (IV) with CTR1 information */ + hcryp->Instance->IV0L = (hcryp->Init.B0[0]) & CRYP_CCM_CTR1_0; + hcryp->Instance->IV0R = hcryp->Init.B0[1]; + hcryp->Instance->IV1L = hcryp->Init.B0[2]; + hcryp->Instance->IV1R = (hcryp->Init.B0[3] & CRYP_CCM_CTR1_1) | CRYP_CCM_CTR1_2; + + /* Enable the CRYP peripheral */ + __DAL_CRYP_ENABLE(hcryp); + + /*Write the B0 packet into CRYP_DATAIN Register*/ + if (hcryp->Init.DataType == CRYP_DATATYPE_8B) + { + hcryp->Instance->DATAIN = __REV(*(uint32_t *)(hcryp->Init.B0)); + hcryp->Instance->DATAIN = __REV(*(uint32_t *)(hcryp->Init.B0 + 1)); + hcryp->Instance->DATAIN = __REV(*(uint32_t *)(hcryp->Init.B0 + 2)); + hcryp->Instance->DATAIN = __REV(*(uint32_t *)(hcryp->Init.B0 + 3)); + } + else if (hcryp->Init.DataType == CRYP_DATATYPE_16B) + { + hcryp->Instance->DATAIN = __ROR(*(uint32_t *)(hcryp->Init.B0), 16); + hcryp->Instance->DATAIN = __ROR(*(uint32_t *)(hcryp->Init.B0 + 1), 16); + hcryp->Instance->DATAIN = __ROR(*(uint32_t *)(hcryp->Init.B0 + 2), 16); + hcryp->Instance->DATAIN = __ROR(*(uint32_t *)(hcryp->Init.B0 + 3), 16); + } + else if (hcryp->Init.DataType == CRYP_DATATYPE_1B) + { + hcryp->Instance->DATAIN = __RBIT(*(uint32_t *)(hcryp->Init.B0)); + hcryp->Instance->DATAIN = __RBIT(*(uint32_t *)(hcryp->Init.B0 + 1)); + hcryp->Instance->DATAIN = __RBIT(*(uint32_t *)(hcryp->Init.B0 + 2)); + hcryp->Instance->DATAIN = __RBIT(*(uint32_t *)(hcryp->Init.B0 + 3)); + } + else + { + hcryp->Instance->DATAIN = *(uint32_t *)(hcryp->Init.B0); + hcryp->Instance->DATAIN = *(uint32_t *)(hcryp->Init.B0 + 1); + hcryp->Instance->DATAIN = *(uint32_t *)(hcryp->Init.B0 + 2); + hcryp->Instance->DATAIN = *(uint32_t *)(hcryp->Init.B0 + 3); + } + + /*Wait for the CRYPEN bit to be cleared*/ + count = CRYP_TIMEOUT_GCMCCMINITPHASE; + do + { + count-- ; + if (count == 0U) + { + /* Disable the CRYP peripheral clock */ + __DAL_CRYP_DISABLE(hcryp); + + /* Change state */ + hcryp->ErrorCode |= DAL_CRYP_ERROR_TIMEOUT; + hcryp->State = DAL_CRYP_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hcryp); + return DAL_ERROR; + } + } while ((hcryp->Instance->CTRL & CRYP_CTRL_CRYPEN) == CRYP_CTRL_CRYPEN); + +#else /* AES */ + + /*AES2v1.1.1 : CCM authentication : no init phase, only header and final phase */ + /* Select header phase */ + CRYP_SET_PHASE(hcryp, CRYP_PHASE_HEADER); + + /* configured encryption mode */ + MODIFY_REG(hcryp->Instance->CTRL, AES_CR_MODE, CRYP_OPERATINGMODE_ENCRYPT); + + /* Set the key */ + CRYP_SetKey(hcryp, hcryp->Init.KeySize); + + /* Set the initialization vector with zero values*/ + hcryp->Instance->IVR3 = 0U; + hcryp->Instance->IVR2 = 0U; + hcryp->Instance->IVR1 = 0U; + hcryp->Instance->IVR0 = 0U; + + /* Enable the CRYP peripheral */ + __DAL_CRYP_ENABLE(hcryp); + + /*Write the B0 packet into CRYP_DATAIN*/ + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->Init.B0); + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->Init.B0 + 1); + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->Init.B0 + 2); + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->Init.B0 + 3); + + count = CRYP_TIMEOUT_GCMCCMINITPHASE; + do + { + count-- ; + if (count == 0U) + { + /* Disable the CRYP peripheral clock */ + __DAL_CRYP_DISABLE(hcryp); + + /* Change state */ + hcryp->ErrorCode |= DAL_CRYP_ERROR_TIMEOUT; + hcryp->State = DAL_CRYP_STATE_READY; + + /* Process Unlocked */ + __DAL_UNLOCK(hcryp); + return DAL_ERROR; + } + } while (DAL_IS_BIT_CLR(hcryp->Instance->STS, AES_SR_CCF)); + /* Clear CCF flag */ + __DAL_CRYP_CLEAR_FLAG(hcryp, CRYP_CCF_CLEAR); + + /* Set the phase */ + hcryp->Phase = CRYP_PHASE_PROCESS; + + /* From that point the whole message must be processed, first the Header then the payload. + First the Header block(B1) : associated data length expressed in bytes concatenated with Associated Data (A)*/ + + if (hcryp->Init.HeaderSize != 0U) + { + if ((hcryp->Init.HeaderSize % 4U) == 0U) + { + /* HeaderSize %4, no padding */ + for (loopcounter = 0U; (loopcounter < hcryp->Init.HeaderSize); loopcounter += 4U) + { + /* Write the Input block in the Data Input register */ + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount); + hcryp->CrypHeaderCount++ ; + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount); + hcryp->CrypHeaderCount++ ; + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount); + hcryp->CrypHeaderCount++ ; + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount); + hcryp->CrypHeaderCount++ ; + + /* wait until the end of computation */ + count = CRYP_TIMEOUT_GCMCCMINITPHASE; + do + { + count-- ; + if (count == 0U) + { + /* Disable the CRYP peripheral clock */ + __DAL_CRYP_DISABLE(hcryp); + + /* Change state */ + hcryp->ErrorCode |= DAL_CRYP_ERROR_TIMEOUT; + hcryp->State = DAL_CRYP_STATE_READY; + + /* Process Unlocked */ + __DAL_UNLOCK(hcryp); + return DAL_ERROR; + } + } while (DAL_IS_BIT_CLR(hcryp->Instance->STS, AES_SR_CCF)); + /* Clear CCF flag */ + __DAL_CRYP_CLEAR_FLAG(hcryp, CRYP_CCF_CLEAR); + } + } + else + { + /*Write Header block in the IN FIFO without last block */ + for (loopcounter = 0U; (loopcounter < ((hcryp->Init.HeaderSize) - (hcryp->Init.HeaderSize % 4U))); loopcounter += 4U) + { + /* Write the input block in the data input register */ + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount); + hcryp->CrypHeaderCount++ ; + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount); + hcryp->CrypHeaderCount++ ; + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount); + hcryp->CrypHeaderCount++ ; + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount); + hcryp->CrypHeaderCount++ ; + + count = CRYP_TIMEOUT_GCMCCMINITPHASE; + do + { + count-- ; + if (count == 0U) + { + /* Disable the CRYP peripheral clock */ + __DAL_CRYP_DISABLE(hcryp); + + /* Change state */ + hcryp->ErrorCode |= DAL_CRYP_ERROR_TIMEOUT; + hcryp->State = DAL_CRYP_STATE_READY; + + /* Process Unlocked */ + __DAL_UNLOCK(hcryp); + return DAL_ERROR; + } + } while (DAL_IS_BIT_CLR(hcryp->Instance->STS, AES_SR_CCF)); + /* Clear CCF flag */ + __DAL_CRYP_CLEAR_FLAG(hcryp, CRYP_CCF_CLEAR); + } + /* Last block optionally pad the data with zeros*/ + for (loopcounter = 0U; (loopcounter < (hcryp->Init.HeaderSize % 4U)); loopcounter++) + { + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount); + hcryp->CrypHeaderCount++ ; + } + while (loopcounter < 4U) + { + /* Pad the data with zeros to have a complete block */ + hcryp->Instance->DATAINR = 0x0U; + loopcounter++; + } + + count = CRYP_TIMEOUT_GCMCCMINITPHASE; + do + { + count-- ; + if (count == 0U) + { + /* Disable the CRYP peripheral clock */ + __DAL_CRYP_DISABLE(hcryp); + + /* Change state */ + hcryp->ErrorCode |= DAL_CRYP_ERROR_TIMEOUT; + hcryp->State = DAL_CRYP_STATE_READY; + + /* Process Unlocked */ + __DAL_UNLOCK(hcryp); + return DAL_ERROR; + } + } while (DAL_IS_BIT_CLR(hcryp->Instance->STS, AES_SR_CCF)); + /* Clear CCF flag */ + __DAL_CRYP_CLEAR_FLAG(hcryp, CRYP_CCF_CLEAR); + } + } + } /* if (DoKeyIVConfig == 1U) */ + /* Then the payload: cleartext payload (not the ciphertext payload). + Write input Data, no output Data to get */ + if (hcryp->Size != 0U) + { + if (hcryp->Size >= 16U) + { + if ((hcryp->Size % 16U) == 0U) + { + CRYP_SetDMAConfig(hcryp, (uint32_t)(hcryp->pCrypInBuffPtr), (hcryp->Size / 4U), (uint32_t)(hcryp->pCrypOutBuffPtr)); + } + else /*to compute last word<128bits, otherwise it will not be encrypted/decrypted */ + { + wordsize = (uint32_t)(hcryp->Size) + (16U - ((uint32_t)(hcryp->Size) % 16U)) ; + + /* Set the input and output addresses and start DMA transfer, pCrypOutBuffPtr size should be %4 */ + CRYP_SetDMAConfig(hcryp, (uint32_t)(hcryp->pCrypInBuffPtr), ((uint16_t)wordsize / 4U), + (uint32_t)(hcryp->pCrypOutBuffPtr)); + } + } + if ((hcryp->Size < 16U) != 0U) + { + /* Compute the number of padding bytes in last block of payload */ + npblb = ((((uint32_t)(hcryp->Size) / 16U) + 1U) * 16U) - (uint32_t)(hcryp->Size); + + /* Number of valid words (lastwordsize) in last block */ + if ((npblb % 4U) == 0U) + { + lastwordsize = (16U - npblb) / 4U; + } + else + { + lastwordsize = ((16U - npblb) / 4U) + 1U; + } + /* Last block optionally pad the data with zeros*/ + for (loopcounter = 0U; loopcounter < lastwordsize; loopcounter ++) + { + /* Write the last input block in the IN FIFO */ + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount); + hcryp->CrypInCount++; + } + while (loopcounter < 4U) + { + /* Pad the data with zeros to have a complete block */ + hcryp->Instance->DATAINR = 0U; + loopcounter++; + } + count = CRYP_TIMEOUT_GCMCCMINITPHASE; + do + { + count-- ; + if (count == 0U) + { + /* Disable the CRYP peripheral clock */ + __DAL_CRYP_DISABLE(hcryp); + + /* Change state */ + hcryp->ErrorCode |= DAL_CRYP_ERROR_TIMEOUT; + hcryp->State = DAL_CRYP_STATE_READY; + + /* Process Unlocked */ + __DAL_UNLOCK(hcryp); + return DAL_ERROR; + } + } while (DAL_IS_BIT_CLR(hcryp->Instance->STS, AES_SR_CCF)); + /* Clear CCF flag */ + __DAL_CRYP_CLEAR_FLAG(hcryp, CRYP_CCF_CLEAR); + + /* Process unlocked */ + __DAL_UNLOCK(hcryp); + + /* Change the CRYP state and phase */ + hcryp->State = DAL_CRYP_STATE_READY; + } + } + else + { + /* Process unLocked */ + __DAL_UNLOCK(hcryp); + + /* Change the CRYP state and phase */ + hcryp->State = DAL_CRYP_STATE_READY; + } +#endif /* AES */ +#if defined(CRYP) + /********************* Header phase *****************************************/ + + if (CRYP_GCMCCM_SetHeaderPhase_DMA(hcryp) != DAL_OK) + { + return DAL_ERROR; + } + + /******************** Payload phase *****************************************/ + + /* Set the phase */ + hcryp->Phase = CRYP_PHASE_PROCESS; + + /* Disable the CRYP peripheral */ + __DAL_CRYP_DISABLE(hcryp); + + /* Select payload phase once the header phase is performed */ + CRYP_SET_PHASE(hcryp, CRYP_PHASE_PAYLOAD); + + } /* if (DoKeyIVConfig == 1U) */ + if (hcryp->Size != 0U) + { + /* Size should be %4 otherwise Tag will be incorrectly generated for GCM Encryption & CCM Decryption + Workaround is implemented in polling mode, so if last block of + payload <128bit don't use DAL_CRYP_AESGCM_DMA otherwise TAG is incorrectly generated for GCM Encryption. */ + /* Set the input and output addresses and start DMA transfer */ + if ((hcryp->Size % 16U) == 0U) + { + CRYP_SetDMAConfig(hcryp, (uint32_t)(hcryp->pCrypInBuffPtr), hcryp->Size / 4U, (uint32_t)(hcryp->pCrypOutBuffPtr)); + } + else + { + wordsize = (uint32_t)(hcryp->Size) + 16U - ((uint32_t)(hcryp->Size) % 16U) ; + + /* Set the input and output addresses and start DMA transfer, pCrypOutBuffPtr size should be %4*/ + CRYP_SetDMAConfig(hcryp, (uint32_t)(hcryp->pCrypInBuffPtr), (uint16_t)wordsize / 4U, + (uint32_t)(hcryp->pCrypOutBuffPtr)); + } + } + else /*Size = 0*/ + { + /* Process unlocked */ + __DAL_UNLOCK(hcryp); + + /* Change the CRYP state and phase */ + hcryp->State = DAL_CRYP_STATE_READY; + } +#endif /* CRYP */ + /* Return function status */ + return DAL_OK; +} + +/** + * @brief Sets the payload phase in iterrupt mode + * @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains + * the configuration information for CRYP module + * @retval state + */ +static void CRYP_GCMCCM_SetPayloadPhase_IT(CRYP_HandleTypeDef *hcryp) +{ + uint32_t loopcounter; + uint32_t temp[4]; /* Temporary CrypOutBuff */ + uint32_t lastwordsize; + uint32_t npblb; + uint32_t i; +#if defined(AES) + uint16_t outcount; /* Temporary CrypOutCount Value */ +#endif /* AES */ + + /***************************** Payload phase *******************************/ + +#if defined(CRYP) + if (hcryp->Size == 0U) + { + /* Disable interrupts */ + __DAL_CRYP_DISABLE_IT(hcryp, CRYP_IT_INI | CRYP_IT_OUTI); + + /* Process unlocked */ + __DAL_UNLOCK(hcryp); + + /* Change the CRYP state */ + hcryp->State = DAL_CRYP_STATE_READY; + } + + else if (((hcryp->Size / 4U) - (hcryp->CrypInCount)) >= 4U) + { + /* Write the input block in the IN FIFO */ + hcryp->Instance->DATAIN = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount); + hcryp->CrypInCount++; + hcryp->Instance->DATAIN = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount); + hcryp->CrypInCount++; + hcryp->Instance->DATAIN = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount); + hcryp->CrypInCount++; + hcryp->Instance->DATAIN = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount); + hcryp->CrypInCount++; + if (((hcryp->Size / 4U) == hcryp->CrypInCount) && ((hcryp->Size % 16U) == 0U)) + { + /* Disable interrupts */ + __DAL_CRYP_DISABLE_IT(hcryp, CRYP_IT_INI); + + /* Call the input data transfer complete callback */ +#if (USE_DAL_CRYP_REGISTER_CALLBACKS == 1U) + /*Call registered Input complete callback*/ + hcryp->InCpltCallback(hcryp); +#else + /*Call legacy weak Input complete callback*/ + DAL_CRYP_InCpltCallback(hcryp); +#endif /* USE_DAL_CRYP_REGISTER_CALLBACKS */ + } + if (hcryp->CrypOutCount < (hcryp->Size / 4U)) + { + /* Read the output block from the Output FIFO and put them in temporary buffer then get CrypOutBuff from temporary buffer */ + for (i = 0U; i < 4U; i++) + { + temp[i] = hcryp->Instance->DATAOUT; + } + i = 0U; + while (((hcryp->CrypOutCount < ((hcryp->Size) / 4U))) && (i < 4U)) + { + *(uint32_t *)(hcryp->pCrypOutBuffPtr + hcryp->CrypOutCount) = temp[i]; + hcryp->CrypOutCount++; + i++; + } + if (((hcryp->Size / 4U) == hcryp->CrypOutCount) && ((hcryp->Size % 16U) == 0U)) + { + /* Disable interrupts */ + __DAL_CRYP_DISABLE_IT(hcryp, CRYP_IT_OUTI); + + /* Change the CRYP state */ + hcryp->State = DAL_CRYP_STATE_READY; + + /* Disable CRYP */ + __DAL_CRYP_DISABLE(hcryp); + + /* Process unlocked */ + __DAL_UNLOCK(hcryp); + + /* Call output transfer complete callback */ +#if (USE_DAL_CRYP_REGISTER_CALLBACKS == 1) + /*Call registered Output complete callback*/ + hcryp->OutCpltCallback(hcryp); +#else + /*Call legacy weak Output complete callback*/ + DAL_CRYP_OutCpltCallback(hcryp); +#endif /* USE_DAL_CRYP_REGISTER_CALLBACKS */ + } + } + } + else if ((hcryp->Size % 16U) != 0U) + { + /* Size should be %4 in word and %16 in byte otherwise TAG will be incorrectly generated for GCM Encryption & CCM Decryption + Workaround is implemented in polling mode, so if last block of + payload <128bit don't use CRYP_AESGCM_Encrypt_IT otherwise TAG is incorrectly generated. */ + + /* Compute the number of padding bytes in last block of payload */ + npblb = ((((uint32_t)(hcryp->Size) / 16U) + 1U) * 16U) - (uint32_t)(hcryp->Size); + + /* Number of valid words (lastwordsize) in last block */ + if ((npblb % 4U) == 0U) + { + lastwordsize = (16U - npblb) / 4U; + } + else + { + lastwordsize = ((16U - npblb) / 4U) + 1U; + } + + /* Last block optionally pad the data with zeros*/ + for (loopcounter = 0U; loopcounter < lastwordsize; loopcounter++) + { + hcryp->Instance->DATAIN = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount); + hcryp->CrypInCount++; + } + while (loopcounter < 4U) + { + /* Pad the data with zeros to have a complete block */ + hcryp->Instance->DATAIN = 0x0U; + loopcounter++; + } + __DAL_CRYP_DISABLE_IT(hcryp, CRYP_IT_INI); + + if ((hcryp->Instance->STS & CRYP_FLAG_OFNE) != 0x0U) + { + for (i = 0U; i < 4U; i++) + { + temp[i] = hcryp->Instance->DATAOUT; + } + if (((hcryp->Size) / 4U) == 0U) + { + for (i = 0U; i < ((uint32_t)(hcryp->Size) % 4U); i++) + { + *(uint32_t *)(hcryp->pCrypOutBuffPtr + hcryp->CrypOutCount) = temp[i]; + hcryp->CrypOutCount++; + } + } + i = 0x0U; + while (((hcryp->CrypOutCount < ((hcryp->Size) / 4U))) && (i < 4U)) + { + *(uint32_t *)(hcryp->pCrypOutBuffPtr + hcryp->CrypOutCount) = temp[i]; + hcryp->CrypOutCount++; + i++; + } + } + if (hcryp->CrypOutCount >= (hcryp->Size / 4U)) + { + /* Disable interrupts */ + __DAL_CRYP_DISABLE_IT(hcryp, CRYP_IT_OUTI | CRYP_IT_INI); + + /* Change the CRYP peripheral state */ + hcryp->State = DAL_CRYP_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hcryp); + + /* Call output transfer complete callback */ +#if (USE_DAL_CRYP_REGISTER_CALLBACKS == 1) + /*Call registered Output complete callback*/ + hcryp->OutCpltCallback(hcryp); +#else + /*Call legacy weak Output complete callback*/ + DAL_CRYP_OutCpltCallback(hcryp); +#endif /* USE_DAL_CRYP_REGISTER_CALLBACKS */ + } + } + else + { + /* Nothing to do */ + } +#else /* AES */ + + /* Read the output block from the output FIFO and put them in temporary buffer then get CrypOutBuff from temporary buffer*/ + for (i = 0U; i < 4U; i++) + { + temp[i] = hcryp->Instance->DATAOUTR; + } + i = 0U; + while ((hcryp->CrypOutCount < ((hcryp->Size + 3U) / 4U)) && (i < 4U)) + { + *(uint32_t *)(hcryp->pCrypOutBuffPtr + hcryp->CrypOutCount) = temp[i]; + hcryp->CrypOutCount++; + i++; + } + /*Temporary CrypOutCount Value*/ + outcount = hcryp->CrypOutCount; + + if ((hcryp->CrypOutCount >= (hcryp->Size / 4U)) && ((outcount * 4U) >= hcryp->Size)) + { + /* Disable computation complete flag and errors interrupts */ + __DAL_CRYP_DISABLE_IT(hcryp, CRYP_IT_CCFIE | CRYP_IT_ERRIE); + + /* Change the CRYP state */ + hcryp->State = DAL_CRYP_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hcryp); + + /* Call output transfer complete callback */ +#if (USE_DAL_CRYP_REGISTER_CALLBACKS == 1) + /*Call registered Output complete callback*/ + hcryp->OutCpltCallback(hcryp); +#else + /*Call legacy weak Output complete callback*/ + DAL_CRYP_OutCpltCallback(hcryp); +#endif /* USE_DAL_CRYP_REGISTER_CALLBACKS */ + } + + else if (((hcryp->Size / 4U) - (hcryp->CrypInCount)) >= 4U) + { + /* Write the input block in the IN FIFO */ + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount); + hcryp->CrypInCount++; + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount); + hcryp->CrypInCount++; + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount); + hcryp->CrypInCount++; + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount); + hcryp->CrypInCount++; + if ((hcryp->CrypInCount == (hcryp->Size / 4U)) && ((hcryp->Size % 16U) == 0U)) + { + /* Call Input transfer complete callback */ +#if (USE_DAL_CRYP_REGISTER_CALLBACKS == 1) + /*Call registered Input complete callback*/ + hcryp->InCpltCallback(hcryp); +#else + /*Call legacy weak Input complete callback*/ + DAL_CRYP_InCpltCallback(hcryp); +#endif /* USE_DAL_CRYP_REGISTER_CALLBACKS */ + } + } + else /* Last block of payload < 128bit*/ + { + /* Workaround not implemented, Size should be %4 otherwise Tag will be incorrectly + generated for GCM Encryption & CCM Decryption. Workaround is implemented in polling mode, so if last block of + payload <128bit don't use CRYP_Encrypt_IT otherwise TAG is incorrectly generated for GCM Encryption & CCM Decryption. */ + + /* Compute the number of padding bytes in last block of payload */ + npblb = ((((uint32_t)(hcryp->Size) / 16U) + 1U) * 16U) - (uint32_t)(hcryp->Size); + + /* Number of valid words (lastwordsize) in last block */ + if ((npblb % 4U) == 0U) + { + lastwordsize = (16U - npblb) / 4U; + } + else + { + lastwordsize = ((16U - npblb) / 4U) + 1U; + } + + /* Last block optionally pad the data with zeros*/ + for (loopcounter = 0U; loopcounter < lastwordsize; loopcounter++) + { + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount); + hcryp->CrypInCount++; + } + while (loopcounter < 4U) + { + /* pad the data with zeros to have a complete block */ + hcryp->Instance->DATAINR = 0x0U; + loopcounter++; + } + } +#endif /* AES */ + +} + + +/** + * @brief Sets the header phase in polling mode + * @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains + * the configuration information for CRYP module(Header & HeaderSize) + * @param Timeout: Timeout value + * @retval state + */ +static DAL_StatusTypeDef CRYP_GCMCCM_SetHeaderPhase(CRYP_HandleTypeDef *hcryp, uint32_t Timeout) +{ + uint32_t loopcounter; + uint32_t size_in_bytes; + uint32_t tmp; + uint32_t mask[12] = {0x0U, 0xFF000000U, 0xFFFF0000U, 0xFFFFFF00U, /* 32-bit data type */ + 0x0U, 0x0000FF00U, 0x0000FFFFU, 0xFF00FFFFU, /* 16-bit data type */ + 0x0U, 0x000000FFU, 0x0000FFFFU, 0x00FFFFFFU}; /* 8-bit data type */ + + /***************************** Header phase for GCM/GMAC or CCM *********************************/ + + if (hcryp->Init.HeaderWidthUnit == CRYP_HEADERWIDTHUNIT_WORD) + { + size_in_bytes = hcryp->Init.HeaderSize * 4U; + } + else + { + size_in_bytes = hcryp->Init.HeaderSize; + } + + if (size_in_bytes != 0U) + { + +#if defined(CRYP) + + /* Select header phase */ + CRYP_SET_PHASE(hcryp, CRYP_PHASE_HEADER); + + /* Enable the CRYP peripheral */ + __DAL_CRYP_ENABLE(hcryp); + + if ((size_in_bytes % 16U) == 0U) + { + /* HeaderSize %4, no padding */ + for (loopcounter = 0U; (loopcounter < (size_in_bytes / 4U)); loopcounter += 4U) + { + hcryp->Instance->DATAIN = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount); + hcryp->CrypHeaderCount++ ; + hcryp->Instance->DATAIN = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount); + hcryp->CrypHeaderCount++ ; + hcryp->Instance->DATAIN = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount); + hcryp->CrypHeaderCount++ ; + hcryp->Instance->DATAIN = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount); + hcryp->CrypHeaderCount++ ; + + /* Wait for IFEM to be raised */ + if (CRYP_WaitOnIFEMFlag(hcryp, Timeout) != DAL_OK) + { + /* Disable the CRYP peripheral clock */ + __DAL_CRYP_DISABLE(hcryp); + + /* Change state */ + hcryp->ErrorCode |= DAL_CRYP_ERROR_TIMEOUT; + hcryp->State = DAL_CRYP_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hcryp); + return DAL_ERROR; + } + } + } + else + { + /*Write header block in the IN FIFO without last block */ + for (loopcounter = 0U; (loopcounter < ((size_in_bytes / 16U) * 4U)); loopcounter += 4U) + { + hcryp->Instance->DATAIN = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount); + hcryp->CrypHeaderCount++ ; + hcryp->Instance->DATAIN = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount); + hcryp->CrypHeaderCount++ ; + hcryp->Instance->DATAIN = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount); + hcryp->CrypHeaderCount++ ; + hcryp->Instance->DATAIN = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount); + hcryp->CrypHeaderCount++ ; + + /* Wait for IFEM to be raised */ + if (CRYP_WaitOnIFEMFlag(hcryp, Timeout) != DAL_OK) + { + /* Disable the CRYP peripheral clock */ + __DAL_CRYP_DISABLE(hcryp); + + /* Change state */ + hcryp->ErrorCode |= DAL_CRYP_ERROR_TIMEOUT; + hcryp->State = DAL_CRYP_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hcryp); + return DAL_ERROR; + } + } + /* Last block optionally pad the data with zeros*/ + for (loopcounter = 0U; (loopcounter < ((size_in_bytes / 4U) % 4U)); loopcounter++) + { + hcryp->Instance->DATAIN = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount); + hcryp->CrypHeaderCount++ ; + } + /* If the header size is a multiple of words */ + if ((size_in_bytes % 4U) == 0U) + { + /* Pad the data with zeros to have a complete block */ + while (loopcounter < 4U) + { + hcryp->Instance->DATAIN = 0x0U; + loopcounter++; + } + } + else + { + /* Enter last bytes, padded with zeroes */ + tmp = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount); + tmp &= mask[(hcryp->Init.DataType * 2U) + (size_in_bytes % 4U)]; + hcryp->Instance->DATAIN = tmp; + loopcounter++; + /* Pad the data with zeros to have a complete block */ + while (loopcounter < 4U) + { + hcryp->Instance->DATAIN = 0x0U; + loopcounter++; + } + } + /* Wait for CCF IFEM to be raised */ + if (CRYP_WaitOnIFEMFlag(hcryp, Timeout) != DAL_OK) + { + /* Disable the CRYP peripheral clock */ + __DAL_CRYP_DISABLE(hcryp); + + /* Change state */ + hcryp->ErrorCode |= DAL_CRYP_ERROR_TIMEOUT; + hcryp->State = DAL_CRYP_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hcryp); + return DAL_ERROR; + } + } + /* Wait until the complete message has been processed */ + if (CRYP_WaitOnBUSYFlag(hcryp, Timeout) != DAL_OK) + { + /* Disable the CRYP peripheral clock */ + __DAL_CRYP_DISABLE(hcryp); + + /* Change state */ + hcryp->ErrorCode |= DAL_CRYP_ERROR_TIMEOUT; + hcryp->State = DAL_CRYP_STATE_READY; + + /* Process unlocked & return error */ + __DAL_UNLOCK(hcryp); + return DAL_ERROR; + } + +#else /* AES */ + + if (hcryp->Init.Algorithm == CRYP_AES_GCM_GMAC) + { + /* Workaround 1 :only AES before re-enabling the IP, datatype can be configured.*/ + MODIFY_REG(hcryp->Instance->CTRL, AES_CR_DATATYPE, hcryp->Init.DataType); + + /* Select header phase */ + CRYP_SET_PHASE(hcryp, CRYP_PHASE_HEADER); + + /* Enable the CRYP peripheral */ + __DAL_CRYP_ENABLE(hcryp); + + } + /* If size_in_bytes is a multiple of blocks (a multiple of four 32-bits words ) */ + if ((size_in_bytes % 16U) == 0U) + { + /* No padding */ + for (loopcounter = 0U; (loopcounter < (size_in_bytes / 4U)); loopcounter += 4U) + { + /* Write the input block in the data input register */ + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount); + hcryp->CrypHeaderCount++ ; + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount); + hcryp->CrypHeaderCount++ ; + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount); + hcryp->CrypHeaderCount++ ; + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount); + hcryp->CrypHeaderCount++ ; + + if (CRYP_WaitOnCCFlag(hcryp, Timeout) != DAL_OK) + { + /* Disable the CRYP peripheral clock */ + __DAL_CRYP_DISABLE(hcryp); + + /* Change state */ + hcryp->ErrorCode |= DAL_CRYP_ERROR_TIMEOUT; + hcryp->State = DAL_CRYP_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hcryp); + return DAL_ERROR; + } + /* Clear CCF flag */ + __DAL_CRYP_CLEAR_FLAG(hcryp, CRYP_CCF_CLEAR); + } + } + else + { + /*Write header block in the IN FIFO without last block */ + for (loopcounter = 0U; (loopcounter < ((size_in_bytes / 16U) * 4U)); loopcounter += 4U) + { + /* Write the input block in the data input register */ + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount); + hcryp->CrypHeaderCount++ ; + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount); + hcryp->CrypHeaderCount++ ; + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount); + hcryp->CrypHeaderCount++ ; + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount); + hcryp->CrypHeaderCount++ ; + + if (CRYP_WaitOnCCFlag(hcryp, Timeout) != DAL_OK) + { + /* Disable the CRYP peripheral clock */ + __DAL_CRYP_DISABLE(hcryp); + + /* Change state */ + hcryp->ErrorCode |= DAL_CRYP_ERROR_TIMEOUT; + hcryp->State = DAL_CRYP_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hcryp); + return DAL_ERROR; + } + /* Clear CCF flag */ + __DAL_CRYP_CLEAR_FLAG(hcryp, CRYP_CCF_CLEAR); + } + /* Write last complete words */ + for (loopcounter = 0U; (loopcounter < ((size_in_bytes / 4U) % 4U)); loopcounter++) + { + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount); + hcryp->CrypHeaderCount++ ; + } + /* If the header size is a multiple of words */ + if ((size_in_bytes % 4U) == 0U) + { + /* Pad the data with zeros to have a complete block */ + while (loopcounter < 4U) + { + hcryp->Instance->DATAINR = 0x0U; + loopcounter++; + } + } + else + { + /* Enter last bytes, padded with zeroes */ + tmp = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount); + tmp &= mask[(hcryp->Init.DataType * 2U) + (size_in_bytes % 4U)]; + hcryp->Instance->DATAINR = tmp; + loopcounter++; + /* Pad the data with zeros to have a complete block */ + while (loopcounter < 4U) + { + hcryp->Instance->DATAINR = 0x0U; + loopcounter++; + } + } + + if (CRYP_WaitOnCCFlag(hcryp, Timeout) != DAL_OK) + { + /* Disable the CRYP peripheral clock */ + __DAL_CRYP_DISABLE(hcryp); + + /* Change state */ + hcryp->ErrorCode |= DAL_CRYP_ERROR_TIMEOUT; + hcryp->State = DAL_CRYP_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hcryp); + return DAL_ERROR; + } + /* Clear CCF flag */ + __DAL_CRYP_CLEAR_FLAG(hcryp, CRYP_CCF_CLEAR); + } +#endif /* End AES or CRYP */ + } + else + { +#if defined(AES) + if (hcryp->Init.Algorithm == CRYP_AES_GCM_GMAC) + { + /*Workaround 1: only AES, before re-enabling the IP, datatype can be configured.*/ + MODIFY_REG(hcryp->Instance->CTRL, AES_CR_DATATYPE, hcryp->Init.DataType); + + /* Select header phase */ + CRYP_SET_PHASE(hcryp, CRYP_PHASE_HEADER); + + /* Enable the CRYP peripheral */ + __DAL_CRYP_ENABLE(hcryp); + } +#endif /* AES */ + } + /* Return function status */ + return DAL_OK; +} + +/** + * @brief Sets the header phase when using DMA in process + * @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains + * the configuration information for CRYP module(Header & HeaderSize) + * @retval None + */ +static DAL_StatusTypeDef CRYP_GCMCCM_SetHeaderPhase_DMA(CRYP_HandleTypeDef *hcryp) +{ + __IO uint32_t count = 0U; + uint32_t loopcounter; + uint32_t headersize_in_bytes; + uint32_t tmp; + uint32_t mask[12] = {0x0U, 0xFF000000U, 0xFFFF0000U, 0xFFFFFF00U, /* 32-bit data type */ + 0x0U, 0x0000FF00U, 0x0000FFFFU, 0xFF00FFFFU, /* 16-bit data type */ + 0x0U, 0x000000FFU, 0x0000FFFFU, 0x00FFFFFFU}; /* 8-bit data type */ + + /***************************** Header phase for GCM/GMAC or CCM *********************************/ + if (hcryp->Init.HeaderWidthUnit == CRYP_HEADERWIDTHUNIT_WORD) + { + headersize_in_bytes = hcryp->Init.HeaderSize * 4U; + } + else + { + headersize_in_bytes = hcryp->Init.HeaderSize; + } + + if (headersize_in_bytes != 0U) + { + +#if defined(CRYP) + + /* Select header phase */ + CRYP_SET_PHASE(hcryp, CRYP_PHASE_HEADER); + + /* Enable the CRYP peripheral */ + __DAL_CRYP_ENABLE(hcryp); + + if ((headersize_in_bytes % 16U) == 0U) + { + /* HeaderSize %4, no padding */ + for (loopcounter = 0U; (loopcounter < (headersize_in_bytes / 4U)); loopcounter += 4U) + { + hcryp->Instance->DATAIN = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount); + hcryp->CrypHeaderCount++ ; + hcryp->Instance->DATAIN = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount); + hcryp->CrypHeaderCount++ ; + hcryp->Instance->DATAIN = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount); + hcryp->CrypHeaderCount++ ; + hcryp->Instance->DATAIN = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount); + hcryp->CrypHeaderCount++ ; + + /* Wait for IFEM to be raised */ + count = CRYP_TIMEOUT_GCMCCMHEADERPHASE; + do + { + count-- ; + if (count == 0U) + { + /* Disable the CRYP peripheral clock */ + __DAL_CRYP_DISABLE(hcryp); + + /* Change state */ + hcryp->ErrorCode |= DAL_CRYP_ERROR_TIMEOUT; + hcryp->State = DAL_CRYP_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hcryp); + return DAL_ERROR; + } + } while (DAL_IS_BIT_CLR(hcryp->Instance->STS, CRYP_FLAG_IFEM)); + } + } + else + { + /*Write header block in the IN FIFO without last block */ + for (loopcounter = 0U; (loopcounter < ((headersize_in_bytes / 16U) * 4U)); loopcounter += 4U) + { + hcryp->Instance->DATAIN = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount); + hcryp->CrypHeaderCount++ ; + hcryp->Instance->DATAIN = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount); + hcryp->CrypHeaderCount++ ; + hcryp->Instance->DATAIN = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount); + hcryp->CrypHeaderCount++ ; + hcryp->Instance->DATAIN = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount); + hcryp->CrypHeaderCount++ ; + + /* Wait for IFEM to be raised */ + count = CRYP_TIMEOUT_GCMCCMHEADERPHASE; + do + { + count-- ; + if (count == 0U) + { + /* Disable the CRYP peripheral clock */ + __DAL_CRYP_DISABLE(hcryp); + + /* Change state */ + hcryp->ErrorCode |= DAL_CRYP_ERROR_TIMEOUT; + hcryp->State = DAL_CRYP_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hcryp); + return DAL_ERROR; + } + } while (DAL_IS_BIT_CLR(hcryp->Instance->STS, CRYP_FLAG_IFEM)); + } + /* Last block optionally pad the data with zeros*/ + for (loopcounter = 0U; (loopcounter < ((headersize_in_bytes / 4U) % 4U)); loopcounter++) + { + hcryp->Instance->DATAIN = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount); + hcryp->CrypHeaderCount++ ; + } + /* If the header size is a multiple of words */ + if ((headersize_in_bytes % 4U) == 0U) + { + /* Pad the data with zeros to have a complete block */ + while (loopcounter < 4U) + { + hcryp->Instance->DATAIN = 0x0U; + loopcounter++; + } + } + else + { + /* Enter last bytes, padded with zeroes */ + tmp = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount); + tmp &= mask[(hcryp->Init.DataType * 2U) + (headersize_in_bytes % 4U)]; + hcryp->Instance->DATAIN = tmp; + loopcounter++; + /* Pad the data with zeros to have a complete block */ + while (loopcounter < 4U) + { + hcryp->Instance->DATAIN = 0x0U; + loopcounter++; + } + } + /* Wait for IFEM to be raised */ + count = CRYP_TIMEOUT_GCMCCMHEADERPHASE; + do + { + count-- ; + if (count == 0U) + { + /* Disable the CRYP peripheral clock */ + __DAL_CRYP_DISABLE(hcryp); + + /* Change state */ + hcryp->ErrorCode |= DAL_CRYP_ERROR_TIMEOUT; + hcryp->State = DAL_CRYP_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hcryp); + return DAL_ERROR; + } + } while (DAL_IS_BIT_CLR(hcryp->Instance->STS, CRYP_FLAG_IFEM)); + } + /* Wait until the complete message has been processed */ + count = CRYP_TIMEOUT_GCMCCMHEADERPHASE; + do + { + count-- ; + if (count == 0U) + { + /* Disable the CRYP peripheral clock */ + __DAL_CRYP_DISABLE(hcryp); + + /* Change state */ + hcryp->ErrorCode |= DAL_CRYP_ERROR_TIMEOUT; + hcryp->State = DAL_CRYP_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hcryp); + return DAL_ERROR; + } + } while (DAL_IS_BIT_SET(hcryp->Instance->STS, CRYP_FLAG_BUSY)); + +#else /* AES */ + + if (hcryp->Init.Algorithm == CRYP_AES_GCM_GMAC) + { + /* Workaround 1: only AES, before re-enabling the IP, datatype can be configured.*/ + MODIFY_REG(hcryp->Instance->CTRL, AES_CR_DATATYPE, hcryp->Init.DataType); + + /* Select header phase */ + CRYP_SET_PHASE(hcryp, CRYP_PHASE_HEADER); + + /* Enable the CRYP peripheral */ + __DAL_CRYP_ENABLE(hcryp); + } + if ((headersize_in_bytes % 16U) == 0U) + { + /* HeaderSize %4, no padding */ + for (loopcounter = 0U; (loopcounter < (headersize_in_bytes / 4U)); loopcounter += 4U) + { + /* Write the input block in the data input register */ + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount); + hcryp->CrypHeaderCount++ ; + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount); + hcryp->CrypHeaderCount++ ; + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount); + hcryp->CrypHeaderCount++ ; + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount); + hcryp->CrypHeaderCount++ ; + + /*Wait on CCF flag*/ + count = CRYP_TIMEOUT_GCMCCMHEADERPHASE; + do + { + count-- ; + if (count == 0U) + { + /* Disable the CRYP peripheral clock */ + __DAL_CRYP_DISABLE(hcryp); + + /* Change state */ + hcryp->ErrorCode |= DAL_CRYP_ERROR_TIMEOUT; + hcryp->State = DAL_CRYP_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hcryp); + return DAL_ERROR; + } + } while (DAL_IS_BIT_CLR(hcryp->Instance->STS, AES_SR_CCF)); + + /* Clear CCF flag */ + __DAL_CRYP_CLEAR_FLAG(hcryp, CRYP_CCF_CLEAR); + } + } + else + { + /*Write header block in the IN FIFO without last block */ + for (loopcounter = 0U; (loopcounter < ((headersize_in_bytes / 16U) * 4U)); loopcounter += 4U) + { + /* Write the Input block in the Data Input register */ + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount); + hcryp->CrypHeaderCount++ ; + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount); + hcryp->CrypHeaderCount++ ; + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount); + hcryp->CrypHeaderCount++ ; + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount); + hcryp->CrypHeaderCount++ ; + + /*Wait on CCF flag*/ + count = CRYP_TIMEOUT_GCMCCMHEADERPHASE; + do + { + count-- ; + if (count == 0U) + { + /* Disable the CRYP peripheral clock */ + __DAL_CRYP_DISABLE(hcryp); + + /* Change state */ + hcryp->ErrorCode |= DAL_CRYP_ERROR_TIMEOUT; + hcryp->State = DAL_CRYP_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hcryp); + return DAL_ERROR; + } + } while (DAL_IS_BIT_CLR(hcryp->Instance->STS, AES_SR_CCF)); + + /* Clear CCF flag */ + __DAL_CRYP_CLEAR_FLAG(hcryp, CRYP_CCF_CLEAR); + } + /* Last block optionally pad the data with zeros*/ + for (loopcounter = 0U; (loopcounter < ((headersize_in_bytes /4U) % 4U)); loopcounter++) + { + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount); + hcryp->CrypHeaderCount++ ; + } + /* If the header size is a multiple of words */ + if ((headersize_in_bytes % 4U) == 0U) + { + /* Pad the data with zeros to have a complete block */ + while (loopcounter < 4U) + { + hcryp->Instance->DATAINR = 0x0U; + loopcounter++; + } + } + else + { + /* Enter last bytes, padded with zeroes */ + tmp = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount); + tmp &= mask[(hcryp->Init.DataType * 2U) + (headersize_in_bytes % 4U)]; + hcryp->Instance->DATAINR = tmp; + loopcounter++; + /* Pad the data with zeros to have a complete block */ + while (loopcounter < 4U) + { + hcryp->Instance->DATAINR = 0x0U; + loopcounter++; + } + } + /*Wait on CCF flag*/ + count = CRYP_TIMEOUT_GCMCCMHEADERPHASE; + do + { + count-- ; + if (count == 0U) + { + /* Disable the CRYP peripheral clock */ + __DAL_CRYP_DISABLE(hcryp); + + /* Change state */ + hcryp->ErrorCode |= DAL_CRYP_ERROR_TIMEOUT; + hcryp->State = DAL_CRYP_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hcryp); + return DAL_ERROR; + } + } while (DAL_IS_BIT_CLR(hcryp->Instance->STS, AES_SR_CCF)); + + /* Clear CCF flag */ + __DAL_CRYP_CLEAR_FLAG(hcryp, CRYP_CCF_CLEAR); + } +#endif /* End AES or CRYP */ + } + else + { +#if defined(AES) + if (hcryp->Init.Algorithm == CRYP_AES_GCM_GMAC) + { + /*Workaround 1: only AES, before re-enabling the IP, datatype can be configured.*/ + MODIFY_REG(hcryp->Instance->CTRL, AES_CR_DATATYPE, hcryp->Init.DataType); + + /* Select header phase */ + CRYP_SET_PHASE(hcryp, CRYP_PHASE_HEADER); + + /* Enable the CRYP peripheral */ + __DAL_CRYP_ENABLE(hcryp); + } +#endif /* AES */ + } + /* Return function status */ + return DAL_OK; +} + +/** + * @brief Sets the header phase in interrupt mode + * @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains + * the configuration information for CRYP module(Header & HeaderSize) + * @retval None + */ +static void CRYP_GCMCCM_SetHeaderPhase_IT(CRYP_HandleTypeDef *hcryp) +{ + uint32_t loopcounter; +#if defined(AES) + uint32_t lastwordsize; + uint32_t npblb; +#endif + uint32_t headersize_in_bytes; + uint32_t tmp; + uint32_t mask[12] = {0x0U, 0xFF000000U, 0xFFFF0000U, 0xFFFFFF00U, /* 32-bit data type */ + 0x0U, 0x0000FF00U, 0x0000FFFFU, 0xFF00FFFFU, /* 16-bit data type */ + 0x0U, 0x000000FFU, 0x0000FFFFU, 0x00FFFFFFU}; /* 8-bit data type */ + + if (hcryp->Init.HeaderWidthUnit == CRYP_HEADERWIDTHUNIT_WORD) + { + headersize_in_bytes = hcryp->Init.HeaderSize * 4U; + } + else + { + headersize_in_bytes = hcryp->Init.HeaderSize; + } + + /***************************** Header phase *********************************/ + +#if defined(CRYP) + if (headersize_in_bytes <= ((uint32_t)(hcryp->CrypHeaderCount) * 4U)) + { + /* Disable interrupts */ + __DAL_CRYP_DISABLE_IT(hcryp, CRYP_IT_INI); + + /* Disable the CRYP peripheral */ + __DAL_CRYP_DISABLE(hcryp); + + /* Set the phase */ + hcryp->Phase = CRYP_PHASE_PROCESS; + + /* Select payload phase once the header phase is performed */ + CRYP_SET_PHASE(hcryp, CRYP_PHASE_PAYLOAD); + + /* Enable Interrupts */ + __DAL_CRYP_ENABLE_IT(hcryp, CRYP_IT_INI | CRYP_IT_OUTI); + + /* Enable the CRYP peripheral */ + __DAL_CRYP_ENABLE(hcryp); + } + else if (((headersize_in_bytes / 4U) - (hcryp->CrypHeaderCount)) >= 4U) + + { + /* HeaderSize %4, no padding */ + hcryp->Instance->DATAIN = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount); + hcryp->CrypHeaderCount++ ; + hcryp->Instance->DATAIN = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount); + hcryp->CrypHeaderCount++ ; + hcryp->Instance->DATAIN = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount); + hcryp->CrypHeaderCount++ ; + hcryp->Instance->DATAIN = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount); + hcryp->CrypHeaderCount++ ; + } + else + { + /* Last block optionally pad the data with zeros*/ + for (loopcounter = 0U; loopcounter < ((headersize_in_bytes / 4U) % 4U); loopcounter++) + { + hcryp->Instance->DATAIN = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount); + hcryp->CrypHeaderCount++ ; + } + if ((headersize_in_bytes % 4U) == 0U) + { + /* Pad the data with zeros to have a complete block */ + while (loopcounter < 4U) + { + hcryp->Instance->DATAIN = 0x0U; + loopcounter++; + hcryp->CrypHeaderCount++; + } + } + else + { + /* Enter last bytes, padded with zeros */ + tmp = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount); + tmp &= mask[(hcryp->Init.DataType * 2U) + (headersize_in_bytes % 4U)]; + hcryp->Instance->DATAIN = tmp; + loopcounter++; + hcryp->CrypHeaderCount++; + /* Pad the data with zeros to have a complete block */ + while (loopcounter < 4U) + { + hcryp->Instance->DATAIN = 0x0U; + loopcounter++; + hcryp->CrypHeaderCount++; + } + } + } +#else /* AES */ + + if (headersize_in_bytes <= ((uint32_t)(hcryp->CrypHeaderCount) * 4U)) + { + /* Set the phase */ + hcryp->Phase = CRYP_PHASE_PROCESS; + + /* Payload phase not supported in CCM AES2 */ + if (hcryp->Init.Algorithm == CRYP_AES_GCM_GMAC) + { + /* Select payload phase once the header phase is performed */ + MODIFY_REG(hcryp->Instance->CTRL, AES_CR_GCMPH, CRYP_PHASE_PAYLOAD); + } + if (hcryp->Init.Algorithm == CRYP_AES_CCM) + { + /* Increment CrypHeaderCount to pass in CRYP_GCMCCM_SetPayloadPhase_IT */ + hcryp->CrypHeaderCount++; + } + /* Write the payload Input block in the IN FIFO */ + if (hcryp->Size == 0U) + { + /* Disable interrupts */ + __DAL_CRYP_DISABLE_IT(hcryp, CRYP_IT_CCFIE | CRYP_IT_ERRIE); + + /* Change the CRYP state */ + hcryp->State = DAL_CRYP_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hcryp); + } + else if (hcryp->Size >= 16U) + { + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount); + hcryp->CrypInCount++; + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount); + hcryp->CrypInCount++; + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount); + hcryp->CrypInCount++; + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount); + hcryp->CrypInCount++; + + if ((hcryp->CrypInCount == (hcryp->Size / 4U)) && ((hcryp->Size % 16U) == 0U)) + { + /* Call the input data transfer complete callback */ +#if (USE_DAL_CRYP_REGISTER_CALLBACKS == 1) + /*Call registered Input complete callback*/ + hcryp->InCpltCallback(hcryp); +#else + /*Call legacy weak Input complete callback*/ + DAL_CRYP_InCpltCallback(hcryp); +#endif /* USE_DAL_CRYP_REGISTER_CALLBACKS */ + } + } + else /* Size < 4 words : first block is the last block*/ + { + /* Workaround not implemented, Size should be %4 otherwise Tag will be incorrectly + generated for GCM Encryption. Workaround is implemented in polling mode, so if last block of + payload <128bit don't use CRYP_Encrypt_IT otherwise TAG is incorrectly generated for GCM Encryption. */ + + /* Compute the number of padding bytes in last block of payload */ + npblb = ((((uint32_t)(hcryp->Size) / 16U) + 1U) * 16U) - (uint32_t)(hcryp->Size); + + /* Number of valid words (lastwordsize) in last block */ + if ((npblb % 4U) == 0U) + { + lastwordsize = (16U - npblb) / 4U; + } + else + { + lastwordsize = ((16U - npblb) / 4U) + 1U; + } + + /* Last block optionally pad the data with zeros*/ + for (loopcounter = 0U; loopcounter < lastwordsize; loopcounter++) + { + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount); + hcryp->CrypInCount++; + } + while (loopcounter < 4U) + { + /* Pad the data with zeros to have a complete block */ + hcryp->Instance->DATAINR = 0x0U; + loopcounter++; + } + } + } + else if (((headersize_in_bytes / 4U) - (hcryp->CrypHeaderCount)) >= 4U) + { + /* Write the input block in the IN FIFO */ + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount); + hcryp->CrypHeaderCount++; + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount); + hcryp->CrypHeaderCount++; + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount); + hcryp->CrypHeaderCount++; + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount); + hcryp->CrypHeaderCount++; + } + else /*HeaderSize < 4 or HeaderSize >4 & HeaderSize %4 != 0*/ + { + /* Last block optionally pad the data with zeros*/ + for (loopcounter = 0U; loopcounter < ((headersize_in_bytes / 4U) % 4U); loopcounter++) + { + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount); + hcryp->CrypHeaderCount++ ; + } + /* If the header size is a multiple of words */ + if ((headersize_in_bytes % 4U) == 0U) + { + /* Pad the data with zeros to have a complete block */ + while (loopcounter < 4U) + { + hcryp->Instance->DATAINR = 0x0U; + loopcounter++; + hcryp->CrypHeaderCount++; + } + } + else + { + /* Enter last bytes, padded with zeros */ + tmp = *(uint32_t *)(hcryp->Init.Header + hcryp->CrypHeaderCount); + tmp &= mask[(hcryp->Init.DataType * 2U) + (headersize_in_bytes % 4U)]; + hcryp->Instance->DATAINR = tmp; + loopcounter++; + hcryp->CrypHeaderCount++; + /* Pad the data with zeros to have a complete block */ + while (loopcounter < 4U) + { + hcryp->Instance->DATAINR = 0x0U; + loopcounter++; + hcryp->CrypHeaderCount++; + } + } + } +#endif /* End AES or CRYP */ +} + + +/** + * @brief Workaround used for GCM/CCM mode. + * @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains + * the configuration information for CRYP module + * @param Timeout: specify Timeout value + * @retval None + */ +static void CRYP_Workaround(CRYP_HandleTypeDef *hcryp, uint32_t Timeout) +{ + uint32_t lastwordsize; + uint32_t npblb; +#if defined(CRYP) + uint32_t iv1temp; + uint32_t temp[4] = {0}; + uint32_t temp2[4] = {0}; +#endif /* CRYP */ + uint32_t intermediate_data[4] = {0}; + uint32_t index; + + /* Compute the number of padding bytes in last block of payload */ + npblb = ((((uint32_t)(hcryp->Size) / 16U) + 1U) * 16U) - (uint32_t)(hcryp->Size); + + /* Number of valid words (lastwordsize) in last block */ + if ((npblb % 4U) == 0U) + { + lastwordsize = (16U - npblb) / 4U; + } + else + { + lastwordsize = ((16U - npblb) / 4U) + 1U; + } + +#if defined(CRYP) + + /* Workaround 2, case GCM encryption */ + if (hcryp->Init.Algorithm == CRYP_AES_GCM) + { + if ((hcryp->Instance->CTRL & CRYP_CTRL_ALGODIRSEL) == CRYP_OPERATINGMODE_ENCRYPT) + { + /*Workaround in order to properly compute authentication tags while doing + a GCM encryption with the last block of payload size inferior to 128 bits*/ + /* Disable CRYP to start the final phase */ + __DAL_CRYP_DISABLE(hcryp); + + /*Update CRYP_IV1R register and ALGOMODE*/ + hcryp->Instance->IV1R = ((hcryp->Instance->CSGCMCCM7R) - 1U); + MODIFY_REG(hcryp->Instance->CTRL, CRYP_CTRL_ALGOMSEL, CRYP_AES_CTR); + + /* Enable CRYP to start the final phase */ + __DAL_CRYP_ENABLE(hcryp); + } + /* Last block optionally pad the data with zeros*/ + for (index = 0; index < lastwordsize; index ++) + { + /* Write the last input block in the IN FIFO */ + hcryp->Instance->DATAIN = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount); + hcryp->CrypInCount++; + } + while (index < 4U) + { + /* Pad the data with zeros to have a complete block */ + hcryp->Instance->DATAIN = 0U; + index++; + } + /* Wait for OFNE flag to be raised */ + if (CRYP_WaitOnOFNEFlag(hcryp, Timeout) != DAL_OK) + { + /* Disable the CRYP peripheral clock */ + __DAL_CRYP_DISABLE(hcryp); + + /* Change state */ + hcryp->ErrorCode |= DAL_CRYP_ERROR_TIMEOUT; + hcryp->State = DAL_CRYP_STATE_READY; + + /* Process Unlocked */ + __DAL_UNLOCK(hcryp); +#if (USE_DAL_CRYP_REGISTER_CALLBACKS == 1) + /*Call registered error callback*/ + hcryp->ErrorCallback(hcryp); +#else + /*Call legacy weak error callback*/ + DAL_CRYP_ErrorCallback(hcryp); +#endif /* USE_DAL_CRYP_REGISTER_CALLBACKS */ + } + if ((hcryp->Instance->STS & CRYP_FLAG_OFNE) != 0x0U) + { + for (index = 0U; index < 4U; index++) + { + /* Read the output block from the output FIFO */ + intermediate_data[index] = hcryp->Instance->DATAOUT; + + /* Intermediate data buffer to be used in for the workaround*/ + *(uint32_t *)(hcryp->pCrypOutBuffPtr + (hcryp->CrypOutCount)) = intermediate_data[index]; + hcryp->CrypOutCount++; + } + } + + if ((hcryp->Instance->CTRL & CRYP_CTRL_ALGODIRSEL) == CRYP_OPERATINGMODE_ENCRYPT) + { + /*workaround in order to properly compute authentication tags while doing + a GCM encryption with the last block of payload size inferior to 128 bits*/ + /* Change the AES mode to GCM mode and Select Final phase */ + /* configured CHMOD GCM */ + MODIFY_REG(hcryp->Instance->CTRL, CRYP_CTRL_ALGOMSEL, CRYP_AES_GCM); + + /* configured final phase */ + MODIFY_REG(hcryp->Instance->CTRL, CRYP_CTRL_GCM_CCMPH, CRYP_PHASE_FINAL); + + if ((hcryp->Instance->CTRL & CRYP_CTRL_DTSEL) == CRYP_DATATYPE_32B) + { + if ((npblb % 4U) == 1U) + { + intermediate_data[lastwordsize - 1U] &= 0xFFFFFF00U; + } + if ((npblb % 4U) == 2U) + { + intermediate_data[lastwordsize - 1U] &= 0xFFFF0000U; + } + if ((npblb % 4U) == 3U) + { + intermediate_data[lastwordsize - 1U] &= 0xFF000000U; + } + } + else if ((hcryp->Instance->CTRL & CRYP_CTRL_DTSEL) == CRYP_DATATYPE_8B) + { + if ((npblb % 4U) == 1U) + { + intermediate_data[lastwordsize - 1U] &= __REV(0xFFFFFF00U); + } + if ((npblb % 4U) == 2U) + { + intermediate_data[lastwordsize - 1U] &= __REV(0xFFFF0000U); + } + if ((npblb % 4U) == 3U) + { + intermediate_data[lastwordsize - 1U] &= __REV(0xFF000000U); + } + } + else if ((hcryp->Instance->CTRL & CRYP_CTRL_DTSEL) == CRYP_DATATYPE_16B) + { + if ((npblb % 4U) == 1U) + { + intermediate_data[lastwordsize - 1U] &= __ROR((0xFFFFFF00U), 16); + } + if ((npblb % 4U) == 2U) + { + intermediate_data[lastwordsize - 1U] &= __ROR((0xFFFF0000U), 16); + } + if ((npblb % 4U) == 3U) + { + intermediate_data[lastwordsize - 1U] &= __ROR((0xFF000000U), 16); + } + } + else /*CRYP_DATATYPE_1B*/ + { + if ((npblb % 4U) == 1U) + { + intermediate_data[lastwordsize - 1U] &= __RBIT(0xFFFFFF00U); + } + if ((npblb % 4U) == 2U) + { + intermediate_data[lastwordsize - 1U] &= __RBIT(0xFFFF0000U); + } + if ((npblb % 4U) == 3U) + { + intermediate_data[lastwordsize - 1U] &= __RBIT(0xFF000000U); + } + } + for (index = 0U; index < lastwordsize; index ++) + { + /*Write the intermediate_data in the IN FIFO */ + hcryp->Instance->DATAIN = intermediate_data[index]; + } + while (index < 4U) + { + /* Pad the data with zeros to have a complete block */ + hcryp->Instance->DATAIN = 0x0U; + index++; + } + /* Wait for OFNE flag to be raised */ + if (CRYP_WaitOnOFNEFlag(hcryp, Timeout) != DAL_OK) + { + /* Disable the CRYP peripheral clock */ + __DAL_CRYP_DISABLE(hcryp); + + /* Change state */ + hcryp->ErrorCode |= DAL_CRYP_ERROR_TIMEOUT; + hcryp->State = DAL_CRYP_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hcryp); +#if (USE_DAL_CRYP_REGISTER_CALLBACKS == 1) + /*Call registered error callback*/ + hcryp->ErrorCallback(hcryp); +#else + /*Call legacy weak error callback*/ + DAL_CRYP_ErrorCallback(hcryp); +#endif /* USE_DAL_CRYP_REGISTER_CALLBACKS */ + } + + if ((hcryp->Instance->STS & CRYP_FLAG_OFNE) != 0x0U) + { + for (index = 0U; index < 4U; index++) + { + intermediate_data[index] = hcryp->Instance->DATAOUT; + } + } + } + } /* End of GCM encryption */ + else + { + /* Workaround 2, case CCM decryption, in order to properly compute + authentication tags while doing a CCM decryption with the last block + of payload size inferior to 128 bits*/ + + if ((hcryp->Instance->CTRL & CRYP_CTRL_ALGODIRSEL) == CRYP_OPERATINGMODE_DECRYPT) + { + iv1temp = hcryp->Instance->CSGCMCCM7R; + + /* Disable CRYP to start the final phase */ + __DAL_CRYP_DISABLE(hcryp); + + temp[0] = hcryp->Instance->CSGCMCCM0R; + temp[1] = hcryp->Instance->CSGCMCCM1R; + temp[2] = hcryp->Instance->CSGCMCCM2R; + temp[3] = hcryp->Instance->CSGCMCCM3R; + + hcryp->Instance->IV1R = iv1temp; + + /* Configured CHMOD CTR */ + MODIFY_REG(hcryp->Instance->CTRL, CRYP_CTRL_ALGOMSEL, CRYP_AES_CTR); + + /* Enable CRYP to start the final phase */ + __DAL_CRYP_ENABLE(hcryp); + } + /* Last block optionally pad the data with zeros*/ + for (index = 0; index < lastwordsize; index ++) + { + /* Write the last Input block in the IN FIFO */ + hcryp->Instance->DATAIN = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount); + hcryp->CrypInCount++; + } + while (index < 4U) + { + /* Pad the data with zeros to have a complete block */ + hcryp->Instance->DATAIN = 0U; + index++; + } + /* Wait for OFNE flag to be raised */ + if (CRYP_WaitOnOFNEFlag(hcryp, Timeout) != DAL_OK) + { + /* Disable the CRYP peripheral clock */ + __DAL_CRYP_DISABLE(hcryp); + + /* Change state */ + hcryp->ErrorCode |= DAL_CRYP_ERROR_TIMEOUT; + hcryp->State = DAL_CRYP_STATE_READY; + + /* Process Unlocked */ + __DAL_UNLOCK(hcryp); +#if (USE_DAL_CRYP_REGISTER_CALLBACKS == 1U) + /*Call registered error callback*/ + hcryp->ErrorCallback(hcryp); +#else + /*Call legacy weak error callback*/ + DAL_CRYP_ErrorCallback(hcryp); +#endif /* USE_DAL_CRYP_REGISTER_CALLBACKS */ + } + + if ((hcryp->Instance->STS & CRYP_FLAG_OFNE) != 0x0U) + { + for (index = 0U; index < 4U; index++) + { + /* Read the Output block from the Output FIFO */ + intermediate_data[index] = hcryp->Instance->DATAOUT; + + /*intermediate data buffer to be used in for the workaround*/ + *(uint32_t *)(hcryp->pCrypOutBuffPtr + (hcryp->CrypOutCount)) = intermediate_data[index]; + hcryp->CrypOutCount++; + } + } + + if ((hcryp->Instance->CTRL & CRYP_CTRL_ALGODIRSEL) == CRYP_OPERATINGMODE_DECRYPT) + { + temp2[0] = hcryp->Instance->CSGCMCCM0R; + temp2[1] = hcryp->Instance->CSGCMCCM1R; + temp2[2] = hcryp->Instance->CSGCMCCM2R; + temp2[3] = hcryp->Instance->CSGCMCCM3R; + + /* configured CHMOD CCM */ + MODIFY_REG(hcryp->Instance->CTRL, CRYP_CTRL_ALGOMSEL, CRYP_AES_CCM); + + /* configured Header phase */ + MODIFY_REG(hcryp->Instance->CTRL, CRYP_CTRL_GCM_CCMPH, CRYP_PHASE_HEADER); + + /*set to zero the bits corresponding to the padded bits*/ + for (index = lastwordsize; index < 4U; index ++) + { + intermediate_data[index] = 0U; + } + if ((npblb % 4U) == 1U) + { + intermediate_data[lastwordsize - 1U] &= 0xFFFFFF00U; + } + if ((npblb % 4U) == 2U) + { + intermediate_data[lastwordsize - 1U] &= 0xFFFF0000U; + } + if ((npblb % 4U) == 3U) + { + intermediate_data[lastwordsize - 1U] &= 0xFF000000U; + } + for (index = 0U; index < 4U ; index ++) + { + intermediate_data[index] ^= temp[index]; + intermediate_data[index] ^= temp2[index]; + } + for (index = 0U; index < 4U; index ++) + { + /* Write the last Input block in the IN FIFO */ + hcryp->Instance->DATAIN = intermediate_data[index] ; + } + + /* Wait for BUSY flag to be raised */ + if (CRYP_WaitOnBUSYFlag(hcryp, Timeout) != DAL_OK) + { + /* Disable the CRYP peripheral clock */ + __DAL_CRYP_DISABLE(hcryp); + + /* Change state */ + hcryp->ErrorCode |= DAL_CRYP_ERROR_TIMEOUT; + hcryp->State = DAL_CRYP_STATE_READY; + + /* Process Unlocked */ + __DAL_UNLOCK(hcryp); +#if (USE_DAL_CRYP_REGISTER_CALLBACKS == 1U) + /*Call registered error callback*/ + hcryp->ErrorCallback(hcryp); +#else + /*Call legacy weak error callback*/ + DAL_CRYP_ErrorCallback(hcryp); +#endif /* USE_DAL_CRYP_REGISTER_CALLBACKS */ + } + } + } /* End of CCM WKA*/ + + /* Process Unlocked */ + __DAL_UNLOCK(hcryp); + +#else /* AES */ + + /*Workaround 2: case GCM encryption, during payload phase and before inserting + the last block of paylaod, which size is inferior to 128 bits */ + + if ((hcryp->Instance->CTRL & AES_CR_MODE) == CRYP_OPERATINGMODE_ENCRYPT) + { + /* configured CHMOD CTR */ + MODIFY_REG(hcryp->Instance->CTRL, AES_CR_CHMOD, CRYP_AES_CTR); + } + /* last block optionally pad the data with zeros*/ + for (index = 0U; index < lastwordsize; index ++) + { + /* Write the last Input block in the IN FIFO */ + hcryp->Instance->DATAINR = *(uint32_t *)(hcryp->pCrypInBuffPtr + hcryp->CrypInCount); + hcryp->CrypInCount++; + } + while (index < 4U) + { + /* pad the data with zeros to have a complete block */ + hcryp->Instance->DATAINR = 0U; + index++; + } + /* Wait for CCF flag to be raised */ + if (CRYP_WaitOnCCFlag(hcryp, Timeout) != DAL_OK) + { + hcryp->State = DAL_CRYP_STATE_READY; + __DAL_UNLOCK(hcryp); +#if (USE_DAL_CRYP_REGISTER_CALLBACKS == 1U) + /*Call registered error callback*/ + hcryp->ErrorCallback(hcryp); +#else + /*Call legacy weak error callback*/ + DAL_CRYP_ErrorCallback(hcryp); +#endif /* USE_DAL_CRYP_REGISTER_CALLBACKS */ + } + + /* Clear CCF Flag */ + __DAL_CRYP_CLEAR_FLAG(hcryp, CRYP_CCF_CLEAR); + + for (index = 0U; index < 4U; index++) + { + /* Read the Output block from the Output FIFO */ + intermediate_data[index] = hcryp->Instance->DATAOUTR; + + /*intermediate data buffer to be used in the workaround*/ + *(uint32_t *)(hcryp->pCrypOutBuffPtr + (hcryp->CrypOutCount)) = intermediate_data[index]; + hcryp->CrypOutCount++; + } + + if ((hcryp->Instance->CTRL & AES_CR_MODE) == CRYP_OPERATINGMODE_ENCRYPT) + { + /* configured CHMOD GCM */ + MODIFY_REG(hcryp->Instance->CTRL, AES_CR_CHMOD, CRYP_AES_GCM_GMAC); + + /* Select final phase */ + MODIFY_REG(hcryp->Instance->CTRL, AES_CR_GCMPH, CRYP_PHASE_FINAL); + + if ((hcryp->Instance->CTRL & AES_CR_DATATYPE) == CRYP_DATATYPE_32B) + { + if ((npblb % 4U) == 1U) + { + intermediate_data[lastwordsize - 1U] &= 0xFFFFFF00U; + } + if ((npblb % 4U) == 2U) + { + intermediate_data[lastwordsize - 1U] &= 0xFFFF0000U; + } + if ((npblb % 4U) == 3U) + { + intermediate_data[lastwordsize - 1U] &= 0xFF000000U; + } + } + else if ((hcryp->Instance->CTRL & AES_CR_DATATYPE) == CRYP_DATATYPE_8B) + { + if ((npblb % 4U) == 1U) + { + intermediate_data[lastwordsize - 1U] &= __REV(0xFFFFFF00U); + } + if ((npblb % 4U) == 2U) + { + intermediate_data[lastwordsize - 1U] &= __REV(0xFFFF0000U); + } + if ((npblb % 4U) == 3U) + { + intermediate_data[lastwordsize - 1U] &= __REV(0xFF000000U); + } + } + else if ((hcryp->Instance->CTRL & AES_CR_DATATYPE) == CRYP_DATATYPE_16B) + { + if ((npblb % 4U) == 1U) + { + intermediate_data[lastwordsize - 1U] &= __ROR((0xFFFFFF00U), 16); + } + if ((npblb % 4U) == 2U) + { + intermediate_data[lastwordsize - 1U] &= __ROR((0xFFFF0000U), 16); + } + if ((npblb % 4U) == 3U) + { + intermediate_data[lastwordsize - 1U] &= __ROR((0xFF000000U), 16); + } + } + else /*CRYP_DATATYPE_1B*/ + { + if ((npblb % 4U) == 1U) + { + intermediate_data[lastwordsize - 1U] &= __RBIT(0xFFFFFF00U); + } + if ((npblb % 4U) == 2U) + { + intermediate_data[lastwordsize - 1U] &= __RBIT(0xFFFF0000U); + } + if ((npblb % 4U) == 3U) + { + intermediate_data[lastwordsize - 1U] &= __RBIT(0xFF000000U); + } + } + + /*Write the intermediate_data in the IN FIFO */ + for (index = 0U; index < lastwordsize; index ++) + { + hcryp->Instance->DATAINR = intermediate_data[index]; + } + while (index < 4U) + { + /* pad the data with zeros to have a complete block */ + hcryp->Instance->DATAINR = 0U; + index++; + } + /* Wait for CCF flag to be raised */ + if (CRYP_WaitOnCCFlag(hcryp, Timeout) != DAL_OK) + { + /* Disable the CRYP peripheral clock */ + __DAL_CRYP_DISABLE(hcryp); + + /* Change state */ + hcryp->ErrorCode |= DAL_CRYP_ERROR_TIMEOUT; + hcryp->State = DAL_CRYP_STATE_READY; + + /* Process Unlocked */ + __DAL_UNLOCK(hcryp); +#if (USE_DAL_CRYP_REGISTER_CALLBACKS == 1U) + /*Call registered error callback*/ + hcryp->ErrorCallback(hcryp); +#else + /*Call legacy weak error callback*/ + DAL_CRYP_ErrorCallback(hcryp); +#endif /* USE_DAL_CRYP_REGISTER_CALLBACKS */ + } + /* Clear CCF Flag */ + __DAL_CRYP_CLEAR_FLAG(hcryp, CRYP_CCF_CLEAR); + + for (index = 0U; index < 4U; index++) + { + intermediate_data[index] = hcryp->Instance->DATAOUTR; + } + }/*End of Workaround 2*/ +#endif /* End AES or CRYP */ +} +#endif /* AES or GCM CCM defined*/ +#if defined (CRYP) +#if defined (CRYP_CTRL_ALGOMSEL_AES_GCM) +/** + * @brief Handle CRYP hardware block Timeout when waiting for IFEM flag to be raised. + * @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains + * the configuration information for CRYP module. + * @param Timeout: Timeout duration. + * @retval DAL status + */ +static DAL_StatusTypeDef CRYP_WaitOnIFEMFlag(CRYP_HandleTypeDef *hcryp, uint32_t Timeout) +{ + uint32_t tickstart; + + /* Get timeout */ + tickstart = DAL_GetTick(); + + while (DAL_IS_BIT_CLR(hcryp->Instance->STS, CRYP_FLAG_IFEM)) + { + /* Check for the Timeout */ + if (Timeout != DAL_MAX_DELAY) + { + if (((DAL_GetTick() - tickstart) > Timeout) || (Timeout == 0U)) + { + return DAL_ERROR; + } + } + } + return DAL_OK; +} +#endif /* GCM CCM defined*/ +/** + * @brief Handle CRYP hardware block Timeout when waiting for BUSY flag to be raised. + * @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains + * the configuration information for CRYP module. + * @param Timeout: Timeout duration. + * @retval DAL status + */ +static DAL_StatusTypeDef CRYP_WaitOnBUSYFlag(CRYP_HandleTypeDef *hcryp, uint32_t Timeout) +{ + uint32_t tickstart; + + /* Get timeout */ + tickstart = DAL_GetTick(); + + while (DAL_IS_BIT_SET(hcryp->Instance->STS, CRYP_FLAG_BUSY)) + { + /* Check for the Timeout */ + if (Timeout != DAL_MAX_DELAY) + { + if (((DAL_GetTick() - tickstart) > Timeout) || (Timeout == 0U)) + { + return DAL_ERROR; + } + } + } + return DAL_OK; +} + + +/** + * @brief Handle CRYP hardware block Timeout when waiting for OFNE flag to be raised. + * @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains + * the configuration information for CRYP module. + * @param Timeout: Timeout duration. + * @retval DAL status + */ +static DAL_StatusTypeDef CRYP_WaitOnOFNEFlag(CRYP_HandleTypeDef *hcryp, uint32_t Timeout) +{ + uint32_t tickstart; + + /* Get timeout */ + tickstart = DAL_GetTick(); + + while (DAL_IS_BIT_CLR(hcryp->Instance->STS, CRYP_FLAG_OFNE)) + { + /* Check for the Timeout */ + if (Timeout != DAL_MAX_DELAY) + { + if (((DAL_GetTick() - tickstart) > Timeout) || (Timeout == 0U)) + { + return DAL_ERROR; + } + } + } + return DAL_OK; +} + +#else /* AES */ + +/** + * @brief Handle CRYP hardware block Timeout when waiting for CCF flag to be raised. + * @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains + * the configuration information for CRYP module. + * @param Timeout: Timeout duration. + * @retval DAL status + */ +static DAL_StatusTypeDef CRYP_WaitOnCCFlag(CRYP_HandleTypeDef *hcryp, uint32_t Timeout) +{ + uint32_t tickstart; + + /* Get timeout */ + tickstart = DAL_GetTick(); + + while (DAL_IS_BIT_CLR(hcryp->Instance->STS, AES_SR_CCF)) + { + /* Check for the Timeout */ + if (Timeout != DAL_MAX_DELAY) + { + if (((DAL_GetTick() - tickstart) > Timeout) || (Timeout == 0U)) + { + return DAL_ERROR; + } + } + } + return DAL_OK; +} + +#endif /* End AES or CRYP */ + + +/** + * @} + */ + + + +/** + * @} + */ + +/** + * @} + */ + +#endif /* DAL_CRYP_MODULE_ENABLED */ + + +/** + * @} + */ +#endif /* TinyAES or CRYP*/ +/** + * @} + */ + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_cryp_ex.c b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_cryp_ex.c new file mode 100644 index 0000000000..292a206046 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_cryp_ex.c @@ -0,0 +1,705 @@ +/** + * + * @file apm32f4xx_dal_cryp_ex.c + * @brief Extended CRYP DAL module driver + * This file provides firmware functions to manage the following + * functionalities of CRYP extension peripheral: + * + Extended AES processing functions + * + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + * + @verbatim + ============================================================================== + ##### How to use this driver ##### + ============================================================================== + [..] + The CRYP extension DAL driver can be used as follows: + (#)After AES-GCM or AES-CCM Encryption/Decryption user can start following API + to get the authentication messages : + (##) DAL_CRYPEx_AESGCM_GenerateAuthTAG + (##) DAL_CRYPEx_AESCCM_GenerateAuthTAG + + @endverbatim + * + */ + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ +#if defined (AES) || defined (CRYP) +#if defined (CRYP_CTRL_ALGOMSEL_AES_GCM)|| defined (AES) +/** @defgroup CRYPEx CRYPEx + * @brief CRYP Extension DAL module driver. + * @{ + */ + + +#ifdef DAL_CRYP_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/** @addtogroup CRYPEx_Private_Defines + * @{ + */ +#if defined(AES) +#define CRYP_PHASE_INIT 0x00000000U /*!< GCM/GMAC (or CCM) init phase */ +#define CRYP_PHASE_HEADER AES_CR_GCMPH_0 /*!< GCM/GMAC or CCM header phase */ +#define CRYP_PHASE_PAYLOAD AES_CR_GCMPH_1 /*!< GCM(/CCM) payload phase */ +#define CRYP_PHASE_FINAL AES_CR_GCMPH /*!< GCM/GMAC or CCM final phase */ + +#define CRYP_OPERATINGMODE_ENCRYPT 0x00000000U /*!< Encryption mode */ +#define CRYP_OPERATINGMODE_KEYDERIVATION AES_CR_MODE_0 /*!< Key derivation mode only used when performing ECB and CBC decryptions */ +#define CRYP_OPERATINGMODE_DECRYPT AES_CR_MODE_1 /*!< Decryption */ +#define CRYP_OPERATINGMODE_KEYDERIVATION_DECRYPT AES_CR_MODE /*!< Key derivation and decryption only used when performing ECB and CBC decryptions */ + +#else /* CRYP */ + +#define CRYP_PHASE_INIT 0x00000000U +#define CRYP_PHASE_HEADER CRYP_CTRL_GCM_CCMPH_0 +#define CRYP_PHASE_PAYLOAD CRYP_CTRL_GCM_CCMPH_1 +#define CRYP_PHASE_FINAL CRYP_CTRL_GCM_CCMPH + +#define CRYP_OPERATINGMODE_ENCRYPT 0x00000000U +#define CRYP_OPERATINGMODE_DECRYPT CRYP_CTRL_ALGODIRSEL +#endif /* End AES or CRYP */ + +#define CRYPEx_PHASE_PROCESS 0x02U /*!< CRYP peripheral is in processing phase */ +#define CRYPEx_PHASE_FINAL 0x03U /*!< CRYP peripheral is in final phase this is relevant only with CCM and GCM modes */ + +/* CTR0 information to use in CCM algorithm */ +#define CRYP_CCM_CTR0_0 0x07FFFFFFU +#define CRYP_CCM_CTR0_3 0xFFFFFF00U + + +/** + * @} + */ + +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ + + + +/* Exported functions---------------------------------------------------------*/ +/** @addtogroup CRYPEx_Exported_Functions + * @{ + */ + +/** @defgroup CRYPEx_Exported_Functions_Group1 Extended AES processing functions + * @brief Extended processing functions. + * +@verbatim + ============================================================================== + ##### Extended AES processing functions ##### + ============================================================================== + [..] This section provides functions allowing to generate the authentication + TAG in Polling mode + (#)DAL_CRYPEx_AESGCM_GenerateAuthTAG + (#)DAL_CRYPEx_AESCCM_GenerateAuthTAG + they should be used after Encrypt/Decrypt operation. + +@endverbatim + * @{ + */ + + +/** + * @brief generate the GCM authentication TAG. + * @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains + * the configuration information for CRYP module + * @param AuthTag: Pointer to the authentication buffer + * @param Timeout: Timeout duration + * @retval DAL status + */ +DAL_StatusTypeDef DAL_CRYPEx_AESGCM_GenerateAuthTAG(CRYP_HandleTypeDef *hcryp, uint32_t *AuthTag, uint32_t Timeout) +{ + uint32_t tickstart; + /* Assume first Init.HeaderSize is in words */ + uint64_t headerlength = (uint64_t)(hcryp->Init.HeaderSize) * 32U; /* Header length in bits */ + uint64_t inputlength = (uint64_t)hcryp->SizesSum * 8U; /* Input length in bits */ + uint32_t tagaddr = (uint32_t)AuthTag; + + /* Correct headerlength if Init.HeaderSize is actually in bytes */ + if (hcryp->Init.HeaderWidthUnit == CRYP_HEADERWIDTHUNIT_BYTE) + { + headerlength /= 4U; + } + + if (hcryp->State == DAL_CRYP_STATE_READY) + { + /* Process locked */ + __DAL_LOCK(hcryp); + + /* Change the CRYP peripheral state */ + hcryp->State = DAL_CRYP_STATE_BUSY; + + /* Check if initialization phase has already been performed */ + if (hcryp->Phase == CRYPEx_PHASE_PROCESS) + { + /* Change the CRYP phase */ + hcryp->Phase = CRYPEx_PHASE_FINAL; + } + else /* Initialization phase has not been performed*/ + { + /* Disable the Peripheral */ + __DAL_CRYP_DISABLE(hcryp); + + /* Sequence error code field */ + hcryp->ErrorCode |= DAL_CRYP_ERROR_AUTH_TAG_SEQUENCE; + + /* Change the CRYP peripheral state */ + hcryp->State = DAL_CRYP_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hcryp); + return DAL_ERROR; + } + +#if defined(CRYP) + + /* Disable CRYP to start the final phase */ + __DAL_CRYP_DISABLE(hcryp); + + /* Select final phase */ + MODIFY_REG(hcryp->Instance->CTRL, CRYP_CTRL_GCM_CCMPH, CRYP_PHASE_FINAL); + + /*ALGODIR bit must be set to '0'.*/ + hcryp->Instance->CTRL &= ~CRYP_CTRL_ALGODIRSEL; + + /* Enable the CRYP peripheral */ + __DAL_CRYP_ENABLE(hcryp); + + /* Write the number of bits in header (64 bits) followed by the number of bits + in the payload */ + if (hcryp->Init.DataType == CRYP_DATATYPE_1B) + { + hcryp->Instance->DATAIN = 0U; + hcryp->Instance->DATAIN = __RBIT((uint32_t)(headerlength)); + hcryp->Instance->DATAIN = 0U; + hcryp->Instance->DATAIN = __RBIT((uint32_t)(inputlength)); + } + else if (hcryp->Init.DataType == CRYP_DATATYPE_8B) + { + hcryp->Instance->DATAIN = 0U; + hcryp->Instance->DATAIN = __REV((uint32_t)(headerlength)); + hcryp->Instance->DATAIN = 0U; + hcryp->Instance->DATAIN = __REV((uint32_t)(inputlength)); + } + else if (hcryp->Init.DataType == CRYP_DATATYPE_16B) + { + hcryp->Instance->DATAIN = 0U; + hcryp->Instance->DATAIN = __ROR((uint32_t)headerlength, 16U); + hcryp->Instance->DATAIN = 0U; + hcryp->Instance->DATAIN = __ROR((uint32_t)inputlength, 16U); + } + else if (hcryp->Init.DataType == CRYP_DATATYPE_32B) + { + hcryp->Instance->DATAIN = 0U; + hcryp->Instance->DATAIN = (uint32_t)(headerlength); + hcryp->Instance->DATAIN = 0U; + hcryp->Instance->DATAIN = (uint32_t)(inputlength); + } + else + { + /* Nothing to do */ + } + + /* Wait for OFNE flag to be raised */ + tickstart = DAL_GetTick(); + while (DAL_IS_BIT_CLR(hcryp->Instance->STS, CRYP_FLAG_OFNE)) + { + /* Check for the Timeout */ + if (Timeout != DAL_MAX_DELAY) + { + if (((DAL_GetTick() - tickstart) > Timeout) || (Timeout == 0U)) + { + /* Disable the CRYP Peripheral Clock */ + __DAL_CRYP_DISABLE(hcryp); + + /* Change state */ + hcryp->ErrorCode |= DAL_CRYP_ERROR_TIMEOUT; + hcryp->State = DAL_CRYP_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hcryp); + return DAL_ERROR; + } + } + } + + /* Read the authentication TAG in the output FIFO */ + *(uint32_t *)(tagaddr) = hcryp->Instance->DATAOUT; + tagaddr += 4U; + *(uint32_t *)(tagaddr) = hcryp->Instance->DATAOUT; + tagaddr += 4U; + *(uint32_t *)(tagaddr) = hcryp->Instance->DATAOUT; + tagaddr += 4U; + *(uint32_t *)(tagaddr) = hcryp->Instance->DATAOUT; + +#else /* AES*/ + + /* Select final phase */ + MODIFY_REG(hcryp->Instance->CTRL, AES_CR_GCMPH, CRYP_PHASE_FINAL); + + /* Write the number of bits in header (64 bits) followed by the number of bits + in the payload */ + if (hcryp->Init.DataType == CRYP_DATATYPE_1B) + { + hcryp->Instance->DATAINR = 0U; + hcryp->Instance->DATAINR = __RBIT((uint32_t)(headerlength)); + hcryp->Instance->DATAINR = 0U; + hcryp->Instance->DATAINR = __RBIT((uint32_t)(inputlength)); + } + else if (hcryp->Init.DataType == CRYP_DATATYPE_8B) + { + hcryp->Instance->DATAINR = 0U; + hcryp->Instance->DATAINR = __REV((uint32_t)(headerlength)); + hcryp->Instance->DATAINR = 0U; + hcryp->Instance->DATAINR = __REV((uint32_t)(inputlength)); + } + else if (hcryp->Init.DataType == CRYP_DATATYPE_16B) + { + hcryp->Instance->DATAINR = 0U; + hcryp->Instance->DATAINR = __ROR((uint32_t)headerlength, 16U); + hcryp->Instance->DATAINR = 0U; + hcryp->Instance->DATAINR = __ROR((uint32_t)inputlength, 16U); + } + else if (hcryp->Init.DataType == CRYP_DATATYPE_32B) + { + hcryp->Instance->DATAINR = 0U; + hcryp->Instance->DATAINR = (uint32_t)(headerlength); + hcryp->Instance->DATAINR = 0U; + hcryp->Instance->DATAINR = (uint32_t)(inputlength); + } + else + { + /* Nothing to do */ + } + /* Wait for CCF flag to be raised */ + tickstart = DAL_GetTick(); + while (DAL_IS_BIT_CLR(hcryp->Instance->STS, AES_SR_CCF)) + { + /* Check for the Timeout */ + if (Timeout != DAL_MAX_DELAY) + { + if (((DAL_GetTick() - tickstart) > Timeout) || (Timeout == 0U)) + { + /* Disable the CRYP peripheral clock */ + __DAL_CRYP_DISABLE(hcryp); + + /* Change state */ + hcryp->ErrorCode |= DAL_CRYP_ERROR_TIMEOUT; + hcryp->State = DAL_CRYP_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hcryp); + return DAL_ERROR; + } + } + } + + /* Read the authentication TAG in the output FIFO */ + *(uint32_t *)(tagaddr) = hcryp->Instance->DATAOUTR; + tagaddr += 4U; + *(uint32_t *)(tagaddr) = hcryp->Instance->DATAOUTR; + tagaddr += 4U; + *(uint32_t *)(tagaddr) = hcryp->Instance->DATAOUTR; + tagaddr += 4U; + *(uint32_t *)(tagaddr) = hcryp->Instance->DATAOUTR; + + /* Clear CCF flag */ + __DAL_CRYP_CLEAR_FLAG(hcryp, CRYP_CCF_CLEAR); + +#endif /* End AES or CRYP */ + + /* Disable the peripheral */ + __DAL_CRYP_DISABLE(hcryp); + + /* Change the CRYP peripheral state */ + hcryp->State = DAL_CRYP_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hcryp); + } + else + { + /* Busy error code field */ + hcryp->ErrorCode |= DAL_CRYP_ERROR_BUSY; + return DAL_ERROR; + } + /* Return function status */ + return DAL_OK; +} + +/** + * @brief AES CCM Authentication TAG generation. + * @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains + * the configuration information for CRYP module + * @param AuthTag: Pointer to the authentication buffer + * @param Timeout: Timeout duration + * @retval DAL status + */ +DAL_StatusTypeDef DAL_CRYPEx_AESCCM_GenerateAuthTAG(CRYP_HandleTypeDef *hcryp, uint32_t *AuthTag, uint32_t Timeout) +{ + uint32_t tagaddr = (uint32_t)AuthTag; + uint32_t ctr0 [4] = {0}; + uint32_t ctr0addr = (uint32_t)ctr0; + uint32_t tickstart; + + if (hcryp->State == DAL_CRYP_STATE_READY) + { + /* Process locked */ + __DAL_LOCK(hcryp); + + /* Change the CRYP peripheral state */ + hcryp->State = DAL_CRYP_STATE_BUSY; + + /* Check if initialization phase has already been performed */ + if (hcryp->Phase == CRYPEx_PHASE_PROCESS) + { + /* Change the CRYP phase */ + hcryp->Phase = CRYPEx_PHASE_FINAL; + } + else /* Initialization phase has not been performed*/ + { + /* Disable the peripheral */ + __DAL_CRYP_DISABLE(hcryp); + + /* Sequence error code field */ + hcryp->ErrorCode |= DAL_CRYP_ERROR_AUTH_TAG_SEQUENCE; + + /* Change the CRYP peripheral state */ + hcryp->State = DAL_CRYP_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hcryp); + return DAL_ERROR; + } + +#if defined(CRYP) + + /* Disable CRYP to start the final phase */ + __DAL_CRYP_DISABLE(hcryp); + + /* Select final phase & ALGODIR bit must be set to '0'. */ + MODIFY_REG(hcryp->Instance->CTRL, CRYP_CTRL_GCM_CCMPH | CRYP_CTRL_ALGODIRSEL, CRYP_PHASE_FINAL | CRYP_OPERATINGMODE_ENCRYPT); + + /* Enable the CRYP peripheral */ + __DAL_CRYP_ENABLE(hcryp); + + /* Write the counter block in the IN FIFO, CTR0 information from B0 + data has to be swapped according to the DATATYPE*/ + ctr0[0] = (hcryp->Init.B0[0]) & CRYP_CCM_CTR0_0; + ctr0[1] = hcryp->Init.B0[1]; + ctr0[2] = hcryp->Init.B0[2]; + ctr0[3] = hcryp->Init.B0[3] & CRYP_CCM_CTR0_3; + + if (hcryp->Init.DataType == CRYP_DATATYPE_8B) + { + hcryp->Instance->DATAIN = __REV(*(uint32_t *)(ctr0addr)); + ctr0addr += 4U; + hcryp->Instance->DATAIN = __REV(*(uint32_t *)(ctr0addr)); + ctr0addr += 4U; + hcryp->Instance->DATAIN = __REV(*(uint32_t *)(ctr0addr)); + ctr0addr += 4U; + hcryp->Instance->DATAIN = __REV(*(uint32_t *)(ctr0addr)); + } + else if (hcryp->Init.DataType == CRYP_DATATYPE_16B) + { + hcryp->Instance->DATAIN = __ROR(*(uint32_t *)(ctr0addr), 16U); + ctr0addr += 4U; + hcryp->Instance->DATAIN = __ROR(*(uint32_t *)(ctr0addr), 16U); + ctr0addr += 4U; + hcryp->Instance->DATAIN = __ROR(*(uint32_t *)(ctr0addr), 16U); + ctr0addr += 4U; + hcryp->Instance->DATAIN = __ROR(*(uint32_t *)(ctr0addr), 16U); + } + else if (hcryp->Init.DataType == CRYP_DATATYPE_1B) + { + hcryp->Instance->DATAIN = __RBIT(*(uint32_t *)(ctr0addr)); + ctr0addr += 4U; + hcryp->Instance->DATAIN = __RBIT(*(uint32_t *)(ctr0addr)); + ctr0addr += 4U; + hcryp->Instance->DATAIN = __RBIT(*(uint32_t *)(ctr0addr)); + ctr0addr += 4U; + hcryp->Instance->DATAIN = __RBIT(*(uint32_t *)(ctr0addr)); + } + else + { + hcryp->Instance->DATAIN = *(uint32_t *)(ctr0addr); + ctr0addr += 4U; + hcryp->Instance->DATAIN = *(uint32_t *)(ctr0addr); + ctr0addr += 4U; + hcryp->Instance->DATAIN = *(uint32_t *)(ctr0addr); + ctr0addr += 4U; + hcryp->Instance->DATAIN = *(uint32_t *)(ctr0addr); + } + /* Wait for OFNE flag to be raised */ + tickstart = DAL_GetTick(); + while (DAL_IS_BIT_CLR(hcryp->Instance->STS, CRYP_FLAG_OFNE)) + { + /* Check for the Timeout */ + if (Timeout != DAL_MAX_DELAY) + { + if (((DAL_GetTick() - tickstart) > Timeout) || (Timeout == 0U)) + { + /* Disable the CRYP peripheral Clock */ + __DAL_CRYP_DISABLE(hcryp); + + /* Change state */ + hcryp->ErrorCode |= DAL_CRYP_ERROR_TIMEOUT; + hcryp->State = DAL_CRYP_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hcryp); + return DAL_ERROR; + } + } + } + + /* Read the Auth TAG in the IN FIFO */ + *(uint32_t *)(tagaddr) = hcryp->Instance->DATAOUT; + tagaddr += 4U; + *(uint32_t *)(tagaddr) = hcryp->Instance->DATAOUT; + tagaddr += 4U; + *(uint32_t *)(tagaddr) = hcryp->Instance->DATAOUT; + tagaddr += 4U; + *(uint32_t *)(tagaddr) = hcryp->Instance->DATAOUT; + +#else /* AES */ + + /* Select final phase */ + MODIFY_REG(hcryp->Instance->CTRL, AES_CR_GCMPH, CRYP_PHASE_FINAL); + + /* Write the counter block in the IN FIFO, CTR0 information from B0 + data has to be swapped according to the DATATYPE*/ + if (hcryp->Init.DataType == CRYP_DATATYPE_8B) + { + ctr0[0] = (__REV(hcryp->Init.B0[0]) & CRYP_CCM_CTR0_0); + ctr0[1] = __REV(hcryp->Init.B0[1]); + ctr0[2] = __REV(hcryp->Init.B0[2]); + ctr0[3] = (__REV(hcryp->Init.B0[3])& CRYP_CCM_CTR0_3); + + hcryp->Instance->DATAINR = __REV(*(uint32_t *)(ctr0addr)); + ctr0addr += 4U; + hcryp->Instance->DATAINR = __REV(*(uint32_t *)(ctr0addr)); + ctr0addr += 4U; + hcryp->Instance->DATAINR = __REV(*(uint32_t *)(ctr0addr)); + ctr0addr += 4U; + hcryp->Instance->DATAINR = __REV(*(uint32_t *)(ctr0addr)); + } + else if (hcryp->Init.DataType == CRYP_DATATYPE_16B) + { + ctr0[0] = (__ROR((hcryp->Init.B0[0]), 16U)& CRYP_CCM_CTR0_0); + ctr0[1] = __ROR((hcryp->Init.B0[1]), 16U); + ctr0[2] = __ROR((hcryp->Init.B0[2]), 16U); + ctr0[3] = (__ROR((hcryp->Init.B0[3]), 16U)& CRYP_CCM_CTR0_3); + + hcryp->Instance->DATAINR = __ROR(*(uint32_t *)(ctr0addr), 16U); + ctr0addr += 4U; + hcryp->Instance->DATAINR = __ROR(*(uint32_t *)(ctr0addr), 16U); + ctr0addr += 4U; + hcryp->Instance->DATAINR = __ROR(*(uint32_t *)(ctr0addr), 16U); + ctr0addr += 4U; + hcryp->Instance->DATAINR = __ROR(*(uint32_t *)(ctr0addr), 16U); + } + else if (hcryp->Init.DataType == CRYP_DATATYPE_1B) + { + ctr0[0] = (__RBIT(hcryp->Init.B0[0])& CRYP_CCM_CTR0_0); + ctr0[1] = __RBIT(hcryp->Init.B0[1]); + ctr0[2] = __RBIT(hcryp->Init.B0[2]); + ctr0[3] = (__RBIT(hcryp->Init.B0[3])& CRYP_CCM_CTR0_3); + + hcryp->Instance->DATAINR = __RBIT(*(uint32_t *)(ctr0addr)); + ctr0addr += 4U; + hcryp->Instance->DATAINR = __RBIT(*(uint32_t *)(ctr0addr)); + ctr0addr += 4U; + hcryp->Instance->DATAINR = __RBIT(*(uint32_t *)(ctr0addr)); + ctr0addr += 4U; + hcryp->Instance->DATAINR = __RBIT(*(uint32_t *)(ctr0addr)); + } + else + { + ctr0[0] = (hcryp->Init.B0[0]) & CRYP_CCM_CTR0_0; + ctr0[1] = hcryp->Init.B0[1]; + ctr0[2] = hcryp->Init.B0[2]; + ctr0[3] = hcryp->Init.B0[3] & CRYP_CCM_CTR0_3; + + hcryp->Instance->DATAINR = *(uint32_t *)(ctr0addr); + ctr0addr += 4U; + hcryp->Instance->DATAINR = *(uint32_t *)(ctr0addr); + ctr0addr += 4U; + hcryp->Instance->DATAINR = *(uint32_t *)(ctr0addr); + ctr0addr += 4U; + hcryp->Instance->DATAINR = *(uint32_t *)(ctr0addr); + } + + /* Wait for CCF flag to be raised */ + tickstart = DAL_GetTick(); + while (DAL_IS_BIT_CLR(hcryp->Instance->STS, AES_SR_CCF)) + { + /* Check for the Timeout */ + if (Timeout != DAL_MAX_DELAY) + { + if (((DAL_GetTick() - tickstart) > Timeout) || (Timeout == 0U)) + { + /* Disable the CRYP peripheral Clock */ + __DAL_CRYP_DISABLE(hcryp); + + /* Change state */ + hcryp->ErrorCode |= DAL_CRYP_ERROR_TIMEOUT; + hcryp->State = DAL_CRYP_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hcryp); + return DAL_ERROR; + } + } + } + + /* Read the authentication TAG in the output FIFO */ + *(uint32_t *)(tagaddr) = hcryp->Instance->DATAOUTR; + tagaddr += 4U; + *(uint32_t *)(tagaddr) = hcryp->Instance->DATAOUTR; + tagaddr += 4U; + *(uint32_t *)(tagaddr) = hcryp->Instance->DATAOUTR; + tagaddr += 4U; + *(uint32_t *)(tagaddr) = hcryp->Instance->DATAOUTR; + + /* Clear CCF Flag */ + __DAL_CRYP_CLEAR_FLAG(hcryp, CRYP_CCF_CLEAR); + +#endif /* End of AES || CRYP */ + + /* Change the CRYP peripheral state */ + hcryp->State = DAL_CRYP_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hcryp); + + /* Disable CRYP */ + __DAL_CRYP_DISABLE(hcryp); + } + else + { + /* Busy error code field */ + hcryp->ErrorCode = DAL_CRYP_ERROR_BUSY; + return DAL_ERROR; + } + /* Return function status */ + return DAL_OK; +} + +/** + * @} + */ + +#if defined (AES) +/** @defgroup CRYPEx_Exported_Functions_Group2 Key Derivation functions + * @brief AutoKeyDerivation functions + * +@verbatim + ============================================================================== + ##### Key Derivation functions ##### + ============================================================================== + [..] This section provides functions allowing to Enable or Disable the + the AutoKeyDerivation parameter in CRYP_HandleTypeDef structure + These function are allowed only in TinyAES IP. + +@endverbatim + * @{ + */ + +/** + * @brief AES enable key derivation functions + * @param hcryp: pointer to a CRYP_HandleTypeDef structure. + * @retval None + */ +void DAL_CRYPEx_EnableAutoKeyDerivation(CRYP_HandleTypeDef *hcryp) +{ + if (hcryp->State == DAL_CRYP_STATE_READY) + { + hcryp->AutoKeyDerivation = ENABLE; + } + else + { + /* Busy error code field */ + hcryp->ErrorCode = DAL_CRYP_ERROR_BUSY; + } +} +/** + * @brief AES disable key derivation functions + * @param hcryp: pointer to a CRYP_HandleTypeDef structure. + * @retval None + */ +void DAL_CRYPEx_DisableAutoKeyDerivation(CRYP_HandleTypeDef *hcryp) +{ + if (hcryp->State == DAL_CRYP_STATE_READY) + { + hcryp->AutoKeyDerivation = DISABLE; + } + else + { + /* Busy error code field */ + hcryp->ErrorCode = DAL_CRYP_ERROR_BUSY; + } +} + +/** + * @} + */ +#endif /* AES or GCM CCM defined*/ +#endif /* AES */ +#endif /* DAL_CRYP_MODULE_ENABLED */ + +/** + * @} + */ +#endif /* TinyAES or CRYP*/ +/** + * @} + */ + +/** + * @} + */ + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_dac.c b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_dac.c new file mode 100644 index 0000000000..a291699588 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_dac.c @@ -0,0 +1,1366 @@ +/** + * + * @file apm32f4xx_dal_dac.c + * @brief DAC DAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the Digital to Analog Converter (DAC) peripheral: + * + Initialization and de-initialization functions + * + IO operation functions + * + Peripheral Control functions + * + Peripheral State and Errors functions + * + * + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + * + @verbatim + ============================================================================== + ##### DAC Peripheral features ##### + ============================================================================== + [..] + *** DAC Channels *** + ==================== + [..] + APM32F4 devices integrate two 12-bit Digital Analog Converters + + The 2 converters (i.e. channel1 & channel2) + can be used independently or simultaneously (dual mode): + (#) DAC channel1 with DAC_OUT1 (PA4) as output + (#) DAC channel2 with DAC_OUT2 (PA5) as output + + *** DAC Triggers *** + ==================== + [..] + Digital to Analog conversion can be non-triggered using DAC_TRIGGER_NONE + and DAC_OUT1/DAC_OUT2 is available once writing to DHRx register. + [..] + Digital to Analog conversion can be triggered by: + (#) External event: EXTI Line 9 (any GPIOx_PIN_9) using DAC_TRIGGER_EXT_IT9. + The used pin (GPIOx_PIN_9) must be configured in input mode. + + (#) Timers TRGO: TMR2, TMR4, TMR5, TMR6, TMR7 and TMR8 + (DAC_TRIGGER_T2_TRGO, DAC_TRIGGER_T4_TRGO...) + + (#) Software using DAC_TRIGGER_SOFTWARE + + *** DAC Buffer mode feature *** + =============================== + [..] + Each DAC channel integrates an output buffer that can be used to + reduce the output impedance, and to drive external loads directly + without having to add an external operational amplifier. + To enable, the output buffer use + sConfig.DAC_OutputBuffer = DAC_OUTPUTBUFFER_ENABLE; + [..] + (@) Refer to the device datasheet for more details about output + impedance value with and without output buffer. + + *** DAC wave generation feature *** + =================================== + [..] + Both DAC channels can be used to generate + (#) Noise wave + (#) Triangle wave + + *** DAC data format *** + ======================= + [..] + The DAC data format can be: + (#) 8-bit right alignment using DAC_ALIGN_8B_R + (#) 12-bit left alignment using DAC_ALIGN_12B_L + (#) 12-bit right alignment using DAC_ALIGN_12B_R + + *** DAC data value to voltage correspondence *** + ================================================ + [..] + The analog output voltage on each DAC channel pin is determined + by the following equation: + [..] + DAC_OUTx = VREF+ * DOR / 4095 + (+) with DOR is the Data Output Register + [..] + VREF+ is the input voltage reference (refer to the device datasheet) + [..] + e.g. To set DAC_OUT1 to 0.7V, use + (+) Assuming that VREF+ = 3.3V, DAC_OUT1 = (3.3 * 868) / 4095 = 0.7V + + *** DMA requests *** + ===================== + [..] + A DMA request can be generated when an external trigger (but not a software trigger) + occurs if DMA1 requests are enabled using DAL_DAC_Start_DMA(). + DMA1 requests are mapped as following: + (#) DAC channel1 mapped on DMA1 Stream5 channel7 which must be + already configured + (#) DAC channel2 mapped on DMA1 Stream6 channel7 which must be + already configured + + [..] + (@) For Dual mode and specific signal (Triangle and noise) generation please + refer to Extended Features Driver description + + ##### How to use this driver ##### + ============================================================================== + [..] + (+) DAC APB clock must be enabled to get write access to DAC + registers using DAL_DAC_Init() + (+) Configure DAC_OUTx (DAC_OUT1: PA4, DAC_OUT2: PA5) in analog mode. + (+) Configure the DAC channel using DAL_DAC_ConfigChannel() function. + (+) Enable the DAC channel using DAL_DAC_Start() or DAL_DAC_Start_DMA() functions. + + + *** Polling mode IO operation *** + ================================= + [..] + (+) Start the DAC peripheral using DAL_DAC_Start() + (+) To read the DAC last data output value, use the DAL_DAC_GetValue() function. + (+) Stop the DAC peripheral using DAL_DAC_Stop() + + *** DMA mode IO operation *** + ============================== + [..] + (+) Start the DAC peripheral using DAL_DAC_Start_DMA(), at this stage the user specify the length + of data to be transferred at each end of conversion + First issued trigger will start the conversion of the value previously set by DAL_DAC_SetValue(). + (+) At the middle of data transfer DAL_DAC_ConvHalfCpltCallbackCh1() or DAL_DACEx_ConvHalfCpltCallbackCh2() + function is executed and user can add his own code by customization of function pointer + DAL_DAC_ConvHalfCpltCallbackCh1() or DAL_DACEx_ConvHalfCpltCallbackCh2() + (+) At The end of data transfer DAL_DAC_ConvCpltCallbackCh1() or DAL_DACEx_ConvHalfCpltCallbackCh2() + function is executed and user can add his own code by customization of function pointer + DAL_DAC_ConvCpltCallbackCh1() or DAL_DACEx_ConvHalfCpltCallbackCh2() + (+) In case of transfer Error, DAL_DAC_ErrorCallbackCh1() function is executed and user can + add his own code by customization of function pointer DAL_DAC_ErrorCallbackCh1 + (+) In case of DMA underrun, DAC interruption triggers and execute internal function DAL_DAC_IRQHandler. + DAL_DAC_DMAUnderrunCallbackCh1() or DAL_DACEx_DMAUnderrunCallbackCh2() + function is executed and user can add his own code by customization of function pointer + DAL_DAC_DMAUnderrunCallbackCh1() or DAL_DACEx_DMAUnderrunCallbackCh2() and + add his own code by customization of function pointer DAL_DAC_ErrorCallbackCh1() + (+) Stop the DAC peripheral using DAL_DAC_Stop_DMA() + + *** Callback registration *** + ============================================= + [..] + The compilation define USE_DAL_DAC_REGISTER_CALLBACKS when set to 1 + allows the user to configure dynamically the driver callbacks. + + Use Functions DAL_DAC_RegisterCallback() to register a user callback, + it allows to register following callbacks: + (+) ConvCpltCallbackCh1 : callback when a half transfer is completed on Ch1. + (+) ConvHalfCpltCallbackCh1 : callback when a transfer is completed on Ch1. + (+) ErrorCallbackCh1 : callback when an error occurs on Ch1. + (+) DMAUnderrunCallbackCh1 : callback when an underrun error occurs on Ch1. + (+) ConvCpltCallbackCh2 : callback when a half transfer is completed on Ch2. + (+) ConvHalfCpltCallbackCh2 : callback when a transfer is completed on Ch2. + (+) ErrorCallbackCh2 : callback when an error occurs on Ch2. + (+) DMAUnderrunCallbackCh2 : callback when an underrun error occurs on Ch2. + (+) MspInitCallback : DAC MspInit. + (+) MspDeInitCallback : DAC MspdeInit. + This function takes as parameters the DAL peripheral handle, the Callback ID + and a pointer to the user callback function. + + Use function DAL_DAC_UnRegisterCallback() to reset a callback to the default + weak (surcharged) function. It allows to reset following callbacks: + (+) ConvCpltCallbackCh1 : callback when a half transfer is completed on Ch1. + (+) ConvHalfCpltCallbackCh1 : callback when a transfer is completed on Ch1. + (+) ErrorCallbackCh1 : callback when an error occurs on Ch1. + (+) DMAUnderrunCallbackCh1 : callback when an underrun error occurs on Ch1. + (+) ConvCpltCallbackCh2 : callback when a half transfer is completed on Ch2. + (+) ConvHalfCpltCallbackCh2 : callback when a transfer is completed on Ch2. + (+) ErrorCallbackCh2 : callback when an error occurs on Ch2. + (+) DMAUnderrunCallbackCh2 : callback when an underrun error occurs on Ch2. + (+) MspInitCallback : DAC MspInit. + (+) MspDeInitCallback : DAC MspdeInit. + (+) All Callbacks + This function) takes as parameters the DAL peripheral handle and the Callback ID. + + By default, after the DAL_DAC_Init and if the state is DAL_DAC_STATE_RESET + all callbacks are reset to the corresponding legacy weak (surcharged) functions. + Exception done for MspInit and MspDeInit callbacks that are respectively + reset to the legacy weak (surcharged) functions in the DAL_DAC_Init + and DAL_DAC_DeInit only when these callbacks are null (not registered beforehand). + If not, MspInit or MspDeInit are not null, the DAL_DAC_Init and DAL_DAC_DeInit + keep and use the user MspInit/MspDeInit callbacks (registered beforehand) + + Callbacks can be registered/unregistered in READY state only. + Exception done for MspInit/MspDeInit callbacks that can be registered/unregistered + in READY or RESET state, thus registered (user) MspInit/DeInit callbacks can be used + during the Init/DeInit. + In that case first register the MspInit/MspDeInit user callbacks + using DAL_DAC_RegisterCallback before calling DAL_DAC_DeInit + or DAL_DAC_Init function. + + When The compilation define USE_DAL_DAC_REGISTER_CALLBACKS is set to 0 or + not defined, the callback registering feature is not available + and weak (surcharged) callbacks are used. + + *** DAC DAL driver macros list *** + ============================================= + [..] + Below the list of most used macros in DAC DAL driver. + + (+) __DAL_DAC_ENABLE : Enable the DAC peripheral + (+) __DAL_DAC_DISABLE : Disable the DAC peripheral + (+) __DAL_DAC_CLEAR_FLAG: Clear the DAC's pending flags + (+) __DAL_DAC_GET_FLAG: Get the selected DAC's flag status + + [..] + (@) You can refer to the DAC DAL driver header file for more useful macros + +@endverbatim + * + */ + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +#ifdef DAL_DAC_MODULE_ENABLED +#if defined(DAC) + +/** @defgroup DAC DAC + * @brief DAC driver modules + * @{ + */ + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Exported functions -------------------------------------------------------*/ + +/** @defgroup DAC_Exported_Functions DAC Exported Functions + * @{ + */ + +/** @defgroup DAC_Exported_Functions_Group1 Initialization and de-initialization functions + * @brief Initialization and Configuration functions + * +@verbatim + ============================================================================== + ##### Initialization and de-initialization functions ##### + ============================================================================== + [..] This section provides functions allowing to: + (+) Initialize and configure the DAC. + (+) De-initialize the DAC. + +@endverbatim + * @{ + */ + +/** + * @brief Initialize the DAC peripheral according to the specified parameters + * in the DAC_InitStruct and initialize the associated handle. + * @param hdac pointer to a DAC_HandleTypeDef structure that contains + * the configuration information for the specified DAC. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_DAC_Init(DAC_HandleTypeDef *hdac) +{ + /* Check DAC handle */ + if (hdac == NULL) + { + return DAL_ERROR; + } + /* Check the parameters */ + ASSERT_PARAM(IS_DAC_ALL_INSTANCE(hdac->Instance)); + + if (hdac->State == DAL_DAC_STATE_RESET) + { +#if (USE_DAL_DAC_REGISTER_CALLBACKS == 1) + /* Init the DAC Callback settings */ + hdac->ConvCpltCallbackCh1 = DAL_DAC_ConvCpltCallbackCh1; + hdac->ConvHalfCpltCallbackCh1 = DAL_DAC_ConvHalfCpltCallbackCh1; + hdac->ErrorCallbackCh1 = DAL_DAC_ErrorCallbackCh1; + hdac->DMAUnderrunCallbackCh1 = DAL_DAC_DMAUnderrunCallbackCh1; +#if defined(DAC_CHANNEL2_SUPPORT) + hdac->ConvCpltCallbackCh2 = DAL_DACEx_ConvCpltCallbackCh2; + hdac->ConvHalfCpltCallbackCh2 = DAL_DACEx_ConvHalfCpltCallbackCh2; + hdac->ErrorCallbackCh2 = DAL_DACEx_ErrorCallbackCh2; + hdac->DMAUnderrunCallbackCh2 = DAL_DACEx_DMAUnderrunCallbackCh2; +#endif /* DAC_CHANNEL2_SUPPORT */ + if (hdac->MspInitCallback == NULL) + { + hdac->MspInitCallback = DAL_DAC_MspInit; + } +#endif /* USE_DAL_DAC_REGISTER_CALLBACKS */ + + /* Allocate lock resource and initialize it */ + hdac->Lock = DAL_UNLOCKED; + +#if (USE_DAL_DAC_REGISTER_CALLBACKS == 1) + /* Init the low level hardware */ + hdac->MspInitCallback(hdac); +#else + /* Init the low level hardware */ + DAL_DAC_MspInit(hdac); +#endif /* USE_DAL_DAC_REGISTER_CALLBACKS */ + } + + /* Initialize the DAC state*/ + hdac->State = DAL_DAC_STATE_BUSY; + + /* Set DAC error code to none */ + hdac->ErrorCode = DAL_DAC_ERROR_NONE; + + /* Initialize the DAC state*/ + hdac->State = DAL_DAC_STATE_READY; + + /* Return function status */ + return DAL_OK; +} + +/** + * @brief Deinitialize the DAC peripheral registers to their default reset values. + * @param hdac pointer to a DAC_HandleTypeDef structure that contains + * the configuration information for the specified DAC. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_DAC_DeInit(DAC_HandleTypeDef *hdac) +{ + /* Check DAC handle */ + if (hdac == NULL) + { + return DAL_ERROR; + } + + /* Check the parameters */ + ASSERT_PARAM(IS_DAC_ALL_INSTANCE(hdac->Instance)); + + /* Change DAC state */ + hdac->State = DAL_DAC_STATE_BUSY; + +#if (USE_DAL_DAC_REGISTER_CALLBACKS == 1) + if (hdac->MspDeInitCallback == NULL) + { + hdac->MspDeInitCallback = DAL_DAC_MspDeInit; + } + /* DeInit the low level hardware */ + hdac->MspDeInitCallback(hdac); +#else + /* DeInit the low level hardware */ + DAL_DAC_MspDeInit(hdac); +#endif /* USE_DAL_DAC_REGISTER_CALLBACKS */ + + /* Set DAC error code to none */ + hdac->ErrorCode = DAL_DAC_ERROR_NONE; + + /* Change DAC state */ + hdac->State = DAL_DAC_STATE_RESET; + + /* Release Lock */ + __DAL_UNLOCK(hdac); + + /* Return function status */ + return DAL_OK; +} + +/** + * @brief Initialize the DAC MSP. + * @param hdac pointer to a DAC_HandleTypeDef structure that contains + * the configuration information for the specified DAC. + * @retval None + */ +__weak void DAL_DAC_MspInit(DAC_HandleTypeDef *hdac) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hdac); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_DAC_MspInit could be implemented in the user file + */ +} + +/** + * @brief DeInitialize the DAC MSP. + * @param hdac pointer to a DAC_HandleTypeDef structure that contains + * the configuration information for the specified DAC. + * @retval None + */ +__weak void DAL_DAC_MspDeInit(DAC_HandleTypeDef *hdac) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hdac); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_DAC_MspDeInit could be implemented in the user file + */ +} + +/** + * @} + */ + +/** @defgroup DAC_Exported_Functions_Group2 IO operation functions + * @brief IO operation functions + * +@verbatim + ============================================================================== + ##### IO operation functions ##### + ============================================================================== + [..] This section provides functions allowing to: + (+) Start conversion. + (+) Stop conversion. + (+) Start conversion and enable DMA transfer. + (+) Stop conversion and disable DMA transfer. + (+) Get result of conversion. + +@endverbatim + * @{ + */ + +/** + * @brief Enables DAC and starts conversion of channel. + * @param hdac pointer to a DAC_HandleTypeDef structure that contains + * the configuration information for the specified DAC. + * @param Channel The selected DAC channel. + * This parameter can be one of the following values: + * @arg DAC_CHANNEL_1: DAC Channel1 selected + * @arg DAC_CHANNEL_2: DAC Channel2 selected + * @retval DAL status + */ +DAL_StatusTypeDef DAL_DAC_Start(DAC_HandleTypeDef *hdac, uint32_t Channel) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_DAC_CHANNEL(Channel)); + + /* Process locked */ + __DAL_LOCK(hdac); + + /* Change DAC state */ + hdac->State = DAL_DAC_STATE_BUSY; + + /* Enable the Peripheral */ + __DAL_DAC_ENABLE(hdac, Channel); + + if (Channel == DAC_CHANNEL_1) + { + /* Check if software trigger enabled */ + if ((hdac->Instance->CTRL & (DAC_CTRL_TRGENCH1 | DAC_CTRL_TRGSELCH1)) == DAC_TRIGGER_SOFTWARE) + { + /* Enable the selected DAC software conversion */ + SET_BIT(hdac->Instance->SWTRG, DAC_SWTRG_SWTRG1); + } + } +#if defined(DAC_CHANNEL2_SUPPORT) + else + { + /* Check if software trigger enabled */ + if ((hdac->Instance->CTRL & (DAC_CTRL_TRGENCH2 | DAC_CTRL_TRGSELCH2)) == (DAC_TRIGGER_SOFTWARE << (Channel & 0x10UL))) + { + /* Enable the selected DAC software conversion*/ + SET_BIT(hdac->Instance->SWTRG, DAC_SWTRG_SWTRG2); + } + } +#endif /* DAC_CHANNEL2_SUPPORT */ + + /* Change DAC state */ + hdac->State = DAL_DAC_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hdac); + + /* Return function status */ + return DAL_OK; +} + +/** + * @brief Disables DAC and stop conversion of channel. + * @param hdac pointer to a DAC_HandleTypeDef structure that contains + * the configuration information for the specified DAC. + * @param Channel The selected DAC channel. + * This parameter can be one of the following values: + * @arg DAC_CHANNEL_1: DAC Channel1 selected + * @arg DAC_CHANNEL_2: DAC Channel2 selected + * @retval DAL status + */ +DAL_StatusTypeDef DAL_DAC_Stop(DAC_HandleTypeDef *hdac, uint32_t Channel) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_DAC_CHANNEL(Channel)); + + /* Disable the Peripheral */ + __DAL_DAC_DISABLE(hdac, Channel); + + /* Change DAC state */ + hdac->State = DAL_DAC_STATE_READY; + + /* Return function status */ + return DAL_OK; +} + +/** + * @brief Enables DAC and starts conversion of channel. + * @param hdac pointer to a DAC_HandleTypeDef structure that contains + * the configuration information for the specified DAC. + * @param Channel The selected DAC channel. + * This parameter can be one of the following values: + * @arg DAC_CHANNEL_1: DAC Channel1 selected + * @arg DAC_CHANNEL_2: DAC Channel2 selected + * @param pData The source Buffer address. + * @param Length The length of data to be transferred from memory to DAC peripheral + * @param Alignment Specifies the data alignment for DAC channel. + * This parameter can be one of the following values: + * @arg DAC_ALIGN_8B_R: 8bit right data alignment selected + * @arg DAC_ALIGN_12B_L: 12bit left data alignment selected + * @arg DAC_ALIGN_12B_R: 12bit right data alignment selected + * @retval DAL status + */ +DAL_StatusTypeDef DAL_DAC_Start_DMA(DAC_HandleTypeDef *hdac, uint32_t Channel, uint32_t *pData, uint32_t Length, + uint32_t Alignment) +{ + DAL_StatusTypeDef status = DAL_OK; + uint32_t tmpreg = 0U; + + /* Check the parameters */ + ASSERT_PARAM(IS_DAC_CHANNEL(Channel)); + ASSERT_PARAM(IS_DAC_ALIGN(Alignment)); + + /* Process locked */ + __DAL_LOCK(hdac); + + /* Change DAC state */ + hdac->State = DAL_DAC_STATE_BUSY; + + if (Channel == DAC_CHANNEL_1) + { + /* Set the DMA transfer complete callback for channel1 */ + hdac->DMA_Handle1->XferCpltCallback = DAC_DMAConvCpltCh1; + + /* Set the DMA half transfer complete callback for channel1 */ + hdac->DMA_Handle1->XferHalfCpltCallback = DAC_DMAHalfConvCpltCh1; + + /* Set the DMA error callback for channel1 */ + hdac->DMA_Handle1->XferErrorCallback = DAC_DMAErrorCh1; + + /* Enable the selected DAC channel1 DMA request */ + SET_BIT(hdac->Instance->CTRL, DAC_CTRL_DMAENCH1); + + /* Case of use of channel 1 */ + switch (Alignment) + { + case DAC_ALIGN_12B_R: + /* Get DHR12R1 address */ + tmpreg = (uint32_t)&hdac->Instance->DH12R1; + break; + case DAC_ALIGN_12B_L: + /* Get DHR12L1 address */ + tmpreg = (uint32_t)&hdac->Instance->DH12L1; + break; + case DAC_ALIGN_8B_R: + /* Get DHR8R1 address */ + tmpreg = (uint32_t)&hdac->Instance->DH8R1; + break; + default: + break; + } + } +#if defined(DAC_CHANNEL2_SUPPORT) + else + { + /* Set the DMA transfer complete callback for channel2 */ + hdac->DMA_Handle2->XferCpltCallback = DAC_DMAConvCpltCh2; + + /* Set the DMA half transfer complete callback for channel2 */ + hdac->DMA_Handle2->XferHalfCpltCallback = DAC_DMAHalfConvCpltCh2; + + /* Set the DMA error callback for channel2 */ + hdac->DMA_Handle2->XferErrorCallback = DAC_DMAErrorCh2; + + /* Enable the selected DAC channel2 DMA request */ + SET_BIT(hdac->Instance->CTRL, DAC_CTRL_DMAENCH2); + + /* Case of use of channel 2 */ + switch (Alignment) + { + case DAC_ALIGN_12B_R: + /* Get DHR12R2 address */ + tmpreg = (uint32_t)&hdac->Instance->DH12R2; + break; + case DAC_ALIGN_12B_L: + /* Get DHR12L2 address */ + tmpreg = (uint32_t)&hdac->Instance->DH12L2; + break; + case DAC_ALIGN_8B_R: + /* Get DHR8R2 address */ + tmpreg = (uint32_t)&hdac->Instance->DH8R2; + break; + default: + break; + } + } +#endif /* DAC_CHANNEL2_SUPPORT */ + + /* Enable the DMA Stream */ + if (Channel == DAC_CHANNEL_1) + { + /* Enable the DAC DMA underrun interrupt */ + __DAL_DAC_ENABLE_IT(hdac, DAC_IT_DMAUDR1); + + /* Enable the DMA Stream */ + status = DAL_DMA_Start_IT(hdac->DMA_Handle1, (uint32_t)pData, tmpreg, Length); + } +#if defined(DAC_CHANNEL2_SUPPORT) + else + { + /* Enable the DAC DMA underrun interrupt */ + __DAL_DAC_ENABLE_IT(hdac, DAC_IT_DMAUDR2); + + /* Enable the DMA Stream */ + status = DAL_DMA_Start_IT(hdac->DMA_Handle2, (uint32_t)pData, tmpreg, Length); + } +#endif /* DAC_CHANNEL2_SUPPORT */ + + /* Process Unlocked */ + __DAL_UNLOCK(hdac); + + if (status == DAL_OK) + { + /* Enable the Peripheral */ + __DAL_DAC_ENABLE(hdac, Channel); + } + else + { + hdac->ErrorCode |= DAL_DAC_ERROR_DMA; + } + + /* Return function status */ + return status; +} + +/** + * @brief Disables DAC and stop conversion of channel. + * @param hdac pointer to a DAC_HandleTypeDef structure that contains + * the configuration information for the specified DAC. + * @param Channel The selected DAC channel. + * This parameter can be one of the following values: + * @arg DAC_CHANNEL_1: DAC Channel1 selected + * @arg DAC_CHANNEL_2: DAC Channel2 selected + * @retval DAL status + */ +DAL_StatusTypeDef DAL_DAC_Stop_DMA(DAC_HandleTypeDef *hdac, uint32_t Channel) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_DAC_CHANNEL(Channel)); + + /* Disable the selected DAC channel DMA request */ + hdac->Instance->CTRL &= ~(DAC_CTRL_DMAENCH1 << (Channel & 0x10UL)); + + /* Disable the Peripheral */ + __DAL_DAC_DISABLE(hdac, Channel); + + /* Disable the DMA Stream */ + + /* Channel1 is used */ + if (Channel == DAC_CHANNEL_1) + { + /* Disable the DMA Stream */ + (void)DAL_DMA_Abort(hdac->DMA_Handle1); + + /* Disable the DAC DMA underrun interrupt */ + __DAL_DAC_DISABLE_IT(hdac, DAC_IT_DMAUDR1); + } +#if defined(DAC_CHANNEL2_SUPPORT) + else /* Channel2 is used for */ + { + /* Disable the DMA Stream */ + (void)DAL_DMA_Abort(hdac->DMA_Handle2); + + /* Disable the DAC DMA underrun interrupt */ + __DAL_DAC_DISABLE_IT(hdac, DAC_IT_DMAUDR2); + } +#endif /* DAC_CHANNEL2_SUPPORT */ + + /* Change DAC state */ + hdac->State = DAL_DAC_STATE_READY; + + /* Return function status */ + return DAL_OK; +} + +/** + * @brief Handles DAC interrupt request + * This function uses the interruption of DMA + * underrun. + * @param hdac pointer to a DAC_HandleTypeDef structure that contains + * the configuration information for the specified DAC. + * @retval None + */ +void DAL_DAC_IRQHandler(DAC_HandleTypeDef *hdac) +{ + if (__DAL_DAC_GET_IT_SOURCE(hdac, DAC_IT_DMAUDR1)) + { + /* Check underrun flag of DAC channel 1 */ + if (__DAL_DAC_GET_FLAG(hdac, DAC_FLAG_DMAUDR1)) + { + /* Change DAC state to error state */ + hdac->State = DAL_DAC_STATE_ERROR; + + /* Set DAC error code to channel1 DMA underrun error */ + SET_BIT(hdac->ErrorCode, DAL_DAC_ERROR_DMAUNDERRUNCH1); + + /* Clear the underrun flag */ + __DAL_DAC_CLEAR_FLAG(hdac, DAC_FLAG_DMAUDR1); + + /* Disable the selected DAC channel1 DMA request */ + CLEAR_BIT(hdac->Instance->CTRL, DAC_CTRL_DMAENCH1); + + /* Error callback */ +#if (USE_DAL_DAC_REGISTER_CALLBACKS == 1) + hdac->DMAUnderrunCallbackCh1(hdac); +#else + DAL_DAC_DMAUnderrunCallbackCh1(hdac); +#endif /* USE_DAL_DAC_REGISTER_CALLBACKS */ + } + } + +#if defined(DAC_CHANNEL2_SUPPORT) + if (__DAL_DAC_GET_IT_SOURCE(hdac, DAC_IT_DMAUDR2)) + { + /* Check underrun flag of DAC channel 2 */ + if (__DAL_DAC_GET_FLAG(hdac, DAC_FLAG_DMAUDR2)) + { + /* Change DAC state to error state */ + hdac->State = DAL_DAC_STATE_ERROR; + + /* Set DAC error code to channel2 DMA underrun error */ + SET_BIT(hdac->ErrorCode, DAL_DAC_ERROR_DMAUNDERRUNCH2); + + /* Clear the underrun flag */ + __DAL_DAC_CLEAR_FLAG(hdac, DAC_FLAG_DMAUDR2); + + /* Disable the selected DAC channel2 DMA request */ + CLEAR_BIT(hdac->Instance->CTRL, DAC_CTRL_DMAENCH2); + + /* Error callback */ +#if (USE_DAL_DAC_REGISTER_CALLBACKS == 1) + hdac->DMAUnderrunCallbackCh2(hdac); +#else + DAL_DACEx_DMAUnderrunCallbackCh2(hdac); +#endif /* USE_DAL_DAC_REGISTER_CALLBACKS */ + } + } +#endif /* DAC_CHANNEL2_SUPPORT */ +} + +/** + * @brief Set the specified data holding register value for DAC channel. + * @param hdac pointer to a DAC_HandleTypeDef structure that contains + * the configuration information for the specified DAC. + * @param Channel The selected DAC channel. + * This parameter can be one of the following values: + * @arg DAC_CHANNEL_1: DAC Channel1 selected + * @arg DAC_CHANNEL_2: DAC Channel2 selected + * @param Alignment Specifies the data alignment. + * This parameter can be one of the following values: + * @arg DAC_ALIGN_8B_R: 8bit right data alignment selected + * @arg DAC_ALIGN_12B_L: 12bit left data alignment selected + * @arg DAC_ALIGN_12B_R: 12bit right data alignment selected + * @param Data Data to be loaded in the selected data holding register. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_DAC_SetValue(DAC_HandleTypeDef *hdac, uint32_t Channel, uint32_t Alignment, uint32_t Data) +{ + __IO uint32_t tmp = 0UL; + + /* Check the parameters */ + ASSERT_PARAM(IS_DAC_CHANNEL(Channel)); + ASSERT_PARAM(IS_DAC_ALIGN(Alignment)); + ASSERT_PARAM(IS_DAC_DATA(Data)); + + tmp = (uint32_t)hdac->Instance; + if (Channel == DAC_CHANNEL_1) + { + tmp += DAC_DH12R1_ALIGNMENT(Alignment); + } +#if defined(DAC_CHANNEL2_SUPPORT) + else + { + tmp += DAC_DH12R2_ALIGNMENT(Alignment); + } +#endif /* DAC_CHANNEL2_SUPPORT */ + + /* Set the DAC channel selected data holding register */ + *(__IO uint32_t *) tmp = Data; + + /* Return function status */ + return DAL_OK; +} + +/** + * @brief Conversion complete callback in non-blocking mode for Channel1 + * @param hdac pointer to a DAC_HandleTypeDef structure that contains + * the configuration information for the specified DAC. + * @retval None + */ +__weak void DAL_DAC_ConvCpltCallbackCh1(DAC_HandleTypeDef *hdac) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hdac); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_DAC_ConvCpltCallbackCh1 could be implemented in the user file + */ +} + +/** + * @brief Conversion half DMA transfer callback in non-blocking mode for Channel1 + * @param hdac pointer to a DAC_HandleTypeDef structure that contains + * the configuration information for the specified DAC. + * @retval None + */ +__weak void DAL_DAC_ConvHalfCpltCallbackCh1(DAC_HandleTypeDef *hdac) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hdac); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_DAC_ConvHalfCpltCallbackCh1 could be implemented in the user file + */ +} + +/** + * @brief Error DAC callback for Channel1. + * @param hdac pointer to a DAC_HandleTypeDef structure that contains + * the configuration information for the specified DAC. + * @retval None + */ +__weak void DAL_DAC_ErrorCallbackCh1(DAC_HandleTypeDef *hdac) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hdac); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_DAC_ErrorCallbackCh1 could be implemented in the user file + */ +} + +/** + * @brief DMA underrun DAC callback for channel1. + * @param hdac pointer to a DAC_HandleTypeDef structure that contains + * the configuration information for the specified DAC. + * @retval None + */ +__weak void DAL_DAC_DMAUnderrunCallbackCh1(DAC_HandleTypeDef *hdac) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hdac); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_DAC_DMAUnderrunCallbackCh1 could be implemented in the user file + */ +} + +/** + * @} + */ + +/** @defgroup DAC_Exported_Functions_Group3 Peripheral Control functions + * @brief Peripheral Control functions + * +@verbatim + ============================================================================== + ##### Peripheral Control functions ##### + ============================================================================== + [..] This section provides functions allowing to: + (+) Configure channels. + (+) Set the specified data holding register value for DAC channel. + +@endverbatim + * @{ + */ + +/** + * @brief Returns the last data output value of the selected DAC channel. + * @param hdac pointer to a DAC_HandleTypeDef structure that contains + * the configuration information for the specified DAC. + * @param Channel The selected DAC channel. + * This parameter can be one of the following values: + * @arg DAC_CHANNEL_1: DAC Channel1 selected + * @arg DAC_CHANNEL_2: DAC Channel2 selected + * @retval The selected DAC channel data output value. + */ +uint32_t DAL_DAC_GetValue(DAC_HandleTypeDef *hdac, uint32_t Channel) +{ + uint32_t result = 0; + + /* Check the parameters */ + ASSERT_PARAM(IS_DAC_CHANNEL(Channel)); + + if (Channel == DAC_CHANNEL_1) + { + result = hdac->Instance->DATAOCH1; + } +#if defined(DAC_CHANNEL2_SUPPORT) + else + { + result = hdac->Instance->DATAOCH2; + } +#endif /* DAC_CHANNEL2_SUPPORT */ + /* Returns the DAC channel data output register value */ + return result; +} + +/** + * @brief Configures the selected DAC channel. + * @param hdac pointer to a DAC_HandleTypeDef structure that contains + * the configuration information for the specified DAC. + * @param sConfig DAC configuration structure. + * @param Channel The selected DAC channel. + * This parameter can be one of the following values: + * @arg DAC_CHANNEL_1: DAC Channel1 selected + * @arg DAC_CHANNEL_2: DAC Channel2 selected + * @retval DAL status + */ +DAL_StatusTypeDef DAL_DAC_ConfigChannel(DAC_HandleTypeDef *hdac, DAC_ChannelConfTypeDef *sConfig, uint32_t Channel) +{ + uint32_t tmpreg1; + uint32_t tmpreg2; + + /* Check the DAC parameters */ + ASSERT_PARAM(IS_DAC_TRIGGER(sConfig->DAC_Trigger)); + ASSERT_PARAM(IS_DAC_OUTPUT_BUFFER_STATE(sConfig->DAC_OutputBuffer)); + ASSERT_PARAM(IS_DAC_CHANNEL(Channel)); + + /* Process locked */ + __DAL_LOCK(hdac); + + /* Change DAC state */ + hdac->State = DAL_DAC_STATE_BUSY; + + /* Get the DAC CTRL value */ + tmpreg1 = hdac->Instance->CTRL; + /* Clear BUFFDx, TRGENx, TRGSELx, WAVENx and MAMPSELx bits */ + tmpreg1 &= ~(((uint32_t)(DAC_CTRL_MAMPSELCH1 | DAC_CTRL_WAVENCH1 | DAC_CTRL_TRGSELCH1 | DAC_CTRL_TRGENCH1 | DAC_CTRL_BUFFDCH1)) << (Channel & 0x10UL)); + /* Configure for the selected DAC channel: buffer output, trigger */ + /* Set TRGSELx and TRGENx bits according to DAC_Trigger value */ + /* Set BUFFDx bit according to DAC_OutputBuffer value */ + tmpreg2 = (sConfig->DAC_Trigger | sConfig->DAC_OutputBuffer); + /* Calculate CTRL register value depending on DAC_Channel */ + tmpreg1 |= tmpreg2 << (Channel & 0x10UL); + /* Write to DAC CTRL */ + hdac->Instance->CTRL = tmpreg1; + /* Disable wave generation */ + CLEAR_BIT(hdac->Instance->CTRL, (DAC_CTRL_WAVENCH1 << (Channel & 0x10UL))); + + /* Change DAC state */ + hdac->State = DAL_DAC_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hdac); + + /* Return function status */ + return DAL_OK; +} + +/** + * @} + */ + +/** @defgroup DAC_Exported_Functions_Group4 Peripheral State and Errors functions + * @brief Peripheral State and Errors functions + * +@verbatim + ============================================================================== + ##### Peripheral State and Errors functions ##### + ============================================================================== + [..] + This subsection provides functions allowing to + (+) Check the DAC state. + (+) Check the DAC Errors. + +@endverbatim + * @{ + */ + +/** + * @brief return the DAC handle state + * @param hdac pointer to a DAC_HandleTypeDef structure that contains + * the configuration information for the specified DAC. + * @retval DAL state + */ +DAL_DAC_StateTypeDef DAL_DAC_GetState(DAC_HandleTypeDef *hdac) +{ + /* Return DAC handle state */ + return hdac->State; +} + + +/** + * @brief Return the DAC error code + * @param hdac pointer to a DAC_HandleTypeDef structure that contains + * the configuration information for the specified DAC. + * @retval DAC Error Code + */ +uint32_t DAL_DAC_GetError(DAC_HandleTypeDef *hdac) +{ + return hdac->ErrorCode; +} + +/** + * @} + */ + +/** + * @} + */ + +/** @addtogroup DAC_Exported_Functions + * @{ + */ + +/** @addtogroup DAC_Exported_Functions_Group1 + * @{ + */ +#if (USE_DAL_DAC_REGISTER_CALLBACKS == 1) +/** + * @brief Register a User DAC Callback + * To be used instead of the weak (surcharged) predefined callback + * @param hdac DAC handle + * @param CallbackID ID of the callback to be registered + * This parameter can be one of the following values: + * @arg @ref DAL_DAC_ERROR_INVALID_CALLBACK DAC Error Callback ID + * @arg @ref DAL_DAC_CH1_COMPLETE_CB_ID DAC CH1 Complete Callback ID + * @arg @ref DAL_DAC_CH1_HALF_COMPLETE_CB_ID DAC CH1 Half Complete Callback ID + * @arg @ref DAL_DAC_CH1_ERROR_ID DAC CH1 Error Callback ID + * @arg @ref DAL_DAC_CH1_UNDERRUN_CB_ID DAC CH1 UnderRun Callback ID + * @arg @ref DAL_DAC_CH2_COMPLETE_CB_ID DAC CH2 Complete Callback ID + * @arg @ref DAL_DAC_CH2_HALF_COMPLETE_CB_ID DAC CH2 Half Complete Callback ID + * @arg @ref DAL_DAC_CH2_ERROR_ID DAC CH2 Error Callback ID + * @arg @ref DAL_DAC_CH2_UNDERRUN_CB_ID DAC CH2 UnderRun Callback ID + * @arg @ref DAL_DAC_MSPINIT_CB_ID DAC MSP Init Callback ID + * @arg @ref DAL_DAC_MSPDEINIT_CB_ID DAC MSP DeInit Callback ID + * + * @param pCallback pointer to the Callback function + * @retval status + */ +DAL_StatusTypeDef DAL_DAC_RegisterCallback(DAC_HandleTypeDef *hdac, DAL_DAC_CallbackIDTypeDef CallbackID, + pDAC_CallbackTypeDef pCallback) +{ + DAL_StatusTypeDef status = DAL_OK; + + if (pCallback == NULL) + { + /* Update the error code */ + hdac->ErrorCode |= DAL_DAC_ERROR_INVALID_CALLBACK; + return DAL_ERROR; + } + + /* Process locked */ + __DAL_LOCK(hdac); + + if (hdac->State == DAL_DAC_STATE_READY) + { + switch (CallbackID) + { + case DAL_DAC_CH1_COMPLETE_CB_ID : + hdac->ConvCpltCallbackCh1 = pCallback; + break; + case DAL_DAC_CH1_HALF_COMPLETE_CB_ID : + hdac->ConvHalfCpltCallbackCh1 = pCallback; + break; + case DAL_DAC_CH1_ERROR_ID : + hdac->ErrorCallbackCh1 = pCallback; + break; + case DAL_DAC_CH1_UNDERRUN_CB_ID : + hdac->DMAUnderrunCallbackCh1 = pCallback; + break; +#if defined(DAC_CHANNEL2_SUPPORT) + case DAL_DAC_CH2_COMPLETE_CB_ID : + hdac->ConvCpltCallbackCh2 = pCallback; + break; + case DAL_DAC_CH2_HALF_COMPLETE_CB_ID : + hdac->ConvHalfCpltCallbackCh2 = pCallback; + break; + case DAL_DAC_CH2_ERROR_ID : + hdac->ErrorCallbackCh2 = pCallback; + break; + case DAL_DAC_CH2_UNDERRUN_CB_ID : + hdac->DMAUnderrunCallbackCh2 = pCallback; + break; +#endif /* DAC_CHANNEL2_SUPPORT */ + case DAL_DAC_MSPINIT_CB_ID : + hdac->MspInitCallback = pCallback; + break; + case DAL_DAC_MSPDEINIT_CB_ID : + hdac->MspDeInitCallback = pCallback; + break; + default : + /* Update the error code */ + hdac->ErrorCode |= DAL_DAC_ERROR_INVALID_CALLBACK; + /* update return status */ + status = DAL_ERROR; + break; + } + } + else if (hdac->State == DAL_DAC_STATE_RESET) + { + switch (CallbackID) + { + case DAL_DAC_MSPINIT_CB_ID : + hdac->MspInitCallback = pCallback; + break; + case DAL_DAC_MSPDEINIT_CB_ID : + hdac->MspDeInitCallback = pCallback; + break; + default : + /* Update the error code */ + hdac->ErrorCode |= DAL_DAC_ERROR_INVALID_CALLBACK; + /* update return status */ + status = DAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + hdac->ErrorCode |= DAL_DAC_ERROR_INVALID_CALLBACK; + /* update return status */ + status = DAL_ERROR; + } + + /* Release Lock */ + __DAL_UNLOCK(hdac); + return status; +} + +/** + * @brief Unregister a User DAC Callback + * DAC Callback is redirected to the weak (surcharged) predefined callback + * @param hdac DAC handle + * @param CallbackID ID of the callback to be unregistered + * This parameter can be one of the following values: + * @arg @ref DAL_DAC_CH1_COMPLETE_CB_ID DAC CH1 transfer Complete Callback ID + * @arg @ref DAL_DAC_CH1_HALF_COMPLETE_CB_ID DAC CH1 Half Complete Callback ID + * @arg @ref DAL_DAC_CH1_ERROR_ID DAC CH1 Error Callback ID + * @arg @ref DAL_DAC_CH1_UNDERRUN_CB_ID DAC CH1 UnderRun Callback ID + * @arg @ref DAL_DAC_CH2_COMPLETE_CB_ID DAC CH2 Complete Callback ID + * @arg @ref DAL_DAC_CH2_HALF_COMPLETE_CB_ID DAC CH2 Half Complete Callback ID + * @arg @ref DAL_DAC_CH2_ERROR_ID DAC CH2 Error Callback ID + * @arg @ref DAL_DAC_CH2_UNDERRUN_CB_ID DAC CH2 UnderRun Callback ID + * @arg @ref DAL_DAC_MSPINIT_CB_ID DAC MSP Init Callback ID + * @arg @ref DAL_DAC_MSPDEINIT_CB_ID DAC MSP DeInit Callback ID + * @arg @ref DAL_DAC_ALL_CB_ID DAC All callbacks + * @retval status + */ +DAL_StatusTypeDef DAL_DAC_UnRegisterCallback(DAC_HandleTypeDef *hdac, DAL_DAC_CallbackIDTypeDef CallbackID) +{ + DAL_StatusTypeDef status = DAL_OK; + + /* Process locked */ + __DAL_LOCK(hdac); + + if (hdac->State == DAL_DAC_STATE_READY) + { + switch (CallbackID) + { + case DAL_DAC_CH1_COMPLETE_CB_ID : + hdac->ConvCpltCallbackCh1 = DAL_DAC_ConvCpltCallbackCh1; + break; + case DAL_DAC_CH1_HALF_COMPLETE_CB_ID : + hdac->ConvHalfCpltCallbackCh1 = DAL_DAC_ConvHalfCpltCallbackCh1; + break; + case DAL_DAC_CH1_ERROR_ID : + hdac->ErrorCallbackCh1 = DAL_DAC_ErrorCallbackCh1; + break; + case DAL_DAC_CH1_UNDERRUN_CB_ID : + hdac->DMAUnderrunCallbackCh1 = DAL_DAC_DMAUnderrunCallbackCh1; + break; +#if defined(DAC_CHANNEL2_SUPPORT) + case DAL_DAC_CH2_COMPLETE_CB_ID : + hdac->ConvCpltCallbackCh2 = DAL_DACEx_ConvCpltCallbackCh2; + break; + case DAL_DAC_CH2_HALF_COMPLETE_CB_ID : + hdac->ConvHalfCpltCallbackCh2 = DAL_DACEx_ConvHalfCpltCallbackCh2; + break; + case DAL_DAC_CH2_ERROR_ID : + hdac->ErrorCallbackCh2 = DAL_DACEx_ErrorCallbackCh2; + break; + case DAL_DAC_CH2_UNDERRUN_CB_ID : + hdac->DMAUnderrunCallbackCh2 = DAL_DACEx_DMAUnderrunCallbackCh2; + break; +#endif /* DAC_CHANNEL2_SUPPORT */ + case DAL_DAC_MSPINIT_CB_ID : + hdac->MspInitCallback = DAL_DAC_MspInit; + break; + case DAL_DAC_MSPDEINIT_CB_ID : + hdac->MspDeInitCallback = DAL_DAC_MspDeInit; + break; + case DAL_DAC_ALL_CB_ID : + hdac->ConvCpltCallbackCh1 = DAL_DAC_ConvCpltCallbackCh1; + hdac->ConvHalfCpltCallbackCh1 = DAL_DAC_ConvHalfCpltCallbackCh1; + hdac->ErrorCallbackCh1 = DAL_DAC_ErrorCallbackCh1; + hdac->DMAUnderrunCallbackCh1 = DAL_DAC_DMAUnderrunCallbackCh1; +#if defined(DAC_CHANNEL2_SUPPORT) + hdac->ConvCpltCallbackCh2 = DAL_DACEx_ConvCpltCallbackCh2; + hdac->ConvHalfCpltCallbackCh2 = DAL_DACEx_ConvHalfCpltCallbackCh2; + hdac->ErrorCallbackCh2 = DAL_DACEx_ErrorCallbackCh2; + hdac->DMAUnderrunCallbackCh2 = DAL_DACEx_DMAUnderrunCallbackCh2; +#endif /* DAC_CHANNEL2_SUPPORT */ + hdac->MspInitCallback = DAL_DAC_MspInit; + hdac->MspDeInitCallback = DAL_DAC_MspDeInit; + break; + default : + /* Update the error code */ + hdac->ErrorCode |= DAL_DAC_ERROR_INVALID_CALLBACK; + /* update return status */ + status = DAL_ERROR; + break; + } + } + else if (hdac->State == DAL_DAC_STATE_RESET) + { + switch (CallbackID) + { + case DAL_DAC_MSPINIT_CB_ID : + hdac->MspInitCallback = DAL_DAC_MspInit; + break; + case DAL_DAC_MSPDEINIT_CB_ID : + hdac->MspDeInitCallback = DAL_DAC_MspDeInit; + break; + default : + /* Update the error code */ + hdac->ErrorCode |= DAL_DAC_ERROR_INVALID_CALLBACK; + /* update return status */ + status = DAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + hdac->ErrorCode |= DAL_DAC_ERROR_INVALID_CALLBACK; + /* update return status */ + status = DAL_ERROR; + } + + /* Release Lock */ + __DAL_UNLOCK(hdac); + return status; +} +#endif /* USE_DAL_DAC_REGISTER_CALLBACKS */ + +/** + * @} + */ + +/** + * @} + */ + +/** @addtogroup DAC_Private_Functions + * @{ + */ + +/** + * @brief DMA conversion complete callback. + * @param hdma pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +void DAC_DMAConvCpltCh1(DMA_HandleTypeDef *hdma) +{ + DAC_HandleTypeDef *hdac = (DAC_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + +#if (USE_DAL_DAC_REGISTER_CALLBACKS == 1) + hdac->ConvCpltCallbackCh1(hdac); +#else + DAL_DAC_ConvCpltCallbackCh1(hdac); +#endif /* USE_DAL_DAC_REGISTER_CALLBACKS */ + + hdac->State = DAL_DAC_STATE_READY; +} + +/** + * @brief DMA half transfer complete callback. + * @param hdma pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +void DAC_DMAHalfConvCpltCh1(DMA_HandleTypeDef *hdma) +{ + DAC_HandleTypeDef *hdac = (DAC_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + /* Conversion complete callback */ +#if (USE_DAL_DAC_REGISTER_CALLBACKS == 1) + hdac->ConvHalfCpltCallbackCh1(hdac); +#else + DAL_DAC_ConvHalfCpltCallbackCh1(hdac); +#endif /* USE_DAL_DAC_REGISTER_CALLBACKS */ +} + +/** + * @brief DMA error callback + * @param hdma pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +void DAC_DMAErrorCh1(DMA_HandleTypeDef *hdma) +{ + DAC_HandleTypeDef *hdac = (DAC_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + + /* Set DAC error code to DMA error */ + hdac->ErrorCode |= DAL_DAC_ERROR_DMA; + +#if (USE_DAL_DAC_REGISTER_CALLBACKS == 1) + hdac->ErrorCallbackCh1(hdac); +#else + DAL_DAC_ErrorCallbackCh1(hdac); +#endif /* USE_DAL_DAC_REGISTER_CALLBACKS */ + + hdac->State = DAL_DAC_STATE_READY; +} + +/** + * @} + */ + +/** + * @} + */ + +#endif /* DAC */ + +#endif /* DAL_DAC_MODULE_ENABLED */ + +/** + * @} + */ + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_dac_ex.c b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_dac_ex.c new file mode 100644 index 0000000000..5cb76cbe59 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_dac_ex.c @@ -0,0 +1,520 @@ +/** + * + * @file apm32f4xx_dal_dac_ex.c + * @brief Extended DAC DAL module driver. + * This file provides firmware functions to manage the extended + * functionalities of the DAC peripheral. + * + * + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + * + @verbatim + ============================================================================== + ##### How to use this driver ##### + ============================================================================== + [..] + + *** Dual mode IO operation *** + ============================== + [..] + (+) When Dual mode is enabled (i.e. DAC Channel1 and Channel2 are used simultaneously) : + Use DAL_DACEx_DualGetValue() to get digital data to be converted and use + DAL_DACEx_DualSetValue() to set digital value to converted simultaneously in + Channel 1 and Channel 2. + + *** Signal generation operation *** + =================================== + [..] + (+) Use DAL_DACEx_TriangleWaveGenerate() to generate Triangle signal. + (+) Use DAL_DACEx_NoiseWaveGenerate() to generate Noise signal. + + @endverbatim + * + */ + + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +#ifdef DAL_DAC_MODULE_ENABLED + +#if defined(DAC) + +/** @defgroup DACEx DACEx + * @brief DAC Extended DAL module driver + * @{ + */ + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Exported functions --------------------------------------------------------*/ + +/** @defgroup DACEx_Exported_Functions DACEx Exported Functions + * @{ + */ + +/** @defgroup DACEx_Exported_Functions_Group2 IO operation functions + * @brief Extended IO operation functions + * +@verbatim + ============================================================================== + ##### Extended features functions ##### + ============================================================================== + [..] This section provides functions allowing to: + (+) Start conversion. + (+) Stop conversion. + (+) Start conversion and enable DMA transfer. + (+) Stop conversion and disable DMA transfer. + (+) Get result of conversion. + (+) Get result of dual mode conversion. + +@endverbatim + * @{ + */ + +#if defined(DAC_CHANNEL2_SUPPORT) +/** + * @brief Enables DAC and starts conversion of both channels. + * @param hdac pointer to a DAC_HandleTypeDef structure that contains + * the configuration information for the specified DAC. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_DACEx_DualStart(DAC_HandleTypeDef *hdac) +{ + uint32_t tmp_swtrig = 0UL; + + + /* Process locked */ + __DAL_LOCK(hdac); + + /* Change DAC state */ + hdac->State = DAL_DAC_STATE_BUSY; + + /* Enable the Peripheral */ + __DAL_DAC_ENABLE(hdac, DAC_CHANNEL_1); + __DAL_DAC_ENABLE(hdac, DAC_CHANNEL_2); + + /* Check if software trigger enabled */ + if ((hdac->Instance->CTRL & (DAC_CTRL_TRGENCH1 | DAC_CTRL_TRGSELCH1)) == DAC_TRIGGER_SOFTWARE) + { + tmp_swtrig |= DAC_SWTRG_SWTRG1; + } + if ((hdac->Instance->CTRL & (DAC_CTRL_TRGENCH2 | DAC_CTRL_TRGSELCH2)) == (DAC_TRIGGER_SOFTWARE << (DAC_CHANNEL_2 & 0x10UL))) + { + tmp_swtrig |= DAC_SWTRG_SWTRG2; + } + /* Enable the selected DAC software conversion*/ + SET_BIT(hdac->Instance->SWTRG, tmp_swtrig); + + /* Change DAC state */ + hdac->State = DAL_DAC_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hdac); + + /* Return function status */ + return DAL_OK; +} + +/** + * @brief Disables DAC and stop conversion of both channels. + * @param hdac pointer to a DAC_HandleTypeDef structure that contains + * the configuration information for the specified DAC. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_DACEx_DualStop(DAC_HandleTypeDef *hdac) +{ + + /* Disable the Peripheral */ + __DAL_DAC_DISABLE(hdac, DAC_CHANNEL_1); + __DAL_DAC_DISABLE(hdac, DAC_CHANNEL_2); + + /* Change DAC state */ + hdac->State = DAL_DAC_STATE_READY; + + /* Return function status */ + return DAL_OK; +} +#endif /* DAC_CHANNEL2_SUPPORT */ + +/** + * @brief Enable or disable the selected DAC channel wave generation. + * @param hdac pointer to a DAC_HandleTypeDef structure that contains + * the configuration information for the specified DAC. + * @param Channel The selected DAC channel. + * This parameter can be one of the following values: + * @arg DAC_CHANNEL_1: DAC Channel1 selected + * @arg DAC_CHANNEL_2: DAC Channel2 selected + * @param Amplitude Select max triangle amplitude. + * This parameter can be one of the following values: + * @arg DAC_TRIANGLEAMPLITUDE_1: Select max triangle amplitude of 1 + * @arg DAC_TRIANGLEAMPLITUDE_3: Select max triangle amplitude of 3 + * @arg DAC_TRIANGLEAMPLITUDE_7: Select max triangle amplitude of 7 + * @arg DAC_TRIANGLEAMPLITUDE_15: Select max triangle amplitude of 15 + * @arg DAC_TRIANGLEAMPLITUDE_31: Select max triangle amplitude of 31 + * @arg DAC_TRIANGLEAMPLITUDE_63: Select max triangle amplitude of 63 + * @arg DAC_TRIANGLEAMPLITUDE_127: Select max triangle amplitude of 127 + * @arg DAC_TRIANGLEAMPLITUDE_255: Select max triangle amplitude of 255 + * @arg DAC_TRIANGLEAMPLITUDE_511: Select max triangle amplitude of 511 + * @arg DAC_TRIANGLEAMPLITUDE_1023: Select max triangle amplitude of 1023 + * @arg DAC_TRIANGLEAMPLITUDE_2047: Select max triangle amplitude of 2047 + * @arg DAC_TRIANGLEAMPLITUDE_4095: Select max triangle amplitude of 4095 + * @retval DAL status + */ +DAL_StatusTypeDef DAL_DACEx_TriangleWaveGenerate(DAC_HandleTypeDef *hdac, uint32_t Channel, uint32_t Amplitude) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_DAC_CHANNEL(Channel)); + ASSERT_PARAM(IS_DAC_LFSR_UNMASK_TRIANGLE_AMPLITUDE(Amplitude)); + + /* Process locked */ + __DAL_LOCK(hdac); + + /* Change DAC state */ + hdac->State = DAL_DAC_STATE_BUSY; + + /* Enable the triangle wave generation for the selected DAC channel */ + MODIFY_REG(hdac->Instance->CTRL, ((DAC_CTRL_WAVENCH1) | (DAC_CTRL_MAMPSELCH1)) << (Channel & 0x10UL), + (DAC_CTRL_WAVENCH1_1 | Amplitude) << (Channel & 0x10UL)); + + /* Change DAC state */ + hdac->State = DAL_DAC_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hdac); + + /* Return function status */ + return DAL_OK; +} + +/** + * @brief Enable or disable the selected DAC channel wave generation. + * @param hdac pointer to a DAC_HandleTypeDef structure that contains + * the configuration information for the specified DAC. + * @param Channel The selected DAC channel. + * This parameter can be one of the following values: + * @arg DAC_CHANNEL_1: DAC Channel1 selected + * @arg DAC_CHANNEL_2: DAC Channel2 selected + * @param Amplitude Unmask DAC channel LFSR for noise wave generation. + * This parameter can be one of the following values: + * @arg DAC_LFSRUNMASK_BIT0: Unmask DAC channel LFSR bit0 for noise wave generation + * @arg DAC_LFSRUNMASK_BITS1_0: Unmask DAC channel LFSR bit[1:0] for noise wave generation + * @arg DAC_LFSRUNMASK_BITS2_0: Unmask DAC channel LFSR bit[2:0] for noise wave generation + * @arg DAC_LFSRUNMASK_BITS3_0: Unmask DAC channel LFSR bit[3:0] for noise wave generation + * @arg DAC_LFSRUNMASK_BITS4_0: Unmask DAC channel LFSR bit[4:0] for noise wave generation + * @arg DAC_LFSRUNMASK_BITS5_0: Unmask DAC channel LFSR bit[5:0] for noise wave generation + * @arg DAC_LFSRUNMASK_BITS6_0: Unmask DAC channel LFSR bit[6:0] for noise wave generation + * @arg DAC_LFSRUNMASK_BITS7_0: Unmask DAC channel LFSR bit[7:0] for noise wave generation + * @arg DAC_LFSRUNMASK_BITS8_0: Unmask DAC channel LFSR bit[8:0] for noise wave generation + * @arg DAC_LFSRUNMASK_BITS9_0: Unmask DAC channel LFSR bit[9:0] for noise wave generation + * @arg DAC_LFSRUNMASK_BITS10_0: Unmask DAC channel LFSR bit[10:0] for noise wave generation + * @arg DAC_LFSRUNMASK_BITS11_0: Unmask DAC channel LFSR bit[11:0] for noise wave generation + * @retval DAL status + */ +DAL_StatusTypeDef DAL_DACEx_NoiseWaveGenerate(DAC_HandleTypeDef *hdac, uint32_t Channel, uint32_t Amplitude) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_DAC_CHANNEL(Channel)); + ASSERT_PARAM(IS_DAC_LFSR_UNMASK_TRIANGLE_AMPLITUDE(Amplitude)); + + /* Process locked */ + __DAL_LOCK(hdac); + + /* Change DAC state */ + hdac->State = DAL_DAC_STATE_BUSY; + + /* Enable the noise wave generation for the selected DAC channel */ + MODIFY_REG(hdac->Instance->CTRL, ((DAC_CTRL_WAVENCH1) | (DAC_CTRL_MAMPSELCH1)) << (Channel & 0x10UL), + (DAC_CTRL_WAVENCH1_0 | Amplitude) << (Channel & 0x10UL)); + + /* Change DAC state */ + hdac->State = DAL_DAC_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hdac); + + /* Return function status */ + return DAL_OK; +} + +#if defined(DAC_CHANNEL2_SUPPORT) +/** + * @brief Set the specified data holding register value for dual DAC channel. + * @param hdac pointer to a DAC_HandleTypeDef structure that contains + * the configuration information for the specified DAC. + * @param Alignment Specifies the data alignment for dual channel DAC. + * This parameter can be one of the following values: + * DAC_ALIGN_8B_R: 8bit right data alignment selected + * DAC_ALIGN_12B_L: 12bit left data alignment selected + * DAC_ALIGN_12B_R: 12bit right data alignment selected + * @param Data1 Data for DAC Channel1 to be loaded in the selected data holding register. + * @param Data2 Data for DAC Channel2 to be loaded in the selected data holding register. + * @note In dual mode, a unique register access is required to write in both + * DAC channels at the same time. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_DACEx_DualSetValue(DAC_HandleTypeDef *hdac, uint32_t Alignment, uint32_t Data1, uint32_t Data2) +{ + uint32_t data; + uint32_t tmp; + + /* Check the parameters */ + ASSERT_PARAM(IS_DAC_ALIGN(Alignment)); + ASSERT_PARAM(IS_DAC_DATA(Data1)); + ASSERT_PARAM(IS_DAC_DATA(Data2)); + + /* Calculate and set dual DAC data holding register value */ + if (Alignment == DAC_ALIGN_8B_R) + { + data = ((uint32_t)Data2 << 8U) | Data1; + } + else + { + data = ((uint32_t)Data2 << 16U) | Data1; + } + + tmp = (uint32_t)hdac->Instance; + tmp += DAC_DH12RDUAL_ALIGNMENT(Alignment); + + /* Set the dual DAC selected data holding register */ + *(__IO uint32_t *)tmp = data; + + /* Return function status */ + return DAL_OK; +} + +/** + * @brief Conversion complete callback in non-blocking mode for Channel2. + * @param hdac pointer to a DAC_HandleTypeDef structure that contains + * the configuration information for the specified DAC. + * @retval None + */ +__weak void DAL_DACEx_ConvCpltCallbackCh2(DAC_HandleTypeDef *hdac) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hdac); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_DACEx_ConvCpltCallbackCh2 could be implemented in the user file + */ +} + +/** + * @brief Conversion half DMA transfer callback in non-blocking mode for Channel2. + * @param hdac pointer to a DAC_HandleTypeDef structure that contains + * the configuration information for the specified DAC. + * @retval None + */ +__weak void DAL_DACEx_ConvHalfCpltCallbackCh2(DAC_HandleTypeDef *hdac) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hdac); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_DACEx_ConvHalfCpltCallbackCh2 could be implemented in the user file + */ +} + +/** + * @brief Error DAC callback for Channel2. + * @param hdac pointer to a DAC_HandleTypeDef structure that contains + * the configuration information for the specified DAC. + * @retval None + */ +__weak void DAL_DACEx_ErrorCallbackCh2(DAC_HandleTypeDef *hdac) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hdac); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_DACEx_ErrorCallbackCh2 could be implemented in the user file + */ +} + +/** + * @brief DMA underrun DAC callback for Channel2. + * @param hdac pointer to a DAC_HandleTypeDef structure that contains + * the configuration information for the specified DAC. + * @retval None + */ +__weak void DAL_DACEx_DMAUnderrunCallbackCh2(DAC_HandleTypeDef *hdac) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hdac); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_DACEx_DMAUnderrunCallbackCh2 could be implemented in the user file + */ +} +#endif /* DAC_CHANNEL2_SUPPORT */ + + +/** + * @} + */ + +/** @defgroup DACEx_Exported_Functions_Group3 Peripheral Control functions + * @brief Extended Peripheral Control functions + * +@verbatim + ============================================================================== + ##### Peripheral Control functions ##### + ============================================================================== + [..] This section provides functions allowing to: + (+) Set the specified data holding register value for DAC channel. + +@endverbatim + * @{ + */ + +#if defined(DAC_CHANNEL2_SUPPORT) +/** + * @brief Return the last data output value of the selected DAC channel. + * @param hdac pointer to a DAC_HandleTypeDef structure that contains + * the configuration information for the specified DAC. + * @retval The selected DAC channel data output value. + */ +uint32_t DAL_DACEx_DualGetValue(DAC_HandleTypeDef *hdac) +{ + uint32_t tmp = 0UL; + + tmp |= hdac->Instance->DATAOCH1; + + tmp |= hdac->Instance->DATAOCH2 << 16UL; + + /* Returns the DAC channel data output register value */ + return tmp; +} +#endif /* DAC_CHANNEL2_SUPPORT */ + +/** + * @} + */ +/** + * @} + */ + +/* Private functions ---------------------------------------------------------*/ +/** @defgroup DACEx_Private_Functions DACEx private functions + * @brief Extended private functions + * @{ + */ + +#if defined(DAC_CHANNEL2_SUPPORT) +/** + * @brief DMA conversion complete callback. + * @param hdma pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +void DAC_DMAConvCpltCh2(DMA_HandleTypeDef *hdma) +{ + DAC_HandleTypeDef *hdac = (DAC_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + +#if (USE_DAL_DAC_REGISTER_CALLBACKS == 1) + hdac->ConvCpltCallbackCh2(hdac); +#else + DAL_DACEx_ConvCpltCallbackCh2(hdac); +#endif /* USE_DAL_DAC_REGISTER_CALLBACKS */ + + hdac->State = DAL_DAC_STATE_READY; +} + +/** + * @brief DMA half transfer complete callback. + * @param hdma pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +void DAC_DMAHalfConvCpltCh2(DMA_HandleTypeDef *hdma) +{ + DAC_HandleTypeDef *hdac = (DAC_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + /* Conversion complete callback */ +#if (USE_DAL_DAC_REGISTER_CALLBACKS == 1) + hdac->ConvHalfCpltCallbackCh2(hdac); +#else + DAL_DACEx_ConvHalfCpltCallbackCh2(hdac); +#endif /* USE_DAL_DAC_REGISTER_CALLBACKS */ +} + +/** + * @brief DMA error callback. + * @param hdma pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +void DAC_DMAErrorCh2(DMA_HandleTypeDef *hdma) +{ + DAC_HandleTypeDef *hdac = (DAC_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + + /* Set DAC error code to DMA error */ + hdac->ErrorCode |= DAL_DAC_ERROR_DMA; + +#if (USE_DAL_DAC_REGISTER_CALLBACKS == 1) + hdac->ErrorCallbackCh2(hdac); +#else + DAL_DACEx_ErrorCallbackCh2(hdac); +#endif /* USE_DAL_DAC_REGISTER_CALLBACKS */ + + hdac->State = DAL_DAC_STATE_READY; +} +#endif /* DAC_CHANNEL2_SUPPORT */ + +/** + * @} + */ + +/** + * @} + */ + +#endif /* DAC */ + +#endif /* DAL_DAC_MODULE_ENABLED */ + +/** + * @} + */ + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_dci.c b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_dci.c new file mode 100644 index 0000000000..7c8f3bf4b5 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_dci.c @@ -0,0 +1,1182 @@ +/** + * + * @file apm32f4xx_dal_dci.c + * @brief DCI DAL module driver + * This file provides firmware functions to manage the following + * functionalities of the Digital Camera Interface (DCI) peripheral: + * + Initialization and de-initialization functions + * + IO operation functions + * + Peripheral Control functions + * + Peripheral State and Error functions + * + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2017 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file in + * the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + @verbatim + ============================================================================== + ##### How to use this driver ##### + ============================================================================== + [..] + The sequence below describes how to use this driver to capture image + from a camera module connected to the DCI Interface. + This sequence does not take into account the configuration of the + camera module, which should be made before to configure and enable + the DCI to capture images. + + (#) Program the required configuration through following parameters: + horizontal and vertical polarity, pixel clock polarity, Capture Rate, + Synchronization Mode, code of the frame delimiter and data width + using DAL_DCI_Init() function. + + (#) Configure the DMA2_Stream1 channel1 to transfer Data from DCI DR + register to the destination memory buffer. + + (#) Program the required configuration through following parameters: + DCI mode, destination memory Buffer address and the data length + and enable capture using DAL_DCI_Start_DMA() function. + + (#) Optionally, configure and Enable the CROP feature to select a rectangular + window from the received image using DAL_DCI_ConfigCrop() + and DAL_DCI_EnableCROP() functions + + (#) The capture can be stopped using DAL_DCI_Stop() function. + + (#) To control DCI state you can use the function DAL_DCI_GetState(). + + *** DCI DAL driver macros list *** + ============================================= + [..] + Below the list of most used macros in DCI DAL driver. + + (+) __DAL_DCI_ENABLE: Enable the DCI peripheral. + (+) __DAL_DCI_DISABLE: Disable the DCI peripheral. + (+) __DAL_DCI_GET_FLAG: Get the DCI pending flags. + (+) __DAL_DCI_CLEAR_FLAG: Clear the DCI pending flags. + (+) __DAL_DCI_ENABLE_IT: Enable the specified DCI interrupts. + (+) __DAL_DCI_DISABLE_IT: Disable the specified DCI interrupts. + (+) __DAL_DCI_GET_IT_SOURCE: Check whether the specified DCI interrupt has occurred or not. + + [..] + (@) You can refer to the DCI DAL driver header file for more useful macros + + *** Callback registration *** + ============================= + + The compilation define USE_DAL_DCI_REGISTER_CALLBACKS when set to 1 + allows the user to configure dynamically the driver callbacks. + Use functions DAL_DCI_RegisterCallback() to register a user callback. + + Function DAL_DCI_RegisterCallback() allows to register following callbacks: + (+) FrameEventCallback : DCI Frame Event. + (+) VsyncEventCallback : DCI Vsync Event. + (+) LineEventCallback : DCI Line Event. + (+) ErrorCallback : DCI error. + (+) MspInitCallback : DCI MspInit. + (+) MspDeInitCallback : DCI MspDeInit. + This function takes as parameters the DAL peripheral handle, the callback ID + and a pointer to the user callback function. + + Use function DAL_DCI_UnRegisterCallback() to reset a callback to the default + weak (surcharged) function. + DAL_DCI_UnRegisterCallback() takes as parameters the DAL peripheral handle, + and the callback ID. + This function allows to reset following callbacks: + (+) FrameEventCallback : DCI Frame Event. + (+) VsyncEventCallback : DCI Vsync Event. + (+) LineEventCallback : DCI Line Event. + (+) ErrorCallback : DCI error. + (+) MspInitCallback : DCI MspInit. + (+) MspDeInitCallback : DCI MspDeInit. + + By default, after the DAL_DCI_Init and if the state is DAL_DCI_STATE_RESET + all callbacks are reset to the corresponding legacy weak (surcharged) functions: + examples FrameEventCallback(), DAL_DCI_ErrorCallback(). + Exception done for MspInit and MspDeInit callbacks that are respectively + reset to the legacy weak (surcharged) functions in the DAL_DCI_Init + and DAL_DCI_DeInit only when these callbacks are null (not registered beforehand). + If not, MspInit or MspDeInit are not null, the DAL_DCI_Init and DAL_DCI_DeInit + keep and use the user MspInit/MspDeInit callbacks (registered beforehand). + + Callbacks can be registered/unregistered in READY state only. + Exception done for MspInit/MspDeInit callbacks that can be registered/unregistered + in READY or RESET state, thus registered (user) MspInit/DeInit callbacks can be used + during the Init/DeInit. + In that case first register the MspInit/MspDeInit user callbacks + using DAL_DCI_RegisterCallback before calling DAL_DCI_DeInit + or DAL_DCI_Init function. + + When the compilation define USE_DAL_DCI_REGISTER_CALLBACKS is set to 0 or + not defined, the callback registering feature is not available + and weak (surcharged) callbacks are used. + + @endverbatim + * + */ + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ +/** @defgroup DCI DCI + * @brief DCI DAL module driver + * @{ + */ + +#ifdef DAL_DCI_MODULE_ENABLED + +#if defined(APM32F407xx) || defined(APM32F417xx) +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +#define DAL_TIMEOUT_DCI_STOP 14U /* Set timeout to 1s */ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +static void DCI_DMAXferCplt(DMA_HandleTypeDef *hdma); +static void DCI_DMAError(DMA_HandleTypeDef *hdma); + +/* Exported functions --------------------------------------------------------*/ + +/** @defgroup DCI_Exported_Functions DCI Exported Functions + * @{ + */ + +/** @defgroup DCI_Exported_Functions_Group1 Initialization and Configuration functions + * @brief Initialization and Configuration functions + * +@verbatim + =============================================================================== + ##### Initialization and Configuration functions ##### + =============================================================================== + [..] This section provides functions allowing to: + (+) Initialize and configure the DCI + (+) De-initialize the DCI + +@endverbatim + * @{ + */ + +/** + * @brief Initializes the DCI according to the specified + * parameters in the DCI_InitTypeDef and create the associated handle. + * @param hdci pointer to a DCI_HandleTypeDef structure that contains + * the configuration information for DCI. + * @retval DAL status + */ +__weak DAL_StatusTypeDef DAL_DCI_Init(DCI_HandleTypeDef *hdci) +{ + /* Check the DCI peripheral state */ + if(hdci == NULL) + { + return DAL_ERROR; + } + + /* Check function parameters */ + ASSERT_PARAM(IS_DCI_ALL_INSTANCE(hdci->Instance)); + ASSERT_PARAM(IS_DCI_PCKPOLARITY(hdci->Init.PCKPolarity)); + ASSERT_PARAM(IS_DCI_VSPOLARITY(hdci->Init.VSPolarity)); + ASSERT_PARAM(IS_DCI_HSPOLARITY(hdci->Init.HSPolarity)); + ASSERT_PARAM(IS_DCI_SYNCHRO(hdci->Init.SynchroMode)); + ASSERT_PARAM(IS_DCI_CAPTURE_RATE(hdci->Init.CaptureRate)); + ASSERT_PARAM(IS_DCI_EXTENDED_DATA(hdci->Init.ExtendedDataMode)); + ASSERT_PARAM(IS_DCI_MODE_JPEG(hdci->Init.JPEGMode)); + + if(hdci->State == DAL_DCI_STATE_RESET) + { + /* Allocate lock resource and initialize it */ + hdci->Lock = DAL_UNLOCKED; + /* Init the low level hardware */ + /* Init the DCI Callback settings */ +#if (USE_DAL_DCI_REGISTER_CALLBACKS == 1) + hdci->FrameEventCallback = DAL_DCI_FrameEventCallback; /* Legacy weak FrameEventCallback */ + hdci->VsyncEventCallback = DAL_DCI_VsyncEventCallback; /* Legacy weak VsyncEventCallback */ + hdci->LineEventCallback = DAL_DCI_LineEventCallback; /* Legacy weak LineEventCallback */ + hdci->ErrorCallback = DAL_DCI_ErrorCallback; /* Legacy weak ErrorCallback */ + + if(hdci->MspInitCallback == NULL) + { + /* Legacy weak MspInit Callback */ + hdci->MspInitCallback = DAL_DCI_MspInit; + } + /* Initialize the low level hardware (MSP) */ + hdci->MspInitCallback(hdci); +#else + /* Init the low level hardware : GPIO, CLOCK, NVIC and DMA */ + DAL_DCI_MspInit(hdci); +#endif /* (USE_DAL_DCI_REGISTER_CALLBACKS) */ + DAL_DCI_MspInit(hdci); + } + + /* Change the DCI state */ + hdci->State = DAL_DCI_STATE_BUSY; + + /* Set DCI parameters */ + /* Configures the HS, VS, DE and PC polarity */ + hdci->Instance->CTRL &= ~(DCI_CTRL_PXCLKPOL | DCI_CTRL_HSYNCPOL | DCI_CTRL_VSYNCPOL | DCI_CTRL_EXDMOD_0 | + DCI_CTRL_EXDMOD_1 | DCI_CTRL_FCRCFG_0 | DCI_CTRL_FCRCFG_1 | DCI_CTRL_JPGFM | + DCI_CTRL_ESYNCSEL); + hdci->Instance->CTRL |= (uint32_t)(hdci->Init.SynchroMode | hdci->Init.CaptureRate | \ + hdci->Init.VSPolarity | hdci->Init.HSPolarity | \ + hdci->Init.PCKPolarity | hdci->Init.ExtendedDataMode | \ + hdci->Init.JPEGMode); + + if(hdci->Init.SynchroMode == DCI_SYNCHRO_EMBEDDED) + { + hdci->Instance->ESYNCC = (((uint32_t)hdci->Init.SyncroCode.FrameStartCode) | + ((uint32_t)hdci->Init.SyncroCode.LineStartCode << DCI_POSITION_ESCR_LSC)| + ((uint32_t)hdci->Init.SyncroCode.LineEndCode << DCI_POSITION_ESCR_LEC) | + ((uint32_t)hdci->Init.SyncroCode.FrameEndCode << DCI_POSITION_ESCR_FEC)); + } + + /* Enable the Line, Vsync, Error and Overrun interrupts */ + __DAL_DCI_ENABLE_IT(hdci, DCI_IT_LINE | DCI_IT_VSYNC | DCI_IT_ERR | DCI_IT_OVR); + + /* Update error code */ + hdci->ErrorCode = DAL_DCI_ERROR_NONE; + + /* Initialize the DCI state*/ + hdci->State = DAL_DCI_STATE_READY; + + return DAL_OK; +} + +/** + * @brief Deinitializes the DCI peripheral registers to their default reset + * values. + * @param hdci pointer to a DCI_HandleTypeDef structure that contains + * the configuration information for DCI. + * @retval DAL status + */ + +DAL_StatusTypeDef DAL_DCI_DeInit(DCI_HandleTypeDef *hdci) +{ +#if (USE_DAL_DCI_REGISTER_CALLBACKS == 1) + if(hdci->MspDeInitCallback == NULL) + { + hdci->MspDeInitCallback = DAL_DCI_MspDeInit; + } + /* De-Initialize the low level hardware (MSP) */ + hdci->MspDeInitCallback(hdci); +#else + /* DeInit the low level hardware: GPIO, CLOCK, NVIC and DMA */ + DAL_DCI_MspDeInit(hdci); +#endif /* (USE_DAL_DCI_REGISTER_CALLBACKS) */ + + /* Update error code */ + hdci->ErrorCode = DAL_DCI_ERROR_NONE; + + /* Initialize the DCI state*/ + hdci->State = DAL_DCI_STATE_RESET; + + /* Release Lock */ + __DAL_UNLOCK(hdci); + + return DAL_OK; +} + +/** + * @brief Initializes the DCI MSP. + * @param hdci pointer to a DCI_HandleTypeDef structure that contains + * the configuration information for DCI. + * @retval None + */ +__weak void DAL_DCI_MspInit(DCI_HandleTypeDef* hdci) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hdci); + /* NOTE : This function Should not be modified, when the callback is needed, + the DAL_DCI_MspInit could be implemented in the user file + */ +} + +/** + * @brief DeInitializes the DCI MSP. + * @param hdci pointer to a DCI_HandleTypeDef structure that contains + * the configuration information for DCI. + * @retval None + */ +__weak void DAL_DCI_MspDeInit(DCI_HandleTypeDef* hdci) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hdci); + /* NOTE : This function Should not be modified, when the callback is needed, + the DAL_DCI_MspDeInit could be implemented in the user file + */ +} + +/** + * @} + */ +/** @defgroup DCI_Exported_Functions_Group2 IO operation functions + * @brief IO operation functions + * +@verbatim + =============================================================================== + ##### IO operation functions ##### + =============================================================================== + [..] This section provides functions allowing to: + (+) Configure destination address and data length and + Enables DCI DMA request and enables DCI capture + (+) Stop the DCI capture. + (+) Handles DCI interrupt request. + +@endverbatim + * @{ + */ + +/** + * @brief Enables DCI DMA request and enables DCI capture + * @param hdci pointer to a DCI_HandleTypeDef structure that contains + * the configuration information for DCI. + * @param DCI_Mode DCI capture mode snapshot or continuous grab. + * @param pData The destination memory Buffer address (LCD Frame buffer). + * @param Length The length of capture to be transferred. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_DCI_Start_DMA(DCI_HandleTypeDef* hdci, uint32_t DCI_Mode, uint32_t pData, uint32_t Length) +{ + /* Initialize the second memory address */ + uint32_t SecondMemAddress = 0U; + + /* Check function parameters */ + ASSERT_PARAM(IS_DCI_CAPTURE_MODE(DCI_Mode)); + + /* Process Locked */ + __DAL_LOCK(hdci); + + /* Lock the DCI peripheral state */ + hdci->State = DAL_DCI_STATE_BUSY; + + /* Enable DCI by setting DCIEN bit */ + __DAL_DCI_ENABLE(hdci); + + /* Configure the DCI Mode */ + hdci->Instance->CTRL &= ~(DCI_CTRL_CMODE); + hdci->Instance->CTRL |= (uint32_t)(DCI_Mode); + + /* Set the DMA memory0 conversion complete callback */ + hdci->DMA_Handle->XferCpltCallback = DCI_DMAXferCplt; + + /* Set the DMA error callback */ + hdci->DMA_Handle->XferErrorCallback = DCI_DMAError; + + /* Set the dma abort callback */ + hdci->DMA_Handle->XferAbortCallback = NULL; + + /* Reset transfer counters value */ + hdci->XferCount = 0U; + hdci->XferTransferNumber = 0U; + + if(Length <= 0xFFFFU) + { + /* Enable the DMA Stream */ + DAL_DMA_Start_IT(hdci->DMA_Handle, (uint32_t)&hdci->Instance->DATA, (uint32_t)pData, Length); + } + else /* DCI_DOUBLE_BUFFER Mode */ + { + /* Set the DMA memory1 conversion complete callback */ + hdci->DMA_Handle->XferM1CpltCallback = DCI_DMAXferCplt; + + /* Initialize transfer parameters */ + hdci->XferCount = 1U; + hdci->XferSize = Length; + hdci->pBuffPtr = pData; + + /* Get the number of buffer */ + while(hdci->XferSize > 0xFFFFU) + { + hdci->XferSize = (hdci->XferSize/2U); + hdci->XferCount = hdci->XferCount*2U; + } + + /* Update DCI counter and transfer number*/ + hdci->XferCount = (hdci->XferCount - 2U); + hdci->XferTransferNumber = hdci->XferCount; + + /* Update second memory address */ + SecondMemAddress = (uint32_t)(pData + (4U*hdci->XferSize)); + + /* Start DMA multi buffer transfer */ + DAL_DMAEx_MultiBufferStart_IT(hdci->DMA_Handle, (uint32_t)&hdci->Instance->DATA, (uint32_t)pData, SecondMemAddress, hdci->XferSize); + } + + /* Enable Capture */ + hdci->Instance->CTRL |= DCI_CTRL_CEN; + + /* Release Lock */ + __DAL_UNLOCK(hdci); + + /* Return function status */ + return DAL_OK; +} + +/** + * @brief Disable DCI DMA request and Disable DCI capture + * @param hdci pointer to a DCI_HandleTypeDef structure that contains + * the configuration information for DCI. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_DCI_Stop(DCI_HandleTypeDef* hdci) +{ + __IO uint32_t count = SystemCoreClock / DAL_TIMEOUT_DCI_STOP; + DAL_StatusTypeDef status = DAL_OK; + + /* Process locked */ + __DAL_LOCK(hdci); + + /* Lock the DCI peripheral state */ + hdci->State = DAL_DCI_STATE_BUSY; + + /* Disable Capture */ + hdci->Instance->CTRL &= ~(DCI_CTRL_CEN); + + /* Check if the DCI capture effectively disabled */ + do + { + if (count-- == 0U) + { + /* Update error code */ + hdci->ErrorCode |= DAL_DCI_ERROR_TIMEOUT; + + status = DAL_TIMEOUT; + break; + } + } + while((hdci->Instance->CTRL & DCI_CTRL_CEN) != 0U); + + /* Disable the DCI */ + __DAL_DCI_DISABLE(hdci); + + /* Disable the DMA */ + DAL_DMA_Abort(hdci->DMA_Handle); + + /* Update error code */ + hdci->ErrorCode |= DAL_DCI_ERROR_NONE; + + /* Change DCI state */ + hdci->State = DAL_DCI_STATE_READY; + + /* Process Unlocked */ + __DAL_UNLOCK(hdci); + + /* Return function status */ + return status; +} + +/** + * @brief Suspend DCI capture + * @param hdci pointer to a DCI_HandleTypeDef structure that contains + * the configuration information for DCI. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_DCI_Suspend(DCI_HandleTypeDef* hdci) +{ + __IO uint32_t count = SystemCoreClock / DAL_TIMEOUT_DCI_STOP; + DAL_StatusTypeDef status = DAL_OK; + + /* Process locked */ + __DAL_LOCK(hdci); + + if(hdci->State == DAL_DCI_STATE_BUSY) + { + /* Change DCI state */ + hdci->State = DAL_DCI_STATE_SUSPENDED; + + /* Disable Capture */ + hdci->Instance->CTRL &= ~(DCI_CTRL_CEN); + + /* Check if the DCI capture effectively disabled */ + do + { + if (count-- == 0U) + { + /* Update error code */ + hdci->ErrorCode |= DAL_DCI_ERROR_TIMEOUT; + + /* Change DCI state */ + hdci->State = DAL_DCI_STATE_READY; + + status = DAL_TIMEOUT; + break; + } + } + while((hdci->Instance->CTRL & DCI_CTRL_CEN) != 0); + } + /* Process Unlocked */ + __DAL_UNLOCK(hdci); + + /* Return function status */ + return status; +} + +/** + * @brief Resume DCI capture + * @param hdci pointer to a DCI_HandleTypeDef structure that contains + * the configuration information for DCI. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_DCI_Resume(DCI_HandleTypeDef* hdci) +{ + /* Process locked */ + __DAL_LOCK(hdci); + + if(hdci->State == DAL_DCI_STATE_SUSPENDED) + { + /* Change DCI state */ + hdci->State = DAL_DCI_STATE_BUSY; + + /* Disable Capture */ + hdci->Instance->CTRL |= DCI_CTRL_CEN; + } + /* Process Unlocked */ + __DAL_UNLOCK(hdci); + + /* Return function status */ + return DAL_OK; +} + +/** + * @brief Handles DCI interrupt request. + * @param hdci pointer to a DCI_HandleTypeDef structure that contains + * the configuration information for the DCI. + * @retval None + */ +void DAL_DCI_IRQHandler(DCI_HandleTypeDef *hdci) +{ + uint32_t isr_value = READ_REG(hdci->Instance->MINTSTS); + + /* Synchronization error interrupt management *******************************/ + if((isr_value & DCI_FLAG_ERRRI) == DCI_FLAG_ERRRI) + { + /* Clear the Synchronization error flag */ + __DAL_DCI_CLEAR_FLAG(hdci, DCI_FLAG_ERRRI); + + /* Update error code */ + hdci->ErrorCode |= DAL_DCI_ERROR_SYNC; + + /* Change DCI state */ + hdci->State = DAL_DCI_STATE_ERROR; + + /* Set the synchronization error callback */ + hdci->DMA_Handle->XferAbortCallback = DCI_DMAError; + + /* Abort the DMA Transfer */ + DAL_DMA_Abort_IT(hdci->DMA_Handle); + } + /* Overflow interrupt management ********************************************/ + if((isr_value & DCI_FLAG_OVRRI) == DCI_FLAG_OVRRI) + { + /* Clear the Overflow flag */ + __DAL_DCI_CLEAR_FLAG(hdci, DCI_FLAG_OVRRI); + + /* Update error code */ + hdci->ErrorCode |= DAL_DCI_ERROR_OVR; + + /* Change DCI state */ + hdci->State = DAL_DCI_STATE_ERROR; + + /* Set the overflow callback */ + hdci->DMA_Handle->XferAbortCallback = DCI_DMAError; + + /* Abort the DMA Transfer */ + DAL_DMA_Abort_IT(hdci->DMA_Handle); + } + /* Line Interrupt management ************************************************/ + if((isr_value & DCI_FLAG_LINERI) == DCI_FLAG_LINERI) + { + /* Clear the Line interrupt flag */ + __DAL_DCI_CLEAR_FLAG(hdci, DCI_FLAG_LINERI); + + /* Line interrupt Callback */ +#if (USE_DAL_DCI_REGISTER_CALLBACKS == 1) + /*Call registered DCI line event callback*/ + hdci->LineEventCallback(hdci); +#else + DAL_DCI_LineEventCallback(hdci); +#endif /* USE_DAL_DCI_REGISTER_CALLBACKS */ + } + /* VSYNC interrupt management ***********************************************/ + if((isr_value & DCI_FLAG_VSYNCRI) == DCI_FLAG_VSYNCRI) + { + /* Clear the VSYNCRI flag */ + __DAL_DCI_CLEAR_FLAG(hdci, DCI_FLAG_VSYNCRI); + + /* VSYNC Callback */ +#if (USE_DAL_DCI_REGISTER_CALLBACKS == 1) + /*Call registered DCI vsync event callback*/ + hdci->VsyncEventCallback(hdci); +#else + DAL_DCI_VsyncEventCallback(hdci); +#endif /* USE_DAL_DCI_REGISTER_CALLBACKS */ + } + /* FRAME interrupt management ***********************************************/ + if((isr_value & DCI_FLAG_FRAMERI) == DCI_FLAG_FRAMERI) + { + /* When snapshot mode, disable Vsync, Error and Overrun interrupts */ + if((hdci->Instance->CTRL & DCI_CTRL_CMODE) == DCI_MODE_SNAPSHOT) + { + /* Disable the Line, Vsync, Error and Overrun interrupts */ + __DAL_DCI_DISABLE_IT(hdci, DCI_IT_LINE | DCI_IT_VSYNC | DCI_IT_ERR | DCI_IT_OVR); + } + + /* Disable the Frame interrupt */ + __DAL_DCI_DISABLE_IT(hdci, DCI_IT_FRAME); + + /* Frame Callback */ +#if (USE_DAL_DCI_REGISTER_CALLBACKS == 1) + /*Call registered DCI frame event callback*/ + hdci->FrameEventCallback(hdci); +#else + DAL_DCI_FrameEventCallback(hdci); +#endif /* USE_DAL_DCI_REGISTER_CALLBACKS */ + } +} + +/** + * @brief Error DCI callback. + * @param hdci pointer to a DCI_HandleTypeDef structure that contains + * the configuration information for DCI. + * @retval None + */ +__weak void DAL_DCI_ErrorCallback(DCI_HandleTypeDef *hdci) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hdci); + /* NOTE : This function Should not be modified, when the callback is needed, + the DAL_DCI_ErrorCallback could be implemented in the user file + */ +} + +/** + * @brief Line Event callback. + * @param hdci pointer to a DCI_HandleTypeDef structure that contains + * the configuration information for DCI. + * @retval None + */ +__weak void DAL_DCI_LineEventCallback(DCI_HandleTypeDef *hdci) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hdci); + /* NOTE : This function Should not be modified, when the callback is needed, + the DAL_DCI_LineEventCallback could be implemented in the user file + */ +} + +/** + * @brief VSYNC Event callback. + * @param hdci pointer to a DCI_HandleTypeDef structure that contains + * the configuration information for DCI. + * @retval None + */ +__weak void DAL_DCI_VsyncEventCallback(DCI_HandleTypeDef *hdci) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hdci); + /* NOTE : This function Should not be modified, when the callback is needed, + the DAL_DCI_VsyncEventCallback could be implemented in the user file + */ +} + +/** + * @brief Frame Event callback. + * @param hdci pointer to a DCI_HandleTypeDef structure that contains + * the configuration information for DCI. + * @retval None + */ +__weak void DAL_DCI_FrameEventCallback(DCI_HandleTypeDef *hdci) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hdci); + /* NOTE : This function Should not be modified, when the callback is needed, + the DAL_DCI_FrameEventCallback could be implemented in the user file + */ +} + +/** + * @} + */ + +/** @defgroup DCI_Exported_Functions_Group3 Peripheral Control functions + * @brief Peripheral Control functions + * +@verbatim + =============================================================================== + ##### Peripheral Control functions ##### + =============================================================================== +[..] This section provides functions allowing to: + (+) Configure the CROP feature. + (+) Enable/Disable the CROP feature. + +@endverbatim + * @{ + */ + +/** + * @brief Configure the DCI CROP coordinate. + * @param hdci pointer to a DCI_HandleTypeDef structure that contains + * the configuration information for DCI. + * @param X0 DCI window X offset + * @param Y0 DCI window Y offset + * @param XSize DCI Pixel per line + * @param YSize DCI Line number + * @retval DAL status + */ +DAL_StatusTypeDef DAL_DCI_ConfigCrop(DCI_HandleTypeDef *hdci, uint32_t X0, uint32_t Y0, uint32_t XSize, uint32_t YSize) +{ + /* Process Locked */ + __DAL_LOCK(hdci); + + /* Lock the DCI peripheral state */ + hdci->State = DAL_DCI_STATE_BUSY; + + /* Check the parameters */ + ASSERT_PARAM(IS_DCI_WINDOW_COORDINATE(X0)); + ASSERT_PARAM(IS_DCI_WINDOW_COORDINATE(YSize)); + ASSERT_PARAM(IS_DCI_WINDOW_COORDINATE(XSize)); + ASSERT_PARAM(IS_DCI_WINDOW_HEIGHT(Y0)); + + /* Configure CROP */ + hdci->Instance->CROPWSIZE = (XSize | (YSize << DCI_POSITION_CWSIZE_VLINE)); + hdci->Instance->CROPWSTAT = (X0 | (Y0 << DCI_POSITION_CWSTRT_VST)); + + /* Initialize the DCI state*/ + hdci->State = DAL_DCI_STATE_READY; + + /* Process Unlocked */ + __DAL_UNLOCK(hdci); + + return DAL_OK; +} + +/** + * @brief Disable the Crop feature. + * @param hdci pointer to a DCI_HandleTypeDef structure that contains + * the configuration information for DCI. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_DCI_DisableCrop(DCI_HandleTypeDef *hdci) +{ + /* Process Locked */ + __DAL_LOCK(hdci); + + /* Lock the DCI peripheral state */ + hdci->State = DAL_DCI_STATE_BUSY; + + /* Disable DCI Crop feature */ + hdci->Instance->CTRL &= ~(uint32_t)DCI_CTRL_CROPF; + + /* Change the DCI state*/ + hdci->State = DAL_DCI_STATE_READY; + + /* Process Unlocked */ + __DAL_UNLOCK(hdci); + + return DAL_OK; +} + +/** + * @brief Enable the Crop feature. + * @param hdci pointer to a DCI_HandleTypeDef structure that contains + * the configuration information for DCI. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_DCI_EnableCrop(DCI_HandleTypeDef *hdci) +{ + /* Process Locked */ + __DAL_LOCK(hdci); + + /* Lock the DCI peripheral state */ + hdci->State = DAL_DCI_STATE_BUSY; + + /* Enable DCI Crop feature */ + hdci->Instance->CTRL |= (uint32_t)DCI_CTRL_CROPF; + + /* Change the DCI state*/ + hdci->State = DAL_DCI_STATE_READY; + + /* Process Unlocked */ + __DAL_UNLOCK(hdci); + + return DAL_OK; +} + +/** + * @brief Set embedded synchronization delimiters unmasks. + * @param hdci pointer to a DCI_HandleTypeDef structure that contains + * the configuration information for DCI. + * @param SyncUnmask pointer to a DCI_SyncUnmaskTypeDef structure that contains + * the embedded synchronization delimiters unmasks. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_DCI_ConfigSyncUnmask(DCI_HandleTypeDef *hdci, DCI_SyncUnmaskTypeDef *SyncUnmask) +{ + /* Process Locked */ + __DAL_LOCK(hdci); + + /* Lock the DCI peripheral state */ + hdci->State = DAL_DCI_STATE_BUSY; + + /* Write DCI embedded synchronization unmask register */ + hdci->Instance->ESYNCUM = (((uint32_t)SyncUnmask->FrameStartUnmask) |\ + ((uint32_t)SyncUnmask->LineStartUnmask << DCI_ESYNCUM_LSDUM_Pos)|\ + ((uint32_t)SyncUnmask->LineEndUnmask << DCI_ESYNCUM_LEDUM_Pos)|\ + ((uint32_t)SyncUnmask->FrameEndUnmask << DCI_ESYNCUM_FEDUM_Pos)); + + /* Change the DCI state*/ + hdci->State = DAL_DCI_STATE_READY; + + /* Process Unlocked */ + __DAL_UNLOCK(hdci); + + return DAL_OK; +} + +/** + * @} + */ + +/** @defgroup DCI_Exported_Functions_Group4 Peripheral State functions + * @brief Peripheral State functions + * +@verbatim + =============================================================================== + ##### Peripheral State and Errors functions ##### + =============================================================================== + [..] + This subsection provides functions allowing to + (+) Check the DCI state. + (+) Get the specific DCI error flag. + +@endverbatim + * @{ + */ + +/** + * @brief Return the DCI state + * @param hdci pointer to a DCI_HandleTypeDef structure that contains + * the configuration information for DCI. + * @retval DAL state + */ +DAL_DCI_StateTypeDef DAL_DCI_GetState(DCI_HandleTypeDef *hdci) +{ + return hdci->State; +} + +/** + * @brief Return the DCI error code + * @param hdci pointer to a DCI_HandleTypeDef structure that contains + * the configuration information for DCI. + * @retval DCI Error Code + */ +uint32_t DAL_DCI_GetError(DCI_HandleTypeDef *hdci) +{ + return hdci->ErrorCode; +} + +#if (USE_DAL_DCI_REGISTER_CALLBACKS == 1) +/** + * @brief DCI Callback registering + * @param hdci pointer to a DCI_HandleTypeDef structure that contains + * the configuration information for DCI. + * @param CallbackID dci Callback ID + * @param pCallback pointer to DCI_CallbackTypeDef structure + * @retval status + */ +DAL_StatusTypeDef DAL_DCI_RegisterCallback(DCI_HandleTypeDef *hdci, DAL_DCI_CallbackIDTypeDef CallbackID, pDCI_CallbackTypeDef pCallback) +{ + DAL_StatusTypeDef status = DAL_OK; + + if(pCallback == NULL) + { + /* update the error code */ + hdci->ErrorCode |= DAL_DCI_ERROR_INVALID_CALLBACK; + /* update return status */ + status = DAL_ERROR; + } + else + { + if(hdci->State == DAL_DCI_STATE_READY) + { + switch (CallbackID) + { + case DAL_DCI_FRAME_EVENT_CB_ID : + hdci->FrameEventCallback = pCallback; + break; + + case DAL_DCI_VSYNC_EVENT_CB_ID : + hdci->VsyncEventCallback = pCallback; + break; + + case DAL_DCI_LINE_EVENT_CB_ID : + hdci->LineEventCallback = pCallback; + break; + + case DAL_DCI_ERROR_CB_ID : + hdci->ErrorCallback = pCallback; + break; + + case DAL_DCI_MSPINIT_CB_ID : + hdci->MspInitCallback = pCallback; + break; + + case DAL_DCI_MSPDEINIT_CB_ID : + hdci->MspDeInitCallback = pCallback; + break; + + default : + /* Return error status */ + status = DAL_ERROR; + break; + } + } + else if(hdci->State == DAL_DCI_STATE_RESET) + { + switch (CallbackID) + { + case DAL_DCI_MSPINIT_CB_ID : + hdci->MspInitCallback = pCallback; + break; + + case DAL_DCI_MSPDEINIT_CB_ID : + hdci->MspDeInitCallback = pCallback; + break; + + default : + /* update the error code */ + hdci->ErrorCode |= DAL_DCI_ERROR_INVALID_CALLBACK; + /* update return status */ + status = DAL_ERROR; + break; + } + } + else + { + /* update the error code */ + hdci->ErrorCode |= DAL_DCI_ERROR_INVALID_CALLBACK; + /* update return status */ + status = DAL_ERROR; + } + } + + return status; +} + +/** + * @brief DCI Callback Unregistering + * @param hdci dci handle + * @param CallbackID dci Callback ID + * @retval status + */ +DAL_StatusTypeDef DAL_DCI_UnRegisterCallback(DCI_HandleTypeDef *hdci, DAL_DCI_CallbackIDTypeDef CallbackID) +{ + DAL_StatusTypeDef status = DAL_OK; + + if(hdci->State == DAL_DCI_STATE_READY) + { + switch (CallbackID) + { + case DAL_DCI_FRAME_EVENT_CB_ID : + hdci->FrameEventCallback = DAL_DCI_FrameEventCallback; /* Legacy weak FrameEventCallback */ + break; + + case DAL_DCI_VSYNC_EVENT_CB_ID : + hdci->VsyncEventCallback = DAL_DCI_VsyncEventCallback; /* Legacy weak VsyncEventCallback */ + break; + + case DAL_DCI_LINE_EVENT_CB_ID : + hdci->LineEventCallback = DAL_DCI_LineEventCallback; /* Legacy weak LineEventCallback */ + break; + + case DAL_DCI_ERROR_CB_ID : + hdci->ErrorCallback = DAL_DCI_ErrorCallback; /* Legacy weak ErrorCallback */ + break; + + case DAL_DCI_MSPINIT_CB_ID : + hdci->MspInitCallback = DAL_DCI_MspInit; + break; + + case DAL_DCI_MSPDEINIT_CB_ID : + hdci->MspDeInitCallback = DAL_DCI_MspDeInit; + break; + + default : + /* update the error code */ + hdci->ErrorCode |= DAL_DCI_ERROR_INVALID_CALLBACK; + /* update return status */ + status = DAL_ERROR; + break; + } + } + else if(hdci->State == DAL_DCI_STATE_RESET) + { + switch (CallbackID) + { + case DAL_DCI_MSPINIT_CB_ID : + hdci->MspInitCallback = DAL_DCI_MspInit; + break; + + case DAL_DCI_MSPDEINIT_CB_ID : + hdci->MspDeInitCallback = DAL_DCI_MspDeInit; + break; + + default : + /* update the error code */ + hdci->ErrorCode |= DAL_DCI_ERROR_INVALID_CALLBACK; + /* update return status */ + status = DAL_ERROR; + break; + } + } + else + { + /* update the error code */ + hdci->ErrorCode |= DAL_DCI_ERROR_INVALID_CALLBACK; + /* update return status */ + status = DAL_ERROR; + } + + return status; +} +#endif /* USE_DAL_DCI_REGISTER_CALLBACKS */ + +/** + * @} + */ +/* Private functions ---------------------------------------------------------*/ +/** @defgroup DCI_Private_Functions DCI Private Functions + * @{ + */ + +/** + * @brief DMA conversion complete callback. + * @param hdma pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +static void DCI_DMAXferCplt(DMA_HandleTypeDef *hdma) +{ + uint32_t tmp = 0U; + + DCI_HandleTypeDef* hdci = ( DCI_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + + if(hdci->XferCount != 0U) + { + /* Update memory 0 address location */ + tmp = ((hdci->DMA_Handle->Instance->SCFG) & DMA_SCFGx_CTARG); + if(((hdci->XferCount % 2U) == 0U) && (tmp != 0U)) + { + tmp = hdci->DMA_Handle->Instance->M0ADDR; + DAL_DMAEx_ChangeMemory(hdci->DMA_Handle, (tmp + (8U*hdci->XferSize)), MEMORY0); + hdci->XferCount--; + } + /* Update memory 1 address location */ + else if((hdci->DMA_Handle->Instance->SCFG & DMA_SCFGx_CTARG) == 0U) + { + tmp = hdci->DMA_Handle->Instance->M1ADDR; + DAL_DMAEx_ChangeMemory(hdci->DMA_Handle, (tmp + (8U*hdci->XferSize)), MEMORY1); + hdci->XferCount--; + } + } + /* Update memory 0 address location */ + else if((hdci->DMA_Handle->Instance->SCFG & DMA_SCFGx_CTARG) != 0U) + { + hdci->DMA_Handle->Instance->M0ADDR = hdci->pBuffPtr; + } + /* Update memory 1 address location */ + else if((hdci->DMA_Handle->Instance->SCFG & DMA_SCFGx_CTARG) == 0U) + { + tmp = hdci->pBuffPtr; + hdci->DMA_Handle->Instance->M1ADDR = (tmp + (4U*hdci->XferSize)); + hdci->XferCount = hdci->XferTransferNumber; + } + + /* Check if the frame is transferred */ + if(hdci->XferCount == hdci->XferTransferNumber) + { + /* Enable the Frame interrupt */ + __DAL_DCI_ENABLE_IT(hdci, DCI_IT_FRAME); + + /* When snapshot mode, set dci state to ready */ + if((hdci->Instance->CTRL & DCI_CTRL_CMODE) == DCI_MODE_SNAPSHOT) + { + hdci->State= DAL_DCI_STATE_READY; + } + } +} + +/** + * @brief DMA error callback + * @param hdma pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +static void DCI_DMAError(DMA_HandleTypeDef *hdma) +{ + DCI_HandleTypeDef* hdci = ( DCI_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + + if(hdci->DMA_Handle->ErrorCode != DAL_DMA_ERROR_FE) + { + /* Initialize the DCI state*/ + hdci->State = DAL_DCI_STATE_READY; + } + + /* DCI error Callback */ +#if (USE_DAL_DCI_REGISTER_CALLBACKS == 1) + /*Call registered DCI error callback*/ + hdci->ErrorCallback(hdci); +#else + DAL_DCI_ErrorCallback(hdci); +#endif /* USE_DAL_DCI_REGISTER_CALLBACKS */ + +} + +/** + * @} + */ + +/** + * @} + */ +#endif /* APM32F407xx || APM32F417xx */ +#endif /* DAL_DCI_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_dci_ex.c b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_dci_ex.c new file mode 100644 index 0000000000..04baef2b8b --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_dci_ex.c @@ -0,0 +1,191 @@ +/** + * + * @file apm32f4xx_dal_dci_ex.c + * @brief DCI Extension DAL module driver + * This file provides firmware functions to manage the following + * functionalities of DCI extension peripheral: + * + Extension features functions + * + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2017 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file in + * the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + @verbatim + ============================================================================== + ##### DCI peripheral extension features ##### + ============================================================================== + + [..] Comparing to other previous devices, the DCI interface for APM32F446xx + devices contains the following additional features : + + (+) Support of Black and White cameras + + ##### How to use this driver ##### + ============================================================================== + [..] This driver provides functions to manage the Black and White feature + + @endverbatim + * + */ + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ +/** @defgroup DCIEx DCIEx + * @brief DCI Extended DAL module driver + * @{ + */ + +#ifdef DAL_DCI_MODULE_ENABLED + +#if defined(APM32F407xx) || defined(APM32F417xx) +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Exported functions --------------------------------------------------------*/ + +/** @defgroup DCIEx_Exported_Functions DCI Extended Exported Functions + * @{ + */ + +/** + * @} + */ + +/** @addtogroup DCI_Exported_Functions_Group1 Initialization and Configuration functions + * @{ + */ + +/** + * @brief Initializes the DCI according to the specified + * parameters in the DCI_InitTypeDef and create the associated handle. + * @param hdcmi pointer to a DCI_HandleTypeDef structure that contains + * the configuration information for DCI. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_DCI_Init(DCI_HandleTypeDef *hdcmi) +{ + /* Check the DCI peripheral state */ + if(hdcmi == NULL) + { + return DAL_ERROR; + } + + /* Check function parameters */ + ASSERT_PARAM(IS_DCI_ALL_INSTANCE(hdcmi->Instance)); + ASSERT_PARAM(IS_DCI_PCKPOLARITY(hdcmi->Init.PCKPolarity)); + ASSERT_PARAM(IS_DCI_VSPOLARITY(hdcmi->Init.VSPolarity)); + ASSERT_PARAM(IS_DCI_HSPOLARITY(hdcmi->Init.HSPolarity)); + ASSERT_PARAM(IS_DCI_SYNCHRO(hdcmi->Init.SynchroMode)); + ASSERT_PARAM(IS_DCI_CAPTURE_RATE(hdcmi->Init.CaptureRate)); + ASSERT_PARAM(IS_DCI_EXTENDED_DATA(hdcmi->Init.ExtendedDataMode)); + ASSERT_PARAM(IS_DCI_MODE_JPEG(hdcmi->Init.JPEGMode)); + + if(hdcmi->State == DAL_DCI_STATE_RESET) + { + /* Allocate lock resource and initialize it */ + hdcmi->Lock = DAL_UNLOCKED; + /* Init the low level hardware */ + /* Init the DCI Callback settings */ +#if (USE_DAL_DCI_REGISTER_CALLBACKS == 1) + hdcmi->FrameEventCallback = DAL_DCI_FrameEventCallback; /* Legacy weak FrameEventCallback */ + hdcmi->VsyncEventCallback = DAL_DCI_VsyncEventCallback; /* Legacy weak VsyncEventCallback */ + hdcmi->LineEventCallback = DAL_DCI_LineEventCallback; /* Legacy weak LineEventCallback */ + hdcmi->ErrorCallback = DAL_DCI_ErrorCallback; /* Legacy weak ErrorCallback */ + + if(hdcmi->MspInitCallback == NULL) + { + /* Legacy weak MspInit Callback */ + hdcmi->MspInitCallback = DAL_DCI_MspInit; + } + /* Initialize the low level hardware (MSP) */ + hdcmi->MspInitCallback(hdcmi); +#else + /* Init the low level hardware : GPIO, CLOCK, NVIC and DMA */ + DAL_DCI_MspInit(hdcmi); +#endif /* (USE_DAL_DCI_REGISTER_CALLBACKS) */ + DAL_DCI_MspInit(hdcmi); + } + + /* Change the DCI state */ + hdcmi->State = DAL_DCI_STATE_BUSY; + /* Configures the HS, VS, DE and PC polarity */ + hdcmi->Instance->CTRL &= ~(DCI_CTRL_PXCLKPOL | DCI_CTRL_HSYNCPOL | DCI_CTRL_VSYNCPOL | DCI_CTRL_EXDMOD_0 |\ + DCI_CTRL_EXDMOD_1 | DCI_CTRL_FCRCFG_0 | DCI_CTRL_FCRCFG_1 | DCI_CTRL_JPGFM |\ + DCI_CTRL_ESYNCSEL + ); + hdcmi->Instance->CTRL |= (uint32_t)(hdcmi->Init.SynchroMode | hdcmi->Init.CaptureRate |\ + hdcmi->Init.VSPolarity | hdcmi->Init.HSPolarity |\ + hdcmi->Init.PCKPolarity | hdcmi->Init.ExtendedDataMode |\ + hdcmi->Init.JPEGMode + ); + if(hdcmi->Init.SynchroMode == DCI_SYNCHRO_EMBEDDED) + { + hdcmi->Instance->ESYNCC = (((uint32_t)hdcmi->Init.SyncroCode.FrameStartCode) | + ((uint32_t)hdcmi->Init.SyncroCode.LineStartCode << DCI_POSITION_ESCR_LSC)| + ((uint32_t)hdcmi->Init.SyncroCode.LineEndCode << DCI_POSITION_ESCR_LEC) | + ((uint32_t)hdcmi->Init.SyncroCode.FrameEndCode << DCI_POSITION_ESCR_FEC)); + + } + + /* Enable the Line, Vsync, Error and Overrun interrupts */ + __DAL_DCI_ENABLE_IT(hdcmi, DCI_IT_LINE | DCI_IT_VSYNC | DCI_IT_ERR | DCI_IT_OVR); + + /* Update error code */ + hdcmi->ErrorCode = DAL_DCI_ERROR_NONE; + + /* Initialize the DCI state*/ + hdcmi->State = DAL_DCI_STATE_READY; + + return DAL_OK; +} + +/** + * @} + */ +#endif /* APM32F407xx || APM32F417xx */ +#endif /* DAL_DCI_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_dma.c b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_dma.c new file mode 100644 index 0000000000..6fc0aaa283 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_dma.c @@ -0,0 +1,1330 @@ +/** + * + * @file apm32f4xx_dal_dma.c + * @brief DMA DAL module driver. + * + * This file provides firmware functions to manage the following + * functionalities of the Direct Memory Access (DMA) peripheral: + * + Initialization and de-initialization functions + * + IO operation functions + * + Peripheral State and errors functions + @verbatim + ============================================================================== + ##### How to use this driver ##### + ============================================================================== + [..] + (#) Enable and configure the peripheral to be connected to the DMA Stream + (except for internal SRAM/FLASH memories: no initialization is + necessary) please refer to Reference manual for connection between peripherals + and DMA requests. + + (#) For a given Stream, program the required configuration through the following parameters: + Transfer Direction, Source and Destination data formats, + Circular, Normal or peripheral flow control mode, Stream Priority level, + Source and Destination Increment mode, FIFO mode and its Threshold (if needed), + Burst mode for Source and/or Destination (if needed) using DAL_DMA_Init() function. + + -@- Prior to DAL_DMA_Init() the clock must be enabled for DMA through the following macros: + __DAL_RCM_DMA1_CLK_ENABLE() or __DAL_RCM_DMA2_CLK_ENABLE(). + + *** Polling mode IO operation *** + ================================= + [..] + (+) Use DAL_DMA_Start() to start DMA transfer after the configuration of Source + address and destination address and the Length of data to be transferred. + (+) Use DAL_DMA_PollForTransfer() to poll for the end of current transfer, in this + case a fixed Timeout can be configured by User depending from his application. + (+) Use DAL_DMA_Abort() function to abort the current transfer. + + *** Interrupt mode IO operation *** + =================================== + [..] + (+) Configure the DMA interrupt priority using DAL_NVIC_SetPriority() + (+) Enable the DMA IRQ handler using DAL_NVIC_EnableIRQ() + (+) Use DAL_DMA_Start_IT() to start DMA transfer after the configuration of + Source address and destination address and the Length of data to be transferred. In this + case the DMA interrupt is configured + (+) Use DAL_DMA_IRQHandler() called under DMA_IRQHandler() Interrupt subroutine + (+) At the end of data transfer DAL_DMA_IRQHandler() function is executed and user can + add his own function by customization of function pointer XferCpltCallback and + XferErrorCallback (i.e a member of DMA handle structure). + [..] + (#) Use DAL_DMA_GetState() function to return the DMA state and DAL_DMA_GetError() in case of error + detection. + + (#) Use DAL_DMA_Abort_IT() function to abort the current transfer + + -@- In Memory-to-Memory transfer mode, Circular mode is not allowed. + + -@- The FIFO is used mainly to reduce bus usage and to allow data packing/unpacking: it is + possible to set different Data Sizes for the Peripheral and the Memory (ie. you can set + Half-Word data size for the peripheral to access its data register and set Word data size + for the Memory to gain in access time. Each two half words will be packed and written in + a single access to a Word in the Memory). + + -@- When FIFO is disabled, it is not allowed to configure different Data Sizes for Source + and Destination. In this case the Peripheral Data Size will be applied to both Source + and Destination. + + *** DMA DAL driver macros list *** + ============================================= + [..] + Below the list of most used macros in DMA DAL driver. + + (+) __DAL_DMA_ENABLE: Enable the specified DMA Stream. + (+) __DAL_DMA_DISABLE: Disable the specified DMA Stream. + (+) __DAL_DMA_GET_IT_SOURCE: Check whether the specified DMA Stream interrupt has occurred or not. + + [..] + (@) You can refer to the DMA DAL driver header file for more useful macros + + @endverbatim + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2017 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file in + * the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + * + */ + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @defgroup DMA DMA + * @brief DMA DAL module driver + * @{ + */ + +#ifdef DAL_DMA_MODULE_ENABLED + +/* Private types -------------------------------------------------------------*/ +typedef struct +{ + __IO uint32_t ISR; /*!< DMA interrupt status register */ + __IO uint32_t Reserved0; + __IO uint32_t IFCR; /*!< DMA interrupt flag clear register */ +} DMA_Base_Registers; + +/* Private variables ---------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/** @addtogroup DMA_Private_Constants + * @{ + */ + #define DAL_TIMEOUT_DMA_ABORT 5U /* 5 ms */ +/** + * @} + */ +/* Private macros ------------------------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ +/** @addtogroup DMA_Private_Functions + * @{ + */ +static void DMA_SetConfig(DMA_HandleTypeDef *hdma, uint32_t SrcAddress, uint32_t DstAddress, uint32_t DataLength); +static uint32_t DMA_CalcBaseAndBitshift(DMA_HandleTypeDef *hdma); +static DAL_StatusTypeDef DMA_CheckFifoParam(DMA_HandleTypeDef *hdma); + +/** + * @} + */ + +/* Exported functions ---------------------------------------------------------*/ +/** @addtogroup DMA_Exported_Functions + * @{ + */ + +/** @addtogroup DMA_Exported_Functions_Group1 + * +@verbatim + =============================================================================== + ##### Initialization and de-initialization functions ##### + =============================================================================== + [..] + This section provides functions allowing to initialize the DMA Stream source + and destination addresses, incrementation and data sizes, transfer direction, + circular/normal mode selection, memory-to-memory mode selection and Stream priority value. + [..] + The DAL_DMA_Init() function follows the DMA configuration procedures as described in + reference manual. + +@endverbatim + * @{ + */ + +/** + * @brief Initialize the DMA according to the specified + * parameters in the DMA_InitTypeDef and create the associated handle. + * @param hdma Pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA Stream. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_DMA_Init(DMA_HandleTypeDef *hdma) +{ + uint32_t tmp = 0U; + uint32_t tickstart = DAL_GetTick(); + DMA_Base_Registers *regs; + + /* Check the DMA peripheral state */ + if(hdma == NULL) + { + return DAL_ERROR; + } + + /* Check the parameters */ + ASSERT_PARAM(IS_DMA_STREAM_ALL_INSTANCE(hdma->Instance)); + ASSERT_PARAM(IS_DMA_CHANNEL(hdma->Init.Channel)); + ASSERT_PARAM(IS_DMA_DIRECTION(hdma->Init.Direction)); + ASSERT_PARAM(IS_DMA_PERIPHERAL_INC_STATE(hdma->Init.PeriphInc)); + ASSERT_PARAM(IS_DMA_MEMORY_INC_STATE(hdma->Init.MemInc)); + ASSERT_PARAM(IS_DMA_PERIPHERAL_DATA_SIZE(hdma->Init.PeriphDataAlignment)); + ASSERT_PARAM(IS_DMA_MEMORY_DATA_SIZE(hdma->Init.MemDataAlignment)); + ASSERT_PARAM(IS_DMA_MODE(hdma->Init.Mode)); + ASSERT_PARAM(IS_DMA_PRIORITY(hdma->Init.Priority)); + ASSERT_PARAM(IS_DMA_FIFO_MODE_STATE(hdma->Init.FIFOMode)); + /* Check the memory burst, peripheral burst and FIFO threshold parameters only + when FIFO mode is enabled */ + if(hdma->Init.FIFOMode != DMA_FIFOMODE_DISABLE) + { + ASSERT_PARAM(IS_DMA_FIFO_THRESHOLD(hdma->Init.FIFOThreshold)); + ASSERT_PARAM(IS_DMA_MEMORY_BURST(hdma->Init.MemBurst)); + ASSERT_PARAM(IS_DMA_PERIPHERAL_BURST(hdma->Init.PeriphBurst)); + } + + /* Change DMA peripheral state */ + hdma->State = DAL_DMA_STATE_BUSY; + + /* Allocate lock resource */ + __DAL_UNLOCK(hdma); + + /* Disable the peripheral */ + __DAL_DMA_DISABLE(hdma); + + /* Check if the DMA Stream is effectively disabled */ + while((hdma->Instance->SCFG & DMA_SCFGx_EN) != RESET) + { + /* Check for the Timeout */ + if((DAL_GetTick() - tickstart ) > DAL_TIMEOUT_DMA_ABORT) + { + /* Update error code */ + hdma->ErrorCode = DAL_DMA_ERROR_TIMEOUT; + + /* Change the DMA state */ + hdma->State = DAL_DMA_STATE_TIMEOUT; + + return DAL_TIMEOUT; + } + } + + /* Get the SCFG register value */ + tmp = hdma->Instance->SCFG; + + /* Clear CHSEL, MBCFG, PBCFG, PRILCFG, MEMSIZECFG, PERSIZECFG, MEMIM, PERIM, CIRCMEN, DIRCFG, CTARG and DBM bits */ + tmp &= ((uint32_t)~(DMA_SCFGx_CHSEL | DMA_SCFGx_MBCFG | DMA_SCFGx_PBCFG | \ + DMA_SCFGx_PRILCFG | DMA_SCFGx_MEMSIZECFG | DMA_SCFGx_PERSIZECFG | \ + DMA_SCFGx_MEMIM | DMA_SCFGx_PERIM | DMA_SCFGx_CIRCMEN | \ + DMA_SCFGx_DIRCFG | DMA_SCFGx_CTARG | DMA_SCFGx_DBM)); + + /* Prepare the DMA Stream configuration */ + tmp |= hdma->Init.Channel | hdma->Init.Direction | + hdma->Init.PeriphInc | hdma->Init.MemInc | + hdma->Init.PeriphDataAlignment | hdma->Init.MemDataAlignment | + hdma->Init.Mode | hdma->Init.Priority; + + /* the Memory burst and peripheral burst are not used when the FIFO is disabled */ + if(hdma->Init.FIFOMode == DMA_FIFOMODE_ENABLE) + { + /* Get memory burst and peripheral burst */ + tmp |= hdma->Init.MemBurst | hdma->Init.PeriphBurst; + } + + /* Write to DMA Stream SCFG register */ + hdma->Instance->SCFG = tmp; + + /* Get the FCTRL register value */ + tmp = hdma->Instance->FCTRL; + + /* Clear Direct mode and FIFO threshold bits */ + tmp &= (uint32_t)~(DMA_FCTRLx_DMDEN | DMA_FCTRLx_FTHSEL); + + /* Prepare the DMA Stream FIFO configuration */ + tmp |= hdma->Init.FIFOMode; + + /* The FIFO threshold is not used when the FIFO mode is disabled */ + if(hdma->Init.FIFOMode == DMA_FIFOMODE_ENABLE) + { + /* Get the FIFO threshold */ + tmp |= hdma->Init.FIFOThreshold; + + /* Check compatibility between FIFO threshold level and size of the memory burst */ + /* for INCR4, INCR8, INCR16 bursts */ + if (hdma->Init.MemBurst != DMA_MBURST_SINGLE) + { + if (DMA_CheckFifoParam(hdma) != DAL_OK) + { + /* Update error code */ + hdma->ErrorCode = DAL_DMA_ERROR_PARAM; + + /* Change the DMA state */ + hdma->State = DAL_DMA_STATE_READY; + + return DAL_ERROR; + } + } + } + + /* Write to DMA Stream FCTRL */ + hdma->Instance->FCTRL = tmp; + + /* Initialize StreamBaseAddress and StreamIndex parameters to be used to calculate + DMA steam Base Address needed by DAL_DMA_IRQHandler() and DAL_DMA_PollForTransfer() */ + regs = (DMA_Base_Registers *)DMA_CalcBaseAndBitshift(hdma); + + /* Clear all interrupt flags */ + regs->IFCR = 0x3FU << hdma->StreamIndex; + + /* Initialize the error code */ + hdma->ErrorCode = DAL_DMA_ERROR_NONE; + + /* Initialize the DMA state */ + hdma->State = DAL_DMA_STATE_READY; + + return DAL_OK; +} + +/** + * @brief DeInitializes the DMA peripheral + * @param hdma pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA Stream. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_DMA_DeInit(DMA_HandleTypeDef *hdma) +{ + DMA_Base_Registers *regs; + + /* Check the DMA peripheral state */ + if(hdma == NULL) + { + return DAL_ERROR; + } + + /* Check the DMA peripheral state */ + if(hdma->State == DAL_DMA_STATE_BUSY) + { + /* Return error status */ + return DAL_BUSY; + } + + /* Check the parameters */ + ASSERT_PARAM(IS_DMA_STREAM_ALL_INSTANCE(hdma->Instance)); + + /* Disable the selected DMA Streamx */ + __DAL_DMA_DISABLE(hdma); + + /* Reset DMA Streamx control register */ + hdma->Instance->SCFG = 0U; + + /* Reset DMA Streamx number of data to transfer register */ + hdma->Instance->NDATA = 0U; + + /* Reset DMA Streamx peripheral address register */ + hdma->Instance->PADDR = 0U; + + /* Reset DMA Streamx memory 0 address register */ + hdma->Instance->M0ADDR = 0U; + + /* Reset DMA Streamx memory 1 address register */ + hdma->Instance->M1ADDR = 0U; + + /* Reset DMA Streamx FIFO control register */ + hdma->Instance->FCTRL = 0x00000021U; + + /* Get DMA steam Base Address */ + regs = (DMA_Base_Registers *)DMA_CalcBaseAndBitshift(hdma); + + /* Clean all callbacks */ + hdma->XferCpltCallback = NULL; + hdma->XferHalfCpltCallback = NULL; + hdma->XferM1CpltCallback = NULL; + hdma->XferM1HalfCpltCallback = NULL; + hdma->XferErrorCallback = NULL; + hdma->XferAbortCallback = NULL; + + /* Clear all interrupt flags at correct offset within the register */ + regs->IFCR = 0x3FU << hdma->StreamIndex; + + /* Reset the error code */ + hdma->ErrorCode = DAL_DMA_ERROR_NONE; + + /* Reset the DMA state */ + hdma->State = DAL_DMA_STATE_RESET; + + /* Release Lock */ + __DAL_UNLOCK(hdma); + + return DAL_OK; +} + +/** + * @} + */ + +/** @addtogroup DMA_Exported_Functions_Group2 + * +@verbatim + =============================================================================== + ##### IO operation functions ##### + =============================================================================== + [..] This section provides functions allowing to: + (+) Configure the source, destination address and data length and Start DMA transfer + (+) Configure the source, destination address and data length and + Start DMA transfer with interrupt + (+) Abort DMA transfer + (+) Poll for transfer complete + (+) Handle DMA interrupt request + +@endverbatim + * @{ + */ + +/** + * @brief Starts the DMA Transfer. + * @param hdma pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA Stream. + * @param SrcAddress The source memory Buffer address + * @param DstAddress The destination memory Buffer address + * @param DataLength The length of data to be transferred from source to destination + * @retval DAL status + */ +DAL_StatusTypeDef DAL_DMA_Start(DMA_HandleTypeDef *hdma, uint32_t SrcAddress, uint32_t DstAddress, uint32_t DataLength) +{ + DAL_StatusTypeDef status = DAL_OK; + + /* Check the parameters */ + ASSERT_PARAM(IS_DMA_BUFFER_SIZE(DataLength)); + + /* Process locked */ + __DAL_LOCK(hdma); + + if(DAL_DMA_STATE_READY == hdma->State) + { + /* Change DMA peripheral state */ + hdma->State = DAL_DMA_STATE_BUSY; + + /* Initialize the error code */ + hdma->ErrorCode = DAL_DMA_ERROR_NONE; + + /* Configure the source, destination address and the data length */ + DMA_SetConfig(hdma, SrcAddress, DstAddress, DataLength); + + /* Enable the Peripheral */ + __DAL_DMA_ENABLE(hdma); + } + else + { + /* Process unlocked */ + __DAL_UNLOCK(hdma); + + /* Return error status */ + status = DAL_BUSY; + } + return status; +} + +/** + * @brief Start the DMA Transfer with interrupt enabled. + * @param hdma pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA Stream. + * @param SrcAddress The source memory Buffer address + * @param DstAddress The destination memory Buffer address + * @param DataLength The length of data to be transferred from source to destination + * @retval DAL status + */ +DAL_StatusTypeDef DAL_DMA_Start_IT(DMA_HandleTypeDef *hdma, uint32_t SrcAddress, uint32_t DstAddress, uint32_t DataLength) +{ + DAL_StatusTypeDef status = DAL_OK; + + /* calculate DMA base and stream number */ + DMA_Base_Registers *regs = (DMA_Base_Registers *)hdma->StreamBaseAddress; + + /* Check the parameters */ + ASSERT_PARAM(IS_DMA_BUFFER_SIZE(DataLength)); + + /* Process locked */ + __DAL_LOCK(hdma); + + if(DAL_DMA_STATE_READY == hdma->State) + { + /* Change DMA peripheral state */ + hdma->State = DAL_DMA_STATE_BUSY; + + /* Initialize the error code */ + hdma->ErrorCode = DAL_DMA_ERROR_NONE; + + /* Configure the source, destination address and the data length */ + DMA_SetConfig(hdma, SrcAddress, DstAddress, DataLength); + + /* Clear all interrupt flags at correct offset within the register */ + regs->IFCR = 0x3FU << hdma->StreamIndex; + + /* Enable Common interrupts*/ + hdma->Instance->SCFG |= DMA_IT_TC | DMA_IT_TE | DMA_IT_DME; + + if(hdma->XferHalfCpltCallback != NULL) + { + hdma->Instance->SCFG |= DMA_IT_HT; + } + + /* Enable the Peripheral */ + __DAL_DMA_ENABLE(hdma); + } + else + { + /* Process unlocked */ + __DAL_UNLOCK(hdma); + + /* Return error status */ + status = DAL_BUSY; + } + + return status; +} + +/** + * @brief Aborts the DMA Transfer. + * @param hdma pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA Stream. + * + * @note After disabling a DMA Stream, a check for wait until the DMA Stream is + * effectively disabled is added. If a Stream is disabled + * while a data transfer is ongoing, the current data will be transferred + * and the Stream will be effectively disabled only after the transfer of + * this single data is finished. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_DMA_Abort(DMA_HandleTypeDef *hdma) +{ + /* calculate DMA base and stream number */ + DMA_Base_Registers *regs = (DMA_Base_Registers *)hdma->StreamBaseAddress; + + uint32_t tickstart = DAL_GetTick(); + + if(hdma->State != DAL_DMA_STATE_BUSY) + { + hdma->ErrorCode = DAL_DMA_ERROR_NO_XFER; + + /* Process Unlocked */ + __DAL_UNLOCK(hdma); + + return DAL_ERROR; + } + else + { + /* Disable all the transfer interrupts */ + hdma->Instance->SCFG &= ~(DMA_IT_TC | DMA_IT_TE | DMA_IT_DME); + hdma->Instance->FCTRL &= ~(DMA_IT_FE); + + if((hdma->XferHalfCpltCallback != NULL) || (hdma->XferM1HalfCpltCallback != NULL)) + { + hdma->Instance->SCFG &= ~(DMA_IT_HT); + } + + /* Disable the stream */ + __DAL_DMA_DISABLE(hdma); + + /* Check if the DMA Stream is effectively disabled */ + while((hdma->Instance->SCFG & DMA_SCFGx_EN) != RESET) + { + /* Check for the Timeout */ + if((DAL_GetTick() - tickstart ) > DAL_TIMEOUT_DMA_ABORT) + { + /* Update error code */ + hdma->ErrorCode = DAL_DMA_ERROR_TIMEOUT; + + /* Change the DMA state */ + hdma->State = DAL_DMA_STATE_TIMEOUT; + + /* Process Unlocked */ + __DAL_UNLOCK(hdma); + + return DAL_TIMEOUT; + } + } + + /* Clear all interrupt flags at correct offset within the register */ + regs->IFCR = 0x3FU << hdma->StreamIndex; + + /* Change the DMA state*/ + hdma->State = DAL_DMA_STATE_READY; + + /* Process Unlocked */ + __DAL_UNLOCK(hdma); + } + return DAL_OK; +} + +/** + * @brief Aborts the DMA Transfer in Interrupt mode. + * @param hdma pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA Stream. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_DMA_Abort_IT(DMA_HandleTypeDef *hdma) +{ + if(hdma->State != DAL_DMA_STATE_BUSY) + { + hdma->ErrorCode = DAL_DMA_ERROR_NO_XFER; + return DAL_ERROR; + } + else + { + /* Set Abort State */ + hdma->State = DAL_DMA_STATE_ABORT; + + /* Disable the stream */ + __DAL_DMA_DISABLE(hdma); + } + + return DAL_OK; +} + +/** + * @brief Polling for transfer complete. + * @param hdma pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA Stream. + * @param CompleteLevel Specifies the DMA level complete. + * @note The polling mode is kept in this version for legacy. it is recommended to use the IT model instead. + * This model could be used for debug purpose. + * @note The DAL_DMA_PollForTransfer API cannot be used in circular and double buffering mode (automatic circular mode). + * @param Timeout Timeout duration. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_DMA_PollForTransfer(DMA_HandleTypeDef *hdma, DAL_DMA_LevelCompleteTypeDef CompleteLevel, uint32_t Timeout) +{ + DAL_StatusTypeDef status = DAL_OK; + uint32_t mask_cpltlevel; + uint32_t tickstart = DAL_GetTick(); + uint32_t tmpisr; + + /* calculate DMA base and stream number */ + DMA_Base_Registers *regs; + + if(DAL_DMA_STATE_BUSY != hdma->State) + { + /* No transfer ongoing */ + hdma->ErrorCode = DAL_DMA_ERROR_NO_XFER; + __DAL_UNLOCK(hdma); + return DAL_ERROR; + } + + /* Polling mode not supported in circular mode and double buffering mode */ + if ((hdma->Instance->SCFG & DMA_SCFGx_CIRCMEN) != RESET) + { + hdma->ErrorCode = DAL_DMA_ERROR_NOT_SUPPORTED; + return DAL_ERROR; + } + + /* Get the level transfer complete flag */ + if(CompleteLevel == DAL_DMA_FULL_TRANSFER) + { + /* Transfer Complete flag */ + mask_cpltlevel = DMA_FLAG_TCIF0_4 << hdma->StreamIndex; + } + else + { + /* Half Transfer Complete flag */ + mask_cpltlevel = DMA_FLAG_HTIF0_4 << hdma->StreamIndex; + } + + regs = (DMA_Base_Registers *)hdma->StreamBaseAddress; + tmpisr = regs->ISR; + + while(((tmpisr & mask_cpltlevel) == RESET) && ((hdma->ErrorCode & DAL_DMA_ERROR_TE) == RESET)) + { + /* Check for the Timeout (Not applicable in circular mode)*/ + if(Timeout != DAL_MAX_DELAY) + { + if((Timeout == 0U)||((DAL_GetTick() - tickstart ) > Timeout)) + { + /* Update error code */ + hdma->ErrorCode = DAL_DMA_ERROR_TIMEOUT; + + /* Change the DMA state */ + hdma->State = DAL_DMA_STATE_READY; + + /* Process Unlocked */ + __DAL_UNLOCK(hdma); + + return DAL_TIMEOUT; + } + } + + /* Get the ISR register value */ + tmpisr = regs->ISR; + + if((tmpisr & (DMA_FLAG_TEIF0_4 << hdma->StreamIndex)) != RESET) + { + /* Update error code */ + hdma->ErrorCode |= DAL_DMA_ERROR_TE; + + /* Clear the transfer error flag */ + regs->IFCR = DMA_FLAG_TEIF0_4 << hdma->StreamIndex; + } + + if((tmpisr & (DMA_FLAG_FEIF0_4 << hdma->StreamIndex)) != RESET) + { + /* Update error code */ + hdma->ErrorCode |= DAL_DMA_ERROR_FE; + + /* Clear the FIFO error flag */ + regs->IFCR = DMA_FLAG_FEIF0_4 << hdma->StreamIndex; + } + + if((tmpisr & (DMA_FLAG_DMEIF0_4 << hdma->StreamIndex)) != RESET) + { + /* Update error code */ + hdma->ErrorCode |= DAL_DMA_ERROR_DME; + + /* Clear the Direct Mode error flag */ + regs->IFCR = DMA_FLAG_DMEIF0_4 << hdma->StreamIndex; + } + } + + if(hdma->ErrorCode != DAL_DMA_ERROR_NONE) + { + if((hdma->ErrorCode & DAL_DMA_ERROR_TE) != RESET) + { + DAL_DMA_Abort(hdma); + + /* Clear the half transfer and transfer complete flags */ + regs->IFCR = (DMA_FLAG_HTIF0_4 | DMA_FLAG_TCIF0_4) << hdma->StreamIndex; + + /* Change the DMA state */ + hdma->State= DAL_DMA_STATE_READY; + + /* Process Unlocked */ + __DAL_UNLOCK(hdma); + + return DAL_ERROR; + } + } + + /* Get the level transfer complete flag */ + if(CompleteLevel == DAL_DMA_FULL_TRANSFER) + { + /* Clear the half transfer and transfer complete flags */ + regs->IFCR = (DMA_FLAG_HTIF0_4 | DMA_FLAG_TCIF0_4) << hdma->StreamIndex; + + hdma->State = DAL_DMA_STATE_READY; + + /* Process Unlocked */ + __DAL_UNLOCK(hdma); + } + else + { + /* Clear the half transfer and transfer complete flags */ + regs->IFCR = (DMA_FLAG_HTIF0_4) << hdma->StreamIndex; + } + + return status; +} + +/** + * @brief Handles DMA interrupt request. + * @param hdma pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA Stream. + * @retval None + */ +void DAL_DMA_IRQHandler(DMA_HandleTypeDef *hdma) +{ + uint32_t tmpisr; + __IO uint32_t count = 0U; + uint32_t timeout = SystemCoreClock / 9600U; + + /* calculate DMA base and stream number */ + DMA_Base_Registers *regs = (DMA_Base_Registers *)hdma->StreamBaseAddress; + + tmpisr = regs->ISR; + + /* Transfer Error Interrupt management ***************************************/ + if ((tmpisr & (DMA_FLAG_TEIF0_4 << hdma->StreamIndex)) != RESET) + { + if(__DAL_DMA_GET_IT_SOURCE(hdma, DMA_IT_TE) != RESET) + { + /* Disable the transfer error interrupt */ + hdma->Instance->SCFG &= ~(DMA_IT_TE); + + /* Clear the transfer error flag */ + regs->IFCR = DMA_FLAG_TEIF0_4 << hdma->StreamIndex; + + /* Update error code */ + hdma->ErrorCode |= DAL_DMA_ERROR_TE; + } + } + /* FIFO Error Interrupt management ******************************************/ + if ((tmpisr & (DMA_FLAG_FEIF0_4 << hdma->StreamIndex)) != RESET) + { + if(__DAL_DMA_GET_IT_SOURCE(hdma, DMA_IT_FE) != RESET) + { + /* Clear the FIFO error flag */ + regs->IFCR = DMA_FLAG_FEIF0_4 << hdma->StreamIndex; + + /* Update error code */ + hdma->ErrorCode |= DAL_DMA_ERROR_FE; + } + } + /* Direct Mode Error Interrupt management ***********************************/ + if ((tmpisr & (DMA_FLAG_DMEIF0_4 << hdma->StreamIndex)) != RESET) + { + if(__DAL_DMA_GET_IT_SOURCE(hdma, DMA_IT_DME) != RESET) + { + /* Clear the direct mode error flag */ + regs->IFCR = DMA_FLAG_DMEIF0_4 << hdma->StreamIndex; + + /* Update error code */ + hdma->ErrorCode |= DAL_DMA_ERROR_DME; + } + } + /* Half Transfer Complete Interrupt management ******************************/ + if ((tmpisr & (DMA_FLAG_HTIF0_4 << hdma->StreamIndex)) != RESET) + { + if(__DAL_DMA_GET_IT_SOURCE(hdma, DMA_IT_HT) != RESET) + { + /* Clear the half transfer complete flag */ + regs->IFCR = DMA_FLAG_HTIF0_4 << hdma->StreamIndex; + + /* Multi_Buffering mode enabled */ + if(((hdma->Instance->SCFG) & (uint32_t)(DMA_SCFGx_DBM)) != RESET) + { + /* Current memory buffer used is Memory 0 */ + if((hdma->Instance->SCFG & DMA_SCFGx_CTARG) == RESET) + { + if(hdma->XferHalfCpltCallback != NULL) + { + /* Half transfer callback */ + hdma->XferHalfCpltCallback(hdma); + } + } + /* Current memory buffer used is Memory 1 */ + else + { + if(hdma->XferM1HalfCpltCallback != NULL) + { + /* Half transfer callback */ + hdma->XferM1HalfCpltCallback(hdma); + } + } + } + else + { + /* Disable the half transfer interrupt if the DMA mode is not CIRCULAR */ + if((hdma->Instance->SCFG & DMA_SCFGx_CIRCMEN) == RESET) + { + /* Disable the half transfer interrupt */ + hdma->Instance->SCFG &= ~(DMA_IT_HT); + } + + if(hdma->XferHalfCpltCallback != NULL) + { + /* Half transfer callback */ + hdma->XferHalfCpltCallback(hdma); + } + } + } + } + /* Transfer Complete Interrupt management ***********************************/ + if ((tmpisr & (DMA_FLAG_TCIF0_4 << hdma->StreamIndex)) != RESET) + { + if(__DAL_DMA_GET_IT_SOURCE(hdma, DMA_IT_TC) != RESET) + { + /* Clear the transfer complete flag */ + regs->IFCR = DMA_FLAG_TCIF0_4 << hdma->StreamIndex; + + if(DAL_DMA_STATE_ABORT == hdma->State) + { + /* Disable all the transfer interrupts */ + hdma->Instance->SCFG &= ~(DMA_IT_TC | DMA_IT_TE | DMA_IT_DME); + hdma->Instance->FCTRL &= ~(DMA_IT_FE); + + if((hdma->XferHalfCpltCallback != NULL) || (hdma->XferM1HalfCpltCallback != NULL)) + { + hdma->Instance->SCFG &= ~(DMA_IT_HT); + } + + /* Clear all interrupt flags at correct offset within the register */ + regs->IFCR = 0x3FU << hdma->StreamIndex; + + /* Change the DMA state */ + hdma->State = DAL_DMA_STATE_READY; + + /* Process Unlocked */ + __DAL_UNLOCK(hdma); + + if(hdma->XferAbortCallback != NULL) + { + hdma->XferAbortCallback(hdma); + } + return; + } + + if(((hdma->Instance->SCFG) & (uint32_t)(DMA_SCFGx_DBM)) != RESET) + { + /* Current memory buffer used is Memory 0 */ + if((hdma->Instance->SCFG & DMA_SCFGx_CTARG) == RESET) + { + if(hdma->XferM1CpltCallback != NULL) + { + /* Transfer complete Callback for memory1 */ + hdma->XferM1CpltCallback(hdma); + } + } + /* Current memory buffer used is Memory 1 */ + else + { + if(hdma->XferCpltCallback != NULL) + { + /* Transfer complete Callback for memory0 */ + hdma->XferCpltCallback(hdma); + } + } + } + /* Disable the transfer complete interrupt if the DMA mode is not CIRCULAR */ + else + { + if((hdma->Instance->SCFG & DMA_SCFGx_CIRCMEN) == RESET) + { + /* Disable the transfer complete interrupt */ + hdma->Instance->SCFG &= ~(DMA_IT_TC); + + /* Change the DMA state */ + hdma->State = DAL_DMA_STATE_READY; + + /* Process Unlocked */ + __DAL_UNLOCK(hdma); + } + + if(hdma->XferCpltCallback != NULL) + { + /* Transfer complete callback */ + hdma->XferCpltCallback(hdma); + } + } + } + } + + /* manage error case */ + if(hdma->ErrorCode != DAL_DMA_ERROR_NONE) + { + if((hdma->ErrorCode & DAL_DMA_ERROR_TE) != RESET) + { + hdma->State = DAL_DMA_STATE_ABORT; + + /* Disable the stream */ + __DAL_DMA_DISABLE(hdma); + + do + { + if (++count > timeout) + { + break; + } + } + while((hdma->Instance->SCFG & DMA_SCFGx_EN) != RESET); + + /* Change the DMA state */ + hdma->State = DAL_DMA_STATE_READY; + + /* Process Unlocked */ + __DAL_UNLOCK(hdma); + } + + if(hdma->XferErrorCallback != NULL) + { + /* Transfer error callback */ + hdma->XferErrorCallback(hdma); + } + } +} + +/** + * @brief Register callbacks + * @param hdma pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA Stream. + * @param CallbackID User Callback identifier + * a DMA_HandleTypeDef structure as parameter. + * @param pCallback pointer to private callback function which has pointer to + * a DMA_HandleTypeDef structure as parameter. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_DMA_RegisterCallback(DMA_HandleTypeDef *hdma, DAL_DMA_CallbackIDTypeDef CallbackID, void (* pCallback)(DMA_HandleTypeDef *_hdma)) +{ + + DAL_StatusTypeDef status = DAL_OK; + + /* Process locked */ + __DAL_LOCK(hdma); + + if(DAL_DMA_STATE_READY == hdma->State) + { + switch (CallbackID) + { + case DAL_DMA_XFER_CPLT_CB_ID: + hdma->XferCpltCallback = pCallback; + break; + + case DAL_DMA_XFER_HALFCPLT_CB_ID: + hdma->XferHalfCpltCallback = pCallback; + break; + + case DAL_DMA_XFER_M1CPLT_CB_ID: + hdma->XferM1CpltCallback = pCallback; + break; + + case DAL_DMA_XFER_M1HALFCPLT_CB_ID: + hdma->XferM1HalfCpltCallback = pCallback; + break; + + case DAL_DMA_XFER_ERROR_CB_ID: + hdma->XferErrorCallback = pCallback; + break; + + case DAL_DMA_XFER_ABORT_CB_ID: + hdma->XferAbortCallback = pCallback; + break; + + default: + /* Return error status */ + status = DAL_ERROR; + break; + } + } + else + { + /* Return error status */ + status = DAL_ERROR; + } + + /* Release Lock */ + __DAL_UNLOCK(hdma); + + return status; +} + +/** + * @brief UnRegister callbacks + * @param hdma pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA Stream. + * @param CallbackID User Callback identifier + * a DAL_DMA_CallbackIDTypeDef ENUM as parameter. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_DMA_UnRegisterCallback(DMA_HandleTypeDef *hdma, DAL_DMA_CallbackIDTypeDef CallbackID) +{ + DAL_StatusTypeDef status = DAL_OK; + + /* Process locked */ + __DAL_LOCK(hdma); + + if(DAL_DMA_STATE_READY == hdma->State) + { + switch (CallbackID) + { + case DAL_DMA_XFER_CPLT_CB_ID: + hdma->XferCpltCallback = NULL; + break; + + case DAL_DMA_XFER_HALFCPLT_CB_ID: + hdma->XferHalfCpltCallback = NULL; + break; + + case DAL_DMA_XFER_M1CPLT_CB_ID: + hdma->XferM1CpltCallback = NULL; + break; + + case DAL_DMA_XFER_M1HALFCPLT_CB_ID: + hdma->XferM1HalfCpltCallback = NULL; + break; + + case DAL_DMA_XFER_ERROR_CB_ID: + hdma->XferErrorCallback = NULL; + break; + + case DAL_DMA_XFER_ABORT_CB_ID: + hdma->XferAbortCallback = NULL; + break; + + case DAL_DMA_XFER_ALL_CB_ID: + hdma->XferCpltCallback = NULL; + hdma->XferHalfCpltCallback = NULL; + hdma->XferM1CpltCallback = NULL; + hdma->XferM1HalfCpltCallback = NULL; + hdma->XferErrorCallback = NULL; + hdma->XferAbortCallback = NULL; + break; + + default: + status = DAL_ERROR; + break; + } + } + else + { + status = DAL_ERROR; + } + + /* Release Lock */ + __DAL_UNLOCK(hdma); + + return status; +} + +/** + * @} + */ + +/** @addtogroup DMA_Exported_Functions_Group3 + * +@verbatim + =============================================================================== + ##### State and Errors functions ##### + =============================================================================== + [..] + This subsection provides functions allowing to + (+) Check the DMA state + (+) Get error code + +@endverbatim + * @{ + */ + +/** + * @brief Returns the DMA state. + * @param hdma pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA Stream. + * @retval DAL state + */ +DAL_DMA_StateTypeDef DAL_DMA_GetState(DMA_HandleTypeDef *hdma) +{ + return hdma->State; +} + +/** + * @brief Return the DMA error code + * @param hdma pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA Stream. + * @retval DMA Error Code + */ +uint32_t DAL_DMA_GetError(DMA_HandleTypeDef *hdma) +{ + return hdma->ErrorCode; +} + +/** + * @} + */ + +/** + * @} + */ + +/** @addtogroup DMA_Private_Functions + * @{ + */ + +/** + * @brief Sets the DMA Transfer parameter. + * @param hdma pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA Stream. + * @param SrcAddress The source memory Buffer address + * @param DstAddress The destination memory Buffer address + * @param DataLength The length of data to be transferred from source to destination + * @retval DAL status + */ +static void DMA_SetConfig(DMA_HandleTypeDef *hdma, uint32_t SrcAddress, uint32_t DstAddress, uint32_t DataLength) +{ + /* Clear DBM bit */ + hdma->Instance->SCFG &= (uint32_t)(~DMA_SCFGx_DBM); + + /* Configure DMA Stream data length */ + hdma->Instance->NDATA = DataLength; + + /* Memory to Peripheral */ + if((hdma->Init.Direction) == DMA_MEMORY_TO_PERIPH) + { + /* Configure DMA Stream destination address */ + hdma->Instance->PADDR = DstAddress; + + /* Configure DMA Stream source address */ + hdma->Instance->M0ADDR = SrcAddress; + } + /* Peripheral to Memory */ + else + { + /* Configure DMA Stream source address */ + hdma->Instance->PADDR = SrcAddress; + + /* Configure DMA Stream destination address */ + hdma->Instance->M0ADDR = DstAddress; + } +} + +/** + * @brief Returns the DMA Stream base address depending on stream number + * @param hdma pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA Stream. + * @retval Stream base address + */ +static uint32_t DMA_CalcBaseAndBitshift(DMA_HandleTypeDef *hdma) +{ + uint32_t stream_number = (((uint32_t)hdma->Instance & 0xFFU) - 16U) / 24U; + + /* lookup table for necessary bitshift of flags within status registers */ + static const uint8_t flagBitshiftOffset[8U] = {0U, 6U, 16U, 22U, 0U, 6U, 16U, 22U}; + hdma->StreamIndex = flagBitshiftOffset[stream_number]; + + if (stream_number > 3U) + { + /* return pointer to HINTSTS and HIFCLR */ + hdma->StreamBaseAddress = (((uint32_t)hdma->Instance & (uint32_t)(~0x3FFU)) + 4U); + } + else + { + /* return pointer to LINTSTS and LIFCLR */ + hdma->StreamBaseAddress = ((uint32_t)hdma->Instance & (uint32_t)(~0x3FFU)); + } + + return hdma->StreamBaseAddress; +} + +/** + * @brief Check compatibility between FIFO threshold level and size of the memory burst + * @param hdma pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA Stream. + * @retval DAL status + */ +static DAL_StatusTypeDef DMA_CheckFifoParam(DMA_HandleTypeDef *hdma) +{ + DAL_StatusTypeDef status = DAL_OK; + uint32_t tmp = hdma->Init.FIFOThreshold; + + /* Memory Data size equal to Byte */ + if(hdma->Init.MemDataAlignment == DMA_MDATAALIGN_BYTE) + { + switch (tmp) + { + case DMA_FIFO_THRESHOLD_1QUARTERFULL: + case DMA_FIFO_THRESHOLD_3QUARTERSFULL: + if ((hdma->Init.MemBurst & DMA_SCFGx_MBCFG_1) == DMA_SCFGx_MBCFG_1) + { + status = DAL_ERROR; + } + break; + case DMA_FIFO_THRESHOLD_HALFFULL: + if (hdma->Init.MemBurst == DMA_MBURST_INC16) + { + status = DAL_ERROR; + } + break; + case DMA_FIFO_THRESHOLD_FULL: + break; + default: + break; + } + } + + /* Memory Data size equal to Half-Word */ + else if (hdma->Init.MemDataAlignment == DMA_MDATAALIGN_HALFWORD) + { + switch (tmp) + { + case DMA_FIFO_THRESHOLD_1QUARTERFULL: + case DMA_FIFO_THRESHOLD_3QUARTERSFULL: + status = DAL_ERROR; + break; + case DMA_FIFO_THRESHOLD_HALFFULL: + if ((hdma->Init.MemBurst & DMA_SCFGx_MBCFG_1) == DMA_SCFGx_MBCFG_1) + { + status = DAL_ERROR; + } + break; + case DMA_FIFO_THRESHOLD_FULL: + if (hdma->Init.MemBurst == DMA_MBURST_INC16) + { + status = DAL_ERROR; + } + break; + default: + break; + } + } + + /* Memory Data size equal to Word */ + else + { + switch (tmp) + { + case DMA_FIFO_THRESHOLD_1QUARTERFULL: + case DMA_FIFO_THRESHOLD_HALFFULL: + case DMA_FIFO_THRESHOLD_3QUARTERSFULL: + status = DAL_ERROR; + break; + case DMA_FIFO_THRESHOLD_FULL: + if ((hdma->Init.MemBurst & DMA_SCFGx_MBCFG_1) == DMA_SCFGx_MBCFG_1) + { + status = DAL_ERROR; + } + break; + default: + break; + } + } + + return status; +} + +/** + * @} + */ + +#endif /* DAL_DMA_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_dma_ex.c b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_dma_ex.c new file mode 100644 index 0000000000..7dddbe8ec2 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_dma_ex.c @@ -0,0 +1,338 @@ +/** + * + * @file apm32f4xx_dal_dma_ex.c + * @brief DMA Extension DAL module driver + * This file provides firmware functions to manage the following + * functionalities of the DMA Extension peripheral: + * + Extended features functions + * + @verbatim + ============================================================================== + ##### How to use this driver ##### + ============================================================================== + [..] + The DMA Extension DAL driver can be used as follows: + (#) Start a multi buffer transfer using the DAL_DMA_MultiBufferStart() function + for polling mode or DAL_DMA_MultiBufferStart_IT() for interrupt mode. + + -@- In Memory-to-Memory transfer mode, Multi (Double) Buffer mode is not allowed. + -@- When Multi (Double) Buffer mode is enabled the, transfer is circular by default. + -@- In Multi (Double) buffer mode, it is possible to update the base address for + the AHB memory port on the fly (DMA_SxM0AR or DMA_SxM1AR) when the stream is enabled. + + @endverbatim + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2017 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file in + * the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + * + */ + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @defgroup DMAEx DMAEx + * @brief DMA Extended DAL module driver + * @{ + */ + +#ifdef DAL_DMA_MODULE_ENABLED + +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private Constants ---------------------------------------------------------*/ +/* Private macros ------------------------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ +/** @addtogroup DMAEx_Private_Functions + * @{ + */ +static void DMA_MultiBufferSetConfig(DMA_HandleTypeDef *hdma, uint32_t SrcAddress, uint32_t DstAddress, uint32_t DataLength); +/** + * @} + */ + +/* Exported functions ---------------------------------------------------------*/ + +/** @addtogroup DMAEx_Exported_Functions + * @{ + */ + + +/** @addtogroup DMAEx_Exported_Functions_Group1 + * +@verbatim + =============================================================================== + ##### Extended features functions ##### + =============================================================================== + [..] This section provides functions allowing to: + (+) Configure the source, destination address and data length and + Start MultiBuffer DMA transfer + (+) Configure the source, destination address and data length and + Start MultiBuffer DMA transfer with interrupt + (+) Change on the fly the memory0 or memory1 address. + +@endverbatim + * @{ + */ + + +/** + * @brief Starts the multi_buffer DMA Transfer. + * @param hdma pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA Stream. + * @param SrcAddress The source memory Buffer address + * @param DstAddress The destination memory Buffer address + * @param SecondMemAddress The second memory Buffer address in case of multi buffer Transfer + * @param DataLength The length of data to be transferred from source to destination + * @retval DAL status + */ +DAL_StatusTypeDef DAL_DMAEx_MultiBufferStart(DMA_HandleTypeDef *hdma, uint32_t SrcAddress, uint32_t DstAddress, uint32_t SecondMemAddress, uint32_t DataLength) +{ + DAL_StatusTypeDef status = DAL_OK; + + /* Check the parameters */ + ASSERT_PARAM(IS_DMA_BUFFER_SIZE(DataLength)); + + /* Memory-to-memory transfer not supported in double buffering mode */ + if (hdma->Init.Direction == DMA_MEMORY_TO_MEMORY) + { + hdma->ErrorCode = DAL_DMA_ERROR_NOT_SUPPORTED; + status = DAL_ERROR; + } + else + { + /* Process Locked */ + __DAL_LOCK(hdma); + + if(DAL_DMA_STATE_READY == hdma->State) + { + /* Change DMA peripheral state */ + hdma->State = DAL_DMA_STATE_BUSY; + + /* Enable the double buffer mode */ + hdma->Instance->SCFG |= (uint32_t)DMA_SCFGx_DBM; + + /* Configure DMA Stream destination address */ + hdma->Instance->M1ADDR = SecondMemAddress; + + /* Configure the source, destination address and the data length */ + DMA_MultiBufferSetConfig(hdma, SrcAddress, DstAddress, DataLength); + + /* Enable the peripheral */ + __DAL_DMA_ENABLE(hdma); + } + else + { + /* Return error status */ + status = DAL_BUSY; + } + } + return status; +} + +/** + * @brief Starts the multi_buffer DMA Transfer with interrupt enabled. + * @param hdma pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA Stream. + * @param SrcAddress The source memory Buffer address + * @param DstAddress The destination memory Buffer address + * @param SecondMemAddress The second memory Buffer address in case of multi buffer Transfer + * @param DataLength The length of data to be transferred from source to destination + * @retval DAL status + */ +DAL_StatusTypeDef DAL_DMAEx_MultiBufferStart_IT(DMA_HandleTypeDef *hdma, uint32_t SrcAddress, uint32_t DstAddress, uint32_t SecondMemAddress, uint32_t DataLength) +{ + DAL_StatusTypeDef status = DAL_OK; + + /* Check the parameters */ + ASSERT_PARAM(IS_DMA_BUFFER_SIZE(DataLength)); + + /* Memory-to-memory transfer not supported in double buffering mode */ + if (hdma->Init.Direction == DMA_MEMORY_TO_MEMORY) + { + hdma->ErrorCode = DAL_DMA_ERROR_NOT_SUPPORTED; + return DAL_ERROR; + } + + /* Check callback functions */ + if ((NULL == hdma->XferCpltCallback) || (NULL == hdma->XferM1CpltCallback) || (NULL == hdma->XferErrorCallback)) + { + hdma->ErrorCode = DAL_DMA_ERROR_PARAM; + return DAL_ERROR; + } + + /* Process locked */ + __DAL_LOCK(hdma); + + if(DAL_DMA_STATE_READY == hdma->State) + { + /* Change DMA peripheral state */ + hdma->State = DAL_DMA_STATE_BUSY; + + /* Initialize the error code */ + hdma->ErrorCode = DAL_DMA_ERROR_NONE; + + /* Enable the Double buffer mode */ + hdma->Instance->SCFG |= (uint32_t)DMA_SCFGx_DBM; + + /* Configure DMA Stream destination address */ + hdma->Instance->M1ADDR = SecondMemAddress; + + /* Configure the source, destination address and the data length */ + DMA_MultiBufferSetConfig(hdma, SrcAddress, DstAddress, DataLength); + + /* Clear all flags */ + __DAL_DMA_CLEAR_FLAG (hdma, __DAL_DMA_GET_TC_FLAG_INDEX(hdma)); + __DAL_DMA_CLEAR_FLAG (hdma, __DAL_DMA_GET_HT_FLAG_INDEX(hdma)); + __DAL_DMA_CLEAR_FLAG (hdma, __DAL_DMA_GET_TE_FLAG_INDEX(hdma)); + __DAL_DMA_CLEAR_FLAG (hdma, __DAL_DMA_GET_DME_FLAG_INDEX(hdma)); + __DAL_DMA_CLEAR_FLAG (hdma, __DAL_DMA_GET_FE_FLAG_INDEX(hdma)); + + /* Enable Common interrupts*/ + hdma->Instance->SCFG |= DMA_IT_TC | DMA_IT_TE | DMA_IT_DME; + hdma->Instance->FCTRL |= DMA_IT_FE; + + if((hdma->XferHalfCpltCallback != NULL) || (hdma->XferM1HalfCpltCallback != NULL)) + { + hdma->Instance->SCFG |= DMA_IT_HT; + } + + /* Enable the peripheral */ + __DAL_DMA_ENABLE(hdma); + } + else + { + /* Process unlocked */ + __DAL_UNLOCK(hdma); + + /* Return error status */ + status = DAL_BUSY; + } + return status; +} + +/** + * @brief Change the memory0 or memory1 address on the fly. + * @param hdma pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA Stream. + * @param Address The new address + * @param memory the memory to be changed, This parameter can be one of + * the following values: + * MEMORY0 / + * MEMORY1 + * @note The MEMORY0 address can be changed only when the current transfer use + * MEMORY1 and the MEMORY1 address can be changed only when the current + * transfer use MEMORY0. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_DMAEx_ChangeMemory(DMA_HandleTypeDef *hdma, uint32_t Address, DAL_DMA_MemoryTypeDef memory) +{ + if(memory == MEMORY0) + { + /* change the memory0 address */ + hdma->Instance->M0ADDR = Address; + } + else + { + /* change the memory1 address */ + hdma->Instance->M1ADDR = Address; + } + + return DAL_OK; +} + +/** + * @} + */ + +/** + * @} + */ + +/** @addtogroup DMAEx_Private_Functions + * @{ + */ + +/** + * @brief Set the DMA Transfer parameter. + * @param hdma pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA Stream. + * @param SrcAddress The source memory Buffer address + * @param DstAddress The destination memory Buffer address + * @param DataLength The length of data to be transferred from source to destination + * @retval DAL status + */ +static void DMA_MultiBufferSetConfig(DMA_HandleTypeDef *hdma, uint32_t SrcAddress, uint32_t DstAddress, uint32_t DataLength) +{ + /* Configure DMA Stream data length */ + hdma->Instance->NDATA = DataLength; + + /* Peripheral to Memory */ + if((hdma->Init.Direction) == DMA_MEMORY_TO_PERIPH) + { + /* Configure DMA Stream destination address */ + hdma->Instance->PADDR = DstAddress; + + /* Configure DMA Stream source address */ + hdma->Instance->M0ADDR = SrcAddress; + } + /* Memory to Peripheral */ + else + { + /* Configure DMA Stream source address */ + hdma->Instance->PADDR = SrcAddress; + + /* Configure DMA Stream destination address */ + hdma->Instance->M0ADDR = DstAddress; + } +} + +/** + * @} + */ + +#endif /* DAL_DMA_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_eint.c b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_eint.c new file mode 100644 index 0000000000..330de8d23c --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_eint.c @@ -0,0 +1,573 @@ +/** + * + * @file apm32f4xx_dal_eint.c + * @author MCD Application Team + * @brief EINT DAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the Extended Interrupts and events controller (EINT) peripheral: + * + Initialization and de-initialization functions + * + IO operation functions + * + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2018 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + * + @verbatim + ============================================================================== + ##### EINT Peripheral features ##### + ============================================================================== + [..] + (+) Each Eint line can be configured within this driver. + + (+) Eint line can be configured in 3 different modes + (++) Interrupt + (++) Event + (++) Both of them + + (+) Configurable Eint lines can be configured with 3 different triggers + (++) Rising + (++) Falling + (++) Both of them + + (+) When set in interrupt mode, configurable Eint lines have two different + interrupts pending registers which allow to distinguish which transition + occurs: + (++) Rising edge pending interrupt + (++) Falling + + (+) Eint lines 0 to 15 are linked to gpio pin number 0 to 15. Gpio port can + be selected through multiplexer. + + ##### How to use this driver ##### + ============================================================================== + [..] + + (#) Configure the EINT line using DAL_EINT_SetConfigLine(). + (++) Choose the interrupt line number by setting "Line" member from + EINT_ConfigTypeDef structure. + (++) Configure the interrupt and/or event mode using "Mode" member from + EINT_ConfigTypeDef structure. + (++) For configurable lines, configure rising and/or falling trigger + "Trigger" member from EINT_ConfigTypeDef structure. + (++) For Eint lines linked to gpio, choose gpio port using "GPIOSel" + member from GPIO_InitTypeDef structure. + + (#) Get current Eint configuration of a dedicated line using + DAL_EINT_GetConfigLine(). + (++) Provide exiting handle as parameter. + (++) Provide pointer on EINT_ConfigTypeDef structure as second parameter. + + (#) Clear Eint configuration of a dedicated line using DAL_EINT_GetConfigLine(). + (++) Provide exiting handle as parameter. + + (#) Register callback to treat Eint interrupts using DAL_EINT_RegisterCallback(). + (++) Provide exiting handle as first parameter. + (++) Provide which callback will be registered using one value from + EINT_CallbackIDTypeDef. + (++) Provide callback function pointer. + + (#) Get interrupt pending bit using DAL_EINT_GetPending(). + + (#) Clear interrupt pending bit using DAL_EINT_GetPending(). + + (#) Generate software interrupt using DAL_EINT_GenerateSWI(). + + @endverbatim + */ + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @addtogroup EINT + * @{ + */ +/** MISRA C:2012 deviation rule has been granted for following rule: + * Rule-18.1_b - Medium: Array `EINTCR' 1st subscript interval [0,7] may be out + * of bounds [0,3] in following API : + * DAL_EINT_SetConfigLine + * DAL_EINT_GetConfigLine + * DAL_EINT_ClearConfigLine + */ + +#ifdef DAL_EINT_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private defines -----------------------------------------------------------*/ +/** @defgroup EINT_Private_Constants EINT Private Constants + * @{ + */ + +/** + * @} + */ + +/* Private macros ------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Exported functions --------------------------------------------------------*/ + +/** @addtogroup EINT_Exported_Functions + * @{ + */ + +/** @addtogroup EINT_Exported_Functions_Group1 + * @brief Configuration functions + * +@verbatim + =============================================================================== + ##### Configuration functions ##### + =============================================================================== + +@endverbatim + * @{ + */ + +/** + * @brief Set configuration of a dedicated Eint line. + * @param heint Eint handle. + * @param pEintConfig Pointer on EINT configuration to be set. + * @retval DAL Status. + */ +DAL_StatusTypeDef DAL_EINT_SetConfigLine(EINT_HandleTypeDef *heint, EINT_ConfigTypeDef *pEintConfig) +{ + uint32_t regval; + uint32_t linepos; + uint32_t maskline; + + /* Check null pointer */ + if ((heint == NULL) || (pEintConfig == NULL)) + { + return DAL_ERROR; + } + + /* Check parameters */ + ASSERT_PARAM(IS_EINT_LINE(pEintConfig->Line)); + ASSERT_PARAM(IS_EINT_MODE(pEintConfig->Mode)); + + /* Assign line number to handle */ + heint->Line = pEintConfig->Line; + + /* Compute line mask */ + linepos = (pEintConfig->Line & EINT_PIN_MASK); + maskline = (1uL << linepos); + + /* Configure triggers for configurable lines */ + if ((pEintConfig->Line & EINT_CONFIG) != 0x00u) + { + ASSERT_PARAM(IS_EINT_TRIGGER(pEintConfig->Trigger)); + + /* Configure rising trigger */ + /* Mask or set line */ + if ((pEintConfig->Trigger & EINT_TRIGGER_RISING) != 0x00u) + { + EINT->RTEN |= maskline; + } + else + { + EINT->RTEN &= ~maskline; + } + + /* Configure falling trigger */ + /* Mask or set line */ + if ((pEintConfig->Trigger & EINT_TRIGGER_FALLING) != 0x00u) + { + EINT->FTEN |= maskline; + } + else + { + EINT->FTEN &= ~maskline; + } + + + /* Configure gpio port selection in case of gpio exti line */ + if ((pEintConfig->Line & EINT_GPIO) == EINT_GPIO) + { + ASSERT_PARAM(IS_EINT_GPIO_PORT(pEintConfig->GPIOSel)); + ASSERT_PARAM(IS_EINT_GPIO_PIN(linepos)); + + regval = SYSCFG->EINTCFG[linepos >> 2u]; + regval &= ~(SYSCFG_EINTCFG1_EINT0 << (SYSCFG_EINTCFG1_EINT1_Pos * (linepos & 0x03u))); + regval |= (pEintConfig->GPIOSel << (SYSCFG_EINTCFG1_EINT1_Pos * (linepos & 0x03u))); + SYSCFG->EINTCFG[linepos >> 2u] = regval; + } + } + + /* Configure interrupt mode : read current mode */ + /* Mask or set line */ + if ((pEintConfig->Mode & EINT_MODE_INTERRUPT) != 0x00u) + { + EINT->IMASK |= maskline; + } + else + { + EINT->IMASK &= ~maskline; + } + + /* Configure event mode : read current mode */ + /* Mask or set line */ + if ((pEintConfig->Mode & EINT_MODE_EVENT) != 0x00u) + { + EINT->EMASK |= maskline; + } + else + { + EINT->EMASK &= ~maskline; + } + + return DAL_OK; +} + +/** + * @brief Get configuration of a dedicated Eint line. + * @param heint Eint handle. + * @param pEintConfig Pointer on structure to store Eint configuration. + * @retval DAL Status. + */ +DAL_StatusTypeDef DAL_EINT_GetConfigLine(EINT_HandleTypeDef *heint, EINT_ConfigTypeDef *pEintConfig) +{ + uint32_t regval; + uint32_t linepos; + uint32_t maskline; + + /* Check null pointer */ + if ((heint == NULL) || (pEintConfig == NULL)) + { + return DAL_ERROR; + } + + /* Check the parameter */ + ASSERT_PARAM(IS_EINT_LINE(heint->Line)); + + /* Store handle line number to configuration structure */ + pEintConfig->Line = heint->Line; + + /* Compute line mask */ + linepos = (pEintConfig->Line & EINT_PIN_MASK); + maskline = (1uL << linepos); + + /* 1] Get core mode : interrupt */ + + /* Check if selected line is enable */ + if ((EINT->IMASK & maskline) != 0x00u) + { + pEintConfig->Mode = EINT_MODE_INTERRUPT; + } + else + { + pEintConfig->Mode = EINT_MODE_NONE; + } + + /* Get event mode */ + /* Check if selected line is enable */ + if ((EINT->EMASK & maskline) != 0x00u) + { + pEintConfig->Mode |= EINT_MODE_EVENT; + } + + /* Get default Trigger and GPIOSel configuration */ + pEintConfig->Trigger = EINT_TRIGGER_NONE; + pEintConfig->GPIOSel = 0x00u; + + /* 2] Get trigger for configurable lines : rising */ + if ((pEintConfig->Line & EINT_CONFIG) != 0x00u) + { + /* Check if configuration of selected line is enable */ + if ((EINT->RTEN & maskline) != 0x00u) + { + pEintConfig->Trigger = EINT_TRIGGER_RISING; + } + + /* Get falling configuration */ + /* Check if configuration of selected line is enable */ + if ((EINT->FTEN & maskline) != 0x00u) + { + pEintConfig->Trigger |= EINT_TRIGGER_FALLING; + } + + /* Get Gpio port selection for gpio lines */ + if ((pEintConfig->Line & EINT_GPIO) == EINT_GPIO) + { + ASSERT_PARAM(IS_EINT_GPIO_PIN(linepos)); + + regval = (SYSCFG->EINTCFG[linepos >> 2u] << 16u ); + pEintConfig->GPIOSel = ((regval << (SYSCFG_EINTCFG1_EINT1_Pos * (3uL - (linepos & 0x03u)))) >> 28u); + } + } + + return DAL_OK; +} + +/** + * @brief Clear whole configuration of a dedicated Eint line. + * @param heint Eint handle. + * @retval DAL Status. + */ +DAL_StatusTypeDef DAL_EINT_ClearConfigLine(EINT_HandleTypeDef *heint) +{ + uint32_t regval; + uint32_t linepos; + uint32_t maskline; + + /* Check null pointer */ + if (heint == NULL) + { + return DAL_ERROR; + } + + /* Check the parameter */ + ASSERT_PARAM(IS_EINT_LINE(heint->Line)); + + /* compute line mask */ + linepos = (heint->Line & EINT_PIN_MASK); + maskline = (1uL << linepos); + + /* 1] Clear interrupt mode */ + EINT->IMASK = (EINT->IMASK & ~maskline); + + /* 2] Clear event mode */ + EINT->EMASK = (EINT->EMASK & ~maskline); + + /* 3] Clear triggers in case of configurable lines */ + if ((heint->Line & EINT_CONFIG) != 0x00u) + { + EINT->RTEN = (EINT->RTEN & ~maskline); + EINT->FTEN = (EINT->FTEN & ~maskline); + + /* Get Gpio port selection for gpio lines */ + if ((heint->Line & EINT_GPIO) == EINT_GPIO) + { + ASSERT_PARAM(IS_EINT_GPIO_PIN(linepos)); + + regval = SYSCFG->EINTCFG[linepos >> 2u]; + regval &= ~(SYSCFG_EINTCFG1_EINT0 << (SYSCFG_EINTCFG1_EINT1_Pos * (linepos & 0x03u))); + SYSCFG->EINTCFG[linepos >> 2u] = regval; + } + } + + return DAL_OK; +} + +/** + * @brief Register callback for a dedicated Eint line. + * @param heint Eint handle. + * @param CallbackID User callback identifier. + * This parameter can be one of @arg @ref EINT_CallbackIDTypeDef values. + * @param pPendingCbfn function pointer to be stored as callback. + * @retval DAL Status. + */ +DAL_StatusTypeDef DAL_EINT_RegisterCallback(EINT_HandleTypeDef *heint, EINT_CallbackIDTypeDef CallbackID, void (*pPendingCbfn)(void)) +{ + DAL_StatusTypeDef status = DAL_OK; + + switch (CallbackID) + { + case DAL_EINT_COMMON_CB_ID: + heint->PendingCallback = pPendingCbfn; + break; + + default: + status = DAL_ERROR; + break; + } + + return status; +} + +/** + * @brief Store line number as handle private field. + * @param heint Eint handle. + * @param EintLine Eint line number. + * This parameter can be from 0 to @ref EINT_LINE_NB. + * @retval DAL Status. + */ +DAL_StatusTypeDef DAL_EINT_GetHandle(EINT_HandleTypeDef *heint, uint32_t EintLine) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_EINT_LINE(EintLine)); + + /* Check null pointer */ + if (heint == NULL) + { + return DAL_ERROR; + } + else + { + /* Store line number as handle private field */ + heint->Line = EintLine; + + return DAL_OK; + } +} + +/** + * @} + */ + +/** @addtogroup EINT_Exported_Functions_Group2 + * @brief EINT IO functions. + * +@verbatim + =============================================================================== + ##### IO operation functions ##### + =============================================================================== + +@endverbatim + * @{ + */ + +/** + * @brief Handle EINT interrupt request. + * @param heint Eint handle. + * @retval none. + */ +void DAL_EINT_IRQHandler(EINT_HandleTypeDef *heint) +{ + uint32_t regval; + uint32_t maskline; + + /* Compute line mask */ + maskline = (1uL << (heint->Line & EINT_PIN_MASK)); + + /* Get pending bit */ + regval = (EINT->IPEND & maskline); + if (regval != 0x00u) + { + /* Clear pending bit */ + EINT->IPEND = maskline; + + /* Call callback */ + if (heint->PendingCallback != NULL) + { + heint->PendingCallback(); + } + } +} + +/** + * @brief Get interrupt pending bit of a dedicated line. + * @param heint Eint handle. + * @param Edge Specify which pending edge as to be checked. + * This parameter can be one of the following values: + * @arg @ref EINT_TRIGGER_RISING_FALLING + * This parameter is kept for compatibility with other series. + * @retval 1 if interrupt is pending else 0. + */ +uint32_t DAL_EINT_GetPending(EINT_HandleTypeDef *heint, uint32_t Edge) +{ + uint32_t regval; + uint32_t linepos; + uint32_t maskline; + + /* Check parameters */ + ASSERT_PARAM(IS_EINT_LINE(heint->Line)); + ASSERT_PARAM(IS_EINT_CONFIG_LINE(heint->Line)); + ASSERT_PARAM(IS_EINT_PENDING_EDGE(Edge)); + + /* Compute line mask */ + linepos = (heint->Line & EINT_PIN_MASK); + maskline = (1uL << linepos); + + /* return 1 if bit is set else 0 */ + regval = ((EINT->IPEND & maskline) >> linepos); + return regval; +} + +/** + * @brief Clear interrupt pending bit of a dedicated line. + * @param heint Eint handle. + * @param Edge Specify which pending edge as to be clear. + * This parameter can be one of the following values: + * @arg @ref EINT_TRIGGER_RISING_FALLING + * This parameter is kept for compatibility with other series. + * @retval None. + */ +void DAL_EINT_ClearPending(EINT_HandleTypeDef *heint, uint32_t Edge) +{ + uint32_t maskline; + + /* Check parameters */ + ASSERT_PARAM(IS_EINT_LINE(heint->Line)); + ASSERT_PARAM(IS_EINT_CONFIG_LINE(heint->Line)); + ASSERT_PARAM(IS_EINT_PENDING_EDGE(Edge)); + + /* Compute line mask */ + maskline = (1uL << (heint->Line & EINT_PIN_MASK)); + + /* Clear Pending bit */ + EINT->IPEND = maskline; +} + +/** + * @brief Generate a software interrupt for a dedicated line. + * @param heint Eint handle. + * @retval None. + */ +void DAL_EINT_GenerateSWI(EINT_HandleTypeDef *heint) +{ + uint32_t maskline; + + /* Check parameters */ + ASSERT_PARAM(IS_EINT_LINE(heint->Line)); + ASSERT_PARAM(IS_EINT_CONFIG_LINE(heint->Line)); + + /* Compute line mask */ + maskline = (1uL << (heint->Line & EINT_PIN_MASK)); + + /* Generate Software interrupt */ + EINT->SWINTE = maskline; +} + +/** + * @} + */ + +/** + * @} + */ + +#endif /* DAL_EINT_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_eth.c b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_eth.c new file mode 100644 index 0000000000..3a48c7b951 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_eth.c @@ -0,0 +1,3137 @@ +/** + * + * @file apm32f4xx_dal_eth.c + * @brief ETH DAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the Ethernet (ETH) peripheral: + * + Initialization and deinitialization functions + * + IO operation functions + * + Peripheral Control functions + * + Peripheral State and Errors functions + * + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + * + @verbatim + ============================================================================== + ##### How to use this driver ##### + ============================================================================== + [..] + The ETH DAL driver can be used as follows: + + (#)Declare a ETH_HandleTypeDef handle structure, for example: + ETH_HandleTypeDef heth; + + (#)Fill parameters of Init structure in heth handle + + (#)Call DAL_ETH_Init() API to initialize the Ethernet peripheral (MAC, DMA, ...) + + (#)Initialize the ETH low level resources through the DAL_ETH_MspInit() API: + (##) Enable the Ethernet interface clock using + (+++) __DAL_RCM_ETH1MAC_CLK_ENABLE() + (+++) __DAL_RCM_ETH1TX_CLK_ENABLE() + (+++) __DAL_RCM_ETH1RX_CLK_ENABLE() + + (##) Initialize the related GPIO clocks + (##) Configure Ethernet pinout + (##) Configure Ethernet NVIC interrupt (in Interrupt mode) + + (#) Ethernet data reception is asynchronous, so call the following API + to start the listening mode: + (##) DAL_ETH_Start(): + This API starts the MAC and DMA transmission and reception process, + without enabling end of transfer interrupts, in this mode user + has to poll for data reception by calling DAL_ETH_ReadData() + (##) DAL_ETH_Start_IT(): + This API starts the MAC and DMA transmission and reception process, + end of transfer interrupts are enabled in this mode, + DAL_ETH_RxCpltCallback() will be executed when an Ethernet packet is received + + (#) When data is received user can call the following API to get received data: + (##) DAL_ETH_ReadData(): Read a received packet + + (#) For transmission path, two APIs are available: + (##) DAL_ETH_Transmit(): Transmit an ETH frame in blocking mode + (##) DAL_ETH_Transmit_IT(): Transmit an ETH frame in interrupt mode, + DAL_ETH_TxCpltCallback() will be executed when end of transfer occur + + (#) Communication with an external PHY device: + (##) DAL_ETH_ReadPHYRegister(): Read a register from an external PHY + (##) DAL_ETH_WritePHYRegister(): Write data to an external RHY register + + (#) Configure the Ethernet MAC after ETH peripheral initialization + (##) DAL_ETH_GetMACConfig(): Get MAC actual configuration into ETH_MACConfigTypeDef + (##) DAL_ETH_SetMACConfig(): Set MAC configuration based on ETH_MACConfigTypeDef + + (#) Configure the Ethernet DMA after ETH peripheral initialization + (##) DAL_ETH_GetDMAConfig(): Get DMA actual configuration into ETH_DMAConfigTypeDef + (##) DAL_ETH_SetDMAConfig(): Set DMA configuration based on ETH_DMAConfigTypeDef + + (#) Configure the Ethernet PTP after ETH peripheral initialization + (##) Define DAL_ETH_USE_PTP to use PTP APIs. + (##) DAL_ETH_PTP_GetConfig(): Get PTP actual configuration into ETH_PTP_ConfigTypeDef + (##) DAL_ETH_PTP_SetConfig(): Set PTP configuration based on ETH_PTP_ConfigTypeDef + (##) DAL_ETH_PTP_GetTime(): Get Seconds and Nanoseconds for the Ethernet PTP registers + (##) DAL_ETH_PTP_SetTime(): Set Seconds and Nanoseconds for the Ethernet PTP registers + (##) DAL_ETH_PTP_AddTimeOffset(): Add Seconds and Nanoseconds offset for the Ethernet PTP registers + (##) DAL_ETH_PTP_InsertTxTimestamp(): Insert Timestamp in transmission + (##) DAL_ETH_PTP_GetTxTimestamp(): Get transmission timestamp + (##) DAL_ETH_PTP_GetRxTimestamp(): Get reception timestamp + + -@- The ARP offload feature is not supported in this driver. + + -@- The PTP offload feature is not supported in this driver. + + *** Callback registration *** + ============================================= + + The compilation define USE_DAL_ETH_REGISTER_CALLBACKS when set to 1 + allows the user to configure dynamically the driver callbacks. + Use Function DAL_ETH_RegisterCallback() to register an interrupt callback. + + Function DAL_ETH_RegisterCallback() allows to register following callbacks: + (+) TxCpltCallback : Tx Complete Callback. + (+) RxCpltCallback : Rx Complete Callback. + (+) ErrorCallback : Error Callback. + (+) PMTCallback : Power Management Callback + (+) EEECallback : EEE Callback. + (+) WakeUpCallback : Wake UP Callback + (+) MspInitCallback : MspInit Callback. + (+) MspDeInitCallback: MspDeInit Callback. + + This function takes as parameters the DAL peripheral handle, the Callback ID + and a pointer to the user callback function. + + For specific callbacks RxAllocateCallback use dedicated register callbacks: + respectively DAL_ETH_RegisterRxAllocateCallback(). + + For specific callbacks RxLinkCallback use dedicated register callbacks: + respectively DAL_ETH_RegisterRxLinkCallback(). + + For specific callbacks TxFreeCallback use dedicated register callbacks: + respectively DAL_ETH_RegisterTxFreeCallback(). + + For specific callbacks TxPtpCallback use dedicated register callbacks: + respectively DAL_ETH_RegisterTxPtpCallback(). + + Use function DAL_ETH_UnRegisterCallback() to reset a callback to the default + weak function. + DAL_ETH_UnRegisterCallback takes as parameters the DAL peripheral handle, + and the Callback ID. + This function allows to reset following callbacks: + (+) TxCpltCallback : Tx Complete Callback. + (+) RxCpltCallback : Rx Complete Callback. + (+) ErrorCallback : Error Callback. + (+) PMTCallback : Power Management Callback + (+) EEECallback : EEE Callback. + (+) WakeUpCallback : Wake UP Callback + (+) MspInitCallback : MspInit Callback. + (+) MspDeInitCallback: MspDeInit Callback. + + For specific callbacks RxAllocateCallback use dedicated unregister callbacks: + respectively DAL_ETH_UnRegisterRxAllocateCallback(). + + For specific callbacks RxLinkCallback use dedicated unregister callbacks: + respectively DAL_ETH_UnRegisterRxLinkCallback(). + + For specific callbacks TxFreeCallback use dedicated unregister callbacks: + respectively DAL_ETH_UnRegisterTxFreeCallback(). + + For specific callbacks TxPtpCallback use dedicated unregister callbacks: + respectively DAL_ETH_UnRegisterTxPtpCallback(). + + By default, after the DAL_ETH_Init and when the state is DAL_ETH_STATE_RESET + all callbacks are set to the corresponding weak functions: + examples DAL_ETH_TxCpltCallback(), DAL_ETH_RxCpltCallback(). + Exception done for MspInit and MspDeInit functions that are + reset to the legacy weak function in the DAL_ETH_Init/ DAL_ETH_DeInit only when + these callbacks are null (not registered beforehand). + if not, MspInit or MspDeInit are not null, the DAL_ETH_Init/ DAL_ETH_DeInit + keep and use the user MspInit/MspDeInit callbacks (registered beforehand) + + Callbacks can be registered/unregistered in DAL_ETH_STATE_READY state only. + Exception done MspInit/MspDeInit that can be registered/unregistered + in DAL_ETH_STATE_READY or DAL_ETH_STATE_RESET state, + thus registered (user) MspInit/DeInit callbacks can be used during the Init/DeInit. + In that case first register the MspInit/MspDeInit user callbacks + using DAL_ETH_RegisterCallback() before calling DAL_ETH_DeInit + or DAL_ETH_Init function. + + When The compilation define USE_DAL_ETH_REGISTER_CALLBACKS is set to 0 or + not defined, the callback registration feature is not available and all callbacks + are set to the corresponding weak functions. + + @endverbatim + * + */ + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ +#ifdef DAL_ETH_MODULE_ENABLED + +#if defined(ETH) + +/** @defgroup ETH ETH + * @brief ETH DAL module driver + * @{ + */ + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/** @addtogroup ETH_Private_Constants ETH Private Constants + * @{ + */ +#define ETH_MACCFG_MASK ((uint32_t)0xFFFB7F7CU) +#define ETH_MACECR_MASK ((uint32_t)0x3F077FFFU) +#define ETH_MACFRAF_MASK ((uint32_t)0x800007FFU) +#define ETH_MACWTR_MASK ((uint32_t)0x0000010FU) +#define ETH_MACTFCR_MASK ((uint32_t)0xFFFF00F2U) +#define ETH_MACRFCR_MASK ((uint32_t)0x00000003U) +#define ETH_MTLTQOMR_MASK ((uint32_t)0x00000072U) +#define ETH_MTLRQOMR_MASK ((uint32_t)0x0000007BU) + +#define ETH_DMAMR_MASK ((uint32_t)0x00007802U) +#define ETH_DMASBMR_MASK ((uint32_t)0x0000D001U) +#define ETH_DMACCR_MASK ((uint32_t)0x00013FFFU) +#define ETH_DMACTCR_MASK ((uint32_t)0x003F1010U) +#define ETH_DMACRCR_MASK ((uint32_t)0x803F0000U) +#define ETH_MACPMTCTRLSTS_MASK (ETH_MACPMTCTRLSTS_PD | ETH_MACPMTCTRLSTS_WKUPFEN | \ + ETH_MACPMTCTRLSTS_MPEN | ETH_MACPMTCTRLSTS_GUN) + +/* Timeout values */ +#define ETH_SWRESET_TIMEOUT ((uint32_t)500U) +#define ETH_MDIO_BUS_TIMEOUT ((uint32_t)1000U) + +#define ETH_DMARXDESC_ERRORS_MASK ((uint32_t)(ETH_DMARXDESC_DBE | ETH_DMARXDESC_RE | \ + ETH_DMARXDESC_OE | ETH_DMARXDESC_RWT |\ + ETH_DMARXDESC_LC | ETH_DMARXDESC_CE |\ + ETH_DMARXDESC_DE | ETH_DMARXDESC_IPV4HCE)) + +#define ETH_MAC_US_TICK ((uint32_t)1000000U) + +#define ETH_MACTSCR_MASK ((uint32_t)0x0087FF2FU) + +#define ETH_PTPTSH_VALUE ((uint32_t)0xFFFFFFFFU) +#define ETH_PTPTSL_VALUE ((uint32_t)0xBB9ACA00U) + +/* Ethernet MACMIIAR register Mask */ +#define ETH_MACADDR_CR_MASK ((uint32_t)0xFFFFFFE3U) + +/* Delay to wait when writing to some Ethernet registers */ +#define ETH_REG_WRITE_DELAY ((uint32_t)0x00000001U) + +/* ETHERNET MACCR register Mask */ +#define ETH_MACCFG_CLEAR_MASK 0xFF20810FU + +/* ETHERNET MACFCR register Mask */ +#define ETH_MACFCTRL_CLEAR_MASK 0x0000FF41U + +/* ETHERNET DMAOMR register Mask */ +#define ETH_DMAOPMOD_CLEAR_MASK 0xF8DE3F23U + +/* ETHERNET MAC address offsets */ +#define ETH_MAC_ADDR_HBASE (uint32_t)(ETH_MAC_BASE + 0x40U) /* ETHERNET MAC address high offset */ +#define ETH_MAC_ADDR_LBASE (uint32_t)(ETH_MAC_BASE + 0x44U) /* ETHERNET MAC address low offset */ + +/* ETHERNET DMA Rx descriptors Frame length Shift */ +#define ETH_DMARXDESC_FRAMELENGTHSHIFT 16U +/** + * @} + */ + +/* Private macros ------------------------------------------------------------*/ +/** @defgroup ETH_Private_Macros ETH Private Macros + * @{ + */ +/* Helper macros for TX descriptor handling */ +#define INCR_TX_DESC_INDEX(inx, offset) do {\ + (inx) += (offset);\ + if ((inx) >= (uint32_t)ETH_TX_DESC_CNT){\ + (inx) = ((inx) - (uint32_t)ETH_TX_DESC_CNT);}\ + } while (0) + +/* Helper macros for RX descriptor handling */ +#define INCR_RX_DESC_INDEX(inx, offset) do {\ + (inx) += (offset);\ + if ((inx) >= (uint32_t)ETH_RX_DESC_CNT){\ + (inx) = ((inx) - (uint32_t)ETH_RX_DESC_CNT);}\ + } while (0) +/** + * @} + */ +/* Private function prototypes -----------------------------------------------*/ +/** @defgroup ETH_Private_Functions ETH Private Functions + * @{ + */ +static void ETH_SetMACConfig(ETH_HandleTypeDef *heth, ETH_MACConfigTypeDef *macconf); +static void ETH_SetDMAConfig(ETH_HandleTypeDef *heth, ETH_DMAConfigTypeDef *dmaconf); +static void ETH_MACDMAConfig(ETH_HandleTypeDef *heth); +static void ETH_DMATxDescListInit(ETH_HandleTypeDef *heth); +static void ETH_DMARxDescListInit(ETH_HandleTypeDef *heth); +static uint32_t ETH_Prepare_Tx_Descriptors(ETH_HandleTypeDef *heth, ETH_TxPacketConfig *pTxConfig, uint32_t ItMode); +static void ETH_UpdateDescriptor(ETH_HandleTypeDef *heth); +static void ETH_FlushTransmitFIFO(ETH_HandleTypeDef *heth); +static void ETH_MACAddressConfig(ETH_HandleTypeDef *heth, uint32_t MacAddr, uint8_t *Addr); + +#if (USE_DAL_ETH_REGISTER_CALLBACKS == 1) +static void ETH_InitCallbacksToDefault(ETH_HandleTypeDef *heth); +#endif /* USE_DAL_ETH_REGISTER_CALLBACKS */ +/** + * @} + */ + +/* Exported functions ---------------------------------------------------------*/ +/** @defgroup ETH_Exported_Functions ETH Exported Functions + * @{ + */ + +/** @defgroup ETH_Exported_Functions_Group1 Initialization and deinitialization functions + * @brief Initialization and Configuration functions + * +@verbatim +=============================================================================== + ##### Initialization and Configuration functions ##### + =============================================================================== + [..] This subsection provides a set of functions allowing to initialize and + deinitialize the ETH peripheral: + + (+) User must Implement DAL_ETH_MspInit() function in which he configures + all related peripherals resources (CLOCK, GPIO and NVIC ). + + (+) Call the function DAL_ETH_Init() to configure the selected device with + the selected configuration: + (++) MAC address + (++) Media interface (MII or RMII) + (++) Rx DMA Descriptors Tab + (++) Tx DMA Descriptors Tab + (++) Length of Rx Buffers + + (+) Call the function DAL_ETH_DeInit() to restore the default configuration + of the selected ETH peripheral. + +@endverbatim + * @{ + */ + +/** + * @brief Initialize the Ethernet peripheral registers. + * @param heth: pointer to a ETH_HandleTypeDef structure that contains + * the configuration information for ETHERNET module + * @retval DAL status + */ +DAL_StatusTypeDef DAL_ETH_Init(ETH_HandleTypeDef *heth) +{ + uint32_t tickstart; + + if (heth == NULL) + { + return DAL_ERROR; + } + if (heth->gState == DAL_ETH_STATE_RESET) + { + heth->gState = DAL_ETH_STATE_BUSY; + +#if (USE_DAL_ETH_REGISTER_CALLBACKS == 1) + + ETH_InitCallbacksToDefault(heth); + + if (heth->MspInitCallback == NULL) + { + heth->MspInitCallback = DAL_ETH_MspInit; + } + + /* Init the low level hardware */ + heth->MspInitCallback(heth); +#else + /* Init the low level hardware : GPIO, CLOCK, NVIC. */ + DAL_ETH_MspInit(heth); + +#endif /* (USE_DAL_ETH_REGISTER_CALLBACKS) */ + } + + __DAL_RCM_SYSCFG_CLK_ENABLE(); + + /* Select MII or RMII Mode*/ + SYSCFG->PMCFG &= ~(SYSCFG_PMCFG_ENETSEL); + SYSCFG->PMCFG |= (uint32_t)heth->Init.MediaInterface; + /* Dummy read to sync SYSCFG with ETH */ + (void)SYSCFG->PMCFG; + + /* Ethernet Software reset */ + /* Set the SWR bit: resets all MAC subsystem internal registers and logic */ + /* After reset all the registers holds their respective reset values */ + SET_BIT(heth->Instance->DMABMOD, ETH_DMABMOD_SWR); + + /* Get tick */ + tickstart = DAL_GetTick(); + + /* Wait for software reset */ + while (READ_BIT(heth->Instance->DMABMOD, ETH_DMABMOD_SWR) > 0U) + { + if (((DAL_GetTick() - tickstart) > ETH_SWRESET_TIMEOUT)) + { + /* Set Error Code */ + heth->ErrorCode = DAL_ETH_ERROR_TIMEOUT; + /* Set State as Error */ + heth->gState = DAL_ETH_STATE_ERROR; + /* Return Error */ + return DAL_ERROR; + } + } + + + /*------------------ MAC, MTL and DMA default Configuration ----------------*/ + ETH_MACDMAConfig(heth); + + + /*------------------ DMA Tx Descriptors Configuration ----------------------*/ + ETH_DMATxDescListInit(heth); + + /*------------------ DMA Rx Descriptors Configuration ----------------------*/ + ETH_DMARxDescListInit(heth); + + /*--------------------- ETHERNET MAC Address Configuration ------------------*/ + ETH_MACAddressConfig(heth, ETH_MAC_ADDRESS0, heth->Init.MACAddr); + + heth->ErrorCode = DAL_ETH_ERROR_NONE; + heth->gState = DAL_ETH_STATE_READY; + + return DAL_OK; +} + +/** + * @brief DeInitializes the ETH peripheral. + * @param heth: pointer to a ETH_HandleTypeDef structure that contains + * the configuration information for ETHERNET module + * @retval DAL status + */ +DAL_StatusTypeDef DAL_ETH_DeInit(ETH_HandleTypeDef *heth) +{ + /* Set the ETH peripheral state to BUSY */ + heth->gState = DAL_ETH_STATE_BUSY; + +#if (USE_DAL_ETH_REGISTER_CALLBACKS == 1) + + if (heth->MspDeInitCallback == NULL) + { + heth->MspDeInitCallback = DAL_ETH_MspDeInit; + } + /* DeInit the low level hardware */ + heth->MspDeInitCallback(heth); +#else + + /* De-Init the low level hardware : GPIO, CLOCK, NVIC. */ + DAL_ETH_MspDeInit(heth); + +#endif /* (USE_DAL_ETH_REGISTER_CALLBACKS) */ + + /* Set ETH DAL state to Disabled */ + heth->gState = DAL_ETH_STATE_RESET; + + /* Return function status */ + return DAL_OK; +} + +/** + * @brief Initializes the ETH MSP. + * @param heth: pointer to a ETH_HandleTypeDef structure that contains + * the configuration information for ETHERNET module + * @retval None + */ +__weak void DAL_ETH_MspInit(ETH_HandleTypeDef *heth) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(heth); + /* NOTE : This function Should not be modified, when the callback is needed, + the DAL_ETH_MspInit could be implemented in the user file + */ +} + +/** + * @brief DeInitializes ETH MSP. + * @param heth: pointer to a ETH_HandleTypeDef structure that contains + * the configuration information for ETHERNET module + * @retval None + */ +__weak void DAL_ETH_MspDeInit(ETH_HandleTypeDef *heth) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(heth); + /* NOTE : This function Should not be modified, when the callback is needed, + the DAL_ETH_MspDeInit could be implemented in the user file + */ +} + +#if (USE_DAL_ETH_REGISTER_CALLBACKS == 1) +/** + * @brief Register a User ETH Callback + * To be used instead of the weak predefined callback + * @param heth eth handle + * @param CallbackID ID of the callback to be registered + * This parameter can be one of the following values: + * @arg @ref DAL_ETH_TX_COMPLETE_CB_ID Tx Complete Callback ID + * @arg @ref DAL_ETH_RX_COMPLETE_CB_ID Rx Complete Callback ID + * @arg @ref DAL_ETH_ERROR_CB_ID Error Callback ID + * @arg @ref DAL_ETH_PMT_CB_ID Power Management Callback ID + * @arg @ref DAL_ETH_WAKEUP_CB_ID Wake UP Callback ID + * @arg @ref DAL_ETH_MSPINIT_CB_ID MspInit callback ID + * @arg @ref DAL_ETH_MSPDEINIT_CB_ID MspDeInit callback ID + * @param pCallback pointer to the Callback function + * @retval status + */ +DAL_StatusTypeDef DAL_ETH_RegisterCallback(ETH_HandleTypeDef *heth, DAL_ETH_CallbackIDTypeDef CallbackID, + pETH_CallbackTypeDef pCallback) +{ + DAL_StatusTypeDef status = DAL_OK; + + if (pCallback == NULL) + { + /* Update the error code */ + heth->ErrorCode |= DAL_ETH_ERROR_INVALID_CALLBACK; + + return DAL_ERROR; + } + + if (heth->gState == DAL_ETH_STATE_READY) + { + switch (CallbackID) + { + case DAL_ETH_TX_COMPLETE_CB_ID : + heth->TxCpltCallback = pCallback; + break; + + case DAL_ETH_RX_COMPLETE_CB_ID : + heth->RxCpltCallback = pCallback; + break; + + case DAL_ETH_ERROR_CB_ID : + heth->ErrorCallback = pCallback; + break; + + case DAL_ETH_PMT_CB_ID : + heth->PMTCallback = pCallback; + break; + + + case DAL_ETH_WAKEUP_CB_ID : + heth->WakeUpCallback = pCallback; + break; + + case DAL_ETH_MSPINIT_CB_ID : + heth->MspInitCallback = pCallback; + break; + + case DAL_ETH_MSPDEINIT_CB_ID : + heth->MspDeInitCallback = pCallback; + break; + + default : + /* Update the error code */ + heth->ErrorCode |= DAL_ETH_ERROR_INVALID_CALLBACK; + /* Return error status */ + status = DAL_ERROR; + break; + } + } + else if (heth->gState == DAL_ETH_STATE_RESET) + { + switch (CallbackID) + { + case DAL_ETH_MSPINIT_CB_ID : + heth->MspInitCallback = pCallback; + break; + + case DAL_ETH_MSPDEINIT_CB_ID : + heth->MspDeInitCallback = pCallback; + break; + + default : + /* Update the error code */ + heth->ErrorCode |= DAL_ETH_ERROR_INVALID_CALLBACK; + /* Return error status */ + status = DAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + heth->ErrorCode |= DAL_ETH_ERROR_INVALID_CALLBACK; + /* Return error status */ + status = DAL_ERROR; + } + + return status; +} + +/** + * @brief Unregister an ETH Callback + * ETH callabck is redirected to the weak predefined callback + * @param heth eth handle + * @param CallbackID ID of the callback to be unregistered + * This parameter can be one of the following values: + * @arg @ref DAL_ETH_TX_COMPLETE_CB_ID Tx Complete Callback ID + * @arg @ref DAL_ETH_RX_COMPLETE_CB_ID Rx Complete Callback ID + * @arg @ref DAL_ETH_ERROR_CB_ID Error Callback ID + * @arg @ref DAL_ETH_PMT_CB_ID Power Management Callback ID + * @arg @ref DAL_ETH_WAKEUP_CB_ID Wake UP Callback ID + * @arg @ref DAL_ETH_MSPINIT_CB_ID MspInit callback ID + * @arg @ref DAL_ETH_MSPDEINIT_CB_ID MspDeInit callback ID + * @retval status + */ +DAL_StatusTypeDef DAL_ETH_UnRegisterCallback(ETH_HandleTypeDef *heth, DAL_ETH_CallbackIDTypeDef CallbackID) +{ + DAL_StatusTypeDef status = DAL_OK; + + if (heth->gState == DAL_ETH_STATE_READY) + { + switch (CallbackID) + { + case DAL_ETH_TX_COMPLETE_CB_ID : + heth->TxCpltCallback = DAL_ETH_TxCpltCallback; + break; + + case DAL_ETH_RX_COMPLETE_CB_ID : + heth->RxCpltCallback = DAL_ETH_RxCpltCallback; + break; + + case DAL_ETH_ERROR_CB_ID : + heth->ErrorCallback = DAL_ETH_ErrorCallback; + break; + + case DAL_ETH_PMT_CB_ID : + heth->PMTCallback = DAL_ETH_PMTCallback; + break; + + + case DAL_ETH_WAKEUP_CB_ID : + heth->WakeUpCallback = DAL_ETH_WakeUpCallback; + break; + + case DAL_ETH_MSPINIT_CB_ID : + heth->MspInitCallback = DAL_ETH_MspInit; + break; + + case DAL_ETH_MSPDEINIT_CB_ID : + heth->MspDeInitCallback = DAL_ETH_MspDeInit; + break; + + default : + /* Update the error code */ + heth->ErrorCode |= DAL_ETH_ERROR_INVALID_CALLBACK; + /* Return error status */ + status = DAL_ERROR; + break; + } + } + else if (heth->gState == DAL_ETH_STATE_RESET) + { + switch (CallbackID) + { + case DAL_ETH_MSPINIT_CB_ID : + heth->MspInitCallback = DAL_ETH_MspInit; + break; + + case DAL_ETH_MSPDEINIT_CB_ID : + heth->MspDeInitCallback = DAL_ETH_MspDeInit; + break; + + default : + /* Update the error code */ + heth->ErrorCode |= DAL_ETH_ERROR_INVALID_CALLBACK; + /* Return error status */ + status = DAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + heth->ErrorCode |= DAL_ETH_ERROR_INVALID_CALLBACK; + /* Return error status */ + status = DAL_ERROR; + } + + return status; +} +#endif /* USE_DAL_ETH_REGISTER_CALLBACKS */ + +/** + * @} + */ + +/** @defgroup ETH_Exported_Functions_Group2 IO operation functions + * @brief ETH Transmit and Receive functions + * +@verbatim + ============================================================================== + ##### IO operation functions ##### + ============================================================================== + [..] + This subsection provides a set of functions allowing to manage the ETH + data transfer. + +@endverbatim + * @{ + */ + +/** + * @brief Enables Ethernet MAC and DMA reception and transmission + * @param heth: pointer to a ETH_HandleTypeDef structure that contains + * the configuration information for ETHERNET module + * @retval DAL status + */ +DAL_StatusTypeDef DAL_ETH_Start(ETH_HandleTypeDef *heth) +{ + if (heth->gState == DAL_ETH_STATE_READY) + { + heth->gState = DAL_ETH_STATE_BUSY; + + /* Set nombre of descriptors to build */ + heth->RxDescList.RxBuildDescCnt = ETH_RX_DESC_CNT; + + /* Build all descriptors */ + ETH_UpdateDescriptor(heth); + + /* Enable the MAC transmission */ + SET_BIT(heth->Instance->MACCFG, ETH_MACCFG_TXEN); + + /* Enable the MAC reception */ + SET_BIT(heth->Instance->MACCFG, ETH_MACCFG_RXEN); + + /* Flush Transmit FIFO */ + ETH_FlushTransmitFIFO(heth); + + /* Enable the DMA transmission */ + SET_BIT(heth->Instance->DMAOPMOD, ETH_DMAOPMOD_STTX); + + /* Enable the DMA reception */ + SET_BIT(heth->Instance->DMAOPMOD, ETH_DMAOPMOD_STRX); + + heth->gState = DAL_ETH_STATE_STARTED; + + return DAL_OK; + } + else + { + return DAL_ERROR; + } +} + +/** + * @brief Enables Ethernet MAC and DMA reception/transmission in Interrupt mode + * @param heth: pointer to a ETH_HandleTypeDef structure that contains + * the configuration information for ETHERNET module + * @retval DAL status + */ +DAL_StatusTypeDef DAL_ETH_Start_IT(ETH_HandleTypeDef *heth) +{ + if (heth->gState == DAL_ETH_STATE_READY) + { + heth->gState = DAL_ETH_STATE_BUSY; + + /* save IT mode to ETH Handle */ + heth->RxDescList.ItMode = 1U; + /* Disable MMC Interrupts */ + SET_BIT(heth->Instance->MACIMASK, ETH_MACIMASK_TSTIM | ETH_MACIMASK_PMTIM); + + /* Disable Rx MMC Interrupts */ + SET_BIT(heth->Instance->MMCRXINTMASK, ETH_MMCRXINTMASK_RXGUNFM | ETH_MMCRXINTMASK_RXFAEM | \ + ETH_MMCRXINTMASK_RXFCEM); + + /* Disable Tx MMC Interrupts */ + SET_BIT(heth->Instance->MMCTXINTMASK, ETH_MMCTXINTMASK_TXGFM | ETH_MMCTXINTMASK_TXGFMCOLM | \ + ETH_MMCTXINTMASK_TXGFSCOLM); + + /* Set nombre of descriptors to build */ + heth->RxDescList.RxBuildDescCnt = ETH_RX_DESC_CNT; + + /* Build all descriptors */ + ETH_UpdateDescriptor(heth); + + /* Enable the MAC transmission */ + SET_BIT(heth->Instance->MACCFG, ETH_MACCFG_TXEN); + + /* Enable the MAC reception */ + SET_BIT(heth->Instance->MACCFG, ETH_MACCFG_RXEN); + + /* Flush Transmit FIFO */ + ETH_FlushTransmitFIFO(heth); + + /* Enable the DMA transmission */ + SET_BIT(heth->Instance->DMAOPMOD, ETH_DMAOPMOD_STTX); + + /* Enable the DMA reception */ + SET_BIT(heth->Instance->DMAOPMOD, ETH_DMAOPMOD_STRX); + + /* Enable ETH DMA interrupts: + - Tx complete interrupt + - Rx complete interrupt + - Fatal bus interrupt + */ + __DAL_ETH_DMA_ENABLE_IT(heth, (ETH_DMAINTEN_NINTSEN | ETH_DMAINTEN_RXIEN | ETH_DMAINTEN_TXIEN | + ETH_DMAINTEN_FBERREN | ETH_DMAINTEN_AINTSEN | ETH_DMAINTEN_RXBUEN)); + + heth->gState = DAL_ETH_STATE_STARTED; + return DAL_OK; + } + else + { + return DAL_ERROR; + } +} + +/** + * @brief Stop Ethernet MAC and DMA reception/transmission + * @param heth: pointer to a ETH_HandleTypeDef structure that contains + * the configuration information for ETHERNET module + * @retval DAL status + */ +DAL_StatusTypeDef DAL_ETH_Stop(ETH_HandleTypeDef *heth) +{ + if (heth->gState == DAL_ETH_STATE_STARTED) + { + /* Set the ETH peripheral state to BUSY */ + heth->gState = DAL_ETH_STATE_BUSY; + /* Disable the DMA transmission */ + CLEAR_BIT(heth->Instance->MACCFG, ETH_MACCFG_TXEN); + + /* Disable the DMA reception */ + CLEAR_BIT(heth->Instance->DMAOPMOD, ETH_DMAOPMOD_STRX); + + /* Disable the MAC reception */ + CLEAR_BIT(heth->Instance->MACCFG, ETH_MACCFG_RXEN); + + /* Flush Transmit FIFO */ + ETH_FlushTransmitFIFO(heth); + + /* Disable the MAC transmission */ + CLEAR_BIT(heth->Instance->MACCFG, ETH_MACCFG_TXEN); + + heth->gState = DAL_ETH_STATE_READY; + + /* Return function status */ + return DAL_OK; + } + else + { + return DAL_ERROR; + } +} + +/** + * @brief Stop Ethernet MAC and DMA reception/transmission in Interrupt mode + * @param heth: pointer to a ETH_HandleTypeDef structure that contains + * the configuration information for ETHERNET module + * @retval DAL status + */ +DAL_StatusTypeDef DAL_ETH_Stop_IT(ETH_HandleTypeDef *heth) +{ + ETH_DMADescTypeDef *dmarxdesc; + uint32_t descindex; + + if (heth->gState == DAL_ETH_STATE_STARTED) + { + /* Set the ETH peripheral state to BUSY */ + heth->gState = DAL_ETH_STATE_BUSY; + + __DAL_ETH_DMA_DISABLE_IT(heth, (ETH_DMAINTEN_NINTSEN | ETH_DMAINTEN_RXIEN | ETH_DMAINTEN_TXIEN | + ETH_DMAINTEN_FBERREN | ETH_DMAINTEN_AINTSEN | ETH_DMAINTEN_RXBUEN)); + + /* Disable the DMA transmission */ + CLEAR_BIT(heth->Instance->MACCFG, ETH_MACCFG_TXEN); + + /* Disable the DMA reception */ + CLEAR_BIT(heth->Instance->DMAOPMOD, ETH_DMAOPMOD_STRX); + + /* Disable the MAC reception */ + CLEAR_BIT(heth->Instance->MACCFG, ETH_MACCFG_RXEN); + /* Flush Transmit FIFO */ + ETH_FlushTransmitFIFO(heth); + + /* Disable the MAC transmission */ + CLEAR_BIT(heth->Instance->MACCFG, ETH_MACCFG_TXEN); + + /* Clear IOC bit to all Rx descriptors */ + for (descindex = 0; descindex < (uint32_t)ETH_RX_DESC_CNT; descindex++) + { + dmarxdesc = (ETH_DMADescTypeDef *)heth->RxDescList.RxDesc[descindex]; + SET_BIT(dmarxdesc->DESC1, ETH_DMARXDESC_DIC); + } + + heth->RxDescList.ItMode = 0U; + + heth->gState = DAL_ETH_STATE_READY; + + /* Return function status */ + return DAL_OK; + } + else + { + return DAL_ERROR; + } +} + +/** + * @brief Sends an Ethernet Packet in polling mode. + * @param heth: pointer to a ETH_HandleTypeDef structure that contains + * the configuration information for ETHERNET module + * @param pTxConfig: Hold the configuration of packet to be transmitted + * @param Timeout: timeout value + * @retval DAL status + */ +DAL_StatusTypeDef DAL_ETH_Transmit(ETH_HandleTypeDef *heth, ETH_TxPacketConfig *pTxConfig, uint32_t Timeout) +{ + uint32_t tickstart; + ETH_DMADescTypeDef *dmatxdesc; + + if (pTxConfig == NULL) + { + heth->ErrorCode |= DAL_ETH_ERROR_PARAM; + return DAL_ERROR; + } + + if (heth->gState == DAL_ETH_STATE_STARTED) + { + /* Config DMA Tx descriptor by Tx Packet info */ + if (ETH_Prepare_Tx_Descriptors(heth, pTxConfig, 0) != DAL_ETH_ERROR_NONE) + { + /* Set the ETH error code */ + heth->ErrorCode |= DAL_ETH_ERROR_BUSY; + return DAL_ERROR; + } + + /* Ensure completion of descriptor preparation before transmission start */ + __DSB(); + + dmatxdesc = (ETH_DMADescTypeDef *)(&heth->TxDescList)->TxDesc[heth->TxDescList.CurTxDesc]; + + /* Incr current tx desc index */ + INCR_TX_DESC_INDEX(heth->TxDescList.CurTxDesc, 1U); + + /* Start transmission */ + /* issue a poll command to Tx DMA by writing address of next immediate free descriptor */ + WRITE_REG(heth->Instance->DMATXPD, (uint32_t)(heth->TxDescList.TxDesc[heth->TxDescList.CurTxDesc])); + + tickstart = DAL_GetTick(); + + /* Wait for data to be transmitted or timeout occurred */ + while ((dmatxdesc->DESC0 & ETH_DMATXDESC_OWN) != (uint32_t)RESET) + { + if ((heth->Instance->DMASTS & ETH_DMASTS_FBERRFLG) != (uint32_t)RESET) + { + heth->ErrorCode |= DAL_ETH_ERROR_DMA; + heth->DMAErrorCode = heth->Instance->DMASTS; + /* Return function status */ + return DAL_ERROR; + } + + /* Check for the Timeout */ + if (Timeout != DAL_MAX_DELAY) + { + if (((DAL_GetTick() - tickstart) > Timeout) || (Timeout == 0U)) + { + heth->ErrorCode |= DAL_ETH_ERROR_TIMEOUT; + /* Clear TX descriptor so that we can proceed */ + dmatxdesc->DESC0 = (ETH_DMATXDESC_FS | ETH_DMATXDESC_LS); + return DAL_ERROR; + } + } + } + + /* Return function status */ + return DAL_OK; + } + else + { + return DAL_ERROR; + } +} + +/** + * @brief Sends an Ethernet Packet in interrupt mode. + * @param heth: pointer to a ETH_HandleTypeDef structure that contains + * the configuration information for ETHERNET module + * @param pTxConfig: Hold the configuration of packet to be transmitted + * @retval DAL status + */ +DAL_StatusTypeDef DAL_ETH_Transmit_IT(ETH_HandleTypeDef *heth, ETH_TxPacketConfig *pTxConfig) +{ + if (pTxConfig == NULL) + { + heth->ErrorCode |= DAL_ETH_ERROR_PARAM; + return DAL_ERROR; + } + + if (heth->gState == DAL_ETH_STATE_STARTED) + { + /* Save the packet pointer to release. */ + heth->TxDescList.CurrentPacketAddress = (uint32_t *)pTxConfig->pData; + + /* Config DMA Tx descriptor by Tx Packet info */ + if (ETH_Prepare_Tx_Descriptors(heth, pTxConfig, 1) != DAL_ETH_ERROR_NONE) + { + heth->ErrorCode |= DAL_ETH_ERROR_BUSY; + return DAL_ERROR; + } + + /* Ensure completion of descriptor preparation before transmission start */ + __DSB(); + + /* Incr current tx desc index */ + INCR_TX_DESC_INDEX(heth->TxDescList.CurTxDesc, 1U); + + /* Start transmission */ + /* issue a poll command to Tx DMA by writing address of next immediate free descriptor */ + if (((heth->Instance)->DMASTS & ETH_DMASTS_TXBU) != (uint32_t)RESET) + { + /* Clear TXBU ETHERNET DMA flag */ + (heth->Instance)->DMASTS = ETH_DMASTS_TXBU; + /* Resume DMA transmission*/ + (heth->Instance)->DMATXPD = 0U; + } + + return DAL_OK; + + } + else + { + return DAL_ERROR; + } +} + +/** + * @brief Read a received packet. + * @param heth: pointer to a ETH_HandleTypeDef structure that contains + * the configuration information for ETHERNET module + * @param pAppBuff: Pointer to an application buffer to receive the packet. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_ETH_ReadData(ETH_HandleTypeDef *heth, void **pAppBuff) +{ + uint32_t descidx; + ETH_DMADescTypeDef *dmarxdesc; + uint32_t desccnt = 0U; + uint32_t desccntmax; + uint32_t bufflength; + uint8_t rxdataready = 0U; + + + if (pAppBuff == NULL) + { + heth->ErrorCode |= DAL_ETH_ERROR_PARAM; + return DAL_ERROR; + } + + if (heth->gState != DAL_ETH_STATE_STARTED) + { + return DAL_ERROR; + } + + descidx = heth->RxDescList.RxDescIdx; + dmarxdesc = (ETH_DMADescTypeDef *)heth->RxDescList.RxDesc[descidx]; + desccntmax = ETH_RX_DESC_CNT - heth->RxDescList.RxBuildDescCnt; + + /* Check if descriptor is not owned by DMA */ + while ((READ_BIT(dmarxdesc->DESC0, ETH_DMARXDESC_OWN) == (uint32_t)RESET) && (desccnt < desccntmax) + && (rxdataready == 0U)) + { + if (READ_BIT(dmarxdesc->DESC0, ETH_DMARXDESC_LS) != (uint32_t)RESET) + { + /* Get timestamp high */ + heth->RxDescList.TimeStamp.TimeStampHigh = dmarxdesc->DESC6; + /* Get timestamp low */ + heth->RxDescList.TimeStamp.TimeStampLow = dmarxdesc->DESC7; + } + if ((READ_BIT(dmarxdesc->DESC0, ETH_DMARXDESC_FS) != (uint32_t)RESET) || (heth->RxDescList.pRxStart != NULL)) + { + /* Check first descriptor */ + if (READ_BIT(dmarxdesc->DESC0, ETH_DMARXDESC_FS) != (uint32_t)RESET) + { + heth->RxDescList.RxDescCnt = 0; + heth->RxDescList.RxDataLength = 0; + } + + /* Check if last descriptor */ + bufflength = heth->Init.RxBuffLen; + if (READ_BIT(dmarxdesc->DESC0, ETH_DMARXDESC_LS) != (uint32_t)RESET) + { + /* Get the Frame Length of the received packet: substruct 4 bytes of the CRC */ + bufflength = ((dmarxdesc->DESC0 & ETH_DMARXDESC_FL) >> ETH_DMARXDESC_FRAMELENGTHSHIFT) - 4U; + + /* Save Last descriptor index */ + heth->RxDescList.pRxLastRxDesc = dmarxdesc->DESC0; + + /* Packet ready */ + rxdataready = 1; + } + + /* Link data */ + WRITE_REG(dmarxdesc->BackupAddr0, dmarxdesc->DESC2); +#if (USE_DAL_ETH_REGISTER_CALLBACKS == 1) + /*Call registered Link callback*/ + heth->rxLinkCallback(&heth->RxDescList.pRxStart, &heth->RxDescList.pRxEnd, + (uint8_t *)dmarxdesc->BackupAddr0, bufflength); +#else + /* Link callback */ + DAL_ETH_RxLinkCallback(&heth->RxDescList.pRxStart, &heth->RxDescList.pRxEnd, + (uint8_t *)dmarxdesc->BackupAddr0, (uint16_t) bufflength); +#endif /* USE_DAL_ETH_REGISTER_CALLBACKS */ + heth->RxDescList.RxDescCnt++; + heth->RxDescList.RxDataLength += bufflength; + + /* Clear buffer pointer */ + dmarxdesc->BackupAddr0 = 0; + } + + /* Increment current rx descriptor index */ + INCR_RX_DESC_INDEX(descidx, 1U); + /* Get current descriptor address */ + dmarxdesc = (ETH_DMADescTypeDef *)heth->RxDescList.RxDesc[descidx]; + desccnt++; + } + + heth->RxDescList.RxBuildDescCnt += desccnt; + if ((heth->RxDescList.RxBuildDescCnt) != 0U) + { + /* Update Descriptors */ + ETH_UpdateDescriptor(heth); + } + + heth->RxDescList.RxDescIdx = descidx; + + if (rxdataready == 1U) + { + /* Return received packet */ + *pAppBuff = heth->RxDescList.pRxStart; + /* Reset first element */ + heth->RxDescList.pRxStart = NULL; + + return DAL_OK; + } + + /* Packet not ready */ + return DAL_ERROR; +} + +/** + * @brief This function gives back Rx Desc of the last received Packet + * to the DMA, so ETH DMA will be able to use these descriptors + * to receive next Packets. + * @param heth: pointer to a ETH_HandleTypeDef structure that contains + * the configuration information for ETHERNET module + * @retval DAL status + */ +static void ETH_UpdateDescriptor(ETH_HandleTypeDef *heth) +{ + uint32_t descidx; + uint32_t desccount; + ETH_DMADescTypeDef *dmarxdesc; + uint8_t *buff = NULL; + uint8_t allocStatus = 1U; + + descidx = heth->RxDescList.RxBuildDescIdx; + dmarxdesc = (ETH_DMADescTypeDef *)heth->RxDescList.RxDesc[descidx]; + desccount = heth->RxDescList.RxBuildDescCnt; + + while ((desccount > 0U) && (allocStatus != 0U)) + { + /* Check if a buffer's attached the descriptor */ + if (READ_REG(dmarxdesc->BackupAddr0) == 0U) + { + /* Get a new buffer. */ +#if (USE_DAL_ETH_REGISTER_CALLBACKS == 1) + /*Call registered Allocate callback*/ + heth->rxAllocateCallback(&buff); +#else + /* Allocate callback */ + DAL_ETH_RxAllocateCallback(&buff); +#endif /* USE_DAL_ETH_REGISTER_CALLBACKS */ + if (buff == NULL) + { + allocStatus = 0U; + } + else + { + WRITE_REG(dmarxdesc->BackupAddr0, (uint32_t)buff); + WRITE_REG(dmarxdesc->DESC2, (uint32_t)buff); + } + } + + if (allocStatus != 0U) + { + /* Ensure rest of descriptor is written to RAM before the OWN bit */ + __DMB(); + + WRITE_REG(dmarxdesc->DESC0, ETH_DMARXDESC_OWN); + + if (heth->RxDescList.ItMode == 0U) + { + WRITE_REG(dmarxdesc->DESC1, ETH_DMARXDESC_DIC | 1000U | ETH_DMARXDESC_RCH); + } + else + { + WRITE_REG(dmarxdesc->DESC1, 1000U | ETH_DMARXDESC_RCH); + } + + /* Increment current rx descriptor index */ + INCR_RX_DESC_INDEX(descidx, 1U); + /* Get current descriptor address */ + dmarxdesc = (ETH_DMADescTypeDef *)heth->RxDescList.RxDesc[descidx]; + desccount--; + } + } + + if (heth->RxDescList.RxBuildDescCnt != desccount) + { + /* Set the Tail pointer address */ + WRITE_REG(heth->Instance->DMARXPD, 0); + + heth->RxDescList.RxBuildDescIdx = descidx; + heth->RxDescList.RxBuildDescCnt = desccount; + } +} + +/** + * @brief Register the Rx alloc callback. + * @param heth: pointer to a ETH_HandleTypeDef structure that contains + * the configuration information for ETHERNET module + * @param rxAllocateCallback: pointer to function to alloc buffer + * @retval DAL status + */ +DAL_StatusTypeDef DAL_ETH_RegisterRxAllocateCallback(ETH_HandleTypeDef *heth, + pETH_rxAllocateCallbackTypeDef rxAllocateCallback) +{ + if (rxAllocateCallback == NULL) + { + /* No buffer to save */ + return DAL_ERROR; + } + + /* Set function to allocate buffer */ + heth->rxAllocateCallback = rxAllocateCallback; + + return DAL_OK; +} + +/** + * @brief Unregister the Rx alloc callback. + * @param heth: pointer to a ETH_HandleTypeDef structure that contains + * the configuration information for ETHERNET module + * @retval DAL status + */ +DAL_StatusTypeDef DAL_ETH_UnRegisterRxAllocateCallback(ETH_HandleTypeDef *heth) +{ + /* Set function to allocate buffer */ + heth->rxAllocateCallback = DAL_ETH_RxAllocateCallback; + + return DAL_OK; +} + +/** + * @brief Rx Allocate callback. + * @param buff: pointer to allocated buffer + * @retval None + */ +__weak void DAL_ETH_RxAllocateCallback(uint8_t **buff) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(buff); + /* NOTE : This function Should not be modified, when the callback is needed, + the DAL_ETH_RxAllocateCallback could be implemented in the user file + */ +} + +/** + * @brief Rx Link callback. + * @param pStart: pointer to packet start + * @param pStart: pointer to packet end + * @param buff: pointer to received data + * @param Length: received data length + * @retval None + */ +__weak void DAL_ETH_RxLinkCallback(void **pStart, void **pEnd, uint8_t *buff, uint16_t Length) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(pStart); + UNUSED(pEnd); + UNUSED(buff); + UNUSED(Length); + /* NOTE : This function Should not be modified, when the callback is needed, + the DAL_ETH_RxLinkCallback could be implemented in the user file + */ +} + +/** + * @brief Set the Rx link data function. + * @param heth: pointer to a ETH_HandleTypeDef structure that contains + * the configuration information for ETHERNET module + * @param rxLinkCallback: pointer to function to link data + * @retval DAL status + */ +DAL_StatusTypeDef DAL_ETH_RegisterRxLinkCallback(ETH_HandleTypeDef *heth, pETH_rxLinkCallbackTypeDef rxLinkCallback) +{ + if (rxLinkCallback == NULL) + { + /* No buffer to save */ + return DAL_ERROR; + } + + /* Set function to link data */ + heth->rxLinkCallback = rxLinkCallback; + + return DAL_OK; +} + +/** + * @brief Unregister the Rx link callback. + * @param heth: pointer to a ETH_HandleTypeDef structure that contains + * the configuration information for ETHERNET module + * @retval DAL status + */ +DAL_StatusTypeDef DAL_ETH_UnRegisterRxLinkCallback(ETH_HandleTypeDef *heth) +{ + /* Set function to allocate buffer */ + heth->rxLinkCallback = DAL_ETH_RxLinkCallback; + + return DAL_OK; +} + +/** + * @brief Get the error state of the last received packet. + * @param heth: pointer to a ETH_HandleTypeDef structure that contains + * the configuration information for ETHERNET module + * @param pErrorCode: pointer to uint32_t to hold the error code + * @retval DAL status + */ +DAL_StatusTypeDef DAL_ETH_GetRxDataErrorCode(ETH_HandleTypeDef *heth, uint32_t *pErrorCode) +{ + /* Get error bits. */ + *pErrorCode = READ_BIT(heth->RxDescList.pRxLastRxDesc, ETH_DMARXDESC_ERRORS_MASK); + + return DAL_OK; +} + +/** + * @brief Set the Tx free function. + * @param heth: pointer to a ETH_HandleTypeDef structure that contains + * the configuration information for ETHERNET module + * @param txFreeCallback: pointer to function to release the packet + * @retval DAL status + */ +DAL_StatusTypeDef DAL_ETH_RegisterTxFreeCallback(ETH_HandleTypeDef *heth, pETH_txFreeCallbackTypeDef txFreeCallback) +{ + if (txFreeCallback == NULL) + { + /* No buffer to save */ + return DAL_ERROR; + } + + /* Set function to free transmmitted packet */ + heth->txFreeCallback = txFreeCallback; + + return DAL_OK; +} + +/** + * @brief Unregister the Tx free callback. + * @param heth: pointer to a ETH_HandleTypeDef structure that contains + * the configuration information for ETHERNET module + * @retval DAL status + */ +DAL_StatusTypeDef DAL_ETH_UnRegisterTxFreeCallback(ETH_HandleTypeDef *heth) +{ + /* Set function to allocate buffer */ + heth->txFreeCallback = DAL_ETH_TxFreeCallback; + + return DAL_OK; +} + +/** + * @brief Tx Free callback. + * @param buff: pointer to buffer to free + * @retval None + */ +__weak void DAL_ETH_TxFreeCallback(uint32_t *buff) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(buff); + /* NOTE : This function Should not be modified, when the callback is needed, + the DAL_ETH_TxFreeCallback could be implemented in the user file + */ +} + +/** + * @brief Release transmitted Tx packets. + * @param heth: pointer to a ETH_HandleTypeDef structure that contains + * the configuration information for ETHERNET module + * @retval DAL status + */ +DAL_StatusTypeDef DAL_ETH_ReleaseTxPacket(ETH_HandleTypeDef *heth) +{ + ETH_TxDescListTypeDef *dmatxdesclist = &heth->TxDescList; + uint32_t numOfBuf = dmatxdesclist->BuffersInUse; + uint32_t idx = dmatxdesclist->releaseIndex; + uint8_t pktTxStatus = 1U; + uint8_t pktInUse; +#ifdef DAL_ETH_USE_PTP + ETH_TimeStampTypeDef *timestamp = &heth->TxTimestamp; +#endif /* DAL_ETH_USE_PTP */ + + /* Loop through buffers in use. */ + while ((numOfBuf != 0U) && (pktTxStatus != 0U)) + { + pktInUse = 1U; + numOfBuf--; + /* If no packet, just examine the next packet. */ + if (dmatxdesclist->PacketAddress[idx] == NULL) + { + /* No packet in use, skip to next. */ + idx = (idx + 1U) & (ETH_TX_DESC_CNT - 1U); + pktInUse = 0U; + } + + if (pktInUse != 0U) + { + /* Determine if the packet has been transmitted. */ + if ((heth->Init.TxDesc[idx].DESC0 & ETH_DMATXDESC_OWN) == 0U) + { +#ifdef DAL_ETH_USE_PTP + /* Get timestamp low */ + timestamp->TimeStampLow = heth->Init.TxDesc[idx].DESC6; + /* Get timestamp high */ + timestamp->TimeStampHigh = heth->Init.TxDesc[idx].DESC7; +#endif /* DAL_ETH_USE_PTP */ + +#if (USE_DAL_ETH_REGISTER_CALLBACKS == 1) + /*Call registered callbacks*/ +#ifdef DAL_ETH_USE_PTP + /* Handle Ptp */ + heth->txPtpCallback(dmatxdesclist->PacketAddress[idx], timestamp); +#endif /* DAL_ETH_USE_PTP */ + /* Release the packet. */ + heth->txFreeCallback(dmatxdesclist->PacketAddress[idx]); +#else + /* Call callbacks */ +#ifdef DAL_ETH_USE_PTP + /* Handle Ptp */ + DAL_ETH_TxPtpCallback(dmatxdesclist->PacketAddress[idx], timestamp); +#endif /* DAL_ETH_USE_PTP */ + /* Release the packet. */ + DAL_ETH_TxFreeCallback(dmatxdesclist->PacketAddress[idx]); +#endif /* USE_DAL_ETH_REGISTER_CALLBACKS */ + + /* Clear the entry in the in-use array. */ + dmatxdesclist->PacketAddress[idx] = NULL; + + /* Update the transmit relesae index and number of buffers in use. */ + idx = (idx + 1U) & (ETH_TX_DESC_CNT - 1U); + dmatxdesclist->BuffersInUse = numOfBuf; + dmatxdesclist->releaseIndex = idx; + } + else + { + /* Get out of the loop! */ + pktTxStatus = 0U; + } + } + } + return DAL_OK; +} + +#ifdef DAL_ETH_USE_PTP +/** + * @brief Set the Ethernet PTP configuration. + * @param heth: pointer to a ETH_HandleTypeDef structure that contains + * the configuration information for ETHERNET module + * @param ptpconfig: pointer to a ETH_PTP_ConfigTypeDef structure that contains + * the configuration information for PTP + * @retval DAL status + */ +DAL_StatusTypeDef DAL_ETH_PTP_SetConfig(ETH_HandleTypeDef *heth, ETH_PTP_ConfigTypeDef *ptpconfig) +{ + uint32_t tmpTSCTRL; + ETH_TimeTypeDef time; + + if (ptpconfig == NULL) + { + return DAL_ERROR; + } + + tmpTSCTRL = ptpconfig->Timestamp | + ((uint32_t)ptpconfig->TimestampUpdate << ETH_PTPTSCTRL_TSUDSEL_Pos) | + ((uint32_t)ptpconfig->TimestampAll << ETH_PTPTSCTRL_TSSNEN_Pos) | + ((uint32_t)ptpconfig->TimestampRolloverMode << ETH_PTPTSCTRL_TSSUBRO_Pos) | + ((uint32_t)ptpconfig->TimestampV2 << ETH_PTPTSCTRL_LISTVSEL_Pos) | + ((uint32_t)ptpconfig->TimestampEthernet << ETH_PTPTSCTRL_TSSPTPEN_Pos) | + ((uint32_t)ptpconfig->TimestampIPv6 << ETH_PTPTSCTRL_TSS6EN_Pos) | + ((uint32_t)ptpconfig->TimestampIPv4 << ETH_PTPTSCTRL_TSS4EN_Pos) | + ((uint32_t)ptpconfig->TimestampEvent << ETH_PTPTSCTRL_TSSMESEL_Pos) | + ((uint32_t)ptpconfig->TimestampMaster << ETH_PTPTSCTRL_TSSMNSEL_Pos) | + ((uint32_t)ptpconfig->TimestampFilter << ETH_PTPTSCTRL_TSSPTPFMACEN_Pos) | + ((uint32_t)ptpconfig->TimestampClockType << ETH_PTPTSCTRL_TSCLKNSEL_Pos); + + /* Write to MACTSCR */ + MODIFY_REG(heth->Instance->PTPTSCTRL, ETH_MACTSCR_MASK, tmpTSCTRL); + + /* Enable Timestamp */ + SET_BIT(heth->Instance->PTPTSCTRL, ETH_PTPTSCTRL_TSEN); + WRITE_REG(heth->Instance->PTPSUBSECI, ptpconfig->TimestampSubsecondInc); + WRITE_REG(heth->Instance->PTPTSA, ptpconfig->TimestampAddend); + + /* Enable Timestamp */ + if (ptpconfig->TimestampAddendUpdate == ENABLE) + { + SET_BIT(heth->Instance->PTPTSCTRL, ETH_PTPTSCTRL_TSADDUD); + while ((heth->Instance->PTPTSCTRL & ETH_PTPTSCTRL_TSADDUD) != 0) {} + } + + /* Enable Update mode */ + if (ptpconfig->TimestampUpdateMode == ENABLE) + { + SET_BIT(heth->Instance->PTPTSCTRL, ETH_PTPTSCTRL_TSUDSEL); + } + + /* Initialize Time */ + time.Seconds = 0; + time.NanoSeconds = 0; + DAL_ETH_PTP_SetTime(heth, &time); + + /* Ptp Init */ + SET_BIT(heth->Instance->PTPTSCTRL, ETH_PTPTSCTRL_TSSTINIT); + + /* Set PTP Configuration done */ + heth->IsPtpConfigured = DAL_ETH_PTP_CONFIGURATED; + + /* Return function status */ + return DAL_OK; +} + +/** + * @brief Get the Ethernet PTP configuration. + * @param heth: pointer to a ETH_HandleTypeDef structure that contains + * the configuration information for ETHERNET module + * @param ptpconfig: pointer to a ETH_PTP_ConfigTypeDef structure that contains + * the configuration information for PTP + * @retval DAL status + */ +DAL_StatusTypeDef DAL_ETH_PTP_GetConfig(ETH_HandleTypeDef *heth, ETH_PTP_ConfigTypeDef *ptpconfig) +{ + if (ptpconfig == NULL) + { + return DAL_ERROR; + } + ptpconfig->Timestamp = READ_BIT(heth->Instance->PTPTSCTRL, ETH_PTPTSCTRL_TSEN); + ptpconfig->TimestampUpdate = ((READ_BIT(heth->Instance->PTPTSCTRL, + ETH_PTPTSCTRL_TSUDSEL) >> ETH_PTPTSCTRL_TSUDSEL_Pos) > 0U) ? ENABLE : DISABLE; + ptpconfig->TimestampAll = ((READ_BIT(heth->Instance->PTPTSCTRL, + ETH_PTPTSCTRL_TSSNEN) >> ETH_PTPTSCTRL_TSSNEN_Pos) > 0U) ? ENABLE : DISABLE; + ptpconfig->TimestampRolloverMode = ((READ_BIT(heth->Instance->PTPTSCTRL, + ETH_PTPTSCTRL_TSSUBRO) >> ETH_PTPTSCTRL_TSSUBRO_Pos) > 0U) + ? ENABLE : DISABLE; + ptpconfig->TimestampV2 = ((READ_BIT(heth->Instance->PTPTSCTRL, + ETH_PTPTSCTRL_LISTVSEL) >> ETH_PTPTSCTRL_LISTVSEL_Pos) > 0U) ? ENABLE : DISABLE; + ptpconfig->TimestampEthernet = ((READ_BIT(heth->Instance->PTPTSCTRL, + ETH_PTPTSCTRL_TSSPTPEN) >> ETH_PTPTSCTRL_TSSPTPEN_Pos) > 0U) + ? ENABLE : DISABLE; + ptpconfig->TimestampIPv6 = ((READ_BIT(heth->Instance->PTPTSCTRL, + ETH_PTPTSCTRL_TSS6EN) >> ETH_PTPTSCTRL_TSS6EN_Pos) > 0U) ? ENABLE : DISABLE; + ptpconfig->TimestampIPv4 = ((READ_BIT(heth->Instance->PTPTSCTRL, + ETH_PTPTSCTRL_TSS4EN) >> ETH_PTPTSCTRL_TSS4EN_Pos) > 0U) ? ENABLE : DISABLE; + ptpconfig->TimestampEvent = ((READ_BIT(heth->Instance->PTPTSCTRL, + ETH_PTPTSCTRL_TSSMESEL) >> ETH_PTPTSCTRL_TSSMESEL_Pos) > 0U) ? ENABLE : DISABLE; + ptpconfig->TimestampMaster = ((READ_BIT(heth->Instance->PTPTSCTRL, + ETH_PTPTSCTRL_TSSMNSEL) >> ETH_PTPTSCTRL_TSSMNSEL_Pos) > 0U) ? ENABLE : DISABLE; + ptpconfig->TimestampFilter = ((READ_BIT(heth->Instance->PTPTSCTRL, + ETH_PTPTSCTRL_TSSPTPFMACEN) >> ETH_PTPTSCTRL_TSSPTPFMACEN_Pos) > 0U) ? ENABLE : DISABLE; + ptpconfig->TimestampClockType = ((READ_BIT(heth->Instance->PTPTSCTRL, + ETH_PTPTSCTRL_TSCLKNSEL) >> ETH_PTPTSCTRL_TSCLKNSEL_Pos) > 0U) ? ENABLE : DISABLE; + + /* Return function status */ + return DAL_OK; +} + +/** + * @brief Set Seconds and Nanoseconds for the Ethernet PTP registers. + * @param heth: pointer to a ETH_HandleTypeDef structure that contains + * the configuration information for ETHERNET module + * @param heth: pointer to a ETH_TimeTypeDef structure that contains + * time to set + * @retval DAL status + */ +DAL_StatusTypeDef DAL_ETH_PTP_SetTime(ETH_HandleTypeDef *heth, ETH_TimeTypeDef *time) +{ + if (heth->IsPtpConfigured == DAL_ETH_PTP_CONFIGURATED) + { + /* Set Seconds */ + heth->Instance->PTPTSHUD = time->Seconds; + + /* Set NanoSeconds */ + heth->Instance->PTPTSLUD = time->NanoSeconds; + + /* Return function status */ + return DAL_OK; + } + else + { + /* Return function status */ + return DAL_ERROR; + } +} + +/** + * @brief Get Seconds and Nanoseconds for the Ethernet PTP registers. + * @param heth: pointer to a ETH_HandleTypeDef structure that contains + * the configuration information for ETHERNET module + * @param heth: pointer to a ETH_TimeTypeDef structure that contains + * time to get + * @retval DAL status + */ +DAL_StatusTypeDef DAL_ETH_PTP_GetTime(ETH_HandleTypeDef *heth, ETH_TimeTypeDef *time) +{ + if (heth->IsPtpConfigured == DAL_ETH_PTP_CONFIGURATED) + { + /* Get Seconds */ + time->Seconds = heth->Instance->PTPTSH; + + /* Get NanoSeconds */ + time->NanoSeconds = heth->Instance->PTPTSL; + + /* Return function status */ + return DAL_OK; + } + else + { + /* Return function status */ + return DAL_ERROR; + } +} + +/** + * @brief Update time for the Ethernet PTP registers. + * @param heth: pointer to a ETH_HandleTypeDef structure that contains + * the configuration information for ETHERNET module + * @param timeupdate: pointer to a ETH_TIMEUPDATETypeDef structure that contains + * the time update information + * @retval DAL status + */ +DAL_StatusTypeDef DAL_ETH_PTP_AddTimeOffset(ETH_HandleTypeDef *heth, ETH_PtpUpdateTypeDef ptpoffsettype, + ETH_TimeTypeDef *timeoffset) +{ + if (heth->IsPtpConfigured == DAL_ETH_PTP_CONFIGURATED) + { + if (ptpoffsettype == DAL_ETH_PTP_NEGATIVE_UPDATE) + { + /* Set Seconds update */ + heth->Instance->PTPTSHUD = ETH_PTPTSH_VALUE - timeoffset->Seconds + 1U; + + if (READ_BIT(heth->Instance->PTPTSCTRL, ETH_PTPTSCTRL_TSSUBRO) == ETH_PTPTSCTRL_TSSUBRO) + { + /* Set nanoSeconds update */ + heth->Instance->PTPTSLUD = ETH_PTPTSL_VALUE - timeoffset->NanoSeconds; + } + else + { + heth->Instance->PTPTSLUD = ETH_PTPTSH_VALUE - timeoffset->NanoSeconds + 1U; + } + } + else + { + /* Set Seconds update */ + heth->Instance->PTPTSHUD = timeoffset->Seconds; + /* Set nanoSeconds update */ + heth->Instance->PTPTSLUD = timeoffset->NanoSeconds; + } + + /* Return function status */ + return DAL_OK; + } + else + { + /* Return function status */ + return DAL_ERROR; + } +} + +/** + * @brief Insert Timestamp in transmission. + * @param heth: pointer to a ETH_HandleTypeDef structure that contains + * the configuration information for ETHERNET module + * @param txtimestampconf: Enable or Disable timestamp in transmission + * @retval DAL status + */ +DAL_StatusTypeDef DAL_ETH_PTP_InsertTxTimestamp(ETH_HandleTypeDef *heth) +{ + ETH_TxDescListTypeDef *dmatxdesclist = &heth->TxDescList; + uint32_t descidx = dmatxdesclist->CurTxDesc; + ETH_DMADescTypeDef *dmatxdesc = (ETH_DMADescTypeDef *)dmatxdesclist->TxDesc[descidx]; + + if (heth->IsPtpConfigured == DAL_ETH_PTP_CONFIGURATED) + { + /* Enable Time Stamp transmission */ + SET_BIT(dmatxdesc->DESC0, ETH_DMATXDESC_TTSE); + + /* Return function status */ + return DAL_OK; + } + else + { + /* Return function status */ + return DAL_ERROR; + } +} + +/** + * @brief Get transmission timestamp. + * @param heth: pointer to a ETH_HandleTypeDef structure that contains + * the configuration information for ETHERNET module + * @param timestamp: pointer to ETH_TIMESTAMPTypeDef structure that contains + * transmission timestamp + * @retval DAL status + */ +DAL_StatusTypeDef DAL_ETH_PTP_GetTxTimestamp(ETH_HandleTypeDef *heth, ETH_TimeStampTypeDef *timestamp) +{ + ETH_TxDescListTypeDef *dmatxdesclist = &heth->TxDescList; + uint32_t idx = dmatxdesclist->releaseIndex; + ETH_DMADescTypeDef *dmatxdesc = (ETH_DMADescTypeDef *)dmatxdesclist->TxDesc[idx]; + + if (heth->IsPtpConfigured == DAL_ETH_PTP_CONFIGURATED) + { + /* Get timestamp low */ + timestamp->TimeStampLow = dmatxdesc->DESC0; + /* Get timestamp high */ + timestamp->TimeStampHigh = dmatxdesc->DESC1; + + /* Return function status */ + return DAL_OK; + } + else + { + /* Return function status */ + return DAL_ERROR; + } +} + +/** + * @brief Get receive timestamp. + * @param heth: pointer to a ETH_HandleTypeDef structure that contains + * the configuration information for ETHERNET module + * @param timestamp: pointer to ETH_TIMESTAMPTypeDef structure that contains + * receive timestamp + * @retval DAL status + */ +DAL_StatusTypeDef DAL_ETH_PTP_GetRxTimestamp(ETH_HandleTypeDef *heth, ETH_TimeStampTypeDef *timestamp) +{ + if (heth->IsPtpConfigured == DAL_ETH_PTP_CONFIGURATED) + { + /* Get timestamp low */ + timestamp->TimeStampLow = heth->RxDescList.TimeStamp.TimeStampLow; + /* Get timestamp high */ + timestamp->TimeStampHigh = heth->RxDescList.TimeStamp.TimeStampHigh; + + /* Return function status */ + return DAL_OK; + } + else + { + /* Return function status */ + return DAL_ERROR; + } +} + +/** + * @brief Register the Tx Ptp callback. + * @param heth: pointer to a ETH_HandleTypeDef structure that contains + * the configuration information for ETHERNET module + * @param txPtpCallback: Function to handle Ptp transmission + * @retval DAL status + */ +DAL_StatusTypeDef DAL_ETH_RegisterTxPtpCallback(ETH_HandleTypeDef *heth, pETH_txPtpCallbackTypeDef txPtpCallback) +{ + if (txPtpCallback == NULL) + { + /* No buffer to save */ + return DAL_ERROR; + } + /* Set Function to handle Tx Ptp */ + heth->txPtpCallback = txPtpCallback; + + return DAL_OK; +} + +/** + * @brief Unregister the Tx Ptp callback. + * @param heth: pointer to a ETH_HandleTypeDef structure that contains + * the configuration information for ETHERNET module + * @retval DAL status + */ +DAL_StatusTypeDef DAL_ETH_UnRegisterTxPtpCallback(ETH_HandleTypeDef *heth) +{ + /* Set function to allocate buffer */ + heth->txPtpCallback = DAL_ETH_TxPtpCallback; + + return DAL_OK; +} + +/** + * @brief Tx Ptp callback. + * @param buff: pointer to application buffer + * @retval None + */ +__weak void DAL_ETH_TxPtpCallback(uint32_t *buff, ETH_TimeStampTypeDef *timestamp) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(buff); + /* NOTE : This function Should not be modified, when the callback is needed, + the DAL_ETH_TxPtpCallback could be implemented in the user file + */ +} +#endif /* DAL_ETH_USE_PTP */ + +/** + * @brief This function handles ETH interrupt request. + * @param heth: pointer to a ETH_HandleTypeDef structure that contains + * the configuration information for ETHERNET module + * @retval DAL status + */ +void DAL_ETH_IRQHandler(ETH_HandleTypeDef *heth) +{ + /* Packet received */ + if (__DAL_ETH_DMA_GET_IT(heth, ETH_DMASTS_RXFLG)) + { + if (__DAL_ETH_DMA_GET_IT_SOURCE(heth, ETH_DMAINTEN_RXIEN)) + { + /* Clear the Eth DMA Rx IT pending bits */ + __DAL_ETH_DMA_CLEAR_IT(heth, ETH_DMASTS_RXFLG | ETH_DMASTS_NINTS); + +#if (USE_DAL_ETH_REGISTER_CALLBACKS == 1) + /*Call registered Receive complete callback*/ + heth->RxCpltCallback(heth); +#else + /* Receive complete callback */ + DAL_ETH_RxCpltCallback(heth); +#endif /* USE_DAL_ETH_REGISTER_CALLBACKS */ + } + } + + /* Packet transmitted */ + if (__DAL_ETH_DMA_GET_IT(heth, ETH_DMASTS_TXFLG)) + { + if (__DAL_ETH_DMA_GET_IT_SOURCE(heth, ETH_DMAINTEN_TXIEN)) + { + /* Clear the Eth DMA Tx IT pending bits */ + __DAL_ETH_DMA_CLEAR_IT(heth, ETH_DMASTS_TXFLG | ETH_DMASTS_NINTS); + +#if (USE_DAL_ETH_REGISTER_CALLBACKS == 1) + /*Call registered Transmit complete callback*/ + heth->TxCpltCallback(heth); +#else + /* Transfer complete callback */ + DAL_ETH_TxCpltCallback(heth); +#endif /* USE_DAL_ETH_REGISTER_CALLBACKS */ + } + } + + + /* ETH DMA Error */ + if (__DAL_ETH_DMA_GET_IT(heth, ETH_DMASTS_AINTS)) + { + if (__DAL_ETH_DMA_GET_IT_SOURCE(heth, ETH_DMAINTEN_AINTSEN)) + { + heth->ErrorCode |= DAL_ETH_ERROR_DMA; + + /* if fatal bus error occurred */ + if (__DAL_ETH_DMA_GET_IT(heth, ETH_DMASTS_FBERRFLG)) + { + /* Get DMA error code */ + heth->DMAErrorCode = READ_BIT(heth->Instance->DMASTS, (ETH_DMASTS_FBERRFLG | ETH_DMASTS_TXSTS | ETH_DMASTS_RXSTS)); + + /* Disable all interrupts */ + __DAL_ETH_DMA_DISABLE_IT(heth, ETH_DMAINTEN_NINTSEN | ETH_DMAINTEN_AINTSEN); + + /* Set DAL state to ERROR */ + heth->gState = DAL_ETH_STATE_ERROR; + } + else + { + /* Get DMA error status */ + heth->DMAErrorCode = READ_BIT(heth->Instance->DMASTS, (ETH_DMASTS_ETXFLG | ETH_DMASTS_RXWTOFLG | + ETH_DMASTS_RXBU | ETH_DMASTS_AINTS)); + + /* Clear the interrupt summary flag */ + __DAL_ETH_DMA_CLEAR_IT(heth, (ETH_DMASTS_ETXFLG | ETH_DMASTS_RXWTOFLG | + ETH_DMASTS_RXBU | ETH_DMASTS_AINTS)); + } +#if (USE_DAL_ETH_REGISTER_CALLBACKS == 1) + /* Call registered Error callback*/ + heth->ErrorCallback(heth); +#else + /* Ethernet DMA Error callback */ + DAL_ETH_ErrorCallback(heth); +#endif /* USE_DAL_ETH_REGISTER_CALLBACKS */ + + } + } + + + /* ETH PMT IT */ + if (__DAL_ETH_MAC_GET_IT(heth, ETH_MAC_PMT_IT)) + { + /* Get MAC Wake-up source and clear the status register pending bit */ + heth->MACWakeUpEvent = READ_BIT(heth->Instance->MACPMTCTRLSTS, (ETH_MACPMTCTRLSTS_WKUPFRX | ETH_MACPMTCTRLSTS_MPRX)); + +#if (USE_DAL_ETH_REGISTER_CALLBACKS == 1) + /* Call registered PMT callback*/ + heth->PMTCallback(heth); +#else + /* Ethernet PMT callback */ + DAL_ETH_PMTCallback(heth); +#endif /* USE_DAL_ETH_REGISTER_CALLBACKS */ + + heth->MACWakeUpEvent = (uint32_t)(0x0U); + } + + + /* check ETH WAKEUP exti flag */ + if (__DAL_ETH_WAKEUP_EINT_GET_FLAG(ETH_WAKEUP_EINT_LINE) != (uint32_t)RESET) + { + /* Clear ETH WAKEUP Exti pending bit */ + __DAL_ETH_WAKEUP_EINT_CLEAR_FLAG(ETH_WAKEUP_EINT_LINE); +#if (USE_DAL_ETH_REGISTER_CALLBACKS == 1) + /* Call registered WakeUp callback*/ + heth->WakeUpCallback(heth); +#else + /* ETH WAKEUP callback */ + DAL_ETH_WakeUpCallback(heth); +#endif /* USE_DAL_ETH_REGISTER_CALLBACKS */ + } +} + +/** + * @brief Tx Transfer completed callbacks. + * @param heth: pointer to a ETH_HandleTypeDef structure that contains + * the configuration information for ETHERNET module + * @retval None + */ +__weak void DAL_ETH_TxCpltCallback(ETH_HandleTypeDef *heth) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(heth); + /* NOTE : This function Should not be modified, when the callback is needed, + the DAL_ETH_TxCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Rx Transfer completed callbacks. + * @param heth: pointer to a ETH_HandleTypeDef structure that contains + * the configuration information for ETHERNET module + * @retval None + */ +__weak void DAL_ETH_RxCpltCallback(ETH_HandleTypeDef *heth) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(heth); + /* NOTE : This function Should not be modified, when the callback is needed, + the DAL_ETH_RxCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Ethernet transfer error callbacks + * @param heth: pointer to a ETH_HandleTypeDef structure that contains + * the configuration information for ETHERNET module + * @retval None + */ +__weak void DAL_ETH_ErrorCallback(ETH_HandleTypeDef *heth) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(heth); + /* NOTE : This function Should not be modified, when the callback is needed, + the DAL_ETH_ErrorCallback could be implemented in the user file + */ +} + +/** + * @brief Ethernet Power Management module IT callback + * @param heth: pointer to a ETH_HandleTypeDef structure that contains + * the configuration information for ETHERNET module + * @retval None + */ +__weak void DAL_ETH_PMTCallback(ETH_HandleTypeDef *heth) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(heth); + /* NOTE : This function Should not be modified, when the callback is needed, + the DAL_ETH_PMTCallback could be implemented in the user file + */ +} + + +/** + * @brief ETH WAKEUP interrupt callback + * @param heth: pointer to a ETH_HandleTypeDef structure that contains + * the configuration information for ETHERNET module + * @retval None + */ +__weak void DAL_ETH_WakeUpCallback(ETH_HandleTypeDef *heth) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(heth); + /* NOTE : This function Should not be modified, when the callback is needed, + the DAL_ETH_WakeUpCallback could be implemented in the user file + */ +} + +/** + * @brief Read a PHY register + * @param heth: pointer to a ETH_HandleTypeDef structure that contains + * the configuration information for ETHERNET module + * @param PHYAddr: PHY port address, must be a value from 0 to 31 + * @param PHYReg: PHY register address, must be a value from 0 to 31 + * @param pRegValue: parameter to hold read value + * @retval DAL status + */ +DAL_StatusTypeDef DAL_ETH_ReadPHYRegister(ETH_HandleTypeDef *heth, uint32_t PHYAddr, uint32_t PHYReg, + uint32_t *pRegValue) +{ + uint32_t tmpreg1; + uint32_t tickstart; + + /* Get the ETHERNET MACADDR value */ + tmpreg1 = heth->Instance->MACADDR; + + /* Keep only the CSR Clock Range CR[2:0] bits value */ + tmpreg1 &= ~ETH_MACADDR_CR_MASK; + + /* Prepare the MII address register value */ + tmpreg1 |= ((PHYAddr << 11U) & ETH_MACADDR_PA); /* Set the PHY device address */ + tmpreg1 |= (((uint32_t)PHYReg << 6U) & ETH_MACADDR_MR); /* Set the PHY register address */ + tmpreg1 &= ~ETH_MACADDR_MW; /* Set the read mode */ + tmpreg1 |= ETH_MACADDR_MB; /* Set the MII Busy bit */ + + /* Write the result value into the MII Address register */ + heth->Instance->MACADDR = tmpreg1; + + + tickstart = DAL_GetTick(); + + /* Check for the Busy flag */ + while ((tmpreg1 & ETH_MACADDR_MB) == ETH_MACADDR_MB) + { + /* Check for the Timeout */ + if ((DAL_GetTick() - tickstart) > EXT_PHY_READ_TIMEOUT) + { + return DAL_ERROR; + } + + tmpreg1 = heth->Instance->MACADDR; + } + + /* Get MACDATA value */ + *pRegValue = (uint16_t)(heth->Instance->MACDATA); + + return DAL_OK; +} + + +/** + * @brief Writes to a PHY register. + * @param heth: pointer to a ETH_HandleTypeDef structure that contains + * the configuration information for ETHERNET module + * @param PHYAddr: PHY port address, must be a value from 0 to 31 + * @param PHYReg: PHY register address, must be a value from 0 to 31 + * @param RegValue: the value to write + * @retval DAL status + */ +DAL_StatusTypeDef DAL_ETH_WritePHYRegister(ETH_HandleTypeDef *heth, uint32_t PHYAddr, uint32_t PHYReg, + uint32_t RegValue) +{ + uint32_t tmpreg1; + uint32_t tickstart; + + /* Get the ETHERNET MACADDR value */ + tmpreg1 = heth->Instance->MACADDR; + + /* Keep only the CSR Clock Range CR[2:0] bits value */ + tmpreg1 &= ~ETH_MACADDR_CR_MASK; + + /* Prepare the MII register address value */ + tmpreg1 |= ((PHYAddr << 11U) & ETH_MACADDR_PA); /* Set the PHY device address */ + tmpreg1 |= (((uint32_t)PHYReg << 6U) & ETH_MACADDR_MR); /* Set the PHY register address */ + tmpreg1 |= ETH_MACADDR_MW; /* Set the write mode */ + tmpreg1 |= ETH_MACADDR_MB; /* Set the MII Busy bit */ + + /* Give the value to the MII data register */ + heth->Instance->MACDATA = (uint16_t)RegValue; + + /* Write the result value into the MII Address register */ + heth->Instance->MACADDR = tmpreg1; + + /* Get tick */ + tickstart = DAL_GetTick(); + + /* Check for the Busy flag */ + while ((tmpreg1 & ETH_MACADDR_MB) == ETH_MACADDR_MB) + { + /* Check for the Timeout */ + if ((DAL_GetTick() - tickstart) > EXT_PHY_WRITE_TIMEOUT) + { + return DAL_ERROR; + } + + tmpreg1 = heth->Instance->MACADDR; + } + + return DAL_OK; +} + +/** + * @} + */ + +/** @defgroup ETH_Exported_Functions_Group3 Peripheral Control functions + * @brief ETH control functions + * +@verbatim + ============================================================================== + ##### Peripheral Control functions ##### + ============================================================================== + [..] + This subsection provides a set of functions allowing to control the ETH + peripheral. + +@endverbatim + * @{ + */ +/** + * @brief Get the configuration of the MAC and MTL subsystems. + * @param heth: pointer to a ETH_HandleTypeDef structure that contains + * the configuration information for ETHERNET module + * @param macconf: pointer to a ETH_MACConfigTypeDef structure that will hold + * the configuration of the MAC. + * @retval DAL Status + */ +DAL_StatusTypeDef DAL_ETH_GetMACConfig(ETH_HandleTypeDef *heth, ETH_MACConfigTypeDef *macconf) +{ + if (macconf == NULL) + { + return DAL_ERROR; + } + + /* Get MAC parameters */ + macconf->DeferralCheck = ((READ_BIT(heth->Instance->MACCFG, ETH_MACCFG_DC) >> 4) > 0U) ? ENABLE : DISABLE; + macconf->BackOffLimit = READ_BIT(heth->Instance->MACCFG, ETH_MACCFG_BL); + macconf->RetryTransmission = ((READ_BIT(heth->Instance->MACCFG, ETH_MACCFG_DISR) >> 9) == 0U) ? ENABLE : DISABLE; + macconf->CarrierSenseDuringTransmit = ((READ_BIT(heth->Instance->MACCFG, ETH_MACCFG_DISCRS) >> 16) > 0U) + ? ENABLE : DISABLE; + macconf->ReceiveOwn = ((READ_BIT(heth->Instance->MACCFG, ETH_MACCFG_DISRXO) >> 13) == 0U) ? ENABLE : DISABLE; + macconf->LoopbackMode = ((READ_BIT(heth->Instance->MACCFG, ETH_MACCFG_LBM) >> 12) > 0U) ? ENABLE : DISABLE; + macconf->DuplexMode = READ_BIT(heth->Instance->MACCFG, ETH_MACCFG_DM); + macconf->Speed = READ_BIT(heth->Instance->MACCFG, ETH_MACCFG_SSEL); + macconf->Jabber = ((READ_BIT(heth->Instance->MACCFG, ETH_MACCFG_JDIS) >> 22) == 0U) ? ENABLE : DISABLE; + macconf->Watchdog = ((READ_BIT(heth->Instance->MACCFG, ETH_MACCFG_WDTDIS) >> 23) == 0U) ? ENABLE : DISABLE; + macconf->AutomaticPadCRCStrip = ((READ_BIT(heth->Instance->MACCFG, ETH_MACCFG_ACS) >> 7) > 0U) ? ENABLE : DISABLE; + macconf->InterPacketGapVal = READ_BIT(heth->Instance->MACCFG, ETH_MACCFG_IFG); + macconf->ChecksumOffload = ((READ_BIT(heth->Instance->MACCFG, ETH_MACCFG_IPC) >> 27) > 0U) ? ENABLE : DISABLE; + + + macconf->TransmitFlowControl = ((READ_BIT(heth->Instance->MACFCTRL, ETH_MACFCTRL_TXFCTRLEN) >> 1) > 0U) ? ENABLE : DISABLE; + macconf->ZeroQuantaPause = ((READ_BIT(heth->Instance->MACFCTRL, ETH_MACFCTRL_ZQPDIS) >> 7) == 0U) ? ENABLE : DISABLE; + macconf->PauseLowThreshold = READ_BIT(heth->Instance->MACFCTRL, ETH_MACFCTRL_PTSEL); + macconf->PauseTime = (READ_BIT(heth->Instance->MACFCTRL, ETH_MACFCTRL_PT) >> 16); + macconf->ReceiveFlowControl = (READ_BIT(heth->Instance->MACFCTRL, ETH_MACFCTRL_RXFCTRLEN) > 0U) ? ENABLE : DISABLE; + macconf->UnicastPausePacketDetect = ((READ_BIT(heth->Instance->MACFCTRL, ETH_MACFCTRL_UNPFDETE) >> 1) > 0U) + ? ENABLE : DISABLE; + + return DAL_OK; +} + +/** + * @brief Get the configuration of the DMA. + * @param heth: pointer to a ETH_HandleTypeDef structure that contains + * the configuration information for ETHERNET module + * @param dmaconf: pointer to a ETH_DMAConfigTypeDef structure that will hold + * the configuration of the ETH DMA. + * @retval DAL Status + */ +DAL_StatusTypeDef DAL_ETH_GetDMAConfig(ETH_HandleTypeDef *heth, ETH_DMAConfigTypeDef *dmaconf) +{ + if (dmaconf == NULL) + { + return DAL_ERROR; + } + + dmaconf->DMAArbitration = READ_BIT(heth->Instance->DMABMOD, ETH_DMABMOD_DSL) >> 2; + dmaconf->AddressAlignedBeats = ((READ_BIT(heth->Instance->DMABMOD, ETH_DMABMOD_AAL) >> 12) > 0U) ? ENABLE : DISABLE; + dmaconf->BurstMode = READ_BIT(heth->Instance->DMABMOD, ETH_DMABMOD_FB | ETH_DMABMOD_MB); + dmaconf->RxDMABurstLength = READ_BIT(heth->Instance->DMABMOD, ETH_DMABMOD_RPBL); + dmaconf->TxDMABurstLength = READ_BIT(heth->Instance->DMABMOD, ETH_DMABMOD_PBL); + dmaconf->EnhancedDescriptorFormat = ((READ_BIT(heth->Instance->DMABMOD, ETH_DMABMOD_EDFEN) >> 7) > 0U) ? ENABLE : DISABLE; + dmaconf->DescriptorSkipLength = READ_BIT(heth->Instance->DMABMOD, ETH_DMABMOD_DSL) >> 2; + + dmaconf->DropTCPIPChecksumErrorFrame = ((READ_BIT(heth->Instance->DMAOPMOD, + ETH_DMAOPMOD_DISDT) >> 26) > 0U) ? DISABLE : ENABLE; + dmaconf->ReceiveStoreForward = ((READ_BIT(heth->Instance->DMAOPMOD, ETH_DMAOPMOD_RXSF) >> 25) > 0U) ? ENABLE : DISABLE; + dmaconf->FlushRxPacket = ((READ_BIT(heth->Instance->DMAOPMOD, ETH_DMAOPMOD_FTXF) >> 20) > 0U) ? DISABLE : ENABLE; + dmaconf->TransmitStoreForward = ((READ_BIT(heth->Instance->DMAOPMOD, ETH_DMAOPMOD_TXSF) >> 21) > 0U) ? ENABLE : DISABLE; + dmaconf->TransmitThresholdControl = READ_BIT(heth->Instance->DMAOPMOD, ETH_DMAOPMOD_TXTHCTRL); + dmaconf->ForwardErrorFrames = ((READ_BIT(heth->Instance->DMAOPMOD, ETH_DMAOPMOD_FERRF) >> 7) > 0U) ? ENABLE : DISABLE; + dmaconf->ForwardUndersizedGoodFrames = ((READ_BIT(heth->Instance->DMAOPMOD, + ETH_DMAOPMOD_FUF) >> 6) > 0U) ? ENABLE : DISABLE; + dmaconf->ReceiveThresholdControl = READ_BIT(heth->Instance->DMAOPMOD, ETH_DMAOPMOD_RXTHCTRL); + dmaconf->SecondFrameOperate = ((READ_BIT(heth->Instance->DMAOPMOD, ETH_DMAOPMOD_OSECF) >> 2) > 0U) ? ENABLE : DISABLE; + return DAL_OK; +} + +/** + * @brief Set the MAC configuration. + * @param heth: pointer to a ETH_HandleTypeDef structure that contains + * the configuration information for ETHERNET module + * @param macconf: pointer to a ETH_MACConfigTypeDef structure that contains + * the configuration of the MAC. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_ETH_SetMACConfig(ETH_HandleTypeDef *heth, ETH_MACConfigTypeDef *macconf) +{ + if (macconf == NULL) + { + return DAL_ERROR; + } + + if (heth->gState == DAL_ETH_STATE_READY) + { + ETH_SetMACConfig(heth, macconf); + + return DAL_OK; + } + else + { + return DAL_ERROR; + } +} + +/** + * @brief Set the ETH DMA configuration. + * @param heth: pointer to a ETH_HandleTypeDef structure that contains + * the configuration information for ETHERNET module + * @param dmaconf: pointer to a ETH_DMAConfigTypeDef structure that will hold + * the configuration of the ETH DMA. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_ETH_SetDMAConfig(ETH_HandleTypeDef *heth, ETH_DMAConfigTypeDef *dmaconf) +{ + if (dmaconf == NULL) + { + return DAL_ERROR; + } + + if (heth->gState == DAL_ETH_STATE_READY) + { + ETH_SetDMAConfig(heth, dmaconf); + + return DAL_OK; + } + else + { + return DAL_ERROR; + } +} + +/** + * @brief Configures the Clock range of ETH MDIO interface. + * @param heth: pointer to a ETH_HandleTypeDef structure that contains + * the configuration information for ETHERNET module + * @retval None + */ +void DAL_ETH_SetMDIOClockRange(ETH_HandleTypeDef *heth) +{ + uint32_t hclk; + uint32_t tmpreg; + + /* Get the ETHERNET MACADDR value */ + tmpreg = (heth->Instance)->MACADDR; + /* Clear CSR Clock Range CR[2:0] bits */ + tmpreg &= ETH_MACADDR_CR_MASK; + + /* Get hclk frequency value */ + hclk = DAL_RCM_GetHCLKFreq(); + + /* Set CR bits depending on hclk value */ + if ((hclk >= 20000000U) && (hclk < 35000000U)) + { + /* CSR Clock Range between 20-35 MHz */ + tmpreg |= (uint32_t)ETH_MACADDR_CR_Div16; + } + else if ((hclk >= 35000000U) && (hclk < 60000000U)) + { + /* CSR Clock Range between 35-60 MHz */ + tmpreg |= (uint32_t)ETH_MACADDR_CR_Div26; + } + else if ((hclk >= 60000000U) && (hclk < 100000000U)) + { + /* CSR Clock Range between 60-100 MHz */ + tmpreg |= (uint32_t)ETH_MACADDR_CR_Div42; + } + else if ((hclk >= 100000000U) && (hclk < 150000000U)) + { + /* CSR Clock Range between 100-150 MHz */ + tmpreg |= (uint32_t)ETH_MACADDR_CR_Div62; + } + else /* ((hclk >= 150000000)&&(hclk <= 183000000))*/ + { + /* CSR Clock Range between 150-183 MHz */ + tmpreg |= (uint32_t)ETH_MACADDR_CR_Div102; + } + + /* Write to ETHERNET MAC MACADDR: Configure the ETHERNET CSR Clock Range */ + (heth->Instance)->MACADDR = (uint32_t)tmpreg; +} + +/** + * @brief Set the ETH MAC (L2) Filters configuration. + * @param heth: pointer to a ETH_HandleTypeDef structure that contains + * the configuration information for ETHERNET module + * @param pFilterConfig: pointer to a ETH_MACFilterConfigTypeDef structure that contains + * the configuration of the ETH MAC filters. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_ETH_SetMACFilterConfig(ETH_HandleTypeDef *heth, ETH_MACFilterConfigTypeDef *pFilterConfig) +{ + uint32_t filterconfig; + + if (pFilterConfig == NULL) + { + return DAL_ERROR; + } + + filterconfig = ((uint32_t)pFilterConfig->PromiscuousMode | + ((uint32_t)pFilterConfig->HashUnicast << 1) | + ((uint32_t)pFilterConfig->HashMulticast << 2) | + ((uint32_t)pFilterConfig->DestAddrInverseFiltering << 3) | + ((uint32_t)pFilterConfig->PassAllMulticast << 4) | + ((uint32_t)((pFilterConfig->BroadcastFilter == DISABLE) ? 1U : 0U) << 5) | + ((uint32_t)pFilterConfig->SrcAddrInverseFiltering << 8) | + ((uint32_t)pFilterConfig->SrcAddrFiltering << 9) | + ((uint32_t)pFilterConfig->HachOrPerfectFilter << 10) | + ((uint32_t)pFilterConfig->ReceiveAllMode << 31) | + pFilterConfig->ControlPacketsFilter); + + MODIFY_REG(heth->Instance->MACFRAF, ETH_MACFRAF_MASK, filterconfig); + + return DAL_OK; +} + +/** + * @brief Get the ETH MAC (L2) Filters configuration. + * @param heth: pointer to a ETH_HandleTypeDef structure that contains + * the configuration information for ETHERNET module + * @param pFilterConfig: pointer to a ETH_MACFilterConfigTypeDef structure that will hold + * the configuration of the ETH MAC filters. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_ETH_GetMACFilterConfig(ETH_HandleTypeDef *heth, ETH_MACFilterConfigTypeDef *pFilterConfig) +{ + if (pFilterConfig == NULL) + { + return DAL_ERROR; + } + + pFilterConfig->PromiscuousMode = ((READ_BIT(heth->Instance->MACFRAF, ETH_MACFRAF_PR)) > 0U) ? ENABLE : DISABLE; + pFilterConfig->HashUnicast = ((READ_BIT(heth->Instance->MACFRAF, ETH_MACFRAF_HUC) >> 1) > 0U) ? ENABLE : DISABLE; + pFilterConfig->HashMulticast = ((READ_BIT(heth->Instance->MACFRAF, ETH_MACFRAF_HMC) >> 2) > 0U) ? ENABLE : DISABLE; + pFilterConfig->DestAddrInverseFiltering = ((READ_BIT(heth->Instance->MACFRAF, + ETH_MACFRAF_DAIF) >> 3) > 0U) ? ENABLE : DISABLE; + pFilterConfig->PassAllMulticast = ((READ_BIT(heth->Instance->MACFRAF, ETH_MACFRAF_PM) >> 4) > 0U) ? ENABLE : DISABLE; + pFilterConfig->BroadcastFilter = ((READ_BIT(heth->Instance->MACFRAF, ETH_MACFRAF_DISBF) >> 5) == 0U) ? ENABLE : DISABLE; + pFilterConfig->ControlPacketsFilter = READ_BIT(heth->Instance->MACFRAF, ETH_MACFRAF_PCTRLF); + pFilterConfig->SrcAddrInverseFiltering = ((READ_BIT(heth->Instance->MACFRAF, + ETH_MACFRAF_SAIF) >> 8) > 0U) ? ENABLE : DISABLE; + pFilterConfig->SrcAddrFiltering = ((READ_BIT(heth->Instance->MACFRAF, ETH_MACFRAF_SAFEN) >> 9) > 0U) ? ENABLE : DISABLE; + pFilterConfig->HachOrPerfectFilter = ((READ_BIT(heth->Instance->MACFRAF, ETH_MACFRAF_HPF) >> 10) > 0U) + ? ENABLE : DISABLE; + pFilterConfig->ReceiveAllMode = ((READ_BIT(heth->Instance->MACFRAF, ETH_MACFRAF_RXA) >> 31) > 0U) ? ENABLE : DISABLE; + + return DAL_OK; +} + +/** + * @brief Set the source MAC Address to be matched. + * @param heth: pointer to a ETH_HandleTypeDef structure that contains + * the configuration information for ETHERNET module + * @param AddrNbr: The MAC address to configure + * This parameter must be a value of the following: + * ETH_MAC_ADDRESS1 + * ETH_MAC_ADDRESS2 + * ETH_MAC_ADDRESS3 + * @param pMACAddr: Pointer to MAC address buffer data (6 bytes) + * @retval DAL status + */ +DAL_StatusTypeDef DAL_ETH_SetSourceMACAddrMatch(ETH_HandleTypeDef *heth, uint32_t AddrNbr, uint8_t *pMACAddr) +{ + uint32_t macaddrlr; + uint32_t macaddrhr; + + if (pMACAddr == NULL) + { + return DAL_ERROR; + } + + /* Get mac addr high reg offset */ + macaddrhr = ((uint32_t) &(heth->Instance->MACADDR0H) + AddrNbr); + /* Get mac addr low reg offset */ + macaddrlr = ((uint32_t) &(heth->Instance->MACADDR0L) + AddrNbr); + + /* Set MAC addr bits 32 to 47 */ + (*(__IO uint32_t *)macaddrhr) = (((uint32_t)(pMACAddr[5]) << 8) | (uint32_t)pMACAddr[4]); + /* Set MAC addr bits 0 to 31 */ + (*(__IO uint32_t *)macaddrlr) = (((uint32_t)(pMACAddr[3]) << 24) | ((uint32_t)(pMACAddr[2]) << 16) | + ((uint32_t)(pMACAddr[1]) << 8) | (uint32_t)pMACAddr[0]); + + /* Enable address and set source address bit */ + (*(__IO uint32_t *)macaddrhr) |= (ETH_MACADDR1H_ADDREN | ETH_MACADDR1H_ADDRSEL); + + return DAL_OK; +} + +/** + * @brief Set the ETH Hash Table Value. + * @param heth: pointer to a ETH_HandleTypeDef structure that contains + * the configuration information for ETHERNET module + * @param pHashTable: pointer to a table of two 32 bit values, that contains + * the 64 bits of the hash table. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_ETH_SetHashTable(ETH_HandleTypeDef *heth, uint32_t *pHashTable) +{ + if (pHashTable == NULL) + { + return DAL_ERROR; + } + + heth->Instance->MACHTH = pHashTable[0]; + heth->Instance->MACHTL = pHashTable[1]; + + return DAL_OK; +} + +/** + * @brief Set the VLAN Identifier for Rx packets + * @param heth: pointer to a ETH_HandleTypeDef structure that contains + * the configuration information for ETHERNET module + * @param ComparisonBits: 12 or 16 bit comparison mode + must be a value of @ref ETH_VLAN_Tag_Comparison + * @param VLANIdentifier: VLAN Identifier value + * @retval None + */ +void DAL_ETH_SetRxVLANIdentifier(ETH_HandleTypeDef *heth, uint32_t ComparisonBits, uint32_t VLANIdentifier) +{ + MODIFY_REG(heth->Instance->MACVLANT, ETH_MACVLANT_VLANTID, VLANIdentifier); + if (ComparisonBits == ETH_VLANTAGCOMPARISON_16BIT) + { + CLEAR_BIT(heth->Instance->MACVLANT, ETH_MACVLANT_VLANTCOMP); + } + else + { + SET_BIT(heth->Instance->MACVLANT, ETH_MACVLANT_VLANTCOMP); + } +} + +/** + * @brief Enters the Power down mode. + * @param heth: pointer to a ETH_HandleTypeDef structure that contains + * the configuration information for ETHERNET module + * @param pPowerDownConfig: a pointer to ETH_PowerDownConfigTypeDef structure + * that contains the Power Down configuration + * @retval None. + */ +void DAL_ETH_EnterPowerDownMode(ETH_HandleTypeDef *heth, ETH_PowerDownConfigTypeDef *pPowerDownConfig) +{ + uint32_t powerdownconfig; + + powerdownconfig = (((uint32_t)pPowerDownConfig->MagicPacket << ETH_MACPMTCTRLSTS_MPEN_Pos) | + ((uint32_t)pPowerDownConfig->WakeUpPacket << ETH_MACPMTCTRLSTS_WKUPFEN_Pos) | + ((uint32_t)pPowerDownConfig->GlobalUnicast << ETH_MACPMTCTRLSTS_GUN_Pos) | + ETH_MACPMTCTRLSTS_PD); + + MODIFY_REG(heth->Instance->MACPMTCTRLSTS, ETH_MACPMTCTRLSTS_MASK, powerdownconfig); +} + +/** + * @brief Exits from the Power down mode. + * @param heth: pointer to a ETH_HandleTypeDef structure that contains + * the configuration information for ETHERNET module + * @retval None. + */ +void DAL_ETH_ExitPowerDownMode(ETH_HandleTypeDef *heth) +{ + /* clear wake up sources */ + CLEAR_BIT(heth->Instance->MACPMTCTRLSTS, ETH_MACPMTCTRLSTS_WKUPFEN | ETH_MACPMTCTRLSTS_MPEN | ETH_MACPMTCTRLSTS_GUN); + + if (READ_BIT(heth->Instance->MACPMTCTRLSTS, ETH_MACPMTCTRLSTS_PD) != 0U) + { + /* Exit power down mode */ + CLEAR_BIT(heth->Instance->MACPMTCTRLSTS, ETH_MACPMTCTRLSTS_PD); + } + + /* Disable PMT interrupt */ + SET_BIT(heth->Instance->MACIMASK, ETH_MACIMASK_PMTIM); +} + +/** + * @brief Set the WakeUp filter. + * @param heth: pointer to a ETH_HandleTypeDef structure that contains + * the configuration information for ETHERNET module + * @param pFilter: pointer to filter registers values + * @param Count: number of filter registers, must be from 1 to 8. + * @retval None. + */ +DAL_StatusTypeDef DAL_ETH_SetWakeUpFilter(ETH_HandleTypeDef *heth, uint32_t *pFilter, uint32_t Count) +{ + uint32_t regindex; + + if (pFilter == NULL) + { + return DAL_ERROR; + } + + /* Reset Filter Pointer */ + SET_BIT(heth->Instance->MACPMTCTRLSTS, ETH_MACPMTCTRLSTS_WKUPFRST); + + /* Wake up packet filter config */ + for (regindex = 0; regindex < Count; regindex++) + { + /* Write filter regs */ + WRITE_REG(heth->Instance->MACPMTCTRLSTS, pFilter[regindex]); + } + + return DAL_OK; +} + +/** + * @} + */ + +/** @defgroup ETH_Exported_Functions_Group4 Peripheral State and Errors functions + * @brief ETH State and Errors functions + * +@verbatim + ============================================================================== + ##### Peripheral State and Errors functions ##### + ============================================================================== + [..] + This subsection provides a set of functions allowing to return the State of + ETH communication process, return Peripheral Errors occurred during communication + process + + +@endverbatim + * @{ + */ + +/** + * @brief Returns the ETH state. + * @param heth: pointer to a ETH_HandleTypeDef structure that contains + * the configuration information for ETHERNET module + * @retval DAL state + */ +DAL_ETH_StateTypeDef DAL_ETH_GetState(ETH_HandleTypeDef *heth) +{ + return heth->gState; +} + +/** + * @brief Returns the ETH error code + * @param heth: pointer to a ETH_HandleTypeDef structure that contains + * the configuration information for ETHERNET module + * @retval ETH Error Code + */ +uint32_t DAL_ETH_GetError(ETH_HandleTypeDef *heth) +{ + return heth->ErrorCode; +} + +/** + * @brief Returns the ETH DMA error code + * @param heth: pointer to a ETH_HandleTypeDef structure that contains + * the configuration information for ETHERNET module + * @retval ETH DMA Error Code + */ +uint32_t DAL_ETH_GetDMAError(ETH_HandleTypeDef *heth) +{ + return heth->DMAErrorCode; +} + +/** + * @brief Returns the ETH MAC error code + * @param heth: pointer to a ETH_HandleTypeDef structure that contains + * the configuration information for ETHERNET module + * @retval ETH MAC Error Code + */ +uint32_t DAL_ETH_GetMACError(ETH_HandleTypeDef *heth) +{ + return heth->MACErrorCode; +} + +/** + * @brief Returns the ETH MAC WakeUp event source + * @param heth: pointer to a ETH_HandleTypeDef structure that contains + * the configuration information for ETHERNET module + * @retval ETH MAC WakeUp event source + */ +uint32_t DAL_ETH_GetMACWakeUpSource(ETH_HandleTypeDef *heth) +{ + return heth->MACWakeUpEvent; +} + +/** + * @} + */ + +/** + * @} + */ + +/** @addtogroup ETH_Private_Functions ETH Private Functions + * @{ + */ + +/** + * @brief Clears the ETHERNET transmit FIFO. + * @param heth pointer to a ETH_HandleTypeDef structure that contains + * the configuration information for ETHERNET module + * @retval None + */ +static void ETH_FlushTransmitFIFO(ETH_HandleTypeDef *heth) +{ + __IO uint32_t tmpreg = 0; + + /* Set the Flush Transmit FIFO bit */ + (heth->Instance)->DMAOPMOD |= ETH_DMAOPMOD_FTXF; + + /* Wait until the write operation will be taken into account: + at least four TX_CLK/RX_CLK clock cycles */ + tmpreg = (heth->Instance)->DMAOPMOD; + DAL_Delay(ETH_REG_WRITE_DELAY); + (heth->Instance)->DMAOPMOD = tmpreg; +} + +static void ETH_SetMACConfig(ETH_HandleTypeDef *heth, ETH_MACConfigTypeDef *macconf) +{ + uint32_t tmpreg1; + + /*------------------------ ETHERNET MACCFG Configuration --------------------*/ + /* Get the ETHERNET MACCFG value */ + tmpreg1 = (heth->Instance)->MACCFG; + /* Clear WD, PCE, PS, TE and RE bits */ + tmpreg1 &= ETH_MACCFG_CLEAR_MASK; + + tmpreg1 |= (uint32_t)(((uint32_t)((macconf->Watchdog == DISABLE) ? 1U : 0U) << 23U) | + ((uint32_t)((macconf->Jabber == DISABLE) ? 1U : 0U) << 22U) | + (uint32_t)macconf->InterPacketGapVal | + ((uint32_t)macconf->CarrierSenseDuringTransmit << 16U) | + macconf->Speed | + ((uint32_t)((macconf->ReceiveOwn == DISABLE) ? 1U : 0U) << 13U) | + ((uint32_t)macconf->LoopbackMode << 12U) | + macconf->DuplexMode | + ((uint32_t)macconf->ChecksumOffload << 10U) | + ((uint32_t)((macconf->RetryTransmission == DISABLE) ? 1U : 0U) << 9U) | + ((uint32_t)macconf->AutomaticPadCRCStrip << 7U) | + macconf->BackOffLimit | + ((uint32_t)macconf->DeferralCheck << 4U)); + + /* Write to ETHERNET MACCFG */ + (heth->Instance)->MACCFG = (uint32_t)tmpreg1; + + /* Wait until the write operation will be taken into account : + at least four TX_CLK/RX_CLK clock cycles */ + tmpreg1 = (heth->Instance)->MACCFG; + DAL_Delay(ETH_REG_WRITE_DELAY); + (heth->Instance)->MACCFG = tmpreg1; + + /*----------------------- ETHERNET MACFCTRL Configuration --------------------*/ + + /* Get the ETHERNET MACFCTRL value */ + tmpreg1 = (heth->Instance)->MACFCTRL; + /* Clear xx bits */ + tmpreg1 &= ETH_MACFCTRL_CLEAR_MASK; + + tmpreg1 |= (uint32_t)((macconf->PauseTime << 16U) | + (uint32_t)macconf->ZeroQuantaPause | + macconf->PauseLowThreshold | + (uint32_t)macconf->UnicastSlowProtocolPacketDetect | + (uint32_t)macconf->ReceiveFlowControl | + (uint32_t)macconf->TransmitFlowControl); + + /* Write to ETHERNET MACFCTRL */ + (heth->Instance)->MACFCTRL = (uint32_t)tmpreg1; + + /* Wait until the write operation will be taken into account : + at least four TX_CLK/RX_CLK clock cycles */ + tmpreg1 = (heth->Instance)->MACFCTRL; + DAL_Delay(ETH_REG_WRITE_DELAY); + (heth->Instance)->MACFCTRL = tmpreg1; +} + +static void ETH_SetDMAConfig(ETH_HandleTypeDef *heth, ETH_DMAConfigTypeDef *dmaconf) +{ + uint32_t tmpreg1; + + /*----------------------- ETHERNET DMAOPMOD Configuration --------------------*/ + /* Get the ETHERNET DMAOPMOD value */ + tmpreg1 = (heth->Instance)->DMAOPMOD; + /* Clear xx bits */ + tmpreg1 &= ETH_DMAOPMOD_CLEAR_MASK; + + tmpreg1 |= (uint32_t)(((uint32_t)((dmaconf->DropTCPIPChecksumErrorFrame == DISABLE) ? 1U : 0U) << 26U) | + ((uint32_t)dmaconf->ReceiveStoreForward << 25U) | + ((uint32_t)((dmaconf->FlushRxPacket == DISABLE) ? 1U : 0U) << 20U) | + ((uint32_t)dmaconf->TransmitStoreForward << 21U) | + dmaconf->TransmitThresholdControl | + ((uint32_t)dmaconf->ForwardErrorFrames << 7U) | + ((uint32_t)dmaconf->ForwardUndersizedGoodFrames << 6U) | + dmaconf->ReceiveThresholdControl | + ((uint32_t)dmaconf->SecondFrameOperate << 2U)); + + /* Write to ETHERNET DMAOPMOD */ + (heth->Instance)->DMAOPMOD = (uint32_t)tmpreg1; + + /* Wait until the write operation will be taken into account: + at least four TX_CLK/RX_CLK clock cycles */ + tmpreg1 = (heth->Instance)->DMAOPMOD; + DAL_Delay(ETH_REG_WRITE_DELAY); + (heth->Instance)->DMAOPMOD = tmpreg1; + + /*----------------------- ETHERNET DMABMOD Configuration --------------------*/ + (heth->Instance)->DMABMOD = (uint32_t)(((uint32_t)dmaconf->AddressAlignedBeats << 25U) | + dmaconf->BurstMode | + dmaconf->RxDMABurstLength | /* !! if 4xPBL is selected for Tx or + Rx it is applied for the other */ + dmaconf->TxDMABurstLength | + ((uint32_t)dmaconf->EnhancedDescriptorFormat << 7U) | + (dmaconf->DescriptorSkipLength << 2U) | + dmaconf->DMAArbitration | + ETH_DMABMOD_USP); /* Enable use of separate PBL for Rx and Tx */ + + /* Wait until the write operation will be taken into account: + at least four TX_CLK/RX_CLK clock cycles */ + tmpreg1 = (heth->Instance)->DMABMOD; + DAL_Delay(ETH_REG_WRITE_DELAY); + (heth->Instance)->DMABMOD = tmpreg1; +} + +/** + * @brief Configures Ethernet MAC and DMA with default parameters. + * called by DAL_ETH_Init() API. + * @param heth: pointer to a ETH_HandleTypeDef structure that contains + * the configuration information for ETHERNET module + * @retval DAL status + */ +static void ETH_MACDMAConfig(ETH_HandleTypeDef *heth) +{ + ETH_MACConfigTypeDef macDefaultConf; + ETH_DMAConfigTypeDef dmaDefaultConf; + + /*--------------- ETHERNET MAC registers default Configuration --------------*/ + macDefaultConf.Watchdog = ENABLE; + macDefaultConf.Jabber = ENABLE; + macDefaultConf.InterPacketGapVal = ETH_INTERFRAMEGAP_96BIT; + macDefaultConf.CarrierSenseDuringTransmit = DISABLE; + macDefaultConf.ReceiveOwn = ENABLE; + macDefaultConf.LoopbackMode = DISABLE; + macDefaultConf.ChecksumOffload = ENABLE; + macDefaultConf.RetryTransmission = DISABLE; + macDefaultConf.AutomaticPadCRCStrip = DISABLE; + macDefaultConf.BackOffLimit = ETH_BACKOFFLIMIT_10; + macDefaultConf.DeferralCheck = DISABLE; + macDefaultConf.PauseTime = 0x0U; + macDefaultConf.ZeroQuantaPause = DISABLE; + macDefaultConf.PauseLowThreshold = ETH_PAUSELOWTHRESHOLD_MINUS4; + macDefaultConf.ReceiveFlowControl = DISABLE; + macDefaultConf.TransmitFlowControl = DISABLE; + macDefaultConf.Speed = ETH_SPEED_100M; + macDefaultConf.DuplexMode = ETH_FULLDUPLEX_MODE; + macDefaultConf.UnicastSlowProtocolPacketDetect = DISABLE; + + /* MAC default configuration */ + ETH_SetMACConfig(heth, &macDefaultConf); + + /*--------------- ETHERNET DMA registers default Configuration --------------*/ + dmaDefaultConf.DropTCPIPChecksumErrorFrame = ENABLE; + dmaDefaultConf.ReceiveStoreForward = ENABLE; + dmaDefaultConf.FlushRxPacket = ENABLE; + dmaDefaultConf.TransmitStoreForward = ENABLE; + dmaDefaultConf.TransmitThresholdControl = ETH_TRANSMITTHRESHOLDCONTROL_64BYTES; + dmaDefaultConf.ForwardErrorFrames = DISABLE; + dmaDefaultConf.ForwardUndersizedGoodFrames = DISABLE; + dmaDefaultConf.ReceiveThresholdControl = ETH_RECEIVEDTHRESHOLDCONTROL_64BYTES; + dmaDefaultConf.SecondFrameOperate = ENABLE; + dmaDefaultConf.AddressAlignedBeats = ENABLE; + dmaDefaultConf.BurstMode = ETH_BURSTLENGTH_FIXED; + dmaDefaultConf.RxDMABurstLength = ETH_RXDMABURSTLENGTH_32BEAT; + dmaDefaultConf.TxDMABurstLength = ETH_TXDMABURSTLENGTH_32BEAT; + dmaDefaultConf.EnhancedDescriptorFormat = ENABLE; + dmaDefaultConf.DescriptorSkipLength = 0x0U; + dmaDefaultConf.DMAArbitration = ETH_DMAARBITRATION_ROUNDROBIN_RXTX_1_1; + + /* DMA default configuration */ + ETH_SetDMAConfig(heth, &dmaDefaultConf); +} + +/** + * @brief Configures the selected MAC address. + * @param heth pointer to a ETH_HandleTypeDef structure that contains + * the configuration information for ETHERNET module + * @param MacAddr The MAC address to configure + * This parameter can be one of the following values: + * @arg ETH_MAC_Address0: MAC Address0 + * @arg ETH_MAC_Address1: MAC Address1 + * @arg ETH_MAC_Address2: MAC Address2 + * @arg ETH_MAC_Address3: MAC Address3 + * @param Addr Pointer to MAC address buffer data (6 bytes) + * @retval DAL status + */ +static void ETH_MACAddressConfig(ETH_HandleTypeDef *heth, uint32_t MacAddr, uint8_t *Addr) +{ + uint32_t tmpreg1; + + /* Prevent unused argument(s) compilation warning */ + UNUSED(heth); + + /* Calculate the selected MAC address high register */ + tmpreg1 = ((uint32_t)Addr[5U] << 8U) | (uint32_t)Addr[4U]; + /* Load the selected MAC address high register */ + (*(__IO uint32_t *)((uint32_t)(ETH_MAC_ADDR_HBASE + MacAddr))) = tmpreg1; + /* Calculate the selected MAC address low register */ + tmpreg1 = ((uint32_t)Addr[3U] << 24U) | ((uint32_t)Addr[2U] << 16U) | ((uint32_t)Addr[1U] << 8U) | Addr[0U]; + + /* Load the selected MAC address low register */ + (*(__IO uint32_t *)((uint32_t)(ETH_MAC_ADDR_LBASE + MacAddr))) = tmpreg1; +} + +/** + * @brief Initializes the DMA Tx descriptors. + * called by DAL_ETH_Init() API. + * @param heth: pointer to a ETH_HandleTypeDef structure that contains + * the configuration information for ETHERNET module + * @retval None + */ +static void ETH_DMATxDescListInit(ETH_HandleTypeDef *heth) +{ + ETH_DMADescTypeDef *dmatxdesc; + uint32_t i; + + /* Fill each DMATxDesc descriptor with the right values */ + for (i = 0; i < (uint32_t)ETH_TX_DESC_CNT; i++) + { + dmatxdesc = heth->Init.TxDesc + i; + + WRITE_REG(dmatxdesc->DESC0, 0x0); + WRITE_REG(dmatxdesc->DESC1, 0x0); + WRITE_REG(dmatxdesc->DESC2, 0x0); + WRITE_REG(dmatxdesc->DESC3, 0x0); + + WRITE_REG(heth->TxDescList.TxDesc[i], (uint32_t)dmatxdesc); + + /* Set Second Address Chained bit */ + SET_BIT(dmatxdesc->DESC0, ETH_DMATXDESC_TCH); + + if (i < ((uint32_t)ETH_TX_DESC_CNT - 1U)) + { + WRITE_REG(dmatxdesc->DESC3, (uint32_t)(heth->Init.TxDesc + i + 1U)); + } + else + { + WRITE_REG(dmatxdesc->DESC3, (uint32_t)(heth->Init.TxDesc)); + } + + /* Set the DMA Tx descriptors checksum insertion */ + SET_BIT(dmatxdesc->DESC0, ETH_DMATXDESC_CHECKSUMTCPUDPICMPFULL); + } + + heth->TxDescList.CurTxDesc = 0; + + /* Set Transmit Descriptor List Address */ + WRITE_REG(heth->Instance->DMATXDLADDR, (uint32_t) heth->Init.TxDesc); +} + +/** + * @brief Initializes the DMA Rx descriptors in chain mode. + * called by DAL_ETH_Init() API. + * @param heth: pointer to a ETH_HandleTypeDef structure that contains + * the configuration information for ETHERNET module + * @retval None + */ +static void ETH_DMARxDescListInit(ETH_HandleTypeDef *heth) +{ + ETH_DMADescTypeDef *dmarxdesc; + uint32_t i; + + for (i = 0; i < (uint32_t)ETH_RX_DESC_CNT; i++) + { + dmarxdesc = heth->Init.RxDesc + i; + + WRITE_REG(dmarxdesc->DESC0, 0x0); + WRITE_REG(dmarxdesc->DESC1, 0x0); + WRITE_REG(dmarxdesc->DESC2, 0x0); + WRITE_REG(dmarxdesc->DESC3, 0x0); + WRITE_REG(dmarxdesc->BackupAddr0, 0x0); + WRITE_REG(dmarxdesc->BackupAddr1, 0x0); + + /* Set Own bit of the Rx descriptor Status */ + dmarxdesc->DESC0 = ETH_DMARXDESC_OWN; + + /* Set Buffer1 size and Second Address Chained bit */ + dmarxdesc->DESC1 = ETH_DMARXDESC_RCH | ETH_BUFFER_SIZE_RX; + + /* Enable Ethernet DMA Rx Descriptor interrupt */ + dmarxdesc->DESC1 &= ~ETH_DMARXDESC_DIC; + + /* Set Rx descritors addresses */ + WRITE_REG(heth->RxDescList.RxDesc[i], (uint32_t)dmarxdesc); + + if (i < ((uint32_t)ETH_RX_DESC_CNT - 1U)) + { + WRITE_REG(dmarxdesc->DESC3, (uint32_t)(heth->Init.RxDesc + i + 1U)); + } + else + { + WRITE_REG(dmarxdesc->DESC3, (uint32_t)(heth->Init.RxDesc)); + } + } + + WRITE_REG(heth->RxDescList.RxDescIdx, 0); + WRITE_REG(heth->RxDescList.RxDescCnt, 0); + WRITE_REG(heth->RxDescList.RxBuildDescIdx, 0); + WRITE_REG(heth->RxDescList.RxBuildDescCnt, 0); + WRITE_REG(heth->RxDescList.ItMode, 0); + + /* Set Receive Descriptor List Address */ + WRITE_REG(heth->Instance->DMARXDLADDR, (uint32_t) heth->Init.RxDesc); +} + +/** + * @brief Prepare Tx DMA descriptor before transmission. + * called by DAL_ETH_Transmit_IT and DAL_ETH_Transmit_IT() API. + * @param heth: pointer to a ETH_HandleTypeDef structure that contains + * the configuration information for ETHERNET module + * @param pTxConfig: Tx packet configuration + * @param ItMode: Enable or disable Tx EOT interrept + * @retval Status + */ +static uint32_t ETH_Prepare_Tx_Descriptors(ETH_HandleTypeDef *heth, ETH_TxPacketConfig *pTxConfig, uint32_t ItMode) +{ + ETH_TxDescListTypeDef *dmatxdesclist = &heth->TxDescList; + uint32_t descidx = dmatxdesclist->CurTxDesc; + uint32_t firstdescidx = dmatxdesclist->CurTxDesc; + uint32_t idx; + uint32_t descnbr = 0; + ETH_DMADescTypeDef *dmatxdesc = (ETH_DMADescTypeDef *)dmatxdesclist->TxDesc[descidx]; + + ETH_BufferTypeDef *txbuffer = pTxConfig->TxBuffer; + uint32_t bd_count = 0; + + /* Current Tx Descriptor Owned by DMA: cannot be used by the application */ + if ((READ_BIT(dmatxdesc->DESC0, ETH_DMATXDESC_OWN) == ETH_DMATXDESC_OWN) + || (dmatxdesclist->PacketAddress[descidx] != NULL)) + { + return DAL_ETH_ERROR_BUSY; + } + + + descnbr += 1U; + + /* Set header or buffer 1 address */ + WRITE_REG(dmatxdesc->DESC2, (uint32_t)txbuffer->buffer); + + /* Set header or buffer 1 Length */ + MODIFY_REG(dmatxdesc->DESC1, ETH_DMATXDESC_TBS1, txbuffer->len); + + if (READ_BIT(pTxConfig->Attributes, ETH_TX_PACKETS_FEATURES_CSUM) != 0U) + { + MODIFY_REG(dmatxdesc->DESC0, ETH_DMATXDESC_CIC, pTxConfig->ChecksumCtrl); + } + + if (READ_BIT(pTxConfig->Attributes, ETH_TX_PACKETS_FEATURES_CRCPAD) != 0U) + { + MODIFY_REG(dmatxdesc->DESC0, ETH_CRC_PAD_DISABLE, pTxConfig->CRCPadCtrl); + } + + + if (READ_BIT(pTxConfig->Attributes, ETH_TX_PACKETS_FEATURES_VLANTAG) != 0U) + { + /* Set Vlan Type */ + SET_BIT(dmatxdesc->DESC0, ETH_DMATXDESC_VF); + } + + /* Mark it as First Descriptor */ + SET_BIT(dmatxdesc->DESC0, ETH_DMATXDESC_FS); + + /* Ensure rest of descriptor is written to RAM before the OWN bit */ + __DMB(); + /* set OWN bit of FIRST descriptor */ + SET_BIT(dmatxdesc->DESC0, ETH_DMATXDESC_OWN); + + /* only if the packet is split into more than one descriptors > 1 */ + while (txbuffer->next != NULL) + { + /* Clear the LD bit of previous descriptor */ + CLEAR_BIT(dmatxdesc->DESC0, ETH_DMATXDESC_LS); + if (ItMode != ((uint32_t)RESET)) + { + /* Set Interrupt on completion bit */ + SET_BIT(dmatxdesc->DESC0, ETH_DMATXDESC_IC); + } + else + { + /* Clear Interrupt on completion bit */ + CLEAR_BIT(dmatxdesc->DESC0, ETH_DMATXDESC_IC); + } + /* Increment current tx descriptor index */ + INCR_TX_DESC_INDEX(descidx, 1U); + /* Get current descriptor address */ + dmatxdesc = (ETH_DMADescTypeDef *)dmatxdesclist->TxDesc[descidx]; + + /* Clear the FD bit of new Descriptor */ + CLEAR_BIT(dmatxdesc->DESC0, ETH_DMATXDESC_FS); + + /* Current Tx Descriptor Owned by DMA: cannot be used by the application */ + if ((READ_BIT(dmatxdesc->DESC0, ETH_DMATXDESC_OWN) == ETH_DMATXDESC_OWN) + || (dmatxdesclist->PacketAddress[descidx] != NULL)) + { + descidx = firstdescidx; + dmatxdesc = (ETH_DMADescTypeDef *)dmatxdesclist->TxDesc[descidx]; + + /* clear previous desc own bit */ + for (idx = 0; idx < descnbr; idx ++) + { + /* Ensure rest of descriptor is written to RAM before the OWN bit */ + __DMB(); + + CLEAR_BIT(dmatxdesc->DESC0, ETH_DMATXDESC_OWN); + + /* Increment current tx descriptor index */ + INCR_TX_DESC_INDEX(descidx, 1U); + /* Get current descriptor address */ + dmatxdesc = (ETH_DMADescTypeDef *)dmatxdesclist->TxDesc[descidx]; + } + + return DAL_ETH_ERROR_BUSY; + } + + descnbr += 1U; + + /* Get the next Tx buffer in the list */ + txbuffer = txbuffer->next; + + /* Set header or buffer 1 address */ + WRITE_REG(dmatxdesc->DESC2, (uint32_t)txbuffer->buffer); + + /* Set header or buffer 1 Length */ + MODIFY_REG(dmatxdesc->DESC1, ETH_DMATXDESC_TBS1, txbuffer->len); + + bd_count += 1U; + + /* Ensure rest of descriptor is written to RAM before the OWN bit */ + __DMB(); + /* Set Own bit */ + SET_BIT(dmatxdesc->DESC0, ETH_DMATXDESC_OWN); + } + + if (ItMode != ((uint32_t)RESET)) + { + /* Set Interrupt on completion bit */ + SET_BIT(dmatxdesc->DESC0, ETH_DMATXDESC_IC); + } + else + { + /* Clear Interrupt on completion bit */ + CLEAR_BIT(dmatxdesc->DESC0, ETH_DMATXDESC_IC); + } + + /* Mark it as LAST descriptor */ + SET_BIT(dmatxdesc->DESC0, ETH_DMATXDESC_LS); + /* Save the current packet address to expose it to the application */ + dmatxdesclist->PacketAddress[descidx] = dmatxdesclist->CurrentPacketAddress; + + dmatxdesclist->CurTxDesc = descidx; + + /* disable the interrupt */ + __disable_irq(); + + dmatxdesclist->BuffersInUse += bd_count + 1U; + + /* Enable interrupts back */ + __enable_irq(); + + + /* Return function status */ + return DAL_ETH_ERROR_NONE; +} + +#if (USE_DAL_ETH_REGISTER_CALLBACKS == 1) +static void ETH_InitCallbacksToDefault(ETH_HandleTypeDef *heth) +{ + /* Init the ETH Callback settings */ + heth->TxCpltCallback = DAL_ETH_TxCpltCallback; /* Legacy weak TxCpltCallback */ + heth->RxCpltCallback = DAL_ETH_RxCpltCallback; /* Legacy weak RxCpltCallback */ + heth->ErrorCallback = DAL_ETH_ErrorCallback; /* Legacy weak ErrorCallback */ + heth->PMTCallback = DAL_ETH_PMTCallback; /* Legacy weak PMTCallback */ + heth->WakeUpCallback = DAL_ETH_WakeUpCallback; /* Legacy weak WakeUpCallback */ +} +#endif /* USE_DAL_ETH_REGISTER_CALLBACKS */ + +/** + * @} + */ + +/** + * @} + */ + +#endif /* ETH */ + +#endif /* DAL_ETH_MODULE_ENABLED */ + +/** + * @} + */ + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_flash.c b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_flash.c new file mode 100644 index 0000000000..7f7e8dc0f7 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_flash.c @@ -0,0 +1,800 @@ +/** + * + * @file apm32f4xx_dal_flash.c + * @brief FLASH DAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the internal FLASH memory: + * + Program operations functions + * + Memory Control functions + * + Peripheral Errors functions + * + @verbatim + ============================================================================== + ##### FLASH peripheral features ##### + ============================================================================== + + [..] The Flash memory interface manages CPU AHB I-Code and D-Code accesses + to the Flash memory. It implements the erase and program Flash memory operations + and the read and write protection mechanisms. + + [..] The Flash memory interface accelerates code execution with a system of instruction + prefetch and cache lines. + + [..] The FLASH main features are: + (+) Flash memory read operations + (+) Flash memory program/erase operations + (+) Read / write protections + (+) Prefetch on I-Code + (+) 64 cache lines of 128 bits on I-Code + (+) 8 cache lines of 128 bits on D-Code + + + ##### How to use this driver ##### + ============================================================================== + [..] + This driver provides functions and macros to configure and program the FLASH + memory of all APM32F4xx devices. + + (#) FLASH Memory IO Programming functions: + (++) Lock and Unlock the FLASH interface using DAL_FLASH_Unlock() and + DAL_FLASH_Lock() functions + (++) Program functions: byte, half word, word and double word + (++) There Two modes of programming : + (+++) Polling mode using DAL_FLASH_Program() function + (+++) Interrupt mode using DAL_FLASH_Program_IT() function + + (#) Interrupts and flags management functions : + (++) Handle FLASH interrupts by calling DAL_FLASH_IRQHandler() + (++) Wait for last FLASH operation according to its status + (++) Get error flag status by calling DAL_SetErrorCode() + + [..] + In addition to these functions, this driver includes a set of macros allowing + to handle the following operations: + (+) Set the latency + (+) Enable/Disable the prefetch buffer + (+) Enable/Disable the Instruction cache and the Data cache + (+) Reset the Instruction cache and the Data cache + (+) Enable/Disable the FLASH interrupts + (+) Monitor the FLASH flags status + + @endverbatim + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2017 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file in + * the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + */ + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @defgroup FLASH FLASH + * @brief FLASH DAL module driver + * @{ + */ + +#ifdef DAL_FLASH_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/** @addtogroup FLASH_Private_Constants + * @{ + */ +#define FLASH_TIMEOUT_VALUE 50000U /* 50 s */ +/** + * @} + */ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/** @addtogroup FLASH_Private_Variables + * @{ + */ +/* Variable used for Erase sectors under interruption */ +FLASH_ProcessTypeDef pFlash; +/** + * @} + */ + +/* Private function prototypes -----------------------------------------------*/ +/** @addtogroup FLASH_Private_Functions + * @{ + */ +/* Program operations */ +static void FLASH_Program_DoubleWord(uint32_t Address, uint64_t Data); +static void FLASH_Program_Word(uint32_t Address, uint32_t Data); +static void FLASH_Program_HalfWord(uint32_t Address, uint16_t Data); +static void FLASH_Program_Byte(uint32_t Address, uint8_t Data); +static void FLASH_SetErrorCode(void); + +DAL_StatusTypeDef FLASH_WaitForLastOperation(uint32_t Timeout); +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +/** @defgroup FLASH_Exported_Functions FLASH Exported Functions + * @{ + */ + +/** @defgroup FLASH_Exported_Functions_Group1 Programming operation functions + * @brief Programming operation functions + * +@verbatim + =============================================================================== + ##### Programming operation functions ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to manage the FLASH + program operations. + +@endverbatim + * @{ + */ + +/** + * @brief Program byte, halfword, word or double word at a specified address + * @param TypeProgram Indicate the way to program at a specified address. + * This parameter can be a value of @ref FLASH_Type_Program + * @param Address specifies the address to be programmed. + * @param Data specifies the data to be programmed + * + * @retval DAL_StatusTypeDef DAL Status + */ +DAL_StatusTypeDef DAL_FLASH_Program(uint32_t TypeProgram, uint32_t Address, uint64_t Data) +{ + DAL_StatusTypeDef status = DAL_ERROR; + + /* Process Locked */ + __DAL_LOCK(&pFlash); + + /* Check the parameters */ + ASSERT_PARAM(IS_FLASH_TYPEPROGRAM(TypeProgram)); + + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE); + + if(status == DAL_OK) + { + if(TypeProgram == FLASH_TYPEPROGRAM_BYTE) + { + /*Program byte (8-bit) at a specified address.*/ + FLASH_Program_Byte(Address, (uint8_t) Data); + } + else if(TypeProgram == FLASH_TYPEPROGRAM_HALFWORD) + { + /*Program halfword (16-bit) at a specified address.*/ + FLASH_Program_HalfWord(Address, (uint16_t) Data); + } + else if(TypeProgram == FLASH_TYPEPROGRAM_WORD) + { + /*Program word (32-bit) at a specified address.*/ + FLASH_Program_Word(Address, (uint32_t) Data); + } + else + { + /*Program double word (64-bit) at a specified address.*/ + FLASH_Program_DoubleWord(Address, Data); + } + + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE); + + /* If the program operation is completed, disable the PG Bit */ + FLASH->CTRL &= (~FLASH_CTRL_PG); + } + + /* Process Unlocked */ + __DAL_UNLOCK(&pFlash); + + return status; +} + +/** + * @brief Program byte, halfword, word or double word at a specified address with interrupt enabled. + * @param TypeProgram Indicate the way to program at a specified address. + * This parameter can be a value of @ref FLASH_Type_Program + * @param Address specifies the address to be programmed. + * @param Data specifies the data to be programmed + * + * @retval DAL Status + */ +DAL_StatusTypeDef DAL_FLASH_Program_IT(uint32_t TypeProgram, uint32_t Address, uint64_t Data) +{ + DAL_StatusTypeDef status = DAL_OK; + + /* Process Locked */ + __DAL_LOCK(&pFlash); + + /* Check the parameters */ + ASSERT_PARAM(IS_FLASH_TYPEPROGRAM(TypeProgram)); + + /* Enable End of FLASH Operation interrupt */ + __DAL_FLASH_ENABLE_IT(FLASH_IT_EOP); + + /* Enable Error source interrupt */ + __DAL_FLASH_ENABLE_IT(FLASH_IT_ERR); + + pFlash.ProcedureOnGoing = FLASH_PROC_PROGRAM; + pFlash.Address = Address; + + if(TypeProgram == FLASH_TYPEPROGRAM_BYTE) + { + /*Program byte (8-bit) at a specified address.*/ + FLASH_Program_Byte(Address, (uint8_t) Data); + } + else if(TypeProgram == FLASH_TYPEPROGRAM_HALFWORD) + { + /*Program halfword (16-bit) at a specified address.*/ + FLASH_Program_HalfWord(Address, (uint16_t) Data); + } + else if(TypeProgram == FLASH_TYPEPROGRAM_WORD) + { + /*Program word (32-bit) at a specified address.*/ + FLASH_Program_Word(Address, (uint32_t) Data); + } + else + { + /*Program double word (64-bit) at a specified address.*/ + FLASH_Program_DoubleWord(Address, Data); + } + + return status; +} + +/** + * @brief This function handles FLASH interrupt request. + * @retval None + */ +void DAL_FLASH_IRQHandler(void) +{ + uint32_t addresstmp = 0U; + + /* Check FLASH operation error flags */ +#if defined(FLASH_STS_RPROERR) + if(__DAL_FLASH_GET_FLAG((FLASH_FLAG_OPERR | FLASH_FLAG_WRPERR | FLASH_FLAG_PGAERR | \ + FLASH_FLAG_PGPERR | FLASH_FLAG_PGSERR | FLASH_FLAG_RDERR)) != RESET) +#else + if(__DAL_FLASH_GET_FLAG((FLASH_FLAG_OPERR | FLASH_FLAG_WRPERR | FLASH_FLAG_PGAERR | \ + FLASH_FLAG_PGPERR | FLASH_FLAG_PGSERR)) != RESET) +#endif /* FLASH_STS_RPROERR */ + { + if(pFlash.ProcedureOnGoing == FLASH_PROC_SECTERASE) + { + /*return the faulty sector*/ + addresstmp = pFlash.Sector; + pFlash.Sector = 0xFFFFFFFFU; + } + else if(pFlash.ProcedureOnGoing == FLASH_PROC_MASSERASE) + { + /*return the faulty bank*/ + addresstmp = pFlash.Bank; + } + else + { + /*return the faulty address*/ + addresstmp = pFlash.Address; + } + + /*Save the Error code*/ + FLASH_SetErrorCode(); + + /* FLASH error interrupt user callback */ + DAL_FLASH_OperationErrorCallback(addresstmp); + + /*Stop the procedure ongoing*/ + pFlash.ProcedureOnGoing = FLASH_PROC_NONE; + } + + /* Check FLASH End of Operation flag */ + if(__DAL_FLASH_GET_FLAG(FLASH_FLAG_EOP) != RESET) + { + /* Clear FLASH End of Operation pending bit */ + __DAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP); + + if(pFlash.ProcedureOnGoing == FLASH_PROC_SECTERASE) + { + /*Nb of sector to erased can be decreased*/ + pFlash.NbSectorsToErase--; + + /* Check if there are still sectors to erase*/ + if(pFlash.NbSectorsToErase != 0U) + { + addresstmp = pFlash.Sector; + /*Indicate user which sector has been erased*/ + DAL_FLASH_EndOfOperationCallback(addresstmp); + + /*Increment sector number*/ + pFlash.Sector++; + addresstmp = pFlash.Sector; + FLASH_Erase_Sector(addresstmp, pFlash.VoltageForErase); + } + else + { + /*No more sectors to Erase, user callback can be called.*/ + /*Reset Sector and stop Erase sectors procedure*/ + pFlash.Sector = addresstmp = 0xFFFFFFFFU; + pFlash.ProcedureOnGoing = FLASH_PROC_NONE; + + /* Flush the caches to be sure of the data consistency */ + FLASH_FlushCaches() ; + + /* FLASH EOP interrupt user callback */ + DAL_FLASH_EndOfOperationCallback(addresstmp); + } + } + else + { + if(pFlash.ProcedureOnGoing == FLASH_PROC_MASSERASE) + { + /* MassErase ended. Return the selected bank */ + /* Flush the caches to be sure of the data consistency */ + FLASH_FlushCaches() ; + + /* FLASH EOP interrupt user callback */ + DAL_FLASH_EndOfOperationCallback(pFlash.Bank); + } + else + { + /*Program ended. Return the selected address*/ + /* FLASH EOP interrupt user callback */ + DAL_FLASH_EndOfOperationCallback(pFlash.Address); + } + pFlash.ProcedureOnGoing = FLASH_PROC_NONE; + } + } + + if(pFlash.ProcedureOnGoing == FLASH_PROC_NONE) + { + /* Operation is completed, disable the PG, SERS, SNUM and MER Bits */ + CLEAR_BIT(FLASH->CTRL, (FLASH_CTRL_PG | FLASH_CTRL_SERS | FLASH_CTRL_SNUM | FLASH_MER_BIT)); + + /* Disable End of FLASH Operation interrupt */ + __DAL_FLASH_DISABLE_IT(FLASH_IT_EOP); + + /* Disable Error source interrupt */ + __DAL_FLASH_DISABLE_IT(FLASH_IT_ERR); + + /* Process Unlocked */ + __DAL_UNLOCK(&pFlash); + } +} + +/** + * @brief FLASH end of operation interrupt callback + * @param ReturnValue The value saved in this parameter depends on the ongoing procedure + * Mass Erase: Bank number which has been requested to erase + * Sectors Erase: Sector which has been erased + * (if 0xFFFFFFFFU, it means that all the selected sectors have been erased) + * Program: Address which was selected for data program + * @retval None + */ +__weak void DAL_FLASH_EndOfOperationCallback(uint32_t ReturnValue) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(ReturnValue); + /* NOTE : This function Should not be modified, when the callback is needed, + the DAL_FLASH_EndOfOperationCallback could be implemented in the user file + */ +} + +/** + * @brief FLASH operation error interrupt callback + * @param ReturnValue The value saved in this parameter depends on the ongoing procedure + * Mass Erase: Bank number which has been requested to erase + * Sectors Erase: Sector number which returned an error + * Program: Address which was selected for data program + * @retval None + */ +__weak void DAL_FLASH_OperationErrorCallback(uint32_t ReturnValue) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(ReturnValue); + /* NOTE : This function Should not be modified, when the callback is needed, + the DAL_FLASH_OperationErrorCallback could be implemented in the user file + */ +} + +/** + * @} + */ + +/** @defgroup FLASH_Exported_Functions_Group2 Peripheral Control functions + * @brief management functions + * +@verbatim + =============================================================================== + ##### Peripheral Control functions ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to control the FLASH + memory operations. + +@endverbatim + * @{ + */ + +/** + * @brief Unlock the FLASH control register access + * @retval DAL Status + */ +DAL_StatusTypeDef DAL_FLASH_Unlock(void) +{ + DAL_StatusTypeDef status = DAL_OK; + + if(READ_BIT(FLASH->CTRL, FLASH_CTRL_LOCK) != RESET) + { + /* Authorize the FLASH Registers access */ + WRITE_REG(FLASH->KEY, FLASH_KEY1); + WRITE_REG(FLASH->KEY, FLASH_KEY2); + + /* Verify Flash is unlocked */ + if(READ_BIT(FLASH->CTRL, FLASH_CTRL_LOCK) != RESET) + { + status = DAL_ERROR; + } + } + + return status; +} + +/** + * @brief Locks the FLASH control register access + * @retval DAL Status + */ +DAL_StatusTypeDef DAL_FLASH_Lock(void) +{ + /* Set the LOCK Bit to lock the FLASH Registers access */ + FLASH->CTRL |= FLASH_CTRL_LOCK; + + return DAL_OK; +} + +/** + * @brief Unlock the FLASH Option Control Registers access. + * @retval DAL Status + */ +DAL_StatusTypeDef DAL_FLASH_OB_Unlock(void) +{ + if((FLASH->OPTCTRL & FLASH_OPTCTRL_OPTLOCK) != RESET) + { + /* Authorizes the Option Byte register programming */ + FLASH->OPTKEY = FLASH_OPT_KEY1; + FLASH->OPTKEY = FLASH_OPT_KEY2; + } + else + { + return DAL_ERROR; + } + + return DAL_OK; +} + +/** + * @brief Lock the FLASH Option Control Registers access. + * @retval DAL Status + */ +DAL_StatusTypeDef DAL_FLASH_OB_Lock(void) +{ + /* Set the OPTLOCK Bit to lock the FLASH Option Byte Registers access */ + FLASH->OPTCTRL |= FLASH_OPTCTRL_OPTLOCK; + + return DAL_OK; +} + +/** + * @brief Launch the option byte loading. + * @retval DAL Status + */ +DAL_StatusTypeDef DAL_FLASH_OB_Launch(void) +{ + /* Set the OPTSTRT bit in OPTCR register */ + *(__IO uint8_t *)OPTCTRL_BYTE0_ADDRESS |= FLASH_OPTCTRL_OPTSTART; + + /* Wait for last operation to be completed */ + return(FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE)); +} + +/** + * @} + */ + +/** @defgroup FLASH_Exported_Functions_Group3 Peripheral State and Errors functions + * @brief Peripheral Errors functions + * +@verbatim + =============================================================================== + ##### Peripheral Errors functions ##### + =============================================================================== + [..] + This subsection permits to get in run-time Errors of the FLASH peripheral. + +@endverbatim + * @{ + */ + +/** + * @brief Get the specific FLASH error flag. + * @retval FLASH_ErrorCode: The returned value can be a combination of: + * @arg DAL_FLASH_ERROR_RD: FLASH Read Protection error flag (PCROP) + * @arg DAL_FLASH_ERROR_PGS: FLASH Programming Sequence error flag + * @arg DAL_FLASH_ERROR_PGP: FLASH Programming Parallelism error flag + * @arg DAL_FLASH_ERROR_PGA: FLASH Programming Alignment error flag + * @arg DAL_FLASH_ERROR_WRP: FLASH Write protected error flag + * @arg DAL_FLASH_ERROR_OPERATION: FLASH operation Error flag + */ +uint32_t DAL_FLASH_GetError(void) +{ + return pFlash.ErrorCode; +} + +/** + * @} + */ + +/** + * @brief Wait for a FLASH operation to complete. + * @param Timeout maximum flash operationtimeout + * @retval DAL Status + */ +DAL_StatusTypeDef FLASH_WaitForLastOperation(uint32_t Timeout) +{ + uint32_t tickstart = 0U; + + /* Clear Error Code */ + pFlash.ErrorCode = DAL_FLASH_ERROR_NONE; + + /* Wait for the FLASH operation to complete by polling on BUSY flag to be reset. + Even if the FLASH operation fails, the BUSY flag will be reset and an error + flag will be set */ + /* Get tick */ + tickstart = DAL_GetTick(); + + while(__DAL_FLASH_GET_FLAG(FLASH_FLAG_BSY) != RESET) + { + if(Timeout != DAL_MAX_DELAY) + { + if((Timeout == 0U)||((DAL_GetTick() - tickstart ) > Timeout)) + { + return DAL_TIMEOUT; + } + } + } + + /* Check FLASH End of Operation flag */ + if (__DAL_FLASH_GET_FLAG(FLASH_FLAG_EOP) != RESET) + { + /* Clear FLASH End of Operation pending bit */ + __DAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP); + } +#if defined(FLASH_STS_RPROERR) + if(__DAL_FLASH_GET_FLAG((FLASH_FLAG_OPERR | FLASH_FLAG_WRPERR | FLASH_FLAG_PGAERR | \ + FLASH_FLAG_PGPERR | FLASH_FLAG_PGSERR | FLASH_FLAG_RDERR)) != RESET) +#else + if(__DAL_FLASH_GET_FLAG((FLASH_FLAG_OPERR | FLASH_FLAG_WRPERR | FLASH_FLAG_PGAERR | \ + FLASH_FLAG_PGPERR | FLASH_FLAG_PGSERR)) != RESET) +#endif /* FLASH_STS_RPROERR */ + { + /*Save the error code*/ + FLASH_SetErrorCode(); + return DAL_ERROR; + } + + /* If there is no error flag set */ + return DAL_OK; + +} + +/** + * @brief Program a double word (64-bit) at a specified address. + * @note This function must be used when the device voltage range is from + * 2.7V to 3.6V and Vpp in the range 7V to 9V. + * + * @note If an erase and a program operations are requested simultaneously, + * the erase operation is performed before the program one. + * + * @param Address specifies the address to be programmed. + * @param Data specifies the data to be programmed. + * @retval None + */ +static void FLASH_Program_DoubleWord(uint32_t Address, uint64_t Data) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_FLASH_ADDRESS(Address)); + + /* If the previous operation is completed, proceed to program the new data */ + CLEAR_BIT(FLASH->CTRL, FLASH_CTRL_PGSIZE); + FLASH->CTRL |= FLASH_PSIZE_DOUBLE_WORD; + FLASH->CTRL |= FLASH_CTRL_PG; + + /* Program first word */ + *(__IO uint32_t*)Address = (uint32_t)Data; + + /* Barrier to ensure programming is performed in 2 steps, in right order + (independently of compiler optimization behavior) */ + __ISB(); + + /* Program second word */ + *(__IO uint32_t*)(Address+4) = (uint32_t)(Data >> 32); +} + + +/** + * @brief Program word (32-bit) at a specified address. + * @note This function must be used when the device voltage range is from + * 2.7V to 3.6V. + * + * @note If an erase and a program operations are requested simultaneously, + * the erase operation is performed before the program one. + * + * @param Address specifies the address to be programmed. + * @param Data specifies the data to be programmed. + * @retval None + */ +static void FLASH_Program_Word(uint32_t Address, uint32_t Data) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_FLASH_ADDRESS(Address)); + + /* If the previous operation is completed, proceed to program the new data */ + CLEAR_BIT(FLASH->CTRL, FLASH_CTRL_PGSIZE); + FLASH->CTRL |= FLASH_PSIZE_WORD; + FLASH->CTRL |= FLASH_CTRL_PG; + + *(__IO uint32_t*)Address = Data; +} + +/** + * @brief Program a half-word (16-bit) at a specified address. + * @note This function must be used when the device voltage range is from + * 2.1V to 3.6V. + * + * @note If an erase and a program operations are requested simultaneously, + * the erase operation is performed before the program one. + * + * @param Address specifies the address to be programmed. + * @param Data specifies the data to be programmed. + * @retval None + */ +static void FLASH_Program_HalfWord(uint32_t Address, uint16_t Data) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_FLASH_ADDRESS(Address)); + + /* If the previous operation is completed, proceed to program the new data */ + CLEAR_BIT(FLASH->CTRL, FLASH_CTRL_PGSIZE); + FLASH->CTRL |= FLASH_PSIZE_HALF_WORD; + FLASH->CTRL |= FLASH_CTRL_PG; + + *(__IO uint16_t*)Address = Data; +} + +/** + * @brief Program byte (8-bit) at a specified address. + * @note This function must be used when the device voltage range is from + * 1.8V to 3.6V. + * + * @note If an erase and a program operations are requested simultaneously, + * the erase operation is performed before the program one. + * + * @param Address specifies the address to be programmed. + * @param Data specifies the data to be programmed. + * @retval None + */ +static void FLASH_Program_Byte(uint32_t Address, uint8_t Data) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_FLASH_ADDRESS(Address)); + + /* If the previous operation is completed, proceed to program the new data */ + CLEAR_BIT(FLASH->CTRL, FLASH_CTRL_PGSIZE); + FLASH->CTRL |= FLASH_PSIZE_BYTE; + FLASH->CTRL |= FLASH_CTRL_PG; + + *(__IO uint8_t*)Address = Data; +} + +/** + * @brief Set the specific FLASH error flag. + * @retval None + */ +static void FLASH_SetErrorCode(void) +{ + if(__DAL_FLASH_GET_FLAG(FLASH_FLAG_WRPERR) != RESET) + { + pFlash.ErrorCode |= DAL_FLASH_ERROR_WRP; + + /* Clear FLASH write protection error pending bit */ + __DAL_FLASH_CLEAR_FLAG(FLASH_FLAG_WRPERR); + } + + if(__DAL_FLASH_GET_FLAG(FLASH_FLAG_PGAERR) != RESET) + { + pFlash.ErrorCode |= DAL_FLASH_ERROR_PGA; + + /* Clear FLASH Programming alignment error pending bit */ + __DAL_FLASH_CLEAR_FLAG(FLASH_FLAG_PGAERR); + } + + if(__DAL_FLASH_GET_FLAG(FLASH_FLAG_PGPERR) != RESET) + { + pFlash.ErrorCode |= DAL_FLASH_ERROR_PGP; + + /* Clear FLASH Programming parallelism error pending bit */ + __DAL_FLASH_CLEAR_FLAG(FLASH_FLAG_PGPERR); + } + + if(__DAL_FLASH_GET_FLAG(FLASH_FLAG_PGSERR) != RESET) + { + pFlash.ErrorCode |= DAL_FLASH_ERROR_PGS; + + /* Clear FLASH Programming sequence error pending bit */ + __DAL_FLASH_CLEAR_FLAG(FLASH_FLAG_PGSERR); + } +#if defined(FLASH_STS_RPROERR) + if(__DAL_FLASH_GET_FLAG(FLASH_FLAG_RDERR) != RESET) + { + pFlash.ErrorCode |= DAL_FLASH_ERROR_RD; + + /* Clear FLASH Proprietary readout protection error pending bit */ + __DAL_FLASH_CLEAR_FLAG(FLASH_FLAG_RDERR); + } +#endif /* FLASH_STS_RPROERR */ + if(__DAL_FLASH_GET_FLAG(FLASH_FLAG_OPERR) != RESET) + { + pFlash.ErrorCode |= DAL_FLASH_ERROR_OPERATION; + + /* Clear FLASH Operation error pending bit */ + __DAL_FLASH_CLEAR_FLAG(FLASH_FLAG_OPERR); + } +} + +/** + * @} + */ + +#endif /* DAL_FLASH_MODULE_ENABLED */ + +/** + * @} + */ + +/** + * @} + */ + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_flash_ex.c b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_flash_ex.c new file mode 100644 index 0000000000..19d7d44117 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_flash_ex.c @@ -0,0 +1,893 @@ +/** + * + * @file apm32f4xx_dal_flash_ex.c + * @brief Extended FLASH DAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the FLASH extension peripheral: + * + Extended programming operations functions + * + @verbatim + ============================================================================== + ##### Flash Extension features ##### + ============================================================================== + + [..] Comparing to other previous devices, the FLASH interface for APM32F411xx + devices contains the following additional features + + (+) Capacity up to 2 Mbyte with dual bank architecture supporting read-while-write + capability (RWW) + (+) Dual bank memory organization + (+) PCROP protection for all banks + + ##### How to use this driver ##### + ============================================================================== + [..] This driver provides functions to configure and program the FLASH memory + of all APM32F411xx devices. It includes + (#) FLASH Memory Erase functions: + (++) Lock and Unlock the FLASH interface using DAL_FLASH_Unlock() and + DAL_FLASH_Lock() functions + (++) Erase function: Erase sector, erase all sectors + (++) There are two modes of erase : + (+++) Polling Mode using DAL_FLASHEx_Erase() + (+++) Interrupt Mode using DAL_FLASHEx_Erase_IT() + + (#) Option Bytes Programming functions: Use DAL_FLASHEx_OBProgram() to : + (++) Set/Reset the write protection + (++) Set the Read protection Level + (++) Set the BOR level + (++) Program the user Option Bytes + (#) Advanced Option Bytes Programming functions: Use DAL_FLASHEx_AdvOBProgram() to : + (++) Extended space (bank 2) erase function + (++) Full FLASH space (2 Mo) erase (bank 1 and bank 2) + (++) Dual Boot activation + (++) Write protection configuration for bank 2 + (++) PCROP protection configuration and control for both banks + + @endverbatim + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2017 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file in + * the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + */ + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @defgroup FLASHEx FLASHEx + * @brief FLASH DAL Extension module driver + * @{ + */ + +#ifdef DAL_FLASH_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/** @addtogroup FLASHEx_Private_Constants + * @{ + */ +#define FLASH_TIMEOUT_VALUE 50000U /* 50 s */ +/** + * @} + */ + +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/** @addtogroup FLASHEx_Private_Variables + * @{ + */ +extern FLASH_ProcessTypeDef pFlash; +/** + * @} + */ + +/* Private function prototypes -----------------------------------------------*/ +/** @addtogroup FLASHEx_Private_Functions + * @{ + */ +/* Option bytes control */ +static void FLASH_MassErase(uint8_t VoltageRange, uint32_t Banks); +static DAL_StatusTypeDef FLASH_OB_EnableWRP(uint32_t WRPSector, uint32_t Banks); +static DAL_StatusTypeDef FLASH_OB_DisableWRP(uint32_t WRPSector, uint32_t Banks); +static DAL_StatusTypeDef FLASH_OB_RDP_LevelConfig(uint8_t Level); +static DAL_StatusTypeDef FLASH_OB_UserConfig(uint8_t Iwdt, uint8_t Stop, uint8_t Stdby); +static DAL_StatusTypeDef FLASH_OB_BOR_LevelConfig(uint8_t Level); +static uint8_t FLASH_OB_GetUser(void); +static uint16_t FLASH_OB_GetWRP(void); +static uint8_t FLASH_OB_GetRDP(void); +static uint8_t FLASH_OB_GetBOR(void); + +#if defined(APM32F411xx) +static DAL_StatusTypeDef FLASH_OB_EnablePCROP(uint32_t Sector); +static DAL_StatusTypeDef FLASH_OB_DisablePCROP(uint32_t Sector); +#endif /* APM32F411xx */ + +extern DAL_StatusTypeDef FLASH_WaitForLastOperation(uint32_t Timeout); +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +/** @defgroup FLASHEx_Exported_Functions FLASHEx Exported Functions + * @{ + */ + +/** @defgroup FLASHEx_Exported_Functions_Group1 Extended IO operation functions + * @brief Extended IO operation functions + * +@verbatim + =============================================================================== + ##### Extended programming operation functions ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to manage the Extension FLASH + programming operations. + +@endverbatim + * @{ + */ +/** + * @brief Perform a mass erase or erase the specified FLASH memory sectors + * @param[in] pEraseInit pointer to an FLASH_EraseInitTypeDef structure that + * contains the configuration information for the erasing. + * + * @param[out] SectorError pointer to variable that + * contains the configuration information on faulty sector in case of error + * (0xFFFFFFFFU means that all the sectors have been correctly erased) + * + * @retval DAL Status + */ +DAL_StatusTypeDef DAL_FLASHEx_Erase(FLASH_EraseInitTypeDef *pEraseInit, uint32_t *SectorError) +{ + DAL_StatusTypeDef status = DAL_ERROR; + uint32_t index = 0U; + + /* Process Locked */ + __DAL_LOCK(&pFlash); + + /* Check the parameters */ + ASSERT_PARAM(IS_FLASH_TYPEERASE(pEraseInit->TypeErase)); + + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE); + + if (status == DAL_OK) + { + /*Initialization of SectorError variable*/ + *SectorError = 0xFFFFFFFFU; + + if (pEraseInit->TypeErase == FLASH_TYPEERASE_MASSERASE) + { + /*Mass erase to be done*/ + FLASH_MassErase((uint8_t) pEraseInit->VoltageRange, pEraseInit->Banks); + + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE); + + /* if the erase operation is completed, disable the MER Bit */ + FLASH->CTRL &= (~FLASH_MER_BIT); + } + else + { + /* Check the parameters */ + ASSERT_PARAM(IS_FLASH_NBSECTORS(pEraseInit->NbSectors + pEraseInit->Sector)); + + /* Erase by sector by sector to be done*/ + for (index = pEraseInit->Sector; index < (pEraseInit->NbSectors + pEraseInit->Sector); index++) + { + FLASH_Erase_Sector(index, (uint8_t) pEraseInit->VoltageRange); + + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE); + + /* If the erase operation is completed, disable the SER and SNB Bits */ + CLEAR_BIT(FLASH->CTRL, (FLASH_CTRL_SERS | FLASH_CTRL_SNUM)); + + if (status != DAL_OK) + { + /* In case of error, stop erase procedure and return the faulty sector*/ + *SectorError = index; + break; + } + } + } + /* Flush the caches to be sure of the data consistency */ + FLASH_FlushCaches(); + } + + /* Process Unlocked */ + __DAL_UNLOCK(&pFlash); + + return status; +} + +/** + * @brief Perform a mass erase or erase the specified FLASH memory sectors with interrupt enabled + * @param pEraseInit pointer to an FLASH_EraseInitTypeDef structure that + * contains the configuration information for the erasing. + * + * @retval DAL Status + */ +DAL_StatusTypeDef DAL_FLASHEx_Erase_IT(FLASH_EraseInitTypeDef *pEraseInit) +{ + DAL_StatusTypeDef status = DAL_OK; + + /* Process Locked */ + __DAL_LOCK(&pFlash); + + /* Check the parameters */ + ASSERT_PARAM(IS_FLASH_TYPEERASE(pEraseInit->TypeErase)); + + /* Enable End of FLASH Operation interrupt */ + __DAL_FLASH_ENABLE_IT(FLASH_IT_EOP); + + /* Enable Error source interrupt */ + __DAL_FLASH_ENABLE_IT(FLASH_IT_ERR); + + /* Clear pending flags (if any) */ + __DAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP | FLASH_FLAG_OPERR | FLASH_FLAG_WRPERR | \ + FLASH_FLAG_PGAERR | FLASH_FLAG_PGPERR | FLASH_FLAG_PGSERR); + + if (pEraseInit->TypeErase == FLASH_TYPEERASE_MASSERASE) + { + /*Mass erase to be done*/ + pFlash.ProcedureOnGoing = FLASH_PROC_MASSERASE; + pFlash.Bank = pEraseInit->Banks; + FLASH_MassErase((uint8_t) pEraseInit->VoltageRange, pEraseInit->Banks); + } + else + { + /* Erase by sector to be done*/ + + /* Check the parameters */ + ASSERT_PARAM(IS_FLASH_NBSECTORS(pEraseInit->NbSectors + pEraseInit->Sector)); + + pFlash.ProcedureOnGoing = FLASH_PROC_SECTERASE; + pFlash.NbSectorsToErase = pEraseInit->NbSectors; + pFlash.Sector = pEraseInit->Sector; + pFlash.VoltageForErase = (uint8_t)pEraseInit->VoltageRange; + + /*Erase 1st sector and wait for IT*/ + FLASH_Erase_Sector(pEraseInit->Sector, pEraseInit->VoltageRange); + } + + return status; +} + +/** + * @brief Program option bytes + * @param pOBInit pointer to an FLASH_OBInitStruct structure that + * contains the configuration information for the programming. + * + * @retval DAL Status + */ +DAL_StatusTypeDef DAL_FLASHEx_OBProgram(FLASH_OBProgramInitTypeDef *pOBInit) +{ + DAL_StatusTypeDef status = DAL_ERROR; + + /* Process Locked */ + __DAL_LOCK(&pFlash); + + /* Check the parameters */ + ASSERT_PARAM(IS_OPTIONBYTE(pOBInit->OptionType)); + + /*Write protection configuration*/ + if ((pOBInit->OptionType & OPTIONBYTE_WRP) == OPTIONBYTE_WRP) + { + ASSERT_PARAM(IS_WRPSTATE(pOBInit->WRPState)); + if (pOBInit->WRPState == OB_WRPSTATE_ENABLE) + { + /*Enable of Write protection on the selected Sector*/ + status = FLASH_OB_EnableWRP(pOBInit->WRPSector, pOBInit->Banks); + } + else + { + /*Disable of Write protection on the selected Sector*/ + status = FLASH_OB_DisableWRP(pOBInit->WRPSector, pOBInit->Banks); + } + } + + /*Read protection configuration*/ + if ((pOBInit->OptionType & OPTIONBYTE_RDP) == OPTIONBYTE_RDP) + { + status = FLASH_OB_RDP_LevelConfig(pOBInit->RDPLevel); + } + + /*USER configuration*/ + if ((pOBInit->OptionType & OPTIONBYTE_USER) == OPTIONBYTE_USER) + { + status = FLASH_OB_UserConfig(pOBInit->USERConfig & OB_IWDT_SW, + pOBInit->USERConfig & OB_STOP_NO_RST, + pOBInit->USERConfig & OB_STDBY_NO_RST); + } + + /*BOR Level configuration*/ + if ((pOBInit->OptionType & OPTIONBYTE_BOR) == OPTIONBYTE_BOR) + { + status = FLASH_OB_BOR_LevelConfig(pOBInit->BORLevel); + } + + /* Process Unlocked */ + __DAL_UNLOCK(&pFlash); + + return status; +} + +/** + * @brief Get the Option byte configuration + * @param pOBInit pointer to an FLASH_OBInitStruct structure that + * contains the configuration information for the programming. + * + * @retval None + */ +void DAL_FLASHEx_OBGetConfig(FLASH_OBProgramInitTypeDef *pOBInit) +{ + pOBInit->OptionType = OPTIONBYTE_WRP | OPTIONBYTE_RDP | OPTIONBYTE_USER | OPTIONBYTE_BOR; + + /*Get WRP*/ + pOBInit->WRPSector = (uint32_t)FLASH_OB_GetWRP(); + + /*Get RDP Level*/ + pOBInit->RDPLevel = (uint32_t)FLASH_OB_GetRDP(); + + /*Get USER*/ + pOBInit->USERConfig = (uint8_t)FLASH_OB_GetUser(); + + /*Get BOR Level*/ + pOBInit->BORLevel = (uint32_t)FLASH_OB_GetBOR(); +} + +#if defined(APM32F411xx) +/** + * @brief Program option bytes + * @param pAdvOBInit pointer to an FLASH_AdvOBProgramInitTypeDef structure that + * contains the configuration information for the programming. + * + * @retval DAL Status + */ +DAL_StatusTypeDef DAL_FLASHEx_AdvOBProgram(FLASH_AdvOBProgramInitTypeDef *pAdvOBInit) +{ + DAL_StatusTypeDef status = DAL_ERROR; + + /* Check the parameters */ + ASSERT_PARAM(IS_OBEX(pAdvOBInit->OptionType)); + + /*Program PCROP option byte*/ + if (((pAdvOBInit->OptionType) & OPTIONBYTE_PCROP) == OPTIONBYTE_PCROP) + { + /* Check the parameters */ + ASSERT_PARAM(IS_PCROPSTATE(pAdvOBInit->PCROPState)); + if ((pAdvOBInit->PCROPState) == OB_PCROP_STATE_ENABLE) + { + /*Enable of Write protection on the selected Sector*/ +#if defined(APM32F411xx) + status = FLASH_OB_EnablePCROP(pAdvOBInit->Sectors); +#endif /* APM32F411xx */ + } + else + { + /*Disable of Write protection on the selected Sector*/ +#if defined(APM32F411xx) + status = FLASH_OB_DisablePCROP(pAdvOBInit->Sectors); +#endif /* APM32F411xx */ + } + } + + return status; +} + +/** + * @brief Get the OBEX byte configuration + * @param pAdvOBInit pointer to an FLASH_AdvOBProgramInitTypeDef structure that + * contains the configuration information for the programming. + * + * @retval None + */ +void DAL_FLASHEx_AdvOBGetConfig(FLASH_AdvOBProgramInitTypeDef *pAdvOBInit) +{ +#if defined(APM32F411xx) + /*Get Sector*/ + pAdvOBInit->Sectors = (*(__IO uint16_t *)(OPTCTRL_BYTE2_ADDRESS)); +#endif /* APM32F411xx */ +} + +/** + * @brief Select the Protection Mode + * + * @note After PCROP activated Option Byte modification NOT POSSIBLE! excepted + * Global Read Out Protection modification (from level1 to level0) + * @note Once SPRMOD bit is active unprotection of a protected sector is not possible + * @note Read a protected sector will set RDERR Flag and write a protected sector will set WRPERR Flag + * @note This function can be used only for APM32F411xx devices. + * + * @retval DAL Status + */ +DAL_StatusTypeDef DAL_FLASHEx_OB_SelectPCROP(void) +{ + uint8_t optiontmp = 0xFF; + + /* Mask SPRMOD bit */ + optiontmp = (uint8_t)((*(__IO uint8_t *)OPTCTRL_BYTE3_ADDRESS) & (uint8_t)0x7F); + + /* Update Option Byte */ + *(__IO uint8_t *)OPTCTRL_BYTE3_ADDRESS = (uint8_t)(OB_PCROP_SELECTED | optiontmp); + + return DAL_OK; +} + +/** + * @brief Deselect the Protection Mode + * + * @note After PCROP activated Option Byte modification NOT POSSIBLE! excepted + * Global Read Out Protection modification (from level1 to level0) + * @note Once SPRMOD bit is active unprotection of a protected sector is not possible + * @note Read a protected sector will set RDERR Flag and write a protected sector will set WRPERR Flag + * @note This function can be used only for APM32F411xx devices. + * + * @retval DAL Status + */ +DAL_StatusTypeDef DAL_FLASHEx_OB_DeSelectPCROP(void) +{ + uint8_t optiontmp = 0xFF; + + /* Mask SPRMOD bit */ + optiontmp = (uint8_t)((*(__IO uint8_t *)OPTCTRL_BYTE3_ADDRESS) & (uint8_t)0x7F); + + /* Update Option Byte */ + *(__IO uint8_t *)OPTCTRL_BYTE3_ADDRESS = (uint8_t)(OB_PCROP_DESELECTED | optiontmp); + + return DAL_OK; +} +#endif /* APM32F411xx */ + +/** + * @} + */ + +#if defined(APM32F405xx) || defined(APM32F407xx) || defined(APM32F417xx) ||\ + defined(APM32F465xx) || defined(APM32F411xx) +/** + * @brief Mass erase of FLASH memory + * @param VoltageRange The device voltage range which defines the erase parallelism. + * This parameter can be one of the following values: + * @arg FLASH_VOLTAGE_RANGE_1: when the device voltage range is 1.8V to 2.1V, + * the operation will be done by byte (8-bit) + * @arg FLASH_VOLTAGE_RANGE_2: when the device voltage range is 2.1V to 2.7V, + * the operation will be done by half word (16-bit) + * @arg FLASH_VOLTAGE_RANGE_3: when the device voltage range is 2.7V to 3.6V, + * the operation will be done by word (32-bit) + * @arg FLASH_VOLTAGE_RANGE_4: when the device voltage range is 2.7V to 3.6V + External Vpp, + * the operation will be done by double word (64-bit) + * + * @param Banks Banks to be erased + * This parameter can be one of the following values: + * @arg FLASH_BANK_1: Bank1 to be erased + * + * @retval None + */ +static void FLASH_MassErase(uint8_t VoltageRange, uint32_t Banks) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_VOLTAGERANGE(VoltageRange)); + ASSERT_PARAM(IS_FLASH_BANK(Banks)); + + /* If the previous operation is completed, proceed to erase all sectors */ + CLEAR_BIT(FLASH->CTRL, FLASH_CTRL_PGSIZE); + FLASH->CTRL |= FLASH_CTRL_MERS; + FLASH->CTRL |= FLASH_CTRL_START | ((uint32_t)VoltageRange << 8U); +} + +/** + * @brief Erase the specified FLASH memory sector + * @param Sector FLASH sector to erase + * The value of this parameter depend on device used within the same series + * @param VoltageRange The device voltage range which defines the erase parallelism. + * This parameter can be one of the following values: + * @arg FLASH_VOLTAGE_RANGE_1: when the device voltage range is 1.8V to 2.1V, + * the operation will be done by byte (8-bit) + * @arg FLASH_VOLTAGE_RANGE_2: when the device voltage range is 2.1V to 2.7V, + * the operation will be done by half word (16-bit) + * @arg FLASH_VOLTAGE_RANGE_3: when the device voltage range is 2.7V to 3.6V, + * the operation will be done by word (32-bit) + * @arg FLASH_VOLTAGE_RANGE_4: when the device voltage range is 2.7V to 3.6V + External Vpp, + * the operation will be done by double word (64-bit) + * + * @retval None + */ +void FLASH_Erase_Sector(uint32_t Sector, uint8_t VoltageRange) +{ + uint32_t tmp_psize = 0U; + + /* Check the parameters */ + ASSERT_PARAM(IS_FLASH_SECTOR(Sector)); + ASSERT_PARAM(IS_VOLTAGERANGE(VoltageRange)); + + if (VoltageRange == FLASH_VOLTAGE_RANGE_1) + { + tmp_psize = FLASH_PSIZE_BYTE; + } + else if (VoltageRange == FLASH_VOLTAGE_RANGE_2) + { + tmp_psize = FLASH_PSIZE_HALF_WORD; + } + else if (VoltageRange == FLASH_VOLTAGE_RANGE_3) + { + tmp_psize = FLASH_PSIZE_WORD; + } + else + { + tmp_psize = FLASH_PSIZE_DOUBLE_WORD; + } + + /* If the previous operation is completed, proceed to erase the sector */ + CLEAR_BIT(FLASH->CTRL, FLASH_CTRL_PGSIZE); + FLASH->CTRL |= tmp_psize; + CLEAR_BIT(FLASH->CTRL, FLASH_CTRL_SNUM); + FLASH->CTRL |= FLASH_CTRL_SERS | (Sector << FLASH_CTRL_SNUM_Pos); + FLASH->CTRL |= FLASH_CTRL_START; +} + +/** + * @brief Enable the write protection of the desired bank 1 sectors + * + * @note When the memory read protection level is selected (RDP level = 1), + * it is not possible to program or erase the flash sector i if CortexM4 + * debug features are connected or boot code is executed in RAM, even if nWRPi = 1 + * @note Active value of nWRPi bits is inverted when PCROP mode is active (SPRMOD =1). + * + * @param WRPSector specifies the sector(s) to be write protected. + * The value of this parameter depend on device used within the same series + * + * @param Banks Enable write protection on all the sectors for the specific bank + * This parameter can be one of the following values: + * @arg FLASH_BANK_1: WRP on all sectors of bank1 + * + * @retval DAL Status + */ +static DAL_StatusTypeDef FLASH_OB_EnableWRP(uint32_t WRPSector, uint32_t Banks) +{ + DAL_StatusTypeDef status = DAL_OK; + + /* Check the parameters */ + ASSERT_PARAM(IS_OB_WRP_SECTOR(WRPSector)); + ASSERT_PARAM(IS_FLASH_BANK(Banks)); + + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE); + + if (status == DAL_OK) + { + *(__IO uint16_t *)OPTCTRL_BYTE2_ADDRESS &= (~WRPSector); + } + + return status; +} + +/** + * @brief Disable the write protection of the desired bank 1 sectors + * + * @note When the memory read protection level is selected (RDP level = 1), + * it is not possible to program or erase the flash sector i if CortexM4 + * debug features are connected or boot code is executed in RAM, even if nWRPi = 1 + * @note Active value of nWRPi bits is inverted when PCROP mode is active (SPRMOD =1). + * + * @param WRPSector specifies the sector(s) to be write protected. + * The value of this parameter depend on device used within the same series + * + * @param Banks Enable write protection on all the sectors for the specific bank + * This parameter can be one of the following values: + * @arg FLASH_BANK_1: WRP on all sectors of bank1 + * + * @retval DAL Status + */ +static DAL_StatusTypeDef FLASH_OB_DisableWRP(uint32_t WRPSector, uint32_t Banks) +{ + DAL_StatusTypeDef status = DAL_OK; + + /* Check the parameters */ + ASSERT_PARAM(IS_OB_WRP_SECTOR(WRPSector)); + ASSERT_PARAM(IS_FLASH_BANK(Banks)); + + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE); + + if (status == DAL_OK) + { + *(__IO uint16_t *)OPTCTRL_BYTE2_ADDRESS |= (uint16_t)WRPSector; + } + + return status; +} +#endif /* APM32F40xxx || APM32F41xxx || APM32F411xx || APM32F465xx */ + +#if defined(APM32F411xx) +/** + * @brief Enable the read/write protection (PCROP) of the desired sectors. + * @param Sector specifies the sector(s) to be read/write protected or unprotected. + * This parameter can be one of the following values: + * @arg OB_PCROP: A value between OB_PCROP_Sector0 and OB_PCROP_Sector5 + * @arg OB_PCROP_Sector_All + * @retval DAL Status + */ +static DAL_StatusTypeDef FLASH_OB_EnablePCROP(uint32_t Sector) +{ + DAL_StatusTypeDef status = DAL_OK; + + /* Check the parameters */ + ASSERT_PARAM(IS_OB_PCROP(Sector)); + + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE); + + if (status == DAL_OK) + { + *(__IO uint16_t *)OPTCTRL_BYTE2_ADDRESS |= (uint16_t)Sector; + } + + return status; +} + + +/** + * @brief Disable the read/write protection (PCROP) of the desired sectors. + * @param Sector specifies the sector(s) to be read/write protected or unprotected. + * This parameter can be one of the following values: + * @arg OB_PCROP: A value between OB_PCROP_Sector0 and OB_PCROP_Sector5 + * @arg OB_PCROP_Sector_All + * @retval DAL Status + */ +static DAL_StatusTypeDef FLASH_OB_DisablePCROP(uint32_t Sector) +{ + DAL_StatusTypeDef status = DAL_OK; + + /* Check the parameters */ + ASSERT_PARAM(IS_OB_PCROP(Sector)); + + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE); + + if (status == DAL_OK) + { + *(__IO uint16_t *)OPTCTRL_BYTE2_ADDRESS &= (~Sector); + } + + return status; + +} +#endif /* APM32F411xx */ + +/** + * @brief Set the read protection level. + * @param Level specifies the read protection level. + * This parameter can be one of the following values: + * @arg OB_RDP_LEVEL_0: No protection + * @arg OB_RDP_LEVEL_1: Read protection of the memory + * @arg OB_RDP_LEVEL_2: Full chip protection + * + * @note WARNING: When enabling OB_RDP level 2 it's no more possible to go back to level 1 or 0 + * + * @retval DAL Status + */ +static DAL_StatusTypeDef FLASH_OB_RDP_LevelConfig(uint8_t Level) +{ + DAL_StatusTypeDef status = DAL_OK; + + /* Check the parameters */ + ASSERT_PARAM(IS_OB_RDP_LEVEL(Level)); + + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE); + + if (status == DAL_OK) + { + *(__IO uint8_t *)OPTCTRL_BYTE1_ADDRESS = Level; + } + + return status; +} + +/** + * @brief Program the FLASH User Option Byte: IWDT_SW / RST_STOP / RST_STDBY. + * @param Iwdt Selects the IWDT mode + * This parameter can be one of the following values: + * @arg OB_IWDT_SW: Software IWDT selected + * @arg OB_IWDT_HW: Hardware IWDT selected + * @param Stop Reset event when entering STOP mode. + * This parameter can be one of the following values: + * @arg OB_STOP_NO_RST: No reset generated when entering in STOP + * @arg OB_STOP_RST: Reset generated when entering in STOP + * @param Stdby Reset event when entering Standby mode. + * This parameter can be one of the following values: + * @arg OB_STDBY_NO_RST: No reset generated when entering in STANDBY + * @arg OB_STDBY_RST: Reset generated when entering in STANDBY + * @retval DAL Status + */ +static DAL_StatusTypeDef FLASH_OB_UserConfig(uint8_t Iwdt, uint8_t Stop, uint8_t Stdby) +{ + uint8_t optiontmp = 0xFF; + DAL_StatusTypeDef status = DAL_OK; + + /* Check the parameters */ + ASSERT_PARAM(IS_OB_IWDT_SOURCE(Iwdt)); + ASSERT_PARAM(IS_OB_STOP_SOURCE(Stop)); + ASSERT_PARAM(IS_OB_STDBY_SOURCE(Stdby)); + + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE); + + if (status == DAL_OK) + { + /* Mask OPTLOCK, OPTSTRT, BOR_LEV and BFB2 bits */ + optiontmp = (uint8_t)((*(__IO uint8_t *)OPTCTRL_BYTE0_ADDRESS) & (uint8_t)0x1F); + + /* Update User Option Byte */ + *(__IO uint8_t *)OPTCTRL_BYTE0_ADDRESS = Iwdt | (uint8_t)(Stdby | (uint8_t)(Stop | ((uint8_t)optiontmp))); + } + + return status; +} + +/** + * @brief Set the BOR Level. + * @param Level specifies the Option Bytes BOR Reset Level. + * This parameter can be one of the following values: + * @arg OB_BOR_LEVEL3: Supply voltage ranges from 2.7 to 3.6 V + * @arg OB_BOR_LEVEL2: Supply voltage ranges from 2.4 to 2.7 V + * @arg OB_BOR_LEVEL1: Supply voltage ranges from 2.1 to 2.4 V + * @arg OB_BOR_OFF: Supply voltage ranges from 1.62 to 2.1 V + * @retval DAL Status + */ +static DAL_StatusTypeDef FLASH_OB_BOR_LevelConfig(uint8_t Level) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_OB_BOR_LEVEL(Level)); + + /* Set the BOR Level */ + *(__IO uint8_t *)OPTCTRL_BYTE0_ADDRESS &= (~FLASH_OPTCTRL_BORLVL); + *(__IO uint8_t *)OPTCTRL_BYTE0_ADDRESS |= Level; + + return DAL_OK; + +} + +/** + * @brief Return the FLASH User Option Byte value. + * @retval uint8_t FLASH User Option Bytes values: IWDT_SW(Bit0), RST_STOP(Bit1) + * and RST_STDBY(Bit2). + */ +static uint8_t FLASH_OB_GetUser(void) +{ + /* Return the User Option Byte */ + return ((uint8_t)(FLASH->OPTCTRL & 0xE0)); +} + +/** + * @brief Return the FLASH Write Protection Option Bytes value. + * @retval uint16_t FLASH Write Protection Option Bytes value + */ +static uint16_t FLASH_OB_GetWRP(void) +{ + /* Return the FLASH write protection Register value */ + return (*(__IO uint16_t *)(OPTCTRL_BYTE2_ADDRESS)); +} + +/** + * @brief Returns the FLASH Read Protection level. + * @retval FLASH ReadOut Protection Status: + * This parameter can be one of the following values: + * @arg OB_RDP_LEVEL_0: No protection + * @arg OB_RDP_LEVEL_1: Read protection of the memory + * @arg OB_RDP_LEVEL_2: Full chip protection + */ +static uint8_t FLASH_OB_GetRDP(void) +{ + uint8_t readstatus = OB_RDP_LEVEL_0; + + if (*(__IO uint8_t *)(OPTCTRL_BYTE1_ADDRESS) == (uint8_t)OB_RDP_LEVEL_2) + { + readstatus = OB_RDP_LEVEL_2; + } + else if (*(__IO uint8_t *)(OPTCTRL_BYTE1_ADDRESS) == (uint8_t)OB_RDP_LEVEL_0) + { + readstatus = OB_RDP_LEVEL_0; + } + else + { + readstatus = OB_RDP_LEVEL_1; + } + + return readstatus; +} + +/** + * @brief Returns the FLASH BOR level. + * @retval uint8_t The FLASH BOR level: + * - OB_BOR_LEVEL3: Supply voltage ranges from 2.7 to 3.6 V + * - OB_BOR_LEVEL2: Supply voltage ranges from 2.4 to 2.7 V + * - OB_BOR_LEVEL1: Supply voltage ranges from 2.1 to 2.4 V + * - OB_BOR_OFF : Supply voltage ranges from 1.62 to 2.1 V + */ +static uint8_t FLASH_OB_GetBOR(void) +{ + /* Return the FLASH BOR level */ + return (uint8_t)(*(__IO uint8_t *)(OPTCTRL_BYTE0_ADDRESS) & (uint8_t)0x0C); +} + +/** + * @brief Flush the instruction and data caches + * @retval None + */ +void FLASH_FlushCaches(void) +{ + /* Flush instruction cache */ + if (READ_BIT(FLASH->ACCTRL, FLASH_ACCTRL_ICACHEEN) != RESET) + { + /* Disable instruction cache */ + __DAL_FLASH_INSTRUCTION_CACHE_DISABLE(); + /* Reset instruction cache */ + __DAL_FLASH_INSTRUCTION_CACHE_RESET(); + /* Enable instruction cache */ + __DAL_FLASH_INSTRUCTION_CACHE_ENABLE(); + } + + /* Flush data cache */ + if (READ_BIT(FLASH->ACCTRL, FLASH_ACCTRL_DCACHEEN) != RESET) + { + /* Disable data cache */ + __DAL_FLASH_DATA_CACHE_DISABLE(); + /* Reset data cache */ + __DAL_FLASH_DATA_CACHE_RESET(); + /* Enable data cache */ + __DAL_FLASH_DATA_CACHE_ENABLE(); + } +} + +/** + * @} + */ + +#endif /* DAL_FLASH_MODULE_ENABLED */ + +/** + * @} + */ + +/** + * @} + */ + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_flash_ramfunc.c b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_flash_ramfunc.c new file mode 100644 index 0000000000..d238020c79 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_flash_ramfunc.c @@ -0,0 +1,196 @@ +/** + * + * @file apm32f4xx_dal_flash_ramfunc.c + * @brief FLASH RAMFUNC module driver. + * This file provides a FLASH firmware functions which should be + * executed from internal SRAM + * + Stop/Start the flash interface while System Run + * + Enable/Disable the flash sleep while System Run + @verbatim + ============================================================================== + ##### APIs executed from Internal RAM ##### + ============================================================================== + [..] + *** ARM Compiler *** + -------------------- + [..] RAM functions are defined using the toolchain options. + Functions that are be executed in RAM should reside in a separate + source module. Using the 'Options for File' dialog you can simply change + the 'Code / Const' area of a module to a memory space in physical RAM. + Available memory areas are declared in the 'Target' tab of the + Options for Target' dialog. + + *** ICCARM Compiler *** + ----------------------- + [..] RAM functions are defined using a specific toolchain keyword "__ramfunc". + + *** GNU Compiler *** + -------------------- + [..] RAM functions are defined using a specific toolchain attribute + "__attribute__((section(".RamFunc")))". + + @endverbatim + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2017 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file in + * the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + */ + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @defgroup FLASH_RAMFUNC FLASH RAMFUNC + * @brief FLASH functions executed from RAM + * @{ + */ +#ifdef DAL_FLASH_MODULE_ENABLED +#if defined(APM32F411xx) + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Exported functions --------------------------------------------------------*/ +/** @defgroup FLASH_RAMFUNC_Exported_Functions FLASH RAMFUNC Exported Functions + * @{ + */ + +/** @defgroup FLASH_RAMFUNC_Exported_Functions_Group1 Peripheral features functions executed from internal RAM + * @brief Peripheral Extended features functions + * +@verbatim + + =============================================================================== + ##### ramfunc functions ##### + =============================================================================== + [..] + This subsection provides a set of functions that should be executed from RAM + transfers. + +@endverbatim + * @{ + */ + +/** + * @brief Stop the flash interface while System Run + * @note This mode is only available for APM32F41xxx/APM32F446xx devices. + * @note This mode couldn't be set while executing with the flash itself. + * It should be done with specific routine executed from RAM. + * @retval DAL status + */ +__RAM_FUNC DAL_StatusTypeDef DAL_FLASHEx_StopFlashInterfaceClk(void) +{ + /* Enable Power ctrl clock */ + __DAL_RCM_PMU_CLK_ENABLE(); + /* Stop the flash interface while System Run */ + SET_BIT(PMU->CTRL, PMU_CTRL_FLASHEN); + + return DAL_OK; +} + +/** + * @brief Start the flash interface while System Run + * @note This mode is only available for APM32F411xx/APM32F446xx devices. + * @note This mode couldn't be set while executing with the flash itself. + * It should be done with specific routine executed from RAM. + * @retval DAL status + */ +__RAM_FUNC DAL_StatusTypeDef DAL_FLASHEx_StartFlashInterfaceClk(void) +{ + /* Enable Power ctrl clock */ + __DAL_RCM_PMU_CLK_ENABLE(); + /* Start the flash interface while System Run */ + CLEAR_BIT(PMU->CTRL, PMU_CTRL_FLASHEN); + + return DAL_OK; +} + +/** + * @brief Enable the flash sleep while System Run + * @note This mode is only available for APM32F41xxx/APM32F446xx devices. + * @note This mode could n't be set while executing with the flash itself. + * It should be done with specific routine executed from RAM. + * @retval DAL status + */ +__RAM_FUNC DAL_StatusTypeDef DAL_FLASHEx_EnableFlashSleepMode(void) +{ + /* Enable Power ctrl clock */ + __DAL_RCM_PMU_CLK_ENABLE(); + /* Enable the flash sleep while System Run */ + SET_BIT(PMU->CTRL, PMU_CTRL_FSMODE); + + return DAL_OK; +} + +/** + * @brief Disable the flash sleep while System Run + * @note This mode is only available for APM32F41xxx/APM32F446xx devices. + * @note This mode couldn't be set while executing with the flash itself. + * It should be done with specific routine executed from RAM. + * @retval DAL status + */ +__RAM_FUNC DAL_StatusTypeDef DAL_FLASHEx_DisableFlashSleepMode(void) +{ + /* Enable Power ctrl clock */ + __DAL_RCM_PMU_CLK_ENABLE(); + /* Disable the flash sleep while System Run */ + CLEAR_BIT(PMU->CTRL, PMU_CTRL_FSMODE); + + return DAL_OK; +} + +/** + * @} + */ + +/** + * @} + */ + +#endif /* APM32F411xx */ +#endif /* DAL_FLASH_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_gpio.c b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_gpio.c new file mode 100644 index 0000000000..2849f4aece --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_gpio.c @@ -0,0 +1,553 @@ +/** + * + * @file apm32f4xx_dal_gpio.c + * @brief GPIO DAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the General Purpose Input/Output (GPIO) peripheral: + * + Initialization and de-initialization functions + * + IO operation functions + * + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2017 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + * + @verbatim + ============================================================================== + ##### GPIO Peripheral features ##### + ============================================================================== + [..] + Subject to the specific hardware characteristics of each I/O port listed in the datasheet, each + port bit of the General Purpose IO (GPIO) Ports, can be individually configured by software + in several modes: + (+) Input mode + (+) Analog mode + (+) Output mode + (+) Alternate function mode + (+) External interrupt/event lines + + [..] + During and just after reset, the alternate functions and external interrupt + lines are not active and the I/O ports are configured in input floating mode. + + [..] + All GPIO pins have weak internal pull-up and pull-down resistors, which can be + activated or not. + + [..] + In Output or Alternate mode, each IO can be configured on open-drain or push-pull + type and the IO speed can be selected depending on the VDD value. + + [..] + All ports have external interrupt/event capability. To use external interrupt + lines, the port must be configured in input mode. All available GPIO pins are + connected to the 16 external interrupt/event lines from EINT0 to EINT15. + + [..] + The external interrupt/event controller consists of up to 23 edge detectors + (16 lines are connected to GPIO) for generating event/interrupt requests (each + input line can be independently configured to select the type (interrupt or event) + and the corresponding trigger event (rising or falling or both). Each line can + also be masked independently. + + ##### How to use this driver ##### + ============================================================================== + [..] + (#) Enable the GPIO AHB clock using the following function: __DAL_RCM_GPIOx_CLK_ENABLE(). + + (#) Configure the GPIO pin(s) using DAL_GPIO_Init(). + (++) Configure the IO mode using "Mode" member from GPIO_InitTypeDef structure + (++) Activate Pull-up, Pull-down resistor using "Pull" member from GPIO_InitTypeDef + structure. + (++) In case of Output or alternate function mode selection: the speed is + configured through "Speed" member from GPIO_InitTypeDef structure. + (++) In alternate mode is selection, the alternate function connected to the IO + is configured through "Alternate" member from GPIO_InitTypeDef structure. + (++) Analog mode is required when a pin is to be used as ADC channel + or DAC output. + (++) In case of external interrupt/event selection the "Mode" member from + GPIO_InitTypeDef structure select the type (interrupt or event) and + the corresponding trigger event (rising or falling or both). + + (#) In case of external interrupt/event mode selection, configure NVIC IRQ priority + mapped to the EINT line using DAL_NVIC_SetPriority() and enable it using + DAL_NVIC_EnableIRQ(). + + (#) To get the level of a pin configured in input mode use DAL_GPIO_ReadPin(). + + (#) To set/reset the level of a pin configured in output mode use + DAL_GPIO_WritePin()/DAL_GPIO_TogglePin(). + + (#) To lock pin configuration until next reset use DAL_GPIO_LockPin(). + + + (#) During and just after reset, the alternate functions are not + active and the GPIO pins are configured in input floating mode (except JTAG + pins). + + (#) The LSE oscillator pins OSC32_IN and OSC32_OUT can be used as general purpose + (PC14 and PC15, respectively) when the LSE oscillator is off. The LSE has + priority over the GPIO function. + + (#) The HSE oscillator pins OSC_IN/OSC_OUT can be used as + general purpose PH0 and PH1, respectively, when the HSE oscillator is off. + The HSE has priority over the GPIO function. + + @endverbatim + * + */ + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @defgroup GPIO GPIO + * @brief GPIO DAL module driver + * @{ + */ + +#ifdef DAL_GPIO_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/** @addtogroup GPIO_Private_Constants GPIO Private Constants + * @{ + */ + +#define GPIO_NUMBER 16U +/** + * @} + */ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ +/* Exported functions --------------------------------------------------------*/ +/** @defgroup GPIO_Exported_Functions GPIO Exported Functions + * @{ + */ + +/** @defgroup GPIO_Exported_Functions_Group1 Initialization and de-initialization functions + * @brief Initialization and Configuration functions + * +@verbatim + =============================================================================== + ##### Initialization and de-initialization functions ##### + =============================================================================== + [..] + This section provides functions allowing to initialize and de-initialize the GPIOs + to be ready for use. + +@endverbatim + * @{ + */ + + +/** + * @brief Initializes the GPIOx peripheral according to the specified parameters in the GPIO_Init. + * @param GPIOx where x can be (A..I) to select the GPIO peripheral for APM32F40XX. + * @param GPIO_Init pointer to a GPIO_InitTypeDef structure that contains + * the configuration information for the specified GPIO peripheral. + * @retval None + */ +void DAL_GPIO_Init(GPIO_TypeDef *GPIOx, GPIO_InitTypeDef *GPIO_Init) +{ + uint32_t position; + uint32_t ioposition = 0x00U; + uint32_t iocurrent = 0x00U; + uint32_t temp = 0x00U; + + /* Check the parameters */ + ASSERT_PARAM(IS_GPIO_ALL_INSTANCE(GPIOx)); + ASSERT_PARAM(IS_GPIO_PIN(GPIO_Init->Pin)); + ASSERT_PARAM(IS_GPIO_MODE(GPIO_Init->Mode)); + + /* Configure the port pins */ + for(position = 0U; position < GPIO_NUMBER; position++) + { + /* Get the IO position */ + ioposition = 0x01U << position; + /* Get the current IO position */ + iocurrent = (uint32_t)(GPIO_Init->Pin) & ioposition; + + if(iocurrent == ioposition) + { + /*--------------------- GPIO Mode Configuration ------------------------*/ + /* In case of Output or Alternate function mode selection */ + if(((GPIO_Init->Mode & GPIO_MODE) == MODE_OUTPUT) || \ + (GPIO_Init->Mode & GPIO_MODE) == MODE_AF) + { + /* Check the Speed parameter */ + ASSERT_PARAM(IS_GPIO_SPEED(GPIO_Init->Speed)); + /* Configure the IO Speed */ + temp = GPIOx->OSSEL; + temp &= ~(GPIO_OSPEEDER_OSPEEDR0 << (position * 2U)); + temp |= (GPIO_Init->Speed << (position * 2U)); + GPIOx->OSSEL = temp; + + /* Configure the IO Output Type */ + temp = GPIOx->OMODE; + temp &= ~(GPIO_OMODE_OT_0 << position) ; + temp |= (((GPIO_Init->Mode & OUTPUT_TYPE) >> OUTPUT_TYPE_Pos) << position); + GPIOx->OMODE = temp; + } + + if((GPIO_Init->Mode & GPIO_MODE) != MODE_ANALOG) + { + /* Check the parameters */ + ASSERT_PARAM(IS_GPIO_PULL(GPIO_Init->Pull)); + + /* Activate the Pull-up or Pull down resistor for the current IO */ + temp = GPIOx->PUPD; + temp &= ~(GPIO_PUPD_PUPDR0 << (position * 2U)); + temp |= ((GPIO_Init->Pull) << (position * 2U)); + GPIOx->PUPD = temp; + } + + /* In case of Alternate function mode selection */ + if((GPIO_Init->Mode & GPIO_MODE) == MODE_AF) + { + /* Check the Alternate function parameter */ + ASSERT_PARAM(IS_GPIO_AF(GPIO_Init->Alternate)); + /* Configure Alternate function mapped with the current IO */ + temp = GPIOx->ALF[position >> 3U]; + temp &= ~(0xFU << ((uint32_t)(position & 0x07U) * 4U)) ; + temp |= ((uint32_t)(GPIO_Init->Alternate) << (((uint32_t)position & 0x07U) * 4U)); + GPIOx->ALF[position >> 3U] = temp; + } + + /* Configure IO Direction mode (Input, Output, Alternate or Analog) */ + temp = GPIOx->MODE; + temp &= ~(GPIO_MODE_MODE0 << (position * 2U)); + temp |= ((GPIO_Init->Mode & GPIO_MODE) << (position * 2U)); + GPIOx->MODE = temp; + + /*--------------------- EINT Mode Configuration ------------------------*/ + /* Configure the External Interrupt or event for the current IO */ + if((GPIO_Init->Mode & EINT_MODE) != 0x00U) + { + /* Enable SYSCFG Clock */ + __DAL_RCM_SYSCFG_CLK_ENABLE(); + + temp = SYSCFG->EINTCFG[position >> 2U]; + temp &= ~(0x0FU << (4U * (position & 0x03U))); + temp |= ((uint32_t)(GPIO_GET_INDEX(GPIOx)) << (4U * (position & 0x03U))); + SYSCFG->EINTCFG[position >> 2U] = temp; + + /* Clear Rising Falling edge configuration */ + temp = EINT->RTEN; + temp &= ~((uint32_t)iocurrent); + if((GPIO_Init->Mode & TRIGGER_RISING) != 0x00U) + { + temp |= iocurrent; + } + EINT->RTEN = temp; + + temp = EINT->FTEN; + temp &= ~((uint32_t)iocurrent); + if((GPIO_Init->Mode & TRIGGER_FALLING) != 0x00U) + { + temp |= iocurrent; + } + EINT->FTEN = temp; + + temp = EINT->EMASK; + temp &= ~((uint32_t)iocurrent); + if((GPIO_Init->Mode & EINT_EVT) != 0x00U) + { + temp |= iocurrent; + } + EINT->EMASK = temp; + + /* Clear EINT line configuration */ + temp = EINT->IMASK; + temp &= ~((uint32_t)iocurrent); + if((GPIO_Init->Mode & EINT_IT) != 0x00U) + { + temp |= iocurrent; + } + EINT->IMASK = temp; + } + } + } +} + +/** + * @brief De-initializes the GPIOx peripheral registers to their default reset values. + * @param GPIOx where x can be (A..I) to select the GPIO peripheral for APM32F40XX. + * @param GPIO_Pin specifies the port bit to be written. + * This parameter can be one of GPIO_PIN_x where x can be (0..15). + * @retval None + */ +void DAL_GPIO_DeInit(GPIO_TypeDef *GPIOx, uint32_t GPIO_Pin) +{ + uint32_t position; + uint32_t ioposition = 0x00U; + uint32_t iocurrent = 0x00U; + uint32_t tmp = 0x00U; + + /* Check the parameters */ + ASSERT_PARAM(IS_GPIO_ALL_INSTANCE(GPIOx)); + + /* Configure the port pins */ + for(position = 0U; position < GPIO_NUMBER; position++) + { + /* Get the IO position */ + ioposition = 0x01U << position; + /* Get the current IO position */ + iocurrent = (GPIO_Pin) & ioposition; + + if(iocurrent == ioposition) + { + /*------------------------- EINT Mode Configuration --------------------*/ + tmp = SYSCFG->EINTCFG[position >> 2U]; + tmp &= (0x0FU << (4U * (position & 0x03U))); + if(tmp == ((uint32_t)(GPIO_GET_INDEX(GPIOx)) << (4U * (position & 0x03U)))) + { + /* Clear EINT line configuration */ + EINT->IMASK &= ~((uint32_t)iocurrent); + EINT->EMASK &= ~((uint32_t)iocurrent); + + /* Clear Rising Falling edge configuration */ + EINT->FTEN &= ~((uint32_t)iocurrent); + EINT->RTEN &= ~((uint32_t)iocurrent); + + /* Configure the External Interrupt or event for the current IO */ + tmp = 0x0FU << (4U * (position & 0x03U)); + SYSCFG->EINTCFG[position >> 2U] &= ~tmp; + } + + /*------------------------- GPIO Mode Configuration --------------------*/ + /* Configure IO Direction in Input Floating Mode */ + GPIOx->MODE &= ~(GPIO_MODE_MODE0 << (position * 2U)); + + /* Configure the default Alternate Function in current IO */ + GPIOx->ALF[position >> 3U] &= ~(0xFU << ((uint32_t)(position & 0x07U) * 4U)) ; + + /* Deactivate the Pull-up and Pull-down resistor for the current IO */ + GPIOx->PUPD &= ~(GPIO_PUPD_PUPDR0 << (position * 2U)); + + /* Configure the default value IO Output Type */ + GPIOx->OMODE &= ~(GPIO_OMODE_OT_0 << position) ; + + /* Configure the default value for IO Speed */ + GPIOx->OSSEL &= ~(GPIO_OSPEEDER_OSPEEDR0 << (position * 2U)); + } + } +} + +/** + * @} + */ + +/** @defgroup GPIO_Exported_Functions_Group2 IO operation functions + * @brief GPIO Read and Write + * +@verbatim + =============================================================================== + ##### IO operation functions ##### + =============================================================================== + +@endverbatim + * @{ + */ + +/** + * @brief Reads the specified input port pin. + * @param GPIOx where x can be (A..I) to select the GPIO peripheral for APM32F40XX. + * @param GPIO_Pin specifies the port bit to read. + * This parameter can be GPIO_PIN_x where x can be (0..15). + * @retval The input port pin value. + */ +GPIO_PinState DAL_GPIO_ReadPin(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin) +{ + GPIO_PinState bitstatus; + + /* Check the parameters */ + ASSERT_PARAM(IS_GPIO_PIN(GPIO_Pin)); + + if((GPIOx->IDATA & GPIO_Pin) != (uint32_t)GPIO_PIN_RESET) + { + bitstatus = GPIO_PIN_SET; + } + else + { + bitstatus = GPIO_PIN_RESET; + } + return bitstatus; +} + +/** + * @brief Sets or clears the selected data port bit. + * + * @note This function uses GPIOx_BSRR register to allow atomic read/modify + * accesses. In this way, there is no risk of an IRQ occurring between + * the read and the modify access. + * + * @param GPIOx where x can be (A..I) to select the GPIO peripheral for APM32F40XX. + * @param GPIO_Pin specifies the port bit to be written. + * This parameter can be one of GPIO_PIN_x where x can be (0..15). + * @param PinState specifies the value to be written to the selected bit. + * This parameter can be one of the GPIO_PinState enum values: + * @arg GPIO_PIN_RESET: to clear the port pin + * @arg GPIO_PIN_SET: to set the port pin + * @retval None + */ +void DAL_GPIO_WritePin(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin, GPIO_PinState PinState) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_GPIO_PIN(GPIO_Pin)); + ASSERT_PARAM(IS_GPIO_PIN_ACTION(PinState)); + + if(PinState != GPIO_PIN_RESET) + { + GPIOx->BSC = GPIO_Pin; + } + else + { + GPIOx->BSC = (uint32_t)GPIO_Pin << 16U; + } +} + +/** + * @brief Toggles the specified GPIO pins. + * @param GPIOx Where x can be (A..I) to select the GPIO peripheral for APM32F40XX. + * @param GPIO_Pin Specifies the pins to be toggled. + * @retval None + */ +void DAL_GPIO_TogglePin(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin) +{ + uint32_t odr; + + /* Check the parameters */ + ASSERT_PARAM(IS_GPIO_PIN(GPIO_Pin)); + + /* get current Output Data Register value */ + odr = GPIOx->ODATA; + + /* Set selected pins that were at low level, and reset ones that were high */ + GPIOx->BSC = ((odr & GPIO_Pin) << GPIO_NUMBER) | (~odr & GPIO_Pin); +} + +/** + * @brief Locks GPIO Pins configuration registers. + * @note The locked registers are GPIOx_MODE, GPIOx_OMODE, GPIOx_OSSEL, + * GPIOx_PUPD, GPIOx_ALFL and GPIOx_ALFH. + * @note The configuration of the locked GPIO pins can no longer be modified + * until the next reset. + * @param GPIOx where x can be (A..F) to select the GPIO peripheral for APM32F4 family + * @param GPIO_Pin specifies the port bit to be locked. + * This parameter can be any combination of GPIO_PIN_x where x can be (0..15). + * @retval None + */ +DAL_StatusTypeDef DAL_GPIO_LockPin(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin) +{ + __IO uint32_t tmp = GPIO_LOCK_LOCKKEY; + + /* Check the parameters */ + ASSERT_PARAM(IS_GPIO_PIN(GPIO_Pin)); + + /* Apply lock key write sequence */ + tmp |= GPIO_Pin; + /* Set LCKx bit(s): LCKK='1' + LCK[15-0] */ + GPIOx->LOCK = tmp; + /* Reset LCKx bit(s): LCKK='0' + LCK[15-0] */ + GPIOx->LOCK = GPIO_Pin; + /* Set LCKx bit(s): LCKK='1' + LCK[15-0] */ + GPIOx->LOCK = tmp; + /* Read LCKR register. This read is mandatory to complete key lock sequence */ + tmp = GPIOx->LOCK; + + /* Read again in order to confirm lock is active */ + if((GPIOx->LOCK & GPIO_LOCK_LOCKKEY) != RESET) + { + return DAL_OK; + } + else + { + return DAL_ERROR; + } +} + +/** + * @brief This function handles EINT interrupt request. + * @param GPIO_Pin Specifies the pins connected EINT line + * @retval None + */ +void DAL_GPIO_EINT_IRQHandler(uint16_t GPIO_Pin) +{ + /* EINT line interrupt detected */ + if(__DAL_GPIO_EINT_GET_IT(GPIO_Pin) != RESET) + { + __DAL_GPIO_EINT_CLEAR_IT(GPIO_Pin); + DAL_GPIO_EINT_Callback(GPIO_Pin); + } +} + +/** + * @brief EINT line detection callbacks. + * @param GPIO_Pin Specifies the pins connected EINT line + * @retval None + */ +__weak void DAL_GPIO_EINT_Callback(uint16_t GPIO_Pin) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(GPIO_Pin); + /* NOTE: This function Should not be modified, when the callback is needed, + the DAL_GPIO_EINT_Callback could be implemented in the user file + */ +} + +/** + * @} + */ + + +/** + * @} + */ + +#endif /* DAL_GPIO_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_hash.c b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_hash.c new file mode 100644 index 0000000000..b09028428f --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_hash.c @@ -0,0 +1,3539 @@ +/** + * + * @file apm32f4xx_dal_hash.c + * @brief HASH DAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the HASH peripheral: + * + Initialization and de-initialization methods + * + HASH or HMAC processing in polling mode + * + HASH or HMAC processing in interrupt mode + * + HASH or HMAC processing in DMA mode + * + Peripheral State methods + * + HASH or HMAC processing suspension/resumption + * + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + * + @verbatim + =============================================================================== + ##### How to use this driver ##### + =============================================================================== + [..] + The HASH DAL driver can be used as follows: + + (#)Initialize the HASH low level resources by implementing the DAL_HASH_MspInit(): + (##) Enable the HASH interface clock using __HASH_CLK_ENABLE() + (##) When resorting to interrupt-based APIs (e.g. DAL_HASH_xxx_Start_IT()) + (+++) Configure the HASH interrupt priority using DAL_NVIC_SetPriority() + (+++) Enable the HASH IRQ handler using DAL_NVIC_EnableIRQ() + (+++) In HASH IRQ handler, call DAL_HASH_IRQHandler() API + (##) When resorting to DMA-based APIs (e.g. DAL_HASH_xxx_Start_DMA()) + (+++) Enable the DMAx interface clock using + __DMAx_CLK_ENABLE() + (+++) Configure and enable one DMA stream to manage data transfer from + memory to peripheral (input stream). Managing data transfer from + peripheral to memory can be performed only using CPU. + (+++) Associate the initialized DMA handle to the HASH DMA handle + using __DAL_LINKDMA() + (+++) Configure the priority and enable the NVIC for the transfer complete + interrupt on the DMA stream: use + DAL_NVIC_SetPriority() and + DAL_NVIC_EnableIRQ() + + (#)Initialize the HASH DAL using DAL_HASH_Init(). This function: + (##) resorts to DAL_HASH_MspInit() for low-level initialization, + (##) configures the data type: 1-bit, 8-bit, 16-bit or 32-bit. + + (#)Three processing schemes are available: + (##) Polling mode: processing APIs are blocking functions + i.e. they process the data and wait till the digest computation is finished, + e.g. DAL_HASH_xxx_Start() for HASH or DAL_HMAC_xxx_Start() for HMAC + (##) Interrupt mode: processing APIs are not blocking functions + i.e. they process the data under interrupt, + e.g. DAL_HASH_xxx_Start_IT() for HASH or DAL_HMAC_xxx_Start_IT() for HMAC + (##) DMA mode: processing APIs are not blocking functions and the CPU is + not used for data transfer i.e. the data transfer is ensured by DMA, + e.g. DAL_HASH_xxx_Start_DMA() for HASH or DAL_HMAC_xxx_Start_DMA() + for HMAC. Note that in DMA mode, a call to DAL_HASH_xxx_Finish() + is then required to retrieve the digest. + + (#)When the processing function is called after DAL_HASH_Init(), the HASH peripheral is + initialized and processes the buffer fed in input. When the input data have all been + fed to the Peripheral, the digest computation can start. + + (#)Multi-buffer processing is possible in polling, interrupt and DMA modes. + (##) In polling mode, only multi-buffer HASH processing is possible. + API DAL_HASH_xxx_Accumulate() must be called for each input buffer, except for the last one. + User must resort to DAL_HASH_xxx_Accumulate_End() to enter the last one and retrieve as + well the computed digest. + + (##) In interrupt mode, API DAL_HASH_xxx_Accumulate_IT() must be called for each input buffer, + except for the last one. + User must resort to DAL_HASH_xxx_Accumulate_End_IT() to enter the last one and retrieve as + well the computed digest. + + (##) In DMA mode, multi-buffer HASH and HMAC processing are possible. + (+++) HASH processing: once initialization is done, MDMAT bit must be set + through __DAL_HASH_SET_MDMAT() macro. + From that point, each buffer can be fed to the Peripheral through DAL_HASH_xxx_Start_DMA() API. + Before entering the last buffer, reset the MDMAT bit with __DAL_HASH_RESET_MDMAT() + macro then wrap-up the HASH processing in feeding the last input buffer through the + same API DAL_HASH_xxx_Start_DMA(). The digest can then be retrieved with a call to + API DAL_HASH_xxx_Finish(). + (+++) HMAC processing (requires to resort to extended functions): + after initialization, the key and the first input buffer are entered + in the Peripheral with the API DAL_HMACEx_xxx_Step1_2_DMA(). This carries out HMAC step 1 and + starts step 2. + The following buffers are next entered with the API DAL_HMACEx_xxx_Step2_DMA(). At this + point, the HMAC processing is still carrying out step 2. + Then, step 2 for the last input buffer and step 3 are carried out by a single call + to DAL_HMACEx_xxx_Step2_3_DMA(). + + The digest can finally be retrieved with a call to API DAL_HASH_xxx_Finish(). + + + (#)Context swapping. + (##) Two APIs are available to suspend HASH or HMAC processing: + (+++) DAL_HASH_SwFeed_ProcessSuspend() when data are entered by software (polling or IT mode), + (+++) DAL_HASH_DMAFeed_ProcessSuspend() when data are entered by DMA. + + (##) When HASH or HMAC processing is suspended, DAL_HASH_ContextSaving() allows + to save in memory the Peripheral context. This context can be restored afterwards + to resume the HASH processing thanks to DAL_HASH_ContextRestoring(). + + (##) Once the HASH Peripheral has been restored to the same configuration as that at suspension + time, processing can be restarted with the same API call (same API, same handle, + same parameters) as done before the suspension. Relevant parameters to restart at + the proper location are internally saved in the HASH handle. + + (#)Call DAL_HASH_DeInit() to deinitialize the HASH peripheral. + + *** Remarks on message length *** + =================================== + [..] + (#) DAL in interruption mode (interruptions driven) + + (##)Due to HASH peripheral hardware design, the peripheral interruption is triggered every 64 bytes. + This is why, for driver implementation simplicity’s sake, user is requested to enter a message the + length of which is a multiple of 4 bytes. + + (##) When the message length (in bytes) is not a multiple of words, a specific field exists in HASH_START + to specify which bits to discard at the end of the complete message to process only the message bits + and not extra bits. + + (##) If user needs to perform a hash computation of a large input buffer that is spread around various places + in memory and where each piece of this input buffer is not necessarily a multiple of 4 bytes in size, it becomes + necessary to use a temporary buffer to format the data accordingly before feeding them to the Peripheral. + It is advised to the user to + (+++) achieve the first formatting operation by software then enter the data + (+++) while the Peripheral is processing the first input set, carry out the second formatting + operation by software, to be ready when DINIS occurs. + (+++) repeat step 2 until the whole message is processed. + + [..] + (#) DAL in DMA mode + + (##) Again, due to hardware design, the DMA transfer to feed the data can only be done on a word-basis. + The same field described above in HASH_START is used to specify which bits to discard at the end of the + DMA transfer to process only the message bits and not extra bits. Due to hardware implementation, + this is possible only at the end of the complete message. When several DMA transfers are needed to + enter the message, this is not applicable at the end of the intermediary transfers. + + (##) Similarly to the interruption-driven mode, it is suggested to the user to format the consecutive + chunks of data by software while the DMA transfer and processing is on-going for the first parts of + the message. Due to the 32-bit alignment required for the DMA transfer, it is underlined that the + software formatting operation is more complex than in the IT mode. + + *** Callback registration *** + =================================== + [..] + (#) The compilation define USE_DAL_HASH_REGISTER_CALLBACKS when set to 1 + allows the user to configure dynamically the driver callbacks. + Use function DAL_HASH_RegisterCallback() to register a user callback. + + (#) Function DAL_HASH_RegisterCallback() allows to register following callbacks: + (+) InCpltCallback : callback for input completion. + (+) DgstCpltCallback : callback for digest computation completion. + (+) ErrorCallback : callback for error. + (+) MspInitCallback : HASH MspInit. + (+) MspDeInitCallback : HASH MspDeInit. + This function takes as parameters the DAL peripheral handle, the Callback ID + and a pointer to the user callback function. + + (#) Use function DAL_HASH_UnRegisterCallback() to reset a callback to the default + weak (surcharged) function. + DAL_HASH_UnRegisterCallback() takes as parameters the DAL peripheral handle, + and the Callback ID. + This function allows to reset following callbacks: + (+) InCpltCallback : callback for input completion. + (+) DgstCpltCallback : callback for digest computation completion. + (+) ErrorCallback : callback for error. + (+) MspInitCallback : HASH MspInit. + (+) MspDeInitCallback : HASH MspDeInit. + + (#) By default, after the DAL_HASH_Init and if the state is DAL_HASH_STATE_RESET + all callbacks are reset to the corresponding legacy weak (surcharged) functions: + examples DAL_HASH_InCpltCallback(), DAL_HASH_DgstCpltCallback() + Exception done for MspInit and MspDeInit callbacks that are respectively + reset to the legacy weak (surcharged) functions in the DAL_HASH_Init + and DAL_HASH_DeInit only when these callbacks are null (not registered beforehand) + If not, MspInit or MspDeInit are not null, the DAL_HASH_Init and DAL_HASH_DeInit + keep and use the user MspInit/MspDeInit callbacks (registered beforehand). + + Callbacks can be registered/unregistered in READY state only. + Exception done for MspInit/MspDeInit callbacks that can be registered/unregistered + in READY or RESET state, thus registered (user) MspInit/DeInit callbacks can be used + during the Init/DeInit. + In that case first register the MspInit/MspDeInit user callbacks + using DAL_HASH_RegisterCallback before calling DAL_HASH_DeInit + or DAL_HASH_Init function. + + When The compilation define USE_DAL_HASH_REGISTER_CALLBACKS is set to 0 or + not defined, the callback registering feature is not available + and weak (surcharged) callbacks are used. + + @endverbatim + * + */ + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal.h" + + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ +#if defined (HASH) + +/** @defgroup HASH HASH + * @brief HASH DAL module driver. + * @{ + */ + +#ifdef DAL_HASH_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/** @defgroup HASH_Private_Constants HASH Private Constants + * @{ + */ + +/** @defgroup HASH_Digest_Calculation_Status HASH Digest Calculation Status + * @{ + */ +#define HASH_DIGEST_CALCULATION_NOT_STARTED ((uint32_t)0x00000000U) /*!< DCAL not set after input data written in DIN register */ +#define HASH_DIGEST_CALCULATION_STARTED ((uint32_t)0x00000001U) /*!< DCAL set after input data written in DIN register */ +/** + * @} + */ + +/** @defgroup HASH_Number_Of_CTSWAP_Registers HASH Number of Context Swap Registers + * @{ + */ +#define HASH_NUMBER_OF_CTSWAP_REGISTERS 54U /*!< Number of Context Swap Registers */ +/** + * @} + */ + +/** @defgroup HASH_TimeOut_Value HASH TimeOut Value + * @{ + */ +#define HASH_TIMEOUTVALUE 1000U /*!< Time-out value */ +/** + * @} + */ + +/** @defgroup HASH_DMA_Suspension_Words_Limit HASH DMA suspension words limit + * @{ + */ +#define HASH_DMA_SUSPENSION_WORDS_LIMIT 20U /*!< Number of words below which DMA suspension is aborted */ +/** + * @} + */ + +/** + * @} + */ + +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/** @defgroup HASH_Private_Functions HASH Private Functions + * @{ + */ +static void HASH_DMAXferCplt(DMA_HandleTypeDef *hdma); +static void HASH_DMAError(DMA_HandleTypeDef *hdma); +static void HASH_GetDigest(uint8_t *pMsgDigest, uint8_t Size); +static DAL_StatusTypeDef HASH_WaitOnFlagUntilTimeout(HASH_HandleTypeDef *hhash, uint32_t Flag, FlagStatus Status, + uint32_t Timeout); +static DAL_StatusTypeDef HASH_WriteData(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size); +static DAL_StatusTypeDef HASH_IT(HASH_HandleTypeDef *hhash); +static uint32_t HASH_Write_Block_Data(HASH_HandleTypeDef *hhash); +static DAL_StatusTypeDef HMAC_Processing(HASH_HandleTypeDef *hhash, uint32_t Timeout); +/** + * @} + */ + +/** @defgroup HASH_Exported_Functions HASH Exported Functions + * @{ + */ + +/** @defgroup HASH_Exported_Functions_Group1 Initialization and de-initialization functions + * @brief Initialization, configuration and call-back functions. + * +@verbatim + =============================================================================== + ##### Initialization and de-initialization functions ##### + =============================================================================== + [..] This section provides functions allowing to: + (+) Initialize the HASH according to the specified parameters + in the HASH_InitTypeDef and create the associated handle + (+) DeInitialize the HASH peripheral + (+) Initialize the HASH MCU Specific Package (MSP) + (+) DeInitialize the HASH MSP + + [..] This section provides as well call back functions definitions for user + code to manage: + (+) Input data transfer to Peripheral completion + (+) Calculated digest retrieval completion + (+) Error management + + + +@endverbatim + * @{ + */ + +/** + * @brief Initialize the HASH according to the specified parameters in the + HASH_HandleTypeDef and create the associated handle. + * @note Only MDMAT and DATATYPE bits of HASH Peripheral are set by DAL_HASH_Init(), + * other configuration bits are set by HASH or HMAC processing APIs. + * @note MDMAT bit is systematically reset by DAL_HASH_Init(). To set it for + * multi-buffer HASH processing, user needs to resort to + * __DAL_HASH_SET_MDMAT() macro. For HMAC multi-buffer processing, the + * relevant APIs manage themselves the MDMAT bit. + * @param hhash HASH handle + * @retval DAL status + */ +DAL_StatusTypeDef DAL_HASH_Init(HASH_HandleTypeDef *hhash) +{ + /* Check the hash handle allocation */ + if (hhash == NULL) + { + return DAL_ERROR; + } + + /* Check the parameters */ + ASSERT_PARAM(IS_HASH_DATATYPE(hhash->Init.DataType)); + +#if (USE_DAL_HASH_REGISTER_CALLBACKS == 1) + if (hhash->State == DAL_HASH_STATE_RESET) + { + /* Allocate lock resource and initialize it */ + hhash->Lock = DAL_UNLOCKED; + + /* Reset Callback pointers in DAL_HASH_STATE_RESET only */ + hhash->InCpltCallback = DAL_HASH_InCpltCallback; /* Legacy weak (surcharged) input completion callback */ + hhash->DgstCpltCallback = DAL_HASH_DgstCpltCallback; /* Legacy weak (surcharged) digest computation + completion callback */ + hhash->ErrorCallback = DAL_HASH_ErrorCallback; /* Legacy weak (surcharged) error callback */ + if (hhash->MspInitCallback == NULL) + { + hhash->MspInitCallback = DAL_HASH_MspInit; + } + + /* Init the low level hardware */ + hhash->MspInitCallback(hhash); + } +#else + if (hhash->State == DAL_HASH_STATE_RESET) + { + /* Allocate lock resource and initialize it */ + hhash->Lock = DAL_UNLOCKED; + + /* Init the low level hardware */ + DAL_HASH_MspInit(hhash); + } +#endif /* (USE_DAL_HASH_REGISTER_CALLBACKS) */ + + /* Change the HASH state */ + hhash->State = DAL_HASH_STATE_BUSY; + + /* Reset HashInCount, HashITCounter, HashBuffSize and NbWordsAlreadyPushed */ + hhash->HashInCount = 0; + hhash->HashBuffSize = 0; + hhash->HashITCounter = 0; + hhash->NbWordsAlreadyPushed = 0; + /* Reset digest calculation bridle (MDMAT bit control) */ + hhash->DigestCalculationDisable = RESET; + /* Set phase to READY */ + hhash->Phase = DAL_HASH_PHASE_READY; + /* Reset suspension request flag */ + hhash->SuspendRequest = DAL_HASH_SUSPEND_NONE; + + /* Set the data type bit */ + MODIFY_REG(HASH->CTRL, HASH_CTRL_DTYPE, hhash->Init.DataType); +#if defined(HASH_CTRL_MDMAT) + /* Reset MDMAT bit */ + __DAL_HASH_RESET_MDMAT(); +#endif /* HASH_CTRL_MDMAT */ + /* Reset HASH handle status */ + hhash->Status = DAL_OK; + + /* Set the HASH state to Ready */ + hhash->State = DAL_HASH_STATE_READY; + + /* Initialise the error code */ + hhash->ErrorCode = DAL_HASH_ERROR_NONE; + + /* Return function status */ + return DAL_OK; +} + +/** + * @brief DeInitialize the HASH peripheral. + * @param hhash HASH handle. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_HASH_DeInit(HASH_HandleTypeDef *hhash) +{ + /* Check the HASH handle allocation */ + if (hhash == NULL) + { + return DAL_ERROR; + } + + /* Change the HASH state */ + hhash->State = DAL_HASH_STATE_BUSY; + + /* Set the default HASH phase */ + hhash->Phase = DAL_HASH_PHASE_READY; + + /* Reset HashInCount, HashITCounter and HashBuffSize */ + hhash->HashInCount = 0; + hhash->HashBuffSize = 0; + hhash->HashITCounter = 0; + /* Reset digest calculation bridle (MDMAT bit control) */ + hhash->DigestCalculationDisable = RESET; + +#if (USE_DAL_HASH_REGISTER_CALLBACKS == 1) + if (hhash->MspDeInitCallback == NULL) + { + hhash->MspDeInitCallback = DAL_HASH_MspDeInit; + } + + /* DeInit the low level hardware */ + hhash->MspDeInitCallback(hhash); +#else + /* DeInit the low level hardware: CLOCK, NVIC */ + DAL_HASH_MspDeInit(hhash); +#endif /* (USE_DAL_HASH_REGISTER_CALLBACKS) */ + + + /* Reset HASH handle status */ + hhash->Status = DAL_OK; + + /* Set the HASH state to Ready */ + hhash->State = DAL_HASH_STATE_RESET; + + /* Initialise the error code */ + hhash->ErrorCode = DAL_HASH_ERROR_NONE; + + /* Reset multi buffers accumulation flag */ + hhash->Accumulation = 0U; + + /* Return function status */ + return DAL_OK; +} + +/** + * @brief Initialize the HASH MSP. + * @param hhash HASH handle. + * @retval None + */ +__weak void DAL_HASH_MspInit(HASH_HandleTypeDef *hhash) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hhash); + + /* NOTE : This function should not be modified; when the callback is needed, + DAL_HASH_MspInit() can be implemented in the user file. + */ +} + +/** + * @brief DeInitialize the HASH MSP. + * @param hhash HASH handle. + * @retval None + */ +__weak void DAL_HASH_MspDeInit(HASH_HandleTypeDef *hhash) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hhash); + + /* NOTE : This function should not be modified; when the callback is needed, + DAL_HASH_MspDeInit() can be implemented in the user file. + */ +} + +/** + * @brief Input data transfer complete call back. + * @note DAL_HASH_InCpltCallback() is called when the complete input message + * has been fed to the Peripheral. This API is invoked only when input data are + * entered under interruption or through DMA. + * @note In case of HASH or HMAC multi-buffer DMA feeding case (MDMAT bit set), + * DAL_HASH_InCpltCallback() is called at the end of each buffer feeding + * to the Peripheral. + * @param hhash HASH handle. + * @retval None + */ +__weak void DAL_HASH_InCpltCallback(HASH_HandleTypeDef *hhash) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hhash); + + /* NOTE : This function should not be modified; when the callback is needed, + DAL_HASH_InCpltCallback() can be implemented in the user file. + */ +} + +/** + * @brief Digest computation complete call back. + * @note DAL_HASH_DgstCpltCallback() is used under interruption, is not + * relevant with DMA. + * @param hhash HASH handle. + * @retval None + */ +__weak void DAL_HASH_DgstCpltCallback(HASH_HandleTypeDef *hhash) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hhash); + + /* NOTE : This function should not be modified; when the callback is needed, + DAL_HASH_DgstCpltCallback() can be implemented in the user file. + */ +} + +/** + * @brief Error callback. + * @note Code user can resort to hhash->Status (DAL_ERROR, DAL_TIMEOUT,...) + * to retrieve the error type. + * @param hhash HASH handle. + * @retval None + */ +__weak void DAL_HASH_ErrorCallback(HASH_HandleTypeDef *hhash) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hhash); + + /* NOTE : This function should not be modified; when the callback is needed, + DAL_HASH_ErrorCallback() can be implemented in the user file. + */ +} + +#if (USE_DAL_HASH_REGISTER_CALLBACKS == 1) +/** + * @brief Register a User HASH Callback + * To be used instead of the weak (surcharged) predefined callback + * @param hhash HASH handle + * @param CallbackID ID of the callback to be registered + * This parameter can be one of the following values: + * @arg @ref DAL_HASH_INPUTCPLT_CB_ID HASH input completion Callback ID + * @arg @ref DAL_HASH_DGSTCPLT_CB_ID HASH digest computation completion Callback ID + * @arg @ref DAL_HASH_ERROR_CB_ID HASH error Callback ID + * @arg @ref DAL_HASH_MSPINIT_CB_ID HASH MspInit callback ID + * @arg @ref DAL_HASH_MSPDEINIT_CB_ID HASH MspDeInit callback ID + * @param pCallback pointer to the Callback function + * @retval status + */ +DAL_StatusTypeDef DAL_HASH_RegisterCallback(HASH_HandleTypeDef *hhash, DAL_HASH_CallbackIDTypeDef CallbackID, + pHASH_CallbackTypeDef pCallback) +{ + DAL_StatusTypeDef status = DAL_OK; + + if (pCallback == NULL) + { + /* Update the error code */ + hhash->ErrorCode |= DAL_HASH_ERROR_INVALID_CALLBACK; + return DAL_ERROR; + } + /* Process locked */ + __DAL_LOCK(hhash); + + if (DAL_HASH_STATE_READY == hhash->State) + { + switch (CallbackID) + { + case DAL_HASH_INPUTCPLT_CB_ID : + hhash->InCpltCallback = pCallback; + break; + + case DAL_HASH_DGSTCPLT_CB_ID : + hhash->DgstCpltCallback = pCallback; + break; + + case DAL_HASH_ERROR_CB_ID : + hhash->ErrorCallback = pCallback; + break; + + case DAL_HASH_MSPINIT_CB_ID : + hhash->MspInitCallback = pCallback; + break; + + case DAL_HASH_MSPDEINIT_CB_ID : + hhash->MspDeInitCallback = pCallback; + break; + + default : + /* Update the error code */ + hhash->ErrorCode |= DAL_HASH_ERROR_INVALID_CALLBACK; + /* update return status */ + status = DAL_ERROR; + break; + } + } + else if (DAL_HASH_STATE_RESET == hhash->State) + { + switch (CallbackID) + { + case DAL_HASH_MSPINIT_CB_ID : + hhash->MspInitCallback = pCallback; + break; + + case DAL_HASH_MSPDEINIT_CB_ID : + hhash->MspDeInitCallback = pCallback; + break; + + default : + /* Update the error code */ + hhash->ErrorCode |= DAL_HASH_ERROR_INVALID_CALLBACK; + /* update return status */ + status = DAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + hhash->ErrorCode |= DAL_HASH_ERROR_INVALID_CALLBACK; + /* update return status */ + status = DAL_ERROR; + } + + /* Release Lock */ + __DAL_UNLOCK(hhash); + return status; +} + +/** + * @brief Unregister a HASH Callback + * HASH Callback is redirected to the weak (surcharged) predefined callback + * @param hhash HASH handle + * @param CallbackID ID of the callback to be unregistered + * This parameter can be one of the following values: + * @arg @ref DAL_HASH_INPUTCPLT_CB_ID HASH input completion Callback ID + * @arg @ref DAL_HASH_DGSTCPLT_CB_ID HASH digest computation completion Callback ID + * @arg @ref DAL_HASH_ERROR_CB_ID HASH error Callback ID + * @arg @ref DAL_HASH_MSPINIT_CB_ID HASH MspInit callback ID + * @arg @ref DAL_HASH_MSPDEINIT_CB_ID HASH MspDeInit callback ID + * @retval status + */ +DAL_StatusTypeDef DAL_HASH_UnRegisterCallback(HASH_HandleTypeDef *hhash, DAL_HASH_CallbackIDTypeDef CallbackID) +{ + DAL_StatusTypeDef status = DAL_OK; + + /* Process locked */ + __DAL_LOCK(hhash); + + if (DAL_HASH_STATE_READY == hhash->State) + { + switch (CallbackID) + { + case DAL_HASH_INPUTCPLT_CB_ID : + hhash->InCpltCallback = DAL_HASH_InCpltCallback; /* Legacy weak (surcharged) input completion callback */ + break; + + case DAL_HASH_DGSTCPLT_CB_ID : + hhash->DgstCpltCallback = DAL_HASH_DgstCpltCallback; /* Legacy weak (surcharged) digest computation + completion callback */ + break; + + case DAL_HASH_ERROR_CB_ID : + hhash->ErrorCallback = DAL_HASH_ErrorCallback; /* Legacy weak (surcharged) error callback */ + break; + + case DAL_HASH_MSPINIT_CB_ID : + hhash->MspInitCallback = DAL_HASH_MspInit; /* Legacy weak (surcharged) Msp Init */ + break; + + case DAL_HASH_MSPDEINIT_CB_ID : + hhash->MspDeInitCallback = DAL_HASH_MspDeInit; /* Legacy weak (surcharged) Msp DeInit */ + break; + + default : + /* Update the error code */ + hhash->ErrorCode |= DAL_HASH_ERROR_INVALID_CALLBACK; + /* update return status */ + status = DAL_ERROR; + break; + } + } + else if (DAL_HASH_STATE_RESET == hhash->State) + { + switch (CallbackID) + { + case DAL_HASH_MSPINIT_CB_ID : + hhash->MspInitCallback = DAL_HASH_MspInit; /* Legacy weak (surcharged) Msp Init */ + break; + + case DAL_HASH_MSPDEINIT_CB_ID : + hhash->MspDeInitCallback = DAL_HASH_MspDeInit; /* Legacy weak (surcharged) Msp DeInit */ + break; + + default : + /* Update the error code */ + hhash->ErrorCode |= DAL_HASH_ERROR_INVALID_CALLBACK; + /* update return status */ + status = DAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + hhash->ErrorCode |= DAL_HASH_ERROR_INVALID_CALLBACK; + /* update return status */ + status = DAL_ERROR; + } + + /* Release Lock */ + __DAL_UNLOCK(hhash); + return status; +} +#endif /* USE_DAL_HASH_REGISTER_CALLBACKS */ + +/** + * @} + */ + +/** @defgroup HASH_Exported_Functions_Group2 HASH processing functions in polling mode + * @brief HASH processing functions using polling mode. + * +@verbatim + =============================================================================== + ##### Polling mode HASH processing functions ##### + =============================================================================== + [..] This section provides functions allowing to calculate in polling mode + the hash value using one of the following algorithms: + (+) MD5 + (++) DAL_HASH_MD5_Start() + (++) DAL_HASH_MD5_Accmlt() + (++) DAL_HASH_MD5_Accmlt_End() + (+) SHA1 + (++) DAL_HASH_SHA1_Start() + (++) DAL_HASH_SHA1_Accmlt() + (++) DAL_HASH_SHA1_Accmlt_End() + + [..] For a single buffer to be hashed, user can resort to DAL_HASH_xxx_Start(). + + [..] In case of multi-buffer HASH processing (a single digest is computed while + several buffers are fed to the Peripheral), the user can resort to successive calls + to DAL_HASH_xxx_Accumulate() and wrap-up the digest computation by a call + to DAL_HASH_xxx_Accumulate_End(). + +@endverbatim + * @{ + */ + +/** + * @brief Initialize the HASH peripheral in MD5 mode, next process pInBuffer then + * read the computed digest. + * @note Digest is available in pOutBuffer. + * @param hhash HASH handle. + * @param pInBuffer pointer to the input buffer (buffer to be hashed). + * @param Size length of the input buffer in bytes. + * @param pOutBuffer pointer to the computed digest. Digest size is 16 bytes. + * @param Timeout Timeout value + * @retval DAL status + */ +DAL_StatusTypeDef DAL_HASH_MD5_Start(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, uint8_t *pOutBuffer, + uint32_t Timeout) +{ + return HASH_Start(hhash, pInBuffer, Size, pOutBuffer, Timeout, HASH_ALGOSELECTION_MD5); +} + +/** + * @brief If not already done, initialize the HASH peripheral in MD5 mode then + * processes pInBuffer. + * @note Consecutive calls to DAL_HASH_MD5_Accmlt() can be used to feed + * several input buffers back-to-back to the Peripheral that will yield a single + * HASH signature once all buffers have been entered. Wrap-up of input + * buffers feeding and retrieval of digest is done by a call to + * DAL_HASH_MD5_Accmlt_End(). + * @note Field hhash->Phase of HASH handle is tested to check whether or not + * the Peripheral has already been initialized. + * @note Digest is not retrieved by this API, user must resort to DAL_HASH_MD5_Accmlt_End() + * to read it, feeding at the same time the last input buffer to the Peripheral. + * @note The input buffer size (in bytes) must be a multiple of 4 otherwise, the + * HASH digest computation is corrupted. Only DAL_HASH_MD5_Accmlt_End() is able + * to manage the ending buffer with a length in bytes not a multiple of 4. + * @param hhash HASH handle. + * @param pInBuffer pointer to the input buffer (buffer to be hashed). + * @param Size length of the input buffer in bytes, must be a multiple of 4. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_HASH_MD5_Accmlt(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size) +{ + return HASH_Accumulate(hhash, pInBuffer, Size, HASH_ALGOSELECTION_MD5); +} + +/** + * @brief End computation of a single HASH signature after several calls to DAL_HASH_MD5_Accmlt() API. + * @note Digest is available in pOutBuffer. + * @param hhash HASH handle. + * @param pInBuffer pointer to the input buffer (buffer to be hashed). + * @param Size length of the input buffer in bytes. + * @param pOutBuffer pointer to the computed digest. Digest size is 16 bytes. + * @param Timeout Timeout value + * @retval DAL status + */ +DAL_StatusTypeDef DAL_HASH_MD5_Accmlt_End(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, + uint8_t *pOutBuffer, uint32_t Timeout) +{ + return HASH_Start(hhash, pInBuffer, Size, pOutBuffer, Timeout, HASH_ALGOSELECTION_MD5); +} + +/** + * @brief Initialize the HASH peripheral in SHA1 mode, next process pInBuffer then + * read the computed digest. + * @note Digest is available in pOutBuffer. + * @param hhash HASH handle. + * @param pInBuffer pointer to the input buffer (buffer to be hashed). + * @param Size length of the input buffer in bytes. + * @param pOutBuffer pointer to the computed digest. Digest size is 20 bytes. + * @param Timeout Timeout value + * @retval DAL status + */ +DAL_StatusTypeDef DAL_HASH_SHA1_Start(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, uint8_t *pOutBuffer, + uint32_t Timeout) +{ + return HASH_Start(hhash, pInBuffer, Size, pOutBuffer, Timeout, HASH_ALGOSELECTION_SHA1); +} + +/** + * @brief If not already done, initialize the HASH peripheral in SHA1 mode then + * processes pInBuffer. + * @note Consecutive calls to DAL_HASH_SHA1_Accmlt() can be used to feed + * several input buffers back-to-back to the Peripheral that will yield a single + * HASH signature once all buffers have been entered. Wrap-up of input + * buffers feeding and retrieval of digest is done by a call to + * DAL_HASH_SHA1_Accmlt_End(). + * @note Field hhash->Phase of HASH handle is tested to check whether or not + * the Peripheral has already been initialized. + * @note Digest is not retrieved by this API, user must resort to DAL_HASH_SHA1_Accmlt_End() + * to read it, feeding at the same time the last input buffer to the Peripheral. + * @note The input buffer size (in bytes) must be a multiple of 4 otherwise, the + * HASH digest computation is corrupted. Only DAL_HASH_SHA1_Accmlt_End() is able + * to manage the ending buffer with a length in bytes not a multiple of 4. + * @param hhash HASH handle. + * @param pInBuffer pointer to the input buffer (buffer to be hashed). + * @param Size length of the input buffer in bytes, must be a multiple of 4. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_HASH_SHA1_Accmlt(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size) +{ + return HASH_Accumulate(hhash, pInBuffer, Size, HASH_ALGOSELECTION_SHA1); +} + +/** + * @brief End computation of a single HASH signature after several calls to DAL_HASH_SHA1_Accmlt() API. + * @note Digest is available in pOutBuffer. + * @param hhash HASH handle. + * @param pInBuffer pointer to the input buffer (buffer to be hashed). + * @param Size length of the input buffer in bytes. + * @param pOutBuffer pointer to the computed digest. Digest size is 20 bytes. + * @param Timeout Timeout value + * @retval DAL status + */ +DAL_StatusTypeDef DAL_HASH_SHA1_Accmlt_End(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, + uint8_t *pOutBuffer, uint32_t Timeout) +{ + return HASH_Start(hhash, pInBuffer, Size, pOutBuffer, Timeout, HASH_ALGOSELECTION_SHA1); +} + +/** + * @} + */ + +/** @defgroup HASH_Exported_Functions_Group3 HASH processing functions in interrupt mode + * @brief HASH processing functions using interrupt mode. + * +@verbatim + =============================================================================== + ##### Interruption mode HASH processing functions ##### + =============================================================================== + [..] This section provides functions allowing to calculate in interrupt mode + the hash value using one of the following algorithms: + (+) MD5 + (++) DAL_HASH_MD5_Start_IT() + (++) DAL_HASH_MD5_Accmlt_IT() + (++) DAL_HASH_MD5_Accmlt_End_IT() + (+) SHA1 + (++) DAL_HASH_SHA1_Start_IT() + (++) DAL_HASH_SHA1_Accmlt_IT() + (++) DAL_HASH_SHA1_Accmlt_End_IT() + + [..] API DAL_HASH_IRQHandler() manages each HASH interruption. + + [..] Note that DAL_HASH_IRQHandler() manages as well HASH Peripheral interruptions when in + HMAC processing mode. + + +@endverbatim + * @{ + */ + +/** + * @brief Initialize the HASH peripheral in MD5 mode, next process pInBuffer then + * read the computed digest in interruption mode. + * @note Digest is available in pOutBuffer. + * @param hhash HASH handle. + * @param pInBuffer pointer to the input buffer (buffer to be hashed). + * @param Size length of the input buffer in bytes. + * @param pOutBuffer pointer to the computed digest. Digest size is 16 bytes. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_HASH_MD5_Start_IT(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, + uint8_t *pOutBuffer) +{ + return HASH_Start_IT(hhash, pInBuffer, Size, pOutBuffer, HASH_ALGOSELECTION_MD5); +} + +/** + * @brief If not already done, initialize the HASH peripheral in MD5 mode then + * processes pInBuffer in interruption mode. + * @note Consecutive calls to DAL_HASH_MD5_Accmlt_IT() can be used to feed + * several input buffers back-to-back to the Peripheral that will yield a single + * HASH signature once all buffers have been entered. Wrap-up of input + * buffers feeding and retrieval of digest is done by a call to + * DAL_HASH_MD5_Accmlt_End_IT(). + * @note Field hhash->Phase of HASH handle is tested to check whether or not + * the Peripheral has already been initialized. + * @note The input buffer size (in bytes) must be a multiple of 4 otherwise, the + * HASH digest computation is corrupted. Only DAL_HASH_MD5_Accmlt_End_IT() is able + * to manage the ending buffer with a length in bytes not a multiple of 4. + * @param hhash HASH handle. + * @param pInBuffer pointer to the input buffer (buffer to be hashed). + * @param Size length of the input buffer in bytes, must be a multiple of 4. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_HASH_MD5_Accmlt_IT(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size) +{ + return HASH_Accumulate_IT(hhash, pInBuffer, Size, HASH_ALGOSELECTION_MD5); +} + +/** + * @brief End computation of a single HASH signature after several calls to DAL_HASH_MD5_Accmlt_IT() API. + * @note Digest is available in pOutBuffer. + * @param hhash HASH handle. + * @param pInBuffer pointer to the input buffer (buffer to be hashed). + * @param Size length of the input buffer in bytes. + * @param pOutBuffer pointer to the computed digest. Digest size is 16 bytes. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_HASH_MD5_Accmlt_End_IT(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, + uint8_t *pOutBuffer) +{ + return HASH_Start_IT(hhash, pInBuffer, Size, pOutBuffer, HASH_ALGOSELECTION_MD5); +} + +/** + * @brief Initialize the HASH peripheral in SHA1 mode, next process pInBuffer then + * read the computed digest in interruption mode. + * @note Digest is available in pOutBuffer. + * @param hhash HASH handle. + * @param pInBuffer pointer to the input buffer (buffer to be hashed). + * @param Size length of the input buffer in bytes. + * @param pOutBuffer pointer to the computed digest. Digest size is 20 bytes. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_HASH_SHA1_Start_IT(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, + uint8_t *pOutBuffer) +{ + return HASH_Start_IT(hhash, pInBuffer, Size, pOutBuffer, HASH_ALGOSELECTION_SHA1); +} + + +/** + * @brief If not already done, initialize the HASH peripheral in SHA1 mode then + * processes pInBuffer in interruption mode. + * @note Consecutive calls to DAL_HASH_SHA1_Accmlt_IT() can be used to feed + * several input buffers back-to-back to the Peripheral that will yield a single + * HASH signature once all buffers have been entered. Wrap-up of input + * buffers feeding and retrieval of digest is done by a call to + * DAL_HASH_SHA1_Accmlt_End_IT(). + * @note Field hhash->Phase of HASH handle is tested to check whether or not + * the Peripheral has already been initialized. + * @note The input buffer size (in bytes) must be a multiple of 4 otherwise, the + * HASH digest computation is corrupted. Only DAL_HASH_SHA1_Accmlt_End_IT() is able + * to manage the ending buffer with a length in bytes not a multiple of 4. + * @param hhash HASH handle. + * @param pInBuffer pointer to the input buffer (buffer to be hashed). + * @param Size length of the input buffer in bytes, must be a multiple of 4. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_HASH_SHA1_Accmlt_IT(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size) +{ + return HASH_Accumulate_IT(hhash, pInBuffer, Size, HASH_ALGOSELECTION_SHA1); +} + +/** + * @brief End computation of a single HASH signature after several calls to DAL_HASH_SHA1_Accmlt_IT() API. + * @note Digest is available in pOutBuffer. + * @param hhash HASH handle. + * @param pInBuffer pointer to the input buffer (buffer to be hashed). + * @param Size length of the input buffer in bytes. + * @param pOutBuffer pointer to the computed digest. Digest size is 20 bytes. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_HASH_SHA1_Accmlt_End_IT(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, + uint8_t *pOutBuffer) +{ + return HASH_Start_IT(hhash, pInBuffer, Size, pOutBuffer, HASH_ALGOSELECTION_SHA1); +} + +/** + * @brief Handle HASH interrupt request. + * @param hhash HASH handle. + * @note DAL_HASH_IRQHandler() handles interrupts in HMAC processing as well. + * @note In case of error reported during the HASH interruption processing, + * DAL_HASH_ErrorCallback() API is called so that user code can + * manage the error. The error type is available in hhash->Status field. + * @retval None + */ +void DAL_HASH_IRQHandler(HASH_HandleTypeDef *hhash) +{ + hhash->Status = HASH_IT(hhash); + if (hhash->Status != DAL_OK) + { + hhash->ErrorCode |= DAL_HASH_ERROR_IT; +#if (USE_DAL_HASH_REGISTER_CALLBACKS == 1) + hhash->ErrorCallback(hhash); +#else + DAL_HASH_ErrorCallback(hhash); +#endif /* USE_DAL_HASH_REGISTER_CALLBACKS */ + /* After error handling by code user, reset HASH handle DAL status */ + hhash->Status = DAL_OK; + } +} + +/** + * @} + */ + +/** @defgroup HASH_Exported_Functions_Group4 HASH processing functions in DMA mode + * @brief HASH processing functions using DMA mode. + * +@verbatim + =============================================================================== + ##### DMA mode HASH processing functions ##### + =============================================================================== + [..] This section provides functions allowing to calculate in DMA mode + the hash value using one of the following algorithms: + (+) MD5 + (++) DAL_HASH_MD5_Start_DMA() + (++) DAL_HASH_MD5_Finish() + (+) SHA1 + (++) DAL_HASH_SHA1_Start_DMA() + (++) DAL_HASH_SHA1_Finish() + + [..] When resorting to DMA mode to enter the data in the Peripheral, user must resort + to DAL_HASH_xxx_Start_DMA() then read the resulting digest with + DAL_HASH_xxx_Finish(). + [..] In case of multi-buffer HASH processing, MDMAT bit must first be set before + the successive calls to DAL_HASH_xxx_Start_DMA(). Then, MDMAT bit needs to be + reset before the last call to DAL_HASH_xxx_Start_DMA(). Digest is finally + retrieved thanks to DAL_HASH_xxx_Finish(). + +@endverbatim + * @{ + */ + +/** + * @brief Initialize the HASH peripheral in MD5 mode then initiate a DMA transfer + * to feed the input buffer to the Peripheral. + * @note Once the DMA transfer is finished, DAL_HASH_MD5_Finish() API must + * be called to retrieve the computed digest. + * @param hhash HASH handle. + * @param pInBuffer pointer to the input buffer (buffer to be hashed). + * @param Size length of the input buffer in bytes. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_HASH_MD5_Start_DMA(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size) +{ + return HASH_Start_DMA(hhash, pInBuffer, Size, HASH_ALGOSELECTION_MD5); +} + +/** + * @brief Return the computed digest in MD5 mode. + * @note The API waits for DCIS to be set then reads the computed digest. + * @note DAL_HASH_MD5_Finish() can be used as well to retrieve the digest in + * HMAC MD5 mode. + * @param hhash HASH handle. + * @param pOutBuffer pointer to the computed digest. Digest size is 16 bytes. + * @param Timeout Timeout value. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_HASH_MD5_Finish(HASH_HandleTypeDef *hhash, uint8_t *pOutBuffer, uint32_t Timeout) +{ + return HASH_Finish(hhash, pOutBuffer, Timeout); +} + +/** + * @brief Initialize the HASH peripheral in SHA1 mode then initiate a DMA transfer + * to feed the input buffer to the Peripheral. + * @note Once the DMA transfer is finished, DAL_HASH_SHA1_Finish() API must + * be called to retrieve the computed digest. + * @param hhash HASH handle. + * @param pInBuffer pointer to the input buffer (buffer to be hashed). + * @param Size length of the input buffer in bytes. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_HASH_SHA1_Start_DMA(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size) +{ + return HASH_Start_DMA(hhash, pInBuffer, Size, HASH_ALGOSELECTION_SHA1); +} + + +/** + * @brief Return the computed digest in SHA1 mode. + * @note The API waits for DCIS to be set then reads the computed digest. + * @note DAL_HASH_SHA1_Finish() can be used as well to retrieve the digest in + * HMAC SHA1 mode. + * @param hhash HASH handle. + * @param pOutBuffer pointer to the computed digest. Digest size is 20 bytes. + * @param Timeout Timeout value. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_HASH_SHA1_Finish(HASH_HandleTypeDef *hhash, uint8_t *pOutBuffer, uint32_t Timeout) +{ + return HASH_Finish(hhash, pOutBuffer, Timeout); +} + +/** + * @} + */ + +/** @defgroup HASH_Exported_Functions_Group5 HMAC processing functions in polling mode + * @brief HMAC processing functions using polling mode. + * +@verbatim + =============================================================================== + ##### Polling mode HMAC processing functions ##### + =============================================================================== + [..] This section provides functions allowing to calculate in polling mode + the HMAC value using one of the following algorithms: + (+) MD5 + (++) DAL_HMAC_MD5_Start() + (+) SHA1 + (++) DAL_HMAC_SHA1_Start() + + +@endverbatim + * @{ + */ + +/** + * @brief Initialize the HASH peripheral in HMAC MD5 mode, next process pInBuffer then + * read the computed digest. + * @note Digest is available in pOutBuffer. + * @note Same key is used for the inner and the outer hash functions; pointer to key and + * key size are respectively stored in hhash->Init.pKey and hhash->Init.KeySize. + * @param hhash HASH handle. + * @param pInBuffer pointer to the input buffer (buffer to be hashed). + * @param Size length of the input buffer in bytes. + * @param pOutBuffer pointer to the computed digest. Digest size is 16 bytes. + * @param Timeout Timeout value. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_HMAC_MD5_Start(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, uint8_t *pOutBuffer, + uint32_t Timeout) +{ + return HMAC_Start(hhash, pInBuffer, Size, pOutBuffer, Timeout, HASH_ALGOSELECTION_MD5); +} + +/** + * @brief Initialize the HASH peripheral in HMAC SHA1 mode, next process pInBuffer then + * read the computed digest. + * @note Digest is available in pOutBuffer. + * @note Same key is used for the inner and the outer hash functions; pointer to key and + * key size are respectively stored in hhash->Init.pKey and hhash->Init.KeySize. + * @param hhash HASH handle. + * @param pInBuffer pointer to the input buffer (buffer to be hashed). + * @param Size length of the input buffer in bytes. + * @param pOutBuffer pointer to the computed digest. Digest size is 20 bytes. + * @param Timeout Timeout value. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_HMAC_SHA1_Start(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, uint8_t *pOutBuffer, + uint32_t Timeout) +{ + return HMAC_Start(hhash, pInBuffer, Size, pOutBuffer, Timeout, HASH_ALGOSELECTION_SHA1); +} + +/** + * @} + */ + + +/** @defgroup HASH_Exported_Functions_Group6 HMAC processing functions in interrupt mode + * @brief HMAC processing functions using interrupt mode. + * +@verbatim + =============================================================================== + ##### Interrupt mode HMAC processing functions ##### + =============================================================================== + [..] This section provides functions allowing to calculate in interrupt mode + the HMAC value using one of the following algorithms: + (+) MD5 + (++) DAL_HMAC_MD5_Start_IT() + (+) SHA1 + (++) DAL_HMAC_SHA1_Start_IT() + +@endverbatim + * @{ + */ + + +/** + * @brief Initialize the HASH peripheral in HMAC MD5 mode, next process pInBuffer then + * read the computed digest in interrupt mode. + * @note Digest is available in pOutBuffer. + * @note Same key is used for the inner and the outer hash functions; pointer to key and + * key size are respectively stored in hhash->Init.pKey and hhash->Init.KeySize. + * @param hhash HASH handle. + * @param pInBuffer pointer to the input buffer (buffer to be hashed). + * @param Size length of the input buffer in bytes. + * @param pOutBuffer pointer to the computed digest. Digest size is 16 bytes. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_HMAC_MD5_Start_IT(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, + uint8_t *pOutBuffer) +{ + return HMAC_Start_IT(hhash, pInBuffer, Size, pOutBuffer, HASH_ALGOSELECTION_MD5); +} + +/** + * @brief Initialize the HASH peripheral in HMAC SHA1 mode, next process pInBuffer then + * read the computed digest in interrupt mode. + * @note Digest is available in pOutBuffer. + * @note Same key is used for the inner and the outer hash functions; pointer to key and + * key size are respectively stored in hhash->Init.pKey and hhash->Init.KeySize. + * @param hhash HASH handle. + * @param pInBuffer pointer to the input buffer (buffer to be hashed). + * @param Size length of the input buffer in bytes. + * @param pOutBuffer pointer to the computed digest. Digest size is 20 bytes. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_HMAC_SHA1_Start_IT(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, + uint8_t *pOutBuffer) +{ + return HMAC_Start_IT(hhash, pInBuffer, Size, pOutBuffer, HASH_ALGOSELECTION_SHA1); +} + +/** + * @} + */ + + + +/** @defgroup HASH_Exported_Functions_Group7 HMAC processing functions in DMA mode + * @brief HMAC processing functions using DMA modes. + * +@verbatim + =============================================================================== + ##### DMA mode HMAC processing functions ##### + =============================================================================== + [..] This section provides functions allowing to calculate in DMA mode + the HMAC value using one of the following algorithms: + (+) MD5 + (++) DAL_HMAC_MD5_Start_DMA() + (+) SHA1 + (++) DAL_HMAC_SHA1_Start_DMA() + + [..] When resorting to DMA mode to enter the data in the Peripheral for HMAC processing, + user must resort to DAL_HMAC_xxx_Start_DMA() then read the resulting digest + with DAL_HASH_xxx_Finish(). + +@endverbatim + * @{ + */ + + +/** + * @brief Initialize the HASH peripheral in HMAC MD5 mode then initiate the required + * DMA transfers to feed the key and the input buffer to the Peripheral. + * @note Once the DMA transfers are finished (indicated by hhash->State set back + * to DAL_HASH_STATE_READY), DAL_HASH_MD5_Finish() API must be called to retrieve + * the computed digest. + * @note Same key is used for the inner and the outer hash functions; pointer to key and + * key size are respectively stored in hhash->Init.pKey and hhash->Init.KeySize. + * @note If MDMAT bit is set before calling this function (multi-buffer + * HASH processing case), the input buffer size (in bytes) must be + * a multiple of 4 otherwise, the HASH digest computation is corrupted. + * For the processing of the last buffer of the thread, MDMAT bit must + * be reset and the buffer length (in bytes) doesn't have to be a + * multiple of 4. + * @param hhash HASH handle. + * @param pInBuffer pointer to the input buffer (buffer to be hashed). + * @param Size length of the input buffer in bytes. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_HMAC_MD5_Start_DMA(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size) +{ + return HMAC_Start_DMA(hhash, pInBuffer, Size, HASH_ALGOSELECTION_MD5); +} + + +/** + * @brief Initialize the HASH peripheral in HMAC SHA1 mode then initiate the required + * DMA transfers to feed the key and the input buffer to the Peripheral. + * @note Once the DMA transfers are finished (indicated by hhash->State set back + * to DAL_HASH_STATE_READY), DAL_HASH_SHA1_Finish() API must be called to retrieve + * the computed digest. + * @note Same key is used for the inner and the outer hash functions; pointer to key and + * key size are respectively stored in hhash->Init.pKey and hhash->Init.KeySize. + * @note If MDMAT bit is set before calling this function (multi-buffer + * HASH processing case), the input buffer size (in bytes) must be + * a multiple of 4 otherwise, the HASH digest computation is corrupted. + * For the processing of the last buffer of the thread, MDMAT bit must + * be reset and the buffer length (in bytes) doesn't have to be a + * multiple of 4. + * @param hhash HASH handle. + * @param pInBuffer pointer to the input buffer (buffer to be hashed). + * @param Size length of the input buffer in bytes. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_HMAC_SHA1_Start_DMA(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size) +{ + return HMAC_Start_DMA(hhash, pInBuffer, Size, HASH_ALGOSELECTION_SHA1); +} + +/** + * @} + */ + +/** @defgroup HASH_Exported_Functions_Group8 Peripheral states functions + * @brief Peripheral State functions. + * +@verbatim + =============================================================================== + ##### Peripheral State methods ##### + =============================================================================== + [..] + This section permits to get in run-time the state and the peripheral handle + status of the peripheral: + (+) DAL_HASH_GetState() + (+) DAL_HASH_GetStatus() + + [..] + Additionally, this subsection provides functions allowing to save and restore + the HASH or HMAC processing context in case of calculation suspension: + (+) DAL_HASH_ContextSaving() + (+) DAL_HASH_ContextRestoring() + + [..] + This subsection provides functions allowing to suspend the HASH processing + (+) when input are fed to the Peripheral by software + (++) DAL_HASH_SwFeed_ProcessSuspend() + (+) when input are fed to the Peripheral by DMA + (++) DAL_HASH_DMAFeed_ProcessSuspend() + + + +@endverbatim + * @{ + */ + +/** + * @brief Return the HASH handle state. + * @note The API yields the current state of the handle (BUSY, READY,...). + * @param hhash HASH handle. + * @retval DAL HASH state + */ +DAL_HASH_StateTypeDef DAL_HASH_GetState(HASH_HandleTypeDef *hhash) +{ + return hhash->State; +} + + +/** + * @brief Return the HASH DAL status. + * @note The API yields the DAL status of the handle: it is the result of the + * latest HASH processing and allows to report any issue (e.g. DAL_TIMEOUT). + * @param hhash HASH handle. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_HASH_GetStatus(HASH_HandleTypeDef *hhash) +{ + return hhash->Status; +} + +/** + * @brief Save the HASH context in case of processing suspension. + * @param hhash HASH handle. + * @param pMemBuffer pointer to the memory buffer where the HASH context + * is saved. + * @note The INT, START, CTRL then all the CTSWAP registers are saved + * in that order. Only the r/w bits are read to be restored later on. + * @note By default, all the context swap registers (there are + * HASH_NUMBER_OF_CTSWAP_REGISTERS of those) are saved. + * @note pMemBuffer points to a buffer allocated by the user. The buffer size + * must be at least (HASH_NUMBER_OF_CTSWAP_REGISTERS + 3) * 4 uint8 long. + * @retval None + */ +void DAL_HASH_ContextSaving(HASH_HandleTypeDef *hhash, uint8_t *pMemBuffer) +{ + uint32_t mem_ptr = (uint32_t)pMemBuffer; + uint32_t csr_ptr = (uint32_t)HASH->CTSWAP; + uint32_t i; + + /* Prevent unused argument(s) compilation warning */ + UNUSED(hhash); + + /* Save INT register content */ + *(uint32_t *)(mem_ptr) = READ_BIT(HASH->INT, HASH_IT_DINI | HASH_IT_DCI); + mem_ptr += 4U; + /* Save START register content */ + *(uint32_t *)(mem_ptr) = READ_BIT(HASH->START, HASH_START_LWNUM); + mem_ptr += 4U; + /* Save CTRL register content */ +#if defined(HASH_CTRL_MDMAT) + *(uint32_t *)(mem_ptr) = READ_BIT(HASH->CTRL, HASH_CTRL_DMAEN | HASH_CTRL_DTYPE | HASH_CTRL_MODESEL | HASH_CTRL_ALGSEL | + HASH_CTRL_LKEYSEL | HASH_CTRL_MDMAT); +#else + *(uint32_t *)(mem_ptr) = READ_BIT(HASH->CTRL, HASH_CTRL_DMAEN | HASH_CTRL_DTYPE | HASH_CTRL_MODESEL | HASH_CTRL_ALGSEL | + HASH_CTRL_LKEYSEL); +#endif /* HASH_CTRL_MDMAT*/ + mem_ptr += 4U; + /* By default, save all CTSWAPs registers */ + for (i = HASH_NUMBER_OF_CTSWAP_REGISTERS; i > 0U; i--) + { + *(uint32_t *)(mem_ptr) = *(uint32_t *)(csr_ptr); + mem_ptr += 4U; + csr_ptr += 4U; + } +} + + +/** + * @brief Restore the HASH context in case of processing resumption. + * @param hhash HASH handle. + * @param pMemBuffer pointer to the memory buffer where the HASH context + * is stored. + * @note The INT, START, CTRL then all the CTSWAP registers are restored + * in that order. Only the r/w bits are restored. + * @note By default, all the context swap registers (HASH_NUMBER_OF_CTSWAP_REGISTERS + * of those) are restored (all of them have been saved by default + * beforehand). + * @retval None + */ +void DAL_HASH_ContextRestoring(HASH_HandleTypeDef *hhash, uint8_t *pMemBuffer) +{ + uint32_t mem_ptr = (uint32_t)pMemBuffer; + uint32_t csr_ptr = (uint32_t)HASH->CTSWAP; + uint32_t i; + + /* Prevent unused argument(s) compilation warning */ + UNUSED(hhash); + + /* Restore INT register content */ + WRITE_REG(HASH->INT, (*(uint32_t *)(mem_ptr))); + mem_ptr += 4U; + /* Restore START register content */ + WRITE_REG(HASH->START, (*(uint32_t *)(mem_ptr))); + mem_ptr += 4U; + /* Restore CTRL register content */ + WRITE_REG(HASH->CTRL, (*(uint32_t *)(mem_ptr))); + mem_ptr += 4U; + + /* Reset the HASH processor before restoring the Context + Swap Registers (CTSWAP) */ + __DAL_HASH_INIT(); + + /* By default, restore all CTSWAP registers */ + for (i = HASH_NUMBER_OF_CTSWAP_REGISTERS; i > 0U; i--) + { + WRITE_REG((*(uint32_t *)(csr_ptr)), (*(uint32_t *)(mem_ptr))); + mem_ptr += 4U; + csr_ptr += 4U; + } +} + + +/** + * @brief Initiate HASH processing suspension when in polling or interruption mode. + * @param hhash HASH handle. + * @note Set the handle field SuspendRequest to the appropriate value so that + * the on-going HASH processing is suspended as soon as the required + * conditions are met. Note that the actual suspension is carried out + * by the functions HASH_WriteData() in polling mode and HASH_IT() in + * interruption mode. + * @retval None + */ +void DAL_HASH_SwFeed_ProcessSuspend(HASH_HandleTypeDef *hhash) +{ + /* Set Handle Suspend Request field */ + hhash->SuspendRequest = DAL_HASH_SUSPEND; +} + +/** + * @brief Suspend the HASH processing when in DMA mode. + * @param hhash HASH handle. + * @note When suspension attempt occurs at the very end of a DMA transfer and + * all the data have already been entered in the Peripheral, hhash->State is + * set to DAL_HASH_STATE_READY and the API returns DAL_ERROR. It is + * recommended to wrap-up the processing in reading the digest as usual. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_HASH_DMAFeed_ProcessSuspend(HASH_HandleTypeDef *hhash) +{ + uint32_t tmp_remaining_DMATransferSize_inWords; + uint32_t tmp_initial_DMATransferSize_inWords; + uint32_t tmp_words_already_pushed; + + if (hhash->State == DAL_HASH_STATE_READY) + { + return DAL_ERROR; + } + else + { + + /* Make sure there is enough time to suspend the processing */ + tmp_remaining_DMATransferSize_inWords = ((DMA_Stream_TypeDef *)hhash->hdmain->Instance)->NDATA; + + if (tmp_remaining_DMATransferSize_inWords <= HASH_DMA_SUSPENSION_WORDS_LIMIT) + { + /* No suspension attempted since almost to the end of the transferred data. */ + /* Best option for user code is to wrap up low priority message hashing */ + return DAL_ERROR; + } + + /* Wait for BUSY flag to be reset */ + if (HASH_WaitOnFlagUntilTimeout(hhash, HASH_FLAG_BUSY, SET, HASH_TIMEOUTVALUE) != DAL_OK) + { + return DAL_TIMEOUT; + } + + if (__DAL_HASH_GET_FLAG(HASH_FLAG_DCIS) != RESET) + { + return DAL_ERROR; + } + + /* Wait for BUSY flag to be set */ + if (HASH_WaitOnFlagUntilTimeout(hhash, HASH_FLAG_BUSY, RESET, HASH_TIMEOUTVALUE) != DAL_OK) + { + return DAL_TIMEOUT; + } + /* Disable DMA channel */ + /* Note that the Abort function will + - Clear the transfer error flags + - Unlock + - Set the State + */ + if (DAL_DMA_Abort(hhash->hdmain) != DAL_OK) + { + return DAL_ERROR; + } + + /* Clear DMAE bit */ + CLEAR_BIT(HASH->CTRL, HASH_CTRL_DMAEN); + + /* Wait for BUSY flag to be reset */ + if (HASH_WaitOnFlagUntilTimeout(hhash, HASH_FLAG_BUSY, SET, HASH_TIMEOUTVALUE) != DAL_OK) + { + return DAL_TIMEOUT; + } + + if (__DAL_HASH_GET_FLAG(HASH_FLAG_DCIS) != RESET) + { + return DAL_ERROR; + } + + /* At this point, DMA interface is disabled and no transfer is on-going */ + /* Retrieve from the DMA handle how many words remain to be written */ + tmp_remaining_DMATransferSize_inWords = ((DMA_Stream_TypeDef *)hhash->hdmain->Instance)->NDATA; + + if (tmp_remaining_DMATransferSize_inWords == 0U) + { + /* All the DMA transfer is actually done. Suspension occurred at the very end + of the transfer. Either the digest computation is about to start (HASH case) + or processing is about to move from one step to another (HMAC case). + In both cases, the processing can't be suspended at this point. It is + safer to + - retrieve the low priority block digest before starting the high + priority block processing (HASH case) + - re-attempt a new suspension (HMAC case) + */ + return DAL_ERROR; + } + else + { + + /* Compute how many words were supposed to be transferred by DMA */ + tmp_initial_DMATransferSize_inWords = (((hhash->HashInCount % 4U) != 0U) ? \ + ((hhash->HashInCount + 3U) / 4U) : (hhash->HashInCount / 4U)); + + /* If discrepancy between the number of words reported by DMA Peripheral and + the numbers of words entered as reported by HASH Peripheral, correct it */ + /* tmp_words_already_pushed reflects the number of words that were already pushed before + the start of DMA transfer (multi-buffer processing case) */ + tmp_words_already_pushed = hhash->NbWordsAlreadyPushed; + if (((tmp_words_already_pushed + tmp_initial_DMATransferSize_inWords - \ + tmp_remaining_DMATransferSize_inWords) % 16U) != HASH_NBW_PUSHED()) + { + tmp_remaining_DMATransferSize_inWords--; /* one less word to be transferred again */ + } + + /* Accordingly, update the input pointer that points at the next word to be + transferred to the Peripheral by DMA */ + hhash->pHashInBuffPtr += 4U * (tmp_initial_DMATransferSize_inWords - tmp_remaining_DMATransferSize_inWords) ; + + /* And store in HashInCount the remaining size to transfer (in bytes) */ + hhash->HashInCount = 4U * tmp_remaining_DMATransferSize_inWords; + + } + + /* Set State as suspended */ + hhash->State = DAL_HASH_STATE_SUSPENDED; + + return DAL_OK; + + } +} + +/** + * @brief Return the HASH handle error code. + * @param hhash pointer to a HASH_HandleTypeDef structure. + * @retval HASH Error Code + */ +uint32_t DAL_HASH_GetError(HASH_HandleTypeDef *hhash) +{ + /* Return HASH Error Code */ + return hhash->ErrorCode; +} +/** + * @} + */ + + +/** + * @} + */ + +/** @defgroup HASH_Private_Functions HASH Private Functions + * @{ + */ + +/** + * @brief DMA HASH Input Data transfer completion callback. + * @param hdma DMA handle. + * @note In case of HMAC processing, HASH_DMAXferCplt() initiates + * the next DMA transfer for the following HMAC step. + * @retval None + */ +static void HASH_DMAXferCplt(DMA_HandleTypeDef *hdma) +{ + HASH_HandleTypeDef *hhash = (HASH_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + uint32_t inputaddr; + uint32_t buffersize; + DAL_StatusTypeDef status = DAL_OK; + + if (hhash->State != DAL_HASH_STATE_SUSPENDED) + { + + /* Disable the DMA transfer */ + CLEAR_BIT(HASH->CTRL, HASH_CTRL_DMAEN); + + if (READ_BIT(HASH->CTRL, HASH_CTRL_MODESEL) == 0U) + { + /* If no HMAC processing, input data transfer is now over */ + + /* Change the HASH state to ready */ + hhash->State = DAL_HASH_STATE_READY; + + /* Call Input data transfer complete call back */ +#if (USE_DAL_HASH_REGISTER_CALLBACKS == 1) + hhash->InCpltCallback(hhash); +#else + DAL_HASH_InCpltCallback(hhash); +#endif /* USE_DAL_HASH_REGISTER_CALLBACKS */ + + } + else + { + /* HMAC processing: depending on the current HMAC step and whether or + not multi-buffer processing is on-going, the next step is initiated + and MDMAT bit is set. */ + + + if (hhash->Phase == DAL_HASH_PHASE_HMAC_STEP_3) + { + /* This is the end of HMAC processing */ + + /* Change the HASH state to ready */ + hhash->State = DAL_HASH_STATE_READY; + + /* Call Input data transfer complete call back + (note that the last DMA transfer was that of the key + for the outer HASH operation). */ +#if (USE_DAL_HASH_REGISTER_CALLBACKS == 1) + hhash->InCpltCallback(hhash); +#else + DAL_HASH_InCpltCallback(hhash); +#endif /* USE_DAL_HASH_REGISTER_CALLBACKS */ + + return; + } + else if (hhash->Phase == DAL_HASH_PHASE_HMAC_STEP_1) + { + inputaddr = (uint32_t)hhash->pHashMsgBuffPtr; /* DMA transfer start address */ + buffersize = hhash->HashBuffSize; /* DMA transfer size (in bytes) */ + hhash->Phase = DAL_HASH_PHASE_HMAC_STEP_2; /* Move phase from Step 1 to Step 2 */ + + /* In case of suspension request, save the new starting parameters */ + hhash->HashInCount = hhash->HashBuffSize; /* Initial DMA transfer size (in bytes) */ + hhash->pHashInBuffPtr = hhash->pHashMsgBuffPtr ; /* DMA transfer start address */ + + hhash->NbWordsAlreadyPushed = 0U; /* Reset number of words already pushed */ +#if defined(HASH_CTRL_MDMAT) + /* Check whether or not digest calculation must be disabled (in case of multi-buffer HMAC processing) */ + if (hhash->DigestCalculationDisable != RESET) + { + /* Digest calculation is disabled: Step 2 must start with MDMAT bit set, + no digest calculation will be triggered at the end of the input buffer feeding to the Peripheral */ + __DAL_HASH_SET_MDMAT(); + } +#endif /* HASH_CTRL_MDMAT*/ + } + else /*case (hhash->Phase == DAL_HASH_PHASE_HMAC_STEP_2)*/ + { + if (hhash->DigestCalculationDisable != RESET) + { + /* No automatic move to Step 3 as a new message buffer will be fed to the Peripheral + (case of multi-buffer HMAC processing): + DCAL must not be set. + Phase remains in Step 2, MDMAT remains set at this point. + Change the HASH state to ready and call Input data transfer complete call back. */ + hhash->State = DAL_HASH_STATE_READY; +#if (USE_DAL_HASH_REGISTER_CALLBACKS == 1) + hhash->InCpltCallback(hhash); +#else + DAL_HASH_InCpltCallback(hhash); +#endif /* USE_DAL_HASH_REGISTER_CALLBACKS */ + return ; + } + else + { + /* Digest calculation is not disabled (case of single buffer input or last buffer + of multi-buffer HMAC processing) */ + inputaddr = (uint32_t)hhash->Init.pKey; /* DMA transfer start address */ + buffersize = hhash->Init.KeySize; /* DMA transfer size (in bytes) */ + hhash->Phase = DAL_HASH_PHASE_HMAC_STEP_3; /* Move phase from Step 2 to Step 3 */ + /* In case of suspension request, save the new starting parameters */ + hhash->HashInCount = hhash->Init.KeySize; /* Initial size for second DMA transfer (input data) */ + hhash->pHashInBuffPtr = hhash->Init.pKey ; /* address passed to DMA, now entering data message */ + + hhash->NbWordsAlreadyPushed = 0U; /* Reset number of words already pushed */ + } + } + + /* Configure the Number of valid bits in last word of the message */ + __DAL_HASH_SET_NBVALIDBITS(buffersize); + + /* Set the HASH DMA transfer completion call back */ + hhash->hdmain->XferCpltCallback = HASH_DMAXferCplt; + + /* Enable the DMA In DMA stream */ + status = DAL_DMA_Start_IT(hhash->hdmain, inputaddr, (uint32_t)&HASH->INDATA, \ + (((buffersize % 4U) != 0U) ? ((buffersize + (4U - (buffersize % 4U))) / 4U) : \ + (buffersize / 4U))); + + /* Enable DMA requests */ + SET_BIT(HASH->CTRL, HASH_CTRL_DMAEN); + + /* Return function status */ + if (status != DAL_OK) + { + /* Update HASH state machine to error */ + hhash->State = DAL_HASH_STATE_ERROR; + } + else + { + /* Change HASH state */ + hhash->State = DAL_HASH_STATE_BUSY; + } + } + } + + return; +} + +/** + * @brief DMA HASH communication error callback. + * @param hdma DMA handle. + * @note HASH_DMAError() callback invokes DAL_HASH_ErrorCallback() that + * can contain user code to manage the error. + * @retval None + */ +static void HASH_DMAError(DMA_HandleTypeDef *hdma) +{ + HASH_HandleTypeDef *hhash = (HASH_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + + if (hhash->State != DAL_HASH_STATE_SUSPENDED) + { + hhash->ErrorCode |= DAL_HASH_ERROR_DMA; + /* Set HASH state to ready to prevent any blocking issue in user code + present in DAL_HASH_ErrorCallback() */ + hhash->State = DAL_HASH_STATE_READY; + /* Set HASH handle status to error */ + hhash->Status = DAL_ERROR; +#if (USE_DAL_HASH_REGISTER_CALLBACKS == 1) + hhash->ErrorCallback(hhash); +#else + DAL_HASH_ErrorCallback(hhash); +#endif /* USE_DAL_HASH_REGISTER_CALLBACKS */ + /* After error handling by code user, reset HASH handle DAL status */ + hhash->Status = DAL_OK; + + } +} + +/** + * @brief Feed the input buffer to the HASH Peripheral. + * @param hhash HASH handle. + * @param pInBuffer pointer to input buffer. + * @param Size the size of input buffer in bytes. + * @note HASH_WriteData() regularly reads hhash->SuspendRequest to check whether + * or not the HASH processing must be suspended. If this is the case, the + * processing is suspended when possible and the Peripheral feeding point reached at + * suspension time is stored in the handle for resumption later on. + * @retval DAL status + */ +static DAL_StatusTypeDef HASH_WriteData(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size) +{ + uint32_t buffercounter; + __IO uint32_t inputaddr = (uint32_t) pInBuffer; + + for (buffercounter = 0U; buffercounter < Size; buffercounter += 4U) + { + /* Write input data 4 bytes at a time */ + HASH->INDATA = *(uint32_t *)inputaddr; + inputaddr += 4U; + + /* If the suspension flag has been raised and if the processing is not about + to end, suspend processing */ + if ((hhash->SuspendRequest == DAL_HASH_SUSPEND) && ((buffercounter + 4U) < Size)) + { + /* Wait for DINIS = 1, which occurs when 16 32-bit locations are free + in the input buffer */ + if (__DAL_HASH_GET_FLAG(HASH_FLAG_DINIS)) + { + /* Reset SuspendRequest */ + hhash->SuspendRequest = DAL_HASH_SUSPEND_NONE; + + /* Depending whether the key or the input data were fed to the Peripheral, the feeding point + reached at suspension time is not saved in the same handle fields */ + if ((hhash->Phase == DAL_HASH_PHASE_PROCESS) || (hhash->Phase == DAL_HASH_PHASE_HMAC_STEP_2)) + { + /* Save current reading and writing locations of Input and Output buffers */ + hhash->pHashInBuffPtr = (uint8_t *)inputaddr; + /* Save the number of bytes that remain to be processed at this point */ + hhash->HashInCount = Size - (buffercounter + 4U); + } + else if ((hhash->Phase == DAL_HASH_PHASE_HMAC_STEP_1) || (hhash->Phase == DAL_HASH_PHASE_HMAC_STEP_3)) + { + /* Save current reading and writing locations of Input and Output buffers */ + hhash->pHashKeyBuffPtr = (uint8_t *)inputaddr; + /* Save the number of bytes that remain to be processed at this point */ + hhash->HashKeyCount = Size - (buffercounter + 4U); + } + else + { + /* Unexpected phase: unlock process and report error */ + hhash->State = DAL_HASH_STATE_READY; + __DAL_UNLOCK(hhash); + return DAL_ERROR; + } + + /* Set the HASH state to Suspended and exit to stop entering data */ + hhash->State = DAL_HASH_STATE_SUSPENDED; + + return DAL_OK; + } /* if (__DAL_HASH_GET_FLAG(HASH_FLAG_DINIS)) */ + } /* if ((hhash->SuspendRequest == DAL_HASH_SUSPEND) && ((buffercounter+4) < Size)) */ + } /* for(buffercounter = 0; buffercounter < Size; buffercounter+=4) */ + + /* At this point, all the data have been entered to the Peripheral: exit */ + return DAL_OK; +} + +/** + * @brief Retrieve the message digest. + * @param pMsgDigest pointer to the computed digest. + * @param Size message digest size in bytes. + * @retval None + */ +static void HASH_GetDigest(uint8_t *pMsgDigest, uint8_t Size) +{ + uint32_t msgdigest = (uint32_t)pMsgDigest; + + switch (Size) + { + /* Read the message digest */ + case 16: /* MD5 */ + *(uint32_t *)(msgdigest) = __REV(HASH->DIG[0]); + msgdigest += 4U; + *(uint32_t *)(msgdigest) = __REV(HASH->DIG[1]); + msgdigest += 4U; + *(uint32_t *)(msgdigest) = __REV(HASH->DIG[2]); + msgdigest += 4U; + *(uint32_t *)(msgdigest) = __REV(HASH->DIG[3]); + break; + case 20: /* SHA1 */ + *(uint32_t *)(msgdigest) = __REV(HASH->DIG[0]); + msgdigest += 4U; + *(uint32_t *)(msgdigest) = __REV(HASH->DIG[1]); + msgdigest += 4U; + *(uint32_t *)(msgdigest) = __REV(HASH->DIG[2]); + msgdigest += 4U; + *(uint32_t *)(msgdigest) = __REV(HASH->DIG[3]); + msgdigest += 4U; + *(uint32_t *)(msgdigest) = __REV(HASH->DIG[4]); + break; + case 28: /* SHA224 */ + *(uint32_t *)(msgdigest) = __REV(HASH->DIG[0]); + msgdigest += 4U; + *(uint32_t *)(msgdigest) = __REV(HASH->DIG[1]); + msgdigest += 4U; + *(uint32_t *)(msgdigest) = __REV(HASH->DIG[2]); + msgdigest += 4U; + *(uint32_t *)(msgdigest) = __REV(HASH->DIG[3]); + msgdigest += 4U; + *(uint32_t *)(msgdigest) = __REV(HASH->DIG[4]); +#if defined(HASH_CTRL_MDMAT) + msgdigest += 4U; + *(uint32_t *)(msgdigest) = __REV(HASH_DIGEST->HR[5]); + msgdigest += 4U; + *(uint32_t *)(msgdigest) = __REV(HASH_DIGEST->HR[6]); +#endif /* HASH_CTRL_MDMAT*/ + break; + case 32: /* SHA256 */ + *(uint32_t *)(msgdigest) = __REV(HASH->DIG[0]); + msgdigest += 4U; + *(uint32_t *)(msgdigest) = __REV(HASH->DIG[1]); + msgdigest += 4U; + *(uint32_t *)(msgdigest) = __REV(HASH->DIG[2]); + msgdigest += 4U; + *(uint32_t *)(msgdigest) = __REV(HASH->DIG[3]); + msgdigest += 4U; + *(uint32_t *)(msgdigest) = __REV(HASH->DIG[4]); +#if defined(HASH_CTRL_MDMAT) + msgdigest += 4U; + *(uint32_t *)(msgdigest) = __REV(HASH_DIGEST->HR[5]); + msgdigest += 4U; + *(uint32_t *)(msgdigest) = __REV(HASH_DIGEST->HR[6]); + msgdigest += 4U; + *(uint32_t *)(msgdigest) = __REV(HASH_DIGEST->HR[7]); +#endif /* HASH_CTRL_MDMAT*/ + break; + default: + break; + } +} + + + +/** + * @brief Handle HASH processing Timeout. + * @param hhash HASH handle. + * @param Flag specifies the HASH flag to check. + * @param Status the Flag status (SET or RESET). + * @param Timeout Timeout duration. + * @retval DAL status + */ +static DAL_StatusTypeDef HASH_WaitOnFlagUntilTimeout(HASH_HandleTypeDef *hhash, uint32_t Flag, FlagStatus Status, + uint32_t Timeout) +{ + uint32_t tickstart = DAL_GetTick(); + + /* Wait until flag is set */ + if (Status == RESET) + { + while (__DAL_HASH_GET_FLAG(Flag) == RESET) + { + /* Check for the Timeout */ + if (Timeout != DAL_MAX_DELAY) + { + if (((DAL_GetTick() - tickstart) > Timeout) || (Timeout == 0U)) + { + /* Set State to Ready to be able to restart later on */ + hhash->State = DAL_HASH_STATE_READY; + /* Store time out issue in handle status */ + hhash->Status = DAL_TIMEOUT; + + /* Process Unlocked */ + __DAL_UNLOCK(hhash); + + return DAL_TIMEOUT; + } + } + } + } + else + { + while (__DAL_HASH_GET_FLAG(Flag) != RESET) + { + /* Check for the Timeout */ + if (Timeout != DAL_MAX_DELAY) + { + if (((DAL_GetTick() - tickstart) > Timeout) || (Timeout == 0U)) + { + /* Set State to Ready to be able to restart later on */ + hhash->State = DAL_HASH_STATE_READY; + /* Store time out issue in handle status */ + hhash->Status = DAL_TIMEOUT; + + /* Process Unlocked */ + __DAL_UNLOCK(hhash); + + return DAL_TIMEOUT; + } + } + } + } + return DAL_OK; +} + + +/** + * @brief HASH processing in interruption mode. + * @param hhash HASH handle. + * @note HASH_IT() regularly reads hhash->SuspendRequest to check whether + * or not the HASH processing must be suspended. If this is the case, the + * processing is suspended when possible and the Peripheral feeding point reached at + * suspension time is stored in the handle for resumption later on. + * @retval DAL status + */ +static DAL_StatusTypeDef HASH_IT(HASH_HandleTypeDef *hhash) +{ + if (hhash->State == DAL_HASH_STATE_BUSY) + { + /* ITCounter must not be equal to 0 at this point. Report an error if this is the case. */ + if (hhash->HashITCounter == 0U) + { + /* Disable Interrupts */ + __DAL_HASH_DISABLE_IT(HASH_IT_DINI | HASH_IT_DCI); + /* HASH state set back to Ready to prevent any issue in user code + present in DAL_HASH_ErrorCallback() */ + hhash->State = DAL_HASH_STATE_READY; + return DAL_ERROR; + } + else if (hhash->HashITCounter == 1U) + { + /* This is the first call to HASH_IT, the first input data are about to be + entered in the Peripheral. A specific processing is carried out at this point to + start-up the processing. */ + hhash->HashITCounter = 2U; + } + else + { + /* Cruise speed reached, HashITCounter remains equal to 3 until the end of + the HASH processing or the end of the current step for HMAC processing. */ + hhash->HashITCounter = 3U; + } + + /* If digest is ready */ + if (__DAL_HASH_GET_FLAG(HASH_FLAG_DCIS)) + { + /* Read the digest */ + HASH_GetDigest(hhash->pHashOutBuffPtr, HASH_DIGEST_LENGTH()); + + /* Disable Interrupts */ + __DAL_HASH_DISABLE_IT(HASH_IT_DINI | HASH_IT_DCI); + /* Change the HASH state */ + hhash->State = DAL_HASH_STATE_READY; + /* Reset HASH state machine */ + hhash->Phase = DAL_HASH_PHASE_READY; + /* Call digest computation complete call back */ +#if (USE_DAL_HASH_REGISTER_CALLBACKS == 1) + hhash->DgstCpltCallback(hhash); +#else + DAL_HASH_DgstCpltCallback(hhash); +#endif /* USE_DAL_HASH_REGISTER_CALLBACKS */ + + return DAL_OK; + } + + /* If Peripheral ready to accept new data */ + if (__DAL_HASH_GET_FLAG(HASH_FLAG_DINIS)) + { + + /* If the suspension flag has been raised and if the processing is not about + to end, suspend processing */ + if ((hhash->HashInCount != 0U) && (hhash->SuspendRequest == DAL_HASH_SUSPEND)) + { + /* Disable Interrupts */ + __DAL_HASH_DISABLE_IT(HASH_IT_DINI | HASH_IT_DCI); + + /* Reset SuspendRequest */ + hhash->SuspendRequest = DAL_HASH_SUSPEND_NONE; + + /* Change the HASH state */ + hhash->State = DAL_HASH_STATE_SUSPENDED; + + return DAL_OK; + } + + /* Enter input data in the Peripheral through HASH_Write_Block_Data() call and + check whether the digest calculation has been triggered */ + if (HASH_Write_Block_Data(hhash) == HASH_DIGEST_CALCULATION_STARTED) + { + /* Call Input data transfer complete call back + (called at the end of each step for HMAC) */ +#if (USE_DAL_HASH_REGISTER_CALLBACKS == 1) + hhash->InCpltCallback(hhash); +#else + DAL_HASH_InCpltCallback(hhash); +#endif /* USE_DAL_HASH_REGISTER_CALLBACKS */ + + if (hhash->Phase == DAL_HASH_PHASE_HMAC_STEP_1) + { + /* Wait until Peripheral is not busy anymore */ + if (HASH_WaitOnFlagUntilTimeout(hhash, HASH_FLAG_BUSY, SET, HASH_TIMEOUTVALUE) != DAL_OK) + { + /* Disable Interrupts */ + __DAL_HASH_DISABLE_IT(HASH_IT_DINI | HASH_IT_DCI); + return DAL_TIMEOUT; + } + /* Initialization start for HMAC STEP 2 */ + hhash->Phase = DAL_HASH_PHASE_HMAC_STEP_2; /* Move phase from Step 1 to Step 2 */ + __DAL_HASH_SET_NBVALIDBITS(hhash->HashBuffSize); /* Set NBLW for the input message */ + hhash->HashInCount = hhash->HashBuffSize; /* Set the input data size (in bytes) */ + hhash->pHashInBuffPtr = hhash->pHashMsgBuffPtr; /* Set the input data address */ + hhash->HashITCounter = 1; /* Set ITCounter to 1 to indicate the start + of a new phase */ + __DAL_HASH_ENABLE_IT(HASH_IT_DINI); /* Enable IT (was disabled in HASH_Write_Block_Data) */ + } + else if (hhash->Phase == DAL_HASH_PHASE_HMAC_STEP_2) + { + /* Wait until Peripheral is not busy anymore */ + if (HASH_WaitOnFlagUntilTimeout(hhash, HASH_FLAG_BUSY, SET, HASH_TIMEOUTVALUE) != DAL_OK) + { + /* Disable Interrupts */ + __DAL_HASH_DISABLE_IT(HASH_IT_DINI | HASH_IT_DCI); + return DAL_TIMEOUT; + } + /* Initialization start for HMAC STEP 3 */ + hhash->Phase = DAL_HASH_PHASE_HMAC_STEP_3; /* Move phase from Step 2 to Step 3 */ + __DAL_HASH_SET_NBVALIDBITS(hhash->Init.KeySize); /* Set NBLW for the key */ + hhash->HashInCount = hhash->Init.KeySize; /* Set the key size (in bytes) */ + hhash->pHashInBuffPtr = hhash->Init.pKey; /* Set the key address */ + hhash->HashITCounter = 1; /* Set ITCounter to 1 to indicate the start + of a new phase */ + __DAL_HASH_ENABLE_IT(HASH_IT_DINI); /* Enable IT (was disabled in HASH_Write_Block_Data) */ + } + else + { + /* Nothing to do */ + } + } /* if (HASH_Write_Block_Data(hhash) == HASH_DIGEST_CALCULATION_STARTED) */ + } /* if (__DAL_HASH_GET_FLAG(HASH_FLAG_DINIS))*/ + + /* Return function status */ + return DAL_OK; + } + else + { + return DAL_BUSY; + } +} + + +/** + * @brief Write a block of data in HASH Peripheral in interruption mode. + * @param hhash HASH handle. + * @note HASH_Write_Block_Data() is called under interruption by HASH_IT(). + * @retval DAL status + */ +static uint32_t HASH_Write_Block_Data(HASH_HandleTypeDef *hhash) +{ + uint32_t inputaddr; + uint32_t buffercounter; + uint32_t inputcounter; + uint32_t ret = HASH_DIGEST_CALCULATION_NOT_STARTED; + + /* If there are more than 64 bytes remaining to be entered */ + if (hhash->HashInCount > 64U) + { + inputaddr = (uint32_t)hhash->pHashInBuffPtr; + /* Write the Input block in the Data IN register + (16 32-bit words, or 64 bytes are entered) */ + for (buffercounter = 0U; buffercounter < 64U; buffercounter += 4U) + { + HASH->INDATA = *(uint32_t *)inputaddr; + inputaddr += 4U; + } + /* If this is the start of input data entering, an additional word + must be entered to start up the HASH processing */ + if (hhash->HashITCounter == 2U) + { + HASH->INDATA = *(uint32_t *)inputaddr; + if (hhash->HashInCount >= 68U) + { + /* There are still data waiting to be entered in the Peripheral. + Decrement buffer counter and set pointer to the proper + memory location for the next data entering round. */ + hhash->HashInCount -= 68U; + hhash->pHashInBuffPtr += 68U; + } + else + { + /* All the input buffer has been fed to the HW. */ + hhash->HashInCount = 0U; + } + } + else + { + /* 64 bytes have been entered and there are still some remaining: + Decrement buffer counter and set pointer to the proper + memory location for the next data entering round.*/ + hhash->HashInCount -= 64U; + hhash->pHashInBuffPtr += 64U; + } + } + else + { + /* 64 or less bytes remain to be entered. This is the last + data entering round. */ + + /* Get the buffer address */ + inputaddr = (uint32_t)hhash->pHashInBuffPtr; + /* Get the buffer counter */ + inputcounter = hhash->HashInCount; + /* Disable Interrupts */ + __DAL_HASH_DISABLE_IT(HASH_IT_DINI); + + /* Write the Input block in the Data IN register */ + for (buffercounter = 0U; buffercounter < ((inputcounter + 3U) / 4U); buffercounter++) + { + HASH->INDATA = *(uint32_t *)inputaddr; + inputaddr += 4U; + } + + if (hhash->Accumulation == 1U) + { + /* Field accumulation is set, API only feeds data to the Peripheral and under interruption. + The digest computation will be started when the last buffer data are entered. */ + + /* Reset multi buffers accumulation flag */ + hhash->Accumulation = 0U; + /* Change the HASH state */ + hhash->State = DAL_HASH_STATE_READY; + /* Call Input data transfer complete call back */ +#if (USE_DAL_HASH_REGISTER_CALLBACKS == 1) + hhash->InCpltCallback(hhash); +#else + DAL_HASH_InCpltCallback(hhash); +#endif /* USE_DAL_HASH_REGISTER_CALLBACKS */ + } + else + { + /* Start the Digest calculation */ + __DAL_HASH_START_DIGEST(); + /* Return indication that digest calculation has started: + this return value triggers the call to Input data transfer + complete call back as well as the proper transition from + one step to another in HMAC mode. */ + ret = HASH_DIGEST_CALCULATION_STARTED; + } + /* Reset buffer counter */ + hhash->HashInCount = 0; + } + + /* Return whether or digest calculation has started */ + return ret; +} + +/** + * @brief HMAC processing in polling mode. + * @param hhash HASH handle. + * @param Timeout Timeout value. + * @retval DAL status + */ +static DAL_StatusTypeDef HMAC_Processing(HASH_HandleTypeDef *hhash, uint32_t Timeout) +{ + /* Ensure first that Phase is correct */ + if ((hhash->Phase != DAL_HASH_PHASE_HMAC_STEP_1) && (hhash->Phase != DAL_HASH_PHASE_HMAC_STEP_2) + && (hhash->Phase != DAL_HASH_PHASE_HMAC_STEP_3)) + { + /* Change the HASH state */ + hhash->State = DAL_HASH_STATE_READY; + + /* Process Unlock */ + __DAL_UNLOCK(hhash); + + /* Return function status */ + return DAL_ERROR; + } + + /* HMAC Step 1 processing */ + if (hhash->Phase == DAL_HASH_PHASE_HMAC_STEP_1) + { + /************************** STEP 1 ******************************************/ + /* Configure the Number of valid bits in last word of the message */ + __DAL_HASH_SET_NBVALIDBITS(hhash->Init.KeySize); + + /* Write input buffer in Data register */ + hhash->Status = HASH_WriteData(hhash, hhash->pHashKeyBuffPtr, hhash->HashKeyCount); + if (hhash->Status != DAL_OK) + { + return hhash->Status; + } + + /* Check whether or not key entering process has been suspended */ + if (hhash->State == DAL_HASH_STATE_SUSPENDED) + { + /* Process Unlocked */ + __DAL_UNLOCK(hhash); + + /* Stop right there and return function status */ + return DAL_OK; + } + + /* No processing suspension at this point: set DCAL bit. */ + __DAL_HASH_START_DIGEST(); + + /* Wait for BUSY flag to be cleared */ + if (HASH_WaitOnFlagUntilTimeout(hhash, HASH_FLAG_BUSY, SET, Timeout) != DAL_OK) + { + return DAL_TIMEOUT; + } + + /* Move from Step 1 to Step 2 */ + hhash->Phase = DAL_HASH_PHASE_HMAC_STEP_2; + + } + + /* HMAC Step 2 processing. + After phase check, HMAC_Processing() may + - directly start up from this point in resumption case + if the same Step 2 processing was suspended previously + - or fall through from the Step 1 processing carried out hereabove */ + if (hhash->Phase == DAL_HASH_PHASE_HMAC_STEP_2) + { + /************************** STEP 2 ******************************************/ + /* Configure the Number of valid bits in last word of the message */ + __DAL_HASH_SET_NBVALIDBITS(hhash->HashBuffSize); + + /* Write input buffer in Data register */ + hhash->Status = HASH_WriteData(hhash, hhash->pHashInBuffPtr, hhash->HashInCount); + if (hhash->Status != DAL_OK) + { + return hhash->Status; + } + + /* Check whether or not data entering process has been suspended */ + if (hhash->State == DAL_HASH_STATE_SUSPENDED) + { + /* Process Unlocked */ + __DAL_UNLOCK(hhash); + + /* Stop right there and return function status */ + return DAL_OK; + } + + /* No processing suspension at this point: set DCAL bit. */ + __DAL_HASH_START_DIGEST(); + + /* Wait for BUSY flag to be cleared */ + if (HASH_WaitOnFlagUntilTimeout(hhash, HASH_FLAG_BUSY, SET, Timeout) != DAL_OK) + { + return DAL_TIMEOUT; + } + + /* Move from Step 2 to Step 3 */ + hhash->Phase = DAL_HASH_PHASE_HMAC_STEP_3; + /* In case Step 1 phase was suspended then resumed, + set again Key input buffers and size before moving to + next step */ + hhash->pHashKeyBuffPtr = hhash->Init.pKey; + hhash->HashKeyCount = hhash->Init.KeySize; + } + + + /* HMAC Step 3 processing. + After phase check, HMAC_Processing() may + - directly start up from this point in resumption case + if the same Step 3 processing was suspended previously + - or fall through from the Step 2 processing carried out hereabove */ + if (hhash->Phase == DAL_HASH_PHASE_HMAC_STEP_3) + { + /************************** STEP 3 ******************************************/ + /* Configure the Number of valid bits in last word of the message */ + __DAL_HASH_SET_NBVALIDBITS(hhash->Init.KeySize); + + /* Write input buffer in Data register */ + hhash->Status = HASH_WriteData(hhash, hhash->pHashKeyBuffPtr, hhash->HashKeyCount); + if (hhash->Status != DAL_OK) + { + return hhash->Status; + } + + /* Check whether or not key entering process has been suspended */ + if (hhash->State == DAL_HASH_STATE_SUSPENDED) + { + /* Process Unlocked */ + __DAL_UNLOCK(hhash); + + /* Stop right there and return function status */ + return DAL_OK; + } + + /* No processing suspension at this point: start the Digest calculation. */ + __DAL_HASH_START_DIGEST(); + + /* Wait for DCIS flag to be set */ + if (HASH_WaitOnFlagUntilTimeout(hhash, HASH_FLAG_DCIS, RESET, Timeout) != DAL_OK) + { + return DAL_TIMEOUT; + } + + /* Read the message digest */ + HASH_GetDigest(hhash->pHashOutBuffPtr, HASH_DIGEST_LENGTH()); + + /* Reset HASH state machine */ + hhash->Phase = DAL_HASH_PHASE_READY; + } + + /* Change the HASH state */ + hhash->State = DAL_HASH_STATE_READY; + + /* Process Unlock */ + __DAL_UNLOCK(hhash); + + /* Return function status */ + return DAL_OK; +} + + +/** + * @brief Initialize the HASH peripheral, next process pInBuffer then + * read the computed digest. + * @note Digest is available in pOutBuffer. + * @param hhash HASH handle. + * @param pInBuffer pointer to the input buffer (buffer to be hashed). + * @param Size length of the input buffer in bytes. + * @param pOutBuffer pointer to the computed digest. + * @param Timeout Timeout value. + * @param Algorithm HASH algorithm. + * @retval DAL status + */ +DAL_StatusTypeDef HASH_Start(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, uint8_t *pOutBuffer, + uint32_t Timeout, uint32_t Algorithm) +{ + uint8_t *pInBuffer_tmp; /* input data address, input parameter of HASH_WriteData() */ + uint32_t Size_tmp; /* input data size (in bytes), input parameter of HASH_WriteData() */ + DAL_HASH_StateTypeDef State_tmp = hhash->State; + + + /* Initiate HASH processing in case of start or resumption */ + if ((State_tmp == DAL_HASH_STATE_READY) || (State_tmp == DAL_HASH_STATE_SUSPENDED)) + { + /* Check input parameters */ + if ((pInBuffer == NULL) || (pOutBuffer == NULL)) + { + hhash->State = DAL_HASH_STATE_READY; + return DAL_ERROR; + } + + /* Process Locked */ + __DAL_LOCK(hhash); + + /* Check if initialization phase has not been already performed */ + if (hhash->Phase == DAL_HASH_PHASE_READY) + { + /* Change the HASH state */ + hhash->State = DAL_HASH_STATE_BUSY; + + /* Select the HASH algorithm, clear HMAC mode and long key selection bit, reset the HASH processor core */ + MODIFY_REG(HASH->CTRL, HASH_CTRL_LKEYSEL | HASH_CTRL_ALGSEL | HASH_CTRL_MODESEL | HASH_CTRL_INITCAL, Algorithm | HASH_CTRL_INITCAL); + + /* Configure the number of valid bits in last word of the message */ + __DAL_HASH_SET_NBVALIDBITS(Size); + + /* pInBuffer_tmp and Size_tmp are initialized to be used afterwards as + input parameters of HASH_WriteData() */ + pInBuffer_tmp = pInBuffer; /* pInBuffer_tmp is set to the input data address */ + Size_tmp = Size; /* Size_tmp contains the input data size in bytes */ + + /* Set the phase */ + hhash->Phase = DAL_HASH_PHASE_PROCESS; + } + else if (hhash->Phase == DAL_HASH_PHASE_PROCESS) + { + /* if the Peripheral has already been initialized, two cases are possible */ + + /* Process resumption time ... */ + if (hhash->State == DAL_HASH_STATE_SUSPENDED) + { + /* Since this is resumption, pInBuffer_tmp and Size_tmp are not set + to the API input parameters but to those saved beforehand by HASH_WriteData() + when the processing was suspended */ + pInBuffer_tmp = hhash->pHashInBuffPtr; + Size_tmp = hhash->HashInCount; + } + /* ... or multi-buffer HASH processing end */ + else + { + /* pInBuffer_tmp and Size_tmp are initialized to be used afterwards as + input parameters of HASH_WriteData() */ + pInBuffer_tmp = pInBuffer; + Size_tmp = Size; + /* Configure the number of valid bits in last word of the message */ + __DAL_HASH_SET_NBVALIDBITS(Size); + } + /* Change the HASH state */ + hhash->State = DAL_HASH_STATE_BUSY; + } + else + { + /* Phase error */ + hhash->State = DAL_HASH_STATE_READY; + + /* Process Unlocked */ + __DAL_UNLOCK(hhash); + + /* Return function status */ + return DAL_ERROR; + } + + + /* Write input buffer in Data register */ + hhash->Status = HASH_WriteData(hhash, pInBuffer_tmp, Size_tmp); + if (hhash->Status != DAL_OK) + { + return hhash->Status; + } + + /* If the process has not been suspended, carry on to digest calculation */ + if (hhash->State != DAL_HASH_STATE_SUSPENDED) + { + /* Start the Digest calculation */ + __DAL_HASH_START_DIGEST(); + + /* Wait for DCIS flag to be set */ + if (HASH_WaitOnFlagUntilTimeout(hhash, HASH_FLAG_DCIS, RESET, Timeout) != DAL_OK) + { + return DAL_TIMEOUT; + } + + /* Read the message digest */ + HASH_GetDigest(pOutBuffer, HASH_DIGEST_LENGTH()); + + /* Change the HASH state */ + hhash->State = DAL_HASH_STATE_READY; + + /* Reset HASH state machine */ + hhash->Phase = DAL_HASH_PHASE_READY; + + } + + /* Process Unlocked */ + __DAL_UNLOCK(hhash); + + /* Return function status */ + return DAL_OK; + + } + else + { + return DAL_BUSY; + } +} + + +/** + * @brief If not already done, initialize the HASH peripheral then + * processes pInBuffer. + * @note Field hhash->Phase of HASH handle is tested to check whether or not + * the Peripheral has already been initialized. + * @note The input buffer size (in bytes) must be a multiple of 4 otherwise, the + * HASH digest computation is corrupted. + * @param hhash HASH handle. + * @param pInBuffer pointer to the input buffer (buffer to be hashed). + * @param Size length of the input buffer in bytes, must be a multiple of 4. + * @param Algorithm HASH algorithm. + * @retval DAL status + */ +DAL_StatusTypeDef HASH_Accumulate(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, uint32_t Algorithm) +{ + uint8_t *pInBuffer_tmp; /* input data address, input parameter of HASH_WriteData() */ + uint32_t Size_tmp; /* input data size (in bytes), input parameter of HASH_WriteData() */ + DAL_HASH_StateTypeDef State_tmp = hhash->State; + + /* Make sure the input buffer size (in bytes) is a multiple of 4 */ + if ((Size % 4U) != 0U) + { + return DAL_ERROR; + } + + /* Initiate HASH processing in case of start or resumption */ + if ((State_tmp == DAL_HASH_STATE_READY) || (State_tmp == DAL_HASH_STATE_SUSPENDED)) + { + /* Check input parameters */ + if ((pInBuffer == NULL) || (Size == 0U)) + { + hhash->State = DAL_HASH_STATE_READY; + return DAL_ERROR; + } + + /* Process Locked */ + __DAL_LOCK(hhash); + + /* If resuming the HASH processing */ + if (hhash->State == DAL_HASH_STATE_SUSPENDED) + { + /* Change the HASH state */ + hhash->State = DAL_HASH_STATE_BUSY; + + /* Since this is resumption, pInBuffer_tmp and Size_tmp are not set + to the API input parameters but to those saved beforehand by HASH_WriteData() + when the processing was suspended */ + pInBuffer_tmp = hhash->pHashInBuffPtr; /* pInBuffer_tmp is set to the input data address */ + Size_tmp = hhash->HashInCount; /* Size_tmp contains the input data size in bytes */ + + } + else + { + /* Change the HASH state */ + hhash->State = DAL_HASH_STATE_BUSY; + + /* pInBuffer_tmp and Size_tmp are initialized to be used afterwards as + input parameters of HASH_WriteData() */ + pInBuffer_tmp = pInBuffer; /* pInBuffer_tmp is set to the input data address */ + Size_tmp = Size; /* Size_tmp contains the input data size in bytes */ + + /* Check if initialization phase has already be performed */ + if (hhash->Phase == DAL_HASH_PHASE_READY) + { + /* Select the HASH algorithm, clear HMAC mode and long key selection bit, reset the HASH processor core */ + MODIFY_REG(HASH->CTRL, HASH_CTRL_LKEYSEL | HASH_CTRL_ALGSEL | HASH_CTRL_MODESEL | HASH_CTRL_INITCAL, Algorithm | HASH_CTRL_INITCAL); + } + + /* Set the phase */ + hhash->Phase = DAL_HASH_PHASE_PROCESS; + + } + + /* Write input buffer in Data register */ + hhash->Status = HASH_WriteData(hhash, pInBuffer_tmp, Size_tmp); + if (hhash->Status != DAL_OK) + { + return hhash->Status; + } + + /* If the process has not been suspended, move the state to Ready */ + if (hhash->State != DAL_HASH_STATE_SUSPENDED) + { + /* Change the HASH state */ + hhash->State = DAL_HASH_STATE_READY; + } + + /* Process Unlocked */ + __DAL_UNLOCK(hhash); + + /* Return function status */ + return DAL_OK; + + } + else + { + return DAL_BUSY; + } + + +} + + +/** + * @brief If not already done, initialize the HASH peripheral then + * processes pInBuffer in interruption mode. + * @note Field hhash->Phase of HASH handle is tested to check whether or not + * the Peripheral has already been initialized. + * @note The input buffer size (in bytes) must be a multiple of 4 otherwise, the + * HASH digest computation is corrupted. + * @param hhash HASH handle. + * @param pInBuffer pointer to the input buffer (buffer to be hashed). + * @param Size length of the input buffer in bytes, must be a multiple of 4. + * @param Algorithm HASH algorithm. + * @retval DAL status + */ +DAL_StatusTypeDef HASH_Accumulate_IT(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, uint32_t Algorithm) +{ + DAL_HASH_StateTypeDef State_tmp = hhash->State; + __IO uint32_t inputaddr = (uint32_t) pInBuffer; + uint32_t SizeVar = Size; + + /* Make sure the input buffer size (in bytes) is a multiple of 4 */ + if ((Size % 4U) != 0U) + { + return DAL_ERROR; + } + + /* Initiate HASH processing in case of start or resumption */ + if ((State_tmp == DAL_HASH_STATE_READY) || (State_tmp == DAL_HASH_STATE_SUSPENDED)) + { + /* Check input parameters */ + if ((pInBuffer == NULL) || (Size == 0U)) + { + hhash->State = DAL_HASH_STATE_READY; + return DAL_ERROR; + } + + /* Process Locked */ + __DAL_LOCK(hhash); + + /* If resuming the HASH processing */ + if (hhash->State == DAL_HASH_STATE_SUSPENDED) + { + /* Change the HASH state */ + hhash->State = DAL_HASH_STATE_BUSY; + } + else + { + /* Change the HASH state */ + hhash->State = DAL_HASH_STATE_BUSY; + + /* Check if initialization phase has already be performed */ + if (hhash->Phase == DAL_HASH_PHASE_READY) + { + /* Select the HASH algorithm, clear HMAC mode and long key selection bit, reset the HASH processor core */ + MODIFY_REG(HASH->CTRL, HASH_CTRL_LKEYSEL | HASH_CTRL_ALGSEL | HASH_CTRL_MODESEL | HASH_CTRL_INITCAL, Algorithm | HASH_CTRL_INITCAL); + hhash->HashITCounter = 1; + } + else + { + hhash->HashITCounter = 3; /* 'cruise-speed' reached during a previous buffer processing */ + } + + /* Set the phase */ + hhash->Phase = DAL_HASH_PHASE_PROCESS; + + /* If DINIS is equal to 0 (for example if an incomplete block has been previously + fed to the Peripheral), the DINIE interruption won't be triggered when DINIE is set. + Therefore, first words are manually entered until DINIS raises, or until there + is not more data to enter. */ + while ((!(__DAL_HASH_GET_FLAG(HASH_FLAG_DINIS))) && (SizeVar > 0U)) + { + + /* Write input data 4 bytes at a time */ + HASH->INDATA = *(uint32_t *)inputaddr; + inputaddr += 4U; + SizeVar -= 4U; + } + + /* If DINIS is still not set or if all the data have been fed, stop here */ + if ((!(__DAL_HASH_GET_FLAG(HASH_FLAG_DINIS))) || (SizeVar == 0U)) + { + /* Change the HASH state */ + hhash->State = DAL_HASH_STATE_READY; + + /* Process Unlock */ + __DAL_UNLOCK(hhash); + + /* Return function status */ + return DAL_OK; + } + + /* otherwise, carry on in interrupt-mode */ + hhash->HashInCount = SizeVar; /* Counter used to keep track of number of data + to be fed to the Peripheral */ + hhash->pHashInBuffPtr = (uint8_t *)inputaddr; /* Points at data which will be fed to the Peripheral at + the next interruption */ + /* In case of suspension, hhash->HashInCount and hhash->pHashInBuffPtr contain + the information describing where the HASH process is stopped. + These variables are used later on to resume the HASH processing at the + correct location. */ + + } + + /* Set multi buffers accumulation flag */ + hhash->Accumulation = 1U; + + /* Process Unlock */ + __DAL_UNLOCK(hhash); + + /* Enable Data Input interrupt */ + __DAL_HASH_ENABLE_IT(HASH_IT_DINI); + + /* Return function status */ + return DAL_OK; + + } + else + { + return DAL_BUSY; + } + +} + + + +/** + * @brief Initialize the HASH peripheral, next process pInBuffer then + * read the computed digest in interruption mode. + * @note Digest is available in pOutBuffer. + * @param hhash HASH handle. + * @param pInBuffer pointer to the input buffer (buffer to be hashed). + * @param Size length of the input buffer in bytes. + * @param pOutBuffer pointer to the computed digest. + * @param Algorithm HASH algorithm. + * @retval DAL status + */ +DAL_StatusTypeDef HASH_Start_IT(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, uint8_t *pOutBuffer, + uint32_t Algorithm) +{ + DAL_HASH_StateTypeDef State_tmp = hhash->State; + __IO uint32_t inputaddr = (uint32_t) pInBuffer; + uint32_t polling_step = 0U; + uint32_t initialization_skipped = 0U; + uint32_t SizeVar = Size; + + /* If State is ready or suspended, start or resume IT-based HASH processing */ + if ((State_tmp == DAL_HASH_STATE_READY) || (State_tmp == DAL_HASH_STATE_SUSPENDED)) + { + /* Check input parameters */ + if ((pInBuffer == NULL) || (Size == 0U) || (pOutBuffer == NULL)) + { + hhash->State = DAL_HASH_STATE_READY; + return DAL_ERROR; + } + + /* Process Locked */ + __DAL_LOCK(hhash); + + /* Change the HASH state */ + hhash->State = DAL_HASH_STATE_BUSY; + + /* Initialize IT counter */ + hhash->HashITCounter = 1; + + /* Check if initialization phase has already be performed */ + if (hhash->Phase == DAL_HASH_PHASE_READY) + { + /* Select the HASH algorithm, clear HMAC mode and long key selection bit, reset the HASH processor core */ + MODIFY_REG(HASH->CTRL, HASH_CTRL_LKEYSEL | HASH_CTRL_ALGSEL | HASH_CTRL_MODESEL | HASH_CTRL_INITCAL, Algorithm | HASH_CTRL_INITCAL); + + /* Configure the number of valid bits in last word of the message */ + __DAL_HASH_SET_NBVALIDBITS(SizeVar); + + + hhash->HashInCount = SizeVar; /* Counter used to keep track of number of data + to be fed to the Peripheral */ + hhash->pHashInBuffPtr = pInBuffer; /* Points at data which will be fed to the Peripheral at + the next interruption */ + /* In case of suspension, hhash->HashInCount and hhash->pHashInBuffPtr contain + the information describing where the HASH process is stopped. + These variables are used later on to resume the HASH processing at the + correct location. */ + + hhash->pHashOutBuffPtr = pOutBuffer; /* Points at the computed digest */ + } + else + { + initialization_skipped = 1; /* info user later on in case of multi-buffer */ + } + + /* Set the phase */ + hhash->Phase = DAL_HASH_PHASE_PROCESS; + + /* If DINIS is equal to 0 (for example if an incomplete block has been previously + fed to the Peripheral), the DINIE interruption won't be triggered when DINIE is set. + Therefore, first words are manually entered until DINIS raises. */ + while ((!(__DAL_HASH_GET_FLAG(HASH_FLAG_DINIS))) && (SizeVar > 3U)) + { + polling_step = 1U; /* note that some words are entered before enabling the interrupt */ + + /* Write input data 4 bytes at a time */ + HASH->INDATA = *(uint32_t *)inputaddr; + inputaddr += 4U; + SizeVar -= 4U; + } + + if (polling_step == 1U) + { + if (SizeVar == 0U) + { + /* If all the data have been entered at this point, it only remains to + read the digest */ + hhash->pHashOutBuffPtr = pOutBuffer; /* Points at the computed digest */ + + /* Start the Digest calculation */ + __DAL_HASH_START_DIGEST(); + /* Process Unlock */ + __DAL_UNLOCK(hhash); + + /* Enable Interrupts */ + __DAL_HASH_ENABLE_IT(HASH_IT_DCI); + + /* Return function status */ + return DAL_OK; + } + else if (__DAL_HASH_GET_FLAG(HASH_FLAG_DINIS)) + { + /* It remains data to enter and the Peripheral is ready to trigger DINIE, + carry on as usual. + Update HashInCount and pHashInBuffPtr accordingly. */ + hhash->HashInCount = SizeVar; + hhash->pHashInBuffPtr = (uint8_t *)inputaddr; + /* Update the configuration of the number of valid bits in last word of the message */ + __DAL_HASH_SET_NBVALIDBITS(SizeVar); + hhash->pHashOutBuffPtr = pOutBuffer; /* Points at the computed digest */ + if (initialization_skipped == 1U) + { + hhash->HashITCounter = 3; /* 'cruise-speed' reached during a previous buffer processing */ + } + } + else + { + /* DINIS is not set but it remains a few data to enter (not enough for a full word). + Manually enter the last bytes before enabling DCIE. */ + __DAL_HASH_SET_NBVALIDBITS(SizeVar); + HASH->INDATA = *(uint32_t *)inputaddr; + + /* Start the Digest calculation */ + hhash->pHashOutBuffPtr = pOutBuffer; /* Points at the computed digest */ + __DAL_HASH_START_DIGEST(); + /* Process Unlock */ + __DAL_UNLOCK(hhash); + + /* Enable Interrupts */ + __DAL_HASH_ENABLE_IT(HASH_IT_DCI); + + /* Return function status */ + return DAL_OK; + } + } /* if (polling_step == 1) */ + + + /* Process Unlock */ + __DAL_UNLOCK(hhash); + + /* Enable Interrupts */ + __DAL_HASH_ENABLE_IT(HASH_IT_DINI | HASH_IT_DCI); + + /* Return function status */ + return DAL_OK; + } + else + { + return DAL_BUSY; + } + +} + + +/** + * @brief Initialize the HASH peripheral then initiate a DMA transfer + * to feed the input buffer to the Peripheral. + * @note If MDMAT bit is set before calling this function (multi-buffer + * HASH processing case), the input buffer size (in bytes) must be + * a multiple of 4 otherwise, the HASH digest computation is corrupted. + * For the processing of the last buffer of the thread, MDMAT bit must + * be reset and the buffer length (in bytes) doesn't have to be a + * multiple of 4. + * @param hhash HASH handle. + * @param pInBuffer pointer to the input buffer (buffer to be hashed). + * @param Size length of the input buffer in bytes. + * @param Algorithm HASH algorithm. + * @retval DAL status + */ +DAL_StatusTypeDef HASH_Start_DMA(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, uint32_t Algorithm) +{ + uint32_t inputaddr; + uint32_t inputSize; + DAL_StatusTypeDef status ; + DAL_HASH_StateTypeDef State_tmp = hhash->State; + +#if defined (HASH_CTRL_MDMAT) + /* Make sure the input buffer size (in bytes) is a multiple of 4 when MDMAT bit is set + (case of multi-buffer HASH processing) */ + ASSERT_PARAM(IS_HASH_DMA_MULTIBUFFER_SIZE(Size)); +#endif /* MDMA defined*/ + /* If State is ready or suspended, start or resume polling-based HASH processing */ + if ((State_tmp == DAL_HASH_STATE_READY) || (State_tmp == DAL_HASH_STATE_SUSPENDED)) + { + /* Check input parameters */ + if ((pInBuffer == NULL) || (Size == 0U) || + /* Check phase coherency. Phase must be + either READY (fresh start) + or PROCESS (multi-buffer HASH management) */ + ((hhash->Phase != DAL_HASH_PHASE_READY) && (!(IS_HASH_PROCESSING(hhash))))) + { + hhash->State = DAL_HASH_STATE_READY; + return DAL_ERROR; + } + + + /* Process Locked */ + __DAL_LOCK(hhash); + + /* If not a resumption case */ + if (hhash->State == DAL_HASH_STATE_READY) + { + /* Change the HASH state */ + hhash->State = DAL_HASH_STATE_BUSY; + + /* Check if initialization phase has already been performed. + If Phase is already set to DAL_HASH_PHASE_PROCESS, this means the + API is processing a new input data message in case of multi-buffer HASH + computation. */ + if (hhash->Phase == DAL_HASH_PHASE_READY) + { + /* Select the HASH algorithm, clear HMAC mode and long key selection bit, reset the HASH processor core */ + MODIFY_REG(HASH->CTRL, HASH_CTRL_LKEYSEL | HASH_CTRL_ALGSEL | HASH_CTRL_MODESEL | HASH_CTRL_INITCAL, Algorithm | HASH_CTRL_INITCAL); + + /* Set the phase */ + hhash->Phase = DAL_HASH_PHASE_PROCESS; + } + + /* Configure the Number of valid bits in last word of the message */ + __DAL_HASH_SET_NBVALIDBITS(Size); + + inputaddr = (uint32_t)pInBuffer; /* DMA transfer start address */ + inputSize = Size; /* DMA transfer size (in bytes) */ + + /* In case of suspension request, save the starting parameters */ + hhash->pHashInBuffPtr = pInBuffer; /* DMA transfer start address */ + hhash->HashInCount = Size; /* DMA transfer size (in bytes) */ + + } + /* If resumption case */ + else + { + /* Change the HASH state */ + hhash->State = DAL_HASH_STATE_BUSY; + + /* Resumption case, inputaddr and inputSize are not set to the API input parameters + but to those saved beforehand by DAL_HASH_DMAFeed_ProcessSuspend() when the + processing was suspended */ + inputaddr = (uint32_t)hhash->pHashInBuffPtr; /* DMA transfer start address */ + inputSize = hhash->HashInCount; /* DMA transfer size (in bytes) */ + + } + + /* Set the HASH DMA transfer complete callback */ + hhash->hdmain->XferCpltCallback = HASH_DMAXferCplt; + /* Set the DMA error callback */ + hhash->hdmain->XferErrorCallback = HASH_DMAError; + + /* Store number of words already pushed to manage proper DMA processing suspension */ + hhash->NbWordsAlreadyPushed = HASH_NBW_PUSHED(); + + /* Enable the DMA In DMA stream */ + status = DAL_DMA_Start_IT(hhash->hdmain, inputaddr, (uint32_t)&HASH->INDATA, \ + (((inputSize % 4U) != 0U) ? ((inputSize + (4U - (inputSize % 4U))) / 4U) : \ + (inputSize / 4U))); + + /* Enable DMA requests */ + SET_BIT(HASH->CTRL, HASH_CTRL_DMAEN); + + /* Process Unlock */ + __DAL_UNLOCK(hhash); + + /* Return function status */ + if (status != DAL_OK) + { + /* Update HASH state machine to error */ + hhash->State = DAL_HASH_STATE_ERROR; + } + + return status; + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief Return the computed digest. + * @note The API waits for DCIS to be set then reads the computed digest. + * @param hhash HASH handle. + * @param pOutBuffer pointer to the computed digest. + * @param Timeout Timeout value. + * @retval DAL status + */ +DAL_StatusTypeDef HASH_Finish(HASH_HandleTypeDef *hhash, uint8_t *pOutBuffer, uint32_t Timeout) +{ + + if (hhash->State == DAL_HASH_STATE_READY) + { + /* Check parameter */ + if (pOutBuffer == NULL) + { + return DAL_ERROR; + } + + /* Process Locked */ + __DAL_LOCK(hhash); + + /* Change the HASH state to busy */ + hhash->State = DAL_HASH_STATE_BUSY; + + /* Wait for DCIS flag to be set */ + if (HASH_WaitOnFlagUntilTimeout(hhash, HASH_FLAG_DCIS, RESET, Timeout) != DAL_OK) + { + return DAL_TIMEOUT; + } + + /* Read the message digest */ + HASH_GetDigest(pOutBuffer, HASH_DIGEST_LENGTH()); + + /* Change the HASH state to ready */ + hhash->State = DAL_HASH_STATE_READY; + + /* Reset HASH state machine */ + hhash->Phase = DAL_HASH_PHASE_READY; + + /* Process UnLock */ + __DAL_UNLOCK(hhash); + + /* Return function status */ + return DAL_OK; + + } + else + { + return DAL_BUSY; + } + +} + + +/** + * @brief Initialize the HASH peripheral in HMAC mode, next process pInBuffer then + * read the computed digest. + * @note Digest is available in pOutBuffer. + * @note Same key is used for the inner and the outer hash functions; pointer to key and + * key size are respectively stored in hhash->Init.pKey and hhash->Init.KeySize. + * @param hhash HASH handle. + * @param pInBuffer pointer to the input buffer (buffer to be hashed). + * @param Size length of the input buffer in bytes. + * @param pOutBuffer pointer to the computed digest. + * @param Timeout Timeout value. + * @param Algorithm HASH algorithm. + * @retval DAL status + */ +DAL_StatusTypeDef HMAC_Start(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, uint8_t *pOutBuffer, + uint32_t Timeout, uint32_t Algorithm) +{ + DAL_HASH_StateTypeDef State_tmp = hhash->State; + + /* If State is ready or suspended, start or resume polling-based HASH processing */ + if ((State_tmp == DAL_HASH_STATE_READY) || (State_tmp == DAL_HASH_STATE_SUSPENDED)) + { + /* Check input parameters */ + if ((pInBuffer == NULL) || (Size == 0U) || (hhash->Init.pKey == NULL) || (hhash->Init.KeySize == 0U) + || (pOutBuffer == NULL)) + { + hhash->State = DAL_HASH_STATE_READY; + return DAL_ERROR; + } + + /* Process Locked */ + __DAL_LOCK(hhash); + + /* Change the HASH state */ + hhash->State = DAL_HASH_STATE_BUSY; + + /* Check if initialization phase has already be performed */ + if (hhash->Phase == DAL_HASH_PHASE_READY) + { + /* Check if key size is larger than 64 bytes, accordingly set LKEY and the other setting bits */ + if (hhash->Init.KeySize > 64U) + { + MODIFY_REG(HASH->CTRL, HASH_CTRL_LKEYSEL | HASH_CTRL_ALGSEL | HASH_CTRL_MODESEL | HASH_CTRL_INITCAL, + Algorithm | HASH_ALGOMODE_HMAC | HASH_HMAC_KEYTYPE_LONGKEY | HASH_CTRL_INITCAL); + } + else + { + MODIFY_REG(HASH->CTRL, HASH_CTRL_LKEYSEL | HASH_CTRL_ALGSEL | HASH_CTRL_MODESEL | HASH_CTRL_INITCAL, + Algorithm | HASH_ALGOMODE_HMAC | HASH_CTRL_INITCAL); + } + /* Set the phase to Step 1 */ + hhash->Phase = DAL_HASH_PHASE_HMAC_STEP_1; + /* Resort to hhash internal fields to feed the Peripheral. + Parameters will be updated in case of suspension to contain the proper + information at resumption time. */ + hhash->pHashOutBuffPtr = pOutBuffer; /* Output digest address */ + hhash->pHashInBuffPtr = pInBuffer; /* Input data address, HMAC_Processing input + parameter for Step 2 */ + hhash->HashInCount = Size; /* Input data size, HMAC_Processing input + parameter for Step 2 */ + hhash->HashBuffSize = Size; /* Store the input buffer size for the whole HMAC process*/ + hhash->pHashKeyBuffPtr = hhash->Init.pKey; /* Key address, HMAC_Processing input parameter for Step + 1 and Step 3 */ + hhash->HashKeyCount = hhash->Init.KeySize; /* Key size, HMAC_Processing input parameter for Step 1 + and Step 3 */ + } + + /* Carry out HMAC processing */ + return HMAC_Processing(hhash, Timeout); + + } + else + { + return DAL_BUSY; + } +} + + + +/** + * @brief Initialize the HASH peripheral in HMAC mode, next process pInBuffer then + * read the computed digest in interruption mode. + * @note Digest is available in pOutBuffer. + * @note Same key is used for the inner and the outer hash functions; pointer to key and + * key size are respectively stored in hhash->Init.pKey and hhash->Init.KeySize. + * @param hhash HASH handle. + * @param pInBuffer pointer to the input buffer (buffer to be hashed). + * @param Size length of the input buffer in bytes. + * @param pOutBuffer pointer to the computed digest. + * @param Algorithm HASH algorithm. + * @retval DAL status + */ +DAL_StatusTypeDef HMAC_Start_IT(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, uint8_t *pOutBuffer, + uint32_t Algorithm) +{ + DAL_HASH_StateTypeDef State_tmp = hhash->State; + + /* If State is ready or suspended, start or resume IT-based HASH processing */ + if ((State_tmp == DAL_HASH_STATE_READY) || (State_tmp == DAL_HASH_STATE_SUSPENDED)) + { + /* Check input parameters */ + if ((pInBuffer == NULL) || (Size == 0U) || (hhash->Init.pKey == NULL) || (hhash->Init.KeySize == 0U) + || (pOutBuffer == NULL)) + { + hhash->State = DAL_HASH_STATE_READY; + return DAL_ERROR; + } + + /* Process Locked */ + __DAL_LOCK(hhash); + + /* Change the HASH state */ + hhash->State = DAL_HASH_STATE_BUSY; + + /* Initialize IT counter */ + hhash->HashITCounter = 1; + + /* Check if initialization phase has already be performed */ + if (hhash->Phase == DAL_HASH_PHASE_READY) + { + /* Check if key size is larger than 64 bytes, accordingly set LKEY and the other setting bits */ + if (hhash->Init.KeySize > 64U) + { + MODIFY_REG(HASH->CTRL, HASH_CTRL_LKEYSEL | HASH_CTRL_ALGSEL | HASH_CTRL_MODESEL | HASH_CTRL_INITCAL, + Algorithm | HASH_ALGOMODE_HMAC | HASH_HMAC_KEYTYPE_LONGKEY | HASH_CTRL_INITCAL); + } + else + { + MODIFY_REG(HASH->CTRL, HASH_CTRL_LKEYSEL | HASH_CTRL_ALGSEL | HASH_CTRL_MODESEL | HASH_CTRL_INITCAL, + Algorithm | HASH_ALGOMODE_HMAC | HASH_CTRL_INITCAL); + } + + /* Resort to hhash internal fields hhash->pHashInBuffPtr and hhash->HashInCount + to feed the Peripheral whatever the HMAC step. + Lines below are set to start HMAC Step 1 processing where key is entered first. */ + hhash->HashInCount = hhash->Init.KeySize; /* Key size */ + hhash->pHashInBuffPtr = hhash->Init.pKey ; /* Key address */ + + /* Store input and output parameters in handle fields to manage steps transition + or possible HMAC suspension/resumption */ + hhash->pHashKeyBuffPtr = hhash->Init.pKey; /* Key address */ + hhash->pHashMsgBuffPtr = pInBuffer; /* Input message address */ + hhash->HashBuffSize = Size; /* Input message size (in bytes) */ + hhash->pHashOutBuffPtr = pOutBuffer; /* Output digest address */ + + /* Configure the number of valid bits in last word of the key */ + __DAL_HASH_SET_NBVALIDBITS(hhash->Init.KeySize); + + /* Set the phase to Step 1 */ + hhash->Phase = DAL_HASH_PHASE_HMAC_STEP_1; + } + else if ((hhash->Phase == DAL_HASH_PHASE_HMAC_STEP_1) || (hhash->Phase == DAL_HASH_PHASE_HMAC_STEP_3)) + { + /* Restart IT-based HASH processing after Step 1 or Step 3 suspension */ + + } + else if (hhash->Phase == DAL_HASH_PHASE_HMAC_STEP_2) + { + /* Restart IT-based HASH processing after Step 2 suspension */ + + } + else + { + /* Error report as phase incorrect */ + /* Process Unlock */ + __DAL_UNLOCK(hhash); + hhash->State = DAL_HASH_STATE_READY; + return DAL_ERROR; + } + + /* Process Unlock */ + __DAL_UNLOCK(hhash); + + /* Enable Interrupts */ + __DAL_HASH_ENABLE_IT(HASH_IT_DINI | HASH_IT_DCI); + + /* Return function status */ + return DAL_OK; + } + else + { + return DAL_BUSY; + } + +} + + + +/** + * @brief Initialize the HASH peripheral in HMAC mode then initiate the required + * DMA transfers to feed the key and the input buffer to the Peripheral. + * @note Same key is used for the inner and the outer hash functions; pointer to key and + * key size are respectively stored in hhash->Init.pKey and hhash->Init.KeySize. + * @note In case of multi-buffer HMAC processing, the input buffer size (in bytes) must + * be a multiple of 4 otherwise, the HASH digest computation is corrupted. + * Only the length of the last buffer of the thread doesn't have to be a + * multiple of 4. + * @param hhash HASH handle. + * @param pInBuffer pointer to the input buffer (buffer to be hashed). + * @param Size length of the input buffer in bytes. + * @param Algorithm HASH algorithm. + * @retval DAL status + */ +DAL_StatusTypeDef HMAC_Start_DMA(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, uint32_t Algorithm) +{ + uint32_t inputaddr; + uint32_t inputSize; + DAL_StatusTypeDef status ; + DAL_HASH_StateTypeDef State_tmp = hhash->State; + /* Make sure the input buffer size (in bytes) is a multiple of 4 when digest calculation + is disabled (multi-buffer HMAC processing, MDMAT bit to be set) */ + ASSERT_PARAM(IS_HMAC_DMA_MULTIBUFFER_SIZE(hhash, Size)); + /* If State is ready or suspended, start or resume DMA-based HASH processing */ + if ((State_tmp == DAL_HASH_STATE_READY) || (State_tmp == DAL_HASH_STATE_SUSPENDED)) + { + /* Check input parameters */ + if ((pInBuffer == NULL) || (Size == 0U) || (hhash->Init.pKey == NULL) || (hhash->Init.KeySize == 0U) || + /* Check phase coherency. Phase must be + either READY (fresh start) + or one of HMAC PROCESS steps (multi-buffer HASH management) */ + ((hhash->Phase != DAL_HASH_PHASE_READY) && (!(IS_HMAC_PROCESSING(hhash))))) + { + hhash->State = DAL_HASH_STATE_READY; + return DAL_ERROR; + } + + + /* Process Locked */ + __DAL_LOCK(hhash); + + /* If not a case of resumption after suspension */ + if (hhash->State == DAL_HASH_STATE_READY) + { + /* Check whether or not initialization phase has already be performed */ + if (hhash->Phase == DAL_HASH_PHASE_READY) + { + /* Change the HASH state */ + hhash->State = DAL_HASH_STATE_BUSY; +#if defined(HASH_CTRL_MDMAT) + /* Check if key size is larger than 64 bytes, accordingly set LKEY and the other setting bits. + At the same time, ensure MDMAT bit is cleared. */ + if (hhash->Init.KeySize > 64U) + { + MODIFY_REG(HASH->CTRL, HASH_CTRL_MDMAT | HASH_CTRL_LKEYSEL | HASH_CTRL_ALGSEL | HASH_CTRL_MODESEL | HASH_CTRL_INITCAL, + Algorithm | HASH_ALGOMODE_HMAC | HASH_HMAC_KEYTYPE_LONGKEY | HASH_CTRL_INITCAL); + } + else + { + MODIFY_REG(HASH->CTRL, HASH_CTRL_MDMAT | HASH_CTRL_LKEYSEL | HASH_CTRL_ALGSEL | HASH_CTRL_MODESEL | HASH_CTRL_INITCAL, + Algorithm | HASH_ALGOMODE_HMAC | HASH_CTRL_INITCAL); + } +#else + /* Check if key size is larger than 64 bytes, accordingly set LKEY and the other setting bits */ + if (hhash->Init.KeySize > 64U) + { + MODIFY_REG(HASH->CTRL, HASH_CTRL_LKEYSEL | HASH_CTRL_ALGSEL | HASH_CTRL_MODESEL | HASH_CTRL_INITCAL, + Algorithm | HASH_ALGOMODE_HMAC | HASH_HMAC_KEYTYPE_LONGKEY | HASH_CTRL_INITCAL); + } + else + { + MODIFY_REG(HASH->CTRL, HASH_CTRL_LKEYSEL | HASH_CTRL_ALGSEL | HASH_CTRL_MODESEL | HASH_CTRL_INITCAL, + Algorithm | HASH_ALGOMODE_HMAC | HASH_CTRL_INITCAL); + } +#endif /* HASH_CTRL_MDMAT*/ + /* Store input aparameters in handle fields to manage steps transition + or possible HMAC suspension/resumption */ + hhash->HashInCount = hhash->Init.KeySize; /* Initial size for first DMA transfer (key size) */ + hhash->pHashKeyBuffPtr = hhash->Init.pKey; /* Key address */ + hhash->pHashInBuffPtr = hhash->Init.pKey ; /* First address passed to DMA (key address at Step 1) */ + hhash->pHashMsgBuffPtr = pInBuffer; /* Input data address */ + hhash->HashBuffSize = Size; /* input data size (in bytes) */ + + /* Set DMA input parameters */ + inputaddr = (uint32_t)(hhash->Init.pKey); /* Address passed to DMA (start by entering Key message) */ + inputSize = hhash->Init.KeySize; /* Size for first DMA transfer (in bytes) */ + + /* Configure the number of valid bits in last word of the key */ + __DAL_HASH_SET_NBVALIDBITS(hhash->Init.KeySize); + + /* Set the phase to Step 1 */ + hhash->Phase = DAL_HASH_PHASE_HMAC_STEP_1; + + } + else if (hhash->Phase == DAL_HASH_PHASE_HMAC_STEP_2) + { + /* Process a new input data message in case of multi-buffer HMAC processing + (this is not a resumption case) */ + + /* Change the HASH state */ + hhash->State = DAL_HASH_STATE_BUSY; + + /* Save input parameters to be able to manage possible suspension/resumption */ + hhash->HashInCount = Size; /* Input message address */ + hhash->pHashInBuffPtr = pInBuffer; /* Input message size in bytes */ + + /* Set DMA input parameters */ + inputaddr = (uint32_t)pInBuffer; /* Input message address */ + inputSize = Size; /* Input message size in bytes */ + + if (hhash->DigestCalculationDisable == RESET) + { + /* This means this is the last buffer of the multi-buffer sequence: DCAL needs to be set. */ +#if defined(HASH_CTRL_MDMAT) + __DAL_HASH_RESET_MDMAT(); +#endif /* HASH_CTRL_MDMAT*/ + __DAL_HASH_SET_NBVALIDBITS(inputSize); + } + } + else + { + /* Phase not aligned with handle READY state */ + __DAL_UNLOCK(hhash); + /* Return function status */ + return DAL_ERROR; + } + } + else + { + /* Resumption case (phase may be Step 1, 2 or 3) */ + + /* Change the HASH state */ + hhash->State = DAL_HASH_STATE_BUSY; + + /* Set DMA input parameters at resumption location; + inputaddr and inputSize are not set to the API input parameters + but to those saved beforehand by DAL_HASH_DMAFeed_ProcessSuspend() when the + processing was suspended. */ + inputaddr = (uint32_t)(hhash->pHashInBuffPtr); /* Input message address */ + inputSize = hhash->HashInCount; /* Input message size in bytes */ + } + + + /* Set the HASH DMA transfer complete callback */ + hhash->hdmain->XferCpltCallback = HASH_DMAXferCplt; + /* Set the DMA error callback */ + hhash->hdmain->XferErrorCallback = HASH_DMAError; + + /* Store number of words already pushed to manage proper DMA processing suspension */ + hhash->NbWordsAlreadyPushed = HASH_NBW_PUSHED(); + + /* Enable the DMA In DMA stream */ + status = DAL_DMA_Start_IT(hhash->hdmain, inputaddr, (uint32_t)&HASH->INDATA, \ + (((inputSize % 4U) != 0U) ? ((inputSize + (4U - (inputSize % 4U))) / 4U) \ + : (inputSize / 4U))); + + /* Enable DMA requests */ + SET_BIT(HASH->CTRL, HASH_CTRL_DMAEN); + + /* Process Unlocked */ + __DAL_UNLOCK(hhash); + + /* Return function status */ + if (status != DAL_OK) + { + /* Update HASH state machine to error */ + hhash->State = DAL_HASH_STATE_ERROR; + } + + /* Return function status */ + return status; + } + else + { + return DAL_BUSY; + } +} +/** + * @} + */ + +#endif /* DAL_HASH_MODULE_ENABLED */ + +/** + * @} + */ +#endif /* HASH*/ +/** + * @} + */ + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_hash_ex.c b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_hash_ex.c new file mode 100644 index 0000000000..e5856a57f2 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_hash_ex.c @@ -0,0 +1,1065 @@ +/** + * + * @file apm32f4xx_dal_hash_ex.c + * @brief Extended HASH DAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the HASH peripheral for SHA-224 and SHA-256 + * algorithms: + * + HASH or HMAC processing in polling mode + * + HASH or HMAC processing in interrupt mode + * + HASH or HMAC processing in DMA mode + * Additionally, this file provides functions to manage HMAC + * multi-buffer DMA-based processing for MD-5, SHA-1, SHA-224 + * and SHA-256. + * + * + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + * + @verbatim + =============================================================================== + ##### HASH peripheral extended features ##### + =============================================================================== + [..] + The SHA-224 and SHA-256 HASH and HMAC processing can be carried out exactly + the same way as for SHA-1 or MD-5 algorithms. + (#) Three modes are available. + (##) Polling mode: processing APIs are blocking functions + i.e. they process the data and wait till the digest computation is finished, + e.g. DAL_HASHEx_xxx_Start() + (##) Interrupt mode: processing APIs are not blocking functions + i.e. they process the data under interrupt, + e.g. DAL_HASHEx_xxx_Start_IT() + (##) DMA mode: processing APIs are not blocking functions and the CPU is + not used for data transfer i.e. the data transfer is ensured by DMA, + e.g. DAL_HASHEx_xxx_Start_DMA(). Note that in DMA mode, a call to + DAL_HASHEx_xxx_Finish() is then required to retrieve the digest. + + (#)Multi-buffer processing is possible in polling, interrupt and DMA modes. + (##) In polling mode, only multi-buffer HASH processing is possible. + API DAL_HASHEx_xxx_Accumulate() must be called for each input buffer, except for the last one. + User must resort to DAL_HASHEx_xxx_Accumulate_End() to enter the last one and retrieve as + well the computed digest. + + (##) In interrupt mode, API DAL_HASHEx_xxx_Accumulate_IT() must be called for each input buffer, + except for the last one. + User must resort to DAL_HASHEx_xxx_Accumulate_End_IT() to enter the last one and retrieve as + well the computed digest. + + (##) In DMA mode, multi-buffer HASH and HMAC processing are possible. + + (+++) HASH processing: once initialization is done, MDMAT bit must be set through + __DAL_HASH_SET_MDMAT() macro. + From that point, each buffer can be fed to the Peripheral through DAL_HASHEx_xxx_Start_DMA() API. + Before entering the last buffer, reset the MDMAT bit with __DAL_HASH_RESET_MDMAT() + macro then wrap-up the HASH processing in feeding the last input buffer through the + same API DAL_HASHEx_xxx_Start_DMA(). The digest can then be retrieved with a call to + API DAL_HASHEx_xxx_Finish(). + + (+++) HMAC processing (MD-5, SHA-1, SHA-224 and SHA-256 must all resort to + extended functions): after initialization, the key and the first input buffer are entered + in the Peripheral with the API DAL_HMACEx_xxx_Step1_2_DMA(). This carries out HMAC step 1 and + starts step 2. + The following buffers are next entered with the API DAL_HMACEx_xxx_Step2_DMA(). At this + point, the HMAC processing is still carrying out step 2. + Then, step 2 for the last input buffer and step 3 are carried out by a single call + to DAL_HMACEx_xxx_Step2_3_DMA(). + + The digest can finally be retrieved with a call to API DAL_HASH_xxx_Finish() for + MD-5 and SHA-1, to DAL_HASHEx_xxx_Finish() for SHA-224 and SHA-256. + + + @endverbatim + * + */ + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal.h" + + + + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ +#if defined (HASH) + +/** @defgroup HASHEx HASHEx + * @brief HASH DAL extended module driver. + * @{ + */ +#ifdef DAL_HASH_MODULE_ENABLED +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ +#if defined (HASH_CTRL_MDMAT) + +/** @defgroup HASHEx_Exported_Functions HASH Extended Exported Functions + * @{ + */ + +/** @defgroup HASHEx_Exported_Functions_Group1 HASH extended processing functions in polling mode + * @brief HASH extended processing functions using polling mode. + * +@verbatim + =============================================================================== + ##### Polling mode HASH extended processing functions ##### + =============================================================================== + [..] This section provides functions allowing to calculate in polling mode + the hash value using one of the following algorithms: + (+) SHA224 + (++) DAL_HASHEx_SHA224_Start() + (++) DAL_HASHEx_SHA224_Accmlt() + (++) DAL_HASHEx_SHA224_Accmlt_End() + (+) SHA256 + (++) DAL_HASHEx_SHA256_Start() + (++) DAL_HASHEx_SHA256_Accmlt() + (++) DAL_HASHEx_SHA256_Accmlt_End() + + [..] For a single buffer to be hashed, user can resort to DAL_HASH_xxx_Start(). + + [..] In case of multi-buffer HASH processing (a single digest is computed while + several buffers are fed to the Peripheral), the user can resort to successive calls + to DAL_HASHEx_xxx_Accumulate() and wrap-up the digest computation by a call + to DAL_HASHEx_xxx_Accumulate_End(). + +@endverbatim + * @{ + */ + + +/** + * @brief Initialize the HASH peripheral in SHA224 mode, next process pInBuffer then + * read the computed digest. + * @note Digest is available in pOutBuffer. + * @param hhash HASH handle. + * @param pInBuffer pointer to the input buffer (buffer to be hashed). + * @param Size length of the input buffer in bytes. + * @param pOutBuffer pointer to the computed digest. Digest size is 28 bytes. + * @param Timeout Timeout value + * @retval DAL status + */ +DAL_StatusTypeDef DAL_HASHEx_SHA224_Start(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, + uint8_t *pOutBuffer, uint32_t Timeout) +{ + return HASH_Start(hhash, pInBuffer, Size, pOutBuffer, Timeout, HASH_ALGOSELECTION_SHA224); +} + +/** + * @brief If not already done, initialize the HASH peripheral in SHA224 mode then + * processes pInBuffer. + * @note Consecutive calls to DAL_HASHEx_SHA224_Accmlt() can be used to feed + * several input buffers back-to-back to the Peripheral that will yield a single + * HASH signature once all buffers have been entered. Wrap-up of input + * buffers feeding and retrieval of digest is done by a call to + * DAL_HASHEx_SHA224_Accmlt_End(). + * @note Field hhash->Phase of HASH handle is tested to check whether or not + * the Peripheral has already been initialized. + * @note Digest is not retrieved by this API, user must resort to DAL_HASHEx_SHA224_Accmlt_End() + * to read it, feeding at the same time the last input buffer to the Peripheral. + * @note The input buffer size (in bytes) must be a multiple of 4 otherwise, the + * HASH digest computation is corrupted. Only DAL_HASHEx_SHA224_Accmlt_End() is able + * to manage the ending buffer with a length in bytes not a multiple of 4. + * @param hhash HASH handle. + * @param pInBuffer pointer to the input buffer (buffer to be hashed). + * @param Size length of the input buffer in bytes, must be a multiple of 4. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_HASHEx_SHA224_Accmlt(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size) +{ + return HASH_Accumulate(hhash, pInBuffer, Size, HASH_ALGOSELECTION_SHA224); +} + +/** + * @brief End computation of a single HASH signature after several calls to DAL_HASHEx_SHA224_Accmlt() API. + * @note Digest is available in pOutBuffer. + * @param hhash HASH handle. + * @param pInBuffer pointer to the input buffer (buffer to be hashed). + * @param Size length of the input buffer in bytes. + * @param pOutBuffer pointer to the computed digest. Digest size is 28 bytes. + * @param Timeout Timeout value + * @retval DAL status + */ +DAL_StatusTypeDef DAL_HASHEx_SHA224_Accmlt_End(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, + uint8_t *pOutBuffer, uint32_t Timeout) +{ + return HASH_Start(hhash, pInBuffer, Size, pOutBuffer, Timeout, HASH_ALGOSELECTION_SHA224); +} + +/** + * @brief Initialize the HASH peripheral in SHA256 mode, next process pInBuffer then + * read the computed digest. + * @note Digest is available in pOutBuffer. + * @param hhash HASH handle. + * @param pInBuffer pointer to the input buffer (buffer to be hashed). + * @param Size length of the input buffer in bytes. + * @param pOutBuffer pointer to the computed digest. Digest size is 32 bytes. + * @param Timeout Timeout value + * @retval DAL status + */ +DAL_StatusTypeDef DAL_HASHEx_SHA256_Start(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, + uint8_t *pOutBuffer, uint32_t Timeout) +{ + return HASH_Start(hhash, pInBuffer, Size, pOutBuffer, Timeout, HASH_ALGOSELECTION_SHA256); +} + +/** + * @brief If not already done, initialize the HASH peripheral in SHA256 mode then + * processes pInBuffer. + * @note Consecutive calls to DAL_HASHEx_SHA256_Accmlt() can be used to feed + * several input buffers back-to-back to the Peripheral that will yield a single + * HASH signature once all buffers have been entered. Wrap-up of input + * buffers feeding and retrieval of digest is done by a call to + * DAL_HASHEx_SHA256_Accmlt_End(). + * @note Field hhash->Phase of HASH handle is tested to check whether or not + * the Peripheral has already been initialized. + * @note Digest is not retrieved by this API, user must resort to DAL_HASHEx_SHA256_Accmlt_End() + * to read it, feeding at the same time the last input buffer to the Peripheral. + * @note The input buffer size (in bytes) must be a multiple of 4 otherwise, the + * HASH digest computation is corrupted. Only DAL_HASHEx_SHA256_Accmlt_End() is able + * to manage the ending buffer with a length in bytes not a multiple of 4. + * @param hhash HASH handle. + * @param pInBuffer pointer to the input buffer (buffer to be hashed). + * @param Size length of the input buffer in bytes, must be a multiple of 4. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_HASHEx_SHA256_Accmlt(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size) +{ + return HASH_Accumulate(hhash, pInBuffer, Size, HASH_ALGOSELECTION_SHA256); +} + +/** + * @brief End computation of a single HASH signature after several calls to DAL_HASHEx_SHA256_Accmlt() API. + * @note Digest is available in pOutBuffer. + * @param hhash HASH handle. + * @param pInBuffer pointer to the input buffer (buffer to be hashed). + * @param Size length of the input buffer in bytes. + * @param pOutBuffer pointer to the computed digest. Digest size is 32 bytes. + * @param Timeout Timeout value + * @retval DAL status + */ +DAL_StatusTypeDef DAL_HASHEx_SHA256_Accmlt_End(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, + uint8_t *pOutBuffer, uint32_t Timeout) +{ + return HASH_Start(hhash, pInBuffer, Size, pOutBuffer, Timeout, HASH_ALGOSELECTION_SHA256); +} + +/** + * @} + */ + +/** @defgroup HASHEx_Exported_Functions_Group2 HASH extended processing functions in interrupt mode + * @brief HASH extended processing functions using interrupt mode. + * +@verbatim + =============================================================================== + ##### Interruption mode HASH extended processing functions ##### + =============================================================================== + [..] This section provides functions allowing to calculate in interrupt mode + the hash value using one of the following algorithms: + (+) SHA224 + (++) DAL_HASHEx_SHA224_Start_IT() + (++) DAL_HASHEx_SHA224_Accmlt_IT() + (++) DAL_HASHEx_SHA224_Accmlt_End_IT() + (+) SHA256 + (++) DAL_HASHEx_SHA256_Start_IT() + (++) DAL_HASHEx_SHA256_Accmlt_IT() + (++) DAL_HASHEx_SHA256_Accmlt_End_IT() + +@endverbatim + * @{ + */ + + +/** + * @brief Initialize the HASH peripheral in SHA224 mode, next process pInBuffer then + * read the computed digest in interruption mode. + * @note Digest is available in pOutBuffer. + * @param hhash HASH handle. + * @param pInBuffer pointer to the input buffer (buffer to be hashed). + * @param Size length of the input buffer in bytes. + * @param pOutBuffer pointer to the computed digest. Digest size is 28 bytes. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_HASHEx_SHA224_Start_IT(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, + uint8_t *pOutBuffer) +{ + return HASH_Start_IT(hhash, pInBuffer, Size, pOutBuffer, HASH_ALGOSELECTION_SHA224); +} + +/** + * @brief If not already done, initialize the HASH peripheral in SHA224 mode then + * processes pInBuffer in interruption mode. + * @note Consecutive calls to DAL_HASHEx_SHA224_Accmlt_IT() can be used to feed + * several input buffers back-to-back to the Peripheral that will yield a single + * HASH signature once all buffers have been entered. Wrap-up of input + * buffers feeding and retrieval of digest is done by a call to + * DAL_HASHEx_SHA224_Accmlt_End_IT(). + * @note Field hhash->Phase of HASH handle is tested to check whether or not + * the Peripheral has already been initialized. + * @note The input buffer size (in bytes) must be a multiple of 4 otherwise, the + * HASH digest computation is corrupted. Only DAL_HASHEx_SHA224_Accmlt_End_IT() is able + * to manage the ending buffer with a length in bytes not a multiple of 4. + * @param hhash HASH handle. + * @param pInBuffer pointer to the input buffer (buffer to be hashed). + * @param Size length of the input buffer in bytes, must be a multiple of 4. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_HASHEx_SHA224_Accmlt_IT(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size) +{ + return HASH_Accumulate_IT(hhash, pInBuffer, Size, HASH_ALGOSELECTION_SHA224); +} + +/** + * @brief End computation of a single HASH signature after several calls to DAL_HASHEx_SHA224_Accmlt_IT() API. + * @note Digest is available in pOutBuffer. + * @param hhash HASH handle. + * @param pInBuffer pointer to the input buffer (buffer to be hashed). + * @param Size length of the input buffer in bytes. + * @param pOutBuffer pointer to the computed digest. Digest size is 28 bytes. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_HASHEx_SHA224_Accmlt_End_IT(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, + uint8_t *pOutBuffer) +{ + return HASH_Start_IT(hhash, pInBuffer, Size, pOutBuffer, HASH_ALGOSELECTION_SHA224); +} + +/** + * @brief Initialize the HASH peripheral in SHA256 mode, next process pInBuffer then + * read the computed digest in interruption mode. + * @note Digest is available in pOutBuffer. + * @param hhash HASH handle. + * @param pInBuffer pointer to the input buffer (buffer to be hashed). + * @param Size length of the input buffer in bytes. + * @param pOutBuffer pointer to the computed digest. Digest size is 32 bytes. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_HASHEx_SHA256_Start_IT(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, + uint8_t *pOutBuffer) +{ + return HASH_Start_IT(hhash, pInBuffer, Size, pOutBuffer, HASH_ALGOSELECTION_SHA256); +} + +/** + * @brief If not already done, initialize the HASH peripheral in SHA256 mode then + * processes pInBuffer in interruption mode. + * @note Consecutive calls to DAL_HASHEx_SHA256_Accmlt_IT() can be used to feed + * several input buffers back-to-back to the Peripheral that will yield a single + * HASH signature once all buffers have been entered. Wrap-up of input + * buffers feeding and retrieval of digest is done by a call to + * DAL_HASHEx_SHA256_Accmlt_End_IT(). + * @note Field hhash->Phase of HASH handle is tested to check whether or not + * the Peripheral has already been initialized. + * @note The input buffer size (in bytes) must be a multiple of 4 otherwise, the + * HASH digest computation is corrupted. Only DAL_HASHEx_SHA256_Accmlt_End_IT() is able + * to manage the ending buffer with a length in bytes not a multiple of 4. + * @param hhash HASH handle. + * @param pInBuffer pointer to the input buffer (buffer to be hashed). + * @param Size length of the input buffer in bytes, must be a multiple of 4. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_HASHEx_SHA256_Accmlt_IT(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size) +{ + return HASH_Accumulate_IT(hhash, pInBuffer, Size, HASH_ALGOSELECTION_SHA256); +} + +/** + * @brief End computation of a single HASH signature after several calls to DAL_HASHEx_SHA256_Accmlt_IT() API. + * @note Digest is available in pOutBuffer. + * @param hhash HASH handle. + * @param pInBuffer pointer to the input buffer (buffer to be hashed). + * @param Size length of the input buffer in bytes. + * @param pOutBuffer pointer to the computed digest. Digest size is 32 bytes. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_HASHEx_SHA256_Accmlt_End_IT(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, + uint8_t *pOutBuffer) +{ + return HASH_Start_IT(hhash, pInBuffer, Size, pOutBuffer, HASH_ALGOSELECTION_SHA256); +} + +/** + * @} + */ + +/** @defgroup HASHEx_Exported_Functions_Group3 HASH extended processing functions in DMA mode + * @brief HASH extended processing functions using DMA mode. + * +@verbatim + =============================================================================== + ##### DMA mode HASH extended processing functions ##### + =============================================================================== + [..] This section provides functions allowing to calculate in DMA mode + the hash value using one of the following algorithms: + (+) SHA224 + (++) DAL_HASHEx_SHA224_Start_DMA() + (++) DAL_HASHEx_SHA224_Finish() + (+) SHA256 + (++) DAL_HASHEx_SHA256_Start_DMA() + (++) DAL_HASHEx_SHA256_Finish() + + [..] When resorting to DMA mode to enter the data in the Peripheral, user must resort + to DAL_HASHEx_xxx_Start_DMA() then read the resulting digest with + DAL_HASHEx_xxx_Finish(). + + [..] In case of multi-buffer HASH processing, MDMAT bit must first be set before + the successive calls to DAL_HASHEx_xxx_Start_DMA(). Then, MDMAT bit needs to be + reset before the last call to DAL_HASHEx_xxx_Start_DMA(). Digest is finally + retrieved thanks to DAL_HASHEx_xxx_Finish(). + +@endverbatim + * @{ + */ + + + + +/** + * @brief Initialize the HASH peripheral in SHA224 mode then initiate a DMA transfer + * to feed the input buffer to the Peripheral. + * @note Once the DMA transfer is finished, DAL_HASHEx_SHA224_Finish() API must + * be called to retrieve the computed digest. + * @param hhash HASH handle. + * @param pInBuffer pointer to the input buffer (buffer to be hashed). + * @param Size length of the input buffer in bytes. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_HASHEx_SHA224_Start_DMA(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size) +{ + return HASH_Start_DMA(hhash, pInBuffer, Size, HASH_ALGOSELECTION_SHA224); +} + +/** + * @brief Return the computed digest in SHA224 mode. + * @note The API waits for DCIS to be set then reads the computed digest. + * @note DAL_HASHEx_SHA224_Finish() can be used as well to retrieve the digest in + * HMAC SHA224 mode. + * @param hhash HASH handle. + * @param pOutBuffer pointer to the computed digest. Digest size is 28 bytes. + * @param Timeout Timeout value. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_HASHEx_SHA224_Finish(HASH_HandleTypeDef *hhash, uint8_t *pOutBuffer, uint32_t Timeout) +{ + return HASH_Finish(hhash, pOutBuffer, Timeout); +} + +/** + * @brief Initialize the HASH peripheral in SHA256 mode then initiate a DMA transfer + * to feed the input buffer to the Peripheral. + * @note Once the DMA transfer is finished, DAL_HASHEx_SHA256_Finish() API must + * be called to retrieve the computed digest. + * @param hhash HASH handle. + * @param pInBuffer pointer to the input buffer (buffer to be hashed). + * @param Size length of the input buffer in bytes. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_HASHEx_SHA256_Start_DMA(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size) +{ + return HASH_Start_DMA(hhash, pInBuffer, Size, HASH_ALGOSELECTION_SHA256); +} + +/** + * @brief Return the computed digest in SHA256 mode. + * @note The API waits for DCIS to be set then reads the computed digest. + * @note DAL_HASHEx_SHA256_Finish() can be used as well to retrieve the digest in + * HMAC SHA256 mode. + * @param hhash HASH handle. + * @param pOutBuffer pointer to the computed digest. Digest size is 32 bytes. + * @param Timeout Timeout value. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_HASHEx_SHA256_Finish(HASH_HandleTypeDef *hhash, uint8_t *pOutBuffer, uint32_t Timeout) +{ + return HASH_Finish(hhash, pOutBuffer, Timeout); +} + +/** + * @} + */ + +/** @defgroup HASHEx_Exported_Functions_Group4 HMAC extended processing functions in polling mode + * @brief HMAC extended processing functions using polling mode. + * +@verbatim + =============================================================================== + ##### Polling mode HMAC extended processing functions ##### + =============================================================================== + [..] This section provides functions allowing to calculate in polling mode + the HMAC value using one of the following algorithms: + (+) SHA224 + (++) DAL_HMACEx_SHA224_Start() + (+) SHA256 + (++) DAL_HMACEx_SHA256_Start() + +@endverbatim + * @{ + */ + + + +/** + * @brief Initialize the HASH peripheral in HMAC SHA224 mode, next process pInBuffer then + * read the computed digest. + * @note Digest is available in pOutBuffer. + * @note Same key is used for the inner and the outer hash functions; pointer to key and + * key size are respectively stored in hhash->Init.pKey and hhash->Init.KeySize. + * @param hhash HASH handle. + * @param pInBuffer pointer to the input buffer (buffer to be hashed). + * @param Size length of the input buffer in bytes. + * @param pOutBuffer pointer to the computed digest. Digest size is 28 bytes. + * @param Timeout Timeout value. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_HMACEx_SHA224_Start(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, + uint8_t *pOutBuffer, uint32_t Timeout) +{ + return HMAC_Start(hhash, pInBuffer, Size, pOutBuffer, Timeout, HASH_ALGOSELECTION_SHA224); +} + +/** + * @brief Initialize the HASH peripheral in HMAC SHA256 mode, next process pInBuffer then + * read the computed digest. + * @note Digest is available in pOutBuffer. + * @note Same key is used for the inner and the outer hash functions; pointer to key and + * key size are respectively stored in hhash->Init.pKey and hhash->Init.KeySize. + * @param hhash HASH handle. + * @param pInBuffer pointer to the input buffer (buffer to be hashed). + * @param Size length of the input buffer in bytes. + * @param pOutBuffer pointer to the computed digest. Digest size is 32 bytes. + * @param Timeout Timeout value. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_HMACEx_SHA256_Start(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, + uint8_t *pOutBuffer, uint32_t Timeout) +{ + return HMAC_Start(hhash, pInBuffer, Size, pOutBuffer, Timeout, HASH_ALGOSELECTION_SHA256); +} + +/** + * @} + */ + + +/** @defgroup HASHEx_Exported_Functions_Group5 HMAC extended processing functions in interrupt mode + * @brief HMAC extended processing functions using interruption mode. + * +@verbatim + =============================================================================== + ##### Interrupt mode HMAC extended processing functions ##### + =============================================================================== + [..] This section provides functions allowing to calculate in interrupt mode + the HMAC value using one of the following algorithms: + (+) SHA224 + (++) DAL_HMACEx_SHA224_Start_IT() + (+) SHA256 + (++) DAL_HMACEx_SHA256_Start_IT() + +@endverbatim + * @{ + */ + + + +/** + * @brief Initialize the HASH peripheral in HMAC SHA224 mode, next process pInBuffer then + * read the computed digest in interrupt mode. + * @note Digest is available in pOutBuffer. + * @note Same key is used for the inner and the outer hash functions; pointer to key and + * key size are respectively stored in hhash->Init.pKey and hhash->Init.KeySize. + * @param hhash HASH handle. + * @param pInBuffer pointer to the input buffer (buffer to be hashed). + * @param Size length of the input buffer in bytes. + * @param pOutBuffer pointer to the computed digest. Digest size is 28 bytes. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_HMACEx_SHA224_Start_IT(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, + uint8_t *pOutBuffer) +{ + return HMAC_Start_IT(hhash, pInBuffer, Size, pOutBuffer, HASH_ALGOSELECTION_SHA224); +} + +/** + * @brief Initialize the HASH peripheral in HMAC SHA256 mode, next process pInBuffer then + * read the computed digest in interrupt mode. + * @note Digest is available in pOutBuffer. + * @note Same key is used for the inner and the outer hash functions; pointer to key and + * key size are respectively stored in hhash->Init.pKey and hhash->Init.KeySize. + * @param hhash HASH handle. + * @param pInBuffer pointer to the input buffer (buffer to be hashed). + * @param Size length of the input buffer in bytes. + * @param pOutBuffer pointer to the computed digest. Digest size is 32 bytes. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_HMACEx_SHA256_Start_IT(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, + uint8_t *pOutBuffer) +{ + return HMAC_Start_IT(hhash, pInBuffer, Size, pOutBuffer, HASH_ALGOSELECTION_SHA256); +} + + + + +/** + * @} + */ + + +/** @defgroup HASHEx_Exported_Functions_Group6 HMAC extended processing functions in DMA mode + * @brief HMAC extended processing functions using DMA mode. + * +@verbatim + =============================================================================== + ##### DMA mode HMAC extended processing functions ##### + =============================================================================== + [..] This section provides functions allowing to calculate in DMA mode + the HMAC value using one of the following algorithms: + (+) SHA224 + (++) DAL_HMACEx_SHA224_Start_DMA() + (+) SHA256 + (++) DAL_HMACEx_SHA256_Start_DMA() + + [..] When resorting to DMA mode to enter the data in the Peripheral for HMAC processing, + user must resort to DAL_HMACEx_xxx_Start_DMA() then read the resulting digest + with DAL_HASHEx_xxx_Finish(). + + +@endverbatim + * @{ + */ + + + +/** + * @brief Initialize the HASH peripheral in HMAC SHA224 mode then initiate the required + * DMA transfers to feed the key and the input buffer to the Peripheral. + * @note Once the DMA transfers are finished (indicated by hhash->State set back + * to DAL_HASH_STATE_READY), DAL_HASHEx_SHA224_Finish() API must be called to retrieve + * the computed digest. + * @note Same key is used for the inner and the outer hash functions; pointer to key and + * key size are respectively stored in hhash->Init.pKey and hhash->Init.KeySize. + * @note If MDMAT bit is set before calling this function (multi-buffer + * HASH processing case), the input buffer size (in bytes) must be + * a multiple of 4 otherwise, the HASH digest computation is corrupted. + * For the processing of the last buffer of the thread, MDMAT bit must + * be reset and the buffer length (in bytes) doesn't have to be a + * multiple of 4. + * @param hhash HASH handle. + * @param pInBuffer pointer to the input buffer (buffer to be hashed). + * @param Size length of the input buffer in bytes. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_HMACEx_SHA224_Start_DMA(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size) +{ + return HMAC_Start_DMA(hhash, pInBuffer, Size, HASH_ALGOSELECTION_SHA224); +} + +/** + * @brief Initialize the HASH peripheral in HMAC SHA224 mode then initiate the required + * DMA transfers to feed the key and the input buffer to the Peripheral. + * @note Once the DMA transfers are finished (indicated by hhash->State set back + * to DAL_HASH_STATE_READY), DAL_HASHEx_SHA256_Finish() API must be called to retrieve + * the computed digest. + * @note Same key is used for the inner and the outer hash functions; pointer to key and + * key size are respectively stored in hhash->Init.pKey and hhash->Init.KeySize. + * @note If MDMAT bit is set before calling this function (multi-buffer + * HASH processing case), the input buffer size (in bytes) must be + * a multiple of 4 otherwise, the HASH digest computation is corrupted. + * For the processing of the last buffer of the thread, MDMAT bit must + * be reset and the buffer length (in bytes) doesn't have to be a + * multiple of 4. + * @param hhash HASH handle. + * @param pInBuffer pointer to the input buffer (buffer to be hashed). + * @param Size length of the input buffer in bytes. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_HMACEx_SHA256_Start_DMA(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size) +{ + return HMAC_Start_DMA(hhash, pInBuffer, Size, HASH_ALGOSELECTION_SHA256); +} + + +/** + * @} + */ + +/** @defgroup HASHEx_Exported_Functions_Group7 Multi-buffer HMAC extended processing functions in DMA mode + * @brief HMAC extended processing functions in multi-buffer DMA mode. + * +@verbatim + =============================================================================== + ##### Multi-buffer DMA mode HMAC extended processing functions ##### + =============================================================================== + [..] This section provides functions to manage HMAC multi-buffer + DMA-based processing for MD5, SHA1, SHA224 and SHA256 algorithms. + (+) MD5 + (++) DAL_HMACEx_MD5_Step1_2_DMA() + (++) DAL_HMACEx_MD5_Step2_DMA() + (++) DAL_HMACEx_MD5_Step2_3_DMA() + (+) SHA1 + (++) DAL_HMACEx_SHA1_Step1_2_DMA() + (++) DAL_HMACEx_SHA1_Step2_DMA() + (++) DAL_HMACEx_SHA1_Step2_3_DMA() + + (+) SHA256 + (++) DAL_HMACEx_SHA224_Step1_2_DMA() + (++) DAL_HMACEx_SHA224_Step2_DMA() + (++) DAL_HMACEx_SHA224_Step2_3_DMA() + (+) SHA256 + (++) DAL_HMACEx_SHA256_Step1_2_DMA() + (++) DAL_HMACEx_SHA256_Step2_DMA() + (++) DAL_HMACEx_SHA256_Step2_3_DMA() + + [..] User must first start-up the multi-buffer DMA-based HMAC computation in + calling DAL_HMACEx_xxx_Step1_2_DMA(). This carries out HMAC step 1 and + intiates step 2 with the first input buffer. + + [..] The following buffers are next fed to the Peripheral with a call to the API + DAL_HMACEx_xxx_Step2_DMA(). There may be several consecutive calls + to this API. + + [..] Multi-buffer DMA-based HMAC computation is wrapped up by a call to + DAL_HMACEx_xxx_Step2_3_DMA(). This finishes step 2 in feeding the last input + buffer to the Peripheral then carries out step 3. + + [..] Digest is retrieved by a call to DAL_HASH_xxx_Finish() for MD-5 or + SHA-1, to DAL_HASHEx_xxx_Finish() for SHA-224 or SHA-256. + + [..] If only two buffers need to be consecutively processed, a call to + DAL_HMACEx_xxx_Step1_2_DMA() followed by a call to DAL_HMACEx_xxx_Step2_3_DMA() + is sufficient. + +@endverbatim + * @{ + */ + +/** + * @brief MD5 HMAC step 1 completion and step 2 start in multi-buffer DMA mode. + * @note Step 1 consists in writing the inner hash function key in the Peripheral, + * step 2 consists in writing the message text. + * @note The API carries out the HMAC step 1 then starts step 2 with + * the first buffer entered to the Peripheral. DCAL bit is not automatically set after + * the message buffer feeding, allowing other messages DMA transfers to occur. + * @note Same key is used for the inner and the outer hash functions; pointer to key and + * key size are respectively stored in hhash->Init.pKey and hhash->Init.KeySize. + * @note The input buffer size (in bytes) must be a multiple of 4 otherwise, the + * HASH digest computation is corrupted. + * @param hhash HASH handle. + * @param pInBuffer pointer to the input buffer (message buffer). + * @param Size length of the input buffer in bytes. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_HMACEx_MD5_Step1_2_DMA(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size) +{ + hhash->DigestCalculationDisable = SET; + return HMAC_Start_DMA(hhash, pInBuffer, Size, HASH_ALGOSELECTION_MD5); +} + +/** + * @brief MD5 HMAC step 2 in multi-buffer DMA mode. + * @note Step 2 consists in writing the message text in the Peripheral. + * @note The API carries on the HMAC step 2, applied to the buffer entered as input + * parameter. DCAL bit is not automatically set after the message buffer feeding, + * allowing other messages DMA transfers to occur. + * @note Same key is used for the inner and the outer hash functions; pointer to key and + * key size are respectively stored in hhash->Init.pKey and hhash->Init.KeySize. + * @note The input buffer size (in bytes) must be a multiple of 4 otherwise, the + * HASH digest computation is corrupted. + * @param hhash HASH handle. + * @param pInBuffer pointer to the input buffer (message buffer). + * @param Size length of the input buffer in bytes. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_HMACEx_MD5_Step2_DMA(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size) +{ + if (hhash->DigestCalculationDisable != SET) + { + return DAL_ERROR; + } + return HMAC_Start_DMA(hhash, pInBuffer, Size, HASH_ALGOSELECTION_MD5); +} + +/** + * @brief MD5 HMAC step 2 wrap-up and step 3 completion in multi-buffer DMA mode. + * @note Step 2 consists in writing the message text in the Peripheral, + * step 3 consists in writing the outer hash function key. + * @note The API wraps up the HMAC step 2 in processing the buffer entered as input + * parameter (the input buffer must be the last one of the multi-buffer thread) + * then carries out HMAC step 3. + * @note Same key is used for the inner and the outer hash functions; pointer to key and + * key size are respectively stored in hhash->Init.pKey and hhash->Init.KeySize. + * @note Once the DMA transfers are finished (indicated by hhash->State set back + * to DAL_HASH_STATE_READY), DAL_HASHEx_SHA256_Finish() API must be called to retrieve + * the computed digest. + * @param hhash HASH handle. + * @param pInBuffer pointer to the input buffer (message buffer). + * @param Size length of the input buffer in bytes. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_HMACEx_MD5_Step2_3_DMA(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size) +{ + hhash->DigestCalculationDisable = RESET; + return HMAC_Start_DMA(hhash, pInBuffer, Size, HASH_ALGOSELECTION_MD5); +} + + +/** + * @brief SHA1 HMAC step 1 completion and step 2 start in multi-buffer DMA mode. + * @note Step 1 consists in writing the inner hash function key in the Peripheral, + * step 2 consists in writing the message text. + * @note The API carries out the HMAC step 1 then starts step 2 with + * the first buffer entered to the Peripheral. DCAL bit is not automatically set after + * the message buffer feeding, allowing other messages DMA transfers to occur. + * @note Same key is used for the inner and the outer hash functions; pointer to key and + * key size are respectively stored in hhash->Init.pKey and hhash->Init.KeySize. + * @note The input buffer size (in bytes) must be a multiple of 4 otherwise, the + * HASH digest computation is corrupted. + * @param hhash HASH handle. + * @param pInBuffer pointer to the input buffer (message buffer). + * @param Size length of the input buffer in bytes. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_HMACEx_SHA1_Step1_2_DMA(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size) +{ + hhash->DigestCalculationDisable = SET; + return HMAC_Start_DMA(hhash, pInBuffer, Size, HASH_ALGOSELECTION_SHA1); +} + +/** + * @brief SHA1 HMAC step 2 in multi-buffer DMA mode. + * @note Step 2 consists in writing the message text in the Peripheral. + * @note The API carries on the HMAC step 2, applied to the buffer entered as input + * parameter. DCAL bit is not automatically set after the message buffer feeding, + * allowing other messages DMA transfers to occur. + * @note Same key is used for the inner and the outer hash functions; pointer to key and + * key size are respectively stored in hhash->Init.pKey and hhash->Init.KeySize. + * @note The input buffer size (in bytes) must be a multiple of 4 otherwise, the + * HASH digest computation is corrupted. + * @param hhash HASH handle. + * @param pInBuffer pointer to the input buffer (message buffer). + * @param Size length of the input buffer in bytes. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_HMACEx_SHA1_Step2_DMA(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size) +{ + if (hhash->DigestCalculationDisable != SET) + { + return DAL_ERROR; + } + return HMAC_Start_DMA(hhash, pInBuffer, Size, HASH_ALGOSELECTION_SHA1); +} + +/** + * @brief SHA1 HMAC step 2 wrap-up and step 3 completion in multi-buffer DMA mode. + * @note Step 2 consists in writing the message text in the Peripheral, + * step 3 consists in writing the outer hash function key. + * @note The API wraps up the HMAC step 2 in processing the buffer entered as input + * parameter (the input buffer must be the last one of the multi-buffer thread) + * then carries out HMAC step 3. + * @note Same key is used for the inner and the outer hash functions; pointer to key and + * key size are respectively stored in hhash->Init.pKey and hhash->Init.KeySize. + * @note Once the DMA transfers are finished (indicated by hhash->State set back + * to DAL_HASH_STATE_READY), DAL_HASHEx_SHA256_Finish() API must be called to retrieve + * the computed digest. + * @param hhash HASH handle. + * @param pInBuffer pointer to the input buffer (message buffer). + * @param Size length of the input buffer in bytes. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_HMACEx_SHA1_Step2_3_DMA(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size) +{ + hhash->DigestCalculationDisable = RESET; + return HMAC_Start_DMA(hhash, pInBuffer, Size, HASH_ALGOSELECTION_SHA1); +} + +/** + * @brief SHA224 HMAC step 1 completion and step 2 start in multi-buffer DMA mode. + * @note Step 1 consists in writing the inner hash function key in the Peripheral, + * step 2 consists in writing the message text. + * @note The API carries out the HMAC step 1 then starts step 2 with + * the first buffer entered to the Peripheral. DCAL bit is not automatically set after + * the message buffer feeding, allowing other messages DMA transfers to occur. + * @note Same key is used for the inner and the outer hash functions; pointer to key and + * key size are respectively stored in hhash->Init.pKey and hhash->Init.KeySize. + * @note The input buffer size (in bytes) must be a multiple of 4 otherwise, the + * HASH digest computation is corrupted. + * @param hhash HASH handle. + * @param pInBuffer pointer to the input buffer (message buffer). + * @param Size length of the input buffer in bytes. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_HMACEx_SHA224_Step1_2_DMA(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size) +{ + hhash->DigestCalculationDisable = SET; + return HMAC_Start_DMA(hhash, pInBuffer, Size, HASH_ALGOSELECTION_SHA224); +} + +/** + * @brief SHA224 HMAC step 2 in multi-buffer DMA mode. + * @note Step 2 consists in writing the message text in the Peripheral. + * @note The API carries on the HMAC step 2, applied to the buffer entered as input + * parameter. DCAL bit is not automatically set after the message buffer feeding, + * allowing other messages DMA transfers to occur. + * @note Same key is used for the inner and the outer hash functions; pointer to key and + * key size are respectively stored in hhash->Init.pKey and hhash->Init.KeySize. + * @note The input buffer size (in bytes) must be a multiple of 4 otherwise, the + * HASH digest computation is corrupted. + * @param hhash HASH handle. + * @param pInBuffer pointer to the input buffer (message buffer). + * @param Size length of the input buffer in bytes. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_HMACEx_SHA224_Step2_DMA(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size) +{ + if (hhash->DigestCalculationDisable != SET) + { + return DAL_ERROR; + } + return HMAC_Start_DMA(hhash, pInBuffer, Size, HASH_ALGOSELECTION_SHA224); +} + +/** + * @brief SHA224 HMAC step 2 wrap-up and step 3 completion in multi-buffer DMA mode. + * @note Step 2 consists in writing the message text in the Peripheral, + * step 3 consists in writing the outer hash function key. + * @note The API wraps up the HMAC step 2 in processing the buffer entered as input + * parameter (the input buffer must be the last one of the multi-buffer thread) + * then carries out HMAC step 3. + * @note Same key is used for the inner and the outer hash functions; pointer to key and + * key size are respectively stored in hhash->Init.pKey and hhash->Init.KeySize. + * @note Once the DMA transfers are finished (indicated by hhash->State set back + * to DAL_HASH_STATE_READY), DAL_HASHEx_SHA256_Finish() API must be called to retrieve + * the computed digest. + * @param hhash HASH handle. + * @param pInBuffer pointer to the input buffer (message buffer). + * @param Size length of the input buffer in bytes. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_HMACEx_SHA224_Step2_3_DMA(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size) +{ + hhash->DigestCalculationDisable = RESET; + return HMAC_Start_DMA(hhash, pInBuffer, Size, HASH_ALGOSELECTION_SHA224); +} + +/** + * @brief SHA256 HMAC step 1 completion and step 2 start in multi-buffer DMA mode. + * @note Step 1 consists in writing the inner hash function key in the Peripheral, + * step 2 consists in writing the message text. + * @note The API carries out the HMAC step 1 then starts step 2 with + * the first buffer entered to the Peripheral. DCAL bit is not automatically set after + * the message buffer feeding, allowing other messages DMA transfers to occur. + * @note Same key is used for the inner and the outer hash functions; pointer to key and + * key size are respectively stored in hhash->Init.pKey and hhash->Init.KeySize. + * @note The input buffer size (in bytes) must be a multiple of 4 otherwise, the + * HASH digest computation is corrupted. + * @param hhash HASH handle. + * @param pInBuffer pointer to the input buffer (message buffer). + * @param Size length of the input buffer in bytes. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_HMACEx_SHA256_Step1_2_DMA(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size) +{ + hhash->DigestCalculationDisable = SET; + return HMAC_Start_DMA(hhash, pInBuffer, Size, HASH_ALGOSELECTION_SHA256); +} + +/** + * @brief SHA256 HMAC step 2 in multi-buffer DMA mode. + * @note Step 2 consists in writing the message text in the Peripheral. + * @note The API carries on the HMAC step 2, applied to the buffer entered as input + * parameter. DCAL bit is not automatically set after the message buffer feeding, + * allowing other messages DMA transfers to occur. + * @note Same key is used for the inner and the outer hash functions; pointer to key and + * key size are respectively stored in hhash->Init.pKey and hhash->Init.KeySize. + * @note The input buffer size (in bytes) must be a multiple of 4 otherwise, the + * HASH digest computation is corrupted. + * @param hhash HASH handle. + * @param pInBuffer pointer to the input buffer (message buffer). + * @param Size length of the input buffer in bytes. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_HMACEx_SHA256_Step2_DMA(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size) +{ + if (hhash->DigestCalculationDisable != SET) + { + return DAL_ERROR; + } + return HMAC_Start_DMA(hhash, pInBuffer, Size, HASH_ALGOSELECTION_SHA256); +} + +/** + * @brief SHA256 HMAC step 2 wrap-up and step 3 completion in multi-buffer DMA mode. + * @note Step 2 consists in writing the message text in the Peripheral, + * step 3 consists in writing the outer hash function key. + * @note The API wraps up the HMAC step 2 in processing the buffer entered as input + * parameter (the input buffer must be the last one of the multi-buffer thread) + * then carries out HMAC step 3. + * @note Same key is used for the inner and the outer hash functions; pointer to key and + * key size are respectively stored in hhash->Init.pKey and hhash->Init.KeySize. + * @note Once the DMA transfers are finished (indicated by hhash->State set back + * to DAL_HASH_STATE_READY), DAL_HASHEx_SHA256_Finish() API must be called to retrieve + * the computed digest. + * @param hhash HASH handle. + * @param pInBuffer pointer to the input buffer (message buffer). + * @param Size length of the input buffer in bytes. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_HMACEx_SHA256_Step2_3_DMA(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size) +{ + hhash->DigestCalculationDisable = RESET; + return HMAC_Start_DMA(hhash, pInBuffer, Size, HASH_ALGOSELECTION_SHA256); +} + +/** + * @} + */ + +#endif /* MDMA defined*/ +/** + * @} + */ +#endif /* DAL_HASH_MODULE_ENABLED */ + +/** + * @} + */ +#endif /* HASH*/ +/** + * @} + */ + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_hcd.c b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_hcd.c new file mode 100644 index 0000000000..b3e9c01d18 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_hcd.c @@ -0,0 +1,1830 @@ +/** + * + * @file apm32f4xx_dal_hcd.c + * @brief HCD DAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the USB Peripheral Controller: + * + Initialization and de-initialization functions + * + IO operation functions + * + Peripheral Control functions + * + Peripheral State functions + * + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + * + @verbatim + ============================================================================== + ##### How to use this driver ##### + ============================================================================== + [..] + (#)Declare a HCD_HandleTypeDef handle structure, for example: + HCD_HandleTypeDef hhcd; + + (#)Fill parameters of Init structure in HCD handle + + (#)Call DAL_HCD_Init() API to initialize the HCD peripheral (Core, Host core, ...) + + (#)Initialize the HCD low level resources through the DAL_HCD_MspInit() API: + (##) Enable the HCD/USB Low Level interface clock using the following macros + (+++) __DAL_RCM_USB_OTG_FS_CLK_ENABLE(); + (+++) __DAL_RCM_USB_OTG_HS_CLK_ENABLE(); (For High Speed Mode) + (+++) __DAL_RCM_USB_OTG_HS_ULPI_CLK_ENABLE(); (For High Speed Mode) + + (##) Initialize the related GPIO clocks + (##) Configure HCD pin-out + (##) Configure HCD NVIC interrupt + + (#)Associate the Upper USB Host stack to the DAL HCD Driver: + (##) hhcd.pData = phost; + + (#)Enable HCD transmission and reception: + (##) DAL_HCD_Start(); + + @endverbatim + * + */ + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +#ifdef DAL_HCD_MODULE_ENABLED +#if defined (USB_OTG_FS) || defined (USB_OTG_HS) + +/** @defgroup HCD HCD + * @brief HCD DAL module driver + * @{ + */ + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/** @defgroup HCD_Private_Functions HCD Private Functions + * @{ + */ +static void HCD_HC_IN_IRQHandler(HCD_HandleTypeDef *hhcd, uint8_t chnum); +static void HCD_HC_OUT_IRQHandler(HCD_HandleTypeDef *hhcd, uint8_t chnum); +static void HCD_RXQLVL_IRQHandler(HCD_HandleTypeDef *hhcd); +static void HCD_Port_IRQHandler(HCD_HandleTypeDef *hhcd); +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +/** @defgroup HCD_Exported_Functions HCD Exported Functions + * @{ + */ + +/** @defgroup HCD_Exported_Functions_Group1 Initialization and de-initialization functions + * @brief Initialization and Configuration functions + * +@verbatim + =============================================================================== + ##### Initialization and de-initialization functions ##### + =============================================================================== + [..] This section provides functions allowing to: + +@endverbatim + * @{ + */ + +/** + * @brief Initialize the host driver. + * @param hhcd HCD handle + * @retval DAL status + */ +DAL_StatusTypeDef DAL_HCD_Init(HCD_HandleTypeDef *hhcd) +{ + USB_OTG_GlobalTypeDef *USBx; + + /* Check the HCD handle allocation */ + if (hhcd == NULL) + { + return DAL_ERROR; + } + + /* Check the parameters */ + ASSERT_PARAM(IS_HCD_ALL_INSTANCE(hhcd->Instance)); + + USBx = hhcd->Instance; + + if (hhcd->State == DAL_HCD_STATE_RESET) + { + /* Allocate lock resource and initialize it */ + hhcd->Lock = DAL_UNLOCKED; + +#if (USE_DAL_HCD_REGISTER_CALLBACKS == 1U) + hhcd->SOFCallback = DAL_HCD_SOF_Callback; + hhcd->ConnectCallback = DAL_HCD_Connect_Callback; + hhcd->DisconnectCallback = DAL_HCD_Disconnect_Callback; + hhcd->PortEnabledCallback = DAL_HCD_PortEnabled_Callback; + hhcd->PortDisabledCallback = DAL_HCD_PortDisabled_Callback; + hhcd->HC_NotifyURBChangeCallback = DAL_HCD_HC_NotifyURBChange_Callback; + + if (hhcd->MspInitCallback == NULL) + { + hhcd->MspInitCallback = DAL_HCD_MspInit; + } + + /* Init the low level hardware */ + hhcd->MspInitCallback(hhcd); +#else + /* Init the low level hardware : GPIO, CLOCK, NVIC... */ + DAL_HCD_MspInit(hhcd); +#endif /* (USE_DAL_HCD_REGISTER_CALLBACKS) */ + } + + hhcd->State = DAL_HCD_STATE_BUSY; + + /* Disable DMA mode for FS instance */ + if ((USBx->GCID & (0x1U << 8)) == 0U) + { + hhcd->Init.dma_enable = 0U; + } + + /* Disable the Interrupts */ + __DAL_HCD_DISABLE(hhcd); + + /* Init the Core (common init.) */ + (void)USB_CoreInit(hhcd->Instance, hhcd->Init); + + /* Force Host Mode*/ + (void)USB_SetCurrentMode(hhcd->Instance, USB_HOST_MODE); + + /* Init Host */ + (void)USB_HostInit(hhcd->Instance, hhcd->Init); + + hhcd->State = DAL_HCD_STATE_READY; + + return DAL_OK; +} + +/** + * @brief Initialize a host channel. + * @param hhcd HCD handle + * @param ch_num Channel number. + * This parameter can be a value from 1 to 15 + * @param epnum Endpoint number. + * This parameter can be a value from 1 to 15 + * @param dev_address Current device address + * This parameter can be a value from 0 to 255 + * @param speed Current device speed. + * This parameter can be one of these values: + * HCD_DEVICE_SPEED_HIGH: High speed mode, + * HCD_DEVICE_SPEED_FULL: Full speed mode, + * HCD_DEVICE_SPEED_LOW: Low speed mode + * @param ep_type Endpoint Type. + * This parameter can be one of these values: + * EP_TYPE_CTRL: Control type, + * EP_TYPE_ISOC: Isochronous type, + * EP_TYPE_BULK: Bulk type, + * EP_TYPE_INTR: Interrupt type + * @param mps Max Packet Size. + * This parameter can be a value from 0 to 32K + * @retval DAL status + */ +DAL_StatusTypeDef DAL_HCD_HC_Init(HCD_HandleTypeDef *hhcd, + uint8_t ch_num, + uint8_t epnum, + uint8_t dev_address, + uint8_t speed, + uint8_t ep_type, + uint16_t mps) +{ + DAL_StatusTypeDef status; + + __DAL_LOCK(hhcd); + hhcd->hc[ch_num].do_ping = 0U; + hhcd->hc[ch_num].dev_addr = dev_address; + hhcd->hc[ch_num].max_packet = mps; + hhcd->hc[ch_num].ch_num = ch_num; + hhcd->hc[ch_num].ep_type = ep_type; + hhcd->hc[ch_num].ep_num = epnum & 0x7FU; + + if ((epnum & 0x80U) == 0x80U) + { + hhcd->hc[ch_num].ep_is_in = 1U; + } + else + { + hhcd->hc[ch_num].ep_is_in = 0U; + } + + hhcd->hc[ch_num].speed = speed; + + status = USB_HC_Init(hhcd->Instance, + ch_num, + epnum, + dev_address, + speed, + ep_type, + mps); + __DAL_UNLOCK(hhcd); + + return status; +} + +/** + * @brief Halt a host channel. + * @param hhcd HCD handle + * @param ch_num Channel number. + * This parameter can be a value from 1 to 15 + * @retval DAL status + */ +DAL_StatusTypeDef DAL_HCD_HC_Halt(HCD_HandleTypeDef *hhcd, uint8_t ch_num) +{ + DAL_StatusTypeDef status = DAL_OK; + + __DAL_LOCK(hhcd); + (void)USB_HC_Halt(hhcd->Instance, (uint8_t)ch_num); + __DAL_UNLOCK(hhcd); + + return status; +} + +/** + * @brief DeInitialize the host driver. + * @param hhcd HCD handle + * @retval DAL status + */ +DAL_StatusTypeDef DAL_HCD_DeInit(HCD_HandleTypeDef *hhcd) +{ + /* Check the HCD handle allocation */ + if (hhcd == NULL) + { + return DAL_ERROR; + } + + hhcd->State = DAL_HCD_STATE_BUSY; + +#if (USE_DAL_HCD_REGISTER_CALLBACKS == 1U) + if (hhcd->MspDeInitCallback == NULL) + { + hhcd->MspDeInitCallback = DAL_HCD_MspDeInit; /* Legacy weak MspDeInit */ + } + + /* DeInit the low level hardware */ + hhcd->MspDeInitCallback(hhcd); +#else + /* DeInit the low level hardware: CLOCK, NVIC.*/ + DAL_HCD_MspDeInit(hhcd); +#endif /* USE_DAL_HCD_REGISTER_CALLBACKS */ + + __DAL_HCD_DISABLE(hhcd); + + hhcd->State = DAL_HCD_STATE_RESET; + + return DAL_OK; +} + +/** + * @brief Initialize the HCD MSP. + * @param hhcd HCD handle + * @retval None + */ +__weak void DAL_HCD_MspInit(HCD_HandleTypeDef *hhcd) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hhcd); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_HCD_MspInit could be implemented in the user file + */ +} + +/** + * @brief DeInitialize the HCD MSP. + * @param hhcd HCD handle + * @retval None + */ +__weak void DAL_HCD_MspDeInit(HCD_HandleTypeDef *hhcd) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hhcd); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_HCD_MspDeInit could be implemented in the user file + */ +} + +/** + * @} + */ + +/** @defgroup HCD_Exported_Functions_Group2 Input and Output operation functions + * @brief HCD IO operation functions + * +@verbatim + =============================================================================== + ##### IO operation functions ##### + =============================================================================== + [..] This subsection provides a set of functions allowing to manage the USB Host Data + Transfer + +@endverbatim + * @{ + */ + +/** + * @brief Submit a new URB for processing. + * @param hhcd HCD handle + * @param ch_num Channel number. + * This parameter can be a value from 1 to 15 + * @param direction Channel number. + * This parameter can be one of these values: + * 0 : Output / 1 : Input + * @param ep_type Endpoint Type. + * This parameter can be one of these values: + * EP_TYPE_CTRL: Control type/ + * EP_TYPE_ISOC: Isochronous type/ + * EP_TYPE_BULK: Bulk type/ + * EP_TYPE_INTR: Interrupt type/ + * @param token Endpoint Type. + * This parameter can be one of these values: + * 0: HC_PID_SETUP / 1: HC_PID_DATA1 + * @param pbuff pointer to URB data + * @param length Length of URB data + * @param do_ping activate do ping protocol (for high speed only). + * This parameter can be one of these values: + * 0 : do ping inactive / 1 : do ping active + * @retval DAL status + */ +DAL_StatusTypeDef DAL_HCD_HC_SubmitRequest(HCD_HandleTypeDef *hhcd, + uint8_t ch_num, + uint8_t direction, + uint8_t ep_type, + uint8_t token, + uint8_t *pbuff, + uint16_t length, + uint8_t do_ping) +{ + hhcd->hc[ch_num].ep_is_in = direction; + hhcd->hc[ch_num].ep_type = ep_type; + + if (token == 0U) + { + hhcd->hc[ch_num].data_pid = HC_PID_SETUP; + hhcd->hc[ch_num].do_ping = do_ping; + } + else + { + hhcd->hc[ch_num].data_pid = HC_PID_DATA1; + } + + /* Manage Data Toggle */ + switch (ep_type) + { + case EP_TYPE_CTRL: + if ((token == 1U) && (direction == 0U)) /*send data */ + { + if (length == 0U) + { + /* For Status OUT stage, Length==0, Status Out PID = 1 */ + hhcd->hc[ch_num].toggle_out = 1U; + } + + /* Set the Data Toggle bit as per the Flag */ + if (hhcd->hc[ch_num].toggle_out == 0U) + { + /* Put the PID 0 */ + hhcd->hc[ch_num].data_pid = HC_PID_DATA0; + } + else + { + /* Put the PID 1 */ + hhcd->hc[ch_num].data_pid = HC_PID_DATA1; + } + } + break; + + case EP_TYPE_BULK: + if (direction == 0U) + { + /* Set the Data Toggle bit as per the Flag */ + if (hhcd->hc[ch_num].toggle_out == 0U) + { + /* Put the PID 0 */ + hhcd->hc[ch_num].data_pid = HC_PID_DATA0; + } + else + { + /* Put the PID 1 */ + hhcd->hc[ch_num].data_pid = HC_PID_DATA1; + } + } + else + { + if (hhcd->hc[ch_num].toggle_in == 0U) + { + hhcd->hc[ch_num].data_pid = HC_PID_DATA0; + } + else + { + hhcd->hc[ch_num].data_pid = HC_PID_DATA1; + } + } + + break; + case EP_TYPE_INTR: + if (direction == 0U) + { + /* Set the Data Toggle bit as per the Flag */ + if (hhcd->hc[ch_num].toggle_out == 0U) + { + /* Put the PID 0 */ + hhcd->hc[ch_num].data_pid = HC_PID_DATA0; + } + else + { + /* Put the PID 1 */ + hhcd->hc[ch_num].data_pid = HC_PID_DATA1; + } + } + else + { + if (hhcd->hc[ch_num].toggle_in == 0U) + { + hhcd->hc[ch_num].data_pid = HC_PID_DATA0; + } + else + { + hhcd->hc[ch_num].data_pid = HC_PID_DATA1; + } + } + break; + + case EP_TYPE_ISOC: + hhcd->hc[ch_num].data_pid = HC_PID_DATA0; + break; + + default: + break; + } + + hhcd->hc[ch_num].xfer_buff = pbuff; + hhcd->hc[ch_num].xfer_len = length; + hhcd->hc[ch_num].urb_state = URB_IDLE; + hhcd->hc[ch_num].xfer_count = 0U; + hhcd->hc[ch_num].ch_num = ch_num; + hhcd->hc[ch_num].state = HC_IDLE; + + return USB_HC_StartXfer(hhcd->Instance, &hhcd->hc[ch_num], (uint8_t)hhcd->Init.dma_enable); +} + +/** + * @brief Handle HCD interrupt request. + * @param hhcd HCD handle + * @retval None + */ +void DAL_HCD_IRQHandler(HCD_HandleTypeDef *hhcd) +{ + USB_OTG_GlobalTypeDef *USBx = hhcd->Instance; + uint32_t USBx_BASE = (uint32_t)USBx; + uint32_t i; + uint32_t interrupt; + + /* Ensure that we are in device mode */ + if (USB_GetMode(hhcd->Instance) == USB_OTG_MODE_HOST) + { + /* Avoid spurious interrupt */ + if (__DAL_HCD_IS_INVALID_INTERRUPT(hhcd)) + { + return; + } + + if (__DAL_HCD_GET_FLAG(hhcd, USB_OTG_GCINT_IP_OUTTX)) + { + /* Incorrect mode, acknowledge the interrupt */ + __DAL_HCD_CLEAR_FLAG(hhcd, USB_OTG_GCINT_IP_OUTTX); + } + + if (__DAL_HCD_GET_FLAG(hhcd, USB_OTG_GCINT_IIINTX)) + { + /* Incorrect mode, acknowledge the interrupt */ + __DAL_HCD_CLEAR_FLAG(hhcd, USB_OTG_GCINT_IIINTX); + } + + if (__DAL_HCD_GET_FLAG(hhcd, USB_OTG_GCINT_PTXFE)) + { + /* Incorrect mode, acknowledge the interrupt */ + __DAL_HCD_CLEAR_FLAG(hhcd, USB_OTG_GCINT_PTXFE); + } + + if (__DAL_HCD_GET_FLAG(hhcd, USB_OTG_GCINT_MMIS)) + { + /* Incorrect mode, acknowledge the interrupt */ + __DAL_HCD_CLEAR_FLAG(hhcd, USB_OTG_GCINT_MMIS); + } + + /* Handle Host Disconnect Interrupts */ + if (__DAL_HCD_GET_FLAG(hhcd, USB_OTG_GCINT_DEDIS)) + { + __DAL_HCD_CLEAR_FLAG(hhcd, USB_OTG_GCINT_DEDIS); + + if ((USBx_HPRT0 & USB_OTG_HPORTCSTS_PCNNTFLG) == 0U) + { + /* Flush USB Fifo */ + (void)USB_FlushTxFifo(USBx, 0x10U); + (void)USB_FlushRxFifo(USBx); + + /* Restore FS Clock */ + (void)USB_InitFSLSPClkSel(hhcd->Instance, HCFG_48_MHZ); + + /* Handle Host Port Disconnect Interrupt */ +#if (USE_DAL_HCD_REGISTER_CALLBACKS == 1U) + hhcd->DisconnectCallback(hhcd); +#else + DAL_HCD_Disconnect_Callback(hhcd); +#endif /* USE_DAL_HCD_REGISTER_CALLBACKS */ + } + } + + /* Handle Host Port Interrupts */ + if (__DAL_HCD_GET_FLAG(hhcd, USB_OTG_GCINT_HPORT)) + { + HCD_Port_IRQHandler(hhcd); + } + + /* Handle Host SOF Interrupt */ + if (__DAL_HCD_GET_FLAG(hhcd, USB_OTG_GCINT_SOF)) + { +#if (USE_DAL_HCD_REGISTER_CALLBACKS == 1U) + hhcd->SOFCallback(hhcd); +#else + DAL_HCD_SOF_Callback(hhcd); +#endif /* USE_DAL_HCD_REGISTER_CALLBACKS */ + + __DAL_HCD_CLEAR_FLAG(hhcd, USB_OTG_GCINT_SOF); + } + + /* Handle Rx Queue Level Interrupts */ + if ((__DAL_HCD_GET_FLAG(hhcd, USB_OTG_GCINT_RXFNONE)) != 0U) + { + USB_MASK_INTERRUPT(hhcd->Instance, USB_OTG_GCINT_RXFNONE); + + HCD_RXQLVL_IRQHandler(hhcd); + + USB_UNMASK_INTERRUPT(hhcd->Instance, USB_OTG_GCINT_RXFNONE); + } + + /* Handle Host channel Interrupt */ + if (__DAL_HCD_GET_FLAG(hhcd, USB_OTG_GCINT_HCHAN)) + { + interrupt = USB_HC_ReadInterrupt(hhcd->Instance); + for (i = 0U; i < hhcd->Init.Host_channels; i++) + { + if ((interrupt & (1UL << (i & 0xFU))) != 0U) + { + if ((USBx_HC(i)->HCH & USB_OTG_HCH_EDPDRT) == USB_OTG_HCH_EDPDRT) + { + HCD_HC_IN_IRQHandler(hhcd, (uint8_t)i); + } + else + { + HCD_HC_OUT_IRQHandler(hhcd, (uint8_t)i); + } + } + } + __DAL_HCD_CLEAR_FLAG(hhcd, USB_OTG_GCINT_HCHAN); + } + } +} + + +/** + * @brief Handles HCD Wakeup interrupt request. + * @param hhcd HCD handle + * @retval DAL status + */ +void DAL_HCD_WKUP_IRQHandler(HCD_HandleTypeDef *hhcd) +{ + UNUSED(hhcd); +} + + +/** + * @brief SOF callback. + * @param hhcd HCD handle + * @retval None + */ +__weak void DAL_HCD_SOF_Callback(HCD_HandleTypeDef *hhcd) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hhcd); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_HCD_SOF_Callback could be implemented in the user file + */ +} + +/** + * @brief Connection Event callback. + * @param hhcd HCD handle + * @retval None + */ +__weak void DAL_HCD_Connect_Callback(HCD_HandleTypeDef *hhcd) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hhcd); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_HCD_Connect_Callback could be implemented in the user file + */ +} + +/** + * @brief Disconnection Event callback. + * @param hhcd HCD handle + * @retval None + */ +__weak void DAL_HCD_Disconnect_Callback(HCD_HandleTypeDef *hhcd) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hhcd); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_HCD_Disconnect_Callback could be implemented in the user file + */ +} + +/** + * @brief Port Enabled Event callback. + * @param hhcd HCD handle + * @retval None + */ +__weak void DAL_HCD_PortEnabled_Callback(HCD_HandleTypeDef *hhcd) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hhcd); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_HCD_Disconnect_Callback could be implemented in the user file + */ +} + +/** + * @brief Port Disabled Event callback. + * @param hhcd HCD handle + * @retval None + */ +__weak void DAL_HCD_PortDisabled_Callback(HCD_HandleTypeDef *hhcd) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hhcd); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_HCD_Disconnect_Callback could be implemented in the user file + */ +} + +/** + * @brief Notify URB state change callback. + * @param hhcd HCD handle + * @param chnum Channel number. + * This parameter can be a value from 1 to 15 + * @param urb_state: + * This parameter can be one of these values: + * URB_IDLE/ + * URB_DONE/ + * URB_NOTREADY/ + * URB_NYET/ + * URB_ERROR/ + * URB_STALL/ + * @retval None + */ +__weak void DAL_HCD_HC_NotifyURBChange_Callback(HCD_HandleTypeDef *hhcd, uint8_t chnum, HCD_URBStateTypeDef urb_state) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hhcd); + UNUSED(chnum); + UNUSED(urb_state); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_HCD_HC_NotifyURBChange_Callback could be implemented in the user file + */ +} + +#if (USE_DAL_HCD_REGISTER_CALLBACKS == 1U) +/** + * @brief Register a User USB HCD Callback + * To be used instead of the weak predefined callback + * @param hhcd USB HCD handle + * @param CallbackID ID of the callback to be registered + * This parameter can be one of the following values: + * @arg @ref DAL_HCD_SOF_CB_ID USB HCD SOF callback ID + * @arg @ref DAL_HCD_CONNECT_CB_ID USB HCD Connect callback ID + * @arg @ref DAL_HCD_DISCONNECT_CB_ID OTG HCD Disconnect callback ID + * @arg @ref DAL_HCD_PORT_ENABLED_CB_ID USB HCD Port Enable callback ID + * @arg @ref DAL_HCD_PORT_DISABLED_CB_ID USB HCD Port Disable callback ID + * @arg @ref DAL_HCD_MSPINIT_CB_ID MspDeInit callback ID + * @arg @ref DAL_HCD_MSPDEINIT_CB_ID MspDeInit callback ID + * @param pCallback pointer to the Callback function + * @retval DAL status + */ +DAL_StatusTypeDef DAL_HCD_RegisterCallback(HCD_HandleTypeDef *hhcd, + DAL_HCD_CallbackIDTypeDef CallbackID, + pHCD_CallbackTypeDef pCallback) +{ + DAL_StatusTypeDef status = DAL_OK; + + if (pCallback == NULL) + { + /* Update the error code */ + hhcd->ErrorCode |= DAL_HCD_ERROR_INVALID_CALLBACK; + return DAL_ERROR; + } + /* Process locked */ + __DAL_LOCK(hhcd); + + if (hhcd->State == DAL_HCD_STATE_READY) + { + switch (CallbackID) + { + case DAL_HCD_SOF_CB_ID : + hhcd->SOFCallback = pCallback; + break; + + case DAL_HCD_CONNECT_CB_ID : + hhcd->ConnectCallback = pCallback; + break; + + case DAL_HCD_DISCONNECT_CB_ID : + hhcd->DisconnectCallback = pCallback; + break; + + case DAL_HCD_PORT_ENABLED_CB_ID : + hhcd->PortEnabledCallback = pCallback; + break; + + case DAL_HCD_PORT_DISABLED_CB_ID : + hhcd->PortDisabledCallback = pCallback; + break; + + case DAL_HCD_MSPINIT_CB_ID : + hhcd->MspInitCallback = pCallback; + break; + + case DAL_HCD_MSPDEINIT_CB_ID : + hhcd->MspDeInitCallback = pCallback; + break; + + default : + /* Update the error code */ + hhcd->ErrorCode |= DAL_HCD_ERROR_INVALID_CALLBACK; + /* Return error status */ + status = DAL_ERROR; + break; + } + } + else if (hhcd->State == DAL_HCD_STATE_RESET) + { + switch (CallbackID) + { + case DAL_HCD_MSPINIT_CB_ID : + hhcd->MspInitCallback = pCallback; + break; + + case DAL_HCD_MSPDEINIT_CB_ID : + hhcd->MspDeInitCallback = pCallback; + break; + + default : + /* Update the error code */ + hhcd->ErrorCode |= DAL_HCD_ERROR_INVALID_CALLBACK; + /* Return error status */ + status = DAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + hhcd->ErrorCode |= DAL_HCD_ERROR_INVALID_CALLBACK; + /* Return error status */ + status = DAL_ERROR; + } + + /* Release Lock */ + __DAL_UNLOCK(hhcd); + return status; +} + +/** + * @brief Unregister an USB HCD Callback + * USB HCD callback is redirected to the weak predefined callback + * @param hhcd USB HCD handle + * @param CallbackID ID of the callback to be unregistered + * This parameter can be one of the following values: + * @arg @ref DAL_HCD_SOF_CB_ID USB HCD SOF callback ID + * @arg @ref DAL_HCD_CONNECT_CB_ID USB HCD Connect callback ID + * @arg @ref DAL_HCD_DISCONNECT_CB_ID OTG HCD Disconnect callback ID + * @arg @ref DAL_HCD_PORT_ENABLED_CB_ID USB HCD Port Enabled callback ID + * @arg @ref DAL_HCD_PORT_DISABLED_CB_ID USB HCD Port Disabled callback ID + * @arg @ref DAL_HCD_MSPINIT_CB_ID MspDeInit callback ID + * @arg @ref DAL_HCD_MSPDEINIT_CB_ID MspDeInit callback ID + * @retval DAL status + */ +DAL_StatusTypeDef DAL_HCD_UnRegisterCallback(HCD_HandleTypeDef *hhcd, DAL_HCD_CallbackIDTypeDef CallbackID) +{ + DAL_StatusTypeDef status = DAL_OK; + + /* Process locked */ + __DAL_LOCK(hhcd); + + /* Setup Legacy weak Callbacks */ + if (hhcd->State == DAL_HCD_STATE_READY) + { + switch (CallbackID) + { + case DAL_HCD_SOF_CB_ID : + hhcd->SOFCallback = DAL_HCD_SOF_Callback; + break; + + case DAL_HCD_CONNECT_CB_ID : + hhcd->ConnectCallback = DAL_HCD_Connect_Callback; + break; + + case DAL_HCD_DISCONNECT_CB_ID : + hhcd->DisconnectCallback = DAL_HCD_Disconnect_Callback; + break; + + case DAL_HCD_PORT_ENABLED_CB_ID : + hhcd->PortEnabledCallback = DAL_HCD_PortEnabled_Callback; + break; + + case DAL_HCD_PORT_DISABLED_CB_ID : + hhcd->PortDisabledCallback = DAL_HCD_PortDisabled_Callback; + break; + + case DAL_HCD_MSPINIT_CB_ID : + hhcd->MspInitCallback = DAL_HCD_MspInit; + break; + + case DAL_HCD_MSPDEINIT_CB_ID : + hhcd->MspDeInitCallback = DAL_HCD_MspDeInit; + break; + + default : + /* Update the error code */ + hhcd->ErrorCode |= DAL_HCD_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = DAL_ERROR; + break; + } + } + else if (hhcd->State == DAL_HCD_STATE_RESET) + { + switch (CallbackID) + { + case DAL_HCD_MSPINIT_CB_ID : + hhcd->MspInitCallback = DAL_HCD_MspInit; + break; + + case DAL_HCD_MSPDEINIT_CB_ID : + hhcd->MspDeInitCallback = DAL_HCD_MspDeInit; + break; + + default : + /* Update the error code */ + hhcd->ErrorCode |= DAL_HCD_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = DAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + hhcd->ErrorCode |= DAL_HCD_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = DAL_ERROR; + } + + /* Release Lock */ + __DAL_UNLOCK(hhcd); + return status; +} + +/** + * @brief Register USB HCD Host Channel Notify URB Change Callback + * To be used instead of the weak DAL_HCD_HC_NotifyURBChange_Callback() predefined callback + * @param hhcd HCD handle + * @param pCallback pointer to the USB HCD Host Channel Notify URB Change Callback function + * @retval DAL status + */ +DAL_StatusTypeDef DAL_HCD_RegisterHC_NotifyURBChangeCallback(HCD_HandleTypeDef *hhcd, + pHCD_HC_NotifyURBChangeCallbackTypeDef pCallback) +{ + DAL_StatusTypeDef status = DAL_OK; + + if (pCallback == NULL) + { + /* Update the error code */ + hhcd->ErrorCode |= DAL_HCD_ERROR_INVALID_CALLBACK; + + return DAL_ERROR; + } + + /* Process locked */ + __DAL_LOCK(hhcd); + + if (hhcd->State == DAL_HCD_STATE_READY) + { + hhcd->HC_NotifyURBChangeCallback = pCallback; + } + else + { + /* Update the error code */ + hhcd->ErrorCode |= DAL_HCD_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = DAL_ERROR; + } + + /* Release Lock */ + __DAL_UNLOCK(hhcd); + + return status; +} + +/** + * @brief Unregister the USB HCD Host Channel Notify URB Change Callback + * USB HCD Host Channel Notify URB Change Callback is redirected + * to the weak DAL_HCD_HC_NotifyURBChange_Callback() predefined callback + * @param hhcd HCD handle + * @retval DAL status + */ +DAL_StatusTypeDef DAL_HCD_UnRegisterHC_NotifyURBChangeCallback(HCD_HandleTypeDef *hhcd) +{ + DAL_StatusTypeDef status = DAL_OK; + + /* Process locked */ + __DAL_LOCK(hhcd); + + if (hhcd->State == DAL_HCD_STATE_READY) + { + hhcd->HC_NotifyURBChangeCallback = DAL_HCD_HC_NotifyURBChange_Callback; /* Legacy weak DataOutStageCallback */ + } + else + { + /* Update the error code */ + hhcd->ErrorCode |= DAL_HCD_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = DAL_ERROR; + } + + /* Release Lock */ + __DAL_UNLOCK(hhcd); + + return status; +} +#endif /* USE_DAL_HCD_REGISTER_CALLBACKS */ + +/** + * @} + */ + +/** @defgroup HCD_Exported_Functions_Group3 Peripheral Control functions + * @brief Management functions + * +@verbatim + =============================================================================== + ##### Peripheral Control functions ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to control the HCD data + transfers. + +@endverbatim + * @{ + */ + +/** + * @brief Start the host driver. + * @param hhcd HCD handle + * @retval DAL status + */ +DAL_StatusTypeDef DAL_HCD_Start(HCD_HandleTypeDef *hhcd) +{ + __DAL_LOCK(hhcd); + /* Enable port power */ + (void)USB_DriveVbus(hhcd->Instance, 1U); + + /* Enable global interrupt */ + __DAL_HCD_ENABLE(hhcd); + __DAL_UNLOCK(hhcd); + + return DAL_OK; +} + +/** + * @brief Stop the host driver. + * @param hhcd HCD handle + * @retval DAL status + */ + +DAL_StatusTypeDef DAL_HCD_Stop(HCD_HandleTypeDef *hhcd) +{ + __DAL_LOCK(hhcd); + (void)USB_StopHost(hhcd->Instance); + __DAL_UNLOCK(hhcd); + + return DAL_OK; +} + +/** + * @brief Reset the host port. + * @param hhcd HCD handle + * @retval DAL status + */ +DAL_StatusTypeDef DAL_HCD_ResetPort(HCD_HandleTypeDef *hhcd) +{ + return (USB_ResetPort(hhcd->Instance)); +} + +/** + * @} + */ + +/** @defgroup HCD_Exported_Functions_Group4 Peripheral State functions + * @brief Peripheral State functions + * +@verbatim + =============================================================================== + ##### Peripheral State functions ##### + =============================================================================== + [..] + This subsection permits to get in run-time the status of the peripheral + and the data flow. + +@endverbatim + * @{ + */ + +/** + * @brief Return the HCD handle state. + * @param hhcd HCD handle + * @retval DAL state + */ +HCD_StateTypeDef DAL_HCD_GetState(HCD_HandleTypeDef *hhcd) +{ + return hhcd->State; +} + +/** + * @brief Return URB state for a channel. + * @param hhcd HCD handle + * @param chnum Channel number. + * This parameter can be a value from 1 to 15 + * @retval URB state. + * This parameter can be one of these values: + * URB_IDLE/ + * URB_DONE/ + * URB_NOTREADY/ + * URB_NYET/ + * URB_ERROR/ + * URB_STALL + */ +HCD_URBStateTypeDef DAL_HCD_HC_GetURBState(HCD_HandleTypeDef *hhcd, uint8_t chnum) +{ + return hhcd->hc[chnum].urb_state; +} + + +/** + * @brief Return the last host transfer size. + * @param hhcd HCD handle + * @param chnum Channel number. + * This parameter can be a value from 1 to 15 + * @retval last transfer size in byte + */ +uint32_t DAL_HCD_HC_GetXferCount(HCD_HandleTypeDef *hhcd, uint8_t chnum) +{ + return hhcd->hc[chnum].xfer_count; +} + +/** + * @brief Return the Host Channel state. + * @param hhcd HCD handle + * @param chnum Channel number. + * This parameter can be a value from 1 to 15 + * @retval Host channel state + * This parameter can be one of these values: + * HC_IDLE/ + * HC_XFRC/ + * HC_DALTED/ + * HC_NYET/ + * HC_NAK/ + * HC_STALL/ + * HC_XACTERR/ + * HC_BBLERR/ + * HC_DATATGLERR + */ +HCD_HCStateTypeDef DAL_HCD_HC_GetState(HCD_HandleTypeDef *hhcd, uint8_t chnum) +{ + return hhcd->hc[chnum].state; +} + +/** + * @brief Return the current Host frame number. + * @param hhcd HCD handle + * @retval Current Host frame number + */ +uint32_t DAL_HCD_GetCurrentFrame(HCD_HandleTypeDef *hhcd) +{ + return (USB_GetCurrentFrame(hhcd->Instance)); +} + +/** + * @brief Return the Host enumeration speed. + * @param hhcd HCD handle + * @retval Enumeration speed + */ +uint32_t DAL_HCD_GetCurrentSpeed(HCD_HandleTypeDef *hhcd) +{ + return (USB_GetHostSpeed(hhcd->Instance)); +} + +/** + * @brief USB host configure toggle of channel + * + * @param hhcd: hhcd HCD handle + * + * @param pipe: pipe number + * + * @param toggle: toggle + * + * @retval None + */ +void DAL_HCD_ConfigToggle(HCD_HandleTypeDef* hhcd, uint8_t pipe, uint8_t toggle) +{ + if (hhcd->hc[pipe].ep_is_in) + { + hhcd->hc[pipe].toggle_in = toggle; + } + else + { + hhcd->hc[pipe].toggle_out = toggle; + } +} + +/** + * @brief USB host read toggle of channel + * + * @param hhcd: hhcd HCD handle + * + * @param pipe: pipe number + * + * @retval toggle + */ +uint8_t DAL_HCD_ReadToggle(HCD_HandleTypeDef* hhcd, uint8_t pipe) +{ + uint8_t toggle; + + if (hhcd->hc[pipe].ep_is_in) + { + toggle = hhcd->hc[pipe].toggle_in; + } + else + { + toggle = hhcd->hc[pipe].toggle_out; + } + + return toggle; +} + +/** + * @} + */ + +/** + * @} + */ + +/** @addtogroup HCD_Private_Functions + * @{ + */ +/** + * @brief Handle Host Channel IN interrupt requests. + * @param hhcd HCD handle + * @param chnum Channel number. + * This parameter can be a value from 1 to 15 + * @retval none + */ +static void HCD_HC_IN_IRQHandler(HCD_HandleTypeDef *hhcd, uint8_t chnum) +{ + USB_OTG_GlobalTypeDef *USBx = hhcd->Instance; + uint32_t USBx_BASE = (uint32_t)USBx; + uint32_t ch_num = (uint32_t)chnum; + + uint32_t tmpreg; + + if ((USBx_HC(ch_num)->HCHINT & USB_OTG_HCHINT_AHBERR) == USB_OTG_HCHINT_AHBERR) + { + __DAL_HCD_CLEAR_HC_INT(ch_num, USB_OTG_HCHINT_AHBERR); + hhcd->hc[ch_num].state = HC_XACTERR; + (void)USB_HC_Halt(hhcd->Instance, (uint8_t)ch_num); + } + else if ((USBx_HC(ch_num)->HCHINT & USB_OTG_HCHINT_BABBLE) == USB_OTG_HCHINT_BABBLE) + { + __DAL_HCD_CLEAR_HC_INT(ch_num, USB_OTG_HCHINT_BABBLE); + hhcd->hc[ch_num].state = HC_BBLERR; + (void)USB_HC_Halt(hhcd->Instance, (uint8_t)ch_num); + } + else if ((USBx_HC(ch_num)->HCHINT & USB_OTG_HCHINT_RXTXACK) == USB_OTG_HCHINT_RXTXACK) + { + __DAL_HCD_CLEAR_HC_INT(ch_num, USB_OTG_HCHINT_RXTXACK); + } + else if ((USBx_HC(ch_num)->HCHINT & USB_OTG_HCHINT_RXSTALL) == USB_OTG_HCHINT_RXSTALL) + { + __DAL_HCD_CLEAR_HC_INT(ch_num, USB_OTG_HCHINT_RXSTALL); + hhcd->hc[ch_num].state = HC_STALL; + (void)USB_HC_Halt(hhcd->Instance, (uint8_t)ch_num); + } + else if ((USBx_HC(ch_num)->HCHINT & USB_OTG_HCHINT_DTOG) == USB_OTG_HCHINT_DTOG) + { + __DAL_HCD_CLEAR_HC_INT(ch_num, USB_OTG_HCHINT_DTOG); + hhcd->hc[ch_num].state = HC_DATATGLERR; + (void)USB_HC_Halt(hhcd->Instance, (uint8_t)ch_num); + } + else if ((USBx_HC(ch_num)->HCHINT & USB_OTG_HCHINT_TERR) == USB_OTG_HCHINT_TERR) + { + __DAL_HCD_CLEAR_HC_INT(ch_num, USB_OTG_HCHINT_TERR); + hhcd->hc[ch_num].state = HC_XACTERR; + (void)USB_HC_Halt(hhcd->Instance, (uint8_t)ch_num); + } + else + { + /* ... */ + } + + if ((USBx_HC(ch_num)->HCHINT & USB_OTG_HCHINT_FOVR) == USB_OTG_HCHINT_FOVR) + { + (void)USB_HC_Halt(hhcd->Instance, (uint8_t)ch_num); + __DAL_HCD_CLEAR_HC_INT(ch_num, USB_OTG_HCHINT_FOVR); + } + else if ((USBx_HC(ch_num)->HCHINT & USB_OTG_HCHINT_TSFCMPN) == USB_OTG_HCHINT_TSFCMPN) + { + if (hhcd->Init.dma_enable != 0U) + { + hhcd->hc[ch_num].xfer_count = hhcd->hc[ch_num].XferSize - \ + (USBx_HC(ch_num)->HCHTSIZE & USB_OTG_HCHTSIZE_TSFSIZE); + } + + hhcd->hc[ch_num].state = HC_XFRC; + hhcd->hc[ch_num].ErrCnt = 0U; + __DAL_HCD_CLEAR_HC_INT(ch_num, USB_OTG_HCHINT_TSFCMPN); + + if ((hhcd->hc[ch_num].ep_type == EP_TYPE_CTRL) || + (hhcd->hc[ch_num].ep_type == EP_TYPE_BULK)) + { + (void)USB_HC_Halt(hhcd->Instance, (uint8_t)ch_num); + __DAL_HCD_CLEAR_HC_INT(ch_num, USB_OTG_HCHINT_RXNAK); + } + else if ((hhcd->hc[ch_num].ep_type == EP_TYPE_INTR) || + (hhcd->hc[ch_num].ep_type == EP_TYPE_ISOC)) + { + USBx_HC(ch_num)->HCH |= USB_OTG_HCH_ODDF; + hhcd->hc[ch_num].urb_state = URB_DONE; + +#if (USE_DAL_HCD_REGISTER_CALLBACKS == 1U) + hhcd->HC_NotifyURBChangeCallback(hhcd, (uint8_t)ch_num, hhcd->hc[ch_num].urb_state); +#else + DAL_HCD_HC_NotifyURBChange_Callback(hhcd, (uint8_t)ch_num, hhcd->hc[ch_num].urb_state); +#endif /* USE_DAL_HCD_REGISTER_CALLBACKS */ + } + else + { + /* ... */ + } + + if (hhcd->Init.dma_enable == 1U) + { + if (((hhcd->hc[ch_num].XferSize / hhcd->hc[ch_num].max_packet) & 1U) != 0U) + { + hhcd->hc[ch_num].toggle_in ^= 1U; + } + } + else + { + hhcd->hc[ch_num].toggle_in ^= 1U; + } + } + else if ((USBx_HC(ch_num)->HCHINT & USB_OTG_HCHINT_TSFCMPAN) == USB_OTG_HCHINT_TSFCMPAN) + { + if (hhcd->hc[ch_num].state == HC_XFRC) + { + hhcd->hc[ch_num].urb_state = URB_DONE; + } + else if (hhcd->hc[ch_num].state == HC_STALL) + { + hhcd->hc[ch_num].urb_state = URB_STALL; + } + else if ((hhcd->hc[ch_num].state == HC_XACTERR) || + (hhcd->hc[ch_num].state == HC_DATATGLERR)) + { + hhcd->hc[ch_num].ErrCnt++; + if (hhcd->hc[ch_num].ErrCnt > 2U) + { + hhcd->hc[ch_num].ErrCnt = 0U; + hhcd->hc[ch_num].urb_state = URB_ERROR; + } + else + { + hhcd->hc[ch_num].urb_state = URB_NOTREADY; + + /* re-activate the channel */ + tmpreg = USBx_HC(ch_num)->HCH; + tmpreg &= ~USB_OTG_HCH_CHINT; + tmpreg |= USB_OTG_HCH_CHEN; + USBx_HC(ch_num)->HCH = tmpreg; + } + } + else if (hhcd->hc[ch_num].state == HC_NAK) + { + hhcd->hc[ch_num].urb_state = URB_NOTREADY; + + /* re-activate the channel */ + tmpreg = USBx_HC(ch_num)->HCH; + tmpreg &= ~USB_OTG_HCH_CHINT; + tmpreg |= USB_OTG_HCH_CHEN; + USBx_HC(ch_num)->HCH = tmpreg; + } + else if (hhcd->hc[ch_num].state == HC_BBLERR) + { + hhcd->hc[ch_num].ErrCnt++; + hhcd->hc[ch_num].urb_state = URB_ERROR; + } + else + { + /* ... */ + } + __DAL_HCD_CLEAR_HC_INT(ch_num, USB_OTG_HCHINT_TSFCMPAN); + +#if (USE_DAL_HCD_REGISTER_CALLBACKS == 1U) + hhcd->HC_NotifyURBChangeCallback(hhcd, (uint8_t)ch_num, hhcd->hc[ch_num].urb_state); +#else + DAL_HCD_HC_NotifyURBChange_Callback(hhcd, (uint8_t)ch_num, hhcd->hc[ch_num].urb_state); +#endif /* USE_DAL_HCD_REGISTER_CALLBACKS */ + } + else if ((USBx_HC(ch_num)->HCHINT & USB_OTG_HCHINT_RXNAK) == USB_OTG_HCHINT_RXNAK) + { + if (hhcd->hc[ch_num].ep_type == EP_TYPE_INTR) + { + hhcd->hc[ch_num].ErrCnt = 0U; + (void)USB_HC_Halt(hhcd->Instance, (uint8_t)ch_num); + } + else if ((hhcd->hc[ch_num].ep_type == EP_TYPE_CTRL) || + (hhcd->hc[ch_num].ep_type == EP_TYPE_BULK)) + { + hhcd->hc[ch_num].ErrCnt = 0U; + + if (hhcd->Init.dma_enable == 0U) + { + hhcd->hc[ch_num].state = HC_NAK; + (void)USB_HC_Halt(hhcd->Instance, (uint8_t)ch_num); + } + } + else + { + /* ... */ + } + __DAL_HCD_CLEAR_HC_INT(ch_num, USB_OTG_HCHINT_RXNAK); + } + else + { + /* ... */ + } +} + +/** + * @brief Handle Host Channel OUT interrupt requests. + * @param hhcd HCD handle + * @param chnum Channel number. + * This parameter can be a value from 1 to 15 + * @retval none + */ +static void HCD_HC_OUT_IRQHandler(HCD_HandleTypeDef *hhcd, uint8_t chnum) +{ + USB_OTG_GlobalTypeDef *USBx = hhcd->Instance; + uint32_t USBx_BASE = (uint32_t)USBx; + uint32_t ch_num = (uint32_t)chnum; + uint32_t tmpreg; + uint32_t num_packets; + + if ((USBx_HC(ch_num)->HCHINT & USB_OTG_HCHINT_AHBERR) == USB_OTG_HCHINT_AHBERR) + { + __DAL_HCD_CLEAR_HC_INT(ch_num, USB_OTG_HCHINT_AHBERR); + hhcd->hc[ch_num].state = HC_XACTERR; + (void)USB_HC_Halt(hhcd->Instance, (uint8_t)ch_num); + } + else if ((USBx_HC(ch_num)->HCHINT & USB_OTG_HCHINT_RXTXACK) == USB_OTG_HCHINT_RXTXACK) + { + __DAL_HCD_CLEAR_HC_INT(ch_num, USB_OTG_HCHINT_RXTXACK); + + if (hhcd->hc[ch_num].do_ping == 1U) + { + hhcd->hc[ch_num].do_ping = 0U; + hhcd->hc[ch_num].urb_state = URB_NOTREADY; + (void)USB_HC_Halt(hhcd->Instance, (uint8_t)ch_num); + } + } + else if ((USBx_HC(ch_num)->HCHINT & USB_OTG_HCHINT_FOVR) == USB_OTG_HCHINT_FOVR) + { + __DAL_HCD_CLEAR_HC_INT(ch_num, USB_OTG_HCHINT_FOVR); + (void)USB_HC_Halt(hhcd->Instance, (uint8_t)ch_num); + } + else if ((USBx_HC(ch_num)->HCHINT & USB_OTG_HCHINT_TSFCMPN) == USB_OTG_HCHINT_TSFCMPN) + { + hhcd->hc[ch_num].ErrCnt = 0U; + + /* transaction completed with NYET state, update do ping state */ + if ((USBx_HC(ch_num)->HCHINT & USB_OTG_HCHINT_RXNYET) == USB_OTG_HCHINT_RXNYET) + { + hhcd->hc[ch_num].do_ping = 1U; + __DAL_HCD_CLEAR_HC_INT(ch_num, USB_OTG_HCHINT_RXNYET); + } + __DAL_HCD_CLEAR_HC_INT(ch_num, USB_OTG_HCHINT_TSFCMPN); + hhcd->hc[ch_num].state = HC_XFRC; + (void)USB_HC_Halt(hhcd->Instance, (uint8_t)ch_num); + } + else if ((USBx_HC(ch_num)->HCHINT & USB_OTG_HCHINT_RXNYET) == USB_OTG_HCHINT_RXNYET) + { + hhcd->hc[ch_num].state = HC_NYET; + hhcd->hc[ch_num].do_ping = 1U; + hhcd->hc[ch_num].ErrCnt = 0U; + (void)USB_HC_Halt(hhcd->Instance, (uint8_t)ch_num); + __DAL_HCD_CLEAR_HC_INT(ch_num, USB_OTG_HCHINT_RXNYET); + } + else if ((USBx_HC(ch_num)->HCHINT & USB_OTG_HCHINT_RXSTALL) == USB_OTG_HCHINT_RXSTALL) + { + __DAL_HCD_CLEAR_HC_INT(ch_num, USB_OTG_HCHINT_RXSTALL); + hhcd->hc[ch_num].state = HC_STALL; + (void)USB_HC_Halt(hhcd->Instance, (uint8_t)ch_num); + } + else if ((USBx_HC(ch_num)->HCHINT & USB_OTG_HCHINT_RXNAK) == USB_OTG_HCHINT_RXNAK) + { + hhcd->hc[ch_num].ErrCnt = 0U; + hhcd->hc[ch_num].state = HC_NAK; + + if (hhcd->hc[ch_num].do_ping == 0U) + { + if (hhcd->hc[ch_num].speed == HCD_DEVICE_SPEED_HIGH) + { + hhcd->hc[ch_num].do_ping = 1U; + } + } + + (void)USB_HC_Halt(hhcd->Instance, (uint8_t)ch_num); + __DAL_HCD_CLEAR_HC_INT(ch_num, USB_OTG_HCHINT_RXNAK); + } + else if ((USBx_HC(ch_num)->HCHINT & USB_OTG_HCHINT_TERR) == USB_OTG_HCHINT_TERR) + { + if (hhcd->Init.dma_enable == 0U) + { + hhcd->hc[ch_num].state = HC_XACTERR; + (void)USB_HC_Halt(hhcd->Instance, (uint8_t)ch_num); + } + else + { + hhcd->hc[ch_num].ErrCnt++; + if (hhcd->hc[ch_num].ErrCnt > 2U) + { + hhcd->hc[ch_num].ErrCnt = 0U; + hhcd->hc[ch_num].urb_state = URB_ERROR; + +#if (USE_DAL_HCD_REGISTER_CALLBACKS == 1U) + hhcd->HC_NotifyURBChangeCallback(hhcd, (uint8_t)ch_num, hhcd->hc[ch_num].urb_state); +#else + DAL_HCD_HC_NotifyURBChange_Callback(hhcd, (uint8_t)ch_num, hhcd->hc[ch_num].urb_state); +#endif /* USE_DAL_HCD_REGISTER_CALLBACKS */ + } + else + { + hhcd->hc[ch_num].urb_state = URB_NOTREADY; + } + } + __DAL_HCD_CLEAR_HC_INT(ch_num, USB_OTG_HCHINT_TERR); + } + else if ((USBx_HC(ch_num)->HCHINT & USB_OTG_HCHINT_DTOG) == USB_OTG_HCHINT_DTOG) + { + hhcd->hc[ch_num].state = HC_DATATGLERR; + (void)USB_HC_Halt(hhcd->Instance, (uint8_t)ch_num); + __DAL_HCD_CLEAR_HC_INT(ch_num, USB_OTG_HCHINT_DTOG); + } + else if ((USBx_HC(ch_num)->HCHINT & USB_OTG_HCHINT_TSFCMPAN) == USB_OTG_HCHINT_TSFCMPAN) + { + if (hhcd->hc[ch_num].state == HC_XFRC) + { + hhcd->hc[ch_num].urb_state = URB_DONE; + if ((hhcd->hc[ch_num].ep_type == EP_TYPE_BULK) || + (hhcd->hc[ch_num].ep_type == EP_TYPE_INTR)) + { + if (hhcd->Init.dma_enable == 0U) + { + hhcd->hc[ch_num].toggle_out ^= 1U; + } + + if ((hhcd->Init.dma_enable == 1U) && (hhcd->hc[ch_num].xfer_len > 0U)) + { + num_packets = (hhcd->hc[ch_num].xfer_len + hhcd->hc[ch_num].max_packet - 1U) / hhcd->hc[ch_num].max_packet; + + if ((num_packets & 1U) != 0U) + { + hhcd->hc[ch_num].toggle_out ^= 1U; + } + } + } + } + else if (hhcd->hc[ch_num].state == HC_NAK) + { + hhcd->hc[ch_num].urb_state = URB_NOTREADY; + } + else if (hhcd->hc[ch_num].state == HC_NYET) + { + hhcd->hc[ch_num].urb_state = URB_NOTREADY; + } + else if (hhcd->hc[ch_num].state == HC_STALL) + { + hhcd->hc[ch_num].urb_state = URB_STALL; + } + else if ((hhcd->hc[ch_num].state == HC_XACTERR) || + (hhcd->hc[ch_num].state == HC_DATATGLERR)) + { + hhcd->hc[ch_num].ErrCnt++; + if (hhcd->hc[ch_num].ErrCnt > 2U) + { + hhcd->hc[ch_num].ErrCnt = 0U; + hhcd->hc[ch_num].urb_state = URB_ERROR; + } + else + { + hhcd->hc[ch_num].urb_state = URB_NOTREADY; + + /* re-activate the channel */ + tmpreg = USBx_HC(ch_num)->HCH; + tmpreg &= ~USB_OTG_HCH_CHINT; + tmpreg |= USB_OTG_HCH_CHEN; + USBx_HC(ch_num)->HCH = tmpreg; + } + } + else + { + /* ... */ + } + + __DAL_HCD_CLEAR_HC_INT(ch_num, USB_OTG_HCHINT_TSFCMPAN); + +#if (USE_DAL_HCD_REGISTER_CALLBACKS == 1U) + hhcd->HC_NotifyURBChangeCallback(hhcd, (uint8_t)ch_num, hhcd->hc[ch_num].urb_state); +#else + DAL_HCD_HC_NotifyURBChange_Callback(hhcd, (uint8_t)ch_num, hhcd->hc[ch_num].urb_state); +#endif /* USE_DAL_HCD_REGISTER_CALLBACKS */ + } + else + { + /* ... */ + } +} + +/** + * @brief Handle Rx Queue Level interrupt requests. + * @param hhcd HCD handle + * @retval none + */ +static void HCD_RXQLVL_IRQHandler(HCD_HandleTypeDef *hhcd) +{ + USB_OTG_GlobalTypeDef *USBx = hhcd->Instance; + uint32_t USBx_BASE = (uint32_t)USBx; + uint32_t pktsts; + uint32_t pktcnt; + uint32_t GrxstspReg; + uint32_t xferSizePktCnt; + uint32_t tmpreg; + uint32_t ch_num; + + GrxstspReg = hhcd->Instance->GRXSTSP; + ch_num = GrxstspReg & USB_OTG_GRXSTSP_EPNUM; + pktsts = (GrxstspReg & USB_OTG_GRXSTSP_PSTS) >> 17; + pktcnt = (GrxstspReg & USB_OTG_GRXSTSP_BCNT) >> 4; + + switch (pktsts) + { + case GRXSTS_PKTSTS_IN: + /* Read the data into the host buffer. */ + if ((pktcnt > 0U) && (hhcd->hc[ch_num].xfer_buff != (void *)0)) + { + if ((hhcd->hc[ch_num].xfer_count + pktcnt) <= hhcd->hc[ch_num].xfer_len) + { + (void)USB_ReadPacket(hhcd->Instance, + hhcd->hc[ch_num].xfer_buff, (uint16_t)pktcnt); + + /* manage multiple Xfer */ + hhcd->hc[ch_num].xfer_buff += pktcnt; + hhcd->hc[ch_num].xfer_count += pktcnt; + + /* get transfer size packet count */ + xferSizePktCnt = (USBx_HC(ch_num)->HCHTSIZE & USB_OTG_HCHTSIZE_PCKTCNT) >> 19; + + if ((hhcd->hc[ch_num].max_packet == pktcnt) && (xferSizePktCnt > 0U)) + { + /* re-activate the channel when more packets are expected */ + tmpreg = USBx_HC(ch_num)->HCH; + tmpreg &= ~USB_OTG_HCH_CHINT; + tmpreg |= USB_OTG_HCH_CHEN; + USBx_HC(ch_num)->HCH = tmpreg; + hhcd->hc[ch_num].toggle_in ^= 1U; + } + } + else + { + hhcd->hc[ch_num].urb_state = URB_ERROR; + } + } + break; + + case GRXSTS_PKTSTS_DATA_TOGGLE_ERR: + break; + + case GRXSTS_PKTSTS_IN_XFER_COMP: + case GRXSTS_PKTSTS_CH_HALTED: + default: + break; + } +} + +/** + * @brief Handle Host Port interrupt requests. + * @param hhcd HCD handle + * @retval None + */ +static void HCD_Port_IRQHandler(HCD_HandleTypeDef *hhcd) +{ + USB_OTG_GlobalTypeDef *USBx = hhcd->Instance; + uint32_t USBx_BASE = (uint32_t)USBx; + __IO uint32_t hprt0; + __IO uint32_t hprt0_dup; + + /* Handle Host Port Interrupts */ + hprt0 = USBx_HPRT0; + hprt0_dup = USBx_HPRT0; + + hprt0_dup &= ~(USB_OTG_HPORTCSTS_PEN | USB_OTG_HPORTCSTS_PCINTFLG | \ + USB_OTG_HPORTCSTS_PENCHG | USB_OTG_HPORTCSTS_POVCCHG); + + /* Check whether Port Connect detected */ + if ((hprt0 & USB_OTG_HPORTCSTS_PCINTFLG) == USB_OTG_HPORTCSTS_PCINTFLG) + { + if ((hprt0 & USB_OTG_HPORTCSTS_PCNNTFLG) == USB_OTG_HPORTCSTS_PCNNTFLG) + { +#if (USE_DAL_HCD_REGISTER_CALLBACKS == 1U) + hhcd->ConnectCallback(hhcd); +#else + DAL_HCD_Connect_Callback(hhcd); +#endif /* USE_DAL_HCD_REGISTER_CALLBACKS */ + } + hprt0_dup |= USB_OTG_HPORTCSTS_PCINTFLG; + } + + /* Check whether Port Enable Changed */ + if ((hprt0 & USB_OTG_HPORTCSTS_PENCHG) == USB_OTG_HPORTCSTS_PENCHG) + { + hprt0_dup |= USB_OTG_HPORTCSTS_PENCHG; + + if ((hprt0 & USB_OTG_HPORTCSTS_PEN) == USB_OTG_HPORTCSTS_PEN) + { + if (hhcd->Init.phy_itface == USB_OTG_EMBEDDED_PHY) + { +#if defined(APM32F405xx) || defined(APM32F407xx) || defined(APM32F417xx) + if (hhcd->Init.speed == USBH_HS_SPEED) + { + if ((hprt0 & USB_OTG_HPORTCSTS_PSPDSEL) == (HPRT0_PRTSPD_LOW_SPEED << 17)) + { + (void)USB_InitFSLSPClkSel(hhcd->Instance, HCFG_6_MHZ); + } + else if ((hprt0 & USB_OTG_HPORTCSTS_PSPDSEL) == (HPRT0_PRTSPD_FULL_SPEED << 17)) + { + (void)USB_InitFSLSPClkSel(hhcd->Instance, HCFG_48_MHZ); + } + else + { + (void)USB_InitFSLSPClkSel(hhcd->Instance, HCFG_30_60_MHZ); + } + } + else + { + if ((hprt0 & USB_OTG_HPORTCSTS_PSPDSEL) == (HPRT0_PRTSPD_LOW_SPEED << 17)) + { + (void)USB_InitFSLSPClkSel(hhcd->Instance, HCFG_6_MHZ); + } + else + { + (void)USB_InitFSLSPClkSel(hhcd->Instance, HCFG_48_MHZ); + } + } +#else + if ((hprt0 & USB_OTG_HPORTCSTS_PSPDSEL) == (HPRT0_PRTSPD_LOW_SPEED << 17)) + { + (void)USB_InitFSLSPClkSel(hhcd->Instance, HCFG_6_MHZ); + } + else + { + (void)USB_InitFSLSPClkSel(hhcd->Instance, HCFG_48_MHZ); + } +#endif /* APM32F405xx || APM32F407xx || APM32F417xx */ + } + else + { + if (hhcd->Init.speed == HCD_SPEED_FULL) + { + USBx_HOST->HFIVL = 60000U; + } + } +#if (USE_DAL_HCD_REGISTER_CALLBACKS == 1U) + hhcd->PortEnabledCallback(hhcd); +#else + DAL_HCD_PortEnabled_Callback(hhcd); +#endif /* USE_DAL_HCD_REGISTER_CALLBACKS */ + + } + else + { +#if (USE_DAL_HCD_REGISTER_CALLBACKS == 1U) + hhcd->PortDisabledCallback(hhcd); +#else + DAL_HCD_PortDisabled_Callback(hhcd); +#endif /* USE_DAL_HCD_REGISTER_CALLBACKS */ + } + } + + /* Check for an overcurrent */ + if ((hprt0 & USB_OTG_HPORTCSTS_POVCCHG) == USB_OTG_HPORTCSTS_POVCCHG) + { + hprt0_dup |= USB_OTG_HPORTCSTS_POVCCHG; + } + + /* Clear Port Interrupts */ + USBx_HPRT0 = hprt0_dup; +} + +/** + * @} + */ + +/** + * @} + */ + +#endif /* defined (USB_OTG_FS) || defined (USB_OTG_HS) */ +#endif /* DAL_HCD_MODULE_ENABLED */ + +/** + * @} + */ + +/** + * @} + */ diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_i2c.c b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_i2c.c new file mode 100644 index 0000000000..e3f36958a4 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_i2c.c @@ -0,0 +1,7549 @@ +/** + * + * @file apm32f4xx_dal_i2c.c + * @brief I2C DAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the Inter Integrated Circuit (I2C) peripheral: + * + Initialization and de-initialization functions + * + IO operation functions + * + Peripheral State, Mode and Error functions + * + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + * + @verbatim + ============================================================================== + ##### How to use this driver ##### + ============================================================================== + [..] + The I2C DAL driver can be used as follows: + + (#) Declare a I2C_HandleTypeDef handle structure, for example: + I2C_HandleTypeDef hi2c; + + (#)Initialize the I2C low level resources by implementing the DAL_I2C_MspInit() API: + (##) Enable the I2Cx interface clock + (##) I2C pins configuration + (+++) Enable the clock for the I2C GPIOs + (+++) Configure I2C pins as alternate function open-drain + (##) NVIC configuration if you need to use interrupt process + (+++) Configure the I2Cx interrupt priority + (+++) Enable the NVIC I2C IRQ Channel + (##) DMA Configuration if you need to use DMA process + (+++) Declare a DMA_HandleTypeDef handle structure for the transmit or receive stream + (+++) Enable the DMAx interface clock using + (+++) Configure the DMA handle parameters + (+++) Configure the DMA Tx or Rx stream + (+++) Associate the initialized DMA handle to the hi2c DMA Tx or Rx handle + (+++) Configure the priority and enable the NVIC for the transfer complete interrupt on + the DMA Tx or Rx stream + + (#) Configure the Communication Speed, Duty cycle, Addressing mode, Own Address1, + Dual Addressing mode, Own Address2, General call and Nostretch mode in the hi2c Init structure. + + (#) Initialize the I2C registers by calling the DAL_I2C_Init(), configures also the low level Hardware + (GPIO, CLOCK, NVIC...etc) by calling the customized DAL_I2C_MspInit() API. + + (#) To check if target device is ready for communication, use the function DAL_I2C_IsDeviceReady() + + (#) For I2C IO and IO MEM operations, three operation modes are available within this driver : + + *** Polling mode IO operation *** + ================================= + [..] + (+) Transmit in master mode an amount of data in blocking mode using DAL_I2C_Master_Transmit() + (+) Receive in master mode an amount of data in blocking mode using DAL_I2C_Master_Receive() + (+) Transmit in slave mode an amount of data in blocking mode using DAL_I2C_Slave_Transmit() + (+) Receive in slave mode an amount of data in blocking mode using DAL_I2C_Slave_Receive() + + *** Polling mode IO MEM operation *** + ===================================== + [..] + (+) Write an amount of data in blocking mode to a specific memory address using DAL_I2C_Mem_Write() + (+) Read an amount of data in blocking mode from a specific memory address using DAL_I2C_Mem_Read() + + + *** Interrupt mode IO operation *** + =================================== + [..] + (+) Transmit in master mode an amount of data in non-blocking mode using DAL_I2C_Master_Transmit_IT() + (+) At transmission end of transfer, DAL_I2C_MasterTxCpltCallback() is executed and user can + add his own code by customization of function pointer DAL_I2C_MasterTxCpltCallback() + (+) Receive in master mode an amount of data in non-blocking mode using DAL_I2C_Master_Receive_IT() + (+) At reception end of transfer, DAL_I2C_MasterRxCpltCallback() is executed and user can + add his own code by customization of function pointer DAL_I2C_MasterRxCpltCallback() + (+) Transmit in slave mode an amount of data in non-blocking mode using DAL_I2C_Slave_Transmit_IT() + (+) At transmission end of transfer, DAL_I2C_SlaveTxCpltCallback() is executed and user can + add his own code by customization of function pointer DAL_I2C_SlaveTxCpltCallback() + (+) Receive in slave mode an amount of data in non-blocking mode using DAL_I2C_Slave_Receive_IT() + (+) At reception end of transfer, DAL_I2C_SlaveRxCpltCallback() is executed and user can + add his own code by customization of function pointer DAL_I2C_SlaveRxCpltCallback() + (+) In case of transfer Error, DAL_I2C_ErrorCallback() function is executed and user can + add his own code by customization of function pointer DAL_I2C_ErrorCallback() + (+) Abort a master I2C process communication with Interrupt using DAL_I2C_Master_Abort_IT() + (+) End of abort process, DAL_I2C_AbortCpltCallback() is executed and user can + add his own code by customization of function pointer DAL_I2C_AbortCpltCallback() + + *** Interrupt mode or DMA mode IO sequential operation *** + ========================================================== + [..] + (@) These interfaces allow to manage a sequential transfer with a repeated start condition + when a direction change during transfer + [..] + (+) A specific option field manage the different steps of a sequential transfer + (+) Option field values are defined through I2C_XferOptions_definition and are listed below: + (++) I2C_FIRST_AND_LAST_FRAME: No sequential usage, functional is same as associated interfaces in no sequential mode + (++) I2C_FIRST_FRAME: Sequential usage, this option allow to manage a sequence with start condition, address + and data to transfer without a final stop condition + (++) I2C_FIRST_AND_NEXT_FRAME: Sequential usage (Master only), this option allow to manage a sequence with start condition, address + and data to transfer without a final stop condition, an then permit a call the same master sequential interface + several times (like DAL_I2C_Master_Seq_Transmit_IT() then DAL_I2C_Master_Seq_Transmit_IT() + or DAL_I2C_Master_Seq_Transmit_DMA() then DAL_I2C_Master_Seq_Transmit_DMA()) + (++) I2C_NEXT_FRAME: Sequential usage, this option allow to manage a sequence with a restart condition, address + and with new data to transfer if the direction change or manage only the new data to transfer + if no direction change and without a final stop condition in both cases + (++) I2C_LAST_FRAME: Sequential usage, this option allow to manage a sequance with a restart condition, address + and with new data to transfer if the direction change or manage only the new data to transfer + if no direction change and with a final stop condition in both cases + (++) I2C_LAST_FRAME_NO_STOP: Sequential usage (Master only), this option allow to manage a restart condition after several call of the same master sequential + interface several times (link with option I2C_FIRST_AND_NEXT_FRAME). + Usage can, transfer several bytes one by one using DAL_I2C_Master_Seq_Transmit_IT(option I2C_FIRST_AND_NEXT_FRAME then I2C_NEXT_FRAME) + or DAL_I2C_Master_Seq_Receive_IT(option I2C_FIRST_AND_NEXT_FRAME then I2C_NEXT_FRAME) + or DAL_I2C_Master_Seq_Transmit_DMA(option I2C_FIRST_AND_NEXT_FRAME then I2C_NEXT_FRAME) + or DAL_I2C_Master_Seq_Receive_DMA(option I2C_FIRST_AND_NEXT_FRAME then I2C_NEXT_FRAME). + Then usage of this option I2C_LAST_FRAME_NO_STOP at the last Transmit or Receive sequence permit to call the opposite interface Receive or Transmit + without stopping the communication and so generate a restart condition. + (++) I2C_OTHER_FRAME: Sequential usage (Master only), this option allow to manage a restart condition after each call of the same master sequential + interface. + Usage can, transfer several bytes one by one with a restart with slave address between each bytes using DAL_I2C_Master_Seq_Transmit_IT(option I2C_FIRST_FRAME then I2C_OTHER_FRAME) + or DAL_I2C_Master_Seq_Receive_IT(option I2C_FIRST_FRAME then I2C_OTHER_FRAME) + or DAL_I2C_Master_Seq_Transmit_DMA(option I2C_FIRST_FRAME then I2C_OTHER_FRAME) + or DAL_I2C_Master_Seq_Receive_DMA(option I2C_FIRST_FRAME then I2C_OTHER_FRAME). + Then usage of this option I2C_OTHER_AND_LAST_FRAME at the last frame to help automatic generation of STOP condition. + + (+) Different sequential I2C interfaces are listed below: + (++) Sequential transmit in master I2C mode an amount of data in non-blocking mode using DAL_I2C_Master_Seq_Transmit_IT() + or using DAL_I2C_Master_Seq_Transmit_DMA() + (+++) At transmission end of current frame transfer, DAL_I2C_MasterTxCpltCallback() is executed and user can + add his own code by customization of function pointer DAL_I2C_MasterTxCpltCallback() + (++) Sequential receive in master I2C mode an amount of data in non-blocking mode using DAL_I2C_Master_Seq_Receive_IT() + or using DAL_I2C_Master_Seq_Receive_DMA() + (+++) At reception end of current frame transfer, DAL_I2C_MasterRxCpltCallback() is executed and user can + add his own code by customization of function pointer DAL_I2C_MasterRxCpltCallback() + (++) Abort a master IT or DMA I2C process communication with Interrupt using DAL_I2C_Master_Abort_IT() + (+++) End of abort process, DAL_I2C_AbortCpltCallback() is executed and user can + add his own code by customization of function pointer DAL_I2C_AbortCpltCallback() + (++) Enable/disable the Address listen mode in slave I2C mode using DAL_I2C_EnableListen_IT() DAL_I2C_DisableListen_IT() + (+++) When address slave I2C match, DAL_I2C_AddrCallback() is executed and user can + add his own code to check the Address Match Code and the transmission direction request by master (Write/Read). + (+++) At Listen mode end DAL_I2C_ListenCpltCallback() is executed and user can + add his own code by customization of function pointer DAL_I2C_ListenCpltCallback() + (++) Sequential transmit in slave I2C mode an amount of data in non-blocking mode using DAL_I2C_Slave_Seq_Transmit_IT() + or using DAL_I2C_Slave_Seq_Transmit_DMA() + (+++) At transmission end of current frame transfer, DAL_I2C_SlaveTxCpltCallback() is executed and user can + add his own code by customization of function pointer DAL_I2C_SlaveTxCpltCallback() + (++) Sequential receive in slave I2C mode an amount of data in non-blocking mode using DAL_I2C_Slave_Seq_Receive_IT() + or using DAL_I2C_Slave_Seq_Receive_DMA() + (+++) At reception end of current frame transfer, DAL_I2C_SlaveRxCpltCallback() is executed and user can + add his own code by customization of function pointer DAL_I2C_SlaveRxCpltCallback() + (++) In case of transfer Error, DAL_I2C_ErrorCallback() function is executed and user can + add his own code by customization of function pointer DAL_I2C_ErrorCallback() + + *** Interrupt mode IO MEM operation *** + ======================================= + [..] + (+) Write an amount of data in non-blocking mode with Interrupt to a specific memory address using + DAL_I2C_Mem_Write_IT() + (+) At Memory end of write transfer, DAL_I2C_MemTxCpltCallback() is executed and user can + add his own code by customization of function pointer DAL_I2C_MemTxCpltCallback() + (+) Read an amount of data in non-blocking mode with Interrupt from a specific memory address using + DAL_I2C_Mem_Read_IT() + (+) At Memory end of read transfer, DAL_I2C_MemRxCpltCallback() is executed and user can + add his own code by customization of function pointer DAL_I2C_MemRxCpltCallback() + (+) In case of transfer Error, DAL_I2C_ErrorCallback() function is executed and user can + add his own code by customization of function pointer DAL_I2C_ErrorCallback() + + *** DMA mode IO operation *** + ============================== + [..] + (+) Transmit in master mode an amount of data in non-blocking mode (DMA) using + DAL_I2C_Master_Transmit_DMA() + (+) At transmission end of transfer, DAL_I2C_MasterTxCpltCallback() is executed and user can + add his own code by customization of function pointer DAL_I2C_MasterTxCpltCallback() + (+) Receive in master mode an amount of data in non-blocking mode (DMA) using + DAL_I2C_Master_Receive_DMA() + (+) At reception end of transfer, DAL_I2C_MasterRxCpltCallback() is executed and user can + add his own code by customization of function pointer DAL_I2C_MasterRxCpltCallback() + (+) Transmit in slave mode an amount of data in non-blocking mode (DMA) using + DAL_I2C_Slave_Transmit_DMA() + (+) At transmission end of transfer, DAL_I2C_SlaveTxCpltCallback() is executed and user can + add his own code by customization of function pointer DAL_I2C_SlaveTxCpltCallback() + (+) Receive in slave mode an amount of data in non-blocking mode (DMA) using + DAL_I2C_Slave_Receive_DMA() + (+) At reception end of transfer, DAL_I2C_SlaveRxCpltCallback() is executed and user can + add his own code by customization of function pointer DAL_I2C_SlaveRxCpltCallback() + (+) In case of transfer Error, DAL_I2C_ErrorCallback() function is executed and user can + add his own code by customization of function pointer DAL_I2C_ErrorCallback() + (+) Abort a master I2C process communication with Interrupt using DAL_I2C_Master_Abort_IT() + (+) End of abort process, DAL_I2C_AbortCpltCallback() is executed and user can + add his own code by customization of function pointer DAL_I2C_AbortCpltCallback() + + *** DMA mode IO MEM operation *** + ================================= + [..] + (+) Write an amount of data in non-blocking mode with DMA to a specific memory address using + DAL_I2C_Mem_Write_DMA() + (+) At Memory end of write transfer, DAL_I2C_MemTxCpltCallback() is executed and user can + add his own code by customization of function pointer DAL_I2C_MemTxCpltCallback() + (+) Read an amount of data in non-blocking mode with DMA from a specific memory address using + DAL_I2C_Mem_Read_DMA() + (+) At Memory end of read transfer, DAL_I2C_MemRxCpltCallback() is executed and user can + add his own code by customization of function pointer DAL_I2C_MemRxCpltCallback() + (+) In case of transfer Error, DAL_I2C_ErrorCallback() function is executed and user can + add his own code by customization of function pointer DAL_I2C_ErrorCallback() + + + *** I2C DAL driver macros list *** + ================================== + [..] + Below the list of most used macros in I2C DAL driver. + + (+) __DAL_I2C_ENABLE: Enable the I2C peripheral + (+) __DAL_I2C_DISABLE: Disable the I2C peripheral + (+) __DAL_I2C_GET_FLAG: Checks whether the specified I2C flag is set or not + (+) __DAL_I2C_CLEAR_FLAG: Clear the specified I2C pending flag + (+) __DAL_I2C_ENABLE_IT: Enable the specified I2C interrupt + (+) __DAL_I2C_DISABLE_IT: Disable the specified I2C interrupt + + *** Callback registration *** + ============================================= + [..] + The compilation flag USE_DAL_I2C_REGISTER_CALLBACKS when set to 1 + allows the user to configure dynamically the driver callbacks. + Use Functions DAL_I2C_RegisterCallback() or DAL_I2C_RegisterAddrCallback() + to register an interrupt callback. + [..] + Function DAL_I2C_RegisterCallback() allows to register following callbacks: + (+) MasterTxCpltCallback : callback for Master transmission end of transfer. + (+) MasterRxCpltCallback : callback for Master reception end of transfer. + (+) SlaveTxCpltCallback : callback for Slave transmission end of transfer. + (+) SlaveRxCpltCallback : callback for Slave reception end of transfer. + (+) ListenCpltCallback : callback for end of listen mode. + (+) MemTxCpltCallback : callback for Memory transmission end of transfer. + (+) MemRxCpltCallback : callback for Memory reception end of transfer. + (+) ErrorCallback : callback for error detection. + (+) AbortCpltCallback : callback for abort completion process. + (+) MspInitCallback : callback for Msp Init. + (+) MspDeInitCallback : callback for Msp DeInit. + This function takes as parameters the DAL peripheral handle, the Callback ID + and a pointer to the user callback function. + [..] + For specific callback AddrCallback use dedicated register callbacks : DAL_I2C_RegisterAddrCallback(). + [..] + Use function DAL_I2C_UnRegisterCallback to reset a callback to the default + weak function. + DAL_I2C_UnRegisterCallback takes as parameters the DAL peripheral handle, + and the Callback ID. + This function allows to reset following callbacks: + (+) MasterTxCpltCallback : callback for Master transmission end of transfer. + (+) MasterRxCpltCallback : callback for Master reception end of transfer. + (+) SlaveTxCpltCallback : callback for Slave transmission end of transfer. + (+) SlaveRxCpltCallback : callback for Slave reception end of transfer. + (+) ListenCpltCallback : callback for end of listen mode. + (+) MemTxCpltCallback : callback for Memory transmission end of transfer. + (+) MemRxCpltCallback : callback for Memory reception end of transfer. + (+) ErrorCallback : callback for error detection. + (+) AbortCpltCallback : callback for abort completion process. + (+) MspInitCallback : callback for Msp Init. + (+) MspDeInitCallback : callback for Msp DeInit. + [..] + For callback AddrCallback use dedicated register callbacks : DAL_I2C_UnRegisterAddrCallback(). + [..] + By default, after the DAL_I2C_Init() and when the state is DAL_I2C_STATE_RESET + all callbacks are set to the corresponding weak functions: + examples DAL_I2C_MasterTxCpltCallback(), DAL_I2C_MasterRxCpltCallback(). + Exception done for MspInit and MspDeInit functions that are + reset to the legacy weak functions in the DAL_I2C_Init()/ DAL_I2C_DeInit() only when + these callbacks are null (not registered beforehand). + If MspInit or MspDeInit are not null, the DAL_I2C_Init()/ DAL_I2C_DeInit() + keep and use the user MspInit/MspDeInit callbacks (registered beforehand) whatever the state. + [..] + Callbacks can be registered/unregistered in DAL_I2C_STATE_READY state only. + Exception done MspInit/MspDeInit functions that can be registered/unregistered + in DAL_I2C_STATE_READY or DAL_I2C_STATE_RESET state, + thus registered (user) MspInit/DeInit callbacks can be used during the Init/DeInit. + Then, the user first registers the MspInit/MspDeInit user callbacks + using DAL_I2C_RegisterCallback() before calling DAL_I2C_DeInit() + or DAL_I2C_Init() function. + [..] + When the compilation flag USE_DAL_I2C_REGISTER_CALLBACKS is set to 0 or + not defined, the callback registration feature is not available and all callbacks + are set to the corresponding weak functions. + + + + [..] + (@) You can refer to the I2C DAL driver header file for more useful macros + + @endverbatim + */ + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @defgroup I2C I2C + * @brief I2C DAL module driver + * @{ + */ + +#ifdef DAL_I2C_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/** @addtogroup I2C_Private_Define + * @{ + */ +#define I2C_TIMEOUT_FLAG 35U /*!< Timeout 35 ms */ +#define I2C_TIMEOUT_BUSY_FLAG 25U /*!< Timeout 25 ms */ +#define I2C_TIMEOUT_STOP_FLAG 5U /*!< Timeout 5 ms */ +#define I2C_NO_OPTION_FRAME 0xFFFF0000U /*!< XferOptions default value */ + +/* Private define for @ref PreviousState usage */ +#define I2C_STATE_MSK ((uint32_t)((uint32_t)((uint32_t)DAL_I2C_STATE_BUSY_TX | (uint32_t)DAL_I2C_STATE_BUSY_RX) & (uint32_t)(~((uint32_t)DAL_I2C_STATE_READY)))) /*!< Mask State define, keep only RX and TX bits */ +#define I2C_STATE_NONE ((uint32_t)(DAL_I2C_MODE_NONE)) /*!< Default Value */ +#define I2C_STATE_MASTER_BUSY_TX ((uint32_t)(((uint32_t)DAL_I2C_STATE_BUSY_TX & I2C_STATE_MSK) | (uint32_t)DAL_I2C_MODE_MASTER)) /*!< Master Busy TX, combinaison of State LSB and Mode enum */ +#define I2C_STATE_MASTER_BUSY_RX ((uint32_t)(((uint32_t)DAL_I2C_STATE_BUSY_RX & I2C_STATE_MSK) | (uint32_t)DAL_I2C_MODE_MASTER)) /*!< Master Busy RX, combinaison of State LSB and Mode enum */ +#define I2C_STATE_SLAVE_BUSY_TX ((uint32_t)(((uint32_t)DAL_I2C_STATE_BUSY_TX & I2C_STATE_MSK) | (uint32_t)DAL_I2C_MODE_SLAVE)) /*!< Slave Busy TX, combinaison of State LSB and Mode enum */ +#define I2C_STATE_SLAVE_BUSY_RX ((uint32_t)(((uint32_t)DAL_I2C_STATE_BUSY_RX & I2C_STATE_MSK) | (uint32_t)DAL_I2C_MODE_SLAVE)) /*!< Slave Busy RX, combinaison of State LSB and Mode enum */ + +/** + * @} + */ + +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ + +/** @defgroup I2C_Private_Functions I2C Private Functions + * @{ + */ +/* Private functions to handle DMA transfer */ +static void I2C_DMAXferCplt(DMA_HandleTypeDef *hdma); +static void I2C_DMAError(DMA_HandleTypeDef *hdma); +static void I2C_DMAAbort(DMA_HandleTypeDef *hdma); + +static void I2C_ITError(I2C_HandleTypeDef *hi2c); + +static DAL_StatusTypeDef I2C_MasterRequestWrite(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint32_t Timeout, uint32_t Tickstart); +static DAL_StatusTypeDef I2C_MasterRequestRead(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint32_t Timeout, uint32_t Tickstart); +static DAL_StatusTypeDef I2C_RequestMemoryWrite(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint32_t Timeout, uint32_t Tickstart); +static DAL_StatusTypeDef I2C_RequestMemoryRead(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint32_t Timeout, uint32_t Tickstart); + +/* Private functions to handle flags during polling transfer */ +static DAL_StatusTypeDef I2C_WaitOnFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Flag, FlagStatus Status, uint32_t Timeout, uint32_t Tickstart); +static DAL_StatusTypeDef I2C_WaitOnMasterAddressFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Flag, uint32_t Timeout, uint32_t Tickstart); +static DAL_StatusTypeDef I2C_WaitOnTXEFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Timeout, uint32_t Tickstart); +static DAL_StatusTypeDef I2C_WaitOnBTFFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Timeout, uint32_t Tickstart); +static DAL_StatusTypeDef I2C_WaitOnRXNEFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Timeout, uint32_t Tickstart); +static DAL_StatusTypeDef I2C_WaitOnSTOPFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Timeout, uint32_t Tickstart); +static DAL_StatusTypeDef I2C_WaitOnSTOPRequestThroughIT(I2C_HandleTypeDef *hi2c); +static DAL_StatusTypeDef I2C_IsAcknowledgeFailed(I2C_HandleTypeDef *hi2c); + +/* Private functions for I2C transfer IRQ handler */ +static void I2C_MasterTransmit_TXE(I2C_HandleTypeDef *hi2c); +static void I2C_MasterTransmit_BTF(I2C_HandleTypeDef *hi2c); +static void I2C_MasterReceive_RXNE(I2C_HandleTypeDef *hi2c); +static void I2C_MasterReceive_BTF(I2C_HandleTypeDef *hi2c); +static void I2C_Master_SB(I2C_HandleTypeDef *hi2c); +static void I2C_Master_ADD10(I2C_HandleTypeDef *hi2c); +static void I2C_Master_ADDR(I2C_HandleTypeDef *hi2c); + +static void I2C_SlaveTransmit_TXE(I2C_HandleTypeDef *hi2c); +static void I2C_SlaveTransmit_BTF(I2C_HandleTypeDef *hi2c); +static void I2C_SlaveReceive_RXNE(I2C_HandleTypeDef *hi2c); +static void I2C_SlaveReceive_BTF(I2C_HandleTypeDef *hi2c); +static void I2C_Slave_ADDR(I2C_HandleTypeDef *hi2c, uint32_t IT2Flags); +static void I2C_Slave_STOPF(I2C_HandleTypeDef *hi2c); +static void I2C_Slave_AF(I2C_HandleTypeDef *hi2c); + +static void I2C_MemoryTransmit_TXE_BTF(I2C_HandleTypeDef *hi2c); + +/* Private function to Convert Specific options */ +static void I2C_ConvertOtherXferOptions(I2C_HandleTypeDef *hi2c); +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ + +/** @defgroup I2C_Exported_Functions I2C Exported Functions + * @{ + */ + +/** @defgroup I2C_Exported_Functions_Group1 Initialization and de-initialization functions + * @brief Initialization and Configuration functions + * +@verbatim + =============================================================================== + ##### Initialization and de-initialization functions ##### + =============================================================================== + [..] This subsection provides a set of functions allowing to initialize and + deinitialize the I2Cx peripheral: + + (+) User must Implement DAL_I2C_MspInit() function in which he configures + all related peripherals resources (CLOCK, GPIO, DMA, IT and NVIC). + + (+) Call the function DAL_I2C_Init() to configure the selected device with + the selected configuration: + (++) Communication Speed + (++) Duty cycle + (++) Addressing mode + (++) Own Address 1 + (++) Dual Addressing mode + (++) Own Address 2 + (++) General call mode + (++) Nostretch mode + + (+) Call the function DAL_I2C_DeInit() to restore the default configuration + of the selected I2Cx peripheral. + +@endverbatim + * @{ + */ + +/** + * @brief Initializes the I2C according to the specified parameters + * in the I2C_InitTypeDef and initialize the associated handle. + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_I2C_Init(I2C_HandleTypeDef *hi2c) +{ + uint32_t freqrange; + uint32_t pclk1; + + /* Check the I2C handle allocation */ + if (hi2c == NULL) + { + return DAL_ERROR; + } + + /* Check the parameters */ + ASSERT_PARAM(IS_I2C_ALL_INSTANCE(hi2c->Instance)); + ASSERT_PARAM(IS_I2C_CLOCK_SPEED(hi2c->Init.ClockSpeed)); + ASSERT_PARAM(IS_I2C_DUTY_CYCLE(hi2c->Init.DutyCycle)); + ASSERT_PARAM(IS_I2C_OWN_ADDRESS1(hi2c->Init.OwnAddress1)); + ASSERT_PARAM(IS_I2C_ADDRESSING_MODE(hi2c->Init.AddressingMode)); + ASSERT_PARAM(IS_I2C_DUAL_ADDRESS(hi2c->Init.DualAddressMode)); + ASSERT_PARAM(IS_I2C_OWN_ADDRESS2(hi2c->Init.OwnAddress2)); + ASSERT_PARAM(IS_I2C_GENERAL_CALL(hi2c->Init.GeneralCallMode)); + ASSERT_PARAM(IS_I2C_NO_STRETCH(hi2c->Init.NoStretchMode)); + + if (hi2c->State == DAL_I2C_STATE_RESET) + { + /* Allocate lock resource and initialize it */ + hi2c->Lock = DAL_UNLOCKED; + +#if (USE_DAL_I2C_REGISTER_CALLBACKS == 1) + /* Init the I2C Callback settings */ + hi2c->MasterTxCpltCallback = DAL_I2C_MasterTxCpltCallback; /* Legacy weak MasterTxCpltCallback */ + hi2c->MasterRxCpltCallback = DAL_I2C_MasterRxCpltCallback; /* Legacy weak MasterRxCpltCallback */ + hi2c->SlaveTxCpltCallback = DAL_I2C_SlaveTxCpltCallback; /* Legacy weak SlaveTxCpltCallback */ + hi2c->SlaveRxCpltCallback = DAL_I2C_SlaveRxCpltCallback; /* Legacy weak SlaveRxCpltCallback */ + hi2c->ListenCpltCallback = DAL_I2C_ListenCpltCallback; /* Legacy weak ListenCpltCallback */ + hi2c->MemTxCpltCallback = DAL_I2C_MemTxCpltCallback; /* Legacy weak MemTxCpltCallback */ + hi2c->MemRxCpltCallback = DAL_I2C_MemRxCpltCallback; /* Legacy weak MemRxCpltCallback */ + hi2c->ErrorCallback = DAL_I2C_ErrorCallback; /* Legacy weak ErrorCallback */ + hi2c->AbortCpltCallback = DAL_I2C_AbortCpltCallback; /* Legacy weak AbortCpltCallback */ + hi2c->AddrCallback = DAL_I2C_AddrCallback; /* Legacy weak AddrCallback */ + + if (hi2c->MspInitCallback == NULL) + { + hi2c->MspInitCallback = DAL_I2C_MspInit; /* Legacy weak MspInit */ + } + + /* Init the low level hardware : GPIO, CLOCK, NVIC */ + hi2c->MspInitCallback(hi2c); +#else + /* Init the low level hardware : GPIO, CLOCK, NVIC */ + DAL_I2C_MspInit(hi2c); +#endif /* USE_DAL_I2C_REGISTER_CALLBACKS */ + } + + hi2c->State = DAL_I2C_STATE_BUSY; + + /* Disable the selected I2C peripheral */ + __DAL_I2C_DISABLE(hi2c); + + /*Reset I2C*/ + hi2c->Instance->CTRL1 |= I2C_CTRL1_SWRST; + hi2c->Instance->CTRL1 &= ~I2C_CTRL1_SWRST; + + /* Get PCLK1 frequency */ + pclk1 = DAL_RCM_GetPCLK1Freq(); + + /* Check the minimum allowed PCLK1 frequency */ + if (I2C_MIN_PCLK_FREQ(pclk1, hi2c->Init.ClockSpeed) == 1U) + { + return DAL_ERROR; + } + + /* Calculate frequency range */ + freqrange = I2C_FREQRANGE(pclk1); + + /*---------------------------- I2Cx CTRL2 Configuration ----------------------*/ + /* Configure I2Cx: Frequency range */ + MODIFY_REG(hi2c->Instance->CTRL2, I2C_CTRL2_CLKFCFG, freqrange); + + /*---------------------------- I2Cx RISETMAX Configuration --------------------*/ + /* Configure I2Cx: Rise Time */ + MODIFY_REG(hi2c->Instance->RISETMAX, I2C_RISETMAX_RISETMAX, I2C_RISE_TIME(freqrange, hi2c->Init.ClockSpeed)); + + /*---------------------------- I2Cx CLKCTRL Configuration ----------------------*/ + /* Configure I2Cx: Speed */ + MODIFY_REG(hi2c->Instance->CLKCTRL, (I2C_CLKCTRL_SPEEDCFG | I2C_CLKCTRL_FDUTYCFG | I2C_CLKCTRL_CLKS), I2C_SPEED(pclk1, hi2c->Init.ClockSpeed, hi2c->Init.DutyCycle)); + + /*---------------------------- I2Cx CTRL1 Configuration ----------------------*/ + /* Configure I2Cx: Generalcall and NoStretch mode */ + MODIFY_REG(hi2c->Instance->CTRL1, (I2C_CTRL1_SRBEN | I2C_CTRL1_CLKSTRETCHD), (hi2c->Init.GeneralCallMode | hi2c->Init.NoStretchMode)); + + /*---------------------------- I2Cx SADDR1 Configuration ---------------------*/ + /* Configure I2Cx: Own Address1 and addressing mode */ + MODIFY_REG(hi2c->Instance->SADDR1, (I2C_SADDR1_ADDRLEN | I2C_SADDR1_ADDR8_9 | I2C_SADDR1_ADDR1_7 | I2C_SADDR1_ADDR0), (hi2c->Init.AddressingMode | hi2c->Init.OwnAddress1)); + + /*---------------------------- I2Cx SADDR2 Configuration ---------------------*/ + /* Configure I2Cx: Dual mode and Own Address2 */ + MODIFY_REG(hi2c->Instance->SADDR2, (I2C_SADDR2_ADDRNUM | I2C_SADDR2_ADDR2), (hi2c->Init.DualAddressMode | hi2c->Init.OwnAddress2)); + + /* Enable the selected I2C peripheral */ + __DAL_I2C_ENABLE(hi2c); + + hi2c->ErrorCode = DAL_I2C_ERROR_NONE; + hi2c->State = DAL_I2C_STATE_READY; + hi2c->PreviousState = I2C_STATE_NONE; + hi2c->Mode = DAL_I2C_MODE_NONE; + + return DAL_OK; +} + +/** + * @brief DeInitialize the I2C peripheral. + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_I2C_DeInit(I2C_HandleTypeDef *hi2c) +{ + /* Check the I2C handle allocation */ + if (hi2c == NULL) + { + return DAL_ERROR; + } + + /* Check the parameters */ + ASSERT_PARAM(IS_I2C_ALL_INSTANCE(hi2c->Instance)); + + hi2c->State = DAL_I2C_STATE_BUSY; + + /* Disable the I2C Peripheral Clock */ + __DAL_I2C_DISABLE(hi2c); + +#if (USE_DAL_I2C_REGISTER_CALLBACKS == 1) + if (hi2c->MspDeInitCallback == NULL) + { + hi2c->MspDeInitCallback = DAL_I2C_MspDeInit; /* Legacy weak MspDeInit */ + } + + /* DeInit the low level hardware: GPIO, CLOCK, NVIC */ + hi2c->MspDeInitCallback(hi2c); +#else + /* DeInit the low level hardware: GPIO, CLOCK, NVIC */ + DAL_I2C_MspDeInit(hi2c); +#endif /* USE_DAL_I2C_REGISTER_CALLBACKS */ + + hi2c->ErrorCode = DAL_I2C_ERROR_NONE; + hi2c->State = DAL_I2C_STATE_RESET; + hi2c->PreviousState = I2C_STATE_NONE; + hi2c->Mode = DAL_I2C_MODE_NONE; + + /* Release Lock */ + __DAL_UNLOCK(hi2c); + + return DAL_OK; +} + +/** + * @brief Initialize the I2C MSP. + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @retval None + */ +__weak void DAL_I2C_MspInit(I2C_HandleTypeDef *hi2c) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hi2c); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_I2C_MspInit could be implemented in the user file + */ +} + +/** + * @brief DeInitialize the I2C MSP. + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @retval None + */ +__weak void DAL_I2C_MspDeInit(I2C_HandleTypeDef *hi2c) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hi2c); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_I2C_MspDeInit could be implemented in the user file + */ +} + +#if (USE_DAL_I2C_REGISTER_CALLBACKS == 1) +/** + * @brief Register a User I2C Callback + * To be used instead of the weak predefined callback + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param CallbackID ID of the callback to be registered + * This parameter can be one of the following values: + * @arg @ref DAL_I2C_MASTER_TX_COMPLETE_CB_ID Master Tx Transfer completed callback ID + * @arg @ref DAL_I2C_MASTER_RX_COMPLETE_CB_ID Master Rx Transfer completed callback ID + * @arg @ref DAL_I2C_SLAVE_TX_COMPLETE_CB_ID Slave Tx Transfer completed callback ID + * @arg @ref DAL_I2C_SLAVE_RX_COMPLETE_CB_ID Slave Rx Transfer completed callback ID + * @arg @ref DAL_I2C_LISTEN_COMPLETE_CB_ID Listen Complete callback ID + * @arg @ref DAL_I2C_MEM_TX_COMPLETE_CB_ID Memory Tx Transfer callback ID + * @arg @ref DAL_I2C_MEM_RX_COMPLETE_CB_ID Memory Rx Transfer completed callback ID + * @arg @ref DAL_I2C_ERROR_CB_ID Error callback ID + * @arg @ref DAL_I2C_ABORT_CB_ID Abort callback ID + * @arg @ref DAL_I2C_MSPINIT_CB_ID MspInit callback ID + * @arg @ref DAL_I2C_MSPDEINIT_CB_ID MspDeInit callback ID + * @param pCallback pointer to the Callback function + * @retval DAL status + */ +DAL_StatusTypeDef DAL_I2C_RegisterCallback(I2C_HandleTypeDef *hi2c, DAL_I2C_CallbackIDTypeDef CallbackID, pI2C_CallbackTypeDef pCallback) +{ + DAL_StatusTypeDef status = DAL_OK; + + if (pCallback == NULL) + { + /* Update the error code */ + hi2c->ErrorCode |= DAL_I2C_ERROR_INVALID_CALLBACK; + + return DAL_ERROR; + } + /* Process locked */ + __DAL_LOCK(hi2c); + + if (DAL_I2C_STATE_READY == hi2c->State) + { + switch (CallbackID) + { + case DAL_I2C_MASTER_TX_COMPLETE_CB_ID : + hi2c->MasterTxCpltCallback = pCallback; + break; + + case DAL_I2C_MASTER_RX_COMPLETE_CB_ID : + hi2c->MasterRxCpltCallback = pCallback; + break; + + case DAL_I2C_SLAVE_TX_COMPLETE_CB_ID : + hi2c->SlaveTxCpltCallback = pCallback; + break; + + case DAL_I2C_SLAVE_RX_COMPLETE_CB_ID : + hi2c->SlaveRxCpltCallback = pCallback; + break; + + case DAL_I2C_LISTEN_COMPLETE_CB_ID : + hi2c->ListenCpltCallback = pCallback; + break; + + case DAL_I2C_MEM_TX_COMPLETE_CB_ID : + hi2c->MemTxCpltCallback = pCallback; + break; + + case DAL_I2C_MEM_RX_COMPLETE_CB_ID : + hi2c->MemRxCpltCallback = pCallback; + break; + + case DAL_I2C_ERROR_CB_ID : + hi2c->ErrorCallback = pCallback; + break; + + case DAL_I2C_ABORT_CB_ID : + hi2c->AbortCpltCallback = pCallback; + break; + + case DAL_I2C_MSPINIT_CB_ID : + hi2c->MspInitCallback = pCallback; + break; + + case DAL_I2C_MSPDEINIT_CB_ID : + hi2c->MspDeInitCallback = pCallback; + break; + + default : + /* Update the error code */ + hi2c->ErrorCode |= DAL_I2C_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = DAL_ERROR; + break; + } + } + else if (DAL_I2C_STATE_RESET == hi2c->State) + { + switch (CallbackID) + { + case DAL_I2C_MSPINIT_CB_ID : + hi2c->MspInitCallback = pCallback; + break; + + case DAL_I2C_MSPDEINIT_CB_ID : + hi2c->MspDeInitCallback = pCallback; + break; + + default : + /* Update the error code */ + hi2c->ErrorCode |= DAL_I2C_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = DAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + hi2c->ErrorCode |= DAL_I2C_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = DAL_ERROR; + } + + /* Release Lock */ + __DAL_UNLOCK(hi2c); + return status; +} + +/** + * @brief Unregister an I2C Callback + * I2C callback is redirected to the weak predefined callback + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param CallbackID ID of the callback to be unregistered + * This parameter can be one of the following values: + * This parameter can be one of the following values: + * @arg @ref DAL_I2C_MASTER_TX_COMPLETE_CB_ID Master Tx Transfer completed callback ID + * @arg @ref DAL_I2C_MASTER_RX_COMPLETE_CB_ID Master Rx Transfer completed callback ID + * @arg @ref DAL_I2C_SLAVE_TX_COMPLETE_CB_ID Slave Tx Transfer completed callback ID + * @arg @ref DAL_I2C_SLAVE_RX_COMPLETE_CB_ID Slave Rx Transfer completed callback ID + * @arg @ref DAL_I2C_LISTEN_COMPLETE_CB_ID Listen Complete callback ID + * @arg @ref DAL_I2C_MEM_TX_COMPLETE_CB_ID Memory Tx Transfer callback ID + * @arg @ref DAL_I2C_MEM_RX_COMPLETE_CB_ID Memory Rx Transfer completed callback ID + * @arg @ref DAL_I2C_ERROR_CB_ID Error callback ID + * @arg @ref DAL_I2C_ABORT_CB_ID Abort callback ID + * @arg @ref DAL_I2C_MSPINIT_CB_ID MspInit callback ID + * @arg @ref DAL_I2C_MSPDEINIT_CB_ID MspDeInit callback ID + * @retval DAL status + */ +DAL_StatusTypeDef DAL_I2C_UnRegisterCallback(I2C_HandleTypeDef *hi2c, DAL_I2C_CallbackIDTypeDef CallbackID) +{ + DAL_StatusTypeDef status = DAL_OK; + + /* Process locked */ + __DAL_LOCK(hi2c); + + if (DAL_I2C_STATE_READY == hi2c->State) + { + switch (CallbackID) + { + case DAL_I2C_MASTER_TX_COMPLETE_CB_ID : + hi2c->MasterTxCpltCallback = DAL_I2C_MasterTxCpltCallback; /* Legacy weak MasterTxCpltCallback */ + break; + + case DAL_I2C_MASTER_RX_COMPLETE_CB_ID : + hi2c->MasterRxCpltCallback = DAL_I2C_MasterRxCpltCallback; /* Legacy weak MasterRxCpltCallback */ + break; + + case DAL_I2C_SLAVE_TX_COMPLETE_CB_ID : + hi2c->SlaveTxCpltCallback = DAL_I2C_SlaveTxCpltCallback; /* Legacy weak SlaveTxCpltCallback */ + break; + + case DAL_I2C_SLAVE_RX_COMPLETE_CB_ID : + hi2c->SlaveRxCpltCallback = DAL_I2C_SlaveRxCpltCallback; /* Legacy weak SlaveRxCpltCallback */ + break; + + case DAL_I2C_LISTEN_COMPLETE_CB_ID : + hi2c->ListenCpltCallback = DAL_I2C_ListenCpltCallback; /* Legacy weak ListenCpltCallback */ + break; + + case DAL_I2C_MEM_TX_COMPLETE_CB_ID : + hi2c->MemTxCpltCallback = DAL_I2C_MemTxCpltCallback; /* Legacy weak MemTxCpltCallback */ + break; + + case DAL_I2C_MEM_RX_COMPLETE_CB_ID : + hi2c->MemRxCpltCallback = DAL_I2C_MemRxCpltCallback; /* Legacy weak MemRxCpltCallback */ + break; + + case DAL_I2C_ERROR_CB_ID : + hi2c->ErrorCallback = DAL_I2C_ErrorCallback; /* Legacy weak ErrorCallback */ + break; + + case DAL_I2C_ABORT_CB_ID : + hi2c->AbortCpltCallback = DAL_I2C_AbortCpltCallback; /* Legacy weak AbortCpltCallback */ + break; + + case DAL_I2C_MSPINIT_CB_ID : + hi2c->MspInitCallback = DAL_I2C_MspInit; /* Legacy weak MspInit */ + break; + + case DAL_I2C_MSPDEINIT_CB_ID : + hi2c->MspDeInitCallback = DAL_I2C_MspDeInit; /* Legacy weak MspDeInit */ + break; + + default : + /* Update the error code */ + hi2c->ErrorCode |= DAL_I2C_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = DAL_ERROR; + break; + } + } + else if (DAL_I2C_STATE_RESET == hi2c->State) + { + switch (CallbackID) + { + case DAL_I2C_MSPINIT_CB_ID : + hi2c->MspInitCallback = DAL_I2C_MspInit; /* Legacy weak MspInit */ + break; + + case DAL_I2C_MSPDEINIT_CB_ID : + hi2c->MspDeInitCallback = DAL_I2C_MspDeInit; /* Legacy weak MspDeInit */ + break; + + default : + /* Update the error code */ + hi2c->ErrorCode |= DAL_I2C_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = DAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + hi2c->ErrorCode |= DAL_I2C_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = DAL_ERROR; + } + + /* Release Lock */ + __DAL_UNLOCK(hi2c); + return status; +} + +/** + * @brief Register the Slave Address Match I2C Callback + * To be used instead of the weak DAL_I2C_AddrCallback() predefined callback + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param pCallback pointer to the Address Match Callback function + * @retval DAL status + */ +DAL_StatusTypeDef DAL_I2C_RegisterAddrCallback(I2C_HandleTypeDef *hi2c, pI2C_AddrCallbackTypeDef pCallback) +{ + DAL_StatusTypeDef status = DAL_OK; + + if (pCallback == NULL) + { + /* Update the error code */ + hi2c->ErrorCode |= DAL_I2C_ERROR_INVALID_CALLBACK; + + return DAL_ERROR; + } + /* Process locked */ + __DAL_LOCK(hi2c); + + if (DAL_I2C_STATE_READY == hi2c->State) + { + hi2c->AddrCallback = pCallback; + } + else + { + /* Update the error code */ + hi2c->ErrorCode |= DAL_I2C_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = DAL_ERROR; + } + + /* Release Lock */ + __DAL_UNLOCK(hi2c); + return status; +} + +/** + * @brief UnRegister the Slave Address Match I2C Callback + * Info Ready I2C Callback is redirected to the weak DAL_I2C_AddrCallback() predefined callback + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_I2C_UnRegisterAddrCallback(I2C_HandleTypeDef *hi2c) +{ + DAL_StatusTypeDef status = DAL_OK; + + /* Process locked */ + __DAL_LOCK(hi2c); + + if (DAL_I2C_STATE_READY == hi2c->State) + { + hi2c->AddrCallback = DAL_I2C_AddrCallback; /* Legacy weak AddrCallback */ + } + else + { + /* Update the error code */ + hi2c->ErrorCode |= DAL_I2C_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = DAL_ERROR; + } + + /* Release Lock */ + __DAL_UNLOCK(hi2c); + return status; +} + +#endif /* USE_DAL_I2C_REGISTER_CALLBACKS */ + +/** + * @} + */ + +/** @defgroup I2C_Exported_Functions_Group2 Input and Output operation functions + * @brief Data transfers functions + * +@verbatim + =============================================================================== + ##### IO operation functions ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to manage the I2C data + transfers. + + (#) There are two modes of transfer: + (++) Blocking mode : The communication is performed in the polling mode. + The status of all data processing is returned by the same function + after finishing transfer. + (++) No-Blocking mode : The communication is performed using Interrupts + or DMA. These functions return the status of the transfer startup. + The end of the data processing will be indicated through the + dedicated I2C IRQ when using Interrupt mode or the DMA IRQ when + using DMA mode. + + (#) Blocking mode functions are : + (++) DAL_I2C_Master_Transmit() + (++) DAL_I2C_Master_Receive() + (++) DAL_I2C_Slave_Transmit() + (++) DAL_I2C_Slave_Receive() + (++) DAL_I2C_Mem_Write() + (++) DAL_I2C_Mem_Read() + (++) DAL_I2C_IsDeviceReady() + + (#) No-Blocking mode functions with Interrupt are : + (++) DAL_I2C_Master_Transmit_IT() + (++) DAL_I2C_Master_Receive_IT() + (++) DAL_I2C_Slave_Transmit_IT() + (++) DAL_I2C_Slave_Receive_IT() + (++) DAL_I2C_Mem_Write_IT() + (++) DAL_I2C_Mem_Read_IT() + (++) DAL_I2C_Master_Seq_Transmit_IT() + (++) DAL_I2C_Master_Seq_Receive_IT() + (++) DAL_I2C_Slave_Seq_Transmit_IT() + (++) DAL_I2C_Slave_Seq_Receive_IT() + (++) DAL_I2C_EnableListen_IT() + (++) DAL_I2C_DisableListen_IT() + (++) DAL_I2C_Master_Abort_IT() + + (#) No-Blocking mode functions with DMA are : + (++) DAL_I2C_Master_Transmit_DMA() + (++) DAL_I2C_Master_Receive_DMA() + (++) DAL_I2C_Slave_Transmit_DMA() + (++) DAL_I2C_Slave_Receive_DMA() + (++) DAL_I2C_Mem_Write_DMA() + (++) DAL_I2C_Mem_Read_DMA() + (++) DAL_I2C_Master_Seq_Transmit_DMA() + (++) DAL_I2C_Master_Seq_Receive_DMA() + (++) DAL_I2C_Slave_Seq_Transmit_DMA() + (++) DAL_I2C_Slave_Seq_Receive_DMA() + + (#) A set of Transfer Complete Callbacks are provided in non Blocking mode: + (++) DAL_I2C_MasterTxCpltCallback() + (++) DAL_I2C_MasterRxCpltCallback() + (++) DAL_I2C_SlaveTxCpltCallback() + (++) DAL_I2C_SlaveRxCpltCallback() + (++) DAL_I2C_MemTxCpltCallback() + (++) DAL_I2C_MemRxCpltCallback() + (++) DAL_I2C_AddrCallback() + (++) DAL_I2C_ListenCpltCallback() + (++) DAL_I2C_ErrorCallback() + (++) DAL_I2C_AbortCpltCallback() + +@endverbatim + * @{ + */ + +/** + * @brief Transmits in master mode an amount of data in blocking mode. + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param DevAddress Target device address: The device 7 bits address value + * in datasheet must be shifted to the left before calling the interface + * @param pData Pointer to data buffer + * @param Size Amount of data to be sent + * @param Timeout Timeout duration + * @retval DAL status + */ +DAL_StatusTypeDef DAL_I2C_Master_Transmit(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t Timeout) +{ + /* Init tickstart for timeout management*/ + uint32_t tickstart = DAL_GetTick(); + + if (hi2c->State == DAL_I2C_STATE_READY) + { + /* Wait until BUSY flag is reset */ + if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, I2C_TIMEOUT_BUSY_FLAG, tickstart) != DAL_OK) + { + return DAL_BUSY; + } + + /* Process Locked */ + __DAL_LOCK(hi2c); + + /* Check if the I2C is already enabled */ + if ((hi2c->Instance->CTRL1 & I2C_CTRL1_I2CEN) != I2C_CTRL1_I2CEN) + { + /* Enable I2C peripheral */ + __DAL_I2C_ENABLE(hi2c); + } + + /* Disable Pos */ + CLEAR_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKPOS); + + hi2c->State = DAL_I2C_STATE_BUSY_TX; + hi2c->Mode = DAL_I2C_MODE_MASTER; + hi2c->ErrorCode = DAL_I2C_ERROR_NONE; + + /* Prepare transfer parameters */ + hi2c->pBuffPtr = pData; + hi2c->XferCount = Size; + hi2c->XferSize = hi2c->XferCount; + hi2c->XferOptions = I2C_NO_OPTION_FRAME; + + /* Send Slave Address */ + if (I2C_MasterRequestWrite(hi2c, DevAddress, Timeout, tickstart) != DAL_OK) + { + return DAL_ERROR; + } + + /* Clear ADDR flag */ + __DAL_I2C_CLEAR_ADDRFLAG(hi2c); + + while (hi2c->XferSize > 0U) + { + /* Wait until TXE flag is set */ + if (I2C_WaitOnTXEFlagUntilTimeout(hi2c, Timeout, tickstart) != DAL_OK) + { + if (hi2c->ErrorCode == DAL_I2C_ERROR_AF) + { + /* Generate Stop */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_STOP); + } + return DAL_ERROR; + } + + /* Write data to DATA */ + hi2c->Instance->DATA = *hi2c->pBuffPtr; + + /* Increment Buffer pointer */ + hi2c->pBuffPtr++; + + /* Update counter */ + hi2c->XferCount--; + hi2c->XferSize--; + + if ((__DAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BTF) == SET) && (hi2c->XferSize != 0U)) + { + /* Write data to DATA */ + hi2c->Instance->DATA = *hi2c->pBuffPtr; + + /* Increment Buffer pointer */ + hi2c->pBuffPtr++; + + /* Update counter */ + hi2c->XferCount--; + hi2c->XferSize--; + } + + /* Wait until BTF flag is set */ + if (I2C_WaitOnBTFFlagUntilTimeout(hi2c, Timeout, tickstart) != DAL_OK) + { + if (hi2c->ErrorCode == DAL_I2C_ERROR_AF) + { + /* Generate Stop */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_STOP); + } + return DAL_ERROR; + } + } + + /* Generate Stop */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_STOP); + + hi2c->State = DAL_I2C_STATE_READY; + hi2c->Mode = DAL_I2C_MODE_NONE; + + /* Process Unlocked */ + __DAL_UNLOCK(hi2c); + + return DAL_OK; + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief Receives in master mode an amount of data in blocking mode. + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param DevAddress Target device address: The device 7 bits address value + * in datasheet must be shifted to the left before calling the interface + * @param pData Pointer to data buffer + * @param Size Amount of data to be sent + * @param Timeout Timeout duration + * @retval DAL status + */ +DAL_StatusTypeDef DAL_I2C_Master_Receive(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t Timeout) +{ + /* Init tickstart for timeout management*/ + uint32_t tickstart = DAL_GetTick(); + + if (hi2c->State == DAL_I2C_STATE_READY) + { + /* Wait until BUSY flag is reset */ + if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, I2C_TIMEOUT_BUSY_FLAG, tickstart) != DAL_OK) + { + return DAL_BUSY; + } + + /* Process Locked */ + __DAL_LOCK(hi2c); + + /* Check if the I2C is already enabled */ + if ((hi2c->Instance->CTRL1 & I2C_CTRL1_I2CEN) != I2C_CTRL1_I2CEN) + { + /* Enable I2C peripheral */ + __DAL_I2C_ENABLE(hi2c); + } + + /* Disable Pos */ + CLEAR_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKPOS); + + hi2c->State = DAL_I2C_STATE_BUSY_RX; + hi2c->Mode = DAL_I2C_MODE_MASTER; + hi2c->ErrorCode = DAL_I2C_ERROR_NONE; + + /* Prepare transfer parameters */ + hi2c->pBuffPtr = pData; + hi2c->XferCount = Size; + hi2c->XferSize = hi2c->XferCount; + hi2c->XferOptions = I2C_NO_OPTION_FRAME; + + /* Send Slave Address */ + if (I2C_MasterRequestRead(hi2c, DevAddress, Timeout, tickstart) != DAL_OK) + { + return DAL_ERROR; + } + + if (hi2c->XferSize == 0U) + { + /* Clear ADDR flag */ + __DAL_I2C_CLEAR_ADDRFLAG(hi2c); + + /* Generate Stop */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_STOP); + } + else if (hi2c->XferSize == 1U) + { + /* Disable Acknowledge */ + CLEAR_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKEN); + + /* Clear ADDR flag */ + __DAL_I2C_CLEAR_ADDRFLAG(hi2c); + + /* Generate Stop */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_STOP); + } + else if (hi2c->XferSize == 2U) + { + /* Disable Acknowledge */ + CLEAR_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKEN); + + /* Enable Pos */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKPOS); + + /* Clear ADDR flag */ + __DAL_I2C_CLEAR_ADDRFLAG(hi2c); + } + else + { + /* Enable Acknowledge */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKEN); + + /* Clear ADDR flag */ + __DAL_I2C_CLEAR_ADDRFLAG(hi2c); + } + + while (hi2c->XferSize > 0U) + { + if (hi2c->XferSize <= 3U) + { + /* One byte */ + if (hi2c->XferSize == 1U) + { + /* Wait until RXNE flag is set */ + if (I2C_WaitOnRXNEFlagUntilTimeout(hi2c, Timeout, tickstart) != DAL_OK) + { + return DAL_ERROR; + } + + /* Read data from DATA */ + *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->DATA; + + /* Increment Buffer pointer */ + hi2c->pBuffPtr++; + + /* Update counter */ + hi2c->XferSize--; + hi2c->XferCount--; + } + /* Two bytes */ + else if (hi2c->XferSize == 2U) + { + /* Wait until BTF flag is set */ + if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BTF, RESET, Timeout, tickstart) != DAL_OK) + { + return DAL_ERROR; + } + + /* Generate Stop */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_STOP); + + /* Read data from DATA */ + *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->DATA; + + /* Increment Buffer pointer */ + hi2c->pBuffPtr++; + + /* Update counter */ + hi2c->XferSize--; + hi2c->XferCount--; + + /* Read data from DATA */ + *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->DATA; + + /* Increment Buffer pointer */ + hi2c->pBuffPtr++; + + /* Update counter */ + hi2c->XferSize--; + hi2c->XferCount--; + } + /* 3 Last bytes */ + else + { + /* Wait until BTF flag is set */ + if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BTF, RESET, Timeout, tickstart) != DAL_OK) + { + return DAL_ERROR; + } + + /* Disable Acknowledge */ + CLEAR_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKEN); + + /* Read data from DATA */ + *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->DATA; + + /* Increment Buffer pointer */ + hi2c->pBuffPtr++; + + /* Update counter */ + hi2c->XferSize--; + hi2c->XferCount--; + + /* Wait until BTF flag is set */ + if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BTF, RESET, Timeout, tickstart) != DAL_OK) + { + return DAL_ERROR; + } + + /* Generate Stop */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_STOP); + + /* Read data from DATA */ + *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->DATA; + + /* Increment Buffer pointer */ + hi2c->pBuffPtr++; + + /* Update counter */ + hi2c->XferSize--; + hi2c->XferCount--; + + /* Read data from DATA */ + *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->DATA; + + /* Increment Buffer pointer */ + hi2c->pBuffPtr++; + + /* Update counter */ + hi2c->XferSize--; + hi2c->XferCount--; + } + } + else + { + /* Wait until RXNE flag is set */ + if (I2C_WaitOnRXNEFlagUntilTimeout(hi2c, Timeout, tickstart) != DAL_OK) + { + return DAL_ERROR; + } + + /* Read data from DATA */ + *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->DATA; + + /* Increment Buffer pointer */ + hi2c->pBuffPtr++; + + /* Update counter */ + hi2c->XferSize--; + hi2c->XferCount--; + + if (__DAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BTF) == SET) + { + /* Read data from DATA */ + *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->DATA; + + /* Increment Buffer pointer */ + hi2c->pBuffPtr++; + + /* Update counter */ + hi2c->XferSize--; + hi2c->XferCount--; + } + } + } + + hi2c->State = DAL_I2C_STATE_READY; + hi2c->Mode = DAL_I2C_MODE_NONE; + + /* Process Unlocked */ + __DAL_UNLOCK(hi2c); + + return DAL_OK; + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief Transmits in slave mode an amount of data in blocking mode. + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param pData Pointer to data buffer + * @param Size Amount of data to be sent + * @param Timeout Timeout duration + * @retval DAL status + */ +DAL_StatusTypeDef DAL_I2C_Slave_Transmit(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size, uint32_t Timeout) +{ + /* Init tickstart for timeout management*/ + uint32_t tickstart = DAL_GetTick(); + + if (hi2c->State == DAL_I2C_STATE_READY) + { + if ((pData == NULL) || (Size == 0U)) + { + return DAL_ERROR; + } + + /* Process Locked */ + __DAL_LOCK(hi2c); + + /* Check if the I2C is already enabled */ + if ((hi2c->Instance->CTRL1 & I2C_CTRL1_I2CEN) != I2C_CTRL1_I2CEN) + { + /* Enable I2C peripheral */ + __DAL_I2C_ENABLE(hi2c); + } + + /* Disable Pos */ + CLEAR_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKPOS); + + hi2c->State = DAL_I2C_STATE_BUSY_TX; + hi2c->Mode = DAL_I2C_MODE_SLAVE; + hi2c->ErrorCode = DAL_I2C_ERROR_NONE; + + /* Prepare transfer parameters */ + hi2c->pBuffPtr = pData; + hi2c->XferCount = Size; + hi2c->XferSize = hi2c->XferCount; + hi2c->XferOptions = I2C_NO_OPTION_FRAME; + + /* Enable Address Acknowledge */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKEN); + + /* Wait until ADDR flag is set */ + if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, RESET, Timeout, tickstart) != DAL_OK) + { + return DAL_ERROR; + } + + /* Clear ADDR flag */ + __DAL_I2C_CLEAR_ADDRFLAG(hi2c); + + /* If 10bit addressing mode is selected */ + if (hi2c->Init.AddressingMode == I2C_ADDRESSINGMODE_10BIT) + { + /* Wait until ADDR flag is set */ + if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, RESET, Timeout, tickstart) != DAL_OK) + { + return DAL_ERROR; + } + + /* Clear ADDR flag */ + __DAL_I2C_CLEAR_ADDRFLAG(hi2c); + } + + while (hi2c->XferSize > 0U) + { + /* Wait until TXE flag is set */ + if (I2C_WaitOnTXEFlagUntilTimeout(hi2c, Timeout, tickstart) != DAL_OK) + { + /* Disable Address Acknowledge */ + CLEAR_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKEN); + + return DAL_ERROR; + } + + /* Write data to DATA */ + hi2c->Instance->DATA = *hi2c->pBuffPtr; + + /* Increment Buffer pointer */ + hi2c->pBuffPtr++; + + /* Update counter */ + hi2c->XferCount--; + hi2c->XferSize--; + + if ((__DAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BTF) == SET) && (hi2c->XferSize != 0U)) + { + /* Write data to DATA */ + hi2c->Instance->DATA = *hi2c->pBuffPtr; + + /* Increment Buffer pointer */ + hi2c->pBuffPtr++; + + /* Update counter */ + hi2c->XferCount--; + hi2c->XferSize--; + } + } + + /* Wait until AF flag is set */ + if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_AF, RESET, Timeout, tickstart) != DAL_OK) + { + return DAL_ERROR; + } + + /* Clear AF flag */ + __DAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF); + + /* Disable Address Acknowledge */ + CLEAR_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKEN); + + hi2c->State = DAL_I2C_STATE_READY; + hi2c->Mode = DAL_I2C_MODE_NONE; + + /* Process Unlocked */ + __DAL_UNLOCK(hi2c); + + return DAL_OK; + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief Receive in slave mode an amount of data in blocking mode + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param pData Pointer to data buffer + * @param Size Amount of data to be sent + * @param Timeout Timeout duration + * @retval DAL status + */ +DAL_StatusTypeDef DAL_I2C_Slave_Receive(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size, uint32_t Timeout) +{ + /* Init tickstart for timeout management*/ + uint32_t tickstart = DAL_GetTick(); + + if (hi2c->State == DAL_I2C_STATE_READY) + { + if ((pData == NULL) || (Size == (uint16_t)0)) + { + return DAL_ERROR; + } + + /* Process Locked */ + __DAL_LOCK(hi2c); + + /* Check if the I2C is already enabled */ + if ((hi2c->Instance->CTRL1 & I2C_CTRL1_I2CEN) != I2C_CTRL1_I2CEN) + { + /* Enable I2C peripheral */ + __DAL_I2C_ENABLE(hi2c); + } + + /* Disable Pos */ + CLEAR_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKPOS); + + hi2c->State = DAL_I2C_STATE_BUSY_RX; + hi2c->Mode = DAL_I2C_MODE_SLAVE; + hi2c->ErrorCode = DAL_I2C_ERROR_NONE; + + /* Prepare transfer parameters */ + hi2c->pBuffPtr = pData; + hi2c->XferCount = Size; + hi2c->XferSize = hi2c->XferCount; + hi2c->XferOptions = I2C_NO_OPTION_FRAME; + + /* Enable Address Acknowledge */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKEN); + + /* Wait until ADDR flag is set */ + if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, RESET, Timeout, tickstart) != DAL_OK) + { + return DAL_ERROR; + } + + /* Clear ADDR flag */ + __DAL_I2C_CLEAR_ADDRFLAG(hi2c); + + while (hi2c->XferSize > 0U) + { + /* Wait until RXNE flag is set */ + if (I2C_WaitOnRXNEFlagUntilTimeout(hi2c, Timeout, tickstart) != DAL_OK) + { + /* Disable Address Acknowledge */ + CLEAR_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKEN); + + return DAL_ERROR; + } + + /* Read data from DATA */ + *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->DATA; + + /* Increment Buffer pointer */ + hi2c->pBuffPtr++; + + /* Update counter */ + hi2c->XferSize--; + hi2c->XferCount--; + + if ((__DAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BTF) == SET) && (hi2c->XferSize != 0U)) + { + /* Read data from DATA */ + *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->DATA; + + /* Increment Buffer pointer */ + hi2c->pBuffPtr++; + + /* Update counter */ + hi2c->XferSize--; + hi2c->XferCount--; + } + } + + /* Wait until STOP flag is set */ + if (I2C_WaitOnSTOPFlagUntilTimeout(hi2c, Timeout, tickstart) != DAL_OK) + { + /* Disable Address Acknowledge */ + CLEAR_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKEN); + + return DAL_ERROR; + } + + /* Clear STOP flag */ + __DAL_I2C_CLEAR_STOPFLAG(hi2c); + + /* Disable Address Acknowledge */ + CLEAR_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKEN); + + hi2c->State = DAL_I2C_STATE_READY; + hi2c->Mode = DAL_I2C_MODE_NONE; + + /* Process Unlocked */ + __DAL_UNLOCK(hi2c); + + return DAL_OK; + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief Transmit in master mode an amount of data in non-blocking mode with Interrupt + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param DevAddress Target device address: The device 7 bits address value + * in datasheet must be shifted to the left before calling the interface + * @param pData Pointer to data buffer + * @param Size Amount of data to be sent + * @retval DAL status + */ +DAL_StatusTypeDef DAL_I2C_Master_Transmit_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size) +{ + __IO uint32_t count = 0U; + + if (hi2c->State == DAL_I2C_STATE_READY) + { + /* Wait until BUSY flag is reset */ + count = I2C_TIMEOUT_BUSY_FLAG * (SystemCoreClock / 25U / 1000U); + do + { + count--; + if (count == 0U) + { + hi2c->PreviousState = I2C_STATE_NONE; + hi2c->State = DAL_I2C_STATE_READY; + hi2c->Mode = DAL_I2C_MODE_NONE; + hi2c->ErrorCode |= DAL_I2C_ERROR_TIMEOUT; + + /* Process Unlocked */ + __DAL_UNLOCK(hi2c); + + return DAL_ERROR; + } + } + while (__DAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) != RESET); + + /* Process Locked */ + __DAL_LOCK(hi2c); + + /* Check if the I2C is already enabled */ + if ((hi2c->Instance->CTRL1 & I2C_CTRL1_I2CEN) != I2C_CTRL1_I2CEN) + { + /* Enable I2C peripheral */ + __DAL_I2C_ENABLE(hi2c); + } + + /* Disable Pos */ + CLEAR_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKPOS); + + hi2c->State = DAL_I2C_STATE_BUSY_TX; + hi2c->Mode = DAL_I2C_MODE_MASTER; + hi2c->ErrorCode = DAL_I2C_ERROR_NONE; + + /* Prepare transfer parameters */ + hi2c->pBuffPtr = pData; + hi2c->XferCount = Size; + hi2c->XferSize = hi2c->XferCount; + hi2c->XferOptions = I2C_NO_OPTION_FRAME; + hi2c->Devaddress = DevAddress; + + /* Process Unlocked */ + __DAL_UNLOCK(hi2c); + + /* Note : The I2C interrupts must be enabled after unlocking current process + to avoid the risk of I2C interrupt handle execution before current + process unlock */ + /* Enable EVT, BUF and ERR interrupt */ + __DAL_I2C_ENABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR); + + /* Generate Start */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_START); + + return DAL_OK; + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief Receive in master mode an amount of data in non-blocking mode with Interrupt + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param DevAddress Target device address: The device 7 bits address value + * in datasheet must be shifted to the left before calling the interface + * @param pData Pointer to data buffer + * @param Size Amount of data to be sent + * @retval DAL status + */ +DAL_StatusTypeDef DAL_I2C_Master_Receive_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size) +{ + __IO uint32_t count = 0U; + + if (hi2c->State == DAL_I2C_STATE_READY) + { + /* Wait until BUSY flag is reset */ + count = I2C_TIMEOUT_BUSY_FLAG * (SystemCoreClock / 25U / 1000U); + do + { + count--; + if (count == 0U) + { + hi2c->PreviousState = I2C_STATE_NONE; + hi2c->State = DAL_I2C_STATE_READY; + hi2c->Mode = DAL_I2C_MODE_NONE; + hi2c->ErrorCode |= DAL_I2C_ERROR_TIMEOUT; + + /* Process Unlocked */ + __DAL_UNLOCK(hi2c); + + return DAL_ERROR; + } + } + while (__DAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) != RESET); + + /* Process Locked */ + __DAL_LOCK(hi2c); + + /* Check if the I2C is already enabled */ + if ((hi2c->Instance->CTRL1 & I2C_CTRL1_I2CEN) != I2C_CTRL1_I2CEN) + { + /* Enable I2C peripheral */ + __DAL_I2C_ENABLE(hi2c); + } + + /* Disable Pos */ + CLEAR_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKPOS); + + hi2c->State = DAL_I2C_STATE_BUSY_RX; + hi2c->Mode = DAL_I2C_MODE_MASTER; + hi2c->ErrorCode = DAL_I2C_ERROR_NONE; + + /* Prepare transfer parameters */ + hi2c->pBuffPtr = pData; + hi2c->XferCount = Size; + hi2c->XferSize = hi2c->XferCount; + hi2c->XferOptions = I2C_NO_OPTION_FRAME; + hi2c->Devaddress = DevAddress; + + + /* Process Unlocked */ + __DAL_UNLOCK(hi2c); + + /* Note : The I2C interrupts must be enabled after unlocking current process + to avoid the risk of I2C interrupt handle execution before current + process unlock */ + + /* Enable EVT, BUF and ERR interrupt */ + __DAL_I2C_ENABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR); + + /* Enable Acknowledge */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKEN); + + /* Generate Start */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_START); + + return DAL_OK; + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief Transmit in slave mode an amount of data in non-blocking mode with Interrupt + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param pData Pointer to data buffer + * @param Size Amount of data to be sent + * @retval DAL status + */ +DAL_StatusTypeDef DAL_I2C_Slave_Transmit_IT(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size) +{ + + if (hi2c->State == DAL_I2C_STATE_READY) + { + if ((pData == NULL) || (Size == 0U)) + { + return DAL_ERROR; + } + + /* Process Locked */ + __DAL_LOCK(hi2c); + + /* Check if the I2C is already enabled */ + if ((hi2c->Instance->CTRL1 & I2C_CTRL1_I2CEN) != I2C_CTRL1_I2CEN) + { + /* Enable I2C peripheral */ + __DAL_I2C_ENABLE(hi2c); + } + + /* Disable Pos */ + CLEAR_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKPOS); + + hi2c->State = DAL_I2C_STATE_BUSY_TX; + hi2c->Mode = DAL_I2C_MODE_SLAVE; + hi2c->ErrorCode = DAL_I2C_ERROR_NONE; + + /* Prepare transfer parameters */ + hi2c->pBuffPtr = pData; + hi2c->XferCount = Size; + hi2c->XferSize = hi2c->XferCount; + hi2c->XferOptions = I2C_NO_OPTION_FRAME; + + /* Enable Address Acknowledge */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKEN); + + /* Process Unlocked */ + __DAL_UNLOCK(hi2c); + + /* Note : The I2C interrupts must be enabled after unlocking current process + to avoid the risk of I2C interrupt handle execution before current + process unlock */ + + /* Enable EVT, BUF and ERR interrupt */ + __DAL_I2C_ENABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR); + + return DAL_OK; + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief Receive in slave mode an amount of data in non-blocking mode with Interrupt + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param pData Pointer to data buffer + * @param Size Amount of data to be sent + * @retval DAL status + */ +DAL_StatusTypeDef DAL_I2C_Slave_Receive_IT(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size) +{ + + if (hi2c->State == DAL_I2C_STATE_READY) + { + if ((pData == NULL) || (Size == 0U)) + { + return DAL_ERROR; + } + + /* Process Locked */ + __DAL_LOCK(hi2c); + + /* Check if the I2C is already enabled */ + if ((hi2c->Instance->CTRL1 & I2C_CTRL1_I2CEN) != I2C_CTRL1_I2CEN) + { + /* Enable I2C peripheral */ + __DAL_I2C_ENABLE(hi2c); + } + + /* Disable Pos */ + CLEAR_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKPOS); + + hi2c->State = DAL_I2C_STATE_BUSY_RX; + hi2c->Mode = DAL_I2C_MODE_SLAVE; + hi2c->ErrorCode = DAL_I2C_ERROR_NONE; + + /* Prepare transfer parameters */ + hi2c->pBuffPtr = pData; + hi2c->XferCount = Size; + hi2c->XferSize = hi2c->XferCount; + hi2c->XferOptions = I2C_NO_OPTION_FRAME; + + /* Enable Address Acknowledge */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKEN); + + /* Process Unlocked */ + __DAL_UNLOCK(hi2c); + + /* Note : The I2C interrupts must be enabled after unlocking current process + to avoid the risk of I2C interrupt handle execution before current + process unlock */ + + /* Enable EVT, BUF and ERR interrupt */ + __DAL_I2C_ENABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR); + + return DAL_OK; + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief Transmit in master mode an amount of data in non-blocking mode with DMA + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param DevAddress Target device address: The device 7 bits address value + * in datasheet must be shifted to the left before calling the interface + * @param pData Pointer to data buffer + * @param Size Amount of data to be sent + * @retval DAL status + */ +DAL_StatusTypeDef DAL_I2C_Master_Transmit_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size) +{ + __IO uint32_t count = 0U; + DAL_StatusTypeDef dmaxferstatus; + + if (hi2c->State == DAL_I2C_STATE_READY) + { + /* Wait until BUSY flag is reset */ + count = I2C_TIMEOUT_BUSY_FLAG * (SystemCoreClock / 25U / 1000U); + do + { + count--; + if (count == 0U) + { + hi2c->PreviousState = I2C_STATE_NONE; + hi2c->State = DAL_I2C_STATE_READY; + hi2c->Mode = DAL_I2C_MODE_NONE; + hi2c->ErrorCode |= DAL_I2C_ERROR_TIMEOUT; + + /* Process Unlocked */ + __DAL_UNLOCK(hi2c); + + return DAL_ERROR; + } + } + while (__DAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) != RESET); + + /* Process Locked */ + __DAL_LOCK(hi2c); + + /* Check if the I2C is already enabled */ + if ((hi2c->Instance->CTRL1 & I2C_CTRL1_I2CEN) != I2C_CTRL1_I2CEN) + { + /* Enable I2C peripheral */ + __DAL_I2C_ENABLE(hi2c); + } + + /* Disable Pos */ + CLEAR_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKPOS); + + hi2c->State = DAL_I2C_STATE_BUSY_TX; + hi2c->Mode = DAL_I2C_MODE_MASTER; + hi2c->ErrorCode = DAL_I2C_ERROR_NONE; + + /* Prepare transfer parameters */ + hi2c->pBuffPtr = pData; + hi2c->XferCount = Size; + hi2c->XferSize = hi2c->XferCount; + hi2c->XferOptions = I2C_NO_OPTION_FRAME; + hi2c->Devaddress = DevAddress; + + if (hi2c->XferSize > 0U) + { + if (hi2c->hdmatx != NULL) + { + /* Set the I2C DMA transfer complete callback */ + hi2c->hdmatx->XferCpltCallback = I2C_DMAXferCplt; + + /* Set the DMA error callback */ + hi2c->hdmatx->XferErrorCallback = I2C_DMAError; + + /* Set the unused DMA callbacks to NULL */ + hi2c->hdmatx->XferHalfCpltCallback = NULL; + hi2c->hdmatx->XferM1CpltCallback = NULL; + hi2c->hdmatx->XferM1HalfCpltCallback = NULL; + hi2c->hdmatx->XferAbortCallback = NULL; + + /* Enable the DMA stream */ + dmaxferstatus = DAL_DMA_Start_IT(hi2c->hdmatx, (uint32_t)hi2c->pBuffPtr, (uint32_t)&hi2c->Instance->DATA, hi2c->XferSize); + } + else + { + /* Update I2C state */ + hi2c->State = DAL_I2C_STATE_READY; + hi2c->Mode = DAL_I2C_MODE_NONE; + + /* Update I2C error code */ + hi2c->ErrorCode |= DAL_I2C_ERROR_DMA_PARAM; + + /* Process Unlocked */ + __DAL_UNLOCK(hi2c); + + return DAL_ERROR; + } + + if (dmaxferstatus == DAL_OK) + { + /* Process Unlocked */ + __DAL_UNLOCK(hi2c); + + /* Note : The I2C interrupts must be enabled after unlocking current process + to avoid the risk of I2C interrupt handle execution before current + process unlock */ + + /* Enable EVT and ERR interrupt */ + __DAL_I2C_ENABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_ERR); + + /* Enable DMA Request */ + SET_BIT(hi2c->Instance->CTRL2, I2C_CTRL2_DMAEN); + + /* Enable Acknowledge */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKEN); + + /* Generate Start */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_START); + } + else + { + /* Update I2C state */ + hi2c->State = DAL_I2C_STATE_READY; + hi2c->Mode = DAL_I2C_MODE_NONE; + + /* Update I2C error code */ + hi2c->ErrorCode |= DAL_I2C_ERROR_DMA; + + /* Process Unlocked */ + __DAL_UNLOCK(hi2c); + + return DAL_ERROR; + } + } + else + { + /* Enable Acknowledge */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKEN); + + /* Generate Start */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_START); + + /* Process Unlocked */ + __DAL_UNLOCK(hi2c); + + /* Note : The I2C interrupts must be enabled after unlocking current process + to avoid the risk of I2C interrupt handle execution before current + process unlock */ + + /* Enable EVT, BUF and ERR interrupt */ + __DAL_I2C_ENABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR); + } + + return DAL_OK; + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief Receive in master mode an amount of data in non-blocking mode with DMA + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param DevAddress Target device address: The device 7 bits address value + * in datasheet must be shifted to the left before calling the interface + * @param pData Pointer to data buffer + * @param Size Amount of data to be sent + * @retval DAL status + */ +DAL_StatusTypeDef DAL_I2C_Master_Receive_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size) +{ + __IO uint32_t count = 0U; + DAL_StatusTypeDef dmaxferstatus; + + if (hi2c->State == DAL_I2C_STATE_READY) + { + /* Wait until BUSY flag is reset */ + count = I2C_TIMEOUT_BUSY_FLAG * (SystemCoreClock / 25U / 1000U); + do + { + count--; + if (count == 0U) + { + hi2c->PreviousState = I2C_STATE_NONE; + hi2c->State = DAL_I2C_STATE_READY; + hi2c->Mode = DAL_I2C_MODE_NONE; + hi2c->ErrorCode |= DAL_I2C_ERROR_TIMEOUT; + + /* Process Unlocked */ + __DAL_UNLOCK(hi2c); + + return DAL_ERROR; + } + } + while (__DAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) != RESET); + + /* Process Locked */ + __DAL_LOCK(hi2c); + + /* Check if the I2C is already enabled */ + if ((hi2c->Instance->CTRL1 & I2C_CTRL1_I2CEN) != I2C_CTRL1_I2CEN) + { + /* Enable I2C peripheral */ + __DAL_I2C_ENABLE(hi2c); + } + + /* Disable Pos */ + CLEAR_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKPOS); + + hi2c->State = DAL_I2C_STATE_BUSY_RX; + hi2c->Mode = DAL_I2C_MODE_MASTER; + hi2c->ErrorCode = DAL_I2C_ERROR_NONE; + + /* Prepare transfer parameters */ + hi2c->pBuffPtr = pData; + hi2c->XferCount = Size; + hi2c->XferSize = hi2c->XferCount; + hi2c->XferOptions = I2C_NO_OPTION_FRAME; + hi2c->Devaddress = DevAddress; + + if (hi2c->XferSize > 0U) + { + if (hi2c->hdmarx != NULL) + { + /* Set the I2C DMA transfer complete callback */ + hi2c->hdmarx->XferCpltCallback = I2C_DMAXferCplt; + + /* Set the DMA error callback */ + hi2c->hdmarx->XferErrorCallback = I2C_DMAError; + + /* Set the unused DMA callbacks to NULL */ + hi2c->hdmarx->XferHalfCpltCallback = NULL; + hi2c->hdmarx->XferM1CpltCallback = NULL; + hi2c->hdmarx->XferM1HalfCpltCallback = NULL; + hi2c->hdmarx->XferAbortCallback = NULL; + + /* Enable the DMA stream */ + dmaxferstatus = DAL_DMA_Start_IT(hi2c->hdmarx, (uint32_t)&hi2c->Instance->DATA, (uint32_t)hi2c->pBuffPtr, hi2c->XferSize); + } + else + { + /* Update I2C state */ + hi2c->State = DAL_I2C_STATE_READY; + hi2c->Mode = DAL_I2C_MODE_NONE; + + /* Update I2C error code */ + hi2c->ErrorCode |= DAL_I2C_ERROR_DMA_PARAM; + + /* Process Unlocked */ + __DAL_UNLOCK(hi2c); + + return DAL_ERROR; + } + + if (dmaxferstatus == DAL_OK) + { + /* Enable Acknowledge */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKEN); + + /* Generate Start */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_START); + + /* Process Unlocked */ + __DAL_UNLOCK(hi2c); + + /* Note : The I2C interrupts must be enabled after unlocking current process + to avoid the risk of I2C interrupt handle execution before current + process unlock */ + + /* Enable EVT and ERR interrupt */ + __DAL_I2C_ENABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_ERR); + + /* Enable DMA Request */ + SET_BIT(hi2c->Instance->CTRL2, I2C_CTRL2_DMAEN); + } + else + { + /* Update I2C state */ + hi2c->State = DAL_I2C_STATE_READY; + hi2c->Mode = DAL_I2C_MODE_NONE; + + /* Update I2C error code */ + hi2c->ErrorCode |= DAL_I2C_ERROR_DMA; + + /* Process Unlocked */ + __DAL_UNLOCK(hi2c); + + return DAL_ERROR; + } + } + else + { + /* Process Unlocked */ + __DAL_UNLOCK(hi2c); + + /* Note : The I2C interrupts must be enabled after unlocking current process + to avoid the risk of I2C interrupt handle execution before current + process unlock */ + + /* Enable EVT, BUF and ERR interrupt */ + __DAL_I2C_ENABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR); + + /* Enable Acknowledge */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKEN); + + /* Generate Start */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_START); + } + + return DAL_OK; + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief Transmit in slave mode an amount of data in non-blocking mode with DMA + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param pData Pointer to data buffer + * @param Size Amount of data to be sent + * @retval DAL status + */ +DAL_StatusTypeDef DAL_I2C_Slave_Transmit_DMA(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size) +{ + DAL_StatusTypeDef dmaxferstatus; + + if (hi2c->State == DAL_I2C_STATE_READY) + { + if ((pData == NULL) || (Size == 0U)) + { + return DAL_ERROR; + } + + /* Process Locked */ + __DAL_LOCK(hi2c); + + /* Check if the I2C is already enabled */ + if ((hi2c->Instance->CTRL1 & I2C_CTRL1_I2CEN) != I2C_CTRL1_I2CEN) + { + /* Enable I2C peripheral */ + __DAL_I2C_ENABLE(hi2c); + } + + /* Disable Pos */ + CLEAR_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKPOS); + + hi2c->State = DAL_I2C_STATE_BUSY_TX; + hi2c->Mode = DAL_I2C_MODE_SLAVE; + hi2c->ErrorCode = DAL_I2C_ERROR_NONE; + + /* Prepare transfer parameters */ + hi2c->pBuffPtr = pData; + hi2c->XferCount = Size; + hi2c->XferSize = hi2c->XferCount; + hi2c->XferOptions = I2C_NO_OPTION_FRAME; + + if (hi2c->hdmatx != NULL) + { + /* Set the I2C DMA transfer complete callback */ + hi2c->hdmatx->XferCpltCallback = I2C_DMAXferCplt; + + /* Set the DMA error callback */ + hi2c->hdmatx->XferErrorCallback = I2C_DMAError; + + /* Set the unused DMA callbacks to NULL */ + hi2c->hdmatx->XferHalfCpltCallback = NULL; + hi2c->hdmatx->XferM1CpltCallback = NULL; + hi2c->hdmatx->XferM1HalfCpltCallback = NULL; + hi2c->hdmatx->XferAbortCallback = NULL; + + /* Enable the DMA stream */ + dmaxferstatus = DAL_DMA_Start_IT(hi2c->hdmatx, (uint32_t)hi2c->pBuffPtr, (uint32_t)&hi2c->Instance->DATA, hi2c->XferSize); + } + else + { + /* Update I2C state */ + hi2c->State = DAL_I2C_STATE_LISTEN; + hi2c->Mode = DAL_I2C_MODE_NONE; + + /* Update I2C error code */ + hi2c->ErrorCode |= DAL_I2C_ERROR_DMA_PARAM; + + /* Process Unlocked */ + __DAL_UNLOCK(hi2c); + + return DAL_ERROR; + } + + if (dmaxferstatus == DAL_OK) + { + /* Enable Address Acknowledge */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKEN); + + /* Process Unlocked */ + __DAL_UNLOCK(hi2c); + + /* Note : The I2C interrupts must be enabled after unlocking current process + to avoid the risk of I2C interrupt handle execution before current + process unlock */ + /* Enable EVT and ERR interrupt */ + __DAL_I2C_ENABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_ERR); + + /* Enable DMA Request */ + hi2c->Instance->CTRL2 |= I2C_CTRL2_DMAEN; + + return DAL_OK; + } + else + { + /* Update I2C state */ + hi2c->State = DAL_I2C_STATE_READY; + hi2c->Mode = DAL_I2C_MODE_NONE; + + /* Update I2C error code */ + hi2c->ErrorCode |= DAL_I2C_ERROR_DMA; + + /* Process Unlocked */ + __DAL_UNLOCK(hi2c); + + return DAL_ERROR; + } + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief Receive in slave mode an amount of data in non-blocking mode with DMA + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param pData Pointer to data buffer + * @param Size Amount of data to be sent + * @retval DAL status + */ +DAL_StatusTypeDef DAL_I2C_Slave_Receive_DMA(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size) +{ + DAL_StatusTypeDef dmaxferstatus; + + if (hi2c->State == DAL_I2C_STATE_READY) + { + if ((pData == NULL) || (Size == 0U)) + { + return DAL_ERROR; + } + + /* Process Locked */ + __DAL_LOCK(hi2c); + + /* Check if the I2C is already enabled */ + if ((hi2c->Instance->CTRL1 & I2C_CTRL1_I2CEN) != I2C_CTRL1_I2CEN) + { + /* Enable I2C peripheral */ + __DAL_I2C_ENABLE(hi2c); + } + + /* Disable Pos */ + CLEAR_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKPOS); + + hi2c->State = DAL_I2C_STATE_BUSY_RX; + hi2c->Mode = DAL_I2C_MODE_SLAVE; + hi2c->ErrorCode = DAL_I2C_ERROR_NONE; + + /* Prepare transfer parameters */ + hi2c->pBuffPtr = pData; + hi2c->XferCount = Size; + hi2c->XferSize = hi2c->XferCount; + hi2c->XferOptions = I2C_NO_OPTION_FRAME; + + if (hi2c->hdmarx != NULL) + { + /* Set the I2C DMA transfer complete callback */ + hi2c->hdmarx->XferCpltCallback = I2C_DMAXferCplt; + + /* Set the DMA error callback */ + hi2c->hdmarx->XferErrorCallback = I2C_DMAError; + + /* Set the unused DMA callbacks to NULL */ + hi2c->hdmarx->XferHalfCpltCallback = NULL; + hi2c->hdmarx->XferM1CpltCallback = NULL; + hi2c->hdmarx->XferM1HalfCpltCallback = NULL; + hi2c->hdmarx->XferAbortCallback = NULL; + + /* Enable the DMA stream */ + dmaxferstatus = DAL_DMA_Start_IT(hi2c->hdmarx, (uint32_t)&hi2c->Instance->DATA, (uint32_t)hi2c->pBuffPtr, hi2c->XferSize); + } + else + { + /* Update I2C state */ + hi2c->State = DAL_I2C_STATE_LISTEN; + hi2c->Mode = DAL_I2C_MODE_NONE; + + /* Update I2C error code */ + hi2c->ErrorCode |= DAL_I2C_ERROR_DMA_PARAM; + + /* Process Unlocked */ + __DAL_UNLOCK(hi2c); + + return DAL_ERROR; + } + + if (dmaxferstatus == DAL_OK) + { + /* Enable Address Acknowledge */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKEN); + + /* Process Unlocked */ + __DAL_UNLOCK(hi2c); + + /* Note : The I2C interrupts must be enabled after unlocking current process + to avoid the risk of I2C interrupt handle execution before current + process unlock */ + /* Enable EVT and ERR interrupt */ + __DAL_I2C_ENABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_ERR); + + /* Enable DMA Request */ + SET_BIT(hi2c->Instance->CTRL2, I2C_CTRL2_DMAEN); + + return DAL_OK; + } + else + { + /* Update I2C state */ + hi2c->State = DAL_I2C_STATE_READY; + hi2c->Mode = DAL_I2C_MODE_NONE; + + /* Update I2C error code */ + hi2c->ErrorCode |= DAL_I2C_ERROR_DMA; + + /* Process Unlocked */ + __DAL_UNLOCK(hi2c); + + return DAL_ERROR; + } + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief Write an amount of data in blocking mode to a specific memory address + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param DevAddress Target device address: The device 7 bits address value + * in datasheet must be shifted to the left before calling the interface + * @param MemAddress Internal memory address + * @param MemAddSize Size of internal memory address + * @param pData Pointer to data buffer + * @param Size Amount of data to be sent + * @param Timeout Timeout duration + * @retval DAL status + */ +DAL_StatusTypeDef DAL_I2C_Mem_Write(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size, uint32_t Timeout) +{ + /* Init tickstart for timeout management*/ + uint32_t tickstart = DAL_GetTick(); + + /* Check the parameters */ + ASSERT_PARAM(IS_I2C_MEMADD_SIZE(MemAddSize)); + + if (hi2c->State == DAL_I2C_STATE_READY) + { + /* Wait until BUSY flag is reset */ + if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, I2C_TIMEOUT_BUSY_FLAG, tickstart) != DAL_OK) + { + return DAL_BUSY; + } + + /* Process Locked */ + __DAL_LOCK(hi2c); + + /* Check if the I2C is already enabled */ + if ((hi2c->Instance->CTRL1 & I2C_CTRL1_I2CEN) != I2C_CTRL1_I2CEN) + { + /* Enable I2C peripheral */ + __DAL_I2C_ENABLE(hi2c); + } + + /* Disable Pos */ + CLEAR_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKPOS); + + hi2c->State = DAL_I2C_STATE_BUSY_TX; + hi2c->Mode = DAL_I2C_MODE_MEM; + hi2c->ErrorCode = DAL_I2C_ERROR_NONE; + + /* Prepare transfer parameters */ + hi2c->pBuffPtr = pData; + hi2c->XferCount = Size; + hi2c->XferSize = hi2c->XferCount; + hi2c->XferOptions = I2C_NO_OPTION_FRAME; + + /* Send Slave Address and Memory Address */ + if (I2C_RequestMemoryWrite(hi2c, DevAddress, MemAddress, MemAddSize, Timeout, tickstart) != DAL_OK) + { + return DAL_ERROR; + } + + while (hi2c->XferSize > 0U) + { + /* Wait until TXE flag is set */ + if (I2C_WaitOnTXEFlagUntilTimeout(hi2c, Timeout, tickstart) != DAL_OK) + { + if (hi2c->ErrorCode == DAL_I2C_ERROR_AF) + { + /* Generate Stop */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_STOP); + } + return DAL_ERROR; + } + + /* Write data to DATA */ + hi2c->Instance->DATA = *hi2c->pBuffPtr; + + /* Increment Buffer pointer */ + hi2c->pBuffPtr++; + + /* Update counter */ + hi2c->XferSize--; + hi2c->XferCount--; + + if ((__DAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BTF) == SET) && (hi2c->XferSize != 0U)) + { + /* Write data to DATA */ + hi2c->Instance->DATA = *hi2c->pBuffPtr; + + /* Increment Buffer pointer */ + hi2c->pBuffPtr++; + + /* Update counter */ + hi2c->XferSize--; + hi2c->XferCount--; + } + } + + /* Wait until BTF flag is set */ + if (I2C_WaitOnBTFFlagUntilTimeout(hi2c, Timeout, tickstart) != DAL_OK) + { + if (hi2c->ErrorCode == DAL_I2C_ERROR_AF) + { + /* Generate Stop */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_STOP); + } + return DAL_ERROR; + } + + /* Generate Stop */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_STOP); + + hi2c->State = DAL_I2C_STATE_READY; + hi2c->Mode = DAL_I2C_MODE_NONE; + + /* Process Unlocked */ + __DAL_UNLOCK(hi2c); + + return DAL_OK; + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief Read an amount of data in blocking mode from a specific memory address + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param DevAddress Target device address: The device 7 bits address value + * in datasheet must be shifted to the left before calling the interface + * @param MemAddress Internal memory address + * @param MemAddSize Size of internal memory address + * @param pData Pointer to data buffer + * @param Size Amount of data to be sent + * @param Timeout Timeout duration + * @retval DAL status + */ +DAL_StatusTypeDef DAL_I2C_Mem_Read(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size, uint32_t Timeout) +{ + /* Init tickstart for timeout management*/ + uint32_t tickstart = DAL_GetTick(); + + /* Check the parameters */ + ASSERT_PARAM(IS_I2C_MEMADD_SIZE(MemAddSize)); + + if (hi2c->State == DAL_I2C_STATE_READY) + { + /* Wait until BUSY flag is reset */ + if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, I2C_TIMEOUT_BUSY_FLAG, tickstart) != DAL_OK) + { + return DAL_BUSY; + } + + /* Process Locked */ + __DAL_LOCK(hi2c); + + /* Check if the I2C is already enabled */ + if ((hi2c->Instance->CTRL1 & I2C_CTRL1_I2CEN) != I2C_CTRL1_I2CEN) + { + /* Enable I2C peripheral */ + __DAL_I2C_ENABLE(hi2c); + } + + /* Disable Pos */ + CLEAR_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKPOS); + + hi2c->State = DAL_I2C_STATE_BUSY_RX; + hi2c->Mode = DAL_I2C_MODE_MEM; + hi2c->ErrorCode = DAL_I2C_ERROR_NONE; + + /* Prepare transfer parameters */ + hi2c->pBuffPtr = pData; + hi2c->XferCount = Size; + hi2c->XferSize = hi2c->XferCount; + hi2c->XferOptions = I2C_NO_OPTION_FRAME; + + /* Send Slave Address and Memory Address */ + if (I2C_RequestMemoryRead(hi2c, DevAddress, MemAddress, MemAddSize, Timeout, tickstart) != DAL_OK) + { + return DAL_ERROR; + } + + if (hi2c->XferSize == 0U) + { + /* Clear ADDR flag */ + __DAL_I2C_CLEAR_ADDRFLAG(hi2c); + + /* Generate Stop */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_STOP); + } + else if (hi2c->XferSize == 1U) + { + /* Disable Acknowledge */ + CLEAR_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKEN); + + /* Clear ADDR flag */ + __DAL_I2C_CLEAR_ADDRFLAG(hi2c); + + /* Generate Stop */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_STOP); + } + else if (hi2c->XferSize == 2U) + { + /* Disable Acknowledge */ + CLEAR_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKEN); + + /* Enable Pos */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKPOS); + + /* Clear ADDR flag */ + __DAL_I2C_CLEAR_ADDRFLAG(hi2c); + } + else + { + /* Clear ADDR flag */ + __DAL_I2C_CLEAR_ADDRFLAG(hi2c); + } + + while (hi2c->XferSize > 0U) + { + if (hi2c->XferSize <= 3U) + { + /* One byte */ + if (hi2c->XferSize == 1U) + { + /* Wait until RXNE flag is set */ + if (I2C_WaitOnRXNEFlagUntilTimeout(hi2c, Timeout, tickstart) != DAL_OK) + { + return DAL_ERROR; + } + + /* Read data from DATA */ + *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->DATA; + + /* Increment Buffer pointer */ + hi2c->pBuffPtr++; + + /* Update counter */ + hi2c->XferSize--; + hi2c->XferCount--; + } + /* Two bytes */ + else if (hi2c->XferSize == 2U) + { + /* Wait until BTF flag is set */ + if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BTF, RESET, Timeout, tickstart) != DAL_OK) + { + return DAL_ERROR; + } + + /* Generate Stop */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_STOP); + + /* Read data from DATA */ + *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->DATA; + + /* Increment Buffer pointer */ + hi2c->pBuffPtr++; + + /* Update counter */ + hi2c->XferSize--; + hi2c->XferCount--; + + /* Read data from DATA */ + *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->DATA; + + /* Increment Buffer pointer */ + hi2c->pBuffPtr++; + + /* Update counter */ + hi2c->XferSize--; + hi2c->XferCount--; + } + /* 3 Last bytes */ + else + { + /* Wait until BTF flag is set */ + if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BTF, RESET, Timeout, tickstart) != DAL_OK) + { + return DAL_ERROR; + } + + /* Disable Acknowledge */ + CLEAR_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKEN); + + /* Read data from DATA */ + *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->DATA; + + /* Increment Buffer pointer */ + hi2c->pBuffPtr++; + + /* Update counter */ + hi2c->XferSize--; + hi2c->XferCount--; + + /* Wait until BTF flag is set */ + if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BTF, RESET, Timeout, tickstart) != DAL_OK) + { + return DAL_ERROR; + } + + /* Generate Stop */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_STOP); + + /* Read data from DATA */ + *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->DATA; + + /* Increment Buffer pointer */ + hi2c->pBuffPtr++; + + /* Update counter */ + hi2c->XferSize--; + hi2c->XferCount--; + + /* Read data from DATA */ + *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->DATA; + + /* Increment Buffer pointer */ + hi2c->pBuffPtr++; + + /* Update counter */ + hi2c->XferSize--; + hi2c->XferCount--; + } + } + else + { + /* Wait until RXNE flag is set */ + if (I2C_WaitOnRXNEFlagUntilTimeout(hi2c, Timeout, tickstart) != DAL_OK) + { + return DAL_ERROR; + } + + /* Read data from DATA */ + *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->DATA; + + /* Increment Buffer pointer */ + hi2c->pBuffPtr++; + + /* Update counter */ + hi2c->XferSize--; + hi2c->XferCount--; + + if (__DAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BTF) == SET) + { + /* Read data from DATA */ + *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->DATA; + + /* Increment Buffer pointer */ + hi2c->pBuffPtr++; + + /* Update counter */ + hi2c->XferSize--; + hi2c->XferCount--; + } + } + } + + hi2c->State = DAL_I2C_STATE_READY; + hi2c->Mode = DAL_I2C_MODE_NONE; + + /* Process Unlocked */ + __DAL_UNLOCK(hi2c); + + return DAL_OK; + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief Write an amount of data in non-blocking mode with Interrupt to a specific memory address + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param DevAddress Target device address: The device 7 bits address value + * in datasheet must be shifted to the left before calling the interface + * @param MemAddress Internal memory address + * @param MemAddSize Size of internal memory address + * @param pData Pointer to data buffer + * @param Size Amount of data to be sent + * @retval DAL status + */ +DAL_StatusTypeDef DAL_I2C_Mem_Write_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size) +{ + __IO uint32_t count = 0U; + + /* Check the parameters */ + ASSERT_PARAM(IS_I2C_MEMADD_SIZE(MemAddSize)); + + if (hi2c->State == DAL_I2C_STATE_READY) + { + /* Wait until BUSY flag is reset */ + count = I2C_TIMEOUT_BUSY_FLAG * (SystemCoreClock / 25U / 1000U); + do + { + count--; + if (count == 0U) + { + hi2c->PreviousState = I2C_STATE_NONE; + hi2c->State = DAL_I2C_STATE_READY; + hi2c->Mode = DAL_I2C_MODE_NONE; + hi2c->ErrorCode |= DAL_I2C_ERROR_TIMEOUT; + + /* Process Unlocked */ + __DAL_UNLOCK(hi2c); + + return DAL_ERROR; + } + } + while (__DAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) != RESET); + + /* Process Locked */ + __DAL_LOCK(hi2c); + + /* Check if the I2C is already enabled */ + if ((hi2c->Instance->CTRL1 & I2C_CTRL1_I2CEN) != I2C_CTRL1_I2CEN) + { + /* Enable I2C peripheral */ + __DAL_I2C_ENABLE(hi2c); + } + + /* Disable Pos */ + CLEAR_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKPOS); + + hi2c->State = DAL_I2C_STATE_BUSY_TX; + hi2c->Mode = DAL_I2C_MODE_MEM; + hi2c->ErrorCode = DAL_I2C_ERROR_NONE; + + /* Prepare transfer parameters */ + hi2c->pBuffPtr = pData; + hi2c->XferCount = Size; + hi2c->XferSize = hi2c->XferCount; + hi2c->XferOptions = I2C_NO_OPTION_FRAME; + hi2c->Devaddress = DevAddress; + hi2c->Memaddress = MemAddress; + hi2c->MemaddSize = MemAddSize; + hi2c->EventCount = 0U; + + /* Generate Start */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_START); + + /* Process Unlocked */ + __DAL_UNLOCK(hi2c); + + /* Note : The I2C interrupts must be enabled after unlocking current process + to avoid the risk of I2C interrupt handle execution before current + process unlock */ + + /* Enable EVT, BUF and ERR interrupt */ + __DAL_I2C_ENABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR); + + return DAL_OK; + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief Read an amount of data in non-blocking mode with Interrupt from a specific memory address + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param DevAddress Target device address + * @param MemAddress Internal memory address + * @param MemAddSize Size of internal memory address + * @param pData Pointer to data buffer + * @param Size Amount of data to be sent + * @retval DAL status + */ +DAL_StatusTypeDef DAL_I2C_Mem_Read_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size) +{ + __IO uint32_t count = 0U; + + /* Check the parameters */ + ASSERT_PARAM(IS_I2C_MEMADD_SIZE(MemAddSize)); + + if (hi2c->State == DAL_I2C_STATE_READY) + { + /* Wait until BUSY flag is reset */ + count = I2C_TIMEOUT_BUSY_FLAG * (SystemCoreClock / 25U / 1000U); + do + { + count--; + if (count == 0U) + { + hi2c->PreviousState = I2C_STATE_NONE; + hi2c->State = DAL_I2C_STATE_READY; + hi2c->Mode = DAL_I2C_MODE_NONE; + hi2c->ErrorCode |= DAL_I2C_ERROR_TIMEOUT; + + /* Process Unlocked */ + __DAL_UNLOCK(hi2c); + + return DAL_ERROR; + } + } + while (__DAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) != RESET); + + /* Process Locked */ + __DAL_LOCK(hi2c); + + /* Check if the I2C is already enabled */ + if ((hi2c->Instance->CTRL1 & I2C_CTRL1_I2CEN) != I2C_CTRL1_I2CEN) + { + /* Enable I2C peripheral */ + __DAL_I2C_ENABLE(hi2c); + } + + /* Disable Pos */ + CLEAR_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKPOS); + + hi2c->State = DAL_I2C_STATE_BUSY_RX; + hi2c->Mode = DAL_I2C_MODE_MEM; + hi2c->ErrorCode = DAL_I2C_ERROR_NONE; + + /* Prepare transfer parameters */ + hi2c->pBuffPtr = pData; + hi2c->XferCount = Size; + hi2c->XferSize = hi2c->XferCount; + hi2c->XferOptions = I2C_NO_OPTION_FRAME; + hi2c->Devaddress = DevAddress; + hi2c->Memaddress = MemAddress; + hi2c->MemaddSize = MemAddSize; + hi2c->EventCount = 0U; + + /* Enable Acknowledge */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKEN); + + /* Generate Start */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_START); + + /* Process Unlocked */ + __DAL_UNLOCK(hi2c); + + if (hi2c->XferSize > 0U) + { + /* Note : The I2C interrupts must be enabled after unlocking current process + to avoid the risk of I2C interrupt handle execution before current + process unlock */ + + /* Enable EVT, BUF and ERR interrupt */ + __DAL_I2C_ENABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR); + } + return DAL_OK; + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief Write an amount of data in non-blocking mode with DMA to a specific memory address + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param DevAddress Target device address: The device 7 bits address value + * in datasheet must be shifted to the left before calling the interface + * @param MemAddress Internal memory address + * @param MemAddSize Size of internal memory address + * @param pData Pointer to data buffer + * @param Size Amount of data to be sent + * @retval DAL status + */ +DAL_StatusTypeDef DAL_I2C_Mem_Write_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size) +{ + __IO uint32_t count = 0U; + DAL_StatusTypeDef dmaxferstatus; + + /* Init tickstart for timeout management*/ + uint32_t tickstart = DAL_GetTick(); + + /* Check the parameters */ + ASSERT_PARAM(IS_I2C_MEMADD_SIZE(MemAddSize)); + + if (hi2c->State == DAL_I2C_STATE_READY) + { + /* Wait until BUSY flag is reset */ + count = I2C_TIMEOUT_BUSY_FLAG * (SystemCoreClock / 25U / 1000U); + do + { + count--; + if (count == 0U) + { + hi2c->PreviousState = I2C_STATE_NONE; + hi2c->State = DAL_I2C_STATE_READY; + hi2c->Mode = DAL_I2C_MODE_NONE; + hi2c->ErrorCode |= DAL_I2C_ERROR_TIMEOUT; + + /* Process Unlocked */ + __DAL_UNLOCK(hi2c); + + return DAL_ERROR; + } + } + while (__DAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) != RESET); + + /* Process Locked */ + __DAL_LOCK(hi2c); + + /* Check if the I2C is already enabled */ + if ((hi2c->Instance->CTRL1 & I2C_CTRL1_I2CEN) != I2C_CTRL1_I2CEN) + { + /* Enable I2C peripheral */ + __DAL_I2C_ENABLE(hi2c); + } + + /* Disable Pos */ + CLEAR_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKPOS); + + hi2c->State = DAL_I2C_STATE_BUSY_TX; + hi2c->Mode = DAL_I2C_MODE_MEM; + hi2c->ErrorCode = DAL_I2C_ERROR_NONE; + + /* Prepare transfer parameters */ + hi2c->pBuffPtr = pData; + hi2c->XferCount = Size; + hi2c->XferSize = hi2c->XferCount; + hi2c->XferOptions = I2C_NO_OPTION_FRAME; + hi2c->Devaddress = DevAddress; + hi2c->Memaddress = MemAddress; + hi2c->MemaddSize = MemAddSize; + hi2c->EventCount = 0U; + + if (hi2c->XferSize > 0U) + { + if (hi2c->hdmatx != NULL) + { + /* Set the I2C DMA transfer complete callback */ + hi2c->hdmatx->XferCpltCallback = I2C_DMAXferCplt; + + /* Set the DMA error callback */ + hi2c->hdmatx->XferErrorCallback = I2C_DMAError; + + /* Set the unused DMA callbacks to NULL */ + hi2c->hdmatx->XferHalfCpltCallback = NULL; + hi2c->hdmatx->XferM1CpltCallback = NULL; + hi2c->hdmatx->XferM1HalfCpltCallback = NULL; + hi2c->hdmatx->XferAbortCallback = NULL; + + /* Enable the DMA stream */ + dmaxferstatus = DAL_DMA_Start_IT(hi2c->hdmatx, (uint32_t)hi2c->pBuffPtr, (uint32_t)&hi2c->Instance->DATA, hi2c->XferSize); + } + else + { + /* Update I2C state */ + hi2c->State = DAL_I2C_STATE_READY; + hi2c->Mode = DAL_I2C_MODE_NONE; + + /* Update I2C error code */ + hi2c->ErrorCode |= DAL_I2C_ERROR_DMA_PARAM; + + /* Process Unlocked */ + __DAL_UNLOCK(hi2c); + + return DAL_ERROR; + } + + if (dmaxferstatus == DAL_OK) + { + /* Send Slave Address and Memory Address */ + if (I2C_RequestMemoryWrite(hi2c, DevAddress, MemAddress, MemAddSize, I2C_TIMEOUT_FLAG, tickstart) != DAL_OK) + { + /* Abort the ongoing DMA */ + dmaxferstatus = DAL_DMA_Abort_IT(hi2c->hdmatx); + + /* Prevent unused argument(s) compilation and MISRA warning */ + UNUSED(dmaxferstatus); + + /* Set the unused I2C DMA transfer complete callback to NULL */ + hi2c->hdmatx->XferCpltCallback = NULL; + + /* Disable Acknowledge */ + CLEAR_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKEN); + + hi2c->XferSize = 0U; + hi2c->XferCount = 0U; + + /* Disable I2C peripheral to prevent dummy data in buffer */ + __DAL_I2C_DISABLE(hi2c); + + return DAL_ERROR; + } + + /* Clear ADDR flag */ + __DAL_I2C_CLEAR_ADDRFLAG(hi2c); + + /* Process Unlocked */ + __DAL_UNLOCK(hi2c); + + /* Note : The I2C interrupts must be enabled after unlocking current process + to avoid the risk of I2C interrupt handle execution before current + process unlock */ + /* Enable ERR interrupt */ + __DAL_I2C_ENABLE_IT(hi2c, I2C_IT_ERR); + + /* Enable DMA Request */ + SET_BIT(hi2c->Instance->CTRL2, I2C_CTRL2_DMAEN); + + return DAL_OK; + } + else + { + /* Update I2C state */ + hi2c->State = DAL_I2C_STATE_READY; + hi2c->Mode = DAL_I2C_MODE_NONE; + + /* Update I2C error code */ + hi2c->ErrorCode |= DAL_I2C_ERROR_DMA; + + /* Process Unlocked */ + __DAL_UNLOCK(hi2c); + + return DAL_ERROR; + } + } + else + { + /* Update I2C state */ + hi2c->State = DAL_I2C_STATE_READY; + hi2c->Mode = DAL_I2C_MODE_NONE; + + /* Update I2C error code */ + hi2c->ErrorCode |= DAL_I2C_ERROR_SIZE; + + /* Process Unlocked */ + __DAL_UNLOCK(hi2c); + + return DAL_ERROR; + } + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief Reads an amount of data in non-blocking mode with DMA from a specific memory address. + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param DevAddress Target device address: The device 7 bits address value + * in datasheet must be shifted to the left before calling the interface + * @param MemAddress Internal memory address + * @param MemAddSize Size of internal memory address + * @param pData Pointer to data buffer + * @param Size Amount of data to be read + * @retval DAL status + */ +DAL_StatusTypeDef DAL_I2C_Mem_Read_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size) +{ + /* Init tickstart for timeout management*/ + uint32_t tickstart = DAL_GetTick(); + __IO uint32_t count = 0U; + DAL_StatusTypeDef dmaxferstatus; + + /* Check the parameters */ + ASSERT_PARAM(IS_I2C_MEMADD_SIZE(MemAddSize)); + + if (hi2c->State == DAL_I2C_STATE_READY) + { + /* Wait until BUSY flag is reset */ + count = I2C_TIMEOUT_BUSY_FLAG * (SystemCoreClock / 25U / 1000U); + do + { + count--; + if (count == 0U) + { + hi2c->PreviousState = I2C_STATE_NONE; + hi2c->State = DAL_I2C_STATE_READY; + hi2c->Mode = DAL_I2C_MODE_NONE; + hi2c->ErrorCode |= DAL_I2C_ERROR_TIMEOUT; + + /* Process Unlocked */ + __DAL_UNLOCK(hi2c); + + return DAL_ERROR; + } + } + while (__DAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) != RESET); + + /* Process Locked */ + __DAL_LOCK(hi2c); + + /* Check if the I2C is already enabled */ + if ((hi2c->Instance->CTRL1 & I2C_CTRL1_I2CEN) != I2C_CTRL1_I2CEN) + { + /* Enable I2C peripheral */ + __DAL_I2C_ENABLE(hi2c); + } + + /* Disable Pos */ + CLEAR_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKPOS); + + hi2c->State = DAL_I2C_STATE_BUSY_RX; + hi2c->Mode = DAL_I2C_MODE_MEM; + hi2c->ErrorCode = DAL_I2C_ERROR_NONE; + + /* Prepare transfer parameters */ + hi2c->pBuffPtr = pData; + hi2c->XferCount = Size; + hi2c->XferSize = hi2c->XferCount; + hi2c->XferOptions = I2C_NO_OPTION_FRAME; + hi2c->Devaddress = DevAddress; + hi2c->Memaddress = MemAddress; + hi2c->MemaddSize = MemAddSize; + hi2c->EventCount = 0U; + + if (hi2c->XferSize > 0U) + { + if (hi2c->hdmarx != NULL) + { + /* Set the I2C DMA transfer complete callback */ + hi2c->hdmarx->XferCpltCallback = I2C_DMAXferCplt; + + /* Set the DMA error callback */ + hi2c->hdmarx->XferErrorCallback = I2C_DMAError; + + /* Set the unused DMA callbacks to NULL */ + hi2c->hdmarx->XferHalfCpltCallback = NULL; + hi2c->hdmarx->XferM1CpltCallback = NULL; + hi2c->hdmarx->XferM1HalfCpltCallback = NULL; + hi2c->hdmarx->XferAbortCallback = NULL; + + /* Enable the DMA stream */ + dmaxferstatus = DAL_DMA_Start_IT(hi2c->hdmarx, (uint32_t)&hi2c->Instance->DATA, (uint32_t)hi2c->pBuffPtr, hi2c->XferSize); + } + else + { + /* Update I2C state */ + hi2c->State = DAL_I2C_STATE_READY; + hi2c->Mode = DAL_I2C_MODE_NONE; + + /* Update I2C error code */ + hi2c->ErrorCode |= DAL_I2C_ERROR_DMA_PARAM; + + /* Process Unlocked */ + __DAL_UNLOCK(hi2c); + + return DAL_ERROR; + } + + if (dmaxferstatus == DAL_OK) + { + /* Send Slave Address and Memory Address */ + if (I2C_RequestMemoryRead(hi2c, DevAddress, MemAddress, MemAddSize, I2C_TIMEOUT_FLAG, tickstart) != DAL_OK) + { + /* Abort the ongoing DMA */ + dmaxferstatus = DAL_DMA_Abort_IT(hi2c->hdmarx); + + /* Prevent unused argument(s) compilation and MISRA warning */ + UNUSED(dmaxferstatus); + + /* Set the unused I2C DMA transfer complete callback to NULL */ + hi2c->hdmarx->XferCpltCallback = NULL; + + /* Disable Acknowledge */ + CLEAR_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKEN); + + hi2c->XferSize = 0U; + hi2c->XferCount = 0U; + + /* Disable I2C peripheral to prevent dummy data in buffer */ + __DAL_I2C_DISABLE(hi2c); + + return DAL_ERROR; + } + + if (hi2c->XferSize == 1U) + { + /* Disable Acknowledge */ + CLEAR_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKEN); + } + else + { + /* Enable Last DMA bit */ + SET_BIT(hi2c->Instance->CTRL2, I2C_CTRL2_LTCFG); + } + + /* Clear ADDR flag */ + __DAL_I2C_CLEAR_ADDRFLAG(hi2c); + + /* Process Unlocked */ + __DAL_UNLOCK(hi2c); + + /* Note : The I2C interrupts must be enabled after unlocking current process + to avoid the risk of I2C interrupt handle execution before current + process unlock */ + /* Enable ERR interrupt */ + __DAL_I2C_ENABLE_IT(hi2c, I2C_IT_ERR); + + /* Enable DMA Request */ + hi2c->Instance->CTRL2 |= I2C_CTRL2_DMAEN; + } + else + { + /* Update I2C state */ + hi2c->State = DAL_I2C_STATE_READY; + hi2c->Mode = DAL_I2C_MODE_NONE; + + /* Update I2C error code */ + hi2c->ErrorCode |= DAL_I2C_ERROR_DMA; + + /* Process Unlocked */ + __DAL_UNLOCK(hi2c); + + return DAL_ERROR; + } + } + else + { + /* Send Slave Address and Memory Address */ + if (I2C_RequestMemoryRead(hi2c, DevAddress, MemAddress, MemAddSize, I2C_TIMEOUT_FLAG, tickstart) != DAL_OK) + { + return DAL_ERROR; + } + + /* Clear ADDR flag */ + __DAL_I2C_CLEAR_ADDRFLAG(hi2c); + + /* Generate Stop */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_STOP); + + hi2c->State = DAL_I2C_STATE_READY; + + /* Process Unlocked */ + __DAL_UNLOCK(hi2c); + } + + return DAL_OK; + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief Checks if target device is ready for communication. + * @note This function is used with Memory devices + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param DevAddress Target device address: The device 7 bits address value + * in datasheet must be shifted to the left before calling the interface + * @param Trials Number of trials + * @param Timeout Timeout duration + * @retval DAL status + */ +DAL_StatusTypeDef DAL_I2C_IsDeviceReady(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint32_t Trials, uint32_t Timeout) +{ + /* Get tick */ + uint32_t tickstart = DAL_GetTick(); + uint32_t I2C_Trials = 0U; + FlagStatus tmp1; + FlagStatus tmp2; + + if (hi2c->State == DAL_I2C_STATE_READY) + { + /* Wait until BUSY flag is reset */ + if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, I2C_TIMEOUT_BUSY_FLAG, tickstart) != DAL_OK) + { + return DAL_BUSY; + } + + /* Process Locked */ + __DAL_LOCK(hi2c); + + /* Check if the I2C is already enabled */ + if ((hi2c->Instance->CTRL1 & I2C_CTRL1_I2CEN) != I2C_CTRL1_I2CEN) + { + /* Enable I2C peripheral */ + __DAL_I2C_ENABLE(hi2c); + } + + /* Disable Pos */ + CLEAR_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKPOS); + + hi2c->State = DAL_I2C_STATE_BUSY; + hi2c->ErrorCode = DAL_I2C_ERROR_NONE; + hi2c->XferOptions = I2C_NO_OPTION_FRAME; + + do + { + /* Generate Start */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_START); + + /* Wait until SB flag is set */ + if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_SB, RESET, Timeout, tickstart) != DAL_OK) + { + if (READ_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_START) == I2C_CTRL1_START) + { + hi2c->ErrorCode = DAL_I2C_WRONG_START; + } + return DAL_TIMEOUT; + } + + /* Send slave address */ + hi2c->Instance->DATA = I2C_7BIT_ADD_WRITE(DevAddress); + + /* Wait until ADDR or AF flag are set */ + /* Get tick */ + tickstart = DAL_GetTick(); + + tmp1 = __DAL_I2C_GET_FLAG(hi2c, I2C_FLAG_ADDR); + tmp2 = __DAL_I2C_GET_FLAG(hi2c, I2C_FLAG_AF); + while ((hi2c->State != DAL_I2C_STATE_TIMEOUT) && (tmp1 == RESET) && (tmp2 == RESET)) + { + if (((DAL_GetTick() - tickstart) > Timeout) || (Timeout == 0U)) + { + hi2c->State = DAL_I2C_STATE_TIMEOUT; + } + tmp1 = __DAL_I2C_GET_FLAG(hi2c, I2C_FLAG_ADDR); + tmp2 = __DAL_I2C_GET_FLAG(hi2c, I2C_FLAG_AF); + } + + hi2c->State = DAL_I2C_STATE_READY; + + /* Check if the ADDR flag has been set */ + if (__DAL_I2C_GET_FLAG(hi2c, I2C_FLAG_ADDR) == SET) + { + /* Generate Stop */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_STOP); + + /* Clear ADDR Flag */ + __DAL_I2C_CLEAR_ADDRFLAG(hi2c); + + /* Wait until BUSY flag is reset */ + if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, I2C_TIMEOUT_BUSY_FLAG, tickstart) != DAL_OK) + { + return DAL_ERROR; + } + + hi2c->State = DAL_I2C_STATE_READY; + + /* Process Unlocked */ + __DAL_UNLOCK(hi2c); + + return DAL_OK; + } + else + { + /* Generate Stop */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_STOP); + + /* Clear AF Flag */ + __DAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF); + + /* Wait until BUSY flag is reset */ + if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, I2C_TIMEOUT_BUSY_FLAG, tickstart) != DAL_OK) + { + return DAL_ERROR; + } + } + + /* Increment Trials */ + I2C_Trials++; + } + while (I2C_Trials < Trials); + + hi2c->State = DAL_I2C_STATE_READY; + + /* Process Unlocked */ + __DAL_UNLOCK(hi2c); + + return DAL_ERROR; + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief Sequential transmit in master I2C mode an amount of data in non-blocking mode with Interrupt. + * @note This interface allow to manage repeated start condition when a direction change during transfer + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param DevAddress Target device address: The device 7 bits address value + * in datasheet must be shifted to the left before calling the interface + * @param pData Pointer to data buffer + * @param Size Amount of data to be sent + * @param XferOptions Options of Transfer, value of @ref I2C_XferOptions_definition + * @retval DAL status + */ +DAL_StatusTypeDef DAL_I2C_Master_Seq_Transmit_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t XferOptions) +{ + __IO uint32_t Prev_State = 0x00U; + __IO uint32_t count = 0x00U; + + /* Check the parameters */ + ASSERT_PARAM(IS_I2C_TRANSFER_OPTIONS_REQUEST(XferOptions)); + + if (hi2c->State == DAL_I2C_STATE_READY) + { + /* Check Busy Flag only if FIRST call of Master interface */ + if ((READ_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_STOP) == I2C_CTRL1_STOP) || (XferOptions == I2C_FIRST_AND_LAST_FRAME) || (XferOptions == I2C_FIRST_FRAME)) + { + /* Wait until BUSY flag is reset */ + count = I2C_TIMEOUT_BUSY_FLAG * (SystemCoreClock / 25U / 1000U); + do + { + count--; + if (count == 0U) + { + hi2c->PreviousState = I2C_STATE_NONE; + hi2c->State = DAL_I2C_STATE_READY; + hi2c->Mode = DAL_I2C_MODE_NONE; + hi2c->ErrorCode |= DAL_I2C_ERROR_TIMEOUT; + + /* Process Unlocked */ + __DAL_UNLOCK(hi2c); + + return DAL_ERROR; + } + } + while (__DAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) != RESET); + } + + /* Process Locked */ + __DAL_LOCK(hi2c); + + /* Check if the I2C is already enabled */ + if ((hi2c->Instance->CTRL1 & I2C_CTRL1_I2CEN) != I2C_CTRL1_I2CEN) + { + /* Enable I2C peripheral */ + __DAL_I2C_ENABLE(hi2c); + } + + /* Disable Pos */ + CLEAR_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKPOS); + + hi2c->State = DAL_I2C_STATE_BUSY_TX; + hi2c->Mode = DAL_I2C_MODE_MASTER; + hi2c->ErrorCode = DAL_I2C_ERROR_NONE; + + /* Prepare transfer parameters */ + hi2c->pBuffPtr = pData; + hi2c->XferCount = Size; + hi2c->XferSize = hi2c->XferCount; + hi2c->XferOptions = XferOptions; + hi2c->Devaddress = DevAddress; + + Prev_State = hi2c->PreviousState; + + /* If transfer direction not change and there is no request to start another frame, do not generate Restart Condition */ + /* Mean Previous state is same as current state */ + if ((Prev_State != I2C_STATE_MASTER_BUSY_TX) || (IS_I2C_TRANSFER_OTHER_OPTIONS_REQUEST(XferOptions) == 1)) + { + /* Generate Start */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_START); + } + + /* Process Unlocked */ + __DAL_UNLOCK(hi2c); + + /* Note : The I2C interrupts must be enabled after unlocking current process + to avoid the risk of I2C interrupt handle execution before current + process unlock */ + + /* Enable EVT, BUF and ERR interrupt */ + __DAL_I2C_ENABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR); + + return DAL_OK; + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief Sequential transmit in master I2C mode an amount of data in non-blocking mode with DMA. + * @note This interface allow to manage repeated start condition when a direction change during transfer + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param DevAddress Target device address: The device 7 bits address value + * in datasheet must be shifted to the left before calling the interface + * @param pData Pointer to data buffer + * @param Size Amount of data to be sent + * @param XferOptions Options of Transfer, value of @ref I2C_XferOptions_definition + * @retval DAL status + */ +DAL_StatusTypeDef DAL_I2C_Master_Seq_Transmit_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t XferOptions) +{ + __IO uint32_t Prev_State = 0x00U; + __IO uint32_t count = 0x00U; + DAL_StatusTypeDef dmaxferstatus; + + /* Check the parameters */ + ASSERT_PARAM(IS_I2C_TRANSFER_OPTIONS_REQUEST(XferOptions)); + + if (hi2c->State == DAL_I2C_STATE_READY) + { + /* Check Busy Flag only if FIRST call of Master interface */ + if ((READ_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_STOP) == I2C_CTRL1_STOP) || (XferOptions == I2C_FIRST_AND_LAST_FRAME) || (XferOptions == I2C_FIRST_FRAME)) + { + /* Wait until BUSY flag is reset */ + count = I2C_TIMEOUT_BUSY_FLAG * (SystemCoreClock / 25U / 1000U); + do + { + count--; + if (count == 0U) + { + hi2c->PreviousState = I2C_STATE_NONE; + hi2c->State = DAL_I2C_STATE_READY; + hi2c->Mode = DAL_I2C_MODE_NONE; + hi2c->ErrorCode |= DAL_I2C_ERROR_TIMEOUT; + + /* Process Unlocked */ + __DAL_UNLOCK(hi2c); + + return DAL_ERROR; + } + } + while (__DAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) != RESET); + } + + /* Process Locked */ + __DAL_LOCK(hi2c); + + /* Check if the I2C is already enabled */ + if ((hi2c->Instance->CTRL1 & I2C_CTRL1_I2CEN) != I2C_CTRL1_I2CEN) + { + /* Enable I2C peripheral */ + __DAL_I2C_ENABLE(hi2c); + } + + /* Disable Pos */ + CLEAR_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKPOS); + + hi2c->State = DAL_I2C_STATE_BUSY_TX; + hi2c->Mode = DAL_I2C_MODE_MASTER; + hi2c->ErrorCode = DAL_I2C_ERROR_NONE; + + /* Prepare transfer parameters */ + hi2c->pBuffPtr = pData; + hi2c->XferCount = Size; + hi2c->XferSize = hi2c->XferCount; + hi2c->XferOptions = XferOptions; + hi2c->Devaddress = DevAddress; + + Prev_State = hi2c->PreviousState; + + if (hi2c->XferSize > 0U) + { + if (hi2c->hdmatx != NULL) + { + /* Set the I2C DMA transfer complete callback */ + hi2c->hdmatx->XferCpltCallback = I2C_DMAXferCplt; + + /* Set the DMA error callback */ + hi2c->hdmatx->XferErrorCallback = I2C_DMAError; + + /* Set the unused DMA callbacks to NULL */ + hi2c->hdmatx->XferHalfCpltCallback = NULL; + hi2c->hdmatx->XferAbortCallback = NULL; + + /* Enable the DMA stream */ + dmaxferstatus = DAL_DMA_Start_IT(hi2c->hdmatx, (uint32_t)hi2c->pBuffPtr, (uint32_t)&hi2c->Instance->DATA, hi2c->XferSize); + } + else + { + /* Update I2C state */ + hi2c->State = DAL_I2C_STATE_READY; + hi2c->Mode = DAL_I2C_MODE_NONE; + + /* Update I2C error code */ + hi2c->ErrorCode |= DAL_I2C_ERROR_DMA_PARAM; + + /* Process Unlocked */ + __DAL_UNLOCK(hi2c); + + return DAL_ERROR; + } + + if (dmaxferstatus == DAL_OK) + { + /* Enable Acknowledge */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKEN); + + /* If transfer direction not change and there is no request to start another frame, do not generate Restart Condition */ + /* Mean Previous state is same as current state */ + if ((Prev_State != I2C_STATE_MASTER_BUSY_TX) || (IS_I2C_TRANSFER_OTHER_OPTIONS_REQUEST(XferOptions) == 1)) + { + /* Generate Start */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_START); + } + + /* Process Unlocked */ + __DAL_UNLOCK(hi2c); + + /* Note : The I2C interrupts must be enabled after unlocking current process + to avoid the risk of I2C interrupt handle execution before current + process unlock */ + + /* If XferOptions is not associated to a new frame, mean no start bit is request, enable directly the DMA request */ + /* In other cases, DMA request is enabled after Slave address treatment in IRQHandler */ + if ((XferOptions == I2C_NEXT_FRAME) || (XferOptions == I2C_LAST_FRAME) || (XferOptions == I2C_LAST_FRAME_NO_STOP)) + { + /* Enable DMA Request */ + SET_BIT(hi2c->Instance->CTRL2, I2C_CTRL2_DMAEN); + } + + /* Enable EVT and ERR interrupt */ + __DAL_I2C_ENABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_ERR); + } + else + { + /* Update I2C state */ + hi2c->State = DAL_I2C_STATE_READY; + hi2c->Mode = DAL_I2C_MODE_NONE; + + /* Update I2C error code */ + hi2c->ErrorCode |= DAL_I2C_ERROR_DMA; + + /* Process Unlocked */ + __DAL_UNLOCK(hi2c); + + return DAL_ERROR; + } + } + else + { + /* Enable Acknowledge */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKEN); + + /* If transfer direction not change and there is no request to start another frame, do not generate Restart Condition */ + /* Mean Previous state is same as current state */ + if ((Prev_State != I2C_STATE_MASTER_BUSY_TX) || (IS_I2C_TRANSFER_OTHER_OPTIONS_REQUEST(XferOptions) == 1)) + { + /* Generate Start */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_START); + } + + /* Process Unlocked */ + __DAL_UNLOCK(hi2c); + + /* Note : The I2C interrupts must be enabled after unlocking current process + to avoid the risk of I2C interrupt handle execution before current + process unlock */ + + /* Enable EVT, BUF and ERR interrupt */ + __DAL_I2C_ENABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR); + } + + return DAL_OK; + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief Sequential receive in master I2C mode an amount of data in non-blocking mode with Interrupt + * @note This interface allow to manage repeated start condition when a direction change during transfer + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param DevAddress Target device address: The device 7 bits address value + * in datasheet must be shifted to the left before calling the interface + * @param pData Pointer to data buffer + * @param Size Amount of data to be sent + * @param XferOptions Options of Transfer, value of @ref I2C_XferOptions_definition + * @retval DAL status + */ +DAL_StatusTypeDef DAL_I2C_Master_Seq_Receive_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t XferOptions) +{ + __IO uint32_t Prev_State = 0x00U; + __IO uint32_t count = 0U; + uint32_t enableIT = (I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR); + + /* Check the parameters */ + ASSERT_PARAM(IS_I2C_TRANSFER_OPTIONS_REQUEST(XferOptions)); + + if (hi2c->State == DAL_I2C_STATE_READY) + { + /* Check Busy Flag only if FIRST call of Master interface */ + if ((READ_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_STOP) == I2C_CTRL1_STOP) || (XferOptions == I2C_FIRST_AND_LAST_FRAME) || (XferOptions == I2C_FIRST_FRAME)) + { + /* Wait until BUSY flag is reset */ + count = I2C_TIMEOUT_BUSY_FLAG * (SystemCoreClock / 25U / 1000U); + do + { + count--; + if (count == 0U) + { + hi2c->PreviousState = I2C_STATE_NONE; + hi2c->State = DAL_I2C_STATE_READY; + hi2c->Mode = DAL_I2C_MODE_NONE; + hi2c->ErrorCode |= DAL_I2C_ERROR_TIMEOUT; + + /* Process Unlocked */ + __DAL_UNLOCK(hi2c); + + return DAL_ERROR; + } + } + while (__DAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) != RESET); + } + + /* Process Locked */ + __DAL_LOCK(hi2c); + + /* Check if the I2C is already enabled */ + if ((hi2c->Instance->CTRL1 & I2C_CTRL1_I2CEN) != I2C_CTRL1_I2CEN) + { + /* Enable I2C peripheral */ + __DAL_I2C_ENABLE(hi2c); + } + + /* Disable Pos */ + CLEAR_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKPOS); + + hi2c->State = DAL_I2C_STATE_BUSY_RX; + hi2c->Mode = DAL_I2C_MODE_MASTER; + hi2c->ErrorCode = DAL_I2C_ERROR_NONE; + + /* Prepare transfer parameters */ + hi2c->pBuffPtr = pData; + hi2c->XferCount = Size; + hi2c->XferSize = hi2c->XferCount; + hi2c->XferOptions = XferOptions; + hi2c->Devaddress = DevAddress; + + Prev_State = hi2c->PreviousState; + + if ((hi2c->XferCount == 2U) && ((XferOptions == I2C_LAST_FRAME) || (XferOptions == I2C_LAST_FRAME_NO_STOP))) + { + if (Prev_State == I2C_STATE_MASTER_BUSY_RX) + { + /* Disable Acknowledge */ + CLEAR_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKEN); + + /* Enable Pos */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKPOS); + + /* Remove Enabling of IT_BUF, mean RXNE treatment, treat the 2 bytes through BTF */ + enableIT &= ~I2C_IT_BUF; + } + else + { + /* Enable Acknowledge */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKEN); + } + } + else + { + /* Enable Acknowledge */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKEN); + } + + /* If transfer direction not change and there is no request to start another frame, do not generate Restart Condition */ + /* Mean Previous state is same as current state */ + if ((Prev_State != I2C_STATE_MASTER_BUSY_RX) || (IS_I2C_TRANSFER_OTHER_OPTIONS_REQUEST(XferOptions) == 1)) + { + /* Generate Start */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_START); + } + + /* Process Unlocked */ + __DAL_UNLOCK(hi2c); + + /* Note : The I2C interrupts must be enabled after unlocking current process + to avoid the risk of I2C interrupt handle execution before current + process unlock */ + + /* Enable interrupts */ + __DAL_I2C_ENABLE_IT(hi2c, enableIT); + + return DAL_OK; + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief Sequential receive in master mode an amount of data in non-blocking mode with DMA + * @note This interface allow to manage repeated start condition when a direction change during transfer + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param DevAddress Target device address: The device 7 bits address value + * in datasheet must be shifted to the left before calling the interface + * @param pData Pointer to data buffer + * @param Size Amount of data to be sent + * @param XferOptions Options of Transfer, value of @ref I2C_XferOptions_definition + * @retval DAL status + */ +DAL_StatusTypeDef DAL_I2C_Master_Seq_Receive_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t XferOptions) +{ + __IO uint32_t Prev_State = 0x00U; + __IO uint32_t count = 0U; + uint32_t enableIT = (I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR); + DAL_StatusTypeDef dmaxferstatus; + + /* Check the parameters */ + ASSERT_PARAM(IS_I2C_TRANSFER_OPTIONS_REQUEST(XferOptions)); + + if (hi2c->State == DAL_I2C_STATE_READY) + { + /* Check Busy Flag only if FIRST call of Master interface */ + if ((READ_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_STOP) == I2C_CTRL1_STOP) || (XferOptions == I2C_FIRST_AND_LAST_FRAME) || (XferOptions == I2C_FIRST_FRAME)) + { + /* Wait until BUSY flag is reset */ + count = I2C_TIMEOUT_BUSY_FLAG * (SystemCoreClock / 25U / 1000U); + do + { + count--; + if (count == 0U) + { + hi2c->PreviousState = I2C_STATE_NONE; + hi2c->State = DAL_I2C_STATE_READY; + hi2c->Mode = DAL_I2C_MODE_NONE; + hi2c->ErrorCode |= DAL_I2C_ERROR_TIMEOUT; + + /* Process Unlocked */ + __DAL_UNLOCK(hi2c); + + return DAL_ERROR; + } + } + while (__DAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) != RESET); + } + + /* Process Locked */ + __DAL_LOCK(hi2c); + + /* Check if the I2C is already enabled */ + if ((hi2c->Instance->CTRL1 & I2C_CTRL1_I2CEN) != I2C_CTRL1_I2CEN) + { + /* Enable I2C peripheral */ + __DAL_I2C_ENABLE(hi2c); + } + + /* Disable Pos */ + CLEAR_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKPOS); + + /* Clear Last DMA bit */ + CLEAR_BIT(hi2c->Instance->CTRL2, I2C_CTRL2_LTCFG); + + hi2c->State = DAL_I2C_STATE_BUSY_RX; + hi2c->Mode = DAL_I2C_MODE_MASTER; + hi2c->ErrorCode = DAL_I2C_ERROR_NONE; + + /* Prepare transfer parameters */ + hi2c->pBuffPtr = pData; + hi2c->XferCount = Size; + hi2c->XferSize = hi2c->XferCount; + hi2c->XferOptions = XferOptions; + hi2c->Devaddress = DevAddress; + + Prev_State = hi2c->PreviousState; + + if (hi2c->XferSize > 0U) + { + if ((hi2c->XferCount == 2U) && ((XferOptions == I2C_LAST_FRAME) || (XferOptions == I2C_LAST_FRAME_NO_STOP))) + { + if (Prev_State == I2C_STATE_MASTER_BUSY_RX) + { + /* Disable Acknowledge */ + CLEAR_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKEN); + + /* Enable Pos */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKPOS); + + /* Enable Last DMA bit */ + SET_BIT(hi2c->Instance->CTRL2, I2C_CTRL2_LTCFG); + } + else + { + /* Enable Acknowledge */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKEN); + } + } + else + { + /* Enable Acknowledge */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKEN); + + if ((XferOptions == I2C_LAST_FRAME) || (XferOptions == I2C_OTHER_AND_LAST_FRAME) || (XferOptions == I2C_LAST_FRAME_NO_STOP)) + { + /* Enable Last DMA bit */ + SET_BIT(hi2c->Instance->CTRL2, I2C_CTRL2_LTCFG); + } + } + if (hi2c->hdmarx != NULL) + { + /* Set the I2C DMA transfer complete callback */ + hi2c->hdmarx->XferCpltCallback = I2C_DMAXferCplt; + + /* Set the DMA error callback */ + hi2c->hdmarx->XferErrorCallback = I2C_DMAError; + + /* Set the unused DMA callbacks to NULL */ + hi2c->hdmarx->XferHalfCpltCallback = NULL; + hi2c->hdmarx->XferAbortCallback = NULL; + + /* Enable the DMA stream */ + dmaxferstatus = DAL_DMA_Start_IT(hi2c->hdmarx, (uint32_t)&hi2c->Instance->DATA, (uint32_t)hi2c->pBuffPtr, hi2c->XferSize); + } + else + { + /* Update I2C state */ + hi2c->State = DAL_I2C_STATE_READY; + hi2c->Mode = DAL_I2C_MODE_NONE; + + /* Update I2C error code */ + hi2c->ErrorCode |= DAL_I2C_ERROR_DMA_PARAM; + + /* Process Unlocked */ + __DAL_UNLOCK(hi2c); + + return DAL_ERROR; + } + if (dmaxferstatus == DAL_OK) + { + /* If transfer direction not change and there is no request to start another frame, do not generate Restart Condition */ + /* Mean Previous state is same as current state */ + if ((Prev_State != I2C_STATE_MASTER_BUSY_RX) || (IS_I2C_TRANSFER_OTHER_OPTIONS_REQUEST(XferOptions) == 1)) + { + /* Generate Start */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_START); + + /* Update interrupt for only EVT and ERR */ + enableIT = (I2C_IT_EVT | I2C_IT_ERR); + } + else + { + /* Update interrupt for only ERR */ + enableIT = I2C_IT_ERR; + } + + /* Process Unlocked */ + __DAL_UNLOCK(hi2c); + + /* Note : The I2C interrupts must be enabled after unlocking current process + to avoid the risk of I2C interrupt handle execution before current + process unlock */ + + /* If XferOptions is not associated to a new frame, mean no start bit is request, enable directly the DMA request */ + /* In other cases, DMA request is enabled after Slave address treatment in IRQHandler */ + if ((XferOptions == I2C_NEXT_FRAME) || (XferOptions == I2C_LAST_FRAME) || (XferOptions == I2C_LAST_FRAME_NO_STOP)) + { + /* Enable DMA Request */ + SET_BIT(hi2c->Instance->CTRL2, I2C_CTRL2_DMAEN); + } + + /* Enable EVT and ERR interrupt */ + __DAL_I2C_ENABLE_IT(hi2c, enableIT); + } + else + { + /* Update I2C state */ + hi2c->State = DAL_I2C_STATE_READY; + hi2c->Mode = DAL_I2C_MODE_NONE; + + /* Update I2C error code */ + hi2c->ErrorCode |= DAL_I2C_ERROR_DMA; + + /* Process Unlocked */ + __DAL_UNLOCK(hi2c); + + return DAL_ERROR; + } + } + else + { + /* Enable Acknowledge */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKEN); + + /* If transfer direction not change and there is no request to start another frame, do not generate Restart Condition */ + /* Mean Previous state is same as current state */ + if ((Prev_State != I2C_STATE_MASTER_BUSY_RX) || (IS_I2C_TRANSFER_OTHER_OPTIONS_REQUEST(XferOptions) == 1)) + { + /* Generate Start */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_START); + } + + /* Process Unlocked */ + __DAL_UNLOCK(hi2c); + + /* Note : The I2C interrupts must be enabled after unlocking current process + to avoid the risk of I2C interrupt handle execution before current + process unlock */ + + /* Enable interrupts */ + __DAL_I2C_ENABLE_IT(hi2c, enableIT); + } + return DAL_OK; + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief Sequential transmit in slave mode an amount of data in non-blocking mode with Interrupt + * @note This interface allow to manage repeated start condition when a direction change during transfer + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param pData Pointer to data buffer + * @param Size Amount of data to be sent + * @param XferOptions Options of Transfer, value of @ref I2C_XferOptions_definition + * @retval DAL status + */ +DAL_StatusTypeDef DAL_I2C_Slave_Seq_Transmit_IT(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size, uint32_t XferOptions) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_I2C_TRANSFER_OPTIONS_REQUEST(XferOptions)); + + if (((uint32_t)hi2c->State & (uint32_t)DAL_I2C_STATE_LISTEN) == (uint32_t)DAL_I2C_STATE_LISTEN) + { + if ((pData == NULL) || (Size == 0U)) + { + return DAL_ERROR; + } + + /* Process Locked */ + __DAL_LOCK(hi2c); + + /* Check if the I2C is already enabled */ + if ((hi2c->Instance->CTRL1 & I2C_CTRL1_I2CEN) != I2C_CTRL1_I2CEN) + { + /* Enable I2C peripheral */ + __DAL_I2C_ENABLE(hi2c); + } + + /* Disable Pos */ + CLEAR_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKPOS); + + hi2c->State = DAL_I2C_STATE_BUSY_TX_LISTEN; + hi2c->Mode = DAL_I2C_MODE_SLAVE; + hi2c->ErrorCode = DAL_I2C_ERROR_NONE; + + /* Prepare transfer parameters */ + hi2c->pBuffPtr = pData; + hi2c->XferCount = Size; + hi2c->XferSize = hi2c->XferCount; + hi2c->XferOptions = XferOptions; + + /* Clear ADDR flag */ + __DAL_I2C_CLEAR_ADDRFLAG(hi2c); + + /* Process Unlocked */ + __DAL_UNLOCK(hi2c); + + /* Note : The I2C interrupts must be enabled after unlocking current process + to avoid the risk of I2C interrupt handle execution before current + process unlock */ + + /* Enable EVT, BUF and ERR interrupt */ + __DAL_I2C_ENABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR); + + return DAL_OK; + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief Sequential transmit in slave mode an amount of data in non-blocking mode with DMA + * @note This interface allow to manage repeated start condition when a direction change during transfer + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param pData Pointer to data buffer + * @param Size Amount of data to be sent + * @param XferOptions Options of Transfer, value of @ref I2C_XferOptions_definition + * @retval DAL status + */ +DAL_StatusTypeDef DAL_I2C_Slave_Seq_Transmit_DMA(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size, uint32_t XferOptions) +{ + DAL_StatusTypeDef dmaxferstatus; + + /* Check the parameters */ + ASSERT_PARAM(IS_I2C_TRANSFER_OPTIONS_REQUEST(XferOptions)); + + if (((uint32_t)hi2c->State & (uint32_t)DAL_I2C_STATE_LISTEN) == (uint32_t)DAL_I2C_STATE_LISTEN) + { + if ((pData == NULL) || (Size == 0U)) + { + return DAL_ERROR; + } + + /* Process Locked */ + __DAL_LOCK(hi2c); + + /* Disable Interrupts, to prevent preemption during treatment in case of multicall */ + __DAL_I2C_DISABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_ERR); + + /* I2C cannot manage full duplex exchange so disable previous IT enabled if any */ + /* and then toggle the DAL slave RX state to TX state */ + if (hi2c->State == DAL_I2C_STATE_BUSY_RX_LISTEN) + { + if ((hi2c->Instance->CTRL2 & I2C_CTRL2_DMAEN) == I2C_CTRL2_DMAEN) + { + /* Abort DMA Xfer if any */ + if (hi2c->hdmarx != NULL) + { + CLEAR_BIT(hi2c->Instance->CTRL2, I2C_CTRL2_DMAEN); + + /* Set the I2C DMA Abort callback : + will lead to call DAL_I2C_ErrorCallback() at end of DMA abort procedure */ + hi2c->hdmarx->XferAbortCallback = I2C_DMAAbort; + + /* Abort DMA RX */ + if (DAL_DMA_Abort_IT(hi2c->hdmarx) != DAL_OK) + { + /* Call Directly XferAbortCallback function in case of error */ + hi2c->hdmarx->XferAbortCallback(hi2c->hdmarx); + } + } + } + } + else if (hi2c->State == DAL_I2C_STATE_BUSY_TX_LISTEN) + { + if ((hi2c->Instance->CTRL2 & I2C_CTRL2_DMAEN) == I2C_CTRL2_DMAEN) + { + CLEAR_BIT(hi2c->Instance->CTRL2, I2C_CTRL2_DMAEN); + + /* Abort DMA Xfer if any */ + if (hi2c->hdmatx != NULL) + { + /* Set the I2C DMA Abort callback : + will lead to call DAL_I2C_ErrorCallback() at end of DMA abort procedure */ + hi2c->hdmatx->XferAbortCallback = I2C_DMAAbort; + + /* Abort DMA TX */ + if (DAL_DMA_Abort_IT(hi2c->hdmatx) != DAL_OK) + { + /* Call Directly XferAbortCallback function in case of error */ + hi2c->hdmatx->XferAbortCallback(hi2c->hdmatx); + } + } + } + } + else + { + /* Nothing to do */ + } + + /* Check if the I2C is already enabled */ + if ((hi2c->Instance->CTRL1 & I2C_CTRL1_I2CEN) != I2C_CTRL1_I2CEN) + { + /* Enable I2C peripheral */ + __DAL_I2C_ENABLE(hi2c); + } + + /* Disable Pos */ + CLEAR_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKPOS); + + hi2c->State = DAL_I2C_STATE_BUSY_TX_LISTEN; + hi2c->Mode = DAL_I2C_MODE_SLAVE; + hi2c->ErrorCode = DAL_I2C_ERROR_NONE; + + /* Prepare transfer parameters */ + hi2c->pBuffPtr = pData; + hi2c->XferCount = Size; + hi2c->XferSize = hi2c->XferCount; + hi2c->XferOptions = XferOptions; + + if (hi2c->hdmatx != NULL) + { + /* Set the I2C DMA transfer complete callback */ + hi2c->hdmatx->XferCpltCallback = I2C_DMAXferCplt; + + /* Set the DMA error callback */ + hi2c->hdmatx->XferErrorCallback = I2C_DMAError; + + /* Set the unused DMA callbacks to NULL */ + hi2c->hdmatx->XferHalfCpltCallback = NULL; + hi2c->hdmatx->XferAbortCallback = NULL; + + /* Enable the DMA stream */ + dmaxferstatus = DAL_DMA_Start_IT(hi2c->hdmatx, (uint32_t)hi2c->pBuffPtr, (uint32_t)&hi2c->Instance->DATA, hi2c->XferSize); + } + else + { + /* Update I2C state */ + hi2c->State = DAL_I2C_STATE_LISTEN; + hi2c->Mode = DAL_I2C_MODE_NONE; + + /* Update I2C error code */ + hi2c->ErrorCode |= DAL_I2C_ERROR_DMA_PARAM; + + /* Process Unlocked */ + __DAL_UNLOCK(hi2c); + + return DAL_ERROR; + } + + if (dmaxferstatus == DAL_OK) + { + /* Enable Address Acknowledge */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKEN); + + /* Clear ADDR flag */ + __DAL_I2C_CLEAR_ADDRFLAG(hi2c); + + /* Process Unlocked */ + __DAL_UNLOCK(hi2c); + + /* Note : The I2C interrupts must be enabled after unlocking current process + to avoid the risk of I2C interrupt handle execution before current + process unlock */ + /* Enable EVT and ERR interrupt */ + __DAL_I2C_ENABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_ERR); + + /* Enable DMA Request */ + hi2c->Instance->CTRL2 |= I2C_CTRL2_DMAEN; + + return DAL_OK; + } + else + { + /* Update I2C state */ + hi2c->State = DAL_I2C_STATE_READY; + hi2c->Mode = DAL_I2C_MODE_NONE; + + /* Update I2C error code */ + hi2c->ErrorCode |= DAL_I2C_ERROR_DMA; + + /* Process Unlocked */ + __DAL_UNLOCK(hi2c); + + return DAL_ERROR; + } + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief Sequential receive in slave mode an amount of data in non-blocking mode with Interrupt + * @note This interface allow to manage repeated start condition when a direction change during transfer + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param pData Pointer to data buffer + * @param Size Amount of data to be sent + * @param XferOptions Options of Transfer, value of @ref I2C_XferOptions_definition + * @retval DAL status + */ +DAL_StatusTypeDef DAL_I2C_Slave_Seq_Receive_IT(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size, uint32_t XferOptions) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_I2C_TRANSFER_OPTIONS_REQUEST(XferOptions)); + + if (((uint32_t)hi2c->State & (uint32_t)DAL_I2C_STATE_LISTEN) == (uint32_t)DAL_I2C_STATE_LISTEN) + { + if ((pData == NULL) || (Size == 0U)) + { + return DAL_ERROR; + } + + /* Process Locked */ + __DAL_LOCK(hi2c); + + /* Check if the I2C is already enabled */ + if ((hi2c->Instance->CTRL1 & I2C_CTRL1_I2CEN) != I2C_CTRL1_I2CEN) + { + /* Enable I2C peripheral */ + __DAL_I2C_ENABLE(hi2c); + } + + /* Disable Pos */ + CLEAR_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKPOS); + + hi2c->State = DAL_I2C_STATE_BUSY_RX_LISTEN; + hi2c->Mode = DAL_I2C_MODE_SLAVE; + hi2c->ErrorCode = DAL_I2C_ERROR_NONE; + + /* Prepare transfer parameters */ + hi2c->pBuffPtr = pData; + hi2c->XferCount = Size; + hi2c->XferSize = hi2c->XferCount; + hi2c->XferOptions = XferOptions; + + /* Clear ADDR flag */ + __DAL_I2C_CLEAR_ADDRFLAG(hi2c); + + /* Process Unlocked */ + __DAL_UNLOCK(hi2c); + + /* Note : The I2C interrupts must be enabled after unlocking current process + to avoid the risk of I2C interrupt handle execution before current + process unlock */ + + /* Enable EVT, BUF and ERR interrupt */ + __DAL_I2C_ENABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR); + + return DAL_OK; + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief Sequential receive in slave mode an amount of data in non-blocking mode with DMA + * @note This interface allow to manage repeated start condition when a direction change during transfer + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param pData Pointer to data buffer + * @param Size Amount of data to be sent + * @param XferOptions Options of Transfer, value of @ref I2C_XferOptions_definition + * @retval DAL status + */ +DAL_StatusTypeDef DAL_I2C_Slave_Seq_Receive_DMA(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size, uint32_t XferOptions) +{ + DAL_StatusTypeDef dmaxferstatus; + + /* Check the parameters */ + ASSERT_PARAM(IS_I2C_TRANSFER_OPTIONS_REQUEST(XferOptions)); + + if (((uint32_t)hi2c->State & (uint32_t)DAL_I2C_STATE_LISTEN) == (uint32_t)DAL_I2C_STATE_LISTEN) + { + if ((pData == NULL) || (Size == 0U)) + { + return DAL_ERROR; + } + + /* Process Locked */ + __DAL_LOCK(hi2c); + + /* Disable Interrupts, to prevent preemption during treatment in case of multicall */ + __DAL_I2C_DISABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_ERR); + + /* I2C cannot manage full duplex exchange so disable previous IT enabled if any */ + /* and then toggle the DAL slave RX state to TX state */ + if (hi2c->State == DAL_I2C_STATE_BUSY_RX_LISTEN) + { + if ((hi2c->Instance->CTRL2 & I2C_CTRL2_DMAEN) == I2C_CTRL2_DMAEN) + { + /* Abort DMA Xfer if any */ + if (hi2c->hdmarx != NULL) + { + CLEAR_BIT(hi2c->Instance->CTRL2, I2C_CTRL2_DMAEN); + + /* Set the I2C DMA Abort callback : + will lead to call DAL_I2C_ErrorCallback() at end of DMA abort procedure */ + hi2c->hdmarx->XferAbortCallback = I2C_DMAAbort; + + /* Abort DMA RX */ + if (DAL_DMA_Abort_IT(hi2c->hdmarx) != DAL_OK) + { + /* Call Directly XferAbortCallback function in case of error */ + hi2c->hdmarx->XferAbortCallback(hi2c->hdmarx); + } + } + } + } + else if (hi2c->State == DAL_I2C_STATE_BUSY_TX_LISTEN) + { + if ((hi2c->Instance->CTRL2 & I2C_CTRL2_DMAEN) == I2C_CTRL2_DMAEN) + { + CLEAR_BIT(hi2c->Instance->CTRL2, I2C_CTRL2_DMAEN); + + /* Abort DMA Xfer if any */ + if (hi2c->hdmatx != NULL) + { + /* Set the I2C DMA Abort callback : + will lead to call DAL_I2C_ErrorCallback() at end of DMA abort procedure */ + hi2c->hdmatx->XferAbortCallback = I2C_DMAAbort; + + /* Abort DMA TX */ + if (DAL_DMA_Abort_IT(hi2c->hdmatx) != DAL_OK) + { + /* Call Directly XferAbortCallback function in case of error */ + hi2c->hdmatx->XferAbortCallback(hi2c->hdmatx); + } + } + } + } + else + { + /* Nothing to do */ + } + + /* Check if the I2C is already enabled */ + if ((hi2c->Instance->CTRL1 & I2C_CTRL1_I2CEN) != I2C_CTRL1_I2CEN) + { + /* Enable I2C peripheral */ + __DAL_I2C_ENABLE(hi2c); + } + + /* Disable Pos */ + CLEAR_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKPOS); + + hi2c->State = DAL_I2C_STATE_BUSY_RX_LISTEN; + hi2c->Mode = DAL_I2C_MODE_SLAVE; + hi2c->ErrorCode = DAL_I2C_ERROR_NONE; + + /* Prepare transfer parameters */ + hi2c->pBuffPtr = pData; + hi2c->XferCount = Size; + hi2c->XferSize = hi2c->XferCount; + hi2c->XferOptions = XferOptions; + + if (hi2c->hdmarx != NULL) + { + /* Set the I2C DMA transfer complete callback */ + hi2c->hdmarx->XferCpltCallback = I2C_DMAXferCplt; + + /* Set the DMA error callback */ + hi2c->hdmarx->XferErrorCallback = I2C_DMAError; + + /* Set the unused DMA callbacks to NULL */ + hi2c->hdmarx->XferHalfCpltCallback = NULL; + hi2c->hdmarx->XferAbortCallback = NULL; + + /* Enable the DMA stream */ + dmaxferstatus = DAL_DMA_Start_IT(hi2c->hdmarx, (uint32_t)&hi2c->Instance->DATA, (uint32_t)hi2c->pBuffPtr, hi2c->XferSize); + } + else + { + /* Update I2C state */ + hi2c->State = DAL_I2C_STATE_LISTEN; + hi2c->Mode = DAL_I2C_MODE_NONE; + + /* Update I2C error code */ + hi2c->ErrorCode |= DAL_I2C_ERROR_DMA_PARAM; + + /* Process Unlocked */ + __DAL_UNLOCK(hi2c); + + return DAL_ERROR; + } + + if (dmaxferstatus == DAL_OK) + { + /* Enable Address Acknowledge */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKEN); + + /* Clear ADDR flag */ + __DAL_I2C_CLEAR_ADDRFLAG(hi2c); + + /* Process Unlocked */ + __DAL_UNLOCK(hi2c); + + /* Enable DMA Request */ + SET_BIT(hi2c->Instance->CTRL2, I2C_CTRL2_DMAEN); + + /* Note : The I2C interrupts must be enabled after unlocking current process + to avoid the risk of I2C interrupt handle execution before current + process unlock */ + /* Enable EVT and ERR interrupt */ + __DAL_I2C_ENABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_ERR); + + return DAL_OK; + } + else + { + /* Update I2C state */ + hi2c->State = DAL_I2C_STATE_READY; + hi2c->Mode = DAL_I2C_MODE_NONE; + + /* Update I2C error code */ + hi2c->ErrorCode |= DAL_I2C_ERROR_DMA; + + /* Process Unlocked */ + __DAL_UNLOCK(hi2c); + + return DAL_ERROR; + } + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief Enable the Address listen mode with Interrupt. + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_I2C_EnableListen_IT(I2C_HandleTypeDef *hi2c) +{ + if (hi2c->State == DAL_I2C_STATE_READY) + { + hi2c->State = DAL_I2C_STATE_LISTEN; + + /* Check if the I2C is already enabled */ + if ((hi2c->Instance->CTRL1 & I2C_CTRL1_I2CEN) != I2C_CTRL1_I2CEN) + { + /* Enable I2C peripheral */ + __DAL_I2C_ENABLE(hi2c); + } + + /* Enable Address Acknowledge */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKEN); + + /* Enable EVT and ERR interrupt */ + __DAL_I2C_ENABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_ERR); + + return DAL_OK; + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief Disable the Address listen mode with Interrupt. + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_I2C_DisableListen_IT(I2C_HandleTypeDef *hi2c) +{ + /* Declaration of tmp to prevent undefined behavior of volatile usage */ + uint32_t tmp; + + /* Disable Address listen mode only if a transfer is not ongoing */ + if (hi2c->State == DAL_I2C_STATE_LISTEN) + { + tmp = (uint32_t)(hi2c->State) & I2C_STATE_MSK; + hi2c->PreviousState = tmp | (uint32_t)(hi2c->Mode); + hi2c->State = DAL_I2C_STATE_READY; + hi2c->Mode = DAL_I2C_MODE_NONE; + + /* Disable Address Acknowledge */ + CLEAR_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKEN); + + /* Disable EVT and ERR interrupt */ + __DAL_I2C_DISABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_ERR); + + return DAL_OK; + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief Abort a master I2C IT or DMA process communication with Interrupt. + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param DevAddress Target device address: The device 7 bits address value + * in datasheet must be shifted to the left before calling the interface + * @retval DAL status + */ +DAL_StatusTypeDef DAL_I2C_Master_Abort_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress) +{ + /* Declaration of temporary variables to prevent undefined behavior of volatile usage */ + DAL_I2C_ModeTypeDef CurrentMode = hi2c->Mode; + + /* Prevent unused argument(s) compilation warning */ + UNUSED(DevAddress); + + /* Abort Master transfer during Receive or Transmit process */ + if ((__DAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) != RESET) && (CurrentMode == DAL_I2C_MODE_MASTER)) + { + /* Process Locked */ + __DAL_LOCK(hi2c); + + hi2c->PreviousState = I2C_STATE_NONE; + hi2c->State = DAL_I2C_STATE_ABORT; + + /* Disable Acknowledge */ + CLEAR_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKEN); + + /* Generate Stop */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_STOP); + + hi2c->XferCount = 0U; + + /* Disable EVT, BUF and ERR interrupt */ + __DAL_I2C_DISABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR); + + /* Process Unlocked */ + __DAL_UNLOCK(hi2c); + + /* Call the corresponding callback to inform upper layer of End of Transfer */ + I2C_ITError(hi2c); + + return DAL_OK; + } + else + { + /* Wrong usage of abort function */ + /* This function should be used only in case of abort monitored by master device */ + /* Or periphal is not in busy state, mean there is no active sequence to be abort */ + return DAL_ERROR; + } +} + +/** + * @} + */ + +/** @defgroup I2C_IRQ_Handler_and_Callbacks IRQ Handler and Callbacks + * @{ + */ + +/** + * @brief This function handles I2C event interrupt request. + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @retval None + */ +void DAL_I2C_EV_IRQHandler(I2C_HandleTypeDef *hi2c) +{ + uint32_t sr1itflags; + uint32_t sr2itflags = 0U; + uint32_t itsources = READ_REG(hi2c->Instance->CTRL2); + uint32_t CurrentXferOptions = hi2c->XferOptions; + DAL_I2C_ModeTypeDef CurrentMode = hi2c->Mode; + DAL_I2C_StateTypeDef CurrentState = hi2c->State; + + /* Master or Memory mode selected */ + if ((CurrentMode == DAL_I2C_MODE_MASTER) || (CurrentMode == DAL_I2C_MODE_MEM)) + { + sr2itflags = READ_REG(hi2c->Instance->STS2); + sr1itflags = READ_REG(hi2c->Instance->STS1); + + /* Exit IRQ event until Start Bit detected in case of Other frame requested */ + if ((I2C_CHECK_FLAG(sr1itflags, I2C_FLAG_SB) == RESET) && (IS_I2C_TRANSFER_OTHER_OPTIONS_REQUEST(CurrentXferOptions) == 1U)) + { + return; + } + + /* SB Set ----------------------------------------------------------------*/ + if ((I2C_CHECK_FLAG(sr1itflags, I2C_FLAG_SB) != RESET) && (I2C_CHECK_IT_SOURCE(itsources, I2C_IT_EVT) != RESET)) + { + /* Convert OTHER_xxx XferOptions if any */ + I2C_ConvertOtherXferOptions(hi2c); + + I2C_Master_SB(hi2c); + } + /* ADD10 Set -------------------------------------------------------------*/ + else if ((I2C_CHECK_FLAG(sr1itflags, I2C_FLAG_ADD10) != RESET) && (I2C_CHECK_IT_SOURCE(itsources, I2C_IT_EVT) != RESET)) + { + I2C_Master_ADD10(hi2c); + } + /* ADDR Set --------------------------------------------------------------*/ + else if ((I2C_CHECK_FLAG(sr1itflags, I2C_FLAG_ADDR) != RESET) && (I2C_CHECK_IT_SOURCE(itsources, I2C_IT_EVT) != RESET)) + { + I2C_Master_ADDR(hi2c); + } + /* I2C in mode Transmitter -----------------------------------------------*/ + else if (I2C_CHECK_FLAG(sr2itflags, I2C_FLAG_TRA) != RESET) + { + /* Do not check buffer and BTF flag if a Xfer DMA is on going */ + if (READ_BIT(hi2c->Instance->CTRL2, I2C_CTRL2_DMAEN) != I2C_CTRL2_DMAEN) + { + /* TXE set and BTF reset -----------------------------------------------*/ + if ((I2C_CHECK_FLAG(sr1itflags, I2C_FLAG_TXE) != RESET) && (I2C_CHECK_IT_SOURCE(itsources, I2C_IT_BUF) != RESET) && (I2C_CHECK_FLAG(sr1itflags, I2C_FLAG_BTF) == RESET)) + { + I2C_MasterTransmit_TXE(hi2c); + } + /* BTF set -------------------------------------------------------------*/ + else if ((I2C_CHECK_FLAG(sr1itflags, I2C_FLAG_BTF) != RESET) && (I2C_CHECK_IT_SOURCE(itsources, I2C_IT_EVT) != RESET)) + { + if (CurrentState == DAL_I2C_STATE_BUSY_TX) + { + I2C_MasterTransmit_BTF(hi2c); + } + else /* DAL_I2C_MODE_MEM */ + { + if (CurrentMode == DAL_I2C_MODE_MEM) + { + I2C_MemoryTransmit_TXE_BTF(hi2c); + } + } + } + else + { + /* Do nothing */ + } + } + } + /* I2C in mode Receiver --------------------------------------------------*/ + else + { + /* Do not check buffer and BTF flag if a Xfer DMA is on going */ + if (READ_BIT(hi2c->Instance->CTRL2, I2C_CTRL2_DMAEN) != I2C_CTRL2_DMAEN) + { + /* RXNE set and BTF reset -----------------------------------------------*/ + if ((I2C_CHECK_FLAG(sr1itflags, I2C_FLAG_RXNE) != RESET) && (I2C_CHECK_IT_SOURCE(itsources, I2C_IT_BUF) != RESET) && (I2C_CHECK_FLAG(sr1itflags, I2C_FLAG_BTF) == RESET)) + { + I2C_MasterReceive_RXNE(hi2c); + } + /* BTF set -------------------------------------------------------------*/ + else if ((I2C_CHECK_FLAG(sr1itflags, I2C_FLAG_BTF) != RESET) && (I2C_CHECK_IT_SOURCE(itsources, I2C_IT_EVT) != RESET)) + { + I2C_MasterReceive_BTF(hi2c); + } + else + { + /* Do nothing */ + } + } + } + } + /* Slave mode selected */ + else + { + /* If an error is detected, read only STS1 register to prevent */ + /* a clear of ADDR flags by reading STS2 after reading STS1 in Error treatment */ + if (hi2c->ErrorCode != DAL_I2C_ERROR_NONE) + { + sr1itflags = READ_REG(hi2c->Instance->STS1); + } + else + { + sr2itflags = READ_REG(hi2c->Instance->STS2); + sr1itflags = READ_REG(hi2c->Instance->STS1); + } + + /* ADDR set --------------------------------------------------------------*/ + if ((I2C_CHECK_FLAG(sr1itflags, I2C_FLAG_ADDR) != RESET) && (I2C_CHECK_IT_SOURCE(itsources, I2C_IT_EVT) != RESET)) + { + /* Now time to read STS2, this will clear ADDR flag automatically */ + if (hi2c->ErrorCode != DAL_I2C_ERROR_NONE) + { + sr2itflags = READ_REG(hi2c->Instance->STS2); + } + I2C_Slave_ADDR(hi2c, sr2itflags); + } + /* STOPF set --------------------------------------------------------------*/ + else if ((I2C_CHECK_FLAG(sr1itflags, I2C_FLAG_STOPF) != RESET) && (I2C_CHECK_IT_SOURCE(itsources, I2C_IT_EVT) != RESET)) + { + I2C_Slave_STOPF(hi2c); + } + /* I2C in mode Transmitter -----------------------------------------------*/ + else if ((CurrentState == DAL_I2C_STATE_BUSY_TX) || (CurrentState == DAL_I2C_STATE_BUSY_TX_LISTEN)) + { + /* TXE set and BTF reset -----------------------------------------------*/ + if ((I2C_CHECK_FLAG(sr1itflags, I2C_FLAG_TXE) != RESET) && (I2C_CHECK_IT_SOURCE(itsources, I2C_IT_BUF) != RESET) && (I2C_CHECK_FLAG(sr1itflags, I2C_FLAG_BTF) == RESET)) + { + I2C_SlaveTransmit_TXE(hi2c); + } + /* BTF set -------------------------------------------------------------*/ + else if ((I2C_CHECK_FLAG(sr1itflags, I2C_FLAG_BTF) != RESET) && (I2C_CHECK_IT_SOURCE(itsources, I2C_IT_EVT) != RESET)) + { + I2C_SlaveTransmit_BTF(hi2c); + } + else + { + /* Do nothing */ + } + } + /* I2C in mode Receiver --------------------------------------------------*/ + else + { + /* RXNE set and BTF reset ----------------------------------------------*/ + if ((I2C_CHECK_FLAG(sr1itflags, I2C_FLAG_RXNE) != RESET) && (I2C_CHECK_IT_SOURCE(itsources, I2C_IT_BUF) != RESET) && (I2C_CHECK_FLAG(sr1itflags, I2C_FLAG_BTF) == RESET)) + { + I2C_SlaveReceive_RXNE(hi2c); + } + /* BTF set -------------------------------------------------------------*/ + else if ((I2C_CHECK_FLAG(sr1itflags, I2C_FLAG_BTF) != RESET) && (I2C_CHECK_IT_SOURCE(itsources, I2C_IT_EVT) != RESET)) + { + I2C_SlaveReceive_BTF(hi2c); + } + else + { + /* Do nothing */ + } + } + } +} + +/** + * @brief This function handles I2C error interrupt request. + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @retval None + */ +void DAL_I2C_ER_IRQHandler(I2C_HandleTypeDef *hi2c) +{ + DAL_I2C_ModeTypeDef tmp1; + uint32_t tmp2; + DAL_I2C_StateTypeDef tmp3; + uint32_t tmp4; + uint32_t sr1itflags = READ_REG(hi2c->Instance->STS1); + uint32_t itsources = READ_REG(hi2c->Instance->CTRL2); + uint32_t error = DAL_I2C_ERROR_NONE; + DAL_I2C_ModeTypeDef CurrentMode = hi2c->Mode; + + /* I2C Bus error interrupt occurred ----------------------------------------*/ + if ((I2C_CHECK_FLAG(sr1itflags, I2C_FLAG_BERR) != RESET) && (I2C_CHECK_IT_SOURCE(itsources, I2C_IT_ERR) != RESET)) + { + error |= DAL_I2C_ERROR_BERR; + + /* Clear BERR flag */ + __DAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_BERR); + } + + /* I2C Arbitration Lost error interrupt occurred ---------------------------*/ + if ((I2C_CHECK_FLAG(sr1itflags, I2C_FLAG_ARLO) != RESET) && (I2C_CHECK_IT_SOURCE(itsources, I2C_IT_ERR) != RESET)) + { + error |= DAL_I2C_ERROR_ARLO; + + /* Clear ARLO flag */ + __DAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_ARLO); + } + + /* I2C Acknowledge failure error interrupt occurred ------------------------*/ + if ((I2C_CHECK_FLAG(sr1itflags, I2C_FLAG_AF) != RESET) && (I2C_CHECK_IT_SOURCE(itsources, I2C_IT_ERR) != RESET)) + { + tmp1 = CurrentMode; + tmp2 = hi2c->XferCount; + tmp3 = hi2c->State; + tmp4 = hi2c->PreviousState; + if ((tmp1 == DAL_I2C_MODE_SLAVE) && (tmp2 == 0U) && \ + ((tmp3 == DAL_I2C_STATE_BUSY_TX) || (tmp3 == DAL_I2C_STATE_BUSY_TX_LISTEN) || \ + ((tmp3 == DAL_I2C_STATE_LISTEN) && (tmp4 == I2C_STATE_SLAVE_BUSY_TX)))) + { + I2C_Slave_AF(hi2c); + } + else + { + /* Clear AF flag */ + __DAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF); + + error |= DAL_I2C_ERROR_AF; + + /* Do not generate a STOP in case of Slave receive non acknowledge during transfer (mean not at the end of transfer) */ + if ((CurrentMode == DAL_I2C_MODE_MASTER) || (CurrentMode == DAL_I2C_MODE_MEM)) + { + /* Generate Stop */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_STOP); + } + } + } + + /* I2C Over-Run/Under-Run interrupt occurred -------------------------------*/ + if ((I2C_CHECK_FLAG(sr1itflags, I2C_FLAG_OVR) != RESET) && (I2C_CHECK_IT_SOURCE(itsources, I2C_IT_ERR) != RESET)) + { + error |= DAL_I2C_ERROR_OVR; + /* Clear OVR flag */ + __DAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_OVR); + } + + /* Call the Error Callback in case of Error detected -----------------------*/ + if (error != DAL_I2C_ERROR_NONE) + { + hi2c->ErrorCode |= error; + I2C_ITError(hi2c); + } +} + +/** + * @brief Master Tx Transfer completed callback. + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @retval None + */ +__weak void DAL_I2C_MasterTxCpltCallback(I2C_HandleTypeDef *hi2c) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hi2c); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_I2C_MasterTxCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Master Rx Transfer completed callback. + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @retval None + */ +__weak void DAL_I2C_MasterRxCpltCallback(I2C_HandleTypeDef *hi2c) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hi2c); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_I2C_MasterRxCpltCallback could be implemented in the user file + */ +} + +/** @brief Slave Tx Transfer completed callback. + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @retval None + */ +__weak void DAL_I2C_SlaveTxCpltCallback(I2C_HandleTypeDef *hi2c) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hi2c); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_I2C_SlaveTxCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Slave Rx Transfer completed callback. + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @retval None + */ +__weak void DAL_I2C_SlaveRxCpltCallback(I2C_HandleTypeDef *hi2c) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hi2c); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_I2C_SlaveRxCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Slave Address Match callback. + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param TransferDirection Master request Transfer Direction (Write/Read), value of @ref I2C_XferDirection_definition + * @param AddrMatchCode Address Match Code + * @retval None + */ +__weak void DAL_I2C_AddrCallback(I2C_HandleTypeDef *hi2c, uint8_t TransferDirection, uint16_t AddrMatchCode) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hi2c); + UNUSED(TransferDirection); + UNUSED(AddrMatchCode); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_I2C_AddrCallback() could be implemented in the user file + */ +} + +/** + * @brief Listen Complete callback. + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @retval None + */ +__weak void DAL_I2C_ListenCpltCallback(I2C_HandleTypeDef *hi2c) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hi2c); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_I2C_ListenCpltCallback() could be implemented in the user file + */ +} + +/** + * @brief Memory Tx Transfer completed callback. + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @retval None + */ +__weak void DAL_I2C_MemTxCpltCallback(I2C_HandleTypeDef *hi2c) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hi2c); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_I2C_MemTxCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Memory Rx Transfer completed callback. + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @retval None + */ +__weak void DAL_I2C_MemRxCpltCallback(I2C_HandleTypeDef *hi2c) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hi2c); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_I2C_MemRxCpltCallback could be implemented in the user file + */ +} + +/** + * @brief I2C error callback. + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @retval None + */ +__weak void DAL_I2C_ErrorCallback(I2C_HandleTypeDef *hi2c) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hi2c); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_I2C_ErrorCallback could be implemented in the user file + */ +} + +/** + * @brief I2C abort callback. + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @retval None + */ +__weak void DAL_I2C_AbortCpltCallback(I2C_HandleTypeDef *hi2c) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hi2c); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_I2C_AbortCpltCallback could be implemented in the user file + */ +} + +/** + * @} + */ + +/** @defgroup I2C_Exported_Functions_Group3 Peripheral State, Mode and Error functions + * @brief Peripheral State, Mode and Error functions + * +@verbatim + =============================================================================== + ##### Peripheral State, Mode and Error functions ##### + =============================================================================== + [..] + This subsection permit to get in run-time the status of the peripheral + and the data flow. + +@endverbatim + * @{ + */ + +/** + * @brief Return the I2C handle state. + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @retval DAL state + */ +DAL_I2C_StateTypeDef DAL_I2C_GetState(I2C_HandleTypeDef *hi2c) +{ + /* Return I2C handle state */ + return hi2c->State; +} + +/** + * @brief Returns the I2C Master, Slave, Memory or no mode. + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for I2C module + * @retval DAL mode + */ +DAL_I2C_ModeTypeDef DAL_I2C_GetMode(I2C_HandleTypeDef *hi2c) +{ + return hi2c->Mode; +} + +/** + * @brief Return the I2C error code. + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @retval I2C Error Code + */ +uint32_t DAL_I2C_GetError(I2C_HandleTypeDef *hi2c) +{ + return hi2c->ErrorCode; +} + +/** + * @} + */ + +/** + * @} + */ + +/** @addtogroup I2C_Private_Functions + * @{ + */ + +/** + * @brief Handle TXE flag for Master + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for I2C module + * @retval None + */ +static void I2C_MasterTransmit_TXE(I2C_HandleTypeDef *hi2c) +{ + /* Declaration of temporary variables to prevent undefined behavior of volatile usage */ + DAL_I2C_StateTypeDef CurrentState = hi2c->State; + DAL_I2C_ModeTypeDef CurrentMode = hi2c->Mode; + uint32_t CurrentXferOptions = hi2c->XferOptions; + + if ((hi2c->XferSize == 0U) && (CurrentState == DAL_I2C_STATE_BUSY_TX)) + { + /* Call TxCpltCallback() directly if no stop mode is set */ + if ((CurrentXferOptions != I2C_FIRST_AND_LAST_FRAME) && (CurrentXferOptions != I2C_LAST_FRAME) && (CurrentXferOptions != I2C_NO_OPTION_FRAME)) + { + __DAL_I2C_DISABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR); + + hi2c->PreviousState = I2C_STATE_MASTER_BUSY_TX; + hi2c->Mode = DAL_I2C_MODE_NONE; + hi2c->State = DAL_I2C_STATE_READY; + +#if (USE_DAL_I2C_REGISTER_CALLBACKS == 1) + hi2c->MasterTxCpltCallback(hi2c); +#else + DAL_I2C_MasterTxCpltCallback(hi2c); +#endif /* USE_DAL_I2C_REGISTER_CALLBACKS */ + } + else /* Generate Stop condition then Call TxCpltCallback() */ + { + /* Disable EVT, BUF and ERR interrupt */ + __DAL_I2C_DISABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR); + + /* Generate Stop */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_STOP); + + hi2c->PreviousState = I2C_STATE_NONE; + hi2c->State = DAL_I2C_STATE_READY; + + if (hi2c->Mode == DAL_I2C_MODE_MEM) + { + hi2c->Mode = DAL_I2C_MODE_NONE; +#if (USE_DAL_I2C_REGISTER_CALLBACKS == 1) + hi2c->MemTxCpltCallback(hi2c); +#else + DAL_I2C_MemTxCpltCallback(hi2c); +#endif /* USE_DAL_I2C_REGISTER_CALLBACKS */ + } + else + { + hi2c->Mode = DAL_I2C_MODE_NONE; +#if (USE_DAL_I2C_REGISTER_CALLBACKS == 1) + hi2c->MasterTxCpltCallback(hi2c); +#else + DAL_I2C_MasterTxCpltCallback(hi2c); +#endif /* USE_DAL_I2C_REGISTER_CALLBACKS */ + } + } + } + else if ((CurrentState == DAL_I2C_STATE_BUSY_TX) || \ + ((CurrentMode == DAL_I2C_MODE_MEM) && (CurrentState == DAL_I2C_STATE_BUSY_RX))) + { + if (hi2c->XferCount == 0U) + { + /* Disable BUF interrupt */ + __DAL_I2C_DISABLE_IT(hi2c, I2C_IT_BUF); + } + else + { + if (hi2c->Mode == DAL_I2C_MODE_MEM) + { + I2C_MemoryTransmit_TXE_BTF(hi2c); + } + else + { + /* Write data to DATA */ + hi2c->Instance->DATA = *hi2c->pBuffPtr; + + /* Increment Buffer pointer */ + hi2c->pBuffPtr++; + + /* Update counter */ + hi2c->XferCount--; + } + } + } + else + { + /* Do nothing */ + } +} + +/** + * @brief Handle BTF flag for Master transmitter + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for I2C module + * @retval None + */ +static void I2C_MasterTransmit_BTF(I2C_HandleTypeDef *hi2c) +{ + /* Declaration of temporary variables to prevent undefined behavior of volatile usage */ + uint32_t CurrentXferOptions = hi2c->XferOptions; + + if (hi2c->State == DAL_I2C_STATE_BUSY_TX) + { + if (hi2c->XferCount != 0U) + { + /* Write data to DATA */ + hi2c->Instance->DATA = *hi2c->pBuffPtr; + + /* Increment Buffer pointer */ + hi2c->pBuffPtr++; + + /* Update counter */ + hi2c->XferCount--; + } + else + { + /* Call TxCpltCallback() directly if no stop mode is set */ + if ((CurrentXferOptions != I2C_FIRST_AND_LAST_FRAME) && (CurrentXferOptions != I2C_LAST_FRAME) && (CurrentXferOptions != I2C_NO_OPTION_FRAME)) + { + __DAL_I2C_DISABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR); + + hi2c->PreviousState = I2C_STATE_MASTER_BUSY_TX; + hi2c->Mode = DAL_I2C_MODE_NONE; + hi2c->State = DAL_I2C_STATE_READY; + +#if (USE_DAL_I2C_REGISTER_CALLBACKS == 1) + hi2c->MasterTxCpltCallback(hi2c); +#else + DAL_I2C_MasterTxCpltCallback(hi2c); +#endif /* USE_DAL_I2C_REGISTER_CALLBACKS */ + } + else /* Generate Stop condition then Call TxCpltCallback() */ + { + /* Disable EVT, BUF and ERR interrupt */ + __DAL_I2C_DISABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR); + + /* Generate Stop */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_STOP); + + hi2c->PreviousState = I2C_STATE_NONE; + hi2c->State = DAL_I2C_STATE_READY; + if (hi2c->Mode == DAL_I2C_MODE_MEM) + { + hi2c->Mode = DAL_I2C_MODE_NONE; +#if (USE_DAL_I2C_REGISTER_CALLBACKS == 1) + hi2c->MemTxCpltCallback(hi2c); +#else + DAL_I2C_MemTxCpltCallback(hi2c); +#endif /* USE_DAL_I2C_REGISTER_CALLBACKS */ + } + else + { + hi2c->Mode = DAL_I2C_MODE_NONE; + +#if (USE_DAL_I2C_REGISTER_CALLBACKS == 1) + hi2c->MasterTxCpltCallback(hi2c); +#else + DAL_I2C_MasterTxCpltCallback(hi2c); +#endif /* USE_DAL_I2C_REGISTER_CALLBACKS */ + } + } + } + } + else + { + /* Do nothing */ + } +} + +/** + * @brief Handle TXE and BTF flag for Memory transmitter + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for I2C module + * @retval None + */ +static void I2C_MemoryTransmit_TXE_BTF(I2C_HandleTypeDef *hi2c) +{ + /* Declaration of temporary variables to prevent undefined behavior of volatile usage */ + DAL_I2C_StateTypeDef CurrentState = hi2c->State; + + if (hi2c->EventCount == 0U) + { + /* If Memory address size is 8Bit */ + if (hi2c->MemaddSize == I2C_MEMADD_SIZE_8BIT) + { + /* Send Memory Address */ + hi2c->Instance->DATA = I2C_MEM_ADD_LSB(hi2c->Memaddress); + + hi2c->EventCount += 2U; + } + /* If Memory address size is 16Bit */ + else + { + /* Send MSB of Memory Address */ + hi2c->Instance->DATA = I2C_MEM_ADD_MSB(hi2c->Memaddress); + + hi2c->EventCount++; + } + } + else if (hi2c->EventCount == 1U) + { + /* Send LSB of Memory Address */ + hi2c->Instance->DATA = I2C_MEM_ADD_LSB(hi2c->Memaddress); + + hi2c->EventCount++; + } + else if (hi2c->EventCount == 2U) + { + if (CurrentState == DAL_I2C_STATE_BUSY_RX) + { + /* Generate Restart */ + hi2c->Instance->CTRL1 |= I2C_CTRL1_START; + + hi2c->EventCount++; + } + else if ((hi2c->XferCount > 0U) && (CurrentState == DAL_I2C_STATE_BUSY_TX)) + { + /* Write data to DATA */ + hi2c->Instance->DATA = *hi2c->pBuffPtr; + + /* Increment Buffer pointer */ + hi2c->pBuffPtr++; + + /* Update counter */ + hi2c->XferCount--; + } + else if ((hi2c->XferCount == 0U) && (CurrentState == DAL_I2C_STATE_BUSY_TX)) + { + /* Generate Stop condition then Call TxCpltCallback() */ + /* Disable EVT, BUF and ERR interrupt */ + __DAL_I2C_DISABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR); + + /* Generate Stop */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_STOP); + + hi2c->PreviousState = I2C_STATE_NONE; + hi2c->State = DAL_I2C_STATE_READY; + hi2c->Mode = DAL_I2C_MODE_NONE; +#if (USE_DAL_I2C_REGISTER_CALLBACKS == 1) + hi2c->MemTxCpltCallback(hi2c); +#else + DAL_I2C_MemTxCpltCallback(hi2c); +#endif /* USE_DAL_I2C_REGISTER_CALLBACKS */ + } + else + { + /* Do nothing */ + } + } + else + { + /* Do nothing */ + } +} + +/** + * @brief Handle RXNE flag for Master + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for I2C module + * @retval None + */ +static void I2C_MasterReceive_RXNE(I2C_HandleTypeDef *hi2c) +{ + if (hi2c->State == DAL_I2C_STATE_BUSY_RX) + { + uint32_t tmp; + + tmp = hi2c->XferCount; + if (tmp > 3U) + { + /* Read data from DATA */ + *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->DATA; + + /* Increment Buffer pointer */ + hi2c->pBuffPtr++; + + /* Update counter */ + hi2c->XferCount--; + + if (hi2c->XferCount == (uint16_t)3) + { + /* Disable BUF interrupt, this help to treat correctly the last 4 bytes + on BTF subroutine */ + /* Disable BUF interrupt */ + __DAL_I2C_DISABLE_IT(hi2c, I2C_IT_BUF); + } + } + else if ((hi2c->XferOptions != I2C_FIRST_AND_NEXT_FRAME) && ((tmp == 1U) || (tmp == 0U))) + { + if (I2C_WaitOnSTOPRequestThroughIT(hi2c) == DAL_OK) + { + /* Disable Acknowledge */ + CLEAR_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKEN); + + /* Disable EVT, BUF and ERR interrupt */ + __DAL_I2C_DISABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR); + + /* Read data from DATA */ + *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->DATA; + + /* Increment Buffer pointer */ + hi2c->pBuffPtr++; + + /* Update counter */ + hi2c->XferCount--; + + hi2c->State = DAL_I2C_STATE_READY; + + if (hi2c->Mode == DAL_I2C_MODE_MEM) + { + hi2c->Mode = DAL_I2C_MODE_NONE; + hi2c->PreviousState = I2C_STATE_NONE; + +#if (USE_DAL_I2C_REGISTER_CALLBACKS == 1) + hi2c->MemRxCpltCallback(hi2c); +#else + DAL_I2C_MemRxCpltCallback(hi2c); +#endif /* USE_DAL_I2C_REGISTER_CALLBACKS */ + } + else + { + hi2c->Mode = DAL_I2C_MODE_NONE; + hi2c->PreviousState = I2C_STATE_MASTER_BUSY_RX; + +#if (USE_DAL_I2C_REGISTER_CALLBACKS == 1) + hi2c->MasterRxCpltCallback(hi2c); +#else + DAL_I2C_MasterRxCpltCallback(hi2c); +#endif /* USE_DAL_I2C_REGISTER_CALLBACKS */ + } + } + else + { + /* Disable EVT, BUF and ERR interrupt */ + __DAL_I2C_DISABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR); + + /* Read data from DATA */ + *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->DATA; + + /* Increment Buffer pointer */ + hi2c->pBuffPtr++; + + /* Update counter */ + hi2c->XferCount--; + + hi2c->State = DAL_I2C_STATE_READY; + hi2c->Mode = DAL_I2C_MODE_NONE; + + /* Call user error callback */ +#if (USE_DAL_I2C_REGISTER_CALLBACKS == 1) + hi2c->ErrorCallback(hi2c); +#else + DAL_I2C_ErrorCallback(hi2c); +#endif /* USE_DAL_I2C_REGISTER_CALLBACKS */ + } + } + else + { + /* Disable BUF interrupt, this help to treat correctly the last 2 bytes + on BTF subroutine if there is a reception delay between N-1 and N byte */ + __DAL_I2C_DISABLE_IT(hi2c, I2C_IT_BUF); + } + } +} + +/** + * @brief Handle BTF flag for Master receiver + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for I2C module + * @retval None + */ +static void I2C_MasterReceive_BTF(I2C_HandleTypeDef *hi2c) +{ + /* Declaration of temporary variables to prevent undefined behavior of volatile usage */ + uint32_t CurrentXferOptions = hi2c->XferOptions; + + if (hi2c->XferCount == 4U) + { + /* Disable BUF interrupt, this help to treat correctly the last 2 bytes + on BTF subroutine if there is a reception delay between N-1 and N byte */ + __DAL_I2C_DISABLE_IT(hi2c, I2C_IT_BUF); + + /* Read data from DATA */ + *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->DATA; + + /* Increment Buffer pointer */ + hi2c->pBuffPtr++; + + /* Update counter */ + hi2c->XferCount--; + } + else if (hi2c->XferCount == 3U) + { + /* Disable BUF interrupt, this help to treat correctly the last 2 bytes + on BTF subroutine if there is a reception delay between N-1 and N byte */ + __DAL_I2C_DISABLE_IT(hi2c, I2C_IT_BUF); + + if ((CurrentXferOptions != I2C_NEXT_FRAME) && (CurrentXferOptions != I2C_FIRST_AND_NEXT_FRAME)) + { + /* Disable Acknowledge */ + CLEAR_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKEN); + } + + /* Read data from DATA */ + *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->DATA; + + /* Increment Buffer pointer */ + hi2c->pBuffPtr++; + + /* Update counter */ + hi2c->XferCount--; + } + else if (hi2c->XferCount == 2U) + { + /* Prepare next transfer or stop current transfer */ + if ((CurrentXferOptions == I2C_FIRST_FRAME) || (CurrentXferOptions == I2C_LAST_FRAME_NO_STOP)) + { + /* Disable Acknowledge */ + CLEAR_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKEN); + } + else if ((CurrentXferOptions == I2C_NEXT_FRAME) || (CurrentXferOptions == I2C_FIRST_AND_NEXT_FRAME)) + { + /* Enable Acknowledge */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKEN); + } + else if (CurrentXferOptions != I2C_LAST_FRAME_NO_STOP) + { + /* Generate Stop */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_STOP); + } + else + { + /* Do nothing */ + } + + /* Read data from DATA */ + *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->DATA; + + /* Increment Buffer pointer */ + hi2c->pBuffPtr++; + + /* Update counter */ + hi2c->XferCount--; + + /* Read data from DATA */ + *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->DATA; + + /* Increment Buffer pointer */ + hi2c->pBuffPtr++; + + /* Update counter */ + hi2c->XferCount--; + + /* Disable EVT and ERR interrupt */ + __DAL_I2C_DISABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_ERR); + + hi2c->State = DAL_I2C_STATE_READY; + if (hi2c->Mode == DAL_I2C_MODE_MEM) + { + hi2c->Mode = DAL_I2C_MODE_NONE; + hi2c->PreviousState = I2C_STATE_NONE; +#if (USE_DAL_I2C_REGISTER_CALLBACKS == 1) + hi2c->MemRxCpltCallback(hi2c); +#else + DAL_I2C_MemRxCpltCallback(hi2c); +#endif /* USE_DAL_I2C_REGISTER_CALLBACKS */ + } + else + { + hi2c->Mode = DAL_I2C_MODE_NONE; + hi2c->PreviousState = I2C_STATE_MASTER_BUSY_RX; +#if (USE_DAL_I2C_REGISTER_CALLBACKS == 1) + hi2c->MasterRxCpltCallback(hi2c); +#else + DAL_I2C_MasterRxCpltCallback(hi2c); +#endif /* USE_DAL_I2C_REGISTER_CALLBACKS */ + } + } + else + { + /* Read data from DATA */ + *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->DATA; + + /* Increment Buffer pointer */ + hi2c->pBuffPtr++; + + /* Update counter */ + hi2c->XferCount--; + } +} + +/** + * @brief Handle SB flag for Master + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for I2C module + * @retval None + */ +static void I2C_Master_SB(I2C_HandleTypeDef *hi2c) +{ + if (hi2c->Mode == DAL_I2C_MODE_MEM) + { + if (hi2c->EventCount == 0U) + { + /* Send slave address */ + hi2c->Instance->DATA = I2C_7BIT_ADD_WRITE(hi2c->Devaddress); + } + else + { + hi2c->Instance->DATA = I2C_7BIT_ADD_READ(hi2c->Devaddress); + } + } + else + { + if (hi2c->Init.AddressingMode == I2C_ADDRESSINGMODE_7BIT) + { + /* Send slave 7 Bits address */ + if (hi2c->State == DAL_I2C_STATE_BUSY_TX) + { + hi2c->Instance->DATA = I2C_7BIT_ADD_WRITE(hi2c->Devaddress); + } + else + { + hi2c->Instance->DATA = I2C_7BIT_ADD_READ(hi2c->Devaddress); + } + + if (((hi2c->hdmatx != NULL) && (hi2c->hdmatx->XferCpltCallback != NULL)) + || ((hi2c->hdmarx != NULL) && (hi2c->hdmarx->XferCpltCallback != NULL))) + { + /* Enable DMA Request */ + SET_BIT(hi2c->Instance->CTRL2, I2C_CTRL2_DMAEN); + } + } + else + { + if (hi2c->EventCount == 0U) + { + /* Send header of slave address */ + hi2c->Instance->DATA = I2C_10BIT_HEADER_WRITE(hi2c->Devaddress); + } + else if (hi2c->EventCount == 1U) + { + /* Send header of slave address */ + hi2c->Instance->DATA = I2C_10BIT_HEADER_READ(hi2c->Devaddress); + } + else + { + /* Do nothing */ + } + } + } +} + +/** + * @brief Handle ADD10 flag for Master + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for I2C module + * @retval None + */ +static void I2C_Master_ADD10(I2C_HandleTypeDef *hi2c) +{ + /* Send slave address */ + hi2c->Instance->DATA = I2C_10BIT_ADDRESS(hi2c->Devaddress); + + if (((hi2c->hdmatx != NULL) && (hi2c->hdmatx->XferCpltCallback != NULL)) + || ((hi2c->hdmarx != NULL) && (hi2c->hdmarx->XferCpltCallback != NULL))) + { + /* Enable DMA Request */ + SET_BIT(hi2c->Instance->CTRL2, I2C_CTRL2_DMAEN); + } +} + +/** + * @brief Handle ADDR flag for Master + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for I2C module + * @retval None + */ +static void I2C_Master_ADDR(I2C_HandleTypeDef *hi2c) +{ + /* Declaration of temporary variable to prevent undefined behavior of volatile usage */ + DAL_I2C_ModeTypeDef CurrentMode = hi2c->Mode; + uint32_t CurrentXferOptions = hi2c->XferOptions; + uint32_t Prev_State = hi2c->PreviousState; + + if (hi2c->State == DAL_I2C_STATE_BUSY_RX) + { + if ((hi2c->EventCount == 0U) && (CurrentMode == DAL_I2C_MODE_MEM)) + { + /* Clear ADDR flag */ + __DAL_I2C_CLEAR_ADDRFLAG(hi2c); + } + else if ((hi2c->EventCount == 0U) && (hi2c->Init.AddressingMode == I2C_ADDRESSINGMODE_10BIT)) + { + /* Clear ADDR flag */ + __DAL_I2C_CLEAR_ADDRFLAG(hi2c); + + /* Generate Restart */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_START); + + hi2c->EventCount++; + } + else + { + if (hi2c->XferCount == 0U) + { + /* Clear ADDR flag */ + __DAL_I2C_CLEAR_ADDRFLAG(hi2c); + + /* Generate Stop */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_STOP); + } + else if (hi2c->XferCount == 1U) + { + if (CurrentXferOptions == I2C_NO_OPTION_FRAME) + { + /* Disable Acknowledge */ + CLEAR_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKEN); + + if ((hi2c->Instance->CTRL2 & I2C_CTRL2_DMAEN) == I2C_CTRL2_DMAEN) + { + /* Disable Acknowledge */ + CLEAR_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKEN); + + /* Clear ADDR flag */ + __DAL_I2C_CLEAR_ADDRFLAG(hi2c); + } + else + { + /* Clear ADDR flag */ + __DAL_I2C_CLEAR_ADDRFLAG(hi2c); + + /* Generate Stop */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_STOP); + } + } + /* Prepare next transfer or stop current transfer */ + else if ((CurrentXferOptions != I2C_FIRST_AND_LAST_FRAME) && (CurrentXferOptions != I2C_LAST_FRAME) \ + && ((Prev_State != I2C_STATE_MASTER_BUSY_RX) || (CurrentXferOptions == I2C_FIRST_FRAME))) + { + if ((CurrentXferOptions != I2C_NEXT_FRAME) && (CurrentXferOptions != I2C_FIRST_AND_NEXT_FRAME) && (CurrentXferOptions != I2C_LAST_FRAME_NO_STOP)) + { + /* Disable Acknowledge */ + CLEAR_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKEN); + } + else + { + /* Enable Acknowledge */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKEN); + } + + /* Clear ADDR flag */ + __DAL_I2C_CLEAR_ADDRFLAG(hi2c); + } + else + { + /* Disable Acknowledge */ + CLEAR_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKEN); + + /* Clear ADDR flag */ + __DAL_I2C_CLEAR_ADDRFLAG(hi2c); + + /* Generate Stop */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_STOP); + } + } + else if (hi2c->XferCount == 2U) + { + if ((CurrentXferOptions != I2C_NEXT_FRAME) && (CurrentXferOptions != I2C_FIRST_AND_NEXT_FRAME) && (CurrentXferOptions != I2C_LAST_FRAME_NO_STOP)) + { + /* Disable Acknowledge */ + CLEAR_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKEN); + + /* Enable Pos */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKPOS); + } + else + { + /* Enable Acknowledge */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKEN); + } + + if (((hi2c->Instance->CTRL2 & I2C_CTRL2_DMAEN) == I2C_CTRL2_DMAEN) && ((CurrentXferOptions == I2C_NO_OPTION_FRAME) || (CurrentXferOptions == I2C_FIRST_FRAME) || (CurrentXferOptions == I2C_FIRST_AND_LAST_FRAME) || (CurrentXferOptions == I2C_LAST_FRAME_NO_STOP) || (CurrentXferOptions == I2C_LAST_FRAME))) + { + /* Enable Last DMA bit */ + SET_BIT(hi2c->Instance->CTRL2, I2C_CTRL2_LTCFG); + } + + /* Clear ADDR flag */ + __DAL_I2C_CLEAR_ADDRFLAG(hi2c); + } + else + { + /* Enable Acknowledge */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKEN); + + if (((hi2c->Instance->CTRL2 & I2C_CTRL2_DMAEN) == I2C_CTRL2_DMAEN) && ((CurrentXferOptions == I2C_NO_OPTION_FRAME) || (CurrentXferOptions == I2C_FIRST_FRAME) || (CurrentXferOptions == I2C_FIRST_AND_LAST_FRAME) || (CurrentXferOptions == I2C_LAST_FRAME_NO_STOP) || (CurrentXferOptions == I2C_LAST_FRAME))) + { + /* Enable Last DMA bit */ + SET_BIT(hi2c->Instance->CTRL2, I2C_CTRL2_LTCFG); + } + + /* Clear ADDR flag */ + __DAL_I2C_CLEAR_ADDRFLAG(hi2c); + } + + /* Reset Event counter */ + hi2c->EventCount = 0U; + } + } + else + { + /* Clear ADDR flag */ + __DAL_I2C_CLEAR_ADDRFLAG(hi2c); + } +} + +/** + * @brief Handle TXE flag for Slave + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for I2C module + * @retval None + */ +static void I2C_SlaveTransmit_TXE(I2C_HandleTypeDef *hi2c) +{ + /* Declaration of temporary variables to prevent undefined behavior of volatile usage */ + DAL_I2C_StateTypeDef CurrentState = hi2c->State; + + if (hi2c->XferCount != 0U) + { + /* Write data to DATA */ + hi2c->Instance->DATA = *hi2c->pBuffPtr; + + /* Increment Buffer pointer */ + hi2c->pBuffPtr++; + + /* Update counter */ + hi2c->XferCount--; + + if ((hi2c->XferCount == 0U) && (CurrentState == DAL_I2C_STATE_BUSY_TX_LISTEN)) + { + /* Last Byte is received, disable Interrupt */ + __DAL_I2C_DISABLE_IT(hi2c, I2C_IT_BUF); + + /* Set state at DAL_I2C_STATE_LISTEN */ + hi2c->PreviousState = I2C_STATE_SLAVE_BUSY_TX; + hi2c->State = DAL_I2C_STATE_LISTEN; + + /* Call the corresponding callback to inform upper layer of End of Transfer */ +#if (USE_DAL_I2C_REGISTER_CALLBACKS == 1) + hi2c->SlaveTxCpltCallback(hi2c); +#else + DAL_I2C_SlaveTxCpltCallback(hi2c); +#endif /* USE_DAL_I2C_REGISTER_CALLBACKS */ + } + } +} + +/** + * @brief Handle BTF flag for Slave transmitter + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for I2C module + * @retval None + */ +static void I2C_SlaveTransmit_BTF(I2C_HandleTypeDef *hi2c) +{ + if (hi2c->XferCount != 0U) + { + /* Write data to DATA */ + hi2c->Instance->DATA = *hi2c->pBuffPtr; + + /* Increment Buffer pointer */ + hi2c->pBuffPtr++; + + /* Update counter */ + hi2c->XferCount--; + } +} + +/** + * @brief Handle RXNE flag for Slave + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for I2C module + * @retval None + */ +static void I2C_SlaveReceive_RXNE(I2C_HandleTypeDef *hi2c) +{ + /* Declaration of temporary variables to prevent undefined behavior of volatile usage */ + DAL_I2C_StateTypeDef CurrentState = hi2c->State; + + if (hi2c->XferCount != 0U) + { + /* Read data from DATA */ + *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->DATA; + + /* Increment Buffer pointer */ + hi2c->pBuffPtr++; + + /* Update counter */ + hi2c->XferCount--; + + if ((hi2c->XferCount == 0U) && (CurrentState == DAL_I2C_STATE_BUSY_RX_LISTEN)) + { + /* Last Byte is received, disable Interrupt */ + __DAL_I2C_DISABLE_IT(hi2c, I2C_IT_BUF); + + /* Set state at DAL_I2C_STATE_LISTEN */ + hi2c->PreviousState = I2C_STATE_SLAVE_BUSY_RX; + hi2c->State = DAL_I2C_STATE_LISTEN; + + /* Call the corresponding callback to inform upper layer of End of Transfer */ +#if (USE_DAL_I2C_REGISTER_CALLBACKS == 1) + hi2c->SlaveRxCpltCallback(hi2c); +#else + DAL_I2C_SlaveRxCpltCallback(hi2c); +#endif /* USE_DAL_I2C_REGISTER_CALLBACKS */ + } + } +} + +/** + * @brief Handle BTF flag for Slave receiver + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for I2C module + * @retval None + */ +static void I2C_SlaveReceive_BTF(I2C_HandleTypeDef *hi2c) +{ + if (hi2c->XferCount != 0U) + { + /* Read data from DATA */ + *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->DATA; + + /* Increment Buffer pointer */ + hi2c->pBuffPtr++; + + /* Update counter */ + hi2c->XferCount--; + } +} + +/** + * @brief Handle ADD flag for Slave + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for I2C module + * @param IT2Flags Interrupt2 flags to handle. + * @retval None + */ +static void I2C_Slave_ADDR(I2C_HandleTypeDef *hi2c, uint32_t IT2Flags) +{ + uint8_t TransferDirection = I2C_DIRECTION_RECEIVE; + uint16_t SlaveAddrCode; + + if (((uint32_t)hi2c->State & (uint32_t)DAL_I2C_STATE_LISTEN) == (uint32_t)DAL_I2C_STATE_LISTEN) + { + /* Disable BUF interrupt, BUF enabling is manage through slave specific interface */ + __DAL_I2C_DISABLE_IT(hi2c, (I2C_IT_BUF)); + + /* Transfer Direction requested by Master */ + if (I2C_CHECK_FLAG(IT2Flags, I2C_FLAG_TRA) == RESET) + { + TransferDirection = I2C_DIRECTION_TRANSMIT; + } + + if (I2C_CHECK_FLAG(IT2Flags, I2C_FLAG_DUALF) == RESET) + { + SlaveAddrCode = (uint16_t)hi2c->Init.OwnAddress1; + } + else + { + SlaveAddrCode = (uint16_t)hi2c->Init.OwnAddress2; + } + + /* Process Unlocked */ + __DAL_UNLOCK(hi2c); + + /* Call Slave Addr callback */ +#if (USE_DAL_I2C_REGISTER_CALLBACKS == 1) + hi2c->AddrCallback(hi2c, TransferDirection, SlaveAddrCode); +#else + DAL_I2C_AddrCallback(hi2c, TransferDirection, SlaveAddrCode); +#endif /* USE_DAL_I2C_REGISTER_CALLBACKS */ + } + else + { + /* Clear ADDR flag */ + __DAL_I2C_CLEAR_ADDRFLAG(hi2c); + + /* Process Unlocked */ + __DAL_UNLOCK(hi2c); + } +} + +/** + * @brief Handle STOPF flag for Slave + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for I2C module + * @retval None + */ +static void I2C_Slave_STOPF(I2C_HandleTypeDef *hi2c) +{ + /* Declaration of temporary variable to prevent undefined behavior of volatile usage */ + DAL_I2C_StateTypeDef CurrentState = hi2c->State; + + /* Disable EVT, BUF and ERR interrupt */ + __DAL_I2C_DISABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR); + + /* Clear STOPF flag */ + __DAL_I2C_CLEAR_STOPFLAG(hi2c); + + /* Disable Acknowledge */ + CLEAR_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKEN); + + /* If a DMA is ongoing, Update handle size context */ + if ((hi2c->Instance->CTRL2 & I2C_CTRL2_DMAEN) == I2C_CTRL2_DMAEN) + { + if ((CurrentState == DAL_I2C_STATE_BUSY_RX) || (CurrentState == DAL_I2C_STATE_BUSY_RX_LISTEN)) + { + hi2c->XferCount = (uint16_t)(__DAL_DMA_GET_COUNTER(hi2c->hdmarx)); + + if (hi2c->XferCount != 0U) + { + /* Set ErrorCode corresponding to a Non-Acknowledge */ + hi2c->ErrorCode |= DAL_I2C_ERROR_AF; + } + + /* Disable, stop the current DMA */ + CLEAR_BIT(hi2c->Instance->CTRL2, I2C_CTRL2_DMAEN); + + /* Abort DMA Xfer if any */ + if (DAL_DMA_GetState(hi2c->hdmarx) != DAL_DMA_STATE_READY) + { + /* Set the I2C DMA Abort callback : + will lead to call DAL_I2C_ErrorCallback() at end of DMA abort procedure */ + hi2c->hdmarx->XferAbortCallback = I2C_DMAAbort; + + /* Abort DMA RX */ + if (DAL_DMA_Abort_IT(hi2c->hdmarx) != DAL_OK) + { + /* Call Directly XferAbortCallback function in case of error */ + hi2c->hdmarx->XferAbortCallback(hi2c->hdmarx); + } + } + } + else + { + hi2c->XferCount = (uint16_t)(__DAL_DMA_GET_COUNTER(hi2c->hdmatx)); + + if (hi2c->XferCount != 0U) + { + /* Set ErrorCode corresponding to a Non-Acknowledge */ + hi2c->ErrorCode |= DAL_I2C_ERROR_AF; + } + + /* Disable, stop the current DMA */ + CLEAR_BIT(hi2c->Instance->CTRL2, I2C_CTRL2_DMAEN); + + /* Abort DMA Xfer if any */ + if (DAL_DMA_GetState(hi2c->hdmatx) != DAL_DMA_STATE_READY) + { + /* Set the I2C DMA Abort callback : + will lead to call DAL_I2C_ErrorCallback() at end of DMA abort procedure */ + hi2c->hdmatx->XferAbortCallback = I2C_DMAAbort; + + /* Abort DMA TX */ + if (DAL_DMA_Abort_IT(hi2c->hdmatx) != DAL_OK) + { + /* Call Directly XferAbortCallback function in case of error */ + hi2c->hdmatx->XferAbortCallback(hi2c->hdmatx); + } + } + } + } + + /* All data are not transferred, so set error code accordingly */ + if (hi2c->XferCount != 0U) + { + /* Store Last receive data if any */ + if (__DAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BTF) == SET) + { + /* Read data from DATA */ + *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->DATA; + + /* Increment Buffer pointer */ + hi2c->pBuffPtr++; + + /* Update counter */ + hi2c->XferCount--; + } + + /* Store Last receive data if any */ + if (__DAL_I2C_GET_FLAG(hi2c, I2C_FLAG_RXNE) == SET) + { + /* Read data from DATA */ + *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->DATA; + + /* Increment Buffer pointer */ + hi2c->pBuffPtr++; + + /* Update counter */ + hi2c->XferCount--; + } + + if (hi2c->XferCount != 0U) + { + /* Set ErrorCode corresponding to a Non-Acknowledge */ + hi2c->ErrorCode |= DAL_I2C_ERROR_AF; + } + } + + if (hi2c->ErrorCode != DAL_I2C_ERROR_NONE) + { + /* Call the corresponding callback to inform upper layer of End of Transfer */ + I2C_ITError(hi2c); + } + else + { + if (CurrentState == DAL_I2C_STATE_BUSY_RX_LISTEN) + { + /* Set state at DAL_I2C_STATE_LISTEN */ + hi2c->PreviousState = I2C_STATE_NONE; + hi2c->State = DAL_I2C_STATE_LISTEN; + + /* Call the corresponding callback to inform upper layer of End of Transfer */ +#if (USE_DAL_I2C_REGISTER_CALLBACKS == 1) + hi2c->SlaveRxCpltCallback(hi2c); +#else + DAL_I2C_SlaveRxCpltCallback(hi2c); +#endif /* USE_DAL_I2C_REGISTER_CALLBACKS */ + } + + if (hi2c->State == DAL_I2C_STATE_LISTEN) + { + hi2c->XferOptions = I2C_NO_OPTION_FRAME; + hi2c->PreviousState = I2C_STATE_NONE; + hi2c->State = DAL_I2C_STATE_READY; + hi2c->Mode = DAL_I2C_MODE_NONE; + + /* Call the Listen Complete callback, to inform upper layer of the end of Listen usecase */ +#if (USE_DAL_I2C_REGISTER_CALLBACKS == 1) + hi2c->ListenCpltCallback(hi2c); +#else + DAL_I2C_ListenCpltCallback(hi2c); +#endif /* USE_DAL_I2C_REGISTER_CALLBACKS */ + } + else + { + if ((hi2c->PreviousState == I2C_STATE_SLAVE_BUSY_RX) || (CurrentState == DAL_I2C_STATE_BUSY_RX)) + { + hi2c->PreviousState = I2C_STATE_NONE; + hi2c->State = DAL_I2C_STATE_READY; + hi2c->Mode = DAL_I2C_MODE_NONE; + +#if (USE_DAL_I2C_REGISTER_CALLBACKS == 1) + hi2c->SlaveRxCpltCallback(hi2c); +#else + DAL_I2C_SlaveRxCpltCallback(hi2c); +#endif /* USE_DAL_I2C_REGISTER_CALLBACKS */ + } + } + } +} + +/** + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for I2C module + * @retval None + */ +static void I2C_Slave_AF(I2C_HandleTypeDef *hi2c) +{ + /* Declaration of temporary variables to prevent undefined behavior of volatile usage */ + DAL_I2C_StateTypeDef CurrentState = hi2c->State; + uint32_t CurrentXferOptions = hi2c->XferOptions; + + if (((CurrentXferOptions == I2C_FIRST_AND_LAST_FRAME) || (CurrentXferOptions == I2C_LAST_FRAME)) && \ + (CurrentState == DAL_I2C_STATE_LISTEN)) + { + hi2c->XferOptions = I2C_NO_OPTION_FRAME; + + /* Disable EVT, BUF and ERR interrupt */ + __DAL_I2C_DISABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR); + + /* Clear AF flag */ + __DAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF); + + /* Disable Acknowledge */ + CLEAR_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKEN); + + hi2c->PreviousState = I2C_STATE_NONE; + hi2c->State = DAL_I2C_STATE_READY; + hi2c->Mode = DAL_I2C_MODE_NONE; + + /* Call the Listen Complete callback, to inform upper layer of the end of Listen usecase */ +#if (USE_DAL_I2C_REGISTER_CALLBACKS == 1) + hi2c->ListenCpltCallback(hi2c); +#else + DAL_I2C_ListenCpltCallback(hi2c); +#endif /* USE_DAL_I2C_REGISTER_CALLBACKS */ + } + else if (CurrentState == DAL_I2C_STATE_BUSY_TX) + { + hi2c->XferOptions = I2C_NO_OPTION_FRAME; + hi2c->PreviousState = I2C_STATE_SLAVE_BUSY_TX; + hi2c->State = DAL_I2C_STATE_READY; + hi2c->Mode = DAL_I2C_MODE_NONE; + + /* Disable EVT, BUF and ERR interrupt */ + __DAL_I2C_DISABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR); + + /* Clear AF flag */ + __DAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF); + + /* Disable Acknowledge */ + CLEAR_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKEN); + +#if (USE_DAL_I2C_REGISTER_CALLBACKS == 1) + hi2c->SlaveTxCpltCallback(hi2c); +#else + DAL_I2C_SlaveTxCpltCallback(hi2c); +#endif /* USE_DAL_I2C_REGISTER_CALLBACKS */ + } + else + { + /* Clear AF flag only */ + /* State Listen, but XferOptions == FIRST or NEXT */ + __DAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF); + } +} + +/** + * @brief I2C interrupts error process + * @param hi2c I2C handle. + * @retval None + */ +static void I2C_ITError(I2C_HandleTypeDef *hi2c) +{ + /* Declaration of temporary variable to prevent undefined behavior of volatile usage */ + DAL_I2C_StateTypeDef CurrentState = hi2c->State; + DAL_I2C_ModeTypeDef CurrentMode = hi2c->Mode; + uint32_t CurrentError; + + if (((CurrentMode == DAL_I2C_MODE_MASTER) || (CurrentMode == DAL_I2C_MODE_MEM)) && (CurrentState == DAL_I2C_STATE_BUSY_RX)) + { + /* Disable Pos bit in I2C CR1 when error occurred in Master/Mem Receive IT Process */ + hi2c->Instance->CTRL1 &= ~I2C_CTRL1_ACKPOS; + } + + if (((uint32_t)CurrentState & (uint32_t)DAL_I2C_STATE_LISTEN) == (uint32_t)DAL_I2C_STATE_LISTEN) + { + /* keep DAL_I2C_STATE_LISTEN */ + hi2c->PreviousState = I2C_STATE_NONE; + hi2c->State = DAL_I2C_STATE_LISTEN; + } + else + { + /* If state is an abort treatment on going, don't change state */ + /* This change will be do later */ + if ((READ_BIT(hi2c->Instance->CTRL2, I2C_CTRL2_DMAEN) != I2C_CTRL2_DMAEN) && (CurrentState != DAL_I2C_STATE_ABORT)) + { + hi2c->State = DAL_I2C_STATE_READY; + hi2c->Mode = DAL_I2C_MODE_NONE; + } + hi2c->PreviousState = I2C_STATE_NONE; + } + + /* Abort DMA transfer */ + if (READ_BIT(hi2c->Instance->CTRL2, I2C_CTRL2_DMAEN) == I2C_CTRL2_DMAEN) + { + hi2c->Instance->CTRL2 &= ~I2C_CTRL2_DMAEN; + + if (hi2c->hdmatx->State != DAL_DMA_STATE_READY) + { + /* Set the DMA Abort callback : + will lead to call DAL_I2C_ErrorCallback() at end of DMA abort procedure */ + hi2c->hdmatx->XferAbortCallback = I2C_DMAAbort; + + if (DAL_DMA_Abort_IT(hi2c->hdmatx) != DAL_OK) + { + /* Disable I2C peripheral to prevent dummy data in buffer */ + __DAL_I2C_DISABLE(hi2c); + + hi2c->State = DAL_I2C_STATE_READY; + + /* Call Directly XferAbortCallback function in case of error */ + hi2c->hdmatx->XferAbortCallback(hi2c->hdmatx); + } + } + else + { + /* Set the DMA Abort callback : + will lead to call DAL_I2C_ErrorCallback() at end of DMA abort procedure */ + hi2c->hdmarx->XferAbortCallback = I2C_DMAAbort; + + if (DAL_DMA_Abort_IT(hi2c->hdmarx) != DAL_OK) + { + /* Store Last receive data if any */ + if (__DAL_I2C_GET_FLAG(hi2c, I2C_FLAG_RXNE) == SET) + { + /* Read data from DATA */ + *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->DATA; + + /* Increment Buffer pointer */ + hi2c->pBuffPtr++; + } + + /* Disable I2C peripheral to prevent dummy data in buffer */ + __DAL_I2C_DISABLE(hi2c); + + hi2c->State = DAL_I2C_STATE_READY; + + /* Call Directly hi2c->hdmarx->XferAbortCallback function in case of error */ + hi2c->hdmarx->XferAbortCallback(hi2c->hdmarx); + } + } + } + else if (hi2c->State == DAL_I2C_STATE_ABORT) + { + hi2c->State = DAL_I2C_STATE_READY; + hi2c->ErrorCode = DAL_I2C_ERROR_NONE; + + /* Store Last receive data if any */ + if (__DAL_I2C_GET_FLAG(hi2c, I2C_FLAG_RXNE) == SET) + { + /* Read data from DATA */ + *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->DATA; + + /* Increment Buffer pointer */ + hi2c->pBuffPtr++; + } + + /* Disable I2C peripheral to prevent dummy data in buffer */ + __DAL_I2C_DISABLE(hi2c); + + /* Call the corresponding callback to inform upper layer of End of Transfer */ +#if (USE_DAL_I2C_REGISTER_CALLBACKS == 1) + hi2c->AbortCpltCallback(hi2c); +#else + DAL_I2C_AbortCpltCallback(hi2c); +#endif /* USE_DAL_I2C_REGISTER_CALLBACKS */ + } + else + { + /* Store Last receive data if any */ + if (__DAL_I2C_GET_FLAG(hi2c, I2C_FLAG_RXNE) == SET) + { + /* Read data from DATA */ + *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->DATA; + + /* Increment Buffer pointer */ + hi2c->pBuffPtr++; + } + + /* Call user error callback */ +#if (USE_DAL_I2C_REGISTER_CALLBACKS == 1) + hi2c->ErrorCallback(hi2c); +#else + DAL_I2C_ErrorCallback(hi2c); +#endif /* USE_DAL_I2C_REGISTER_CALLBACKS */ + } + + /* STOP Flag is not set after a NACK reception, BusError, ArbitrationLost, OverRun */ + CurrentError = hi2c->ErrorCode; + + if (((CurrentError & DAL_I2C_ERROR_BERR) == DAL_I2C_ERROR_BERR) || \ + ((CurrentError & DAL_I2C_ERROR_ARLO) == DAL_I2C_ERROR_ARLO) || \ + ((CurrentError & DAL_I2C_ERROR_AF) == DAL_I2C_ERROR_AF) || \ + ((CurrentError & DAL_I2C_ERROR_OVR) == DAL_I2C_ERROR_OVR)) + { + /* Disable EVT, BUF and ERR interrupt */ + __DAL_I2C_DISABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR); + } + + /* So may inform upper layer that listen phase is stopped */ + /* during NACK error treatment */ + CurrentState = hi2c->State; + if (((hi2c->ErrorCode & DAL_I2C_ERROR_AF) == DAL_I2C_ERROR_AF) && (CurrentState == DAL_I2C_STATE_LISTEN)) + { + hi2c->XferOptions = I2C_NO_OPTION_FRAME; + hi2c->PreviousState = I2C_STATE_NONE; + hi2c->State = DAL_I2C_STATE_READY; + hi2c->Mode = DAL_I2C_MODE_NONE; + + /* Call the Listen Complete callback, to inform upper layer of the end of Listen usecase */ +#if (USE_DAL_I2C_REGISTER_CALLBACKS == 1) + hi2c->ListenCpltCallback(hi2c); +#else + DAL_I2C_ListenCpltCallback(hi2c); +#endif /* USE_DAL_I2C_REGISTER_CALLBACKS */ + } +} + +/** + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for I2C module + * @param DevAddress Target device address: The device 7 bits address value + * in datasheet must be shifted to the left before calling the interface + * @param Timeout Timeout duration + * @param Tickstart Tick start value + * @retval DAL status + */ +static DAL_StatusTypeDef I2C_MasterRequestWrite(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint32_t Timeout, uint32_t Tickstart) +{ + /* Declaration of temporary variable to prevent undefined behavior of volatile usage */ + uint32_t CurrentXferOptions = hi2c->XferOptions; + + /* Generate Start condition if first transfer */ + if ((CurrentXferOptions == I2C_FIRST_AND_LAST_FRAME) || (CurrentXferOptions == I2C_FIRST_FRAME) || (CurrentXferOptions == I2C_NO_OPTION_FRAME)) + { + /* Generate Start */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_START); + } + else if (hi2c->PreviousState == I2C_STATE_MASTER_BUSY_RX) + { + /* Generate ReStart */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_START); + } + else + { + /* Do nothing */ + } + + /* Wait until SB flag is set */ + if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_SB, RESET, Timeout, Tickstart) != DAL_OK) + { + if (READ_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_START) == I2C_CTRL1_START) + { + hi2c->ErrorCode = DAL_I2C_WRONG_START; + } + return DAL_TIMEOUT; + } + + if (hi2c->Init.AddressingMode == I2C_ADDRESSINGMODE_7BIT) + { + /* Send slave address */ + hi2c->Instance->DATA = I2C_7BIT_ADD_WRITE(DevAddress); + } + else + { + /* Send header of slave address */ + hi2c->Instance->DATA = I2C_10BIT_HEADER_WRITE(DevAddress); + + /* Wait until ADD10 flag is set */ + if (I2C_WaitOnMasterAddressFlagUntilTimeout(hi2c, I2C_FLAG_ADD10, Timeout, Tickstart) != DAL_OK) + { + return DAL_ERROR; + } + + /* Send slave address */ + hi2c->Instance->DATA = I2C_10BIT_ADDRESS(DevAddress); + } + + /* Wait until ADDR flag is set */ + if (I2C_WaitOnMasterAddressFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, Timeout, Tickstart) != DAL_OK) + { + return DAL_ERROR; + } + + return DAL_OK; +} + +/** + * @brief Master sends target device address for read request. + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for I2C module + * @param DevAddress Target device address: The device 7 bits address value + * in datasheet must be shifted to the left before calling the interface + * @param Timeout Timeout duration + * @param Tickstart Tick start value + * @retval DAL status + */ +static DAL_StatusTypeDef I2C_MasterRequestRead(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint32_t Timeout, uint32_t Tickstart) +{ + /* Declaration of temporary variable to prevent undefined behavior of volatile usage */ + uint32_t CurrentXferOptions = hi2c->XferOptions; + + /* Enable Acknowledge */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKEN); + + /* Generate Start condition if first transfer */ + if ((CurrentXferOptions == I2C_FIRST_AND_LAST_FRAME) || (CurrentXferOptions == I2C_FIRST_FRAME) || (CurrentXferOptions == I2C_NO_OPTION_FRAME)) + { + /* Generate Start */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_START); + } + else if (hi2c->PreviousState == I2C_STATE_MASTER_BUSY_TX) + { + /* Generate ReStart */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_START); + } + else + { + /* Do nothing */ + } + + /* Wait until SB flag is set */ + if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_SB, RESET, Timeout, Tickstart) != DAL_OK) + { + if (READ_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_START) == I2C_CTRL1_START) + { + hi2c->ErrorCode = DAL_I2C_WRONG_START; + } + return DAL_TIMEOUT; + } + + if (hi2c->Init.AddressingMode == I2C_ADDRESSINGMODE_7BIT) + { + /* Send slave address */ + hi2c->Instance->DATA = I2C_7BIT_ADD_READ(DevAddress); + } + else + { + /* Send header of slave address */ + hi2c->Instance->DATA = I2C_10BIT_HEADER_WRITE(DevAddress); + + /* Wait until ADD10 flag is set */ + if (I2C_WaitOnMasterAddressFlagUntilTimeout(hi2c, I2C_FLAG_ADD10, Timeout, Tickstart) != DAL_OK) + { + return DAL_ERROR; + } + + /* Send slave address */ + hi2c->Instance->DATA = I2C_10BIT_ADDRESS(DevAddress); + + /* Wait until ADDR flag is set */ + if (I2C_WaitOnMasterAddressFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, Timeout, Tickstart) != DAL_OK) + { + return DAL_ERROR; + } + + /* Clear ADDR flag */ + __DAL_I2C_CLEAR_ADDRFLAG(hi2c); + + /* Generate Restart */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_START); + + /* Wait until SB flag is set */ + if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_SB, RESET, Timeout, Tickstart) != DAL_OK) + { + if (READ_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_START) == I2C_CTRL1_START) + { + hi2c->ErrorCode = DAL_I2C_WRONG_START; + } + return DAL_TIMEOUT; + } + + /* Send header of slave address */ + hi2c->Instance->DATA = I2C_10BIT_HEADER_READ(DevAddress); + } + + /* Wait until ADDR flag is set */ + if (I2C_WaitOnMasterAddressFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, Timeout, Tickstart) != DAL_OK) + { + return DAL_ERROR; + } + + return DAL_OK; +} + +/** + * @brief Master sends target device address followed by internal memory address for write request. + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for I2C module + * @param DevAddress Target device address: The device 7 bits address value + * in datasheet must be shifted to the left before calling the interface + * @param MemAddress Internal memory address + * @param MemAddSize Size of internal memory address + * @param Timeout Timeout duration + * @param Tickstart Tick start value + * @retval DAL status + */ +static DAL_StatusTypeDef I2C_RequestMemoryWrite(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint32_t Timeout, uint32_t Tickstart) +{ + /* Generate Start */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_START); + + /* Wait until SB flag is set */ + if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_SB, RESET, Timeout, Tickstart) != DAL_OK) + { + if (READ_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_START) == I2C_CTRL1_START) + { + hi2c->ErrorCode = DAL_I2C_WRONG_START; + } + return DAL_TIMEOUT; + } + + /* Send slave address */ + hi2c->Instance->DATA = I2C_7BIT_ADD_WRITE(DevAddress); + + /* Wait until ADDR flag is set */ + if (I2C_WaitOnMasterAddressFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, Timeout, Tickstart) != DAL_OK) + { + return DAL_ERROR; + } + + /* Clear ADDR flag */ + __DAL_I2C_CLEAR_ADDRFLAG(hi2c); + + /* Wait until TXE flag is set */ + if (I2C_WaitOnTXEFlagUntilTimeout(hi2c, Timeout, Tickstart) != DAL_OK) + { + if (hi2c->ErrorCode == DAL_I2C_ERROR_AF) + { + /* Generate Stop */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_STOP); + } + return DAL_ERROR; + } + + /* If Memory address size is 8Bit */ + if (MemAddSize == I2C_MEMADD_SIZE_8BIT) + { + /* Send Memory Address */ + hi2c->Instance->DATA = I2C_MEM_ADD_LSB(MemAddress); + } + /* If Memory address size is 16Bit */ + else + { + /* Send MSB of Memory Address */ + hi2c->Instance->DATA = I2C_MEM_ADD_MSB(MemAddress); + + /* Wait until TXE flag is set */ + if (I2C_WaitOnTXEFlagUntilTimeout(hi2c, Timeout, Tickstart) != DAL_OK) + { + if (hi2c->ErrorCode == DAL_I2C_ERROR_AF) + { + /* Generate Stop */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_STOP); + } + return DAL_ERROR; + } + + /* Send LSB of Memory Address */ + hi2c->Instance->DATA = I2C_MEM_ADD_LSB(MemAddress); + } + + return DAL_OK; +} + +/** + * @brief Master sends target device address followed by internal memory address for read request. + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for I2C module + * @param DevAddress Target device address: The device 7 bits address value + * in datasheet must be shifted to the left before calling the interface + * @param MemAddress Internal memory address + * @param MemAddSize Size of internal memory address + * @param Timeout Timeout duration + * @param Tickstart Tick start value + * @retval DAL status + */ +static DAL_StatusTypeDef I2C_RequestMemoryRead(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint32_t Timeout, uint32_t Tickstart) +{ + /* Enable Acknowledge */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKEN); + + /* Generate Start */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_START); + + /* Wait until SB flag is set */ + if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_SB, RESET, Timeout, Tickstart) != DAL_OK) + { + if (READ_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_START) == I2C_CTRL1_START) + { + hi2c->ErrorCode = DAL_I2C_WRONG_START; + } + return DAL_TIMEOUT; + } + + /* Send slave address */ + hi2c->Instance->DATA = I2C_7BIT_ADD_WRITE(DevAddress); + + /* Wait until ADDR flag is set */ + if (I2C_WaitOnMasterAddressFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, Timeout, Tickstart) != DAL_OK) + { + return DAL_ERROR; + } + + /* Clear ADDR flag */ + __DAL_I2C_CLEAR_ADDRFLAG(hi2c); + + /* Wait until TXE flag is set */ + if (I2C_WaitOnTXEFlagUntilTimeout(hi2c, Timeout, Tickstart) != DAL_OK) + { + if (hi2c->ErrorCode == DAL_I2C_ERROR_AF) + { + /* Generate Stop */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_STOP); + } + return DAL_ERROR; + } + + /* If Memory address size is 8Bit */ + if (MemAddSize == I2C_MEMADD_SIZE_8BIT) + { + /* Send Memory Address */ + hi2c->Instance->DATA = I2C_MEM_ADD_LSB(MemAddress); + } + /* If Memory address size is 16Bit */ + else + { + /* Send MSB of Memory Address */ + hi2c->Instance->DATA = I2C_MEM_ADD_MSB(MemAddress); + + /* Wait until TXE flag is set */ + if (I2C_WaitOnTXEFlagUntilTimeout(hi2c, Timeout, Tickstart) != DAL_OK) + { + if (hi2c->ErrorCode == DAL_I2C_ERROR_AF) + { + /* Generate Stop */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_STOP); + } + return DAL_ERROR; + } + + /* Send LSB of Memory Address */ + hi2c->Instance->DATA = I2C_MEM_ADD_LSB(MemAddress); + } + + /* Wait until TXE flag is set */ + if (I2C_WaitOnTXEFlagUntilTimeout(hi2c, Timeout, Tickstart) != DAL_OK) + { + if (hi2c->ErrorCode == DAL_I2C_ERROR_AF) + { + /* Generate Stop */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_STOP); + } + return DAL_ERROR; + } + + /* Generate Restart */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_START); + + /* Wait until SB flag is set */ + if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_SB, RESET, Timeout, Tickstart) != DAL_OK) + { + if (READ_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_START) == I2C_CTRL1_START) + { + hi2c->ErrorCode = DAL_I2C_WRONG_START; + } + return DAL_TIMEOUT; + } + + /* Send slave address */ + hi2c->Instance->DATA = I2C_7BIT_ADD_READ(DevAddress); + + /* Wait until ADDR flag is set */ + if (I2C_WaitOnMasterAddressFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, Timeout, Tickstart) != DAL_OK) + { + return DAL_ERROR; + } + + return DAL_OK; +} + +/** + * @brief DMA I2C process complete callback. + * @param hdma DMA handle + * @retval None + */ +static void I2C_DMAXferCplt(DMA_HandleTypeDef *hdma) +{ + I2C_HandleTypeDef *hi2c = (I2C_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; /* Derogation MISRAC2012-Rule-11.5 */ + + /* Declaration of temporary variable to prevent undefined behavior of volatile usage */ + DAL_I2C_StateTypeDef CurrentState = hi2c->State; + DAL_I2C_ModeTypeDef CurrentMode = hi2c->Mode; + uint32_t CurrentXferOptions = hi2c->XferOptions; + + /* Disable EVT and ERR interrupt */ + __DAL_I2C_DISABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_ERR); + + /* Clear Complete callback */ + if (hi2c->hdmatx != NULL) + { + hi2c->hdmatx->XferCpltCallback = NULL; + } + if (hi2c->hdmarx != NULL) + { + hi2c->hdmarx->XferCpltCallback = NULL; + } + + if ((((uint32_t)CurrentState & (uint32_t)DAL_I2C_STATE_BUSY_TX) == (uint32_t)DAL_I2C_STATE_BUSY_TX) || ((((uint32_t)CurrentState & (uint32_t)DAL_I2C_STATE_BUSY_RX) == (uint32_t)DAL_I2C_STATE_BUSY_RX) && (CurrentMode == DAL_I2C_MODE_SLAVE))) + { + /* Disable DMA Request */ + CLEAR_BIT(hi2c->Instance->CTRL2, I2C_CTRL2_DMAEN); + + hi2c->XferCount = 0U; + + if (CurrentState == DAL_I2C_STATE_BUSY_TX_LISTEN) + { + /* Set state at DAL_I2C_STATE_LISTEN */ + hi2c->PreviousState = I2C_STATE_SLAVE_BUSY_TX; + hi2c->State = DAL_I2C_STATE_LISTEN; + + /* Call the corresponding callback to inform upper layer of End of Transfer */ +#if (USE_DAL_I2C_REGISTER_CALLBACKS == 1) + hi2c->SlaveTxCpltCallback(hi2c); +#else + DAL_I2C_SlaveTxCpltCallback(hi2c); +#endif /* USE_DAL_I2C_REGISTER_CALLBACKS */ + } + else if (CurrentState == DAL_I2C_STATE_BUSY_RX_LISTEN) + { + /* Set state at DAL_I2C_STATE_LISTEN */ + hi2c->PreviousState = I2C_STATE_SLAVE_BUSY_RX; + hi2c->State = DAL_I2C_STATE_LISTEN; + + /* Call the corresponding callback to inform upper layer of End of Transfer */ +#if (USE_DAL_I2C_REGISTER_CALLBACKS == 1) + hi2c->SlaveRxCpltCallback(hi2c); +#else + DAL_I2C_SlaveRxCpltCallback(hi2c); +#endif /* USE_DAL_I2C_REGISTER_CALLBACKS */ + } + else + { + /* Do nothing */ + } + + /* Enable EVT and ERR interrupt to treat end of transfer in IRQ handler */ + __DAL_I2C_ENABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_ERR); + } + /* Check current Mode, in case of treatment DMA handler have been preempted by a prior interrupt */ + else if (hi2c->Mode != DAL_I2C_MODE_NONE) + { + if (hi2c->XferCount == (uint16_t)1) + { + /* Disable Acknowledge */ + CLEAR_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKEN); + } + + /* Disable EVT and ERR interrupt */ + __DAL_I2C_DISABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_ERR); + + /* Prepare next transfer or stop current transfer */ + if ((CurrentXferOptions == I2C_NO_OPTION_FRAME) || (CurrentXferOptions == I2C_FIRST_AND_LAST_FRAME) || (CurrentXferOptions == I2C_OTHER_AND_LAST_FRAME) || (CurrentXferOptions == I2C_LAST_FRAME)) + { + /* Generate Stop */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_STOP); + } + + /* Disable Last DMA */ + CLEAR_BIT(hi2c->Instance->CTRL2, I2C_CTRL2_LTCFG); + + /* Disable DMA Request */ + CLEAR_BIT(hi2c->Instance->CTRL2, I2C_CTRL2_DMAEN); + + hi2c->XferCount = 0U; + + /* Check if Errors has been detected during transfer */ + if (hi2c->ErrorCode != DAL_I2C_ERROR_NONE) + { +#if (USE_DAL_I2C_REGISTER_CALLBACKS == 1) + hi2c->ErrorCallback(hi2c); +#else + DAL_I2C_ErrorCallback(hi2c); +#endif /* USE_DAL_I2C_REGISTER_CALLBACKS */ + } + else + { + hi2c->State = DAL_I2C_STATE_READY; + + if (hi2c->Mode == DAL_I2C_MODE_MEM) + { + hi2c->Mode = DAL_I2C_MODE_NONE; + hi2c->PreviousState = I2C_STATE_NONE; + +#if (USE_DAL_I2C_REGISTER_CALLBACKS == 1) + hi2c->MemRxCpltCallback(hi2c); +#else + DAL_I2C_MemRxCpltCallback(hi2c); +#endif /* USE_DAL_I2C_REGISTER_CALLBACKS */ + } + else + { + hi2c->Mode = DAL_I2C_MODE_NONE; + hi2c->PreviousState = I2C_STATE_MASTER_BUSY_RX; + +#if (USE_DAL_I2C_REGISTER_CALLBACKS == 1) + hi2c->MasterRxCpltCallback(hi2c); +#else + DAL_I2C_MasterRxCpltCallback(hi2c); +#endif /* USE_DAL_I2C_REGISTER_CALLBACKS */ + } + } + } + else + { + /* Do nothing */ + } +} + +/** + * @brief DMA I2C communication error callback. + * @param hdma DMA handle + * @retval None + */ +static void I2C_DMAError(DMA_HandleTypeDef *hdma) +{ + I2C_HandleTypeDef *hi2c = (I2C_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; /* Derogation MISRAC2012-Rule-11.5 */ + + /* Clear Complete callback */ + if (hi2c->hdmatx != NULL) + { + hi2c->hdmatx->XferCpltCallback = NULL; + } + if (hi2c->hdmarx != NULL) + { + hi2c->hdmarx->XferCpltCallback = NULL; + } + + /* Ignore DMA FIFO error */ + if (DAL_DMA_GetError(hdma) != DAL_DMA_ERROR_FE) + { + /* Disable Acknowledge */ + hi2c->Instance->CTRL1 &= ~I2C_CTRL1_ACKEN; + + hi2c->XferCount = 0U; + + hi2c->State = DAL_I2C_STATE_READY; + hi2c->Mode = DAL_I2C_MODE_NONE; + + hi2c->ErrorCode |= DAL_I2C_ERROR_DMA; + +#if (USE_DAL_I2C_REGISTER_CALLBACKS == 1) + hi2c->ErrorCallback(hi2c); +#else + DAL_I2C_ErrorCallback(hi2c); +#endif /* USE_DAL_I2C_REGISTER_CALLBACKS */ + } +} + +/** + * @brief DMA I2C communication abort callback + * (To be called at end of DMA Abort procedure). + * @param hdma DMA handle. + * @retval None + */ +static void I2C_DMAAbort(DMA_HandleTypeDef *hdma) +{ + __IO uint32_t count = 0U; + I2C_HandleTypeDef *hi2c = (I2C_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; /* Derogation MISRAC2012-Rule-11.5 */ + + /* Declaration of temporary variable to prevent undefined behavior of volatile usage */ + DAL_I2C_StateTypeDef CurrentState = hi2c->State; + + /* During abort treatment, check that there is no pending STOP request */ + /* Wait until STOP flag is reset */ + count = I2C_TIMEOUT_FLAG * (SystemCoreClock / 25U / 1000U); + do + { + if (count == 0U) + { + hi2c->ErrorCode |= DAL_I2C_ERROR_TIMEOUT; + break; + } + count--; + } + while (READ_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_STOP) == I2C_CTRL1_STOP); + + /* Clear Complete callback */ + if (hi2c->hdmatx != NULL) + { + hi2c->hdmatx->XferCpltCallback = NULL; + } + if (hi2c->hdmarx != NULL) + { + hi2c->hdmarx->XferCpltCallback = NULL; + } + + /* Disable Acknowledge */ + CLEAR_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKEN); + + hi2c->XferCount = 0U; + + /* Reset XferAbortCallback */ + if (hi2c->hdmatx != NULL) + { + hi2c->hdmatx->XferAbortCallback = NULL; + } + if (hi2c->hdmarx != NULL) + { + hi2c->hdmarx->XferAbortCallback = NULL; + } + + /* Disable I2C peripheral to prevent dummy data in buffer */ + __DAL_I2C_DISABLE(hi2c); + + /* Check if come from abort from user */ + if (hi2c->State == DAL_I2C_STATE_ABORT) + { + hi2c->State = DAL_I2C_STATE_READY; + hi2c->Mode = DAL_I2C_MODE_NONE; + hi2c->ErrorCode = DAL_I2C_ERROR_NONE; + + /* Call the corresponding callback to inform upper layer of End of Transfer */ +#if (USE_DAL_I2C_REGISTER_CALLBACKS == 1) + hi2c->AbortCpltCallback(hi2c); +#else + DAL_I2C_AbortCpltCallback(hi2c); +#endif /* USE_DAL_I2C_REGISTER_CALLBACKS */ + } + else + { + if (((uint32_t)CurrentState & (uint32_t)DAL_I2C_STATE_LISTEN) == (uint32_t)DAL_I2C_STATE_LISTEN) + { + /* Renable I2C peripheral */ + __DAL_I2C_ENABLE(hi2c); + + /* Enable Acknowledge */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_ACKEN); + + /* keep DAL_I2C_STATE_LISTEN */ + hi2c->PreviousState = I2C_STATE_NONE; + hi2c->State = DAL_I2C_STATE_LISTEN; + } + else + { + hi2c->State = DAL_I2C_STATE_READY; + hi2c->Mode = DAL_I2C_MODE_NONE; + } + + /* Call the corresponding callback to inform upper layer of End of Transfer */ +#if (USE_DAL_I2C_REGISTER_CALLBACKS == 1) + hi2c->ErrorCallback(hi2c); +#else + DAL_I2C_ErrorCallback(hi2c); +#endif /* USE_DAL_I2C_REGISTER_CALLBACKS */ + } +} + +/** + * @brief This function handles I2C Communication Timeout. + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for I2C module + * @param Flag specifies the I2C flag to check. + * @param Status The new Flag status (SET or RESET). + * @param Timeout Timeout duration + * @param Tickstart Tick start value + * @retval DAL status + */ +static DAL_StatusTypeDef I2C_WaitOnFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Flag, FlagStatus Status, uint32_t Timeout, uint32_t Tickstart) +{ + /* Wait until flag is set */ + while (__DAL_I2C_GET_FLAG(hi2c, Flag) == Status) + { + /* Check for the Timeout */ + if (Timeout != DAL_MAX_DELAY) + { + if (((DAL_GetTick() - Tickstart) > Timeout) || (Timeout == 0U)) + { + hi2c->PreviousState = I2C_STATE_NONE; + hi2c->State = DAL_I2C_STATE_READY; + hi2c->Mode = DAL_I2C_MODE_NONE; + hi2c->ErrorCode |= DAL_I2C_ERROR_TIMEOUT; + + /* Process Unlocked */ + __DAL_UNLOCK(hi2c); + + return DAL_ERROR; + } + } + } + return DAL_OK; +} + +/** + * @brief This function handles I2C Communication Timeout for Master addressing phase. + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for I2C module + * @param Flag specifies the I2C flag to check. + * @param Timeout Timeout duration + * @param Tickstart Tick start value + * @retval DAL status + */ +static DAL_StatusTypeDef I2C_WaitOnMasterAddressFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Flag, uint32_t Timeout, uint32_t Tickstart) +{ + while (__DAL_I2C_GET_FLAG(hi2c, Flag) == RESET) + { + if (__DAL_I2C_GET_FLAG(hi2c, I2C_FLAG_AF) == SET) + { + /* Generate Stop */ + SET_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_STOP); + + /* Clear AF Flag */ + __DAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF); + + hi2c->PreviousState = I2C_STATE_NONE; + hi2c->State = DAL_I2C_STATE_READY; + hi2c->Mode = DAL_I2C_MODE_NONE; + hi2c->ErrorCode |= DAL_I2C_ERROR_AF; + + /* Process Unlocked */ + __DAL_UNLOCK(hi2c); + + return DAL_ERROR; + } + + /* Check for the Timeout */ + if (Timeout != DAL_MAX_DELAY) + { + if (((DAL_GetTick() - Tickstart) > Timeout) || (Timeout == 0U)) + { + hi2c->PreviousState = I2C_STATE_NONE; + hi2c->State = DAL_I2C_STATE_READY; + hi2c->Mode = DAL_I2C_MODE_NONE; + hi2c->ErrorCode |= DAL_I2C_ERROR_TIMEOUT; + + /* Process Unlocked */ + __DAL_UNLOCK(hi2c); + + return DAL_ERROR; + } + } + } + return DAL_OK; +} + +/** + * @brief This function handles I2C Communication Timeout for specific usage of TXE flag. + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param Timeout Timeout duration + * @param Tickstart Tick start value + * @retval DAL status + */ +static DAL_StatusTypeDef I2C_WaitOnTXEFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Timeout, uint32_t Tickstart) +{ + while (__DAL_I2C_GET_FLAG(hi2c, I2C_FLAG_TXE) == RESET) + { + /* Check if a NACK is detected */ + if (I2C_IsAcknowledgeFailed(hi2c) != DAL_OK) + { + return DAL_ERROR; + } + + /* Check for the Timeout */ + if (Timeout != DAL_MAX_DELAY) + { + if (((DAL_GetTick() - Tickstart) > Timeout) || (Timeout == 0U)) + { + hi2c->PreviousState = I2C_STATE_NONE; + hi2c->State = DAL_I2C_STATE_READY; + hi2c->Mode = DAL_I2C_MODE_NONE; + hi2c->ErrorCode |= DAL_I2C_ERROR_TIMEOUT; + + /* Process Unlocked */ + __DAL_UNLOCK(hi2c); + + return DAL_ERROR; + } + } + } + return DAL_OK; +} + +/** + * @brief This function handles I2C Communication Timeout for specific usage of BTF flag. + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param Timeout Timeout duration + * @param Tickstart Tick start value + * @retval DAL status + */ +static DAL_StatusTypeDef I2C_WaitOnBTFFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Timeout, uint32_t Tickstart) +{ + while (__DAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BTF) == RESET) + { + /* Check if a NACK is detected */ + if (I2C_IsAcknowledgeFailed(hi2c) != DAL_OK) + { + return DAL_ERROR; + } + + /* Check for the Timeout */ + if (Timeout != DAL_MAX_DELAY) + { + if (((DAL_GetTick() - Tickstart) > Timeout) || (Timeout == 0U)) + { + hi2c->PreviousState = I2C_STATE_NONE; + hi2c->State = DAL_I2C_STATE_READY; + hi2c->Mode = DAL_I2C_MODE_NONE; + hi2c->ErrorCode |= DAL_I2C_ERROR_TIMEOUT; + + /* Process Unlocked */ + __DAL_UNLOCK(hi2c); + + return DAL_ERROR; + } + } + } + return DAL_OK; +} + +/** + * @brief This function handles I2C Communication Timeout for specific usage of STOP flag. + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param Timeout Timeout duration + * @param Tickstart Tick start value + * @retval DAL status + */ +static DAL_StatusTypeDef I2C_WaitOnSTOPFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Timeout, uint32_t Tickstart) +{ + while (__DAL_I2C_GET_FLAG(hi2c, I2C_FLAG_STOPF) == RESET) + { + /* Check if a NACK is detected */ + if (I2C_IsAcknowledgeFailed(hi2c) != DAL_OK) + { + return DAL_ERROR; + } + + /* Check for the Timeout */ + if (((DAL_GetTick() - Tickstart) > Timeout) || (Timeout == 0U)) + { + hi2c->PreviousState = I2C_STATE_NONE; + hi2c->State = DAL_I2C_STATE_READY; + hi2c->Mode = DAL_I2C_MODE_NONE; + hi2c->ErrorCode |= DAL_I2C_ERROR_TIMEOUT; + + /* Process Unlocked */ + __DAL_UNLOCK(hi2c); + + return DAL_ERROR; + } + } + return DAL_OK; +} + +/** + * @brief This function handles I2C Communication Timeout for specific usage of STOP request through Interrupt. + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @retval DAL status + */ +static DAL_StatusTypeDef I2C_WaitOnSTOPRequestThroughIT(I2C_HandleTypeDef *hi2c) +{ + __IO uint32_t count = 0U; + + /* Wait until STOP flag is reset */ + count = I2C_TIMEOUT_STOP_FLAG * (SystemCoreClock / 25U / 1000U); + do + { + count--; + if (count == 0U) + { + hi2c->ErrorCode |= DAL_I2C_ERROR_TIMEOUT; + + return DAL_ERROR; + } + } + while (READ_BIT(hi2c->Instance->CTRL1, I2C_CTRL1_STOP) == I2C_CTRL1_STOP); + + return DAL_OK; +} + +/** + * @brief This function handles I2C Communication Timeout for specific usage of RXNE flag. + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param Timeout Timeout duration + * @param Tickstart Tick start value + * @retval DAL status + */ +static DAL_StatusTypeDef I2C_WaitOnRXNEFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Timeout, uint32_t Tickstart) +{ + + while (__DAL_I2C_GET_FLAG(hi2c, I2C_FLAG_RXNE) == RESET) + { + /* Check if a STOPF is detected */ + if (__DAL_I2C_GET_FLAG(hi2c, I2C_FLAG_STOPF) == SET) + { + /* Clear STOP Flag */ + __DAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF); + + hi2c->PreviousState = I2C_STATE_NONE; + hi2c->State = DAL_I2C_STATE_READY; + hi2c->Mode = DAL_I2C_MODE_NONE; + hi2c->ErrorCode |= DAL_I2C_ERROR_NONE; + + /* Process Unlocked */ + __DAL_UNLOCK(hi2c); + + return DAL_ERROR; + } + + /* Check for the Timeout */ + if (((DAL_GetTick() - Tickstart) > Timeout) || (Timeout == 0U)) + { + hi2c->PreviousState = I2C_STATE_NONE; + hi2c->State = DAL_I2C_STATE_READY; + hi2c->Mode = DAL_I2C_MODE_NONE; + hi2c->ErrorCode |= DAL_I2C_ERROR_TIMEOUT; + + /* Process Unlocked */ + __DAL_UNLOCK(hi2c); + + return DAL_ERROR; + } + } + return DAL_OK; +} + +/** + * @brief This function handles Acknowledge failed detection during an I2C Communication. + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @retval DAL status + */ +static DAL_StatusTypeDef I2C_IsAcknowledgeFailed(I2C_HandleTypeDef *hi2c) +{ + if (__DAL_I2C_GET_FLAG(hi2c, I2C_FLAG_AF) == SET) + { + /* Clear NACKF Flag */ + __DAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF); + + hi2c->PreviousState = I2C_STATE_NONE; + hi2c->State = DAL_I2C_STATE_READY; + hi2c->Mode = DAL_I2C_MODE_NONE; + hi2c->ErrorCode |= DAL_I2C_ERROR_AF; + + /* Process Unlocked */ + __DAL_UNLOCK(hi2c); + + return DAL_ERROR; + } + return DAL_OK; +} + +/** + * @brief Convert I2Cx OTHER_xxx XferOptions to functional XferOptions. + * @param hi2c I2C handle. + * @retval None + */ +static void I2C_ConvertOtherXferOptions(I2C_HandleTypeDef *hi2c) +{ + /* if user set XferOptions to I2C_OTHER_FRAME */ + /* it request implicitly to generate a restart condition */ + /* set XferOptions to I2C_FIRST_FRAME */ + if (hi2c->XferOptions == I2C_OTHER_FRAME) + { + hi2c->XferOptions = I2C_FIRST_FRAME; + } + /* else if user set XferOptions to I2C_OTHER_AND_LAST_FRAME */ + /* it request implicitly to generate a restart condition */ + /* then generate a stop condition at the end of transfer */ + /* set XferOptions to I2C_FIRST_AND_LAST_FRAME */ + else if (hi2c->XferOptions == I2C_OTHER_AND_LAST_FRAME) + { + hi2c->XferOptions = I2C_FIRST_AND_LAST_FRAME; + } + else + { + /* Nothing to do */ + } +} + +/** + * @} + */ + +#endif /* DAL_I2C_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_i2c_ex.c b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_i2c_ex.c new file mode 100644 index 0000000000..0a0f9b49c5 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_i2c_ex.c @@ -0,0 +1,207 @@ +/** + * + * @file apm32f4xx_dal_i2c_ex.c + * @brief I2C Extension DAL module driver. + * This file provides firmware functions to manage the following + * functionalities of I2C extension peripheral: + * + Extension features functions + * + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + * + @verbatim + ============================================================================== + ##### I2C peripheral extension features ##### + ============================================================================== + + [..] Comparing to other previous devices, the I2C interface for APM32F427xx/437xx/ + 429xx/439xx devices contains the following additional features : + + (+) Possibility to disable or enable Analog Noise Filter + (+) Use of a configured Digital Noise Filter + + ##### How to use this driver ##### + ============================================================================== + [..] This driver provides functions to configure Noise Filter + (#) Configure I2C Analog noise filter using the function DAL_I2C_AnalogFilter_Config() + (#) Configure I2C Digital noise filter using the function DAL_I2C_DigitalFilter_Config() + + @endverbatim + */ + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @defgroup I2CEx I2CEx + * @brief I2C DAL module driver + * @{ + */ + +#ifdef DAL_I2C_MODULE_ENABLED + +#if defined(I2C_FILTER_ANFDIS) && defined(I2C_FILTER_DNFCFG) +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Exported functions --------------------------------------------------------*/ +/** @defgroup I2CEx_Exported_Functions I2C Exported Functions + * @{ + */ + + +/** @defgroup I2CEx_Exported_Functions_Group1 Extension features functions + * @brief Extension features functions + * +@verbatim + =============================================================================== + ##### Extension features functions ##### + =============================================================================== + [..] This section provides functions allowing to: + (+) Configure Noise Filters + +@endverbatim + * @{ + */ + +/** + * @brief Configures I2C Analog noise filter. + * @param hi2c pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2Cx peripheral. + * @param AnalogFilter new state of the Analog filter. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_I2CEx_ConfigAnalogFilter(I2C_HandleTypeDef *hi2c, uint32_t AnalogFilter) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_I2C_ALL_INSTANCE(hi2c->Instance)); + ASSERT_PARAM(IS_I2C_ANALOG_FILTER(AnalogFilter)); + + if (hi2c->State == DAL_I2C_STATE_READY) + { + hi2c->State = DAL_I2C_STATE_BUSY; + + /* Disable the selected I2C peripheral */ + __DAL_I2C_DISABLE(hi2c); + + /* Reset I2Cx ANFDIS bit */ + hi2c->Instance->FILTER &= ~(I2C_FILTER_ANFDIS); + + /* Disable the analog filter */ + hi2c->Instance->FILTER |= AnalogFilter; + + __DAL_I2C_ENABLE(hi2c); + + hi2c->State = DAL_I2C_STATE_READY; + + return DAL_OK; + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief Configures I2C Digital noise filter. + * @param hi2c pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2Cx peripheral. + * @param DigitalFilter Coefficient of digital noise filter between 0x00 and 0x0F. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_I2CEx_ConfigDigitalFilter(I2C_HandleTypeDef *hi2c, uint32_t DigitalFilter) +{ + uint16_t tmpreg = 0; + + /* Check the parameters */ + ASSERT_PARAM(IS_I2C_ALL_INSTANCE(hi2c->Instance)); + ASSERT_PARAM(IS_I2C_DIGITAL_FILTER(DigitalFilter)); + + if (hi2c->State == DAL_I2C_STATE_READY) + { + hi2c->State = DAL_I2C_STATE_BUSY; + + /* Disable the selected I2C peripheral */ + __DAL_I2C_DISABLE(hi2c); + + /* Get the old register value */ + tmpreg = hi2c->Instance->FILTER; + + /* Reset I2Cx DNFCFG bit [3:0] */ + tmpreg &= ~(I2C_FILTER_DNFCFG); + + /* Set I2Cx DNFCFG coefficient */ + tmpreg |= DigitalFilter; + + /* Store the new register value */ + hi2c->Instance->FILTER = tmpreg; + + __DAL_I2C_ENABLE(hi2c); + + hi2c->State = DAL_I2C_STATE_READY; + + return DAL_OK; + } + else + { + return DAL_BUSY; + } +} + +/** + * @} + */ + +/** + * @} + */ +#endif /* I2C_FILTER_ANFDIS && I2C_FILTER_DNFCFG */ + +#endif /* DAL_I2C_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_i2s.c b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_i2s.c new file mode 100644 index 0000000000..32503dd09a --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_i2s.c @@ -0,0 +1,2119 @@ +/** + * + * @file apm32f4xx_dal_i2s.c + * @brief I2S DAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the Integrated Interchip Sound (I2S) peripheral: + * + Initialization and de-initialization functions + * + IO operation functions + * + Peripheral State and Errors functions + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + * + @verbatim + =============================================================================== + ##### How to use this driver ##### + =============================================================================== + [..] + The I2S DAL driver can be used as follow: + + (#) Declare a I2S_HandleTypeDef handle structure. + (#) Initialize the I2S low level resources by implement the DAL_I2S_MspInit() API: + (##) Enable the SPIx interface clock. + (##) I2S pins configuration: + (+++) Enable the clock for the I2S GPIOs. + (+++) Configure these I2S pins as alternate function pull-up. + (##) NVIC configuration if you need to use interrupt process (DAL_I2S_Transmit_IT() + and DAL_I2S_Receive_IT() APIs). + (+++) Configure the I2Sx interrupt priority. + (+++) Enable the NVIC I2S IRQ handle. + (##) DMA Configuration if you need to use DMA process (DAL_I2S_Transmit_DMA() + and DAL_I2S_Receive_DMA() APIs: + (+++) Declare a DMA handle structure for the Tx/Rx Stream/Channel. + (+++) Enable the DMAx interface clock. + (+++) Configure the declared DMA handle structure with the required Tx/Rx parameters. + (+++) Configure the DMA Tx/Rx Stream/Channel. + (+++) Associate the initialized DMA handle to the I2S DMA Tx/Rx handle. + (+++) Configure the priority and enable the NVIC for the transfer complete interrupt on the + DMA Tx/Rx Stream/Channel. + + (#) Program the Mode, Standard, Data Format, MCLK Output, Audio frequency and Polarity + using DAL_I2S_Init() function. + + -@- The specific I2S interrupts (Transmission complete interrupt, + RXNE interrupt and Error Interrupts) will be managed using the macros + __DAL_I2S_ENABLE_IT() and __DAL_I2S_DISABLE_IT() inside the transmit and receive process. + -@- Make sure that either: + (+@) I2S PLL clock is configured or + (+@) External clock source is configured after setting correctly + the define constant EXTERNAL_CLOCK_VALUE in the apm32f4xx_dal_cfg.h file. + + (#) Three mode of operations are available within this driver : + + *** Polling mode IO operation *** + ================================= + [..] + (+) Send an amount of data in blocking mode using DAL_I2S_Transmit() + (+) Receive an amount of data in blocking mode using DAL_I2S_Receive() + + *** Interrupt mode IO operation *** + =================================== + [..] + (+) Send an amount of data in non blocking mode using DAL_I2S_Transmit_IT() + (+) At transmission end of half transfer DAL_I2S_TxHalfCpltCallback is executed and user can + add his own code by customization of function pointer DAL_I2S_TxHalfCpltCallback + (+) At transmission end of transfer DAL_I2S_TxCpltCallback is executed and user can + add his own code by customization of function pointer DAL_I2S_TxCpltCallback + (+) Receive an amount of data in non blocking mode using DAL_I2S_Receive_IT() + (+) At reception end of half transfer DAL_I2S_RxHalfCpltCallback is executed and user can + add his own code by customization of function pointer DAL_I2S_RxHalfCpltCallback + (+) At reception end of transfer DAL_I2S_RxCpltCallback is executed and user can + add his own code by customization of function pointer DAL_I2S_RxCpltCallback + (+) In case of transfer Error, DAL_I2S_ErrorCallback() function is executed and user can + add his own code by customization of function pointer DAL_I2S_ErrorCallback + + *** DMA mode IO operation *** + ============================== + [..] + (+) Send an amount of data in non blocking mode (DMA) using DAL_I2S_Transmit_DMA() + (+) At transmission end of half transfer DAL_I2S_TxHalfCpltCallback is executed and user can + add his own code by customization of function pointer DAL_I2S_TxHalfCpltCallback + (+) At transmission end of transfer DAL_I2S_TxCpltCallback is executed and user can + add his own code by customization of function pointer DAL_I2S_TxCpltCallback + (+) Receive an amount of data in non blocking mode (DMA) using DAL_I2S_Receive_DMA() + (+) At reception end of half transfer DAL_I2S_RxHalfCpltCallback is executed and user can + add his own code by customization of function pointer DAL_I2S_RxHalfCpltCallback + (+) At reception end of transfer DAL_I2S_RxCpltCallback is executed and user can + add his own code by customization of function pointer DAL_I2S_RxCpltCallback + (+) In case of transfer Error, DAL_I2S_ErrorCallback() function is executed and user can + add his own code by customization of function pointer DAL_I2S_ErrorCallback + (+) Pause the DMA Transfer using DAL_I2S_DMAPause() + (+) Resume the DMA Transfer using DAL_I2S_DMAResume() + (+) Stop the DMA Transfer using DAL_I2S_DMAStop() + In Slave mode, if DAL_I2S_DMAStop is used to stop the communication, an error + DAL_I2S_ERROR_BUSY_LINE_RX is raised as the master continue to transmit data. + In this case __DAL_I2S_FLUSH_RX_DR macro must be used to flush the remaining data + inside DATA register and avoid using DeInit/Init process for the next transfer. + + *** I2S DAL driver macros list *** + =================================== + [..] + Below the list of most used macros in I2S DAL driver. + + (+) __DAL_I2S_ENABLE: Enable the specified SPI peripheral (in I2S mode) + (+) __DAL_I2S_DISABLE: Disable the specified SPI peripheral (in I2S mode) + (+) __DAL_I2S_ENABLE_IT : Enable the specified I2S interrupts + (+) __DAL_I2S_DISABLE_IT : Disable the specified I2S interrupts + (+) __DAL_I2S_GET_FLAG: Check whether the specified I2S flag is set or not + (+) __DAL_I2S_FLUSH_RX_DR: Read DATA Register to Flush RX Data + + [..] + (@) You can refer to the I2S DAL driver header file for more useful macros + + *** I2S DAL driver macros list *** + =================================== + [..] + Callback registration: + + (#) The compilation flag USE_DAL_I2S_REGISTER_CALLBACKS when set to 1U + allows the user to configure dynamically the driver callbacks. + Use Functions DAL_I2S_RegisterCallback() to register an interrupt callback. + + Function DAL_I2S_RegisterCallback() allows to register following callbacks: + (++) TxCpltCallback : I2S Tx Completed callback + (++) RxCpltCallback : I2S Rx Completed callback + (++) TxRxCpltCallback : I2S TxRx Completed callback + (++) TxHalfCpltCallback : I2S Tx Half Completed callback + (++) RxHalfCpltCallback : I2S Rx Half Completed callback + (++) ErrorCallback : I2S Error callback + (++) MspInitCallback : I2S Msp Init callback + (++) MspDeInitCallback : I2S Msp DeInit callback + This function takes as parameters the DAL peripheral handle, the Callback ID + and a pointer to the user callback function. + + + (#) Use function DAL_I2S_UnRegisterCallback to reset a callback to the default + weak function. + DAL_I2S_UnRegisterCallback takes as parameters the DAL peripheral handle, + and the Callback ID. + This function allows to reset following callbacks: + (++) TxCpltCallback : I2S Tx Completed callback + (++) RxCpltCallback : I2S Rx Completed callback + (++) TxRxCpltCallback : I2S TxRx Completed callback + (++) TxHalfCpltCallback : I2S Tx Half Completed callback + (++) RxHalfCpltCallback : I2S Rx Half Completed callback + (++) ErrorCallback : I2S Error callback + (++) MspInitCallback : I2S Msp Init callback + (++) MspDeInitCallback : I2S Msp DeInit callback + + [..] + By default, after the DAL_I2S_Init() and when the state is DAL_I2S_STATE_RESET + all callbacks are set to the corresponding weak functions: + examples DAL_I2S_MasterTxCpltCallback(), DAL_I2S_MasterRxCpltCallback(). + Exception done for MspInit and MspDeInit functions that are + reset to the legacy weak functions in the DAL_I2S_Init()/ DAL_I2S_DeInit() only when + these callbacks are null (not registered beforehand). + If MspInit or MspDeInit are not null, the DAL_I2S_Init()/ DAL_I2S_DeInit() + keep and use the user MspInit/MspDeInit callbacks (registered beforehand) whatever the state. + + [..] + Callbacks can be registered/unregistered in DAL_I2S_STATE_READY state only. + Exception done MspInit/MspDeInit functions that can be registered/unregistered + in DAL_I2S_STATE_READY or DAL_I2S_STATE_RESET state, + thus registered (user) MspInit/DeInit callbacks can be used during the Init/DeInit. + Then, the user first registers the MspInit/MspDeInit user callbacks + using DAL_I2S_RegisterCallback() before calling DAL_I2S_DeInit() + or DAL_I2S_Init() function. + + [..] + When the compilation define USE_DAL_I2S_REGISTER_CALLBACKS is set to 0 or + not defined, the callback registering feature is not available + and weak (surcharged) callbacks are used. + + @endverbatim + + */ + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal.h" + +#ifdef DAL_I2S_MODULE_ENABLED + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @defgroup I2S I2S + * @brief I2S DAL module driver + * @{ + */ + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +#define I2S_TIMEOUT_FLAG 100U /*!< Timeout 100 ms */ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/** @defgroup I2S_Private_Functions I2S Private Functions + * @{ + */ +static void I2S_DMATxCplt(DMA_HandleTypeDef *hdma); +static void I2S_DMATxHalfCplt(DMA_HandleTypeDef *hdma); +static void I2S_DMARxCplt(DMA_HandleTypeDef *hdma); +static void I2S_DMARxHalfCplt(DMA_HandleTypeDef *hdma); +static void I2S_DMAError(DMA_HandleTypeDef *hdma); +static void I2S_Transmit_IT(I2S_HandleTypeDef *hi2s); +static void I2S_Receive_IT(I2S_HandleTypeDef *hi2s); +static void I2S_IRQHandler(I2S_HandleTypeDef *hi2s); +static DAL_StatusTypeDef I2S_WaitFlagStateUntilTimeout(I2S_HandleTypeDef *hi2s, uint32_t Flag, FlagStatus State, + uint32_t Timeout); +/** + * @} + */ + +/* Exported functions ---------------------------------------------------------*/ + +/** @defgroup I2S_Exported_Functions I2S Exported Functions + * @{ + */ + +/** @defgroup I2S_Exported_Functions_Group1 Initialization and de-initialization functions + * @brief Initialization and Configuration functions + * +@verbatim + =============================================================================== + ##### Initialization and de-initialization functions ##### + =============================================================================== + [..] This subsection provides a set of functions allowing to initialize and + de-initialize the I2Sx peripheral in simplex mode: + + (+) User must Implement DAL_I2S_MspInit() function in which he configures + all related peripherals resources (CLOCK, GPIO, DMA, IT and NVIC ). + + (+) Call the function DAL_I2S_Init() to configure the selected device with + the selected configuration: + (++) Mode + (++) Standard + (++) Data Format + (++) MCLK Output + (++) Audio frequency + (++) Polarity + (++) Full duplex mode + + (+) Call the function DAL_I2S_DeInit() to restore the default configuration + of the selected I2Sx peripheral. + @endverbatim + * @{ + */ + +/** + * @brief Initializes the I2S according to the specified parameters + * in the I2S_InitTypeDef and create the associated handle. + * @param hi2s pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for I2S module + * @retval DAL status + */ +DAL_StatusTypeDef DAL_I2S_Init(I2S_HandleTypeDef *hi2s) +{ + uint32_t i2sdiv; + uint32_t i2sodd; + uint32_t packetlength; + uint32_t tmp; + uint32_t i2sclk; +#if defined (SPI_I2S_FULLDUPLEX_SUPPORT) + uint16_t tmpreg; +#endif + + /* Check the I2S handle allocation */ + if (hi2s == NULL) + { + return DAL_ERROR; + } + + /* Check the I2S parameters */ + ASSERT_PARAM(IS_I2S_ALL_INSTANCE(hi2s->Instance)); + ASSERT_PARAM(IS_I2S_MODE(hi2s->Init.Mode)); + ASSERT_PARAM(IS_I2S_STANDARD(hi2s->Init.Standard)); + ASSERT_PARAM(IS_I2S_DATA_FORMAT(hi2s->Init.DataFormat)); + ASSERT_PARAM(IS_I2S_MCLK_OUTPUT(hi2s->Init.MCLKOutput)); + ASSERT_PARAM(IS_I2S_AUDIO_FREQ(hi2s->Init.AudioFreq)); + ASSERT_PARAM(IS_I2S_CPOL(hi2s->Init.CPOL)); + ASSERT_PARAM(IS_I2S_CLOCKSOURCE(hi2s->Init.ClockSource)); + + if (hi2s->State == DAL_I2S_STATE_RESET) + { + /* Allocate lock resource and initialize it */ + hi2s->Lock = DAL_UNLOCKED; + + /* Initialize Default I2S IrqHandler ISR */ + hi2s->IrqHandlerISR = I2S_IRQHandler; + +#if (USE_DAL_I2S_REGISTER_CALLBACKS == 1U) + /* Init the I2S Callback settings */ + hi2s->TxCpltCallback = DAL_I2S_TxCpltCallback; /* Legacy weak TxCpltCallback */ + hi2s->RxCpltCallback = DAL_I2S_RxCpltCallback; /* Legacy weak RxCpltCallback */ +#if defined (SPI_I2S_FULLDUPLEX_SUPPORT) + hi2s->TxRxCpltCallback = DAL_I2SEx_TxRxCpltCallback; /* Legacy weak TxRxCpltCallback */ +#endif /* SPI_I2S_FULLDUPLEX_SUPPORT */ + hi2s->TxHalfCpltCallback = DAL_I2S_TxHalfCpltCallback; /* Legacy weak TxHalfCpltCallback */ + hi2s->RxHalfCpltCallback = DAL_I2S_RxHalfCpltCallback; /* Legacy weak RxHalfCpltCallback */ +#if defined (SPI_I2S_FULLDUPLEX_SUPPORT) + hi2s->TxRxHalfCpltCallback = DAL_I2SEx_TxRxHalfCpltCallback; /* Legacy weak TxRxHalfCpltCallback */ +#endif /* SPI_I2S_FULLDUPLEX_SUPPORT */ + hi2s->ErrorCallback = DAL_I2S_ErrorCallback; /* Legacy weak ErrorCallback */ + + if (hi2s->MspInitCallback == NULL) + { + hi2s->MspInitCallback = DAL_I2S_MspInit; /* Legacy weak MspInit */ + } + + /* Init the low level hardware : GPIO, CLOCK, NVIC... */ + hi2s->MspInitCallback(hi2s); +#else + /* Init the low level hardware : GPIO, CLOCK, CORTEX...etc */ + DAL_I2S_MspInit(hi2s); +#endif /* USE_DAL_I2S_REGISTER_CALLBACKS */ + } + + hi2s->State = DAL_I2S_STATE_BUSY; + + /*----------------------- SPIx I2SCFGR & I2SPR Configuration ----------------*/ + /* Clear I2SMOD, I2SE, I2SCFG, PCMSYNC, I2SSTD, CKPOL, DATLEN and CHLEN bits */ + CLEAR_BIT(hi2s->Instance->I2SCFG, (SPI_I2SCFG_CHLEN | SPI_I2SCFG_DATALEN | SPI_I2SCFG_CPOL | \ + SPI_I2SCFG_I2SSSEL | SPI_I2SCFG_PFSSEL | SPI_I2SCFG_I2SMOD | \ + SPI_I2SCFG_I2SEN | SPI_I2SCFG_MODESEL)); + hi2s->Instance->I2SPSC = 0x0002U; + + /*----------------------- I2SPR: I2SDIV and ODD Calculation -----------------*/ + /* If the requested audio frequency is not the default, compute the prescaler */ + if (hi2s->Init.AudioFreq != I2S_AUDIOFREQ_DEFAULT) + { + /* Check the frame length (For the Prescaler computing) ********************/ + if (hi2s->Init.DataFormat == I2S_DATAFORMAT_16B) + { + /* Packet length is 16 bits */ + packetlength = 16U; + } + else + { + /* Packet length is 32 bits */ + packetlength = 32U; + } + + /* I2S standard */ + if (hi2s->Init.Standard <= I2S_STANDARD_LSB) + { + /* In I2S standard packet length is multiplied by 2 */ + packetlength = packetlength * 2U; + } + + /* Get the source clock value **********************************************/ +#if defined(I2S_APB1_APB2_FEATURE) + if (IS_I2S_APB1_INSTANCE(hi2s->Instance)) + { + i2sclk = DAL_RCMEx_GetPeriphCLKFreq(RCM_PERIPHCLK_I2S_APB1); + } + else + { + i2sclk = DAL_RCMEx_GetPeriphCLKFreq(RCM_PERIPHCLK_I2S_APB2); + } +#else + i2sclk = DAL_RCMEx_GetPeriphCLKFreq(RCM_PERIPHCLK_I2S); +#endif /* I2S_APB1_APB2_FEATURE */ + + /* Compute the Real divider depending on the MCLK output state, with a floating point */ + if (hi2s->Init.MCLKOutput == I2S_MCLKOUTPUT_ENABLE) + { + /* MCLK output is enabled */ + if (hi2s->Init.DataFormat != I2S_DATAFORMAT_16B) + { + tmp = (uint32_t)(((((i2sclk / (packetlength * 4U)) * 10U) / hi2s->Init.AudioFreq)) + 5U); + } + else + { + tmp = (uint32_t)(((((i2sclk / (packetlength * 8U)) * 10U) / hi2s->Init.AudioFreq)) + 5U); + } + } + else + { + /* MCLK output is disabled */ + tmp = (uint32_t)(((((i2sclk / packetlength) * 10U) / hi2s->Init.AudioFreq)) + 5U); + } + + /* Remove the flatting point */ + tmp = tmp / 10U; + + /* Check the parity of the divider */ + i2sodd = (uint32_t)(tmp & (uint32_t)1U); + + /* Compute the i2sdiv prescaler */ + i2sdiv = (uint32_t)((tmp - i2sodd) / 2U); + + /* Get the Mask for the Odd bit (SPI_I2SPSC[8]) register */ + i2sodd = (uint32_t)(i2sodd << 8U); + } + else + { + /* Set the default values */ + i2sdiv = 2U; + i2sodd = 0U; + } + + /* Test if the divider is 1 or 0 or greater than 0xFF */ + if ((i2sdiv < 2U) || (i2sdiv > 0xFFU)) + { + /* Set the error code and execute error callback*/ + SET_BIT(hi2s->ErrorCode, DAL_I2S_ERROR_PRESCALER); + return DAL_ERROR; + } + + /*----------------------- SPIx I2SCFG & I2SPSC Configuration ----------------*/ + + /* Write to SPIx I2SPSC register the computed value */ + hi2s->Instance->I2SPSC = (uint32_t)((uint32_t)i2sdiv | (uint32_t)(i2sodd | (uint32_t)hi2s->Init.MCLKOutput)); + + /* Clear CHLEN, DATALEN, CPOL, I2SSSEL, PFSSEL, I2SMOD, I2SEN and MODESEL bits */ + /* And configure the I2S with the I2S_InitStruct values */ + MODIFY_REG(hi2s->Instance->I2SCFG, (SPI_I2SCFG_CHLEN | SPI_I2SCFG_DATALEN | \ + SPI_I2SCFG_CPOL | SPI_I2SCFG_I2SSSEL | \ + SPI_I2SCFG_PFSSEL | SPI_I2SCFG_I2SMOD | \ + SPI_I2SCFG_I2SEN | SPI_I2SCFG_MODESEL), \ + (SPI_I2SCFG_MODESEL | hi2s->Init.Mode | \ + hi2s->Init.Standard | hi2s->Init.DataFormat | \ + hi2s->Init.CPOL)); + +#if defined(SPI_I2SCFG_ASTRTEN) + if ((hi2s->Init.Standard == I2S_STANDARD_PCM_SHORT) || ((hi2s->Init.Standard == I2S_STANDARD_PCM_LONG))) + { + /* Write to SPIx I2SCFG */ + SET_BIT(hi2s->Instance->I2SCFG, SPI_I2SCFG_ASTRTEN); + } +#endif /* SPI_I2SCFG_ASTRTEN */ + +#if defined (SPI_I2S_FULLDUPLEX_SUPPORT) + + /* Configure the I2S extended if the full duplex mode is enabled */ + ASSERT_PARAM(IS_I2S_FULLDUPLEX_MODE(hi2s->Init.FullDuplexMode)); + + if (hi2s->Init.FullDuplexMode == I2S_FULLDUPLEXMODE_ENABLE) + { + /* Set FullDuplex I2S IrqHandler ISR if FULLDUPLEXMODE is enabled */ + hi2s->IrqHandlerISR = DAL_I2SEx_FullDuplex_IRQHandler; + + /* Clear CHLEN, DATALEN, CPOL, I2SSSEL, PFSSEL, I2SMOD, I2SEN and MODESEL bits */ + CLEAR_BIT(I2SxEXT(hi2s->Instance)->I2SCFG, (SPI_I2SCFG_CHLEN | SPI_I2SCFG_DATALEN | SPI_I2SCFG_CPOL | \ + SPI_I2SCFG_I2SSSEL | SPI_I2SCFG_PFSSEL | SPI_I2SCFG_I2SMOD | \ + SPI_I2SCFG_I2SEN | SPI_I2SCFG_MODESEL)); + I2SxEXT(hi2s->Instance)->I2SPSC = 2U; + + /* Get the I2SCFG register value */ + tmpreg = I2SxEXT(hi2s->Instance)->I2SCFG; + + /* Get the mode to be configured for the extended I2S */ + if ((hi2s->Init.Mode == I2S_MODE_MASTER_TX) || (hi2s->Init.Mode == I2S_MODE_SLAVE_TX)) + { + tmp = I2S_MODE_SLAVE_RX; + } + else /* I2S_MODE_MASTER_RX || I2S_MODE_SLAVE_RX */ + { + tmp = I2S_MODE_SLAVE_TX; + } + + /* Configure the I2S Slave with the I2S Master parameter values */ + tmpreg |= (uint16_t)((uint16_t)SPI_I2SCFG_MODESEL | \ + (uint16_t)tmp | \ + (uint16_t)hi2s->Init.Standard | \ + (uint16_t)hi2s->Init.DataFormat | \ + (uint16_t)hi2s->Init.CPOL); + + /* Write to SPIx I2SCFG */ + WRITE_REG(I2SxEXT(hi2s->Instance)->I2SCFG, tmpreg); + } +#endif /* SPI_I2S_FULLDUPLEX_SUPPORT */ + + hi2s->ErrorCode = DAL_I2S_ERROR_NONE; + hi2s->State = DAL_I2S_STATE_READY; + + return DAL_OK; +} + +/** + * @brief DeInitializes the I2S peripheral + * @param hi2s pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for I2S module + * @retval DAL status + */ +DAL_StatusTypeDef DAL_I2S_DeInit(I2S_HandleTypeDef *hi2s) +{ + /* Check the I2S handle allocation */ + if (hi2s == NULL) + { + return DAL_ERROR; + } + + /* Check the parameters */ + ASSERT_PARAM(IS_I2S_ALL_INSTANCE(hi2s->Instance)); + + hi2s->State = DAL_I2S_STATE_BUSY; + + /* Disable the I2S Peripheral Clock */ + __DAL_I2S_DISABLE(hi2s); + +#if (USE_DAL_I2S_REGISTER_CALLBACKS == 1U) + if (hi2s->MspDeInitCallback == NULL) + { + hi2s->MspDeInitCallback = DAL_I2S_MspDeInit; /* Legacy weak MspDeInit */ + } + + /* DeInit the low level hardware: GPIO, CLOCK, NVIC... */ + hi2s->MspDeInitCallback(hi2s); +#else + /* DeInit the low level hardware: GPIO, CLOCK, NVIC... */ + DAL_I2S_MspDeInit(hi2s); +#endif /* USE_DAL_I2S_REGISTER_CALLBACKS */ + + hi2s->ErrorCode = DAL_I2S_ERROR_NONE; + hi2s->State = DAL_I2S_STATE_RESET; + + /* Release Lock */ + __DAL_UNLOCK(hi2s); + + return DAL_OK; +} + +/** + * @brief I2S MSP Init + * @param hi2s pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for I2S module + * @retval None + */ +__weak void DAL_I2S_MspInit(I2S_HandleTypeDef *hi2s) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hi2s); + + /* NOTE : This function Should not be modified, when the callback is needed, + the DAL_I2S_MspInit could be implemented in the user file + */ +} + +/** + * @brief I2S MSP DeInit + * @param hi2s pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for I2S module + * @retval None + */ +__weak void DAL_I2S_MspDeInit(I2S_HandleTypeDef *hi2s) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hi2s); + + /* NOTE : This function Should not be modified, when the callback is needed, + the DAL_I2S_MspDeInit could be implemented in the user file + */ +} + +#if (USE_DAL_I2S_REGISTER_CALLBACKS == 1U) +/** + * @brief Register a User I2S Callback + * To be used instead of the weak predefined callback + * @param hi2s Pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for the specified I2S. + * @param CallbackID ID of the callback to be registered + * @param pCallback pointer to the Callback function + * @retval DAL status + */ +DAL_StatusTypeDef DAL_I2S_RegisterCallback(I2S_HandleTypeDef *hi2s, DAL_I2S_CallbackIDTypeDef CallbackID, + pI2S_CallbackTypeDef pCallback) +{ + DAL_StatusTypeDef status = DAL_OK; + + if (pCallback == NULL) + { + /* Update the error code */ + hi2s->ErrorCode |= DAL_I2S_ERROR_INVALID_CALLBACK; + + return DAL_ERROR; + } + /* Process locked */ + __DAL_LOCK(hi2s); + + if (DAL_I2S_STATE_READY == hi2s->State) + { + switch (CallbackID) + { + case DAL_I2S_TX_COMPLETE_CB_ID : + hi2s->TxCpltCallback = pCallback; + break; + + case DAL_I2S_RX_COMPLETE_CB_ID : + hi2s->RxCpltCallback = pCallback; + break; + +#if defined (SPI_I2S_FULLDUPLEX_SUPPORT) + case DAL_I2S_TX_RX_COMPLETE_CB_ID : + hi2s->TxRxCpltCallback = pCallback; + break; +#endif /* SPI_I2S_FULLDUPLEX_SUPPORT */ + + case DAL_I2S_TX_HALF_COMPLETE_CB_ID : + hi2s->TxHalfCpltCallback = pCallback; + break; + + case DAL_I2S_RX_HALF_COMPLETE_CB_ID : + hi2s->RxHalfCpltCallback = pCallback; + break; + +#if defined (SPI_I2S_FULLDUPLEX_SUPPORT) + case DAL_I2S_TX_RX_HALF_COMPLETE_CB_ID : + hi2s->TxRxHalfCpltCallback = pCallback; + break; +#endif /* SPI_I2S_FULLDUPLEX_SUPPORT */ + + case DAL_I2S_ERROR_CB_ID : + hi2s->ErrorCallback = pCallback; + break; + + case DAL_I2S_MSPINIT_CB_ID : + hi2s->MspInitCallback = pCallback; + break; + + case DAL_I2S_MSPDEINIT_CB_ID : + hi2s->MspDeInitCallback = pCallback; + break; + + default : + /* Update the error code */ + SET_BIT(hi2s->ErrorCode, DAL_I2S_ERROR_INVALID_CALLBACK); + + /* Return error status */ + status = DAL_ERROR; + break; + } + } + else if (DAL_I2S_STATE_RESET == hi2s->State) + { + switch (CallbackID) + { + case DAL_I2S_MSPINIT_CB_ID : + hi2s->MspInitCallback = pCallback; + break; + + case DAL_I2S_MSPDEINIT_CB_ID : + hi2s->MspDeInitCallback = pCallback; + break; + + default : + /* Update the error code */ + SET_BIT(hi2s->ErrorCode, DAL_I2S_ERROR_INVALID_CALLBACK); + + /* Return error status */ + status = DAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + SET_BIT(hi2s->ErrorCode, DAL_I2S_ERROR_INVALID_CALLBACK); + + /* Return error status */ + status = DAL_ERROR; + } + + /* Release Lock */ + __DAL_UNLOCK(hi2s); + return status; +} + +/** + * @brief Unregister an I2S Callback + * I2S callback is redirected to the weak predefined callback + * @param hi2s Pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for the specified I2S. + * @param CallbackID ID of the callback to be unregistered + * @retval DAL status + */ +DAL_StatusTypeDef DAL_I2S_UnRegisterCallback(I2S_HandleTypeDef *hi2s, DAL_I2S_CallbackIDTypeDef CallbackID) +{ + DAL_StatusTypeDef status = DAL_OK; + + /* Process locked */ + __DAL_LOCK(hi2s); + + if (DAL_I2S_STATE_READY == hi2s->State) + { + switch (CallbackID) + { + case DAL_I2S_TX_COMPLETE_CB_ID : + hi2s->TxCpltCallback = DAL_I2S_TxCpltCallback; /* Legacy weak TxCpltCallback */ + break; + + case DAL_I2S_RX_COMPLETE_CB_ID : + hi2s->RxCpltCallback = DAL_I2S_RxCpltCallback; /* Legacy weak RxCpltCallback */ + break; + +#if defined (SPI_I2S_FULLDUPLEX_SUPPORT) + case DAL_I2S_TX_RX_COMPLETE_CB_ID : + hi2s->TxRxCpltCallback = DAL_I2SEx_TxRxCpltCallback; /* Legacy weak TxRxCpltCallback */ + break; +#endif /* SPI_I2S_FULLDUPLEX_SUPPORT */ + + case DAL_I2S_TX_HALF_COMPLETE_CB_ID : + hi2s->TxHalfCpltCallback = DAL_I2S_TxHalfCpltCallback; /* Legacy weak TxHalfCpltCallback */ + break; + + case DAL_I2S_RX_HALF_COMPLETE_CB_ID : + hi2s->RxHalfCpltCallback = DAL_I2S_RxHalfCpltCallback; /* Legacy weak RxHalfCpltCallback */ + break; + +#if defined (SPI_I2S_FULLDUPLEX_SUPPORT) + case DAL_I2S_TX_RX_HALF_COMPLETE_CB_ID : + hi2s->TxRxHalfCpltCallback = DAL_I2SEx_TxRxHalfCpltCallback; /* Legacy weak TxRxHalfCpltCallback */ + break; +#endif /* SPI_I2S_FULLDUPLEX_SUPPORT */ + + case DAL_I2S_ERROR_CB_ID : + hi2s->ErrorCallback = DAL_I2S_ErrorCallback; /* Legacy weak ErrorCallback */ + break; + + case DAL_I2S_MSPINIT_CB_ID : + hi2s->MspInitCallback = DAL_I2S_MspInit; /* Legacy weak MspInit */ + break; + + case DAL_I2S_MSPDEINIT_CB_ID : + hi2s->MspDeInitCallback = DAL_I2S_MspDeInit; /* Legacy weak MspDeInit */ + break; + + default : + /* Update the error code */ + SET_BIT(hi2s->ErrorCode, DAL_I2S_ERROR_INVALID_CALLBACK); + + /* Return error status */ + status = DAL_ERROR; + break; + } + } + else if (DAL_I2S_STATE_RESET == hi2s->State) + { + switch (CallbackID) + { + case DAL_I2S_MSPINIT_CB_ID : + hi2s->MspInitCallback = DAL_I2S_MspInit; /* Legacy weak MspInit */ + break; + + case DAL_I2S_MSPDEINIT_CB_ID : + hi2s->MspDeInitCallback = DAL_I2S_MspDeInit; /* Legacy weak MspDeInit */ + break; + + default : + /* Update the error code */ + SET_BIT(hi2s->ErrorCode, DAL_I2S_ERROR_INVALID_CALLBACK); + + /* Return error status */ + status = DAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + SET_BIT(hi2s->ErrorCode, DAL_I2S_ERROR_INVALID_CALLBACK); + + /* Return error status */ + status = DAL_ERROR; + } + + /* Release Lock */ + __DAL_UNLOCK(hi2s); + return status; +} +#endif /* USE_DAL_I2S_REGISTER_CALLBACKS */ +/** + * @} + */ + +/** @defgroup I2S_Exported_Functions_Group2 IO operation functions + * @brief Data transfers functions + * +@verbatim + =============================================================================== + ##### IO operation functions ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to manage the I2S data + transfers. + + (#) There are two modes of transfer: + (++) Blocking mode : The communication is performed in the polling mode. + The status of all data processing is returned by the same function + after finishing transfer. + (++) No-Blocking mode : The communication is performed using Interrupts + or DMA. These functions return the status of the transfer startup. + The end of the data processing will be indicated through the + dedicated I2S IRQ when using Interrupt mode or the DMA IRQ when + using DMA mode. + + (#) Blocking mode functions are : + (++) DAL_I2S_Transmit() + (++) DAL_I2S_Receive() + + (#) No-Blocking mode functions with Interrupt are : + (++) DAL_I2S_Transmit_IT() + (++) DAL_I2S_Receive_IT() + + (#) No-Blocking mode functions with DMA are : + (++) DAL_I2S_Transmit_DMA() + (++) DAL_I2S_Receive_DMA() + + (#) A set of Transfer Complete Callbacks are provided in non Blocking mode: + (++) DAL_I2S_TxCpltCallback() + (++) DAL_I2S_RxCpltCallback() + (++) DAL_I2S_ErrorCallback() + +@endverbatim + * @{ + */ + +/** + * @brief Transmit an amount of data in blocking mode + * @param hi2s pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for I2S module + * @param pData a 16-bit pointer to data buffer. + * @param Size number of data sample to be sent: + * @note When a 16-bit data frame or a 16-bit data frame extended is selected during the I2S + * configuration phase, the Size parameter means the number of 16-bit data length + * in the transaction and when a 24-bit data frame or a 32-bit data frame is selected + * the Size parameter means the number of 24-bit or 32-bit data length. + * @param Timeout Timeout duration + * @note The I2S is kept enabled at the end of transaction to avoid the clock de-synchronization + * between Master and Slave(example: audio streaming). + * @retval DAL status + */ +DAL_StatusTypeDef DAL_I2S_Transmit(I2S_HandleTypeDef *hi2s, uint16_t *pData, uint16_t Size, uint32_t Timeout) +{ + uint32_t tmpreg_cfgr; + + if ((pData == NULL) || (Size == 0U)) + { + return DAL_ERROR; + } + + /* Process Locked */ + __DAL_LOCK(hi2s); + + if (hi2s->State != DAL_I2S_STATE_READY) + { + __DAL_UNLOCK(hi2s); + return DAL_BUSY; + } + + /* Set state and reset error code */ + hi2s->State = DAL_I2S_STATE_BUSY_TX; + hi2s->ErrorCode = DAL_I2S_ERROR_NONE; + hi2s->pTxBuffPtr = pData; + + tmpreg_cfgr = hi2s->Instance->I2SCFG & (SPI_I2SCFG_DATALEN | SPI_I2SCFG_CHLEN); + + if ((tmpreg_cfgr == I2S_DATAFORMAT_24B) || (tmpreg_cfgr == I2S_DATAFORMAT_32B)) + { + hi2s->TxXferSize = (Size << 1U); + hi2s->TxXferCount = (Size << 1U); + } + else + { + hi2s->TxXferSize = Size; + hi2s->TxXferCount = Size; + } + + tmpreg_cfgr = hi2s->Instance->I2SCFG; + + /* Check if the I2S is already enabled */ + if ((hi2s->Instance->I2SCFG & SPI_I2SCFG_I2SEN) != SPI_I2SCFG_I2SEN) + { + /* Enable I2S peripheral */ + __DAL_I2S_ENABLE(hi2s); + } + + /* Wait until TXE flag is set */ + if (I2S_WaitFlagStateUntilTimeout(hi2s, I2S_FLAG_TXE, SET, Timeout) != DAL_OK) + { + /* Set the error code */ + SET_BIT(hi2s->ErrorCode, DAL_I2S_ERROR_TIMEOUT); + hi2s->State = DAL_I2S_STATE_READY; + __DAL_UNLOCK(hi2s); + return DAL_ERROR; + } + + while (hi2s->TxXferCount > 0U) + { + hi2s->Instance->DATA = (*hi2s->pTxBuffPtr); + hi2s->pTxBuffPtr++; + hi2s->TxXferCount--; + + /* Wait until TXE flag is set */ + if (I2S_WaitFlagStateUntilTimeout(hi2s, I2S_FLAG_TXE, SET, Timeout) != DAL_OK) + { + /* Set the error code */ + SET_BIT(hi2s->ErrorCode, DAL_I2S_ERROR_TIMEOUT); + hi2s->State = DAL_I2S_STATE_READY; + __DAL_UNLOCK(hi2s); + return DAL_ERROR; + } + + /* Check if an underrun occurs */ + if (__DAL_I2S_GET_FLAG(hi2s, I2S_FLAG_UDR) == SET) + { + /* Clear underrun flag */ + __DAL_I2S_CLEAR_UDRFLAG(hi2s); + + /* Set the error code */ + SET_BIT(hi2s->ErrorCode, DAL_I2S_ERROR_UDR); + } + } + + /* Check if Slave mode is selected */ + if (((tmpreg_cfgr & SPI_I2SCFG_I2SMOD) == I2S_MODE_SLAVE_TX) + || ((tmpreg_cfgr & SPI_I2SCFG_I2SMOD) == I2S_MODE_SLAVE_RX)) + { + /* Wait until Busy flag is reset */ + if (I2S_WaitFlagStateUntilTimeout(hi2s, I2S_FLAG_BSY, RESET, Timeout) != DAL_OK) + { + /* Set the error code */ + SET_BIT(hi2s->ErrorCode, DAL_I2S_ERROR_TIMEOUT); + hi2s->State = DAL_I2S_STATE_READY; + __DAL_UNLOCK(hi2s); + return DAL_ERROR; + } + } + + hi2s->State = DAL_I2S_STATE_READY; + __DAL_UNLOCK(hi2s); + return DAL_OK; +} + +/** + * @brief Receive an amount of data in blocking mode + * @param hi2s pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for I2S module + * @param pData a 16-bit pointer to data buffer. + * @param Size number of data sample to be sent: + * @note When a 16-bit data frame or a 16-bit data frame extended is selected during the I2S + * configuration phase, the Size parameter means the number of 16-bit data length + * in the transaction and when a 24-bit data frame or a 32-bit data frame is selected + * the Size parameter means the number of 24-bit or 32-bit data length. + * @param Timeout Timeout duration + * @note The I2S is kept enabled at the end of transaction to avoid the clock de-synchronization + * between Master and Slave(example: audio streaming). + * @note In I2S Master Receiver mode, just after enabling the peripheral the clock will be generate + * in continuous way and as the I2S is not disabled at the end of the I2S transaction. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_I2S_Receive(I2S_HandleTypeDef *hi2s, uint16_t *pData, uint16_t Size, uint32_t Timeout) +{ + uint32_t tmpreg_cfgr; + + if ((pData == NULL) || (Size == 0U)) + { + return DAL_ERROR; + } + + /* Process Locked */ + __DAL_LOCK(hi2s); + + if (hi2s->State != DAL_I2S_STATE_READY) + { + __DAL_UNLOCK(hi2s); + return DAL_BUSY; + } + + /* Set state and reset error code */ + hi2s->State = DAL_I2S_STATE_BUSY_RX; + hi2s->ErrorCode = DAL_I2S_ERROR_NONE; + hi2s->pRxBuffPtr = pData; + + tmpreg_cfgr = hi2s->Instance->I2SCFG & (SPI_I2SCFG_DATALEN | SPI_I2SCFG_CHLEN); + + if ((tmpreg_cfgr == I2S_DATAFORMAT_24B) || (tmpreg_cfgr == I2S_DATAFORMAT_32B)) + { + hi2s->RxXferSize = (Size << 1U); + hi2s->RxXferCount = (Size << 1U); + } + else + { + hi2s->RxXferSize = Size; + hi2s->RxXferCount = Size; + } + + /* Check if the I2S is already enabled */ + if ((hi2s->Instance->I2SCFG & SPI_I2SCFG_I2SEN) != SPI_I2SCFG_I2SEN) + { + /* Enable I2S peripheral */ + __DAL_I2S_ENABLE(hi2s); + } + + /* Check if Master Receiver mode is selected */ + if ((hi2s->Instance->I2SCFG & SPI_I2SCFG_I2SMOD) == I2S_MODE_MASTER_RX) + { + /* Clear the Overrun Flag by a read operation on the SPI_DATA register followed by a read + access to the SPI_STS register. */ + __DAL_I2S_CLEAR_OVRFLAG(hi2s); + } + + /* Receive data */ + while (hi2s->RxXferCount > 0U) + { + /* Wait until RXNE flag is set */ + if (I2S_WaitFlagStateUntilTimeout(hi2s, I2S_FLAG_RXNE, SET, Timeout) != DAL_OK) + { + /* Set the error code */ + SET_BIT(hi2s->ErrorCode, DAL_I2S_ERROR_TIMEOUT); + hi2s->State = DAL_I2S_STATE_READY; + __DAL_UNLOCK(hi2s); + return DAL_ERROR; + } + + (*hi2s->pRxBuffPtr) = (uint16_t)hi2s->Instance->DATA; + hi2s->pRxBuffPtr++; + hi2s->RxXferCount--; + + /* Check if an overrun occurs */ + if (__DAL_I2S_GET_FLAG(hi2s, I2S_FLAG_OVR) == SET) + { + /* Clear overrun flag */ + __DAL_I2S_CLEAR_OVRFLAG(hi2s); + + /* Set the error code */ + SET_BIT(hi2s->ErrorCode, DAL_I2S_ERROR_OVR); + } + } + + hi2s->State = DAL_I2S_STATE_READY; + __DAL_UNLOCK(hi2s); + return DAL_OK; +} + +/** + * @brief Transmit an amount of data in non-blocking mode with Interrupt + * @param hi2s pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for I2S module + * @param pData a 16-bit pointer to data buffer. + * @param Size number of data sample to be sent: + * @note When a 16-bit data frame or a 16-bit data frame extended is selected during the I2S + * configuration phase, the Size parameter means the number of 16-bit data length + * in the transaction and when a 24-bit data frame or a 32-bit data frame is selected + * the Size parameter means the number of 24-bit or 32-bit data length. + * @note The I2S is kept enabled at the end of transaction to avoid the clock de-synchronization + * between Master and Slave(example: audio streaming). + * @retval DAL status + */ +DAL_StatusTypeDef DAL_I2S_Transmit_IT(I2S_HandleTypeDef *hi2s, uint16_t *pData, uint16_t Size) +{ + uint32_t tmpreg_cfgr; + + if ((pData == NULL) || (Size == 0U)) + { + return DAL_ERROR; + } + + /* Process Locked */ + __DAL_LOCK(hi2s); + + if (hi2s->State != DAL_I2S_STATE_READY) + { + __DAL_UNLOCK(hi2s); + return DAL_BUSY; + } + + /* Set state and reset error code */ + hi2s->State = DAL_I2S_STATE_BUSY_TX; + hi2s->ErrorCode = DAL_I2S_ERROR_NONE; + hi2s->pTxBuffPtr = pData; + + tmpreg_cfgr = hi2s->Instance->I2SCFG & (SPI_I2SCFG_DATALEN | SPI_I2SCFG_CHLEN); + + if ((tmpreg_cfgr == I2S_DATAFORMAT_24B) || (tmpreg_cfgr == I2S_DATAFORMAT_32B)) + { + hi2s->TxXferSize = (Size << 1U); + hi2s->TxXferCount = (Size << 1U); + } + else + { + hi2s->TxXferSize = Size; + hi2s->TxXferCount = Size; + } + + /* Enable TXE and ERR interrupt */ + __DAL_I2S_ENABLE_IT(hi2s, (I2S_IT_TXE | I2S_IT_ERR)); + + /* Check if the I2S is already enabled */ + if ((hi2s->Instance->I2SCFG & SPI_I2SCFG_I2SEN) != SPI_I2SCFG_I2SEN) + { + /* Enable I2S peripheral */ + __DAL_I2S_ENABLE(hi2s); + } + + __DAL_UNLOCK(hi2s); + return DAL_OK; +} + +/** + * @brief Receive an amount of data in non-blocking mode with Interrupt + * @param hi2s pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for I2S module + * @param pData a 16-bit pointer to the Receive data buffer. + * @param Size number of data sample to be sent: + * @note When a 16-bit data frame or a 16-bit data frame extended is selected during the I2S + * configuration phase, the Size parameter means the number of 16-bit data length + * in the transaction and when a 24-bit data frame or a 32-bit data frame is selected + * the Size parameter means the number of 24-bit or 32-bit data length. + * @note The I2S is kept enabled at the end of transaction to avoid the clock de-synchronization + * between Master and Slave(example: audio streaming). + * @note It is recommended to use DMA for the I2S receiver to avoid de-synchronization + * between Master and Slave otherwise the I2S interrupt should be optimized. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_I2S_Receive_IT(I2S_HandleTypeDef *hi2s, uint16_t *pData, uint16_t Size) +{ + uint32_t tmpreg_cfgr; + + if ((pData == NULL) || (Size == 0U)) + { + return DAL_ERROR; + } + + /* Process Locked */ + __DAL_LOCK(hi2s); + + if (hi2s->State != DAL_I2S_STATE_READY) + { + __DAL_UNLOCK(hi2s); + return DAL_BUSY; + } + + /* Set state and reset error code */ + hi2s->State = DAL_I2S_STATE_BUSY_RX; + hi2s->ErrorCode = DAL_I2S_ERROR_NONE; + hi2s->pRxBuffPtr = pData; + + tmpreg_cfgr = hi2s->Instance->I2SCFG & (SPI_I2SCFG_DATALEN | SPI_I2SCFG_CHLEN); + + if ((tmpreg_cfgr == I2S_DATAFORMAT_24B) || (tmpreg_cfgr == I2S_DATAFORMAT_32B)) + { + hi2s->RxXferSize = (Size << 1U); + hi2s->RxXferCount = (Size << 1U); + } + else + { + hi2s->RxXferSize = Size; + hi2s->RxXferCount = Size; + } + + /* Enable RXNE and ERR interrupt */ + __DAL_I2S_ENABLE_IT(hi2s, (I2S_IT_RXNE | I2S_IT_ERR)); + + /* Check if the I2S is already enabled */ + if ((hi2s->Instance->I2SCFG & SPI_I2SCFG_I2SEN) != SPI_I2SCFG_I2SEN) + { + /* Enable I2S peripheral */ + __DAL_I2S_ENABLE(hi2s); + } + + __DAL_UNLOCK(hi2s); + return DAL_OK; +} + +/** + * @brief Transmit an amount of data in non-blocking mode with DMA + * @param hi2s pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for I2S module + * @param pData a 16-bit pointer to the Transmit data buffer. + * @param Size number of data sample to be sent: + * @note When a 16-bit data frame or a 16-bit data frame extended is selected during the I2S + * configuration phase, the Size parameter means the number of 16-bit data length + * in the transaction and when a 24-bit data frame or a 32-bit data frame is selected + * the Size parameter means the number of 24-bit or 32-bit data length. + * @note The I2S is kept enabled at the end of transaction to avoid the clock de-synchronization + * between Master and Slave(example: audio streaming). + * @retval DAL status + */ +DAL_StatusTypeDef DAL_I2S_Transmit_DMA(I2S_HandleTypeDef *hi2s, uint16_t *pData, uint16_t Size) +{ + uint32_t tmpreg_cfgr; + + if ((pData == NULL) || (Size == 0U)) + { + return DAL_ERROR; + } + + /* Process Locked */ + __DAL_LOCK(hi2s); + + if (hi2s->State != DAL_I2S_STATE_READY) + { + __DAL_UNLOCK(hi2s); + return DAL_BUSY; + } + + /* Set state and reset error code */ + hi2s->State = DAL_I2S_STATE_BUSY_TX; + hi2s->ErrorCode = DAL_I2S_ERROR_NONE; + hi2s->pTxBuffPtr = pData; + + tmpreg_cfgr = hi2s->Instance->I2SCFG & (SPI_I2SCFG_DATALEN | SPI_I2SCFG_CHLEN); + + if ((tmpreg_cfgr == I2S_DATAFORMAT_24B) || (tmpreg_cfgr == I2S_DATAFORMAT_32B)) + { + hi2s->TxXferSize = (Size << 1U); + hi2s->TxXferCount = (Size << 1U); + } + else + { + hi2s->TxXferSize = Size; + hi2s->TxXferCount = Size; + } + + /* Set the I2S Tx DMA Half transfer complete callback */ + hi2s->hdmatx->XferHalfCpltCallback = I2S_DMATxHalfCplt; + + /* Set the I2S Tx DMA transfer complete callback */ + hi2s->hdmatx->XferCpltCallback = I2S_DMATxCplt; + + /* Set the DMA error callback */ + hi2s->hdmatx->XferErrorCallback = I2S_DMAError; + + /* Enable the Tx DMA Stream/Channel */ + if (DAL_OK != DAL_DMA_Start_IT(hi2s->hdmatx, + (uint32_t)hi2s->pTxBuffPtr, + (uint32_t)&hi2s->Instance->DATA, + hi2s->TxXferSize)) + { + /* Update SPI error code */ + SET_BIT(hi2s->ErrorCode, DAL_I2S_ERROR_DMA); + hi2s->State = DAL_I2S_STATE_READY; + + __DAL_UNLOCK(hi2s); + return DAL_ERROR; + } + + /* Check if the I2S is already enabled */ + if (DAL_IS_BIT_CLR(hi2s->Instance->I2SCFG, SPI_I2SCFG_I2SEN)) + { + /* Enable I2S peripheral */ + __DAL_I2S_ENABLE(hi2s); + } + + /* Check if the I2S Tx request is already enabled */ + if (DAL_IS_BIT_CLR(hi2s->Instance->CTRL2, SPI_CTRL2_TXDEN)) + { + /* Enable Tx DMA Request */ + SET_BIT(hi2s->Instance->CTRL2, SPI_CTRL2_TXDEN); + } + + __DAL_UNLOCK(hi2s); + return DAL_OK; +} + +/** + * @brief Receive an amount of data in non-blocking mode with DMA + * @param hi2s pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for I2S module + * @param pData a 16-bit pointer to the Receive data buffer. + * @param Size number of data sample to be sent: + * @note When a 16-bit data frame or a 16-bit data frame extended is selected during the I2S + * configuration phase, the Size parameter means the number of 16-bit data length + * in the transaction and when a 24-bit data frame or a 32-bit data frame is selected + * the Size parameter means the number of 24-bit or 32-bit data length. + * @note The I2S is kept enabled at the end of transaction to avoid the clock de-synchronization + * between Master and Slave(example: audio streaming). + * @retval DAL status + */ +DAL_StatusTypeDef DAL_I2S_Receive_DMA(I2S_HandleTypeDef *hi2s, uint16_t *pData, uint16_t Size) +{ + uint32_t tmpreg_cfgr; + + if ((pData == NULL) || (Size == 0U)) + { + return DAL_ERROR; + } + + /* Process Locked */ + __DAL_LOCK(hi2s); + + if (hi2s->State != DAL_I2S_STATE_READY) + { + __DAL_UNLOCK(hi2s); + return DAL_BUSY; + } + + /* Set state and reset error code */ + hi2s->State = DAL_I2S_STATE_BUSY_RX; + hi2s->ErrorCode = DAL_I2S_ERROR_NONE; + hi2s->pRxBuffPtr = pData; + + tmpreg_cfgr = hi2s->Instance->I2SCFG & (SPI_I2SCFG_DATALEN | SPI_I2SCFG_CHLEN); + + if ((tmpreg_cfgr == I2S_DATAFORMAT_24B) || (tmpreg_cfgr == I2S_DATAFORMAT_32B)) + { + hi2s->RxXferSize = (Size << 1U); + hi2s->RxXferCount = (Size << 1U); + } + else + { + hi2s->RxXferSize = Size; + hi2s->RxXferCount = Size; + } + + /* Set the I2S Rx DMA Half transfer complete callback */ + hi2s->hdmarx->XferHalfCpltCallback = I2S_DMARxHalfCplt; + + /* Set the I2S Rx DMA transfer complete callback */ + hi2s->hdmarx->XferCpltCallback = I2S_DMARxCplt; + + /* Set the DMA error callback */ + hi2s->hdmarx->XferErrorCallback = I2S_DMAError; + + /* Check if Master Receiver mode is selected */ + if ((hi2s->Instance->I2SCFG & SPI_I2SCFG_I2SMOD) == I2S_MODE_MASTER_RX) + { + /* Clear the Overrun Flag by a read operation to the SPI_DATA register followed by a read + access to the SPI_STS register. */ + __DAL_I2S_CLEAR_OVRFLAG(hi2s); + } + + /* Enable the Rx DMA Stream/Channel */ + if (DAL_OK != DAL_DMA_Start_IT(hi2s->hdmarx, (uint32_t)&hi2s->Instance->DATA, (uint32_t)hi2s->pRxBuffPtr, + hi2s->RxXferSize)) + { + /* Update SPI error code */ + SET_BIT(hi2s->ErrorCode, DAL_I2S_ERROR_DMA); + hi2s->State = DAL_I2S_STATE_READY; + + __DAL_UNLOCK(hi2s); + return DAL_ERROR; + } + + /* Check if the I2S is already enabled */ + if (DAL_IS_BIT_CLR(hi2s->Instance->I2SCFG, SPI_I2SCFG_I2SEN)) + { + /* Enable I2S peripheral */ + __DAL_I2S_ENABLE(hi2s); + } + + /* Check if the I2S Rx request is already enabled */ + if (DAL_IS_BIT_CLR(hi2s->Instance->CTRL2, SPI_CTRL2_RXDEN)) + { + /* Enable Rx DMA Request */ + SET_BIT(hi2s->Instance->CTRL2, SPI_CTRL2_RXDEN); + } + + __DAL_UNLOCK(hi2s); + return DAL_OK; +} + +/** + * @brief Pauses the audio DMA Stream/Channel playing from the Media. + * @param hi2s pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for I2S module + * @retval DAL status + */ +DAL_StatusTypeDef DAL_I2S_DMAPause(I2S_HandleTypeDef *hi2s) +{ + /* Process Locked */ + __DAL_LOCK(hi2s); + + if (hi2s->State == DAL_I2S_STATE_BUSY_TX) + { + /* Disable the I2S DMA Tx request */ + CLEAR_BIT(hi2s->Instance->CTRL2, SPI_CTRL2_TXDEN); + } + else if (hi2s->State == DAL_I2S_STATE_BUSY_RX) + { + /* Disable the I2S DMA Rx request */ + CLEAR_BIT(hi2s->Instance->CTRL2, SPI_CTRL2_RXDEN); + } +#if defined (SPI_I2S_FULLDUPLEX_SUPPORT) + else if (hi2s->State == DAL_I2S_STATE_BUSY_TX_RX) + { + /* Pause the audio file playing by disabling the I2S DMA request */ + CLEAR_BIT(hi2s->Instance->CTRL2, (SPI_CTRL2_TXDEN | SPI_CTRL2_RXDEN)); + CLEAR_BIT(I2SxEXT(hi2s->Instance)->CTRL2, (SPI_CTRL2_TXDEN | SPI_CTRL2_RXDEN)); + } +#endif /* SPI_I2S_FULLDUPLEX_SUPPORT */ + else + { + /* nothing to do */ + } + + /* Process Unlocked */ + __DAL_UNLOCK(hi2s); + + return DAL_OK; +} + +/** + * @brief Resumes the audio DMA Stream/Channel playing from the Media. + * @param hi2s pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for I2S module + * @retval DAL status + */ +DAL_StatusTypeDef DAL_I2S_DMAResume(I2S_HandleTypeDef *hi2s) +{ + /* Process Locked */ + __DAL_LOCK(hi2s); + + if (hi2s->State == DAL_I2S_STATE_BUSY_TX) + { + /* Enable the I2S DMA Tx request */ + SET_BIT(hi2s->Instance->CTRL2, SPI_CTRL2_TXDEN); + } + else if (hi2s->State == DAL_I2S_STATE_BUSY_RX) + { + /* Enable the I2S DMA Rx request */ + SET_BIT(hi2s->Instance->CTRL2, SPI_CTRL2_RXDEN); + } +#if defined (SPI_I2S_FULLDUPLEX_SUPPORT) + else if (hi2s->State == DAL_I2S_STATE_BUSY_TX_RX) + { + /* Pause the audio file playing by disabling the I2S DMA request */ + SET_BIT(hi2s->Instance->CTRL2, (SPI_CTRL2_RXDEN | SPI_CTRL2_TXDEN)); + SET_BIT(I2SxEXT(hi2s->Instance)->CTRL2, (SPI_CTRL2_RXDEN | SPI_CTRL2_TXDEN)); + + /* If the I2Sext peripheral is still not enabled, enable it */ + if ((I2SxEXT(hi2s->Instance)->I2SCFG & SPI_I2SCFG_I2SEN) == 0U) + { + /* Enable I2Sext peripheral */ + __DAL_I2SEXT_ENABLE(hi2s); + } + } +#endif /* SPI_I2S_FULLDUPLEX_SUPPORT */ + else + { + /* nothing to do */ + } + + /* If the I2S peripheral is still not enabled, enable it */ + if (DAL_IS_BIT_CLR(hi2s->Instance->I2SCFG, SPI_I2SCFG_I2SEN)) + { + /* Enable I2S peripheral */ + __DAL_I2S_ENABLE(hi2s); + } + + /* Process Unlocked */ + __DAL_UNLOCK(hi2s); + + return DAL_OK; +} + +/** + * @brief Stops the audio DMA Stream/Channel playing from the Media. + * @param hi2s pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for I2S module + * @retval DAL status + */ +DAL_StatusTypeDef DAL_I2S_DMAStop(I2S_HandleTypeDef *hi2s) +{ +#if defined (SPI_I2S_FULLDUPLEX_SUPPORT) + uint32_t tickstart; +#endif /* SPI_I2S_FULLDUPLEX_SUPPORT */ + DAL_StatusTypeDef errorcode = DAL_OK; + /* The Lock is not implemented on this API to allow the user application + to call the DAL SPI API under callbacks DAL_I2S_TxCpltCallback() or DAL_I2S_RxCpltCallback() + when calling DAL_DMA_Abort() API the DMA TX or RX Transfer complete interrupt is generated + and the correspond call back is executed DAL_I2S_TxCpltCallback() or DAL_I2S_RxCpltCallback() + */ + + if ((hi2s->Init.Mode == I2S_MODE_MASTER_TX) || (hi2s->Init.Mode == I2S_MODE_SLAVE_TX)) + { + /* Abort the I2S DMA tx Stream/Channel */ + if (hi2s->hdmatx != NULL) + { + /* Disable the I2S DMA tx Stream/Channel */ + if (DAL_OK != DAL_DMA_Abort(hi2s->hdmatx)) + { + SET_BIT(hi2s->ErrorCode, DAL_I2S_ERROR_DMA); + errorcode = DAL_ERROR; + } + } + + /* Wait until TXE flag is set */ + if (I2S_WaitFlagStateUntilTimeout(hi2s, I2S_FLAG_TXE, SET, I2S_TIMEOUT_FLAG) != DAL_OK) + { + /* Set the error code */ + SET_BIT(hi2s->ErrorCode, DAL_I2S_ERROR_TIMEOUT); + hi2s->State = DAL_I2S_STATE_READY; + errorcode = DAL_ERROR; + } + + /* Wait until BSY flag is Reset */ + if (I2S_WaitFlagStateUntilTimeout(hi2s, I2S_FLAG_BSY, RESET, I2S_TIMEOUT_FLAG) != DAL_OK) + { + /* Set the error code */ + SET_BIT(hi2s->ErrorCode, DAL_I2S_ERROR_TIMEOUT); + hi2s->State = DAL_I2S_STATE_READY; + errorcode = DAL_ERROR; + } + + /* Disable I2S peripheral */ + __DAL_I2S_DISABLE(hi2s); + + /* Clear UDR flag */ + __DAL_I2S_CLEAR_UDRFLAG(hi2s); + + /* Disable the I2S Tx DMA requests */ + CLEAR_BIT(hi2s->Instance->CTRL2, SPI_CTRL2_TXDEN); + +#if defined (SPI_I2S_FULLDUPLEX_SUPPORT) + + if (hi2s->State == DAL_I2S_STATE_BUSY_TX_RX) + { + /* Abort the I2S DMA rx Stream/Channel */ + if (hi2s->hdmarx != NULL) + { + /* Disable the I2S DMA rx Stream/Channel */ + if (DAL_OK != DAL_DMA_Abort(hi2s->hdmarx)) + { + SET_BIT(hi2s->ErrorCode, DAL_I2S_ERROR_DMA); + errorcode = DAL_ERROR; + } + } + + /* Disable I2Sext peripheral */ + __DAL_I2SEXT_DISABLE(hi2s); + + /* Clear OVR flag */ + __DAL_I2SEXT_CLEAR_OVRFLAG(hi2s); + + /* Disable the I2SxEXT DMA request */ + CLEAR_BIT(I2SxEXT(hi2s->Instance)->CTRL2, SPI_CTRL2_RXDEN); + + if (hi2s->Init.Mode == I2S_MODE_SLAVE_TX) + { + /* Set the error code */ + SET_BIT(hi2s->ErrorCode, DAL_I2S_ERROR_BUSY_LINE_RX); + + /* Set the I2S State ready */ + hi2s->State = DAL_I2S_STATE_READY; + errorcode = DAL_ERROR; + } + else + { + /* Read DATA to Flush RX Data */ + READ_REG(I2SxEXT(hi2s->Instance)->DATA); + } + } +#endif /* SPI_I2S_FULLDUPLEX_SUPPORT */ + } + + else if ((hi2s->Init.Mode == I2S_MODE_MASTER_RX) || (hi2s->Init.Mode == I2S_MODE_SLAVE_RX)) + { + /* Abort the I2S DMA rx Stream/Channel */ + if (hi2s->hdmarx != NULL) + { + /* Disable the I2S DMA rx Stream/Channel */ + if (DAL_OK != DAL_DMA_Abort(hi2s->hdmarx)) + { + SET_BIT(hi2s->ErrorCode, DAL_I2S_ERROR_DMA); + errorcode = DAL_ERROR; + } + } +#if defined (SPI_I2S_FULLDUPLEX_SUPPORT) + + if (hi2s->State == DAL_I2S_STATE_BUSY_TX_RX) + { + /* Abort the I2S DMA tx Stream/Channel */ + if (hi2s->hdmatx != NULL) + { + /* Disable the I2S DMA tx Stream/Channel */ + if (DAL_OK != DAL_DMA_Abort(hi2s->hdmatx)) + { + SET_BIT(hi2s->ErrorCode, DAL_I2S_ERROR_DMA); + errorcode = DAL_ERROR; + } + } + + tickstart = DAL_GetTick(); + + /* Wait until TXE flag is set */ + while (__DAL_I2SEXT_GET_FLAG(hi2s, I2S_FLAG_TXE) != SET) + { + if (((DAL_GetTick() - tickstart) > I2S_TIMEOUT_FLAG)) + { + /* Set the error code */ + SET_BIT(hi2s->ErrorCode, DAL_I2S_ERROR_TIMEOUT); + + /* Set the I2S State ready */ + hi2s->State = DAL_I2S_STATE_READY; + errorcode = DAL_ERROR; + } + } + + /* Wait until BSY flag is Reset */ + while (__DAL_I2SEXT_GET_FLAG(hi2s, I2S_FLAG_BSY) != RESET) + { + if (((DAL_GetTick() - tickstart) > I2S_TIMEOUT_FLAG)) + { + /* Set the error code */ + SET_BIT(hi2s->ErrorCode, DAL_I2S_ERROR_TIMEOUT); + + /* Set the I2S State ready */ + hi2s->State = DAL_I2S_STATE_READY; + errorcode = DAL_ERROR; + } + } + + /* Disable I2Sext peripheral */ + __DAL_I2SEXT_DISABLE(hi2s); + + /* Clear UDR flag */ + __DAL_I2SEXT_CLEAR_UDRFLAG(hi2s); + + /* Disable the I2SxEXT DMA request */ + CLEAR_BIT(I2SxEXT(hi2s->Instance)->CTRL2, SPI_CTRL2_TXDEN); + } +#endif /* SPI_I2S_FULLDUPLEX_SUPPORT */ + + /* Disable I2S peripheral */ + __DAL_I2S_DISABLE(hi2s); + + /* Clear OVR flag */ + __DAL_I2S_CLEAR_OVRFLAG(hi2s); + + /* Disable the I2S Rx DMA request */ + CLEAR_BIT(hi2s->Instance->CTRL2, SPI_CTRL2_RXDEN); + + if (hi2s->Init.Mode == I2S_MODE_SLAVE_RX) + { + /* Set the error code */ + SET_BIT(hi2s->ErrorCode, DAL_I2S_ERROR_BUSY_LINE_RX); + + /* Set the I2S State ready */ + hi2s->State = DAL_I2S_STATE_READY; + errorcode = DAL_ERROR; + } + else + { + /* Read DATA to Flush RX Data */ + READ_REG((hi2s->Instance)->DATA); + } + } + + hi2s->State = DAL_I2S_STATE_READY; + + return errorcode; +} + +/** + * @brief This function handles I2S interrupt request. + * @param hi2s pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for I2S module + * @retval None + */ +void DAL_I2S_IRQHandler(I2S_HandleTypeDef *hi2s) +{ + /* Call the IrqHandler ISR set during DAL_I2S_INIT */ + hi2s->IrqHandlerISR(hi2s); +} + +/** + * @brief Tx Transfer Half completed callbacks + * @param hi2s pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for I2S module + * @retval None + */ +__weak void DAL_I2S_TxHalfCpltCallback(I2S_HandleTypeDef *hi2s) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hi2s); + + /* NOTE : This function Should not be modified, when the callback is needed, + the DAL_I2S_TxHalfCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Tx Transfer completed callbacks + * @param hi2s pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for I2S module + * @retval None + */ +__weak void DAL_I2S_TxCpltCallback(I2S_HandleTypeDef *hi2s) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hi2s); + + /* NOTE : This function Should not be modified, when the callback is needed, + the DAL_I2S_TxCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Rx Transfer half completed callbacks + * @param hi2s pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for I2S module + * @retval None + */ +__weak void DAL_I2S_RxHalfCpltCallback(I2S_HandleTypeDef *hi2s) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hi2s); + + /* NOTE : This function Should not be modified, when the callback is needed, + the DAL_I2S_RxHalfCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Rx Transfer completed callbacks + * @param hi2s pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for I2S module + * @retval None + */ +__weak void DAL_I2S_RxCpltCallback(I2S_HandleTypeDef *hi2s) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hi2s); + + /* NOTE : This function Should not be modified, when the callback is needed, + the DAL_I2S_RxCpltCallback could be implemented in the user file + */ +} + +/** + * @brief I2S error callbacks + * @param hi2s pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for I2S module + * @retval None + */ +__weak void DAL_I2S_ErrorCallback(I2S_HandleTypeDef *hi2s) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hi2s); + + /* NOTE : This function Should not be modified, when the callback is needed, + the DAL_I2S_ErrorCallback could be implemented in the user file + */ +} + +/** + * @} + */ + +/** @defgroup I2S_Exported_Functions_Group3 Peripheral State and Errors functions + * @brief Peripheral State functions + * +@verbatim + =============================================================================== + ##### Peripheral State and Errors functions ##### + =============================================================================== + [..] + This subsection permits to get in run-time the status of the peripheral + and the data flow. + +@endverbatim + * @{ + */ + +/** + * @brief Return the I2S state + * @param hi2s pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for I2S module + * @retval DAL state + */ +DAL_I2S_StateTypeDef DAL_I2S_GetState(I2S_HandleTypeDef *hi2s) +{ + return hi2s->State; +} + +/** + * @brief Return the I2S error code + * @param hi2s pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for I2S module + * @retval I2S Error Code + */ +uint32_t DAL_I2S_GetError(I2S_HandleTypeDef *hi2s) +{ + return hi2s->ErrorCode; +} +/** + * @} + */ + +/** + * @} + */ + +/** @addtogroup I2S_Private_Functions I2S Private Functions + * @{ + */ +/** + * @brief DMA I2S transmit process complete callback + * @param hdma pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +static void I2S_DMATxCplt(DMA_HandleTypeDef *hdma) +{ + I2S_HandleTypeDef *hi2s = (I2S_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; /* Derogation MISRAC2012-Rule-11.5 */ + + /* if DMA is configured in DMA_NORMAL Mode */ + if (hdma->Init.Mode == DMA_NORMAL) + { + /* Disable Tx DMA Request */ + CLEAR_BIT(hi2s->Instance->CTRL2, SPI_CTRL2_TXDEN); + + hi2s->TxXferCount = 0U; + hi2s->State = DAL_I2S_STATE_READY; + } + /* Call user Tx complete callback */ +#if (USE_DAL_I2S_REGISTER_CALLBACKS == 1U) + hi2s->TxCpltCallback(hi2s); +#else + DAL_I2S_TxCpltCallback(hi2s); +#endif /* USE_DAL_I2S_REGISTER_CALLBACKS */ +} + +/** + * @brief DMA I2S transmit process half complete callback + * @param hdma pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +static void I2S_DMATxHalfCplt(DMA_HandleTypeDef *hdma) +{ + I2S_HandleTypeDef *hi2s = (I2S_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; /* Derogation MISRAC2012-Rule-11.5 */ + + /* Call user Tx half complete callback */ +#if (USE_DAL_I2S_REGISTER_CALLBACKS == 1U) + hi2s->TxHalfCpltCallback(hi2s); +#else + DAL_I2S_TxHalfCpltCallback(hi2s); +#endif /* USE_DAL_I2S_REGISTER_CALLBACKS */ +} + +/** + * @brief DMA I2S receive process complete callback + * @param hdma pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +static void I2S_DMARxCplt(DMA_HandleTypeDef *hdma) +{ + I2S_HandleTypeDef *hi2s = (I2S_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; /* Derogation MISRAC2012-Rule-11.5 */ + + /* if DMA is configured in DMA_NORMAL Mode */ + if (hdma->Init.Mode == DMA_NORMAL) + { + /* Disable Rx DMA Request */ + CLEAR_BIT(hi2s->Instance->CTRL2, SPI_CTRL2_RXDEN); + hi2s->RxXferCount = 0U; + hi2s->State = DAL_I2S_STATE_READY; + } + /* Call user Rx complete callback */ +#if (USE_DAL_I2S_REGISTER_CALLBACKS == 1U) + hi2s->RxCpltCallback(hi2s); +#else + DAL_I2S_RxCpltCallback(hi2s); +#endif /* USE_DAL_I2S_REGISTER_CALLBACKS */ +} + +/** + * @brief DMA I2S receive process half complete callback + * @param hdma pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +static void I2S_DMARxHalfCplt(DMA_HandleTypeDef *hdma) +{ + I2S_HandleTypeDef *hi2s = (I2S_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; /* Derogation MISRAC2012-Rule-11.5 */ + + /* Call user Rx half complete callback */ +#if (USE_DAL_I2S_REGISTER_CALLBACKS == 1U) + hi2s->RxHalfCpltCallback(hi2s); +#else + DAL_I2S_RxHalfCpltCallback(hi2s); +#endif /* USE_DAL_I2S_REGISTER_CALLBACKS */ +} + +/** + * @brief DMA I2S communication error callback + * @param hdma pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +static void I2S_DMAError(DMA_HandleTypeDef *hdma) +{ + I2S_HandleTypeDef *hi2s = (I2S_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; /* Derogation MISRAC2012-Rule-11.5 */ + + /* Disable Rx and Tx DMA Request */ + CLEAR_BIT(hi2s->Instance->CTRL2, (SPI_CTRL2_RXDEN | SPI_CTRL2_TXDEN)); + hi2s->TxXferCount = 0U; + hi2s->RxXferCount = 0U; + + hi2s->State = DAL_I2S_STATE_READY; + + /* Set the error code and execute error callback*/ + SET_BIT(hi2s->ErrorCode, DAL_I2S_ERROR_DMA); + /* Call user error callback */ +#if (USE_DAL_I2S_REGISTER_CALLBACKS == 1U) + hi2s->ErrorCallback(hi2s); +#else + DAL_I2S_ErrorCallback(hi2s); +#endif /* USE_DAL_I2S_REGISTER_CALLBACKS */ +} + +/** + * @brief Transmit an amount of data in non-blocking mode with Interrupt + * @param hi2s pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for I2S module + * @retval None + */ +static void I2S_Transmit_IT(I2S_HandleTypeDef *hi2s) +{ + /* Transmit data */ + hi2s->Instance->DATA = (*hi2s->pTxBuffPtr); + hi2s->pTxBuffPtr++; + hi2s->TxXferCount--; + + if (hi2s->TxXferCount == 0U) + { + /* Disable TXE and ERR interrupt */ + __DAL_I2S_DISABLE_IT(hi2s, (I2S_IT_TXE | I2S_IT_ERR)); + + hi2s->State = DAL_I2S_STATE_READY; + /* Call user Tx complete callback */ +#if (USE_DAL_I2S_REGISTER_CALLBACKS == 1U) + hi2s->TxCpltCallback(hi2s); +#else + DAL_I2S_TxCpltCallback(hi2s); +#endif /* USE_DAL_I2S_REGISTER_CALLBACKS */ + } +} + +/** + * @brief Receive an amount of data in non-blocking mode with Interrupt + * @param hi2s pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for I2S module + * @retval None + */ +static void I2S_Receive_IT(I2S_HandleTypeDef *hi2s) +{ + /* Receive data */ + (*hi2s->pRxBuffPtr) = (uint16_t)hi2s->Instance->DATA; + hi2s->pRxBuffPtr++; + hi2s->RxXferCount--; + + if (hi2s->RxXferCount == 0U) + { + /* Disable RXNE and ERR interrupt */ + __DAL_I2S_DISABLE_IT(hi2s, (I2S_IT_RXNE | I2S_IT_ERR)); + + hi2s->State = DAL_I2S_STATE_READY; + /* Call user Rx complete callback */ +#if (USE_DAL_I2S_REGISTER_CALLBACKS == 1U) + hi2s->RxCpltCallback(hi2s); +#else + DAL_I2S_RxCpltCallback(hi2s); +#endif /* USE_DAL_I2S_REGISTER_CALLBACKS */ + } +} + +/** + * @brief This function handles I2S interrupt request. + * @param hi2s: pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for I2S module + * @retval None + */ +static void I2S_IRQHandler(I2S_HandleTypeDef *hi2s) +{ + __IO uint32_t i2ssr = hi2s->Instance->STS; + + if (hi2s->State == DAL_I2S_STATE_BUSY_RX) + { + /* I2S in mode Receiver ------------------------------------------------*/ + if (((i2ssr & I2S_FLAG_RXNE) == I2S_FLAG_RXNE) && (__DAL_I2S_GET_IT_SOURCE(hi2s, I2S_IT_RXNE) != RESET)) + { + I2S_Receive_IT(hi2s); + } + + /* I2S Overrun error interrupt occurred -------------------------------------*/ + if (((i2ssr & I2S_FLAG_OVR) == I2S_FLAG_OVR) && (__DAL_I2S_GET_IT_SOURCE(hi2s, I2S_IT_ERR) != RESET)) + { + /* Disable RXNE and ERR interrupt */ + __DAL_I2S_DISABLE_IT(hi2s, (I2S_IT_RXNE | I2S_IT_ERR)); + + /* Clear Overrun flag */ + __DAL_I2S_CLEAR_OVRFLAG(hi2s); + + /* Set the I2S State ready */ + hi2s->State = DAL_I2S_STATE_READY; + + + /* Set the error code and execute error callback*/ + SET_BIT(hi2s->ErrorCode, DAL_I2S_ERROR_OVR); + /* Call user error callback */ +#if (USE_DAL_I2S_REGISTER_CALLBACKS == 1U) + hi2s->ErrorCallback(hi2s); +#else + DAL_I2S_ErrorCallback(hi2s); +#endif /* USE_DAL_I2S_REGISTER_CALLBACKS */ + } + } + + if (hi2s->State == DAL_I2S_STATE_BUSY_TX) + { + /* I2S in mode Transmitter -----------------------------------------------*/ + if (((i2ssr & I2S_FLAG_TXE) == I2S_FLAG_TXE) && (__DAL_I2S_GET_IT_SOURCE(hi2s, I2S_IT_TXE) != RESET)) + { + I2S_Transmit_IT(hi2s); + } + + /* I2S Underrun error interrupt occurred --------------------------------*/ + if (((i2ssr & I2S_FLAG_UDR) == I2S_FLAG_UDR) && (__DAL_I2S_GET_IT_SOURCE(hi2s, I2S_IT_ERR) != RESET)) + { + /* Disable TXE and ERR interrupt */ + __DAL_I2S_DISABLE_IT(hi2s, (I2S_IT_TXE | I2S_IT_ERR)); + + /* Clear Underrun flag */ + __DAL_I2S_CLEAR_UDRFLAG(hi2s); + + /* Set the I2S State ready */ + hi2s->State = DAL_I2S_STATE_READY; + + /* Set the error code and execute error callback*/ + SET_BIT(hi2s->ErrorCode, DAL_I2S_ERROR_UDR); + /* Call user error callback */ +#if (USE_DAL_I2S_REGISTER_CALLBACKS == 1U) + hi2s->ErrorCallback(hi2s); +#else + DAL_I2S_ErrorCallback(hi2s); +#endif /* USE_DAL_I2S_REGISTER_CALLBACKS */ + } + } +} + +/** + * @brief This function handles I2S Communication Timeout. + * @param hi2s pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for I2S module + * @param Flag Flag checked + * @param State Value of the flag expected + * @param Timeout Duration of the timeout + * @retval DAL status + */ +static DAL_StatusTypeDef I2S_WaitFlagStateUntilTimeout(I2S_HandleTypeDef *hi2s, uint32_t Flag, FlagStatus State, + uint32_t Timeout) +{ + uint32_t tickstart; + + /* Get tick */ + tickstart = DAL_GetTick(); + + /* Wait until flag is set to status*/ + while (((__DAL_I2S_GET_FLAG(hi2s, Flag)) ? SET : RESET) != State) + { + if (Timeout != DAL_MAX_DELAY) + { + if (((DAL_GetTick() - tickstart) >= Timeout) || (Timeout == 0U)) + { + /* Set the I2S State ready */ + hi2s->State = DAL_I2S_STATE_READY; + + /* Process Unlocked */ + __DAL_UNLOCK(hi2s); + + return DAL_TIMEOUT; + } + } + } + return DAL_OK; +} + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#endif /* DAL_I2S_MODULE_ENABLED */ + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_i2s_ex.c b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_i2s_ex.c new file mode 100644 index 0000000000..2558165109 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_i2s_ex.c @@ -0,0 +1,1160 @@ +/** + * + * @file apm32f4xx_dal_i2s_ex.c + * @brief I2S DAL module driver. + * This file provides firmware functions to manage the following + * functionalities of I2S extension peripheral: + * + Extension features Functions + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + * + @verbatim + ============================================================================== + ##### I2S Extension features ##### + ============================================================================== + [..] + (#) In I2S full duplex mode, each SPI peripheral is able to manage sending and receiving + data simultaneously using two data lines. Each SPI peripheral has an extended block + called I2Sxext (i.e I2S2ext for SPI2 and I2S3ext for SPI3). + (#) The extension block is not a full SPI IP, it is used only as I2S slave to + implement full duplex mode. The extension block uses the same clock sources + as its master. + + (#) Both I2Sx and I2Sx_ext can be configured as transmitters or receivers. + + [..] + (@) Only I2Sx can deliver SCK and WS to I2Sx_ext in full duplex mode, where + I2Sx can be I2S2 or I2S3. + + ##### How to use this driver ##### + =============================================================================== + [..] + Three operation modes are available within this driver : + + *** Polling mode IO operation *** + ================================= + [..] + (+) Send and receive in the same time an amount of data in blocking mode using DAL_I2SEx_TransmitReceive() + + *** Interrupt mode IO operation *** + =================================== + [..] + (+) Send and receive in the same time an amount of data in non blocking mode using DAL_I2SEx_TransmitReceive_IT() + (+) At transmission/reception end of transfer DAL_I2SEx_TxRxCpltCallback is executed and user can + add his own code by customization of function pointer DAL_I2SEx_TxRxCpltCallback + (+) In case of transfer Error, DAL_I2S_ErrorCallback() function is executed and user can + add his own code by customization of function pointer DAL_I2S_ErrorCallback + + *** DMA mode IO operation *** + ============================== + [..] + (+) Send and receive an amount of data in non blocking mode (DMA) using DAL_I2SEx_TransmitReceive_DMA() + (+) At transmission/reception end of transfer DAL_I2SEx_TxRxCpltCallback is executed and user can + add his own code by customization of function pointer DAL_I2S_TxRxCpltCallback + (+) In case of transfer Error, DAL_I2S_ErrorCallback() function is executed and user can + add his own code by customization of function pointer DAL_I2S_ErrorCallback + (+) __DAL_I2SEXT_FLUSH_RX_DR: In Full-Duplex Slave mode, if DAL_I2S_DMAStop is used to stop the + communication, an error DAL_I2S_ERROR_BUSY_LINE_RX is raised as the master continue to transmit data. + In this case __DAL_I2SEXT_FLUSH_RX_DR macro must be used to flush the remaining data + inside I2Sx and I2Sx_ext DATA registers and avoid using DeInit/Init process for the next transfer. + @endverbatim + + Additional Figure: The Extended block uses the same clock sources as its master. + + +-----------------------+ + I2Sx_SCK | | + ----------+-->| I2Sx |------------------->I2Sx_SD(in/out) + +--|-->| | + | | +-----------------------+ + | | + I2S_WS | | + ------>| | + | | +-----------------------+ + | +-->| | + | | I2Sx_ext |------------------->I2Sx_extSD(in/out) + +----->| | + +-----------------------+ + */ + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +#ifdef DAL_I2S_MODULE_ENABLED + +/** @defgroup I2SEx I2SEx + * @brief I2S Extended DAL module driver + * @{ + */ + +#if defined (SPI_I2S_FULLDUPLEX_SUPPORT) + +/* Private typedef -----------------------------------------------------------*/ +/** @defgroup I2SEx_Private_Typedef I2S Extended Private Typedef + * @{ + */ +typedef enum +{ + I2S_USE_I2S = 0x00U, /*!< I2Sx should be used */ + I2S_USE_I2SEXT = 0x01U, /*!< I2Sx_ext should be used */ +} I2S_UseTypeDef; +/** + * @} + */ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/** @defgroup I2SEx_Private_Functions I2S Extended Private Functions + * @{ + */ +static void I2SEx_TxRxDMAHalfCplt(DMA_HandleTypeDef *hdma); +static void I2SEx_TxRxDMACplt(DMA_HandleTypeDef *hdma); +static void I2SEx_TxRxDMAError(DMA_HandleTypeDef *hdma); +static void I2SEx_RxISR_I2S(I2S_HandleTypeDef *hi2s); +static void I2SEx_RxISR_I2SExt(I2S_HandleTypeDef *hi2s); +static void I2SEx_TxISR_I2S(I2S_HandleTypeDef *hi2s); +static void I2SEx_TxISR_I2SExt(I2S_HandleTypeDef *hi2s); +static DAL_StatusTypeDef I2SEx_FullDuplexWaitFlagStateUntilTimeout(I2S_HandleTypeDef *hi2s, + uint32_t Flag, + uint32_t State, + uint32_t Timeout, + I2S_UseTypeDef i2sUsed); +/** + * @} + */ + +/** + * @} + */ + +/* Private functions ---------------------------------------------------------*/ +/* Exported functions --------------------------------------------------------*/ + +/** @addtogroup I2SEx I2SEx + * @{ + */ + +/** @addtogroup I2SEx_Exported_Functions I2S Extended Exported Functions + * @{ + */ + +/** @defgroup I2SEx_Exported_Functions_Group1 I2S Extended IO operation functions + * @brief I2SEx IO operation functions + * +@verbatim + =============================================================================== + ##### IO operation functions##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to manage the I2S data + transfers. + + (#) There are two modes of transfer: + (++) Blocking mode : The communication is performed in the polling mode. + The status of all data processing is returned by the same function + after finishing transfer. + (++) No-Blocking mode : The communication is performed using Interrupts + or DMA. These functions return the status of the transfer startup. + The end of the data processing will be indicated through the + dedicated I2S IRQ when using Interrupt mode or the DMA IRQ when + using DMA mode. + + (#) Blocking mode functions are : + (++) DAL_I2SEx_TransmitReceive() + + (#) No-Blocking mode functions with Interrupt are : + (++) DAL_I2SEx_TransmitReceive_IT() + (++) DAL_I2SEx_FullDuplex_IRQHandler() + + (#) No-Blocking mode functions with DMA are : + (++) DAL_I2SEx_TransmitReceive_DMA() + + (#) A set of Transfer Complete Callback are provided in non Blocking mode: + (++) DAL_I2SEx_TxRxCpltCallback() +@endverbatim + * @{ + */ +/** + * @brief Full-Duplex Transmit/Receive data in blocking mode. + * @param hi2s pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for I2S module + * @param pTxData a 16-bit pointer to the Transmit data buffer. + * @param pRxData a 16-bit pointer to the Receive data buffer. + * @param Size number of data sample to be sent: + * @note When a 16-bit data frame or a 16-bit data frame extended is selected during the I2S + * configuration phase, the Size parameter means the number of 16-bit data length + * in the transaction and when a 24-bit data frame or a 32-bit data frame is selected + * the Size parameter means the number of 16-bit data length. + * @param Timeout Timeout duration + * @note The I2S is kept enabled at the end of transaction to avoid the clock de-synchronization + * between Master and Slave(example: audio streaming). + * @retval DAL status + */ +DAL_StatusTypeDef DAL_I2SEx_TransmitReceive(I2S_HandleTypeDef *hi2s, + uint16_t *pTxData, + uint16_t *pRxData, + uint16_t Size, + uint32_t Timeout) +{ + uint32_t tmp1 = 0U; + DAL_StatusTypeDef errorcode = DAL_OK; + + if (hi2s->State != DAL_I2S_STATE_READY) + { + errorcode = DAL_BUSY; + goto error; + } + + if ((pTxData == NULL) || (pRxData == NULL) || (Size == 0U)) + { + return DAL_ERROR; + } + + /* Process Locked */ + __DAL_LOCK(hi2s); + + tmp1 = hi2s->Instance->I2SCFG & (SPI_I2SCFG_DATALEN | SPI_I2SCFG_CHLEN); + /* Check the Data format: When a 16-bit data frame or a 16-bit data frame extended + is selected during the I2S configuration phase, the Size parameter means the number + of 16-bit data length in the transaction and when a 24-bit data frame or a 32-bit data + frame is selected the Size parameter means the number of 16-bit data length. */ + if ((tmp1 == I2S_DATAFORMAT_24B) || (tmp1 == I2S_DATAFORMAT_32B)) + { + hi2s->TxXferSize = (Size << 1U); + hi2s->TxXferCount = (Size << 1U); + hi2s->RxXferSize = (Size << 1U); + hi2s->RxXferCount = (Size << 1U); + } + else + { + hi2s->TxXferSize = Size; + hi2s->TxXferCount = Size; + hi2s->RxXferSize = Size; + hi2s->RxXferCount = Size; + } + + /* Set state and reset error code */ + hi2s->ErrorCode = DAL_I2S_ERROR_NONE; + hi2s->State = DAL_I2S_STATE_BUSY_TX_RX; + + tmp1 = hi2s->Instance->I2SCFG & SPI_I2SCFG_I2SMOD; + /* Check if the I2S_MODE_MASTER_TX or I2S_MODE_SLAVE_TX Mode is selected */ + if ((tmp1 == I2S_MODE_MASTER_TX) || (tmp1 == I2S_MODE_SLAVE_TX)) + { + /* Prepare the First Data before enabling the I2S */ + hi2s->Instance->DATA = (*pTxData++); + hi2s->TxXferCount--; + + /* Enable I2Sext(receiver) before enabling I2Sx peripheral */ + __DAL_I2SEXT_ENABLE(hi2s); + + /* Enable I2Sx peripheral */ + __DAL_I2S_ENABLE(hi2s); + + /* Check if Master Receiver mode is selected */ + if ((hi2s->Instance->I2SCFG & SPI_I2SCFG_I2SMOD) == I2S_MODE_MASTER_TX) + { + /* Clear the Overrun Flag by a read operation on the SPI_DATA register followed by a read + access to the SPI_STS register. */ + __DAL_I2SEXT_CLEAR_OVRFLAG(hi2s); + } + + while ((hi2s->RxXferCount > 0U) || (hi2s->TxXferCount > 0U)) + { + if (hi2s->TxXferCount > 0U) + { + /* Wait until TXE flag is set */ + if (I2SEx_FullDuplexWaitFlagStateUntilTimeout(hi2s, I2S_FLAG_TXE, SET, Timeout, I2S_USE_I2S) != DAL_OK) + { + /* Set the error code */ + SET_BIT(hi2s->ErrorCode, DAL_I2S_ERROR_TIMEOUT); + errorcode = DAL_ERROR; + goto error; + } + /* Write Data on DATA register */ + hi2s->Instance->DATA = (*pTxData++); + hi2s->TxXferCount--; + + /* Check if an underrun occurs */ + if ((__DAL_I2S_GET_FLAG(hi2s, I2S_FLAG_UDR) == SET) && (tmp1 == I2S_MODE_SLAVE_TX)) + { + /* Clear Underrun flag */ + __DAL_I2S_CLEAR_UDRFLAG(hi2s); + + /* Set the error code */ + SET_BIT(hi2s->ErrorCode, DAL_I2S_ERROR_UDR); + } + } + if (hi2s->RxXferCount > 0U) + { + /* Wait until RXNE flag is set */ + if (I2SEx_FullDuplexWaitFlagStateUntilTimeout(hi2s, I2S_FLAG_RXNE, SET, Timeout, I2S_USE_I2SEXT) != DAL_OK) + { + /* Set the error code */ + SET_BIT(hi2s->ErrorCode, DAL_I2S_ERROR_TIMEOUT); + errorcode = DAL_ERROR; + goto error; + } + /* Read Data from DATA register */ + (*pRxData++) = I2SxEXT(hi2s->Instance)->DATA; + hi2s->RxXferCount--; + + /* Check if an overrun occurs */ + if (__DAL_I2SEXT_GET_FLAG(hi2s, I2S_FLAG_OVR) == SET) + { + /* Clear Overrun flag */ + __DAL_I2S_CLEAR_OVRFLAG(hi2s); + + /* Set the error code */ + SET_BIT(hi2s->ErrorCode, DAL_I2S_ERROR_OVR); + } + } + } + } + /* The I2S_MODE_MASTER_RX or I2S_MODE_SLAVE_RX Mode is selected */ + else + { + /* Prepare the First Data before enabling the I2S */ + I2SxEXT(hi2s->Instance)->DATA = (*pTxData++); + hi2s->TxXferCount--; + + /* Enable I2Sext(transmitter) after enabling I2Sx peripheral */ + __DAL_I2SEXT_ENABLE(hi2s); + + /* Enable I2S peripheral before the I2Sext*/ + __DAL_I2S_ENABLE(hi2s); + + /* Check if Master Receiver mode is selected */ + if ((hi2s->Instance->I2SCFG & SPI_I2SCFG_I2SMOD) == I2S_MODE_MASTER_RX) + { + /* Clear the Overrun Flag by a read operation on the SPI_DATA register followed by a read + access to the SPI_STS register. */ + __DAL_I2S_CLEAR_OVRFLAG(hi2s); + } + + while ((hi2s->RxXferCount > 0U) || (hi2s->TxXferCount > 0U)) + { + if (hi2s->TxXferCount > 0U) + { + /* Wait until TXE flag is set */ + if (I2SEx_FullDuplexWaitFlagStateUntilTimeout(hi2s, I2S_FLAG_TXE, SET, Timeout, I2S_USE_I2SEXT) != DAL_OK) + { + /* Set the error code */ + SET_BIT(hi2s->ErrorCode, DAL_I2S_ERROR_TIMEOUT); + errorcode = DAL_ERROR; + goto error; + } + /* Write Data on DATA register */ + I2SxEXT(hi2s->Instance)->DATA = (*pTxData++); + hi2s->TxXferCount--; + + /* Check if an underrun occurs */ + if ((__DAL_I2SEXT_GET_FLAG(hi2s, I2S_FLAG_UDR) == SET) && (tmp1 == I2S_MODE_SLAVE_RX)) + { + /* Clear Underrun flag */ + __DAL_I2S_CLEAR_UDRFLAG(hi2s); + + /* Set the error code */ + SET_BIT(hi2s->ErrorCode, DAL_I2S_ERROR_UDR); + } + } + if (hi2s->RxXferCount > 0U) + { + /* Wait until RXNE flag is set */ + if (I2SEx_FullDuplexWaitFlagStateUntilTimeout(hi2s, I2S_FLAG_RXNE, SET, Timeout, I2S_USE_I2S) != DAL_OK) + { + /* Set the error code */ + SET_BIT(hi2s->ErrorCode, DAL_I2S_ERROR_TIMEOUT); + errorcode = DAL_ERROR; + goto error; + } + /* Read Data from DATA register */ + (*pRxData++) = hi2s->Instance->DATA; + hi2s->RxXferCount--; + + /* Check if an overrun occurs */ + if (__DAL_I2S_GET_FLAG(hi2s, I2S_FLAG_OVR) == SET) + { + /* Clear Overrun flag */ + __DAL_I2S_CLEAR_OVRFLAG(hi2s); + + /* Set the error code */ + SET_BIT(hi2s->ErrorCode, DAL_I2S_ERROR_OVR); + } + } + } + } + + if (hi2s->ErrorCode != DAL_I2S_ERROR_NONE) + { + errorcode = DAL_ERROR; + } + +error : + hi2s->State = DAL_I2S_STATE_READY; + __DAL_UNLOCK(hi2s); + return errorcode; +} + +/** + * @brief Full-Duplex Transmit/Receive data in non-blocking mode using Interrupt + * @param hi2s pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for I2S module + * @param pTxData a 16-bit pointer to the Transmit data buffer. + * @param pRxData a 16-bit pointer to the Receive data buffer. + * @param Size number of data sample to be sent: + * @note When a 16-bit data frame or a 16-bit data frame extended is selected during the I2S + * configuration phase, the Size parameter means the number of 16-bit data length + * in the transaction and when a 24-bit data frame or a 32-bit data frame is selected + * the Size parameter means the number of 16-bit data length. + * @note The I2S is kept enabled at the end of transaction to avoid the clock de-synchronization + * between Master and Slave(example: audio streaming). + * @retval DAL status + */ +DAL_StatusTypeDef DAL_I2SEx_TransmitReceive_IT(I2S_HandleTypeDef *hi2s, + uint16_t *pTxData, + uint16_t *pRxData, + uint16_t Size) +{ + uint32_t tmp1 = 0U; + DAL_StatusTypeDef errorcode = DAL_OK; + + if (hi2s->State != DAL_I2S_STATE_READY) + { + errorcode = DAL_BUSY; + goto error; + } + + if ((pTxData == NULL) || (pRxData == NULL) || (Size == 0U)) + { + return DAL_ERROR; + } + + /* Process Locked */ + __DAL_LOCK(hi2s); + + hi2s->pTxBuffPtr = pTxData; + hi2s->pRxBuffPtr = pRxData; + + tmp1 = hi2s->Instance->I2SCFG & (SPI_I2SCFG_DATALEN | SPI_I2SCFG_CHLEN); + /* Check the Data format: When a 16-bit data frame or a 16-bit data frame extended + is selected during the I2S configuration phase, the Size parameter means the number + of 16-bit data length in the transaction and when a 24-bit data frame or a 32-bit data + frame is selected the Size parameter means the number of 16-bit data length. */ + if ((tmp1 == I2S_DATAFORMAT_24B) || (tmp1 == I2S_DATAFORMAT_32B)) + { + hi2s->TxXferSize = (Size << 1U); + hi2s->TxXferCount = (Size << 1U); + hi2s->RxXferSize = (Size << 1U); + hi2s->RxXferCount = (Size << 1U); + } + else + { + hi2s->TxXferSize = Size; + hi2s->TxXferCount = Size; + hi2s->RxXferSize = Size; + hi2s->RxXferCount = Size; + } + + hi2s->ErrorCode = DAL_I2S_ERROR_NONE; + hi2s->State = DAL_I2S_STATE_BUSY_TX_RX; + + /* Set the function for IT treatment */ + if ((hi2s->Init.Mode == I2S_MODE_MASTER_TX) || (hi2s->Init.Mode == I2S_MODE_SLAVE_TX)) + { + /* Enable I2Sext RXNE and ERR interrupts */ + __DAL_I2SEXT_ENABLE_IT(hi2s, (I2S_IT_RXNE | I2S_IT_ERR)); + + /* Enable I2Sx TXE and ERR interrupts */ + __DAL_I2S_ENABLE_IT(hi2s, (I2S_IT_TXE | I2S_IT_ERR)); + + /* Transmit First data */ + hi2s->Instance->DATA = (*hi2s->pTxBuffPtr++); + hi2s->TxXferCount--; + + if (hi2s->TxXferCount == 0U) + { + /* Disable TXE and ERR interrupt */ + __DAL_I2S_DISABLE_IT(hi2s, (I2S_IT_TXE | I2S_IT_ERR)); + } + } + else /* The I2S_MODE_MASTER_RX or I2S_MODE_SLAVE_RX Mode is selected */ + { + /* Enable I2Sext TXE and ERR interrupts */ + __DAL_I2SEXT_ENABLE_IT(hi2s, (I2S_IT_TXE | I2S_IT_ERR)); + + /* Enable I2Sext RXNE and ERR interrupts */ + __DAL_I2S_ENABLE_IT(hi2s, (I2S_IT_RXNE | I2S_IT_ERR)); + + /* Transmit First data */ + I2SxEXT(hi2s->Instance)->DATA = (*hi2s->pTxBuffPtr++); + hi2s->TxXferCount--; + + if (hi2s->TxXferCount == 0U) + { + /* Disable I2Sext TXE and ERR interrupt */ + __DAL_I2SEXT_DISABLE_IT(hi2s, (I2S_IT_TXE | I2S_IT_ERR)); + } + } + + /* Enable I2Sext peripheral */ + __DAL_I2SEXT_ENABLE(hi2s); + + /* Enable I2S peripheral */ + __DAL_I2S_ENABLE(hi2s); + +error : + __DAL_UNLOCK(hi2s); + return errorcode; +} + +/** + * @brief Full-Duplex Transmit/Receive data in non-blocking mode using DMA + * @param hi2s pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for I2S module + * @param pTxData a 16-bit pointer to the Transmit data buffer. + * @param pRxData a 16-bit pointer to the Receive data buffer. + * @param Size number of data sample to be sent: + * @note When a 16-bit data frame or a 16-bit data frame extended is selected during the I2S + * configuration phase, the Size parameter means the number of 16-bit data length + * in the transaction and when a 24-bit data frame or a 32-bit data frame is selected + * the Size parameter means the number of 16-bit data length. + * @note The I2S is kept enabled at the end of transaction to avoid the clock de-synchronization + * between Master and Slave(example: audio streaming). + * @retval DAL status + */ +DAL_StatusTypeDef DAL_I2SEx_TransmitReceive_DMA(I2S_HandleTypeDef *hi2s, + uint16_t *pTxData, + uint16_t *pRxData, + uint16_t Size) +{ + uint32_t *tmp = NULL; + uint32_t tmp1 = 0U; + DAL_StatusTypeDef errorcode = DAL_OK; + + if (hi2s->State != DAL_I2S_STATE_READY) + { + errorcode = DAL_BUSY; + goto error; + } + + if ((pTxData == NULL) || (pRxData == NULL) || (Size == 0U)) + { + return DAL_ERROR; + } + + /* Process Locked */ + __DAL_LOCK(hi2s); + + hi2s->pTxBuffPtr = pTxData; + hi2s->pRxBuffPtr = pRxData; + + tmp1 = hi2s->Instance->I2SCFG & (SPI_I2SCFG_DATALEN | SPI_I2SCFG_CHLEN); + /* Check the Data format: When a 16-bit data frame or a 16-bit data frame extended + is selected during the I2S configuration phase, the Size parameter means the number + of 16-bit data length in the transaction and when a 24-bit data frame or a 32-bit data + frame is selected the Size parameter means the number of 16-bit data length. */ + if ((tmp1 == I2S_DATAFORMAT_24B) || (tmp1 == I2S_DATAFORMAT_32B)) + { + hi2s->TxXferSize = (Size << 1U); + hi2s->TxXferCount = (Size << 1U); + hi2s->RxXferSize = (Size << 1U); + hi2s->RxXferCount = (Size << 1U); + } + else + { + hi2s->TxXferSize = Size; + hi2s->TxXferCount = Size; + hi2s->RxXferSize = Size; + hi2s->RxXferCount = Size; + } + + hi2s->ErrorCode = DAL_I2S_ERROR_NONE; + hi2s->State = DAL_I2S_STATE_BUSY_TX_RX; + + /* Set the I2S Rx DMA Half transfer complete callback */ + hi2s->hdmarx->XferHalfCpltCallback = I2SEx_TxRxDMAHalfCplt; + + /* Set the I2S Rx DMA transfer complete callback */ + hi2s->hdmarx->XferCpltCallback = I2SEx_TxRxDMACplt; + + /* Set the I2S Rx DMA error callback */ + hi2s->hdmarx->XferErrorCallback = I2SEx_TxRxDMAError; + + /* Set the I2S Tx DMA Half transfer complete callback as NULL */ + hi2s->hdmatx->XferHalfCpltCallback = NULL; + + /* Set the I2S Tx DMA transfer complete callback as NULL */ + hi2s->hdmatx->XferCpltCallback = NULL; + + /* Set the I2S Tx DMA error callback */ + hi2s->hdmatx->XferErrorCallback = I2SEx_TxRxDMAError; + + tmp1 = hi2s->Instance->I2SCFG & SPI_I2SCFG_I2SMOD; + /* Check if the I2S_MODE_MASTER_TX or I2S_MODE_SLAVE_TX Mode is selected */ + if ((tmp1 == I2S_MODE_MASTER_TX) || (tmp1 == I2S_MODE_SLAVE_TX)) + { + /* Enable the Rx DMA Stream */ + tmp = (uint32_t *)&pRxData; + DAL_DMA_Start_IT(hi2s->hdmarx, (uint32_t)&I2SxEXT(hi2s->Instance)->DATA, *(uint32_t *)tmp, hi2s->RxXferSize); + + /* Enable Rx DMA Request */ + SET_BIT(I2SxEXT(hi2s->Instance)->CTRL2, SPI_CTRL2_RXDEN); + + /* Enable the Tx DMA Stream */ + tmp = (uint32_t *)&pTxData; + DAL_DMA_Start_IT(hi2s->hdmatx, *(uint32_t *)tmp, (uint32_t)&hi2s->Instance->DATA, hi2s->TxXferSize); + + /* Enable Tx DMA Request */ + SET_BIT(hi2s->Instance->CTRL2, SPI_CTRL2_TXDEN); + + /* Check if the I2S is already enabled */ + if ((hi2s->Instance->I2SCFG & SPI_I2SCFG_I2SEN) != SPI_I2SCFG_I2SEN) + { + /* Enable I2Sext(receiver) before enabling I2Sx peripheral */ + __DAL_I2SEXT_ENABLE(hi2s); + + /* Enable I2S peripheral after the I2Sext */ + __DAL_I2S_ENABLE(hi2s); + } + } + else + { + /* Check if Master Receiver mode is selected */ + if ((hi2s->Instance->I2SCFG & SPI_I2SCFG_I2SMOD) == I2S_MODE_MASTER_RX) + { + /* Clear the Overrun Flag by a read operation on the SPI_DATA register followed by a read + access to the SPI_STS register. */ + __DAL_I2S_CLEAR_OVRFLAG(hi2s); + } + /* Enable the Tx DMA Stream */ + tmp = (uint32_t *)&pTxData; + DAL_DMA_Start_IT(hi2s->hdmatx, *(uint32_t *)tmp, (uint32_t)&I2SxEXT(hi2s->Instance)->DATA, hi2s->TxXferSize); + + /* Enable Tx DMA Request */ + SET_BIT(I2SxEXT(hi2s->Instance)->CTRL2, SPI_CTRL2_TXDEN); + + /* Enable the Rx DMA Stream */ + tmp = (uint32_t *)&pRxData; + DAL_DMA_Start_IT(hi2s->hdmarx, (uint32_t)&hi2s->Instance->DATA, *(uint32_t *)tmp, hi2s->RxXferSize); + + /* Enable Rx DMA Request */ + SET_BIT(hi2s->Instance->CTRL2, SPI_CTRL2_RXDEN); + + /* Check if the I2S is already enabled */ + if ((hi2s->Instance->I2SCFG & SPI_I2SCFG_I2SEN) != SPI_I2SCFG_I2SEN) + { + /* Enable I2Sext(transmitter) before enabling I2Sx peripheral */ + __DAL_I2SEXT_ENABLE(hi2s); + /* Enable I2S peripheral before the I2Sext */ + __DAL_I2S_ENABLE(hi2s); + } + } + +error : + __DAL_UNLOCK(hi2s); + return errorcode; +} + +/** + * @brief This function handles I2S/I2Sext interrupt requests in full-duplex mode. + * @param hi2s I2S handle + * @retval DAL status + */ +void DAL_I2SEx_FullDuplex_IRQHandler(I2S_HandleTypeDef *hi2s) +{ + __IO uint32_t i2ssr = hi2s->Instance->STS; + __IO uint32_t i2sextsr = I2SxEXT(hi2s->Instance)->STS; + __IO uint32_t i2scr2 = hi2s->Instance->CTRL2; + __IO uint32_t i2sextcr2 = I2SxEXT(hi2s->Instance)->CTRL2; + + /* Check if the I2S_MODE_MASTER_TX or I2S_MODE_SLAVE_TX Mode is selected */ + if ((hi2s->Init.Mode == I2S_MODE_MASTER_TX) || (hi2s->Init.Mode == I2S_MODE_SLAVE_TX)) + { + /* I2S in mode Transmitter -------------------------------------------------*/ + if (((i2ssr & I2S_FLAG_TXE) == I2S_FLAG_TXE) && ((i2scr2 & I2S_IT_TXE) != RESET)) + { + /* When the I2S mode is configured as I2S_MODE_MASTER_TX or I2S_MODE_SLAVE_TX, + the I2S TXE interrupt will be generated to manage the full-duplex transmit phase. */ + I2SEx_TxISR_I2S(hi2s); + } + + /* I2Sext in mode Receiver -----------------------------------------------*/ + if (((i2sextsr & I2S_FLAG_RXNE) == I2S_FLAG_RXNE) && ((i2sextcr2 & I2S_IT_RXNE) != RESET)) + { + /* When the I2S mode is configured as I2S_MODE_MASTER_TX or I2S_MODE_SLAVE_TX, + the I2Sext RXNE interrupt will be generated to manage the full-duplex receive phase. */ + I2SEx_RxISR_I2SExt(hi2s); + } + + /* I2Sext Overrun error interrupt occurred --------------------------------*/ + if (((i2sextsr & I2S_FLAG_OVR) == I2S_FLAG_OVR) && ((i2sextcr2 & I2S_IT_ERR) != RESET)) + { + /* Disable RXNE and ERR interrupt */ + __DAL_I2SEXT_DISABLE_IT(hi2s, (I2S_IT_RXNE | I2S_IT_ERR)); + + /* Disable TXE and ERR interrupt */ + __DAL_I2S_DISABLE_IT(hi2s, (I2S_IT_TXE | I2S_IT_ERR)); + + /* Clear Overrun flag */ + __DAL_I2S_CLEAR_OVRFLAG(hi2s); + + /* Set the I2S State ready */ + hi2s->State = DAL_I2S_STATE_READY; + + /* Set the error code and execute error callback*/ + SET_BIT(hi2s->ErrorCode, DAL_I2S_ERROR_OVR); + /* Call user error callback */ +#if (USE_DAL_I2S_REGISTER_CALLBACKS == 1U) + hi2s->ErrorCallback(hi2s); +#else + DAL_I2S_ErrorCallback(hi2s); +#endif /* USE_DAL_I2S_REGISTER_CALLBACKS */ + } + + /* I2S Underrun error interrupt occurred ----------------------------------*/ + if (((i2ssr & I2S_FLAG_UDR) == I2S_FLAG_UDR) && ((i2scr2 & I2S_IT_ERR) != RESET)) + { + /* Disable TXE and ERR interrupt */ + __DAL_I2S_DISABLE_IT(hi2s, (I2S_IT_TXE | I2S_IT_ERR)); + + /* Disable RXNE and ERR interrupt */ + __DAL_I2SEXT_DISABLE_IT(hi2s, (I2S_IT_RXNE | I2S_IT_ERR)); + + /* Clear underrun flag */ + __DAL_I2S_CLEAR_UDRFLAG(hi2s); + + /* Set the I2S State ready */ + hi2s->State = DAL_I2S_STATE_READY; + + /* Set the error code and execute error callback*/ + SET_BIT(hi2s->ErrorCode, DAL_I2S_ERROR_UDR); + /* Call user error callback */ +#if (USE_DAL_I2S_REGISTER_CALLBACKS == 1U) + hi2s->ErrorCallback(hi2s); +#else + DAL_I2S_ErrorCallback(hi2s); +#endif /* USE_DAL_I2S_REGISTER_CALLBACKS */ + } + } + /* The I2S_MODE_MASTER_RX or I2S_MODE_SLAVE_RX Mode is selected */ + else + { + /* I2Sext in mode Transmitter ----------------------------------------------*/ + if (((i2sextsr & I2S_FLAG_TXE) == I2S_FLAG_TXE) && ((i2sextcr2 & I2S_IT_TXE) != RESET)) + { + /* When the I2S mode is configured as I2S_MODE_MASTER_RX or I2S_MODE_SLAVE_RX, + the I2Sext TXE interrupt will be generated to manage the full-duplex transmit phase. */ + I2SEx_TxISR_I2SExt(hi2s); + } + + /* I2S in mode Receiver --------------------------------------------------*/ + if (((i2ssr & I2S_FLAG_RXNE) == I2S_FLAG_RXNE) && ((i2scr2 & I2S_IT_RXNE) != RESET)) + { + /* When the I2S mode is configured as I2S_MODE_MASTER_RX or I2S_MODE_SLAVE_RX, + the I2S RXNE interrupt will be generated to manage the full-duplex receive phase. */ + I2SEx_RxISR_I2S(hi2s); + } + + /* I2S Overrun error interrupt occurred -------------------------------------*/ + if (((i2ssr & I2S_FLAG_OVR) == I2S_FLAG_OVR) && ((i2scr2 & I2S_IT_ERR) != RESET)) + { + /* Disable RXNE and ERR interrupt */ + __DAL_I2S_DISABLE_IT(hi2s, (I2S_IT_RXNE | I2S_IT_ERR)); + + /* Disable TXE and ERR interrupt */ + __DAL_I2SEXT_DISABLE_IT(hi2s, (I2S_IT_TXE | I2S_IT_ERR)); + + /* Set the I2S State ready */ + hi2s->State = DAL_I2S_STATE_READY; + + /* Set the error code and execute error callback*/ + SET_BIT(hi2s->ErrorCode, DAL_I2S_ERROR_OVR); + /* Call user error callback */ +#if (USE_DAL_I2S_REGISTER_CALLBACKS == 1U) + hi2s->ErrorCallback(hi2s); +#else + DAL_I2S_ErrorCallback(hi2s); +#endif /* USE_DAL_I2S_REGISTER_CALLBACKS */ + } + + /* I2Sext Underrun error interrupt occurred -------------------------------*/ + if (((i2sextsr & I2S_FLAG_UDR) == I2S_FLAG_UDR) && ((i2sextcr2 & I2S_IT_ERR) != RESET)) + { + /* Disable TXE and ERR interrupt */ + __DAL_I2SEXT_DISABLE_IT(hi2s, (I2S_IT_TXE | I2S_IT_ERR)); + + /* Disable RXNE and ERR interrupt */ + __DAL_I2S_DISABLE_IT(hi2s, (I2S_IT_RXNE | I2S_IT_ERR)); + + /* Set the I2S State ready */ + hi2s->State = DAL_I2S_STATE_READY; + + /* Set the error code and execute error callback*/ + SET_BIT(hi2s->ErrorCode, DAL_I2S_ERROR_UDR); + /* Call user error callback */ +#if (USE_DAL_I2S_REGISTER_CALLBACKS == 1U) + hi2s->ErrorCallback(hi2s); +#else + DAL_I2S_ErrorCallback(hi2s); +#endif /* USE_DAL_I2S_REGISTER_CALLBACKS */ + } + } +} + +/** + * @brief Tx and Rx Transfer half completed callback + * @param hi2s I2S handle + * @retval None + */ +__weak void DAL_I2SEx_TxRxHalfCpltCallback(I2S_HandleTypeDef *hi2s) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hi2s); + + /* NOTE : This function Should not be modified, when the callback is needed, + the DAL_I2SEx_TxRxHalfCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Tx and Rx Transfer completed callback + * @param hi2s I2S handle + * @retval None + */ +__weak void DAL_I2SEx_TxRxCpltCallback(I2S_HandleTypeDef *hi2s) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hi2s); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_I2SEx_TxRxCpltCallback could be implemented in the user file + */ +} + +/** + * @} + */ + +/** + * @} + */ + +/** @addtogroup I2SEx_Private_Functions I2S Extended Private Functions + * @{ + */ + +/** + * @brief DMA I2S transmit receive process half complete callback + * @param hdma pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +static void I2SEx_TxRxDMAHalfCplt(DMA_HandleTypeDef *hdma) +{ + I2S_HandleTypeDef *hi2s = (I2S_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + + /* Call user TxRx Half complete callback */ +#if (USE_DAL_I2S_REGISTER_CALLBACKS == 1U) + hi2s->TxRxHalfCpltCallback(hi2s); +#else + DAL_I2SEx_TxRxHalfCpltCallback(hi2s); +#endif /* USE_DAL_I2S_REGISTER_CALLBACKS */ +} + +/** + * @brief DMA I2S transmit receive process complete callback + * @param hdma pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +static void I2SEx_TxRxDMACplt(DMA_HandleTypeDef *hdma) +{ + I2S_HandleTypeDef *hi2s = (I2S_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + + /* If DMA is configured in DMA_NORMAL mode */ + if (hdma->Init.Mode == DMA_NORMAL) + { + if (((hi2s->Instance->I2SCFG & SPI_I2SCFG_I2SMOD) == I2S_MODE_MASTER_TX) || \ + ((hi2s->Instance->I2SCFG & SPI_I2SCFG_I2SMOD) == I2S_MODE_SLAVE_TX)) + /* Disable Tx & Rx DMA Requests */ + { + CLEAR_BIT(I2SxEXT(hi2s->Instance)->CTRL2, SPI_CTRL2_RXDEN); + CLEAR_BIT(hi2s->Instance->CTRL2, SPI_CTRL2_TXDEN); + } + else + { + CLEAR_BIT(hi2s->Instance->CTRL2, SPI_CTRL2_RXDEN); + CLEAR_BIT(I2SxEXT(hi2s->Instance)->CTRL2, SPI_CTRL2_TXDEN); + } + + hi2s->RxXferCount = 0U; + hi2s->TxXferCount = 0U; + + hi2s->State = DAL_I2S_STATE_READY; + } + + /* Call user TxRx complete callback */ +#if (USE_DAL_I2S_REGISTER_CALLBACKS == 1U) + hi2s->TxRxCpltCallback(hi2s); +#else + DAL_I2SEx_TxRxCpltCallback(hi2s); +#endif /* USE_DAL_I2S_REGISTER_CALLBACKS */ +} + +/** + * @brief DMA I2S communication error callback + * @param hdma DMA handle + * @retval None + */ +static void I2SEx_TxRxDMAError(DMA_HandleTypeDef *hdma) +{ + I2S_HandleTypeDef *hi2s = (I2S_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + + /* Disable Rx and Tx DMA Request */ + CLEAR_BIT(hi2s->Instance->CTRL2, (SPI_CTRL2_RXDEN | SPI_CTRL2_TXDEN)); + CLEAR_BIT(I2SxEXT(hi2s->Instance)->CTRL2, (SPI_CTRL2_RXDEN | SPI_CTRL2_TXDEN)); + + hi2s->TxXferCount = 0U; + hi2s->RxXferCount = 0U; + + hi2s->State = DAL_I2S_STATE_READY; + + /* Set the error code and execute error callback*/ + SET_BIT(hi2s->ErrorCode, DAL_I2S_ERROR_DMA); + /* Call user error callback */ +#if (USE_DAL_I2S_REGISTER_CALLBACKS == 1U) + hi2s->ErrorCallback(hi2s); +#else + DAL_I2S_ErrorCallback(hi2s); +#endif /* USE_DAL_I2S_REGISTER_CALLBACKS */ +} + +/** + * @brief I2S Full-Duplex IT handler transmit function + * @param hi2s I2S handle + * @retval None + */ +static void I2SEx_TxISR_I2S(I2S_HandleTypeDef *hi2s) +{ + /* Write Data on DATA register */ + hi2s->Instance->DATA = (*hi2s->pTxBuffPtr++); + hi2s->TxXferCount--; + + if (hi2s->TxXferCount == 0U) + { + /* Disable TXE and ERR interrupt */ + __DAL_I2S_DISABLE_IT(hi2s, (I2S_IT_TXE | I2S_IT_ERR)); + + if (hi2s->RxXferCount == 0U) + { + hi2s->State = DAL_I2S_STATE_READY; + /* Call user TxRx complete callback */ +#if (USE_DAL_I2S_REGISTER_CALLBACKS == 1U) + hi2s->TxRxCpltCallback(hi2s); +#else + DAL_I2SEx_TxRxCpltCallback(hi2s); +#endif /* USE_DAL_I2S_REGISTER_CALLBACKS */ + } + } +} + +/** + * @brief I2SExt Full-Duplex IT handler transmit function + * @param hi2s I2S handle + * @retval None + */ +static void I2SEx_TxISR_I2SExt(I2S_HandleTypeDef *hi2s) +{ + /* Write Data on DATA register */ + I2SxEXT(hi2s->Instance)->DATA = (*hi2s->pTxBuffPtr++); + hi2s->TxXferCount--; + + if (hi2s->TxXferCount == 0U) + { + /* Disable I2Sext TXE and ERR interrupt */ + __DAL_I2SEXT_DISABLE_IT(hi2s, (I2S_IT_TXE | I2S_IT_ERR)); + + if (hi2s->RxXferCount == 0U) + { + hi2s->State = DAL_I2S_STATE_READY; + /* Call user TxRx complete callback */ +#if (USE_DAL_I2S_REGISTER_CALLBACKS == 1U) + hi2s->TxRxCpltCallback(hi2s); +#else + DAL_I2SEx_TxRxCpltCallback(hi2s); +#endif /* USE_DAL_I2S_REGISTER_CALLBACKS */ + } + } +} + +/** + * @brief I2S Full-Duplex IT handler receive function + * @param hi2s I2S handle + * @retval None + */ +static void I2SEx_RxISR_I2S(I2S_HandleTypeDef *hi2s) +{ + /* Read Data from DATA register */ + (*hi2s->pRxBuffPtr++) = hi2s->Instance->DATA; + hi2s->RxXferCount--; + + if (hi2s->RxXferCount == 0U) + { + /* Disable RXNE and ERR interrupt */ + __DAL_I2S_DISABLE_IT(hi2s, (I2S_IT_RXNE | I2S_IT_ERR)); + + if (hi2s->TxXferCount == 0U) + { + hi2s->State = DAL_I2S_STATE_READY; + /* Call user TxRx complete callback */ +#if (USE_DAL_I2S_REGISTER_CALLBACKS == 1U) + hi2s->TxRxCpltCallback(hi2s); +#else + DAL_I2SEx_TxRxCpltCallback(hi2s); +#endif /* USE_DAL_I2S_REGISTER_CALLBACKS */ + } + } +} + +/** + * @brief I2SExt Full-Duplex IT handler receive function + * @param hi2s I2S handle + * @retval None + */ +static void I2SEx_RxISR_I2SExt(I2S_HandleTypeDef *hi2s) +{ + /* Read Data from DATA register */ + (*hi2s->pRxBuffPtr++) = I2SxEXT(hi2s->Instance)->DATA; + hi2s->RxXferCount--; + + if (hi2s->RxXferCount == 0U) + { + /* Disable I2Sext RXNE and ERR interrupt */ + __DAL_I2SEXT_DISABLE_IT(hi2s, (I2S_IT_RXNE | I2S_IT_ERR)); + + if (hi2s->TxXferCount == 0U) + { + hi2s->State = DAL_I2S_STATE_READY; + /* Call user TxRx complete callback */ +#if (USE_DAL_I2S_REGISTER_CALLBACKS == 1U) + hi2s->TxRxCpltCallback(hi2s); +#else + DAL_I2SEx_TxRxCpltCallback(hi2s); +#endif /* USE_DAL_I2S_REGISTER_CALLBACKS */ + } + } +} + +/** + * @brief This function handles I2S Communication Timeout. + * @param hi2s I2S handle + * @param Flag Flag checked + * @param State Value of the flag expected + * @param Timeout Duration of the timeout + * @param i2sUsed I2S instance reference + * @retval DAL status + */ +static DAL_StatusTypeDef I2SEx_FullDuplexWaitFlagStateUntilTimeout(I2S_HandleTypeDef *hi2s, + uint32_t Flag, + uint32_t State, + uint32_t Timeout, + I2S_UseTypeDef i2sUsed) +{ + uint32_t tickstart = DAL_GetTick(); + + if (i2sUsed == I2S_USE_I2S) + { + /* Wait until flag is reset */ + while (((__DAL_I2S_GET_FLAG(hi2s, Flag)) ? SET : RESET) != State) + { + if (Timeout != DAL_MAX_DELAY) + { + if ((Timeout == 0U) || ((DAL_GetTick() - tickstart) > Timeout)) + { + /* Set the I2S State ready */ + hi2s->State = DAL_I2S_STATE_READY; + + /* Process Unlocked */ + __DAL_UNLOCK(hi2s); + + return DAL_TIMEOUT; + } + } + } + } + else /* i2sUsed == I2S_USE_I2SEXT */ + { + /* Wait until flag is reset */ + while (((__DAL_I2SEXT_GET_FLAG(hi2s, Flag)) ? SET : RESET) != State) + { + if (Timeout != DAL_MAX_DELAY) + { + if ((Timeout == 0U) || ((DAL_GetTick() - tickstart) > Timeout)) + { + /* Set the I2S State ready */ + hi2s->State = DAL_I2S_STATE_READY; + + /* Process Unlocked */ + __DAL_UNLOCK(hi2s); + + return DAL_TIMEOUT; + } + } + } + } + return DAL_OK; +} + +/** + * @} + */ +#endif /* SPI_I2S_FULLDUPLEX_SUPPORT */ + +/** + * @} + */ +#endif /* DAL_I2S_MODULE_ENABLED */ + +/** + * @} + */ + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_irda.c b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_irda.c new file mode 100644 index 0000000000..02851fb3ca --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_irda.c @@ -0,0 +1,2712 @@ +/** + * + * @file apm32f4xx_dal_irda.c + * @brief IRDA DAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the IrDA SIR ENDEC block (IrDA): + * + Initialization and de-initialization functions + * + IO operation functions + * + Peripheral Control functions + * + Peripheral State and Errors functions + * + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + * + @verbatim + ============================================================================== + ##### How to use this driver ##### + ============================================================================== + [..] + The IRDA DAL driver can be used as follows: + + (#) Declare a IRDA_HandleTypeDef handle structure (eg. IRDA_HandleTypeDef hirda). + (#) Initialize the IRDA low level resources by implementing the DAL_IRDA_MspInit() API: + (##) Enable the USARTx interface clock. + (##) IRDA pins configuration: + (+++) Enable the clock for the IRDA GPIOs. + (+++) Configure IRDA pins as alternate function pull-up. + (##) NVIC configuration if you need to use interrupt process (DAL_IRDA_Transmit_IT() + and DAL_IRDA_Receive_IT() APIs): + (+++) Configure the USARTx interrupt priority. + (+++) Enable the NVIC USART IRQ handle. + (##) DMA Configuration if you need to use DMA process (DAL_IRDA_Transmit_DMA() + and DAL_IRDA_Receive_DMA() APIs): + (+++) Declare a DMA handle structure for the Tx/Rx stream. + (+++) Enable the DMAx interface clock. + (+++) Configure the declared DMA handle structure with the required Tx/Rx parameters. + (+++) Configure the DMA Tx/Rx stream. + (+++) Associate the initialized DMA handle to the IRDA DMA Tx/Rx handle. + (+++) Configure the priority and enable the NVIC for the transfer complete interrupt on the DMA Tx/Rx stream. + (+++) Configure the IRDAx interrupt priority and enable the NVIC USART IRQ handle + (used for last byte sending completion detection in DMA non circular mode) + + (#) Program the Baud Rate, Word Length, Parity, IrDA Mode, Prescaler + and Mode(Receiver/Transmitter) in the hirda Init structure. + + (#) Initialize the IRDA registers by calling the DAL_IRDA_Init() API: + (++) This API configures also the low level Hardware GPIO, CLOCK, CORTEX...etc) + by calling the customized DAL_IRDA_MspInit() API. + + -@@- The specific IRDA interrupts (Transmission complete interrupt, + RXNE interrupt and Error Interrupts) will be managed using the macros + __DAL_IRDA_ENABLE_IT() and __DAL_IRDA_DISABLE_IT() inside the transmit and receive process. + + (#) Three operation modes are available within this driver : + + *** Polling mode IO operation *** + ================================= + [..] + (+) Send an amount of data in blocking mode using DAL_IRDA_Transmit() + (+) Receive an amount of data in blocking mode using DAL_IRDA_Receive() + + *** Interrupt mode IO operation *** + =================================== + [..] + (+) Send an amount of data in non blocking mode using DAL_IRDA_Transmit_IT() + (+) At transmission end of transfer DAL_IRDA_TxCpltCallback is executed and user can + add his own code by customization of function pointer DAL_IRDA_TxCpltCallback + (+) Receive an amount of data in non blocking mode using DAL_IRDA_Receive_IT() + (+) At reception end of transfer DAL_IRDA_RxCpltCallback is executed and user can + add his own code by customization of function pointer DAL_IRDA_RxCpltCallback + (+) In case of transfer Error, DAL_IRDA_ErrorCallback() function is executed and user can + add his own code by customization of function pointer DAL_IRDA_ErrorCallback + + *** DMA mode IO operation *** + ============================= + [..] + (+) Send an amount of data in non blocking mode (DMA) using DAL_IRDA_Transmit_DMA() + (+) At transmission end of half transfer DAL_IRDA_TxHalfCpltCallback is executed and user can + add his own code by customization of function pointer DAL_IRDA_TxHalfCpltCallback + (+) At transmission end of transfer DAL_IRDA_TxCpltCallback is executed and user can + add his own code by customization of function pointer DAL_IRDA_TxCpltCallback + (+) Receive an amount of data in non blocking mode (DMA) using DAL_IRDA_Receive_DMA() + (+) At reception end of half transfer DAL_IRDA_RxHalfCpltCallback is executed and user can + add his own code by customization of function pointer DAL_IRDA_RxHalfCpltCallback + (+) At reception end of transfer DAL_IRDA_RxCpltCallback is executed and user can + add his own code by customization of function pointer DAL_IRDA_RxCpltCallback + (+) In case of transfer Error, DAL_IRDA_ErrorCallback() function is executed and user can + add his own code by customization of function pointer DAL_IRDA_ErrorCallback + (+) Pause the DMA Transfer using DAL_IRDA_DMAPause() + (+) Resume the DMA Transfer using DAL_IRDA_DMAResume() + (+) Stop the DMA Transfer using DAL_IRDA_DMAStop() + + *** IRDA DAL driver macros list *** + =================================== + [..] + Below the list of most used macros in IRDA DAL driver. + + (+) __DAL_IRDA_ENABLE: Enable the IRDA peripheral + (+) __DAL_IRDA_DISABLE: Disable the IRDA peripheral + (+) __DAL_IRDA_GET_FLAG : Check whether the specified IRDA flag is set or not + (+) __DAL_IRDA_CLEAR_FLAG : Clear the specified IRDA pending flag + (+) __DAL_IRDA_ENABLE_IT: Enable the specified IRDA interrupt + (+) __DAL_IRDA_DISABLE_IT: Disable the specified IRDA interrupt + (+) __DAL_IRDA_GET_IT_SOURCE: Check whether the specified IRDA interrupt has occurred or not + + [..] + (@) You can refer to the IRDA DAL driver header file for more useful macros + + ##### Callback registration ##### + ================================== + + [..] + The compilation define USE_DAL_IRDA_REGISTER_CALLBACKS when set to 1 + allows the user to configure dynamically the driver callbacks. + + [..] + Use Function DAL_IRDA_RegisterCallback() to register a user callback. + Function DAL_IRDA_RegisterCallback() allows to register following callbacks: + (+) TxHalfCpltCallback : Tx Half Complete Callback. + (+) TxCpltCallback : Tx Complete Callback. + (+) RxHalfCpltCallback : Rx Half Complete Callback. + (+) RxCpltCallback : Rx Complete Callback. + (+) ErrorCallback : Error Callback. + (+) AbortCpltCallback : Abort Complete Callback. + (+) AbortTransmitCpltCallback : Abort Transmit Complete Callback. + (+) AbortReceiveCpltCallback : Abort Receive Complete Callback. + (+) MspInitCallback : IRDA MspInit. + (+) MspDeInitCallback : IRDA MspDeInit. + This function takes as parameters the DAL peripheral handle, the Callback ID + and a pointer to the user callback function. + + [..] + Use function DAL_IRDA_UnRegisterCallback() to reset a callback to the default + weak (surcharged) function. + DAL_IRDA_UnRegisterCallback() takes as parameters the DAL peripheral handle, + and the Callback ID. + This function allows to reset following callbacks: + (+) TxHalfCpltCallback : Tx Half Complete Callback. + (+) TxCpltCallback : Tx Complete Callback. + (+) RxHalfCpltCallback : Rx Half Complete Callback. + (+) RxCpltCallback : Rx Complete Callback. + (+) ErrorCallback : Error Callback. + (+) AbortCpltCallback : Abort Complete Callback. + (+) AbortTransmitCpltCallback : Abort Transmit Complete Callback. + (+) AbortReceiveCpltCallback : Abort Receive Complete Callback. + (+) MspInitCallback : IRDA MspInit. + (+) MspDeInitCallback : IRDA MspDeInit. + + [..] + By default, after the DAL_IRDA_Init() and when the state is DAL_IRDA_STATE_RESET + all callbacks are set to the corresponding weak (surcharged) functions: + examples DAL_IRDA_TxCpltCallback(), DAL_IRDA_RxHalfCpltCallback(). + Exception done for MspInit and MspDeInit functions that are respectively + reset to the legacy weak (surcharged) functions in the DAL_IRDA_Init() + and DAL_IRDA_DeInit() only when these callbacks are null (not registered beforehand). + If not, MspInit or MspDeInit are not null, the DAL_IRDA_Init() and DAL_IRDA_DeInit() + keep and use the user MspInit/MspDeInit callbacks (registered beforehand). + + [..] + Callbacks can be registered/unregistered in DAL_IRDA_STATE_READY state only. + Exception done MspInit/MspDeInit that can be registered/unregistered + in DAL_IRDA_STATE_READY or DAL_IRDA_STATE_RESET state, thus registered (user) + MspInit/DeInit callbacks can be used during the Init/DeInit. + In that case first register the MspInit/MspDeInit user callbacks + using DAL_IRDA_RegisterCallback() before calling DAL_IRDA_DeInit() + or DAL_IRDA_Init() function. + + [..] + When The compilation define USE_DAL_IRDA_REGISTER_CALLBACKS is set to 0 or + not defined, the callback registration feature is not available + and weak (surcharged) callbacks are used. + + @endverbatim + [..] + (@) Additional remark: If the parity is enabled, then the MSB bit of the data written + in the data register is transmitted but is changed by the parity bit. + Depending on the frame length defined by the M bit (8-bits or 9-bits), + the possible IRDA frame formats are as listed in the following table: + +-------------------------------------------------------------+ + | M bit | PCE bit | IRDA frame | + |---------------------|---------------------------------------| + | 0 | 0 | | SB | 8 bit data | 1 STB | | + |---------|-----------|---------------------------------------| + | 0 | 1 | | SB | 7 bit data | PB | 1 STB | | + |---------|-----------|---------------------------------------| + | 1 | 0 | | SB | 9 bit data | 1 STB | | + |---------|-----------|---------------------------------------| + | 1 | 1 | | SB | 8 bit data | PB | 1 STB | | + +-------------------------------------------------------------+ + * + */ + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @defgroup IRDA IRDA + * @brief DAL IRDA module driver + * @{ + */ + +#ifdef DAL_IRDA_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/** @addtogroup IRDA_Private_Functions + * @{ + */ +#if (USE_DAL_IRDA_REGISTER_CALLBACKS == 1) +void IRDA_InitCallbacksToDefault(IRDA_HandleTypeDef *hirda); +#endif /* USE_DAL_IRDA_REGISTER_CALLBACKS */ +static void IRDA_SetConfig(IRDA_HandleTypeDef *hirda); +static DAL_StatusTypeDef IRDA_Transmit_IT(IRDA_HandleTypeDef *hirda); +static DAL_StatusTypeDef IRDA_EndTransmit_IT(IRDA_HandleTypeDef *hirda); +static DAL_StatusTypeDef IRDA_Receive_IT(IRDA_HandleTypeDef *hirda); +static void IRDA_DMATransmitCplt(DMA_HandleTypeDef *hdma); +static void IRDA_DMATransmitHalfCplt(DMA_HandleTypeDef *hdma); +static void IRDA_DMAReceiveCplt(DMA_HandleTypeDef *hdma); +static void IRDA_DMAReceiveHalfCplt(DMA_HandleTypeDef *hdma); +static void IRDA_DMAError(DMA_HandleTypeDef *hdma); +static void IRDA_DMAAbortOnError(DMA_HandleTypeDef *hdma); +static void IRDA_DMATxAbortCallback(DMA_HandleTypeDef *hdma); +static void IRDA_DMARxAbortCallback(DMA_HandleTypeDef *hdma); +static void IRDA_DMATxOnlyAbortCallback(DMA_HandleTypeDef *hdma); +static void IRDA_DMARxOnlyAbortCallback(DMA_HandleTypeDef *hdma); +static DAL_StatusTypeDef IRDA_WaitOnFlagUntilTimeout(IRDA_HandleTypeDef *hirda, uint32_t Flag, FlagStatus Status, uint32_t Tickstart, uint32_t Timeout); +static void IRDA_EndTxTransfer(IRDA_HandleTypeDef *hirda); +static void IRDA_EndRxTransfer(IRDA_HandleTypeDef *hirda); +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +/** @defgroup IRDA_Exported_Functions IrDA Exported Functions + * @{ + */ + +/** @defgroup IRDA_Exported_Functions_Group1 IrDA Initialization and de-initialization functions + * @brief Initialization and Configuration functions + * +@verbatim + + ============================================================================== + ##### Initialization and Configuration functions ##### + ============================================================================== + [..] + This subsection provides a set of functions allowing to initialize the USARTx or the UARTy + in asynchronous IrDA mode. + (+) For the asynchronous mode only these parameters can be configured: + (++) BaudRate + (++) WordLength + (++) Parity: If the parity is enabled, then the MSB bit of the data written + in the data register is transmitted but is changed by the parity bit. + Depending on the frame length defined by the M bit (8-bits or 9-bits), + please refer to Reference manual for possible IRDA frame formats. + (++) Prescaler: A pulse of width less than two and greater than one PSC period(s) may or may + not be rejected. The receiver set up time should be managed by software. The IrDA physical layer + specification specifies a minimum of 10 ms delay between transmission and + reception (IrDA is a half duplex protocol). + (++) Mode: Receiver/transmitter modes + (++) IrDAMode: the IrDA can operate in the Normal mode or in the Low power mode. + [..] + The DAL_IRDA_Init() API follows IRDA configuration procedures (details for the procedures + are available in reference manual). + +@endverbatim + * @{ + */ + +/** + * @brief Initializes the IRDA mode according to the specified + * parameters in the IRDA_InitTypeDef and create the associated handle. + * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains + * the configuration information for the specified IRDA module. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_IRDA_Init(IRDA_HandleTypeDef *hirda) +{ + /* Check the IRDA handle allocation */ + if (hirda == NULL) + { + return DAL_ERROR; + } + + /* Check the IRDA instance parameters */ + ASSERT_PARAM(IS_IRDA_INSTANCE(hirda->Instance)); + /* Check the IRDA mode parameter in the IRDA handle */ + ASSERT_PARAM(IS_IRDA_POWERMODE(hirda->Init.IrDAMode)); + + if (hirda->gState == DAL_IRDA_STATE_RESET) + { + /* Allocate lock resource and initialize it */ + hirda->Lock = DAL_UNLOCKED; + +#if USE_DAL_IRDA_REGISTER_CALLBACKS == 1 + IRDA_InitCallbacksToDefault(hirda); + + if (hirda->MspInitCallback == NULL) + { + hirda->MspInitCallback = DAL_IRDA_MspInit; + } + + /* Init the low level hardware */ + hirda->MspInitCallback(hirda); +#else + /* Init the low level hardware : GPIO, CLOCK */ + DAL_IRDA_MspInit(hirda); +#endif /* USE_DAL_IRDA_REGISTER_CALLBACKS */ + } + + hirda->gState = DAL_IRDA_STATE_BUSY; + + /* Disable the IRDA peripheral */ + __DAL_IRDA_DISABLE(hirda); + + /* Set the IRDA communication parameters */ + IRDA_SetConfig(hirda); + + /* In IrDA mode, the following bits must be kept cleared: + - LINEN, STOP and CLKEN bits in the USART_CTRL2 register, + - SCEN and HDSEL bits in the USART_CTRL3 register.*/ + CLEAR_BIT(hirda->Instance->CTRL2, (USART_CTRL2_LINMEN | USART_CTRL2_STOPCFG | USART_CTRL2_CLKEN)); + CLEAR_BIT(hirda->Instance->CTRL3, (USART_CTRL3_SCEN | USART_CTRL3_HDEN)); + + /* Enable the IRDA peripheral */ + __DAL_IRDA_ENABLE(hirda); + + /* Set the prescaler */ + MODIFY_REG(hirda->Instance->GTPSC, USART_GTPSC_PSC, hirda->Init.Prescaler); + + /* Configure the IrDA mode */ + MODIFY_REG(hirda->Instance->CTRL3, USART_CTRL3_IRLPEN, hirda->Init.IrDAMode); + + /* Enable the IrDA mode by setting the IREN bit in the CTRL3 register */ + SET_BIT(hirda->Instance->CTRL3, USART_CTRL3_IREN); + + /* Initialize the IRDA state*/ + hirda->ErrorCode = DAL_IRDA_ERROR_NONE; + hirda->gState = DAL_IRDA_STATE_READY; + hirda->RxState = DAL_IRDA_STATE_READY; + + return DAL_OK; +} + +/** + * @brief DeInitializes the IRDA peripheral + * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains + * the configuration information for the specified IRDA module. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_IRDA_DeInit(IRDA_HandleTypeDef *hirda) +{ + /* Check the IRDA handle allocation */ + if (hirda == NULL) + { + return DAL_ERROR; + } + + /* Check the parameters */ + ASSERT_PARAM(IS_IRDA_INSTANCE(hirda->Instance)); + + hirda->gState = DAL_IRDA_STATE_BUSY; + + /* Disable the Peripheral */ + __DAL_IRDA_DISABLE(hirda); + + /* DeInit the low level hardware */ +#if USE_DAL_IRDA_REGISTER_CALLBACKS == 1 + if (hirda->MspDeInitCallback == NULL) + { + hirda->MspDeInitCallback = DAL_IRDA_MspDeInit; + } + /* DeInit the low level hardware */ + hirda->MspDeInitCallback(hirda); +#else + DAL_IRDA_MspDeInit(hirda); +#endif /* USE_DAL_IRDA_REGISTER_CALLBACKS */ + + hirda->ErrorCode = DAL_IRDA_ERROR_NONE; + + hirda->gState = DAL_IRDA_STATE_RESET; + hirda->RxState = DAL_IRDA_STATE_RESET; + + /* Release Lock */ + __DAL_UNLOCK(hirda); + + return DAL_OK; +} + +/** + * @brief IRDA MSP Init. + * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains + * the configuration information for the specified IRDA module. + * @retval None + */ +__weak void DAL_IRDA_MspInit(IRDA_HandleTypeDef *hirda) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hirda); + + /* NOTE: This function should not be modified, when the callback is needed, + the DAL_IRDA_MspInit can be implemented in the user file + */ +} + +/** + * @brief IRDA MSP DeInit. + * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains + * the configuration information for the specified IRDA module. + * @retval None + */ +__weak void DAL_IRDA_MspDeInit(IRDA_HandleTypeDef *hirda) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hirda); + + /* NOTE: This function should not be modified, when the callback is needed, + the DAL_IRDA_MspDeInit can be implemented in the user file + */ +} + +#if (USE_DAL_IRDA_REGISTER_CALLBACKS == 1) +/** + * @brief Register a User IRDA Callback + * To be used instead of the weak predefined callback + * @param hirda irda handle + * @param CallbackID ID of the callback to be registered + * This parameter can be one of the following values: + * @arg @ref DAL_IRDA_TX_HALFCOMPLETE_CB_ID Tx Half Complete Callback ID + * @arg @ref DAL_IRDA_TX_COMPLETE_CB_ID Tx Complete Callback ID + * @arg @ref DAL_IRDA_RX_HALFCOMPLETE_CB_ID Rx Half Complete Callback ID + * @arg @ref DAL_IRDA_RX_COMPLETE_CB_ID Rx Complete Callback ID + * @arg @ref DAL_IRDA_ERROR_CB_ID Error Callback ID + * @arg @ref DAL_IRDA_ABORT_COMPLETE_CB_ID Abort Complete Callback ID + * @arg @ref DAL_IRDA_ABORT_TRANSMIT_COMPLETE_CB_ID Abort Transmit Complete Callback ID + * @arg @ref DAL_IRDA_ABORT_RECEIVE_COMPLETE_CB_ID Abort Receive Complete Callback ID + * @arg @ref DAL_IRDA_MSPINIT_CB_ID MspInit Callback ID + * @arg @ref DAL_IRDA_MSPDEINIT_CB_ID MspDeInit Callback ID + * @param pCallback pointer to the Callback function + * @retval DAL status + */ +DAL_StatusTypeDef DAL_IRDA_RegisterCallback(IRDA_HandleTypeDef *hirda, DAL_IRDA_CallbackIDTypeDef CallbackID, pIRDA_CallbackTypeDef pCallback) +{ + DAL_StatusTypeDef status = DAL_OK; + + if (pCallback == NULL) + { + /* Update the error code */ + hirda->ErrorCode |= DAL_IRDA_ERROR_INVALID_CALLBACK; + + return DAL_ERROR; + } + /* Process locked */ + __DAL_LOCK(hirda); + + if (hirda->gState == DAL_IRDA_STATE_READY) + { + switch (CallbackID) + { + case DAL_IRDA_TX_HALFCOMPLETE_CB_ID : + hirda->TxHalfCpltCallback = pCallback; + break; + + case DAL_IRDA_TX_COMPLETE_CB_ID : + hirda->TxCpltCallback = pCallback; + break; + + case DAL_IRDA_RX_HALFCOMPLETE_CB_ID : + hirda->RxHalfCpltCallback = pCallback; + break; + + case DAL_IRDA_RX_COMPLETE_CB_ID : + hirda->RxCpltCallback = pCallback; + break; + + case DAL_IRDA_ERROR_CB_ID : + hirda->ErrorCallback = pCallback; + break; + + case DAL_IRDA_ABORT_COMPLETE_CB_ID : + hirda->AbortCpltCallback = pCallback; + break; + + case DAL_IRDA_ABORT_TRANSMIT_COMPLETE_CB_ID : + hirda->AbortTransmitCpltCallback = pCallback; + break; + + case DAL_IRDA_ABORT_RECEIVE_COMPLETE_CB_ID : + hirda->AbortReceiveCpltCallback = pCallback; + break; + + case DAL_IRDA_MSPINIT_CB_ID : + hirda->MspInitCallback = pCallback; + break; + + case DAL_IRDA_MSPDEINIT_CB_ID : + hirda->MspDeInitCallback = pCallback; + break; + + default : + /* Update the error code */ + hirda->ErrorCode |= DAL_IRDA_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = DAL_ERROR; + break; + } + } + else if (hirda->gState == DAL_IRDA_STATE_RESET) + { + switch (CallbackID) + { + case DAL_IRDA_MSPINIT_CB_ID : + hirda->MspInitCallback = pCallback; + break; + + case DAL_IRDA_MSPDEINIT_CB_ID : + hirda->MspDeInitCallback = pCallback; + break; + + default : + /* Update the error code */ + hirda->ErrorCode |= DAL_IRDA_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = DAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + hirda->ErrorCode |= DAL_IRDA_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = DAL_ERROR; + } + + /* Release Lock */ + __DAL_UNLOCK(hirda); + + return status; +} + +/** + * @brief Unregister an IRDA callback + * IRDA callback is redirected to the weak predefined callback + * @param hirda irda handle + * @param CallbackID ID of the callback to be unregistered + * This parameter can be one of the following values: + * @arg @ref DAL_IRDA_TX_HALFCOMPLETE_CB_ID Tx Half Complete Callback ID + * @arg @ref DAL_IRDA_TX_COMPLETE_CB_ID Tx Complete Callback ID + * @arg @ref DAL_IRDA_RX_HALFCOMPLETE_CB_ID Rx Half Complete Callback ID + * @arg @ref DAL_IRDA_RX_COMPLETE_CB_ID Rx Complete Callback ID + * @arg @ref DAL_IRDA_ERROR_CB_ID Error Callback ID + * @arg @ref DAL_IRDA_ABORT_COMPLETE_CB_ID Abort Complete Callback ID + * @arg @ref DAL_IRDA_ABORT_TRANSMIT_COMPLETE_CB_ID Abort Transmit Complete Callback ID + * @arg @ref DAL_IRDA_ABORT_RECEIVE_COMPLETE_CB_ID Abort Receive Complete Callback ID + * @arg @ref DAL_IRDA_MSPINIT_CB_ID MspInit Callback ID + * @arg @ref DAL_IRDA_MSPDEINIT_CB_ID MspDeInit Callback ID + * @retval DAL status + */ +DAL_StatusTypeDef DAL_IRDA_UnRegisterCallback(IRDA_HandleTypeDef *hirda, DAL_IRDA_CallbackIDTypeDef CallbackID) +{ + DAL_StatusTypeDef status = DAL_OK; + + /* Process locked */ + __DAL_LOCK(hirda); + + if (DAL_IRDA_STATE_READY == hirda->gState) + { + switch (CallbackID) + { + case DAL_IRDA_TX_HALFCOMPLETE_CB_ID : + hirda->TxHalfCpltCallback = DAL_IRDA_TxHalfCpltCallback; /* Legacy weak TxHalfCpltCallback */ + break; + + case DAL_IRDA_TX_COMPLETE_CB_ID : + hirda->TxCpltCallback = DAL_IRDA_TxCpltCallback; /* Legacy weak TxCpltCallback */ + break; + + case DAL_IRDA_RX_HALFCOMPLETE_CB_ID : + hirda->RxHalfCpltCallback = DAL_IRDA_RxHalfCpltCallback; /* Legacy weak RxHalfCpltCallback */ + break; + + case DAL_IRDA_RX_COMPLETE_CB_ID : + hirda->RxCpltCallback = DAL_IRDA_RxCpltCallback; /* Legacy weak RxCpltCallback */ + break; + + case DAL_IRDA_ERROR_CB_ID : + hirda->ErrorCallback = DAL_IRDA_ErrorCallback; /* Legacy weak ErrorCallback */ + break; + + case DAL_IRDA_ABORT_COMPLETE_CB_ID : + hirda->AbortCpltCallback = DAL_IRDA_AbortCpltCallback; /* Legacy weak AbortCpltCallback */ + break; + + case DAL_IRDA_ABORT_TRANSMIT_COMPLETE_CB_ID : + hirda->AbortTransmitCpltCallback = DAL_IRDA_AbortTransmitCpltCallback; /* Legacy weak AbortTransmitCpltCallback */ + break; + + case DAL_IRDA_ABORT_RECEIVE_COMPLETE_CB_ID : + hirda->AbortReceiveCpltCallback = DAL_IRDA_AbortReceiveCpltCallback; /* Legacy weak AbortReceiveCpltCallback */ + break; + + case DAL_IRDA_MSPINIT_CB_ID : + hirda->MspInitCallback = DAL_IRDA_MspInit; /* Legacy weak MspInitCallback */ + break; + + case DAL_IRDA_MSPDEINIT_CB_ID : + hirda->MspDeInitCallback = DAL_IRDA_MspDeInit; /* Legacy weak MspDeInitCallback */ + break; + + default : + /* Update the error code */ + hirda->ErrorCode |= DAL_IRDA_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = DAL_ERROR; + break; + } + } + else if (DAL_IRDA_STATE_RESET == hirda->gState) + { + switch (CallbackID) + { + case DAL_IRDA_MSPINIT_CB_ID : + hirda->MspInitCallback = DAL_IRDA_MspInit; + break; + + case DAL_IRDA_MSPDEINIT_CB_ID : + hirda->MspDeInitCallback = DAL_IRDA_MspDeInit; + break; + + default : + /* Update the error code */ + hirda->ErrorCode |= DAL_IRDA_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = DAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + hirda->ErrorCode |= DAL_IRDA_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = DAL_ERROR; + } + + /* Release Lock */ + __DAL_UNLOCK(hirda); + + return status; +} +#endif /* USE_DAL_IRDA_REGISTER_CALLBACKS */ + +/** + * @} + */ + +/** @defgroup IRDA_Exported_Functions_Group2 IO operation functions + * @brief IRDA Transmit and Receive functions + * +@verbatim + ============================================================================== + ##### IO operation functions ##### + ============================================================================== + [..] + This subsection provides a set of functions allowing to manage the IRDA data transfers. + IrDA is a half duplex communication protocol. If the Transmitter is busy, any data + on the IrDA receive line will be ignored by the IrDA decoder and if the Receiver + is busy, data on the TX from the USART to IrDA will not be encoded by IrDA. + While receiving data, transmission should be avoided as the data to be transmitted + could be corrupted. + + (#) There are two modes of transfer: + (++) Blocking mode: The communication is performed in polling mode. + The DAL status of all data processing is returned by the same function + after finishing transfer. + (++) Non-Blocking mode: The communication is performed using Interrupts + or DMA, these API's return the DAL status. + The end of the data processing will be indicated through the + dedicated IRDA IRQ when using Interrupt mode or the DMA IRQ when + using DMA mode. + The DAL_IRDA_TxCpltCallback(), DAL_IRDA_RxCpltCallback() user callbacks + will be executed respectively at the end of the Transmit or Receive process + The DAL_IRDA_ErrorCallback() user callback will be executed when a communication error is detected + + (#) Blocking mode APIs are : + (++) DAL_IRDA_Transmit() + (++) DAL_IRDA_Receive() + + (#) Non Blocking mode APIs with Interrupt are : + (++) DAL_IRDA_Transmit_IT() + (++) DAL_IRDA_Receive_IT() + (++) DAL_IRDA_IRQHandler() + + (#) Non Blocking mode functions with DMA are : + (++) DAL_IRDA_Transmit_DMA() + (++) DAL_IRDA_Receive_DMA() + (++) DAL_IRDA_DMAPause() + (++) DAL_IRDA_DMAResume() + (++) DAL_IRDA_DMAStop() + + (#) A set of Transfer Complete Callbacks are provided in Non Blocking mode: + (++) DAL_IRDA_TxHalfCpltCallback() + (++) DAL_IRDA_TxCpltCallback() + (++) DAL_IRDA_RxHalfCpltCallback() + (++) DAL_IRDA_RxCpltCallback() + (++) DAL_IRDA_ErrorCallback() + + (#) Non-Blocking mode transfers could be aborted using Abort API's : + (+) DAL_IRDA_Abort() + (+) DAL_IRDA_AbortTransmit() + (+) DAL_IRDA_AbortReceive() + (+) DAL_IRDA_Abort_IT() + (+) DAL_IRDA_AbortTransmit_IT() + (+) DAL_IRDA_AbortReceive_IT() + + (#) For Abort services based on interrupts (DAL_IRDA_Abortxxx_IT), a set of Abort Complete Callbacks are provided: + (+) DAL_IRDA_AbortCpltCallback() + (+) DAL_IRDA_AbortTransmitCpltCallback() + (+) DAL_IRDA_AbortReceiveCpltCallback() + + (#) In Non-Blocking mode transfers, possible errors are split into 2 categories. + Errors are handled as follows : + (+) Error is considered as Recoverable and non blocking : Transfer could go till end, but error severity is + to be evaluated by user : this concerns Frame Error, Parity Error or Noise Error in Interrupt mode reception . + Received character is then retrieved and stored in Rx buffer, Error code is set to allow user to identify error type, + and DAL_IRDA_ErrorCallback() user callback is executed. Transfer is kept ongoing on IRDA side. + If user wants to abort it, Abort services should be called by user. + (+) Error is considered as Blocking : Transfer could not be completed properly and is aborted. + This concerns Overrun Error In Interrupt mode reception and all errors in DMA mode. + Error code is set to allow user to identify error type, and DAL_IRDA_ErrorCallback() user callback is executed. + +@endverbatim + * @{ + */ + +/** + * @brief Sends an amount of data in blocking mode. + * @note When UART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), + * the sent data is handled as a set of u16. In this case, Size must reflect the number + * of u16 available through pData. + * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains + * the configuration information for the specified IRDA module. + * @param pData Pointer to data buffer (u8 or u16 data elements). + * @param Size Amount of data elements (u8 or u16) to be sent. + * @param Timeout Specify timeout value. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_IRDA_Transmit(IRDA_HandleTypeDef *hirda, const uint8_t *pData, uint16_t Size, uint32_t Timeout) +{ + const uint16_t *tmp; + uint32_t tickstart = 0U; + + /* Check that a Tx process is not already ongoing */ + if (hirda->gState == DAL_IRDA_STATE_READY) + { + if ((pData == NULL) || (Size == 0U)) + { + return DAL_ERROR; + } + + /* Process Locked */ + __DAL_LOCK(hirda); + + hirda->ErrorCode = DAL_IRDA_ERROR_NONE; + hirda->gState = DAL_IRDA_STATE_BUSY_TX; + + /* Init tickstart for timeout management*/ + tickstart = DAL_GetTick(); + + hirda->TxXferSize = Size; + hirda->TxXferCount = Size; + while (hirda->TxXferCount > 0U) + { + hirda->TxXferCount--; + if (hirda->Init.WordLength == IRDA_WORDLENGTH_9B) + { + if (IRDA_WaitOnFlagUntilTimeout(hirda, IRDA_FLAG_TXE, RESET, tickstart, Timeout) != DAL_OK) + { + return DAL_TIMEOUT; + } + tmp = (const uint16_t *) pData; + hirda->Instance->DATA = (*tmp & (uint16_t)0x01FF); + if (hirda->Init.Parity == IRDA_PARITY_NONE) + { + pData += 2U; + } + else + { + pData += 1U; + } + } + else + { + if (IRDA_WaitOnFlagUntilTimeout(hirda, IRDA_FLAG_TXE, RESET, tickstart, Timeout) != DAL_OK) + { + return DAL_TIMEOUT; + } + hirda->Instance->DATA = (*pData++ & (uint8_t)0xFF); + } + } + + if (IRDA_WaitOnFlagUntilTimeout(hirda, IRDA_FLAG_TC, RESET, tickstart, Timeout) != DAL_OK) + { + return DAL_TIMEOUT; + } + + /* At end of Tx process, restore hirda->gState to Ready */ + hirda->gState = DAL_IRDA_STATE_READY; + + /* Process Unlocked */ + __DAL_UNLOCK(hirda); + + return DAL_OK; + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief Receive an amount of data in blocking mode. + * @note When UART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), + * the received data is handled as a set of u16. In this case, Size must reflect the number + * of u16 available through pData. + * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains + * the configuration information for the specified IRDA module. + * @param pData Pointer to data buffer (u8 or u16 data elements). + * @param Size Amount of data elements (u8 or u16) to be received. + * @param Timeout Specify timeout value + * @retval DAL status + */ +DAL_StatusTypeDef DAL_IRDA_Receive(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size, uint32_t Timeout) +{ + uint16_t *tmp; + uint32_t tickstart = 0U; + + /* Check that a Rx process is not already ongoing */ + if (hirda->RxState == DAL_IRDA_STATE_READY) + { + if ((pData == NULL) || (Size == 0U)) + { + return DAL_ERROR; + } + + /* Process Locked */ + __DAL_LOCK(hirda); + + hirda->ErrorCode = DAL_IRDA_ERROR_NONE; + hirda->RxState = DAL_IRDA_STATE_BUSY_RX; + + /* Init tickstart for timeout management*/ + tickstart = DAL_GetTick(); + + hirda->RxXferSize = Size; + hirda->RxXferCount = Size; + + /* Check the remain data to be received */ + while (hirda->RxXferCount > 0U) + { + hirda->RxXferCount--; + + if (hirda->Init.WordLength == IRDA_WORDLENGTH_9B) + { + if (IRDA_WaitOnFlagUntilTimeout(hirda, IRDA_FLAG_RXNE, RESET, tickstart, Timeout) != DAL_OK) + { + return DAL_TIMEOUT; + } + tmp = (uint16_t *) pData ; + if (hirda->Init.Parity == IRDA_PARITY_NONE) + { + *tmp = (uint16_t)(hirda->Instance->DATA & (uint16_t)0x01FF); + pData += 2U; + } + else + { + *tmp = (uint16_t)(hirda->Instance->DATA & (uint16_t)0x00FF); + pData += 1U; + } + } + else + { + if (IRDA_WaitOnFlagUntilTimeout(hirda, IRDA_FLAG_RXNE, RESET, tickstart, Timeout) != DAL_OK) + { + return DAL_TIMEOUT; + } + if (hirda->Init.Parity == IRDA_PARITY_NONE) + { + *pData++ = (uint8_t)(hirda->Instance->DATA & (uint8_t)0x00FF); + } + else + { + *pData++ = (uint8_t)(hirda->Instance->DATA & (uint8_t)0x007F); + } + } + } + + /* At end of Rx process, restore hirda->RxState to Ready */ + hirda->RxState = DAL_IRDA_STATE_READY; + + /* Process Unlocked */ + __DAL_UNLOCK(hirda); + + return DAL_OK; + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief Send an amount of data in non blocking mode. + * @note When UART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), + * the sent data is handled as a set of u16. In this case, Size must reflect the number + * of u16 available through pData. + * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains + * the configuration information for the specified IRDA module. + * @param pData Pointer to data buffer (u8 or u16 data elements). + * @param Size Amount of data elements (u8 or u16) to be sent. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_IRDA_Transmit_IT(IRDA_HandleTypeDef *hirda, const uint8_t *pData, uint16_t Size) +{ + /* Check that a Tx process is not already ongoing */ + if (hirda->gState == DAL_IRDA_STATE_READY) + { + if ((pData == NULL) || (Size == 0U)) + { + return DAL_ERROR; + } + + /* Process Locked */ + __DAL_LOCK(hirda); + + hirda->pTxBuffPtr = pData; + hirda->TxXferSize = Size; + hirda->TxXferCount = Size; + + hirda->ErrorCode = DAL_IRDA_ERROR_NONE; + hirda->gState = DAL_IRDA_STATE_BUSY_TX; + + /* Process Unlocked */ + __DAL_UNLOCK(hirda); + + /* Enable the IRDA Transmit Data Register Empty Interrupt */ + SET_BIT(hirda->Instance->CTRL1, USART_CTRL1_TXBEIEN); + + return DAL_OK; + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief Receive an amount of data in non blocking mode. + * @note When UART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), + * the received data is handled as a set of u16. In this case, Size must reflect the number + * of u16 available through pData. + * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains + * the configuration information for the specified IRDA module. + * @param pData Pointer to data buffer (u8 or u16 data elements). + * @param Size Amount of data elements (u8 or u16) to be received. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_IRDA_Receive_IT(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size) +{ + /* Check that a Rx process is not already ongoing */ + if (hirda->RxState == DAL_IRDA_STATE_READY) + { + if ((pData == NULL) || (Size == 0U)) + { + return DAL_ERROR; + } + + /* Process Locked */ + __DAL_LOCK(hirda); + + hirda->pRxBuffPtr = pData; + hirda->RxXferSize = Size; + hirda->RxXferCount = Size; + + hirda->ErrorCode = DAL_IRDA_ERROR_NONE; + hirda->RxState = DAL_IRDA_STATE_BUSY_RX; + + /* Process Unlocked */ + __DAL_UNLOCK(hirda); + + if (hirda->Init.Parity != IRDA_PARITY_NONE) + { + /* Enable the IRDA Parity Error and Data Register Not Empty Interrupts */ + SET_BIT(hirda->Instance->CTRL1, USART_CTRL1_PEIEN | USART_CTRL1_RXBNEIEN); + } + else + { + /* Enable the IRDA Data Register Not Empty Interrupts */ + SET_BIT(hirda->Instance->CTRL1, USART_CTRL1_RXBNEIEN); + } + + /* Enable the IRDA Error Interrupt: (Frame error, Noise error, Overrun error) */ + SET_BIT(hirda->Instance->CTRL3, USART_CTRL3_ERRIEN); + + return DAL_OK; + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief Send an amount of data in DMA mode. + * @note When UART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), + * the sent data is handled as a set of u16. In this case, Size must reflect the number + * of u16 available through pData. + * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains + * the configuration information for the specified IRDA module. + * @param pData Pointer to data buffer (u8 or u16 data elements). + * @param Size Amount of data elements (u8 or u16) to be sent. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_IRDA_Transmit_DMA(IRDA_HandleTypeDef *hirda, const uint8_t *pData, uint16_t Size) +{ + const uint32_t *tmp; + + /* Check that a Tx process is not already ongoing */ + if (hirda->gState == DAL_IRDA_STATE_READY) + { + if ((pData == NULL) || (Size == 0U)) + { + return DAL_ERROR; + } + + /* Process Locked */ + __DAL_LOCK(hirda); + + hirda->pTxBuffPtr = pData; + hirda->TxXferSize = Size; + hirda->TxXferCount = Size; + + hirda->ErrorCode = DAL_IRDA_ERROR_NONE; + hirda->gState = DAL_IRDA_STATE_BUSY_TX; + + /* Set the IRDA DMA transfer complete callback */ + hirda->hdmatx->XferCpltCallback = IRDA_DMATransmitCplt; + + /* Set the IRDA DMA half transfer complete callback */ + hirda->hdmatx->XferHalfCpltCallback = IRDA_DMATransmitHalfCplt; + + /* Set the DMA error callback */ + hirda->hdmatx->XferErrorCallback = IRDA_DMAError; + + /* Set the DMA abort callback */ + hirda->hdmatx->XferAbortCallback = NULL; + + /* Enable the IRDA transmit DMA stream */ + tmp = (const uint32_t *)&pData; + DAL_DMA_Start_IT(hirda->hdmatx, *(const uint32_t *)tmp, (uint32_t)&hirda->Instance->DATA, Size); + + /* Clear the TC flag in the SR register by writing 0 to it */ + __DAL_IRDA_CLEAR_FLAG(hirda, IRDA_FLAG_TC); + + /* Process Unlocked */ + __DAL_UNLOCK(hirda); + + /* Enable the DMA transfer for transmit request by setting the DMAT bit + in the USART CTRL3 register */ + SET_BIT(hirda->Instance->CTRL3, USART_CTRL3_DMATXEN); + + return DAL_OK; + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief Receives an amount of data in DMA mode. + * @note When UART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), + * the received data is handled as a set of u16. In this case, Size must reflect the number + * of u16 available through pData. + * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains + * the configuration information for the specified IRDA module. + * @param pData Pointer to data buffer (u8 or u16 data elements). + * @param Size Amount of data elements (u8 or u16) to be received. + * @note When the IRDA parity is enabled (PCE = 1) the data received contain the parity bit. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_IRDA_Receive_DMA(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size) +{ + uint32_t *tmp; + + /* Check that a Rx process is not already ongoing */ + if (hirda->RxState == DAL_IRDA_STATE_READY) + { + if ((pData == NULL) || (Size == 0U)) + { + return DAL_ERROR; + } + + /* Process Locked */ + __DAL_LOCK(hirda); + + hirda->pRxBuffPtr = pData; + hirda->RxXferSize = Size; + + hirda->ErrorCode = DAL_IRDA_ERROR_NONE; + hirda->RxState = DAL_IRDA_STATE_BUSY_RX; + + /* Set the IRDA DMA transfer complete callback */ + hirda->hdmarx->XferCpltCallback = IRDA_DMAReceiveCplt; + + /* Set the IRDA DMA half transfer complete callback */ + hirda->hdmarx->XferHalfCpltCallback = IRDA_DMAReceiveHalfCplt; + + /* Set the DMA error callback */ + hirda->hdmarx->XferErrorCallback = IRDA_DMAError; + + /* Set the DMA abort callback */ + hirda->hdmarx->XferAbortCallback = NULL; + + /* Enable the DMA stream */ + tmp = (uint32_t *)&pData; + DAL_DMA_Start_IT(hirda->hdmarx, (uint32_t)&hirda->Instance->DATA, *(uint32_t *)tmp, Size); + + /* Clear the Overrun flag just before enabling the DMA Rx request: can be mandatory for the second transfer */ + __DAL_IRDA_CLEAR_OREFLAG(hirda); + + /* Process Unlocked */ + __DAL_UNLOCK(hirda); + + if (hirda->Init.Parity != IRDA_PARITY_NONE) + { + /* Enable the IRDA Parity Error Interrupt */ + SET_BIT(hirda->Instance->CTRL1, USART_CTRL1_PEIEN); + } + + /* Enable the IRDA Error Interrupt: (Frame error, Noise error, Overrun error) */ + SET_BIT(hirda->Instance->CTRL3, USART_CTRL3_ERRIEN); + + /* Enable the DMA transfer for the receiver request by setting the DMAR bit + in the USART CTRL3 register */ + SET_BIT(hirda->Instance->CTRL3, USART_CTRL3_DMARXEN); + + return DAL_OK; + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief Pauses the DMA Transfer. + * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains + * the configuration information for the specified IRDA module. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_IRDA_DMAPause(IRDA_HandleTypeDef *hirda) +{ + uint32_t dmarequest = 0x00U; + + /* Process Locked */ + __DAL_LOCK(hirda); + + dmarequest = DAL_IS_BIT_SET(hirda->Instance->CTRL3, USART_CTRL3_DMATXEN); + if ((hirda->gState == DAL_IRDA_STATE_BUSY_TX) && dmarequest) + { + /* Disable the IRDA DMA Tx request */ + CLEAR_BIT(hirda->Instance->CTRL3, USART_CTRL3_DMATXEN); + } + + dmarequest = DAL_IS_BIT_SET(hirda->Instance->CTRL3, USART_CTRL3_DMARXEN); + if ((hirda->RxState == DAL_IRDA_STATE_BUSY_RX) && dmarequest) + { + /* Disable PE and ERR (Frame error, noise error, overrun error) interrupts */ + CLEAR_BIT(hirda->Instance->CTRL1, USART_CTRL1_PEIEN); + CLEAR_BIT(hirda->Instance->CTRL3, USART_CTRL3_ERRIEN); + + /* Disable the IRDA DMA Rx request */ + CLEAR_BIT(hirda->Instance->CTRL3, USART_CTRL3_DMARXEN); + } + + /* Process Unlocked */ + __DAL_UNLOCK(hirda); + + return DAL_OK; +} + +/** + * @brief Resumes the DMA Transfer. + * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains + * the configuration information for the specified IRDA module. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_IRDA_DMAResume(IRDA_HandleTypeDef *hirda) +{ + /* Process Locked */ + __DAL_LOCK(hirda); + + if (hirda->gState == DAL_IRDA_STATE_BUSY_TX) + { + /* Enable the IRDA DMA Tx request */ + SET_BIT(hirda->Instance->CTRL3, USART_CTRL3_DMATXEN); + } + + if (hirda->RxState == DAL_IRDA_STATE_BUSY_RX) + { + /* Clear the Overrun flag before resuming the Rx transfer */ + __DAL_IRDA_CLEAR_OREFLAG(hirda); + + /* Re-enable PE and ERR (Frame error, noise error, overrun error) interrupts */ + if (hirda->Init.Parity != IRDA_PARITY_NONE) + { + SET_BIT(hirda->Instance->CTRL1, USART_CTRL1_PEIEN); + } + SET_BIT(hirda->Instance->CTRL3, USART_CTRL3_ERRIEN); + + /* Enable the IRDA DMA Rx request */ + SET_BIT(hirda->Instance->CTRL3, USART_CTRL3_DMARXEN); + } + + /* Process Unlocked */ + __DAL_UNLOCK(hirda); + + return DAL_OK; +} + +/** + * @brief Stops the DMA Transfer. + * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains + * the configuration information for the specified IRDA module. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_IRDA_DMAStop(IRDA_HandleTypeDef *hirda) +{ + uint32_t dmarequest = 0x00U; + /* The Lock is not implemented on this API to allow the user application + to call the DAL IRDA API under callbacks DAL_IRDA_TxCpltCallback() / DAL_IRDA_RxCpltCallback(): + when calling DAL_DMA_Abort() API the DMA TX/RX Transfer complete interrupt is generated + and the correspond call back is executed DAL_IRDA_TxCpltCallback() / DAL_IRDA_RxCpltCallback() + */ + + /* Stop IRDA DMA Tx request if ongoing */ + dmarequest = DAL_IS_BIT_SET(hirda->Instance->CTRL3, USART_CTRL3_DMATXEN); + if ((hirda->gState == DAL_IRDA_STATE_BUSY_TX) && dmarequest) + { + CLEAR_BIT(hirda->Instance->CTRL3, USART_CTRL3_DMATXEN); + + /* Abort the IRDA DMA Tx channel */ + if (hirda->hdmatx != NULL) + { + DAL_DMA_Abort(hirda->hdmatx); + } + IRDA_EndTxTransfer(hirda); + } + + /* Stop IRDA DMA Rx request if ongoing */ + dmarequest = DAL_IS_BIT_SET(hirda->Instance->CTRL3, USART_CTRL3_DMARXEN); + if ((hirda->RxState == DAL_IRDA_STATE_BUSY_RX) && dmarequest) + { + CLEAR_BIT(hirda->Instance->CTRL3, USART_CTRL3_DMARXEN); + + /* Abort the IRDA DMA Rx channel */ + if (hirda->hdmarx != NULL) + { + DAL_DMA_Abort(hirda->hdmarx); + } + IRDA_EndRxTransfer(hirda); + } + + return DAL_OK; +} + +/** + * @brief Abort ongoing transfers (blocking mode). + * @param hirda IRDA handle. + * @note This procedure could be used for aborting any ongoing transfer started in Interrupt or DMA mode. + * This procedure performs following operations : + * - Disable PPP Interrupts + * - Disable the DMA transfer in the peripheral register (if enabled) + * - Abort DMA transfer by calling DAL_DMA_Abort (in case of transfer in DMA mode) + * - Set handle State to READY + * @note This procedure is executed in blocking mode : when exiting function, Abort is considered as completed. + * @retval DAL status +*/ +DAL_StatusTypeDef DAL_IRDA_Abort(IRDA_HandleTypeDef *hirda) +{ + /* Disable TXEIE, TCIE, RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts */ + CLEAR_BIT(hirda->Instance->CTRL1, (USART_CTRL1_RXBNEIEN | USART_CTRL1_PEIEN | USART_CTRL1_TXBEIEN | USART_CTRL1_TXCIEN)); + CLEAR_BIT(hirda->Instance->CTRL3, USART_CTRL3_ERRIEN); + + /* Disable the IRDA DMA Tx request if enabled */ + if (DAL_IS_BIT_SET(hirda->Instance->CTRL3, USART_CTRL3_DMATXEN)) + { + CLEAR_BIT(hirda->Instance->CTRL3, USART_CTRL3_DMATXEN); + + /* Abort the IRDA DMA Tx channel : use blocking DMA Abort API (no callback) */ + if (hirda->hdmatx != NULL) + { + /* Set the IRDA DMA Abort callback to Null. + No call back execution at end of DMA abort procedure */ + hirda->hdmatx->XferAbortCallback = NULL; + + DAL_DMA_Abort(hirda->hdmatx); + } + } + + /* Disable the IRDA DMA Rx request if enabled */ + if (DAL_IS_BIT_SET(hirda->Instance->CTRL3, USART_CTRL3_DMARXEN)) + { + CLEAR_BIT(hirda->Instance->CTRL3, USART_CTRL3_DMARXEN); + + /* Abort the IRDA DMA Rx channel : use blocking DMA Abort API (no callback) */ + if (hirda->hdmarx != NULL) + { + /* Set the IRDA DMA Abort callback to Null. + No call back execution at end of DMA abort procedure */ + hirda->hdmarx->XferAbortCallback = NULL; + + DAL_DMA_Abort(hirda->hdmarx); + } + } + + /* Reset Tx and Rx transfer counters */ + hirda->TxXferCount = 0x00U; + hirda->RxXferCount = 0x00U; + + /* Reset ErrorCode */ + hirda->ErrorCode = DAL_IRDA_ERROR_NONE; + + /* Restore hirda->RxState and hirda->gState to Ready */ + hirda->RxState = DAL_IRDA_STATE_READY; + hirda->gState = DAL_IRDA_STATE_READY; + + return DAL_OK; +} + +/** + * @brief Abort ongoing Transmit transfer (blocking mode). + * @param hirda IRDA handle. + * @note This procedure could be used for aborting any ongoing transfer started in Interrupt or DMA mode. + * This procedure performs following operations : + * - Disable PPP Interrupts + * - Disable the DMA transfer in the peripheral register (if enabled) + * - Abort DMA transfer by calling DAL_DMA_Abort (in case of transfer in DMA mode) + * - Set handle State to READY + * @note This procedure is executed in blocking mode : when exiting function, Abort is considered as completed. + * @retval DAL status +*/ +DAL_StatusTypeDef DAL_IRDA_AbortTransmit(IRDA_HandleTypeDef *hirda) +{ + /* Disable TXEIE and TCIE interrupts */ + CLEAR_BIT(hirda->Instance->CTRL1, (USART_CTRL1_TXBEIEN | USART_CTRL1_TXCIEN)); + + /* Disable the IRDA DMA Tx request if enabled */ + if (DAL_IS_BIT_SET(hirda->Instance->CTRL3, USART_CTRL3_DMATXEN)) + { + CLEAR_BIT(hirda->Instance->CTRL3, USART_CTRL3_DMATXEN); + + /* Abort the IRDA DMA Tx channel : use blocking DMA Abort API (no callback) */ + if (hirda->hdmatx != NULL) + { + /* Set the IRDA DMA Abort callback to Null. + No call back execution at end of DMA abort procedure */ + hirda->hdmatx->XferAbortCallback = NULL; + + DAL_DMA_Abort(hirda->hdmatx); + } + } + + /* Reset Tx transfer counter */ + hirda->TxXferCount = 0x00U; + + /* Restore hirda->gState to Ready */ + hirda->gState = DAL_IRDA_STATE_READY; + + return DAL_OK; +} + +/** + * @brief Abort ongoing Receive transfer (blocking mode). + * @param hirda IRDA handle. + * @note This procedure could be used for aborting any ongoing transfer started in Interrupt or DMA mode. + * This procedure performs following operations : + * - Disable PPP Interrupts + * - Disable the DMA transfer in the peripheral register (if enabled) + * - Abort DMA transfer by calling DAL_DMA_Abort (in case of transfer in DMA mode) + * - Set handle State to READY + * @note This procedure is executed in blocking mode : when exiting function, Abort is considered as completed. + * @retval DAL status +*/ +DAL_StatusTypeDef DAL_IRDA_AbortReceive(IRDA_HandleTypeDef *hirda) +{ + /* Disable RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts */ + CLEAR_BIT(hirda->Instance->CTRL1, (USART_CTRL1_RXBNEIEN | USART_CTRL1_PEIEN)); + CLEAR_BIT(hirda->Instance->CTRL3, USART_CTRL3_ERRIEN); + + /* Disable the IRDA DMA Rx request if enabled */ + if (DAL_IS_BIT_SET(hirda->Instance->CTRL3, USART_CTRL3_DMARXEN)) + { + CLEAR_BIT(hirda->Instance->CTRL3, USART_CTRL3_DMARXEN); + + /* Abort the IRDA DMA Rx channel : use blocking DMA Abort API (no callback) */ + if (hirda->hdmarx != NULL) + { + /* Set the IRDA DMA Abort callback to Null. + No call back execution at end of DMA abort procedure */ + hirda->hdmarx->XferAbortCallback = NULL; + + DAL_DMA_Abort(hirda->hdmarx); + } + } + + /* Reset Rx transfer counter */ + hirda->RxXferCount = 0x00U; + + /* Restore hirda->RxState to Ready */ + hirda->RxState = DAL_IRDA_STATE_READY; + + return DAL_OK; +} + +/** + * @brief Abort ongoing transfers (Interrupt mode). + * @param hirda IRDA handle. + * @note This procedure could be used for aborting any ongoing transfer started in Interrupt or DMA mode. + * This procedure performs following operations : + * - Disable PPP Interrupts + * - Disable the DMA transfer in the peripheral register (if enabled) + * - Abort DMA transfer by calling DAL_DMA_Abort_IT (in case of transfer in DMA mode) + * - Set handle State to READY + * - At abort completion, call user abort complete callback + * @note This procedure is executed in Interrupt mode, meaning that abort procedure could be + * considered as completed only when user abort complete callback is executed (not when exiting function). + * @retval DAL status +*/ +DAL_StatusTypeDef DAL_IRDA_Abort_IT(IRDA_HandleTypeDef *hirda) +{ + uint32_t AbortCplt = 0x01U; + + /* Disable TXEIE, TCIE, RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts */ + CLEAR_BIT(hirda->Instance->CTRL1, (USART_CTRL1_RXBNEIEN | USART_CTRL1_PEIEN | USART_CTRL1_TXBEIEN | USART_CTRL1_TXCIEN)); + CLEAR_BIT(hirda->Instance->CTRL3, USART_CTRL3_ERRIEN); + + /* If DMA Tx and/or DMA Rx Handles are associated to IRDA Handle, DMA Abort complete callbacks should be initialised + before any call to DMA Abort functions */ + /* DMA Tx Handle is valid */ + if (hirda->hdmatx != NULL) + { + /* Set DMA Abort Complete callback if IRDA DMA Tx request if enabled. + Otherwise, set it to NULL */ + if (DAL_IS_BIT_SET(hirda->Instance->CTRL3, USART_CTRL3_DMATXEN)) + { + hirda->hdmatx->XferAbortCallback = IRDA_DMATxAbortCallback; + } + else + { + hirda->hdmatx->XferAbortCallback = NULL; + } + } + /* DMA Rx Handle is valid */ + if (hirda->hdmarx != NULL) + { + /* Set DMA Abort Complete callback if IRDA DMA Rx request if enabled. + Otherwise, set it to NULL */ + if (DAL_IS_BIT_SET(hirda->Instance->CTRL3, USART_CTRL3_DMARXEN)) + { + hirda->hdmarx->XferAbortCallback = IRDA_DMARxAbortCallback; + } + else + { + hirda->hdmarx->XferAbortCallback = NULL; + } + } + + /* Disable the IRDA DMA Tx request if enabled */ + if (DAL_IS_BIT_SET(hirda->Instance->CTRL3, USART_CTRL3_DMATXEN)) + { + /* Disable DMA Tx at IRDA level */ + CLEAR_BIT(hirda->Instance->CTRL3, USART_CTRL3_DMATXEN); + + /* Abort the IRDA DMA Tx channel : use non blocking DMA Abort API (callback) */ + if (hirda->hdmatx != NULL) + { + /* IRDA Tx DMA Abort callback has already been initialised : + will lead to call DAL_IRDA_AbortCpltCallback() at end of DMA abort procedure */ + + /* Abort DMA TX */ + if (DAL_DMA_Abort_IT(hirda->hdmatx) != DAL_OK) + { + hirda->hdmatx->XferAbortCallback = NULL; + } + else + { + AbortCplt = 0x00U; + } + } + } + + /* Disable the IRDA DMA Rx request if enabled */ + if (DAL_IS_BIT_SET(hirda->Instance->CTRL3, USART_CTRL3_DMARXEN)) + { + CLEAR_BIT(hirda->Instance->CTRL3, USART_CTRL3_DMARXEN); + + /* Abort the IRDA DMA Rx channel : use non blocking DMA Abort API (callback) */ + if (hirda->hdmarx != NULL) + { + /* IRDA Rx DMA Abort callback has already been initialised : + will lead to call DAL_IRDA_AbortCpltCallback() at end of DMA abort procedure */ + + /* Abort DMA RX */ + if (DAL_DMA_Abort_IT(hirda->hdmarx) != DAL_OK) + { + hirda->hdmarx->XferAbortCallback = NULL; + AbortCplt = 0x01U; + } + else + { + AbortCplt = 0x00U; + } + } + } + + /* if no DMA abort complete callback execution is required => call user Abort Complete callback */ + if (AbortCplt == 0x01U) + { + /* Reset Tx and Rx transfer counters */ + hirda->TxXferCount = 0x00U; + hirda->RxXferCount = 0x00U; + + /* Reset ErrorCode */ + hirda->ErrorCode = DAL_IRDA_ERROR_NONE; + + /* Restore hirda->gState and hirda->RxState to Ready */ + hirda->gState = DAL_IRDA_STATE_READY; + hirda->RxState = DAL_IRDA_STATE_READY; + + /* As no DMA to be aborted, call directly user Abort complete callback */ +#if (USE_DAL_IRDA_REGISTER_CALLBACKS == 1) + /* Call registered Abort complete callback */ + hirda->AbortCpltCallback(hirda); +#else + /* Call legacy weak Abort complete callback */ + DAL_IRDA_AbortCpltCallback(hirda); +#endif /* USE_DAL_IRDA_REGISTER_CALLBACK */ + } + + return DAL_OK; +} + +/** + * @brief Abort ongoing Transmit transfer (Interrupt mode). + * @param hirda IRDA handle. + * @note This procedure could be used for aborting any ongoing transfer started in Interrupt or DMA mode. + * This procedure performs following operations : + * - Disable IRDA Interrupts (Tx) + * - Disable the DMA transfer in the peripheral register (if enabled) + * - Abort DMA transfer by calling DAL_DMA_Abort_IT (in case of transfer in DMA mode) + * - Set handle State to READY + * - At abort completion, call user abort complete callback + * @note This procedure is executed in Interrupt mode, meaning that abort procedure could be + * considered as completed only when user abort complete callback is executed (not when exiting function). + * @retval DAL status +*/ +DAL_StatusTypeDef DAL_IRDA_AbortTransmit_IT(IRDA_HandleTypeDef *hirda) +{ + /* Disable TXEIE and TCIE interrupts */ + CLEAR_BIT(hirda->Instance->CTRL1, (USART_CTRL1_TXBEIEN | USART_CTRL1_TXCIEN)); + + /* Disable the IRDA DMA Tx request if enabled */ + if (DAL_IS_BIT_SET(hirda->Instance->CTRL3, USART_CTRL3_DMATXEN)) + { + CLEAR_BIT(hirda->Instance->CTRL3, USART_CTRL3_DMATXEN); + + /* Abort the IRDA DMA Tx channel : use non blocking DMA Abort API (callback) */ + if (hirda->hdmatx != NULL) + { + /* Set the IRDA DMA Abort callback : + will lead to call DAL_IRDA_AbortCpltCallback() at end of DMA abort procedure */ + hirda->hdmatx->XferAbortCallback = IRDA_DMATxOnlyAbortCallback; + + /* Abort DMA TX */ + if (DAL_DMA_Abort_IT(hirda->hdmatx) != DAL_OK) + { + /* Call Directly hirda->hdmatx->XferAbortCallback function in case of error */ + hirda->hdmatx->XferAbortCallback(hirda->hdmatx); + } + } + else + { + /* Reset Tx transfer counter */ + hirda->TxXferCount = 0x00U; + + /* Restore hirda->gState to Ready */ + hirda->gState = DAL_IRDA_STATE_READY; + + /* As no DMA to be aborted, call directly user Abort complete callback */ +#if (USE_DAL_IRDA_REGISTER_CALLBACKS == 1) + /* Call registered Abort Transmit Complete Callback */ + hirda->AbortTransmitCpltCallback(hirda); +#else + /* Call legacy weak Abort Transmit Complete Callback */ + DAL_IRDA_AbortTransmitCpltCallback(hirda); +#endif /* USE_DAL_IRDA_REGISTER_CALLBACK */ + } + } + else + { + /* Reset Tx transfer counter */ + hirda->TxXferCount = 0x00U; + + /* Restore hirda->gState to Ready */ + hirda->gState = DAL_IRDA_STATE_READY; + + /* As no DMA to be aborted, call directly user Abort complete callback */ +#if (USE_DAL_IRDA_REGISTER_CALLBACKS == 1) + /* Call registered Abort Transmit Complete Callback */ + hirda->AbortTransmitCpltCallback(hirda); +#else + /* Call legacy weak Abort Transmit Complete Callback */ + DAL_IRDA_AbortTransmitCpltCallback(hirda); +#endif /* USE_DAL_IRDA_REGISTER_CALLBACK */ + } + + return DAL_OK; +} + +/** + * @brief Abort ongoing Receive transfer (Interrupt mode). + * @param hirda IRDA handle. + * @note This procedure could be used for aborting any ongoing transfer started in Interrupt or DMA mode. + * This procedure performs following operations : + * - Disable PPP Interrupts + * - Disable the DMA transfer in the peripheral register (if enabled) + * - Abort DMA transfer by calling DAL_DMA_Abort_IT (in case of transfer in DMA mode) + * - Set handle State to READY + * - At abort completion, call user abort complete callback + * @note This procedure is executed in Interrupt mode, meaning that abort procedure could be + * considered as completed only when user abort complete callback is executed (not when exiting function). + * @retval DAL status +*/ +DAL_StatusTypeDef DAL_IRDA_AbortReceive_IT(IRDA_HandleTypeDef *hirda) +{ + /* Disable RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts */ + CLEAR_BIT(hirda->Instance->CTRL1, (USART_CTRL1_RXBNEIEN | USART_CTRL1_PEIEN)); + CLEAR_BIT(hirda->Instance->CTRL3, USART_CTRL3_ERRIEN); + + /* Disable the IRDA DMA Rx request if enabled */ + if (DAL_IS_BIT_SET(hirda->Instance->CTRL3, USART_CTRL3_DMARXEN)) + { + CLEAR_BIT(hirda->Instance->CTRL3, USART_CTRL3_DMARXEN); + + /* Abort the IRDA DMA Rx channel : use non blocking DMA Abort API (callback) */ + if (hirda->hdmarx != NULL) + { + /* Set the IRDA DMA Abort callback : + will lead to call DAL_IRDA_AbortCpltCallback() at end of DMA abort procedure */ + hirda->hdmarx->XferAbortCallback = IRDA_DMARxOnlyAbortCallback; + + /* Abort DMA RX */ + if (DAL_DMA_Abort_IT(hirda->hdmarx) != DAL_OK) + { + /* Call Directly hirda->hdmarx->XferAbortCallback function in case of error */ + hirda->hdmarx->XferAbortCallback(hirda->hdmarx); + } + } + else + { + /* Reset Rx transfer counter */ + hirda->RxXferCount = 0x00U; + + /* Restore hirda->RxState to Ready */ + hirda->RxState = DAL_IRDA_STATE_READY; + + /* As no DMA to be aborted, call directly user Abort complete callback */ +#if (USE_DAL_IRDA_REGISTER_CALLBACKS == 1) + /* Call registered Abort Receive Complete Callback */ + hirda->AbortReceiveCpltCallback(hirda); +#else + /* Call legacy weak Abort Receive Complete Callback */ + DAL_IRDA_AbortReceiveCpltCallback(hirda); +#endif /* USE_DAL_IRDA_REGISTER_CALLBACK */ + } + } + else + { + /* Reset Rx transfer counter */ + hirda->RxXferCount = 0x00U; + + /* Restore hirda->RxState to Ready */ + hirda->RxState = DAL_IRDA_STATE_READY; + + /* As no DMA to be aborted, call directly user Abort complete callback */ +#if (USE_DAL_IRDA_REGISTER_CALLBACKS == 1) + /* Call registered Abort Receive Complete Callback */ + hirda->AbortReceiveCpltCallback(hirda); +#else + /* Call legacy weak Abort Receive Complete Callback */ + DAL_IRDA_AbortReceiveCpltCallback(hirda); +#endif /* USE_DAL_IRDA_REGISTER_CALLBACK */ + } + + return DAL_OK; +} + +/** + * @brief This function handles IRDA interrupt request. + * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains + * the configuration information for the specified IRDA module. + * @retval None + */ +void DAL_IRDA_IRQHandler(IRDA_HandleTypeDef *hirda) +{ + uint32_t isrflags = READ_REG(hirda->Instance->STS); + uint32_t cr1its = READ_REG(hirda->Instance->CTRL1); + uint32_t cr3its = READ_REG(hirda->Instance->CTRL3); + uint32_t errorflags = 0x00U; + uint32_t dmarequest = 0x00U; + + /* If no error occurs */ + errorflags = (isrflags & (uint32_t)(USART_STS_PEFLG | USART_STS_FEFLG | USART_STS_OVREFLG | USART_STS_NEFLG)); + if (errorflags == RESET) + { + /* IRDA in mode Receiver -----------------------------------------------*/ + if (((isrflags & USART_STS_RXBNEFLG) != RESET) && ((cr1its & USART_CTRL1_RXBNEIEN) != RESET)) + { + IRDA_Receive_IT(hirda); + return; + } + } + + /* If some errors occur */ + if ((errorflags != RESET) && (((cr3its & USART_CTRL3_ERRIEN) != RESET) || ((cr1its & (USART_CTRL1_RXBNEIEN | USART_CTRL1_PEIEN)) != RESET))) + { + /* IRDA parity error interrupt occurred -------------------------------*/ + if (((isrflags & USART_STS_PEFLG) != RESET) && ((cr1its & USART_CTRL1_PEIEN) != RESET)) + { + hirda->ErrorCode |= DAL_IRDA_ERROR_PE; + } + + /* IRDA noise error interrupt occurred --------------------------------*/ + if (((isrflags & USART_STS_NEFLG) != RESET) && ((cr3its & USART_CTRL3_ERRIEN) != RESET)) + { + hirda->ErrorCode |= DAL_IRDA_ERROR_NE; + } + + /* IRDA frame error interrupt occurred --------------------------------*/ + if (((isrflags & USART_STS_FEFLG) != RESET) && ((cr3its & USART_CTRL3_ERRIEN) != RESET)) + { + hirda->ErrorCode |= DAL_IRDA_ERROR_FE; + } + + /* IRDA Over-Run interrupt occurred -----------------------------------*/ + if (((isrflags & USART_STS_OVREFLG) != RESET) && (((cr1its & USART_CTRL1_RXBNEIEN) != RESET) || ((cr3its & USART_CTRL3_ERRIEN) != RESET))) + { + hirda->ErrorCode |= DAL_IRDA_ERROR_ORE; + } + /* Call IRDA Error Call back function if need be -----------------------*/ + if (hirda->ErrorCode != DAL_IRDA_ERROR_NONE) + { + /* IRDA in mode Receiver ---------------------------------------------*/ + if (((isrflags & USART_STS_RXBNEFLG) != RESET) && ((cr1its & USART_CTRL1_RXBNEIEN) != RESET)) + { + IRDA_Receive_IT(hirda); + } + + /* If Overrun error occurs, or if any error occurs in DMA mode reception, + consider error as blocking */ + dmarequest = DAL_IS_BIT_SET(hirda->Instance->CTRL3, USART_CTRL3_DMARXEN); + if (((hirda->ErrorCode & DAL_IRDA_ERROR_ORE) != RESET) || dmarequest) + { + /* Blocking error : transfer is aborted + Set the IRDA state ready to be able to start again the process, + Disable Rx Interrupts, and disable Rx DMA request, if ongoing */ + IRDA_EndRxTransfer(hirda); + + /* Disable the IRDA DMA Rx request if enabled */ + if (DAL_IS_BIT_SET(hirda->Instance->CTRL3, USART_CTRL3_DMARXEN)) + { + CLEAR_BIT(hirda->Instance->CTRL3, USART_CTRL3_DMARXEN); + + /* Abort the IRDA DMA Rx channel */ + if (hirda->hdmarx != NULL) + { + /* Set the IRDA DMA Abort callback : + will lead to call DAL_IRDA_ErrorCallback() at end of DMA abort procedure */ + hirda->hdmarx->XferAbortCallback = IRDA_DMAAbortOnError; + + /* Abort DMA RX */ + if (DAL_DMA_Abort_IT(hirda->hdmarx) != DAL_OK) + { + /* Call Directly XferAbortCallback function in case of error */ + hirda->hdmarx->XferAbortCallback(hirda->hdmarx); + } + } + else + { +#if (USE_DAL_IRDA_REGISTER_CALLBACKS == 1) + /* Call registered user error callback */ + hirda->ErrorCallback(hirda); +#else + /* Call legacy weak user error callback */ + DAL_IRDA_ErrorCallback(hirda); +#endif /* USE_DAL_IRDA_REGISTER_CALLBACK */ + } + } + else + { +#if (USE_DAL_IRDA_REGISTER_CALLBACKS == 1) + /* Call registered user error callback */ + hirda->ErrorCallback(hirda); +#else + /* Call legacy weak user error callback */ + DAL_IRDA_ErrorCallback(hirda); +#endif /* USE_DAL_IRDA_REGISTER_CALLBACK */ + } + } + else + { + /* Non Blocking error : transfer could go on. + Error is notified to user through user error callback */ +#if (USE_DAL_IRDA_REGISTER_CALLBACKS == 1) + /* Call registered user error callback */ + hirda->ErrorCallback(hirda); +#else + /* Call legacy weak user error callback */ + DAL_IRDA_ErrorCallback(hirda); +#endif /* USE_DAL_IRDA_REGISTER_CALLBACK */ + + hirda->ErrorCode = DAL_IRDA_ERROR_NONE; + } + } + return; + } /* End if some error occurs */ + + /* IRDA in mode Transmitter ------------------------------------------------*/ + if (((isrflags & USART_STS_TXBEFLG) != RESET) && ((cr1its & USART_CTRL1_TXBEIEN) != RESET)) + { + IRDA_Transmit_IT(hirda); + return; + } + + /* IRDA in mode Transmitter end --------------------------------------------*/ + if (((isrflags & USART_STS_TXCFLG) != RESET) && ((cr1its & USART_CTRL1_TXCIEN) != RESET)) + { + IRDA_EndTransmit_IT(hirda); + return; + } +} + +/** + * @brief Tx Transfer complete callback. + * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains + * the configuration information for the specified IRDA module. + * @retval None + */ +__weak void DAL_IRDA_TxCpltCallback(IRDA_HandleTypeDef *hirda) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hirda); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_IRDA_TxCpltCallback can be implemented in the user file. + */ +} + +/** + * @brief Tx Half Transfer completed callback. + * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains + * the configuration information for the specified USART module. + * @retval None + */ +__weak void DAL_IRDA_TxHalfCpltCallback(IRDA_HandleTypeDef *hirda) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hirda); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_IRDA_TxHalfCpltCallback can be implemented in the user file. + */ +} + +/** + * @brief Rx Transfer complete callback. + * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains + * the configuration information for the specified IRDA module. + * @retval None + */ +__weak void DAL_IRDA_RxCpltCallback(IRDA_HandleTypeDef *hirda) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hirda); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_IRDA_RxCpltCallback can be implemented in the user file. + */ +} + +/** + * @brief Rx Half Transfer complete callback. + * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains + * the configuration information for the specified IRDA module. + * @retval None + */ +__weak void DAL_IRDA_RxHalfCpltCallback(IRDA_HandleTypeDef *hirda) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hirda); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_IRDA_RxHalfCpltCallback can be implemented in the user file. + */ +} + +/** + * @brief IRDA error callback. + * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains + * the configuration information for the specified IRDA module. + * @retval None + */ +__weak void DAL_IRDA_ErrorCallback(IRDA_HandleTypeDef *hirda) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hirda); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_IRDA_ErrorCallback can be implemented in the user file. + */ +} + +/** + * @brief IRDA Abort Complete callback. + * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains + * the configuration information for the specified IRDA module. + * @retval None + */ +__weak void DAL_IRDA_AbortCpltCallback(IRDA_HandleTypeDef *hirda) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hirda); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_IRDA_AbortCpltCallback can be implemented in the user file. + */ +} + +/** + * @brief IRDA Abort Transmit Complete callback. + * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains + * the configuration information for the specified IRDA module. + * @retval None + */ +__weak void DAL_IRDA_AbortTransmitCpltCallback(IRDA_HandleTypeDef *hirda) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hirda); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_IRDA_AbortTransmitCpltCallback can be implemented in the user file. + */ +} + +/** + * @brief IRDA Abort Receive Complete callback. + * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains + * the configuration information for the specified IRDA module. + * @retval None + */ +__weak void DAL_IRDA_AbortReceiveCpltCallback(IRDA_HandleTypeDef *hirda) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hirda); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_IRDA_AbortReceiveCpltCallback can be implemented in the user file. + */ +} + +/** + * @} + */ + +/** @defgroup IRDA_Exported_Functions_Group3 Peripheral State and Errors functions + * @brief IRDA State and Errors functions + * +@verbatim + ============================================================================== + ##### Peripheral State and Errors functions ##### + ============================================================================== + [..] + This subsection provides a set of functions allowing to return the State of IrDA + communication process and also return Peripheral Errors occurred during communication process + (+) DAL_IRDA_GetState() API can be helpful to check in run-time the state of the IrDA peripheral. + (+) DAL_IRDA_GetError() check in run-time errors that could be occurred during communication. + +@endverbatim + * @{ + */ + +/** + * @brief Return the IRDA state. + * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains + * the configuration information for the specified IRDA. + * @retval DAL state + */ +DAL_IRDA_StateTypeDef DAL_IRDA_GetState(IRDA_HandleTypeDef *hirda) +{ + uint32_t temp1 = 0x00U, temp2 = 0x00U; + temp1 = hirda->gState; + temp2 = hirda->RxState; + + return (DAL_IRDA_StateTypeDef)(temp1 | temp2); +} + +/** + * @brief Return the IRDA error code + * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains + * the configuration information for the specified IRDA. + * @retval IRDA Error Code + */ +uint32_t DAL_IRDA_GetError(IRDA_HandleTypeDef *hirda) +{ + return hirda->ErrorCode; +} + +/** + * @} + */ + +/** + * @} + */ + +/** @defgroup IRDA_Private_Functions IRDA Private Functions + * @{ + */ + +#if (USE_DAL_IRDA_REGISTER_CALLBACKS == 1) +/** + * @brief Initialize the callbacks to their default values. + * @param hirda IRDA handle. + * @retval none + */ +void IRDA_InitCallbacksToDefault(IRDA_HandleTypeDef *hirda) +{ + /* Init the IRDA Callback settings */ + hirda->TxHalfCpltCallback = DAL_IRDA_TxHalfCpltCallback; /* Legacy weak TxHalfCpltCallback */ + hirda->TxCpltCallback = DAL_IRDA_TxCpltCallback; /* Legacy weak TxCpltCallback */ + hirda->RxHalfCpltCallback = DAL_IRDA_RxHalfCpltCallback; /* Legacy weak RxHalfCpltCallback */ + hirda->RxCpltCallback = DAL_IRDA_RxCpltCallback; /* Legacy weak RxCpltCallback */ + hirda->ErrorCallback = DAL_IRDA_ErrorCallback; /* Legacy weak ErrorCallback */ + hirda->AbortCpltCallback = DAL_IRDA_AbortCpltCallback; /* Legacy weak AbortCpltCallback */ + hirda->AbortTransmitCpltCallback = DAL_IRDA_AbortTransmitCpltCallback; /* Legacy weak AbortTransmitCpltCallback */ + hirda->AbortReceiveCpltCallback = DAL_IRDA_AbortReceiveCpltCallback; /* Legacy weak AbortReceiveCpltCallback */ + +} +#endif /* USE_DAL_IRDA_REGISTER_CALLBACKS */ + +/** + * @brief DMA IRDA transmit process complete callback. + * @param hdma Pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA. + * @retval None + */ +static void IRDA_DMATransmitCplt(DMA_HandleTypeDef *hdma) +{ + IRDA_HandleTypeDef *hirda = (IRDA_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + /* DMA Normal mode */ + if ((hdma->Instance->SCFG & DMA_SCFGx_CIRCMEN) == 0U) + { + hirda->TxXferCount = 0U; + + /* Disable the DMA transfer for transmit request by resetting the DMAT bit + in the IRDA CTRL3 register */ + CLEAR_BIT(hirda->Instance->CTRL3, USART_CTRL3_DMATXEN); + + /* Enable the IRDA Transmit Complete Interrupt */ + SET_BIT(hirda->Instance->CTRL1, USART_CTRL1_TXCIEN); + } + /* DMA Circular mode */ + else + { +#if (USE_DAL_IRDA_REGISTER_CALLBACKS == 1) + /* Call registered Tx complete callback */ + hirda->TxCpltCallback(hirda); +#else + /* Call legacy weak Tx complete callback */ + DAL_IRDA_TxCpltCallback(hirda); +#endif /* USE_DAL_IRDA_REGISTER_CALLBACK */ + } +} + +/** + * @brief DMA IRDA receive process half complete callback + * @param hdma Pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA. + * @retval None + */ +static void IRDA_DMATransmitHalfCplt(DMA_HandleTypeDef *hdma) +{ + IRDA_HandleTypeDef *hirda = (IRDA_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + +#if (USE_DAL_IRDA_REGISTER_CALLBACKS == 1) + /* Call registered Tx Half complete callback */ + hirda->TxHalfCpltCallback(hirda); +#else + /* Call legacy weak Tx complete callback */ + DAL_IRDA_TxHalfCpltCallback(hirda); +#endif /* USE_DAL_IRDA_REGISTER_CALLBACK */ +} + +/** + * @brief DMA IRDA receive process complete callback. + * @param hdma Pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA. + * @retval None + */ +static void IRDA_DMAReceiveCplt(DMA_HandleTypeDef *hdma) +{ + IRDA_HandleTypeDef *hirda = (IRDA_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + + /* DMA Normal mode */ + if ((hdma->Instance->SCFG & DMA_SCFGx_CIRCMEN) == 0U) + { + hirda->RxXferCount = 0U; + + /* Disable PE and ERR (Frame error, noise error, overrun error) interrupts */ + CLEAR_BIT(hirda->Instance->CTRL1, USART_CTRL1_PEIEN); + CLEAR_BIT(hirda->Instance->CTRL3, USART_CTRL3_ERRIEN); + + /* Disable the DMA transfer for the receiver request by resetting the DMAR bit + in the IRDA CTRL3 register */ + CLEAR_BIT(hirda->Instance->CTRL3, USART_CTRL3_DMARXEN); + + /* At end of Rx process, restore hirda->RxState to Ready */ + hirda->RxState = DAL_IRDA_STATE_READY; + } + +#if (USE_DAL_IRDA_REGISTER_CALLBACKS == 1) + /* Call registered Rx complete callback */ + hirda->RxCpltCallback(hirda); +#else + /* Call legacy weak Rx complete callback */ + DAL_IRDA_RxCpltCallback(hirda); +#endif /* USE_DAL_IRDA_REGISTER_CALLBACKS */ +} + +/** + * @brief DMA IRDA receive process half complete callback. + * @param hdma Pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA. + * @retval None + */ +static void IRDA_DMAReceiveHalfCplt(DMA_HandleTypeDef *hdma) +{ + IRDA_HandleTypeDef *hirda = (IRDA_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + +#if (USE_DAL_IRDA_REGISTER_CALLBACKS == 1) + /*Call registered Rx Half complete callback*/ + hirda->RxHalfCpltCallback(hirda); +#else + /* Call legacy weak Rx Half complete callback */ + DAL_IRDA_RxHalfCpltCallback(hirda); +#endif /* USE_DAL_IRDA_REGISTER_CALLBACK */ +} + +/** + * @brief DMA IRDA communication error callback. + * @param hdma Pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA. + * @retval None + */ +static void IRDA_DMAError(DMA_HandleTypeDef *hdma) +{ + uint32_t dmarequest = 0x00U; + IRDA_HandleTypeDef *hirda = (IRDA_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + + /* Stop IRDA DMA Tx request if ongoing */ + dmarequest = DAL_IS_BIT_SET(hirda->Instance->CTRL3, USART_CTRL3_DMATXEN); + if ((hirda->gState == DAL_IRDA_STATE_BUSY_TX) && dmarequest) + { + hirda->TxXferCount = 0U; + IRDA_EndTxTransfer(hirda); + } + + /* Stop IRDA DMA Rx request if ongoing */ + dmarequest = DAL_IS_BIT_SET(hirda->Instance->CTRL3, USART_CTRL3_DMARXEN); + if ((hirda->RxState == DAL_IRDA_STATE_BUSY_RX) && dmarequest) + { + hirda->RxXferCount = 0U; + IRDA_EndRxTransfer(hirda); + } + + hirda->ErrorCode |= DAL_IRDA_ERROR_DMA; + +#if (USE_DAL_IRDA_REGISTER_CALLBACKS == 1) + /* Call registered user error callback */ + hirda->ErrorCallback(hirda); +#else + /* Call legacy weak user error callback */ + DAL_IRDA_ErrorCallback(hirda); +#endif /* USE_DAL_IRDA_REGISTER_CALLBACK */ +} + +/** + * @brief This function handles IRDA Communication Timeout. It waits + * until a flag is no longer in the specified status. + * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains + * the configuration information for the specified IRDA. + * @param Flag specifies the IRDA flag to check. + * @param Status The actual Flag status (SET or RESET). + * @param Tickstart Tick start value + * @param Timeout Timeout duration + * @retval DAL status + */ +static DAL_StatusTypeDef IRDA_WaitOnFlagUntilTimeout(IRDA_HandleTypeDef *hirda, uint32_t Flag, FlagStatus Status, uint32_t Tickstart, uint32_t Timeout) +{ + /* Wait until flag is set */ + while ((__DAL_IRDA_GET_FLAG(hirda, Flag) ? SET : RESET) == Status) + { + /* Check for the Timeout */ + if (Timeout != DAL_MAX_DELAY) + { + if ((Timeout == 0U) || ((DAL_GetTick() - Tickstart) > Timeout)) + { + /* Disable TXE, RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts for the interrupt process */ + CLEAR_BIT(hirda->Instance->CTRL1, (USART_CTRL1_RXBNEIEN | USART_CTRL1_PEIEN | USART_CTRL1_TXBEIEN)); + CLEAR_BIT(hirda->Instance->CTRL3, USART_CTRL3_ERRIEN); + + hirda->gState = DAL_IRDA_STATE_READY; + hirda->RxState = DAL_IRDA_STATE_READY; + + /* Process Unlocked */ + __DAL_UNLOCK(hirda); + + return DAL_TIMEOUT; + } + } + } + return DAL_OK; +} + +/** + * @brief End ongoing Tx transfer on IRDA peripheral (following error detection or Transmit completion). + * @param hirda IRDA handle. + * @retval None + */ +static void IRDA_EndTxTransfer(IRDA_HandleTypeDef *hirda) +{ + /* Disable TXEIE and TCIE interrupts */ + CLEAR_BIT(hirda->Instance->CTRL1, (USART_CTRL1_TXBEIEN | USART_CTRL1_TXCIEN)); + + /* At end of Tx process, restore hirda->gState to Ready */ + hirda->gState = DAL_IRDA_STATE_READY; +} + +/** + * @brief End ongoing Rx transfer on IRDA peripheral (following error detection or Reception completion). + * @param hirda IRDA handle. + * @retval None + */ +static void IRDA_EndRxTransfer(IRDA_HandleTypeDef *hirda) +{ + /* Disable RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts */ + CLEAR_BIT(hirda->Instance->CTRL1, (USART_CTRL1_RXBNEIEN | USART_CTRL1_PEIEN)); + CLEAR_BIT(hirda->Instance->CTRL3, USART_CTRL3_ERRIEN); + + /* At end of Rx process, restore hirda->RxState to Ready */ + hirda->RxState = DAL_IRDA_STATE_READY; +} + +/** + * @brief DMA IRDA communication abort callback, when initiated by DAL services on Error + * (To be called at end of DMA Abort procedure following error occurrence). + * @param hdma DMA handle. + * @retval None + */ +static void IRDA_DMAAbortOnError(DMA_HandleTypeDef *hdma) +{ + IRDA_HandleTypeDef *hirda = (IRDA_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + hirda->RxXferCount = 0x00U; + hirda->TxXferCount = 0x00U; + +#if (USE_DAL_IRDA_REGISTER_CALLBACKS == 1) + /* Call registered user error callback */ + hirda->ErrorCallback(hirda); +#else + /* Call legacy weak user error callback */ + DAL_IRDA_ErrorCallback(hirda); +#endif /* USE_DAL_IRDA_REGISTER_CALLBACK */ +} + +/** + * @brief DMA IRDA Tx communication abort callback, when initiated by user + * (To be called at end of DMA Tx Abort procedure following user abort request). + * @note When this callback is executed, User Abort complete call back is called only if no + * Abort still ongoing for Rx DMA Handle. + * @param hdma DMA handle. + * @retval None + */ +static void IRDA_DMATxAbortCallback(DMA_HandleTypeDef *hdma) +{ + IRDA_HandleTypeDef *hirda = (IRDA_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + + hirda->hdmatx->XferAbortCallback = NULL; + + /* Check if an Abort process is still ongoing */ + if (hirda->hdmarx != NULL) + { + if (hirda->hdmarx->XferAbortCallback != NULL) + { + return; + } + } + + /* No Abort process still ongoing : All DMA channels are aborted, call user Abort Complete callback */ + hirda->TxXferCount = 0x00U; + hirda->RxXferCount = 0x00U; + + /* Reset ErrorCode */ + hirda->ErrorCode = DAL_IRDA_ERROR_NONE; + + /* Restore hirda->gState and hirda->RxState to Ready */ + hirda->gState = DAL_IRDA_STATE_READY; + hirda->RxState = DAL_IRDA_STATE_READY; + + /* Call user Abort complete callback */ +#if (USE_DAL_IRDA_REGISTER_CALLBACKS == 1) + /* Call registered Abort complete callback */ + hirda->AbortCpltCallback(hirda); +#else + /* Call legacy weak Abort complete callback */ + DAL_IRDA_AbortCpltCallback(hirda); +#endif /* USE_DAL_IRDA_REGISTER_CALLBACK */ +} + +/** + * @brief DMA IRDA Rx communication abort callback, when initiated by user + * (To be called at end of DMA Rx Abort procedure following user abort request). + * @note When this callback is executed, User Abort complete call back is called only if no + * Abort still ongoing for Tx DMA Handle. + * @param hdma DMA handle. + * @retval None + */ +static void IRDA_DMARxAbortCallback(DMA_HandleTypeDef *hdma) +{ + IRDA_HandleTypeDef *hirda = (IRDA_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + + hirda->hdmarx->XferAbortCallback = NULL; + + /* Check if an Abort process is still ongoing */ + if (hirda->hdmatx != NULL) + { + if (hirda->hdmatx->XferAbortCallback != NULL) + { + return; + } + } + + /* No Abort process still ongoing : All DMA channels are aborted, call user Abort Complete callback */ + hirda->TxXferCount = 0x00U; + hirda->RxXferCount = 0x00U; + + /* Reset ErrorCode */ + hirda->ErrorCode = DAL_IRDA_ERROR_NONE; + + /* Restore hirda->gState and hirda->RxState to Ready */ + hirda->gState = DAL_IRDA_STATE_READY; + hirda->RxState = DAL_IRDA_STATE_READY; + + /* Call user Abort complete callback */ +#if (USE_DAL_IRDA_REGISTER_CALLBACKS == 1) + /* Call registered Abort complete callback */ + hirda->AbortCpltCallback(hirda); +#else + /* Call legacy weak Abort complete callback */ + DAL_IRDA_AbortCpltCallback(hirda); +#endif /* USE_DAL_IRDA_REGISTER_CALLBACK */ +} + +/** + * @brief DMA IRDA Tx communication abort callback, when initiated by user by a call to + * DAL_IRDA_AbortTransmit_IT API (Abort only Tx transfer) + * (This callback is executed at end of DMA Tx Abort procedure following user abort request, + * and leads to user Tx Abort Complete callback execution). + * @param hdma DMA handle. + * @retval None + */ +static void IRDA_DMATxOnlyAbortCallback(DMA_HandleTypeDef *hdma) +{ + IRDA_HandleTypeDef *hirda = (IRDA_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + + hirda->TxXferCount = 0x00U; + + /* Restore hirda->gState to Ready */ + hirda->gState = DAL_IRDA_STATE_READY; + + /* Call user Abort complete callback */ +#if (USE_DAL_IRDA_REGISTER_CALLBACKS == 1) + /* Call registered Abort Transmit Complete Callback */ + hirda->AbortTransmitCpltCallback(hirda); +#else + /* Call legacy weak Abort Transmit Complete Callback */ + DAL_IRDA_AbortTransmitCpltCallback(hirda); +#endif /* USE_DAL_IRDA_REGISTER_CALLBACK */ +} + +/** + * @brief DMA IRDA Rx communication abort callback, when initiated by user by a call to + * DAL_IRDA_AbortReceive_IT API (Abort only Rx transfer) + * (This callback is executed at end of DMA Rx Abort procedure following user abort request, + * and leads to user Rx Abort Complete callback execution). + * @param hdma DMA handle. + * @retval None + */ +static void IRDA_DMARxOnlyAbortCallback(DMA_HandleTypeDef *hdma) +{ + IRDA_HandleTypeDef *hirda = (IRDA_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + + hirda->RxXferCount = 0x00U; + + /* Restore hirda->RxState to Ready */ + hirda->RxState = DAL_IRDA_STATE_READY; + + /* Call user Abort complete callback */ +#if (USE_DAL_IRDA_REGISTER_CALLBACKS == 1) + /* Call registered Abort Receive Complete Callback */ + hirda->AbortReceiveCpltCallback(hirda); +#else + /* Call legacy weak Abort Receive Complete Callback */ + DAL_IRDA_AbortReceiveCpltCallback(hirda); +#endif /* USE_DAL_IRDA_REGISTER_CALLBACK */ +} + +/** + * @brief Send an amount of data in non blocking mode. + * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains + * the configuration information for the specified IRDA module. + * @retval DAL status + */ +static DAL_StatusTypeDef IRDA_Transmit_IT(IRDA_HandleTypeDef *hirda) +{ + const uint16_t *tmp; + + /* Check that a Tx process is ongoing */ + if (hirda->gState == DAL_IRDA_STATE_BUSY_TX) + { + if (hirda->Init.WordLength == IRDA_WORDLENGTH_9B) + { + tmp = (const uint16_t *) hirda->pTxBuffPtr; + hirda->Instance->DATA = (uint16_t)(*tmp & (uint16_t)0x01FF); + if (hirda->Init.Parity == IRDA_PARITY_NONE) + { + hirda->pTxBuffPtr += 2U; + } + else + { + hirda->pTxBuffPtr += 1U; + } + } + else + { + hirda->Instance->DATA = (uint8_t)(*hirda->pTxBuffPtr++ & (uint8_t)0x00FF); + } + + if (--hirda->TxXferCount == 0U) + { + /* Disable the IRDA Transmit Data Register Empty Interrupt */ + CLEAR_BIT(hirda->Instance->CTRL1, USART_CTRL1_TXBEIEN); + + /* Enable the IRDA Transmit Complete Interrupt */ + SET_BIT(hirda->Instance->CTRL1, USART_CTRL1_TXCIEN); + } + + return DAL_OK; + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief Wraps up transmission in non blocking mode. + * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains + * the configuration information for the specified IRDA module. + * @retval DAL status + */ +static DAL_StatusTypeDef IRDA_EndTransmit_IT(IRDA_HandleTypeDef *hirda) +{ + /* Disable the IRDA Transmit Complete Interrupt */ + CLEAR_BIT(hirda->Instance->CTRL1, USART_CTRL1_TXCIEN); + + /* Disable the IRDA Error Interrupt: (Frame error, noise error, overrun error) */ + CLEAR_BIT(hirda->Instance->CTRL3, USART_CTRL3_ERRIEN); + + /* Tx process is ended, restore hirda->gState to Ready */ + hirda->gState = DAL_IRDA_STATE_READY; + +#if (USE_DAL_IRDA_REGISTER_CALLBACKS == 1) + /* Call registered Tx complete callback */ + hirda->TxCpltCallback(hirda); +#else + /* Call legacy weak Tx complete callback */ + DAL_IRDA_TxCpltCallback(hirda); +#endif /* USE_DAL_IRDA_REGISTER_CALLBACK */ + + return DAL_OK; +} + +/** + * @brief Receives an amount of data in non blocking mode. + * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains + * the configuration information for the specified IRDA module. + * @retval DAL status + */ +static DAL_StatusTypeDef IRDA_Receive_IT(IRDA_HandleTypeDef *hirda) +{ + uint16_t *tmp; + uint16_t uhdata; + + /* Check that a Rx process is ongoing */ + if (hirda->RxState == DAL_IRDA_STATE_BUSY_RX) + { + uhdata = (uint16_t) READ_REG(hirda->Instance->DATA); + if (hirda->Init.WordLength == IRDA_WORDLENGTH_9B) + { + tmp = (uint16_t *) hirda->pRxBuffPtr; + if (hirda->Init.Parity == IRDA_PARITY_NONE) + { + *tmp = (uint16_t)(uhdata & (uint16_t)0x01FF); + hirda->pRxBuffPtr += 2U; + } + else + { + *tmp = (uint16_t)(uhdata & (uint16_t)0x00FF); + hirda->pRxBuffPtr += 1U; + } + } + else + { + if (hirda->Init.Parity == IRDA_PARITY_NONE) + { + *hirda->pRxBuffPtr++ = (uint8_t)(uhdata & (uint8_t)0x00FF); + } + else + { + *hirda->pRxBuffPtr++ = (uint8_t)(uhdata & (uint8_t)0x007F); + } + } + + if (--hirda->RxXferCount == 0U) + { + /* Disable the IRDA Data Register not empty Interrupt */ + CLEAR_BIT(hirda->Instance->CTRL1, USART_CTRL1_RXBNEIEN); + + /* Disable the IRDA Parity Error Interrupt */ + CLEAR_BIT(hirda->Instance->CTRL1, USART_CTRL1_PEIEN); + + /* Disable the IRDA Error Interrupt: (Frame error, noise error, overrun error) */ + CLEAR_BIT(hirda->Instance->CTRL3, USART_CTRL3_ERRIEN); + + /* Rx process is completed, restore hirda->RxState to Ready */ + hirda->RxState = DAL_IRDA_STATE_READY; + +#if (USE_DAL_IRDA_REGISTER_CALLBACKS == 1) + /* Call registered Rx complete callback */ + hirda->RxCpltCallback(hirda); +#else + /* Call legacy weak Rx complete callback */ + DAL_IRDA_RxCpltCallback(hirda); +#endif /* USE_DAL_IRDA_REGISTER_CALLBACKS */ + + return DAL_OK; + } + return DAL_OK; + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief Configures the IRDA peripheral. + * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains + * the configuration information for the specified IRDA module. + * @retval None + */ +static void IRDA_SetConfig(IRDA_HandleTypeDef *hirda) +{ + uint32_t pclk; + + /* Check the parameters */ + ASSERT_PARAM(IS_IRDA_INSTANCE(hirda->Instance)); + ASSERT_PARAM(IS_IRDA_BAUDRATE(hirda->Init.BaudRate)); + ASSERT_PARAM(IS_IRDA_WORD_LENGTH(hirda->Init.WordLength)); + ASSERT_PARAM(IS_IRDA_PARITY(hirda->Init.Parity)); + ASSERT_PARAM(IS_IRDA_MODE(hirda->Init.Mode)); + ASSERT_PARAM(IS_IRDA_POWERMODE(hirda->Init.IrDAMode)); + + /*-------------------------- USART CTRL2 Configuration ------------------------*/ + /* Clear STOP[13:12] bits */ + CLEAR_BIT(hirda->Instance->CTRL2, USART_CTRL2_STOPCFG); + + /*-------------------------- USART CTRL1 Configuration -----------------------*/ + /* Clear M, PCE, PS, TE and RE bits */ + CLEAR_BIT(hirda->Instance->CTRL1, (USART_CTRL1_DBLCFG | USART_CTRL1_PCEN | USART_CTRL1_PCFG | USART_CTRL1_TXEN | USART_CTRL1_RXEN)); + + /* Configure the USART Word Length, Parity and mode: + Set the M bits according to hirda->Init.WordLength value + Set PCE and PS bits according to hirda->Init.Parity value + Set TE and RE bits according to hirda->Init.Mode value */ + /* Write to USART CTRL1 */ + SET_BIT(hirda->Instance->CTRL1, (hirda->Init.WordLength | hirda->Init.Parity | hirda->Init.Mode)); + + /*-------------------------- USART CTRL3 Configuration -----------------------*/ + /* Clear CTSE and RTSE bits */ + CLEAR_BIT(hirda->Instance->CTRL3, (USART_CTRL3_RTSEN | USART_CTRL3_CTSEN)); + + /*-------------------------- USART BR Configuration -----------------------*/ +#if defined(USART6) && defined(UART9) && defined(UART10) + if ((hirda->Instance == USART1) || (hirda->Instance == USART6) || (hirda->Instance == UART9) || (hirda->Instance == UART10)) + { + pclk = DAL_RCM_GetPCLK2Freq(); + SET_BIT(hirda->Instance->BR, IRDA_BR(pclk, hirda->Init.BaudRate)); + } +#elif defined(USART6) + if((hirda->Instance == USART1) || (hirda->Instance == USART6)) + { + pclk = DAL_RCM_GetPCLK2Freq(); + SET_BIT(hirda->Instance->BR, IRDA_BR(pclk, hirda->Init.BaudRate)); + } +#else + if(hirda->Instance == USART1) + { + pclk = DAL_RCM_GetPCLK2Freq(); + SET_BIT(hirda->Instance->BR, IRDA_BR(pclk, hirda->Init.BaudRate)); + } +#endif /* USART6 */ + else + { + pclk = DAL_RCM_GetPCLK1Freq(); + SET_BIT(hirda->Instance->BR, IRDA_BR(pclk, hirda->Init.BaudRate)); + } +} + +/** + * @} + */ + +#endif /* DAL_IRDA_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_iwdt.c b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_iwdt.c new file mode 100644 index 0000000000..9c5a216c1e --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_iwdt.c @@ -0,0 +1,287 @@ +/** + * + * @file apm32f4xx_dal_iwdt.c + * @brief IWDT DAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the Independent Watchdog (IWDT) peripheral: + * + Initialization and Start functions + * + IO operation functions + * + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + * + @verbatim + ============================================================================== + ##### IWDT Generic features ##### + ============================================================================== + [..] + (+) The IWDT can be started by either software or hardware (configurable + through option byte). + + (+) The IWDT is clocked by the Low-Speed Internal clock (LSI) and thus stays + active even if the main clock fails. + + (+) Once the IWDT is started, the LSI is forced ON and both cannot be + disabled. The counter starts counting down from the reset value (0xFFF). + When it reaches the end of count value (0x000) a reset signal is + generated (IWDT reset). + + (+) Whenever the key value 0x0000 AAAA is written in the IWDT_KEY register, + the IWDT_CNTRLD value is reloaded into the counter and the watchdog reset + is prevented. + + (+) The IWDT is implemented in the VDD voltage domain that is still functional + in STOP and STANDBY mode (IWDT reset can wake up the CPU from STANDBY). + IWDTRST flag in RCM_CSTS register can be used to inform when an IWDT + reset occurs. + + (+) Debug mode: When the microcontroller enters debug mode (core halted), + the IWDT counter either continues to work normally or stops, depending + on DBG_IWDT_STOP configuration bit in DBG module, accessible through + __DAL_DBGMCU_FREEZE_IWDT() and __DAL_DBGMCU_UNFREEZE_IWDT() macros. + + [..] Min-max timeout value @32KHz (LSI): ~125us / ~32.7s + The IWDT timeout may vary due to LSI clock frequency dispersion. + APM32F4xx devices provide the capability to measure the LSI clock + frequency (LSI clock is internally connected to TMR5 CH4 input capture). + The measured value can be used to have an IWDT timeout with an + acceptable accuracy. + + [..] Default timeout value (necessary for IWDT_STS status register update): + Constant LSI_VALUE is defined based on the nominal LSI clock frequency. + This frequency being subject to variations as mentioned above, the + default timeout value (defined through constant DAL_IWDT_DEFAULT_TIMEOUT + below) may become too short or too long. + In such cases, this default timeout value can be tuned by redefining + the constant LSI_VALUE at user-application level (based, for instance, + on the measured LSI clock frequency as explained above). + + ##### How to use this driver ##### + ============================================================================== + [..] + (#) Use IWDT using DAL_IWDT_Init() function to : + (++) Enable instance by writing Start keyword in IWDT_KEY register. LSI + clock is forced ON and IWDT counter starts counting down. + (++) Enable write access to configuration registers: + IWDT_PSC and IWDT_CNTRLD. + (++) Configure the IWDT prescaler and counter reload value. This reload + value will be loaded in the IWDT counter each time the watchdog is + reloaded, then the IWDT will start counting down from this value. + (++) Wait for status flags to be reset. + + (#) Then the application program must refresh the IWDT counter at regular + intervals during normal operation to prevent an MCU reset, using + DAL_IWDT_Refresh() function. + + *** IWDT DAL driver macros list *** + ==================================== + [..] + Below the list of most used macros in IWDT DAL driver: + (+) __DAL_IWDT_START: Enable the IWDT peripheral + (+) __DAL_IWDT_RELOAD_COUNTER: Reloads IWDT counter with value defined in + the reload register + + @endverbatim + */ + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +#ifdef DAL_IWDT_MODULE_ENABLED +/** @addtogroup IWDT + * @brief IWDT DAL module driver. + * @{ + */ + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/** @defgroup IWDT_Private_Defines IWDT Private Defines + * @{ + */ +/* Status register needs up to 5 LSI clock periods divided by the clock + prescaler to be updated. The number of LSI clock periods is upper-rounded to + 6 for the timeout value calculation. + The timeout value is calculated using the highest prescaler (256) and + the LSI_VALUE constant. The value of this constant can be changed by the user + to take into account possible LSI clock period variations. + The timeout value is multiplied by 1000 to be converted in milliseconds. + LSI startup time is also considered here by adding LSI_STARTUP_TIME + converted in milliseconds. */ +#define DAL_IWDT_DEFAULT_TIMEOUT (((6UL * 256UL * 1000UL) / LSI_VALUE) + ((LSI_STARTUP_TIME / 1000UL) + 1UL)) +#define IWDT_KERNEL_UPDATE_FLAGS (IWDT_STS_CNTUFLG | IWDT_STS_PSCUFLG) +/** + * @} + */ + +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Exported functions --------------------------------------------------------*/ + +/** @addtogroup IWDT_Exported_Functions + * @{ + */ + +/** @addtogroup IWDT_Exported_Functions_Group1 + * @brief Initialization and Start functions. + * +@verbatim + =============================================================================== + ##### Initialization and Start functions ##### + =============================================================================== + [..] This section provides functions allowing to: + (+) Initialize the IWDT according to the specified parameters in the + IWDT_InitTypeDef of associated handle. + (+) Once initialization is performed in DAL_IWDT_Init function, Watchdog + is reloaded in order to exit function with correct time base. + +@endverbatim + * @{ + */ + +/** + * @brief Initialize the IWDT according to the specified parameters in the + * IWDT_InitTypeDef and start watchdog. Before exiting function, + * watchdog is refreshed in order to have correct time base. + * @param hiwdt pointer to a IWDT_HandleTypeDef structure that contains + * the configuration information for the specified IWDT module. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_IWDT_Init(IWDT_HandleTypeDef *hiwdt) +{ + uint32_t tickstart; + + /* Check the IWDT handle allocation */ + if (hiwdt == NULL) + { + return DAL_ERROR; + } + + /* Check the parameters */ + ASSERT_PARAM(IS_IWDT_ALL_INSTANCE(hiwdt->Instance)); + ASSERT_PARAM(IS_IWDT_PSCESCALER(hiwdt->Init.Prescaler)); + ASSERT_PARAM(IS_IWDT_RELOAD(hiwdt->Init.Reload)); + + /* Enable IWDT. LSI is turned on automatically */ + __DAL_IWDT_START(hiwdt); + + /* Enable write access to IWDT_PSC and IWDT_CNTRLD registers by writing + 0x5555 in KR */ + IWDT_ENABLE_WRITE_ACCESS(hiwdt); + + /* Write to IWDT registers the Prescaler & Reload values to work with */ + hiwdt->Instance->PSC = hiwdt->Init.Prescaler; + hiwdt->Instance->CNTRLD = hiwdt->Init.Reload; + + /* Check pending flag, if previous update not done, return timeout */ + tickstart = DAL_GetTick(); + + /* Wait for register to be updated */ + while ((hiwdt->Instance->STS & IWDT_KERNEL_UPDATE_FLAGS) != 0x00u) + { + if ((DAL_GetTick() - tickstart) > DAL_IWDT_DEFAULT_TIMEOUT) + { + if ((hiwdt->Instance->STS & IWDT_KERNEL_UPDATE_FLAGS) != 0x00u) + { + return DAL_TIMEOUT; + } + } + } + + /* Reload IWDT counter with value defined in the reload register */ + __DAL_IWDT_RELOAD_COUNTER(hiwdt); + + /* Return function status */ + return DAL_OK; +} + + +/** + * @} + */ + + +/** @addtogroup IWDT_Exported_Functions_Group2 + * @brief IO operation functions + * +@verbatim + =============================================================================== + ##### IO operation functions ##### + =============================================================================== + [..] This section provides functions allowing to: + (+) Refresh the IWDT. + +@endverbatim + * @{ + */ + +/** + * @brief Refresh the IWDT. + * @param hiwdt pointer to a IWDT_HandleTypeDef structure that contains + * the configuration information for the specified IWDT module. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_IWDT_Refresh(IWDT_HandleTypeDef *hiwdt) +{ + /* Reload IWDT counter with value defined in the reload register */ + __DAL_IWDT_RELOAD_COUNTER(hiwdt); + + /* Return function status */ + return DAL_OK; +} + + +/** + * @} + */ + +/** + * @} + */ + +#endif /* DAL_IWDT_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_log.c b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_log.c new file mode 100644 index 0000000000..3d56754268 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_log.c @@ -0,0 +1,97 @@ +/** + * + * @file apm32f4xx_dal_log.c + * @brief LOG DAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the LOG component. + * + * @attention + * + * Copyright (C) 2023 Geehy Semiconductor + * + * You may not use this file except in compliance with the + * GEEHY COPYRIGHT NOTICE (GEEHY SOFTWARE PACKAGE LICENSE). + * + * The program is only for reference, which is distributed in the hope + * that it will be useful and instructional for customers to develop + * their software. Unless required by applicable law or agreed to in + * writing, the program is distributed on an "AS IS" BASIS, WITHOUT + * ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied. + * See the GEEHY SOFTWARE PACKAGE LICENSE for the governing permissions + * and limitations under the License. + * + */ + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal.h" +#include + +/** @addtogroup APM32F4xx_DAL_Driver + @{ +*/ + +/** @defgroup LOG LOG + @{ +*/ + +#if (USE_LOG_COMPONENT == 1U) + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/** @addtogroup LOG_Private_Functions + * @{ + */ +/* Private function prototypes -----------------------------------------------*/ +static LOG_FUNC_T logCallback = &vprintf; + +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +/** @defgroup LOG_Exported_Functions LOG Exported Functions + * @{ + */ + +/** + * @brief Set log callback function + * + * @param callback: Log callback function + * + * @retval None + */ +void DAL_LOG_SetCallback(LOG_FUNC_T callback) +{ + logCallback = callback; +} + +/** + * @brief Print message into log + * + * @param format: Print message format + * + * @retval None + */ +void DAL_LOG_Print(const char *format, ...) +{ + va_list args; + va_start(args, format); + (*logCallback)(format, args); + va_end(args); + fflush(stdout); +} + +/** + * @} + */ + +#endif /* USE_LOG_COMPONENT */ +/** + * @} + */ + +/** + * @} + */ diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_mmc.c b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_mmc.c new file mode 100644 index 0000000000..b652ed3e86 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_mmc.c @@ -0,0 +1,3226 @@ +/** + * + * @file apm32f4xx_dal_mmc.c + * @brief MMC card DAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the Secure Digital (MMC) peripheral: + * + Initialization and de-initialization functions + * + IO operation functions + * + Peripheral Control functions + * + MMC card Control functions + * + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + * + @verbatim + ============================================================================== + ##### How to use this driver ##### + ============================================================================== + [..] + This driver implements a high level communication layer for read and write from/to + this memory. The needed APM32 hardware resources (SDMMC and GPIO) are performed by + the user in DAL_MMC_MspInit() function (MSP layer). + Basically, the MSP layer configuration should be the same as we provide in the + examples. + You can easily tailor this configuration according to hardware resources. + + [..] + This driver is a generic layered driver for SDMMC memories which uses the DAL + SDMMC driver functions to interface with MMC and eMMC cards devices. + It is used as follows: + + (#)Initialize the SDMMC low level resources by implement the DAL_MMC_MspInit() API: + (##) Enable the SDMMC interface clock using __DAL_RCM_SDMMC_CLK_ENABLE(); + (##) SDMMC pins configuration for MMC card + (+++) Enable the clock for the SDMMC GPIOs using the functions __DAL_RCM_GPIOx_CLK_ENABLE(); + (+++) Configure these SDMMC pins as alternate function pull-up using DAL_GPIO_Init() + and according to your pin assignment; + (##) DMA Configuration if you need to use DMA process (DAL_MMC_ReadBlocks_DMA() + and DAL_MMC_WriteBlocks_DMA() APIs). + (+++) Enable the DMAx interface clock using __DAL_RCM_DMAx_CLK_ENABLE(); + (+++) Configure the DMA using the function DAL_DMA_Init() with predeclared and filled. + (##) NVIC configuration if you need to use interrupt process when using DMA transfer. + (+++) Configure the SDMMC and DMA interrupt priorities using function DAL_NVIC_SetPriority(); + DMA priority is superior to SDMMC's priority + (+++) Enable the NVIC DMA and SDMMC IRQs using function DAL_NVIC_EnableIRQ() + (+++) SDMMC interrupts are managed using the macros __DAL_MMC_ENABLE_IT() + and __DAL_MMC_DISABLE_IT() inside the communication process. + (+++) SDMMC interrupts pending bits are managed using the macros __DAL_MMC_GET_IT() + and __DAL_MMC_CLEAR_IT() + (##) NVIC configuration if you need to use interrupt process (DAL_MMC_ReadBlocks_IT() + and DAL_MMC_WriteBlocks_IT() APIs). + (+++) Configure the SDMMC interrupt priorities using function DAL_NVIC_SetPriority(); + (+++) Enable the NVIC SDMMC IRQs using function DAL_NVIC_EnableIRQ() + (+++) SDMMC interrupts are managed using the macros __DAL_MMC_ENABLE_IT() + and __DAL_MMC_DISABLE_IT() inside the communication process. + (+++) SDMMC interrupts pending bits are managed using the macros __DAL_MMC_GET_IT() + and __DAL_MMC_CLEAR_IT() + (#) At this stage, you can perform MMC read/write/erase operations after MMC card initialization + + + *** MMC Card Initialization and configuration *** + ================================================ + [..] + To initialize the MMC Card, use the DAL_MMC_Init() function. It Initializes + SDMMC Peripheral (APM32 side) and the MMC Card, and put it into StandBy State (Ready for data transfer). + This function provide the following operations: + + (#) Initialize the SDMMC peripheral interface with default configuration. + The initialization process is done at 400KHz. You can change or adapt + this frequency by adjusting the "ClockDiv" field. + The MMC Card frequency (SDMMC_CK) is computed as follows: + + SDMMC_CK = SDMMCCLK / (ClockDiv + 2) + + In initialization mode and according to the MMC Card standard, + make sure that the SDMMC_CK frequency doesn't exceed 400KHz. + + This phase of initialization is done through SDMMC_Init() and + SDMMC_PowerState_ON() SDMMC low level APIs. + + (#) Initialize the MMC card. The API used is DAL_MMC_InitCard(). + This phase allows the card initialization and identification + and check the MMC Card type (Standard Capacity or High Capacity) + The initialization flow is compatible with MMC standard. + + This API (DAL_MMC_InitCard()) could be used also to reinitialize the card in case + of plug-off plug-in. + + (#) Configure the MMC Card Data transfer frequency. By Default, the card transfer + frequency is set to 24MHz. You can change or adapt this frequency by adjusting + the "ClockDiv" field. + In transfer mode and according to the MMC Card standard, make sure that the + SDMMC_CK frequency doesn't exceed 25MHz and 50MHz in High-speed mode switch. + To be able to use a frequency higher than 24MHz, you should use the SDMMC + peripheral in bypass mode. Refer to the corresponding reference manual + for more details. + + (#) Select the corresponding MMC Card according to the address read with the step 2. + + (#) Configure the MMC Card in wide bus mode: 4-bits data. + + *** MMC Card Read operation *** + ============================== + [..] + (+) You can read from MMC card in polling mode by using function DAL_MMC_ReadBlocks(). + This function support only 512-bytes block length (the block size should be + chosen as 512 bytes). + You can choose either one block read operation or multiple block read operation + by adjusting the "NumberOfBlocks" parameter. + After this, you have to ensure that the transfer is done correctly. The check is done + through DAL_MMC_GetCardState() function for MMC card state. + + (+) You can read from MMC card in DMA mode by using function DAL_MMC_ReadBlocks_DMA(). + This function support only 512-bytes block length (the block size should be + chosen as 512 bytes). + You can choose either one block read operation or multiple block read operation + by adjusting the "NumberOfBlocks" parameter. + After this, you have to ensure that the transfer is done correctly. The check is done + through DAL_MMC_GetCardState() function for MMC card state. + You could also check the DMA transfer process through the MMC Rx interrupt event. + + (+) You can read from MMC card in Interrupt mode by using function DAL_MMC_ReadBlocks_IT(). + This function allows the read of 512 bytes blocks. + You can choose either one block read operation or multiple block read operation + by adjusting the "NumberOfBlocks" parameter. + After this, you have to ensure that the transfer is done correctly. The check is done + through DAL_MMC_GetCardState() function for MMC card state. + You could also check the IT transfer process through the MMC Rx interrupt event. + + *** MMC Card Write operation *** + =============================== + [..] + (+) You can write to MMC card in polling mode by using function DAL_MMC_WriteBlocks(). + This function support only 512-bytes block length (the block size should be + chosen as 512 bytes). + You can choose either one block read operation or multiple block read operation + by adjusting the "NumberOfBlocks" parameter. + After this, you have to ensure that the transfer is done correctly. The check is done + through DAL_MMC_GetCardState() function for MMC card state. + + (+) You can write to MMC card in DMA mode by using function DAL_MMC_WriteBlocks_DMA(). + This function support only 512-bytes block length (the block size should be + chosen as 512 byte). + You can choose either one block read operation or multiple block read operation + by adjusting the "NumberOfBlocks" parameter. + After this, you have to ensure that the transfer is done correctly. The check is done + through DAL_MMC_GetCardState() function for MMC card state. + You could also check the DMA transfer process through the MMC Tx interrupt event. + + (+) You can write to MMC card in Interrupt mode by using function DAL_MMC_WriteBlocks_IT(). + This function allows the read of 512 bytes blocks. + You can choose either one block read operation or multiple block read operation + by adjusting the "NumberOfBlocks" parameter. + After this, you have to ensure that the transfer is done correctly. The check is done + through DAL_MMC_GetCardState() function for MMC card state. + You could also check the IT transfer process through the MMC Tx interrupt event. + + *** MMC card information *** + =========================== + [..] + (+) To get MMC card information, you can use the function DAL_MMC_GetCardInfo(). + It returns useful information about the MMC card such as block size, card type, + block number ... + + *** MMC card CSD register *** + ============================ + [..] + (+) The DAL_MMC_GetCardCSD() API allows to get the parameters of the CSD register. + Some of the CSD parameters are useful for card initialization and identification. + + *** MMC card CID register *** + ============================ + [..] + (+) The DAL_MMC_GetCardCID() API allows to get the parameters of the CID register. + Some of the CID parameters are useful for card initialization and identification. + + *** MMC DAL driver macros list *** + ================================== + [..] + Below the list of most used macros in MMC DAL driver. + + (+) __DAL_MMC_ENABLE : Enable the MMC device + (+) __DAL_MMC_DISABLE : Disable the MMC device + (+) __DAL_MMC_DMA_ENABLE: Enable the SDMMC DMA transfer + (+) __DAL_MMC_DMA_DISABLE: Disable the SDMMC DMA transfer + (+) __DAL_MMC_ENABLE_IT: Enable the MMC device interrupt + (+) __DAL_MMC_DISABLE_IT: Disable the MMC device interrupt + (+) __DAL_MMC_GET_FLAG:Check whether the specified MMC flag is set or not + (+) __DAL_MMC_CLEAR_FLAG: Clear the MMC's pending flags + + [..] + (@) You can refer to the MMC DAL driver header file for more useful macros + + *** Callback registration *** + ============================================= + [..] + The compilation define USE_DAL_MMC_REGISTER_CALLBACKS when set to 1 + allows the user to configure dynamically the driver callbacks. + + Use Functions DAL_MMC_RegisterCallback() to register a user callback, + it allows to register following callbacks: + (+) TxCpltCallback : callback when a transmission transfer is completed. + (+) RxCpltCallback : callback when a reception transfer is completed. + (+) ErrorCallback : callback when error occurs. + (+) AbortCpltCallback : callback when abort is completed. + (+) MspInitCallback : MMC MspInit. + (+) MspDeInitCallback : MMC MspDeInit. + This function takes as parameters the DAL peripheral handle, the Callback ID + and a pointer to the user callback function. + + Use function DAL_MMC_UnRegisterCallback() to reset a callback to the default + weak (surcharged) function. It allows to reset following callbacks: + (+) TxCpltCallback : callback when a transmission transfer is completed. + (+) RxCpltCallback : callback when a reception transfer is completed. + (+) ErrorCallback : callback when error occurs. + (+) AbortCpltCallback : callback when abort is completed. + (+) MspInitCallback : MMC MspInit. + (+) MspDeInitCallback : MMC MspDeInit. + This function) takes as parameters the DAL peripheral handle and the Callback ID. + + By default, after the DAL_MMC_Init and if the state is DAL_MMC_STATE_RESET + all callbacks are reset to the corresponding legacy weak (surcharged) functions. + Exception done for MspInit and MspDeInit callbacks that are respectively + reset to the legacy weak (surcharged) functions in the DAL_MMC_Init + and DAL_MMC_DeInit only when these callbacks are null (not registered beforehand). + If not, MspInit or MspDeInit are not null, the DAL_MMC_Init and DAL_MMC_DeInit + keep and use the user MspInit/MspDeInit callbacks (registered beforehand) + + Callbacks can be registered/unregistered in READY state only. + Exception done for MspInit/MspDeInit callbacks that can be registered/unregistered + in READY or RESET state, thus registered (user) MspInit/DeInit callbacks can be used + during the Init/DeInit. + In that case first register the MspInit/MspDeInit user callbacks + using DAL_MMC_RegisterCallback before calling DAL_MMC_DeInit + or DAL_MMC_Init function. + + When The compilation define USE_DAL_MMC_REGISTER_CALLBACKS is set to 0 or + not defined, the callback registering feature is not available + and weak (surcharged) callbacks are used. + + @endverbatim + * + */ + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @defgroup MMC MMC + * @brief MMC DAL module driver + * @{ + */ + +#ifdef DAL_MMC_MODULE_ENABLED + +#if defined(SDIO) + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/** @addtogroup MMC_Private_Defines + * @{ + */ +#if defined (VDD_VALUE) && (VDD_VALUE <= 1950U) +#define MMC_VOLTAGE_RANGE EMMC_LOW_VOLTAGE_RANGE + +#define MMC_EXT_CSD_PWR_CL_26_INDEX 201 +#define MMC_EXT_CSD_PWR_CL_52_INDEX 200 +#define MMC_EXT_CSD_PWR_CL_DDR_52_INDEX 238 + +#define MMC_EXT_CSD_PWR_CL_26_POS 8 +#define MMC_EXT_CSD_PWR_CL_52_POS 0 +#define MMC_EXT_CSD_PWR_CL_DDR_52_POS 16 +#else +#define MMC_VOLTAGE_RANGE EMMC_HIGH_VOLTAGE_RANGE + +#define MMC_EXT_CSD_PWR_CL_26_INDEX 203 +#define MMC_EXT_CSD_PWR_CL_52_INDEX 202 +#define MMC_EXT_CSD_PWR_CL_DDR_52_INDEX 239 + +#define MMC_EXT_CSD_PWR_CL_26_POS 24 +#define MMC_EXT_CSD_PWR_CL_52_POS 16 +#define MMC_EXT_CSD_PWR_CL_DDR_52_POS 24 +#endif + +/* Frequencies used in the driver for clock divider calculation */ +#define MMC_INIT_FREQ 400000U /* Initialization phase : 400 kHz max */ +/** + * @} + */ + +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ +/** @defgroup MMC_Private_Functions MMC Private Functions + * @{ + */ +static uint32_t MMC_InitCard(MMC_HandleTypeDef *hmmc); +static uint32_t MMC_PowerON(MMC_HandleTypeDef *hmmc); +static uint32_t MMC_SendStatus(MMC_HandleTypeDef *hmmc, uint32_t *pCardStatus); +static uint32_t MMC_ReadExtCSD(MMC_HandleTypeDef *hmmc, uint32_t *pFieldData, uint16_t FieldIndex, uint32_t Timeout); +static void MMC_PowerOFF(MMC_HandleTypeDef *hmmc); +static void MMC_Write_IT(MMC_HandleTypeDef *hmmc); +static void MMC_Read_IT(MMC_HandleTypeDef *hmmc); +static void MMC_DMATransmitCplt(DMA_HandleTypeDef *hdma); +static void MMC_DMAReceiveCplt(DMA_HandleTypeDef *hdma); +static void MMC_DMAError(DMA_HandleTypeDef *hdma); +static void MMC_DMATxAbort(DMA_HandleTypeDef *hdma); +static void MMC_DMARxAbort(DMA_HandleTypeDef *hdma); +static uint32_t MMC_PwrClassUpdate(MMC_HandleTypeDef *hmmc, uint32_t Wide); +/** + * @} + */ +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup MMC_Exported_Functions + * @{ + */ + +/** @addtogroup MMC_Exported_Functions_Group1 + * @brief Initialization and de-initialization functions + * +@verbatim + ============================================================================== + ##### Initialization and de-initialization functions ##### + ============================================================================== + [..] + This section provides functions allowing to initialize/de-initialize the MMC + card device to be ready for use. + +@endverbatim + * @{ + */ + +/** + * @brief Initializes the MMC according to the specified parameters in the + MMC_HandleTypeDef and create the associated handle. + * @param hmmc: Pointer to the MMC handle + * @retval DAL status + */ +DAL_StatusTypeDef DAL_MMC_Init(MMC_HandleTypeDef *hmmc) +{ + /* Check the MMC handle allocation */ + if(hmmc == NULL) + { + return DAL_ERROR; + } + + /* Check the parameters */ + ASSERT_PARAM(IS_SDIO_ALL_INSTANCE(hmmc->Instance)); + ASSERT_PARAM(IS_SDIO_CLOCK_EDGE(hmmc->Init.ClockEdge)); + ASSERT_PARAM(IS_SDIO_CLOCK_BYPASS(hmmc->Init.ClockBypass)); + ASSERT_PARAM(IS_SDIO_CLOCK_POWER_SAVE(hmmc->Init.ClockPowerSave)); + ASSERT_PARAM(IS_SDIO_BUS_WIDE(hmmc->Init.BusWide)); + ASSERT_PARAM(IS_SDIO_HARDWARE_FLOW_CONTROL(hmmc->Init.HardwareFlowControl)); + ASSERT_PARAM(IS_SDIO_CLKDIV(hmmc->Init.ClockDiv)); + + if(hmmc->State == DAL_MMC_STATE_RESET) + { + /* Allocate lock resource and initialize it */ + hmmc->Lock = DAL_UNLOCKED; +#if defined (USE_DAL_MMC_REGISTER_CALLBACKS) && (USE_DAL_MMC_REGISTER_CALLBACKS == 1U) + /* Reset Callback pointers in DAL_MMC_STATE_RESET only */ + hmmc->TxCpltCallback = DAL_MMC_TxCpltCallback; + hmmc->RxCpltCallback = DAL_MMC_RxCpltCallback; + hmmc->ErrorCallback = DAL_MMC_ErrorCallback; + hmmc->AbortCpltCallback = DAL_MMC_AbortCallback; + + if(hmmc->MspInitCallback == NULL) + { + hmmc->MspInitCallback = DAL_MMC_MspInit; + } + + /* Init the low level hardware */ + hmmc->MspInitCallback(hmmc); +#else + /* Init the low level hardware : GPIO, CLOCK, CORTEX...etc */ + DAL_MMC_MspInit(hmmc); +#endif + } + + hmmc->State = DAL_MMC_STATE_BUSY; + + /* Initialize the Card parameters */ + if(DAL_MMC_InitCard(hmmc) == DAL_ERROR) + { + return DAL_ERROR; + } + + /* Initialize the error code */ + hmmc->ErrorCode = DAL_MMC_ERROR_NONE; + + /* Initialize the MMC operation */ + hmmc->Context = MMC_CONTEXT_NONE; + + /* Initialize the MMC state */ + hmmc->State = DAL_MMC_STATE_READY; + + /* Configure bus width */ + if (hmmc->Init.BusWide != SDIO_BUS_WIDE_1B) + { + if (DAL_MMC_ConfigWideBusOperation(hmmc, hmmc->Init.BusWide) != DAL_OK) + { + return DAL_ERROR; + } + } + + return DAL_OK; +} + +/** + * @brief Initializes the MMC Card. + * @param hmmc: Pointer to MMC handle + * @note This function initializes the MMC card. It could be used when a card + re-initialization is needed. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_MMC_InitCard(MMC_HandleTypeDef *hmmc) +{ + uint32_t errorstate; + MMC_InitTypeDef Init; + DAL_StatusTypeDef status; + + /* Default SDIO peripheral configuration for MMC card initialization */ + Init.ClockEdge = SDIO_CLOCK_EDGE_RISING; + Init.ClockBypass = SDIO_CLOCK_BYPASS_DISABLE; + Init.ClockPowerSave = SDIO_CLOCK_POWER_SAVE_DISABLE; + Init.BusWide = SDIO_BUS_WIDE_1B; + Init.HardwareFlowControl = SDIO_HARDWARE_FLOW_CONTROL_DISABLE; + Init.ClockDiv = SDIO_INIT_CLK_DIV; + + /* Initialize SDIO peripheral interface with default configuration */ + status = SDIO_Init(hmmc->Instance, Init); + if(status == DAL_ERROR) + { + return DAL_ERROR; + } + + /* Disable SDIO Clock */ + __DAL_MMC_DISABLE(hmmc); + + /* Set Power State to ON */ + status = SDIO_PowerState_ON(hmmc->Instance); + if(status == DAL_ERROR) + { + return DAL_ERROR; + } + + /* Enable MMC Clock */ + __DAL_MMC_ENABLE(hmmc); + + /* Required power up waiting time before starting the MMC initialization sequence */ + DAL_Delay(2); + + /* Identify card operating voltage */ + errorstate = MMC_PowerON(hmmc); + if(errorstate != DAL_MMC_ERROR_NONE) + { + hmmc->State = DAL_MMC_STATE_READY; + hmmc->ErrorCode |= errorstate; + return DAL_ERROR; + } + + /* Card initialization */ + errorstate = MMC_InitCard(hmmc); + if(errorstate != DAL_MMC_ERROR_NONE) + { + hmmc->State = DAL_MMC_STATE_READY; + hmmc->ErrorCode |= errorstate; + return DAL_ERROR; + } + + /* Set Block Size for Card */ + errorstate = SDMMC_CmdBlockLength(hmmc->Instance, MMC_BLOCKSIZE); + if(errorstate != DAL_MMC_ERROR_NONE) + { + /* Clear all the static flags */ + __DAL_MMC_CLEAR_FLAG(hmmc, SDIO_STATIC_FLAGS); + hmmc->ErrorCode |= errorstate; + hmmc->State = DAL_MMC_STATE_READY; + return DAL_ERROR; + } + + return DAL_OK; +} + +/** + * @brief De-Initializes the MMC card. + * @param hmmc: Pointer to MMC handle + * @retval DAL status + */ +DAL_StatusTypeDef DAL_MMC_DeInit(MMC_HandleTypeDef *hmmc) +{ + /* Check the MMC handle allocation */ + if(hmmc == NULL) + { + return DAL_ERROR; + } + + /* Check the parameters */ + ASSERT_PARAM(IS_SDIO_ALL_INSTANCE(hmmc->Instance)); + + hmmc->State = DAL_MMC_STATE_BUSY; + + /* Set MMC power state to off */ + MMC_PowerOFF(hmmc); + +#if defined (USE_DAL_MMC_REGISTER_CALLBACKS) && (USE_DAL_MMC_REGISTER_CALLBACKS == 1U) + if(hmmc->MspDeInitCallback == NULL) + { + hmmc->MspDeInitCallback = DAL_MMC_MspDeInit; + } + + /* DeInit the low level hardware */ + hmmc->MspDeInitCallback(hmmc); +#else + /* De-Initialize the MSP layer */ + DAL_MMC_MspDeInit(hmmc); +#endif + + hmmc->ErrorCode = DAL_MMC_ERROR_NONE; + hmmc->State = DAL_MMC_STATE_RESET; + + return DAL_OK; +} + + +/** + * @brief Initializes the MMC MSP. + * @param hmmc: Pointer to MMC handle + * @retval None + */ +__weak void DAL_MMC_MspInit(MMC_HandleTypeDef *hmmc) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hmmc); + + /* NOTE : This function Should not be modified, when the callback is needed, + the DAL_MMC_MspInit could be implemented in the user file + */ +} + +/** + * @brief De-Initialize MMC MSP. + * @param hmmc: Pointer to MMC handle + * @retval None + */ +__weak void DAL_MMC_MspDeInit(MMC_HandleTypeDef *hmmc) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hmmc); + + /* NOTE : This function Should not be modified, when the callback is needed, + the DAL_MMC_MspDeInit could be implemented in the user file + */ +} + +/** + * @} + */ + +/** @addtogroup MMC_Exported_Functions_Group2 + * @brief Data transfer functions + * +@verbatim + ============================================================================== + ##### IO operation functions ##### + ============================================================================== + [..] + This subsection provides a set of functions allowing to manage the data + transfer from/to MMC card. + +@endverbatim + * @{ + */ + +/** + * @brief Reads block(s) from a specified address in a card. The Data transfer + * is managed by polling mode. + * @note This API should be followed by a check on the card state through + * DAL_MMC_GetCardState(). + * @param hmmc: Pointer to MMC handle + * @param pData: pointer to the buffer that will contain the received data + * @param BlockAdd: Block Address from where data is to be read + * @param NumberOfBlocks: Number of MMC blocks to read + * @param Timeout: Specify timeout value + * @retval DAL status + */ +DAL_StatusTypeDef DAL_MMC_ReadBlocks(MMC_HandleTypeDef *hmmc, uint8_t *pData, uint32_t BlockAdd, uint32_t NumberOfBlocks, uint32_t Timeout) +{ + SDIO_DataInitTypeDef config; + uint32_t errorstate; + uint32_t tickstart = DAL_GetTick(); + uint32_t count, data, dataremaining; + uint32_t add = BlockAdd; + uint8_t *tempbuff = pData; + + if(NULL == pData) + { + hmmc->ErrorCode |= DAL_MMC_ERROR_PARAM; + return DAL_ERROR; + } + + if(hmmc->State == DAL_MMC_STATE_READY) + { + hmmc->ErrorCode = DAL_MMC_ERROR_NONE; + + if((BlockAdd + NumberOfBlocks) > (hmmc->MmcCard.LogBlockNbr)) + { + hmmc->ErrorCode |= DAL_MMC_ERROR_ADDR_OUT_OF_RANGE; + return DAL_ERROR; + } + + hmmc->State = DAL_MMC_STATE_BUSY; + + /* Initialize data control register */ + hmmc->Instance->DCTRL = 0U; + + if ((hmmc->MmcCard.CardType) != MMC_HIGH_CAPACITY_CARD) + { + add *= 512U; + } + + /* Configure the MMC DPSM (Data Path State Machine) */ + config.DataTimeOut = SDMMC_DATATIMEOUT; + config.DataLength = NumberOfBlocks * MMC_BLOCKSIZE; + config.DataBlockSize = SDIO_DATABLOCK_SIZE_512B; + config.TransferDir = SDIO_TRANSFER_DIR_TO_SDIO; + config.TransferMode = SDIO_TRANSFER_MODE_BLOCK; + config.DPSM = SDIO_DPSM_ENABLE; + (void)SDIO_ConfigData(hmmc->Instance, &config); + + /* Read block(s) in polling mode */ + if(NumberOfBlocks > 1U) + { + hmmc->Context = MMC_CONTEXT_READ_MULTIPLE_BLOCK; + + /* Read Multi Block command */ + errorstate = SDMMC_CmdReadMultiBlock(hmmc->Instance, add); + } + else + { + hmmc->Context = MMC_CONTEXT_READ_SINGLE_BLOCK; + + /* Read Single Block command */ + errorstate = SDMMC_CmdReadSingleBlock(hmmc->Instance, add); + } + if(errorstate != DAL_MMC_ERROR_NONE) + { + /* Clear all the static flags */ + __DAL_MMC_CLEAR_FLAG(hmmc, SDIO_STATIC_FLAGS); + hmmc->ErrorCode |= errorstate; + hmmc->State = DAL_MMC_STATE_READY; + return DAL_ERROR; + } + + /* Poll on SDIO flags */ + dataremaining = config.DataLength; +#if defined(SDIO_STS_SBE) + while(!__DAL_MMC_GET_FLAG(hmmc, SDIO_FLAG_RXOVERR | SDIO_FLAG_DCRCFAIL | SDIO_FLAG_DTIMEOUT | SDIO_FLAG_DATAEND | SDIO_FLAG_STBITERR)) +#else /* SDIO_STS_SBE not defined */ + while(!__DAL_MMC_GET_FLAG(hmmc, SDIO_FLAG_RXOVERR | SDIO_FLAG_DCRCFAIL | SDIO_FLAG_DTIMEOUT | SDIO_FLAG_DATAEND)) +#endif /* SDIO_STS_SBE */ + { + if(__DAL_MMC_GET_FLAG(hmmc, SDIO_FLAG_RXFIFOHF) && (dataremaining > 0U)) + { + /* Read data from SDIO Rx FIFO */ + for(count = 0U; count < 8U; count++) + { + data = SDIO_ReadFIFO(hmmc->Instance); + *tempbuff = (uint8_t)(data & 0xFFU); + tempbuff++; + dataremaining--; + *tempbuff = (uint8_t)((data >> 8U) & 0xFFU); + tempbuff++; + dataremaining--; + *tempbuff = (uint8_t)((data >> 16U) & 0xFFU); + tempbuff++; + dataremaining--; + *tempbuff = (uint8_t)((data >> 24U) & 0xFFU); + tempbuff++; + dataremaining--; + } + } + + if(((DAL_GetTick()-tickstart) >= Timeout) || (Timeout == 0U)) + { + /* Clear all the static flags */ + __DAL_MMC_CLEAR_FLAG(hmmc, SDIO_STATIC_FLAGS); + hmmc->ErrorCode |= DAL_MMC_ERROR_TIMEOUT; + hmmc->State= DAL_MMC_STATE_READY; + return DAL_TIMEOUT; + } + } + + /* Send stop transmission command in case of multiblock read */ + if(__DAL_MMC_GET_FLAG(hmmc, SDIO_FLAG_DATAEND) && (NumberOfBlocks > 1U)) + { + /* Send stop transmission command */ + errorstate = SDMMC_CmdStopTransfer(hmmc->Instance); + if(errorstate != DAL_MMC_ERROR_NONE) + { + /* Clear all the static flags */ + __DAL_MMC_CLEAR_FLAG(hmmc, SDIO_STATIC_FLAGS); + hmmc->ErrorCode |= errorstate; + hmmc->State = DAL_MMC_STATE_READY; + return DAL_ERROR; + } + } + + /* Get error state */ + if(__DAL_MMC_GET_FLAG(hmmc, SDIO_FLAG_DTIMEOUT)) + { + /* Clear all the static flags */ + __DAL_MMC_CLEAR_FLAG(hmmc, SDIO_STATIC_FLAGS); + hmmc->ErrorCode |= DAL_MMC_ERROR_DATA_TIMEOUT; + hmmc->State = DAL_MMC_STATE_READY; + return DAL_ERROR; + } + else if(__DAL_MMC_GET_FLAG(hmmc, SDIO_FLAG_DCRCFAIL)) + { + /* Clear all the static flags */ + __DAL_MMC_CLEAR_FLAG(hmmc, SDIO_STATIC_FLAGS); + hmmc->ErrorCode |= DAL_MMC_ERROR_DATA_CRC_FAIL; + hmmc->State = DAL_MMC_STATE_READY; + return DAL_ERROR; + } + else if(__DAL_MMC_GET_FLAG(hmmc, SDIO_FLAG_RXOVERR)) + { + /* Clear all the static flags */ + __DAL_MMC_CLEAR_FLAG(hmmc, SDIO_STATIC_FLAGS); + hmmc->ErrorCode |= DAL_MMC_ERROR_RX_OVERRUN; + hmmc->State = DAL_MMC_STATE_READY; + return DAL_ERROR; + } + else + { + /* Nothing to do */ + } + + /* Empty FIFO if there is still any data */ + while ((__DAL_MMC_GET_FLAG(hmmc, SDIO_FLAG_RXDAVL)) && (dataremaining > 0U)) + { + data = SDIO_ReadFIFO(hmmc->Instance); + *tempbuff = (uint8_t)(data & 0xFFU); + tempbuff++; + dataremaining--; + *tempbuff = (uint8_t)((data >> 8U) & 0xFFU); + tempbuff++; + dataremaining--; + *tempbuff = (uint8_t)((data >> 16U) & 0xFFU); + tempbuff++; + dataremaining--; + *tempbuff = (uint8_t)((data >> 24U) & 0xFFU); + tempbuff++; + dataremaining--; + + if(((DAL_GetTick()-tickstart) >= Timeout) || (Timeout == 0U)) + { + /* Clear all the static flags */ + __DAL_MMC_CLEAR_FLAG(hmmc, SDIO_STATIC_FLAGS); + hmmc->ErrorCode |= DAL_MMC_ERROR_TIMEOUT; + hmmc->State= DAL_MMC_STATE_READY; + return DAL_ERROR; + } + } + + /* Clear all the static flags */ + __DAL_MMC_CLEAR_FLAG(hmmc, SDIO_STATIC_DATA_FLAGS); + + hmmc->State = DAL_MMC_STATE_READY; + + return DAL_OK; + } + else + { + hmmc->ErrorCode |= DAL_MMC_ERROR_BUSY; + return DAL_ERROR; + } +} + +/** + * @brief Allows to write block(s) to a specified address in a card. The Data + * transfer is managed by polling mode. + * @note This API should be followed by a check on the card state through + * DAL_MMC_GetCardState(). + * @param hmmc: Pointer to MMC handle + * @param pData: pointer to the buffer that will contain the data to transmit + * @param BlockAdd: Block Address where data will be written + * @param NumberOfBlocks: Number of MMC blocks to write + * @param Timeout: Specify timeout value + * @retval DAL status + */ +DAL_StatusTypeDef DAL_MMC_WriteBlocks(MMC_HandleTypeDef *hmmc, uint8_t *pData, uint32_t BlockAdd, uint32_t NumberOfBlocks, uint32_t Timeout) +{ + SDIO_DataInitTypeDef config; + uint32_t errorstate; + uint32_t tickstart = DAL_GetTick(); + uint32_t count, data, dataremaining; + uint32_t add = BlockAdd; + uint8_t *tempbuff = pData; + + if(NULL == pData) + { + hmmc->ErrorCode |= DAL_MMC_ERROR_PARAM; + return DAL_ERROR; + } + + if(hmmc->State == DAL_MMC_STATE_READY) + { + hmmc->ErrorCode = DAL_MMC_ERROR_NONE; + + if((BlockAdd + NumberOfBlocks) > (hmmc->MmcCard.LogBlockNbr)) + { + hmmc->ErrorCode |= DAL_MMC_ERROR_ADDR_OUT_OF_RANGE; + return DAL_ERROR; + } + + hmmc->State = DAL_MMC_STATE_BUSY; + + /* Initialize data control register */ + hmmc->Instance->DCTRL = 0U; + + if ((hmmc->MmcCard.CardType) != MMC_HIGH_CAPACITY_CARD) + { + add *= 512U; + } + + /* Write Blocks in Polling mode */ + if(NumberOfBlocks > 1U) + { + hmmc->Context = MMC_CONTEXT_WRITE_MULTIPLE_BLOCK; + + /* Write Multi Block command */ + errorstate = SDMMC_CmdWriteMultiBlock(hmmc->Instance, add); + } + else + { + hmmc->Context = MMC_CONTEXT_WRITE_SINGLE_BLOCK; + + /* Write Single Block command */ + errorstate = SDMMC_CmdWriteSingleBlock(hmmc->Instance, add); + } + if(errorstate != DAL_MMC_ERROR_NONE) + { + /* Clear all the static flags */ + __DAL_MMC_CLEAR_FLAG(hmmc, SDIO_STATIC_FLAGS); + hmmc->ErrorCode |= errorstate; + hmmc->State = DAL_MMC_STATE_READY; + return DAL_ERROR; + } + + /* Configure the MMC DPSM (Data Path State Machine) */ + config.DataTimeOut = SDMMC_DATATIMEOUT; + config.DataLength = NumberOfBlocks * MMC_BLOCKSIZE; + config.DataBlockSize = SDIO_DATABLOCK_SIZE_512B; + config.TransferDir = SDIO_TRANSFER_DIR_TO_CARD; + config.TransferMode = SDIO_TRANSFER_MODE_BLOCK; + config.DPSM = SDIO_DPSM_ENABLE; + (void)SDIO_ConfigData(hmmc->Instance, &config); + + /* Write block(s) in polling mode */ + dataremaining = config.DataLength; +#if defined(SDIO_STS_SBE) + while(!__DAL_MMC_GET_FLAG(hmmc, SDIO_FLAG_TXUNDERR | SDIO_FLAG_DCRCFAIL | SDIO_FLAG_DTIMEOUT | SDIO_FLAG_DATAEND | SDIO_FLAG_STBITERR)) +#else /* SDIO_STS_SBE not defined */ + while(!__DAL_MMC_GET_FLAG(hmmc, SDIO_FLAG_TXUNDERR | SDIO_FLAG_DCRCFAIL | SDIO_FLAG_DTIMEOUT | SDIO_FLAG_DATAEND)) +#endif /* SDIO_STS_SBE */ + { + if(__DAL_MMC_GET_FLAG(hmmc, SDIO_FLAG_TXFIFOHE) && (dataremaining > 0U)) + { + /* Write data to SDIO Tx FIFO */ + for(count = 0U; count < 8U; count++) + { + data = (uint32_t)(*tempbuff); + tempbuff++; + dataremaining--; + data |= ((uint32_t)(*tempbuff) << 8U); + tempbuff++; + dataremaining--; + data |= ((uint32_t)(*tempbuff) << 16U); + tempbuff++; + dataremaining--; + data |= ((uint32_t)(*tempbuff) << 24U); + tempbuff++; + dataremaining--; + (void)SDIO_WriteFIFO(hmmc->Instance, &data); + } + } + + if(((DAL_GetTick()-tickstart) >= Timeout) || (Timeout == 0U)) + { + /* Clear all the static flags */ + __DAL_MMC_CLEAR_FLAG(hmmc, SDIO_STATIC_FLAGS); + hmmc->ErrorCode |= errorstate; + hmmc->State = DAL_MMC_STATE_READY; + return DAL_TIMEOUT; + } + } + + /* Send stop transmission command in case of multiblock write */ + if(__DAL_MMC_GET_FLAG(hmmc, SDIO_FLAG_DATAEND) && (NumberOfBlocks > 1U)) + { + /* Send stop transmission command */ + errorstate = SDMMC_CmdStopTransfer(hmmc->Instance); + if(errorstate != DAL_MMC_ERROR_NONE) + { + /* Clear all the static flags */ + __DAL_MMC_CLEAR_FLAG(hmmc, SDIO_STATIC_FLAGS); + hmmc->ErrorCode |= errorstate; + hmmc->State = DAL_MMC_STATE_READY; + return DAL_ERROR; + } + } + + /* Get error state */ + if(__DAL_MMC_GET_FLAG(hmmc, SDIO_FLAG_DTIMEOUT)) + { + /* Clear all the static flags */ + __DAL_MMC_CLEAR_FLAG(hmmc, SDIO_STATIC_FLAGS); + hmmc->ErrorCode |= DAL_MMC_ERROR_DATA_TIMEOUT; + hmmc->State = DAL_MMC_STATE_READY; + return DAL_ERROR; + } + else if(__DAL_MMC_GET_FLAG(hmmc, SDIO_FLAG_DCRCFAIL)) + { + /* Clear all the static flags */ + __DAL_MMC_CLEAR_FLAG(hmmc, SDIO_STATIC_FLAGS); + hmmc->ErrorCode |= DAL_MMC_ERROR_DATA_CRC_FAIL; + hmmc->State = DAL_MMC_STATE_READY; + return DAL_ERROR; + } + else if(__DAL_MMC_GET_FLAG(hmmc, SDIO_FLAG_TXUNDERR)) + { + /* Clear all the static flags */ + __DAL_MMC_CLEAR_FLAG(hmmc, SDIO_STATIC_FLAGS); + hmmc->ErrorCode |= DAL_MMC_ERROR_TX_UNDERRUN; + hmmc->State = DAL_MMC_STATE_READY; + return DAL_ERROR; + } + else + { + /* Nothing to do */ + } + + /* Clear all the static flags */ + __DAL_MMC_CLEAR_FLAG(hmmc, SDIO_STATIC_DATA_FLAGS); + + hmmc->State = DAL_MMC_STATE_READY; + + return DAL_OK; + } + else + { + hmmc->ErrorCode |= DAL_MMC_ERROR_BUSY; + return DAL_ERROR; + } +} + +/** + * @brief Reads block(s) from a specified address in a card. The Data transfer + * is managed in interrupt mode. + * @note This API should be followed by a check on the card state through + * DAL_MMC_GetCardState(). + * @note You could also check the IT transfer process through the MMC Rx + * interrupt event. + * @param hmmc: Pointer to MMC handle + * @param pData: Pointer to the buffer that will contain the received data + * @param BlockAdd: Block Address from where data is to be read + * @param NumberOfBlocks: Number of blocks to read. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_MMC_ReadBlocks_IT(MMC_HandleTypeDef *hmmc, uint8_t *pData, uint32_t BlockAdd, uint32_t NumberOfBlocks) +{ + SDIO_DataInitTypeDef config; + uint32_t errorstate; + uint32_t add = BlockAdd; + + if(NULL == pData) + { + hmmc->ErrorCode |= DAL_MMC_ERROR_PARAM; + return DAL_ERROR; + } + + if(hmmc->State == DAL_MMC_STATE_READY) + { + hmmc->ErrorCode = DAL_MMC_ERROR_NONE; + + if((BlockAdd + NumberOfBlocks) > (hmmc->MmcCard.LogBlockNbr)) + { + hmmc->ErrorCode |= DAL_MMC_ERROR_ADDR_OUT_OF_RANGE; + return DAL_ERROR; + } + + hmmc->State = DAL_MMC_STATE_BUSY; + + /* Initialize data control register */ + hmmc->Instance->DCTRL = 0U; + + hmmc->pRxBuffPtr = pData; + hmmc->RxXferSize = MMC_BLOCKSIZE * NumberOfBlocks; + +#if defined(SDIO_STS_SBE) + __DAL_MMC_ENABLE_IT(hmmc, (SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT | SDIO_IT_RXOVERR | SDIO_IT_DATAEND | SDIO_FLAG_RXFIFOHF | SDIO_IT_STBITERR)); +#else /* SDIO_STS_SBE not defined */ + __DAL_MMC_ENABLE_IT(hmmc, (SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT | SDIO_IT_RXOVERR | SDIO_IT_DATAEND | SDIO_FLAG_RXFIFOHF)); +#endif /* SDIO_STS_SBE */ + + if ((hmmc->MmcCard.CardType) != MMC_HIGH_CAPACITY_CARD) + { + add *= 512U; + } + + /* Configure the MMC DPSM (Data Path State Machine) */ + config.DataTimeOut = SDMMC_DATATIMEOUT; + config.DataLength = MMC_BLOCKSIZE * NumberOfBlocks; + config.DataBlockSize = SDIO_DATABLOCK_SIZE_512B; + config.TransferDir = SDIO_TRANSFER_DIR_TO_SDIO; + config.TransferMode = SDIO_TRANSFER_MODE_BLOCK; + config.DPSM = SDIO_DPSM_ENABLE; + (void)SDIO_ConfigData(hmmc->Instance, &config); + + /* Read Blocks in IT mode */ + if(NumberOfBlocks > 1U) + { + hmmc->Context = (MMC_CONTEXT_READ_MULTIPLE_BLOCK | MMC_CONTEXT_IT); + + /* Read Multi Block command */ + errorstate = SDMMC_CmdReadMultiBlock(hmmc->Instance, add); + } + else + { + hmmc->Context = (MMC_CONTEXT_READ_SINGLE_BLOCK | MMC_CONTEXT_IT); + + /* Read Single Block command */ + errorstate = SDMMC_CmdReadSingleBlock(hmmc->Instance, add); + } + + if(errorstate != DAL_MMC_ERROR_NONE) + { + /* Clear all the static flags */ + __DAL_MMC_CLEAR_FLAG(hmmc, SDIO_STATIC_FLAGS); + hmmc->ErrorCode |= errorstate; + hmmc->State = DAL_MMC_STATE_READY; + return DAL_ERROR; + } + + return DAL_OK; + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief Writes block(s) to a specified address in a card. The Data transfer + * is managed in interrupt mode. + * @note This API should be followed by a check on the card state through + * DAL_MMC_GetCardState(). + * @note You could also check the IT transfer process through the MMC Tx + * interrupt event. + * @param hmmc: Pointer to MMC handle + * @param pData: Pointer to the buffer that will contain the data to transmit + * @param BlockAdd: Block Address where data will be written + * @param NumberOfBlocks: Number of blocks to write + * @retval DAL status + */ +DAL_StatusTypeDef DAL_MMC_WriteBlocks_IT(MMC_HandleTypeDef *hmmc, uint8_t *pData, uint32_t BlockAdd, uint32_t NumberOfBlocks) +{ + SDIO_DataInitTypeDef config; + uint32_t errorstate; + uint32_t add = BlockAdd; + + if(NULL == pData) + { + hmmc->ErrorCode |= DAL_MMC_ERROR_PARAM; + return DAL_ERROR; + } + + if(hmmc->State == DAL_MMC_STATE_READY) + { + hmmc->ErrorCode = DAL_MMC_ERROR_NONE; + + if((BlockAdd + NumberOfBlocks) > (hmmc->MmcCard.LogBlockNbr)) + { + hmmc->ErrorCode |= DAL_MMC_ERROR_ADDR_OUT_OF_RANGE; + return DAL_ERROR; + } + + hmmc->State = DAL_MMC_STATE_BUSY; + + /* Initialize data control register */ + hmmc->Instance->DCTRL = 0U; + + hmmc->pTxBuffPtr = pData; + hmmc->TxXferSize = MMC_BLOCKSIZE * NumberOfBlocks; + + /* Enable transfer interrupts */ +#if defined(SDIO_STS_SBE) + __DAL_MMC_ENABLE_IT(hmmc, (SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT | SDIO_IT_TXUNDERR | SDIO_IT_DATAEND | SDIO_FLAG_TXFIFOHE | SDIO_IT_STBITERR)); +#else /* SDIO_STS_SBE not defined */ + __DAL_MMC_ENABLE_IT(hmmc, (SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT | SDIO_IT_TXUNDERR | SDIO_IT_DATAEND | SDIO_FLAG_TXFIFOHE)); +#endif /* SDIO_STS_SBE */ + + if ((hmmc->MmcCard.CardType) != MMC_HIGH_CAPACITY_CARD) + { + add *= 512U; + } + + /* Write Blocks in Polling mode */ + if(NumberOfBlocks > 1U) + { + hmmc->Context = (MMC_CONTEXT_WRITE_MULTIPLE_BLOCK| MMC_CONTEXT_IT); + + /* Write Multi Block command */ + errorstate = SDMMC_CmdWriteMultiBlock(hmmc->Instance, add); + } + else + { + hmmc->Context = (MMC_CONTEXT_WRITE_SINGLE_BLOCK | MMC_CONTEXT_IT); + + /* Write Single Block command */ + errorstate = SDMMC_CmdWriteSingleBlock(hmmc->Instance, add); + } + if(errorstate != DAL_MMC_ERROR_NONE) + { + /* Clear all the static flags */ + __DAL_MMC_CLEAR_FLAG(hmmc, SDIO_STATIC_FLAGS); + hmmc->ErrorCode |= errorstate; + hmmc->State = DAL_MMC_STATE_READY; + return DAL_ERROR; + } + + /* Configure the MMC DPSM (Data Path State Machine) */ + config.DataTimeOut = SDMMC_DATATIMEOUT; + config.DataLength = MMC_BLOCKSIZE * NumberOfBlocks; + config.DataBlockSize = SDIO_DATABLOCK_SIZE_512B; + config.TransferDir = SDIO_TRANSFER_DIR_TO_CARD; + config.TransferMode = SDIO_TRANSFER_MODE_BLOCK; + config.DPSM = SDIO_DPSM_ENABLE; + (void)SDIO_ConfigData(hmmc->Instance, &config); + + return DAL_OK; + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief Reads block(s) from a specified address in a card. The Data transfer + * is managed by DMA mode. + * @note This API should be followed by a check on the card state through + * DAL_MMC_GetCardState(). + * @note You could also check the DMA transfer process through the MMC Rx + * interrupt event. + * @param hmmc: Pointer MMC handle + * @param pData: Pointer to the buffer that will contain the received data + * @param BlockAdd: Block Address from where data is to be read + * @param NumberOfBlocks: Number of blocks to read. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_MMC_ReadBlocks_DMA(MMC_HandleTypeDef *hmmc, uint8_t *pData, uint32_t BlockAdd, uint32_t NumberOfBlocks) +{ + SDIO_DataInitTypeDef config; + uint32_t errorstate; + uint32_t add = BlockAdd; + + if(NULL == pData) + { + hmmc->ErrorCode |= DAL_MMC_ERROR_PARAM; + return DAL_ERROR; + } + + if(hmmc->State == DAL_MMC_STATE_READY) + { + hmmc->ErrorCode = DAL_MMC_ERROR_NONE; + + if((BlockAdd + NumberOfBlocks) > (hmmc->MmcCard.LogBlockNbr)) + { + hmmc->ErrorCode |= DAL_MMC_ERROR_ADDR_OUT_OF_RANGE; + return DAL_ERROR; + } + + hmmc->State = DAL_MMC_STATE_BUSY; + + /* Initialize data control register */ + hmmc->Instance->DCTRL = 0U; + +#if defined(SDIO_STS_SBE) + __DAL_MMC_ENABLE_IT(hmmc, (SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT | SDIO_IT_RXOVERR | SDIO_IT_DATAEND | SDIO_IT_STBITERR)); +#else /* SDIO_STS_SBE not defined */ + __DAL_MMC_ENABLE_IT(hmmc, (SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT | SDIO_IT_RXOVERR | SDIO_IT_DATAEND)); +#endif /* SDIO_STS_SBE */ + + /* Set the DMA transfer complete callback */ + hmmc->hdmarx->XferCpltCallback = MMC_DMAReceiveCplt; + + /* Set the DMA error callback */ + hmmc->hdmarx->XferErrorCallback = MMC_DMAError; + + /* Set the DMA Abort callback */ + hmmc->hdmarx->XferAbortCallback = NULL; + + if ((hmmc->MmcCard.CardType) != MMC_HIGH_CAPACITY_CARD) + { + add *= 512U; + } + + /* Force DMA Direction */ + hmmc->hdmarx->Init.Direction = DMA_PERIPH_TO_MEMORY; + MODIFY_REG(hmmc->hdmarx->Instance->SCFG, DMA_SCFGx_DIRCFG, hmmc->hdmarx->Init.Direction); + + /* Enable the DMA Channel */ + if(DAL_DMA_Start_IT(hmmc->hdmarx, (uint32_t)&hmmc->Instance->FIFODATA, (uint32_t)pData, (uint32_t)(MMC_BLOCKSIZE * NumberOfBlocks)/4) != DAL_OK) + { + __DAL_MMC_DISABLE_IT(hmmc, (SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT | SDIO_IT_RXOVERR | SDIO_IT_DATAEND)); + __DAL_MMC_CLEAR_FLAG(hmmc, SDIO_STATIC_FLAGS); + hmmc->ErrorCode = DAL_MMC_ERROR_DMA; + hmmc->State = DAL_MMC_STATE_READY; + return DAL_ERROR; + } + else + { + /* Enable MMC DMA transfer */ + __DAL_MMC_DMA_ENABLE(hmmc); + + /* Configure the MMC DPSM (Data Path State Machine) */ + config.DataTimeOut = SDMMC_DATATIMEOUT; + config.DataLength = MMC_BLOCKSIZE * NumberOfBlocks; + config.DataBlockSize = SDIO_DATABLOCK_SIZE_512B; + config.TransferDir = SDIO_TRANSFER_DIR_TO_SDIO; + config.TransferMode = SDIO_TRANSFER_MODE_BLOCK; + config.DPSM = SDIO_DPSM_ENABLE; + (void)SDIO_ConfigData(hmmc->Instance, &config); + + /* Read Blocks in DMA mode */ + if(NumberOfBlocks > 1U) + { + hmmc->Context = (MMC_CONTEXT_READ_MULTIPLE_BLOCK | MMC_CONTEXT_DMA); + + /* Read Multi Block command */ + errorstate = SDMMC_CmdReadMultiBlock(hmmc->Instance, add); + } + else + { + hmmc->Context = (MMC_CONTEXT_READ_SINGLE_BLOCK | MMC_CONTEXT_DMA); + + /* Read Single Block command */ + errorstate = SDMMC_CmdReadSingleBlock(hmmc->Instance, add); + } + if(errorstate != DAL_MMC_ERROR_NONE) + { + /* Clear all the static flags */ + __DAL_MMC_CLEAR_FLAG(hmmc, SDIO_STATIC_FLAGS); + __DAL_MMC_DISABLE_IT(hmmc, (SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT | SDIO_IT_RXOVERR | SDIO_IT_DATAEND)); + hmmc->ErrorCode = errorstate; + hmmc->State = DAL_MMC_STATE_READY; + return DAL_ERROR; + } + + return DAL_OK; + } + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief Writes block(s) to a specified address in a card. The Data transfer + * is managed by DMA mode. + * @note This API should be followed by a check on the card state through + * DAL_MMC_GetCardState(). + * @note You could also check the DMA transfer process through the MMC Tx + * interrupt event. + * @param hmmc: Pointer to MMC handle + * @param pData: Pointer to the buffer that will contain the data to transmit + * @param BlockAdd: Block Address where data will be written + * @param NumberOfBlocks: Number of blocks to write + * @retval DAL status + */ +DAL_StatusTypeDef DAL_MMC_WriteBlocks_DMA(MMC_HandleTypeDef *hmmc, uint8_t *pData, uint32_t BlockAdd, uint32_t NumberOfBlocks) +{ + SDIO_DataInitTypeDef config; + uint32_t errorstate; + uint32_t add = BlockAdd; + + if(NULL == pData) + { + hmmc->ErrorCode |= DAL_MMC_ERROR_PARAM; + return DAL_ERROR; + } + + if(hmmc->State == DAL_MMC_STATE_READY) + { + hmmc->ErrorCode = DAL_MMC_ERROR_NONE; + + if((BlockAdd + NumberOfBlocks) > (hmmc->MmcCard.LogBlockNbr)) + { + hmmc->ErrorCode |= DAL_MMC_ERROR_ADDR_OUT_OF_RANGE; + return DAL_ERROR; + } + + hmmc->State = DAL_MMC_STATE_BUSY; + + /* Initialize data control register */ + hmmc->Instance->DCTRL = 0U; + + /* Enable MMC Error interrupts */ +#if defined(SDIO_STS_SBE) + __DAL_MMC_ENABLE_IT(hmmc, (SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT | SDIO_IT_TXUNDERR | SDIO_IT_STBITERR)); +#else /* SDIO_STS_SBE not defined */ + __DAL_MMC_ENABLE_IT(hmmc, (SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT | SDIO_IT_TXUNDERR)); +#endif /* SDIO_STS_SBE */ + + /* Set the DMA transfer complete callback */ + hmmc->hdmatx->XferCpltCallback = MMC_DMATransmitCplt; + + /* Set the DMA error callback */ + hmmc->hdmatx->XferErrorCallback = MMC_DMAError; + + /* Set the DMA Abort callback */ + hmmc->hdmatx->XferAbortCallback = NULL; + + if ((hmmc->MmcCard.CardType) != MMC_HIGH_CAPACITY_CARD) + { + add *= 512U; + } + + + /* Write Blocks in Polling mode */ + if(NumberOfBlocks > 1U) + { + hmmc->Context = (MMC_CONTEXT_WRITE_MULTIPLE_BLOCK | MMC_CONTEXT_DMA); + + /* Write Multi Block command */ + errorstate = SDMMC_CmdWriteMultiBlock(hmmc->Instance, add); + } + else + { + hmmc->Context = (MMC_CONTEXT_WRITE_SINGLE_BLOCK | MMC_CONTEXT_DMA); + + /* Write Single Block command */ + errorstate = SDMMC_CmdWriteSingleBlock(hmmc->Instance, add); + } + if(errorstate != DAL_MMC_ERROR_NONE) + { + /* Clear all the static flags */ + __DAL_MMC_CLEAR_FLAG(hmmc, SDIO_STATIC_FLAGS); + __DAL_MMC_DISABLE_IT(hmmc, (SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT | SDIO_IT_TXUNDERR | SDIO_IT_DATAEND)); + hmmc->ErrorCode |= errorstate; + hmmc->State = DAL_MMC_STATE_READY; + return DAL_ERROR; + } + + /* Enable SDIO DMA transfer */ + __DAL_MMC_DMA_ENABLE(hmmc); + + /* Force DMA Direction */ + hmmc->hdmatx->Init.Direction = DMA_MEMORY_TO_PERIPH; + MODIFY_REG(hmmc->hdmatx->Instance->SCFG, DMA_SCFGx_DIRCFG, hmmc->hdmatx->Init.Direction); + + /* Enable the DMA Channel */ + if(DAL_DMA_Start_IT(hmmc->hdmatx, (uint32_t)pData, (uint32_t)&hmmc->Instance->FIFODATA, (uint32_t)(MMC_BLOCKSIZE * NumberOfBlocks)/4) != DAL_OK) + { + __DAL_MMC_DISABLE_IT(hmmc, (SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT | SDIO_IT_TXUNDERR | SDIO_IT_DATAEND)); + __DAL_MMC_CLEAR_FLAG(hmmc, SDIO_STATIC_FLAGS); + hmmc->ErrorCode |= DAL_MMC_ERROR_DMA; + hmmc->State = DAL_MMC_STATE_READY; + return DAL_ERROR; + } + else + { + /* Configure the MMC DPSM (Data Path State Machine) */ + config.DataTimeOut = SDMMC_DATATIMEOUT; + config.DataLength = MMC_BLOCKSIZE * NumberOfBlocks; + config.DataBlockSize = SDIO_DATABLOCK_SIZE_512B; + config.TransferDir = SDIO_TRANSFER_DIR_TO_CARD; + config.TransferMode = SDIO_TRANSFER_MODE_BLOCK; + config.DPSM = SDIO_DPSM_ENABLE; + (void)SDIO_ConfigData(hmmc->Instance, &config); + + return DAL_OK; + } + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief Erases the specified memory area of the given MMC card. + * @note This API should be followed by a check on the card state through + * DAL_MMC_GetCardState(). + * @param hmmc: Pointer to MMC handle + * @param BlockStartAdd: Start Block address + * @param BlockEndAdd: End Block address + * @retval DAL status + */ +DAL_StatusTypeDef DAL_MMC_Erase(MMC_HandleTypeDef *hmmc, uint32_t BlockStartAdd, uint32_t BlockEndAdd) +{ + uint32_t errorstate; + uint32_t start_add = BlockStartAdd; + uint32_t end_add = BlockEndAdd; + + if(hmmc->State == DAL_MMC_STATE_READY) + { + hmmc->ErrorCode = DAL_MMC_ERROR_NONE; + + if(end_add < start_add) + { + hmmc->ErrorCode |= DAL_MMC_ERROR_PARAM; + return DAL_ERROR; + } + + if(end_add > (hmmc->MmcCard.LogBlockNbr)) + { + hmmc->ErrorCode |= DAL_MMC_ERROR_ADDR_OUT_OF_RANGE; + return DAL_ERROR; + } + + hmmc->State = DAL_MMC_STATE_BUSY; + + /* Check if the card command class supports erase command */ + if(((hmmc->MmcCard.Class) & SDIO_CCCC_ERASE) == 0U) + { + /* Clear all the static flags */ + __DAL_MMC_CLEAR_FLAG(hmmc, SDIO_STATIC_FLAGS); + hmmc->ErrorCode |= DAL_MMC_ERROR_REQUEST_NOT_APPLICABLE; + hmmc->State = DAL_MMC_STATE_READY; + return DAL_ERROR; + } + + if((SDIO_GetResponse(hmmc->Instance, SDIO_RES1) & SDMMC_CARD_LOCKED) == SDMMC_CARD_LOCKED) + { + /* Clear all the static flags */ + __DAL_MMC_CLEAR_FLAG(hmmc, SDIO_STATIC_FLAGS); + hmmc->ErrorCode |= DAL_MMC_ERROR_LOCK_UNLOCK_FAILED; + hmmc->State = DAL_MMC_STATE_READY; + return DAL_ERROR; + } + + if ((hmmc->MmcCard.CardType) != MMC_HIGH_CAPACITY_CARD) + { + start_add *= 512U; + end_add *= 512U; + } + + /* Send CMD35 MMC_ERASE_GRP_START with argument as addr */ + errorstate = SDMMC_CmdEraseStartAdd(hmmc->Instance, start_add); + if(errorstate != DAL_MMC_ERROR_NONE) + { + /* Clear all the static flags */ + __DAL_MMC_CLEAR_FLAG(hmmc, SDIO_STATIC_FLAGS); + hmmc->ErrorCode |= errorstate; + hmmc->State = DAL_MMC_STATE_READY; + return DAL_ERROR; + } + + /* Send CMD36 MMC_ERASE_GRP_END with argument as addr */ + errorstate = SDMMC_CmdEraseEndAdd(hmmc->Instance, end_add); + if(errorstate != DAL_MMC_ERROR_NONE) + { + /* Clear all the static flags */ + __DAL_MMC_CLEAR_FLAG(hmmc, SDIO_STATIC_FLAGS); + hmmc->ErrorCode |= errorstate; + hmmc->State = DAL_MMC_STATE_READY; + return DAL_ERROR; + } + + /* Send CMD38 ERASE */ + errorstate = SDMMC_CmdErase(hmmc->Instance); + if(errorstate != DAL_MMC_ERROR_NONE) + { + /* Clear all the static flags */ + __DAL_MMC_CLEAR_FLAG(hmmc, SDIO_STATIC_FLAGS); + hmmc->ErrorCode |= errorstate; + hmmc->State = DAL_MMC_STATE_READY; + return DAL_ERROR; + } + + hmmc->State = DAL_MMC_STATE_READY; + + return DAL_OK; + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief This function handles MMC card interrupt request. + * @param hmmc: Pointer to MMC handle + * @retval None + */ +void DAL_MMC_IRQHandler(MMC_HandleTypeDef *hmmc) +{ + uint32_t errorstate; + uint32_t context = hmmc->Context; + + /* Check for SDIO interrupt flags */ + if((__DAL_MMC_GET_FLAG(hmmc, SDIO_FLAG_RXFIFOHF) != RESET) && ((context & MMC_CONTEXT_IT) != 0U)) + { + MMC_Read_IT(hmmc); + } + + else if(__DAL_MMC_GET_FLAG(hmmc, SDIO_FLAG_DATAEND) != RESET) + { + __DAL_MMC_CLEAR_FLAG(hmmc, SDIO_FLAG_DATAEND); + +#if defined(SDIO_STS_SBE) + __DAL_MMC_DISABLE_IT(hmmc, SDIO_IT_DATAEND | SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT|\ + SDIO_IT_TXUNDERR| SDIO_IT_RXOVERR | SDIO_IT_STBITERR); +#else /* SDIO_STS_SBE not defined */ + __DAL_MMC_DISABLE_IT(hmmc, SDIO_IT_DATAEND | SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT |\ + SDIO_IT_TXUNDERR | SDIO_IT_RXOVERR | SDIO_IT_TXFIFOHE |\ + SDIO_IT_RXFIFOHF); +#endif /* SDIO_STS_SBE */ + + hmmc->Instance->DCTRL &= ~(SDIO_DCTRL_DTEN); + + if((context & MMC_CONTEXT_DMA) != 0U) + { + if((context & MMC_CONTEXT_WRITE_MULTIPLE_BLOCK) != 0U) + { + errorstate = SDMMC_CmdStopTransfer(hmmc->Instance); + if(errorstate != DAL_MMC_ERROR_NONE) + { + hmmc->ErrorCode |= errorstate; +#if defined (USE_DAL_MMC_REGISTER_CALLBACKS) && (USE_DAL_MMC_REGISTER_CALLBACKS == 1U) + hmmc->ErrorCallback(hmmc); +#else + DAL_MMC_ErrorCallback(hmmc); +#endif + } + } + if(((context & MMC_CONTEXT_READ_SINGLE_BLOCK) == 0U) && ((context & MMC_CONTEXT_READ_MULTIPLE_BLOCK) == 0U)) + { + /* Disable the DMA transfer for transmit request by setting the DMAEN bit + in the MMC DCTRL register */ + hmmc->Instance->DCTRL &= (uint32_t)~((uint32_t)SDIO_DCTRL_DMAEN); + + hmmc->State = DAL_MMC_STATE_READY; + +#if defined (USE_DAL_MMC_REGISTER_CALLBACKS) && (USE_DAL_MMC_REGISTER_CALLBACKS == 1U) + hmmc->TxCpltCallback(hmmc); +#else + DAL_MMC_TxCpltCallback(hmmc); +#endif + } + } + else if((context & MMC_CONTEXT_IT) != 0U) + { + /* Stop Transfer for Write Multi blocks or Read Multi blocks */ + if(((context & MMC_CONTEXT_READ_MULTIPLE_BLOCK) != 0U) || ((context & MMC_CONTEXT_WRITE_MULTIPLE_BLOCK) != 0U)) + { + errorstate = SDMMC_CmdStopTransfer(hmmc->Instance); + if(errorstate != DAL_MMC_ERROR_NONE) + { + hmmc->ErrorCode |= errorstate; +#if defined (USE_DAL_MMC_REGISTER_CALLBACKS) && (USE_DAL_MMC_REGISTER_CALLBACKS == 1U) + hmmc->ErrorCallback(hmmc); +#else + DAL_MMC_ErrorCallback(hmmc); +#endif + } + } + + /* Clear all the static flags */ + __DAL_MMC_CLEAR_FLAG(hmmc, SDIO_STATIC_DATA_FLAGS); + + hmmc->State = DAL_MMC_STATE_READY; + if(((context & MMC_CONTEXT_READ_SINGLE_BLOCK) != 0U) || ((context & MMC_CONTEXT_READ_MULTIPLE_BLOCK) != 0U)) + { +#if defined (USE_DAL_MMC_REGISTER_CALLBACKS) && (USE_DAL_MMC_REGISTER_CALLBACKS == 1U) + hmmc->RxCpltCallback(hmmc); +#else + DAL_MMC_RxCpltCallback(hmmc); +#endif + } + else + { +#if defined (USE_DAL_MMC_REGISTER_CALLBACKS) && (USE_DAL_MMC_REGISTER_CALLBACKS == 1U) + hmmc->TxCpltCallback(hmmc); +#else + DAL_MMC_TxCpltCallback(hmmc); +#endif + } + } + else + { + /* Nothing to do */ + } + } + + else if((__DAL_MMC_GET_FLAG(hmmc, SDIO_FLAG_TXFIFOHE) != RESET) && ((context & MMC_CONTEXT_IT) != 0U)) + { + MMC_Write_IT(hmmc); + } + +#if defined(SDIO_STS_SBE) + else if(__DAL_MMC_GET_FLAG(hmmc, SDIO_FLAG_DCRCFAIL | SDIO_FLAG_DTIMEOUT | SDIO_FLAG_RXOVERR | SDIO_FLAG_TXUNDERR | SDIO_FLAG_STBITERR) != RESET) +#else /* SDIO_STS_SBE not defined */ + else if(__DAL_MMC_GET_FLAG(hmmc, SDIO_FLAG_DCRCFAIL | SDIO_FLAG_DTIMEOUT | SDIO_FLAG_RXOVERR | SDIO_FLAG_TXUNDERR) != RESET) +#endif /* SDIO_STS_SBE */ + { + /* Set Error code */ + if(__DAL_MMC_GET_FLAG(hmmc, SDIO_FLAG_DCRCFAIL) != RESET) + { + hmmc->ErrorCode |= DAL_MMC_ERROR_DATA_CRC_FAIL; + } + if(__DAL_MMC_GET_FLAG(hmmc, SDIO_FLAG_DTIMEOUT) != RESET) + { + hmmc->ErrorCode |= DAL_MMC_ERROR_DATA_TIMEOUT; + } + if(__DAL_MMC_GET_FLAG(hmmc, SDIO_FLAG_RXOVERR) != RESET) + { + hmmc->ErrorCode |= DAL_MMC_ERROR_RX_OVERRUN; + } + if(__DAL_MMC_GET_FLAG(hmmc, SDIO_FLAG_TXUNDERR) != RESET) + { + hmmc->ErrorCode |= DAL_MMC_ERROR_TX_UNDERRUN; + } +#if defined(SDIO_STS_SBE) + if(__DAL_MMC_GET_FLAG(hmmc, SDIO_FLAG_STBITERR) != RESET) + { + hmmc->ErrorCode |= DAL_MMC_ERROR_DATA_TIMEOUT; + } +#endif /* SDIO_STS_SBE */ + +#if defined(SDIO_STS_SBE) + /* Clear All flags */ + __DAL_MMC_CLEAR_FLAG(hmmc, SDIO_STATIC_DATA_FLAGS | SDIO_FLAG_STBITERR); + + /* Disable all interrupts */ + __DAL_MMC_DISABLE_IT(hmmc, SDIO_IT_DATAEND | SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT|\ + SDIO_IT_TXUNDERR| SDIO_IT_RXOVERR | SDIO_IT_STBITERR); +#else /* SDIO_STS_SBE */ + /* Clear All flags */ + __DAL_MMC_CLEAR_FLAG(hmmc, SDIO_STATIC_DATA_FLAGS); + + /* Disable all interrupts */ + __DAL_MMC_DISABLE_IT(hmmc, SDIO_IT_DATAEND | SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT|\ + SDIO_IT_TXUNDERR| SDIO_IT_RXOVERR); +#endif /* SDIO_STS_SBE */ + + hmmc->ErrorCode |= SDMMC_CmdStopTransfer(hmmc->Instance); + + if((context & MMC_CONTEXT_IT) != 0U) + { + /* Set the MMC state to ready to be able to start again the process */ + hmmc->State = DAL_MMC_STATE_READY; +#if defined (USE_DAL_MMC_REGISTER_CALLBACKS) && (USE_DAL_MMC_REGISTER_CALLBACKS == 1U) + hmmc->ErrorCallback(hmmc); +#else + DAL_MMC_ErrorCallback(hmmc); +#endif /* USE_DAL_MMC_REGISTER_CALLBACKS */ + } + else if((context & MMC_CONTEXT_DMA) != 0U) + { + /* Abort the MMC DMA Streams */ + if(hmmc->hdmatx != NULL) + { + /* Set the DMA Tx abort callback */ + hmmc->hdmatx->XferAbortCallback = MMC_DMATxAbort; + /* Abort DMA in IT mode */ + if(DAL_DMA_Abort_IT(hmmc->hdmatx) != DAL_OK) + { + MMC_DMATxAbort(hmmc->hdmatx); + } + } + else if(hmmc->hdmarx != NULL) + { + /* Set the DMA Rx abort callback */ + hmmc->hdmarx->XferAbortCallback = MMC_DMARxAbort; + /* Abort DMA in IT mode */ + if(DAL_DMA_Abort_IT(hmmc->hdmarx) != DAL_OK) + { + MMC_DMARxAbort(hmmc->hdmarx); + } + } + else + { + hmmc->ErrorCode = DAL_MMC_ERROR_NONE; + hmmc->State = DAL_MMC_STATE_READY; +#if defined (USE_DAL_MMC_REGISTER_CALLBACKS) && (USE_DAL_MMC_REGISTER_CALLBACKS == 1U) + hmmc->AbortCpltCallback(hmmc); +#else + DAL_MMC_AbortCallback(hmmc); +#endif + } + } + else + { + /* Nothing to do */ + } + } + + else + { + /* Nothing to do */ + } +} + +/** + * @brief return the MMC state + * @param hmmc: Pointer to mmc handle + * @retval DAL state + */ +DAL_MMC_StateTypeDef DAL_MMC_GetState(MMC_HandleTypeDef *hmmc) +{ + return hmmc->State; +} + +/** +* @brief Return the MMC error code +* @param hmmc : Pointer to a MMC_HandleTypeDef structure that contains + * the configuration information. +* @retval MMC Error Code +*/ +uint32_t DAL_MMC_GetError(MMC_HandleTypeDef *hmmc) +{ + return hmmc->ErrorCode; +} + +/** + * @brief Tx Transfer completed callbacks + * @param hmmc: Pointer to MMC handle + * @retval None + */ +__weak void DAL_MMC_TxCpltCallback(MMC_HandleTypeDef *hmmc) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hmmc); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_MMC_TxCpltCallback can be implemented in the user file + */ +} + +/** + * @brief Rx Transfer completed callbacks + * @param hmmc: Pointer MMC handle + * @retval None + */ +__weak void DAL_MMC_RxCpltCallback(MMC_HandleTypeDef *hmmc) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hmmc); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_MMC_RxCpltCallback can be implemented in the user file + */ +} + +/** + * @brief MMC error callbacks + * @param hmmc: Pointer MMC handle + * @retval None + */ +__weak void DAL_MMC_ErrorCallback(MMC_HandleTypeDef *hmmc) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hmmc); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_MMC_ErrorCallback can be implemented in the user file + */ +} + +/** + * @brief MMC Abort callbacks + * @param hmmc: Pointer MMC handle + * @retval None + */ +__weak void DAL_MMC_AbortCallback(MMC_HandleTypeDef *hmmc) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hmmc); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_MMC_AbortCallback can be implemented in the user file + */ +} + +#if defined (USE_DAL_MMC_REGISTER_CALLBACKS) && (USE_DAL_MMC_REGISTER_CALLBACKS == 1U) +/** + * @brief Register a User MMC Callback + * To be used instead of the weak (surcharged) predefined callback + * @param hmmc : MMC handle + * @param CallbackId : ID of the callback to be registered + * This parameter can be one of the following values: + * @arg @ref DAL_MMC_TX_CPLT_CB_ID MMC Tx Complete Callback ID + * @arg @ref DAL_MMC_RX_CPLT_CB_ID MMC Rx Complete Callback ID + * @arg @ref DAL_MMC_ERROR_CB_ID MMC Error Callback ID + * @arg @ref DAL_MMC_ABORT_CB_ID MMC Abort Callback ID + * @arg @ref DAL_MMC_MSP_INIT_CB_ID MMC MspInit Callback ID + * @arg @ref DAL_MMC_MSP_DEINIT_CB_ID MMC MspDeInit Callback ID + * @param pCallback : pointer to the Callback function + * @retval status + */ +DAL_StatusTypeDef DAL_MMC_RegisterCallback(MMC_HandleTypeDef *hmmc, DAL_MMC_CallbackIDTypeDef CallbackId, pMMC_CallbackTypeDef pCallback) +{ + DAL_StatusTypeDef status = DAL_OK; + + if(pCallback == NULL) + { + /* Update the error code */ + hmmc->ErrorCode |= DAL_MMC_ERROR_INVALID_CALLBACK; + return DAL_ERROR; + } + + /* Process locked */ + __DAL_LOCK(hmmc); + + if(hmmc->State == DAL_MMC_STATE_READY) + { + switch (CallbackId) + { + case DAL_MMC_TX_CPLT_CB_ID : + hmmc->TxCpltCallback = pCallback; + break; + case DAL_MMC_RX_CPLT_CB_ID : + hmmc->RxCpltCallback = pCallback; + break; + case DAL_MMC_ERROR_CB_ID : + hmmc->ErrorCallback = pCallback; + break; + case DAL_MMC_ABORT_CB_ID : + hmmc->AbortCpltCallback = pCallback; + break; + case DAL_MMC_MSP_INIT_CB_ID : + hmmc->MspInitCallback = pCallback; + break; + case DAL_MMC_MSP_DEINIT_CB_ID : + hmmc->MspDeInitCallback = pCallback; + break; + default : + /* Update the error code */ + hmmc->ErrorCode |= DAL_MMC_ERROR_INVALID_CALLBACK; + /* update return status */ + status = DAL_ERROR; + break; + } + } + else if (hmmc->State == DAL_MMC_STATE_RESET) + { + switch (CallbackId) + { + case DAL_MMC_MSP_INIT_CB_ID : + hmmc->MspInitCallback = pCallback; + break; + case DAL_MMC_MSP_DEINIT_CB_ID : + hmmc->MspDeInitCallback = pCallback; + break; + default : + /* Update the error code */ + hmmc->ErrorCode |= DAL_MMC_ERROR_INVALID_CALLBACK; + /* update return status */ + status = DAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + hmmc->ErrorCode |= DAL_MMC_ERROR_INVALID_CALLBACK; + /* update return status */ + status = DAL_ERROR; + } + + /* Release Lock */ + __DAL_UNLOCK(hmmc); + return status; +} + +/** + * @brief Unregister a User MMC Callback + * MMC Callback is redirected to the weak (surcharged) predefined callback + * @param hmmc : MMC handle + * @param CallbackId : ID of the callback to be unregistered + * This parameter can be one of the following values: + * @arg @ref DAL_MMC_TX_CPLT_CB_ID MMC Tx Complete Callback ID + * @arg @ref DAL_MMC_RX_CPLT_CB_ID MMC Rx Complete Callback ID + * @arg @ref DAL_MMC_ERROR_CB_ID MMC Error Callback ID + * @arg @ref DAL_MMC_ABORT_CB_ID MMC Abort Callback ID + * @arg @ref DAL_MMC_MSP_INIT_CB_ID MMC MspInit Callback ID + * @arg @ref DAL_MMC_MSP_DEINIT_CB_ID MMC MspDeInit Callback ID + * @retval status + */ +DAL_StatusTypeDef DAL_MMC_UnRegisterCallback(MMC_HandleTypeDef *hmmc, DAL_MMC_CallbackIDTypeDef CallbackId) +{ + DAL_StatusTypeDef status = DAL_OK; + + /* Process locked */ + __DAL_LOCK(hmmc); + + if(hmmc->State == DAL_MMC_STATE_READY) + { + switch (CallbackId) + { + case DAL_MMC_TX_CPLT_CB_ID : + hmmc->TxCpltCallback = DAL_MMC_TxCpltCallback; + break; + case DAL_MMC_RX_CPLT_CB_ID : + hmmc->RxCpltCallback = DAL_MMC_RxCpltCallback; + break; + case DAL_MMC_ERROR_CB_ID : + hmmc->ErrorCallback = DAL_MMC_ErrorCallback; + break; + case DAL_MMC_ABORT_CB_ID : + hmmc->AbortCpltCallback = DAL_MMC_AbortCallback; + break; + case DAL_MMC_MSP_INIT_CB_ID : + hmmc->MspInitCallback = DAL_MMC_MspInit; + break; + case DAL_MMC_MSP_DEINIT_CB_ID : + hmmc->MspDeInitCallback = DAL_MMC_MspDeInit; + break; + default : + /* Update the error code */ + hmmc->ErrorCode |= DAL_MMC_ERROR_INVALID_CALLBACK; + /* update return status */ + status = DAL_ERROR; + break; + } + } + else if (hmmc->State == DAL_MMC_STATE_RESET) + { + switch (CallbackId) + { + case DAL_MMC_MSP_INIT_CB_ID : + hmmc->MspInitCallback = DAL_MMC_MspInit; + break; + case DAL_MMC_MSP_DEINIT_CB_ID : + hmmc->MspDeInitCallback = DAL_MMC_MspDeInit; + break; + default : + /* Update the error code */ + hmmc->ErrorCode |= DAL_MMC_ERROR_INVALID_CALLBACK; + /* update return status */ + status = DAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + hmmc->ErrorCode |= DAL_MMC_ERROR_INVALID_CALLBACK; + /* update return status */ + status = DAL_ERROR; + } + + /* Release Lock */ + __DAL_UNLOCK(hmmc); + return status; +} +#endif + +/** + * @} + */ + +/** @addtogroup MMC_Exported_Functions_Group3 + * @brief management functions + * +@verbatim + ============================================================================== + ##### Peripheral Control functions ##### + ============================================================================== + [..] + This subsection provides a set of functions allowing to control the MMC card + operations and get the related information + +@endverbatim + * @{ + */ + +/** + * @brief Returns information the information of the card which are stored on + * the CID register. + * @param hmmc: Pointer to MMC handle + * @param pCID: Pointer to a DAL_MMC_CIDTypedef structure that + * contains all CID register parameters + * @retval DAL status + */ +DAL_StatusTypeDef DAL_MMC_GetCardCID(MMC_HandleTypeDef *hmmc, DAL_MMC_CardCIDTypeDef *pCID) +{ + pCID->ManufacturerID = (uint8_t)((hmmc->CID[0] & 0xFF000000U) >> 24U); + + pCID->OEM_AppliID = (uint16_t)((hmmc->CID[0] & 0x00FFFF00U) >> 8U); + + pCID->ProdName1 = (((hmmc->CID[0] & 0x000000FFU) << 24U) | ((hmmc->CID[1] & 0xFFFFFF00U) >> 8U)); + + pCID->ProdName2 = (uint8_t)(hmmc->CID[1] & 0x000000FFU); + + pCID->ProdRev = (uint8_t)((hmmc->CID[2] & 0xFF000000U) >> 24U); + + pCID->ProdSN = (((hmmc->CID[2] & 0x00FFFFFFU) << 8U) | ((hmmc->CID[3] & 0xFF000000U) >> 24U)); + + pCID->Reserved1 = (uint8_t)((hmmc->CID[3] & 0x00F00000U) >> 20U); + + pCID->ManufactDate = (uint16_t)((hmmc->CID[3] & 0x000FFF00U) >> 8U); + + pCID->CID_CRC = (uint8_t)((hmmc->CID[3] & 0x000000FEU) >> 1U); + + pCID->Reserved2 = 1U; + + return DAL_OK; +} + +/** + * @brief Returns information the information of the card which are stored on + * the CSD register. + * @param hmmc: Pointer to MMC handle + * @param pCSD: Pointer to a DAL_MMC_CardCSDTypeDef structure that + * contains all CSD register parameters + * @retval DAL status + */ +DAL_StatusTypeDef DAL_MMC_GetCardCSD(MMC_HandleTypeDef *hmmc, DAL_MMC_CardCSDTypeDef *pCSD) +{ + uint32_t block_nbr = 0; + + pCSD->CSDStruct = (uint8_t)((hmmc->CSD[0] & 0xC0000000U) >> 30U); + + pCSD->SysSpecVersion = (uint8_t)((hmmc->CSD[0] & 0x3C000000U) >> 26U); + + pCSD->Reserved1 = (uint8_t)((hmmc->CSD[0] & 0x03000000U) >> 24U); + + pCSD->TAAC = (uint8_t)((hmmc->CSD[0] & 0x00FF0000U) >> 16U); + + pCSD->NSAC = (uint8_t)((hmmc->CSD[0] & 0x0000FF00U) >> 8U); + + pCSD->MaxBusClkFrec = (uint8_t)(hmmc->CSD[0] & 0x000000FFU); + + pCSD->CardComdClasses = (uint16_t)((hmmc->CSD[1] & 0xFFF00000U) >> 20U); + + pCSD->RdBlockLen = (uint8_t)((hmmc->CSD[1] & 0x000F0000U) >> 16U); + + pCSD->PartBlockRead = (uint8_t)((hmmc->CSD[1] & 0x00008000U) >> 15U); + + pCSD->WrBlockMisalign = (uint8_t)((hmmc->CSD[1] & 0x00004000U) >> 14U); + + pCSD->RdBlockMisalign = (uint8_t)((hmmc->CSD[1] & 0x00002000U) >> 13U); + + pCSD->DSRImpl = (uint8_t)((hmmc->CSD[1] & 0x00001000U) >> 12U); + + pCSD->Reserved2 = 0U; /*!< Reserved */ + + pCSD->DeviceSize = (((hmmc->CSD[1] & 0x000003FFU) << 2U) | ((hmmc->CSD[2] & 0xC0000000U) >> 30U)); + + pCSD->MaxRdCurrentVDDMin = (uint8_t)((hmmc->CSD[2] & 0x38000000U) >> 27U); + + pCSD->MaxRdCurrentVDDMax = (uint8_t)((hmmc->CSD[2] & 0x07000000U) >> 24U); + + pCSD->MaxWrCurrentVDDMin = (uint8_t)((hmmc->CSD[2] & 0x00E00000U) >> 21U); + + pCSD->MaxWrCurrentVDDMax = (uint8_t)((hmmc->CSD[2] & 0x001C0000U) >> 18U); + + pCSD->DeviceSizeMul = (uint8_t)((hmmc->CSD[2] & 0x00038000U) >> 15U); + + if(MMC_ReadExtCSD(hmmc, &block_nbr, 212, 0x0FFFFFFFU) != DAL_OK) /* Field SEC_COUNT [215:212] */ + { + return DAL_ERROR; + } + + if(hmmc->MmcCard.CardType == MMC_LOW_CAPACITY_CARD) + { + hmmc->MmcCard.BlockNbr = (pCSD->DeviceSize + 1U) ; + hmmc->MmcCard.BlockNbr *= (1UL << ((pCSD->DeviceSizeMul & 0x07U) + 2U)); + hmmc->MmcCard.BlockSize = (1UL << (pCSD->RdBlockLen & 0x0FU)); + hmmc->MmcCard.LogBlockNbr = (hmmc->MmcCard.BlockNbr) * ((hmmc->MmcCard.BlockSize) / 512U); + hmmc->MmcCard.LogBlockSize = 512U; + } + else if(hmmc->MmcCard.CardType == MMC_HIGH_CAPACITY_CARD) + { + hmmc->MmcCard.BlockNbr = block_nbr; + hmmc->MmcCard.LogBlockNbr = hmmc->MmcCard.BlockNbr; + hmmc->MmcCard.BlockSize = 512U; + hmmc->MmcCard.LogBlockSize = hmmc->MmcCard.BlockSize; + } + else + { + /* Clear all the static flags */ + __DAL_MMC_CLEAR_FLAG(hmmc, SDIO_STATIC_FLAGS); + hmmc->ErrorCode |= DAL_MMC_ERROR_UNSUPPORTED_FEATURE; + hmmc->State = DAL_MMC_STATE_READY; + return DAL_ERROR; + } + + pCSD->EraseGrSize = (uint8_t)((hmmc->CSD[2] & 0x00004000U) >> 14U); + + pCSD->EraseGrMul = (uint8_t)((hmmc->CSD[2] & 0x00003F80U) >> 7U); + + pCSD->WrProtectGrSize = (uint8_t)(hmmc->CSD[2] & 0x0000007FU); + + pCSD->WrProtectGrEnable = (uint8_t)((hmmc->CSD[3] & 0x80000000U) >> 31U); + + pCSD->ManDeflECC = (uint8_t)((hmmc->CSD[3] & 0x60000000U) >> 29U); + + pCSD->WrSpeedFact = (uint8_t)((hmmc->CSD[3] & 0x1C000000U) >> 26U); + + pCSD->MaxWrBlockLen= (uint8_t)((hmmc->CSD[3] & 0x03C00000U) >> 22U); + + pCSD->WriteBlockPaPartial = (uint8_t)((hmmc->CSD[3] & 0x00200000U) >> 21U); + + pCSD->Reserved3 = 0; + + pCSD->ContentProtectAppli = (uint8_t)((hmmc->CSD[3] & 0x00010000U) >> 16U); + + pCSD->FileFormatGroup = (uint8_t)((hmmc->CSD[3] & 0x00008000U) >> 15U); + + pCSD->CopyFlag = (uint8_t)((hmmc->CSD[3] & 0x00004000U) >> 14U); + + pCSD->PermWrProtect = (uint8_t)((hmmc->CSD[3] & 0x00002000U) >> 13U); + + pCSD->TempWrProtect = (uint8_t)((hmmc->CSD[3] & 0x00001000U) >> 12U); + + pCSD->FileFormat = (uint8_t)((hmmc->CSD[3] & 0x00000C00U) >> 10U); + + pCSD->ECC= (uint8_t)((hmmc->CSD[3] & 0x00000300U) >> 8U); + + pCSD->CSD_CRC = (uint8_t)((hmmc->CSD[3] & 0x000000FEU) >> 1U); + + pCSD->Reserved4 = 1; + + return DAL_OK; +} + +/** + * @brief Gets the MMC card info. + * @param hmmc: Pointer to MMC handle + * @param pCardInfo: Pointer to the DAL_MMC_CardInfoTypeDef structure that + * will contain the MMC card status information + * @retval DAL status + */ +DAL_StatusTypeDef DAL_MMC_GetCardInfo(MMC_HandleTypeDef *hmmc, DAL_MMC_CardInfoTypeDef *pCardInfo) +{ + pCardInfo->CardType = (uint32_t)(hmmc->MmcCard.CardType); + pCardInfo->Class = (uint32_t)(hmmc->MmcCard.Class); + pCardInfo->RelCardAdd = (uint32_t)(hmmc->MmcCard.RelCardAdd); + pCardInfo->BlockNbr = (uint32_t)(hmmc->MmcCard.BlockNbr); + pCardInfo->BlockSize = (uint32_t)(hmmc->MmcCard.BlockSize); + pCardInfo->LogBlockNbr = (uint32_t)(hmmc->MmcCard.LogBlockNbr); + pCardInfo->LogBlockSize = (uint32_t)(hmmc->MmcCard.LogBlockSize); + + return DAL_OK; +} + +/** + * @brief Returns information the information of the card which are stored on + * the Extended CSD register. + * @param hmmc Pointer to MMC handle + * @param pExtCSD Pointer to a memory area (512 bytes) that contains all + * Extended CSD register parameters + * @param Timeout Specify timeout value + * @retval DAL status + */ +DAL_StatusTypeDef DAL_MMC_GetCardExtCSD(MMC_HandleTypeDef *hmmc, uint32_t *pExtCSD, uint32_t Timeout) +{ + SDIO_DataInitTypeDef config; + uint32_t errorstate; + uint32_t tickstart = DAL_GetTick(); + uint32_t count; + uint32_t *tmp_buf; + + if(NULL == pExtCSD) + { + hmmc->ErrorCode |= DAL_MMC_ERROR_PARAM; + return DAL_ERROR; + } + + if(hmmc->State == DAL_MMC_STATE_READY) + { + hmmc->ErrorCode = DAL_MMC_ERROR_NONE; + + hmmc->State = DAL_MMC_STATE_BUSY; + + /* Initialize data control register */ + hmmc->Instance->DCTRL = 0; + + /* Initiaize the destination pointer */ + tmp_buf = pExtCSD; + + /* Configure the MMC DPSM (Data Path State Machine) */ + config.DataTimeOut = SDMMC_DATATIMEOUT; + config.DataLength = 512; + config.DataBlockSize = SDIO_DATABLOCK_SIZE_512B; + config.TransferDir = SDIO_TRANSFER_DIR_TO_SDIO; + config.TransferMode = SDIO_TRANSFER_MODE_BLOCK; + config.DPSM = SDIO_DPSM_ENABLE; + (void)SDIO_ConfigData(hmmc->Instance, &config); + + /* Send ExtCSD Read command to Card */ + errorstate = SDMMC_CmdSendEXTCSD(hmmc->Instance, 0); + if(errorstate != DAL_MMC_ERROR_NONE) + { + /* Clear all the static flags */ + __DAL_MMC_CLEAR_FLAG(hmmc, SDIO_STATIC_FLAGS); + hmmc->ErrorCode |= errorstate; + hmmc->State = DAL_MMC_STATE_READY; + return DAL_ERROR; + } + + /* Poll on SDMMC flags */ + while(!__DAL_MMC_GET_FLAG(hmmc, SDIO_FLAG_RXOVERR | SDIO_FLAG_DCRCFAIL | SDIO_FLAG_DTIMEOUT | SDIO_FLAG_DATAEND)) + { + if(__DAL_MMC_GET_FLAG(hmmc, SDIO_FLAG_RXFIFOHF)) + { + /* Read data from SDMMC Rx FIFO */ + for(count = 0U; count < 8U; count++) + { + *tmp_buf = SDIO_ReadFIFO(hmmc->Instance); + tmp_buf++; + } + } + + if(((DAL_GetTick()-tickstart) >= Timeout) || (Timeout == 0U)) + { + /* Clear all the static flags */ + __DAL_MMC_CLEAR_FLAG(hmmc, SDIO_STATIC_FLAGS); + hmmc->ErrorCode |= DAL_MMC_ERROR_TIMEOUT; + hmmc->State= DAL_MMC_STATE_READY; + return DAL_TIMEOUT; + } + } + + /* Get error state */ + if(__DAL_MMC_GET_FLAG(hmmc, SDIO_FLAG_DTIMEOUT)) + { + /* Clear all the static flags */ + __DAL_MMC_CLEAR_FLAG(hmmc, SDIO_STATIC_FLAGS); + hmmc->ErrorCode |= DAL_MMC_ERROR_DATA_TIMEOUT; + hmmc->State = DAL_MMC_STATE_READY; + return DAL_ERROR; + } + else if(__DAL_MMC_GET_FLAG(hmmc, SDIO_FLAG_DCRCFAIL)) + { + /* Clear all the static flags */ + __DAL_MMC_CLEAR_FLAG(hmmc, SDIO_STATIC_FLAGS); + hmmc->ErrorCode |= DAL_MMC_ERROR_DATA_CRC_FAIL; + hmmc->State = DAL_MMC_STATE_READY; + return DAL_ERROR; + } + else if(__DAL_MMC_GET_FLAG(hmmc, SDIO_FLAG_RXOVERR)) + { + /* Clear all the static flags */ + __DAL_MMC_CLEAR_FLAG(hmmc, SDIO_STATIC_FLAGS); + hmmc->ErrorCode |= DAL_MMC_ERROR_RX_OVERRUN; + hmmc->State = DAL_MMC_STATE_READY; + return DAL_ERROR; + } + else + { + /* Nothing to do */ + } + + /* Clear all the static flags */ + __DAL_MMC_CLEAR_FLAG(hmmc, SDIO_STATIC_DATA_FLAGS); + hmmc->State = DAL_MMC_STATE_READY; + } + + return DAL_OK; +} + +/** + * @brief Enables wide bus operation for the requested card if supported by + * card. + * @param hmmc: Pointer to MMC handle + * @param WideMode: Specifies the MMC card wide bus mode + * This parameter can be one of the following values: + * @arg SDIO_BUS_WIDE_8B: 8-bit data transfer + * @arg SDIO_BUS_WIDE_4B: 4-bit data transfer + * @arg SDIO_BUS_WIDE_1B: 1-bit data transfer + * @retval DAL status + */ +DAL_StatusTypeDef DAL_MMC_ConfigWideBusOperation(MMC_HandleTypeDef *hmmc, uint32_t WideMode) +{ + uint32_t count; + SDIO_InitTypeDef Init; + uint32_t errorstate; + uint32_t response = 0U; + + /* Check the parameters */ + ASSERT_PARAM(IS_SDIO_BUS_WIDE(WideMode)); + + /* Change State */ + hmmc->State = DAL_MMC_STATE_BUSY; + + errorstate = MMC_PwrClassUpdate(hmmc, WideMode); + + if(errorstate == DAL_MMC_ERROR_NONE) + { + if(WideMode == SDIO_BUS_WIDE_8B) + { + errorstate = SDMMC_CmdSwitch(hmmc->Instance, 0x03B70200U); + } + else if(WideMode == SDIO_BUS_WIDE_4B) + { + errorstate = SDMMC_CmdSwitch(hmmc->Instance, 0x03B70100U); + } + else if(WideMode == SDIO_BUS_WIDE_1B) + { + errorstate = SDMMC_CmdSwitch(hmmc->Instance, 0x03B70000U); + } + else + { + /* WideMode is not a valid argument*/ + errorstate = DAL_MMC_ERROR_PARAM; + } + + /* Check for switch error and violation of the trial number of sending CMD 13 */ + if(errorstate == DAL_MMC_ERROR_NONE) + { + /* While card is not ready for data and trial number for sending CMD13 is not exceeded */ + count = SDMMC_MAX_TRIAL; + do + { + errorstate = SDMMC_CmdSendStatus(hmmc->Instance, (uint32_t)(((uint32_t)hmmc->MmcCard.RelCardAdd) << 16U)); + if(errorstate != DAL_MMC_ERROR_NONE) + { + break; + } + + /* Get command response */ + response = SDIO_GetResponse(hmmc->Instance, SDIO_RES1); + count--; + }while(((response & 0x100U) == 0U) && (count != 0U)); + + /* Check the status after the switch command execution */ + if ((count != 0U) && (errorstate == DAL_MMC_ERROR_NONE)) + { + /* Check the bit SWITCH_ERROR of the device status */ + if ((response & 0x80U) != 0U) + { + errorstate = SDMMC_ERROR_GENERAL_UNKNOWN_ERR; + } + else + { + /* Configure the SDIO peripheral */ + Init = hmmc->Init; + Init.BusWide = WideMode; + (void)SDIO_Init(hmmc->Instance, Init); + } + } + else if (count == 0U) + { + errorstate = SDMMC_ERROR_TIMEOUT; + } + else + { + /* Nothing to do */ + } + } + } + + /* Change State */ + hmmc->State = DAL_MMC_STATE_READY; + + if(errorstate != DAL_MMC_ERROR_NONE) + { + /* Clear all the static flags */ + __DAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode |= errorstate; + return DAL_ERROR; + } + + return DAL_OK; +} + +/** + * @brief Gets the current mmc card data state. + * @param hmmc: pointer to MMC handle + * @retval Card state + */ +DAL_MMC_CardStateTypeDef DAL_MMC_GetCardState(MMC_HandleTypeDef *hmmc) +{ + uint32_t cardstate; + uint32_t errorstate; + uint32_t resp1 = 0U; + + errorstate = MMC_SendStatus(hmmc, &resp1); + if(errorstate != DAL_MMC_ERROR_NONE) + { + hmmc->ErrorCode |= errorstate; + } + + cardstate = ((resp1 >> 9U) & 0x0FU); + + return (DAL_MMC_CardStateTypeDef)cardstate; +} + +/** + * @brief Abort the current transfer and disable the MMC. + * @param hmmc: pointer to a MMC_HandleTypeDef structure that contains + * the configuration information for MMC module. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_MMC_Abort(MMC_HandleTypeDef *hmmc) +{ + DAL_MMC_CardStateTypeDef CardState; + + /* DIsable All interrupts */ + __DAL_MMC_DISABLE_IT(hmmc, SDIO_IT_DATAEND | SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT|\ + SDIO_IT_TXUNDERR| SDIO_IT_RXOVERR); + + /* Clear All flags */ + __DAL_MMC_CLEAR_FLAG(hmmc, SDIO_STATIC_DATA_FLAGS); + + if((hmmc->hdmatx != NULL) || (hmmc->hdmarx != NULL)) + { + /* Disable the MMC DMA request */ + hmmc->Instance->DCTRL &= (uint32_t)~((uint32_t)SDIO_DCTRL_DMAEN); + + /* Abort the MMC DMA Tx Stream */ + if(hmmc->hdmatx != NULL) + { + if(DAL_DMA_Abort(hmmc->hdmatx) != DAL_OK) + { + hmmc->ErrorCode |= DAL_MMC_ERROR_DMA; + } + } + /* Abort the MMC DMA Rx Stream */ + if(hmmc->hdmarx != NULL) + { + if(DAL_DMA_Abort(hmmc->hdmarx) != DAL_OK) + { + hmmc->ErrorCode |= DAL_MMC_ERROR_DMA; + } + } + } + + hmmc->State = DAL_MMC_STATE_READY; + + /* Initialize the MMC operation */ + hmmc->Context = MMC_CONTEXT_NONE; + + CardState = DAL_MMC_GetCardState(hmmc); + if((CardState == DAL_MMC_CARD_RECEIVING) || (CardState == DAL_MMC_CARD_SENDING)) + { + hmmc->ErrorCode = SDMMC_CmdStopTransfer(hmmc->Instance); + } + if(hmmc->ErrorCode != DAL_MMC_ERROR_NONE) + { + return DAL_ERROR; + } + return DAL_OK; +} + +/** + * @brief Abort the current transfer and disable the MMC (IT mode). + * @param hmmc: pointer to a MMC_HandleTypeDef structure that contains + * the configuration information for MMC module. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_MMC_Abort_IT(MMC_HandleTypeDef *hmmc) +{ + DAL_MMC_CardStateTypeDef CardState; + + /* DIsable All interrupts */ + __DAL_MMC_DISABLE_IT(hmmc, SDIO_IT_DATAEND | SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT|\ + SDIO_IT_TXUNDERR| SDIO_IT_RXOVERR); + + /* Clear All flags */ + __DAL_MMC_CLEAR_FLAG(hmmc, SDIO_STATIC_DATA_FLAGS); + + if((hmmc->hdmatx != NULL) || (hmmc->hdmarx != NULL)) + { + /* Disable the MMC DMA request */ + hmmc->Instance->DCTRL &= (uint32_t)~((uint32_t)SDIO_DCTRL_DMAEN); + + /* Abort the MMC DMA Tx Stream */ + if(hmmc->hdmatx != NULL) + { + hmmc->hdmatx->XferAbortCallback = MMC_DMATxAbort; + if(DAL_DMA_Abort_IT(hmmc->hdmatx) != DAL_OK) + { + hmmc->hdmatx = NULL; + } + } + /* Abort the MMC DMA Rx Stream */ + if(hmmc->hdmarx != NULL) + { + hmmc->hdmarx->XferAbortCallback = MMC_DMARxAbort; + if(DAL_DMA_Abort_IT(hmmc->hdmarx) != DAL_OK) + { + hmmc->hdmarx = NULL; + } + } + } + + /* No transfer ongoing on both DMA channels*/ + if((hmmc->hdmatx == NULL) && (hmmc->hdmarx == NULL)) + { + CardState = DAL_MMC_GetCardState(hmmc); + hmmc->State = DAL_MMC_STATE_READY; + + if((CardState == DAL_MMC_CARD_RECEIVING) || (CardState == DAL_MMC_CARD_SENDING)) + { + hmmc->ErrorCode = SDMMC_CmdStopTransfer(hmmc->Instance); + } + if(hmmc->ErrorCode != DAL_MMC_ERROR_NONE) + { + return DAL_ERROR; + } + else + { +#if defined (USE_DAL_MMC_REGISTER_CALLBACKS) && (USE_DAL_MMC_REGISTER_CALLBACKS == 1U) + hmmc->AbortCpltCallback(hmmc); +#else + DAL_MMC_AbortCallback(hmmc); +#endif + } + } + + return DAL_OK; +} + +/** + * @} + */ + +/** + * @} + */ + +/* Private function ----------------------------------------------------------*/ +/** @addtogroup MMC_Private_Functions + * @{ + */ + +/** + * @brief DMA MMC transmit process complete callback + * @param hdma: DMA handle + * @retval None + */ +static void MMC_DMATransmitCplt(DMA_HandleTypeDef *hdma) +{ + MMC_HandleTypeDef* hmmc = (MMC_HandleTypeDef* )(hdma->Parent); + + /* Enable DATAEND Interrupt */ + __DAL_MMC_ENABLE_IT(hmmc, (SDIO_IT_DATAEND)); +} + +/** + * @brief DMA MMC receive process complete callback + * @param hdma: DMA handle + * @retval None + */ +static void MMC_DMAReceiveCplt(DMA_HandleTypeDef *hdma) +{ + MMC_HandleTypeDef* hmmc = (MMC_HandleTypeDef* )(hdma->Parent); + uint32_t errorstate; + + /* Send stop command in multiblock write */ + if(hmmc->Context == (MMC_CONTEXT_READ_MULTIPLE_BLOCK | MMC_CONTEXT_DMA)) + { + errorstate = SDMMC_CmdStopTransfer(hmmc->Instance); + if(errorstate != DAL_MMC_ERROR_NONE) + { + hmmc->ErrorCode |= errorstate; +#if defined (USE_DAL_MMC_REGISTER_CALLBACKS) && (USE_DAL_MMC_REGISTER_CALLBACKS == 1U) + hmmc->ErrorCallback(hmmc); +#else + DAL_MMC_ErrorCallback(hmmc); +#endif + } + } + + /* Disable the DMA transfer for transmit request by setting the DMAEN bit + in the MMC DCTRL register */ + hmmc->Instance->DCTRL &= (uint32_t)~((uint32_t)SDIO_DCTRL_DMAEN); + + /* Clear all the static flags */ + __DAL_MMC_CLEAR_FLAG(hmmc, SDIO_STATIC_DATA_FLAGS); + + hmmc->State = DAL_MMC_STATE_READY; + +#if defined (USE_DAL_MMC_REGISTER_CALLBACKS) && (USE_DAL_MMC_REGISTER_CALLBACKS == 1U) + hmmc->RxCpltCallback(hmmc); +#else + DAL_MMC_RxCpltCallback(hmmc); +#endif +} + +/** + * @brief DMA MMC communication error callback + * @param hdma: DMA handle + * @retval None + */ +static void MMC_DMAError(DMA_HandleTypeDef *hdma) +{ + MMC_HandleTypeDef* hmmc = (MMC_HandleTypeDef* )(hdma->Parent); + DAL_MMC_CardStateTypeDef CardState; + uint32_t RxErrorCode, TxErrorCode; + + /* if DMA error is FIFO error ignore it */ + if(DAL_DMA_GetError(hdma) != DAL_DMA_ERROR_FE) + { + RxErrorCode = hmmc->hdmarx->ErrorCode; + TxErrorCode = hmmc->hdmatx->ErrorCode; + if((RxErrorCode == DAL_DMA_ERROR_TE) || (TxErrorCode == DAL_DMA_ERROR_TE)) + { + /* Clear All flags */ + __DAL_MMC_CLEAR_FLAG(hmmc, SDIO_STATIC_FLAGS); + + /* Disable All interrupts */ + __DAL_MMC_DISABLE_IT(hmmc, SDIO_IT_DATAEND | SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT|\ + SDIO_IT_TXUNDERR| SDIO_IT_RXOVERR); + + hmmc->ErrorCode |= DAL_MMC_ERROR_DMA; + CardState = DAL_MMC_GetCardState(hmmc); + if((CardState == DAL_MMC_CARD_RECEIVING) || (CardState == DAL_MMC_CARD_SENDING)) + { + hmmc->ErrorCode |= SDMMC_CmdStopTransfer(hmmc->Instance); + } + + hmmc->State= DAL_MMC_STATE_READY; + } + +#if defined (USE_DAL_MMC_REGISTER_CALLBACKS) && (USE_DAL_MMC_REGISTER_CALLBACKS == 1U) + hmmc->ErrorCallback(hmmc); +#else + DAL_MMC_ErrorCallback(hmmc); +#endif + } +} + +/** + * @brief DMA MMC Tx Abort callback + * @param hdma: DMA handle + * @retval None + */ +static void MMC_DMATxAbort(DMA_HandleTypeDef *hdma) +{ + MMC_HandleTypeDef* hmmc = (MMC_HandleTypeDef* )(hdma->Parent); + DAL_MMC_CardStateTypeDef CardState; + + if(hmmc->hdmatx != NULL) + { + hmmc->hdmatx = NULL; + } + + /* All DMA channels are aborted */ + if(hmmc->hdmarx == NULL) + { + CardState = DAL_MMC_GetCardState(hmmc); + hmmc->ErrorCode = DAL_MMC_ERROR_NONE; + hmmc->State = DAL_MMC_STATE_READY; + if((CardState == DAL_MMC_CARD_RECEIVING) || (CardState == DAL_MMC_CARD_SENDING)) + { + hmmc->ErrorCode |= SDMMC_CmdStopTransfer(hmmc->Instance); + + if(hmmc->ErrorCode != DAL_MMC_ERROR_NONE) + { +#if defined (USE_DAL_MMC_REGISTER_CALLBACKS) && (USE_DAL_MMC_REGISTER_CALLBACKS == 1U) + hmmc->AbortCpltCallback(hmmc); +#else + DAL_MMC_AbortCallback(hmmc); +#endif + } + else + { +#if defined (USE_DAL_MMC_REGISTER_CALLBACKS) && (USE_DAL_MMC_REGISTER_CALLBACKS == 1U) + hmmc->ErrorCallback(hmmc); +#else + DAL_MMC_ErrorCallback(hmmc); +#endif + } + } + } +} + +/** + * @brief DMA MMC Rx Abort callback + * @param hdma: DMA handle + * @retval None + */ +static void MMC_DMARxAbort(DMA_HandleTypeDef *hdma) +{ + MMC_HandleTypeDef* hmmc = (MMC_HandleTypeDef* )(hdma->Parent); + DAL_MMC_CardStateTypeDef CardState; + + if(hmmc->hdmarx != NULL) + { + hmmc->hdmarx = NULL; + } + + /* All DMA channels are aborted */ + if(hmmc->hdmatx == NULL) + { + CardState = DAL_MMC_GetCardState(hmmc); + hmmc->ErrorCode = DAL_MMC_ERROR_NONE; + hmmc->State = DAL_MMC_STATE_READY; + if((CardState == DAL_MMC_CARD_RECEIVING) || (CardState == DAL_MMC_CARD_SENDING)) + { + hmmc->ErrorCode |= SDMMC_CmdStopTransfer(hmmc->Instance); + + if(hmmc->ErrorCode != DAL_MMC_ERROR_NONE) + { +#if defined (USE_DAL_MMC_REGISTER_CALLBACKS) && (USE_DAL_MMC_REGISTER_CALLBACKS == 1U) + hmmc->AbortCpltCallback(hmmc); +#else + DAL_MMC_AbortCallback(hmmc); +#endif + } + else + { +#if defined (USE_DAL_MMC_REGISTER_CALLBACKS) && (USE_DAL_MMC_REGISTER_CALLBACKS == 1U) + hmmc->ErrorCallback(hmmc); +#else + DAL_MMC_ErrorCallback(hmmc); +#endif + } + } + } +} + +/** + * @brief Initializes the mmc card. + * @param hmmc: Pointer to MMC handle + * @retval MMC Card error state + */ +static uint32_t MMC_InitCard(MMC_HandleTypeDef *hmmc) +{ + DAL_MMC_CardCSDTypeDef CSD; + uint32_t errorstate; + uint16_t mmc_rca = 2U; + MMC_InitTypeDef Init; + + /* Check the power State */ + if(SDIO_GetPowerState(hmmc->Instance) == 0U) + { + /* Power off */ + return DAL_MMC_ERROR_REQUEST_NOT_APPLICABLE; + } + + /* Send CMD2 ALL_SEND_CID */ + errorstate = SDMMC_CmdSendCID(hmmc->Instance); + if(errorstate != DAL_MMC_ERROR_NONE) + { + return errorstate; + } + else + { + /* Get Card identification number data */ + hmmc->CID[0U] = SDIO_GetResponse(hmmc->Instance, SDIO_RES1); + hmmc->CID[1U] = SDIO_GetResponse(hmmc->Instance, SDIO_RES2); + hmmc->CID[2U] = SDIO_GetResponse(hmmc->Instance, SDIO_RES3); + hmmc->CID[3U] = SDIO_GetResponse(hmmc->Instance, SDIO_RES4); + } + + /* Send CMD3 SET_REL_ADDR with RCA = 2 (should be greater than 1) */ + /* MMC Card publishes its RCA. */ + errorstate = SDMMC_CmdSetRelAddMmc(hmmc->Instance, mmc_rca); + if(errorstate != DAL_MMC_ERROR_NONE) + { + return errorstate; + } + + /* Get the MMC card RCA */ + hmmc->MmcCard.RelCardAdd = mmc_rca; + + /* Send CMD9 SEND_CSD with argument as card's RCA */ + errorstate = SDMMC_CmdSendCSD(hmmc->Instance, (uint32_t)(hmmc->MmcCard.RelCardAdd << 16U)); + if(errorstate != DAL_MMC_ERROR_NONE) + { + return errorstate; + } + else + { + /* Get Card Specific Data */ + hmmc->CSD[0U] = SDIO_GetResponse(hmmc->Instance, SDIO_RES1); + hmmc->CSD[1U] = SDIO_GetResponse(hmmc->Instance, SDIO_RES2); + hmmc->CSD[2U] = SDIO_GetResponse(hmmc->Instance, SDIO_RES3); + hmmc->CSD[3U] = SDIO_GetResponse(hmmc->Instance, SDIO_RES4); + } + + /* Get the Card Class */ + hmmc->MmcCard.Class = (SDIO_GetResponse(hmmc->Instance, SDIO_RES2) >> 20U); + + /* Select the Card */ + errorstate = SDMMC_CmdSelDesel(hmmc->Instance, (uint32_t)(((uint32_t)hmmc->MmcCard.RelCardAdd) << 16U)); + if(errorstate != DAL_MMC_ERROR_NONE) + { + return errorstate; + } + + /* Get CSD parameters */ + if (DAL_MMC_GetCardCSD(hmmc, &CSD) != DAL_OK) + { + return hmmc->ErrorCode; + } + + /* While card is not ready for data and trial number for sending CMD13 is not exceeded */ + errorstate = SDMMC_CmdSendStatus(hmmc->Instance, (uint32_t)(((uint32_t)hmmc->MmcCard.RelCardAdd) << 16U)); + if(errorstate != DAL_MMC_ERROR_NONE) + { + hmmc->ErrorCode |= errorstate; + } + + /* Get Extended CSD parameters */ + if (DAL_MMC_GetCardExtCSD(hmmc, hmmc->Ext_CSD, SDMMC_DATATIMEOUT) != DAL_OK) + { + return hmmc->ErrorCode; + } + + /* While card is not ready for data and trial number for sending CMD13 is not exceeded */ + errorstate = SDMMC_CmdSendStatus(hmmc->Instance, (uint32_t)(((uint32_t)hmmc->MmcCard.RelCardAdd) << 16U)); + if(errorstate != DAL_MMC_ERROR_NONE) + { + hmmc->ErrorCode |= errorstate; + } + + /* Configure the SDIO peripheral */ + Init = hmmc->Init; + Init.BusWide = SDIO_BUS_WIDE_1B; + (void)SDIO_Init(hmmc->Instance, Init); + + /* All cards are initialized */ + return DAL_MMC_ERROR_NONE; +} + +/** + * @brief Enquires cards about their operating voltage and configures clock + * controls and stores MMC information that will be needed in future + * in the MMC handle. + * @param hmmc: Pointer to MMC handle + * @retval error state + */ +static uint32_t MMC_PowerON(MMC_HandleTypeDef *hmmc) +{ + __IO uint32_t count = 0U; + uint32_t response = 0U, validvoltage = 0U; + uint32_t errorstate; + + /* CMD0: GO_IDLE_STATE */ + errorstate = SDMMC_CmdGoIdleState(hmmc->Instance); + if(errorstate != DAL_MMC_ERROR_NONE) + { + return errorstate; + } + + while(validvoltage == 0U) + { + if(count++ == SDMMC_MAX_VOLT_TRIAL) + { + return DAL_MMC_ERROR_INVALID_VOLTRANGE; + } + + /* SEND CMD1 APP_CMD with voltage range as argument */ + errorstate = SDMMC_CmdOpCondition(hmmc->Instance, MMC_VOLTAGE_RANGE); + if(errorstate != DAL_MMC_ERROR_NONE) + { + return DAL_MMC_ERROR_UNSUPPORTED_FEATURE; + } + + /* Get command response */ + response = SDIO_GetResponse(hmmc->Instance, SDIO_RES1); + + /* Get operating voltage*/ + validvoltage = (((response >> 31U) == 1U) ? 1U : 0U); + } + + /* When power routine is finished and command returns valid voltage */ + if (((response & (0xFF000000U)) >> 24U) == 0xC0U) + { + hmmc->MmcCard.CardType = MMC_HIGH_CAPACITY_CARD; + } + else + { + hmmc->MmcCard.CardType = MMC_LOW_CAPACITY_CARD; + } + + return DAL_MMC_ERROR_NONE; +} + +/** + * @brief Turns the SDIO output signals off. + * @param hmmc: Pointer to MMC handle + * @retval None + */ +static void MMC_PowerOFF(MMC_HandleTypeDef *hmmc) +{ + /* Set Power State to OFF */ + (void)SDIO_PowerState_OFF(hmmc->Instance); +} + +/** + * @brief Returns the current card's status. + * @param hmmc: Pointer to MMC handle + * @param pCardStatus: pointer to the buffer that will contain the MMC card + * status (Card Status register) + * @retval error state + */ +static uint32_t MMC_SendStatus(MMC_HandleTypeDef *hmmc, uint32_t *pCardStatus) +{ + uint32_t errorstate; + + if(pCardStatus == NULL) + { + return DAL_MMC_ERROR_PARAM; + } + + /* Send Status command */ + errorstate = SDMMC_CmdSendStatus(hmmc->Instance, (uint32_t)(hmmc->MmcCard.RelCardAdd << 16U)); + if(errorstate != DAL_MMC_ERROR_NONE) + { + return errorstate; + } + + /* Get MMC card status */ + *pCardStatus = SDIO_GetResponse(hmmc->Instance, SDIO_RES1); + + return DAL_MMC_ERROR_NONE; +} + +/** + * @brief Reads extended CSD register to get the sectors number of the device + * @param hmmc: Pointer to MMC handle + * @param pFieldData: Pointer to the read buffer + * @param FieldIndex: Index of the field to be read + * @param Timeout: Specify timeout value + * @retval DAL status + */ +static uint32_t MMC_ReadExtCSD(MMC_HandleTypeDef *hmmc, uint32_t *pFieldData, uint16_t FieldIndex, uint32_t Timeout) +{ + SDIO_DataInitTypeDef config; + uint32_t errorstate; + uint32_t tickstart = DAL_GetTick(); + uint32_t count; + uint32_t i = 0; + uint32_t tmp_data; + + hmmc->ErrorCode = DAL_MMC_ERROR_NONE; + + /* Initialize data control register */ + hmmc->Instance->DCTRL = 0; + + /* Configure the MMC DPSM (Data Path State Machine) */ + config.DataTimeOut = SDMMC_DATATIMEOUT; + config.DataLength = 512; + config.DataBlockSize = SDIO_DATABLOCK_SIZE_512B; + config.TransferDir = SDIO_TRANSFER_DIR_TO_SDIO; + config.TransferMode = SDIO_TRANSFER_MODE_BLOCK; + config.DPSM = SDIO_DPSM_ENABLE; + (void)SDIO_ConfigData(hmmc->Instance, &config); + + /* Set Block Size for Card */ + errorstate = SDMMC_CmdSendEXTCSD(hmmc->Instance, 0); + if(errorstate != DAL_MMC_ERROR_NONE) + { + /* Clear all the static flags */ + __DAL_MMC_CLEAR_FLAG(hmmc, SDIO_STATIC_FLAGS); + hmmc->ErrorCode |= errorstate; + hmmc->State = DAL_MMC_STATE_READY; + return DAL_ERROR; + } + + /* Poll on SDMMC flags */ + while(!__DAL_MMC_GET_FLAG(hmmc, SDIO_FLAG_RXOVERR | SDIO_FLAG_DCRCFAIL | SDIO_FLAG_DTIMEOUT | SDIO_FLAG_DATAEND)) + { + if(__DAL_MMC_GET_FLAG(hmmc, SDIO_FLAG_RXFIFOHF)) + { + /* Read data from SDMMC Rx FIFO */ + for(count = 0U; count < 8U; count++) + { + tmp_data = SDIO_ReadFIFO(hmmc->Instance); + /* eg : SEC_COUNT : FieldIndex = 212 => i+count = 53 */ + /* DEVICE_TYPE : FieldIndex = 196 => i+count = 49 */ + if ((i + count) == ((uint32_t)FieldIndex/4U)) + { + *pFieldData = tmp_data; + } + } + i += 8U; + } + + if(((DAL_GetTick()-tickstart) >= Timeout) || (Timeout == 0U)) + { + /* Clear all the static flags */ + __DAL_MMC_CLEAR_FLAG(hmmc, SDIO_STATIC_FLAGS); + hmmc->ErrorCode |= DAL_MMC_ERROR_TIMEOUT; + hmmc->State= DAL_MMC_STATE_READY; + return DAL_TIMEOUT; + } + } + + /* While card is not ready for data and trial number for sending CMD13 is not exceeded */ + errorstate = SDMMC_CmdSendStatus(hmmc->Instance, (uint32_t)(((uint32_t)hmmc->MmcCard.RelCardAdd) << 16)); + if(errorstate != DAL_MMC_ERROR_NONE) + { + hmmc->ErrorCode |= errorstate; + } + + /* Clear all the static flags */ + __DAL_MMC_CLEAR_FLAG(hmmc, SDIO_STATIC_DATA_FLAGS); + + hmmc->State = DAL_MMC_STATE_READY; + + return DAL_OK; +} + + +/** + * @brief Wrap up reading in non-blocking mode. + * @param hmmc: pointer to a MMC_HandleTypeDef structure that contains + * the configuration information. + * @retval None + */ +static void MMC_Read_IT(MMC_HandleTypeDef *hmmc) +{ + uint32_t count, data, dataremaining; + uint8_t* tmp; + + tmp = hmmc->pRxBuffPtr; + dataremaining = hmmc->RxXferSize; + + if (dataremaining > 0U) + { + /* Read data from SDIO Rx FIFO */ + for(count = 0U; count < 8U; count++) + { + data = SDIO_ReadFIFO(hmmc->Instance); + *tmp = (uint8_t)(data & 0xFFU); + tmp++; + dataremaining--; + *tmp = (uint8_t)((data >> 8U) & 0xFFU); + tmp++; + dataremaining--; + *tmp = (uint8_t)((data >> 16U) & 0xFFU); + tmp++; + dataremaining--; + *tmp = (uint8_t)((data >> 24U) & 0xFFU); + tmp++; + dataremaining--; + } + + hmmc->pRxBuffPtr = tmp; + hmmc->RxXferSize = dataremaining; + } +} + +/** + * @brief Wrap up writing in non-blocking mode. + * @param hmmc: pointer to a MMC_HandleTypeDef structure that contains + * the configuration information. + * @retval None + */ +static void MMC_Write_IT(MMC_HandleTypeDef *hmmc) +{ + uint32_t count, data, dataremaining; + uint8_t* tmp; + + tmp = hmmc->pTxBuffPtr; + dataremaining = hmmc->TxXferSize; + + if (dataremaining > 0U) + { + /* Write data to SDIO Tx FIFO */ + for(count = 0U; count < 8U; count++) + { + data = (uint32_t)(*tmp); + tmp++; + dataremaining--; + data |= ((uint32_t)(*tmp) << 8U); + tmp++; + dataremaining--; + data |= ((uint32_t)(*tmp) << 16U); + tmp++; + dataremaining--; + data |= ((uint32_t)(*tmp) << 24U); + tmp++; + dataremaining--; + (void)SDIO_WriteFIFO(hmmc->Instance, &data); + } + + hmmc->pTxBuffPtr = tmp; + hmmc->TxXferSize = dataremaining; + } +} + +/** + * @brief Update the power class of the device. + * @param hmmc MMC handle + * @param Wide Wide of MMC bus + * @param Speed Speed of the MMC bus + * @retval MMC Card error state + */ +static uint32_t MMC_PwrClassUpdate(MMC_HandleTypeDef *hmmc, uint32_t Wide) +{ + uint32_t count; + uint32_t response = 0U; + uint32_t errorstate = DAL_MMC_ERROR_NONE; + uint32_t power_class, supported_pwr_class; + + if((Wide == SDIO_BUS_WIDE_8B) || (Wide == SDIO_BUS_WIDE_4B)) + { + power_class = 0U; /* Default value after power-on or software reset */ + + /* Read the PowerClass field of the Extended CSD register */ + if(MMC_ReadExtCSD(hmmc, &power_class, 187, SDMMC_DATATIMEOUT) != DAL_OK) /* Field POWER_CLASS [187] */ + { + errorstate = SDMMC_ERROR_GENERAL_UNKNOWN_ERR; + } + else + { + power_class = ((power_class >> 24U) & 0x000000FFU); + } + + /* Get the supported PowerClass field of the Extended CSD register */ + /* Field PWR_CL_26_xxx [201 or 203] */ + supported_pwr_class = ((hmmc->Ext_CSD[(MMC_EXT_CSD_PWR_CL_26_INDEX/4)] >> MMC_EXT_CSD_PWR_CL_26_POS) & 0x000000FFU); + + if(errorstate == DAL_MMC_ERROR_NONE) + { + if(Wide == SDIO_BUS_WIDE_8B) + { + /* Bit [7:4] : power class for 8-bits bus configuration - Bit [3:0] : power class for 4-bits bus configuration */ + supported_pwr_class = (supported_pwr_class >> 4U); + } + + if ((power_class & 0x0FU) != (supported_pwr_class & 0x0FU)) + { + /* Need to change current power class */ + errorstate = SDMMC_CmdSwitch(hmmc->Instance, (0x03BB0000U | ((supported_pwr_class & 0x0FU) << 8U))); + + if(errorstate == DAL_MMC_ERROR_NONE) + { + /* While card is not ready for data and trial number for sending CMD13 is not exceeded */ + count = SDMMC_MAX_TRIAL; + do + { + errorstate = SDMMC_CmdSendStatus(hmmc->Instance, (uint32_t)(((uint32_t)hmmc->MmcCard.RelCardAdd) << 16U)); + if(errorstate != DAL_MMC_ERROR_NONE) + { + break; + } + + /* Get command response */ + response = SDIO_GetResponse(hmmc->Instance, SDIO_RES1); + count--; + }while(((response & 0x100U) == 0U) && (count != 0U)); + + /* Check the status after the switch command execution */ + if ((count != 0U) && (errorstate == DAL_MMC_ERROR_NONE)) + { + /* Check the bit SWITCH_ERROR of the device status */ + if ((response & 0x80U) != 0U) + { + errorstate = SDMMC_ERROR_UNSUPPORTED_FEATURE; + } + } + else if (count == 0U) + { + errorstate = SDMMC_ERROR_TIMEOUT; + } + else + { + /* Nothing to do */ + } + } + } + } + } + + return errorstate; +} + +/** + * @} + */ + +#endif /* SDIO */ + +#endif /* DAL_MMC_MODULE_ENABLED */ + +/** + * @} + */ + +/** + * @} + */ diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_nand.c b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_nand.c new file mode 100644 index 0000000000..cf41c36059 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_nand.c @@ -0,0 +1,2289 @@ +/** + * + * @file apm32f4xx_dal_nand.c + * @brief NAND DAL module driver. + * This file provides a generic firmware to drive NAND memories mounted + * as external device. + * + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + * + @verbatim + ============================================================================== + ##### How to use this driver ##### + ============================================================================== + [..] + This driver is a generic layered driver which contains a set of APIs used to + control NAND flash memories. It uses the SMC/EMMC layer functions to interface + with NAND devices. This driver is used as follows: + + (+) NAND flash memory configuration sequence using the function DAL_NAND_Init() + with control and timing parameters for both common and attribute spaces. + + (+) Read NAND flash memory maker and device IDs using the function + DAL_NAND_Read_ID(). The read information is stored in the NAND_ID_TypeDef + structure declared by the function caller. + + (+) Access NAND flash memory by read/write operations using the functions + DAL_NAND_Read_Page_8b()/DAL_NAND_Read_SpareArea_8b(), + DAL_NAND_Write_Page_8b()/DAL_NAND_Write_SpareArea_8b(), + DAL_NAND_Read_Page_16b()/DAL_NAND_Read_SpareArea_16b(), + DAL_NAND_Write_Page_16b()/DAL_NAND_Write_SpareArea_16b() + to read/write page(s)/spare area(s). These functions use specific device + information (Block, page size..) predefined by the user in the NAND_DeviceConfigTypeDef + structure. The read/write address information is contained by the Nand_Address_Typedef + structure passed as parameter. + + (+) Perform NAND flash Reset chip operation using the function DAL_NAND_Reset(). + + (+) Perform NAND flash erase block operation using the function DAL_NAND_Erase_Block(). + The erase block address information is contained in the Nand_Address_Typedef + structure passed as parameter. + + (+) Read the NAND flash status operation using the function DAL_NAND_Read_Status(). + + (+) You can also control the NAND device by calling the control APIs DAL_NAND_ECC_Enable()/ + DAL_NAND_ECC_Disable() to respectively enable/disable the ECC code correction + feature or the function DAL_NAND_GetECC() to get the ECC correction code. + + (+) You can monitor the NAND device DAL state by calling the function + DAL_NAND_GetState() + + [..] + (@) This driver is a set of generic APIs which handle standard NAND flash operations. + If a NAND flash device contains different operations and/or implementations, + it should be implemented separately. + + *** Callback registration *** + ============================================= + [..] + The compilation define USE_DAL_NAND_REGISTER_CALLBACKS when set to 1 + allows the user to configure dynamically the driver callbacks. + + Use Functions DAL_NAND_RegisterCallback() to register a user callback, + it allows to register following callbacks: + (+) MspInitCallback : NAND MspInit. + (+) MspDeInitCallback : NAND MspDeInit. + This function takes as parameters the DAL peripheral handle, the Callback ID + and a pointer to the user callback function. + + Use function DAL_NAND_UnRegisterCallback() to reset a callback to the default + weak (surcharged) function. It allows to reset following callbacks: + (+) MspInitCallback : NAND MspInit. + (+) MspDeInitCallback : NAND MspDeInit. + This function) takes as parameters the DAL peripheral handle and the Callback ID. + + By default, after the DAL_NAND_Init and if the state is DAL_NAND_STATE_RESET + all callbacks are reset to the corresponding legacy weak (surcharged) functions. + Exception done for MspInit and MspDeInit callbacks that are respectively + reset to the legacy weak (surcharged) functions in the DAL_NAND_Init + and DAL_NAND_DeInit only when these callbacks are null (not registered beforehand). + If not, MspInit or MspDeInit are not null, the DAL_NAND_Init and DAL_NAND_DeInit + keep and use the user MspInit/MspDeInit callbacks (registered beforehand) + + Callbacks can be registered/unregistered in READY state only. + Exception done for MspInit/MspDeInit callbacks that can be registered/unregistered + in READY or RESET state, thus registered (user) MspInit/DeInit callbacks can be used + during the Init/DeInit. + In that case first register the MspInit/MspDeInit user callbacks + using DAL_NAND_RegisterCallback before calling DAL_NAND_DeInit + or DAL_NAND_Init function. + + When The compilation define USE_DAL_NAND_REGISTER_CALLBACKS is set to 0 or + not defined, the callback registering feature is not available + and weak (surcharged) callbacks are used. + + @endverbatim + * + */ + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal.h" + +#if defined(SMC_Bank2_3) + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +#ifdef DAL_NAND_MODULE_ENABLED + +/** @defgroup NAND NAND + * @brief NAND DAL module driver + * @{ + */ + +/* Private typedef -----------------------------------------------------------*/ +/* Private Constants ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Exported functions ---------------------------------------------------------*/ + +/** @defgroup NAND_Exported_Functions NAND Exported Functions + * @{ + */ + +/** @defgroup NAND_Exported_Functions_Group1 Initialization and de-initialization functions + * @brief Initialization and Configuration functions + * + @verbatim + ============================================================================== + ##### NAND Initialization and de-initialization functions ##### + ============================================================================== + [..] + This section provides functions allowing to initialize/de-initialize + the NAND memory + +@endverbatim + * @{ + */ + +/** + * @brief Perform NAND memory Initialization sequence + * @param hnand pointer to a NAND_HandleTypeDef structure that contains + * the configuration information for NAND module. + * @param ComSpace_Timing pointer to Common space timing structure + * @param AttSpace_Timing pointer to Attribute space timing structure + * @retval DAL status + */ +DAL_StatusTypeDef DAL_NAND_Init(NAND_HandleTypeDef *hnand, FMC_NAND_PCC_TimingTypeDef *ComSpace_Timing, + FMC_NAND_PCC_TimingTypeDef *AttSpace_Timing) +{ + /* Check the NAND handle state */ + if (hnand == NULL) + { + return DAL_ERROR; + } + + if (hnand->State == DAL_NAND_STATE_RESET) + { + /* Allocate lock resource and initialize it */ + hnand->Lock = DAL_UNLOCKED; + +#if (USE_DAL_NAND_REGISTER_CALLBACKS == 1) + if (hnand->MspInitCallback == NULL) + { + hnand->MspInitCallback = DAL_NAND_MspInit; + } + hnand->ItCallback = DAL_NAND_ITCallback; + + /* Init the low level hardware */ + hnand->MspInitCallback(hnand); +#else + /* Initialize the low level hardware (MSP) */ + DAL_NAND_MspInit(hnand); +#endif /* (USE_DAL_NAND_REGISTER_CALLBACKS) */ + } + + /* Initialize NAND control Interface */ + (void)FMC_NAND_Init(hnand->Instance, &(hnand->Init)); + + /* Initialize NAND common space timing Interface */ + (void)FMC_NAND_CommonSpace_Timing_Init(hnand->Instance, ComSpace_Timing, hnand->Init.NandBank); + + /* Initialize NAND attribute space timing Interface */ + (void)FMC_NAND_AttributeSpace_Timing_Init(hnand->Instance, AttSpace_Timing, hnand->Init.NandBank); + + /* Enable the NAND device */ +#if defined(SMC_Bank2_3) + __FMC_NAND_ENABLE(hnand->Instance, hnand->Init.NandBank); +#endif + + /* Update the NAND controller state */ + hnand->State = DAL_NAND_STATE_READY; + + return DAL_OK; +} + +/** + * @brief Perform NAND memory De-Initialization sequence + * @param hnand pointer to a NAND_HandleTypeDef structure that contains + * the configuration information for NAND module. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_NAND_DeInit(NAND_HandleTypeDef *hnand) +{ +#if (USE_DAL_NAND_REGISTER_CALLBACKS == 1) + if (hnand->MspDeInitCallback == NULL) + { + hnand->MspDeInitCallback = DAL_NAND_MspDeInit; + } + + /* DeInit the low level hardware */ + hnand->MspDeInitCallback(hnand); +#else + /* Initialize the low level hardware (MSP) */ + DAL_NAND_MspDeInit(hnand); +#endif /* (USE_DAL_NAND_REGISTER_CALLBACKS) */ + + /* Configure the NAND registers with their reset values */ + (void)FMC_NAND_DeInit(hnand->Instance, hnand->Init.NandBank); + + /* Reset the NAND controller state */ + hnand->State = DAL_NAND_STATE_RESET; + + /* Release Lock */ + __DAL_UNLOCK(hnand); + + return DAL_OK; +} + +/** + * @brief NAND MSP Init + * @param hnand pointer to a NAND_HandleTypeDef structure that contains + * the configuration information for NAND module. + * @retval None + */ +__weak void DAL_NAND_MspInit(NAND_HandleTypeDef *hnand) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hnand); + + /* NOTE : This function Should not be modified, when the callback is needed, + the DAL_NAND_MspInit could be implemented in the user file + */ +} + +/** + * @brief NAND MSP DeInit + * @param hnand pointer to a NAND_HandleTypeDef structure that contains + * the configuration information for NAND module. + * @retval None + */ +__weak void DAL_NAND_MspDeInit(NAND_HandleTypeDef *hnand) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hnand); + + /* NOTE : This function Should not be modified, when the callback is needed, + the DAL_NAND_MspDeInit could be implemented in the user file + */ +} + + +/** + * @brief This function handles NAND device interrupt request. + * @param hnand pointer to a NAND_HandleTypeDef structure that contains + * the configuration information for NAND module. + * @retval DAL status + */ +void DAL_NAND_IRQHandler(NAND_HandleTypeDef *hnand) +{ + /* Check NAND interrupt Rising edge flag */ + if (__FMC_NAND_GET_FLAG(hnand->Instance, hnand->Init.NandBank, FMC_FLAG_RISING_EDGE)) + { + /* NAND interrupt callback*/ +#if (USE_DAL_NAND_REGISTER_CALLBACKS == 1) + hnand->ItCallback(hnand); +#else + DAL_NAND_ITCallback(hnand); +#endif /* (USE_DAL_NAND_REGISTER_CALLBACKS) */ + + /* Clear NAND interrupt Rising edge pending bit */ +#if defined(SMC_Bank2_3) + __FMC_NAND_CLEAR_FLAG(hnand->Instance, hnand->Init.NandBank, FMC_FLAG_RISING_EDGE); +#endif /* SMC_Bank2_3 */ + } + + /* Check NAND interrupt Level flag */ + if (__FMC_NAND_GET_FLAG(hnand->Instance, hnand->Init.NandBank, FMC_FLAG_LEVEL)) + { + /* NAND interrupt callback*/ +#if (USE_DAL_NAND_REGISTER_CALLBACKS == 1) + hnand->ItCallback(hnand); +#else + DAL_NAND_ITCallback(hnand); +#endif /* (USE_DAL_NAND_REGISTER_CALLBACKS) */ + + /* Clear NAND interrupt Level pending bit */ +#if defined(SMC_Bank2_3) + __FMC_NAND_CLEAR_FLAG(hnand->Instance, hnand->Init.NandBank, FMC_FLAG_LEVEL); +#endif /* SMC_Bank2_3 */ + } + + /* Check NAND interrupt Falling edge flag */ + if (__FMC_NAND_GET_FLAG(hnand->Instance, hnand->Init.NandBank, FMC_FLAG_FALLING_EDGE)) + { + /* NAND interrupt callback*/ +#if (USE_DAL_NAND_REGISTER_CALLBACKS == 1) + hnand->ItCallback(hnand); +#else + DAL_NAND_ITCallback(hnand); +#endif /* (USE_DAL_NAND_REGISTER_CALLBACKS) */ + + /* Clear NAND interrupt Falling edge pending bit */ +#if defined(SMC_Bank2_3) + __FMC_NAND_CLEAR_FLAG(hnand->Instance, hnand->Init.NandBank, FMC_FLAG_FALLING_EDGE); +#endif /* SMC_Bank2_3 */ + } + + /* Check NAND interrupt FIFO empty flag */ + if (__FMC_NAND_GET_FLAG(hnand->Instance, hnand->Init.NandBank, FMC_FLAG_FEMPT)) + { + /* NAND interrupt callback*/ +#if (USE_DAL_NAND_REGISTER_CALLBACKS == 1) + hnand->ItCallback(hnand); +#else + DAL_NAND_ITCallback(hnand); +#endif /* (USE_DAL_NAND_REGISTER_CALLBACKS) */ + + /* Clear NAND interrupt FIFO empty pending bit */ +#if defined(SMC_Bank2_3) + __FMC_NAND_CLEAR_FLAG(hnand->Instance, hnand->Init.NandBank, FMC_FLAG_FEMPT); +#endif /* SMC_Bank2_3 */ + } + +} + +/** + * @brief NAND interrupt feature callback + * @param hnand pointer to a NAND_HandleTypeDef structure that contains + * the configuration information for NAND module. + * @retval None + */ +__weak void DAL_NAND_ITCallback(NAND_HandleTypeDef *hnand) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hnand); + + /* NOTE : This function Should not be modified, when the callback is needed, + the DAL_NAND_ITCallback could be implemented in the user file + */ +} + +/** + * @} + */ + +/** @defgroup NAND_Exported_Functions_Group2 Input and Output functions + * @brief Input Output and memory control functions + * + @verbatim + ============================================================================== + ##### NAND Input and Output functions ##### + ============================================================================== + [..] + This section provides functions allowing to use and control the NAND + memory + +@endverbatim + * @{ + */ + +/** + * @brief Read the NAND memory electronic signature + * @param hnand pointer to a NAND_HandleTypeDef structure that contains + * the configuration information for NAND module. + * @param pNAND_ID NAND ID structure + * @retval DAL status + */ +DAL_StatusTypeDef DAL_NAND_Read_ID(NAND_HandleTypeDef *hnand, NAND_IDTypeDef *pNAND_ID) +{ + __IO uint32_t data = 0; + __IO uint32_t data1 = 0; + uint32_t deviceaddress; + + /* Check the NAND controller state */ + if (hnand->State == DAL_NAND_STATE_BUSY) + { + return DAL_BUSY; + } + else if (hnand->State == DAL_NAND_STATE_READY) + { + /* Process Locked */ + __DAL_LOCK(hnand); + + /* Update the NAND controller state */ + hnand->State = DAL_NAND_STATE_BUSY; + + /* Identify the device address */ + deviceaddress = NAND_DEVICE; + + /* Send Read ID command sequence */ + *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_READID; + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00; + __DSB(); + + /* Read the electronic signature from NAND flash */ +#ifdef SMC_CTRL2_DBWIDCFG + if (hnand->Init.MemoryDataWidth == SMC_NAND_PCC_MEM_BUS_WIDTH_8) +#else /* FMC_PCR2_PWID is defined */ + if (hnand->Init.MemoryDataWidth == FMC_NAND_PCC_MEM_BUS_WIDTH_8) +#endif + { + data = *(__IO uint32_t *)deviceaddress; + + /* Return the data read */ + pNAND_ID->Maker_Id = ADDR_1ST_CYCLE(data); + pNAND_ID->Device_Id = ADDR_2ND_CYCLE(data); + pNAND_ID->Third_Id = ADDR_3RD_CYCLE(data); + pNAND_ID->Fourth_Id = ADDR_4TH_CYCLE(data); + } + else + { + data = *(__IO uint32_t *)deviceaddress; + data1 = *((__IO uint32_t *)deviceaddress + 4); + + /* Return the data read */ + pNAND_ID->Maker_Id = ADDR_1ST_CYCLE(data); + pNAND_ID->Device_Id = ADDR_3RD_CYCLE(data); + pNAND_ID->Third_Id = ADDR_1ST_CYCLE(data1); + pNAND_ID->Fourth_Id = ADDR_3RD_CYCLE(data1); + } + + /* Update the NAND controller state */ + hnand->State = DAL_NAND_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hnand); + } + else + { + return DAL_ERROR; + } + + return DAL_OK; +} + +/** + * @brief NAND memory reset + * @param hnand pointer to a NAND_HandleTypeDef structure that contains + * the configuration information for NAND module. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_NAND_Reset(NAND_HandleTypeDef *hnand) +{ + uint32_t deviceaddress; + + /* Check the NAND controller state */ + if (hnand->State == DAL_NAND_STATE_BUSY) + { + return DAL_BUSY; + } + else if (hnand->State == DAL_NAND_STATE_READY) + { + /* Process Locked */ + __DAL_LOCK(hnand); + + /* Update the NAND controller state */ + hnand->State = DAL_NAND_STATE_BUSY; + + /* Identify the device address */ + deviceaddress = NAND_DEVICE; + + + /* Send NAND reset command */ + *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = 0xFF; + + /* Update the NAND controller state */ + hnand->State = DAL_NAND_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hnand); + } + else + { + return DAL_ERROR; + } + + return DAL_OK; + +} + +/** + * @brief Configure the device: Enter the physical parameters of the device + * @param hnand pointer to a NAND_HandleTypeDef structure that contains + * the configuration information for NAND module. + * @param pDeviceConfig pointer to NAND_DeviceConfigTypeDef structure + * @retval DAL status + */ +DAL_StatusTypeDef DAL_NAND_ConfigDevice(NAND_HandleTypeDef *hnand, NAND_DeviceConfigTypeDef *pDeviceConfig) +{ + hnand->Config.PageSize = pDeviceConfig->PageSize; + hnand->Config.SpareAreaSize = pDeviceConfig->SpareAreaSize; + hnand->Config.BlockSize = pDeviceConfig->BlockSize; + hnand->Config.BlockNbr = pDeviceConfig->BlockNbr; + hnand->Config.PlaneSize = pDeviceConfig->PlaneSize; + hnand->Config.PlaneNbr = pDeviceConfig->PlaneNbr; + hnand->Config.ExtraCommandEnable = pDeviceConfig->ExtraCommandEnable; + + return DAL_OK; +} + +/** + * @brief Read Page(s) from NAND memory block (8-bits addressing) + * @param hnand pointer to a NAND_HandleTypeDef structure that contains + * the configuration information for NAND module. + * @param pAddress pointer to NAND address structure + * @param pBuffer pointer to destination read buffer + * @param NumPageToRead number of pages to read from block + * @retval DAL status + */ +DAL_StatusTypeDef DAL_NAND_Read_Page_8b(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress, uint8_t *pBuffer, + uint32_t NumPageToRead) +{ + uint32_t index; + uint32_t tickstart; + uint32_t deviceaddress; + uint32_t numpagesread = 0U; + uint32_t nandaddress; + uint32_t nbpages = NumPageToRead; + uint8_t *buff = pBuffer; + + /* Check the NAND controller state */ + if (hnand->State == DAL_NAND_STATE_BUSY) + { + return DAL_BUSY; + } + else if (hnand->State == DAL_NAND_STATE_READY) + { + /* Process Locked */ + __DAL_LOCK(hnand); + + /* Update the NAND controller state */ + hnand->State = DAL_NAND_STATE_BUSY; + + /* Identify the device address */ + deviceaddress = NAND_DEVICE; + + /* NAND raw address calculation */ + nandaddress = ARRAY_ADDRESS(pAddress, hnand); + + /* Page(s) read loop */ + while ((nbpages != 0U) && (nandaddress < ((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)))) + { + /* Send read page command sequence */ + *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_A; + __DSB(); + + /* Cards with page size <= 512 bytes */ + if ((hnand->Config.PageSize) <= 512U) + { + if (((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)) <= 65535U) + { + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); + __DSB(); + } + else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */ + { + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandaddress); + __DSB(); + } + } + else /* (hnand->Config.PageSize) > 512 */ + { + if (((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)) <= 65535U) + { + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); + __DSB(); + } + else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */ + { + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandaddress); + __DSB(); + } + } + + *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_TRUE1; + __DSB(); + + + if (hnand->Config.ExtraCommandEnable == ENABLE) + { + /* Get tick */ + tickstart = DAL_GetTick(); + + /* Read status until NAND is ready */ + while (DAL_NAND_Read_Status(hnand) != NAND_READY) + { + if ((DAL_GetTick() - tickstart) > NAND_WRITE_TIMEOUT) + { + /* Update the NAND controller state */ + hnand->State = DAL_NAND_STATE_ERROR; + + /* Process unlocked */ + __DAL_UNLOCK(hnand); + + return DAL_TIMEOUT; + } + } + + /* Go back to read mode */ + *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = ((uint8_t)0x00); + __DSB(); + } + + /* Get Data into Buffer */ + for (index = 0U; index < hnand->Config.PageSize; index++) + { + *buff = *(uint8_t *)deviceaddress; + buff++; + } + + /* Increment read pages number */ + numpagesread++; + + /* Decrement pages to read */ + nbpages--; + + /* Increment the NAND address */ + nandaddress = (uint32_t)(nandaddress + 1U); + } + + /* Update the NAND controller state */ + hnand->State = DAL_NAND_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hnand); + } + else + { + return DAL_ERROR; + } + + return DAL_OK; +} + +/** + * @brief Read Page(s) from NAND memory block (16-bits addressing) + * @param hnand pointer to a NAND_HandleTypeDef structure that contains + * the configuration information for NAND module. + * @param pAddress pointer to NAND address structure + * @param pBuffer pointer to destination read buffer. pBuffer should be 16bits aligned + * @param NumPageToRead number of pages to read from block + * @retval DAL status + */ +DAL_StatusTypeDef DAL_NAND_Read_Page_16b(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress, uint16_t *pBuffer, + uint32_t NumPageToRead) +{ + uint32_t index; + uint32_t tickstart; + uint32_t deviceaddress; + uint32_t numpagesread = 0U; + uint32_t nandaddress; + uint32_t nbpages = NumPageToRead; + uint16_t *buff = pBuffer; + + /* Check the NAND controller state */ + if (hnand->State == DAL_NAND_STATE_BUSY) + { + return DAL_BUSY; + } + else if (hnand->State == DAL_NAND_STATE_READY) + { + /* Process Locked */ + __DAL_LOCK(hnand); + + /* Update the NAND controller state */ + hnand->State = DAL_NAND_STATE_BUSY; + + /* Identify the device address */ + deviceaddress = NAND_DEVICE; + + /* NAND raw address calculation */ + nandaddress = ARRAY_ADDRESS(pAddress, hnand); + + /* Page(s) read loop */ + while ((nbpages != 0U) && (nandaddress < ((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)))) + { + /* Send read page command sequence */ + *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_A; + __DSB(); + + /* Cards with page size <= 512 bytes */ + if ((hnand->Config.PageSize) <= 512U) + { + if (((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)) <= 65535U) + { + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); + __DSB(); + } + else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */ + { + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandaddress); + __DSB(); + } + } + else /* (hnand->Config.PageSize) > 512 */ + { + if (((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)) <= 65535U) + { + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); + __DSB(); + } + else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */ + { + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandaddress); + __DSB(); + } + } + + *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_TRUE1; + __DSB(); + + if (hnand->Config.ExtraCommandEnable == ENABLE) + { + /* Get tick */ + tickstart = DAL_GetTick(); + + /* Read status until NAND is ready */ + while (DAL_NAND_Read_Status(hnand) != NAND_READY) + { + if ((DAL_GetTick() - tickstart) > NAND_WRITE_TIMEOUT) + { + /* Update the NAND controller state */ + hnand->State = DAL_NAND_STATE_ERROR; + + /* Process unlocked */ + __DAL_UNLOCK(hnand); + + return DAL_TIMEOUT; + } + } + + /* Go back to read mode */ + *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = ((uint8_t)0x00); + __DSB(); + } + + /* Calculate PageSize */ +#if defined(SMC_CTRL2_DBWIDCFG) + if (hnand->Init.MemoryDataWidth == SMC_NAND_PCC_MEM_BUS_WIDTH_8) +#else + if (hnand->Init.MemoryDataWidth == FMC_NAND_PCC_MEM_BUS_WIDTH_8) +#endif /* SMC_CTRL2_DBWIDCFG */ + { + hnand->Config.PageSize = hnand->Config.PageSize / 2U; + } + else + { + /* Do nothing */ + /* Keep the same PageSize for FMC_NAND_MEM_BUS_WIDTH_16*/ + } + + /* Get Data into Buffer */ + for (index = 0U; index < hnand->Config.PageSize; index++) + { + *buff = *(uint16_t *)deviceaddress; + buff++; + } + + /* Increment read pages number */ + numpagesread++; + + /* Decrement pages to read */ + nbpages--; + + /* Increment the NAND address */ + nandaddress = (uint32_t)(nandaddress + 1U); + } + + /* Update the NAND controller state */ + hnand->State = DAL_NAND_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hnand); + } + else + { + return DAL_ERROR; + } + + return DAL_OK; +} + +/** + * @brief Write Page(s) to NAND memory block (8-bits addressing) + * @param hnand pointer to a NAND_HandleTypeDef structure that contains + * the configuration information for NAND module. + * @param pAddress pointer to NAND address structure + * @param pBuffer pointer to source buffer to write + * @param NumPageToWrite number of pages to write to block + * @retval DAL status + */ +DAL_StatusTypeDef DAL_NAND_Write_Page_8b(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress, uint8_t *pBuffer, + uint32_t NumPageToWrite) +{ + uint32_t index; + uint32_t tickstart; + uint32_t deviceaddress; + uint32_t numpageswritten = 0U; + uint32_t nandaddress; + uint32_t nbpages = NumPageToWrite; + uint8_t *buff = pBuffer; + + /* Check the NAND controller state */ + if (hnand->State == DAL_NAND_STATE_BUSY) + { + return DAL_BUSY; + } + else if (hnand->State == DAL_NAND_STATE_READY) + { + /* Process Locked */ + __DAL_LOCK(hnand); + + /* Update the NAND controller state */ + hnand->State = DAL_NAND_STATE_BUSY; + + /* Identify the device address */ + deviceaddress = NAND_DEVICE; + + /* NAND raw address calculation */ + nandaddress = ARRAY_ADDRESS(pAddress, hnand); + + /* Page(s) write loop */ + while ((nbpages != 0U) && (nandaddress < ((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)))) + { + /* Send write page command sequence */ + *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_A; + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_WRITE0; + __DSB(); + + /* Cards with page size <= 512 bytes */ + if ((hnand->Config.PageSize) <= 512U) + { + if (((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)) <= 65535U) + { + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); + __DSB(); + } + else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */ + { + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandaddress); + __DSB(); + } + } + else /* (hnand->Config.PageSize) > 512 */ + { + if (((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)) <= 65535U) + { + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); + __DSB(); + } + else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */ + { + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandaddress); + __DSB(); + } + } + + /* Write data to memory */ + for (index = 0U; index < hnand->Config.PageSize; index++) + { + *(__IO uint8_t *)deviceaddress = *buff; + buff++; + __DSB(); + } + + *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_WRITE_TRUE1; + __DSB(); + + /* Get tick */ + tickstart = DAL_GetTick(); + + /* Read status until NAND is ready */ + while (DAL_NAND_Read_Status(hnand) != NAND_READY) + { + if ((DAL_GetTick() - tickstart) > NAND_WRITE_TIMEOUT) + { + /* Update the NAND controller state */ + hnand->State = DAL_NAND_STATE_ERROR; + + /* Process unlocked */ + __DAL_UNLOCK(hnand); + + return DAL_TIMEOUT; + } + } + + /* Increment written pages number */ + numpageswritten++; + + /* Decrement pages to write */ + nbpages--; + + /* Increment the NAND address */ + nandaddress = (uint32_t)(nandaddress + 1U); + } + + /* Update the NAND controller state */ + hnand->State = DAL_NAND_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hnand); + } + else + { + return DAL_ERROR; + } + + return DAL_OK; +} + +/** + * @brief Write Page(s) to NAND memory block (16-bits addressing) + * @param hnand pointer to a NAND_HandleTypeDef structure that contains + * the configuration information for NAND module. + * @param pAddress pointer to NAND address structure + * @param pBuffer pointer to source buffer to write. pBuffer should be 16bits aligned + * @param NumPageToWrite number of pages to write to block + * @retval DAL status + */ +DAL_StatusTypeDef DAL_NAND_Write_Page_16b(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress, uint16_t *pBuffer, + uint32_t NumPageToWrite) +{ + uint32_t index; + uint32_t tickstart; + uint32_t deviceaddress; + uint32_t numpageswritten = 0U; + uint32_t nandaddress; + uint32_t nbpages = NumPageToWrite; + uint16_t *buff = pBuffer; + + /* Check the NAND controller state */ + if (hnand->State == DAL_NAND_STATE_BUSY) + { + return DAL_BUSY; + } + else if (hnand->State == DAL_NAND_STATE_READY) + { + /* Process Locked */ + __DAL_LOCK(hnand); + + /* Update the NAND controller state */ + hnand->State = DAL_NAND_STATE_BUSY; + + /* Identify the device address */ + deviceaddress = NAND_DEVICE; + + /* NAND raw address calculation */ + nandaddress = ARRAY_ADDRESS(pAddress, hnand); + + /* Page(s) write loop */ + while ((nbpages != 0U) && (nandaddress < ((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)))) + { + /* Send write page command sequence */ + *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_A; + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_WRITE0; + __DSB(); + + /* Cards with page size <= 512 bytes */ + if ((hnand->Config.PageSize) <= 512U) + { + if (((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)) <= 65535U) + { + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); + __DSB(); + } + else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */ + { + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandaddress); + __DSB(); + } + } + else /* (hnand->Config.PageSize) > 512 */ + { + if (((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)) <= 65535U) + { + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); + __DSB(); + } + else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */ + { + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandaddress); + __DSB(); + } + } + + /* Calculate PageSize */ +#if defined(SMC_CTRL2_DBWIDCFG) + if (hnand->Init.MemoryDataWidth == SMC_NAND_PCC_MEM_BUS_WIDTH_8) +#else + if (hnand->Init.MemoryDataWidth == FMC_NAND_PCC_MEM_BUS_WIDTH_8) +#endif /* SMC_CTRL2_DBWIDCFG */ + { + hnand->Config.PageSize = hnand->Config.PageSize / 2U; + } + else + { + /* Do nothing */ + /* Keep the same PageSize for FMC_NAND_MEM_BUS_WIDTH_16*/ + } + + /* Write data to memory */ + for (index = 0U; index < hnand->Config.PageSize; index++) + { + *(__IO uint16_t *)deviceaddress = *buff; + buff++; + __DSB(); + } + + *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_WRITE_TRUE1; + __DSB(); + + /* Get tick */ + tickstart = DAL_GetTick(); + + /* Read status until NAND is ready */ + while (DAL_NAND_Read_Status(hnand) != NAND_READY) + { + if ((DAL_GetTick() - tickstart) > NAND_WRITE_TIMEOUT) + { + /* Update the NAND controller state */ + hnand->State = DAL_NAND_STATE_ERROR; + + /* Process unlocked */ + __DAL_UNLOCK(hnand); + + return DAL_TIMEOUT; + } + } + + /* Increment written pages number */ + numpageswritten++; + + /* Decrement pages to write */ + nbpages--; + + /* Increment the NAND address */ + nandaddress = (uint32_t)(nandaddress + 1U); + } + + /* Update the NAND controller state */ + hnand->State = DAL_NAND_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hnand); + } + else + { + return DAL_ERROR; + } + + return DAL_OK; +} + +/** + * @brief Read Spare area(s) from NAND memory (8-bits addressing) + * @param hnand pointer to a NAND_HandleTypeDef structure that contains + * the configuration information for NAND module. + * @param pAddress pointer to NAND address structure + * @param pBuffer pointer to source buffer to write + * @param NumSpareAreaToRead Number of spare area to read + * @retval DAL status + */ +DAL_StatusTypeDef DAL_NAND_Read_SpareArea_8b(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress, uint8_t *pBuffer, + uint32_t NumSpareAreaToRead) +{ + uint32_t index; + uint32_t tickstart; + uint32_t deviceaddress; + uint32_t numsparearearead = 0U; + uint32_t nandaddress; + uint32_t columnaddress; + uint32_t nbspare = NumSpareAreaToRead; + uint8_t *buff = pBuffer; + + /* Check the NAND controller state */ + if (hnand->State == DAL_NAND_STATE_BUSY) + { + return DAL_BUSY; + } + else if (hnand->State == DAL_NAND_STATE_READY) + { + /* Process Locked */ + __DAL_LOCK(hnand); + + /* Update the NAND controller state */ + hnand->State = DAL_NAND_STATE_BUSY; + + /* Identify the device address */ + deviceaddress = NAND_DEVICE; + + /* NAND raw address calculation */ + nandaddress = ARRAY_ADDRESS(pAddress, hnand); + + /* Column in page address */ + columnaddress = COLUMN_ADDRESS(hnand); + + /* Spare area(s) read loop */ + while ((nbspare != 0U) && (nandaddress < ((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)))) + { + /* Cards with page size <= 512 bytes */ + if ((hnand->Config.PageSize) <= 512U) + { + /* Send read spare area command sequence */ + *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_C; + __DSB(); + + if (((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)) <= 65535U) + { + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); + __DSB(); + } + else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */ + { + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandaddress); + __DSB(); + } + } + else /* (hnand->Config.PageSize) > 512 */ + { + /* Send read spare area command sequence */ + *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_A; + __DSB(); + + if (((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)) <= 65535U) + { + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = COLUMN_1ST_CYCLE(columnaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = COLUMN_2ND_CYCLE(columnaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); + __DSB(); + } + else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */ + { + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = COLUMN_1ST_CYCLE(columnaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = COLUMN_2ND_CYCLE(columnaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandaddress); + __DSB(); + } + } + + *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_TRUE1; + __DSB(); + + if (hnand->Config.ExtraCommandEnable == ENABLE) + { + /* Get tick */ + tickstart = DAL_GetTick(); + + /* Read status until NAND is ready */ + while (DAL_NAND_Read_Status(hnand) != NAND_READY) + { + if ((DAL_GetTick() - tickstart) > NAND_WRITE_TIMEOUT) + { + /* Update the NAND controller state */ + hnand->State = DAL_NAND_STATE_ERROR; + + /* Process unlocked */ + __DAL_UNLOCK(hnand); + + return DAL_TIMEOUT; + } + } + + /* Go back to read mode */ + *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = ((uint8_t)0x00); + __DSB(); + } + + /* Get Data into Buffer */ + for (index = 0U; index < hnand->Config.SpareAreaSize; index++) + { + *buff = *(uint8_t *)deviceaddress; + buff++; + } + + /* Increment read spare areas number */ + numsparearearead++; + + /* Decrement spare areas to read */ + nbspare--; + + /* Increment the NAND address */ + nandaddress = (uint32_t)(nandaddress + 1U); + } + + /* Update the NAND controller state */ + hnand->State = DAL_NAND_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hnand); + } + else + { + return DAL_ERROR; + } + + return DAL_OK; +} + +/** + * @brief Read Spare area(s) from NAND memory (16-bits addressing) + * @param hnand pointer to a NAND_HandleTypeDef structure that contains + * the configuration information for NAND module. + * @param pAddress pointer to NAND address structure + * @param pBuffer pointer to source buffer to write. pBuffer should be 16bits aligned. + * @param NumSpareAreaToRead Number of spare area to read + * @retval DAL status + */ +DAL_StatusTypeDef DAL_NAND_Read_SpareArea_16b(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress, + uint16_t *pBuffer, uint32_t NumSpareAreaToRead) +{ + uint32_t index; + uint32_t tickstart; + uint32_t deviceaddress; + uint32_t numsparearearead = 0U; + uint32_t nandaddress; + uint32_t columnaddress; + uint32_t nbspare = NumSpareAreaToRead; + uint16_t *buff = pBuffer; + + /* Check the NAND controller state */ + if (hnand->State == DAL_NAND_STATE_BUSY) + { + return DAL_BUSY; + } + else if (hnand->State == DAL_NAND_STATE_READY) + { + /* Process Locked */ + __DAL_LOCK(hnand); + + /* Update the NAND controller state */ + hnand->State = DAL_NAND_STATE_BUSY; + + /* Identify the device address */ + deviceaddress = NAND_DEVICE; + + /* NAND raw address calculation */ + nandaddress = ARRAY_ADDRESS(pAddress, hnand); + + /* Column in page address */ + columnaddress = (uint32_t)(COLUMN_ADDRESS(hnand)); + + /* Spare area(s) read loop */ + while ((nbspare != 0U) && (nandaddress < ((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)))) + { + /* Cards with page size <= 512 bytes */ + if ((hnand->Config.PageSize) <= 512U) + { + /* Send read spare area command sequence */ + *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_C; + __DSB(); + + if (((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)) <= 65535U) + { + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); + __DSB(); + } + else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */ + { + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandaddress); + __DSB(); + } + } + else /* (hnand->Config.PageSize) > 512 */ + { + /* Send read spare area command sequence */ + *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_A; + __DSB(); + + if (((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)) <= 65535U) + { + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = COLUMN_1ST_CYCLE(columnaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = COLUMN_2ND_CYCLE(columnaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); + __DSB(); + } + else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */ + { + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = COLUMN_1ST_CYCLE(columnaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = COLUMN_2ND_CYCLE(columnaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandaddress); + __DSB(); + } + } + + *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_TRUE1; + __DSB(); + + if (hnand->Config.ExtraCommandEnable == ENABLE) + { + /* Get tick */ + tickstart = DAL_GetTick(); + + /* Read status until NAND is ready */ + while (DAL_NAND_Read_Status(hnand) != NAND_READY) + { + if ((DAL_GetTick() - tickstart) > NAND_WRITE_TIMEOUT) + { + /* Update the NAND controller state */ + hnand->State = DAL_NAND_STATE_ERROR; + + /* Process unlocked */ + __DAL_UNLOCK(hnand); + + return DAL_TIMEOUT; + } + } + + /* Go back to read mode */ + *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = ((uint8_t)0x00); + __DSB(); + } + + /* Get Data into Buffer */ + for (index = 0U; index < hnand->Config.SpareAreaSize; index++) + { + *buff = *(uint16_t *)deviceaddress; + buff++; + } + + /* Increment read spare areas number */ + numsparearearead++; + + /* Decrement spare areas to read */ + nbspare--; + + /* Increment the NAND address */ + nandaddress = (uint32_t)(nandaddress + 1U); + } + + /* Update the NAND controller state */ + hnand->State = DAL_NAND_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hnand); + } + else + { + return DAL_ERROR; + } + + return DAL_OK; +} + +/** + * @brief Write Spare area(s) to NAND memory (8-bits addressing) + * @param hnand pointer to a NAND_HandleTypeDef structure that contains + * the configuration information for NAND module. + * @param pAddress pointer to NAND address structure + * @param pBuffer pointer to source buffer to write + * @param NumSpareAreaTowrite number of spare areas to write to block + * @retval DAL status + */ +DAL_StatusTypeDef DAL_NAND_Write_SpareArea_8b(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress, + uint8_t *pBuffer, uint32_t NumSpareAreaTowrite) +{ + uint32_t index; + uint32_t tickstart; + uint32_t deviceaddress; + uint32_t numspareareawritten = 0U; + uint32_t nandaddress; + uint32_t columnaddress; + uint32_t nbspare = NumSpareAreaTowrite; + uint8_t *buff = pBuffer; + + /* Check the NAND controller state */ + if (hnand->State == DAL_NAND_STATE_BUSY) + { + return DAL_BUSY; + } + else if (hnand->State == DAL_NAND_STATE_READY) + { + /* Process Locked */ + __DAL_LOCK(hnand); + + /* Update the NAND controller state */ + hnand->State = DAL_NAND_STATE_BUSY; + + /* Identify the device address */ + deviceaddress = NAND_DEVICE; + + /* Page address calculation */ + nandaddress = ARRAY_ADDRESS(pAddress, hnand); + + /* Column in page address */ + columnaddress = COLUMN_ADDRESS(hnand); + + /* Spare area(s) write loop */ + while ((nbspare != 0U) && (nandaddress < ((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)))) + { + /* Cards with page size <= 512 bytes */ + if ((hnand->Config.PageSize) <= 512U) + { + /* Send write Spare area command sequence */ + *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_C; + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_WRITE0; + __DSB(); + + if (((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)) <= 65535U) + { + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); + __DSB(); + } + else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */ + { + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandaddress); + __DSB(); + } + } + else /* (hnand->Config.PageSize) > 512 */ + { + /* Send write Spare area command sequence */ + *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_A; + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_WRITE0; + __DSB(); + + if (((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)) <= 65535U) + { + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = COLUMN_1ST_CYCLE(columnaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = COLUMN_2ND_CYCLE(columnaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); + __DSB(); + } + else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */ + { + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = COLUMN_1ST_CYCLE(columnaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = COLUMN_2ND_CYCLE(columnaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandaddress); + __DSB(); + } + } + + /* Write data to memory */ + for (index = 0U; index < hnand->Config.SpareAreaSize; index++) + { + *(__IO uint8_t *)deviceaddress = *buff; + buff++; + __DSB(); + } + + *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_WRITE_TRUE1; + __DSB(); + + /* Get tick */ + tickstart = DAL_GetTick(); + + /* Read status until NAND is ready */ + while (DAL_NAND_Read_Status(hnand) != NAND_READY) + { + if ((DAL_GetTick() - tickstart) > NAND_WRITE_TIMEOUT) + { + /* Update the NAND controller state */ + hnand->State = DAL_NAND_STATE_ERROR; + + /* Process unlocked */ + __DAL_UNLOCK(hnand); + + return DAL_TIMEOUT; + } + } + + /* Increment written spare areas number */ + numspareareawritten++; + + /* Decrement spare areas to write */ + nbspare--; + + /* Increment the NAND address */ + nandaddress = (uint32_t)(nandaddress + 1U); + } + + /* Update the NAND controller state */ + hnand->State = DAL_NAND_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hnand); + } + else + { + return DAL_ERROR; + } + + return DAL_OK; +} + +/** + * @brief Write Spare area(s) to NAND memory (16-bits addressing) + * @param hnand pointer to a NAND_HandleTypeDef structure that contains + * the configuration information for NAND module. + * @param pAddress pointer to NAND address structure + * @param pBuffer pointer to source buffer to write. pBuffer should be 16bits aligned. + * @param NumSpareAreaTowrite number of spare areas to write to block + * @retval DAL status + */ +DAL_StatusTypeDef DAL_NAND_Write_SpareArea_16b(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress, + uint16_t *pBuffer, uint32_t NumSpareAreaTowrite) +{ + uint32_t index; + uint32_t tickstart; + uint32_t deviceaddress; + uint32_t numspareareawritten = 0U; + uint32_t nandaddress; + uint32_t columnaddress; + uint32_t nbspare = NumSpareAreaTowrite; + uint16_t *buff = pBuffer; + + /* Check the NAND controller state */ + if (hnand->State == DAL_NAND_STATE_BUSY) + { + return DAL_BUSY; + } + else if (hnand->State == DAL_NAND_STATE_READY) + { + /* Process Locked */ + __DAL_LOCK(hnand); + + /* Update the NAND controller state */ + hnand->State = DAL_NAND_STATE_BUSY; + + /* Identify the device address */ + deviceaddress = NAND_DEVICE; + + /* NAND raw address calculation */ + nandaddress = ARRAY_ADDRESS(pAddress, hnand); + + /* Column in page address */ + columnaddress = (uint32_t)(COLUMN_ADDRESS(hnand)); + + /* Spare area(s) write loop */ + while ((nbspare != 0U) && (nandaddress < ((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)))) + { + /* Cards with page size <= 512 bytes */ + if ((hnand->Config.PageSize) <= 512U) + { + /* Send write Spare area command sequence */ + *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_C; + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_WRITE0; + __DSB(); + + if (((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)) <= 65535U) + { + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); + __DSB(); + } + else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */ + { + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandaddress); + __DSB(); + } + } + else /* (hnand->Config.PageSize) > 512 */ + { + /* Send write Spare area command sequence */ + *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_A; + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_WRITE0; + __DSB(); + + if (((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)) <= 65535U) + { + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = COLUMN_1ST_CYCLE(columnaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = COLUMN_2ND_CYCLE(columnaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); + __DSB(); + } + else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */ + { + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = COLUMN_1ST_CYCLE(columnaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = COLUMN_2ND_CYCLE(columnaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandaddress); + __DSB(); + } + } + + /* Write data to memory */ + for (index = 0U; index < hnand->Config.SpareAreaSize; index++) + { + *(__IO uint16_t *)deviceaddress = *buff; + buff++; + __DSB(); + } + + *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_WRITE_TRUE1; + __DSB(); + + /* Get tick */ + tickstart = DAL_GetTick(); + + /* Read status until NAND is ready */ + while (DAL_NAND_Read_Status(hnand) != NAND_READY) + { + if ((DAL_GetTick() - tickstart) > NAND_WRITE_TIMEOUT) + { + /* Update the NAND controller state */ + hnand->State = DAL_NAND_STATE_ERROR; + + /* Process unlocked */ + __DAL_UNLOCK(hnand); + + return DAL_TIMEOUT; + } + } + + /* Increment written spare areas number */ + numspareareawritten++; + + /* Decrement spare areas to write */ + nbspare--; + + /* Increment the NAND address */ + nandaddress = (uint32_t)(nandaddress + 1U); + } + + /* Update the NAND controller state */ + hnand->State = DAL_NAND_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hnand); + } + else + { + return DAL_ERROR; + } + + return DAL_OK; +} + +/** + * @brief NAND memory Block erase + * @param hnand pointer to a NAND_HandleTypeDef structure that contains + * the configuration information for NAND module. + * @param pAddress pointer to NAND address structure + * @retval DAL status + */ +DAL_StatusTypeDef DAL_NAND_Erase_Block(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress) +{ + uint32_t deviceaddress; + + /* Check the NAND controller state */ + if (hnand->State == DAL_NAND_STATE_BUSY) + { + return DAL_BUSY; + } + else if (hnand->State == DAL_NAND_STATE_READY) + { + /* Process Locked */ + __DAL_LOCK(hnand); + + /* Update the NAND controller state */ + hnand->State = DAL_NAND_STATE_BUSY; + + /* Identify the device address */ + deviceaddress = NAND_DEVICE; + + /* Send Erase block command sequence */ + *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_ERASE0; + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(ARRAY_ADDRESS(pAddress, hnand)); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(ARRAY_ADDRESS(pAddress, hnand)); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3RD_CYCLE(ARRAY_ADDRESS(pAddress, hnand)); + __DSB(); + + *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_ERASE1; + __DSB(); + + /* Update the NAND controller state */ + hnand->State = DAL_NAND_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hnand); + } + else + { + return DAL_ERROR; + } + + return DAL_OK; +} + +/** + * @brief Increment the NAND memory address + * @param hnand pointer to a NAND_HandleTypeDef structure that contains + * the configuration information for NAND module. + * @param pAddress pointer to NAND address structure + * @retval The new status of the increment address operation. It can be: + * - NAND_VALID_ADDRESS: When the new address is valid address + * - NAND_INVALID_ADDRESS: When the new address is invalid address + */ +uint32_t DAL_NAND_Address_Inc(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress) +{ + uint32_t status = NAND_VALID_ADDRESS; + + /* Increment page address */ + pAddress->Page++; + + /* Check NAND address is valid */ + if (pAddress->Page == hnand->Config.BlockSize) + { + pAddress->Page = 0; + pAddress->Block++; + + if (pAddress->Block == hnand->Config.PlaneSize) + { + pAddress->Block = 0; + pAddress->Plane++; + + if (pAddress->Plane == (hnand->Config.PlaneNbr)) + { + status = NAND_INVALID_ADDRESS; + } + } + } + + return (status); +} + +#if (USE_DAL_NAND_REGISTER_CALLBACKS == 1) +/** + * @brief Register a User NAND Callback + * To be used instead of the weak (surcharged) predefined callback + * @param hnand : NAND handle + * @param CallbackId : ID of the callback to be registered + * This parameter can be one of the following values: + * @arg @ref DAL_NAND_MSP_INIT_CB_ID NAND MspInit callback ID + * @arg @ref DAL_NAND_MSP_DEINIT_CB_ID NAND MspDeInit callback ID + * @arg @ref DAL_NAND_IT_CB_ID NAND IT callback ID + * @param pCallback : pointer to the Callback function + * @retval status + */ +DAL_StatusTypeDef DAL_NAND_RegisterCallback(NAND_HandleTypeDef *hnand, DAL_NAND_CallbackIDTypeDef CallbackId, + pNAND_CallbackTypeDef pCallback) +{ + DAL_StatusTypeDef status = DAL_OK; + + if (pCallback == NULL) + { + return DAL_ERROR; + } + + /* Process locked */ + __DAL_LOCK(hnand); + + if (hnand->State == DAL_NAND_STATE_READY) + { + switch (CallbackId) + { + case DAL_NAND_MSP_INIT_CB_ID : + hnand->MspInitCallback = pCallback; + break; + case DAL_NAND_MSP_DEINIT_CB_ID : + hnand->MspDeInitCallback = pCallback; + break; + case DAL_NAND_IT_CB_ID : + hnand->ItCallback = pCallback; + break; + default : + /* update return status */ + status = DAL_ERROR; + break; + } + } + else if (hnand->State == DAL_NAND_STATE_RESET) + { + switch (CallbackId) + { + case DAL_NAND_MSP_INIT_CB_ID : + hnand->MspInitCallback = pCallback; + break; + case DAL_NAND_MSP_DEINIT_CB_ID : + hnand->MspDeInitCallback = pCallback; + break; + default : + /* update return status */ + status = DAL_ERROR; + break; + } + } + else + { + /* update return status */ + status = DAL_ERROR; + } + + /* Release Lock */ + __DAL_UNLOCK(hnand); + return status; +} + +/** + * @brief Unregister a User NAND Callback + * NAND Callback is redirected to the weak (surcharged) predefined callback + * @param hnand : NAND handle + * @param CallbackId : ID of the callback to be unregistered + * This parameter can be one of the following values: + * @arg @ref DAL_NAND_MSP_INIT_CB_ID NAND MspInit callback ID + * @arg @ref DAL_NAND_MSP_DEINIT_CB_ID NAND MspDeInit callback ID + * @arg @ref DAL_NAND_IT_CB_ID NAND IT callback ID + * @retval status + */ +DAL_StatusTypeDef DAL_NAND_UnRegisterCallback(NAND_HandleTypeDef *hnand, DAL_NAND_CallbackIDTypeDef CallbackId) +{ + DAL_StatusTypeDef status = DAL_OK; + + /* Process locked */ + __DAL_LOCK(hnand); + + if (hnand->State == DAL_NAND_STATE_READY) + { + switch (CallbackId) + { + case DAL_NAND_MSP_INIT_CB_ID : + hnand->MspInitCallback = DAL_NAND_MspInit; + break; + case DAL_NAND_MSP_DEINIT_CB_ID : + hnand->MspDeInitCallback = DAL_NAND_MspDeInit; + break; + case DAL_NAND_IT_CB_ID : + hnand->ItCallback = DAL_NAND_ITCallback; + break; + default : + /* update return status */ + status = DAL_ERROR; + break; + } + } + else if (hnand->State == DAL_NAND_STATE_RESET) + { + switch (CallbackId) + { + case DAL_NAND_MSP_INIT_CB_ID : + hnand->MspInitCallback = DAL_NAND_MspInit; + break; + case DAL_NAND_MSP_DEINIT_CB_ID : + hnand->MspDeInitCallback = DAL_NAND_MspDeInit; + break; + default : + /* update return status */ + status = DAL_ERROR; + break; + } + } + else + { + /* update return status */ + status = DAL_ERROR; + } + + /* Release Lock */ + __DAL_UNLOCK(hnand); + return status; +} +#endif /* USE_DAL_NAND_REGISTER_CALLBACKS */ + +/** + * @} + */ + +/** @defgroup NAND_Exported_Functions_Group3 Peripheral Control functions + * @brief management functions + * +@verbatim + ============================================================================== + ##### NAND Control functions ##### + ============================================================================== + [..] + This subsection provides a set of functions allowing to control dynamically + the NAND interface. + +@endverbatim + * @{ + */ + + +/** + * @brief Enables dynamically NAND ECC feature. + * @param hnand pointer to a NAND_HandleTypeDef structure that contains + * the configuration information for NAND module. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_NAND_ECC_Enable(NAND_HandleTypeDef *hnand) +{ + /* Check the NAND controller state */ + if (hnand->State == DAL_NAND_STATE_BUSY) + { + return DAL_BUSY; + } + else if (hnand->State == DAL_NAND_STATE_READY) + { + /* Update the NAND state */ + hnand->State = DAL_NAND_STATE_BUSY; + + /* Enable ECC feature */ + (void)FMC_NAND_ECC_Enable(hnand->Instance, hnand->Init.NandBank); + + /* Update the NAND state */ + hnand->State = DAL_NAND_STATE_READY; + } + else + { + return DAL_ERROR; + } + + return DAL_OK; +} + +/** + * @brief Disables dynamically FMC_NAND ECC feature. + * @param hnand pointer to a NAND_HandleTypeDef structure that contains + * the configuration information for NAND module. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_NAND_ECC_Disable(NAND_HandleTypeDef *hnand) +{ + /* Check the NAND controller state */ + if (hnand->State == DAL_NAND_STATE_BUSY) + { + return DAL_BUSY; + } + else if (hnand->State == DAL_NAND_STATE_READY) + { + /* Update the NAND state */ + hnand->State = DAL_NAND_STATE_BUSY; + + /* Disable ECC feature */ + (void)FMC_NAND_ECC_Disable(hnand->Instance, hnand->Init.NandBank); + + /* Update the NAND state */ + hnand->State = DAL_NAND_STATE_READY; + } + else + { + return DAL_ERROR; + } + + return DAL_OK; +} + +/** + * @brief Disables dynamically NAND ECC feature. + * @param hnand pointer to a NAND_HandleTypeDef structure that contains + * the configuration information for NAND module. + * @param ECCval pointer to ECC value + * @param Timeout maximum timeout to wait + * @retval DAL status + */ +DAL_StatusTypeDef DAL_NAND_GetECC(NAND_HandleTypeDef *hnand, uint32_t *ECCval, uint32_t Timeout) +{ + DAL_StatusTypeDef status; + + /* Check the NAND controller state */ + if (hnand->State == DAL_NAND_STATE_BUSY) + { + return DAL_BUSY; + } + else if (hnand->State == DAL_NAND_STATE_READY) + { + /* Update the NAND state */ + hnand->State = DAL_NAND_STATE_BUSY; + + /* Get NAND ECC value */ + status = FMC_NAND_GetECC(hnand->Instance, ECCval, hnand->Init.NandBank, Timeout); + + /* Update the NAND state */ + hnand->State = DAL_NAND_STATE_READY; + } + else + { + return DAL_ERROR; + } + + return status; +} + +/** + * @} + */ + + +/** @defgroup NAND_Exported_Functions_Group4 Peripheral State functions + * @brief Peripheral State functions + * +@verbatim + ============================================================================== + ##### NAND State functions ##### + ============================================================================== + [..] + This subsection permits to get in run-time the status of the NAND controller + and the data flow. + +@endverbatim + * @{ + */ + +/** + * @brief return the NAND state + * @param hnand pointer to a NAND_HandleTypeDef structure that contains + * the configuration information for NAND module. + * @retval DAL state + */ +DAL_NAND_StateTypeDef DAL_NAND_GetState(NAND_HandleTypeDef *hnand) +{ + return hnand->State; +} + +/** + * @brief NAND memory read status + * @param hnand pointer to a NAND_HandleTypeDef structure that contains + * the configuration information for NAND module. + * @retval NAND status + */ +uint32_t DAL_NAND_Read_Status(NAND_HandleTypeDef *hnand) +{ + uint32_t data; + uint32_t deviceaddress; + UNUSED(hnand); + + /* Identify the device address */ + deviceaddress = NAND_DEVICE; + + /* Send Read status operation command */ + *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_STATUS; + + /* Read status register data */ + data = *(__IO uint8_t *)deviceaddress; + + /* Return the status */ + if ((data & NAND_ERROR) == NAND_ERROR) + { + return NAND_ERROR; + } + else if ((data & NAND_READY) == NAND_READY) + { + return NAND_READY; + } + else + { + return NAND_BUSY; + } +} + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#endif /* DAL_NAND_MODULE_ENABLED */ + +/** + * @} + */ + +#endif /* defined(SMC_Bank2_3) */ diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_nor.c b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_nor.c new file mode 100644 index 0000000000..d1124cbe18 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_nor.c @@ -0,0 +1,1568 @@ +/** + * + * @file apm32f4xx_dal_nor.c + * @brief NOR DAL module driver. + * This file provides a generic firmware to drive NOR memories mounted + * as external device. + * + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + * + @verbatim + ============================================================================== + ##### How to use this driver ##### + ============================================================================== + [..] + This driver is a generic layered driver which contains a set of APIs used to + control NOR flash memories. It uses the SMC/EMMC layer functions to interface + with NOR devices. This driver is used as follows: + + (+) NOR flash memory configuration sequence using the function DAL_NOR_Init() + with control and timing parameters for both normal and extended mode. + + (+) Read NOR flash memory manufacturer code and device IDs using the function + DAL_NOR_Read_ID(). The read information is stored in the NOR_ID_TypeDef + structure declared by the function caller. + + (+) Access NOR flash memory by read/write data unit operations using the functions + DAL_NOR_Read(), DAL_NOR_Program(). + + (+) Perform NOR flash erase block/chip operations using the functions + DAL_NOR_Erase_Block() and DAL_NOR_Erase_Chip(). + + (+) Read the NOR flash CFI (common flash interface) IDs using the function + DAL_NOR_Read_CFI(). The read information is stored in the NOR_CFI_TypeDef + structure declared by the function caller. + + (+) You can also control the NOR device by calling the control APIs DAL_NOR_WriteOperation_Enable()/ + DAL_NOR_WriteOperation_Disable() to respectively enable/disable the NOR write operation + + (+) You can monitor the NOR device DAL state by calling the function + DAL_NOR_GetState() + [..] + (@) This driver is a set of generic APIs which handle standard NOR flash operations. + If a NOR flash device contains different operations and/or implementations, + it should be implemented separately. + + *** NOR DAL driver macros list *** + ============================================= + [..] + Below the list of most used macros in NOR DAL driver. + + (+) NOR_WRITE : NOR memory write data to specified address + + *** Callback registration *** + ============================================= + [..] + The compilation define USE_DAL_NOR_REGISTER_CALLBACKS when set to 1 + allows the user to configure dynamically the driver callbacks. + + Use Functions DAL_NOR_RegisterCallback() to register a user callback, + it allows to register following callbacks: + (+) MspInitCallback : NOR MspInit. + (+) MspDeInitCallback : NOR MspDeInit. + This function takes as parameters the DAL peripheral handle, the Callback ID + and a pointer to the user callback function. + + Use function DAL_NOR_UnRegisterCallback() to reset a callback to the default + weak (surcharged) function. It allows to reset following callbacks: + (+) MspInitCallback : NOR MspInit. + (+) MspDeInitCallback : NOR MspDeInit. + This function) takes as parameters the DAL peripheral handle and the Callback ID. + + By default, after the DAL_NOR_Init and if the state is DAL_NOR_STATE_RESET + all callbacks are reset to the corresponding legacy weak (surcharged) functions. + Exception done for MspInit and MspDeInit callbacks that are respectively + reset to the legacy weak (surcharged) functions in the DAL_NOR_Init + and DAL_NOR_DeInit only when these callbacks are null (not registered beforehand). + If not, MspInit or MspDeInit are not null, the DAL_NOR_Init and DAL_NOR_DeInit + keep and use the user MspInit/MspDeInit callbacks (registered beforehand) + + Callbacks can be registered/unregistered in READY state only. + Exception done for MspInit/MspDeInit callbacks that can be registered/unregistered + in READY or RESET state, thus registered (user) MspInit/DeInit callbacks can be used + during the Init/DeInit. + In that case first register the MspInit/MspDeInit user callbacks + using DAL_NOR_RegisterCallback before calling DAL_NOR_DeInit + or DAL_NOR_Init function. + + When The compilation define USE_DAL_NOR_REGISTER_CALLBACKS is set to 0 or + not defined, the callback registering feature is not available + and weak (surcharged) callbacks are used. + + @endverbatim + * + */ + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal.h" + +#if defined(SMC_Bank1) + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +#ifdef DAL_NOR_MODULE_ENABLED + +/** @defgroup NOR NOR + * @brief NOR driver modules + * @{ + */ + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ + +/** @defgroup NOR_Private_Defines NOR Private Defines + * @{ + */ + +/* Constants to define address to set to write a command */ +#define NOR_CMD_ADDRESS_FIRST (uint16_t)0x0555 +#define NOR_CMD_ADDRESS_FIRST_CFI (uint16_t)0x0055 +#define NOR_CMD_ADDRESS_SECOND (uint16_t)0x02AA +#define NOR_CMD_ADDRESS_THIRD (uint16_t)0x0555 +#define NOR_CMD_ADDRESS_FOURTH (uint16_t)0x0555 +#define NOR_CMD_ADDRESS_FIFTH (uint16_t)0x02AA +#define NOR_CMD_ADDRESS_SIXTH (uint16_t)0x0555 + +/* Constants to define data to program a command */ +#define NOR_CMD_DATA_READ_RESET (uint16_t)0x00F0 +#define NOR_CMD_DATA_FIRST (uint16_t)0x00AA +#define NOR_CMD_DATA_SECOND (uint16_t)0x0055 +#define NOR_CMD_DATA_AUTO_SELECT (uint16_t)0x0090 +#define NOR_CMD_DATA_PROGRAM (uint16_t)0x00A0 +#define NOR_CMD_DATA_CHIP_BLOCK_ERASE_THIRD (uint16_t)0x0080 +#define NOR_CMD_DATA_CHIP_BLOCK_ERASE_FOURTH (uint16_t)0x00AA +#define NOR_CMD_DATA_CHIP_BLOCK_ERASE_FIFTH (uint16_t)0x0055 +#define NOR_CMD_DATA_CHIP_ERASE (uint16_t)0x0010 +#define NOR_CMD_DATA_CFI (uint16_t)0x0098 + +#define NOR_CMD_DATA_BUFFER_AND_PROG (uint8_t)0x25 +#define NOR_CMD_DATA_BUFFER_AND_PROG_CONFIRM (uint8_t)0x29 +#define NOR_CMD_DATA_BLOCK_ERASE (uint8_t)0x30 + +#define NOR_CMD_READ_ARRAY (uint16_t)0x00FF +#define NOR_CMD_WORD_PROGRAM (uint16_t)0x0040 +#define NOR_CMD_BUFFERED_PROGRAM (uint16_t)0x00E8 +#define NOR_CMD_CONFIRM (uint16_t)0x00D0 +#define NOR_CMD_BLOCK_ERASE (uint16_t)0x0020 +#define NOR_CMD_BLOCK_UNLOCK (uint16_t)0x0060 +#define NOR_CMD_READ_STATUS_REG (uint16_t)0x0070 +#define NOR_CMD_CLEAR_STATUS_REG (uint16_t)0x0050 + +/* Mask on NOR STATUS REGISTER */ +#define NOR_MASK_STATUS_DQ4 (uint16_t)0x0010 +#define NOR_MASK_STATUS_DQ5 (uint16_t)0x0020 +#define NOR_MASK_STATUS_DQ6 (uint16_t)0x0040 +#define NOR_MASK_STATUS_DQ7 (uint16_t)0x0080 + +/* Address of the primary command set */ +#define NOR_ADDRESS_COMMAND_SET (uint16_t)0x0013 + +/* Command set code assignment (defined in JEDEC JEP137B version may 2004) */ +#define NOR_INTEL_SHARP_EXT_COMMAND_SET (uint16_t)0x0001 /* Supported in this driver */ +#define NOR_AMD_FUJITSU_COMMAND_SET (uint16_t)0x0002 /* Supported in this driver */ +#define NOR_INTEL_STANDARD_COMMAND_SET (uint16_t)0x0003 /* Not Supported in this driver */ +#define NOR_AMD_FUJITSU_EXT_COMMAND_SET (uint16_t)0x0004 /* Not Supported in this driver */ +#define NOR_WINDBOND_STANDARD_COMMAND_SET (uint16_t)0x0006 /* Not Supported in this driver */ +#define NOR_MITSUBISHI_STANDARD_COMMAND_SET (uint16_t)0x0100 /* Not Supported in this driver */ +#define NOR_MITSUBISHI_EXT_COMMAND_SET (uint16_t)0x0101 /* Not Supported in this driver */ +#define NOR_PAGE_WRITE_COMMAND_SET (uint16_t)0x0102 /* Not Supported in this driver */ +#define NOR_INTEL_PERFORMANCE_COMMAND_SET (uint16_t)0x0200 /* Not Supported in this driver */ +#define NOR_INTEL_DATA_COMMAND_SET (uint16_t)0x0210 /* Not Supported in this driver */ + +/** + * @} + */ + +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/** @defgroup NOR_Private_Variables NOR Private Variables + * @{ + */ + +static uint32_t uwNORMemoryDataWidth = NOR_MEMORY_8B; + +/** + * @} + */ + +/* Private functions ---------------------------------------------------------*/ +/* Exported functions --------------------------------------------------------*/ +/** @defgroup NOR_Exported_Functions NOR Exported Functions + * @{ + */ + +/** @defgroup NOR_Exported_Functions_Group1 Initialization and de-initialization functions + * @brief Initialization and Configuration functions + * + @verbatim + ============================================================================== + ##### NOR Initialization and de_initialization functions ##### + ============================================================================== + [..] + This section provides functions allowing to initialize/de-initialize + the NOR memory + +@endverbatim + * @{ + */ + +/** + * @brief Perform the NOR memory Initialization sequence + * @param hnor pointer to a NOR_HandleTypeDef structure that contains + * the configuration information for NOR module. + * @param Timing pointer to NOR control timing structure + * @param ExtTiming pointer to NOR extended mode timing structure + * @retval DAL status + */ +DAL_StatusTypeDef DAL_NOR_Init(NOR_HandleTypeDef *hnor, FMC_NORSRAM_TimingTypeDef *Timing, + FMC_NORSRAM_TimingTypeDef *ExtTiming) +{ + uint32_t deviceaddress; + DAL_StatusTypeDef status = DAL_OK; + + /* Check the NOR handle parameter */ + if (hnor == NULL) + { + return DAL_ERROR; + } + + if (hnor->State == DAL_NOR_STATE_RESET) + { + /* Allocate lock resource and initialize it */ + hnor->Lock = DAL_UNLOCKED; + +#if (USE_DAL_NOR_REGISTER_CALLBACKS == 1) + if (hnor->MspInitCallback == NULL) + { + hnor->MspInitCallback = DAL_NOR_MspInit; + } + + /* Init the low level hardware */ + hnor->MspInitCallback(hnor); +#else + /* Initialize the low level hardware (MSP) */ + DAL_NOR_MspInit(hnor); +#endif /* (USE_DAL_NOR_REGISTER_CALLBACKS) */ + } + + /* Initialize NOR control Interface */ + (void)FMC_NORSRAM_Init(hnor->Instance, &(hnor->Init)); + + /* Initialize NOR timing Interface */ + (void)FMC_NORSRAM_Timing_Init(hnor->Instance, Timing, hnor->Init.NSBank); + + /* Initialize NOR extended mode timing Interface */ + (void)FMC_NORSRAM_Extended_Timing_Init(hnor->Extended, ExtTiming, hnor->Init.NSBank, hnor->Init.ExtendedMode); + + /* Enable the NORSRAM device */ + __FMC_NORSRAM_ENABLE(hnor->Instance, hnor->Init.NSBank); + + /* Initialize NOR Memory Data Width*/ + if (hnor->Init.MemoryDataWidth == FMC_NORSRAM_MEM_BUS_WIDTH_8) + { + uwNORMemoryDataWidth = NOR_MEMORY_8B; + } + else + { + uwNORMemoryDataWidth = NOR_MEMORY_16B; + } + + /* Initialize the NOR controller state */ + hnor->State = DAL_NOR_STATE_READY; + + /* Select the NOR device address */ + if (hnor->Init.NSBank == FMC_NORSRAM_BANK1) + { + deviceaddress = NOR_MEMORY_ADRESS1; + } + else if (hnor->Init.NSBank == FMC_NORSRAM_BANK2) + { + deviceaddress = NOR_MEMORY_ADRESS2; + } + else if (hnor->Init.NSBank == FMC_NORSRAM_BANK3) + { + deviceaddress = NOR_MEMORY_ADRESS3; + } + else /* FMC_NORSRAM_BANK4 */ + { + deviceaddress = NOR_MEMORY_ADRESS4; + } + + if (hnor->Init.WriteOperation == FMC_WRITE_OPERATION_DISABLE) + { + (void)FMC_NORSRAM_WriteOperation_Disable(hnor->Instance, hnor->Init.NSBank); + + /* Update the NOR controller state */ + hnor->State = DAL_NOR_STATE_PROTECTED; + } + else + { + /* Get the value of the command set */ + NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_FIRST_CFI), NOR_CMD_DATA_CFI); + hnor->CommandSet = *(__IO uint16_t *) NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_ADDRESS_COMMAND_SET); + + status = DAL_NOR_ReturnToReadMode(hnor); + } + + return status; +} + +/** + * @brief Perform NOR memory De-Initialization sequence + * @param hnor pointer to a NOR_HandleTypeDef structure that contains + * the configuration information for NOR module. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_NOR_DeInit(NOR_HandleTypeDef *hnor) +{ +#if (USE_DAL_NOR_REGISTER_CALLBACKS == 1) + if (hnor->MspDeInitCallback == NULL) + { + hnor->MspDeInitCallback = DAL_NOR_MspDeInit; + } + + /* DeInit the low level hardware */ + hnor->MspDeInitCallback(hnor); +#else + /* De-Initialize the low level hardware (MSP) */ + DAL_NOR_MspDeInit(hnor); +#endif /* (USE_DAL_NOR_REGISTER_CALLBACKS) */ + + /* Configure the NOR registers with their reset values */ + (void)FMC_NORSRAM_DeInit(hnor->Instance, hnor->Extended, hnor->Init.NSBank); + + /* Reset the NOR controller state */ + hnor->State = DAL_NOR_STATE_RESET; + + /* Release Lock */ + __DAL_UNLOCK(hnor); + + return DAL_OK; +} + +/** + * @brief NOR MSP Init + * @param hnor pointer to a NOR_HandleTypeDef structure that contains + * the configuration information for NOR module. + * @retval None + */ +__weak void DAL_NOR_MspInit(NOR_HandleTypeDef *hnor) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hnor); + + /* NOTE : This function Should not be modified, when the callback is needed, + the DAL_NOR_MspInit could be implemented in the user file + */ +} + +/** + * @brief NOR MSP DeInit + * @param hnor pointer to a NOR_HandleTypeDef structure that contains + * the configuration information for NOR module. + * @retval None + */ +__weak void DAL_NOR_MspDeInit(NOR_HandleTypeDef *hnor) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hnor); + + /* NOTE : This function Should not be modified, when the callback is needed, + the DAL_NOR_MspDeInit could be implemented in the user file + */ +} + +/** + * @brief NOR MSP Wait for Ready/Busy signal + * @param hnor pointer to a NOR_HandleTypeDef structure that contains + * the configuration information for NOR module. + * @param Timeout Maximum timeout value + * @retval None + */ +__weak void DAL_NOR_MspWait(NOR_HandleTypeDef *hnor, uint32_t Timeout) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hnor); + UNUSED(Timeout); + + /* NOTE : This function Should not be modified, when the callback is needed, + the DAL_NOR_MspWait could be implemented in the user file + */ +} + +/** + * @} + */ + +/** @defgroup NOR_Exported_Functions_Group2 Input and Output functions + * @brief Input Output and memory control functions + * + @verbatim + ============================================================================== + ##### NOR Input and Output functions ##### + ============================================================================== + [..] + This section provides functions allowing to use and control the NOR memory + +@endverbatim + * @{ + */ + +/** + * @brief Read NOR flash IDs + * @param hnor pointer to a NOR_HandleTypeDef structure that contains + * the configuration information for NOR module. + * @param pNOR_ID pointer to NOR ID structure + * @retval DAL status + */ +DAL_StatusTypeDef DAL_NOR_Read_ID(NOR_HandleTypeDef *hnor, NOR_IDTypeDef *pNOR_ID) +{ + uint32_t deviceaddress; + DAL_NOR_StateTypeDef state; + DAL_StatusTypeDef status = DAL_OK; + + /* Check the NOR controller state */ + state = hnor->State; + if (state == DAL_NOR_STATE_BUSY) + { + return DAL_BUSY; + } + else if (state == DAL_NOR_STATE_PROTECTED) + { + return DAL_ERROR; + } + else if (state == DAL_NOR_STATE_READY) + { + /* Process Locked */ + __DAL_LOCK(hnor); + + /* Update the NOR controller state */ + hnor->State = DAL_NOR_STATE_BUSY; + + /* Select the NOR device address */ + if (hnor->Init.NSBank == FMC_NORSRAM_BANK1) + { + deviceaddress = NOR_MEMORY_ADRESS1; + } + else if (hnor->Init.NSBank == FMC_NORSRAM_BANK2) + { + deviceaddress = NOR_MEMORY_ADRESS2; + } + else if (hnor->Init.NSBank == FMC_NORSRAM_BANK3) + { + deviceaddress = NOR_MEMORY_ADRESS3; + } + else /* FMC_NORSRAM_BANK4 */ + { + deviceaddress = NOR_MEMORY_ADRESS4; + } + + /* Send read ID command */ + if (hnor->CommandSet == NOR_AMD_FUJITSU_COMMAND_SET) + { + NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_FIRST), NOR_CMD_DATA_FIRST); + NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_SECOND), NOR_CMD_DATA_SECOND); + NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_THIRD), NOR_CMD_DATA_AUTO_SELECT); + } + else if (hnor->CommandSet == NOR_INTEL_SHARP_EXT_COMMAND_SET) + { + NOR_WRITE(deviceaddress, NOR_CMD_DATA_AUTO_SELECT); + } + else + { + /* Primary command set not supported by the driver */ + status = DAL_ERROR; + } + + if (status != DAL_ERROR) + { + /* Read the NOR IDs */ + pNOR_ID->Manufacturer_Code = *(__IO uint16_t *) NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, MC_ADDRESS); + pNOR_ID->Device_Code1 = *(__IO uint16_t *) NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, + DEVICE_CODE1_ADDR); + pNOR_ID->Device_Code2 = *(__IO uint16_t *) NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, + DEVICE_CODE2_ADDR); + pNOR_ID->Device_Code3 = *(__IO uint16_t *) NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, + DEVICE_CODE3_ADDR); + } + + /* Check the NOR controller state */ + hnor->State = state; + + /* Process unlocked */ + __DAL_UNLOCK(hnor); + } + else + { + return DAL_ERROR; + } + + return status; +} + +/** + * @brief Returns the NOR memory to Read mode. + * @param hnor pointer to a NOR_HandleTypeDef structure that contains + * the configuration information for NOR module. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_NOR_ReturnToReadMode(NOR_HandleTypeDef *hnor) +{ + uint32_t deviceaddress; + DAL_NOR_StateTypeDef state; + DAL_StatusTypeDef status = DAL_OK; + + /* Check the NOR controller state */ + state = hnor->State; + if (state == DAL_NOR_STATE_BUSY) + { + return DAL_BUSY; + } + else if (state == DAL_NOR_STATE_PROTECTED) + { + return DAL_ERROR; + } + else if (state == DAL_NOR_STATE_READY) + { + /* Process Locked */ + __DAL_LOCK(hnor); + + /* Update the NOR controller state */ + hnor->State = DAL_NOR_STATE_BUSY; + + /* Select the NOR device address */ + if (hnor->Init.NSBank == FMC_NORSRAM_BANK1) + { + deviceaddress = NOR_MEMORY_ADRESS1; + } + else if (hnor->Init.NSBank == FMC_NORSRAM_BANK2) + { + deviceaddress = NOR_MEMORY_ADRESS2; + } + else if (hnor->Init.NSBank == FMC_NORSRAM_BANK3) + { + deviceaddress = NOR_MEMORY_ADRESS3; + } + else /* FMC_NORSRAM_BANK4 */ + { + deviceaddress = NOR_MEMORY_ADRESS4; + } + + if (hnor->CommandSet == NOR_AMD_FUJITSU_COMMAND_SET) + { + NOR_WRITE(deviceaddress, NOR_CMD_DATA_READ_RESET); + } + else if (hnor->CommandSet == NOR_INTEL_SHARP_EXT_COMMAND_SET) + { + NOR_WRITE(deviceaddress, NOR_CMD_READ_ARRAY); + } + else + { + /* Primary command set not supported by the driver */ + status = DAL_ERROR; + } + + /* Check the NOR controller state */ + hnor->State = state; + + /* Process unlocked */ + __DAL_UNLOCK(hnor); + } + else + { + return DAL_ERROR; + } + + return status; +} + +/** + * @brief Read data from NOR memory + * @param hnor pointer to a NOR_HandleTypeDef structure that contains + * the configuration information for NOR module. + * @param pAddress pointer to Device address + * @param pData pointer to read data + * @retval DAL status + */ +DAL_StatusTypeDef DAL_NOR_Read(NOR_HandleTypeDef *hnor, uint32_t *pAddress, uint16_t *pData) +{ + uint32_t deviceaddress; + DAL_NOR_StateTypeDef state; + DAL_StatusTypeDef status = DAL_OK; + + /* Check the NOR controller state */ + state = hnor->State; + if (state == DAL_NOR_STATE_BUSY) + { + return DAL_BUSY; + } + else if (state == DAL_NOR_STATE_PROTECTED) + { + return DAL_ERROR; + } + else if (state == DAL_NOR_STATE_READY) + { + /* Process Locked */ + __DAL_LOCK(hnor); + + /* Update the NOR controller state */ + hnor->State = DAL_NOR_STATE_BUSY; + + /* Select the NOR device address */ + if (hnor->Init.NSBank == FMC_NORSRAM_BANK1) + { + deviceaddress = NOR_MEMORY_ADRESS1; + } + else if (hnor->Init.NSBank == FMC_NORSRAM_BANK2) + { + deviceaddress = NOR_MEMORY_ADRESS2; + } + else if (hnor->Init.NSBank == FMC_NORSRAM_BANK3) + { + deviceaddress = NOR_MEMORY_ADRESS3; + } + else /* FMC_NORSRAM_BANK4 */ + { + deviceaddress = NOR_MEMORY_ADRESS4; + } + + /* Send read data command */ + if (hnor->CommandSet == NOR_AMD_FUJITSU_COMMAND_SET) + { + NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_FIRST), NOR_CMD_DATA_FIRST); + NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_SECOND), NOR_CMD_DATA_SECOND); + NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_THIRD), NOR_CMD_DATA_READ_RESET); + } + else if (hnor->CommandSet == NOR_INTEL_SHARP_EXT_COMMAND_SET) + { + NOR_WRITE(pAddress, NOR_CMD_READ_ARRAY); + } + else + { + /* Primary command set not supported by the driver */ + status = DAL_ERROR; + } + + if (status != DAL_ERROR) + { + /* Read the data */ + *pData = (uint16_t)(*(__IO uint32_t *)pAddress); + } + + /* Check the NOR controller state */ + hnor->State = state; + + /* Process unlocked */ + __DAL_UNLOCK(hnor); + } + else + { + return DAL_ERROR; + } + + return status; +} + +/** + * @brief Program data to NOR memory + * @param hnor pointer to a NOR_HandleTypeDef structure that contains + * the configuration information for NOR module. + * @param pAddress Device address + * @param pData pointer to the data to write + * @retval DAL status + */ +DAL_StatusTypeDef DAL_NOR_Program(NOR_HandleTypeDef *hnor, uint32_t *pAddress, uint16_t *pData) +{ + uint32_t deviceaddress; + DAL_StatusTypeDef status = DAL_OK; + + /* Check the NOR controller state */ + if (hnor->State == DAL_NOR_STATE_BUSY) + { + return DAL_BUSY; + } + else if (hnor->State == DAL_NOR_STATE_READY) + { + /* Process Locked */ + __DAL_LOCK(hnor); + + /* Update the NOR controller state */ + hnor->State = DAL_NOR_STATE_BUSY; + + /* Select the NOR device address */ + if (hnor->Init.NSBank == FMC_NORSRAM_BANK1) + { + deviceaddress = NOR_MEMORY_ADRESS1; + } + else if (hnor->Init.NSBank == FMC_NORSRAM_BANK2) + { + deviceaddress = NOR_MEMORY_ADRESS2; + } + else if (hnor->Init.NSBank == FMC_NORSRAM_BANK3) + { + deviceaddress = NOR_MEMORY_ADRESS3; + } + else /* FMC_NORSRAM_BANK4 */ + { + deviceaddress = NOR_MEMORY_ADRESS4; + } + + /* Send program data command */ + if (hnor->CommandSet == NOR_AMD_FUJITSU_COMMAND_SET) + { + NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_FIRST), NOR_CMD_DATA_FIRST); + NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_SECOND), NOR_CMD_DATA_SECOND); + NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_THIRD), NOR_CMD_DATA_PROGRAM); + } + else if (hnor->CommandSet == NOR_INTEL_SHARP_EXT_COMMAND_SET) + { + NOR_WRITE(pAddress, NOR_CMD_WORD_PROGRAM); + } + else + { + /* Primary command set not supported by the driver */ + status = DAL_ERROR; + } + + if (status != DAL_ERROR) + { + /* Write the data */ + NOR_WRITE(pAddress, *pData); + } + + /* Check the NOR controller state */ + hnor->State = DAL_NOR_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hnor); + } + else + { + return DAL_ERROR; + } + + return status; +} + +/** + * @brief Reads a half-word buffer from the NOR memory. + * @param hnor pointer to the NOR handle + * @param uwAddress NOR memory internal address to read from. + * @param pData pointer to the buffer that receives the data read from the + * NOR memory. + * @param uwBufferSize number of Half word to read. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_NOR_ReadBuffer(NOR_HandleTypeDef *hnor, uint32_t uwAddress, uint16_t *pData, + uint32_t uwBufferSize) +{ + uint32_t deviceaddress; + uint32_t size = uwBufferSize; + uint32_t address = uwAddress; + uint16_t *data = pData; + DAL_NOR_StateTypeDef state; + DAL_StatusTypeDef status = DAL_OK; + + /* Check the NOR controller state */ + state = hnor->State; + if (state == DAL_NOR_STATE_BUSY) + { + return DAL_BUSY; + } + else if (state == DAL_NOR_STATE_PROTECTED) + { + return DAL_ERROR; + } + else if (state == DAL_NOR_STATE_READY) + { + /* Process Locked */ + __DAL_LOCK(hnor); + + /* Update the NOR controller state */ + hnor->State = DAL_NOR_STATE_BUSY; + + /* Select the NOR device address */ + if (hnor->Init.NSBank == FMC_NORSRAM_BANK1) + { + deviceaddress = NOR_MEMORY_ADRESS1; + } + else if (hnor->Init.NSBank == FMC_NORSRAM_BANK2) + { + deviceaddress = NOR_MEMORY_ADRESS2; + } + else if (hnor->Init.NSBank == FMC_NORSRAM_BANK3) + { + deviceaddress = NOR_MEMORY_ADRESS3; + } + else /* FMC_NORSRAM_BANK4 */ + { + deviceaddress = NOR_MEMORY_ADRESS4; + } + + /* Send read data command */ + if (hnor->CommandSet == NOR_AMD_FUJITSU_COMMAND_SET) + { + NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_FIRST), NOR_CMD_DATA_FIRST); + NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_SECOND), NOR_CMD_DATA_SECOND); + NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_THIRD), NOR_CMD_DATA_READ_RESET); + } + else if (hnor->CommandSet == NOR_INTEL_SHARP_EXT_COMMAND_SET) + { + NOR_WRITE(deviceaddress, NOR_CMD_READ_ARRAY); + } + else + { + /* Primary command set not supported by the driver */ + status = DAL_ERROR; + } + + if (status != DAL_ERROR) + { + /* Read buffer */ + while (size > 0U) + { + *data = *(__IO uint16_t *)address; + data++; + address += 2U; + size--; + } + } + + /* Check the NOR controller state */ + hnor->State = state; + + /* Process unlocked */ + __DAL_UNLOCK(hnor); + } + else + { + return DAL_ERROR; + } + + return status; +} + +/** + * @brief Writes a half-word buffer to the NOR memory. This function must be used + only with S29GL128P NOR memory. + * @param hnor pointer to the NOR handle + * @param uwAddress NOR memory internal start write address + * @param pData pointer to source data buffer. + * @param uwBufferSize Size of the buffer to write + * @retval DAL status + */ +DAL_StatusTypeDef DAL_NOR_ProgramBuffer(NOR_HandleTypeDef *hnor, uint32_t uwAddress, uint16_t *pData, + uint32_t uwBufferSize) +{ + uint16_t *p_currentaddress; + const uint16_t *p_endaddress; + uint16_t *data = pData; + uint32_t deviceaddress; + DAL_StatusTypeDef status = DAL_OK; + + /* Check the NOR controller state */ + if (hnor->State == DAL_NOR_STATE_BUSY) + { + return DAL_BUSY; + } + else if (hnor->State == DAL_NOR_STATE_READY) + { + /* Process Locked */ + __DAL_LOCK(hnor); + + /* Update the NOR controller state */ + hnor->State = DAL_NOR_STATE_BUSY; + + /* Select the NOR device address */ + if (hnor->Init.NSBank == FMC_NORSRAM_BANK1) + { + deviceaddress = NOR_MEMORY_ADRESS1; + } + else if (hnor->Init.NSBank == FMC_NORSRAM_BANK2) + { + deviceaddress = NOR_MEMORY_ADRESS2; + } + else if (hnor->Init.NSBank == FMC_NORSRAM_BANK3) + { + deviceaddress = NOR_MEMORY_ADRESS3; + } + else /* FMC_NORSRAM_BANK4 */ + { + deviceaddress = NOR_MEMORY_ADRESS4; + } + + /* Initialize variables */ + p_currentaddress = (uint16_t *)(deviceaddress + uwAddress); + p_endaddress = (uint16_t *)(deviceaddress + uwAddress + (2U * (uwBufferSize - 1U))); + + if (hnor->CommandSet == NOR_AMD_FUJITSU_COMMAND_SET) + { + /* Issue unlock command sequence */ + NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_FIRST), NOR_CMD_DATA_FIRST); + NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_SECOND), NOR_CMD_DATA_SECOND); + + /* Write Buffer Load Command */ + NOR_WRITE((deviceaddress + uwAddress), NOR_CMD_DATA_BUFFER_AND_PROG); + NOR_WRITE((deviceaddress + uwAddress), (uint16_t)(uwBufferSize - 1U)); + } + else if (hnor->CommandSet == NOR_INTEL_SHARP_EXT_COMMAND_SET) + { + /* Write Buffer Load Command */ + NOR_WRITE((deviceaddress + uwAddress), NOR_CMD_BUFFERED_PROGRAM); + NOR_WRITE((deviceaddress + uwAddress), (uint16_t)(uwBufferSize - 1U)); + } + else + { + /* Primary command set not supported by the driver */ + status = DAL_ERROR; + } + + if (status != DAL_ERROR) + { + /* Load Data into NOR Buffer */ + while (p_currentaddress <= p_endaddress) + { + NOR_WRITE(p_currentaddress, *data); + + data++; + p_currentaddress ++; + } + + if (hnor->CommandSet == NOR_AMD_FUJITSU_COMMAND_SET) + { + NOR_WRITE((deviceaddress + uwAddress), NOR_CMD_DATA_BUFFER_AND_PROG_CONFIRM); + } + else /* => hnor->CommandSet == NOR_INTEL_SHARP_EXT_COMMAND_SET */ + { + NOR_WRITE((deviceaddress + uwAddress), NOR_CMD_CONFIRM); + } + } + + /* Check the NOR controller state */ + hnor->State = DAL_NOR_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hnor); + } + else + { + return DAL_ERROR; + } + + return status; + +} + +/** + * @brief Erase the specified block of the NOR memory + * @param hnor pointer to a NOR_HandleTypeDef structure that contains + * the configuration information for NOR module. + * @param BlockAddress Block to erase address + * @param Address Device address + * @retval DAL status + */ +DAL_StatusTypeDef DAL_NOR_Erase_Block(NOR_HandleTypeDef *hnor, uint32_t BlockAddress, uint32_t Address) +{ + uint32_t deviceaddress; + DAL_StatusTypeDef status = DAL_OK; + + /* Check the NOR controller state */ + if (hnor->State == DAL_NOR_STATE_BUSY) + { + return DAL_BUSY; + } + else if (hnor->State == DAL_NOR_STATE_READY) + { + /* Process Locked */ + __DAL_LOCK(hnor); + + /* Update the NOR controller state */ + hnor->State = DAL_NOR_STATE_BUSY; + + /* Select the NOR device address */ + if (hnor->Init.NSBank == FMC_NORSRAM_BANK1) + { + deviceaddress = NOR_MEMORY_ADRESS1; + } + else if (hnor->Init.NSBank == FMC_NORSRAM_BANK2) + { + deviceaddress = NOR_MEMORY_ADRESS2; + } + else if (hnor->Init.NSBank == FMC_NORSRAM_BANK3) + { + deviceaddress = NOR_MEMORY_ADRESS3; + } + else /* FMC_NORSRAM_BANK4 */ + { + deviceaddress = NOR_MEMORY_ADRESS4; + } + + /* Send block erase command sequence */ + if (hnor->CommandSet == NOR_AMD_FUJITSU_COMMAND_SET) + { + NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_FIRST), NOR_CMD_DATA_FIRST); + NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_SECOND), NOR_CMD_DATA_SECOND); + NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_THIRD), + NOR_CMD_DATA_CHIP_BLOCK_ERASE_THIRD); + NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_FOURTH), + NOR_CMD_DATA_CHIP_BLOCK_ERASE_FOURTH); + NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_FIFTH), + NOR_CMD_DATA_CHIP_BLOCK_ERASE_FIFTH); + NOR_WRITE((uint32_t)(BlockAddress + Address), NOR_CMD_DATA_BLOCK_ERASE); + } + else if (hnor->CommandSet == NOR_INTEL_SHARP_EXT_COMMAND_SET) + { + NOR_WRITE((BlockAddress + Address), NOR_CMD_BLOCK_UNLOCK); + NOR_WRITE((BlockAddress + Address), NOR_CMD_CONFIRM); + NOR_WRITE((BlockAddress + Address), NOR_CMD_BLOCK_ERASE); + NOR_WRITE((BlockAddress + Address), NOR_CMD_CONFIRM); + } + else + { + /* Primary command set not supported by the driver */ + status = DAL_ERROR; + } + + /* Check the NOR memory status and update the controller state */ + hnor->State = DAL_NOR_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hnor); + } + else + { + return DAL_ERROR; + } + + return status; + +} + +/** + * @brief Erase the entire NOR chip. + * @param hnor pointer to a NOR_HandleTypeDef structure that contains + * the configuration information for NOR module. + * @param Address Device address + * @retval DAL status + */ +DAL_StatusTypeDef DAL_NOR_Erase_Chip(NOR_HandleTypeDef *hnor, uint32_t Address) +{ + uint32_t deviceaddress; + DAL_StatusTypeDef status = DAL_OK; + UNUSED(Address); + + /* Check the NOR controller state */ + if (hnor->State == DAL_NOR_STATE_BUSY) + { + return DAL_BUSY; + } + else if (hnor->State == DAL_NOR_STATE_READY) + { + /* Process Locked */ + __DAL_LOCK(hnor); + + /* Update the NOR controller state */ + hnor->State = DAL_NOR_STATE_BUSY; + + /* Select the NOR device address */ + if (hnor->Init.NSBank == FMC_NORSRAM_BANK1) + { + deviceaddress = NOR_MEMORY_ADRESS1; + } + else if (hnor->Init.NSBank == FMC_NORSRAM_BANK2) + { + deviceaddress = NOR_MEMORY_ADRESS2; + } + else if (hnor->Init.NSBank == FMC_NORSRAM_BANK3) + { + deviceaddress = NOR_MEMORY_ADRESS3; + } + else /* FMC_NORSRAM_BANK4 */ + { + deviceaddress = NOR_MEMORY_ADRESS4; + } + + /* Send NOR chip erase command sequence */ + if (hnor->CommandSet == NOR_AMD_FUJITSU_COMMAND_SET) + { + NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_FIRST), NOR_CMD_DATA_FIRST); + NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_SECOND), NOR_CMD_DATA_SECOND); + NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_THIRD), + NOR_CMD_DATA_CHIP_BLOCK_ERASE_THIRD); + NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_FOURTH), + NOR_CMD_DATA_CHIP_BLOCK_ERASE_FOURTH); + NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_FIFTH), + NOR_CMD_DATA_CHIP_BLOCK_ERASE_FIFTH); + NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_SIXTH), NOR_CMD_DATA_CHIP_ERASE); + } + else + { + /* Primary command set not supported by the driver */ + status = DAL_ERROR; + } + + /* Check the NOR memory status and update the controller state */ + hnor->State = DAL_NOR_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hnor); + } + else + { + return DAL_ERROR; + } + + return status; +} + +/** + * @brief Read NOR flash CFI IDs + * @param hnor pointer to a NOR_HandleTypeDef structure that contains + * the configuration information for NOR module. + * @param pNOR_CFI pointer to NOR CFI IDs structure + * @retval DAL status + */ +DAL_StatusTypeDef DAL_NOR_Read_CFI(NOR_HandleTypeDef *hnor, NOR_CFITypeDef *pNOR_CFI) +{ + uint32_t deviceaddress; + DAL_NOR_StateTypeDef state; + + /* Check the NOR controller state */ + state = hnor->State; + if (state == DAL_NOR_STATE_BUSY) + { + return DAL_BUSY; + } + else if (state == DAL_NOR_STATE_PROTECTED) + { + return DAL_ERROR; + } + else if (state == DAL_NOR_STATE_READY) + { + /* Process Locked */ + __DAL_LOCK(hnor); + + /* Update the NOR controller state */ + hnor->State = DAL_NOR_STATE_BUSY; + + /* Select the NOR device address */ + if (hnor->Init.NSBank == FMC_NORSRAM_BANK1) + { + deviceaddress = NOR_MEMORY_ADRESS1; + } + else if (hnor->Init.NSBank == FMC_NORSRAM_BANK2) + { + deviceaddress = NOR_MEMORY_ADRESS2; + } + else if (hnor->Init.NSBank == FMC_NORSRAM_BANK3) + { + deviceaddress = NOR_MEMORY_ADRESS3; + } + else /* FMC_NORSRAM_BANK4 */ + { + deviceaddress = NOR_MEMORY_ADRESS4; + } + + /* Send read CFI query command */ + NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_FIRST_CFI), NOR_CMD_DATA_CFI); + + /* read the NOR CFI information */ + pNOR_CFI->CFI_1 = *(__IO uint16_t *) NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, CFI1_ADDRESS); + pNOR_CFI->CFI_2 = *(__IO uint16_t *) NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, CFI2_ADDRESS); + pNOR_CFI->CFI_3 = *(__IO uint16_t *) NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, CFI3_ADDRESS); + pNOR_CFI->CFI_4 = *(__IO uint16_t *) NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, CFI4_ADDRESS); + + /* Check the NOR controller state */ + hnor->State = state; + + /* Process unlocked */ + __DAL_UNLOCK(hnor); + } + else + { + return DAL_ERROR; + } + + return DAL_OK; +} + +#if (USE_DAL_NOR_REGISTER_CALLBACKS == 1) +/** + * @brief Register a User NOR Callback + * To be used instead of the weak (surcharged) predefined callback + * @param hnor : NOR handle + * @param CallbackId : ID of the callback to be registered + * This parameter can be one of the following values: + * @arg @ref DAL_NOR_MSP_INIT_CB_ID NOR MspInit callback ID + * @arg @ref DAL_NOR_MSP_DEINIT_CB_ID NOR MspDeInit callback ID + * @param pCallback : pointer to the Callback function + * @retval status + */ +DAL_StatusTypeDef DAL_NOR_RegisterCallback(NOR_HandleTypeDef *hnor, DAL_NOR_CallbackIDTypeDef CallbackId, + pNOR_CallbackTypeDef pCallback) +{ + DAL_StatusTypeDef status = DAL_OK; + DAL_NOR_StateTypeDef state; + + if (pCallback == NULL) + { + return DAL_ERROR; + } + + /* Process locked */ + __DAL_LOCK(hnor); + + state = hnor->State; + if ((state == DAL_NOR_STATE_READY) || (state == DAL_NOR_STATE_RESET) || (state == DAL_NOR_STATE_PROTECTED)) + { + switch (CallbackId) + { + case DAL_NOR_MSP_INIT_CB_ID : + hnor->MspInitCallback = pCallback; + break; + case DAL_NOR_MSP_DEINIT_CB_ID : + hnor->MspDeInitCallback = pCallback; + break; + default : + /* update return status */ + status = DAL_ERROR; + break; + } + } + else + { + /* update return status */ + status = DAL_ERROR; + } + + /* Release Lock */ + __DAL_UNLOCK(hnor); + return status; +} + +/** + * @brief Unregister a User NOR Callback + * NOR Callback is redirected to the weak (surcharged) predefined callback + * @param hnor : NOR handle + * @param CallbackId : ID of the callback to be unregistered + * This parameter can be one of the following values: + * @arg @ref DAL_NOR_MSP_INIT_CB_ID NOR MspInit callback ID + * @arg @ref DAL_NOR_MSP_DEINIT_CB_ID NOR MspDeInit callback ID + * @retval status + */ +DAL_StatusTypeDef DAL_NOR_UnRegisterCallback(NOR_HandleTypeDef *hnor, DAL_NOR_CallbackIDTypeDef CallbackId) +{ + DAL_StatusTypeDef status = DAL_OK; + DAL_NOR_StateTypeDef state; + + /* Process locked */ + __DAL_LOCK(hnor); + + state = hnor->State; + if ((state == DAL_NOR_STATE_READY) || (state == DAL_NOR_STATE_RESET) || (state == DAL_NOR_STATE_PROTECTED)) + { + switch (CallbackId) + { + case DAL_NOR_MSP_INIT_CB_ID : + hnor->MspInitCallback = DAL_NOR_MspInit; + break; + case DAL_NOR_MSP_DEINIT_CB_ID : + hnor->MspDeInitCallback = DAL_NOR_MspDeInit; + break; + default : + /* update return status */ + status = DAL_ERROR; + break; + } + } + else + { + /* update return status */ + status = DAL_ERROR; + } + + /* Release Lock */ + __DAL_UNLOCK(hnor); + return status; +} +#endif /* (USE_DAL_NOR_REGISTER_CALLBACKS) */ + +/** + * @} + */ + +/** @defgroup NOR_Exported_Functions_Group3 NOR Control functions + * @brief management functions + * +@verbatim + ============================================================================== + ##### NOR Control functions ##### + ============================================================================== + [..] + This subsection provides a set of functions allowing to control dynamically + the NOR interface. + +@endverbatim + * @{ + */ + +/** + * @brief Enables dynamically NOR write operation. + * @param hnor pointer to a NOR_HandleTypeDef structure that contains + * the configuration information for NOR module. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_NOR_WriteOperation_Enable(NOR_HandleTypeDef *hnor) +{ + /* Check the NOR controller state */ + if (hnor->State == DAL_NOR_STATE_PROTECTED) + { + /* Process Locked */ + __DAL_LOCK(hnor); + + /* Update the NOR controller state */ + hnor->State = DAL_NOR_STATE_BUSY; + + /* Enable write operation */ + (void)FMC_NORSRAM_WriteOperation_Enable(hnor->Instance, hnor->Init.NSBank); + + /* Update the NOR controller state */ + hnor->State = DAL_NOR_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hnor); + } + else + { + return DAL_ERROR; + } + + return DAL_OK; +} + +/** + * @brief Disables dynamically NOR write operation. + * @param hnor pointer to a NOR_HandleTypeDef structure that contains + * the configuration information for NOR module. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_NOR_WriteOperation_Disable(NOR_HandleTypeDef *hnor) +{ + /* Check the NOR controller state */ + if (hnor->State == DAL_NOR_STATE_READY) + { + /* Process Locked */ + __DAL_LOCK(hnor); + + /* Update the NOR controller state */ + hnor->State = DAL_NOR_STATE_BUSY; + + /* Disable write operation */ + (void)FMC_NORSRAM_WriteOperation_Disable(hnor->Instance, hnor->Init.NSBank); + + /* Update the NOR controller state */ + hnor->State = DAL_NOR_STATE_PROTECTED; + + /* Process unlocked */ + __DAL_UNLOCK(hnor); + } + else + { + return DAL_ERROR; + } + + return DAL_OK; +} + +/** + * @} + */ + +/** @defgroup NOR_Exported_Functions_Group4 NOR State functions + * @brief Peripheral State functions + * +@verbatim + ============================================================================== + ##### NOR State functions ##### + ============================================================================== + [..] + This subsection permits to get in run-time the status of the NOR controller + and the data flow. + +@endverbatim + * @{ + */ + +/** + * @brief return the NOR controller state + * @param hnor pointer to a NOR_HandleTypeDef structure that contains + * the configuration information for NOR module. + * @retval NOR controller state + */ +DAL_NOR_StateTypeDef DAL_NOR_GetState(NOR_HandleTypeDef *hnor) +{ + return hnor->State; +} + +/** + * @brief Returns the NOR operation status. + * @param hnor pointer to a NOR_HandleTypeDef structure that contains + * the configuration information for NOR module. + * @param Address Device address + * @param Timeout NOR programming Timeout + * @retval NOR_Status The returned value can be: DAL_NOR_STATUS_SUCCESS, DAL_NOR_STATUS_ERROR + * or DAL_NOR_STATUS_TIMEOUT + */ +DAL_NOR_StatusTypeDef DAL_NOR_GetStatus(NOR_HandleTypeDef *hnor, uint32_t Address, uint32_t Timeout) +{ + DAL_NOR_StatusTypeDef status = DAL_NOR_STATUS_ONGOING; + uint16_t tmpsr1; + uint16_t tmpsr2; + uint32_t tickstart; + + /* Poll on NOR memory Ready/Busy signal ------------------------------------*/ + DAL_NOR_MspWait(hnor, Timeout); + + /* Get the NOR memory operation status -------------------------------------*/ + + /* Get tick */ + tickstart = DAL_GetTick(); + + if (hnor->CommandSet == NOR_AMD_FUJITSU_COMMAND_SET) + { + while ((status != DAL_NOR_STATUS_SUCCESS) && (status != DAL_NOR_STATUS_TIMEOUT)) + { + /* Check for the Timeout */ + if (Timeout != DAL_MAX_DELAY) + { + if (((DAL_GetTick() - tickstart) > Timeout) || (Timeout == 0U)) + { + status = DAL_NOR_STATUS_TIMEOUT; + } + } + + /* Read NOR status register (DQ6 and DQ5) */ + tmpsr1 = *(__IO uint16_t *)Address; + tmpsr2 = *(__IO uint16_t *)Address; + + /* If DQ6 did not toggle between the two reads then return DAL_NOR_STATUS_SUCCESS */ + if ((tmpsr1 & NOR_MASK_STATUS_DQ6) == (tmpsr2 & NOR_MASK_STATUS_DQ6)) + { + return DAL_NOR_STATUS_SUCCESS ; + } + + if ((tmpsr1 & NOR_MASK_STATUS_DQ5) == NOR_MASK_STATUS_DQ5) + { + status = DAL_NOR_STATUS_ONGOING; + } + + tmpsr1 = *(__IO uint16_t *)Address; + tmpsr2 = *(__IO uint16_t *)Address; + + /* If DQ6 did not toggle between the two reads then return DAL_NOR_STATUS_SUCCESS */ + if ((tmpsr1 & NOR_MASK_STATUS_DQ6) == (tmpsr2 & NOR_MASK_STATUS_DQ6)) + { + return DAL_NOR_STATUS_SUCCESS; + } + if ((tmpsr1 & NOR_MASK_STATUS_DQ5) == NOR_MASK_STATUS_DQ5) + { + return DAL_NOR_STATUS_ERROR; + } + } + } + else if (hnor->CommandSet == NOR_INTEL_SHARP_EXT_COMMAND_SET) + { + do + { + NOR_WRITE(Address, NOR_CMD_READ_STATUS_REG); + tmpsr2 = *(__IO uint16_t *)(Address); + + /* Check for the Timeout */ + if (Timeout != DAL_MAX_DELAY) + { + if (((DAL_GetTick() - tickstart) > Timeout) || (Timeout == 0U)) + { + return DAL_NOR_STATUS_TIMEOUT; + } + } + } while ((tmpsr2 & NOR_MASK_STATUS_DQ7) == 0U); + + NOR_WRITE(Address, NOR_CMD_READ_STATUS_REG); + tmpsr1 = *(__IO uint16_t *)(Address); + if ((tmpsr1 & (NOR_MASK_STATUS_DQ5 | NOR_MASK_STATUS_DQ4)) != 0U) + { + /* Clear the Status Register */ + NOR_WRITE(Address, NOR_CMD_READ_STATUS_REG); + status = DAL_NOR_STATUS_ERROR; + } + else + { + status = DAL_NOR_STATUS_SUCCESS; + } + } + else + { + /* Primary command set not supported by the driver */ + status = DAL_NOR_STATUS_ERROR; + } + + /* Return the operation status */ + return status; +} + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#endif /* DAL_NOR_MODULE_ENABLED */ + +/** + * @} + */ + +#endif /* SMC_Bank1 */ diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_pccard.c b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_pccard.c new file mode 100644 index 0000000000..5acf9ad923 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_pccard.c @@ -0,0 +1,971 @@ +/** + * + * @file apm32f4xx_dal_pccard.c + * @brief PCCARD DAL module driver. + * This file provides a generic firmware to drive PCCARD memories mounted + * as external device. + * + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + * + @verbatim + =============================================================================== + ##### How to use this driver ##### + =============================================================================== + [..] + This driver is a generic layered driver which contains a set of APIs used to + control PCCARD/compact flash memories. It uses the SMC/EMMC layer functions + to interface with PCCARD devices. This driver is used for: + + (+) PCCARD/Compact Flash memory configuration sequence using the function + DAL_PCCARD_Init()/DAL_CF_Init() with control and timing parameters for + both common and attribute spaces. + + (+) Read PCCARD/Compact Flash memory maker and device IDs using the function + DAL_PCCARD_Read_ID()/DAL_CF_Read_ID(). The read information is stored in + the CompactFlash_ID structure declared by the function caller. + + (+) Access PCCARD/Compact Flash memory by read/write operations using the functions + DAL_PCCARD_Read_Sector()/ DAL_PCCARD_Write_Sector() - + DAL_CF_Read_Sector()/DAL_CF_Write_Sector(), to read/write sector. + + (+) Perform PCCARD/Compact Flash Reset chip operation using the function + DAL_PCCARD_Reset()/DAL_CF_Reset. + + (+) Perform PCCARD/Compact Flash erase sector operation using the function + DAL_PCCARD_Erase_Sector()/DAL_CF_Erase_Sector. + + (+) Read the PCCARD/Compact Flash status operation using the function + DAL_PCCARD_ReadStatus()/DAL_CF_ReadStatus(). + + (+) You can monitor the PCCARD/Compact Flash device DAL state by calling + the function DAL_PCCARD_GetState()/DAL_CF_GetState() + + [..] + (@) This driver is a set of generic APIs which handle standard PCCARD/compact flash + operations. If a PCCARD/Compact Flash device contains different operations + and/or implementations, it should be implemented separately. + + *** Callback registration *** + ============================================= + [..] + The compilation define USE_DAL_PCCARD_REGISTER_CALLBACKS when set to 1 + allows the user to configure dynamically the driver callbacks. + + Use Functions DAL_PCCARD_RegisterCallback() to register a user callback, + it allows to register following callbacks: + (+) MspInitCallback : PCCARD MspInit. + (+) MspDeInitCallback : PCCARD MspDeInit. + This function takes as parameters the DAL peripheral handle, the Callback ID + and a pointer to the user callback function. + + Use function DAL_PCCARD_UnRegisterCallback() to reset a callback to the default + weak (surcharged) function. It allows to reset following callbacks: + (+) MspInitCallback : PCCARD MspInit. + (+) MspDeInitCallback : PCCARD MspDeInit. + This function) takes as parameters the DAL peripheral handle and the Callback ID. + + By default, after the DAL_PCCARD_Init and if the state is DAL_PCCARD_STATE_RESET + all callbacks are reset to the corresponding legacy weak (surcharged) functions. + Exception done for MspInit and MspDeInit callbacks that are respectively + reset to the legacy weak (surcharged) functions in the DAL_PCCARD_Init + and DAL_PCCARD_DeInit only when these callbacks are null (not registered beforehand). + If not, MspInit or MspDeInit are not null, the DAL_PCCARD_Init and DAL_PCCARD_DeInit + keep and use the user MspInit/MspDeInit callbacks (registered beforehand) + + Callbacks can be registered/unregistered in READY state only. + Exception done for MspInit/MspDeInit callbacks that can be registered/unregistered + in READY or RESET state, thus registered (user) MspInit/DeInit callbacks can be used + during the Init/DeInit. + In that case first register the MspInit/MspDeInit user callbacks + using DAL_PCCARD_RegisterCallback before calling DAL_PCCARD_DeInit + or DAL_PCCARD_Init function. + + When The compilation define USE_DAL_PCCARD_REGISTER_CALLBACKS is set to 0 or + not defined, the callback registering feature is not available + and weak (surcharged) callbacks are used. + + @endverbatim + * + */ + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal.h" + +#if defined(SMC_Bank4) + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +#ifdef DAL_PCCARD_MODULE_ENABLED + +/** @defgroup PCCARD PCCARD + * @brief PCCARD DAL module driver + * @{ + */ +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ + +/** @defgroup PCCARD_Private_Defines PCCARD Private Defines + * @{ + */ +#define PCCARD_TIMEOUT_READ_ID 0x0000FFFFU +#define PCCARD_TIMEOUT_READ_WRITE_SECTOR 0x0000FFFFU +#define PCCARD_TIMEOUT_ERASE_SECTOR 0x00000400U +#define PCCARD_TIMEOUT_STATUS 0x01000000U + +#define PCCARD_STATUS_OK (uint8_t)0x58 +#define PCCARD_STATUS_WRITE_OK (uint8_t)0x50 +/** + * @} + */ + +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function ----------------------------------------------------------*/ +/* Exported functions --------------------------------------------------------*/ +/** @defgroup PCCARD_Exported_Functions PCCARD Exported Functions + * @{ + */ + +/** @defgroup PCCARD_Exported_Functions_Group1 Initialization and de-initialization functions + * @brief Initialization and Configuration functions + * + @verbatim + ============================================================================== + ##### PCCARD Initialization and de-initialization functions ##### + ============================================================================== + [..] + This section provides functions allowing to initialize/de-initialize + the PCCARD memory + +@endverbatim + * @{ + */ + +/** + * @brief Perform the PCCARD memory Initialization sequence + * @param hpccard pointer to a PCCARD_HandleTypeDef structure that contains + * the configuration information for PCCARD module. + * @param ComSpaceTiming Common space timing structure + * @param AttSpaceTiming Attribute space timing structure + * @param IOSpaceTiming IO space timing structure + * @retval DAL status + */ +DAL_StatusTypeDef DAL_PCCARD_Init(PCCARD_HandleTypeDef *hpccard, FMC_NAND_PCC_TimingTypeDef *ComSpaceTiming, + FMC_NAND_PCC_TimingTypeDef *AttSpaceTiming, FMC_NAND_PCC_TimingTypeDef *IOSpaceTiming) +{ + /* Check the PCCARD controller state */ + if (hpccard == NULL) + { + return DAL_ERROR; + } + + if (hpccard->State == DAL_PCCARD_STATE_RESET) + { + /* Allocate lock resource and initialize it */ + hpccard->Lock = DAL_UNLOCKED; +#if (USE_DAL_PCCARD_REGISTER_CALLBACKS == 1) + if (hpccard->MspInitCallback == NULL) + { + hpccard->MspInitCallback = DAL_PCCARD_MspInit; + } + hpccard->ItCallback = DAL_PCCARD_ITCallback; + + /* Init the low level hardware */ + hpccard->MspInitCallback(hpccard); +#else + /* Initialize the low level hardware (MSP) */ + DAL_PCCARD_MspInit(hpccard); +#endif + } + + /* Initialize the PCCARD state */ + hpccard->State = DAL_PCCARD_STATE_BUSY; + + /* Initialize PCCARD control Interface */ + FMC_PCCARD_Init(hpccard->Instance, &(hpccard->Init)); + + /* Init PCCARD common space timing Interface */ + FMC_PCCARD_CommonSpace_Timing_Init(hpccard->Instance, ComSpaceTiming); + + /* Init PCCARD attribute space timing Interface */ + FMC_PCCARD_AttributeSpace_Timing_Init(hpccard->Instance, AttSpaceTiming); + + /* Init PCCARD IO space timing Interface */ + FMC_PCCARD_IOSpace_Timing_Init(hpccard->Instance, IOSpaceTiming); + + /* Enable the PCCARD device */ + __FMC_PCCARD_ENABLE(hpccard->Instance); + + /* Update the PCCARD state */ + hpccard->State = DAL_PCCARD_STATE_READY; + + return DAL_OK; + +} + +/** + * @brief Perform the PCCARD memory De-initialization sequence + * @param hpccard pointer to a PCCARD_HandleTypeDef structure that contains + * the configuration information for PCCARD module. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_PCCARD_DeInit(PCCARD_HandleTypeDef *hpccard) +{ +#if (USE_DAL_PCCARD_REGISTER_CALLBACKS == 1) + if (hpccard->MspDeInitCallback == NULL) + { + hpccard->MspDeInitCallback = DAL_PCCARD_MspDeInit; + } + + /* DeInit the low level hardware */ + hpccard->MspDeInitCallback(hpccard); +#else + /* De-Initialize the low level hardware (MSP) */ + DAL_PCCARD_MspDeInit(hpccard); +#endif + + /* Configure the PCCARD registers with their reset values */ + FMC_PCCARD_DeInit(hpccard->Instance); + + /* Update the PCCARD controller state */ + hpccard->State = DAL_PCCARD_STATE_RESET; + + /* Release Lock */ + __DAL_UNLOCK(hpccard); + + return DAL_OK; +} + +/** + * @brief PCCARD MSP Init + * @param hpccard pointer to a PCCARD_HandleTypeDef structure that contains + * the configuration information for PCCARD module. + * @retval None + */ +__weak void DAL_PCCARD_MspInit(PCCARD_HandleTypeDef *hpccard) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hpccard); + /* NOTE : This function Should not be modified, when the callback is needed, + the DAL_PCCARD_MspInit could be implemented in the user file + */ +} + +/** + * @brief PCCARD MSP DeInit + * @param hpccard pointer to a PCCARD_HandleTypeDef structure that contains + * the configuration information for PCCARD module. + * @retval None + */ +__weak void DAL_PCCARD_MspDeInit(PCCARD_HandleTypeDef *hpccard) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hpccard); + /* NOTE : This function Should not be modified, when the callback is needed, + the DAL_PCCARD_MspDeInit could be implemented in the user file + */ +} + +/** + * @} + */ + +/** @defgroup PCCARD_Exported_Functions_Group2 Input and Output functions + * @brief Input Output and memory control functions + * + @verbatim + ============================================================================== + ##### PCCARD Input and Output functions ##### + ============================================================================== + [..] + This section provides functions allowing to use and control the PCCARD memory + +@endverbatim + * @{ + */ + +/** + * @brief Read Compact Flash's ID. + * @param hpccard pointer to a PCCARD_HandleTypeDef structure that contains + * the configuration information for PCCARD module. + * @param CompactFlash_ID Compact flash ID structure. + * @param pStatus pointer to compact flash status + * @retval DAL status + * + */ +DAL_StatusTypeDef DAL_PCCARD_Read_ID(PCCARD_HandleTypeDef *hpccard, uint8_t CompactFlash_ID[], uint8_t *pStatus) +{ + uint32_t timeout = PCCARD_TIMEOUT_READ_ID, index = 0U; + uint8_t status = 0; + + /* Process Locked */ + __DAL_LOCK(hpccard); + + /* Check the PCCARD controller state */ + if (hpccard->State == DAL_PCCARD_STATE_BUSY) + { + return DAL_BUSY; + } + + /* Update the PCCARD controller state */ + hpccard->State = DAL_PCCARD_STATE_BUSY; + + /* Initialize the PCCARD status */ + *pStatus = PCCARD_READY; + + /* Send the Identify Command */ + *(__IO uint16_t *)(PCCARD_IO_SPACE_PRIMARY_ADDR | ATA_STATUS_CMD) = (uint16_t)0xECEC; + + /* Read PCCARD IDs and timeout treatment */ + do + { + /* Read the PCCARD status */ + status = *(__IO uint8_t *)(PCCARD_IO_SPACE_PRIMARY_ADDR | ATA_STATUS_CMD_ALTERNATE); + + timeout--; + } while ((status != PCCARD_STATUS_OK) && timeout); + + if (timeout == 0U) + { + *pStatus = PCCARD_TIMEOUT_ERROR; + } + else + { + /* Read PCCARD ID bytes */ + for (index = 0U; index < 16U; index++) + { + CompactFlash_ID[index] = *(__IO uint8_t *)(PCCARD_IO_SPACE_PRIMARY_ADDR | ATA_DATA); + } + } + + /* Update the PCCARD controller state */ + hpccard->State = DAL_PCCARD_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hpccard); + + return DAL_OK; +} + +/** + * @brief Read sector from PCCARD memory + * @param hpccard pointer to a PCCARD_HandleTypeDef structure that contains + * the configuration information for PCCARD module. + * @param pBuffer pointer to destination read buffer + * @param SectorAddress Sector address to read + * @param pStatus pointer to PCCARD status + * @retval DAL status + */ +DAL_StatusTypeDef DAL_PCCARD_Read_Sector(PCCARD_HandleTypeDef *hpccard, uint16_t *pBuffer, uint16_t SectorAddress, + uint8_t *pStatus) +{ + uint32_t timeout = PCCARD_TIMEOUT_READ_WRITE_SECTOR, index = 0U; + uint8_t status = 0; + + /* Process Locked */ + __DAL_LOCK(hpccard); + + /* Check the PCCARD controller state */ + if (hpccard->State == DAL_PCCARD_STATE_BUSY) + { + return DAL_BUSY; + } + + /* Update the PCCARD controller state */ + hpccard->State = DAL_PCCARD_STATE_BUSY; + + /* Initialize PCCARD status */ + *pStatus = PCCARD_READY; + + /* Set the parameters to write a sector */ + *(__IO uint16_t *)(PCCARD_IO_SPACE_PRIMARY_ADDR | ATA_CYLINDER_HIGH) = (uint16_t)0x0000; + *(__IO uint16_t *)(PCCARD_IO_SPACE_PRIMARY_ADDR | ATA_SECTOR_COUNT) = ((uint16_t)0x0100) | ((uint16_t)SectorAddress); + *(__IO uint16_t *)(PCCARD_IO_SPACE_PRIMARY_ADDR | ATA_STATUS_CMD) = (uint16_t)0xE4A0; + + do + { + /* wait till the Status = 0x80 */ + status = *(__IO uint16_t *)(PCCARD_IO_SPACE_PRIMARY_ADDR | ATA_STATUS_CMD_ALTERNATE); + timeout--; + } while ((status == 0x80U) && timeout); + + if (timeout == 0U) + { + *pStatus = PCCARD_TIMEOUT_ERROR; + } + + timeout = PCCARD_TIMEOUT_READ_WRITE_SECTOR; + + do + { + /* wait till the Status = PCCARD_STATUS_OK */ + status = *(__IO uint16_t *)(PCCARD_IO_SPACE_PRIMARY_ADDR | ATA_STATUS_CMD_ALTERNATE); + timeout--; + } while ((status != PCCARD_STATUS_OK) && timeout); + + if (timeout == 0U) + { + *pStatus = PCCARD_TIMEOUT_ERROR; + } + + /* Read bytes */ + for (; index < PCCARD_SECTOR_SIZE; index++) + { + *(uint16_t *)pBuffer++ = *(uint16_t *)(PCCARD_IO_SPACE_PRIMARY_ADDR); + } + + /* Update the PCCARD controller state */ + hpccard->State = DAL_PCCARD_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hpccard); + + return DAL_OK; +} + + +/** + * @brief Write sector to PCCARD memory + * @param hpccard pointer to a PCCARD_HandleTypeDef structure that contains + * the configuration information for PCCARD module. + * @param pBuffer pointer to source write buffer + * @param SectorAddress Sector address to write + * @param pStatus pointer to PCCARD status + * @retval DAL status + */ +DAL_StatusTypeDef DAL_PCCARD_Write_Sector(PCCARD_HandleTypeDef *hpccard, uint16_t *pBuffer, uint16_t SectorAddress, + uint8_t *pStatus) +{ + uint32_t timeout = PCCARD_TIMEOUT_READ_WRITE_SECTOR, index = 0U; + uint8_t status = 0; + + /* Process Locked */ + __DAL_LOCK(hpccard); + + /* Check the PCCARD controller state */ + if (hpccard->State == DAL_PCCARD_STATE_BUSY) + { + return DAL_BUSY; + } + + /* Update the PCCARD controller state */ + hpccard->State = DAL_PCCARD_STATE_BUSY; + + /* Initialize PCCARD status */ + *pStatus = PCCARD_READY; + + /* Set the parameters to write a sector */ + *(__IO uint16_t *)(PCCARD_IO_SPACE_PRIMARY_ADDR | ATA_CYLINDER_HIGH) = (uint16_t)0x0000; + *(__IO uint16_t *)(PCCARD_IO_SPACE_PRIMARY_ADDR | ATA_SECTOR_COUNT) = ((uint16_t)0x0100) | ((uint16_t)SectorAddress); + *(__IO uint16_t *)(PCCARD_IO_SPACE_PRIMARY_ADDR | ATA_STATUS_CMD) = (uint16_t)0x30A0; + + do + { + /* Wait till the Status = PCCARD_STATUS_OK */ + status = *(__IO uint8_t *)(PCCARD_IO_SPACE_PRIMARY_ADDR | ATA_STATUS_CMD_ALTERNATE); + timeout--; + } while ((status != PCCARD_STATUS_OK) && timeout); + + if (timeout == 0U) + { + *pStatus = PCCARD_TIMEOUT_ERROR; + } + + /* Write bytes */ + for (; index < PCCARD_SECTOR_SIZE; index++) + { + *(uint16_t *)(PCCARD_IO_SPACE_PRIMARY_ADDR) = *(uint16_t *)pBuffer++; + } + + do + { + /* Wait till the Status = PCCARD_STATUS_WRITE_OK */ + status = *(__IO uint8_t *)(PCCARD_IO_SPACE_PRIMARY_ADDR | ATA_STATUS_CMD_ALTERNATE); + timeout--; + } while ((status != PCCARD_STATUS_WRITE_OK) && timeout); + + if (timeout == 0U) + { + *pStatus = PCCARD_TIMEOUT_ERROR; + } + + /* Update the PCCARD controller state */ + hpccard->State = DAL_PCCARD_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hpccard); + + return DAL_OK; +} + + +/** + * @brief Erase sector from PCCARD memory + * @param hpccard pointer to a PCCARD_HandleTypeDef structure that contains + * the configuration information for PCCARD module. + * @param SectorAddress Sector address to erase + * @param pStatus pointer to PCCARD status + * @retval DAL status + */ +DAL_StatusTypeDef DAL_PCCARD_Erase_Sector(PCCARD_HandleTypeDef *hpccard, uint16_t SectorAddress, uint8_t *pStatus) +{ + uint32_t timeout = PCCARD_TIMEOUT_ERASE_SECTOR; + uint8_t status = 0; + + /* Process Locked */ + __DAL_LOCK(hpccard); + + /* Check the PCCARD controller state */ + if (hpccard->State == DAL_PCCARD_STATE_BUSY) + { + return DAL_BUSY; + } + + /* Update the PCCARD controller state */ + hpccard->State = DAL_PCCARD_STATE_BUSY; + + /* Initialize PCCARD status */ + *pStatus = PCCARD_READY; + + /* Set the parameters to write a sector */ + *(__IO uint8_t *)(PCCARD_IO_SPACE_PRIMARY_ADDR | ATA_CYLINDER_LOW) = 0x00; + *(__IO uint8_t *)(PCCARD_IO_SPACE_PRIMARY_ADDR | ATA_CYLINDER_HIGH) = 0x00; + *(__IO uint8_t *)(PCCARD_IO_SPACE_PRIMARY_ADDR | ATA_SECTOR_NUMBER) = SectorAddress; + *(__IO uint8_t *)(PCCARD_IO_SPACE_PRIMARY_ADDR | ATA_SECTOR_COUNT) = 0x01; + *(__IO uint8_t *)(PCCARD_IO_SPACE_PRIMARY_ADDR | ATA_CARD_HEAD) = 0xA0; + *(__IO uint8_t *)(PCCARD_IO_SPACE_PRIMARY_ADDR | ATA_STATUS_CMD) = ATA_ERASE_SECTOR_CMD; + + /* wait till the PCCARD is ready */ + status = *(__IO uint8_t *)(PCCARD_IO_SPACE_PRIMARY_ADDR | ATA_STATUS_CMD_ALTERNATE); + + while ((status != PCCARD_STATUS_WRITE_OK) && timeout) + { + status = *(__IO uint8_t *)(PCCARD_IO_SPACE_PRIMARY_ADDR | ATA_STATUS_CMD_ALTERNATE); + timeout--; + } + + if (timeout == 0U) + { + *pStatus = PCCARD_TIMEOUT_ERROR; + } + + /* Check the PCCARD controller state */ + hpccard->State = DAL_PCCARD_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hpccard); + + return DAL_OK; +} + +/** + * @brief Reset the PCCARD memory + * @param hpccard pointer to a PCCARD_HandleTypeDef structure that contains + * the configuration information for PCCARD module. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_PCCARD_Reset(PCCARD_HandleTypeDef *hpccard) +{ + /* Process Locked */ + __DAL_LOCK(hpccard); + + /* Check the PCCARD controller state */ + if (hpccard->State == DAL_PCCARD_STATE_BUSY) + { + return DAL_BUSY; + } + + /* Provide a SW reset and Read and verify the: + - PCCard Configuration Option Register at address 0x98000200 --> 0x80 + - Card Configuration and Status Register at address 0x98000202 --> 0x00 + - Pin Replacement Register at address 0x98000204 --> 0x0C + - Socket and Copy Register at address 0x98000206 --> 0x00 + */ + + /* Check the PCCARD controller state */ + hpccard->State = DAL_PCCARD_STATE_BUSY; + + *(__IO uint8_t *)(PCCARD_ATTRIBUTE_SPACE_ADDRESS | ATA_CARD_CONFIGURATION) = 0x01; + + /* Check the PCCARD controller state */ + hpccard->State = DAL_PCCARD_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hpccard); + + return DAL_OK; +} + +/** + * @brief This function handles PCCARD device interrupt request. + * @param hpccard pointer to a PCCARD_HandleTypeDef structure that contains + * the configuration information for PCCARD module. + * @retval DAL status + */ +void DAL_PCCARD_IRQHandler(PCCARD_HandleTypeDef *hpccard) +{ + /* Check PCCARD interrupt Rising edge flag */ + if (__FMC_PCCARD_GET_FLAG(hpccard->Instance, FMC_FLAG_RISING_EDGE)) + { + /* PCCARD interrupt callback*/ +#if (USE_DAL_PCCARD_REGISTER_CALLBACKS == 1) + hpccard->ItCallback(hpccard); +#else + DAL_PCCARD_ITCallback(hpccard); +#endif + + /* Clear PCCARD interrupt Rising edge pending bit */ + __FMC_PCCARD_CLEAR_FLAG(hpccard->Instance, FMC_FLAG_RISING_EDGE); + } + + /* Check PCCARD interrupt Level flag */ + if (__FMC_PCCARD_GET_FLAG(hpccard->Instance, FMC_FLAG_LEVEL)) + { + /* PCCARD interrupt callback*/ +#if (USE_DAL_PCCARD_REGISTER_CALLBACKS == 1) + hpccard->ItCallback(hpccard); +#else + DAL_PCCARD_ITCallback(hpccard); +#endif + + /* Clear PCCARD interrupt Level pending bit */ + __FMC_PCCARD_CLEAR_FLAG(hpccard->Instance, FMC_FLAG_LEVEL); + } + + /* Check PCCARD interrupt Falling edge flag */ + if (__FMC_PCCARD_GET_FLAG(hpccard->Instance, FMC_FLAG_FALLING_EDGE)) + { + /* PCCARD interrupt callback*/ +#if (USE_DAL_PCCARD_REGISTER_CALLBACKS == 1) + hpccard->ItCallback(hpccard); +#else + DAL_PCCARD_ITCallback(hpccard); +#endif + + /* Clear PCCARD interrupt Falling edge pending bit */ + __FMC_PCCARD_CLEAR_FLAG(hpccard->Instance, FMC_FLAG_FALLING_EDGE); + } + + /* Check PCCARD interrupt FIFO empty flag */ + if (__FMC_PCCARD_GET_FLAG(hpccard->Instance, FMC_FLAG_FEMPT)) + { + /* PCCARD interrupt callback*/ +#if (USE_DAL_PCCARD_REGISTER_CALLBACKS == 1) + hpccard->ItCallback(hpccard); +#else + DAL_PCCARD_ITCallback(hpccard); +#endif + + /* Clear PCCARD interrupt FIFO empty pending bit */ + __FMC_PCCARD_CLEAR_FLAG(hpccard->Instance, FMC_FLAG_FEMPT); + } +} + +/** + * @brief PCCARD interrupt feature callback + * @param hpccard pointer to a PCCARD_HandleTypeDef structure that contains + * the configuration information for PCCARD module. + * @retval None + */ +__weak void DAL_PCCARD_ITCallback(PCCARD_HandleTypeDef *hpccard) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hpccard); + /* NOTE : This function Should not be modified, when the callback is needed, + the DAL_PCCARD_ITCallback could be implemented in the user file + */ +} + +#if (USE_DAL_PCCARD_REGISTER_CALLBACKS == 1) +/** + * @brief Register a User PCCARD Callback + * To be used instead of the weak (surcharged) predefined callback + * @param hpccard : PCCARD handle + * @param CallbackId : ID of the callback to be registered + * This parameter can be one of the following values: + * @arg @ref DAL_PCCARD_MSP_INIT_CB_ID PCCARD MspInit callback ID + * @arg @ref DAL_PCCARD_MSP_DEINIT_CB_ID PCCARD MspDeInit callback ID + * @arg @ref DAL_PCCARD_IT_CB_ID PCCARD IT callback ID + * @param pCallback : pointer to the Callback function + * @retval status + */ +DAL_StatusTypeDef DAL_PCCARD_RegisterCallback(PCCARD_HandleTypeDef *hpccard, DAL_PCCARD_CallbackIDTypeDef CallbackId, + pPCCARD_CallbackTypeDef pCallback) +{ + DAL_StatusTypeDef status = DAL_OK; + + if (pCallback == NULL) + { + return DAL_ERROR; + } + + /* Process locked */ + __DAL_LOCK(hpccard); + + if (hpccard->State == DAL_PCCARD_STATE_READY) + { + switch (CallbackId) + { + case DAL_PCCARD_MSP_INIT_CB_ID : + hpccard->MspInitCallback = pCallback; + break; + case DAL_PCCARD_MSP_DEINIT_CB_ID : + hpccard->MspDeInitCallback = pCallback; + break; + case DAL_PCCARD_IT_CB_ID : + hpccard->ItCallback = pCallback; + break; + default : + /* update return status */ + status = DAL_ERROR; + break; + } + } + else if (hpccard->State == DAL_PCCARD_STATE_RESET) + { + switch (CallbackId) + { + case DAL_PCCARD_MSP_INIT_CB_ID : + hpccard->MspInitCallback = pCallback; + break; + case DAL_PCCARD_MSP_DEINIT_CB_ID : + hpccard->MspDeInitCallback = pCallback; + break; + default : + /* update return status */ + status = DAL_ERROR; + break; + } + } + else + { + /* update return status */ + status = DAL_ERROR; + } + + /* Release Lock */ + __DAL_UNLOCK(hpccard); + return status; +} + +/** + * @brief Unregister a User PCCARD Callback + * PCCARD Callback is redirected to the weak (surcharged) predefined callback + * @param hpccard : PCCARD handle + * @param CallbackId : ID of the callback to be unregistered + * This parameter can be one of the following values: + * @arg @ref DAL_PCCARD_MSP_INIT_CB_ID PCCARD MspInit callback ID + * @arg @ref DAL_PCCARD_MSP_DEINIT_CB_ID PCCARD MspDeInit callback ID + * @arg @ref DAL_PCCARD_IT_CB_ID PCCARD IT callback ID + * @retval status + */ +DAL_StatusTypeDef DAL_PCCARD_UnRegisterCallback(PCCARD_HandleTypeDef *hpccard, DAL_PCCARD_CallbackIDTypeDef CallbackId) +{ + DAL_StatusTypeDef status = DAL_OK; + + /* Process locked */ + __DAL_LOCK(hpccard); + + if (hpccard->State == DAL_PCCARD_STATE_READY) + { + switch (CallbackId) + { + case DAL_PCCARD_MSP_INIT_CB_ID : + hpccard->MspInitCallback = DAL_PCCARD_MspInit; + break; + case DAL_PCCARD_MSP_DEINIT_CB_ID : + hpccard->MspDeInitCallback = DAL_PCCARD_MspDeInit; + break; + case DAL_PCCARD_IT_CB_ID : + hpccard->ItCallback = DAL_PCCARD_ITCallback; + break; + default : + /* update return status */ + status = DAL_ERROR; + break; + } + } + else if (hpccard->State == DAL_PCCARD_STATE_RESET) + { + switch (CallbackId) + { + case DAL_PCCARD_MSP_INIT_CB_ID : + hpccard->MspInitCallback = DAL_PCCARD_MspInit; + break; + case DAL_PCCARD_MSP_DEINIT_CB_ID : + hpccard->MspDeInitCallback = DAL_PCCARD_MspDeInit; + break; + default : + /* update return status */ + status = DAL_ERROR; + break; + } + } + else + { + /* update return status */ + status = DAL_ERROR; + } + + /* Release Lock */ + __DAL_UNLOCK(hpccard); + return status; +} +#endif + +/** + * @} + */ + +/** @defgroup PCCARD_Exported_Functions_Group3 State functions + * @brief Peripheral State functions + * +@verbatim + ============================================================================== + ##### PCCARD State functions ##### + ============================================================================== + [..] + This subsection permits to get in run-time the status of the PCCARD controller + and the data flow. + +@endverbatim + * @{ + */ + +/** + * @brief return the PCCARD controller state + * @param hpccard pointer to a PCCARD_HandleTypeDef structure that contains + * the configuration information for PCCARD module. + * @retval DAL state + */ +DAL_PCCARD_StateTypeDef DAL_PCCARD_GetState(PCCARD_HandleTypeDef *hpccard) +{ + return hpccard->State; +} + +/** + * @brief Get the compact flash memory status + * @param hpccard pointer to a PCCARD_HandleTypeDef structure that contains + * the configuration information for PCCARD module. + * @retval New status of the PCCARD operation. This parameter can be: + * - CompactFlash_TIMEOUT_ERROR: when the previous operation generate + * a Timeout error + * - CompactFlash_READY: when memory is ready for the next operation + */ +DAL_PCCARD_StatusTypeDef DAL_PCCARD_GetStatus(PCCARD_HandleTypeDef *hpccard) +{ + uint32_t timeout = PCCARD_TIMEOUT_STATUS, status_pccard = 0U; + + /* Check the PCCARD controller state */ + if (hpccard->State == DAL_PCCARD_STATE_BUSY) + { + return DAL_PCCARD_STATUS_ONGOING; + } + + status_pccard = *(__IO uint8_t *)(PCCARD_IO_SPACE_PRIMARY_ADDR | ATA_STATUS_CMD_ALTERNATE); + + while ((status_pccard == PCCARD_BUSY) && timeout) + { + status_pccard = *(__IO uint8_t *)(PCCARD_IO_SPACE_PRIMARY_ADDR | ATA_STATUS_CMD_ALTERNATE); + timeout--; + } + + if (timeout == 0U) + { + status_pccard = PCCARD_TIMEOUT_ERROR; + } + + /* Return the operation status */ + return (DAL_PCCARD_StatusTypeDef) status_pccard; +} + +/** + * @brief Reads the Compact Flash memory status using the Read status command + * @param hpccard pointer to a PCCARD_HandleTypeDef structure that contains + * the configuration information for PCCARD module. + * @retval The status of the Compact Flash memory. This parameter can be: + * - CompactFlash_BUSY: when memory is busy + * - CompactFlash_READY: when memory is ready for the next operation + * - CompactFlash_ERROR: when the previous operation generates error + */ +DAL_PCCARD_StatusTypeDef DAL_PCCARD_ReadStatus(PCCARD_HandleTypeDef *hpccard) +{ + uint8_t data = 0U, status_pccard = PCCARD_BUSY; + + /* Check the PCCARD controller state */ + if (hpccard->State == DAL_PCCARD_STATE_BUSY) + { + return DAL_PCCARD_STATUS_ONGOING; + } + + /* Read status operation */ + data = *(__IO uint8_t *)(PCCARD_IO_SPACE_PRIMARY_ADDR | ATA_STATUS_CMD_ALTERNATE); + + if ((data & PCCARD_TIMEOUT_ERROR) == PCCARD_TIMEOUT_ERROR) + { + status_pccard = PCCARD_TIMEOUT_ERROR; + } + else if ((data & PCCARD_READY) == PCCARD_READY) + { + status_pccard = PCCARD_READY; + } + + return (DAL_PCCARD_StatusTypeDef) status_pccard; +} + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#endif /* DAL_PCCARD_MODULE_ENABLED */ + +/** + * @} + */ + +#endif /* SMC_Bank4 */ diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_pcd.c b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_pcd.c new file mode 100644 index 0000000000..646103c10e --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_pcd.c @@ -0,0 +1,2402 @@ +/** + * + * @file apm32f4xx_dal_pcd.c + * @brief PCD DAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the USB Peripheral Controller: + * + Initialization and de-initialization functions + * + IO operation functions + * + Peripheral Control functions + * + Peripheral State functions + * + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + * + @verbatim + ============================================================================== + ##### How to use this driver ##### + ============================================================================== + [..] + The PCD DAL driver can be used as follows: + + (#) Declare a PCD_HandleTypeDef handle structure, for example: + PCD_HandleTypeDef hpcd; + + (#) Fill parameters of Init structure in HCD handle + + (#) Call DAL_PCD_Init() API to initialize the PCD peripheral (Core, Device core, ...) + + (#) Initialize the PCD low level resources through the DAL_PCD_MspInit() API: + (##) Enable the PCD/USB Low Level interface clock using + (+++) __DAL_RCM_USB_OTG_FS_CLK_ENABLE(); + (+++) __DAL_RCM_USB_OTG_HS_CLK_ENABLE(); (For High Speed Mode) + + (##) Initialize the related GPIO clocks + (##) Configure PCD pin-out + (##) Configure PCD NVIC interrupt + + (#)Associate the Upper USB device stack to the DAL PCD Driver: + (##) hpcd.pData = pdev; + + (#)Enable PCD transmission and reception: + (##) DAL_PCD_Start(); + + @endverbatim + * + */ + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @defgroup PCD PCD + * @brief PCD DAL module driver + * @{ + */ + +#ifdef DAL_PCD_MODULE_ENABLED + +#if defined (USB_OTG_FS) || defined (USB_OTG_HS) + +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/* Private macros ------------------------------------------------------------*/ +/** @defgroup PCD_Private_Macros PCD Private Macros + * @{ + */ +#define PCD_MIN(a, b) (((a) < (b)) ? (a) : (b)) +#define PCD_MAX(a, b) (((a) > (b)) ? (a) : (b)) +/** + * @} + */ + +/* Private functions prototypes ----------------------------------------------*/ +/** @defgroup PCD_Private_Functions PCD Private Functions + * @{ + */ +#if defined (USB_OTG_FS) || defined (USB_OTG_HS) +static DAL_StatusTypeDef PCD_WriteEmptyTxFifo(PCD_HandleTypeDef *hpcd, uint32_t epnum); +static DAL_StatusTypeDef PCD_EP_OutXfrComplete_int(PCD_HandleTypeDef *hpcd, uint32_t epnum); +static DAL_StatusTypeDef PCD_EP_OutSetupPacket_int(PCD_HandleTypeDef *hpcd, uint32_t epnum); +#endif /* defined (USB_OTG_FS) || defined (USB_OTG_HS) */ +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +/** @defgroup PCD_Exported_Functions PCD Exported Functions + * @{ + */ + +/** @defgroup PCD_Exported_Functions_Group1 Initialization and de-initialization functions + * @brief Initialization and Configuration functions + * +@verbatim + =============================================================================== + ##### Initialization and de-initialization functions ##### + =============================================================================== + [..] This section provides functions allowing to: + +@endverbatim + * @{ + */ + +/** + * @brief Initializes the PCD according to the specified + * parameters in the PCD_InitTypeDef and initialize the associated handle. + * @param hpcd PCD handle + * @retval DAL status + */ +DAL_StatusTypeDef DAL_PCD_Init(PCD_HandleTypeDef *hpcd) +{ + USB_OTG_GlobalTypeDef *USBx; + uint8_t i; + + /* Check the PCD handle allocation */ + if (hpcd == NULL) + { + return DAL_ERROR; + } + + /* Check the parameters */ + ASSERT_PARAM(IS_PCD_ALL_INSTANCE(hpcd->Instance)); + + USBx = hpcd->Instance; + + if (hpcd->State == DAL_PCD_STATE_RESET) + { + /* Allocate lock resource and initialize it */ + hpcd->Lock = DAL_UNLOCKED; + +#if (USE_DAL_PCD_REGISTER_CALLBACKS == 1U) + hpcd->SOFCallback = DAL_PCD_SOFCallback; + hpcd->SetupStageCallback = DAL_PCD_SetupStageCallback; + hpcd->ResetCallback = DAL_PCD_ResetCallback; + hpcd->SuspendCallback = DAL_PCD_SuspendCallback; + hpcd->ResumeCallback = DAL_PCD_ResumeCallback; + hpcd->ConnectCallback = DAL_PCD_ConnectCallback; + hpcd->DisconnectCallback = DAL_PCD_DisconnectCallback; + hpcd->DataOutStageCallback = DAL_PCD_DataOutStageCallback; + hpcd->DataInStageCallback = DAL_PCD_DataInStageCallback; + hpcd->ISOOUTIncompleteCallback = DAL_PCD_ISOOUTIncompleteCallback; + hpcd->ISOINIncompleteCallback = DAL_PCD_ISOINIncompleteCallback; + hpcd->LPMCallback = DAL_PCDEx_LPM_Callback; + hpcd->BCDCallback = DAL_PCDEx_BCD_Callback; + + if (hpcd->MspInitCallback == NULL) + { + hpcd->MspInitCallback = DAL_PCD_MspInit; + } + + /* Init the low level hardware */ + hpcd->MspInitCallback(hpcd); +#else + /* Init the low level hardware : GPIO, CLOCK, NVIC... */ + DAL_PCD_MspInit(hpcd); +#endif /* (USE_DAL_PCD_REGISTER_CALLBACKS) */ + } + + hpcd->State = DAL_PCD_STATE_BUSY; + + /* Disable DMA mode for FS instance */ + if ((USBx->GCID & (0x1U << 8)) == 0U) + { + hpcd->Init.dma_enable = 0U; + } + + /* Disable the Interrupts */ + __DAL_PCD_DISABLE(hpcd); + + /*Init the Core (common init.) */ + if (USB_CoreInit(hpcd->Instance, hpcd->Init) != DAL_OK) + { + hpcd->State = DAL_PCD_STATE_ERROR; + return DAL_ERROR; + } + + /* Force Device Mode*/ + (void)USB_SetCurrentMode(hpcd->Instance, USB_DEVICE_MODE); + + /* Init endpoints structures */ + for (i = 0U; i < hpcd->Init.dev_endpoints; i++) + { + /* Init ep structure */ + hpcd->IN_ep[i].is_in = 1U; + hpcd->IN_ep[i].num = i; + hpcd->IN_ep[i].tx_fifo_num = i; + /* Control until ep is activated */ + hpcd->IN_ep[i].type = EP_TYPE_CTRL; + hpcd->IN_ep[i].maxpacket = 0U; + hpcd->IN_ep[i].xfer_buff = 0U; + hpcd->IN_ep[i].xfer_len = 0U; + } + + for (i = 0U; i < hpcd->Init.dev_endpoints; i++) + { + hpcd->OUT_ep[i].is_in = 0U; + hpcd->OUT_ep[i].num = i; + /* Control until ep is activated */ + hpcd->OUT_ep[i].type = EP_TYPE_CTRL; + hpcd->OUT_ep[i].maxpacket = 0U; + hpcd->OUT_ep[i].xfer_buff = 0U; + hpcd->OUT_ep[i].xfer_len = 0U; + } + + /* Init Device */ + if (USB_DevInit(hpcd->Instance, hpcd->Init) != DAL_OK) + { + hpcd->State = DAL_PCD_STATE_ERROR; + return DAL_ERROR; + } + + hpcd->USB_Address = 0U; + hpcd->State = DAL_PCD_STATE_READY; + + (void)USB_DevDisconnect(hpcd->Instance); + + return DAL_OK; +} + +/** + * @brief DeInitializes the PCD peripheral. + * @param hpcd PCD handle + * @retval DAL status + */ +DAL_StatusTypeDef DAL_PCD_DeInit(PCD_HandleTypeDef *hpcd) +{ + /* Check the PCD handle allocation */ + if (hpcd == NULL) + { + return DAL_ERROR; + } + + hpcd->State = DAL_PCD_STATE_BUSY; + + /* Stop Device */ + if (USB_StopDevice(hpcd->Instance) != DAL_OK) + { + return DAL_ERROR; + } + +#if (USE_DAL_PCD_REGISTER_CALLBACKS == 1U) + if (hpcd->MspDeInitCallback == NULL) + { + hpcd->MspDeInitCallback = DAL_PCD_MspDeInit; /* Legacy weak MspDeInit */ + } + + /* DeInit the low level hardware */ + hpcd->MspDeInitCallback(hpcd); +#else + /* DeInit the low level hardware: CLOCK, NVIC.*/ + DAL_PCD_MspDeInit(hpcd); +#endif /* USE_DAL_PCD_REGISTER_CALLBACKS */ + + hpcd->State = DAL_PCD_STATE_RESET; + + return DAL_OK; +} + +/** + * @brief Initializes the PCD MSP. + * @param hpcd PCD handle + * @retval None + */ +__weak void DAL_PCD_MspInit(PCD_HandleTypeDef *hpcd) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hpcd); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_PCD_MspInit could be implemented in the user file + */ +} + +/** + * @brief DeInitializes PCD MSP. + * @param hpcd PCD handle + * @retval None + */ +__weak void DAL_PCD_MspDeInit(PCD_HandleTypeDef *hpcd) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hpcd); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_PCD_MspDeInit could be implemented in the user file + */ +} + +#if (USE_DAL_PCD_REGISTER_CALLBACKS == 1U) +/** + * @brief Register a User USB PCD Callback + * To be used instead of the weak predefined callback + * @param hpcd USB PCD handle + * @param CallbackID ID of the callback to be registered + * This parameter can be one of the following values: + * @arg @ref DAL_PCD_SOF_CB_ID USB PCD SOF callback ID + * @arg @ref DAL_PCD_SETUPSTAGE_CB_ID USB PCD Setup callback ID + * @arg @ref DAL_PCD_RESET_CB_ID USB PCD Reset callback ID + * @arg @ref DAL_PCD_SUSPEND_CB_ID USB PCD Suspend callback ID + * @arg @ref DAL_PCD_RESUME_CB_ID USB PCD Resume callback ID + * @arg @ref DAL_PCD_CONNECT_CB_ID USB PCD Connect callback ID + * @arg @ref DAL_PCD_DISCONNECT_CB_ID OTG PCD Disconnect callback ID + * @arg @ref DAL_PCD_MSPINIT_CB_ID MspDeInit callback ID + * @arg @ref DAL_PCD_MSPDEINIT_CB_ID MspDeInit callback ID + * @param pCallback pointer to the Callback function + * @retval DAL status + */ +DAL_StatusTypeDef DAL_PCD_RegisterCallback(PCD_HandleTypeDef *hpcd, + DAL_PCD_CallbackIDTypeDef CallbackID, + pPCD_CallbackTypeDef pCallback) +{ + DAL_StatusTypeDef status = DAL_OK; + + if (pCallback == NULL) + { + /* Update the error code */ + hpcd->ErrorCode |= DAL_PCD_ERROR_INVALID_CALLBACK; + return DAL_ERROR; + } + /* Process locked */ + __DAL_LOCK(hpcd); + + if (hpcd->State == DAL_PCD_STATE_READY) + { + switch (CallbackID) + { + case DAL_PCD_SOF_CB_ID : + hpcd->SOFCallback = pCallback; + break; + + case DAL_PCD_SETUPSTAGE_CB_ID : + hpcd->SetupStageCallback = pCallback; + break; + + case DAL_PCD_RESET_CB_ID : + hpcd->ResetCallback = pCallback; + break; + + case DAL_PCD_SUSPEND_CB_ID : + hpcd->SuspendCallback = pCallback; + break; + + case DAL_PCD_RESUME_CB_ID : + hpcd->ResumeCallback = pCallback; + break; + + case DAL_PCD_CONNECT_CB_ID : + hpcd->ConnectCallback = pCallback; + break; + + case DAL_PCD_DISCONNECT_CB_ID : + hpcd->DisconnectCallback = pCallback; + break; + + case DAL_PCD_MSPINIT_CB_ID : + hpcd->MspInitCallback = pCallback; + break; + + case DAL_PCD_MSPDEINIT_CB_ID : + hpcd->MspDeInitCallback = pCallback; + break; + + default : + /* Update the error code */ + hpcd->ErrorCode |= DAL_PCD_ERROR_INVALID_CALLBACK; + /* Return error status */ + status = DAL_ERROR; + break; + } + } + else if (hpcd->State == DAL_PCD_STATE_RESET) + { + switch (CallbackID) + { + case DAL_PCD_MSPINIT_CB_ID : + hpcd->MspInitCallback = pCallback; + break; + + case DAL_PCD_MSPDEINIT_CB_ID : + hpcd->MspDeInitCallback = pCallback; + break; + + default : + /* Update the error code */ + hpcd->ErrorCode |= DAL_PCD_ERROR_INVALID_CALLBACK; + /* Return error status */ + status = DAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + hpcd->ErrorCode |= DAL_PCD_ERROR_INVALID_CALLBACK; + /* Return error status */ + status = DAL_ERROR; + } + + /* Release Lock */ + __DAL_UNLOCK(hpcd); + return status; +} + +/** + * @brief Unregister an USB PCD Callback + * USB PCD callback is redirected to the weak predefined callback + * @param hpcd USB PCD handle + * @param CallbackID ID of the callback to be unregistered + * This parameter can be one of the following values: + * @arg @ref DAL_PCD_SOF_CB_ID USB PCD SOF callback ID + * @arg @ref DAL_PCD_SETUPSTAGE_CB_ID USB PCD Setup callback ID + * @arg @ref DAL_PCD_RESET_CB_ID USB PCD Reset callback ID + * @arg @ref DAL_PCD_SUSPEND_CB_ID USB PCD Suspend callback ID + * @arg @ref DAL_PCD_RESUME_CB_ID USB PCD Resume callback ID + * @arg @ref DAL_PCD_CONNECT_CB_ID USB PCD Connect callback ID + * @arg @ref DAL_PCD_DISCONNECT_CB_ID OTG PCD Disconnect callback ID + * @arg @ref DAL_PCD_MSPINIT_CB_ID MspDeInit callback ID + * @arg @ref DAL_PCD_MSPDEINIT_CB_ID MspDeInit callback ID + * @retval DAL status + */ +DAL_StatusTypeDef DAL_PCD_UnRegisterCallback(PCD_HandleTypeDef *hpcd, DAL_PCD_CallbackIDTypeDef CallbackID) +{ + DAL_StatusTypeDef status = DAL_OK; + + /* Process locked */ + __DAL_LOCK(hpcd); + + /* Setup Legacy weak Callbacks */ + if (hpcd->State == DAL_PCD_STATE_READY) + { + switch (CallbackID) + { + case DAL_PCD_SOF_CB_ID : + hpcd->SOFCallback = DAL_PCD_SOFCallback; + break; + + case DAL_PCD_SETUPSTAGE_CB_ID : + hpcd->SetupStageCallback = DAL_PCD_SetupStageCallback; + break; + + case DAL_PCD_RESET_CB_ID : + hpcd->ResetCallback = DAL_PCD_ResetCallback; + break; + + case DAL_PCD_SUSPEND_CB_ID : + hpcd->SuspendCallback = DAL_PCD_SuspendCallback; + break; + + case DAL_PCD_RESUME_CB_ID : + hpcd->ResumeCallback = DAL_PCD_ResumeCallback; + break; + + case DAL_PCD_CONNECT_CB_ID : + hpcd->ConnectCallback = DAL_PCD_ConnectCallback; + break; + + case DAL_PCD_DISCONNECT_CB_ID : + hpcd->DisconnectCallback = DAL_PCD_DisconnectCallback; + break; + + case DAL_PCD_MSPINIT_CB_ID : + hpcd->MspInitCallback = DAL_PCD_MspInit; + break; + + case DAL_PCD_MSPDEINIT_CB_ID : + hpcd->MspDeInitCallback = DAL_PCD_MspDeInit; + break; + + default : + /* Update the error code */ + hpcd->ErrorCode |= DAL_PCD_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = DAL_ERROR; + break; + } + } + else if (hpcd->State == DAL_PCD_STATE_RESET) + { + switch (CallbackID) + { + case DAL_PCD_MSPINIT_CB_ID : + hpcd->MspInitCallback = DAL_PCD_MspInit; + break; + + case DAL_PCD_MSPDEINIT_CB_ID : + hpcd->MspDeInitCallback = DAL_PCD_MspDeInit; + break; + + default : + /* Update the error code */ + hpcd->ErrorCode |= DAL_PCD_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = DAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + hpcd->ErrorCode |= DAL_PCD_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = DAL_ERROR; + } + + /* Release Lock */ + __DAL_UNLOCK(hpcd); + return status; +} + +/** + * @brief Register USB PCD Data OUT Stage Callback + * To be used instead of the weak DAL_PCD_DataOutStageCallback() predefined callback + * @param hpcd PCD handle + * @param pCallback pointer to the USB PCD Data OUT Stage Callback function + * @retval DAL status + */ +DAL_StatusTypeDef DAL_PCD_RegisterDataOutStageCallback(PCD_HandleTypeDef *hpcd, + pPCD_DataOutStageCallbackTypeDef pCallback) +{ + DAL_StatusTypeDef status = DAL_OK; + + if (pCallback == NULL) + { + /* Update the error code */ + hpcd->ErrorCode |= DAL_PCD_ERROR_INVALID_CALLBACK; + + return DAL_ERROR; + } + + /* Process locked */ + __DAL_LOCK(hpcd); + + if (hpcd->State == DAL_PCD_STATE_READY) + { + hpcd->DataOutStageCallback = pCallback; + } + else + { + /* Update the error code */ + hpcd->ErrorCode |= DAL_PCD_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = DAL_ERROR; + } + + /* Release Lock */ + __DAL_UNLOCK(hpcd); + + return status; +} + +/** + * @brief Unregister the USB PCD Data OUT Stage Callback + * USB PCD Data OUT Stage Callback is redirected to the weak DAL_PCD_DataOutStageCallback() predefined callback + * @param hpcd PCD handle + * @retval DAL status + */ +DAL_StatusTypeDef DAL_PCD_UnRegisterDataOutStageCallback(PCD_HandleTypeDef *hpcd) +{ + DAL_StatusTypeDef status = DAL_OK; + + /* Process locked */ + __DAL_LOCK(hpcd); + + if (hpcd->State == DAL_PCD_STATE_READY) + { + hpcd->DataOutStageCallback = DAL_PCD_DataOutStageCallback; /* Legacy weak DataOutStageCallback */ + } + else + { + /* Update the error code */ + hpcd->ErrorCode |= DAL_PCD_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = DAL_ERROR; + } + + /* Release Lock */ + __DAL_UNLOCK(hpcd); + + return status; +} + +/** + * @brief Register USB PCD Data IN Stage Callback + * To be used instead of the weak DAL_PCD_DataInStageCallback() predefined callback + * @param hpcd PCD handle + * @param pCallback pointer to the USB PCD Data IN Stage Callback function + * @retval DAL status + */ +DAL_StatusTypeDef DAL_PCD_RegisterDataInStageCallback(PCD_HandleTypeDef *hpcd, + pPCD_DataInStageCallbackTypeDef pCallback) +{ + DAL_StatusTypeDef status = DAL_OK; + + if (pCallback == NULL) + { + /* Update the error code */ + hpcd->ErrorCode |= DAL_PCD_ERROR_INVALID_CALLBACK; + + return DAL_ERROR; + } + + /* Process locked */ + __DAL_LOCK(hpcd); + + if (hpcd->State == DAL_PCD_STATE_READY) + { + hpcd->DataInStageCallback = pCallback; + } + else + { + /* Update the error code */ + hpcd->ErrorCode |= DAL_PCD_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = DAL_ERROR; + } + + /* Release Lock */ + __DAL_UNLOCK(hpcd); + + return status; +} + +/** + * @brief Unregister the USB PCD Data IN Stage Callback + * USB PCD Data OUT Stage Callback is redirected to the weak DAL_PCD_DataInStageCallback() predefined callback + * @param hpcd PCD handle + * @retval DAL status + */ +DAL_StatusTypeDef DAL_PCD_UnRegisterDataInStageCallback(PCD_HandleTypeDef *hpcd) +{ + DAL_StatusTypeDef status = DAL_OK; + + /* Process locked */ + __DAL_LOCK(hpcd); + + if (hpcd->State == DAL_PCD_STATE_READY) + { + hpcd->DataInStageCallback = DAL_PCD_DataInStageCallback; /* Legacy weak DataInStageCallback */ + } + else + { + /* Update the error code */ + hpcd->ErrorCode |= DAL_PCD_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = DAL_ERROR; + } + + /* Release Lock */ + __DAL_UNLOCK(hpcd); + + return status; +} + +/** + * @brief Register USB PCD Iso OUT incomplete Callback + * To be used instead of the weak DAL_PCD_ISOOUTIncompleteCallback() predefined callback + * @param hpcd PCD handle + * @param pCallback pointer to the USB PCD Iso OUT incomplete Callback function + * @retval DAL status + */ +DAL_StatusTypeDef DAL_PCD_RegisterIsoOutIncpltCallback(PCD_HandleTypeDef *hpcd, + pPCD_IsoOutIncpltCallbackTypeDef pCallback) +{ + DAL_StatusTypeDef status = DAL_OK; + + if (pCallback == NULL) + { + /* Update the error code */ + hpcd->ErrorCode |= DAL_PCD_ERROR_INVALID_CALLBACK; + + return DAL_ERROR; + } + + /* Process locked */ + __DAL_LOCK(hpcd); + + if (hpcd->State == DAL_PCD_STATE_READY) + { + hpcd->ISOOUTIncompleteCallback = pCallback; + } + else + { + /* Update the error code */ + hpcd->ErrorCode |= DAL_PCD_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = DAL_ERROR; + } + + /* Release Lock */ + __DAL_UNLOCK(hpcd); + + return status; +} + +/** + * @brief Unregister the USB PCD Iso OUT incomplete Callback + * USB PCD Iso OUT incomplete Callback is redirected + * to the weak DAL_PCD_ISOOUTIncompleteCallback() predefined callback + * @param hpcd PCD handle + * @retval DAL status + */ +DAL_StatusTypeDef DAL_PCD_UnRegisterIsoOutIncpltCallback(PCD_HandleTypeDef *hpcd) +{ + DAL_StatusTypeDef status = DAL_OK; + + /* Process locked */ + __DAL_LOCK(hpcd); + + if (hpcd->State == DAL_PCD_STATE_READY) + { + hpcd->ISOOUTIncompleteCallback = DAL_PCD_ISOOUTIncompleteCallback; /* Legacy weak ISOOUTIncompleteCallback */ + } + else + { + /* Update the error code */ + hpcd->ErrorCode |= DAL_PCD_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = DAL_ERROR; + } + + /* Release Lock */ + __DAL_UNLOCK(hpcd); + + return status; +} + +/** + * @brief Register USB PCD Iso IN incomplete Callback + * To be used instead of the weak DAL_PCD_ISOINIncompleteCallback() predefined callback + * @param hpcd PCD handle + * @param pCallback pointer to the USB PCD Iso IN incomplete Callback function + * @retval DAL status + */ +DAL_StatusTypeDef DAL_PCD_RegisterIsoInIncpltCallback(PCD_HandleTypeDef *hpcd, + pPCD_IsoInIncpltCallbackTypeDef pCallback) +{ + DAL_StatusTypeDef status = DAL_OK; + + if (pCallback == NULL) + { + /* Update the error code */ + hpcd->ErrorCode |= DAL_PCD_ERROR_INVALID_CALLBACK; + + return DAL_ERROR; + } + + /* Process locked */ + __DAL_LOCK(hpcd); + + if (hpcd->State == DAL_PCD_STATE_READY) + { + hpcd->ISOINIncompleteCallback = pCallback; + } + else + { + /* Update the error code */ + hpcd->ErrorCode |= DAL_PCD_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = DAL_ERROR; + } + + /* Release Lock */ + __DAL_UNLOCK(hpcd); + + return status; +} + +/** + * @brief Unregister the USB PCD Iso IN incomplete Callback + * USB PCD Iso IN incomplete Callback is redirected + * to the weak DAL_PCD_ISOINIncompleteCallback() predefined callback + * @param hpcd PCD handle + * @retval DAL status + */ +DAL_StatusTypeDef DAL_PCD_UnRegisterIsoInIncpltCallback(PCD_HandleTypeDef *hpcd) +{ + DAL_StatusTypeDef status = DAL_OK; + + /* Process locked */ + __DAL_LOCK(hpcd); + + if (hpcd->State == DAL_PCD_STATE_READY) + { + hpcd->ISOINIncompleteCallback = DAL_PCD_ISOINIncompleteCallback; /* Legacy weak ISOINIncompleteCallback */ + } + else + { + /* Update the error code */ + hpcd->ErrorCode |= DAL_PCD_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = DAL_ERROR; + } + + /* Release Lock */ + __DAL_UNLOCK(hpcd); + + return status; +} + +/** + * @brief Register USB PCD BCD Callback + * To be used instead of the weak DAL_PCDEx_BCD_Callback() predefined callback + * @param hpcd PCD handle + * @param pCallback pointer to the USB PCD BCD Callback function + * @retval DAL status + */ +DAL_StatusTypeDef DAL_PCD_RegisterBcdCallback(PCD_HandleTypeDef *hpcd, pPCD_BcdCallbackTypeDef pCallback) +{ + DAL_StatusTypeDef status = DAL_OK; + + if (pCallback == NULL) + { + /* Update the error code */ + hpcd->ErrorCode |= DAL_PCD_ERROR_INVALID_CALLBACK; + + return DAL_ERROR; + } + + /* Process locked */ + __DAL_LOCK(hpcd); + + if (hpcd->State == DAL_PCD_STATE_READY) + { + hpcd->BCDCallback = pCallback; + } + else + { + /* Update the error code */ + hpcd->ErrorCode |= DAL_PCD_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = DAL_ERROR; + } + + /* Release Lock */ + __DAL_UNLOCK(hpcd); + + return status; +} + +/** + * @brief Unregister the USB PCD BCD Callback + * USB BCD Callback is redirected to the weak DAL_PCDEx_BCD_Callback() predefined callback + * @param hpcd PCD handle + * @retval DAL status + */ +DAL_StatusTypeDef DAL_PCD_UnRegisterBcdCallback(PCD_HandleTypeDef *hpcd) +{ + DAL_StatusTypeDef status = DAL_OK; + + /* Process locked */ + __DAL_LOCK(hpcd); + + if (hpcd->State == DAL_PCD_STATE_READY) + { + hpcd->BCDCallback = DAL_PCDEx_BCD_Callback; /* Legacy weak DAL_PCDEx_BCD_Callback */ + } + else + { + /* Update the error code */ + hpcd->ErrorCode |= DAL_PCD_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = DAL_ERROR; + } + + /* Release Lock */ + __DAL_UNLOCK(hpcd); + + return status; +} + +/** + * @brief Register USB PCD LPM Callback + * To be used instead of the weak DAL_PCDEx_LPM_Callback() predefined callback + * @param hpcd PCD handle + * @param pCallback pointer to the USB PCD LPM Callback function + * @retval DAL status + */ +DAL_StatusTypeDef DAL_PCD_RegisterLpmCallback(PCD_HandleTypeDef *hpcd, pPCD_LpmCallbackTypeDef pCallback) +{ + DAL_StatusTypeDef status = DAL_OK; + + if (pCallback == NULL) + { + /* Update the error code */ + hpcd->ErrorCode |= DAL_PCD_ERROR_INVALID_CALLBACK; + + return DAL_ERROR; + } + + /* Process locked */ + __DAL_LOCK(hpcd); + + if (hpcd->State == DAL_PCD_STATE_READY) + { + hpcd->LPMCallback = pCallback; + } + else + { + /* Update the error code */ + hpcd->ErrorCode |= DAL_PCD_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = DAL_ERROR; + } + + /* Release Lock */ + __DAL_UNLOCK(hpcd); + + return status; +} + +/** + * @brief Unregister the USB PCD LPM Callback + * USB LPM Callback is redirected to the weak DAL_PCDEx_LPM_Callback() predefined callback + * @param hpcd PCD handle + * @retval DAL status + */ +DAL_StatusTypeDef DAL_PCD_UnRegisterLpmCallback(PCD_HandleTypeDef *hpcd) +{ + DAL_StatusTypeDef status = DAL_OK; + + /* Process locked */ + __DAL_LOCK(hpcd); + + if (hpcd->State == DAL_PCD_STATE_READY) + { + hpcd->LPMCallback = DAL_PCDEx_LPM_Callback; /* Legacy weak DAL_PCDEx_LPM_Callback */ + } + else + { + /* Update the error code */ + hpcd->ErrorCode |= DAL_PCD_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = DAL_ERROR; + } + + /* Release Lock */ + __DAL_UNLOCK(hpcd); + + return status; +} +#endif /* USE_DAL_PCD_REGISTER_CALLBACKS */ + +/** + * @} + */ + +/** @defgroup PCD_Exported_Functions_Group2 Input and Output operation functions + * @brief Data transfers functions + * +@verbatim + =============================================================================== + ##### IO operation functions ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to manage the PCD data + transfers. + +@endverbatim + * @{ + */ + +/** + * @brief Start the USB device + * @param hpcd PCD handle + * @retval DAL status + */ +DAL_StatusTypeDef DAL_PCD_Start(PCD_HandleTypeDef *hpcd) +{ + USB_OTG_GlobalTypeDef *USBx = hpcd->Instance; + + __DAL_LOCK(hpcd); + + if ((hpcd->Init.battery_charging_enable == 1U) && + (hpcd->Init.phy_itface != USB_OTG_ULPI_PHY)) + { + /* Enable USB Transceiver */ + USBx->GGCCFG |= USB_OTG_GGCCFG_PWEN; + } + + __DAL_PCD_ENABLE(hpcd); + (void)USB_DevConnect(hpcd->Instance); + __DAL_UNLOCK(hpcd); + + return DAL_OK; +} + +/** + * @brief Stop the USB device. + * @param hpcd PCD handle + * @retval DAL status + */ +DAL_StatusTypeDef DAL_PCD_Stop(PCD_HandleTypeDef *hpcd) +{ + USB_OTG_GlobalTypeDef *USBx = hpcd->Instance; + + __DAL_LOCK(hpcd); + __DAL_PCD_DISABLE(hpcd); + (void)USB_DevDisconnect(hpcd->Instance); + + (void)USB_FlushTxFifo(hpcd->Instance, 0x10U); + + if ((hpcd->Init.battery_charging_enable == 1U) && + (hpcd->Init.phy_itface != USB_OTG_ULPI_PHY)) + { + /* Disable USB Transceiver */ + USBx->GGCCFG &= ~(USB_OTG_GGCCFG_PWEN); + } + + __DAL_UNLOCK(hpcd); + + return DAL_OK; +} + +#if defined (USB_OTG_FS) || defined (USB_OTG_HS) +/** + * @brief Handles PCD interrupt request. + * @param hpcd PCD handle + * @retval DAL status + */ +void DAL_PCD_IRQHandler(PCD_HandleTypeDef *hpcd) +{ + USB_OTG_GlobalTypeDef *USBx = hpcd->Instance; + uint32_t USBx_BASE = (uint32_t)USBx; + USB_OTG_EPTypeDef *ep; + uint32_t i; + uint32_t ep_intr; + uint32_t epint; + uint32_t epnum; + uint32_t fifoemptymsk; + uint32_t RegVal; + + /* ensure that we are in device mode */ + if (USB_GetMode(hpcd->Instance) == USB_OTG_MODE_DEVICE) + { + /* avoid spurious interrupt */ + if (__DAL_PCD_IS_INVALID_INTERRUPT(hpcd)) + { + return; + } + + /* store current frame number */ + hpcd->FrameNumber = (USBx_DEVICE->DSTS & USB_OTG_DSTS_SOFNUM_Msk) >> USB_OTG_DSTS_SOFNUM_Pos; + + if (__DAL_PCD_GET_FLAG(hpcd, USB_OTG_GCINT_MMIS)) + { + /* incorrect mode, acknowledge the interrupt */ + __DAL_PCD_CLEAR_FLAG(hpcd, USB_OTG_GCINT_MMIS); + } + + /* Handle RxQLevel Interrupt */ + if (__DAL_PCD_GET_FLAG(hpcd, USB_OTG_GCINT_RXFNONE)) + { + USB_MASK_INTERRUPT(hpcd->Instance, USB_OTG_GCINT_RXFNONE); + + RegVal = USBx->GRXSTSP; + + ep = &hpcd->OUT_ep[RegVal & USB_OTG_GRXSTSP_EPNUM]; + + if (((RegVal & USB_OTG_GRXSTSP_PSTS) >> 17) == STS_DATA_UPDT) + { + if ((RegVal & USB_OTG_GRXSTSP_BCNT) != 0U) + { + (void)USB_ReadPacket(USBx, ep->xfer_buff, + (uint16_t)((RegVal & USB_OTG_GRXSTSP_BCNT) >> 4)); + + ep->xfer_buff += (RegVal & USB_OTG_GRXSTSP_BCNT) >> 4; + ep->xfer_count += (RegVal & USB_OTG_GRXSTSP_BCNT) >> 4; + } + } + else if (((RegVal & USB_OTG_GRXSTSP_PSTS) >> 17) == STS_SETUP_UPDT) + { + (void)USB_ReadPacket(USBx, (uint8_t *)hpcd->Setup, 8U); + ep->xfer_count += (RegVal & USB_OTG_GRXSTSP_BCNT) >> 4; + } + else + { + /* ... */ + } + + USB_UNMASK_INTERRUPT(hpcd->Instance, USB_OTG_GCINT_RXFNONE); + } + + if (__DAL_PCD_GET_FLAG(hpcd, USB_OTG_GCINT_ONEP)) + { + epnum = 0U; + + /* Read in the device interrupt bits */ + ep_intr = USB_ReadDevAllOutEpInterrupt(hpcd->Instance); + + while (ep_intr != 0U) + { + if ((ep_intr & 0x1U) != 0U) + { + epint = USB_ReadDevOutEPInterrupt(hpcd->Instance, (uint8_t)epnum); + + if ((epint & USB_OTG_DOEPINT_TSFCMP) == USB_OTG_DOEPINT_TSFCMP) + { + CLEAR_OUT_EP_INTR(epnum, USB_OTG_DOEPINT_TSFCMP); + (void)PCD_EP_OutXfrComplete_int(hpcd, epnum); + } + + if ((epint & USB_OTG_DOEPINT_SETPCMP) == USB_OTG_DOEPINT_SETPCMP) + { + CLEAR_OUT_EP_INTR(epnum, USB_OTG_DOEPINT_SETPCMP); + /* Class B setup phase done for previous decoded setup */ + (void)PCD_EP_OutSetupPacket_int(hpcd, epnum); + } + + if ((epint & USB_OTG_DOEPINT_RXOTDIS) == USB_OTG_DOEPINT_RXOTDIS) + { + CLEAR_OUT_EP_INTR(epnum, USB_OTG_DOEPINT_RXOTDIS); + } + + /* Clear OUT Endpoint disable interrupt */ + if ((epint & USB_OTG_DOEPINT_EPDIS) == USB_OTG_DOEPINT_EPDIS) + { + if ((USBx->GCINT & USB_OTG_GCINT_GONAKE) == USB_OTG_GCINT_GONAKE) + { + USBx_DEVICE->DCTRL |= USB_OTG_DCTRL_GONAKCLR; + } + + ep = &hpcd->OUT_ep[epnum]; + + if (ep->is_iso_incomplete == 1U) + { + ep->is_iso_incomplete = 0U; + +#if (USE_DAL_PCD_REGISTER_CALLBACKS == 1U) + hpcd->ISOOUTIncompleteCallback(hpcd, (uint8_t)epnum); +#else + DAL_PCD_ISOOUTIncompleteCallback(hpcd, (uint8_t)epnum); +#endif /* USE_DAL_PCD_REGISTER_CALLBACKS */ + } + + CLEAR_OUT_EP_INTR(epnum, USB_OTG_DOEPINT_EPDIS); + } + + /* Clear Status Phase Received interrupt */ + if ((epint & USB_OTG_DOEPINT_OTEPSPR) == USB_OTG_DOEPINT_OTEPSPR) + { + CLEAR_OUT_EP_INTR(epnum, USB_OTG_DOEPINT_OTEPSPR); + } + + /* Clear OUT NAK interrupt */ + if ((epint & USB_OTG_DOEPINT_NAK) == USB_OTG_DOEPINT_NAK) + { + CLEAR_OUT_EP_INTR(epnum, USB_OTG_DOEPINT_NAK); + } + } + epnum++; + ep_intr >>= 1U; + } + } + + if (__DAL_PCD_GET_FLAG(hpcd, USB_OTG_GCINT_INEP)) + { + /* Read in the device interrupt bits */ + ep_intr = USB_ReadDevAllInEpInterrupt(hpcd->Instance); + + epnum = 0U; + + while (ep_intr != 0U) + { + if ((ep_intr & 0x1U) != 0U) /* In ITR */ + { + epint = USB_ReadDevInEPInterrupt(hpcd->Instance, (uint8_t)epnum); + + if ((epint & USB_OTG_DIEPINT_TSFCMP) == USB_OTG_DIEPINT_TSFCMP) + { + fifoemptymsk = (uint32_t)(0x1UL << (epnum & EP_ADDR_MSK)); + USBx_DEVICE->DIEIMASK &= ~fifoemptymsk; + + CLEAR_IN_EP_INTR(epnum, USB_OTG_DIEPINT_TSFCMP); + + if (hpcd->Init.dma_enable == 1U) + { + hpcd->IN_ep[epnum].xfer_buff += hpcd->IN_ep[epnum].maxpacket; + + /* this is ZLP, so prepare EP0 for next setup */ + if ((epnum == 0U) && (hpcd->IN_ep[epnum].xfer_len == 0U)) + { + /* prepare to rx more setup packets */ + (void)USB_EP0_OutStart(hpcd->Instance, 1U, (uint8_t *)hpcd->Setup); + } + } + +#if (USE_DAL_PCD_REGISTER_CALLBACKS == 1U) + hpcd->DataInStageCallback(hpcd, (uint8_t)epnum); +#else + DAL_PCD_DataInStageCallback(hpcd, (uint8_t)epnum); +#endif /* USE_DAL_PCD_REGISTER_CALLBACKS */ + } + if ((epint & USB_OTG_DIEPINT_TO) == USB_OTG_DIEPINT_TO) + { + CLEAR_IN_EP_INTR(epnum, USB_OTG_DIEPINT_TO); + } + if ((epint & USB_OTG_DIEPINT_ITXEMP) == USB_OTG_DIEPINT_ITXEMP) + { + CLEAR_IN_EP_INTR(epnum, USB_OTG_DIEPINT_ITXEMP); + } + if ((epint & USB_OTG_DIEPINT_IEPNAKE) == USB_OTG_DIEPINT_IEPNAKE) + { + CLEAR_IN_EP_INTR(epnum, USB_OTG_DIEPINT_IEPNAKE); + } + if ((epint & USB_OTG_DIEPINT_EPDIS) == USB_OTG_DIEPINT_EPDIS) + { + (void)USB_FlushTxFifo(USBx, epnum); + + ep = &hpcd->IN_ep[epnum]; + + if (ep->is_iso_incomplete == 1U) + { + ep->is_iso_incomplete = 0U; + +#if (USE_DAL_PCD_REGISTER_CALLBACKS == 1U) + hpcd->ISOINIncompleteCallback(hpcd, (uint8_t)epnum); +#else + DAL_PCD_ISOINIncompleteCallback(hpcd, (uint8_t)epnum); +#endif /* USE_DAL_PCD_REGISTER_CALLBACKS */ + } + + CLEAR_IN_EP_INTR(epnum, USB_OTG_DIEPINT_EPDIS); + } + if ((epint & USB_OTG_DIEPINT_TXFE) == USB_OTG_DIEPINT_TXFE) + { + (void)PCD_WriteEmptyTxFifo(hpcd, epnum); + } + } + epnum++; + ep_intr >>= 1U; + } + } + + /* Handle Resume Interrupt */ + if (__DAL_PCD_GET_FLAG(hpcd, USB_OTG_GCINT_RWAKE)) + { + /* Clear the Remote Wake-up Signaling */ + USBx_DEVICE->DCTRL &= ~USB_OTG_DCTRL_RWKUPS; + + if (hpcd->LPM_State == LPM_L1) + { + hpcd->LPM_State = LPM_L0; + +#if (USE_DAL_PCD_REGISTER_CALLBACKS == 1U) + hpcd->LPMCallback(hpcd, PCD_LPM_L0_ACTIVE); +#else + DAL_PCDEx_LPM_Callback(hpcd, PCD_LPM_L0_ACTIVE); +#endif /* USE_DAL_PCD_REGISTER_CALLBACKS */ + } + else + { +#if (USE_DAL_PCD_REGISTER_CALLBACKS == 1U) + hpcd->ResumeCallback(hpcd); +#else + DAL_PCD_ResumeCallback(hpcd); +#endif /* USE_DAL_PCD_REGISTER_CALLBACKS */ + } + + __DAL_PCD_CLEAR_FLAG(hpcd, USB_OTG_GCINT_RWAKE); + } + + /* Handle Suspend Interrupt */ + if (__DAL_PCD_GET_FLAG(hpcd, USB_OTG_GCINT_USBSUS)) + { + if ((USBx_DEVICE->DSTS & USB_OTG_DSTS_SUSSTS) == USB_OTG_DSTS_SUSSTS) + { +#if (USE_DAL_PCD_REGISTER_CALLBACKS == 1U) + hpcd->SuspendCallback(hpcd); +#else + DAL_PCD_SuspendCallback(hpcd); +#endif /* USE_DAL_PCD_REGISTER_CALLBACKS */ + } + __DAL_PCD_CLEAR_FLAG(hpcd, USB_OTG_GCINT_USBSUS); + } + + /* Handle Reset Interrupt */ + if (__DAL_PCD_GET_FLAG(hpcd, USB_OTG_GCINT_USBRST)) + { + USBx_DEVICE->DCTRL &= ~USB_OTG_DCTRL_RWKUPS; + (void)USB_FlushTxFifo(hpcd->Instance, 0x10U); + + for (i = 0U; i < hpcd->Init.dev_endpoints; i++) + { + USBx_INEP(i)->DIEPINT = 0xFB7FU; + USBx_INEP(i)->DIEPCTRL &= ~USB_OTG_DIEPCTRL_STALLH; + USBx_OUTEP(i)->DOEPINT = 0xFB7FU; + USBx_OUTEP(i)->DOEPCTRL &= ~USB_OTG_DOEPCTRL_STALLH; + USBx_OUTEP(i)->DOEPCTRL |= USB_OTG_DOEPCTRL_NAKSET; + } + USBx_DEVICE->DAEPIMASK |= 0x10001U; + + if (hpcd->Init.use_dedicated_ep1 != 0U) + { + USBx_DEVICE->DOUT1MASK |= USB_OTG_DOUTIMASK_SETPCMPM | + USB_OTG_DOUTIMASK_TSFCMPM | + USB_OTG_DOUTIMASK_EPDISM; + + USBx_DEVICE->DEPIMASK |= USB_OTG_DINIMASK_TOM | + USB_OTG_DINIMASK_TSFCMPM | + USB_OTG_DINIMASK_EPDISM; + } + else + { + USBx_DEVICE->DOUTIMASK |= USB_OTG_DOUTIMASK_SETPCMPM | + USB_OTG_DOUTIMASK_TSFCMPM | + USB_OTG_DOUTIMASK_EPDISM | + USB_OTG_DOUTIMASK_OTEPSPRM | + USB_OTG_DOUTIMASK_NAKM; + + USBx_DEVICE->DINIMASK |= USB_OTG_DINIMASK_TOM | + USB_OTG_DINIMASK_TSFCMPM | + USB_OTG_DINIMASK_EPDISM; + } + + /* Set Default Address to 0 */ + USBx_DEVICE->DCFG &= ~USB_OTG_DCFG_DADDR; + + /* setup EP0 to receive SETUP packets */ + (void)USB_EP0_OutStart(hpcd->Instance, (uint8_t)hpcd->Init.dma_enable, + (uint8_t *)hpcd->Setup); + + __DAL_PCD_CLEAR_FLAG(hpcd, USB_OTG_GCINT_USBRST); + } + + /* Handle Enumeration done Interrupt */ + if (__DAL_PCD_GET_FLAG(hpcd, USB_OTG_GCINT_ENUMD)) + { + (void)USB_ActivateSetup(hpcd->Instance); + hpcd->Init.speed = USB_GetDevSpeed(hpcd->Instance); + + /* Set USB Turnaround time */ + (void)USB_SetTurnaroundTime(hpcd->Instance, + DAL_RCM_GetHCLKFreq(), + (uint8_t)hpcd->Init.speed); + +#if (USE_DAL_PCD_REGISTER_CALLBACKS == 1U) + hpcd->ResetCallback(hpcd); +#else + DAL_PCD_ResetCallback(hpcd); +#endif /* USE_DAL_PCD_REGISTER_CALLBACKS */ + + __DAL_PCD_CLEAR_FLAG(hpcd, USB_OTG_GCINT_ENUMD); + } + + /* Handle SOF Interrupt */ + if (__DAL_PCD_GET_FLAG(hpcd, USB_OTG_GCINT_SOF)) + { +#if (USE_DAL_PCD_REGISTER_CALLBACKS == 1U) + hpcd->SOFCallback(hpcd); +#else + DAL_PCD_SOFCallback(hpcd); +#endif /* USE_DAL_PCD_REGISTER_CALLBACKS */ + + __DAL_PCD_CLEAR_FLAG(hpcd, USB_OTG_GCINT_SOF); + } + + /* Handle Global OUT NAK effective Interrupt */ + if (__DAL_PCD_GET_FLAG(hpcd, USB_OTG_GCINT_GONAKE)) + { + USBx->GINTMASK &= ~USB_OTG_GINTMASK_GONAKEM; + + for (epnum = 1U; epnum < hpcd->Init.dev_endpoints; epnum++) + { + if (hpcd->OUT_ep[epnum].is_iso_incomplete == 1U) + { + /* Abort current transaction and disable the EP */ + (void)DAL_PCD_EP_Abort(hpcd, (uint8_t)epnum); + } + } + } + + /* Handle Incomplete ISO IN Interrupt */ + if (__DAL_PCD_GET_FLAG(hpcd, USB_OTG_GCINT_IIINTX)) + { + for (epnum = 1U; epnum < hpcd->Init.dev_endpoints; epnum++) + { + RegVal = USBx_INEP(epnum)->DIEPCTRL; + + if ((hpcd->IN_ep[epnum].type == EP_TYPE_ISOC) && + ((RegVal & USB_OTG_DIEPCTRL_EPEN) == USB_OTG_DIEPCTRL_EPEN)) + { + hpcd->IN_ep[epnum].is_iso_incomplete = 1U; + + /* Abort current transaction and disable the EP */ + (void)DAL_PCD_EP_Abort(hpcd, (uint8_t)(epnum | 0x80U)); + } + } + + __DAL_PCD_CLEAR_FLAG(hpcd, USB_OTG_GCINT_IIINTX); + } + + /* Handle Incomplete ISO OUT Interrupt */ + if (__DAL_PCD_GET_FLAG(hpcd, USB_OTG_GCINT_IP_OUTTX)) + { + for (epnum = 1U; epnum < hpcd->Init.dev_endpoints; epnum++) + { + RegVal = USBx_OUTEP(epnum)->DOEPCTRL; + + if ((hpcd->OUT_ep[epnum].type == EP_TYPE_ISOC) && + ((RegVal & USB_OTG_DOEPCTRL_EPEN) == USB_OTG_DOEPCTRL_EPEN) && + ((RegVal & (0x1U << 16)) == (hpcd->FrameNumber & 0x1U))) + { + hpcd->OUT_ep[epnum].is_iso_incomplete = 1U; + + USBx->GINTMASK |= USB_OTG_GINTMASK_GONAKEM; + + if ((USBx->GCINT & USB_OTG_GCINT_GONAKE) == 0U) + { + USBx_DEVICE->DCTRL |= USB_OTG_DCTRL_GONAKSET; + break; + } + } + } + + __DAL_PCD_CLEAR_FLAG(hpcd, USB_OTG_GCINT_IP_OUTTX); + } + + /* Handle Connection event Interrupt */ + if (__DAL_PCD_GET_FLAG(hpcd, USB_OTG_GCINT_SREQ)) + { +#if (USE_DAL_PCD_REGISTER_CALLBACKS == 1U) + hpcd->ConnectCallback(hpcd); +#else + DAL_PCD_ConnectCallback(hpcd); +#endif /* USE_DAL_PCD_REGISTER_CALLBACKS */ + + __DAL_PCD_CLEAR_FLAG(hpcd, USB_OTG_GCINT_SREQ); + } + + /* Handle Disconnection event Interrupt */ + if (__DAL_PCD_GET_FLAG(hpcd, USB_OTG_GCINT_OTG)) + { + RegVal = hpcd->Instance->GINT; + + if ((RegVal & USB_OTG_GINT_SEFLG) == USB_OTG_GINT_SEFLG) + { +#if (USE_DAL_PCD_REGISTER_CALLBACKS == 1U) + hpcd->DisconnectCallback(hpcd); +#else + DAL_PCD_DisconnectCallback(hpcd); +#endif /* USE_DAL_PCD_REGISTER_CALLBACKS */ + } + hpcd->Instance->GINT |= RegVal; + } + } +} + + +/** + * @brief Handles PCD Wakeup interrupt request. + * @param hpcd PCD handle + * @retval DAL status + */ +void DAL_PCD_WKUP_IRQHandler(PCD_HandleTypeDef *hpcd) +{ + USB_OTG_GlobalTypeDef *USBx; + + USBx = hpcd->Instance; + + if ((USBx->GCID & (0x1U << 8)) == 0U) + { + /* Clear EINT pending Bit */ + __DAL_USB_OTG_FS_WAKEUP_EINT_CLEAR_FLAG(); + } + else + { + /* Clear EINT pending Bit */ + __DAL_USB_OTG_HS_WAKEUP_EINT_CLEAR_FLAG(); + } +} +#endif /* defined (USB_OTG_FS) || defined (USB_OTG_HS) */ + + +/** + * @brief Data OUT stage callback. + * @param hpcd PCD handle + * @param epnum endpoint number + * @retval None + */ +__weak void DAL_PCD_DataOutStageCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hpcd); + UNUSED(epnum); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_PCD_DataOutStageCallback could be implemented in the user file + */ +} + +/** + * @brief Data IN stage callback + * @param hpcd PCD handle + * @param epnum endpoint number + * @retval None + */ +__weak void DAL_PCD_DataInStageCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hpcd); + UNUSED(epnum); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_PCD_DataInStageCallback could be implemented in the user file + */ +} +/** + * @brief Setup stage callback + * @param hpcd PCD handle + * @retval None + */ +__weak void DAL_PCD_SetupStageCallback(PCD_HandleTypeDef *hpcd) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hpcd); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_PCD_SetupStageCallback could be implemented in the user file + */ +} + +/** + * @brief USB Start Of Frame callback. + * @param hpcd PCD handle + * @retval None + */ +__weak void DAL_PCD_SOFCallback(PCD_HandleTypeDef *hpcd) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hpcd); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_PCD_SOFCallback could be implemented in the user file + */ +} + +/** + * @brief USB Reset callback. + * @param hpcd PCD handle + * @retval None + */ +__weak void DAL_PCD_ResetCallback(PCD_HandleTypeDef *hpcd) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hpcd); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_PCD_ResetCallback could be implemented in the user file + */ +} + +/** + * @brief Suspend event callback. + * @param hpcd PCD handle + * @retval None + */ +__weak void DAL_PCD_SuspendCallback(PCD_HandleTypeDef *hpcd) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hpcd); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_PCD_SuspendCallback could be implemented in the user file + */ +} + +/** + * @brief Resume event callback. + * @param hpcd PCD handle + * @retval None + */ +__weak void DAL_PCD_ResumeCallback(PCD_HandleTypeDef *hpcd) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hpcd); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_PCD_ResumeCallback could be implemented in the user file + */ +} + +/** + * @brief Incomplete ISO OUT callback. + * @param hpcd PCD handle + * @param epnum endpoint number + * @retval None + */ +__weak void DAL_PCD_ISOOUTIncompleteCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hpcd); + UNUSED(epnum); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_PCD_ISOOUTIncompleteCallback could be implemented in the user file + */ +} + +/** + * @brief Incomplete ISO IN callback. + * @param hpcd PCD handle + * @param epnum endpoint number + * @retval None + */ +__weak void DAL_PCD_ISOINIncompleteCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hpcd); + UNUSED(epnum); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_PCD_ISOINIncompleteCallback could be implemented in the user file + */ +} + +/** + * @brief Connection event callback. + * @param hpcd PCD handle + * @retval None + */ +__weak void DAL_PCD_ConnectCallback(PCD_HandleTypeDef *hpcd) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hpcd); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_PCD_ConnectCallback could be implemented in the user file + */ +} + +/** + * @brief Disconnection event callback. + * @param hpcd PCD handle + * @retval None + */ +__weak void DAL_PCD_DisconnectCallback(PCD_HandleTypeDef *hpcd) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hpcd); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_PCD_DisconnectCallback could be implemented in the user file + */ +} + +/** + * @} + */ + +/** @defgroup PCD_Exported_Functions_Group3 Peripheral Control functions + * @brief management functions + * +@verbatim + =============================================================================== + ##### Peripheral Control functions ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to control the PCD data + transfers. + +@endverbatim + * @{ + */ + +/** + * @brief Connect the USB device + * @param hpcd PCD handle + * @retval DAL status + */ +DAL_StatusTypeDef DAL_PCD_DevConnect(PCD_HandleTypeDef *hpcd) +{ + USB_OTG_GlobalTypeDef *USBx = hpcd->Instance; + + __DAL_LOCK(hpcd); + + if ((hpcd->Init.battery_charging_enable == 1U) && + (hpcd->Init.phy_itface != USB_OTG_ULPI_PHY)) + { + /* Enable USB Transceiver */ + USBx->GGCCFG |= USB_OTG_GGCCFG_PWEN; + } + (void)USB_DevConnect(hpcd->Instance); + __DAL_UNLOCK(hpcd); + + return DAL_OK; +} + +/** + * @brief Disconnect the USB device. + * @param hpcd PCD handle + * @retval DAL status + */ +DAL_StatusTypeDef DAL_PCD_DevDisconnect(PCD_HandleTypeDef *hpcd) +{ + USB_OTG_GlobalTypeDef *USBx = hpcd->Instance; + + __DAL_LOCK(hpcd); + (void)USB_DevDisconnect(hpcd->Instance); + + if ((hpcd->Init.battery_charging_enable == 1U) && + (hpcd->Init.phy_itface != USB_OTG_ULPI_PHY)) + { + /* Disable USB Transceiver */ + USBx->GGCCFG &= ~(USB_OTG_GGCCFG_PWEN); + } + + __DAL_UNLOCK(hpcd); + + return DAL_OK; +} + +/** + * @brief Set the USB Device address. + * @param hpcd PCD handle + * @param address new device address + * @retval DAL status + */ +DAL_StatusTypeDef DAL_PCD_SetAddress(PCD_HandleTypeDef *hpcd, uint8_t address) +{ + __DAL_LOCK(hpcd); + hpcd->USB_Address = address; + (void)USB_SetDevAddress(hpcd->Instance, address); + __DAL_UNLOCK(hpcd); + + return DAL_OK; +} +/** + * @brief Open and configure an endpoint. + * @param hpcd PCD handle + * @param ep_addr endpoint address + * @param ep_mps endpoint max packet size + * @param ep_type endpoint type + * @retval DAL status + */ +DAL_StatusTypeDef DAL_PCD_EP_Open(PCD_HandleTypeDef *hpcd, uint8_t ep_addr, + uint16_t ep_mps, uint8_t ep_type) +{ + DAL_StatusTypeDef ret = DAL_OK; + PCD_EPTypeDef *ep; + + if ((ep_addr & 0x80U) == 0x80U) + { + ep = &hpcd->IN_ep[ep_addr & EP_ADDR_MSK]; + ep->is_in = 1U; + } + else + { + ep = &hpcd->OUT_ep[ep_addr & EP_ADDR_MSK]; + ep->is_in = 0U; + } + + ep->num = ep_addr & EP_ADDR_MSK; + ep->maxpacket = ep_mps; + ep->type = ep_type; + + if (ep->is_in != 0U) + { + /* Assign a Tx FIFO */ + ep->tx_fifo_num = ep->num; + } + /* Set initial data PID. */ + if (ep_type == EP_TYPE_BULK) + { + ep->data_pid_start = 0U; + } + + __DAL_LOCK(hpcd); + (void)USB_ActivateEndpoint(hpcd->Instance, ep); + __DAL_UNLOCK(hpcd); + + return ret; +} + +/** + * @brief Deactivate an endpoint. + * @param hpcd PCD handle + * @param ep_addr endpoint address + * @retval DAL status + */ +DAL_StatusTypeDef DAL_PCD_EP_Close(PCD_HandleTypeDef *hpcd, uint8_t ep_addr) +{ + PCD_EPTypeDef *ep; + + if ((ep_addr & 0x80U) == 0x80U) + { + ep = &hpcd->IN_ep[ep_addr & EP_ADDR_MSK]; + ep->is_in = 1U; + } + else + { + ep = &hpcd->OUT_ep[ep_addr & EP_ADDR_MSK]; + ep->is_in = 0U; + } + ep->num = ep_addr & EP_ADDR_MSK; + + __DAL_LOCK(hpcd); + (void)USB_DeactivateEndpoint(hpcd->Instance, ep); + __DAL_UNLOCK(hpcd); + return DAL_OK; +} + + +/** + * @brief Receive an amount of data. + * @param hpcd PCD handle + * @param ep_addr endpoint address + * @param pBuf pointer to the reception buffer + * @param len amount of data to be received + * @retval DAL status + */ +DAL_StatusTypeDef DAL_PCD_EP_Receive(PCD_HandleTypeDef *hpcd, uint8_t ep_addr, uint8_t *pBuf, uint32_t len) +{ + PCD_EPTypeDef *ep; + + ep = &hpcd->OUT_ep[ep_addr & EP_ADDR_MSK]; + + /*setup and start the Xfer */ + ep->xfer_buff = pBuf; + ep->xfer_len = len; + ep->xfer_count = 0U; + ep->is_in = 0U; + ep->num = ep_addr & EP_ADDR_MSK; + + if (hpcd->Init.dma_enable == 1U) + { + ep->dma_addr = (uint32_t)pBuf; + } + + if ((ep_addr & EP_ADDR_MSK) == 0U) + { + (void)USB_EP0StartXfer(hpcd->Instance, ep, (uint8_t)hpcd->Init.dma_enable); + } + else + { + (void)USB_EPStartXfer(hpcd->Instance, ep, (uint8_t)hpcd->Init.dma_enable); + } + + return DAL_OK; +} + +/** + * @brief Get Received Data Size + * @param hpcd PCD handle + * @param ep_addr endpoint address + * @retval Data Size + */ +uint32_t DAL_PCD_EP_GetRxCount(PCD_HandleTypeDef *hpcd, uint8_t ep_addr) +{ + return hpcd->OUT_ep[ep_addr & EP_ADDR_MSK].xfer_count; +} +/** + * @brief Send an amount of data + * @param hpcd PCD handle + * @param ep_addr endpoint address + * @param pBuf pointer to the transmission buffer + * @param len amount of data to be sent + * @retval DAL status + */ +DAL_StatusTypeDef DAL_PCD_EP_Transmit(PCD_HandleTypeDef *hpcd, uint8_t ep_addr, uint8_t *pBuf, uint32_t len) +{ + PCD_EPTypeDef *ep; + + ep = &hpcd->IN_ep[ep_addr & EP_ADDR_MSK]; + + /*setup and start the Xfer */ + ep->xfer_buff = pBuf; + ep->xfer_len = len; + ep->xfer_count = 0U; + ep->is_in = 1U; + ep->num = ep_addr & EP_ADDR_MSK; + + if (hpcd->Init.dma_enable == 1U) + { + ep->dma_addr = (uint32_t)pBuf; + } + + if ((ep_addr & EP_ADDR_MSK) == 0U) + { + (void)USB_EP0StartXfer(hpcd->Instance, ep, (uint8_t)hpcd->Init.dma_enable); + } + else + { + (void)USB_EPStartXfer(hpcd->Instance, ep, (uint8_t)hpcd->Init.dma_enable); + } + + return DAL_OK; +} + +/** + * @brief Set a STALL condition over an endpoint + * @param hpcd PCD handle + * @param ep_addr endpoint address + * @retval DAL status + */ +DAL_StatusTypeDef DAL_PCD_EP_SetStall(PCD_HandleTypeDef *hpcd, uint8_t ep_addr) +{ + PCD_EPTypeDef *ep; + + if (((uint32_t)ep_addr & EP_ADDR_MSK) > hpcd->Init.dev_endpoints) + { + return DAL_ERROR; + } + + if ((0x80U & ep_addr) == 0x80U) + { + ep = &hpcd->IN_ep[ep_addr & EP_ADDR_MSK]; + ep->is_in = 1U; + } + else + { + ep = &hpcd->OUT_ep[ep_addr]; + ep->is_in = 0U; + } + + ep->is_stall = 1U; + ep->num = ep_addr & EP_ADDR_MSK; + + __DAL_LOCK(hpcd); + + (void)USB_EPSetStall(hpcd->Instance, ep); + + if ((ep_addr & EP_ADDR_MSK) == 0U) + { + (void)USB_EP0_OutStart(hpcd->Instance, (uint8_t)hpcd->Init.dma_enable, (uint8_t *)hpcd->Setup); + } + + __DAL_UNLOCK(hpcd); + + return DAL_OK; +} + +/** + * @brief Clear a STALL condition over in an endpoint + * @param hpcd PCD handle + * @param ep_addr endpoint address + * @retval DAL status + */ +DAL_StatusTypeDef DAL_PCD_EP_ClrStall(PCD_HandleTypeDef *hpcd, uint8_t ep_addr) +{ + PCD_EPTypeDef *ep; + + if (((uint32_t)ep_addr & 0x0FU) > hpcd->Init.dev_endpoints) + { + return DAL_ERROR; + } + + if ((0x80U & ep_addr) == 0x80U) + { + ep = &hpcd->IN_ep[ep_addr & EP_ADDR_MSK]; + ep->is_in = 1U; + } + else + { + ep = &hpcd->OUT_ep[ep_addr & EP_ADDR_MSK]; + ep->is_in = 0U; + } + + ep->is_stall = 0U; + ep->num = ep_addr & EP_ADDR_MSK; + + __DAL_LOCK(hpcd); + (void)USB_EPClearStall(hpcd->Instance, ep); + __DAL_UNLOCK(hpcd); + + return DAL_OK; +} + + +/** + * @brief USB device get EP stall status + * + * @param usbdh: USB device handler + * + * @param epAddr: endpoint address + * + * @retval Stall status + */ +uint8_t DAL_PCD_EP_ReadStallStatus(PCD_HandleTypeDef *hpcd, uint8_t epAddr) +{ + if ((epAddr & 0x80) == 0x80) + { + return (hpcd->IN_ep[epAddr & 0x7F].is_stall); + } + else + { + return (hpcd->OUT_ep[epAddr & 0x7F].is_stall); + } +} + +/** + * @brief Abort an USB EP transaction. + * @param hpcd PCD handle + * @param ep_addr endpoint address + * @retval DAL status + */ +DAL_StatusTypeDef DAL_PCD_EP_Abort(PCD_HandleTypeDef *hpcd, uint8_t ep_addr) +{ + DAL_StatusTypeDef ret; + PCD_EPTypeDef *ep; + + if ((0x80U & ep_addr) == 0x80U) + { + ep = &hpcd->IN_ep[ep_addr & EP_ADDR_MSK]; + } + else + { + ep = &hpcd->OUT_ep[ep_addr & EP_ADDR_MSK]; + } + + /* Stop Xfer */ + ret = USB_EPStopXfer(hpcd->Instance, ep); + + return ret; +} + +/** + * @brief Flush an endpoint + * @param hpcd PCD handle + * @param ep_addr endpoint address + * @retval DAL status + */ +DAL_StatusTypeDef DAL_PCD_EP_Flush(PCD_HandleTypeDef *hpcd, uint8_t ep_addr) +{ + __DAL_LOCK(hpcd); + + if ((ep_addr & 0x80U) == 0x80U) + { + (void)USB_FlushTxFifo(hpcd->Instance, (uint32_t)ep_addr & EP_ADDR_MSK); + } + else + { + (void)USB_FlushRxFifo(hpcd->Instance); + } + + __DAL_UNLOCK(hpcd); + + return DAL_OK; +} + +/** + * @brief Activate remote wakeup signalling + * @param hpcd PCD handle + * @retval DAL status + */ +DAL_StatusTypeDef DAL_PCD_ActivateRemoteWakeup(PCD_HandleTypeDef *hpcd) +{ + return (USB_ActivateRemoteWakeup(hpcd->Instance)); +} + +/** + * @brief De-activate remote wakeup signalling. + * @param hpcd PCD handle + * @retval DAL status + */ +DAL_StatusTypeDef DAL_PCD_DeActivateRemoteWakeup(PCD_HandleTypeDef *hpcd) +{ + return (USB_DeActivateRemoteWakeup(hpcd->Instance)); +} + +/** + * @} + */ + +/** @defgroup PCD_Exported_Functions_Group4 Peripheral State functions + * @brief Peripheral State functions + * +@verbatim + =============================================================================== + ##### Peripheral State functions ##### + =============================================================================== + [..] + This subsection permits to get in run-time the status of the peripheral + and the data flow. + +@endverbatim + * @{ + */ + +/** + * @brief Return the PCD handle state. + * @param hpcd PCD handle + * @retval DAL state + */ +PCD_StateTypeDef DAL_PCD_GetState(PCD_HandleTypeDef *hpcd) +{ + return hpcd->State; +} + +/** + * @brief Set the USB Device high speed test mode. + * @param hpcd PCD handle + * @param testmode USB Device high speed test mode + * @retval DAL status + */ +DAL_StatusTypeDef DAL_PCD_SetTestMode(PCD_HandleTypeDef *hpcd, uint8_t testmode) +{ + USB_OTG_GlobalTypeDef *USBx = hpcd->Instance; + uint32_t USBx_BASE = (uint32_t)USBx; + + switch (testmode) + { + case TEST_J: + case TEST_K: + case TEST_SE0_NAK: + case TEST_PACKET: + case TEST_FORCE_EN: + USBx_DEVICE->DCTRL |= (uint32_t)testmode << 4; + break; + + default: + break; + } + + return DAL_OK; +} +/** + * @} + */ + +/** + * @} + */ + +/* Private functions ---------------------------------------------------------*/ +/** @addtogroup PCD_Private_Functions + * @{ + */ +#if defined (USB_OTG_FS) || defined (USB_OTG_HS) +/** + * @brief Check FIFO for the next packet to be loaded. + * @param hpcd PCD handle + * @param epnum endpoint number + * @retval DAL status + */ +static DAL_StatusTypeDef PCD_WriteEmptyTxFifo(PCD_HandleTypeDef *hpcd, uint32_t epnum) +{ + USB_OTG_GlobalTypeDef *USBx = hpcd->Instance; + uint32_t USBx_BASE = (uint32_t)USBx; + USB_OTG_EPTypeDef *ep; + uint32_t len; + uint32_t len32b; + uint32_t fifoemptymsk; + + ep = &hpcd->IN_ep[epnum]; + + if (ep->xfer_count > ep->xfer_len) + { + return DAL_ERROR; + } + + len = ep->xfer_len - ep->xfer_count; + + if (len > ep->maxpacket) + { + len = ep->maxpacket; + } + + len32b = (len + 3U) / 4U; + + while (((USBx_INEP(epnum)->DITXFSTS & USB_OTG_DITXFSTS_INEPTXFSA) >= len32b) && + (ep->xfer_count < ep->xfer_len) && (ep->xfer_len != 0U)) + { + /* Write the FIFO */ + len = ep->xfer_len - ep->xfer_count; + + if (len > ep->maxpacket) + { + len = ep->maxpacket; + } + len32b = (len + 3U) / 4U; + + (void)USB_WritePacket(USBx, ep->xfer_buff, (uint8_t)epnum, (uint16_t)len, + (uint8_t)hpcd->Init.dma_enable); + + ep->xfer_buff += len; + ep->xfer_count += len; + } + + if (ep->xfer_len <= ep->xfer_count) + { + fifoemptymsk = (uint32_t)(0x1UL << (epnum & EP_ADDR_MSK)); + USBx_DEVICE->DIEIMASK &= ~fifoemptymsk; + } + + return DAL_OK; +} + + +/** + * @brief process EP OUT transfer complete interrupt. + * @param hpcd PCD handle + * @param epnum endpoint number + * @retval DAL status + */ +static DAL_StatusTypeDef PCD_EP_OutXfrComplete_int(PCD_HandleTypeDef *hpcd, uint32_t epnum) +{ + USB_OTG_EPTypeDef *ep; + USB_OTG_GlobalTypeDef *USBx = hpcd->Instance; + uint32_t USBx_BASE = (uint32_t)USBx; + uint32_t gSNPSiD = *(__IO uint32_t *)(&USBx->GCID + 0x1U); + uint32_t DoepintReg = USBx_OUTEP(epnum)->DOEPINT; + + if (hpcd->Init.dma_enable == 1U) + { + if ((DoepintReg & USB_OTG_DOEPINT_SETPCMP) == USB_OTG_DOEPINT_SETPCMP) /* Class C */ + { + /* StupPktRcvd = 1 this is a setup packet */ + if ((gSNPSiD > USB_OTG_CORE_ID_300A) && + ((DoepintReg & USB_OTG_DOEPINT_STPKTRX) == USB_OTG_DOEPINT_STPKTRX)) + { + CLEAR_OUT_EP_INTR(epnum, USB_OTG_DOEPINT_STPKTRX); + } + } + else if ((DoepintReg & USB_OTG_DOEPINT_OTEPSPR) == USB_OTG_DOEPINT_OTEPSPR) /* Class E */ + { + CLEAR_OUT_EP_INTR(epnum, USB_OTG_DOEPINT_OTEPSPR); + } + else if ((DoepintReg & (USB_OTG_DOEPINT_SETPCMP | USB_OTG_DOEPINT_OTEPSPR)) == 0U) + { + /* StupPktRcvd = 1 this is a setup packet */ + if ((gSNPSiD > USB_OTG_CORE_ID_300A) && + ((DoepintReg & USB_OTG_DOEPINT_STPKTRX) == USB_OTG_DOEPINT_STPKTRX)) + { + CLEAR_OUT_EP_INTR(epnum, USB_OTG_DOEPINT_STPKTRX); + } + else + { + ep = &hpcd->OUT_ep[epnum]; + + /* out data packet received over EP */ + ep->xfer_count = ep->xfer_size - (USBx_OUTEP(epnum)->DOEPTRS & USB_OTG_DOEPTRS_EPTRS); + + if (epnum == 0U) + { + if (ep->xfer_len == 0U) + { + /* this is ZLP, so prepare EP0 for next setup */ + (void)USB_EP0_OutStart(hpcd->Instance, 1U, (uint8_t *)hpcd->Setup); + } + else + { + ep->xfer_buff += ep->xfer_count; + } + } + +#if (USE_DAL_PCD_REGISTER_CALLBACKS == 1U) + hpcd->DataOutStageCallback(hpcd, (uint8_t)epnum); +#else + DAL_PCD_DataOutStageCallback(hpcd, (uint8_t)epnum); +#endif /* USE_DAL_PCD_REGISTER_CALLBACKS */ + } + } + else + { + /* ... */ + } + } + else + { + if (gSNPSiD == USB_OTG_CORE_ID_310A) + { + /* StupPktRcvd = 1 this is a setup packet */ + if ((DoepintReg & USB_OTG_DOEPINT_STPKTRX) == USB_OTG_DOEPINT_STPKTRX) + { + CLEAR_OUT_EP_INTR(epnum, USB_OTG_DOEPINT_STPKTRX); + } + else + { + if ((DoepintReg & USB_OTG_DOEPINT_OTEPSPR) == USB_OTG_DOEPINT_OTEPSPR) + { + CLEAR_OUT_EP_INTR(epnum, USB_OTG_DOEPINT_OTEPSPR); + } + +#if (USE_DAL_PCD_REGISTER_CALLBACKS == 1U) + hpcd->DataOutStageCallback(hpcd, (uint8_t)epnum); +#else + DAL_PCD_DataOutStageCallback(hpcd, (uint8_t)epnum); +#endif /* USE_DAL_PCD_REGISTER_CALLBACKS */ + } + } + else + { + if ((epnum == 0U) && (hpcd->OUT_ep[epnum].xfer_len == 0U)) + { + /* this is ZLP, so prepare EP0 for next setup */ + (void)USB_EP0_OutStart(hpcd->Instance, 0U, (uint8_t *)hpcd->Setup); + } + +#if (USE_DAL_PCD_REGISTER_CALLBACKS == 1U) + hpcd->DataOutStageCallback(hpcd, (uint8_t)epnum); +#else + DAL_PCD_DataOutStageCallback(hpcd, (uint8_t)epnum); +#endif /* USE_DAL_PCD_REGISTER_CALLBACKS */ + } + } + + return DAL_OK; +} + + +/** + * @brief process EP OUT setup packet received interrupt. + * @param hpcd PCD handle + * @param epnum endpoint number + * @retval DAL status + */ +static DAL_StatusTypeDef PCD_EP_OutSetupPacket_int(PCD_HandleTypeDef *hpcd, uint32_t epnum) +{ + USB_OTG_GlobalTypeDef *USBx = hpcd->Instance; + uint32_t USBx_BASE = (uint32_t)USBx; + uint32_t gSNPSiD = *(__IO uint32_t *)(&USBx->GCID + 0x1U); + uint32_t DoepintReg = USBx_OUTEP(epnum)->DOEPINT; + + if ((gSNPSiD > USB_OTG_CORE_ID_300A) && + ((DoepintReg & USB_OTG_DOEPINT_STPKTRX) == USB_OTG_DOEPINT_STPKTRX)) + { + CLEAR_OUT_EP_INTR(epnum, USB_OTG_DOEPINT_STPKTRX); + } + + /* Inform the upper layer that a setup packet is available */ +#if (USE_DAL_PCD_REGISTER_CALLBACKS == 1U) + hpcd->SetupStageCallback(hpcd); +#else + DAL_PCD_SetupStageCallback(hpcd); +#endif /* USE_DAL_PCD_REGISTER_CALLBACKS */ + + if ((gSNPSiD > USB_OTG_CORE_ID_300A) && (hpcd->Init.dma_enable == 1U)) + { + (void)USB_EP0_OutStart(hpcd->Instance, 1U, (uint8_t *)hpcd->Setup); + } + + return DAL_OK; +} +#endif /* defined (USB_OTG_FS) || defined (USB_OTG_HS) */ + + +/** + * @} + */ +#endif /* defined (USB_OTG_FS) || defined (USB_OTG_HS) */ +#endif /* DAL_PCD_MODULE_ENABLED */ + +/** + * @} + */ + +/** + * @} + */ diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_pcd_ex.c b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_pcd_ex.c new file mode 100644 index 0000000000..9c2d45884d --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_pcd_ex.c @@ -0,0 +1,196 @@ +/** + * + * @file apm32f4xx_dal_pcd_ex.c + * @brief PCD Extended DAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the USB Peripheral Controller: + * + Extended features functions + * + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + * + */ + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @defgroup PCDEx PCDEx + * @brief PCD Extended DAL module driver + * @{ + */ + +#ifdef DAL_PCD_MODULE_ENABLED + +#if defined (USB_OTG_FS) || defined (USB_OTG_HS) +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/* Private macros ------------------------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ +/* Exported functions --------------------------------------------------------*/ + +/** @defgroup PCDEx_Exported_Functions PCDEx Exported Functions + * @{ + */ + +/** @defgroup PCDEx_Exported_Functions_Group1 Peripheral Control functions + * @brief PCDEx control functions + * +@verbatim + =============================================================================== + ##### Extended features functions ##### + =============================================================================== + [..] This section provides functions allowing to: + (+) Update FIFO configuration + +@endverbatim + * @{ + */ +#if defined (USB_OTG_FS) || defined (USB_OTG_HS) +/** + * @brief Set Tx FIFO + * @param hpcd PCD handle + * @param fifo The number of Tx fifo + * @param size Fifo size + * @retval DAL status + */ +DAL_StatusTypeDef DAL_PCDEx_SetTxFiFo(PCD_HandleTypeDef *hpcd, uint8_t fifo, uint16_t size) +{ + uint8_t i; + uint32_t Tx_Offset; + + /* TXn min size = 16 words. (n : Transmit FIFO index) + When a TxFIFO is not used, the Configuration should be as follows: + case 1 : n > m and Txn is not used (n,m : Transmit FIFO indexes) + --> Txm can use the space allocated for Txn. + case2 : n < m and Txn is not used (n,m : Transmit FIFO indexes) + --> Txn should be configured with the minimum space of 16 words + The FIFO is used optimally when used TxFIFOs are allocated in the top + of the FIFO.Ex: use EP1 and EP2 as IN instead of EP1 and EP3 as IN ones. + When DMA is used 3n * FIFO locations should be reserved for internal DMA registers */ + + Tx_Offset = hpcd->Instance->GRXFIFO; + + if (fifo == 0U) + { + hpcd->Instance->GTXFCFG = ((uint32_t)size << 16) | Tx_Offset; + } + else + { + Tx_Offset += (hpcd->Instance->GTXFCFG) >> 16; + for (i = 0U; i < (fifo - 1U); i++) + { + Tx_Offset += (hpcd->Instance->DTXFIFO[i] >> 16); + } + + /* Multiply Tx_Size by 2 to get higher performance */ + hpcd->Instance->DTXFIFO[fifo - 1U] = ((uint32_t)size << 16) | Tx_Offset; + } + + return DAL_OK; +} + +/** + * @brief Set Rx FIFO + * @param hpcd PCD handle + * @param size Size of Rx fifo + * @retval DAL status + */ +DAL_StatusTypeDef DAL_PCDEx_SetRxFiFo(PCD_HandleTypeDef *hpcd, uint16_t size) +{ + hpcd->Instance->GRXFIFO = size; + + return DAL_OK; +} + +#endif /* defined (USB_OTG_FS) || defined (USB_OTG_HS) */ + +/** + * @brief Send LPM message to user layer callback. + * @param hpcd PCD handle + * @param msg LPM message + * @retval DAL status + */ +__weak void DAL_PCDEx_LPM_Callback(PCD_HandleTypeDef *hpcd, PCD_LPM_MsgTypeDef msg) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hpcd); + UNUSED(msg); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_PCDEx_LPM_Callback could be implemented in the user file + */ +} + +/** + * @brief Send BatteryCharging message to user layer callback. + * @param hpcd PCD handle + * @param msg LPM message + * @retval DAL status + */ +__weak void DAL_PCDEx_BCD_Callback(PCD_HandleTypeDef *hpcd, PCD_BCD_MsgTypeDef msg) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hpcd); + UNUSED(msg); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_PCDEx_BCD_Callback could be implemented in the user file + */ +} + +/** + * @} + */ + +/** + * @} + */ +#endif /* defined (USB_OTG_FS) || defined (USB_OTG_HS) */ +#endif /* DAL_PCD_MODULE_ENABLED */ + +/** + * @} + */ + +/** + * @} + */ diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_pmu.c b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_pmu.c new file mode 100644 index 0000000000..fa1421ab2d --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_pmu.c @@ -0,0 +1,591 @@ +/** + * + * @file apm32f4xx_dal_pmu.c + * @author MCD Application Team + * @brief PMU DAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the Power Controller (PMU) peripheral: + * + Initialization and de-initialization functions + * + Peripheral Control functions + * + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2017 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file in + * the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + */ + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @defgroup PMU PMU + * @brief PMU DAL module driver + * @{ + */ + +#ifdef DAL_PMU_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/** @addtogroup PMU_Private_Constants + * @{ + */ + +/** @defgroup PMU_PVD_Mode_Mask PMU PVD Mode Mask + * @{ + */ +#define PVD_MODE_IT 0x00010000U +#define PVD_MODE_EVT 0x00020000U +#define PVD_RISING_EDGE 0x00000001U +#define PVD_FALLING_EDGE 0x00000002U +/** + * @} + */ + +/** + * @} + */ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ + +/** @defgroup PMU_Exported_Functions PMU Exported Functions + * @{ + */ + +/** @defgroup PMU_Exported_Functions_Group1 Initialization and de-initialization functions + * @brief Initialization and de-initialization functions + * +@verbatim + =============================================================================== + ##### Initialization and de-initialization functions ##### + =============================================================================== + [..] + After reset, the backup domain (RTC registers, RTC backup data + registers and backup SRAM) is protected against possible unwanted + write accesses. + To enable access to the RTC Domain and RTC registers, proceed as follows: + (+) Enable the Power Controller (PMU) APB1 interface clock using the + __DAL_RCM_PMU_CLK_ENABLE() macro. + (+) Enable access to RTC domain using the DAL_PMU_EnableBkUpAccess() function. + +@endverbatim + * @{ + */ + +/** + * @brief Deinitializes the DAL PMU peripheral registers to their default reset values. + * @retval None + */ +void DAL_PMU_DeInit(void) +{ + __DAL_RCM_PMU_FORCE_RESET(); + __DAL_RCM_PMU_RELEASE_RESET(); +} + +/** + * @brief Enables access to the backup domain (RTC registers, RTC + * backup data registers and backup SRAM). + * @note If the HSE divided by 2, 3, ..31 is used as the RTC clock, the + * Backup Domain Access should be kept enabled. + * @note The following sequence is required to bypass the delay between + * DBP bit programming and the effective enabling of the backup domain. + * Please check the Errata Sheet for more details under "Possible delay + * in backup domain protection disabling/enabling after programming the + * DBP bit" section. + * @retval None + */ +void DAL_PMU_EnableBkUpAccess(void) +{ + __IO uint32_t dummyread; + *(__IO uint32_t *) CTRL_BPWEN_BB = (uint32_t)ENABLE; + dummyread = PMU->CTRL; + UNUSED(dummyread); +} + +/** + * @brief Disables access to the backup domain (RTC registers, RTC + * backup data registers and backup SRAM). + * @note If the HSE divided by 2, 3, ..31 is used as the RTC clock, the + * Backup Domain Access should be kept enabled. + * @note The following sequence is required to bypass the delay between + * DBP bit programming and the effective disabling of the backup domain. + * Please check the Errata Sheet for more details under "Possible delay + * in backup domain protection disabling/enabling after programming the + * DBP bit" section. + * @retval None + */ +void DAL_PMU_DisableBkUpAccess(void) +{ + __IO uint32_t dummyread; + *(__IO uint32_t *) CTRL_BPWEN_BB = (uint32_t)DISABLE; + dummyread = PMU->CTRL; + UNUSED(dummyread); +} + +/** + * @} + */ + +/** @defgroup PMU_Exported_Functions_Group2 Peripheral Control functions + * @brief Low Power modes configuration functions + * +@verbatim + + =============================================================================== + ##### Peripheral Control functions ##### + =============================================================================== + + *** PVD configuration *** + ========================= + [..] + (+) The PVD is used to monitor the VDD power supply by comparing it to a + threshold selected by the PVD Level (PLS[2:0] bits in the PMU_CTRL). + (+) A PVDO flag is available to indicate if VDD/VDDA is higher or lower + than the PVD threshold. This event is internally connected to the EINT + line16 and can generate an interrupt if enabled. This is done through + __DAL_PMU_PVD_EINT_ENABLE_IT() macro. + (+) The PVD is stopped in Standby mode. + + *** Wake-up pin configuration *** + ================================ + [..] + (+) Wake-up pin is used to wake up the system from Standby mode. This pin is + forced in input pull-down configuration and is active on rising edges. + (+) There is one Wake-up pin: Wake-up Pin 1 on PA.00. + + *** Low Power modes configuration *** + ===================================== + [..] + The devices feature 3 low-power modes: + (+) Sleep mode: Cortex-M4 core stopped, peripherals kept running. + (+) Stop mode: all clocks are stopped, regulator running, regulator + in low power mode + (+) Standby mode: 1.2V domain powered off. + + *** Sleep mode *** + ================== + [..] + (+) Entry: + The Sleep mode is entered by using the DAL_PMU_EnterSLEEPMode(PMU_MAINREGULATOR_ON, PMU_SLEEPENTRY_WFI) + functions with + (++) PMU_SLEEPENTRY_WFI: enter SLEEP mode with WFI instruction + (++) PMU_SLEEPENTRY_WFE: enter SLEEP mode with WFE instruction + + -@@- The Regulator parameter is not used for the APM32F4 family + and is kept as parameter just to maintain compatibility with the + lower power families (APM32L). + (+) Exit: + Any peripheral interrupt acknowledged by the nested vectored interrupt + controller (NVIC) can wake up the device from Sleep mode. + + *** Stop mode *** + ================= + [..] + In Stop mode, all clocks in the 1.2V domain are stopped, the PLL, the HSI, + and the HSE RC oscillators are disabled. Internal SRAM and register contents + are preserved. + The voltage regulator can be configured either in normal or low-power mode. + To minimize the consumption In Stop mode, FLASH can be powered off before + entering the Stop mode using the DAL_PMUEx_EnableFlashPowerDown() function. + It can be switched on again by software after exiting the Stop mode using + the DAL_PMUEx_DisableFlashPowerDown() function. + + (+) Entry: + The Stop mode is entered using the DAL_PMU_EnterSTOPMode(PMU_MAINREGULATOR_ON) + function with: + (++) Main regulator ON. + (++) Low Power regulator ON. + (+) Exit: + Any EINT Line (Internal or External) configured in Interrupt/Event mode. + + *** Standby mode *** + ==================== + [..] + (+) + The Standby mode allows to achieve the lowest power consumption. It is based + on the Cortex-M4 deep sleep mode, with the voltage regulator disabled. + The 1.2V domain is consequently powered off. The PLL, the HSI oscillator and + the HSE oscillator are also switched off. SRAM and register contents are lost + except for the RTC registers, RTC backup registers, backup SRAM and Standby + circuitry. + + The voltage regulator is OFF. + + (++) Entry: + (+++) The Standby mode is entered using the DAL_PMU_EnterSTANDBYMode() function. + (++) Exit: + (+++) WKUP pin rising edge, RTC alarm (Alarm A and Alarm B), RTC wake-up, + tamper event, time-stamp event, external reset in NRST pin, IWDT reset. + + *** Auto-wake-up (AWU) from low-power mode *** + ============================================= + [..] + + (+) The MCU can be woken up from low-power mode by an RTC Alarm event, an RTC + Wake-up event, a tamper event or a time-stamp event, without depending on + an external interrupt (Auto-wake-up mode). + + (+) RTC auto-wake-up (AWU) from the Stop and Standby modes + + (++) To wake up from the Stop mode with an RTC alarm event, it is necessary to + configure the RTC to generate the RTC alarm using the DAL_RTC_SetAlarm_IT() function. + + (++) To wake up from the Stop mode with an RTC Tamper or time stamp event, it + is necessary to configure the RTC to detect the tamper or time stamp event using the + DAL_RTCEx_SetTimeStamp_IT() or DAL_RTCEx_SetTamper_IT() functions. + + (++) To wake up from the Stop mode with an RTC Wake-up event, it is necessary to + configure the RTC to generate the RTC Wake-up event using the DAL_RTCEx_SetWakeUpTimer_IT() function. + +@endverbatim + * @{ + */ + +/** + * @brief Configures the voltage threshold detected by the Power Voltage Detector(PVD). + * @param sConfigPVD pointer to an PMU_PVDTypeDef structure that contains the configuration + * information for the PVD. + * @note Refer to the electrical characteristics of your device datasheet for + * more details about the voltage threshold corresponding to each + * detection level. + * @retval None + */ +void DAL_PMU_ConfigPVD(PMU_PVDTypeDef *sConfigPVD) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_PMU_PVD_LEVEL(sConfigPVD->PVDLevel)); + ASSERT_PARAM(IS_PMU_PVD_MODE(sConfigPVD->Mode)); + + /* Set PLS[7:5] bits according to PVDLevel value */ + MODIFY_REG(PMU->CTRL, PMU_CTRL_PLSEL, sConfigPVD->PVDLevel); + + /* Clear any previous config. Keep it clear if no event or IT mode is selected */ + __DAL_PMU_PVD_EINT_DISABLE_EVENT(); + __DAL_PMU_PVD_EINT_DISABLE_IT(); + __DAL_PMU_PVD_EINT_DISABLE_RISING_EDGE(); + __DAL_PMU_PVD_EINT_DISABLE_FALLING_EDGE(); + + /* Configure interrupt mode */ + if((sConfigPVD->Mode & PVD_MODE_IT) == PVD_MODE_IT) + { + __DAL_PMU_PVD_EINT_ENABLE_IT(); + } + + /* Configure event mode */ + if((sConfigPVD->Mode & PVD_MODE_EVT) == PVD_MODE_EVT) + { + __DAL_PMU_PVD_EINT_ENABLE_EVENT(); + } + + /* Configure the edge */ + if((sConfigPVD->Mode & PVD_RISING_EDGE) == PVD_RISING_EDGE) + { + __DAL_PMU_PVD_EINT_ENABLE_RISING_EDGE(); + } + + if((sConfigPVD->Mode & PVD_FALLING_EDGE) == PVD_FALLING_EDGE) + { + __DAL_PMU_PVD_EINT_ENABLE_FALLING_EDGE(); + } +} + +/** + * @brief Enables the Power Voltage Detector(PVD). + * @retval None + */ +void DAL_PMU_EnablePVD(void) +{ + *(__IO uint32_t *) CTRL_PVDEN_BB = (uint32_t)ENABLE; +} + +/** + * @brief Disables the Power Voltage Detector(PVD). + * @retval None + */ +void DAL_PMU_DisablePVD(void) +{ + *(__IO uint32_t *) CTRL_PVDEN_BB = (uint32_t)DISABLE; +} + +/** + * @brief Enables the Wake-up PINx functionality. + * @param WakeUpPinx Specifies the Power Wake-Up pin to enable. + * This parameter can be one of the following values: + * @arg PMU_WAKEUP_PIN1 + * @retval None + */ +void DAL_PMU_EnableWakeUpPin(uint32_t WakeUpPinx) +{ + /* Check the parameter */ + ASSERT_PARAM(IS_PMU_WAKEUP_PIN(WakeUpPinx)); + + /* Enable the wake up pin */ + SET_BIT(PMU->CSTS, WakeUpPinx); +} + +/** + * @brief Disables the Wake-up PINx functionality. + * @param WakeUpPinx Specifies the Power Wake-Up pin to disable. + * This parameter can be one of the following values: + * @arg PMU_WAKEUP_PIN1 + * @retval None + */ +void DAL_PMU_DisableWakeUpPin(uint32_t WakeUpPinx) +{ + /* Check the parameter */ + ASSERT_PARAM(IS_PMU_WAKEUP_PIN(WakeUpPinx)); + + /* Disable the wake up pin */ + CLEAR_BIT(PMU->CSTS, WakeUpPinx); +} + +/** + * @brief Enters Sleep mode. + * + * @note In Sleep mode, all I/O pins keep the same state as in Run mode. + * + * @note In Sleep mode, the systick is stopped to avoid exit from this mode with + * systick interrupt when used as time base for Timeout + * + * @param Regulator Specifies the regulator state in SLEEP mode. + * This parameter can be one of the following values: + * @arg PMU_MAINREGULATOR_ON: SLEEP mode with regulator ON + * @arg PMU_LOWPOWERREGULATOR_ON: SLEEP mode with low power regulator ON + * @note This parameter is not used for the APM32F4 family and is kept as parameter + * just to maintain compatibility with the lower power families. + * @param SLEEPEntry Specifies if SLEEP mode in entered with WFI or WFE instruction. + * This parameter can be one of the following values: + * @arg PMU_SLEEPENTRY_WFI: enter SLEEP mode with WFI instruction + * @arg PMU_SLEEPENTRY_WFE: enter SLEEP mode with WFE instruction + * @retval None + */ +void DAL_PMU_EnterSLEEPMode(uint32_t Regulator, uint8_t SLEEPEntry) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_PMU_REGULATOR(Regulator)); + ASSERT_PARAM(IS_PMU_SLEEP_ENTRY(SLEEPEntry)); + + /* Clear SLEEPDEEP bit of Cortex System Control Register */ + CLEAR_BIT(SCB->SCR, ((uint32_t)SCB_SCR_SLEEPDEEP_Msk)); + + /* Select SLEEP mode entry -------------------------------------------------*/ + if(SLEEPEntry == PMU_SLEEPENTRY_WFI) + { + /* Request Wait For Interrupt */ + __WFI(); + } + else + { + /* Request Wait For Event */ + __SEV(); + __WFE(); + __WFE(); + } +} + +/** + * @brief Enters Stop mode. + * @note In Stop mode, all I/O pins keep the same state as in Run mode. + * @note When exiting Stop mode by issuing an interrupt or a wake-up event, + * the HSI RC oscillator is selected as system clock. + * @note When the voltage regulator operates in low power mode, an additional + * startup delay is incurred when waking up from Stop mode. + * By keeping the internal regulator ON during Stop mode, the consumption + * is higher although the startup time is reduced. + * @param Regulator Specifies the regulator state in Stop mode. + * This parameter can be one of the following values: + * @arg PMU_MAINREGULATOR_ON: Stop mode with regulator ON + * @arg PMU_LOWPOWERREGULATOR_ON: Stop mode with low power regulator ON + * @param STOPEntry Specifies if Stop mode in entered with WFI or WFE instruction. + * This parameter can be one of the following values: + * @arg PMU_STOPENTRY_WFI: Enter Stop mode with WFI instruction + * @arg PMU_STOPENTRY_WFE: Enter Stop mode with WFE instruction + * @retval None + */ +void DAL_PMU_EnterSTOPMode(uint32_t Regulator, uint8_t STOPEntry) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_PMU_REGULATOR(Regulator)); + ASSERT_PARAM(IS_PMU_STOP_ENTRY(STOPEntry)); + + /* Select the regulator state in Stop mode: Set PDDS and LPDS bits according to PMU_Regulator value */ + MODIFY_REG(PMU->CTRL, (PMU_CTRL_PDDSCFG | PMU_CTRL_LPDSCFG), Regulator); + + /* Set SLEEPDEEP bit of Cortex System Control Register */ + SET_BIT(SCB->SCR, ((uint32_t)SCB_SCR_SLEEPDEEP_Msk)); + + /* Select Stop mode entry --------------------------------------------------*/ + if(STOPEntry == PMU_STOPENTRY_WFI) + { + /* Request Wait For Interrupt */ + __WFI(); + } + else + { + /* Request Wait For Event */ + __SEV(); + __WFE(); + __WFE(); + } + /* Reset SLEEPDEEP bit of Cortex System Control Register */ + CLEAR_BIT(SCB->SCR, ((uint32_t)SCB_SCR_SLEEPDEEP_Msk)); +} + +/** + * @brief Enters Standby mode. + * @note In Standby mode, all I/O pins are high impedance except for: + * - Reset pad (still available) + * - RTC_AF1 pin (PC13) if configured for tamper, time-stamp, RTC + * Alarm out, or RTC clock calibration out. + * - RTC_AF2 pin (PI8) if configured for tamper or time-stamp. + * - WKUP pin 1 (PA0) if enabled. + * @retval None + */ +void DAL_PMU_EnterSTANDBYMode(void) +{ + /* Select Standby mode */ + SET_BIT(PMU->CTRL, PMU_CTRL_PDDSCFG); + + /* Set SLEEPDEEP bit of Cortex System Control Register */ + SET_BIT(SCB->SCR, ((uint32_t)SCB_SCR_SLEEPDEEP_Msk)); + + /* This option is used to ensure that store operations are completed */ +#if defined ( __CC_ARM) + __force_stores(); +#endif + /* Request Wait For Interrupt */ + __WFI(); +} + +/** + * @brief This function handles the PMU PVD interrupt request. + * @note This API should be called under the PVD_IRQHandler(). + * @retval None + */ +void DAL_PMU_PVD_IRQHandler(void) +{ + /* Check PMU Exti flag */ + if(__DAL_PMU_PVD_EINT_GET_FLAG() != RESET) + { + /* PMU PVD interrupt user callback */ + DAL_PMU_PVDCallback(); + + /* Clear PMU Exti pending bit */ + __DAL_PMU_PVD_EINT_CLEAR_FLAG(); + } +} + +/** + * @brief PMU PVD interrupt callback + * @retval None + */ +__weak void DAL_PMU_PVDCallback(void) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the DAL_PMU_PVDCallback could be implemented in the user file + */ +} + +/** + * @brief Indicates Sleep-On-Exit when returning from Handler mode to Thread mode. + * @note Set SLEEPONEXIT bit of SCR register. When this bit is set, the processor + * re-enters SLEEP mode when an interruption handling is over. + * Setting this bit is useful when the processor is expected to run only on + * interruptions handling. + * @retval None + */ +void DAL_PMU_EnableSleepOnExit(void) +{ + /* Set SLEEPONEXIT bit of Cortex System Control Register */ + SET_BIT(SCB->SCR, ((uint32_t)SCB_SCR_SLEEPONEXIT_Msk)); +} + +/** + * @brief Disables Sleep-On-Exit feature when returning from Handler mode to Thread mode. + * @note Clears SLEEPONEXIT bit of SCR register. When this bit is set, the processor + * re-enters SLEEP mode when an interruption handling is over. + * @retval None + */ +void DAL_PMU_DisableSleepOnExit(void) +{ + /* Clear SLEEPONEXIT bit of Cortex System Control Register */ + CLEAR_BIT(SCB->SCR, ((uint32_t)SCB_SCR_SLEEPONEXIT_Msk)); +} + +/** + * @brief Enables CORTEX M4 SEVONPEND bit. + * @note Sets SEVONPEND bit of SCR register. When this bit is set, this causes + * WFE to wake up when an interrupt moves from inactive to pended. + * @retval None + */ +void DAL_PMU_EnableSEVOnPend(void) +{ + /* Set SEVONPEND bit of Cortex System Control Register */ + SET_BIT(SCB->SCR, ((uint32_t)SCB_SCR_SEVONPEND_Msk)); +} + +/** + * @brief Disables CORTEX M4 SEVONPEND bit. + * @note Clears SEVONPEND bit of SCR register. When this bit is set, this causes + * WFE to wake up when an interrupt moves from inactive to pended. + * @retval None + */ +void DAL_PMU_DisableSEVOnPend(void) +{ + /* Clear SEVONPEND bit of Cortex System Control Register */ + CLEAR_BIT(SCB->SCR, ((uint32_t)SCB_SCR_SEVONPEND_Msk)); +} + +/** + * @} + */ + +/** + * @} + */ + +#endif /* DAL_PMU_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_pmu_ex.c b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_pmu_ex.c new file mode 100644 index 0000000000..2bbc0f09b3 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_pmu_ex.c @@ -0,0 +1,403 @@ +/** + * + * @file apm32f4xx_dal_pmu_ex.c + * @brief Extended PMU DAL module driver. + * This file provides firmware functions to manage the following + * functionalities of PMU extension peripheral: + * + Peripheral Extended features functions + * + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2017 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file in + * the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + */ + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @defgroup PMUEx PMUEx + * @brief PMU DAL module driver + * @{ + */ + +#ifdef DAL_PMU_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/** @addtogroup PMUEx_Private_Constants + * @{ + */ +#define PMU_OVERDRIVE_TIMEOUT_VALUE 1000U +#define PMU_UDERDRIVE_TIMEOUT_VALUE 1000U +#define PMU_BKPREG_TIMEOUT_VALUE 1000U +#define PMU_VOSRDY_TIMEOUT_VALUE 1000U +/** + * @} + */ + + +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ +/** @defgroup PMUEx_Exported_Functions PMUEx Exported Functions + * @{ + */ + +/** @defgroup PMUEx_Exported_Functions_Group1 Peripheral Extended features functions + * @brief Peripheral Extended features functions + * +@verbatim + + =============================================================================== + ##### Peripheral extended features functions ##### + =============================================================================== + + *** Main and Backup Regulators configuration *** + ================================================ + [..] + (+) The backup domain includes 4 Kbytes of backup SRAM accessible only from + the CPU, and address in 32-bit, 16-bit or 8-bit mode. Its content is + retained even in Standby or VBAT mode when the low power backup regulator + is enabled. It can be considered as an internal EEPROM when VBAT is + always present. You can use the DAL_PMUEx_EnableBkUpReg() function to + enable the low power backup regulator. + + (+) When the backup domain is supplied by VDD (analog switch connected to VDD) + the backup SRAM is powered from VDD which replaces the VBAT power supply to + save battery life. + + (+) The backup SRAM is not mass erased by a tamper event. It is read + protected to prevent confidential data, such as cryptographic private + key, from being accessed. The backup SRAM can be erased only through + the Flash interface when a protection level change from level 1 to + level 0 is requested. + -@- Refer to the description of Read protection (RDP) in the Flash + programming manual. + + (+) The main internal regulator can be configured to have a tradeoff between + performance and power consumption when the device does not operate at + the maximum frequency. This is done through __DAL_PMU_MAINREGULATORMODE_CONFIG() + macro which configure VOS bit in PMU_CTRL register + + Refer to the product datasheets for more details. + + *** FLASH Power Down configuration **** + ======================================= + [..] + (+) By setting the FPDS bit in the PMU_CTRL register by using the + DAL_PMUEx_EnableFlashPowerDown() function, the Flash memory also enters power + down mode when the device enters Stop mode. When the Flash memory + is in power down mode, an additional startup delay is incurred when + waking up from Stop mode. + + Refer to the datasheets for more details. + +@endverbatim + * @{ + */ + +/** + * @brief Enables the Backup Regulator. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_PMUEx_EnableBkUpReg(void) +{ + uint32_t tickstart = 0U; + + *(__IO uint32_t *) CSTS_BKPREN_BB = (uint32_t)ENABLE; + + /* Get tick */ + tickstart = DAL_GetTick(); + + /* Wait till Backup regulator ready flag is set */ + while(__DAL_PMU_GET_FLAG(PMU_FLAG_BRR) == RESET) + { + if((DAL_GetTick() - tickstart ) > PMU_BKPREG_TIMEOUT_VALUE) + { + return DAL_TIMEOUT; + } + } + return DAL_OK; +} + +/** + * @brief Disables the Backup Regulator. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_PMUEx_DisableBkUpReg(void) +{ + uint32_t tickstart = 0U; + + *(__IO uint32_t *) CSTS_BKPREN_BB = (uint32_t)DISABLE; + + /* Get tick */ + tickstart = DAL_GetTick(); + + /* Wait till Backup regulator ready flag is set */ + while(__DAL_PMU_GET_FLAG(PMU_FLAG_BRR) != RESET) + { + if((DAL_GetTick() - tickstart ) > PMU_BKPREG_TIMEOUT_VALUE) + { + return DAL_TIMEOUT; + } + } + return DAL_OK; +} + +/** + * @brief Enables the Flash Power Down in Stop mode. + * @retval None + */ +void DAL_PMUEx_EnableFlashPowerDown(void) +{ + *(__IO uint32_t *) CTRL_FPDSM_BB = (uint32_t)ENABLE; +} + +/** + * @brief Disables the Flash Power Down in Stop mode. + * @retval None + */ +void DAL_PMUEx_DisableFlashPowerDown(void) +{ + *(__IO uint32_t *) CTRL_FPDSM_BB = (uint32_t)DISABLE; +} + +/** + * @brief Return Voltage Scaling Range. + * @retval The configured scale for the regulator voltage(VOS bit field). + * The returned value can be one of the following: + * - @arg PMU_REGULATOR_VOLTAGE_SCALE1: Regulator voltage output Scale 1 mode + * - @arg PMU_REGULATOR_VOLTAGE_SCALE2: Regulator voltage output Scale 2 mode + * - @arg PMU_REGULATOR_VOLTAGE_SCALE3: Regulator voltage output Scale 3 mode + */ +uint32_t DAL_PMUEx_GetVoltageRange(void) +{ + return (PMU->CTRL & PMU_CTRL_VOSSEL); +} + +#if defined(APM32F405xx) || defined(APM32F407xx) || defined(APM32F417xx) || defined(APM32F465xx) +/** + * @brief Configures the main internal regulator output voltage. + * @param VoltageScaling specifies the regulator output voltage to achieve + * a tradeoff between performance and power consumption. + * This parameter can be one of the following values: + * @arg PMU_REGULATOR_VOLTAGE_SCALE1: Regulator voltage output range 1 mode, + * the maximum value of fHCLK = 168 MHz. + * @arg PMU_REGULATOR_VOLTAGE_SCALE2: Regulator voltage output range 2 mode, + * the maximum value of fHCLK = 144 MHz. + * @note When moving from Range 1 to Range 2, the system frequency must be decreased to + * a value below 144 MHz before calling DAL_PMUEx_ConfigVoltageScaling() API. + * When moving from Range 2 to Range 1, the system frequency can be increased to + * a value up to 168 MHz after calling DAL_PMUEx_ConfigVoltageScaling() API. + * @retval DAL Status + */ +DAL_StatusTypeDef DAL_PMUEx_ControlVoltageScaling(uint32_t VoltageScaling) +{ + uint32_t tickstart = 0U; + + ASSERT_PARAM(IS_PMU_VOLTAGE_SCALING_RANGE(VoltageScaling)); + + /* Enable PMU RCM Clock Peripheral */ + __DAL_RCM_PMU_CLK_ENABLE(); + + /* Set Range */ + __DAL_PMU_VOLTAGESCALING_CONFIG(VoltageScaling); + + /* Get Start Tick*/ + tickstart = DAL_GetTick(); + while((__DAL_PMU_GET_FLAG(PMU_FLAG_VOSRDY) == RESET)) + { + if((DAL_GetTick() - tickstart ) > PMU_VOSRDY_TIMEOUT_VALUE) + { + return DAL_TIMEOUT; + } + } + + return DAL_OK; +} + +#elif defined(APM32F411xx) +/** + * @brief Configures the main internal regulator output voltage. + * @param VoltageScaling specifies the regulator output voltage to achieve + * a tradeoff between performance and power consumption. + * This parameter can be one of the following values: + * @arg PMU_REGULATOR_VOLTAGE_SCALE1: Regulator voltage output range 1 mode, + * the maximum value of fHCLK is 168 MHz. It can be extended to + * 180 MHz by activating the over-drive mode. + * @arg PMU_REGULATOR_VOLTAGE_SCALE2: Regulator voltage output range 2 mode, + * the maximum value of fHCLK is 144 MHz. It can be extended to, + * 168 MHz by activating the over-drive mode. + * @arg PMU_REGULATOR_VOLTAGE_SCALE3: Regulator voltage output range 3 mode, + * the maximum value of fHCLK is 120 MHz. + * @note To update the system clock frequency(SYSCLK): + * - Set the HSI or HSE as system clock frequency using the DAL_RCM_ClockConfig(). + * - Call the DAL_RCM_OscConfig() to configure the PLL. + * - Call DAL_PMUEx_ConfigVoltageScaling() API to adjust the voltage scale. + * - Set the new system clock frequency using the DAL_RCM_ClockConfig(). + * @note The scale can be modified only when the HSI or HSE clock source is selected + * as system clock source, otherwise the API returns DAL_ERROR. + * @note When the PLL is OFF, the voltage scale 3 is automatically selected and the VOS bits + * value in the PMU_CTRL1 register are not taken in account. + * @note This API forces the PLL state ON to allow the possibility to configure the voltage scale 1 or 2. + * @note The new voltage scale is active only when the PLL is ON. + * @retval DAL Status + */ +DAL_StatusTypeDef DAL_PMUEx_ControlVoltageScaling(uint32_t VoltageScaling) +{ + uint32_t tickstart = 0U; + + ASSERT_PARAM(IS_PMU_VOLTAGE_SCALING_RANGE(VoltageScaling)); + + /* Enable PMU RCM Clock Peripheral */ + __DAL_RCM_PMU_CLK_ENABLE(); + + /* Check if the PLL is used as system clock or not */ + if(__DAL_RCM_GET_SYSCLK_SOURCE() != RCM_CFG_SCLKSWSTS_PLL) + { + /* Disable the main PLL */ + __DAL_RCM_PLL_DISABLE(); + + /* Get Start Tick */ + tickstart = DAL_GetTick(); + /* Wait till PLL is disabled */ + while(__DAL_RCM_GET_FLAG(RCM_FLAG_PLLRDY) != RESET) + { + if((DAL_GetTick() - tickstart ) > PLL_TIMEOUT_VALUE) + { + return DAL_TIMEOUT; + } + } + + /* Set Range */ + __DAL_PMU_VOLTAGESCALING_CONFIG(VoltageScaling); + + /* Enable the main PLL */ + __DAL_RCM_PLL_ENABLE(); + + /* Get Start Tick */ + tickstart = DAL_GetTick(); + /* Wait till PLL is ready */ + while(__DAL_RCM_GET_FLAG(RCM_FLAG_PLLRDY) == RESET) + { + if((DAL_GetTick() - tickstart ) > PLL_TIMEOUT_VALUE) + { + return DAL_TIMEOUT; + } + } + + /* Get Start Tick */ + tickstart = DAL_GetTick(); + while((__DAL_PMU_GET_FLAG(PMU_FLAG_VOSRDY) == RESET)) + { + if((DAL_GetTick() - tickstart ) > PMU_VOSRDY_TIMEOUT_VALUE) + { + return DAL_TIMEOUT; + } + } + } + else + { + return DAL_ERROR; + } + + return DAL_OK; +} +#endif /* APM32F405xx || APM32F407xx || APM32F417xx || APM32F465xx */ + +#if defined(APM32F411xx) +/** + * @brief Enables Main Regulator low voltage mode. + * @note This mode is only available for APM32F411xx devices. + * @retval None + */ +void DAL_PMUEx_EnableMainRegulatorLowVoltage(void) +{ + *(__IO uint32_t *) CTRL_MRLV_BB = (uint32_t)ENABLE; +} + +/** + * @brief Disables Main Regulator low voltage mode. + * @note This mode is only available for APM32F411xx devices. + * @retval None + */ +void DAL_PMUEx_DisableMainRegulatorLowVoltage(void) +{ + *(__IO uint32_t *) CTRL_MRLV_BB = (uint32_t)DISABLE; +} + +/** + * @brief Enables Low Power Regulator low voltage mode. + * @note This mode is only available for APM32F411xx devices. + * @retval None + */ +void DAL_PMUEx_EnableLowRegulatorLowVoltage(void) +{ + *(__IO uint32_t *) CTRL_LPRLV_BB = (uint32_t)ENABLE; +} + +/** + * @brief Disables Low Power Regulator low voltage mode. + * @note This mode is only available for APM32F411xx devices. + * @retval None + */ +void DAL_PMUEx_DisableLowRegulatorLowVoltage(void) +{ + *(__IO uint32_t *) CTRL_LPRLV_BB = (uint32_t)DISABLE; +} + +#endif /* APM32F411xx */ + +/** + * @} + */ + +/** + * @} + */ + +#endif /* DAL_PMU_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_qspi.c b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_qspi.c new file mode 100644 index 0000000000..eb6f7cf3bc --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_qspi.c @@ -0,0 +1,2557 @@ +/** + * + * @file apm32f4xx_dal_qspi.c + * @brief QSPI DAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the QSPI peripheral: + * + Initialization and de-initialization functions + * + Peripheral Control functions + * + Peripheral State functions + * + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2017 STMicroelectronics. + * Copyright (C) 2023-2024 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + * + @verbatim + =============================================================================== + ##### How to use this driver ##### + =============================================================================== + [..] + *** Initialization *** + ====================== + [..] + (#) As prerequisite, fill in the DAL_QSPI_MspInit() : + (++) Enable the QSPI interface clock using __DAL_RCM_QSPI_CLK_ENABLE() + (++) Reset QSPI peripheral with __DAL_RCM_QSPI_FORCE_RESET() and + __DAL_RCM_QSPI_RELEASE_RESET(). + (++) Enable the clocks for the QSPI GPIOS with __DAL_GPIO_QSPI_CLK_ENABLE(). + (++) Configure these QSPI pins in alternate function mode using __DAL_GPIO_Init(). + (++) If interrupt mode is used, enable and configure QSPI global + interrupt with DAL_NVIC_SetPriority() and DAL_NVIC_EnableIRQ(). + (++) If DMA mode is used, enable the clocks for the QSPI DMA channel + with __DAL_DMA_QSPI_CLK_ENABLE(), configure DMA with + DAL_DMA_Init() function and link it with QSPI handle using + __DAL_LINKDMA(), enable and configure DMA global interrupt with + DAL_NVIC_SetPriority() and DAL_NVIC_EnableIRQ(). + (#) Configure the baudrate, the clock phase, the clock polarity, the clock stretch, + the data frame size, the frame format, the FIFO threshold and the sample shifting + using the DAL_QSPI_Init() function. + + *** Errors management and abort functionality *** + ================================================ + [..] + (#) DAL_QSPI_GetError() function gives the error raised during the last operation. + (#) DAL_QSPI_Abort() and DAL_QSPI_Abort_IT() functions aborts any on-going operation and + flushes the fifo : + (++) In polling mode, the output of the function is done when the transfer + complete bit is set and the busy bit cleared. + (++) In interrupt mode, DAL_QSPI_AbortCpltCallback() will be called when + the transfer complete bit is set. + + *** Control functions *** + ========================= + [..] + (#) DAL_QSPI_GetState() function gives the current state of the DAL QSPI driver. + (#) DAL_QSPI_SetTimeout() function configures the timeout value used in the driver. + (#) DAL_QSPI_SetFifoThreshold() function configures the threshold on the FIFO of the QSPI IP. + (#) DAL_QSPI_GetFifoThreshold() function gives the current of the Fifo's threshold. + + *** Callback registration *** + ============================= + [..] + The compilation define USE_DAL_QSPI_REGISTER_CALLBACKS when set to 1 + allows the user to configure dynamically the driver callbacks. + + Use Functions @ref DAL_QSPI_RegisterCallback() to register a user callback, + it allows to register following callbacks: + (+) ErrorCallback : callback when error occurs. + (+) AbortCpltCallback : callback when abort is completed. + (+) CmdCpltCallback : callback when command is completed. + (+) RxCpltCallback : callback when receive is completed. + (+) TxCpltCallback : callback when transmit is completed. + (+) TxRxCpltCallback : callback when transmit and receive are completed. + (+) MspInitCallback : QSPI MspInit. + (+) MspDeInitCallback : QSPI MspDeInit. + This function takes as parameters the HAL peripheral handle, the Callback ID + and a pointer to the user callback function. + + Use function @ref DAL_QSPI_UnRegisterCallback() to reset a callback to the default + weak (surcharged) function. It allows to reset following callbacks: + (+) ErrorCallback : callback when error occurs. + (+) AbortCpltCallback : callback when abort is completed. + (+) CmdCpltCallback : callback when command is completed. + (+) RxCpltCallback : callback when receive is completed. + (+) TxCpltCallback : callback when transmit is completed. + (+) TxRxCpltCallback : callback when transmit and receive are completed. + (+) MspInitCallback : QSPI MspInit. + (+) MspDeInitCallback : QSPI MspDeInit. + This function) takes as parameters the DAL peripheral handle and the Callback ID. + + By default, after the DAL_QSPI_Init() and if the state is DAL_QSPI_STATE_RESET + all callbacks are reset to the corresponding legacy weak (surcharged) functions. + Exception done for MspInit and MspDeInit callbacks that are respectively + reset to the legacy weak (surcharged) functions in the DAL_QSPI_Init() + and DAL_QSPI_DeInit() only when these callbacks are null (not registered beforehand). + If not, MspInit or MspDeInit are not null, the DAL_QSPI_Init() and DAL_QSPI_DeInit() + keep and use the user MspInit/MspDeInit callbacks (registered beforehand). + + Callbacks can be registered/unregistered in DAL_QSPI_STATE_READY state only. + Exception done MspInit/MspDeInit callbacks that can be registered/unregistered + in DAL_QSPI_STATE_READY or DAL_QSPI_STATE_RESET state, thus registered (user) + MspInit/DeInit callbacks can be used during the DAL_QSPI_Init()/DAL_QSPI_DeInit(). + In that case first register the MspInit/MspDeInit user callbacks + using DAL_QSPI_RegisterCallback() before calling DAL_QSPI_DeInit() + or DAL_QSPI_Init() function. + + When the compilation define USE_DAL_QSPI_REGISTER_CALLBACKS is set to 0 or + not defined, the callback registration feature is not available and all callbacks + are set to the corresponding legacy weak (surcharged) functions. + @endverbatim + * + */ + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal.h" + +#if defined(QSPI) + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @defgroup QSPI QSPI + * @brief QSPI DAL module driver + * @{ + */ + +#ifdef DAL_QSPI_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ + +/** @defgroup QSPI_Private_Constants QSPI Private Constants + * @{ + */ + +/* TFTL register clear mask */ +#define QSPI_TFTL_CLEAR_MASK ((uint32_t)(QSPI_TFTL_TFTH | QSPI_TFTL_TFT)) + +/** + * @} + */ + +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +static void QSPI_DMATxCplt(DMA_HandleTypeDef *hdma); +static void QSPI_DMARxCplt(DMA_HandleTypeDef *hdma); +static void QSPI_DMAError(DMA_HandleTypeDef *hdma); +static void QSPI_DMAAbortCplt(DMA_HandleTypeDef *hdma); +static DAL_StatusTypeDef DAL_QSPI_WaitFlagStateUntilTimeout(QSPI_HandleTypeDef *hqspi, uint32_t Flag, FlagStatus State, uint32_t TickStart, uint32_t Timeout); +static void QSPI_Config(QSPI_HandleTypeDef *hqspi, QSPI_CommandTypeDef *cmd); + +/* Exported functions --------------------------------------------------------*/ +/** @defgroup QSPI_Exported_Functions QSPI Exported Functions + * @{ + */ + +/** @defgroup QSPI_Exported_Functions_Group1 Initialization and de-initialization functions + * @brief Initialization and Configuration functions + * + * @verbatim + * =============================================================================== + * ##### Initialization and de-initialization functions ##### + * =============================================================================== + * [..] + * This section provides functions allowing to: + * (+) Initialize the QSPI. + * (+) De-initialize the QSPI. + * + * @endverbatim + * @{ + */ + +/** + * @brief Initializes the QSPI according to the specified parameters + * in the DAL_QSPI_InitTypeDef and create the associated handle. + * @param hqspi: QSPI handle + * @retval DAL status + */ +DAL_StatusTypeDef DAL_QSPI_Init(QSPI_HandleTypeDef *hqspi) +{ + DAL_StatusTypeDef status = DAL_OK; + uint32_t tickstart = DAL_GetTick(); + + /* Check the QSPI handle allocation */ + if (hqspi == NULL) + { + return DAL_ERROR; + } + + /* Check the parameters */ + ASSERT_PARAM(IS_QSPI_ALL_INSTANCE(hqspi->Instance)); + ASSERT_PARAM(IS_QSPI_CLOCK_PRESCALER(hqspi->Init.ClockPrescaler)); + ASSERT_PARAM(IS_QSPI_CLOCK_PHASE(hqspi->Init.ClockPhase)); + ASSERT_PARAM(IS_QSPI_CLOCK_POLARITY(hqspi->Init.ClockPolarity)); + ASSERT_PARAM(IS_QSPI_CLOCK_STRETCH(hqspi->Init.ClockStretch)); + ASSERT_PARAM(IS_QSPI_TX_FIFO_THRESHOLD(hqspi->Init.TxFifoThreshold)); + ASSERT_PARAM(IS_QSPI_TX_FIFO_LEVEL(hqspi->Init.TxFifoLevel)); + ASSERT_PARAM(IS_QSPI_RX_FIFO_THRESHOLD(hqspi->Init.RxFifoThreshold)); + ASSERT_PARAM(IS_QSPI_CHIP_SELECT_TOGGLE(hqspi->Init.ChipSelectToggle)); + + if (hqspi->State == DAL_QSPI_STATE_RESET) + { + +#if (USE_DAL_QSPI_REGISTER_CALLBACKS == 1) + /* Reset callback pointers to the legacy weak (surcharged) functions */ + hqspi->ErrorCallback = DAL_QSPI_ErrorCallback; + hqspi->AbortCpltCallback = DAL_QSPI_AbortCpltCallback; + hqspi->CmdCpltCallback = DAL_QSPI_CmdCpltCallback; + hqspi->RxCpltCallback = DAL_QSPI_RxCpltCallback; + hqspi->TxCpltCallback = DAL_QSPI_TxCpltCallback; + hqspi->TxRxCpltCallback = DAL_QSPI_TxRxCpltCallback; + + if (hqspi->MspInitCallback == NULL) + { + hqspi->MspInitCallback = DAL_QSPI_MspInit; + } + + /* Init the low level hardware */ + hqspi->MspInitCallback(hqspi); +#else + /* Init the low level hardware : GPIO, CLOCK, NVIC... */ + DAL_QSPI_MspInit(hqspi); +#endif /* USE_DAL_QSPI_REGISTER_CALLBACKS */ + + /* Configure the default timeout for the QSPI memory access */ + DAL_QSPI_SetTimeout(hqspi, DAL_QSPI_TIMEOUT_DEFAULT_VALUE); + } + + /* Configure QSPI FIFO Threshold */ + MODIFY_REG(hqspi->Instance->TFTL, QSPI_TFTL_CLEAR_MASK, \ + ((hqspi->Init.TxFifoThreshold << QSPI_TFTL_TFT_Pos) | + (hqspi->Init.TxFifoLevel << QSPI_TFTL_TFTH_Pos))); + + MODIFY_REG(hqspi->Instance->RFTL, QSPI_RFTL_RFT, hqspi->Init.RxFifoThreshold << QSPI_RFTL_RFT_Pos); + + /* Wait till BUSY flag reset */ + status = DAL_QSPI_WaitFlagStateUntilTimeout(hqspi, QSPI_FLAG_BUSY, RESET, tickstart, hqspi->Timeout); + + if (status == DAL_OK) + { + /* Disable the QSPI peripheral */ + __DAL_QSPI_DISABLE(hqspi); + + /* Disable the Slave Select signal */ + __DAL_QSPI_DISABLE_SS(hqspi); + + /* Configure QSPI Parameters */ + MODIFY_REG(hqspi->Instance->CTRL1, \ + (QSPI_CTRL1_CPHA | QSPI_CTRL1_CPOL | QSPI_CTRL1_SSTEN), \ + (hqspi->Init.ClockPhase | hqspi->Init.ClockPolarity | hqspi->Init.ChipSelectToggle)); + + /* Configure QSPI Clock Prescaler */ + MODIFY_REG(hqspi->Instance->BR, QSPI_BR_CLKDIV, hqspi->Init.ClockPrescaler << QSPI_BR_CLKDIV_Pos); + + /* Configure QSPI Clock Stretcher */ + MODIFY_REG(hqspi->Instance->CTRL3, QSPI_CTRL3_CSEN, hqspi->Init.ClockStretch << QSPI_CTRL3_CSEN_Pos); + + /* Enable the QSPI peripheral */ + __DAL_QSPI_ENABLE(hqspi); + + /* Set QSPI error code to none */ + hqspi->ErrorCode = DAL_QSPI_ERROR_NONE; + + /* Initialize the QSPI state */ + hqspi->State = DAL_QSPI_STATE_READY; + } + + /* Return function status */ + return status; +} + +/** + * @brief De-Initializes the QSPI peripheral + * @param hqspi: QSPI handle + * @retval DAL status + */ +DAL_StatusTypeDef DAL_QSPI_DeInit(QSPI_HandleTypeDef *hqspi) +{ + /* Check the QSPI handle allocation */ + if (hqspi == NULL) + { + return DAL_ERROR; + } + + /* Check the parameters */ + ASSERT_PARAM(IS_QSPI_ALL_INSTANCE(hqspi->Instance)); + + /* Disable the QSPI Peripheral */ + __DAL_QSPI_DISABLE(hqspi); + +#if (USE_DAL_QSPI_REGISTER_CALLBACKS == 1) + if (hqspi->MspDeInitCallback == NULL) + { + hqspi->MspDeInitCallback = DAL_QSPI_MspDeInit; + } + + /* DeInit the low level hardware */ + hqspi->MspDeInitCallback(hqspi); +#else + /* DeInit the low level hardware: GPIO, CLOCK, NVIC... */ + DAL_QSPI_MspDeInit(hqspi); +#endif /* USE_DAL_QSPI_REGISTER_CALLBACKS */ + + /* Set QSPI error code to none */ + hqspi->ErrorCode = DAL_QSPI_ERROR_NONE; + + /* Initialize the QSPI state */ + hqspi->State = DAL_QSPI_STATE_RESET; + + /* Return function status */ + return DAL_OK; +} + +/** + * @brief Initializes the QSPI MSP. + * @param hqspi: QSPI handle + * @retval None + */ +__weak void DAL_QSPI_MspInit(QSPI_HandleTypeDef *hqspi) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hqspi); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_QSPI_MspInit could be implemented in the user file + */ +} + +/** + * @brief DeInitializes QSPI MSP. + * @param hqspi: QSPI handle + * @retval None + */ +__weak void DAL_QSPI_MspDeInit(QSPI_HandleTypeDef *hqspi) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hqspi); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_QSPI_MspDeInit could be implemented in the user file + */ +} + +/** + * @} + */ + +/** @defgroup QSPI_Exported_Functions_Group2 Input and Output operation functions + * @brief Data transfers functions + * + * @verbatim + * =============================================================================== + * ##### Input and Output operation functions ##### + * =============================================================================== + * [..] + * This subsection provides a set of functions allowing to : + * (+) Handle the interrupts. + * (+) Handle the command sequence. + * (+) Handle the data transmission. + * (+) Handle the data reception. + * + * @endverbatim + * @{ + */ + +/** + * @brief Handle QSPI interrupt request. + * @param hqspi: QSPI handle + * @retval None + */ +void DAL_QSPI_IRQHandler(QSPI_HandleTypeDef *hqspi) +{ + __IO uint32_t *data_reg; + uint32_t flag = READ_REG(hqspi->Instance->STS); + uint32_t isrflags = READ_REG(hqspi->Instance->ISTS); + uint32_t itsource = READ_REG(hqspi->Instance->INTEN); + uint32_t errorFlags = 0x00U; + + errorFlags = (isrflags & (uint32_t)(QSPI_ISTS_TFOIF | QSPI_ISTS_RFUIF | QSPI_ISTS_RFOIF | QSPI_ISTS_MSTIF)); + + /* If some errors occur */ + if (errorFlags != RESET) + { + /* Fifo TX overflow interrupt occurred --------------------------------*/ + if (((isrflags & QSPI_IT_TFO) != RESET) && ((itsource & QSPI_IT_TFO) != RESET)) + { + /* Clear interrupt */ + __DAL_QSPI_CLEAR_FLAG(hqspi, QSPI_IT_TFO); + + /* Set QSPI error code to FIFO Threshold Overrun error */ + hqspi->ErrorCode |= DAL_QSPI_ERROR_TX_OVR; + } + + /* Fifo RX underflow interrupt occurred -------------------------------*/ + if (((isrflags & QSPI_IT_RFU) != RESET) && ((itsource & QSPI_IT_RFU) != RESET)) + { + /* Clear interrupt */ + __DAL_QSPI_CLEAR_FLAG(hqspi, QSPI_IT_RFU); + + /* Set QSPI error code to FIFO Threshold Underrun error */ + hqspi->ErrorCode |= DAL_QSPI_ERROR_RX_UDR; + } + + /* Fifo RX overflow interrupt occurred --------------------------------*/ + if (((isrflags & QSPI_IT_RFO) != RESET) && ((itsource & QSPI_IT_RFO) != RESET)) + { + /* Clear interrupt */ + __DAL_QSPI_CLEAR_FLAG(hqspi, QSPI_IT_RFO); + + /* Set QSPI error code to FIFO Threshold Overrun error */ + hqspi->ErrorCode |= DAL_QSPI_ERROR_RX_OVR; + } + + /* Master complete interrupt occurred ---------------------------------*/ + if (((isrflags & QSPI_IT_MST) != RESET) && ((itsource & QSPI_IT_MST) != RESET)) + { + /* Clear interrupt */ + __DAL_QSPI_CLEAR_FLAG(hqspi, QSPI_IT_MST); + + /* Set QSPI error code to Master error */ + hqspi->ErrorCode |= DAL_QSPI_ERROR_MST; + } + + /* Call QSPI Error call back function if need be ----------------------*/ + if (hqspi->ErrorCode != DAL_QSPI_ERROR_NONE) + { +#if (USE_DAL_QSPI_REGISTER_CALLBACKS == 1) + /* Call error callback */ + hqspi->ErrorCallback(hqspi); +#else + /* Call legacy weak error callback */ + DAL_QSPI_ErrorCallback(hqspi); +#endif /* USE_DAL_QSPI_REGISTER_CALLBACKS */ + + hqspi->ErrorCode = DAL_QSPI_ERROR_NONE; + } + return; + } + + /* Fifo tx empty interrupt or rx full interrupt occurred ------------------*/ + if ((((flag & QSPI_FLAG_TFN) != RESET) && ((itsource & QSPI_IT_TFE) != RESET)) || \ + (((isrflags & QSPI_FLAG_RFF) != RESET) && ((itsource & QSPI_IT_RFF) != RESET))) + { + data_reg = &hqspi->Instance->DATA; + + if (hqspi->State == DAL_QSPI_STATE_BUSY_TX) + { + /* Transmission process */ + while (hqspi->TxXferCount > 0U) + { + while (__DAL_QSPI_GET_FLAG(hqspi, QSPI_FLAG_TFN) == RESET); + + /* Write data to TX FIFO */ + *((__IO uint8_t *)data_reg) = (*hqspi->pTxBuffPtr); + hqspi->pTxBuffPtr++; + hqspi->TxXferCount--; + + if (hqspi->TxXferCount == 0) + { + /* Disable the QSPI FIFO Threshold interrupt */ + __DAL_QSPI_DISABLE_IT(hqspi, QSPI_IT_TFE); + break; + } + } + + /* Set QSPI state to Ready */ + hqspi->State = DAL_QSPI_STATE_READY; + +#if (USE_DAL_QSPI_REGISTER_CALLBACKS == 1) + /* Call Tx complete callback */ + hqspi->TxCpltCallback(hqspi); +#else + /* Call legacy weak Tx complete callback */ + DAL_QSPI_TxCpltCallback(hqspi); +#endif /* USE_DAL_QSPI_REGISTER_CALLBACKS */ + } + else if (hqspi->State == DAL_QSPI_STATE_BUSY_RX) + { + /* Receiving process */ + while (hqspi->RxXferCount > 0U) + { + while(__DAL_QSPI_GET_FLAG(hqspi, QSPI_FLAG_RFNE) == RESET); + + /* Read data from RX FIFO */ + *hqspi->pRxBuffPtr = *((__IO uint8_t *)data_reg); + hqspi->pRxBuffPtr++; + hqspi->RxXferCount--; + + if (hqspi->RxXferCount == 0) + { + /* Disable the QSPI FIFO Threshold interrupt */ + __DAL_QSPI_DISABLE_IT(hqspi, QSPI_IT_RFF); + break; + } + } + + /* Set QSPI state to Ready */ + hqspi->State = DAL_QSPI_STATE_READY; + +#if (USE_DAL_QSPI_REGISTER_CALLBACKS == 1) + /* Call Rx complete callback */ + hqspi->RxCpltCallback(hqspi); +#else + /* Call legacy weak Rx complete callback */ + DAL_QSPI_RxCpltCallback(hqspi); +#endif /* USE_DAL_QSPI_REGISTER_CALLBACKS */ + } + else if (hqspi->State == DAL_QSPI_STATE_BUSY_TX_RX) + { + /* Transmission and receiving process */ + while (__DAL_QSPI_GET_FLAG(hqspi, QSPI_FLAG_TFN) != RESET) + { + if (hqspi->TxXferCount > 0U) + { + /* Send the byte */ + *((__IO uint8_t *)data_reg) = (*hqspi->pTxBuffPtr); + hqspi->pTxBuffPtr++; + hqspi->TxXferCount--; + + while((__DAL_QSPI_GET_FLAG(hqspi, QSPI_FLAG_RFNE) != SET) || \ + (__DAL_QSPI_GET_FLAG(hqspi, QSPI_FLAG_BUSY) != RESET)); + + /* Receive the byte */ + *hqspi->pRxBuffPtr = *((__IO uint8_t *)data_reg); + hqspi->pRxBuffPtr++; + hqspi->RxXferCount--; + } + else + { + /* No more data available for the transfer */ + /* Disable the QSPI FIFO Threshold interrupt */ + __DAL_QSPI_DISABLE_IT(hqspi, QSPI_IT_TFE); + break; + } + } + + /* Set QSPI state to Ready */ + hqspi->State = DAL_QSPI_STATE_READY; + +#if (USE_DAL_QSPI_REGISTER_CALLBACKS == 1) + /* Call Tx and Rx complete callback */ + hqspi->TxRxCpltCallback(hqspi); +#else + /* Call legacy weak Tx and Rx complete callback */ + DAL_QSPI_TxRxCpltCallback(hqspi); +#endif /* USE_DAL_QSPI_REGISTER_CALLBACKS */ + } + else if(hqspi->State == DAL_QSPI_STATE_BUSY) + { + /* Set QSPI state to Ready */ + hqspi->State = DAL_QSPI_STATE_READY; + + /* Disable the QSPI FIFO Threshold interrupt */ + __DAL_QSPI_DISABLE_IT(hqspi, QSPI_IT_TFE); + +#if (USE_DAL_QSPI_REGISTER_CALLBACKS == 1) + /* Call Command complete callback */ + hqspi->CmdCpltCallback(hqspi); +#else + /* Call legacy weak Command complete callback */ + DAL_QSPI_CmdCpltCallback(hqspi); +#endif /* USE_DAL_QSPI_REGISTER_CALLBACKS */ + } + else + { + /* Nothing to do */ + } + + /* Wait till BUSY flag reset */ + while (__DAL_QSPI_GET_FLAG(hqspi, QSPI_FLAG_BUSY) != RESET); + } +} + +/** + * @brief Set the command configuration. + * @param hqspi: QSPI handle + * @param cmd: structure that contains the command configuration information + * @param Timeout: Timeout duration + * @retval DAL status + */ +DAL_StatusTypeDef DAL_QSPI_Command(QSPI_HandleTypeDef *hqspi, QSPI_CommandTypeDef *cmd, uint32_t Timeout) +{ + DAL_StatusTypeDef status; + uint32_t tickstart = DAL_GetTick(); + + /* Check the parameters */ + ASSERT_PARAM(IS_QSPI_INSTRUCTION_MODE(cmd->InstructionMode)); + ASSERT_PARAM(IS_QSPI_INSTRUCTION_SIZE(cmd->InstructionSize)); + ASSERT_PARAM(IS_QSPI_INSTRUCTION(cmd->Instruction)); + ASSERT_PARAM(IS_QSPI_ADDRESS_SIZE(cmd->AddressSize)); + ASSERT_PARAM(IS_QSPI_ADDRESS(cmd->Address)); + ASSERT_PARAM(IS_QSPI_TRANSFER_MODE(cmd->TransferMode)); + ASSERT_PARAM(IS_QSPI_FRAME_FORMAT(cmd->FrameFormat)); + ASSERT_PARAM(IS_QSPI_DATA_FRAME_SIZE(cmd->DataFrameSize)); + + /* Process locked */ + __DAL_LOCK(hqspi); + + if (hqspi->State == DAL_QSPI_STATE_READY) + { + hqspi->ErrorCode = DAL_QSPI_ERROR_NONE; + + /* Update QSPI state */ + hqspi->State = DAL_QSPI_STATE_BUSY; + + status = DAL_QSPI_WaitFlagStateUntilTimeout(hqspi, QSPI_FLAG_BUSY, RESET, tickstart, Timeout); + + if (status == DAL_OK) + { + /* Disable the QSPI peripheral */ + __DAL_QSPI_DISABLE(hqspi); + + /* Call the configuration function */ + QSPI_Config(hqspi, cmd); + + /* Enable the Slave Select signal */ + __DAL_QSPI_ENABLE_SS(hqspi); + + /* Enable the QSPI peripheral */ + __DAL_QSPI_ENABLE(hqspi); + + /* Send the command */ + if (cmd->InstructionSize != QSPI_INSTRUCTION_SIZE_NONE) + { + WRITE_REG(hqspi->Instance->DATA, cmd->Instruction); + } + + /* Send the address */ + if (cmd->AddressSize != QSPI_ADDRESS_SIZE_NONE) + { + WRITE_REG(hqspi->Instance->DATA, cmd->Address); + } + + if (cmd->NbData == 0U) + { + if (status == DAL_OK) + { + status = DAL_QSPI_WaitFlagStateUntilTimeout(hqspi, QSPI_FLAG_BUSY, RESET, tickstart, hqspi->Timeout); + } + } + + if (status == DAL_OK) + { + /* Update QSPI state */ + hqspi->State = DAL_QSPI_STATE_READY; + } + } + } + else + { + status = DAL_BUSY; + } + + /* Process unlocked */ + __DAL_UNLOCK(hqspi); + + /* Return function status */ + return status; +} + +/** + * @brief Set the command configuration in interrupt mode. + * @param hqspi: QSPI handle + * @param cmd: structure that contains the command configuration information + * @retval DAL status + */ +DAL_StatusTypeDef DAL_QSPI_Command_IT(QSPI_HandleTypeDef *hqspi, QSPI_CommandTypeDef *cmd) +{ + DAL_StatusTypeDef status = DAL_OK; + uint32_t tickstart = DAL_GetTick(); + + /* Check the parameters */ + + /* Process locked */ + __DAL_LOCK(hqspi); + + if (hqspi->State == DAL_QSPI_STATE_READY) + { + hqspi->ErrorCode = DAL_QSPI_ERROR_NONE; + + /* Update QSPI state */ + hqspi->State = DAL_QSPI_STATE_BUSY; + + status = DAL_QSPI_WaitFlagStateUntilTimeout(hqspi, QSPI_FLAG_BUSY, RESET, tickstart, hqspi->Timeout); + + if (status == DAL_OK) + { + /* Disable the QSPI peripheral */ + __DAL_QSPI_DISABLE(hqspi); + + /* Call the configuration function */ + QSPI_Config(hqspi, cmd); + + /* Enable the Slave Select signal */ + __DAL_QSPI_ENABLE_SS(hqspi); + + /* Enable the QSPI peripheral */ + __DAL_QSPI_ENABLE(hqspi); + + /* Send the command */ + if (cmd->InstructionSize != QSPI_INSTRUCTION_SIZE_NONE) + { + WRITE_REG(hqspi->Instance->DATA, cmd->Instruction); + } + + /* Send the address */ + if (cmd->AddressSize != QSPI_ADDRESS_SIZE_NONE) + { + WRITE_REG(hqspi->Instance->DATA, cmd->Address); + } + + if (cmd->NbData == 0U) + { + /* Process unlocked */ + __DAL_UNLOCK(hqspi); + + /* Enable the QSPI interrupt */ + __DAL_QSPI_ENABLE_IT(hqspi, (QSPI_IT_TFE)); + } + else + { + /* Update QSPI state */ + hqspi->State = DAL_QSPI_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hqspi); + } + } + else + { + /* Process unlocked */ + __DAL_UNLOCK(hqspi); + } + } + else + { + status = DAL_BUSY; + + /* Process unlocked */ + __DAL_UNLOCK(hqspi); + } + + /* Return function status */ + return status; +} + +/** + * @brief Transmit and Receive a byte in blocking mode. + * @param hqspi: QSPI handle + * @param data_in: received data + * @param data_out: transmitted data + * @param Size: number of bytes to transmit and receive + * @param Timeout: Timeout duration + * @retval DAL status + * @note This function is used only in case of standard communication mode. + */ +DAL_StatusTypeDef DAL_QSPI_TransmitReceive(QSPI_HandleTypeDef *hqspi, uint8_t *data_out, uint8_t *data_in, uint32_t Size, uint32_t Timeout) +{ + DAL_StatusTypeDef status = DAL_OK; + uint32_t tickstart = DAL_GetTick(); + __IO uint32_t *data_reg = &hqspi->Instance->DATA; + + /* Process locked */ + __DAL_LOCK(hqspi); + + if (hqspi->State == DAL_QSPI_STATE_READY) + { + hqspi->ErrorCode = DAL_QSPI_ERROR_NONE; + + if ((data_in != NULL) && (data_out != NULL)) + { + /* Update QSPI state */ + hqspi->State = DAL_QSPI_STATE_BUSY_TX_RX; + + hqspi->pTxBuffPtr = data_out; + hqspi->TxXferSize = Size; + hqspi->TxXferCount = Size; + + hqspi->pRxBuffPtr = data_in; + hqspi->RxXferSize = Size; + hqspi->RxXferCount = Size; + + /* Disable the QSPI peripheral */ + __DAL_QSPI_DISABLE(hqspi); + + /* Configure CTRL1 */ + MODIFY_REG(hqspi->Instance->CTRL1, \ + (QSPI_CTRL1_DFS | QSPI_CTRL1_FRF | QSPI_CTRL1_TXMODE), \ + (QSPI_DATA_FRAME_SIZE_8BITS | QSPI_FRAME_FORMAT_STANDARD | QSPI_TRANSFER_MODE_TX_RX)); + + /* Enable the Slave Select signal */ + __DAL_QSPI_ENABLE_SS(hqspi); + + /* Enable the QSPI peripheral */ + __DAL_QSPI_ENABLE(hqspi); + + /* Transmit and Receive data */ + while (hqspi->TxXferCount > 0U) + { + /* Wait till TFN flag set */ + status = DAL_QSPI_WaitFlagStateUntilTimeout(hqspi, QSPI_FLAG_TFN, SET, tickstart, Timeout); + + if (status != DAL_OK) + { + break; + } + + /* Send the byte */ + *((__IO uint8_t *)data_reg) = (*hqspi->pTxBuffPtr); + hqspi->pTxBuffPtr++; + hqspi->TxXferCount--; + + /* Wait till RFNE flag set or BUSY flag reset */ + while (((__DAL_QSPI_GET_FLAG(hqspi, QSPI_FLAG_RFNE)) != SET) || \ + ((__DAL_QSPI_GET_FLAG(hqspi, QSPI_FLAG_BUSY)) != RESET)) + { + /* Check for the Timeout */ + if (Timeout != DAL_MAX_DELAY) + { + if (((DAL_GetTick() - tickstart) > Timeout) || (Timeout == 0U)) + { + hqspi->State = DAL_QSPI_STATE_ERROR; + hqspi->ErrorCode |= DAL_QSPI_ERROR_TIMEOUT; + + status = DAL_ERROR; + } + } + } + + if (status != DAL_OK) + { + break; + } + + /* Receive the byte */ + *hqspi->pRxBuffPtr = *((__IO uint8_t *)data_reg); + hqspi->pRxBuffPtr++; + hqspi->RxXferCount--; + } + + /* Update QSPI state */ + hqspi->State = DAL_QSPI_STATE_READY; + } + } + else + { + status = DAL_BUSY; + } + + /* Process unlocked */ + __DAL_UNLOCK(hqspi); + + return status; +} + +/** + * @brief Transmit and Receive an amount of data in non-blocking mode with Interrupt. + * @param hqspi: QSPI handle + * @param data_in: received data + * @param data_out: transmitted data + * @param Size: number of bytes to transmit and receive + * @retval DAL status + * @note This function is used only in case of standard communication mode. + */ +DAL_StatusTypeDef DAL_QSPI_TransmitReceive_IT(QSPI_HandleTypeDef *hqspi, uint8_t *data_out, uint8_t *data_in, uint32_t Size) +{ + DAL_StatusTypeDef status = DAL_OK; + + /* Process locked */ + __DAL_LOCK(hqspi); + + if (hqspi->State == DAL_QSPI_STATE_READY) + { + hqspi->ErrorCode = DAL_QSPI_ERROR_NONE; + + if ((data_in != NULL) && (data_out != NULL)) + { + /* Update QSPI state */ + hqspi->State = DAL_QSPI_STATE_BUSY_TX_RX; + + hqspi->pTxBuffPtr = data_out; + hqspi->TxXferSize = Size; + hqspi->TxXferCount = Size; + + hqspi->pRxBuffPtr = data_in; + hqspi->RxXferSize = Size; + hqspi->RxXferCount = Size; + + /* Disable the QSPI peripheral */ + __DAL_QSPI_DISABLE(hqspi); + + /* Configure CTRL1 */ + MODIFY_REG(hqspi->Instance->CTRL1, \ + (QSPI_CTRL1_DFS | QSPI_CTRL1_FRF | QSPI_CTRL1_TXMODE), \ + (QSPI_DATA_FRAME_SIZE_8BITS | QSPI_FRAME_FORMAT_STANDARD | QSPI_TRANSFER_MODE_TX_RX)); + + /* Process unlocked */ + __DAL_UNLOCK(hqspi); + + /* Enable the QSPI interrupt */ + __DAL_QSPI_ENABLE_IT(hqspi, (QSPI_IT_TFE)); + + /* Enable the Slave Select signal */ + __DAL_QSPI_ENABLE_SS(hqspi); + + /* Enable the QSPI peripheral */ + __DAL_QSPI_ENABLE(hqspi); + + } + else + { + hqspi->ErrorCode |= DAL_QSPI_ERROR_INVALID_PARAM; + status = DAL_ERROR; + + /* Process unlocked */ + __DAL_UNLOCK(hqspi); + } + } + else + { + status = DAL_BUSY; + + /* Process unlocked */ + __DAL_UNLOCK(hqspi); + } + + return status; +} + +/** + * @brief Transmit an amount of data in blocking mode. + * @param hqspi: QSPI handle + * @param pData: pointer to data buffer + * @param Timeout: Timeout duration + * @retval DAL status + */ +DAL_StatusTypeDef DAL_QSPI_Transmit(QSPI_HandleTypeDef *hqspi, uint8_t *pData, uint32_t Timeout) +{ + DAL_StatusTypeDef status = DAL_OK; + uint32_t tickstart = DAL_GetTick(); + __IO uint32_t *data_reg = &hqspi->Instance->DATA; + + /* Process locked */ + __DAL_LOCK(hqspi); + + if (hqspi->State == DAL_QSPI_STATE_READY) + { + hqspi->ErrorCode = DAL_QSPI_ERROR_NONE; + + if (pData != NULL) + { + /* Update QSPI state */ + hqspi->State = DAL_QSPI_STATE_BUSY_TX; + + hqspi->pTxBuffPtr = pData; + hqspi->TxXferSize = READ_BIT(hqspi->Instance->CTRL2, QSPI_CTRL2_NDF) + 1U; + hqspi->TxXferCount = READ_BIT(hqspi->Instance->CTRL2, QSPI_CTRL2_NDF) + 1U; + + /* Transmit and Receive data */ + while (hqspi->TxXferCount > 0U) + { + /* Wait till TFN flag set */ + status = DAL_QSPI_WaitFlagStateUntilTimeout(hqspi, QSPI_FLAG_TFN, SET, tickstart, Timeout); + + if (status != DAL_OK) + { + break; + } + + /* Send the byte */ + *((__IO uint8_t *)data_reg) = (*hqspi->pTxBuffPtr); + hqspi->pTxBuffPtr++; + hqspi->TxXferCount--; + } + + if (status == DAL_OK) + { + /* Wait till BUSY flag reset */ + status = DAL_QSPI_WaitFlagStateUntilTimeout(hqspi, QSPI_FLAG_BUSY, RESET, tickstart, Timeout); + } + + /* Update QSPI state */ + hqspi->State = DAL_QSPI_STATE_READY; + } + else + { + hqspi->ErrorCode |= DAL_QSPI_ERROR_INVALID_PARAM; + status = DAL_ERROR; + } + } + else + { + status = DAL_BUSY; + } + + /* Process unlocked */ + __DAL_UNLOCK(hqspi); + + return status; +} + +/** + * @brief Transmit an amount of data in non-blocking mode with Interrupt. + * @param hqspi: QSPI handle + * @param pData: pointer to data buffer + * @retval DAL status + */ +DAL_StatusTypeDef DAL_QSPI_Transmit_IT(QSPI_HandleTypeDef *hqspi, uint8_t *pData) +{ + DAL_StatusTypeDef status = DAL_OK; + + /* Process locked */ + __DAL_LOCK(hqspi); + + if (hqspi->State == DAL_QSPI_STATE_READY) + { + hqspi->ErrorCode = DAL_QSPI_ERROR_NONE; + + if (pData != NULL) + { + /* Update QSPI state */ + hqspi->State = DAL_QSPI_STATE_BUSY_TX; + + hqspi->pTxBuffPtr = pData; + hqspi->TxXferSize = READ_BIT(hqspi->Instance->CTRL2, QSPI_CTRL2_NDF) + 1U; + hqspi->TxXferCount = READ_BIT(hqspi->Instance->CTRL2, QSPI_CTRL2_NDF) + 1U; + + /* Clear interrupt */ + __DAL_QSPI_CLEAR_FLAG(hqspi, QSPI_IT_TFE); + + /* Process unlocked */ + __DAL_UNLOCK(hqspi); + + /* Enable the QSPI interrupt */ + __DAL_QSPI_ENABLE_IT(hqspi, (QSPI_IT_TFE)); + } + else + { + hqspi->ErrorCode |= DAL_QSPI_ERROR_INVALID_PARAM; + status = DAL_ERROR; + + /* Process unlocked */ + __DAL_UNLOCK(hqspi); + } + } + else + { + status = DAL_BUSY; + + /* Process unlocked */ + __DAL_UNLOCK(hqspi); + } + + return status; +} + +/** + * @brief Transmit an amount of data in non-blocking mode with DMA. + * @param hqspi: QSPI handle + * @param pData: pointer to data buffer + * @retval DAL status + */ +DAL_StatusTypeDef DAL_QSPI_Transmit_DMA(QSPI_HandleTypeDef *hqspi, uint8_t *pData) +{ + DAL_StatusTypeDef status = DAL_OK; + + /* Process locked */ + __DAL_LOCK(hqspi); + + if (hqspi->State == DAL_QSPI_STATE_READY) + { + /* Clear the error code */ + hqspi->ErrorCode = DAL_QSPI_ERROR_NONE; + + if (pData != NULL) + { + /* Update QSPI state */ + hqspi->State = DAL_QSPI_STATE_BUSY_TX; + + hqspi->pTxBuffPtr = pData; + hqspi->TxXferSize = READ_BIT(hqspi->Instance->CTRL2, QSPI_CTRL2_NDF) + 1U; + hqspi->TxXferCount = READ_BIT(hqspi->Instance->CTRL2, QSPI_CTRL2_NDF) + 1U; + + /* Set the QSPI DMA transfer complete callback */ + hqspi->hdmatx->XferCpltCallback = QSPI_DMATxCplt; + + /* Set the QSPI DMA error callback */ + hqspi->hdmatx->XferErrorCallback = QSPI_DMAError; + + /* Clear the DMA abort callback */ + hqspi->hdmatx->XferAbortCallback = NULL; + + /* Enable the DMA stream */ + if (DAL_DMA_Start_IT(hqspi->hdmatx, (uint32_t)hqspi->pTxBuffPtr, (uint32_t)&hqspi->Instance->DATA, hqspi->TxXferCount) == DAL_OK) + { + /* Clear interrupt */ + __DAL_QSPI_CLEAR_FLAG(hqspi, QSPI_IT_TFE); + + /* Process unlocked */ + __DAL_UNLOCK(hqspi); + + /* Enable the QSPI DMA transfer for transmit request by setting the TDMAEN bit + in the QSPI DMACTRL register */ + SET_BIT(hqspi->Instance->DMACTRL, QSPI_DMACTRL_TDMAEN); + } + else + { + status = DAL_ERROR; + hqspi->ErrorCode |= DAL_QSPI_ERROR_DMA; + hqspi->State = DAL_QSPI_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hqspi); + } + } + else + { + hqspi->ErrorCode |= DAL_QSPI_ERROR_INVALID_PARAM; + status = DAL_ERROR; + + /* Process unlocked */ + __DAL_UNLOCK(hqspi); + } + } + else + { + status = DAL_BUSY; + + /* Process unlocked */ + __DAL_UNLOCK(hqspi); + } + + return status; +} + +/** + * @brief Receive an amount of data in blocking mode. + * @param hqspi: QSPI handle + * @param pData: pointer to data buffer + * @param Timeout: Timeout duration + * @retval DAL status + */ +DAL_StatusTypeDef DAL_QSPI_Receive(QSPI_HandleTypeDef *hqspi, uint8_t *pData, uint32_t Timeout) +{ + DAL_StatusTypeDef status; + uint32_t tickstart = DAL_GetTick(); + __IO uint32_t *data_reg = &hqspi->Instance->DATA; + + /* Process locked */ + __DAL_LOCK(hqspi); + + if (hqspi->State == DAL_QSPI_STATE_READY) + { + hqspi->ErrorCode = DAL_QSPI_ERROR_NONE; + + if (pData != NULL) + { + /* Update QSPI state */ + hqspi->State = DAL_QSPI_STATE_BUSY_RX; + + hqspi->pRxBuffPtr = pData; + hqspi->RxXferSize = READ_BIT(hqspi->Instance->CTRL2, QSPI_CTRL2_NDF) + 1U; + hqspi->RxXferCount = READ_BIT(hqspi->Instance->CTRL2, QSPI_CTRL2_NDF) + 1U; + + while (hqspi->RxXferCount > 0U) + { + /* Wait till RFNE flag set */ + status = DAL_QSPI_WaitFlagStateUntilTimeout(hqspi, QSPI_FLAG_RFNE, SET, tickstart, Timeout); + + if (status != DAL_OK) + { + break; + } + + /* Receive the byte */ + *hqspi->pRxBuffPtr = *((__IO uint8_t *)data_reg); + hqspi->pRxBuffPtr++; + hqspi->RxXferCount--; + } + + if (status == DAL_OK) + { + /* Wait till BUSY flag reset */ + status = DAL_QSPI_WaitFlagStateUntilTimeout(hqspi, QSPI_FLAG_BUSY, RESET, tickstart, Timeout); + } + + /* Update QSPI state */ + hqspi->State = DAL_QSPI_STATE_READY; + } + else + { + hqspi->ErrorCode |= DAL_QSPI_ERROR_INVALID_PARAM; + status = DAL_ERROR; + } + } + else + { + status = DAL_BUSY; + } + + /* Process unlocked */ + __DAL_UNLOCK(hqspi); + + return status; +} + +/** + * @brief Receive an amount of data in non-blocking mode with Interrupt. + * @param hqspi: QSPI handle + * @param pData: pointer to data buffer + * @retval DAL status + */ +DAL_StatusTypeDef DAL_QSPI_Receive_IT(QSPI_HandleTypeDef *hqspi, uint8_t *pData) +{ + DAL_StatusTypeDef status = DAL_OK; + + /* Process locked */ + __DAL_LOCK(hqspi); + + if (hqspi->State == DAL_QSPI_STATE_READY) + { + hqspi->ErrorCode = DAL_QSPI_ERROR_NONE; + + if (pData != NULL) + { + /* Update QSPI state */ + hqspi->State = DAL_QSPI_STATE_BUSY_RX; + + hqspi->pRxBuffPtr = pData; + hqspi->RxXferSize = READ_BIT(hqspi->Instance->CTRL2, QSPI_CTRL2_NDF) + 1U; + hqspi->RxXferCount = READ_BIT(hqspi->Instance->CTRL2, QSPI_CTRL2_NDF) + 1U; + + /* Clear interrupt */ + __DAL_QSPI_CLEAR_FLAG(hqspi, QSPI_IT_RFF); + + /* Process unlocked */ + __DAL_UNLOCK(hqspi); + + /* Enable the QSPI interrupt */ + __DAL_QSPI_ENABLE_IT(hqspi, (QSPI_IT_RFF)); + } + else + { + hqspi->ErrorCode |= DAL_QSPI_ERROR_INVALID_PARAM; + status = DAL_ERROR; + + /* Process unlocked */ + __DAL_UNLOCK(hqspi); + } + } + else + { + status = DAL_BUSY; + + /* Process unlocked */ + __DAL_UNLOCK(hqspi); + } + + return status; +} + +/** + * @brief Receive an amount of data in non-blocking mode with DMA. + * @param hqspi: QSPI handle + * @param pData: pointer to data buffer + * @retval DAL status + */ +DAL_StatusTypeDef DAL_QSPI_Receive_DMA(QSPI_HandleTypeDef *hqspi, uint8_t *pData) +{ + DAL_StatusTypeDef status = DAL_OK; + + /* Process locked */ + __DAL_LOCK(hqspi); + + if (hqspi->State == DAL_QSPI_STATE_READY) + { + /* Clear the error code */ + hqspi->ErrorCode = DAL_QSPI_ERROR_NONE; + + if (pData != NULL) + { + /* Update QSPI state */ + hqspi->State = DAL_QSPI_STATE_BUSY_RX; + + hqspi->pRxBuffPtr = pData; + hqspi->RxXferSize = READ_BIT(hqspi->Instance->CTRL2, QSPI_CTRL2_NDF) + 1U; + hqspi->RxXferCount = READ_BIT(hqspi->Instance->CTRL2, QSPI_CTRL2_NDF) + 1U; + + /* Set the QSPI DMA transfer complete callback */ + hqspi->hdmarx->XferCpltCallback = QSPI_DMARxCplt; + + /* Set the QSPI DMA error callback */ + hqspi->hdmarx->XferErrorCallback = QSPI_DMAError; + + /* Clear the DMA abort callback */ + hqspi->hdmarx->XferAbortCallback = NULL; + + /* Enable the DMA stream */ + if (DAL_DMA_Start_IT(hqspi->hdmarx, (uint32_t)&hqspi->Instance->DATA, (uint32_t)hqspi->pRxBuffPtr, hqspi->RxXferCount) == DAL_OK) + { + /* Clear interrupt */ + __DAL_QSPI_CLEAR_FLAG(hqspi, QSPI_IT_RFF); + + /* Process unlocked */ + __DAL_UNLOCK(hqspi); + + /* Enable the QSPI DMA transfer for receive request by setting the RDMAEN bit + in the QSPI DMACTRL register */ + SET_BIT(hqspi->Instance->DMACTRL, QSPI_DMACTRL_RDMAEN); + } + else + { + status = DAL_ERROR; + hqspi->ErrorCode |= DAL_QSPI_ERROR_DMA; + hqspi->State = DAL_QSPI_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hqspi); + } + } + else + { + hqspi->ErrorCode |= DAL_QSPI_ERROR_INVALID_PARAM; + status = DAL_ERROR; + + /* Process unlocked */ + __DAL_UNLOCK(hqspi); + } + } + else + { + status = DAL_BUSY; + + /* Process unlocked */ + __DAL_UNLOCK(hqspi); + } + + return status; +} + +/** + * @brief Transfer error callback. + * @param hqspi: QSPI handle + * @retval None + */ +__weak void DAL_QSPI_ErrorCallback(QSPI_HandleTypeDef *hqspi) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hqspi); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_QSPI_ErrorCallback could be implemented in the user file + */ +} + +/** + * @brief Abort completed callback. + * @param hqspi: QSPI handle + * @retval None + */ +__weak void DAL_QSPI_AbortCpltCallback(QSPI_HandleTypeDef *hqspi) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hqspi); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_QSPI_AbortCpltCallback could be implemented in the user file + */ +} + +/** + * @brief FIFO threshold callback. + * @param hqspi: QSPI handle + * @retval None + */ +__weak void DAL_QSPI_FifoThresholdCallback(QSPI_HandleTypeDef *hqspi) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hqspi); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_QSPI_FifoThresholdCallback could be implemented in the user file + */ +} + +/** + * @brief Command completed callback. + * @param hqspi: QSPI handle + * @retval None + */ +__weak void DAL_QSPI_CmdCpltCallback(QSPI_HandleTypeDef *hqspi) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hqspi); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_QSPI_CmdCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Rx Transfer completed callback. + * @param hqspi: QSPI handle + * @retval None + */ +__weak void DAL_QSPI_RxCpltCallback(QSPI_HandleTypeDef *hqspi) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hqspi); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_QSPI_RxCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Tx Transfer completed callback. + * @param hqspi: QSPI handle + * @retval None + */ +__weak void DAL_QSPI_TxCpltCallback(QSPI_HandleTypeDef *hqspi) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hqspi); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_QSPI_TxCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Tx and Rx Transfer completed callback. + * @param hqspi: QSPI handle + * @retval None + */ +__weak void DAL_QSPI_TxRxCpltCallback(QSPI_HandleTypeDef *hqspi) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hqspi); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_QSPI_TxRxCpltCallback could be implemented in the user file + */ +} + +#if (USE_DAL_QSPI_REGISTER_CALLBACKS == 1) +/** + * @brief Register a User QSPI Callback + * To be used instead of the weak predefined callback + * @param hqspi: QSPI handle + * @param CallbackID: ID of the callback to be registered + * This parameter can be one of the following values: + * @arg @ref DAL_QSPI_ERROR_CB_ID QSPI Error Callback ID + * @arg @ref DAL_QSPI_ABORT_CB_ID QSPI Abort Callback ID + * @arg @ref DAL_QSPI_CMD_CPLT_CB_ID QSPI Command Complete Callback ID + * @arg @ref DAL_QSPI_RX_CPLT_CB_ID QSPI Rx Complete Callback ID + * @arg @ref DAL_QSPI_TX_CPLT_CB_ID QSPI Tx Complete Callback ID + * @arg @ref DAL_QSPI_TX_RX_CPLT_CB_ID QSPI Tx Rx Complete Callback ID + * @arg @ref DAL_QSPI_MSP_INIT_CB_ID QSPI MspInit Callback ID + * @arg @ref DAL_QSPI_MSP_DEINIT_CB_ID QSPI MspDeInit Callback ID + * @param pCallback: pointer to the Callback function + * @retval status + */ +DAL_StatusTypeDef DAL_QSPI_RegisterCallback(QSPI_HandleTypeDef *hqspi, DAL_QSPI_CallbackIDTypeDef CallbackID, pQSPI_CallbackTypeDef pCallback) +{ + DAL_StatusTypeDef status = DAL_OK; + + if (pCallback == NULL) + { + /* Update the error code */ + hqspi->ErrorCode |= DAL_QSPI_ERROR_INVALID_CALLBACK; + + return DAL_ERROR; + } + + /* Process locked */ + __DAL_LOCK(hqspi); + + if (hqspi->State == DAL_QSPI_STATE_READY) + { + switch (CallbackID) + { + case DAL_QSPI_ERROR_CB_ID : + hqspi->ErrorCallback = pCallback; + break; + + case DAL_QSPI_ABORT_CB_ID : + hqspi->AbortCpltCallback = pCallback; + break; + + case DAL_QSPI_CMD_CPLT_CB_ID : + hqspi->CmdCpltCallback = pCallback; + break; + + case DAL_QSPI_RX_CPLT_CB_ID : + hqspi->RxCpltCallback = pCallback; + break; + + case DAL_QSPI_TX_CPLT_CB_ID : + hqspi->TxCpltCallback = pCallback; + break; + + case DAL_QSPI_TX_RX_CPLT_CB_ID : + hqspi->TxRxCpltCallback = pCallback; + break; + + case DAL_QSPI_MSP_INIT_CB_ID : + hqspi->MspInitCallback = pCallback; + break; + + case DAL_QSPI_MSP_DEINIT_CB_ID : + hqspi->MspDeInitCallback = pCallback; + break; + + default : + /* Update the error code */ + hqspi->ErrorCode |= DAL_QSPI_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = DAL_ERROR; + break; + } + } + else if (hqspi->State == DAL_QSPI_STATE_RESET) + { + switch (CallbackID) + { + case DAL_QSPI_MSP_INIT_CB_ID : + hqspi->MspInitCallback = pCallback; + break; + + case DAL_QSPI_MSP_DEINIT_CB_ID : + hqspi->MspDeInitCallback = pCallback; + break; + + default : + /* Update the error code */ + hqspi->ErrorCode |= DAL_QSPI_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = DAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + hqspi->ErrorCode |= DAL_QSPI_ERROR_INVALID_CALLBACK; + + /* Update return status */ + status = DAL_ERROR; + } + + /* Process unlocked */ + __DAL_UNLOCK(hqspi); + + return status; +} + +/** + * @brief Unregister a User QSPI Callback + * QSPI Callback is redirected to the weak predefined callback + * @param hqspi: QSPI handle + * @param CallbackID: ID of the callback to be unregistered + * This parameter can be one of the following values: + * @arg @ref DAL_QSPI_ERROR_CB_ID QSPI Error Callback ID + * @arg @ref DAL_QSPI_ABORT_CB_ID QSPI Abort Callback ID + * @arg @ref DAL_QSPI_CMD_CPLT_CB_ID QSPI Command Complete Callback ID + * @arg @ref DAL_QSPI_RX_CPLT_CB_ID QSPI Rx Complete Callback ID + * @arg @ref DAL_QSPI_TX_CPLT_CB_ID QSPI Tx Complete Callback ID + * @arg @ref DAL_QSPI_TX_RX_CPLT_CB_ID QSPI Tx Rx Complete Callback ID + * @arg @ref DAL_QSPI_MSP_INIT_CB_ID QSPI MspInit Callback ID + * @arg @ref DAL_QSPI_MSP_DEINIT_CB_ID QSPI MspDeInit Callback ID + * @retval status + */ +DAL_StatusTypeDef DAL_QSPI_UnRegisterCallback(QSPI_HandleTypeDef *hqspi, DAL_QSPI_CallbackIDTypeDef CallbackID) +{ + DAL_StatusTypeDef status = DAL_OK; + + /* Process locked */ + __DAL_LOCK(hqspi); + + if (hqspi->State == DAL_QSPI_STATE_READY) + { + switch (CallbackID) + { + case DAL_QSPI_ERROR_CB_ID : + hqspi->ErrorCallback = DAL_QSPI_ErrorCallback; /* Legacy weak (surcharged) callback */ + break; + + case DAL_QSPI_ABORT_CB_ID : + hqspi->AbortCpltCallback = DAL_QSPI_AbortCpltCallback; /* Legacy weak (surcharged) callback */ + break; + + case DAL_QSPI_CMD_CPLT_CB_ID : + hqspi->CmdCpltCallback = DAL_QSPI_CmdCpltCallback; /* Legacy weak (surcharged) callback */ + break; + + case DAL_QSPI_RX_CPLT_CB_ID : + hqspi->RxCpltCallback = DAL_QSPI_RxCpltCallback; /* Legacy weak (surcharged) callback */ + break; + + case DAL_QSPI_TX_CPLT_CB_ID : + hqspi->TxCpltCallback = DAL_QSPI_TxCpltCallback; /* Legacy weak (surcharged) callback */ + break; + + case DAL_QSPI_TX_RX_CPLT_CB_ID : + hqspi->TxRxCpltCallback = DAL_QSPI_TxRxCpltCallback; /* Legacy weak (surcharged) callback */ + break; + + case DAL_QSPI_MSP_INIT_CB_ID : + hqspi->MspInitCallback = DAL_QSPI_MspInit; /* Legacy weak (surcharged) callback */ + break; + + case DAL_QSPI_MSP_DEINIT_CB_ID : + hqspi->MspDeInitCallback = DAL_QSPI_MspDeInit; /* Legacy weak (surcharged) callback */ + break; + + default : + /* Update the error code */ + hqspi->ErrorCode |= DAL_QSPI_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = DAL_ERROR; + break; + } + } + else if (hqspi->State == DAL_QSPI_STATE_RESET) + { + switch (CallbackID) + { + case DAL_QSPI_MSP_INIT_CB_ID : + hqspi->MspInitCallback = DAL_QSPI_MspInit; /* Legacy weak (surcharged) callback */ + break; + + case DAL_QSPI_MSP_DEINIT_CB_ID : + hqspi->MspDeInitCallback = DAL_QSPI_MspDeInit; /* Legacy weak (surcharged) callback */ + break; + + default : + /* Update the error code */ + hqspi->ErrorCode |= DAL_QSPI_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = DAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + hqspi->ErrorCode |= DAL_QSPI_ERROR_INVALID_CALLBACK; + + /* Update return status */ + status = DAL_ERROR; + } + + /* Process unlocked */ + __DAL_UNLOCK(hqspi); + + return status; +} +#endif /* USE_DAL_QSPI_REGISTER_CALLBACKS */ + +/** + * @} + */ + +/** @defgroup QSPI_Exported_Functions_Group3 Peripheral Control functions + * @brief QSPI control and state functions + * + * @verbatim + * =============================================================================== + * ##### Peripheral Control and State functions ##### + * =============================================================================== + * [..] + * This subsection provides a set of functions allowing to : + * (+) Check in run-time the state of the driver. + * (+) Check the error code set during last operation. + * (+) Abort any operation. + * + * @endverbatim + * @{ + */ + +/** + * @brief Reture the QSPI handle state. + * @param hqspi QSPI handle + * @retval DAL state + */ +DAL_QSPI_StateTypeDef DAL_QSPI_GetState(QSPI_HandleTypeDef *hqspi) +{ + /* Return QSPI handle state */ + return hqspi->State; +} + +/** + * @brief Return the QSPI error code. + * @param hqspi QSPI handle + * @retval DAL error code + */ +uint32_t DAL_QSPI_GetError(QSPI_HandleTypeDef *hqspi) +{ + /* Return QSPI error code */ + return hqspi->ErrorCode; +} + +/** + * @brief Abort the current transmission. + * @param hqspi QSPI handle + * @retval DAL status + */ +DAL_StatusTypeDef DAL_QSPI_Abort(QSPI_HandleTypeDef *hqspi) +{ + DAL_StatusTypeDef status = DAL_OK; + uint32_t tickstart = DAL_GetTick(); + + /* Check if the state is in one of the busy states */ + if (((uint32_t)hqspi->State & 0x02) != 0U) + { + /* Process locked */ + __DAL_LOCK(hqspi); + + if ((hqspi->Instance->DMACTRL & QSPI_DMACTRL_TDMAEN) != 0U) + { + /* Disable the QSPI DMA Tx request */ + CLEAR_BIT(hqspi->Instance->DMACTRL, QSPI_DMACTRL_TDMAEN); + + /* Abort the QSPI DMA Tx channel */ + if (DAL_DMA_Abort(hqspi->hdmatx) != DAL_OK) + { + hqspi->ErrorCode |= DAL_QSPI_ERROR_DMA; + } + } + + if ((hqspi->Instance->DMACTRL & QSPI_DMACTRL_RDMAEN) != 0U) + { + /* Disable the QSPI DMA Rx request */ + CLEAR_BIT(hqspi->Instance->DMACTRL, QSPI_DMACTRL_RDMAEN); + + /* Abort the QSPI DMA Rx channel */ + if (DAL_DMA_Abort(hqspi->hdmarx) != DAL_OK) + { + hqspi->ErrorCode |= DAL_QSPI_ERROR_DMA; + } + } + + if (__DAL_QSPI_GET_FLAG(hqspi, QSPI_FLAG_BUSY) != RESET) + { + /* Disable slave select */ + __DAL_QSPI_DISABLE_SS(hqspi); + + /* Disable the QSPI peripheral */ + __DAL_QSPI_DISABLE(hqspi); + + /* Wait till BUSY flag reset */ + status = DAL_QSPI_WaitFlagStateUntilTimeout(hqspi, QSPI_FLAG_BUSY, RESET, tickstart, hqspi->Timeout); + } + else + { + /* Update QSPI state */ + hqspi->State = DAL_QSPI_STATE_READY; + } + } + + return status; +} + +/** + * @brief Abort the current transmission (non-blocking mode). + * @param hqspi QSPI handle + * @retval DAL status + */ +DAL_StatusTypeDef DAL_QSPI_Abort_IT(QSPI_HandleTypeDef *hqspi) +{ + DAL_StatusTypeDef status = DAL_OK; + uint32_t tickstart = DAL_GetTick(); + + /* Check if the state is in one of the busy states */ + if (((uint32_t)hqspi->State & 0x02) != 0U) + { + /* Process locked */ + __DAL_LOCK(hqspi); + + /* Update QSPI state */ + hqspi->State = DAL_QSPI_STATE_ABORT; + + /* Disable QSPI interrupts */ + __DAL_QSPI_DISABLE_IT(hqspi, QSPI_IT_TFE \ + | QSPI_IT_TFO \ + | QSPI_IT_RFU \ + | QSPI_IT_RFO \ + | QSPI_IT_RFF \ + | QSPI_IT_MST); + if (hqspi->hdmatx != NULL) + { + if ((hqspi->Instance->DMACTRL & QSPI_DMACTRL_TDMAEN) != 0U) + { + /* Disable the QSPI DMA Tx request */ + CLEAR_BIT(hqspi->Instance->DMACTRL, QSPI_DMACTRL_TDMAEN); + + /* Abort the QSPI DMA Tx channel */ + hqspi->hdmatx->XferAbortCallback = QSPI_DMAAbortCplt; + if (DAL_DMA_Abort_IT(hqspi->hdmatx) != DAL_OK) + { + /* Update QSPI state */ + hqspi->State = DAL_QSPI_STATE_READY; + + /* Abort completed callback */ +#if (USE_DAL_QSPI_REGISTER_CALLBACKS == 1) + hqspi->AbortCpltCallback(hqspi); +#else + DAL_QSPI_AbortCpltCallback(hqspi); +#endif /* USE_DAL_QSPI_REGISTER_CALLBACKS */ + } + } + else + { + hqspi->hdmatx->XferAbortCallback = NULL; + } + } + + if (hqspi->hdmarx != NULL) + { + if ((hqspi->Instance->DMACTRL & QSPI_DMACTRL_RDMAEN) != 0U) + { + /* Disable the QSPI DMA Rx request */ + CLEAR_BIT(hqspi->Instance->DMACTRL, QSPI_DMACTRL_RDMAEN); + + /* Abort the QSPI DMA Rx channel */ + hqspi->hdmarx->XferAbortCallback = QSPI_DMAAbortCplt; + if (DAL_DMA_Abort_IT(hqspi->hdmarx) != DAL_OK) + { + /* Update QSPI state */ + hqspi->State = DAL_QSPI_STATE_READY; + + /* Abort completed callback */ +#if (USE_DAL_QSPI_REGISTER_CALLBACKS == 1) + hqspi->AbortCpltCallback(hqspi); +#else + DAL_QSPI_AbortCpltCallback(hqspi); +#endif /* USE_DAL_QSPI_REGISTER_CALLBACKS */ + } + } + else + { + hqspi->hdmarx->XferAbortCallback = NULL; + } + } + + if (__DAL_QSPI_GET_FLAG(hqspi, QSPI_FLAG_BUSY) != RESET) + { + /* Disable slave select */ + __DAL_QSPI_DISABLE_SS(hqspi); + + /* Disable the QSPI peripheral */ + __DAL_QSPI_DISABLE(hqspi); + + /* Wait till BUSY flag reset */ + status = DAL_QSPI_WaitFlagStateUntilTimeout(hqspi, QSPI_FLAG_BUSY, RESET, tickstart, hqspi->Timeout); + } + else + { + /* Update QSPI state */ + hqspi->State = DAL_QSPI_STATE_READY; + } + } + + return status; +} + +/** + * @brief Set QSPI timeout. + * @param hqspi QSPI handle + * @param Timeout Timeout for the QSPI memory access + * @retval None + */ +void DAL_QSPI_SetTimeout(QSPI_HandleTypeDef *hqspi, uint32_t Timeout) +{ + hqspi->Timeout = Timeout; +} + +/** + * @brief Set QSPI TX Fifo threshold. + * @param hqspi QSPI handle + * @param Threshold threshold for the QSPI Fifo + * @retval DAL status + */ +DAL_StatusTypeDef DAL_QSPI_SetTxFifoThreshold(QSPI_HandleTypeDef *hqspi, uint32_t Threshold) +{ + DAL_StatusTypeDef status = DAL_OK; + + /* Process locked */ + __DAL_LOCK(hqspi); + + if (hqspi->State == DAL_QSPI_STATE_READY) + { + /* Check the parameters */ + ASSERT_PARAM(IS_QSPI_TX_FIFO_THRESHOLD(Threshold)); + + /* Disable the QSPI peripheral */ + __DAL_QSPI_DISABLE(hqspi); + + /* Configure FIFO threshold */ + MODIFY_REG(hqspi->Instance->TFTL, QSPI_TFTL_TFT, Threshold); + + /* Enable the QSPI peripheral */ + __DAL_QSPI_ENABLE(hqspi); + } + else + { + status = DAL_BUSY; + } + + /* Process unlocked */ + __DAL_UNLOCK(hqspi); + + return status; +} + +/** + * @brief Set QSPI RX Fifo threshold. + * @param hqspi QSPI handle + * @param Threshold threshold for the QSPI Fifo + * @retval DAL status + */ +DAL_StatusTypeDef DAL_QSPI_SetRxFifoThreshold(QSPI_HandleTypeDef *hqspi, uint32_t Threshold) +{ + DAL_StatusTypeDef status = DAL_OK; + + /* Process locked */ + __DAL_LOCK(hqspi); + + if (hqspi->State == DAL_QSPI_STATE_READY) + { + /* Check the parameters */ + ASSERT_PARAM(IS_QSPI_RX_FIFO_THRESHOLD(Threshold)); + + /* Disable the QSPI peripheral */ + __DAL_QSPI_DISABLE(hqspi); + + /* Configure FIFO threshold */ + MODIFY_REG(hqspi->Instance->RFTL, QSPI_RFTL_RFT, Threshold); + + /* Enable the QSPI peripheral */ + __DAL_QSPI_ENABLE(hqspi); + } + else + { + status = DAL_BUSY; + } + + /* Process unlocked */ + __DAL_UNLOCK(hqspi); + + return status; +} + +/** + * @berief Set QSPI Tx Fifo level. + * @param hqspi QSPI handle + * @param Level level for the QSPI Fifo + * @retval DAL status + */ +DAL_StatusTypeDef DAL_QSPI_SetTxFifoLevel(QSPI_HandleTypeDef *hqspi, uint32_t Level) +{ + DAL_StatusTypeDef status = DAL_OK; + + /* Process locked */ + __DAL_LOCK(hqspi); + + if (hqspi->State == DAL_QSPI_STATE_READY) + { + /* Check the parameters */ + ASSERT_PARAM(IS_QSPI_TX_FIFO_LEVEL(Level)); + + /* Disable the QSPI peripheral */ + __DAL_QSPI_DISABLE(hqspi); + + /* Configure FIFO level */ + MODIFY_REG(hqspi->Instance->TFTL, QSPI_TFTL_TFTH, Level); + + /* Enable the QSPI peripheral */ + __DAL_QSPI_ENABLE(hqspi); + } + else + { + status = DAL_BUSY; + } + + /* Process unlocked */ + __DAL_UNLOCK(hqspi); + + return status; +} + +/** + * @brief Get QSPI Tx Fifo threshold. + * @param hqspi QSPI handle + * @retval Threshold threshold for the QSPI Fifo + */ +uint32_t DAL_QSPI_GetTxFifoThreshold(QSPI_HandleTypeDef *hqspi) +{ + /* Return the FIFO threshold */ + return READ_BIT(hqspi->Instance->TFTL, QSPI_TFTL_TFT); +} + +/** + * @brief Get QSPI Rx Fifo threshold. + * @param hqspi QSPI handle + * @retval Threshold threshold for the QSPI Fifo + */ +uint32_t DAL_QSPI_GetRxFifoThreshold(QSPI_HandleTypeDef *hqspi) +{ + /* Return the FIFO threshold */ + return READ_BIT(hqspi->Instance->RFTL, QSPI_RFTL_RFT); +} + +/** + * @brief Get QSPI Tx Fifo level. + * @param hqspi QSPI handle + * @retval Level level for the QSPI Fifo + */ +uint32_t DAL_QSPI_GetTxFifoLevel(QSPI_HandleTypeDef *hqspi) +{ + /* Return the FIFO level */ + return READ_BIT(hqspi->Instance->TFTL, QSPI_TFTL_TFTH); +} + +/** + * @brief Set QSPI frame format. + * @param hqspi QSPI handle + * @param FrameFormat frame format + * @retval DAL status + */ +DAL_StatusTypeDef DAL_QSPI_SetFrameFormat(QSPI_HandleTypeDef *hqspi, uint32_t FrameFormat) +{ + DAL_StatusTypeDef status = DAL_OK; + + /* Process locked */ + __DAL_LOCK(hqspi); + + if (hqspi->State == DAL_QSPI_STATE_READY) + { + /* Check the parameters */ + ASSERT_PARAM(IS_QSPI_FRAME_FORMAT(FrameFormat)); + + /* Disable the QSPI peripheral */ + __DAL_QSPI_DISABLE(hqspi); + + /* Configure frame format */ + MODIFY_REG(hqspi->Instance->CTRL1, QSPI_CTRL1_FRF, FrameFormat); + + /* Enable the QSPI peripheral */ + __DAL_QSPI_ENABLE(hqspi); + } + else + { + status = DAL_BUSY; + } + + /* Process unlocked */ + __DAL_UNLOCK(hqspi); + + return status; +} + +/** + * @brief Get QSPI frame format. + * @param hqspi QSPI handle + * @retval FrameFormat frame format + */ +uint32_t DAL_QSPI_GetFrameFormat(QSPI_HandleTypeDef *hqspi) +{ + /* Return the frame format */ + return READ_BIT(hqspi->Instance->CTRL1, QSPI_CTRL1_FRF); +} + +/** + * @brief Set QSPI frame data size. + * @param hqspi QSPI handle + * @param DataFrameSize frame data size + * @retval DAL status + */ +DAL_StatusTypeDef DAL_QSPI_SetDataFrameSize(QSPI_HandleTypeDef *hqspi, uint32_t DataFrameSize) +{ + DAL_StatusTypeDef status = DAL_OK; + + /* Process locked */ + __DAL_LOCK(hqspi); + + if (hqspi->State == DAL_QSPI_STATE_READY) + { + /* Check the parameters */ + ASSERT_PARAM(IS_QSPI_DATA_FRAME_SIZE(DataFrameSize)); + + /* Disable the QSPI peripheral */ + __DAL_QSPI_DISABLE(hqspi); + + /* Configure frame data size */ + MODIFY_REG(hqspi->Instance->CTRL1, QSPI_CTRL1_DFS, DataFrameSize); + + /* Enable the QSPI peripheral */ + __DAL_QSPI_ENABLE(hqspi); + } + else + { + status = DAL_BUSY; + } + + /* Process unlocked */ + __DAL_UNLOCK(hqspi); + + return status; +} + +/** + * @brief Get QSPI frame data size. + * @param hqspi QSPI handle + * @retval DataFrameSize frame data size + */ +uint32_t DAL_QSPI_GetDataFrameSize(QSPI_HandleTypeDef *hqspi) +{ + /* Return the frame data size */ + return READ_BIT(hqspi->Instance->CTRL1, QSPI_CTRL1_DFS); +} + +/** + * @brief Set QSPI transfer mode. + * @param hqspi QSPI handle + * @param TransferMode transfer mode + * @retval DAL status + */ +DAL_StatusTypeDef DAL_QSPI_SetTransferMode(QSPI_HandleTypeDef *hqspi, uint32_t TransferMode) +{ + DAL_StatusTypeDef status = DAL_OK; + + /* Process locked */ + __DAL_LOCK(hqspi); + + if (hqspi->State == DAL_QSPI_STATE_READY) + { + /* Check the parameters */ + ASSERT_PARAM(IS_QSPI_TRANSFER_MODE(TransferMode)); + + /* Disable the QSPI peripheral */ + __DAL_QSPI_DISABLE(hqspi); + + /* Configure transfer mode */ + MODIFY_REG(hqspi->Instance->CTRL1, QSPI_CTRL1_TXMODE, TransferMode); + + /* Enable the QSPI peripheral */ + __DAL_QSPI_ENABLE(hqspi); + } + else + { + status = DAL_BUSY; + } + + /* Process unlocked */ + __DAL_UNLOCK(hqspi); + + return status; +} + +/** + * @brief Get QSPI transfer mode. + * @param hqspi QSPI handle + * @retval TransferMode transfer mode + */ +uint32_t DAL_QSPI_GetTransferMode(QSPI_HandleTypeDef *hqspi) +{ + /* Return the transfer mode */ + return READ_BIT(hqspi->Instance->CTRL1, QSPI_CTRL1_TXMODE); +} + +/** + * @brief Set QSPI number of data frames. + * @param hqspi QSPI handle + * @param NbData number of data frames + * @retval DAL status + */ +DAL_StatusTypeDef DAL_QSPI_SetFrameNbData(QSPI_HandleTypeDef *hqspi, uint32_t NbData) +{ + DAL_StatusTypeDef status = DAL_OK; + + /* Process locked */ + __DAL_LOCK(hqspi); + + if (hqspi->State == DAL_QSPI_STATE_READY) + { + /* Check the parameters */ + ASSERT_PARAM(IS_QSPI_NB_DATA(NbData)); + + /* Disable the QSPI peripheral */ + __DAL_QSPI_DISABLE(hqspi); + + /* Configure number of data frames */ + MODIFY_REG(hqspi->Instance->CTRL2, QSPI_CTRL2_NDF, (NbData - 1) << QSPI_CTRL2_NDF_Pos); + + /* Enable the QSPI peripheral */ + __DAL_QSPI_ENABLE(hqspi); + } + else + { + status = DAL_BUSY; + } + + /* Process unlocked */ + __DAL_UNLOCK(hqspi); + + return status; +} + +/** + * @brief Get QSPI number of data frames. + * @param hqspi QSPI handle + * @retval NbData number of data frames + */ +uint32_t DAL_QSPI_GetFrameNbData(QSPI_HandleTypeDef *hqspi) +{ + /* Return the number of data frames */ + return (READ_BIT(hqspi->Instance->CTRL2, QSPI_CTRL2_NDF) >> QSPI_CTRL2_NDF_Pos) + 1U; +} + +/** + * @} + */ + +/** + * @} + */ + +/** @defgroup QSPI_Private_Functions QSPI Private Functions + * @{ + */ + +/** + * @brief DMA QSPI transmit process complete callback. + * @param hdma DMA handle + * @retval None + */ +static void QSPI_DMATxCplt(DMA_HandleTypeDef *hdma) +{ + QSPI_HandleTypeDef *hqspi = (QSPI_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + + /* DMA Normal mode */ + if ((hdma->Instance->SCFG & DMA_SCFGx_CIRCMEN) == 0U) + { + hqspi->TxXferCount = 0U; + + if (hqspi->State == DAL_QSPI_STATE_BUSY_TX) + { + /* Disable the QSPI DMA Tx request */ + CLEAR_BIT(hqspi->Instance->DMACTRL, QSPI_DMACTRL_TDMAEN); + +#if (USE_DAL_QSPI_REGISTER_CALLBACKS == 1) + hqspi->TxCpltCallback(hqspi); +#else + DAL_QSPI_TxCpltCallback(hqspi); +#endif /* USE_DAL_QSPI_REGISTER_CALLBACKS */ + } + + /* Update QSPI state */ + hqspi->State = DAL_QSPI_STATE_READY; + } + /* DMA Circular mode */ + else + { + if (hqspi->State == DAL_QSPI_STATE_BUSY_TX) + { +#if (USE_DAL_QSPI_REGISTER_CALLBACKS == 1) + hqspi->TxCpltCallback(hqspi); +#else + DAL_QSPI_TxCpltCallback(hqspi); +#endif /* USE_DAL_QSPI_REGISTER_CALLBACKS */ + } + } +} + +/** + * @brief DMA QSPI receive process complete callback. + * @param hdma DMA handle + * @retval None + */ +static void QSPI_DMARxCplt(DMA_HandleTypeDef *hdma) +{ + QSPI_HandleTypeDef *hqspi = (QSPI_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + + /* DMA Normal mode */ + if ((hdma->Instance->SCFG & DMA_SCFGx_CIRCMEN) == 0U) + { + hqspi->RxXferCount = 0U; + + if (hqspi->State == DAL_QSPI_STATE_BUSY_RX) + { + /* Disable the QSPI DMA Rx request */ + CLEAR_BIT(hqspi->Instance->DMACTRL, QSPI_DMACTRL_RDMAEN); + +#if (USE_DAL_QSPI_REGISTER_CALLBACKS == 1) + hqspi->RxCpltCallback(hqspi); +#else + DAL_QSPI_RxCpltCallback(hqspi); +#endif /* USE_DAL_QSPI_REGISTER_CALLBACKS */ + } + + /* Update QSPI state */ + hqspi->State = DAL_QSPI_STATE_READY; + } + /* DMA Circular mode */ + else + { + if (hqspi->State == DAL_QSPI_STATE_BUSY_RX) + { +#if (USE_DAL_QSPI_REGISTER_CALLBACKS == 1) + hqspi->RxCpltCallback(hqspi); +#else + DAL_QSPI_RxCpltCallback(hqspi); +#endif /* USE_DAL_QSPI_REGISTER_CALLBACKS */ + } + } +} + +/** + * @brief DMA QSPI communication error callback. + * @param hdma DMA handle + * @retval None + */ +static void QSPI_DMAError(DMA_HandleTypeDef *hdma) +{ + QSPI_HandleTypeDef *hqspi = (QSPI_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + hqspi->RxXferCount = 0U; + hqspi->TxXferCount = 0U; + hqspi->ErrorCode |= DAL_QSPI_ERROR_DMA; + + /* Disable using DMA by clearing TDMAEN and RDMAEN bit in the QSPI DMACTRL register */ + CLEAR_BIT(hqspi->Instance->DMACTRL, (QSPI_DMACTRL_RDMAEN | QSPI_DMACTRL_TDMAEN)); + + /* Abort the QSPI */ + (void)DAL_QSPI_Abort_IT(hqspi); +} + +/** + * @brief DMA QSPI communication abort callback. + * @param hdma DMA handle + * @retval None + */ +static void QSPI_DMAAbortCplt(DMA_HandleTypeDef *hdma) +{ + QSPI_HandleTypeDef *hqspi = (QSPI_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + + hqspi->RxXferCount = 0U; + hqspi->TxXferCount = 0U; + + if (hqspi->State == DAL_QSPI_STATE_ABORT) + { + /* Disable slave select */ + __DAL_QSPI_DISABLE_SS(hqspi); + + /* Disable the QSPI peripheral */ + __DAL_QSPI_DISABLE(hqspi); + } + else + { + /* Update QSPI state */ + hqspi->State = DAL_QSPI_STATE_READY; + + /* Error callback */ +#if (USE_DAL_QSPI_REGISTER_CALLBACKS == 1) + hqspi->AbortCpltCallback(hqspi); +#else + DAL_QSPI_AbortCpltCallback(hqspi); +#endif /* USE_DAL_QSPI_REGISTER_CALLBACKS */ + } +} + +/** + * @brief Wait for a flag state until timeout + * @param hqspi: QSPI handle + * @param Flag: Flag checked + * @param State: Value of the flag expected + * @param TickStart: Tick start value + * @param Timeout: Timeout duration + * @retval DAL status + */ +static DAL_StatusTypeDef DAL_QSPI_WaitFlagStateUntilTimeout(QSPI_HandleTypeDef *hqspi, uint32_t Flag, FlagStatus State, uint32_t TickStart, uint32_t Timeout) +{ + /* Wait until flag is in expected state */ + while ((__DAL_QSPI_GET_FLAG(hqspi, Flag)) != State) + { + /* Check for the Timeout */ + if (Timeout != DAL_MAX_DELAY) + { + if (((DAL_GetTick() - TickStart) > Timeout) || (Timeout == 0U)) + { + hqspi->State = DAL_QSPI_STATE_ERROR; + hqspi->ErrorCode |= DAL_QSPI_ERROR_TIMEOUT; + + return DAL_ERROR; + } + } + } + + return DAL_OK; +} + +/** + * @brief Configure the communication registers. + * @param hqspi: QSPI handle + * @param cmd: structure that contains the command configuration information + * @retval None + */ +static void QSPI_Config(QSPI_HandleTypeDef *hqspi, QSPI_CommandTypeDef *cmd) +{ + if (cmd->FrameFormat == QSPI_FRAME_FORMAT_STANDARD) + { + /* Configure CTRL1 */ + MODIFY_REG(hqspi->Instance->CTRL1, \ + (QSPI_CTRL1_FRF | QSPI_CTRL1_TXMODE), \ + (cmd->FrameFormat | cmd->TransferMode)); + + if (cmd->TransferMode == QSPI_TRANSFER_MODE_EEPROM_READ) + { + /* Configure CTRL2 */ + MODIFY_REG(hqspi->Instance->CTRL2, QSPI_CTRL2_NDF, (cmd->NbData) << QSPI_CTRL2_NDF_Pos); + } + else + { + /* Configure CTRL2 */ + MODIFY_REG(hqspi->Instance->CTRL2, QSPI_CTRL2_NDF, (cmd->NbData - 1) << QSPI_CTRL2_NDF_Pos); + } + } + else if (cmd->FrameFormat == QSPI_FRAME_FORMAT_DUAL) + { + if ((cmd->TransferMode == QSPI_TRANSFER_MODE_TX) || (cmd->TransferMode == QSPI_TRANSFER_MODE_RX)) + { + /* Configure CTRL1 */ + MODIFY_REG(hqspi->Instance->CTRL1, \ + (QSPI_CTRL1_FRF | QSPI_CTRL1_TXMODE), \ + (cmd->FrameFormat | cmd->TransferMode)); + + /* Configure CTRL2 */ + if (cmd->NbData != 0) + { + MODIFY_REG(hqspi->Instance->CTRL2, QSPI_CTRL2_NDF, (cmd->NbData - 1) << QSPI_CTRL2_NDF_Pos); + } + else + { + MODIFY_REG(hqspi->Instance->CTRL2, QSPI_CTRL2_NDF, 0); + } + + if (cmd->TransferMode == QSPI_TRANSFER_MODE_TX) + { + /* Configure CTRL3 */ + MODIFY_REG(hqspi->Instance->CTRL3, \ + (QSPI_CTRL3_IAT | QSPI_CTRL3_ADDRLEN | QSPI_CTRL3_INSLEN), \ + ((cmd->InstructionMode) | (cmd->AddressSize) | (cmd->InstructionSize))); + } + else + { + /* Configure CTRL3 */ + MODIFY_REG(hqspi->Instance->CTRL3, \ + (QSPI_CTRL3_IAT | QSPI_CTRL3_ADDRLEN | QSPI_CTRL3_INSLEN | QSPI_CTRL3_WAITCYC), \ + ((cmd->InstructionMode) | (cmd->AddressSize) | (cmd->InstructionSize) | (cmd->DummyCycles << QSPI_CTRL3_WAITCYC_Pos))); + } + } + } + else if (cmd->FrameFormat == QSPI_FRAME_FORMAT_QUAD) + { + if ((cmd->TransferMode == QSPI_TRANSFER_MODE_TX) || (cmd->TransferMode == QSPI_TRANSFER_MODE_RX)) + { + /* Configure CTRL1 */ + MODIFY_REG(hqspi->Instance->CTRL1, \ + (QSPI_CTRL1_FRF | QSPI_CTRL1_TXMODE), \ + (cmd->FrameFormat | cmd->TransferMode)); + + /* Configure CTRL2 */ + if (cmd->NbData != 0) + { + MODIFY_REG(hqspi->Instance->CTRL2, QSPI_CTRL2_NDF, (cmd->NbData - 1) << QSPI_CTRL2_NDF_Pos); + } + else + { + MODIFY_REG(hqspi->Instance->CTRL2, QSPI_CTRL2_NDF, 0); + } + + if (cmd->TransferMode == QSPI_TRANSFER_MODE_TX) + { + /* Configure CTRL3 */ + MODIFY_REG(hqspi->Instance->CTRL3, \ + (QSPI_CTRL3_IAT | QSPI_CTRL3_ADDRLEN | QSPI_CTRL3_INSLEN), \ + ((cmd->InstructionMode) | (cmd->AddressSize) | (cmd->InstructionSize))); + } + else + { + /* Configure CTRL3 */ + MODIFY_REG(hqspi->Instance->CTRL3, \ + (QSPI_CTRL3_IAT | QSPI_CTRL3_ADDRLEN | QSPI_CTRL3_INSLEN | QSPI_CTRL3_WAITCYC), \ + ((cmd->InstructionMode) | (cmd->AddressSize) | (cmd->InstructionSize) | (cmd->DummyCycles << QSPI_CTRL3_WAITCYC_Pos))); + } + } + } + else + { + /* Nothing to do */ + } +} + +/** + * @} + */ + +#endif /* DAL_QSPI_MODULE_ENABLED */ + +/** + * @} + */ + +/** + * @} + */ + +#endif /* QSPI */ diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_rcm.c b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_rcm.c new file mode 100644 index 0000000000..b2ef190f35 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_rcm.c @@ -0,0 +1,1137 @@ +/** + * + * @file apm32f4xx_dal_rcm.c + * @brief RCM DAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the Reset and Clock Control (RCM) peripheral: + * + Initialization and de-initialization functions + * + Peripheral Control functions + * + @verbatim + ============================================================================== + ##### RCM specific features ##### + ============================================================================== + [..] + After reset the device is running from Internal High Speed oscillator + (HSI 16MHz) with Flash 0 wait state, Flash prefetch buffer, D-Cache + and I-Cache are disabled, and all peripherals are off except internal + SRAM, Flash and JTAG. + (+) There is no prescaler on High speed (AHB) and Low speed (APB) busses; + all peripherals mapped on these busses are running at HSI speed. + (+) The clock for all peripherals is switched off, except the SRAM and FLASH. + (+) All GPIOs are in input floating state, except the JTAG pins which + are assigned to be used for debug purpose. + + [..] + Once the device started from reset, the user application has to: + (+) Configure the clock source to be used to drive the System clock + (if the application needs higher frequency/performance) + (+) Configure the System clock frequency and Flash settings + (+) Configure the AHB and APB busses prescalers + (+) Enable the clock for the peripheral(s) to be used + (+) Configure the clock source(s) for peripherals which clocks are not + derived from the System clock (I2S, RTC, ADC, USB OTG FS/SDIO/RNG) + + ##### RCM Limitations ##### + ============================================================================== + [..] + A delay between an RCM peripheral clock enable and the effective peripheral + enabling should be taken into account in order to manage the peripheral read/write + from/to registers. + (+) This delay depends on the peripheral mapping. + (+) If peripheral is mapped on AHB: the delay is 2 AHB clock cycle + after the clock enable bit is set on the hardware register + (+) If peripheral is mapped on APB: the delay is 2 APB clock cycle + after the clock enable bit is set on the hardware register + + [..] + Implemented Workaround: + (+) For AHB & APB peripherals, a dummy read to the peripheral register has been + inserted in each __DAL_RCM_PPP_CLK_ENABLE() macro. + + @endverbatim + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2017 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file in + * the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + */ + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @defgroup RCM RCM + * @brief RCM DAL module driver + * @{ + */ + +#ifdef DAL_RCM_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/** @addtogroup RCM_Private_Constants + * @{ + */ + +/* Private macro -------------------------------------------------------------*/ +#define __MCO1_CLK_ENABLE() __DAL_RCM_GPIOA_CLK_ENABLE() +#define MCO1_GPIO_PORT GPIOA +#define MCO1_PIN GPIO_PIN_8 + +#define __MCO2_CLK_ENABLE() __DAL_RCM_GPIOC_CLK_ENABLE() +#define MCO2_GPIO_PORT GPIOC +#define MCO2_PIN GPIO_PIN_9 +/** + * @} + */ + +/* Private variables ---------------------------------------------------------*/ +/** @defgroup RCM_Private_Variables RCM Private Variables + * @{ + */ +/** + * @} + */ +/* Private function prototypes -----------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ + +/** @defgroup RCM_Exported_Functions RCM Exported Functions + * @{ + */ + +/** @defgroup RCM_Exported_Functions_Group1 Initialization and de-initialization functions + * @brief Initialization and Configuration functions + * +@verbatim + =============================================================================== + ##### Initialization and de-initialization functions ##### + =============================================================================== + [..] + This section provides functions allowing to configure the internal/external oscillators + (HSE, HSI, LSE, LSI, PLL, CSS and MCO) and the System busses clocks (SYSCLK, AHB, APB1 + and APB2). + + [..] Internal/external clock and PLL configuration + (#) HSI (high-speed internal), 16 MHz factory-trimmed RC used directly or through + the PLL as System clock source. + + (#) LSI (low-speed internal), 32 KHz low consumption RC used as IWDT and/or RTC + clock source. + + (#) HSE (high-speed external), 4 to 26 MHz crystal oscillator used directly or + through the PLL as System clock source. Can be used also as RTC clock source. + + (#) LSE (low-speed external), 32 KHz oscillator used as RTC clock source. + + (#) PLL (clocked by HSI or HSE), featuring two different output clocks: + (++) The first output is used to generate the high speed system clock (up to 168 MHz) + (++) The second output is used to generate the clock for the USB OTG FS (48 MHz), + the random analog generator (<=48 MHz) and the SDIO (<= 48 MHz). + + (#) CSS (Clock security system), once enable using the macro __DAL_RCM_CSS_ENABLE() + and if a HSE clock failure occurs(HSE used directly or through PLL as System + clock source), the System clocks automatically switched to HSI and an interrupt + is generated if enabled. The interrupt is linked to the Cortex-M4 NMI + (Non-Maskable Interrupt) exception vector. + + (#) MCO1 (microcontroller clock output), used to output HSI, LSE, HSE or PLL + clock (through a configurable prescaler) on PA8 pin. + + (#) MCO2 (microcontroller clock output), used to output HSE, PLL, SYSCLK or PLLI2S + clock (through a configurable prescaler) on PC9 pin. + + [..] System, AHB and APB busses clocks configuration + (#) Several clock sources can be used to drive the System clock (SYSCLK): HSI, + HSE and PLL. + The AHB clock (HCLK) is derived from System clock through configurable + prescaler and used to clock the CPU, memory and peripherals mapped + on AHB bus (DMA, GPIO...). APB1 (PCLK1) and APB2 (PCLK2) clocks are derived + from AHB clock through configurable prescalers and used to clock + the peripherals mapped on these busses. You can use + "DAL_RCM_GetSysClockFreq()" function to retrieve the frequencies of these clocks. + + (#) For the APM32F405xx/07xx and APM32F417xx devices, the maximum + frequency of the SYSCLK and HCLK is 168 MHz, PCLK2 84 MHz and PCLK1 42 MHz. + Depending on the device voltage range, the maximum frequency should + be adapted accordingly (refer to the product datasheets for more details). + + (#) For the APM32F41xxx, the maximum frequency of the SYSCLK and HCLK is 100 MHz, + PCLK2 100 MHz and PCLK1 50 MHz. + Depending on the device voltage range, the maximum frequency should + be adapted accordingly (refer to the product datasheets for more details). + +@endverbatim + * @{ + */ + +/** + * @brief Resets the RCM clock configuration to the default reset state. + * @note The default reset state of the clock configuration is given below: + * - HSI ON and used as system clock source + * - HSE and PLL OFF + * - AHB, APB1 and APB2 prescaler set to 1. + * - CSS, MCO1 and MCO2 OFF + * - All interrupts disabled + * @note This function doesn't modify the configuration of the + * - Peripheral clocks + * - LSI, LSE and RTC clocks + * @retval DAL status + */ +__weak DAL_StatusTypeDef DAL_RCM_DeInit(void) +{ + return DAL_OK; +} + +/** + * @brief Initializes the RCM Oscillators according to the specified parameters in the + * RCM_OscInitTypeDef. + * @param RCM_OscInitStruct pointer to an RCM_OscInitTypeDef structure that + * contains the configuration information for the RCM Oscillators. + * @note The PLL is not disabled when used as system clock. + * @note Transitions LSE Bypass to LSE On and LSE On to LSE Bypass are not + * supported by this API. User should request a transition to LSE Off + * first and then LSE On or LSE Bypass. + * @note Transition HSE Bypass to HSE On and HSE On to HSE Bypass are not + * supported by this API. User should request a transition to HSE Off + * first and then HSE On or HSE Bypass. + * @retval DAL status + */ +__weak DAL_StatusTypeDef DAL_RCM_OscConfig(RCM_OscInitTypeDef *RCM_OscInitStruct) +{ + uint32_t tickstart, pll_config; + + /* Check Null pointer */ + if(RCM_OscInitStruct == NULL) + { + return DAL_ERROR; + } + + /* Check the parameters */ + ASSERT_PARAM(IS_RCM_OSCILLATORTYPE(RCM_OscInitStruct->OscillatorType)); + /*------------------------------- HSE Configuration ------------------------*/ + if(((RCM_OscInitStruct->OscillatorType) & RCM_OSCILLATORTYPE_HSE) == RCM_OSCILLATORTYPE_HSE) + { + /* Check the parameters */ + ASSERT_PARAM(IS_RCM_HSE(RCM_OscInitStruct->HSEState)); + /* When the HSE is used as system clock or clock source for PLL in these cases HSE will not disabled */ + if((__DAL_RCM_GET_SYSCLK_SOURCE() == RCM_CFG_SCLKSWSTS_HSE) ||\ + ((__DAL_RCM_GET_SYSCLK_SOURCE() == RCM_CFG_SCLKSWSTS_PLL) && ((RCM->PLL1CFG & RCM_PLL1CFG_PLL1CLKS) == RCM_PLL1CFG_PLL1CLKS_HSE))) + { + if((__DAL_RCM_GET_FLAG(RCM_FLAG_HSERDY) != RESET) && (RCM_OscInitStruct->HSEState == RCM_HSE_OFF)) + { + return DAL_ERROR; + } + } + else + { + /* Set the new HSE configuration ---------------------------------------*/ + __DAL_RCM_HSE_CONFIG(RCM_OscInitStruct->HSEState); + + /* Check the HSE State */ + if((RCM_OscInitStruct->HSEState) != RCM_HSE_OFF) + { + /* Get Start Tick */ + tickstart = DAL_GetTick(); + + /* Wait till HSE is ready */ + while(__DAL_RCM_GET_FLAG(RCM_FLAG_HSERDY) == RESET) + { + if((DAL_GetTick() - tickstart ) > HSE_TIMEOUT_VALUE) + { + return DAL_TIMEOUT; + } + } + } + else + { + /* Get Start Tick */ + tickstart = DAL_GetTick(); + + /* Wait till HSE is bypassed or disabled */ + while(__DAL_RCM_GET_FLAG(RCM_FLAG_HSERDY) != RESET) + { + if((DAL_GetTick() - tickstart ) > HSE_TIMEOUT_VALUE) + { + return DAL_TIMEOUT; + } + } + } + } + } + /*----------------------------- HSI Configuration --------------------------*/ + if(((RCM_OscInitStruct->OscillatorType) & RCM_OSCILLATORTYPE_HSI) == RCM_OSCILLATORTYPE_HSI) + { + /* Check the parameters */ + ASSERT_PARAM(IS_RCM_HSI(RCM_OscInitStruct->HSIState)); + ASSERT_PARAM(IS_RCM_CALIBRATION_VALUE(RCM_OscInitStruct->HSICalibrationValue)); + + /* Check if HSI is used as system clock or as PLL source when PLL is selected as system clock */ + if((__DAL_RCM_GET_SYSCLK_SOURCE() == RCM_CFG_SCLKSWSTS_HSI) ||\ + ((__DAL_RCM_GET_SYSCLK_SOURCE() == RCM_CFG_SCLKSWSTS_PLL) && ((RCM->PLL1CFG & RCM_PLL1CFG_PLL1CLKS) == RCM_PLL1CFG_PLL1CLKS_HSI))) + { + /* When HSI is used as system clock it will not disabled */ + if((__DAL_RCM_GET_FLAG(RCM_FLAG_HSIRDY) != RESET) && (RCM_OscInitStruct->HSIState != RCM_HSI_ON)) + { + return DAL_ERROR; + } + /* Otherwise, just the calibration is allowed */ + else + { + /* Adjusts the Internal High Speed oscillator (HSI) calibration value.*/ + __DAL_RCM_HSI_CALIBRATIONVALUE_ADJUST(RCM_OscInitStruct->HSICalibrationValue); + } + } + else + { + /* Check the HSI State */ + if((RCM_OscInitStruct->HSIState)!= RCM_HSI_OFF) + { + /* Enable the Internal High Speed oscillator (HSI). */ + __DAL_RCM_HSI_ENABLE(); + + /* Get Start Tick*/ + tickstart = DAL_GetTick(); + + /* Wait till HSI is ready */ + while(__DAL_RCM_GET_FLAG(RCM_FLAG_HSIRDY) == RESET) + { + if((DAL_GetTick() - tickstart ) > HSI_TIMEOUT_VALUE) + { + return DAL_TIMEOUT; + } + } + + /* Adjusts the Internal High Speed oscillator (HSI) calibration value. */ + __DAL_RCM_HSI_CALIBRATIONVALUE_ADJUST(RCM_OscInitStruct->HSICalibrationValue); + } + else + { + /* Disable the Internal High Speed oscillator (HSI). */ + __DAL_RCM_HSI_DISABLE(); + + /* Get Start Tick*/ + tickstart = DAL_GetTick(); + + /* Wait till HSI is ready */ + while(__DAL_RCM_GET_FLAG(RCM_FLAG_HSIRDY) != RESET) + { + if((DAL_GetTick() - tickstart ) > HSI_TIMEOUT_VALUE) + { + return DAL_TIMEOUT; + } + } + } + } + } + /*------------------------------ LSI Configuration -------------------------*/ + if(((RCM_OscInitStruct->OscillatorType) & RCM_OSCILLATORTYPE_LSI) == RCM_OSCILLATORTYPE_LSI) + { + /* Check the parameters */ + ASSERT_PARAM(IS_RCM_LSI(RCM_OscInitStruct->LSIState)); + + /* Check the LSI State */ + if((RCM_OscInitStruct->LSIState)!= RCM_LSI_OFF) + { + /* Enable the Internal Low Speed oscillator (LSI). */ + __DAL_RCM_LSI_ENABLE(); + + /* Get Start Tick*/ + tickstart = DAL_GetTick(); + + /* Wait till LSI is ready */ + while(__DAL_RCM_GET_FLAG(RCM_FLAG_LSIRDY) == RESET) + { + if((DAL_GetTick() - tickstart ) > LSI_TIMEOUT_VALUE) + { + return DAL_TIMEOUT; + } + } + } + else + { + /* Disable the Internal Low Speed oscillator (LSI). */ + __DAL_RCM_LSI_DISABLE(); + + /* Get Start Tick */ + tickstart = DAL_GetTick(); + + /* Wait till LSI is ready */ + while(__DAL_RCM_GET_FLAG(RCM_FLAG_LSIRDY) != RESET) + { + if((DAL_GetTick() - tickstart ) > LSI_TIMEOUT_VALUE) + { + return DAL_TIMEOUT; + } + } + } + } + /*------------------------------ LSE Configuration -------------------------*/ + if(((RCM_OscInitStruct->OscillatorType) & RCM_OSCILLATORTYPE_LSE) == RCM_OSCILLATORTYPE_LSE) + { + FlagStatus pwrclkchanged = RESET; + + /* Check the parameters */ + ASSERT_PARAM(IS_RCM_LSE(RCM_OscInitStruct->LSEState)); + + /* Update LSE configuration in Backup Domain control register */ + /* Requires to enable write access to Backup Domain of necessary */ + if(__DAL_RCM_PMU_IS_CLK_DISABLED()) + { + __DAL_RCM_PMU_CLK_ENABLE(); + pwrclkchanged = SET; + } + + if(DAL_IS_BIT_CLR(PMU->CTRL, PMU_CTRL_BPWEN)) + { + /* Enable write access to Backup domain */ + SET_BIT(PMU->CTRL, PMU_CTRL_BPWEN); + + /* Wait for Backup domain Write protection disable */ + tickstart = DAL_GetTick(); + + while(DAL_IS_BIT_CLR(PMU->CTRL, PMU_CTRL_BPWEN)) + { + if((DAL_GetTick() - tickstart) > RCM_DBP_TIMEOUT_VALUE) + { + return DAL_TIMEOUT; + } + } + } + + /* Set the new LSE configuration -----------------------------------------*/ + __DAL_RCM_LSE_CONFIG(RCM_OscInitStruct->LSEState); + /* Check the LSE State */ + if((RCM_OscInitStruct->LSEState) != RCM_LSE_OFF) + { + /* Get Start Tick*/ + tickstart = DAL_GetTick(); + + /* Wait till LSE is ready */ + while(__DAL_RCM_GET_FLAG(RCM_FLAG_LSERDY) == RESET) + { + if((DAL_GetTick() - tickstart ) > RCM_LSE_TIMEOUT_VALUE) + { + return DAL_TIMEOUT; + } + } + } + else + { + /* Get Start Tick */ + tickstart = DAL_GetTick(); + + /* Wait till LSE is ready */ + while(__DAL_RCM_GET_FLAG(RCM_FLAG_LSERDY) != RESET) + { + if((DAL_GetTick() - tickstart ) > RCM_LSE_TIMEOUT_VALUE) + { + return DAL_TIMEOUT; + } + } + } + + /* Restore clock configuration if changed */ + if(pwrclkchanged == SET) + { + __DAL_RCM_PMU_CLK_DISABLE(); + } + } + /*-------------------------------- PLL Configuration -----------------------*/ + /* Check the parameters */ + ASSERT_PARAM(IS_RCM_PLL(RCM_OscInitStruct->PLL.PLLState)); + if ((RCM_OscInitStruct->PLL.PLLState) != RCM_PLL_NONE) + { + /* Check if the PLL is used as system clock or not */ + if(__DAL_RCM_GET_SYSCLK_SOURCE() != RCM_CFG_SCLKSWSTS_PLL) + { + if((RCM_OscInitStruct->PLL.PLLState) == RCM_PLL_ON) + { + /* Check the parameters */ + ASSERT_PARAM(IS_RCM_PLLSOURCE(RCM_OscInitStruct->PLL.PLLSource)); + ASSERT_PARAM(IS_RCM_PLLB_VALUE(RCM_OscInitStruct->PLL.PLLB)); + ASSERT_PARAM(IS_RCM_PLL1A_VALUE(RCM_OscInitStruct->PLL.PLL1A)); + ASSERT_PARAM(IS_RCM_PLL1C_VALUE(RCM_OscInitStruct->PLL.PLL1C)); + ASSERT_PARAM(IS_RCM_PLLD_VALUE(RCM_OscInitStruct->PLL.PLLD)); + + /* Disable the main PLL. */ + __DAL_RCM_PLL_DISABLE(); + + /* Get Start Tick */ + tickstart = DAL_GetTick(); + + /* Wait till PLL is ready */ + while(__DAL_RCM_GET_FLAG(RCM_FLAG_PLLRDY) != RESET) + { + if((DAL_GetTick() - tickstart ) > PLL_TIMEOUT_VALUE) + { + return DAL_TIMEOUT; + } + } + + /* Configure the main PLL clock source, multiplication and division factors. */ + WRITE_REG(RCM->PLL1CFG, (RCM_OscInitStruct->PLL.PLLSource | \ + RCM_OscInitStruct->PLL.PLLB | \ + (RCM_OscInitStruct->PLL.PLL1A << RCM_PLL1CFG_PLL1A_Pos) | \ + (((RCM_OscInitStruct->PLL.PLL1C >> 1U) - 1U) << RCM_PLL1CFG_PLL1C_Pos) | \ + (RCM_OscInitStruct->PLL.PLLD << RCM_PLL1CFG_PLLD_Pos))); + /* Enable the main PLL. */ + __DAL_RCM_PLL_ENABLE(); + + /* Get Start Tick */ + tickstart = DAL_GetTick(); + + /* Wait till PLL is ready */ + while(__DAL_RCM_GET_FLAG(RCM_FLAG_PLLRDY) == RESET) + { + if((DAL_GetTick() - tickstart ) > PLL_TIMEOUT_VALUE) + { + return DAL_TIMEOUT; + } + } + } + else + { + /* Disable the main PLL. */ + __DAL_RCM_PLL_DISABLE(); + + /* Get Start Tick */ + tickstart = DAL_GetTick(); + + /* Wait till PLL is ready */ + while(__DAL_RCM_GET_FLAG(RCM_FLAG_PLLRDY) != RESET) + { + if((DAL_GetTick() - tickstart ) > PLL_TIMEOUT_VALUE) + { + return DAL_TIMEOUT; + } + } + } + } + else + { + /* Check if there is a request to disable the PLL used as System clock source */ + if((RCM_OscInitStruct->PLL.PLLState) == RCM_PLL_OFF) + { + return DAL_ERROR; + } + else + { + /* Do not return DAL_ERROR if request repeats the current configuration */ + pll_config = RCM->PLL1CFG; +#if defined (RCM_PLL1CFG_PLLR) + if (((RCM_OscInitStruct->PLL.PLLState) == RCM_PLL_OFF) || + (READ_BIT(pll_config, RCM_PLL1CFG_PLL1CLKS) != RCM_OscInitStruct->PLL.PLLSource) || + (READ_BIT(pll_config, RCM_PLL1CFG_PLLB) != (RCM_OscInitStruct->PLL.PLLB) << RCM_PLL1CFG_PLLB_Pos) || + (READ_BIT(pll_config, RCM_PLL1CFG_PLL1A) != (RCM_OscInitStruct->PLL.PLL1A) << RCM_PLL1CFG_PLL1A_Pos) || + (READ_BIT(pll_config, RCM_PLL1CFG_PLL1C) != (((RCM_OscInitStruct->PLL.PLL1C >> 1U) - 1U)) << RCM_PLL1CFG_PLL1C_Pos) || + (READ_BIT(pll_config, RCM_PLL1CFG_PLLD) != (RCM_OscInitStruct->PLL.PLLD << RCM_PLL1CFG_PLLD_Pos)) || + (READ_BIT(pll_config, RCM_PLL1CFG_PLLR) != (RCM_OscInitStruct->PLL.PLLR << RCM_PLL1CFG_PLLR_Pos))) +#else + if (((RCM_OscInitStruct->PLL.PLLState) == RCM_PLL_OFF) || + (READ_BIT(pll_config, RCM_PLL1CFG_PLL1CLKS) != RCM_OscInitStruct->PLL.PLLSource) || + (READ_BIT(pll_config, RCM_PLL1CFG_PLLB) != (RCM_OscInitStruct->PLL.PLLB) << RCM_PLL1CFG_PLLB_Pos) || + (READ_BIT(pll_config, RCM_PLL1CFG_PLL1A) != (RCM_OscInitStruct->PLL.PLL1A) << RCM_PLL1CFG_PLL1A_Pos) || + (READ_BIT(pll_config, RCM_PLL1CFG_PLL1C) != (((RCM_OscInitStruct->PLL.PLL1C >> 1U) - 1U)) << RCM_PLL1CFG_PLL1C_Pos) || + (READ_BIT(pll_config, RCM_PLL1CFG_PLLD) != (RCM_OscInitStruct->PLL.PLLD << RCM_PLL1CFG_PLLD_Pos))) +#endif + { + return DAL_ERROR; + } + } + } + } + return DAL_OK; +} + +/** + * @brief Initializes the CPU, AHB and APB busses clocks according to the specified + * parameters in the RCM_ClkInitStruct. + * @param RCM_ClkInitStruct pointer to an RCM_OscInitTypeDef structure that + * contains the configuration information for the RCM peripheral. + * @param FLatency FLASH Latency, this parameter depend on device selected + * + * @note The SystemCoreClock CMSIS variable is used to store System Clock Frequency + * and updated by DAL_RCM_GetHCLKFreq() function called within this function + * + * @note The HSI is used (enabled by hardware) as system clock source after + * startup from Reset, wake-up from STOP and STANDBY mode, or in case + * of failure of the HSE used directly or indirectly as system clock + * (if the Clock Security System CSS is enabled). + * + * @note A switch from one clock source to another occurs only if the target + * clock source is ready (clock stable after startup delay or PLL locked). + * If a clock source which is not yet ready is selected, the switch will + * occur when the clock source will be ready. + * + * @note Depending on the device voltage range, the software has to set correctly + * HPRE[3:0] bits to ensure that HCLK not exceed the maximum allowed frequency + * (for more details refer to section above "Initialization/de-initialization functions") + * @retval None + */ +DAL_StatusTypeDef DAL_RCM_ClockConfig(RCM_ClkInitTypeDef *RCM_ClkInitStruct, uint32_t FLatency) +{ + uint32_t tickstart; + + /* Check Null pointer */ + if(RCM_ClkInitStruct == NULL) + { + return DAL_ERROR; + } + + /* Check the parameters */ + ASSERT_PARAM(IS_RCM_CLOCKTYPE(RCM_ClkInitStruct->ClockType)); + ASSERT_PARAM(IS_FLASH_LATENCY(FLatency)); + + /* To correctly read data from FLASH memory, the number of wait states (LATENCY) + must be correctly programmed according to the frequency of the CPU clock + (HCLK) and the supply voltage of the device. */ + + /* Increasing the number of wait states because of higher CPU frequency */ + if(FLatency > __DAL_FLASH_GET_LATENCY()) + { + /* Program the new number of wait states to the LATENCY bits in the FLASH_ACCTRL register */ + __DAL_FLASH_SET_LATENCY(FLatency); + + /* Check that the new number of wait states is taken into account to access the Flash + memory by reading the FLASH_ACCTRL register */ + if(__DAL_FLASH_GET_LATENCY() != FLatency) + { + return DAL_ERROR; + } + } + + /*-------------------------- HCLK Configuration --------------------------*/ + if(((RCM_ClkInitStruct->ClockType) & RCM_CLOCKTYPE_HCLK) == RCM_CLOCKTYPE_HCLK) + { + /* Set the highest APBx dividers in order to ensure that we do not go through + a non-spec phase whatever we decrease or increase HCLK. */ + if(((RCM_ClkInitStruct->ClockType) & RCM_CLOCKTYPE_PCLK1) == RCM_CLOCKTYPE_PCLK1) + { + MODIFY_REG(RCM->CFG, RCM_CFG_APB1PSC, RCM_HCLK_DIV16); + } + + if(((RCM_ClkInitStruct->ClockType) & RCM_CLOCKTYPE_PCLK2) == RCM_CLOCKTYPE_PCLK2) + { + MODIFY_REG(RCM->CFG, RCM_CFG_APB2PSC, (RCM_HCLK_DIV16 << 3)); + } + + ASSERT_PARAM(IS_RCM_HCLK(RCM_ClkInitStruct->AHBCLKDivider)); + MODIFY_REG(RCM->CFG, RCM_CFG_AHBPSC, RCM_ClkInitStruct->AHBCLKDivider); + } + + /*------------------------- SYSCLK Configuration ---------------------------*/ + if(((RCM_ClkInitStruct->ClockType) & RCM_CLOCKTYPE_SYSCLK) == RCM_CLOCKTYPE_SYSCLK) + { + ASSERT_PARAM(IS_RCM_SYSCLKSOURCE(RCM_ClkInitStruct->SYSCLKSource)); + + /* HSE is selected as System Clock Source */ + if(RCM_ClkInitStruct->SYSCLKSource == RCM_SYSCLKSOURCE_HSE) + { + /* Check the HSE ready flag */ + if(__DAL_RCM_GET_FLAG(RCM_FLAG_HSERDY) == RESET) + { + return DAL_ERROR; + } + } + /* PLL is selected as System Clock Source */ + else if((RCM_ClkInitStruct->SYSCLKSource == RCM_SYSCLKSOURCE_PLLCLK) || + (RCM_ClkInitStruct->SYSCLKSource == RCM_SYSCLKSOURCE_PLLRCLK)) + { + /* Check the PLL ready flag */ + if(__DAL_RCM_GET_FLAG(RCM_FLAG_PLLRDY) == RESET) + { + return DAL_ERROR; + } + } + /* HSI is selected as System Clock Source */ + else + { + /* Check the HSI ready flag */ + if(__DAL_RCM_GET_FLAG(RCM_FLAG_HSIRDY) == RESET) + { + return DAL_ERROR; + } + } + + __DAL_RCM_SYSCLK_CONFIG(RCM_ClkInitStruct->SYSCLKSource); + + /* Get Start Tick */ + tickstart = DAL_GetTick(); + + while (__DAL_RCM_GET_SYSCLK_SOURCE() != (RCM_ClkInitStruct->SYSCLKSource << RCM_CFG_SCLKSWSTS_Pos)) + { + if ((DAL_GetTick() - tickstart) > CLOCKSWITCH_TIMEOUT_VALUE) + { + return DAL_TIMEOUT; + } + } + } + + /* Decreasing the number of wait states because of lower CPU frequency */ + if(FLatency < __DAL_FLASH_GET_LATENCY()) + { + /* Program the new number of wait states to the LATENCY bits in the FLASH_ACCTRL register */ + __DAL_FLASH_SET_LATENCY(FLatency); + + /* Check that the new number of wait states is taken into account to access the Flash + memory by reading the FLASH_ACCTRL register */ + if(__DAL_FLASH_GET_LATENCY() != FLatency) + { + return DAL_ERROR; + } + } + + /*-------------------------- PCLK1 Configuration ---------------------------*/ + if(((RCM_ClkInitStruct->ClockType) & RCM_CLOCKTYPE_PCLK1) == RCM_CLOCKTYPE_PCLK1) + { + ASSERT_PARAM(IS_RCM_PCLK(RCM_ClkInitStruct->APB1CLKDivider)); + MODIFY_REG(RCM->CFG, RCM_CFG_APB1PSC, RCM_ClkInitStruct->APB1CLKDivider); + } + + /*-------------------------- PCLK2 Configuration ---------------------------*/ + if(((RCM_ClkInitStruct->ClockType) & RCM_CLOCKTYPE_PCLK2) == RCM_CLOCKTYPE_PCLK2) + { + ASSERT_PARAM(IS_RCM_PCLK(RCM_ClkInitStruct->APB2CLKDivider)); + MODIFY_REG(RCM->CFG, RCM_CFG_APB2PSC, ((RCM_ClkInitStruct->APB2CLKDivider) << 3U)); + } + + /* Update the SystemCoreClock global variable */ + SystemCoreClock = DAL_RCM_GetSysClockFreq() >> AHBPrescTable[(RCM->CFG & RCM_CFG_AHBPSC)>> RCM_CFG_AHBPSC_Pos]; + + /* Configure the source of time base considering new system clocks settings */ + DAL_InitTick (uwTickPrio); + + return DAL_OK; +} + +/** + * @} + */ + +/** @defgroup RCM_Exported_Functions_Group2 Peripheral Control functions + * @brief RCM clocks control functions + * +@verbatim + =============================================================================== + ##### Peripheral Control functions ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to control the RCM Clocks + frequencies. + +@endverbatim + * @{ + */ + +/** + * @brief Selects the clock source to output on MCO1 pin(PA8) or on MCO2 pin(PC9). + * @note PA8/PC9 should be configured in alternate function mode. + * @param RCM_MCOx specifies the output direction for the clock source. + * This parameter can be one of the following values: + * @arg RCM_MCO1: Clock source to output on MCO1 pin(PA8). + * @arg RCM_MCO2: Clock source to output on MCO2 pin(PC9). + * @param RCM_MCOSource specifies the clock source to output. + * This parameter can be one of the following values: + * @arg RCM_MCO1SOURCE_HSI: HSI clock selected as MCO1 source + * @arg RCM_MCO1SOURCE_LSE: LSE clock selected as MCO1 source + * @arg RCM_MCO1SOURCE_HSE: HSE clock selected as MCO1 source + * @arg RCM_MCO1SOURCE_PLLCLK: main PLL clock selected as MCO1 source + * @arg RCM_MCO2SOURCE_SYSCLK: System clock (SYSCLK) selected as MCO2 source + * @arg RCM_MCO2SOURCE_PLLI2SCLK: PLLI2S clock selected as MCO2 source, available for all APM32F4 devices except APM32F410xx + * @arg RCM_MCO2SOURCE_I2SCLK: I2SCLK clock selected as MCO2 source, available only for APM32F410Rx devices + * @arg RCM_MCO2SOURCE_HSE: HSE clock selected as MCO2 source + * @arg RCM_MCO2SOURCE_PLLCLK: main PLL clock selected as MCO2 source + * @param RCM_MCODiv specifies the MCOx prescaler. + * This parameter can be one of the following values: + * @arg RCM_MCODIV_1: no division applied to MCOx clock + * @arg RCM_MCODIV_2: division by 2 applied to MCOx clock + * @arg RCM_MCODIV_3: division by 3 applied to MCOx clock + * @arg RCM_MCODIV_4: division by 4 applied to MCOx clock + * @arg RCM_MCODIV_5: division by 5 applied to MCOx clock + * @note For APM32F410Rx devices to output I2SCLK clock on MCO2 you should have + * at last one of the SPI clocks enabled (SPI1, SPI2 or SPI5). + * @retval None + */ +void DAL_RCM_MCOConfig(uint32_t RCM_MCOx, uint32_t RCM_MCOSource, uint32_t RCM_MCODiv) +{ + GPIO_InitTypeDef GPIO_InitStruct; + /* Check the parameters */ + ASSERT_PARAM(IS_RCM_MCO(RCM_MCOx)); + ASSERT_PARAM(IS_RCM_MCODIV(RCM_MCODiv)); + /* RCM_MCO1 */ + if(RCM_MCOx == RCM_MCO1) + { + ASSERT_PARAM(IS_RCM_MCO1SOURCE(RCM_MCOSource)); + + /* MCO1 Clock Enable */ + __MCO1_CLK_ENABLE(); + + /* Configure the MCO1 pin in alternate function mode */ + GPIO_InitStruct.Pin = MCO1_PIN; + GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; + GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH; + GPIO_InitStruct.Pull = GPIO_NOPULL; + GPIO_InitStruct.Alternate = GPIO_AF0_MCO; + DAL_GPIO_Init(MCO1_GPIO_PORT, &GPIO_InitStruct); + + /* Mask MCO1 and MCO1PRE[2:0] bits then Select MCO1 clock source and prescaler */ + MODIFY_REG(RCM->CFG, (RCM_CFG_MCO1SEL | RCM_CFG_MCO1PSC), (RCM_MCOSource | RCM_MCODiv)); + + /* This RCM MCO1 enable feature is available only on APM32F410xx devices */ +#if defined(RCM_CFG_MCO1EN) + __DAL_RCM_MCO1_ENABLE(); +#endif /* RCM_CFG_MCO1EN */ + } +#if defined(RCM_CFG_MCO2SEL) + else + { + ASSERT_PARAM(IS_RCM_MCO2SOURCE(RCM_MCOSource)); + + /* MCO2 Clock Enable */ + __MCO2_CLK_ENABLE(); + + /* Configure the MCO2 pin in alternate function mode */ + GPIO_InitStruct.Pin = MCO2_PIN; + GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; + GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH; + GPIO_InitStruct.Pull = GPIO_NOPULL; + GPIO_InitStruct.Alternate = GPIO_AF0_MCO; + DAL_GPIO_Init(MCO2_GPIO_PORT, &GPIO_InitStruct); + + /* Mask MCO2 and MCO2PRE[2:0] bits then Select MCO2 clock source and prescaler */ + MODIFY_REG(RCM->CFG, (RCM_CFG_MCO2SEL | RCM_CFG_MCO2PSC), (RCM_MCOSource | (RCM_MCODiv << 3U))); + + /* This RCM MCO2 enable feature is available only on APM32F410Rx devices */ +#if defined(RCM_CFG_MCO2EN) + __DAL_RCM_MCO2_ENABLE(); +#endif /* RCM_CFG_MCO2EN */ + } +#endif /* RCM_CFG_MCO2SEL */ +} + +/** + * @brief Enables the Clock Security System. + * @note If a failure is detected on the HSE oscillator clock, this oscillator + * is automatically disabled and an interrupt is generated to inform the + * software about the failure (Clock Security System Interrupt, CSSI), + * allowing the MCU to perform rescue operations. The CSSI is linked to + * the Cortex-M4 NMI (Non-Maskable Interrupt) exception vector. + * @retval None + */ +void DAL_RCM_EnableCSS(void) +{ + *(__IO uint32_t *) RCM_CTRL_CSSEN_BB = (uint32_t)ENABLE; +} + +/** + * @brief Disables the Clock Security System. + * @retval None + */ +void DAL_RCM_DisableCSS(void) +{ + *(__IO uint32_t *) RCM_CTRL_CSSEN_BB = (uint32_t)DISABLE; +} + +/** + * @brief Returns the SYSCLK frequency + * + * @note The system frequency computed by this function is not the real + * frequency in the chip. It is calculated based on the predefined + * constant and the selected clock source: + * @note If SYSCLK source is HSI, function returns values based on HSI_VALUE(*) + * @note If SYSCLK source is HSE, function returns values based on HSE_VALUE(**) + * @note If SYSCLK source is PLL, function returns values based on HSE_VALUE(**) + * or HSI_VALUE(*) multiplied/divided by the PLL factors. + * @note (*) HSI_VALUE is a constant defined in apm32f4xx_dal_cfg.h file (default value + * 16 MHz) but the real value may vary depending on the variations + * in voltage and temperature. + * @note (**) HSE_VALUE is a constant defined in apm32f4xx_dal_cfg.h file (default value + * 25 MHz), user has to ensure that HSE_VALUE is same as the real + * frequency of the crystal used. Otherwise, this function may + * have wrong result. + * + * @note The result of this function could be not correct when using fractional + * value for HSE crystal. + * + * @note This function can be used by the user application to compute the + * baudrate for the communication peripherals or configure other parameters. + * + * @note Each time SYSCLK changes, this function must be called to update the + * right SYSCLK value. Otherwise, any configuration based on this function will be incorrect. + * + * + * @retval SYSCLK frequency + */ +__weak uint32_t DAL_RCM_GetSysClockFreq(void) +{ + uint32_t pllm = 0U, pllvco = 0U, pllp = 0U; + uint32_t sysclockfreq = 0U; + + /* Get SYSCLK source -------------------------------------------------------*/ + switch (RCM->CFG & RCM_CFG_SCLKSWSTS) + { + case RCM_CFG_SCLKSWSTS_HSI: /* HSI used as system clock source */ + { + sysclockfreq = HSI_VALUE; + break; + } + case RCM_CFG_SCLKSWSTS_HSE: /* HSE used as system clock source */ + { + sysclockfreq = HSE_VALUE; + break; + } + case RCM_CFG_SCLKSWSTS_PLL: /* PLL used as system clock source */ + { + /* PLL_VCO = (HSE_VALUE or HSI_VALUE / PLLB) * PLL1A + SYSCLK = PLL_VCO / PLL1C */ + pllm = RCM->PLL1CFG & RCM_PLL1CFG_PLLB; + if(__DAL_RCM_GET_PLL_OSCSOURCE() != RCM_PLLSOURCE_HSI) + { + /* HSE used as PLL clock source */ + pllvco = (uint32_t) ((((uint64_t) HSE_VALUE * ((uint64_t) ((RCM->PLL1CFG & RCM_PLL1CFG_PLL1A) >> RCM_PLL1CFG_PLL1A_Pos)))) / (uint64_t)pllm); + } + else + { + /* HSI used as PLL clock source */ + pllvco = (uint32_t) ((((uint64_t) HSI_VALUE * ((uint64_t) ((RCM->PLL1CFG & RCM_PLL1CFG_PLL1A) >> RCM_PLL1CFG_PLL1A_Pos)))) / (uint64_t)pllm); + } + pllp = ((((RCM->PLL1CFG & RCM_PLL1CFG_PLL1C) >> RCM_PLL1CFG_PLL1C_Pos) + 1U) *2U); + + sysclockfreq = pllvco/pllp; + break; + } + default: + { + sysclockfreq = HSI_VALUE; + break; + } + } + return sysclockfreq; +} + +/** + * @brief Returns the HCLK frequency + * @note Each time HCLK changes, this function must be called to update the + * right HCLK value. Otherwise, any configuration based on this function will be incorrect. + * + * @note The SystemCoreClock CMSIS variable is used to store System Clock Frequency + * and updated within this function + * @retval HCLK frequency + */ +uint32_t DAL_RCM_GetHCLKFreq(void) +{ + return SystemCoreClock; +} + +/** + * @brief Returns the PCLK1 frequency + * @note Each time PCLK1 changes, this function must be called to update the + * right PCLK1 value. Otherwise, any configuration based on this function will be incorrect. + * @retval PCLK1 frequency + */ +uint32_t DAL_RCM_GetPCLK1Freq(void) +{ + /* Get HCLK source and Compute PCLK1 frequency ---------------------------*/ + return (DAL_RCM_GetHCLKFreq() >> APBPrescTable[(RCM->CFG & RCM_CFG_APB1PSC)>> RCM_CFG_APB1PSC_Pos]); +} + +/** + * @brief Returns the PCLK2 frequency + * @note Each time PCLK2 changes, this function must be called to update the + * right PCLK2 value. Otherwise, any configuration based on this function will be incorrect. + * @retval PCLK2 frequency + */ +uint32_t DAL_RCM_GetPCLK2Freq(void) +{ + /* Get HCLK source and Compute PCLK2 frequency ---------------------------*/ + return (DAL_RCM_GetHCLKFreq()>> APBPrescTable[(RCM->CFG & RCM_CFG_APB2PSC)>> RCM_CFG_APB2PSC_Pos]); +} + +/** + * @brief Configures the RCM_OscInitStruct according to the internal + * RCM configuration registers. + * @param RCM_OscInitStruct pointer to an RCM_OscInitTypeDef structure that + * will be configured. + * @retval None + */ +__weak void DAL_RCM_GetOscConfig(RCM_OscInitTypeDef *RCM_OscInitStruct) +{ + /* Set all possible values for the Oscillator type parameter ---------------*/ + RCM_OscInitStruct->OscillatorType = RCM_OSCILLATORTYPE_HSE | RCM_OSCILLATORTYPE_HSI | RCM_OSCILLATORTYPE_LSE | RCM_OSCILLATORTYPE_LSI; + + /* Get the HSE configuration -----------------------------------------------*/ + if((RCM->CTRL &RCM_CTRL_HSEBCFG) == RCM_CTRL_HSEBCFG) + { + RCM_OscInitStruct->HSEState = RCM_HSE_BYPASS; + } + else if((RCM->CTRL &RCM_CTRL_HSEEN) == RCM_CTRL_HSEEN) + { + RCM_OscInitStruct->HSEState = RCM_HSE_ON; + } + else + { + RCM_OscInitStruct->HSEState = RCM_HSE_OFF; + } + + /* Get the HSI configuration -----------------------------------------------*/ + if((RCM->CTRL &RCM_CTRL_HSIEN) == RCM_CTRL_HSIEN) + { + RCM_OscInitStruct->HSIState = RCM_HSI_ON; + } + else + { + RCM_OscInitStruct->HSIState = RCM_HSI_OFF; + } + + RCM_OscInitStruct->HSICalibrationValue = (uint32_t)((RCM->CTRL &RCM_CTRL_HSITRM) >> RCM_CTRL_HSITRM_Pos); + + /* Get the LSE configuration -----------------------------------------------*/ + if((RCM->BDCTRL &RCM_BDCTRL_LSEBCFG) == RCM_BDCTRL_LSEBCFG) + { + RCM_OscInitStruct->LSEState = RCM_LSE_BYPASS; + } + else if((RCM->BDCTRL &RCM_BDCTRL_LSEEN) == RCM_BDCTRL_LSEEN) + { + RCM_OscInitStruct->LSEState = RCM_LSE_ON; + } + else + { + RCM_OscInitStruct->LSEState = RCM_LSE_OFF; + } + + /* Get the LSI configuration -----------------------------------------------*/ + if((RCM->CSTS &RCM_CSTS_LSIEN) == RCM_CSTS_LSIEN) + { + RCM_OscInitStruct->LSIState = RCM_LSI_ON; + } + else + { + RCM_OscInitStruct->LSIState = RCM_LSI_OFF; + } + + /* Get the PLL configuration -----------------------------------------------*/ + if((RCM->CTRL &RCM_CTRL_PLL1EN) == RCM_CTRL_PLL1EN) + { + RCM_OscInitStruct->PLL.PLLState = RCM_PLL_ON; + } + else + { + RCM_OscInitStruct->PLL.PLLState = RCM_PLL_OFF; + } + RCM_OscInitStruct->PLL.PLLSource = (uint32_t)(RCM->PLL1CFG & RCM_PLL1CFG_PLL1CLKS); + RCM_OscInitStruct->PLL.PLLB = (uint32_t)(RCM->PLL1CFG & RCM_PLL1CFG_PLLB); + RCM_OscInitStruct->PLL.PLL1A = (uint32_t)((RCM->PLL1CFG & RCM_PLL1CFG_PLL1A) >> RCM_PLL1CFG_PLL1A_Pos); + RCM_OscInitStruct->PLL.PLL1C = (uint32_t)((((RCM->PLL1CFG & RCM_PLL1CFG_PLL1C) + RCM_PLL1CFG_PLL1C_0) << 1U) >> RCM_PLL1CFG_PLL1C_Pos); + RCM_OscInitStruct->PLL.PLLD = (uint32_t)((RCM->PLL1CFG & RCM_PLL1CFG_PLLD) >> RCM_PLL1CFG_PLLD_Pos); +} + +/** + * @brief Configures the RCM_ClkInitStruct according to the internal + * RCM configuration registers. + * @param RCM_ClkInitStruct pointer to an RCM_ClkInitTypeDef structure that + * will be configured. + * @param pFLatency Pointer on the Flash Latency. + * @retval None + */ +void DAL_RCM_GetClockConfig(RCM_ClkInitTypeDef *RCM_ClkInitStruct, uint32_t *pFLatency) +{ + /* Set all possible values for the Clock type parameter --------------------*/ + RCM_ClkInitStruct->ClockType = RCM_CLOCKTYPE_SYSCLK | RCM_CLOCKTYPE_HCLK | RCM_CLOCKTYPE_PCLK1 | RCM_CLOCKTYPE_PCLK2; + + /* Get the SYSCLK configuration --------------------------------------------*/ + RCM_ClkInitStruct->SYSCLKSource = (uint32_t)(RCM->CFG & RCM_CFG_SCLKSEL); + + /* Get the HCLK configuration ----------------------------------------------*/ + RCM_ClkInitStruct->AHBCLKDivider = (uint32_t)(RCM->CFG & RCM_CFG_AHBPSC); + + /* Get the APB1 configuration ----------------------------------------------*/ + RCM_ClkInitStruct->APB1CLKDivider = (uint32_t)(RCM->CFG & RCM_CFG_APB1PSC); + + /* Get the APB2 configuration ----------------------------------------------*/ + RCM_ClkInitStruct->APB2CLKDivider = (uint32_t)((RCM->CFG & RCM_CFG_APB2PSC) >> 3U); + + /* Get the Flash Wait State (Latency) configuration ------------------------*/ + *pFLatency = (uint32_t)(FLASH->ACCTRL & FLASH_ACCTRL_WAITP); +} + +/** + * @brief This function handles the RCM CSS interrupt request. + * @note This API should be called under the NMI_Handler(). + * @retval None + */ +void DAL_RCM_NMI_IRQHandler(void) +{ + /* Check RCM CSSF flag */ + if(__DAL_RCM_GET_IT(RCM_IT_CSS)) + { + /* RCM Clock Security System interrupt user callback */ + DAL_RCM_CSSCallback(); + + /* Clear RCM CSS pending bit */ + __DAL_RCM_CLEAR_IT(RCM_IT_CSS); + } +} + +/** + * @brief RCM Clock Security System interrupt callback + * @retval None + */ +__weak void DAL_RCM_CSSCallback(void) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the DAL_RCM_CSSCallback could be implemented in the user file + */ +} + +/** + * @} + */ + +/** + * @} + */ + +#endif /* DAL_RCM_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_rcm_ex.c b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_rcm_ex.c new file mode 100644 index 0000000000..2a69bd11a7 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_rcm_ex.c @@ -0,0 +1,685 @@ +/** + * + * @file apm32f4xx_dal_rcm_ex.c + * @brief Extension RCM DAL module driver. + * This file provides firmware functions to manage the following + * functionalities RCM extension peripheral: + * + Extended Peripheral Control functions + * + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2017 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file in + * the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + */ + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @defgroup RCMEx RCMEx + * @brief RCMEx DAL module driver + * @{ + */ + +#ifdef DAL_RCM_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/** @addtogroup RCMEx_Private_Constants + * @{ + */ +/** + * @} + */ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ +/** @defgroup RCMEx_Exported_Functions RCMEx Exported Functions + * @{ + */ + +/** @defgroup RCMEx_Exported_Functions_Group1 Extended Peripheral Control functions + * @brief Extended Peripheral Control functions + * +@verbatim + =============================================================================== + ##### Extended Peripheral Control functions ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to control the RCM Clocks + frequencies. + [..] + (@) Important note: Care must be taken when DAL_RCMEx_PeriphCLKConfig() is used to + select the RTC clock source; in this case the Backup domain will be reset in + order to modify the RTC Clock source, as consequence RTC registers (including + the backup registers) and RCM_BDCTRL register are set to their reset values. + +@endverbatim + * @{ + */ + +#if defined(APM32F405xx) || defined(APM32F407xx)|| defined(APM32F417xx) ||\ + defined(APM32F465xx) || defined(APM32F411xx) +/** + * @brief Initializes the RCM extended peripherals clocks according to the specified parameters in the + * RCM_PeriphCLKInitTypeDef. + * @param PeriphClkInit pointer to an RCM_PeriphCLKInitTypeDef structure that + * contains the configuration information for the Extended Peripherals clocks(I2S and RTC clocks). + * + * @note A caution to be taken when DAL_RCMEx_PeriphCLKConfig() is used to select RTC clock selection, in this case + * the Reset of Backup domain will be applied in order to modify the RTC Clock source as consequence all backup + * domain (RTC and RCM_BDCTRL register expect BKPSRAM) will be reset + * + * @retval DAL status + */ +DAL_StatusTypeDef DAL_RCMEx_PeriphCLKConfig(RCM_PeriphCLKInitTypeDef *PeriphClkInit) +{ + uint32_t tickstart = 0U; + uint32_t tmpreg1 = 0U; + + /* Check the parameters */ + ASSERT_PARAM(IS_RCM_PERIPHCLOCK(PeriphClkInit->PeriphClockSelection)); + +#if defined(APM32F407xx) || defined(APM32F417xx) + /*---------------------------- SDRAM configuration ---------------------------*/ + if(((PeriphClkInit->PeriphClockSelection) & RCM_PERIPHCLK_SDRAM) == RCM_PERIPHCLK_SDRAM) + { + /* Check for parameters */ + ASSERT_PARAM(IS_RCM_SDRAM_DIV(PeriphClkInit->SDRAMClockDivision)); + + /* Set RCM CFG parameters */ + MODIFY_REG(RCM->CFG, RCM_CFG_SDRAMPSC, \ + (PeriphClkInit->SDRAMClockDivision << RCM_CFG_SDRAMPSC_Pos)); + } +#endif /* APM32F407xx || APM32F417xx */ + + /*---------------------------- I2S configuration ---------------------------*/ + if((((PeriphClkInit->PeriphClockSelection) & RCM_PERIPHCLK_I2S) == RCM_PERIPHCLK_I2S) || + (((PeriphClkInit->PeriphClockSelection) & RCM_PERIPHCLK_PLLI2S) == RCM_PERIPHCLK_PLLI2S)) + { + /* check for Parameters */ + ASSERT_PARAM(IS_RCM_PLL2C_VALUE(PeriphClkInit->PLLI2S.PLL2C)); + ASSERT_PARAM(IS_RCM_PLL2A_VALUE(PeriphClkInit->PLLI2S.PLL2A)); +#if defined(APM32F411xx) + ASSERT_PARAM(IS_RCM_PLL2B_VALUE(PeriphClkInit->PLLI2S.PLL2B)); +#endif /* APM32F411xx */ + /* Disable the PLLI2S */ + __DAL_RCM_PLLI2S_DISABLE(); + /* Get tick */ + tickstart = DAL_GetTick(); + /* Wait till PLLI2S is disabled */ + while(__DAL_RCM_GET_FLAG(RCM_FLAG_PLL2RDY) != RESET) + { + if((DAL_GetTick() - tickstart ) > PLLI2S_TIMEOUT_VALUE) + { + /* return in case of Timeout detected */ + return DAL_TIMEOUT; + } + } + +#if defined(APM32F411xx) + /* Configure the PLLI2S division factors */ + /* PLLI2S_VCO = f(VCO clock) = f(PLLI2S clock input) * (PLL2A/PLL2B) */ + /* I2SCLK = f(PLLI2S clock output) = f(VCO clock) / PLL2C */ + __DAL_RCM_PLLI2S_I2SCLK_CONFIG(PeriphClkInit->PLLI2S.PLL2B, PeriphClkInit->PLLI2S.PLL2A, PeriphClkInit->PLLI2S.PLL2C); +#else + /* Configure the PLLI2S division factors */ + /* PLLI2S_VCO = f(VCO clock) = f(PLLI2S clock input) * (PLL2A/PLLB) */ + /* I2SCLK = f(PLLI2S clock output) = f(VCO clock) / PLL2C */ + __DAL_RCM_PLLI2S_CONFIG(PeriphClkInit->PLLI2S.PLL2A , PeriphClkInit->PLLI2S.PLL2C); +#endif /* APM32F411xx */ + + /* Enable the PLLI2S */ + __DAL_RCM_PLLI2S_ENABLE(); + /* Get tick */ + tickstart = DAL_GetTick(); + /* Wait till PLLI2S is ready */ + while(__DAL_RCM_GET_FLAG(RCM_FLAG_PLL2RDY) == RESET) + { + if((DAL_GetTick() - tickstart ) > PLLI2S_TIMEOUT_VALUE) + { + /* return in case of Timeout detected */ + return DAL_TIMEOUT; + } + } + } + + /*---------------------------- RTC configuration ---------------------------*/ + if(((PeriphClkInit->PeriphClockSelection) & RCM_PERIPHCLK_RTC) == (RCM_PERIPHCLK_RTC)) + { + /* Check for RTC Parameters used to output RTCCLK */ + ASSERT_PARAM(IS_RCM_RTCCLKSOURCE(PeriphClkInit->RTCClockSelection)); + + /* Enable Power Clock*/ + __DAL_RCM_PMU_CLK_ENABLE(); + + /* Enable write access to Backup domain */ + PMU->CTRL |= PMU_CTRL_BPWEN; + + /* Get tick */ + tickstart = DAL_GetTick(); + + while((PMU->CTRL & PMU_CTRL_BPWEN) == RESET) + { + if((DAL_GetTick() - tickstart ) > RCM_DBP_TIMEOUT_VALUE) + { + return DAL_TIMEOUT; + } + } + /* Reset the Backup domain only if the RTC Clock source selection is modified from reset value */ + tmpreg1 = (RCM->BDCTRL & RCM_BDCTRL_RTCSRCSEL); + if((tmpreg1 != 0x00000000U) && ((tmpreg1) != (PeriphClkInit->RTCClockSelection & RCM_BDCTRL_RTCSRCSEL))) + { + /* Store the content of BDCTRL register before the reset of Backup Domain */ + tmpreg1 = (RCM->BDCTRL & ~(RCM_BDCTRL_RTCSRCSEL)); + /* RTC Clock selection can be changed only if the Backup Domain is reset */ + __DAL_RCM_BACKUPRESET_FORCE(); + __DAL_RCM_BACKUPRESET_RELEASE(); + /* Restore the Content of BDCTRL register */ + RCM->BDCTRL = tmpreg1; + + /* Wait for LSE reactivation if LSE was enable prior to Backup Domain reset */ + if(DAL_IS_BIT_SET(RCM->BDCTRL, RCM_BDCTRL_LSEEN)) + { + /* Get tick */ + tickstart = DAL_GetTick(); + + /* Wait till LSE is ready */ + while(__DAL_RCM_GET_FLAG(RCM_FLAG_LSERDY) == RESET) + { + if((DAL_GetTick() - tickstart ) > RCM_LSE_TIMEOUT_VALUE) + { + return DAL_TIMEOUT; + } + } + } + } + __DAL_RCM_RTC_CONFIG(PeriphClkInit->RTCClockSelection); + } +#if defined(APM32F411xx) + /*---------------------------- TMR configuration ---------------------------*/ + if(((PeriphClkInit->PeriphClockSelection) & RCM_PERIPHCLK_TMR) == (RCM_PERIPHCLK_TMR)) + { + __DAL_RCM_TMRCLKPRESCALER(PeriphClkInit->TMRPresSelection); + } +#endif /* APM32F411xx */ + return DAL_OK; +} + +/** + * @brief Configures the RCM_OscInitStruct according to the internal + * RCM configuration registers. + * @param PeriphClkInit pointer to an RCM_PeriphCLKInitTypeDef structure that + * will be configured. + * @retval None + */ +void DAL_RCMEx_GetPeriphCLKConfig(RCM_PeriphCLKInitTypeDef *PeriphClkInit) +{ + uint32_t tempreg; + + /* Set all possible values for the extended clock type parameter------------*/ + PeriphClkInit->PeriphClockSelection = RCM_PERIPHCLK_I2S | RCM_PERIPHCLK_RTC; + + /* Get the PLLI2S Clock configuration --------------------------------------*/ + PeriphClkInit->PLLI2S.PLL2A = (uint32_t)((RCM->PLL2CFG & RCM_PLL2CFG_PLL2A) >> RCM_PLL2CFG_PLL2A_Pos); + PeriphClkInit->PLLI2S.PLL2C = (uint32_t)((RCM->PLL2CFG & RCM_PLL2CFG_PLL2C) >> RCM_PLL2CFG_PLL2C_Pos); +#if defined(APM32F411xx) + PeriphClkInit->PLLI2S.PLL2B = (uint32_t)(RCM->PLL2CFG & RCM_PLL2CFG_PLL2B); +#endif /* APM32F411xx */ + /* Get the RTC Clock configuration -----------------------------------------*/ + tempreg = (RCM->CFG & RCM_CFG_RTCPSC); + PeriphClkInit->RTCClockSelection = (uint32_t)((tempreg) | (RCM->BDCTRL & RCM_BDCTRL_RTCSRCSEL)); + +#if defined(APM32F411xx) + /* Get the TMR Prescaler configuration -------------------------------------*/ + if ((RCM->CFGSEL & RCM_CFGSEL_CLKPSEL) == RESET) + { + PeriphClkInit->TMRPresSelection = RCM_TMRPRES_DESACTIVATED; + } + else + { + PeriphClkInit->TMRPresSelection = RCM_TMRPRES_ACTIVATED; + } +#endif /* APM32F411xx */ +} + +/** + * @brief Return the peripheral clock frequency for a given peripheral(SAI..) + * @note Return 0 if peripheral clock identifier not managed by this API + * @param PeriphClk Peripheral clock identifier + * This parameter can be one of the following values: + * @arg RCM_PERIPHCLK_I2S: I2S peripheral clock + * @retval Frequency in KHz + */ +uint32_t DAL_RCMEx_GetPeriphCLKFreq(uint32_t PeriphClk) +{ + /* This variable used to store the I2S clock frequency (value in Hz) */ + uint32_t frequency = 0U; + /* This variable used to store the VCO Input (value in Hz) */ + uint32_t vcoinput = 0U; + uint32_t srcclk = 0U; + /* This variable used to store the VCO Output (value in Hz) */ + uint32_t vcooutput = 0U; + switch (PeriphClk) + { + case RCM_PERIPHCLK_I2S: + { + /* Get the current I2S source */ + srcclk = __DAL_RCM_GET_I2S_SOURCE(); + switch (srcclk) + { + /* Check if I2S clock selection is External clock mapped on the I2S_CKIN pin used as I2S clock */ + case RCM_I2SCLKSOURCE_EXT: + { + /* Set the I2S clock to the external clock value */ + frequency = EXTERNAL_CLOCK_VALUE; + break; + } + /* Check if I2S clock selection is PLLI2S VCO output clock divided by PLL2C used as I2S clock */ + case RCM_I2SCLKSOURCE_PLLI2S: + { +#if defined(APM32F411xx) + /* Configure the PLLI2S division factor */ + /* PLLI2S_VCO Input = PLL_SOURCE/PLL2B */ + if((RCM->PLL1CFG & RCM_PLL1CFG_PLL1CLKS) == RCM_PLLSOURCE_HSE) + { + /* Get the I2S source clock value */ + vcoinput = (uint32_t)(HSE_VALUE / (uint32_t)(RCM->PLL2CFG & RCM_PLL2CFG_PLL2B)); + } + else + { + /* Get the I2S source clock value */ + vcoinput = (uint32_t)(HSI_VALUE / (uint32_t)(RCM->PLL2CFG & RCM_PLL2CFG_PLL2B)); + } +#else + /* Configure the PLLI2S division factor */ + /* PLLI2S_VCO Input = PLL_SOURCE/PLLB */ + if((RCM->PLL1CFG & RCM_PLL1CFG_PLL1CLKS) == RCM_PLLSOURCE_HSE) + { + /* Get the I2S source clock value */ + vcoinput = (uint32_t)(HSE_VALUE / (uint32_t)(RCM->PLL1CFG & RCM_PLL1CFG_PLLB)); + } + else + { + /* Get the I2S source clock value */ + vcoinput = (uint32_t)(HSI_VALUE / (uint32_t)(RCM->PLL1CFG & RCM_PLL1CFG_PLLB)); + } +#endif /* APM32F411xx */ + /* PLLI2S_VCO Output = PLLI2S_VCO Input * PLL2A */ + vcooutput = (uint32_t)(vcoinput * (((RCM->PLL2CFG & RCM_PLL2CFG_PLL2A) >> 6U) & (RCM_PLL2CFG_PLL2A >> 6U))); + /* I2S_CLK = PLLI2S_VCO Output/PLL2C */ + frequency = (uint32_t)(vcooutput /(((RCM->PLL2CFG & RCM_PLL2CFG_PLL2C) >> 28U) & (RCM_PLL2CFG_PLL2C >> 28U))); + break; + } + /* Clock not enabled for I2S*/ + default: + { + frequency = 0U; + break; + } + } + break; + } + } + return frequency; +} +#endif /* APM32F405xx || APM32F407xx || APM32F417xx || APM32F411xx */ + +#if defined(APM32F411xx) && defined(RCM_BDCTRL_LSEMOD) +/** + * @brief Select LSE mode + * + * @note This mode is only available for APM32F411xx devices. + * + * @param Mode specifies the LSE mode. + * This parameter can be one of the following values: + * @arg RCM_LSE_LOWPOWER_MODE: LSE oscillator in low power mode selection + * @arg RCM_LSE_HIGHDRIVE_MODE: LSE oscillator in High Drive mode selection + * @retval None + */ +void DAL_RCMEx_SelectLSEMode(uint8_t Mode) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_RCM_LSE_MODE(Mode)); + if(Mode == RCM_LSE_HIGHDRIVE_MODE) + { + SET_BIT(RCM->BDCTRL, RCM_BDCTRL_LSEMOD); + } + else + { + CLEAR_BIT(RCM->BDCTRL, RCM_BDCTRL_LSEMOD); + } +} + +#endif /* APM32F411xx && RCM_BDCTRL_LSEMOD */ + +/** @defgroup RCMEx_Exported_Functions_Group2 Extended Clock management functions + * @brief Extended Clock management functions + * +@verbatim + =============================================================================== + ##### Extended clock management functions ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to control the + activation or deactivation of PLLI2S, PLLSAI. +@endverbatim + * @{ + */ + +#if defined(RCM_PLLI2S_SUPPORT) +/** + * @brief Enable PLLI2S. + * @param PLLI2SInit pointer to an RCM_PLLI2SInitTypeDef structure that + * contains the configuration information for the PLLI2S + * @retval DAL status + */ +DAL_StatusTypeDef DAL_RCMEx_EnablePLLI2S(RCM_PLLI2SInitTypeDef *PLLI2SInit) +{ + uint32_t tickstart; + + /* Check for parameters */ + ASSERT_PARAM(IS_RCM_PLL2A_VALUE(PLLI2SInit->PLL2A)); + ASSERT_PARAM(IS_RCM_PLL2C_VALUE(PLLI2SInit->PLL2C)); +#if defined(RCM_PLL2CFG_PLL2B) + ASSERT_PARAM(IS_RCM_PLL2B_VALUE(PLLI2SInit->PLL2B)); +#endif /* RCM_PLL2CFG_PLL2B */ +#if defined(RCM_PLL2CFG_PLLI2SP) + ASSERT_PARAM(IS_RCM_PLLI2SP_VALUE(PLLI2SInit->PLLI2SP)); +#endif /* RCM_PLL2CFG_PLLI2SP */ +#if defined(RCM_PLL2CFG_PLLI2SQ) + ASSERT_PARAM(IS_RCM_PLLI2SQ_VALUE(PLLI2SInit->PLLI2SQ)); +#endif /* RCM_PLL2CFG_PLLI2SQ */ + + /* Disable the PLLI2S */ + __DAL_RCM_PLLI2S_DISABLE(); + + /* Wait till PLLI2S is disabled */ + tickstart = DAL_GetTick(); + while(__DAL_RCM_GET_FLAG(RCM_FLAG_PLL2RDY) != RESET) + { + if((DAL_GetTick() - tickstart ) > PLLI2S_TIMEOUT_VALUE) + { + /* return in case of Timeout detected */ + return DAL_TIMEOUT; + } + } + + /* Configure the PLLI2S division factors */ +#if defined(APM32F411xx) + /* PLLI2S_VCO = f(VCO clock) = f(PLLI2S clock input) * (PLL2A/PLL2B) */ + /* I2SRCLK = PLLI2S_VCO / PLL2C */ + __DAL_RCM_PLLI2S_I2SCLK_CONFIG(PLLI2SInit->PLL2B, PLLI2SInit->PLL2A, PLLI2SInit->PLL2C); +#else + /* PLLI2S_VCO = f(VCO clock) = f(PLLI2S clock input) x PLL2A */ + /* I2SRCLK = PLLI2S_VCO / PLL2C */ + __DAL_RCM_PLLI2S_CONFIG(PLLI2SInit->PLL2A, PLLI2SInit->PLL2C); +#endif /* APM32F411xx */ + + /* Enable the PLLI2S */ + __DAL_RCM_PLLI2S_ENABLE(); + + /* Wait till PLLI2S is ready */ + tickstart = DAL_GetTick(); + while(__DAL_RCM_GET_FLAG(RCM_FLAG_PLL2RDY) == RESET) + { + if((DAL_GetTick() - tickstart ) > PLLI2S_TIMEOUT_VALUE) + { + /* return in case of Timeout detected */ + return DAL_TIMEOUT; + } + } + + return DAL_OK; +} + +/** + * @brief Disable PLLI2S. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_RCMEx_DisablePLLI2S(void) +{ + uint32_t tickstart; + + /* Disable the PLLI2S */ + __DAL_RCM_PLLI2S_DISABLE(); + + /* Wait till PLLI2S is disabled */ + tickstart = DAL_GetTick(); + while(READ_BIT(RCM->CTRL, RCM_CTRL_PLL2RDYFLG) != RESET) + { + if((DAL_GetTick() - tickstart) > PLLI2S_TIMEOUT_VALUE) + { + /* return in case of Timeout detected */ + return DAL_TIMEOUT; + } + } + + return DAL_OK; +} + +#endif /* RCM_PLLI2S_SUPPORT */ + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +/** + * @brief Resets the RCM clock configuration to the default reset state. + * @note The default reset state of the clock configuration is given below: + * - HSI ON and used as system clock source + * - HSE, PLL, PLLI2S and PLLSAI OFF + * - AHB, APB1 and APB2 prescaler set to 1. + * - CSS, MCO1 and MCO2 OFF + * - All interrupts disabled + * @note This function doesn't modify the configuration of the + * - Peripheral clocks + * - LSI, LSE and RTC clocks + * @retval DAL status + */ +DAL_StatusTypeDef DAL_RCM_DeInit(void) +{ + uint32_t tickstart; + + /* Get Start Tick */ + tickstart = DAL_GetTick(); + + /* Set HSIEN bit to the reset value */ + SET_BIT(RCM->CTRL, RCM_CTRL_HSIEN); + + /* Wait till HSI is ready */ + while (READ_BIT(RCM->CTRL, RCM_CTRL_HSIRDYFLG) == RESET) + { + if ((DAL_GetTick() - tickstart) > HSI_TIMEOUT_VALUE) + { + return DAL_TIMEOUT; + } + } + + /* Set HSITRM[4:0] bits to the reset value */ + SET_BIT(RCM->CTRL, RCM_CTRL_HSITRM_4); + + /* Get Start Tick */ + tickstart = DAL_GetTick(); + + /* Reset CFG register */ + CLEAR_REG(RCM->CFG); + + /* Wait till clock switch is ready */ + while (READ_BIT(RCM->CFG, RCM_CFG_SCLKSWSTS) != RESET) + { + if ((DAL_GetTick() - tickstart) > CLOCKSWITCH_TIMEOUT_VALUE) + { + return DAL_TIMEOUT; + } + } + + /* Get Start Tick */ + tickstart = DAL_GetTick(); + + /* Clear HSEEN, HSEBCFG and CSSEN bits */ + CLEAR_BIT(RCM->CTRL, RCM_CTRL_HSEEN | RCM_CTRL_HSEBCFG | RCM_CTRL_CSSEN); + + /* Wait till HSE is disabled */ + while (READ_BIT(RCM->CTRL, RCM_CTRL_HSERDYFLG) != RESET) + { + if ((DAL_GetTick() - tickstart) > HSE_TIMEOUT_VALUE) + { + return DAL_TIMEOUT; + } + } + + /* Get Start Tick */ + tickstart = DAL_GetTick(); + + /* Clear PLL1EN bit */ + CLEAR_BIT(RCM->CTRL, RCM_CTRL_PLL1EN); + + /* Wait till PLL is disabled */ + while (READ_BIT(RCM->CTRL, RCM_CTRL_PLL1RDYFLG) != RESET) + { + if ((DAL_GetTick() - tickstart) > PLL_TIMEOUT_VALUE) + { + return DAL_TIMEOUT; + } + } + +#if defined(RCM_PLLI2S_SUPPORT) + /* Get Start Tick */ + tickstart = DAL_GetTick(); + + /* Reset PLL2EN bit */ + CLEAR_BIT(RCM->CTRL, RCM_CTRL_PLL2EN); + + /* Wait till PLLI2S is disabled */ + while (READ_BIT(RCM->CTRL, RCM_CTRL_PLL2RDYFLG) != RESET) + { + if ((DAL_GetTick() - tickstart) > PLLI2S_TIMEOUT_VALUE) + { + return DAL_TIMEOUT; + } + } +#endif /* RCM_PLLI2S_SUPPORT */ + +#if defined(RCM_PLLSAI_SUPPORT) + /* Get Start Tick */ + tickstart = DAL_GetTick(); + + /* Reset PLLSAI bit */ + CLEAR_BIT(RCM->CTRL, RCM_CTRL_PLLSAION); + + /* Wait till PLLSAI is disabled */ + while (READ_BIT(RCM->CTRL, RCM_CTRL_PLLSAIRDY) != RESET) + { + if ((DAL_GetTick() - tickstart) > PLLSAI_TIMEOUT_VALUE) + { + return DAL_TIMEOUT; + } + } +#endif /* RCM_PLLSAI_SUPPORT */ + + /* Once PLL, PLLI2S and PLLSAI are OFF, reset PLLCFGR register to default value */ + RCM->PLL1CFG = RCM_PLL1CFG_PLLB_4 | RCM_PLL1CFG_PLL1A_6 | RCM_PLL1CFG_PLL1A_7 | RCM_PLL1CFG_PLLD_2; + + /* Reset PLLI2SCFGR register to default value */ +#if defined(APM32F405xx) || defined(APM32F407xx) || defined(APM32F417xx) || defined(APM32F465xx) + RCM->PLL2CFG = RCM_PLL2CFG_PLL2A_6 | RCM_PLL2CFG_PLL2A_7 | RCM_PLL2CFG_PLL2C_1; +#elif defined(APM32F411xx) + RCM->PLL2CFG = RCM_PLL2CFG_PLL2B_4 | RCM_PLL2CFG_PLL2A_6 | RCM_PLL2CFG_PLL2A_7 | RCM_PLL2CFG_PLL2C_1; +#endif /* APM32F405xx || APM32F407xx || APM32F417xx || APM32F465xx */ + + /* Disable all interrupts */ + CLEAR_BIT(RCM->INT, RCM_INT_LSIRDYEN | RCM_INT_LSERDYEN | RCM_INT_HSIRDYEN | RCM_INT_HSERDYEN | RCM_INT_PLL1RDYEN); + +#if defined(RCM_INT_PLL2RDYEN) + CLEAR_BIT(RCM->INT, RCM_INT_PLL2RDYEN); +#endif /* RCM_INT_PLL2RDYEN */ + +#if defined(RCM_INT_PLLSAIRDYIE) + CLEAR_BIT(RCM->INT, RCM_INT_PLLSAIRDYIE); +#endif /* RCM_INT_PLLSAIRDYIE */ + + /* Clear all interrupt flags */ + SET_BIT(RCM->INT, RCM_INT_LSIRDYCLR | RCM_INT_LSERDYCLR | RCM_INT_HSIRDYCLR | RCM_INT_HSERDYCLR | RCM_INT_PLL1RDYCLR | RCM_INT_CSSCLR); + +#if defined(RCM_INT_PLL2RDYCLR) + SET_BIT(RCM->INT, RCM_INT_PLL2RDYCLR); +#endif /* RCM_INT_PLL2RDYCLR */ + +#if defined(RCM_INT_PLLSAIRDYC) + SET_BIT(RCM->INT, RCM_INT_PLLSAIRDYC); +#endif /* RCM_INT_PLLSAIRDYC */ + + /* Clear LSIEN bit */ + CLEAR_BIT(RCM->CSTS, RCM_CSTS_LSIEN); + + /* Reset all CSTS flags */ + SET_BIT(RCM->CSTS, RCM_CSTS_RSTFLGCLR); + + /* Update the SystemCoreClock global variable */ + SystemCoreClock = HSI_VALUE; + + /* Adapt Systick interrupt period */ + if(DAL_InitTick(uwTickPrio) != DAL_OK) + { + return DAL_ERROR; + } + else + { + return DAL_OK; + } +} + +#endif /* DAL_RCM_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_rng.c b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_rng.c new file mode 100644 index 0000000000..20abc0f65c --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_rng.c @@ -0,0 +1,892 @@ +/** + * + * @file apm32f4xx_dal_rng.c + * @brief RNG DAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the Random Number Generator (RNG) peripheral: + * + Initialization and configuration functions + * + Peripheral Control functions + * + Peripheral State functions + * + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + * + @verbatim + ============================================================================== + ##### How to use this driver ##### + ============================================================================== + [..] + The RNG DAL driver can be used as follows: + + (#) Enable the RNG controller clock using __DAL_RCM_RNG_CLK_ENABLE() macro + in DAL_RNG_MspInit(). + (#) Activate the RNG peripheral using DAL_RNG_Init() function. + (#) Wait until the 32 bit Random Number Generator contains a valid + random data using (polling/interrupt) mode. + (#) Get the 32 bit random number using DAL_RNG_GenerateRandomNumber() function. + + ##### Callback registration ##### + ================================== + + [..] + The compilation define USE_DAL_RNG_REGISTER_CALLBACKS when set to 1 + allows the user to configure dynamically the driver callbacks. + + [..] + Use Function DAL_RNG_RegisterCallback() to register a user callback. + Function DAL_RNG_RegisterCallback() allows to register following callbacks: + (+) ErrorCallback : RNG Error Callback. + (+) MspInitCallback : RNG MspInit. + (+) MspDeInitCallback : RNG MspDeInit. + This function takes as parameters the DAL peripheral handle, the Callback ID + and a pointer to the user callback function. + + [..] + Use function DAL_RNG_UnRegisterCallback() to reset a callback to the default + weak (surcharged) function. + DAL_RNG_UnRegisterCallback() takes as parameters the DAL peripheral handle, + and the Callback ID. + This function allows to reset following callbacks: + (+) ErrorCallback : RNG Error Callback. + (+) MspInitCallback : RNG MspInit. + (+) MspDeInitCallback : RNG MspDeInit. + + [..] + For specific callback ReadyDataCallback, use dedicated register callbacks: + respectively DAL_RNG_RegisterReadyDataCallback() , DAL_RNG_UnRegisterReadyDataCallback(). + + [..] + By default, after the DAL_RNG_Init() and when the state is DAL_RNG_STATE_RESET + all callbacks are set to the corresponding weak (surcharged) functions: + example DAL_RNG_ErrorCallback(). + Exception done for MspInit and MspDeInit functions that are respectively + reset to the legacy weak (surcharged) functions in the DAL_RNG_Init() + and DAL_RNG_DeInit() only when these callbacks are null (not registered beforehand). + If not, MspInit or MspDeInit are not null, the DAL_RNG_Init() and DAL_RNG_DeInit() + keep and use the user MspInit/MspDeInit callbacks (registered beforehand). + + [..] + Callbacks can be registered/unregistered in DAL_RNG_STATE_READY state only. + Exception done MspInit/MspDeInit that can be registered/unregistered + in DAL_RNG_STATE_READY or DAL_RNG_STATE_RESET state, thus registered (user) + MspInit/DeInit callbacks can be used during the Init/DeInit. + In that case first register the MspInit/MspDeInit user callbacks + using DAL_RNG_RegisterCallback() before calling DAL_RNG_DeInit() + or DAL_RNG_Init() function. + + [..] + When The compilation define USE_DAL_RNG_REGISTER_CALLBACKS is set to 0 or + not defined, the callback registration feature is not available + and weak (surcharged) callbacks are used. + + @endverbatim + * + */ + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +#if defined (RNG) + +/** @addtogroup RNG + * @brief RNG DAL module driver. + * @{ + */ + +#ifdef DAL_RNG_MODULE_ENABLED + +/* Private types -------------------------------------------------------------*/ +/* Private defines -----------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/** @defgroup RNG_Private_Constants RNG Private Constants + * @{ + */ +#define RNG_TIMEOUT_VALUE 2U +/** + * @} + */ +/* Private macros ------------------------------------------------------------*/ +/* Private functions prototypes ----------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ +/* Exported functions --------------------------------------------------------*/ + +/** @addtogroup RNG_Exported_Functions + * @{ + */ + +/** @addtogroup RNG_Exported_Functions_Group1 + * @brief Initialization and configuration functions + * +@verbatim + =============================================================================== + ##### Initialization and configuration functions ##### + =============================================================================== + [..] This section provides functions allowing to: + (+) Initialize the RNG according to the specified parameters + in the RNG_InitTypeDef and create the associated handle + (+) DeInitialize the RNG peripheral + (+) Initialize the RNG MSP + (+) DeInitialize RNG MSP + +@endverbatim + * @{ + */ + +/** + * @brief Initializes the RNG peripheral and creates the associated handle. + * @param hrng pointer to a RNG_HandleTypeDef structure that contains + * the configuration information for RNG. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_RNG_Init(RNG_HandleTypeDef *hrng) +{ + /* Check the RNG handle allocation */ + if (hrng == NULL) + { + return DAL_ERROR; + } + /* Check the parameters */ + ASSERT_PARAM(IS_RNG_ALL_INSTANCE(hrng->Instance)); + +#if (USE_DAL_RNG_REGISTER_CALLBACKS == 1) + if (hrng->State == DAL_RNG_STATE_RESET) + { + /* Allocate lock resource and initialize it */ + hrng->Lock = DAL_UNLOCKED; + + hrng->ReadyDataCallback = DAL_RNG_ReadyDataCallback; /* Legacy weak ReadyDataCallback */ + hrng->ErrorCallback = DAL_RNG_ErrorCallback; /* Legacy weak ErrorCallback */ + + if (hrng->MspInitCallback == NULL) + { + hrng->MspInitCallback = DAL_RNG_MspInit; /* Legacy weak MspInit */ + } + + /* Init the low level hardware */ + hrng->MspInitCallback(hrng); + } +#else + if (hrng->State == DAL_RNG_STATE_RESET) + { + /* Allocate lock resource and initialize it */ + hrng->Lock = DAL_UNLOCKED; + + /* Init the low level hardware */ + DAL_RNG_MspInit(hrng); + } +#endif /* USE_DAL_RNG_REGISTER_CALLBACKS */ + + /* Change RNG peripheral state */ + hrng->State = DAL_RNG_STATE_BUSY; + + + /* Enable the RNG Peripheral */ + __DAL_RNG_ENABLE(hrng); + + /* Initialize the RNG state */ + hrng->State = DAL_RNG_STATE_READY; + + /* Initialise the error code */ + hrng->ErrorCode = DAL_RNG_ERROR_NONE; + + /* Return function status */ + return DAL_OK; +} + +/** + * @brief DeInitializes the RNG peripheral. + * @param hrng pointer to a RNG_HandleTypeDef structure that contains + * the configuration information for RNG. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_RNG_DeInit(RNG_HandleTypeDef *hrng) +{ + /* Check the RNG handle allocation */ + if (hrng == NULL) + { + return DAL_ERROR; + } + + /* Disable the RNG Peripheral */ + CLEAR_BIT(hrng->Instance->CTRL, RNG_CTRL_INTEN | RNG_CTRL_RNGEN); + + /* Clear RNG interrupt status flags */ + CLEAR_BIT(hrng->Instance->STS, RNG_STS_CLKERINT | RNG_STS_FSINT); + +#if (USE_DAL_RNG_REGISTER_CALLBACKS == 1) + if (hrng->MspDeInitCallback == NULL) + { + hrng->MspDeInitCallback = DAL_RNG_MspDeInit; /* Legacy weak MspDeInit */ + } + + /* DeInit the low level hardware */ + hrng->MspDeInitCallback(hrng); +#else + /* DeInit the low level hardware */ + DAL_RNG_MspDeInit(hrng); +#endif /* USE_DAL_RNG_REGISTER_CALLBACKS */ + + /* Update the RNG state */ + hrng->State = DAL_RNG_STATE_RESET; + + /* Initialise the error code */ + hrng->ErrorCode = DAL_RNG_ERROR_NONE; + + /* Release Lock */ + __DAL_UNLOCK(hrng); + + /* Return the function status */ + return DAL_OK; +} + +/** + * @brief Initializes the RNG MSP. + * @param hrng pointer to a RNG_HandleTypeDef structure that contains + * the configuration information for RNG. + * @retval None + */ +__weak void DAL_RNG_MspInit(RNG_HandleTypeDef *hrng) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hrng); + /* NOTE : This function should not be modified. When the callback is needed, + function DAL_RNG_MspInit must be implemented in the user file. + */ +} + +/** + * @brief DeInitializes the RNG MSP. + * @param hrng pointer to a RNG_HandleTypeDef structure that contains + * the configuration information for RNG. + * @retval None + */ +__weak void DAL_RNG_MspDeInit(RNG_HandleTypeDef *hrng) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hrng); + /* NOTE : This function should not be modified. When the callback is needed, + function DAL_RNG_MspDeInit must be implemented in the user file. + */ +} + +#if (USE_DAL_RNG_REGISTER_CALLBACKS == 1) +/** + * @brief Register a User RNG Callback + * To be used instead of the weak predefined callback + * @param hrng RNG handle + * @param CallbackID ID of the callback to be registered + * This parameter can be one of the following values: + * @arg @ref DAL_RNG_ERROR_CB_ID Error callback ID + * @arg @ref DAL_RNG_MSPINIT_CB_ID MspInit callback ID + * @arg @ref DAL_RNG_MSPDEINIT_CB_ID MspDeInit callback ID + * @param pCallback pointer to the Callback function + * @retval DAL status + */ +DAL_StatusTypeDef DAL_RNG_RegisterCallback(RNG_HandleTypeDef *hrng, DAL_RNG_CallbackIDTypeDef CallbackID, + pRNG_CallbackTypeDef pCallback) +{ + DAL_StatusTypeDef status = DAL_OK; + + if (pCallback == NULL) + { + /* Update the error code */ + hrng->ErrorCode = DAL_RNG_ERROR_INVALID_CALLBACK; + return DAL_ERROR; + } + /* Process locked */ + __DAL_LOCK(hrng); + + if (DAL_RNG_STATE_READY == hrng->State) + { + switch (CallbackID) + { + case DAL_RNG_ERROR_CB_ID : + hrng->ErrorCallback = pCallback; + break; + + case DAL_RNG_MSPINIT_CB_ID : + hrng->MspInitCallback = pCallback; + break; + + case DAL_RNG_MSPDEINIT_CB_ID : + hrng->MspDeInitCallback = pCallback; + break; + + default : + /* Update the error code */ + hrng->ErrorCode = DAL_RNG_ERROR_INVALID_CALLBACK; + /* Return error status */ + status = DAL_ERROR; + break; + } + } + else if (DAL_RNG_STATE_RESET == hrng->State) + { + switch (CallbackID) + { + case DAL_RNG_MSPINIT_CB_ID : + hrng->MspInitCallback = pCallback; + break; + + case DAL_RNG_MSPDEINIT_CB_ID : + hrng->MspDeInitCallback = pCallback; + break; + + default : + /* Update the error code */ + hrng->ErrorCode = DAL_RNG_ERROR_INVALID_CALLBACK; + /* Return error status */ + status = DAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + hrng->ErrorCode = DAL_RNG_ERROR_INVALID_CALLBACK; + /* Return error status */ + status = DAL_ERROR; + } + + /* Release Lock */ + __DAL_UNLOCK(hrng); + return status; +} + +/** + * @brief Unregister an RNG Callback + * RNG callback is redirected to the weak predefined callback + * @param hrng RNG handle + * @param CallbackID ID of the callback to be unregistered + * This parameter can be one of the following values: + * @arg @ref DAL_RNG_ERROR_CB_ID Error callback ID + * @arg @ref DAL_RNG_MSPINIT_CB_ID MspInit callback ID + * @arg @ref DAL_RNG_MSPDEINIT_CB_ID MspDeInit callback ID + * @retval DAL status + */ +DAL_StatusTypeDef DAL_RNG_UnRegisterCallback(RNG_HandleTypeDef *hrng, DAL_RNG_CallbackIDTypeDef CallbackID) +{ + DAL_StatusTypeDef status = DAL_OK; + + /* Process locked */ + __DAL_LOCK(hrng); + + if (DAL_RNG_STATE_READY == hrng->State) + { + switch (CallbackID) + { + case DAL_RNG_ERROR_CB_ID : + hrng->ErrorCallback = DAL_RNG_ErrorCallback; /* Legacy weak ErrorCallback */ + break; + + case DAL_RNG_MSPINIT_CB_ID : + hrng->MspInitCallback = DAL_RNG_MspInit; /* Legacy weak MspInit */ + break; + + case DAL_RNG_MSPDEINIT_CB_ID : + hrng->MspDeInitCallback = DAL_RNG_MspDeInit; /* Legacy weak MspDeInit */ + break; + + default : + /* Update the error code */ + hrng->ErrorCode = DAL_RNG_ERROR_INVALID_CALLBACK; + /* Return error status */ + status = DAL_ERROR; + break; + } + } + else if (DAL_RNG_STATE_RESET == hrng->State) + { + switch (CallbackID) + { + case DAL_RNG_MSPINIT_CB_ID : + hrng->MspInitCallback = DAL_RNG_MspInit; /* Legacy weak MspInit */ + break; + + case DAL_RNG_MSPDEINIT_CB_ID : + hrng->MspDeInitCallback = DAL_RNG_MspDeInit; /* Legacy weak MspInit */ + break; + + default : + /* Update the error code */ + hrng->ErrorCode = DAL_RNG_ERROR_INVALID_CALLBACK; + /* Return error status */ + status = DAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + hrng->ErrorCode = DAL_RNG_ERROR_INVALID_CALLBACK; + /* Return error status */ + status = DAL_ERROR; + } + + /* Release Lock */ + __DAL_UNLOCK(hrng); + return status; +} + +/** + * @brief Register Data Ready RNG Callback + * To be used instead of the weak DAL_RNG_ReadyDataCallback() predefined callback + * @param hrng RNG handle + * @param pCallback pointer to the Data Ready Callback function + * @retval DAL status + */ +DAL_StatusTypeDef DAL_RNG_RegisterReadyDataCallback(RNG_HandleTypeDef *hrng, pRNG_ReadyDataCallbackTypeDef pCallback) +{ + DAL_StatusTypeDef status = DAL_OK; + + if (pCallback == NULL) + { + /* Update the error code */ + hrng->ErrorCode = DAL_RNG_ERROR_INVALID_CALLBACK; + return DAL_ERROR; + } + /* Process locked */ + __DAL_LOCK(hrng); + + if (DAL_RNG_STATE_READY == hrng->State) + { + hrng->ReadyDataCallback = pCallback; + } + else + { + /* Update the error code */ + hrng->ErrorCode = DAL_RNG_ERROR_INVALID_CALLBACK; + /* Return error status */ + status = DAL_ERROR; + } + + /* Release Lock */ + __DAL_UNLOCK(hrng); + return status; +} + +/** + * @brief UnRegister the Data Ready RNG Callback + * Data Ready RNG Callback is redirected to the weak DAL_RNG_ReadyDataCallback() predefined callback + * @param hrng RNG handle + * @retval DAL status + */ +DAL_StatusTypeDef DAL_RNG_UnRegisterReadyDataCallback(RNG_HandleTypeDef *hrng) +{ + DAL_StatusTypeDef status = DAL_OK; + + /* Process locked */ + __DAL_LOCK(hrng); + + if (DAL_RNG_STATE_READY == hrng->State) + { + hrng->ReadyDataCallback = DAL_RNG_ReadyDataCallback; /* Legacy weak ReadyDataCallback */ + } + else + { + /* Update the error code */ + hrng->ErrorCode = DAL_RNG_ERROR_INVALID_CALLBACK; + /* Return error status */ + status = DAL_ERROR; + } + + /* Release Lock */ + __DAL_UNLOCK(hrng); + return status; +} + +#endif /* USE_DAL_RNG_REGISTER_CALLBACKS */ + +/** + * @} + */ + +/** @addtogroup RNG_Exported_Functions_Group2 + * @brief Peripheral Control functions + * +@verbatim + =============================================================================== + ##### Peripheral Control functions ##### + =============================================================================== + [..] This section provides functions allowing to: + (+) Get the 32 bit Random number + (+) Get the 32 bit Random number with interrupt enabled + (+) Handle RNG interrupt request + +@endverbatim + * @{ + */ + +/** + * @brief Generates a 32-bit random number. + * @note Each time the random number data is read the RNG_FLAG_DRDY flag + * is automatically cleared. + * @param hrng pointer to a RNG_HandleTypeDef structure that contains + * the configuration information for RNG. + * @param random32bit pointer to generated random number variable if successful. + * @retval DAL status + */ + +DAL_StatusTypeDef DAL_RNG_GenerateRandomNumber(RNG_HandleTypeDef *hrng, uint32_t *random32bit) +{ + uint32_t tickstart; + DAL_StatusTypeDef status = DAL_OK; + + /* Process Locked */ + __DAL_LOCK(hrng); + + /* Check RNG peripheral state */ + if (hrng->State == DAL_RNG_STATE_READY) + { + /* Change RNG peripheral state */ + hrng->State = DAL_RNG_STATE_BUSY; + + /* Get tick */ + tickstart = DAL_GetTick(); + + /* Check if data register contains valid random data */ + while (__DAL_RNG_GET_FLAG(hrng, RNG_FLAG_DRDY) == RESET) + { + if ((DAL_GetTick() - tickstart) > RNG_TIMEOUT_VALUE) + { + /* New check to avoid false timeout detection in case of preemption */ + if (__DAL_RNG_GET_FLAG(hrng, RNG_FLAG_DRDY) == RESET) + { + hrng->State = DAL_RNG_STATE_READY; + hrng->ErrorCode = DAL_RNG_ERROR_TIMEOUT; + /* Process Unlocked */ + __DAL_UNLOCK(hrng); + return DAL_ERROR; + } + } + } + + /* Get a 32bit Random number */ + hrng->RandomNumber = hrng->Instance->DATA; + *random32bit = hrng->RandomNumber; + + hrng->State = DAL_RNG_STATE_READY; + } + else + { + hrng->ErrorCode = DAL_RNG_ERROR_BUSY; + status = DAL_ERROR; + } + + /* Process Unlocked */ + __DAL_UNLOCK(hrng); + + return status; +} + +/** + * @brief Generates a 32-bit random number in interrupt mode. + * @param hrng pointer to a RNG_HandleTypeDef structure that contains + * the configuration information for RNG. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_RNG_GenerateRandomNumber_IT(RNG_HandleTypeDef *hrng) +{ + DAL_StatusTypeDef status = DAL_OK; + + /* Process Locked */ + __DAL_LOCK(hrng); + + /* Check RNG peripheral state */ + if (hrng->State == DAL_RNG_STATE_READY) + { + /* Change RNG peripheral state */ + hrng->State = DAL_RNG_STATE_BUSY; + + /* Enable the RNG Interrupts: Data Ready, Clock error, Seed error */ + __DAL_RNG_ENABLE_IT(hrng); + } + else + { + /* Process Unlocked */ + __DAL_UNLOCK(hrng); + + hrng->ErrorCode = DAL_RNG_ERROR_BUSY; + status = DAL_ERROR; + } + + return status; +} + +/** + * @brief Returns generated random number in polling mode (Obsolete) + * Use DAL_RNG_GenerateRandomNumber() API instead. + * @param hrng pointer to a RNG_HandleTypeDef structure that contains + * the configuration information for RNG. + * @retval Random value + */ +uint32_t DAL_RNG_GetRandomNumber(RNG_HandleTypeDef *hrng) +{ + if (DAL_RNG_GenerateRandomNumber(hrng, &(hrng->RandomNumber)) == DAL_OK) + { + return hrng->RandomNumber; + } + else + { + return 0U; + } +} + +/** + * @brief Returns a 32-bit random number with interrupt enabled (Obsolete), + * Use DAL_RNG_GenerateRandomNumber_IT() API instead. + * @param hrng pointer to a RNG_HandleTypeDef structure that contains + * the configuration information for RNG. + * @retval 32-bit random number + */ +uint32_t DAL_RNG_GetRandomNumber_IT(RNG_HandleTypeDef *hrng) +{ + uint32_t random32bit = 0U; + + /* Process locked */ + __DAL_LOCK(hrng); + + /* Change RNG peripheral state */ + hrng->State = DAL_RNG_STATE_BUSY; + + /* Get a 32bit Random number */ + random32bit = hrng->Instance->DATA; + + /* Enable the RNG Interrupts: Data Ready, Clock error, Seed error */ + __DAL_RNG_ENABLE_IT(hrng); + + /* Return the 32 bit random number */ + return random32bit; +} + +/** + * @brief Handles RNG interrupt request. + * @note In the case of a clock error, the RNG is no more able to generate + * random numbers because the PLL48CLK clock is not correct. User has + * to check that the clock controller is correctly configured to provide + * the RNG clock and clear the CEIS bit using __DAL_RNG_CLEAR_IT(). + * The clock error has no impact on the previously generated + * random numbers, and the RNG_DATA register contents can be used. + * @note In the case of a seed error, the generation of random numbers is + * interrupted as long as the SECS bit is '1'. If a number is + * available in the RNG_DATA register, it must not be used because it may + * not have enough entropy. In this case, it is recommended to clear the + * SEIS bit using __DAL_RNG_CLEAR_IT(), then disable and enable + * the RNG peripheral to reinitialize and restart the RNG. + * @note User-written DAL_RNG_ErrorCallback() API is called once whether SEIS + * or CEIS are set. + * @param hrng pointer to a RNG_HandleTypeDef structure that contains + * the configuration information for RNG. + * @retval None + + */ +void DAL_RNG_IRQHandler(RNG_HandleTypeDef *hrng) +{ + uint32_t rngclockerror = 0U; + + /* RNG clock error interrupt occurred */ + if (__DAL_RNG_GET_IT(hrng, RNG_IT_CEI) != RESET) + { + /* Update the error code */ + hrng->ErrorCode = DAL_RNG_ERROR_CLOCK; + rngclockerror = 1U; + } + else if (__DAL_RNG_GET_IT(hrng, RNG_IT_SEI) != RESET) + { + /* Update the error code */ + hrng->ErrorCode = DAL_RNG_ERROR_SEED; + rngclockerror = 1U; + } + else + { + /* Nothing to do */ + } + + if (rngclockerror == 1U) + { + /* Change RNG peripheral state */ + hrng->State = DAL_RNG_STATE_ERROR; + +#if (USE_DAL_RNG_REGISTER_CALLBACKS == 1) + /* Call registered Error callback */ + hrng->ErrorCallback(hrng); +#else + /* Call legacy weak Error callback */ + DAL_RNG_ErrorCallback(hrng); +#endif /* USE_DAL_RNG_REGISTER_CALLBACKS */ + + /* Clear the clock error flag */ + __DAL_RNG_CLEAR_IT(hrng, RNG_IT_CEI | RNG_IT_SEI); + + return; + } + + /* Check RNG data ready interrupt occurred */ + if (__DAL_RNG_GET_IT(hrng, RNG_IT_DRDY) != RESET) + { + /* Generate random number once, so disable the IT */ + __DAL_RNG_DISABLE_IT(hrng); + + /* Get the 32bit Random number (DRDY flag automatically cleared) */ + hrng->RandomNumber = hrng->Instance->DATA; + + if (hrng->State != DAL_RNG_STATE_ERROR) + { + /* Change RNG peripheral state */ + hrng->State = DAL_RNG_STATE_READY; + /* Process Unlocked */ + __DAL_UNLOCK(hrng); + +#if (USE_DAL_RNG_REGISTER_CALLBACKS == 1) + /* Call registered Data Ready callback */ + hrng->ReadyDataCallback(hrng, hrng->RandomNumber); +#else + /* Call legacy weak Data Ready callback */ + DAL_RNG_ReadyDataCallback(hrng, hrng->RandomNumber); +#endif /* USE_DAL_RNG_REGISTER_CALLBACKS */ + } + } +} + +/** + * @brief Read latest generated random number. + * @param hrng pointer to a RNG_HandleTypeDef structure that contains + * the configuration information for RNG. + * @retval random value + */ +uint32_t DAL_RNG_ReadLastRandomNumber(RNG_HandleTypeDef *hrng) +{ + return (hrng->RandomNumber); +} + +/** + * @brief Data Ready callback in non-blocking mode. + * @param hrng pointer to a RNG_HandleTypeDef structure that contains + * the configuration information for RNG. + * @param random32bit generated random number. + * @retval None + */ +__weak void DAL_RNG_ReadyDataCallback(RNG_HandleTypeDef *hrng, uint32_t random32bit) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hrng); + UNUSED(random32bit); + /* NOTE : This function should not be modified. When the callback is needed, + function DAL_RNG_ReadyDataCallback must be implemented in the user file. + */ +} + +/** + * @brief RNG error callbacks. + * @param hrng pointer to a RNG_HandleTypeDef structure that contains + * the configuration information for RNG. + * @retval None + */ +__weak void DAL_RNG_ErrorCallback(RNG_HandleTypeDef *hrng) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hrng); + /* NOTE : This function should not be modified. When the callback is needed, + function DAL_RNG_ErrorCallback must be implemented in the user file. + */ +} +/** + * @} + */ + + +/** @addtogroup RNG_Exported_Functions_Group3 + * @brief Peripheral State functions + * +@verbatim + =============================================================================== + ##### Peripheral State functions ##### + =============================================================================== + [..] + This subsection permits to get in run-time the status of the peripheral + and the data flow. + +@endverbatim + * @{ + */ + +/** + * @brief Returns the RNG state. + * @param hrng pointer to a RNG_HandleTypeDef structure that contains + * the configuration information for RNG. + * @retval DAL state + */ +DAL_RNG_StateTypeDef DAL_RNG_GetState(RNG_HandleTypeDef *hrng) +{ + return hrng->State; +} + +/** + * @brief Return the RNG handle error code. + * @param hrng: pointer to a RNG_HandleTypeDef structure. + * @retval RNG Error Code + */ +uint32_t DAL_RNG_GetError(RNG_HandleTypeDef *hrng) +{ + /* Return RNG Error Code */ + return hrng->ErrorCode; +} +/** + * @} + */ + +/** + * @} + */ + + +#endif /* DAL_RNG_MODULE_ENABLED */ +/** + * @} + */ + +#endif /* RNG */ + +/** + * @} + */ + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_rtc.c b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_rtc.c new file mode 100644 index 0000000000..e88e3577b0 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_rtc.c @@ -0,0 +1,1921 @@ +/** + * + * @file apm32f4xx_dal_rtc.c + * @brief RTC DAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the Real-Time Clock (RTC) peripheral: + * + Initialization and de-initialization functions + * + RTC Calendar (Time and Date) configuration functions + * + RTC Alarms (Alarm A and Alarm B) configuration functions + * + Peripheral Control functions + * + Peripheral State functions + * + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2017 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + * + @verbatim + ============================================================================== + ##### RTC and Backup Domain Operating Condition ##### + ============================================================================== + [..] The real-time clock (RTC), the RTC backup registers, and the backup + SRAM (BKP SRAM) can be powered from the VBAT voltage when the main + VDD supply is powered off. + To retain the content of the RTC backup registers, BKP SRAM, and supply + the RTC when VDD is turned off, VBAT pin can be connected to an optional + standby voltage supplied by a battery or by another source. + + [..] To allow the RTC operating even when the main digital supply (VDD) is turned + off, the VBAT pin powers the following blocks: + (#) The RTC + (#) The LSE oscillator + (#) The BKP SRAM when the low power backup regulator is enabled + (#) PC13 to PC15 I/Os, plus PI8 I/O (when available) + + [..] When the backup domain is supplied by VDD (analog switch connected to VDD), + the following pins are available: + (#) PC14 and PC15 can be used as either GPIO or LSE pins + (#) PC13 can be used as a GPIO or as the RTC_AF1 pin + (#) PI8 can be used as a GPIO or as the RTC_AF2 pin + + [..] When the backup domain is supplied by VBAT (analog switch connected to VBAT + because VDD is not present), the following pins are available: + (#) PC14 and PC15 can be used as LSE pins only + (#) PC13 can be used as the RTC_AF1 pin + (#) PI8 can be used as the RTC_AF2 pin + + ##### Backup Domain Reset ##### + ================================================================== + [..] The backup domain reset sets all RTC registers and the RCM_BDCTRL register + to their reset values. + The BKP SRAM is not affected by this reset. The only way to reset the BKP + SRAM is through the Flash interface by requesting a protection level + change from 1 to 0. + [..] A backup domain reset is generated when one of the following events occurs: + (#) Software reset, triggered by setting the BDRST bit in the + RCC Backup domain control register (RCM_BDCTRL). + (#) VDD or VBAT power on, if both supplies have previously been powered off. + + ##### Backup Domain Access ##### + ================================================================== + [..] After reset, the backup domain (RTC registers, RTC backup data registers + and BKP SRAM) is protected against possible unwanted write accesses. + [..] To enable access to the RTC Domain and RTC registers, proceed as follows: + (+) Enable the Power Controller (PWR) APB1 interface clock using the + __DAL_RCM_PMU_CLK_ENABLE() macro. + (+) Enable access to RTC domain using the DAL_PWR_EnableBkUpAccess() function. + (+) Select the RTC clock source using the __DAL_RCM_RTC_CONFIG() macro. + (+) Enable RTC Clock using the __DAL_RCM_RTC_ENABLE() macro. + + ============================================================================== + ##### How to use this driver ##### + ============================================================================== + [..] + (+) Enable the RTC domain access (see description in the section above). + (+) Configure the RTC Prescaler (Asynchronous and Synchronous) and RTC hour + format using the DAL_RTC_Init() function. + + *** Time and Date configuration *** + =================================== + [..] + (+) To configure the RTC Calendar (Time and Date) use the DAL_RTC_SetTime() + and DAL_RTC_SetDate() functions. + (+) To read the RTC Calendar, use the DAL_RTC_GetTime() and DAL_RTC_GetDate() + functions. + (+) To manage the RTC summer or winter time change, use the following + functions: + (++) DAL_RTC_DST_Add1Hour() or DAL_RTC_DST_Sub1Hour to add or subtract + 1 hour from the calendar time. + (++) DAL_RTC_DST_SetStoreOperation() or DAL_RTC_DST_ClearStoreOperation + to memorize whether the time change has been performed or not. + + *** Alarm configuration *** + =========================== + [..] + (+) To configure the RTC Alarm use the DAL_RTC_SetAlarm() function. + You can also configure the RTC Alarm with interrupt mode using the + DAL_RTC_SetAlarm_IT() function. + (+) To read the RTC Alarm, use the DAL_RTC_GetAlarm() function. + + ##### RTC and low power modes ##### + ================================================================== + [..] The MCU can be woken up from a low power mode by an RTC alternate + function. + [..] The RTC alternate functions are the RTC alarms (Alarm A and Alarm B), + RTC wakeup, RTC tamper event detection and RTC timestamp event detection. + These RTC alternate functions can wake up the system from the Stop and + Standby low power modes. + [..] The system can also wake up from low power modes without depending + on an external interrupt (Auto-wakeup mode), by using the RTC alarm + or the RTC wakeup events. + [..] The RTC provides a programmable time base for waking up from the + Stop or Standby mode at regular intervals. + Wakeup from STOP and STANDBY modes is possible only when the RTC clock + source is LSE or LSI. + + *** Callback registration *** + ============================================= + [..] + The compilation define USE_DAL_RTC_REGISTER_CALLBACKS when set to 1 + allows the user to configure dynamically the driver callbacks. + Use Function DAL_RTC_RegisterCallback() to register an interrupt callback. + [..] + Function DAL_RTC_RegisterCallback() allows to register following callbacks: + (+) AlarmAEventCallback : RTC Alarm A Event callback. + (+) AlarmBEventCallback : RTC Alarm B Event callback. + (+) TimeStampEventCallback : RTC Timestamp Event callback. + (+) WakeUpTimerEventCallback : RTC WakeUpTimer Event callback. + (+) Tamper1EventCallback : RTC Tamper 1 Event callback. + (+) Tamper2EventCallback : RTC Tamper 2 Event callback. + (+) MspInitCallback : RTC MspInit callback. + (+) MspDeInitCallback : RTC MspDeInit callback. + [..] + This function takes as parameters the DAL peripheral handle, the Callback ID + and a pointer to the user callback function. + [..] + Use function DAL_RTC_UnRegisterCallback() to reset a callback to the default + weak function. + DAL_RTC_UnRegisterCallback() takes as parameters the DAL peripheral handle, + and the Callback ID. + This function allows to reset following callbacks: + (+) AlarmAEventCallback : RTC Alarm A Event callback. + (+) AlarmBEventCallback : RTC Alarm B Event callback. + (+) TimeStampEventCallback : RTC Timestamp Event callback. + (+) WakeUpTimerEventCallback : RTC WakeUpTimer Event callback. + (+) Tamper1EventCallback : RTC Tamper 1 Event callback. + (+) Tamper2EventCallback : RTC Tamper 2 Event callback. + (+) MspInitCallback : RTC MspInit callback. + (+) MspDeInitCallback : RTC MspDeInit callback. + [..] + By default, after the DAL_RTC_Init() and when the state is DAL_RTC_STATE_RESET, + all callbacks are set to the corresponding weak functions: + examples AlarmAEventCallback(), WakeUpTimerEventCallback(). + Exception done for MspInit() and MspDeInit() callbacks that are reset to the + legacy weak function in the DAL_RTC_Init()/DAL_RTC_DeInit() only + when these callbacks are null (not registered beforehand). + If not, MspInit() or MspDeInit() are not null, DAL_RTC_Init()/DAL_RTC_DeInit() + keep and use the user MspInit()/MspDeInit() callbacks (registered beforehand). + [..] + Callbacks can be registered/unregistered in DAL_RTC_STATE_READY state only. + Exception done MspInit()/MspDeInit() that can be registered/unregistered + in DAL_RTC_STATE_READY or DAL_RTC_STATE_RESET state. + Thus registered (user) MspInit()/MspDeInit() callbacks can be used during the + Init/DeInit. + In that case first register the MspInit()/MspDeInit() user callbacks + using DAL_RTC_RegisterCallback() before calling DAL_RTC_DeInit() + or DAL_RTC_Init() functions. + [..] + When The compilation define USE_DAL_RTC_REGISTER_CALLBACKS is set to 0 or + not defined, the callback registration feature is not available and all + callbacks are set to the corresponding weak functions. + + @endverbatim + * + */ + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @defgroup RTC RTC + * @brief RTC DAL module driver + * @{ + */ + +#ifdef DAL_RTC_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Exported functions --------------------------------------------------------*/ + +/** @defgroup RTC_Exported_Functions RTC Exported Functions + * @{ + */ + +/** @defgroup RTC_Exported_Functions_Group1 Initialization and de-initialization functions + * @brief Initialization and Configuration functions + * +@verbatim + =============================================================================== + ##### Initialization and de-initialization functions ##### + =============================================================================== + [..] This section provides functions allowing to initialize and configure the + RTC Prescaler (Synchronous and Asynchronous), RTC Hour format, disable + RTC registers Write protection, enter and exit the RTC initialization mode, + RTC registers synchronization check and reference clock detection enable. + (#) The RTC Prescaler is programmed to generate the RTC 1Hz time base. + It is split into 2 programmable prescalers to minimize power consumption. + (++) A 7-bit asynchronous prescaler and a 15-bit synchronous prescaler. + (++) When both prescalers are used, it is recommended to configure the + asynchronous prescaler to a high value to minimize power consumption. + (#) All RTC registers are Write protected. Writing to the RTC registers + is enabled by writing a key into the Write Protection register, RTC_WRPROT. + (#) To configure the RTC Calendar, user application should enter + initialization mode. In this mode, the calendar counter is stopped + and its value can be updated. When the initialization sequence is + complete, the calendar restarts counting after 4 RTCCLK cycles. + (#) To read the calendar through the shadow registers after Calendar + initialization, calendar update or after wakeup from low power modes + the software must first clear the RSF flag. The software must then + wait until it is set again before reading the calendar, which means + that the calendar registers have been correctly copied into the + RTC_TIME and RTC_DATE shadow registers. The DAL_RTC_WaitForSynchro() function + implements the above software sequence (RSF clear and RSF check). + +@endverbatim + * @{ + */ + +/** + * @brief Initializes the RTC peripheral + * @param hrtc pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_RTC_Init(RTC_HandleTypeDef *hrtc) +{ + DAL_StatusTypeDef status = DAL_ERROR; + + /* Check RTC handler validity */ + if (hrtc == NULL) + { + return DAL_ERROR; + } + + /* Check the parameters */ + ASSERT_PARAM(IS_RTC_ALL_INSTANCE(hrtc->Instance)); + ASSERT_PARAM(IS_RTC_HOUR_FORMAT(hrtc->Init.HourFormat)); + ASSERT_PARAM(IS_RTC_ASYNCH_PREDIV(hrtc->Init.AsynchPrediv)); + ASSERT_PARAM(IS_RTC_SYNCH_PREDIV(hrtc->Init.SynchPrediv)); + ASSERT_PARAM(IS_RTC_OUTPUT(hrtc->Init.OutPut)); + ASSERT_PARAM(IS_RTC_OUTPUT_POL(hrtc->Init.OutPutPolarity)); + ASSERT_PARAM(IS_RTC_OUTPUT_TYPE(hrtc->Init.OutPutType)); + +#if (USE_DAL_RTC_REGISTER_CALLBACKS == 1) + if (hrtc->State == DAL_RTC_STATE_RESET) + { + /* Allocate lock resource and initialize it */ + hrtc->Lock = DAL_UNLOCKED; + + hrtc->AlarmAEventCallback = DAL_RTC_AlarmAEventCallback; /* Legacy weak AlarmAEventCallback */ + hrtc->AlarmBEventCallback = DAL_RTCEx_AlarmBEventCallback; /* Legacy weak AlarmBEventCallback */ + hrtc->TimeStampEventCallback = DAL_RTCEx_TimeStampEventCallback; /* Legacy weak TimeStampEventCallback */ + hrtc->WakeUpTimerEventCallback = DAL_RTCEx_WakeUpTimerEventCallback; /* Legacy weak WakeUpTimerEventCallback */ + hrtc->Tamper1EventCallback = DAL_RTCEx_Tamper1EventCallback; /* Legacy weak Tamper1EventCallback */ +#if defined(RTC_TAMPER2_SUPPORT) + hrtc->Tamper2EventCallback = DAL_RTCEx_Tamper2EventCallback; /* Legacy weak Tamper2EventCallback */ +#endif /* RTC_TAMPER2_SUPPORT */ + + if (hrtc->MspInitCallback == NULL) + { + hrtc->MspInitCallback = DAL_RTC_MspInit; + } + /* Init the low level hardware */ + hrtc->MspInitCallback(hrtc); + + if (hrtc->MspDeInitCallback == NULL) + { + hrtc->MspDeInitCallback = DAL_RTC_MspDeInit; + } + } +#else /* USE_DAL_RTC_REGISTER_CALLBACKS */ + if (hrtc->State == DAL_RTC_STATE_RESET) + { + /* Allocate lock resource and initialize it */ + hrtc->Lock = DAL_UNLOCKED; + + /* Initialize RTC MSP */ + DAL_RTC_MspInit(hrtc); + } +#endif /* USE_DAL_RTC_REGISTER_CALLBACKS */ + + /* Set RTC state */ + hrtc->State = DAL_RTC_STATE_BUSY; + + /* Disable the write protection for RTC registers */ + __DAL_RTC_WRITEPROTECTION_DISABLE(hrtc); + + /* Enter Initialization mode */ + status = RTC_EnterInitMode(hrtc); + + if (status == DAL_OK) + { + /* Clear RTC_CTRL TIMEFCFG, OUTSEL and POLCFG Bits */ + hrtc->Instance->CTRL &= ((uint32_t)~(RTC_CTRL_TIMEFCFG | RTC_CTRL_OUTSEL | RTC_CTRL_POLCFG)); + /* Set RTC_CTRL register */ + hrtc->Instance->CTRL |= (uint32_t)(hrtc->Init.HourFormat | hrtc->Init.OutPut | hrtc->Init.OutPutPolarity); + + /* Configure the RTC PSC */ + hrtc->Instance->PSC = (uint32_t)(hrtc->Init.SynchPrediv); + hrtc->Instance->PSC |= (uint32_t)(hrtc->Init.AsynchPrediv << RTC_PSC_APSC_Pos); + + /* Exit Initialization mode */ + status = RTC_ExitInitMode(hrtc); + } + + if (status == DAL_OK) + { + hrtc->Instance->TACFG &= (uint32_t)~RTC_OUTPUT_TYPE_PUSHPULL; + hrtc->Instance->TACFG |= (uint32_t)(hrtc->Init.OutPutType); + + hrtc->State = DAL_RTC_STATE_READY; + } + + /* Enable the write protection for RTC registers */ + __DAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + return status; +} + +/** + * @brief DeInitializes the RTC peripheral + * @param hrtc pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @note This function does not reset the RTC Backup Data registers. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_RTC_DeInit(RTC_HandleTypeDef *hrtc) +{ + DAL_StatusTypeDef status = DAL_ERROR; + + /* Check the parameters */ + ASSERT_PARAM(IS_RTC_ALL_INSTANCE(hrtc->Instance)); + + /* Set RTC state */ + hrtc->State = DAL_RTC_STATE_BUSY; + + /* Disable the write protection for RTC registers */ + __DAL_RTC_WRITEPROTECTION_DISABLE(hrtc); + + /* Enter Initialization mode */ + status = RTC_EnterInitMode(hrtc); + + if (status == DAL_OK) + { + /* Reset RTC registers */ + hrtc->Instance->TIME = 0x00000000U; + hrtc->Instance->DATE = (RTC_DATE_WEEKSEL_0 | RTC_DATE_MONU_0 | RTC_DATE_DAYU_0); + hrtc->Instance->CTRL &= 0x00000000U; + hrtc->Instance->AUTORLD = RTC_AUTORLD_WUAUTORE; + hrtc->Instance->PSC = (uint32_t)(RTC_PSC_APSC | 0x000000FFU); + hrtc->Instance->DCAL = 0x00000000U; + hrtc->Instance->ALRMA = 0x00000000U; + hrtc->Instance->ALRMB = 0x00000000U; + hrtc->Instance->CAL = 0x00000000U; + hrtc->Instance->SHIFT = 0x00000000U; + hrtc->Instance->ALRMASS = 0x00000000U; + hrtc->Instance->ALRMBSS = 0x00000000U; + + /* Exit Initialization mode */ + status = RTC_ExitInitMode(hrtc); + } + + /* Enable the write protection for RTC registers */ + __DAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + if (status == DAL_OK) + { + /* Reset Tamper and alternate functions configuration register */ + hrtc->Instance->TACFG = 0x00000000U; + +#if (USE_DAL_RTC_REGISTER_CALLBACKS == 1) + if (hrtc->MspDeInitCallback == NULL) + { + hrtc->MspDeInitCallback = DAL_RTC_MspDeInit; + } + + /* DeInit the low level hardware: CLOCK, NVIC.*/ + hrtc->MspDeInitCallback(hrtc); +#else /* USE_DAL_RTC_REGISTER_CALLBACKS */ + /* De-Initialize RTC MSP */ + DAL_RTC_MspDeInit(hrtc); +#endif /* USE_DAL_RTC_REGISTER_CALLBACKS */ + + hrtc->State = DAL_RTC_STATE_RESET; + } + + /* Release Lock */ + __DAL_UNLOCK(hrtc); + + return status; +} + +#if (USE_DAL_RTC_REGISTER_CALLBACKS == 1) +/** + * @brief Registers a User RTC Callback + * To be used instead of the weak predefined callback + * @param hrtc pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @param CallbackID ID of the callback to be registered + * This parameter can be one of the following values: + * @arg @ref DAL_RTC_ALARM_A_EVENT_CB_ID Alarm A Event Callback ID + * @arg @ref DAL_RTC_ALARM_B_EVENT_CB_ID Alarm B Event Callback ID + * @arg @ref DAL_RTC_TIMESTAMP_EVENT_CB_ID Timestamp Event Callback ID + * @arg @ref DAL_RTC_WAKEUPTIMER_EVENT_CB_ID Wakeup Timer Event Callback ID + * @arg @ref DAL_RTC_TAMPER1_EVENT_CB_ID Tamper 1 Callback ID + * @arg @ref DAL_RTC_TAMPER2_EVENT_CB_ID Tamper 2 Callback ID + * @arg @ref DAL_RTC_MSPINIT_CB_ID Msp Init callback ID + * @arg @ref DAL_RTC_MSPDEINIT_CB_ID Msp DeInit callback ID + * @note DAL_RTC_TAMPER2_EVENT_CB_ID is not applicable to all devices. + * @param pCallback pointer to the Callback function + * @retval DAL status + */ +DAL_StatusTypeDef DAL_RTC_RegisterCallback(RTC_HandleTypeDef *hrtc, DAL_RTC_CallbackIDTypeDef CallbackID, pRTC_CallbackTypeDef pCallback) +{ + DAL_StatusTypeDef status = DAL_OK; + + if (pCallback == NULL) + { + return DAL_ERROR; + } + + /* Process locked */ + __DAL_LOCK(hrtc); + + if (DAL_RTC_STATE_READY == hrtc->State) + { + switch (CallbackID) + { + case DAL_RTC_ALARM_A_EVENT_CB_ID : + hrtc->AlarmAEventCallback = pCallback; + break; + + case DAL_RTC_ALARM_B_EVENT_CB_ID : + hrtc->AlarmBEventCallback = pCallback; + break; + + case DAL_RTC_TIMESTAMP_EVENT_CB_ID : + hrtc->TimeStampEventCallback = pCallback; + break; + + case DAL_RTC_WAKEUPTIMER_EVENT_CB_ID : + hrtc->WakeUpTimerEventCallback = pCallback; + break; + + case DAL_RTC_TAMPER1_EVENT_CB_ID : + hrtc->Tamper1EventCallback = pCallback; + break; + +#if defined(RTC_TAMPER2_SUPPORT) + case DAL_RTC_TAMPER2_EVENT_CB_ID : + hrtc->Tamper2EventCallback = pCallback; + break; +#endif /* RTC_TAMPER2_SUPPORT */ + + case DAL_RTC_MSPINIT_CB_ID : + hrtc->MspInitCallback = pCallback; + break; + + case DAL_RTC_MSPDEINIT_CB_ID : + hrtc->MspDeInitCallback = pCallback; + break; + + default : + /* Return error status */ + status = DAL_ERROR; + break; + } + } + else if (DAL_RTC_STATE_RESET == hrtc->State) + { + switch (CallbackID) + { + case DAL_RTC_MSPINIT_CB_ID : + hrtc->MspInitCallback = pCallback; + break; + + case DAL_RTC_MSPDEINIT_CB_ID : + hrtc->MspDeInitCallback = pCallback; + break; + + default : + /* Return error status */ + status = DAL_ERROR; + break; + } + } + else + { + /* Return error status */ + status = DAL_ERROR; + } + + /* Release Lock */ + __DAL_UNLOCK(hrtc); + + return status; +} + +/** + * @brief Unregisters an RTC Callback + * RTC callabck is redirected to the weak predefined callback + * @param hrtc pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @param CallbackID ID of the callback to be unregistered + * This parameter can be one of the following values: + * @arg @ref DAL_RTC_ALARM_A_EVENT_CB_ID Alarm A Event Callback ID + * @arg @ref DAL_RTC_ALARM_B_EVENT_CB_ID Alarm B Event Callback ID + * @arg @ref DAL_RTC_TIMESTAMP_EVENT_CB_ID Timestamp Event Callback ID + * @arg @ref DAL_RTC_WAKEUPTIMER_EVENT_CB_ID Wakeup Timer Event Callback ID + * @arg @ref DAL_RTC_TAMPER1_EVENT_CB_ID Tamper 1 Callback ID + * @arg @ref DAL_RTC_TAMPER2_EVENT_CB_ID Tamper 2 Callback ID + * @arg @ref DAL_RTC_MSPINIT_CB_ID Msp Init callback ID + * @arg @ref DAL_RTC_MSPDEINIT_CB_ID Msp DeInit callback ID + * @note DAL_RTC_TAMPER2_EVENT_CB_ID is not applicable to all devices. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_RTC_UnRegisterCallback(RTC_HandleTypeDef *hrtc, DAL_RTC_CallbackIDTypeDef CallbackID) +{ + DAL_StatusTypeDef status = DAL_OK; + + /* Process locked */ + __DAL_LOCK(hrtc); + + if (DAL_RTC_STATE_READY == hrtc->State) + { + switch (CallbackID) + { + case DAL_RTC_ALARM_A_EVENT_CB_ID : + hrtc->AlarmAEventCallback = DAL_RTC_AlarmAEventCallback; /* Legacy weak AlarmAEventCallback */ + break; + + case DAL_RTC_ALARM_B_EVENT_CB_ID : + hrtc->AlarmBEventCallback = DAL_RTCEx_AlarmBEventCallback; /* Legacy weak AlarmBEventCallback */ + break; + + case DAL_RTC_TIMESTAMP_EVENT_CB_ID : + hrtc->TimeStampEventCallback = DAL_RTCEx_TimeStampEventCallback; /* Legacy weak TimeStampEventCallback */ + break; + + case DAL_RTC_WAKEUPTIMER_EVENT_CB_ID : + hrtc->WakeUpTimerEventCallback = DAL_RTCEx_WakeUpTimerEventCallback; /* Legacy weak WakeUpTimerEventCallback */ + break; + + case DAL_RTC_TAMPER1_EVENT_CB_ID : + hrtc->Tamper1EventCallback = DAL_RTCEx_Tamper1EventCallback; /* Legacy weak Tamper1EventCallback */ + break; + +#if defined(RTC_TAMPER2_SUPPORT) + case DAL_RTC_TAMPER2_EVENT_CB_ID : + hrtc->Tamper2EventCallback = DAL_RTCEx_Tamper2EventCallback; /* Legacy weak Tamper2EventCallback */ + break; +#endif /* RTC_TAMPER2_SUPPORT */ + + case DAL_RTC_MSPINIT_CB_ID : + hrtc->MspInitCallback = DAL_RTC_MspInit; + break; + + case DAL_RTC_MSPDEINIT_CB_ID : + hrtc->MspDeInitCallback = DAL_RTC_MspDeInit; + break; + + default : + /* Return error status */ + status = DAL_ERROR; + break; + } + } + else if (DAL_RTC_STATE_RESET == hrtc->State) + { + switch (CallbackID) + { + case DAL_RTC_MSPINIT_CB_ID : + hrtc->MspInitCallback = DAL_RTC_MspInit; + break; + + case DAL_RTC_MSPDEINIT_CB_ID : + hrtc->MspDeInitCallback = DAL_RTC_MspDeInit; + break; + + default : + /* Return error status */ + status = DAL_ERROR; + break; + } + } + else + { + /* Return error status */ + status = DAL_ERROR; + } + + /* Release Lock */ + __DAL_UNLOCK(hrtc); + + return status; +} +#endif /* USE_DAL_RTC_REGISTER_CALLBACKS */ + +/** + * @brief Initializes the RTC MSP. + * @param hrtc pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @retval None + */ +__weak void DAL_RTC_MspInit(RTC_HandleTypeDef *hrtc) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hrtc); + + /* NOTE: This function should not be modified, when the callback is needed, + the DAL_RTC_MspInit could be implemented in the user file + */ +} + +/** + * @brief DeInitializes the RTC MSP. + * @param hrtc pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @retval None + */ +__weak void DAL_RTC_MspDeInit(RTC_HandleTypeDef *hrtc) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hrtc); + + /* NOTE: This function should not be modified, when the callback is needed, + the DAL_RTC_MspDeInit could be implemented in the user file + */ +} + +/** + * @} + */ + +/** @defgroup RTC_Exported_Functions_Group2 RTC Time and Date functions + * @brief RTC Time and Date functions + * +@verbatim + =============================================================================== + ##### RTC Time and Date functions ##### + =============================================================================== + + [..] This section provides functions allowing to configure Time and Date features + +@endverbatim + * @{ + */ + +/** + * @brief Sets RTC current time. + * @param hrtc pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @param sTime Pointer to Time structure + * @note DayLightSaving and StoreOperation interfaces are deprecated. + * To manage Daylight Saving Time, please use DAL_RTC_DST_xxx functions. + * @param Format Specifies the format of the entered parameters. + * This parameter can be one of the following values: + * @arg RTC_FORMAT_BIN: Binary data format + * @arg RTC_FORMAT_BCD: BCD data format + * @retval DAL status + */ +DAL_StatusTypeDef DAL_RTC_SetTime(RTC_HandleTypeDef *hrtc, RTC_TimeTypeDef *sTime, uint32_t Format) +{ + uint32_t tmpreg = 0U; + DAL_StatusTypeDef status; + + /* Check the parameters */ + ASSERT_PARAM(IS_RTC_FORMAT(Format)); + ASSERT_PARAM(IS_RTC_DAYLIGHT_SAVING(sTime->DayLightSaving)); + ASSERT_PARAM(IS_RTC_STORE_OPERATION(sTime->StoreOperation)); + + /* Process Locked */ + __DAL_LOCK(hrtc); + + hrtc->State = DAL_RTC_STATE_BUSY; + + if (Format == RTC_FORMAT_BIN) + { + if ((hrtc->Instance->CTRL & RTC_CTRL_TIMEFCFG) != 0U) + { + ASSERT_PARAM(IS_RTC_HOUR12(sTime->Hours)); + ASSERT_PARAM(IS_RTC_HOURFORMAT12(sTime->TimeFormat)); + } + else + { + sTime->TimeFormat = 0x00U; + ASSERT_PARAM(IS_RTC_HOUR24(sTime->Hours)); + } + ASSERT_PARAM(IS_RTC_MINUTES(sTime->Minutes)); + ASSERT_PARAM(IS_RTC_SECONDS(sTime->Seconds)); + + tmpreg = (uint32_t)(( (uint32_t)RTC_ByteToBcd2(sTime->Hours) << RTC_TIME_HRU_Pos) | \ + ( (uint32_t)RTC_ByteToBcd2(sTime->Minutes) << RTC_TIME_MINU_Pos) | \ + ( (uint32_t)RTC_ByteToBcd2(sTime->Seconds)) | \ + (((uint32_t)sTime->TimeFormat) << RTC_TIME_TIMEFCFG_Pos)); + } + else + { + if ((hrtc->Instance->CTRL & RTC_CTRL_TIMEFCFG) != 0U) + { + ASSERT_PARAM(IS_RTC_HOUR12(RTC_Bcd2ToByte(sTime->Hours))); + ASSERT_PARAM(IS_RTC_HOURFORMAT12(sTime->TimeFormat)); + } + else + { + sTime->TimeFormat = 0x00U; + ASSERT_PARAM(IS_RTC_HOUR24(RTC_Bcd2ToByte(sTime->Hours))); + } + ASSERT_PARAM(IS_RTC_MINUTES(RTC_Bcd2ToByte(sTime->Minutes))); + ASSERT_PARAM(IS_RTC_SECONDS(RTC_Bcd2ToByte(sTime->Seconds))); + tmpreg = (((uint32_t)(sTime->Hours) << RTC_TIME_HRU_Pos) | \ + ((uint32_t)(sTime->Minutes) << RTC_TIME_MINU_Pos) | \ + ((uint32_t) sTime->Seconds) | \ + ((uint32_t)(sTime->TimeFormat) << RTC_TIME_TIMEFCFG_Pos)); + } + + /* Disable the write protection for RTC registers */ + __DAL_RTC_WRITEPROTECTION_DISABLE(hrtc); + + /* Enter Initialization mode */ + status = RTC_EnterInitMode(hrtc); + + if (status == DAL_OK) + { + /* Set the RTC_TIME register */ + hrtc->Instance->TIME = (uint32_t)(tmpreg & RTC_TIME_RESERVED_MASK); + + /* Clear the bits to be configured (Deprecated. Use DAL_RTC_DST_xxx functions instead) */ + hrtc->Instance->CTRL &= (uint32_t)~RTC_CTRL_BAKP; + + /* Configure the RTC_CTRL register (Deprecated. Use DAL_RTC_DST_xxx functions instead) */ + hrtc->Instance->CTRL |= (uint32_t)(sTime->DayLightSaving | sTime->StoreOperation); + + /* Exit Initialization mode */ + status = RTC_ExitInitMode(hrtc); + } + + if (status == DAL_OK) + { + hrtc->State = DAL_RTC_STATE_READY; + } + + /* Enable the write protection for RTC registers */ + __DAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + /* Process Unlocked */ + __DAL_UNLOCK(hrtc); + + return status; +} + +/** + * @brief Gets RTC current time. + * @param hrtc pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @param sTime Pointer to Time structure + * @param Format Specifies the format of the entered parameters. + * This parameter can be one of the following values: + * @arg RTC_FORMAT_BIN: Binary data format + * @arg RTC_FORMAT_BCD: BCD data format + * @note You can use SubSeconds and SecondFraction (sTime structure fields + * returned) to convert SubSeconds value in second fraction ratio with + * time unit following generic formula: + * Second fraction ratio * time_unit = + * [(SecondFraction - SubSeconds) / (SecondFraction + 1)] * time_unit + * This conversion can be performed only if no shift operation is pending + * (ie. SHFP=0) when PREDIV_S >= SS + * @note You must call DAL_RTC_GetDate() after DAL_RTC_GetTime() to unlock the + * values in the higher-order calendar shadow registers to ensure + * consistency between the time and date values. + * Reading RTC current time locks the values in calendar shadow registers + * until current date is read to ensure consistency between the time and + * date values. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_RTC_GetTime(RTC_HandleTypeDef *hrtc, RTC_TimeTypeDef *sTime, uint32_t Format) +{ + uint32_t tmpreg = 0U; + + /* Check the parameters */ + ASSERT_PARAM(IS_RTC_FORMAT(Format)); + + /* Get subseconds value from the corresponding register */ + sTime->SubSeconds = (uint32_t)(hrtc->Instance->SUBSEC); + + /* Get SecondFraction structure field from the corresponding register field*/ + sTime->SecondFraction = (uint32_t)(hrtc->Instance->PSC & RTC_PSC_SPSC); + + /* Get the TIME register */ + tmpreg = (uint32_t)(hrtc->Instance->TIME & RTC_TIME_RESERVED_MASK); + + /* Fill the structure fields with the read parameters */ + sTime->Hours = (uint8_t)((tmpreg & (RTC_TIME_HRT | RTC_TIME_HRU)) >> RTC_TIME_HRU_Pos); + sTime->Minutes = (uint8_t)((tmpreg & (RTC_TIME_MINT | RTC_TIME_MINU)) >> RTC_TIME_MINU_Pos); + sTime->Seconds = (uint8_t)( tmpreg & (RTC_TIME_SECT | RTC_TIME_SECU)); + sTime->TimeFormat = (uint8_t)((tmpreg & (RTC_TIME_TIMEFCFG)) >> RTC_TIME_TIMEFCFG_Pos); + + /* Check the input parameters format */ + if (Format == RTC_FORMAT_BIN) + { + /* Convert the time structure parameters to Binary format */ + sTime->Hours = (uint8_t)RTC_Bcd2ToByte(sTime->Hours); + sTime->Minutes = (uint8_t)RTC_Bcd2ToByte(sTime->Minutes); + sTime->Seconds = (uint8_t)RTC_Bcd2ToByte(sTime->Seconds); + } + + return DAL_OK; +} + +/** + * @brief Sets RTC current date. + * @param hrtc pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @param sDate Pointer to date structure + * @param Format specifies the format of the entered parameters. + * This parameter can be one of the following values: + * @arg RTC_FORMAT_BIN: Binary data format + * @arg RTC_FORMAT_BCD: BCD data format + * @retval DAL status + */ +DAL_StatusTypeDef DAL_RTC_SetDate(RTC_HandleTypeDef *hrtc, RTC_DateTypeDef *sDate, uint32_t Format) +{ + uint32_t datetmpreg = 0U; + DAL_StatusTypeDef status; + + /* Check the parameters */ + ASSERT_PARAM(IS_RTC_FORMAT(Format)); + + /* Process Locked */ + __DAL_LOCK(hrtc); + + hrtc->State = DAL_RTC_STATE_BUSY; + + if ((Format == RTC_FORMAT_BIN) && ((sDate->Month & 0x10U) == 0x10U)) + { + sDate->Month = (uint8_t)((sDate->Month & (uint8_t)~(0x10U)) + (uint8_t)0x0AU); + } + + ASSERT_PARAM(IS_RTC_WEEKDAY(sDate->WeekDay)); + + if (Format == RTC_FORMAT_BIN) + { + ASSERT_PARAM(IS_RTC_YEAR(sDate->Year)); + ASSERT_PARAM(IS_RTC_MONTH(sDate->Month)); + ASSERT_PARAM(IS_RTC_DATE(sDate->Date)); + + datetmpreg = (((uint32_t)RTC_ByteToBcd2(sDate->Year) << RTC_DATE_YRU_Pos) | \ + ((uint32_t)RTC_ByteToBcd2(sDate->Month) << RTC_DATE_MONU_Pos) | \ + ((uint32_t)RTC_ByteToBcd2(sDate->Date)) | \ + ((uint32_t)sDate->WeekDay << RTC_DATE_WEEKSEL_Pos)); + } + else + { + ASSERT_PARAM(IS_RTC_YEAR(RTC_Bcd2ToByte(sDate->Year))); + ASSERT_PARAM(IS_RTC_MONTH(RTC_Bcd2ToByte(sDate->Month))); + ASSERT_PARAM(IS_RTC_DATE(RTC_Bcd2ToByte(sDate->Date))); + + datetmpreg = ((((uint32_t)sDate->Year) << RTC_DATE_YRU_Pos) | \ + (((uint32_t)sDate->Month) << RTC_DATE_MONU_Pos) | \ + ((uint32_t) sDate->Date) | \ + (((uint32_t)sDate->WeekDay) << RTC_DATE_WEEKSEL_Pos)); + } + + /* Disable the write protection for RTC registers */ + __DAL_RTC_WRITEPROTECTION_DISABLE(hrtc); + + /* Enter Initialization mode */ + status = RTC_EnterInitMode(hrtc); + + if (status == DAL_OK) + { + /* Set the RTC_DATE register */ + hrtc->Instance->DATE = (uint32_t)(datetmpreg & RTC_DATE_RESERVED_MASK); + + /* Exit Initialization mode */ + status = RTC_ExitInitMode(hrtc); + } + + if (status == DAL_OK) + { + hrtc->State = DAL_RTC_STATE_READY; + } + + /* Enable the write protection for RTC registers */ + __DAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + /* Process Unlocked */ + __DAL_UNLOCK(hrtc); + + return status; +} + +/** + * @brief Gets RTC current date. + * @param hrtc pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @param sDate Pointer to Date structure + * @param Format Specifies the format of the entered parameters. + * This parameter can be one of the following values: + * @arg RTC_FORMAT_BIN: Binary data format + * @arg RTC_FORMAT_BCD: BCD data format + * @note You must call DAL_RTC_GetDate() after DAL_RTC_GetTime() to unlock the + * values in the higher-order calendar shadow registers to ensure + * consistency between the time and date values. + * Reading RTC current time locks the values in calendar shadow registers + * until current date is read to ensure consistency between the time and + * date values. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_RTC_GetDate(RTC_HandleTypeDef *hrtc, RTC_DateTypeDef *sDate, uint32_t Format) +{ + uint32_t datetmpreg = 0U; + + /* Check the parameters */ + ASSERT_PARAM(IS_RTC_FORMAT(Format)); + + /* Get the DATE register */ + datetmpreg = (uint32_t)(hrtc->Instance->DATE & RTC_DATE_RESERVED_MASK); + + /* Fill the structure fields with the read parameters */ + sDate->Year = (uint8_t)((datetmpreg & (RTC_DATE_YRT | RTC_DATE_YRU)) >> RTC_DATE_YRU_Pos); + sDate->Month = (uint8_t)((datetmpreg & (RTC_DATE_MONT | RTC_DATE_MONU)) >> RTC_DATE_MONU_Pos); + sDate->Date = (uint8_t) (datetmpreg & (RTC_DATE_DAYT | RTC_DATE_DAYU)); + sDate->WeekDay = (uint8_t)((datetmpreg & (RTC_DATE_WEEKSEL)) >> RTC_DATE_WEEKSEL_Pos); + + /* Check the input parameters format */ + if (Format == RTC_FORMAT_BIN) + { + /* Convert the date structure parameters to Binary format */ + sDate->Year = (uint8_t)RTC_Bcd2ToByte(sDate->Year); + sDate->Month = (uint8_t)RTC_Bcd2ToByte(sDate->Month); + sDate->Date = (uint8_t)RTC_Bcd2ToByte(sDate->Date); + } + return DAL_OK; +} + +/** + * @} + */ + +/** @defgroup RTC_Exported_Functions_Group3 RTC Alarm functions + * @brief RTC Alarm functions + * +@verbatim + =============================================================================== + ##### RTC Alarm functions ##### + =============================================================================== + + [..] This section provides functions allowing to configure Alarm feature + +@endverbatim + * @{ + */ +/** + * @brief Sets the specified RTC Alarm. + * @param hrtc pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @param sAlarm Pointer to Alarm structure + * @param Format Specifies the format of the entered parameters. + * This parameter can be one of the following values: + * @arg RTC_FORMAT_BIN: Binary data format + * @arg RTC_FORMAT_BCD: BCD data format + * @note The Alarm register can only be written when the corresponding Alarm + * is disabled (Use the DAL_RTC_DeactivateAlarm()). + * @note The DAL_RTC_SetTime() must be called before enabling the Alarm feature. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_RTC_SetAlarm(RTC_HandleTypeDef *hrtc, RTC_AlarmTypeDef *sAlarm, uint32_t Format) +{ + uint32_t tickstart = 0U; + uint32_t tmpreg = 0U; + uint32_t subsecondtmpreg = 0U; + + /* Check the parameters */ + ASSERT_PARAM(IS_RTC_FORMAT(Format)); + ASSERT_PARAM(IS_RTC_ALARM(sAlarm->Alarm)); + ASSERT_PARAM(IS_RTC_ALARM_MASK(sAlarm->AlarmMask)); + ASSERT_PARAM(IS_RTC_ALARM_DATE_WEEKDAY_SEL(sAlarm->AlarmDateWeekDaySel)); + ASSERT_PARAM(IS_RTC_ALARM_SUB_SECOND_VALUE(sAlarm->AlarmTime.SubSeconds)); + ASSERT_PARAM(IS_RTC_ALARM_SUB_SECOND_MASK(sAlarm->AlarmSubSecondMask)); + + /* Process Locked */ + __DAL_LOCK(hrtc); + + /* Change RTC state to BUSY */ + hrtc->State = DAL_RTC_STATE_BUSY; + + /* Check the data format (binary or BCD) and store the Alarm time and date + configuration accordingly */ + if (Format == RTC_FORMAT_BIN) + { + if ((hrtc->Instance->CTRL & RTC_CTRL_TIMEFCFG) != 0U) + { + ASSERT_PARAM(IS_RTC_HOUR12(sAlarm->AlarmTime.Hours)); + ASSERT_PARAM(IS_RTC_HOURFORMAT12(sAlarm->AlarmTime.TimeFormat)); + } + else + { + sAlarm->AlarmTime.TimeFormat = 0x00U; + ASSERT_PARAM(IS_RTC_HOUR24(sAlarm->AlarmTime.Hours)); + } + ASSERT_PARAM(IS_RTC_MINUTES(sAlarm->AlarmTime.Minutes)); + ASSERT_PARAM(IS_RTC_SECONDS(sAlarm->AlarmTime.Seconds)); + + if (sAlarm->AlarmDateWeekDaySel == RTC_ALARMDATEWEEKDAYSEL_DATE) + { + ASSERT_PARAM(IS_RTC_ALARM_DATE_WEEKDAY_DATE(sAlarm->AlarmDateWeekDay)); + } + else + { + ASSERT_PARAM(IS_RTC_ALARM_DATE_WEEKDAY_WEEKDAY(sAlarm->AlarmDateWeekDay)); + } + + tmpreg = (((uint32_t)RTC_ByteToBcd2(sAlarm->AlarmTime.Hours) << RTC_ALRMA_HRU_Pos) | \ + ((uint32_t)RTC_ByteToBcd2(sAlarm->AlarmTime.Minutes) << RTC_ALRMA_MINU_Pos) | \ + ((uint32_t)RTC_ByteToBcd2(sAlarm->AlarmTime.Seconds)) | \ + ((uint32_t)(sAlarm->AlarmTime.TimeFormat) << RTC_TIME_TIMEFCFG_Pos) | \ + ((uint32_t)RTC_ByteToBcd2(sAlarm->AlarmDateWeekDay) << RTC_ALRMA_DAYU_Pos) | \ + ((uint32_t)sAlarm->AlarmDateWeekDaySel) | \ + ((uint32_t)sAlarm->AlarmMask)); + } + else + { + if ((hrtc->Instance->CTRL & RTC_CTRL_TIMEFCFG) != 0U) + { + ASSERT_PARAM(IS_RTC_HOUR12(RTC_Bcd2ToByte(sAlarm->AlarmTime.Hours))); + ASSERT_PARAM(IS_RTC_HOURFORMAT12(sAlarm->AlarmTime.TimeFormat)); + } + else + { + sAlarm->AlarmTime.TimeFormat = 0x00U; + ASSERT_PARAM(IS_RTC_HOUR24(RTC_Bcd2ToByte(sAlarm->AlarmTime.Hours))); + } + + ASSERT_PARAM(IS_RTC_MINUTES(RTC_Bcd2ToByte(sAlarm->AlarmTime.Minutes))); + ASSERT_PARAM(IS_RTC_SECONDS(RTC_Bcd2ToByte(sAlarm->AlarmTime.Seconds))); + + if (sAlarm->AlarmDateWeekDaySel == RTC_ALARMDATEWEEKDAYSEL_DATE) + { + ASSERT_PARAM(IS_RTC_ALARM_DATE_WEEKDAY_DATE(RTC_Bcd2ToByte(sAlarm->AlarmDateWeekDay))); + } + else + { + ASSERT_PARAM(IS_RTC_ALARM_DATE_WEEKDAY_WEEKDAY(RTC_Bcd2ToByte(sAlarm->AlarmDateWeekDay))); + } + + tmpreg = (((uint32_t)(sAlarm->AlarmTime.Hours) << RTC_ALRMA_HRU_Pos) | \ + ((uint32_t)(sAlarm->AlarmTime.Minutes) << RTC_ALRMA_MINU_Pos) | \ + ((uint32_t) sAlarm->AlarmTime.Seconds) | \ + ((uint32_t)(sAlarm->AlarmTime.TimeFormat) << RTC_TIME_TIMEFCFG_Pos) | \ + ((uint32_t)(sAlarm->AlarmDateWeekDay) << RTC_ALRMA_DAYU_Pos) | \ + ((uint32_t) sAlarm->AlarmDateWeekDaySel) | \ + ((uint32_t) sAlarm->AlarmMask)); + } + + /* Store the Alarm subseconds configuration */ + subsecondtmpreg = (uint32_t)((uint32_t)(sAlarm->AlarmTime.SubSeconds) | \ + (uint32_t)(sAlarm->AlarmSubSecondMask)); + + /* Disable the write protection for RTC registers */ + __DAL_RTC_WRITEPROTECTION_DISABLE(hrtc); + + /* Configure the Alarm register */ + if (sAlarm->Alarm == RTC_ALARM_A) + { + /* Disable the Alarm A */ + __DAL_RTC_ALARMA_DISABLE(hrtc); + + /* In case interrupt mode is used, the interrupt source must be disabled */ + __DAL_RTC_ALARM_DISABLE_IT(hrtc, RTC_IT_ALRA); + + /* Clear the Alarm flag */ + __DAL_RTC_ALARM_CLEAR_FLAG(hrtc, RTC_FLAG_ALRAF); + + /* Get tick */ + tickstart = DAL_GetTick(); + + /* Wait till RTC ALRAWF flag is set and if timeout is reached exit */ + while (__DAL_RTC_ALARM_GET_FLAG(hrtc, RTC_FLAG_ALRAWF) == 0U) + { + if ((DAL_GetTick() - tickstart) > RTC_TIMEOUT_VALUE) + { + /* Enable the write protection for RTC registers */ + __DAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + hrtc->State = DAL_RTC_STATE_TIMEOUT; + + /* Process Unlocked */ + __DAL_UNLOCK(hrtc); + + return DAL_TIMEOUT; + } + } + + hrtc->Instance->ALRMA = (uint32_t)tmpreg; + /* Configure the Alarm A Subseconds register */ + hrtc->Instance->ALRMASS = subsecondtmpreg; + /* Configure the Alarm state: Enable Alarm */ + __DAL_RTC_ALARMA_ENABLE(hrtc); + } + else + { + /* Disable the Alarm B */ + __DAL_RTC_ALARMB_DISABLE(hrtc); + + /* In case interrupt mode is used, the interrupt source must be disabled */ + __DAL_RTC_ALARM_DISABLE_IT(hrtc, RTC_IT_ALRB); + + /* Clear the Alarm flag */ + __DAL_RTC_ALARM_CLEAR_FLAG(hrtc, RTC_FLAG_ALRBF); + + /* Get tick */ + tickstart = DAL_GetTick(); + + /* Wait till RTC ALRBWF flag is set and if timeout is reached exit */ + while (__DAL_RTC_ALARM_GET_FLAG(hrtc, RTC_FLAG_ALRBWF) == 0U) + { + if ((DAL_GetTick() - tickstart) > RTC_TIMEOUT_VALUE) + { + /* Enable the write protection for RTC registers */ + __DAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + hrtc->State = DAL_RTC_STATE_TIMEOUT; + + /* Process Unlocked */ + __DAL_UNLOCK(hrtc); + + return DAL_TIMEOUT; + } + } + + hrtc->Instance->ALRMB = (uint32_t)tmpreg; + /* Configure the Alarm B Subseconds register */ + hrtc->Instance->ALRMBSS = subsecondtmpreg; + /* Configure the Alarm state: Enable Alarm */ + __DAL_RTC_ALARMB_ENABLE(hrtc); + } + + /* Enable the write protection for RTC registers */ + __DAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + /* Change RTC state back to READY */ + hrtc->State = DAL_RTC_STATE_READY; + + /* Process Unlocked */ + __DAL_UNLOCK(hrtc); + + return DAL_OK; +} + +/** + * @brief Sets the specified RTC Alarm with Interrupt. + * @param hrtc pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @param sAlarm Pointer to Alarm structure + * @param Format Specifies the format of the entered parameters. + * This parameter can be one of the following values: + * @arg RTC_FORMAT_BIN: Binary data format + * @arg RTC_FORMAT_BCD: BCD data format + * @note The Alarm register can only be written when the corresponding Alarm + * is disabled (Use the DAL_RTC_DeactivateAlarm()). + * @note The DAL_RTC_SetTime() must be called before enabling the Alarm feature. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_RTC_SetAlarm_IT(RTC_HandleTypeDef *hrtc, RTC_AlarmTypeDef *sAlarm, uint32_t Format) +{ + __IO uint32_t count = RTC_TIMEOUT_VALUE * (SystemCoreClock / 32U / 1000U); + uint32_t tmpreg = 0U; + uint32_t subsecondtmpreg = 0U; + + /* Check the parameters */ + ASSERT_PARAM(IS_RTC_FORMAT(Format)); + ASSERT_PARAM(IS_RTC_ALARM(sAlarm->Alarm)); + ASSERT_PARAM(IS_RTC_ALARM_MASK(sAlarm->AlarmMask)); + ASSERT_PARAM(IS_RTC_ALARM_DATE_WEEKDAY_SEL(sAlarm->AlarmDateWeekDaySel)); + ASSERT_PARAM(IS_RTC_ALARM_SUB_SECOND_VALUE(sAlarm->AlarmTime.SubSeconds)); + ASSERT_PARAM(IS_RTC_ALARM_SUB_SECOND_MASK(sAlarm->AlarmSubSecondMask)); + + /* Process Locked */ + __DAL_LOCK(hrtc); + + /* Change RTC state to BUSY */ + hrtc->State = DAL_RTC_STATE_BUSY; + + /* Check the data format (binary or BCD) and store the Alarm time and date + configuration accordingly */ + if (Format == RTC_FORMAT_BIN) + { + if ((hrtc->Instance->CTRL & RTC_CTRL_TIMEFCFG) != 0U) + { + ASSERT_PARAM(IS_RTC_HOUR12(sAlarm->AlarmTime.Hours)); + ASSERT_PARAM(IS_RTC_HOURFORMAT12(sAlarm->AlarmTime.TimeFormat)); + } + else + { + sAlarm->AlarmTime.TimeFormat = 0x00U; + ASSERT_PARAM(IS_RTC_HOUR24(sAlarm->AlarmTime.Hours)); + } + ASSERT_PARAM(IS_RTC_MINUTES(sAlarm->AlarmTime.Minutes)); + ASSERT_PARAM(IS_RTC_SECONDS(sAlarm->AlarmTime.Seconds)); + + if (sAlarm->AlarmDateWeekDaySel == RTC_ALARMDATEWEEKDAYSEL_DATE) + { + ASSERT_PARAM(IS_RTC_ALARM_DATE_WEEKDAY_DATE(sAlarm->AlarmDateWeekDay)); + } + else + { + ASSERT_PARAM(IS_RTC_ALARM_DATE_WEEKDAY_WEEKDAY(sAlarm->AlarmDateWeekDay)); + } + + tmpreg = (((uint32_t)RTC_ByteToBcd2(sAlarm->AlarmTime.Hours) << RTC_ALRMA_HRU_Pos) | \ + ((uint32_t)RTC_ByteToBcd2(sAlarm->AlarmTime.Minutes) << RTC_ALRMA_MINU_Pos) | \ + ((uint32_t)RTC_ByteToBcd2(sAlarm->AlarmTime.Seconds)) | \ + ((uint32_t)(sAlarm->AlarmTime.TimeFormat) << RTC_TIME_TIMEFCFG_Pos) | \ + ((uint32_t)RTC_ByteToBcd2(sAlarm->AlarmDateWeekDay) << RTC_ALRMA_DAYU_Pos) | \ + ((uint32_t)sAlarm->AlarmDateWeekDaySel) | \ + ((uint32_t)sAlarm->AlarmMask)); + } + else + { + if ((hrtc->Instance->CTRL & RTC_CTRL_TIMEFCFG) != 0U) + { + ASSERT_PARAM(IS_RTC_HOUR12(RTC_Bcd2ToByte(sAlarm->AlarmTime.Hours))); + ASSERT_PARAM(IS_RTC_HOURFORMAT12(sAlarm->AlarmTime.TimeFormat)); + } + else + { + sAlarm->AlarmTime.TimeFormat = 0x00U; + ASSERT_PARAM(IS_RTC_HOUR24(RTC_Bcd2ToByte(sAlarm->AlarmTime.Hours))); + } + + ASSERT_PARAM(IS_RTC_MINUTES(RTC_Bcd2ToByte(sAlarm->AlarmTime.Minutes))); + ASSERT_PARAM(IS_RTC_SECONDS(RTC_Bcd2ToByte(sAlarm->AlarmTime.Seconds))); + + if (sAlarm->AlarmDateWeekDaySel == RTC_ALARMDATEWEEKDAYSEL_DATE) + { + ASSERT_PARAM(IS_RTC_ALARM_DATE_WEEKDAY_DATE(RTC_Bcd2ToByte(sAlarm->AlarmDateWeekDay))); + } + else + { + ASSERT_PARAM(IS_RTC_ALARM_DATE_WEEKDAY_WEEKDAY(RTC_Bcd2ToByte(sAlarm->AlarmDateWeekDay))); + } + + tmpreg = (((uint32_t)(sAlarm->AlarmTime.Hours) << RTC_ALRMA_HRU_Pos) | \ + ((uint32_t)(sAlarm->AlarmTime.Minutes) << RTC_ALRMA_MINU_Pos) | \ + ((uint32_t) sAlarm->AlarmTime.Seconds) | \ + ((uint32_t)(sAlarm->AlarmTime.TimeFormat) << RTC_TIME_TIMEFCFG_Pos) | \ + ((uint32_t)(sAlarm->AlarmDateWeekDay) << RTC_ALRMA_DAYU_Pos) | \ + ((uint32_t) sAlarm->AlarmDateWeekDaySel) | \ + ((uint32_t) sAlarm->AlarmMask)); + } + + /* Store the Alarm subseconds configuration */ + subsecondtmpreg = (uint32_t)((uint32_t)(sAlarm->AlarmTime.SubSeconds) | \ + (uint32_t)(sAlarm->AlarmSubSecondMask)); + + /* Disable the write protection for RTC registers */ + __DAL_RTC_WRITEPROTECTION_DISABLE(hrtc); + + /* Configure the Alarm register */ + if (sAlarm->Alarm == RTC_ALARM_A) + { + /* Disable the Alarm A */ + __DAL_RTC_ALARMA_DISABLE(hrtc); + + /* Clear the Alarm flag */ + __DAL_RTC_ALARM_CLEAR_FLAG(hrtc, RTC_FLAG_ALRAF); + + /* Wait till RTC ALRAWF flag is set and if timeout is reached exit */ + do + { + if (count-- == 0U) + { + /* Enable the write protection for RTC registers */ + __DAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + hrtc->State = DAL_RTC_STATE_TIMEOUT; + + /* Process Unlocked */ + __DAL_UNLOCK(hrtc); + + return DAL_TIMEOUT; + } + } while (__DAL_RTC_ALARM_GET_FLAG(hrtc, RTC_FLAG_ALRAWF) == 0U); + + hrtc->Instance->ALRMA = (uint32_t)tmpreg; + /* Configure the Alarm A Subseconds register */ + hrtc->Instance->ALRMASS = subsecondtmpreg; + /* Configure the Alarm state: Enable Alarm */ + __DAL_RTC_ALARMA_ENABLE(hrtc); + /* Configure the Alarm interrupt */ + __DAL_RTC_ALARM_ENABLE_IT(hrtc, RTC_IT_ALRA); + } + else + { + /* Disable the Alarm B */ + __DAL_RTC_ALARMB_DISABLE(hrtc); + + /* Clear the Alarm flag */ + __DAL_RTC_ALARM_CLEAR_FLAG(hrtc, RTC_FLAG_ALRBF); + + /* Reload the counter */ + count = RTC_TIMEOUT_VALUE * (SystemCoreClock / 32U / 1000U); + + /* Wait till RTC ALRBWF flag is set and if timeout is reached exit */ + do + { + if (count-- == 0U) + { + /* Enable the write protection for RTC registers */ + __DAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + hrtc->State = DAL_RTC_STATE_TIMEOUT; + + /* Process Unlocked */ + __DAL_UNLOCK(hrtc); + + return DAL_TIMEOUT; + } + } while (__DAL_RTC_ALARM_GET_FLAG(hrtc, RTC_FLAG_ALRBWF) == 0U); + + hrtc->Instance->ALRMB = (uint32_t)tmpreg; + /* Configure the Alarm B Subseconds register */ + hrtc->Instance->ALRMBSS = subsecondtmpreg; + /* Configure the Alarm state: Enable Alarm */ + __DAL_RTC_ALARMB_ENABLE(hrtc); + /* Configure the Alarm interrupt */ + __DAL_RTC_ALARM_ENABLE_IT(hrtc, RTC_IT_ALRB); + } + + /* RTC Alarm Interrupt Configuration: EINT configuration */ + __DAL_RTC_ALARM_EINT_ENABLE_IT(); + __DAL_RTC_ALARM_EINT_ENABLE_RISING_EDGE(); + + /* Enable the write protection for RTC registers */ + __DAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + /* Change RTC state back to READY */ + hrtc->State = DAL_RTC_STATE_READY; + + /* Process Unlocked */ + __DAL_UNLOCK(hrtc); + + return DAL_OK; +} + +/** + * @brief Deactivates the specified RTC Alarm. + * @param hrtc pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @param Alarm Specifies the Alarm. + * This parameter can be one of the following values: + * @arg RTC_ALARM_A: Alarm A + * @arg RTC_ALARM_B: Alarm B + * @retval DAL status + */ +DAL_StatusTypeDef DAL_RTC_DeactivateAlarm(RTC_HandleTypeDef *hrtc, uint32_t Alarm) +{ + uint32_t tickstart = 0U; + + /* Check the parameters */ + ASSERT_PARAM(IS_RTC_ALARM(Alarm)); + + /* Process Locked */ + __DAL_LOCK(hrtc); + + hrtc->State = DAL_RTC_STATE_BUSY; + + /* Disable the write protection for RTC registers */ + __DAL_RTC_WRITEPROTECTION_DISABLE(hrtc); + + if (Alarm == RTC_ALARM_A) + { + /* Disable Alarm A */ + __DAL_RTC_ALARMA_DISABLE(hrtc); + + /* In case interrupt mode is used, the interrupt source must be disabled */ + __DAL_RTC_ALARM_DISABLE_IT(hrtc, RTC_IT_ALRA); + + /* Get tick */ + tickstart = DAL_GetTick(); + + /* Wait till RTC ALRxWF flag is set and if timeout is reached exit */ + while (__DAL_RTC_ALARM_GET_FLAG(hrtc, RTC_FLAG_ALRAWF) == 0U) + { + if ((DAL_GetTick() - tickstart) > RTC_TIMEOUT_VALUE) + { + /* Enable the write protection for RTC registers */ + __DAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + hrtc->State = DAL_RTC_STATE_TIMEOUT; + + /* Process Unlocked */ + __DAL_UNLOCK(hrtc); + + return DAL_TIMEOUT; + } + } + } + else + { + /* Disable Alarm B */ + __DAL_RTC_ALARMB_DISABLE(hrtc); + + /* In case interrupt mode is used, the interrupt source must be disabled */ + __DAL_RTC_ALARM_DISABLE_IT(hrtc, RTC_IT_ALRB); + + /* Get tick */ + tickstart = DAL_GetTick(); + + /* Wait till RTC ALRxWF flag is set and if timeout is reached exit */ + while (__DAL_RTC_ALARM_GET_FLAG(hrtc, RTC_FLAG_ALRBWF) == 0U) + { + if ((DAL_GetTick() - tickstart) > RTC_TIMEOUT_VALUE) + { + /* Enable the write protection for RTC registers */ + __DAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + hrtc->State = DAL_RTC_STATE_TIMEOUT; + + /* Process Unlocked */ + __DAL_UNLOCK(hrtc); + + return DAL_TIMEOUT; + } + } + } + + /* Enable the write protection for RTC registers */ + __DAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + hrtc->State = DAL_RTC_STATE_READY; + + /* Process Unlocked */ + __DAL_UNLOCK(hrtc); + + return DAL_OK; +} + +/** + * @brief Gets the RTC Alarm value and masks. + * @param hrtc pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @param sAlarm Pointer to Date structure + * @param Alarm Specifies the Alarm. + * This parameter can be one of the following values: + * @arg RTC_ALARM_A: Alarm A + * @arg RTC_ALARM_B: Alarm B + * @param Format Specifies the format of the entered parameters. + * This parameter can be one of the following values: + * @arg RTC_FORMAT_BIN: Binary data format + * @arg RTC_FORMAT_BCD: BCD data format + * @retval DAL status + */ +DAL_StatusTypeDef DAL_RTC_GetAlarm(RTC_HandleTypeDef *hrtc, RTC_AlarmTypeDef *sAlarm, uint32_t Alarm, uint32_t Format) +{ + uint32_t tmpreg = 0U; + uint32_t subsecondtmpreg = 0U; + + /* Check the parameters */ + ASSERT_PARAM(IS_RTC_FORMAT(Format)); + ASSERT_PARAM(IS_RTC_ALARM(Alarm)); + + if (Alarm == RTC_ALARM_A) + { + sAlarm->Alarm = RTC_ALARM_A; + + tmpreg = (uint32_t)(hrtc->Instance->ALRMA); + subsecondtmpreg = (uint32_t)((hrtc->Instance->ALRMASS) & RTC_ALRMASS_SUBSEC); + } + else + { + sAlarm->Alarm = RTC_ALARM_B; + + tmpreg = (uint32_t)(hrtc->Instance->ALRMB); + subsecondtmpreg = (uint32_t)((hrtc->Instance->ALRMBSS) & RTC_ALRMBSS_SUBSEC); + } + + /* Fill the structure with the read parameters */ + sAlarm->AlarmTime.Hours = (uint8_t) ((tmpreg & (RTC_ALRMA_HRT | RTC_ALRMA_HRU)) >> RTC_ALRMA_HRU_Pos); + sAlarm->AlarmTime.Minutes = (uint8_t) ((tmpreg & (RTC_ALRMA_MINT | RTC_ALRMA_MINU)) >> RTC_ALRMA_MINU_Pos); + sAlarm->AlarmTime.Seconds = (uint8_t) ( tmpreg & (RTC_ALRMA_SECT | RTC_ALRMA_SECU)); + sAlarm->AlarmTime.TimeFormat = (uint8_t) ((tmpreg & RTC_ALRMA_TIMEFCFG) >> RTC_TIME_TIMEFCFG_Pos); + sAlarm->AlarmTime.SubSeconds = (uint32_t) subsecondtmpreg; + sAlarm->AlarmDateWeekDay = (uint8_t) ((tmpreg & (RTC_ALRMA_DAYT | RTC_ALRMA_DAYU)) >> RTC_ALRMA_DAYU_Pos); + sAlarm->AlarmDateWeekDaySel = (uint32_t) (tmpreg & RTC_ALRMA_WEEKSEL); + sAlarm->AlarmMask = (uint32_t) (tmpreg & RTC_ALARMMASK_ALL); + + if (Format == RTC_FORMAT_BIN) + { + sAlarm->AlarmTime.Hours = RTC_Bcd2ToByte(sAlarm->AlarmTime.Hours); + sAlarm->AlarmTime.Minutes = RTC_Bcd2ToByte(sAlarm->AlarmTime.Minutes); + sAlarm->AlarmTime.Seconds = RTC_Bcd2ToByte(sAlarm->AlarmTime.Seconds); + sAlarm->AlarmDateWeekDay = RTC_Bcd2ToByte(sAlarm->AlarmDateWeekDay); + } + + return DAL_OK; +} + +/** + * @brief Handles Alarm interrupt request. + * @param hrtc pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @retval None + */ +void DAL_RTC_AlarmIRQHandler(RTC_HandleTypeDef *hrtc) +{ + /* Get the Alarm A interrupt source enable status */ + if (__DAL_RTC_ALARM_GET_IT_SOURCE(hrtc, RTC_IT_ALRA) != 0U) + { + /* Get the pending status of the Alarm A Interrupt */ + if (__DAL_RTC_ALARM_GET_FLAG(hrtc, RTC_FLAG_ALRAF) != 0U) + { + /* Alarm A callback */ +#if (USE_DAL_RTC_REGISTER_CALLBACKS == 1) + hrtc->AlarmAEventCallback(hrtc); +#else + DAL_RTC_AlarmAEventCallback(hrtc); +#endif /* USE_DAL_RTC_REGISTER_CALLBACKS */ + + /* Clear the Alarm A interrupt pending bit */ + __DAL_RTC_ALARM_CLEAR_FLAG(hrtc, RTC_FLAG_ALRAF); + } + } + + /* Get the Alarm B interrupt source enable status */ + if (__DAL_RTC_ALARM_GET_IT_SOURCE(hrtc, RTC_IT_ALRB) != 0U) + { + /* Get the pending status of the Alarm B Interrupt */ + if (__DAL_RTC_ALARM_GET_FLAG(hrtc, RTC_FLAG_ALRBF) != 0U) + { + /* Alarm B callback */ +#if (USE_DAL_RTC_REGISTER_CALLBACKS == 1) + hrtc->AlarmBEventCallback(hrtc); +#else + DAL_RTCEx_AlarmBEventCallback(hrtc); +#endif /* USE_DAL_RTC_REGISTER_CALLBACKS */ + + /* Clear the Alarm B interrupt pending bit */ + __DAL_RTC_ALARM_CLEAR_FLAG(hrtc, RTC_FLAG_ALRBF); + } + } + + /* Clear the EINT's line Flag for RTC Alarm */ + __DAL_RTC_ALARM_EINT_CLEAR_FLAG(); + + /* Change RTC state */ + hrtc->State = DAL_RTC_STATE_READY; +} + +/** + * @brief Alarm A callback. + * @param hrtc pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @retval None + */ +__weak void DAL_RTC_AlarmAEventCallback(RTC_HandleTypeDef *hrtc) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hrtc); + + /* NOTE: This function should not be modified, when the callback is needed, + the DAL_RTC_AlarmAEventCallback could be implemented in the user file + */ +} + +/** + * @brief Handles Alarm A Polling request. + * @param hrtc pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @param Timeout Timeout duration + * @retval DAL status + */ +DAL_StatusTypeDef DAL_RTC_PollForAlarmAEvent(RTC_HandleTypeDef *hrtc, uint32_t Timeout) +{ + uint32_t tickstart = 0U; + + /* Get tick */ + tickstart = DAL_GetTick(); + + /* Wait till RTC ALRAF flag is set and if timeout is reached exit */ + while (__DAL_RTC_ALARM_GET_FLAG(hrtc, RTC_FLAG_ALRAF) == 0U) + { + if (Timeout != DAL_MAX_DELAY) + { + if ((Timeout == 0U) || ((DAL_GetTick() - tickstart) > Timeout)) + { + hrtc->State = DAL_RTC_STATE_TIMEOUT; + return DAL_TIMEOUT; + } + } + } + + /* Clear the Alarm flag */ + __DAL_RTC_ALARM_CLEAR_FLAG(hrtc, RTC_FLAG_ALRAF); + + /* Change RTC state */ + hrtc->State = DAL_RTC_STATE_READY; + + return DAL_OK; +} + +/** + * @} + */ + +/** @defgroup RTC_Exported_Functions_Group4 Peripheral Control functions + * @brief Peripheral Control functions + * +@verbatim + =============================================================================== + ##### Peripheral Control functions ##### + =============================================================================== + [..] + This subsection provides functions allowing to + (+) Wait for RTC Time and Date Synchronization + (+) Manage RTC Summer or Winter time change + +@endverbatim + * @{ + */ + +/** + * @brief Waits until the RTC Time and Date registers (RTC_TIME and RTC_DATE) are + * synchronized with RTC APB clock. + * @note The RTC Resynchronization mode is write protected, use the + * __DAL_RTC_WRITEPROTECTION_DISABLE() before calling this function. + * @note To read the calendar through the shadow registers after Calendar + * initialization, calendar update or after wakeup from low power modes + * the software must first clear the RSF flag. + * The software must then wait until it is set again before reading + * the calendar, which means that the calendar registers have been + * correctly copied into the RTC_TIME and RTC_DATE shadow registers. + * @param hrtc pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_RTC_WaitForSynchro(RTC_HandleTypeDef *hrtc) +{ + uint32_t tickstart = 0U; + + /* Clear RSF flag */ + hrtc->Instance->STS &= (uint32_t)RTC_RSF_MASK; + + /* Get tick */ + tickstart = DAL_GetTick(); + + /* Wait the registers to be synchronised */ + while ((hrtc->Instance->STS & RTC_STS_RSFLG) == 0U) + { + if ((DAL_GetTick() - tickstart) > RTC_TIMEOUT_VALUE) + { + return DAL_TIMEOUT; + } + } + + return DAL_OK; +} + +/** + * @brief Daylight Saving Time, adds one hour to the calendar in one + * single operation without going through the initialization procedure. + * @param hrtc pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @retval None + */ +void DAL_RTC_DST_Add1Hour(RTC_HandleTypeDef *hrtc) +{ + __DAL_RTC_WRITEPROTECTION_DISABLE(hrtc); + SET_BIT(hrtc->Instance->CTRL, RTC_CTRL_STCCFG); + __DAL_RTC_WRITEPROTECTION_ENABLE(hrtc); +} + +/** + * @brief Daylight Saving Time, subtracts one hour from the calendar in one + * single operation without going through the initialization procedure. + * @param hrtc pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @retval None + */ +void DAL_RTC_DST_Sub1Hour(RTC_HandleTypeDef *hrtc) +{ + __DAL_RTC_WRITEPROTECTION_DISABLE(hrtc); + SET_BIT(hrtc->Instance->CTRL, RTC_CTRL_WTCCFG); + __DAL_RTC_WRITEPROTECTION_ENABLE(hrtc); +} + +/** + * @brief Daylight Saving Time, sets the store operation bit. + * @note It can be used by the software in order to memorize the DST status. + * @param hrtc pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @retval None + */ +void DAL_RTC_DST_SetStoreOperation(RTC_HandleTypeDef *hrtc) +{ + __DAL_RTC_WRITEPROTECTION_DISABLE(hrtc); + SET_BIT(hrtc->Instance->CTRL, RTC_CTRL_BAKP); + __DAL_RTC_WRITEPROTECTION_ENABLE(hrtc); +} + +/** + * @brief Daylight Saving Time, clears the store operation bit. + * @param hrtc pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @retval None + */ +void DAL_RTC_DST_ClearStoreOperation(RTC_HandleTypeDef *hrtc) +{ + __DAL_RTC_WRITEPROTECTION_DISABLE(hrtc); + CLEAR_BIT(hrtc->Instance->CTRL, RTC_CTRL_BAKP); + __DAL_RTC_WRITEPROTECTION_ENABLE(hrtc); +} + +/** + * @brief Daylight Saving Time, reads the store operation bit. + * @param hrtc RTC handle + * @retval operation see RTC_StoreOperation_Definitions + */ +uint32_t DAL_RTC_DST_ReadStoreOperation(RTC_HandleTypeDef *hrtc) +{ + return READ_BIT(hrtc->Instance->CTRL, RTC_CTRL_BAKP); +} + +/** + * @} + */ + +/** @defgroup RTC_Exported_Functions_Group5 Peripheral State functions + * @brief Peripheral State functions + * +@verbatim + =============================================================================== + ##### Peripheral State functions ##### + =============================================================================== + [..] + This subsection provides functions allowing to + (+) Get RTC state + +@endverbatim + * @{ + */ +/** + * @brief Returns the RTC state. + * @param hrtc pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @retval DAL state + */ +DAL_RTCStateTypeDef DAL_RTC_GetState(RTC_HandleTypeDef *hrtc) +{ + return hrtc->State; +} + +/** + * @} + */ + + +/** + * @} + */ + +/** @addtogroup RTC_Private_Functions + * @{ + */ + +/** + * @brief Enters the RTC Initialization mode. + * @note The RTC Initialization mode is write protected, use the + * __DAL_RTC_WRITEPROTECTION_DISABLE() before calling this function. + * @param hrtc pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @retval DAL status + */ +DAL_StatusTypeDef RTC_EnterInitMode(RTC_HandleTypeDef *hrtc) +{ + uint32_t tickstart = 0U; + DAL_StatusTypeDef status = DAL_OK; + + /* Check that Initialization mode is not already set */ + if (READ_BIT(hrtc->Instance->STS, RTC_STS_RINITFLG) == 0U) + { + /* Set INIT bit to enter Initialization mode */ + SET_BIT(hrtc->Instance->STS, RTC_STS_INITEN); + + /* Get tick */ + tickstart = DAL_GetTick(); + + /* Wait till RTC is in INIT state and if timeout is reached exit */ + while ((READ_BIT(hrtc->Instance->STS, RTC_STS_RINITFLG) == 0U) && (status != DAL_ERROR)) + { + if ((DAL_GetTick() - tickstart) > RTC_TIMEOUT_VALUE) + { + /* Set RTC state */ + hrtc->State = DAL_RTC_STATE_ERROR; + status = DAL_ERROR; + } + } + } + + return status; +} + +/** + * @brief Exits the RTC Initialization mode. + * @param hrtc pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @retval DAL status + */ +DAL_StatusTypeDef RTC_ExitInitMode(RTC_HandleTypeDef *hrtc) +{ + DAL_StatusTypeDef status = DAL_OK; + + /* Clear INIT bit to exit Initialization mode */ + CLEAR_BIT(hrtc->Instance->STS, RTC_STS_INITEN); + + /* If CR_BYPSHAD bit = 0, wait for synchro */ + if (READ_BIT(hrtc->Instance->CTRL, RTC_CTRL_RCMCFG) == 0U) + { + if (DAL_RTC_WaitForSynchro(hrtc) != DAL_OK) + { + /* Set RTC state */ + hrtc->State = DAL_RTC_STATE_ERROR; + status = DAL_ERROR; + } + } + + return status; +} + +/** + * @brief Converts a 2-digit number from decimal to BCD format. + * @param number decimal-formatted number (from 0 to 99) to be converted + * @retval Converted byte + */ +uint8_t RTC_ByteToBcd2(uint8_t number) +{ + uint8_t bcdhigh = 0U; + + while (number >= 10U) + { + bcdhigh++; + number -= 10U; + } + + return ((uint8_t)(bcdhigh << 4U) | number); +} + +/** + * @brief Converts a 2-digit number from BCD to decimal format. + * @param number BCD-formatted number (from 00 to 99) to be converted + * @retval Converted word + */ +uint8_t RTC_Bcd2ToByte(uint8_t number) +{ + uint8_t tmp = 0U; + tmp = ((uint8_t)(number & (uint8_t)0xF0) >> (uint8_t)0x4) * 10; + return (tmp + (number & (uint8_t)0x0F)); +} + +/** + * @} + */ + +#endif /* DAL_RTC_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_rtc_ex.c b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_rtc_ex.c new file mode 100644 index 0000000000..76d451e561 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_rtc_ex.c @@ -0,0 +1,1891 @@ +/** + * + * @file apm32f4xx_dal_rtc_ex.c + * @brief Extended RTC DAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the Real-Time Clock (RTC) Extended peripheral: + * + RTC Timestamp functions + * + RTC Tamper functions + * + RTC Wakeup functions + * + Extended Control functions + * + Extended RTC features functions + * + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2017 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + * + @verbatim + ============================================================================== + ##### How to use this driver ##### + ============================================================================== + [..] + (+) Enable the RTC domain access. + (+) Configure the RTC Prescaler (Asynchronous and Synchronous) and RTC hour + format using the DAL_RTC_Init() function. + + *** RTC Wakeup configuration *** + ================================ + [..] + (+) To configure the RTC Wakeup Clock source and Counter use the + DAL_RTCEx_SetWakeUpTimer() function. + You can also configure the RTC Wakeup timer in interrupt mode using the + DAL_RTCEx_SetWakeUpTimer_IT() function. + (+) To read the RTC Wakeup Counter register, use the DAL_RTCEx_GetWakeUpTimer() + function. + + *** Timestamp configuration *** + =============================== + [..] + (+) To configure the RTC Timestamp use the DAL_RTCEx_SetTimeStamp() function. + You can also configure the RTC Timestamp with interrupt mode using the + DAL_RTCEx_SetTimeStamp_IT() function. + (+) To read the RTC Timestamp Time and Date register, use the + DAL_RTCEx_GetTimeStamp() function. + (+) The Timestamp alternate function can be mapped either to RTC_AF1 (PC13) + or RTC_AF2 (PI8) depending on the value of TSINSEL bit in RTC_TACFG + register. + + *** Tamper configuration *** + ============================ + [..] + (+) To Enable the RTC Tamper and configure the Tamper filter count, trigger + Edge or Level according to the Tamper filter value (if equal to 0 Edge + else Level), sampling frequency, precharge or discharge and Pull-UP use + the DAL_RTCEx_SetTamper() function. + You can configure RTC Tamper in interrupt mode using DAL_RTCEx_SetTamper_IT() + function. + (+) The TAMPER1 alternate function can be mapped either to RTC_AF1 (PC13) + or RTC_AF2 (PI8) depending on the value of TAMP1INSEL bit in RTC_TACFG + register. + The corresponding pin is also selected by DAL_RTCEx_SetTamper() + or DAL_RTCEx_SetTamper_IT() functions. + (+) The TAMPER2 alternate function is mapped to RTC_AF2 (PI8). + + *** Backup Data Registers configuration *** + =========================================== + [..] + (+) To write to the RTC Backup Data registers, use the DAL_RTCEx_BKUPWrite() + function. + (+) To read the RTC Backup Data registers, use the DAL_RTCEx_BKUPRead() + function. + + *** Coarse Digital Calibration configuration *** + ================================================ + [..] + (+) The Coarse Digital Calibration can be used to compensate crystal inaccuracy + by setting the DCS bit in RTC_DCAL register. + (+) When positive calibration is enabled (DCS = ��0��), 2 asynchronous prescaler + clock cycles are added every minute during 2xDC minutes. + This causes the calendar to be updated sooner, thereby adjusting the + effective RTC frequency to be a bit higher. + (+) When negative calibration is enabled (DCS = ��1��), 1 asynchronous prescaler + clock cycle is removed every minute during 2xDC minutes. + This causes the calendar to be updated later, thereby adjusting the + effective RTC frequency to be a bit lower. + (+) DC is configured through bits DC[4:0] of RTC_DCAL register. This number + ranges from 0 to 31 corresponding to a time interval (2xDC) ranging from + 0 to 62. + (+) In order to measure the clock deviation, a 512 Hz clock is output for + calibration. + (+) The RTC Coarse Digital Calibration value and sign can be calibrated using + the DAL_RTCEx_SetCoarseCalib() function. + + *** Smooth Digital Calibration configuration *** + ================================================ + [..] + (+) RTC frequency can be digitally calibrated with a resolution of about + 0.954 ppm with a range from -487.1 ppm to +488.5 ppm. + The correction of the frequency is performed using a series of small + adjustments (adding and/or subtracting individual RTCCLK pulses). + (+) The smooth digital calibration is performed during a cycle of about 2^20 + RTCCLK pulses (or 32 seconds) when the input frequency is 32,768 Hz. + This cycle is maintained by a 20-bit counter clocked by RTCCLK. + (+) The smooth calibration register (RTC_CAL) specifies the number of RTCCLK + clock cycles to be masked during the 32-second cycle. + (+) The RTC Smooth Digital Calibration value and the corresponding calibration + cycle period (32s, 16s, or 8s) can be calibrated using the + DAL_RTCEx_SetSmoothCalib() function. + + @endverbatim + * + */ + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @defgroup RTCEx RTCEx + * @brief RTC Extended DAL module driver + * @{ + */ + +#ifdef DAL_RTC_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Exported functions --------------------------------------------------------*/ + +/** @defgroup RTCEx_Exported_Functions RTCEx Exported Functions + * @{ + */ + +/** @defgroup RTCEx_Exported_Functions_Group1 RTC Timestamp and Tamper functions + * @brief RTC Timestamp and Tamper functions + * +@verbatim + =============================================================================== + ##### RTC Timestamp and Tamper functions ##### + =============================================================================== + + [..] This section provides functions allowing to configure Timestamp feature + +@endverbatim + * @{ + */ + +/** + * @brief Sets Timestamp. + * @note This API must be called before enabling the Timestamp feature. + * @param hrtc pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @param RTC_TimeStampEdge Specifies the pin edge on which the Timestamp is + * activated. + * This parameter can be one of the following values: + * @arg RTC_TIMESTAMPEDGE_RISING: the Timestamp event occurs on + * the rising edge of the related pin. + * @arg RTC_TIMESTAMPEDGE_FALLING: the Timestamp event occurs on + * the falling edge of the related pin. + * @param RTC_TimeStampPin Specifies the RTC Timestamp Pin. + * This parameter can be one of the following values: + * @arg RTC_TIMESTAMPPIN_DEFAULT: PC13 is selected as RTC Timestamp Pin. + * @arg RTC_TIMESTAMPPIN_POS1: PI8 is selected as RTC Timestamp Pin. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_RTCEx_SetTimeStamp(RTC_HandleTypeDef *hrtc, uint32_t RTC_TimeStampEdge, uint32_t RTC_TimeStampPin) +{ + uint32_t tmpreg = 0U; + + /* Check the parameters */ + ASSERT_PARAM(IS_TIMESTAMP_EDGE(RTC_TimeStampEdge)); + ASSERT_PARAM(IS_RTC_TIMESTAMP_PIN(RTC_TimeStampPin)); + + /* Process Locked */ + __DAL_LOCK(hrtc); + + /* Change RTC state to BUSY */ + hrtc->State = DAL_RTC_STATE_BUSY; + + hrtc->Instance->TACFG &= (uint32_t)~RTC_TACFG_TSMSEL; + hrtc->Instance->TACFG |= (uint32_t)(RTC_TimeStampPin); + + /* Get the RTC_CTRL register and clear the bits to be configured */ + tmpreg = (uint32_t)(hrtc->Instance->CTRL & (uint32_t)~(RTC_CTRL_TSETECFG | RTC_CTRL_TSEN)); + + /* Configure the Timestamp TSEDGE bit */ + tmpreg |= RTC_TimeStampEdge; + + /* Disable the write protection for RTC registers */ + __DAL_RTC_WRITEPROTECTION_DISABLE(hrtc); + + /* Copy the desired configuration into the CTRL register */ + hrtc->Instance->CTRL = (uint32_t)tmpreg; + + /* Clear RTC Timestamp flag */ + __DAL_RTC_TIMESTAMP_CLEAR_FLAG(hrtc, RTC_FLAG_TSF); + + /* Clear RTC Timestamp overrun Flag */ + __DAL_RTC_TIMESTAMP_CLEAR_FLAG(hrtc, RTC_FLAG_TSOVF); + + /* Enable the Timestamp saving */ + __DAL_RTC_TIMESTAMP_ENABLE(hrtc); + + /* Enable the write protection for RTC registers */ + __DAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + /* Change RTC state back to READY */ + hrtc->State = DAL_RTC_STATE_READY; + + /* Process Unlocked */ + __DAL_UNLOCK(hrtc); + + return DAL_OK; +} + +/** + * @brief Sets Timestamp with Interrupt. + * @param hrtc pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @note This API must be called before enabling the Timestamp feature. + * @param RTC_TimeStampEdge Specifies the pin edge on which the Timestamp is + * activated. + * This parameter can be one of the following values: + * @arg RTC_TIMESTAMPEDGE_RISING: the Timestamp event occurs on + * the rising edge of the related pin. + * @arg RTC_TIMESTAMPEDGE_FALLING: the Timestamp event occurs on + * the falling edge of the related pin. + * @param RTC_TimeStampPin Specifies the RTC Timestamp Pin. + * This parameter can be one of the following values: + * @arg RTC_TIMESTAMPPIN_DEFAULT: PC13 is selected as RTC Timestamp Pin. + * @arg RTC_TIMESTAMPPIN_POS1: PI8 is selected as RTC Timestamp Pin. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_RTCEx_SetTimeStamp_IT(RTC_HandleTypeDef *hrtc, uint32_t RTC_TimeStampEdge, uint32_t RTC_TimeStampPin) +{ + uint32_t tmpreg = 0U; + + /* Check the parameters */ + ASSERT_PARAM(IS_TIMESTAMP_EDGE(RTC_TimeStampEdge)); + ASSERT_PARAM(IS_RTC_TIMESTAMP_PIN(RTC_TimeStampPin)); + + /* Process Locked */ + __DAL_LOCK(hrtc); + + /* Change RTC state to BUSY */ + hrtc->State = DAL_RTC_STATE_BUSY; + + hrtc->Instance->TACFG &= (uint32_t)~RTC_TACFG_TSMSEL; + hrtc->Instance->TACFG |= (uint32_t)(RTC_TimeStampPin); + + /* Get the RTC_CTRL register and clear the bits to be configured */ + tmpreg = (uint32_t)(hrtc->Instance->CTRL & (uint32_t)~(RTC_CTRL_TSETECFG | RTC_CTRL_TSEN)); + + /* Configure the Timestamp TSETECFG bit */ + tmpreg |= RTC_TimeStampEdge; + + /* Disable the write protection for RTC registers */ + __DAL_RTC_WRITEPROTECTION_DISABLE(hrtc); + + /* Copy the desired configuration into the CTRL register */ + hrtc->Instance->CTRL = (uint32_t)tmpreg; + + /* Clear RTC Timestamp flag */ + __DAL_RTC_TIMESTAMP_CLEAR_FLAG(hrtc, RTC_FLAG_TSF); + + /* Clear RTC Timestamp overrun Flag */ + __DAL_RTC_TIMESTAMP_CLEAR_FLAG(hrtc, RTC_FLAG_TSOVF); + + /* Enable the Timestamp saving */ + __DAL_RTC_TIMESTAMP_ENABLE(hrtc); + + /* Enable IT Timestamp */ + __DAL_RTC_TIMESTAMP_ENABLE_IT(hrtc, RTC_IT_TS); + + /* Enable the write protection for RTC registers */ + __DAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + /* RTC Timestamp Interrupt Configuration: EINT configuration */ + __DAL_RTC_TAMPER_TIMESTAMP_EINT_ENABLE_IT(); + __DAL_RTC_TAMPER_TIMESTAMP_EINT_ENABLE_RISING_EDGE(); + + /* Change RTC state back to READY */ + hrtc->State = DAL_RTC_STATE_READY; + + /* Process Unlocked */ + __DAL_UNLOCK(hrtc); + + return DAL_OK; +} + +/** + * @brief Deactivates Timestamp. + * @param hrtc pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_RTCEx_DeactivateTimeStamp(RTC_HandleTypeDef *hrtc) +{ + uint32_t tmpreg = 0U; + + /* Process Locked */ + __DAL_LOCK(hrtc); + + hrtc->State = DAL_RTC_STATE_BUSY; + + /* Disable the write protection for RTC registers */ + __DAL_RTC_WRITEPROTECTION_DISABLE(hrtc); + + /* In case of interrupt mode is used, the interrupt source must disabled */ + __DAL_RTC_TIMESTAMP_DISABLE_IT(hrtc, RTC_IT_TS); + + /* Get the RTC_CTRL register and clear the bits to be configured */ + tmpreg = (uint32_t)(hrtc->Instance->CTRL & (uint32_t)~(RTC_CTRL_TSETECFG | RTC_CTRL_TSEN)); + + /* Configure the Timestamp TSETECFG and Enable bits */ + hrtc->Instance->CTRL = (uint32_t)tmpreg; + + /* Enable the write protection for RTC registers */ + __DAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + hrtc->State = DAL_RTC_STATE_READY; + + /* Process Unlocked */ + __DAL_UNLOCK(hrtc); + + return DAL_OK; +} + +/** + * @brief Gets the RTC Timestamp value. + * @param hrtc pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @param sTimeStamp Pointer to Time structure + * @param sTimeStampDate Pointer to Date structure + * @param Format specifies the format of the entered parameters. + * This parameter can be one of the following values: + * @arg RTC_FORMAT_BIN: Binary data format + * @arg RTC_FORMAT_BCD: BCD data format + * @retval DAL status + */ +DAL_StatusTypeDef DAL_RTCEx_GetTimeStamp(RTC_HandleTypeDef *hrtc, RTC_TimeTypeDef *sTimeStamp, RTC_DateTypeDef *sTimeStampDate, uint32_t Format) +{ + uint32_t tmptime = 0U; + uint32_t tmpdate = 0U; + + /* Check the parameters */ + ASSERT_PARAM(IS_RTC_FORMAT(Format)); + + /* Get the Timestamp time and date registers values */ + tmptime = (uint32_t)(hrtc->Instance->TSTIME & RTC_TIME_RESERVED_MASK); + tmpdate = (uint32_t)(hrtc->Instance->TSDATE & RTC_DATE_RESERVED_MASK); + + /* Fill the Time structure fields with the read parameters */ + sTimeStamp->Hours = (uint8_t)((tmptime & (RTC_TSTIME_HRT | RTC_TSTIME_HRU)) >> RTC_TSTIME_HRU_Pos); + sTimeStamp->Minutes = (uint8_t)((tmptime & (RTC_TSTIME_MINT | RTC_TSTIME_MINU)) >> RTC_TSTIME_MINU_Pos); + sTimeStamp->Seconds = (uint8_t)((tmptime & (RTC_TSTIME_SECT | RTC_TSTIME_SECU)) >> RTC_TSTIME_SECU_Pos); + sTimeStamp->TimeFormat = (uint8_t)((tmptime & (RTC_TSTIME_TIMEFCFG)) >> RTC_TSTIME_TIMEFCFG_Pos); + sTimeStamp->SubSeconds = (uint32_t) hrtc->Instance->TSSUBSEC; + + /* Fill the Date structure fields with the read parameters */ + sTimeStampDate->Year = 0U; + sTimeStampDate->Month = (uint8_t)((tmpdate & (RTC_TSDATE_MONT | RTC_TSDATE_MONU)) >> RTC_TSDATE_MONU_Pos); + sTimeStampDate->Date = (uint8_t)((tmpdate & (RTC_TSDATE_DAYT | RTC_TSDATE_DAYU)) >> RTC_TSDATE_DAYU_Pos); + sTimeStampDate->WeekDay = (uint8_t)((tmpdate & (RTC_TSDATE_WEEKSEL)) >> RTC_TSDATE_WEEKSEL_Pos); + + /* Check the input parameters format */ + if (Format == RTC_FORMAT_BIN) + { + /* Convert the Timestamp structure parameters to Binary format */ + sTimeStamp->Hours = (uint8_t)RTC_Bcd2ToByte(sTimeStamp->Hours); + sTimeStamp->Minutes = (uint8_t)RTC_Bcd2ToByte(sTimeStamp->Minutes); + sTimeStamp->Seconds = (uint8_t)RTC_Bcd2ToByte(sTimeStamp->Seconds); + + /* Convert the DateTimeStamp structure parameters to Binary format */ + sTimeStampDate->Month = (uint8_t)RTC_Bcd2ToByte(sTimeStampDate->Month); + sTimeStampDate->Date = (uint8_t)RTC_Bcd2ToByte(sTimeStampDate->Date); + sTimeStampDate->WeekDay = (uint8_t)RTC_Bcd2ToByte(sTimeStampDate->WeekDay); + } + + /* Clear the Timestamp Flag */ + __DAL_RTC_TIMESTAMP_CLEAR_FLAG(hrtc, RTC_FLAG_TSF); + + return DAL_OK; +} + +/** + * @brief Sets Tamper. + * @note By calling this API the tamper global interrupt will be disabled. + * @param hrtc pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @param sTamper Pointer to Tamper Structure. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_RTCEx_SetTamper(RTC_HandleTypeDef *hrtc, RTC_TamperTypeDef *sTamper) +{ + uint32_t tmpreg = 0U; + + /* Check the parameters */ + ASSERT_PARAM(IS_RTC_TAMPER(sTamper->Tamper)); + ASSERT_PARAM(IS_RTC_TAMPER_PIN(sTamper->PinSelection)); + ASSERT_PARAM(IS_RTC_TAMPER_TRIGGER(sTamper->Trigger)); + ASSERT_PARAM(IS_RTC_TAMPER_FILTER(sTamper->Filter)); + ASSERT_PARAM(IS_RTC_TAMPER_FILTER_CONFIG_CORRECT(sTamper->Filter, sTamper->Trigger)); + ASSERT_PARAM(IS_RTC_TAMPER_SAMPLING_FREQ(sTamper->SamplingFrequency)); + ASSERT_PARAM(IS_RTC_TAMPER_PRECHARGE_DURATION(sTamper->PrechargeDuration)); + ASSERT_PARAM(IS_RTC_TAMPER_PULLUP_STATE(sTamper->TamperPullUp)); + ASSERT_PARAM(IS_RTC_TAMPER_TIMESTAMPONTAMPER_DETECTION(sTamper->TimeStampOnTamperDetection)); + + /* Process Locked */ + __DAL_LOCK(hrtc); + + hrtc->State = DAL_RTC_STATE_BUSY; + + /* Copy control register into temporary variable */ + tmpreg = hrtc->Instance->TACFG; + + /* Enable selected tamper */ + tmpreg |= (sTamper->Tamper); + + /* Configure the tamper trigger bit (this bit is just on the right of the + tamper enable bit, hence the one-time right shift before updating it) */ + if (sTamper->Trigger == RTC_TAMPERTRIGGER_FALLINGEDGE) + { + /* Set the tamper trigger bit (case of falling edge or high level) */ + tmpreg |= (uint32_t)(sTamper->Tamper << 1U); + } + else + { + /* Clear the tamper trigger bit (case of rising edge or low level) */ + tmpreg &= (uint32_t)~(sTamper->Tamper << 1U); + } + + /* Clear remaining fields before setting them */ + tmpreg &= ~(RTC_TAMPERFILTER_MASK | \ + RTC_TAMPERSAMPLINGFREQ_RTCCLK_MASK | \ + RTC_TAMPERPRECHARGEDURATION_MASK | \ + RTC_TAMPER_PULLUP_MASK | \ + RTC_TACFG_TP1MSEL | \ + RTC_TIMESTAMPONTAMPERDETECTION_MASK); + + /* Set remaining parameters of desired configuration into temporary variable */ + tmpreg |= ((uint32_t)sTamper->Filter | \ + (uint32_t)sTamper->SamplingFrequency | \ + (uint32_t)sTamper->PrechargeDuration | \ + (uint32_t)sTamper->TamperPullUp | \ + (uint32_t)sTamper->PinSelection | \ + (uint32_t)sTamper->TimeStampOnTamperDetection); + + /* Disable tamper global interrupt in case it is enabled */ + tmpreg &= (uint32_t)~RTC_TACFG_TPIEN; + + /* Copy desired configuration into configuration register */ + hrtc->Instance->TACFG = tmpreg; + + hrtc->State = DAL_RTC_STATE_READY; + + /* Process Unlocked */ + __DAL_UNLOCK(hrtc); + + return DAL_OK; +} + +/** + * @brief Sets Tamper with interrupt. + * @note By calling this API the tamper global interrupt will be enabled. + * @param hrtc pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @param sTamper Pointer to RTC Tamper. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_RTCEx_SetTamper_IT(RTC_HandleTypeDef *hrtc, RTC_TamperTypeDef *sTamper) +{ + uint32_t tmpreg = 0U; + + /* Check the parameters */ + ASSERT_PARAM(IS_RTC_TAMPER(sTamper->Tamper)); + ASSERT_PARAM(IS_RTC_TAMPER_PIN(sTamper->PinSelection)); + ASSERT_PARAM(IS_RTC_TAMPER_TRIGGER(sTamper->Trigger)); + ASSERT_PARAM(IS_RTC_TAMPER_FILTER(sTamper->Filter)); + ASSERT_PARAM(IS_RTC_TAMPER_FILTER_CONFIG_CORRECT(sTamper->Filter, sTamper->Trigger)); + ASSERT_PARAM(IS_RTC_TAMPER_SAMPLING_FREQ(sTamper->SamplingFrequency)); + ASSERT_PARAM(IS_RTC_TAMPER_PRECHARGE_DURATION(sTamper->PrechargeDuration)); + ASSERT_PARAM(IS_RTC_TAMPER_PULLUP_STATE(sTamper->TamperPullUp)); + ASSERT_PARAM(IS_RTC_TAMPER_TIMESTAMPONTAMPER_DETECTION(sTamper->TimeStampOnTamperDetection)); + + /* Process Locked */ + __DAL_LOCK(hrtc); + + hrtc->State = DAL_RTC_STATE_BUSY; + + /* Copy control register into temporary variable */ + tmpreg = hrtc->Instance->TACFG; + + /* Enable selected tamper */ + tmpreg |= (sTamper->Tamper); + + /* Configure the tamper trigger bit (this bit is just on the right of the + tamper enable bit, hence the one-time right shift before updating it) */ + if (sTamper->Trigger == RTC_TAMPERTRIGGER_FALLINGEDGE) + { + /* Set the tamper trigger bit (case of falling edge or high level) */ + tmpreg |= (uint32_t)(sTamper->Tamper << 1U); + } + else + { + /* Clear the tamper trigger bit (case of rising edge or low level) */ + tmpreg &= (uint32_t)~(sTamper->Tamper << 1U); + } + + /* Clear remaining fields before setting them */ + tmpreg &= ~(RTC_TAMPERFILTER_MASK | \ + RTC_TAMPERSAMPLINGFREQ_RTCCLK_MASK | \ + RTC_TAMPERPRECHARGEDURATION_MASK | \ + RTC_TAMPER_PULLUP_MASK | \ + RTC_TACFG_TP1MSEL | \ + RTC_TIMESTAMPONTAMPERDETECTION_MASK); + + /* Set remaining parameters of desired configuration into temporary variable */ + tmpreg |= ((uint32_t)sTamper->Filter | \ + (uint32_t)sTamper->SamplingFrequency | \ + (uint32_t)sTamper->PrechargeDuration | \ + (uint32_t)sTamper->TamperPullUp | \ + (uint32_t)sTamper->PinSelection | \ + (uint32_t)sTamper->TimeStampOnTamperDetection); + + /* Enable global tamper interrupt */ + tmpreg |= (uint32_t)RTC_TACFG_TPIEN; + + /* Copy desired configuration into configuration register */ + hrtc->Instance->TACFG = tmpreg; + + /* RTC Tamper Interrupt Configuration: EINT configuration */ + __DAL_RTC_TAMPER_TIMESTAMP_EINT_ENABLE_IT(); + __DAL_RTC_TAMPER_TIMESTAMP_EINT_ENABLE_RISING_EDGE(); + + hrtc->State = DAL_RTC_STATE_READY; + + /* Process Unlocked */ + __DAL_UNLOCK(hrtc); + + return DAL_OK; +} + +/** + * @brief Deactivates Tamper. + * @note The tamper global interrupt bit will remain unchanged. + * @param hrtc pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @param Tamper Selected tamper pin. + * This parameter can be any combination of the following values: + * @arg RTC_TAMPER_1: Tamper 1 + * @arg RTC_TAMPER_2: Tamper 2 + * @note RTC_TAMPER_2 is not applicable to all devices. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_RTCEx_DeactivateTamper(RTC_HandleTypeDef *hrtc, uint32_t Tamper) +{ + ASSERT_PARAM(IS_RTC_TAMPER(Tamper)); + + /* Process Locked */ + __DAL_LOCK(hrtc); + + hrtc->State = DAL_RTC_STATE_BUSY; + + /* Disable the selected Tamper pin */ + hrtc->Instance->TACFG &= (uint32_t)~Tamper; + + hrtc->State = DAL_RTC_STATE_READY; + + /* Process Unlocked */ + __DAL_UNLOCK(hrtc); + + return DAL_OK; +} + +/** + * @brief Handles Timestamp and Tamper interrupt request. + * @param hrtc pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @retval None + */ +void DAL_RTCEx_TamperTimeStampIRQHandler(RTC_HandleTypeDef *hrtc) +{ + /* Get the Timestamp interrupt source enable status */ + if (__DAL_RTC_TIMESTAMP_GET_IT_SOURCE(hrtc, RTC_IT_TS) != 0U) + { + /* Get the pending status of the Timestamp Interrupt */ + if (__DAL_RTC_TIMESTAMP_GET_FLAG(hrtc, RTC_FLAG_TSF) != 0U) + { + /* Timestamp callback */ +#if (USE_DAL_RTC_REGISTER_CALLBACKS == 1) + hrtc->TimeStampEventCallback(hrtc); +#else + DAL_RTCEx_TimeStampEventCallback(hrtc); +#endif /* USE_DAL_RTC_REGISTER_CALLBACKS */ + + /* Clear the Timestamp interrupt pending bit */ + __DAL_RTC_TIMESTAMP_CLEAR_FLAG(hrtc, RTC_FLAG_TSF); + } + } + + /* Get the Tamper 1 interrupt source enable status */ + if (__DAL_RTC_TAMPER_GET_IT_SOURCE(hrtc, RTC_IT_TAMP) != 0U) + { + /* Get the pending status of the Tamper 1 Interrupt */ + if (__DAL_RTC_TAMPER_GET_FLAG(hrtc, RTC_FLAG_TAMP1F) != 0U) + { + /* Tamper callback */ +#if (USE_DAL_RTC_REGISTER_CALLBACKS == 1) + hrtc->Tamper1EventCallback(hrtc); +#else + DAL_RTCEx_Tamper1EventCallback(hrtc); +#endif /* USE_DAL_RTC_REGISTER_CALLBACKS */ + + /* Clear the Tamper interrupt pending bit */ + __DAL_RTC_TAMPER_CLEAR_FLAG(hrtc, RTC_FLAG_TAMP1F); + } + } + +#if defined(RTC_TAMPER2_SUPPORT) + /* Get the Tamper 2 interrupt source enable status */ + if (__DAL_RTC_TAMPER_GET_IT_SOURCE(hrtc, RTC_IT_TAMP) != 0U) + { + /* Get the pending status of the Tamper 2 Interrupt */ + if (__DAL_RTC_TAMPER_GET_FLAG(hrtc, RTC_FLAG_TAMP2F) != 0U) + { + /* Tamper callback */ +#if (USE_DAL_RTC_REGISTER_CALLBACKS == 1) + hrtc->Tamper2EventCallback(hrtc); +#else + DAL_RTCEx_Tamper2EventCallback(hrtc); +#endif /* USE_DAL_RTC_REGISTER_CALLBACKS */ + + /* Clear the Tamper interrupt pending bit */ + __DAL_RTC_TAMPER_CLEAR_FLAG(hrtc, RTC_FLAG_TAMP2F); + } + } +#endif /* RTC_TAMPER2_SUPPORT */ + + /* Clear the EINT's Flag for RTC Timestamp and Tamper */ + __DAL_RTC_TAMPER_TIMESTAMP_EINT_CLEAR_FLAG(); + + /* Change RTC state */ + hrtc->State = DAL_RTC_STATE_READY; +} + +/** + * @brief Timestamp callback. + * @param hrtc pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @retval None + */ +__weak void DAL_RTCEx_TimeStampEventCallback(RTC_HandleTypeDef *hrtc) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hrtc); + + /* NOTE: This function should not be modified, when the callback is needed, + the DAL_RTCEx_TimeStampEventCallback could be implemented in the user file + */ +} + +/** + * @brief Tamper 1 callback. + * @param hrtc pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @retval None + */ +__weak void DAL_RTCEx_Tamper1EventCallback(RTC_HandleTypeDef *hrtc) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hrtc); + + /* NOTE: This function should not be modified, when the callback is needed, + the DAL_RTCEx_Tamper1EventCallback could be implemented in the user file + */ +} + +#if defined(RTC_TAMPER2_SUPPORT) +/** + * @brief Tamper 2 callback. + * @param hrtc pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @retval None + */ +__weak void DAL_RTCEx_Tamper2EventCallback(RTC_HandleTypeDef *hrtc) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hrtc); + + /* NOTE: This function should not be modified, when the callback is needed, + the DAL_RTCEx_Tamper2EventCallback could be implemented in the user file + */ +} +#endif /* RTC_TAMPER2_SUPPORT */ + +/** + * @brief Handles Timestamp polling request. + * @param hrtc pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @param Timeout Timeout duration + * @retval DAL status + */ +DAL_StatusTypeDef DAL_RTCEx_PollForTimeStampEvent(RTC_HandleTypeDef *hrtc, uint32_t Timeout) +{ + uint32_t tickstart = 0U; + + /* Get tick */ + tickstart = DAL_GetTick(); + + while (__DAL_RTC_TIMESTAMP_GET_FLAG(hrtc, RTC_FLAG_TSF) == 0U) + { + if (Timeout != DAL_MAX_DELAY) + { + if ((Timeout == 0U) || ((DAL_GetTick() - tickstart) > Timeout)) + { + hrtc->State = DAL_RTC_STATE_TIMEOUT; + return DAL_TIMEOUT; + } + } + + if (__DAL_RTC_TIMESTAMP_GET_FLAG(hrtc, RTC_FLAG_TSOVF) != 0U) + { + /* Clear the Timestamp Overrun Flag */ + __DAL_RTC_TIMESTAMP_CLEAR_FLAG(hrtc, RTC_FLAG_TSOVF); + + /* Change Timestamp state */ + hrtc->State = DAL_RTC_STATE_ERROR; + + return DAL_ERROR; + } + } + + /* Change RTC state */ + hrtc->State = DAL_RTC_STATE_READY; + + return DAL_OK; +} + +/** + * @brief Handles Tamper 1 Polling. + * @param hrtc pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @param Timeout Timeout duration + * @retval DAL status + */ +DAL_StatusTypeDef DAL_RTCEx_PollForTamper1Event(RTC_HandleTypeDef *hrtc, uint32_t Timeout) +{ + uint32_t tickstart = 0U; + + /* Get tick */ + tickstart = DAL_GetTick(); + + /* Get the status of the Interrupt */ + while (__DAL_RTC_TAMPER_GET_FLAG(hrtc, RTC_FLAG_TAMP1F) == 0U) + { + if (Timeout != DAL_MAX_DELAY) + { + if ((Timeout == 0U) || ((DAL_GetTick() - tickstart) > Timeout)) + { + hrtc->State = DAL_RTC_STATE_TIMEOUT; + return DAL_TIMEOUT; + } + } + } + + /* Clear the Tamper Flag */ + __DAL_RTC_TAMPER_CLEAR_FLAG(hrtc, RTC_FLAG_TAMP1F); + + /* Change RTC state */ + hrtc->State = DAL_RTC_STATE_READY; + + return DAL_OK; +} + +#if defined(RTC_TAMPER2_SUPPORT) +/** + * @brief Handles Tamper 2 Polling. + * @param hrtc pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @param Timeout Timeout duration + * @retval DAL status + */ +DAL_StatusTypeDef DAL_RTCEx_PollForTamper2Event(RTC_HandleTypeDef *hrtc, uint32_t Timeout) +{ + uint32_t tickstart = 0U; + + /* Get tick */ + tickstart = DAL_GetTick(); + + /* Get the status of the Interrupt */ + while (__DAL_RTC_TAMPER_GET_FLAG(hrtc, RTC_FLAG_TAMP2F) == 0U) + { + if (Timeout != DAL_MAX_DELAY) + { + if ((Timeout == 0U) || ((DAL_GetTick() - tickstart) > Timeout)) + { + hrtc->State = DAL_RTC_STATE_TIMEOUT; + return DAL_TIMEOUT; + } + } + } + + /* Clear the Tamper Flag */ + __DAL_RTC_TAMPER_CLEAR_FLAG(hrtc, RTC_FLAG_TAMP2F); + + /* Change RTC state */ + hrtc->State = DAL_RTC_STATE_READY; + + return DAL_OK; +} +#endif /* RTC_TAMPER2_SUPPORT */ + +/** + * @} + */ + +/** @defgroup RTCEx_Exported_Functions_Group2 RTC Wakeup functions + * @brief RTC Wakeup functions + * +@verbatim + =============================================================================== + ##### RTC Wakeup functions ##### + =============================================================================== + + [..] This section provides functions allowing to configure Wakeup feature + +@endverbatim + * @{ + */ + +/** + * @brief Sets wakeup timer. + * @param hrtc pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @param WakeUpCounter Wakeup counter + * @param WakeUpClock Wakeup clock + * @retval DAL status + */ +DAL_StatusTypeDef DAL_RTCEx_SetWakeUpTimer(RTC_HandleTypeDef *hrtc, uint32_t WakeUpCounter, uint32_t WakeUpClock) +{ + uint32_t tickstart = 0U; + + /* Check the parameters */ + ASSERT_PARAM(IS_RTC_WAKEUP_CLOCK(WakeUpClock)); + ASSERT_PARAM(IS_RTC_WAKEUP_COUNTER(WakeUpCounter)); + + /* Process Locked */ + __DAL_LOCK(hrtc); + + hrtc->State = DAL_RTC_STATE_BUSY; + + /* Disable the write protection for RTC registers */ + __DAL_RTC_WRITEPROTECTION_DISABLE(hrtc); + + /* Check RTC WUTWF flag is reset only when wakeup timer enabled*/ + if ((hrtc->Instance->CTRL & RTC_CTRL_WUTEN) != 0U) + { + tickstart = DAL_GetTick(); + + /* Wait till RTC WUTWF flag is reset and if timeout is reached exit */ + while (__DAL_RTC_WAKEUPTIMER_GET_FLAG(hrtc, RTC_FLAG_WUTWF) != 0U) + { + if ((DAL_GetTick() - tickstart) > RTC_TIMEOUT_VALUE) + { + /* Enable the write protection for RTC registers */ + __DAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + hrtc->State = DAL_RTC_STATE_TIMEOUT; + + /* Process Unlocked */ + __DAL_UNLOCK(hrtc); + + return DAL_TIMEOUT; + } + } + } + + /* Disable the Wakeup timer */ + __DAL_RTC_WAKEUPTIMER_DISABLE(hrtc); + + /* Clear the Wakeup flag */ + __DAL_RTC_WAKEUPTIMER_CLEAR_FLAG(hrtc, RTC_FLAG_WUTF); + + /* Get tick */ + tickstart = DAL_GetTick(); + + /* Wait till RTC WUTWF flag is set and if timeout is reached exit */ + while (__DAL_RTC_WAKEUPTIMER_GET_FLAG(hrtc, RTC_FLAG_WUTWF) == 0U) + { + if ((DAL_GetTick() - tickstart) > RTC_TIMEOUT_VALUE) + { + /* Enable the write protection for RTC registers */ + __DAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + hrtc->State = DAL_RTC_STATE_TIMEOUT; + + /* Process Unlocked */ + __DAL_UNLOCK(hrtc); + + return DAL_TIMEOUT; + } + } + + /* Clear the Wakeup Timer clock source bits in CTRL register */ + hrtc->Instance->CTRL &= (uint32_t)~RTC_CTRL_WUCLKSEL; + + /* Configure the clock source */ + hrtc->Instance->CTRL |= (uint32_t)WakeUpClock; + + /* Configure the Wakeup Timer counter */ + hrtc->Instance->AUTORLD = (uint32_t)WakeUpCounter; + + /* Enable the Wakeup Timer */ + __DAL_RTC_WAKEUPTIMER_ENABLE(hrtc); + + /* Enable the write protection for RTC registers */ + __DAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + hrtc->State = DAL_RTC_STATE_READY; + + /* Process Unlocked */ + __DAL_UNLOCK(hrtc); + + return DAL_OK; +} + +/** + * @brief Sets wakeup timer with interrupt. + * @param hrtc pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @param WakeUpCounter Wakeup counter + * @param WakeUpClock Wakeup clock + * @retval DAL status + */ +DAL_StatusTypeDef DAL_RTCEx_SetWakeUpTimer_IT(RTC_HandleTypeDef *hrtc, uint32_t WakeUpCounter, uint32_t WakeUpClock) +{ + __IO uint32_t count = RTC_TIMEOUT_VALUE * (SystemCoreClock / 32U / 1000U); + + /* Check the parameters */ + ASSERT_PARAM(IS_RTC_WAKEUP_CLOCK(WakeUpClock)); + ASSERT_PARAM(IS_RTC_WAKEUP_COUNTER(WakeUpCounter)); + + /* Process Locked */ + __DAL_LOCK(hrtc); + + hrtc->State = DAL_RTC_STATE_BUSY; + + /* Disable the write protection for RTC registers */ + __DAL_RTC_WRITEPROTECTION_DISABLE(hrtc); + + /* Check RTC WUTWF flag is reset only when wakeup timer enabled */ + if ((hrtc->Instance->CTRL & RTC_CTRL_WUTEN) != 0U) + { + /* Wait till RTC WUTWF flag is reset and if timeout is reached exit */ + do + { + if (count-- == 0U) + { + /* Enable the write protection for RTC registers */ + __DAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + hrtc->State = DAL_RTC_STATE_TIMEOUT; + + /* Process Unlocked */ + __DAL_UNLOCK(hrtc); + + return DAL_TIMEOUT; + } + } while (__DAL_RTC_WAKEUPTIMER_GET_FLAG(hrtc, RTC_FLAG_WUTWF) != 0U); + } + + /* Disable the Wakeup timer */ + __DAL_RTC_WAKEUPTIMER_DISABLE(hrtc); + + /* Clear the Wakeup flag */ + __DAL_RTC_WAKEUPTIMER_CLEAR_FLAG(hrtc, RTC_FLAG_WUTF); + + /* Reload the counter */ + count = RTC_TIMEOUT_VALUE * (SystemCoreClock / 32U / 1000U); + + /* Wait till RTC WUTWF flag is set and if timeout is reached exit */ + do + { + if (count-- == 0U) + { + /* Enable the write protection for RTC registers */ + __DAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + hrtc->State = DAL_RTC_STATE_TIMEOUT; + + /* Process Unlocked */ + __DAL_UNLOCK(hrtc); + + return DAL_TIMEOUT; + } + } while (__DAL_RTC_WAKEUPTIMER_GET_FLAG(hrtc, RTC_FLAG_WUTWF) == 0U); + + /* Clear the Wakeup Timer clock source bits in CTRL register */ + hrtc->Instance->CTRL &= (uint32_t)~RTC_CTRL_WUCLKSEL; + + /* Configure the clock source */ + hrtc->Instance->CTRL |= (uint32_t)WakeUpClock; + + /* Configure the Wakeup Timer counter */ + hrtc->Instance->AUTORLD = (uint32_t)WakeUpCounter; + + /* RTC wakeup timer Interrupt Configuration: EINT configuration */ + __DAL_RTC_WAKEUPTIMER_EINT_ENABLE_IT(); + __DAL_RTC_WAKEUPTIMER_EINT_ENABLE_RISING_EDGE(); + + /* Configure the interrupt in the RTC_CTRL register */ + __DAL_RTC_WAKEUPTIMER_ENABLE_IT(hrtc, RTC_IT_WUT); + + /* Enable the Wakeup Timer */ + __DAL_RTC_WAKEUPTIMER_ENABLE(hrtc); + + /* Enable the write protection for RTC registers */ + __DAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + hrtc->State = DAL_RTC_STATE_READY; + + /* Process Unlocked */ + __DAL_UNLOCK(hrtc); + + return DAL_OK; +} + +/** + * @brief Deactivates wakeup timer counter. + * @param hrtc pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_RTCEx_DeactivateWakeUpTimer(RTC_HandleTypeDef *hrtc) +{ + uint32_t tickstart = 0U; + + /* Process Locked */ + __DAL_LOCK(hrtc); + + hrtc->State = DAL_RTC_STATE_BUSY; + + /* Disable the write protection for RTC registers */ + __DAL_RTC_WRITEPROTECTION_DISABLE(hrtc); + + /* Disable the Wakeup Timer */ + __DAL_RTC_WAKEUPTIMER_DISABLE(hrtc); + + /* In case of interrupt mode is used, the interrupt source must disabled */ + __DAL_RTC_WAKEUPTIMER_DISABLE_IT(hrtc, RTC_IT_WUT); + + /* Get tick */ + tickstart = DAL_GetTick(); + + /* Wait till RTC WUTWF flag is set and if timeout is reached exit */ + while (__DAL_RTC_WAKEUPTIMER_GET_FLAG(hrtc, RTC_FLAG_WUTWF) == 0U) + { + if ((DAL_GetTick() - tickstart) > RTC_TIMEOUT_VALUE) + { + /* Enable the write protection for RTC registers */ + __DAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + hrtc->State = DAL_RTC_STATE_TIMEOUT; + + /* Process Unlocked */ + __DAL_UNLOCK(hrtc); + + return DAL_TIMEOUT; + } + } + + /* Enable the write protection for RTC registers */ + __DAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + hrtc->State = DAL_RTC_STATE_READY; + + /* Process Unlocked */ + __DAL_UNLOCK(hrtc); + + return DAL_OK; +} + +/** + * @brief Gets wakeup timer counter. + * @param hrtc pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @retval Counter value + */ +uint32_t DAL_RTCEx_GetWakeUpTimer(RTC_HandleTypeDef *hrtc) +{ + /* Get the counter value */ + return ((uint32_t)(hrtc->Instance->AUTORLD & RTC_AUTORLD_WUAUTORE)); +} + +/** + * @brief Handles Wakeup Timer interrupt request. + * @note Unlike alarm interrupt line (shared by Alarms A and B) or tamper + * interrupt line (shared by timestamp and tampers) wakeup timer + * interrupt line is exclusive to the wakeup timer. + * There is no need in this case to check on the interrupt enable + * status via __DAL_RTC_WAKEUPTIMER_GET_IT_SOURCE(). + * @param hrtc pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @retval None + */ +void DAL_RTCEx_WakeUpTimerIRQHandler(RTC_HandleTypeDef *hrtc) +{ + /* Get the pending status of the Wakeup timer Interrupt */ + if (__DAL_RTC_WAKEUPTIMER_GET_FLAG(hrtc, RTC_FLAG_WUTF) != 0U) + { + /* Wakeup timer callback */ +#if (USE_DAL_RTC_REGISTER_CALLBACKS == 1) + hrtc->WakeUpTimerEventCallback(hrtc); +#else + DAL_RTCEx_WakeUpTimerEventCallback(hrtc); +#endif /* USE_DAL_RTC_REGISTER_CALLBACKS */ + + /* Clear the Wakeup timer interrupt pending bit */ + __DAL_RTC_WAKEUPTIMER_CLEAR_FLAG(hrtc, RTC_FLAG_WUTF); + } + + /* Clear the EINT's line Flag for RTC WakeUpTimer */ + __DAL_RTC_WAKEUPTIMER_EINT_CLEAR_FLAG(); + + /* Change RTC state */ + hrtc->State = DAL_RTC_STATE_READY; +} + +/** + * @brief Wakeup Timer callback. + * @param hrtc pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @retval None + */ +__weak void DAL_RTCEx_WakeUpTimerEventCallback(RTC_HandleTypeDef *hrtc) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hrtc); + + /* NOTE: This function should not be modified, when the callback is needed, + the DAL_RTCEx_WakeUpTimerEventCallback could be implemented in the user file + */ +} + +/** + * @brief Handles Wakeup Timer Polling. + * @param hrtc pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @param Timeout Timeout duration + * @retval DAL status + */ +DAL_StatusTypeDef DAL_RTCEx_PollForWakeUpTimerEvent(RTC_HandleTypeDef *hrtc, uint32_t Timeout) +{ + uint32_t tickstart = 0U; + + /* Get tick */ + tickstart = DAL_GetTick(); + + while (__DAL_RTC_WAKEUPTIMER_GET_FLAG(hrtc, RTC_FLAG_WUTF) == 0U) + { + if (Timeout != DAL_MAX_DELAY) + { + if ((Timeout == 0U) || ((DAL_GetTick() - tickstart) > Timeout)) + { + hrtc->State = DAL_RTC_STATE_TIMEOUT; + return DAL_TIMEOUT; + } + } + } + + /* Clear the Wakeup timer Flag */ + __DAL_RTC_WAKEUPTIMER_CLEAR_FLAG(hrtc, RTC_FLAG_WUTF); + + /* Change RTC state */ + hrtc->State = DAL_RTC_STATE_READY; + + return DAL_OK; +} + +/** + * @} + */ + +/** @defgroup RTCEx_Exported_Functions_Group3 Extended Peripheral Control functions + * @brief Extended Peripheral Control functions + * +@verbatim + =============================================================================== + ##### Extended Peripheral Control functions ##### + =============================================================================== + [..] + This subsection provides functions allowing to + (+) Write a data in a specified RTC Backup data register + (+) Read a data in a specified RTC Backup data register + (+) Set the Coarse calibration parameters. + (+) Deactivate the Coarse calibration parameters + (+) Set the Smooth calibration parameters. + (+) Configure the Synchronization Shift Control Settings. + (+) Configure the Calibration Pinout (RTC_CALIB) Selection (1Hz or 512Hz). + (+) Deactivate the Calibration Pinout (RTC_CALIB) Selection (1Hz or 512Hz). + (+) Enable the RTC reference clock detection. + (+) Disable the RTC reference clock detection. + (+) Enable the Bypass Shadow feature. + (+) Disable the Bypass Shadow feature. + +@endverbatim + * @{ + */ + +/** + * @brief Writes a data in a specified RTC Backup data register. + * @param hrtc pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @param BackupRegister RTC Backup data Register number. + * This parameter can be: RTC_BKP_DRx (where x can be from 0 to 19) + * to specify the register. + * @param Data Data to be written in the specified RTC Backup data register. + * @retval None + */ +void DAL_RTCEx_BKUPWrite(RTC_HandleTypeDef *hrtc, uint32_t BackupRegister, uint32_t Data) +{ + uint32_t tmp = 0U; + + /* Check the parameters */ + ASSERT_PARAM(IS_RTC_BKP(BackupRegister)); + + tmp = (uint32_t) & (hrtc->Instance->BAKP0); + tmp += (BackupRegister * 4U); + + /* Write the specified register */ + *(__IO uint32_t *)tmp = (uint32_t)Data; +} + +/** + * @brief Reads data from the specified RTC Backup data Register. + * @param hrtc pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @param BackupRegister RTC Backup data Register number. + * This parameter can be: RTC_BKP_DRx (where x can be from 0 to 19) + * to specify the register. + * @retval Read value + */ +uint32_t DAL_RTCEx_BKUPRead(RTC_HandleTypeDef *hrtc, uint32_t BackupRegister) +{ + uint32_t tmp = 0U; + + /* Check the parameters */ + ASSERT_PARAM(IS_RTC_BKP(BackupRegister)); + + tmp = (uint32_t) & (hrtc->Instance->BAKP0); + tmp += (BackupRegister * 4U); + + /* Read the specified register */ + return (*(__IO uint32_t *)tmp); +} + +/** + * @brief Sets the Coarse calibration parameters. + * @param hrtc pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @param CalibSign Specifies the sign of the coarse calibration value. + * This parameter can be one of the following values: + * @arg RTC_CALIBSIGN_POSITIVE: The value sign is positive + * @arg RTC_CALIBSIGN_NEGATIVE: The value sign is negative + * @param Value value of coarse calibration expressed in ppm (coded on 5 bits). + * + * @note This Calibration value should be between 0 and 63 when using negative + * sign with a 2-ppm step. + * + * @note This Calibration value should be between 0 and 126 when using positive + * sign with a 4-ppm step. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_RTCEx_SetCoarseCalib(RTC_HandleTypeDef *hrtc, uint32_t CalibSign, uint32_t Value) +{ + DAL_StatusTypeDef status; + + /* Check the parameters */ + ASSERT_PARAM(IS_RTC_CALIB_SIGN(CalibSign)); + ASSERT_PARAM(IS_RTC_CALIB_VALUE(Value)); + + /* Process Locked */ + __DAL_LOCK(hrtc); + + hrtc->State = DAL_RTC_STATE_BUSY; + + /* Disable the write protection for RTC registers */ + __DAL_RTC_WRITEPROTECTION_DISABLE(hrtc); + + /* Enter Initialization mode */ + status = RTC_EnterInitMode(hrtc); + + if (status == DAL_OK) + { + /* Enable the Coarse Calibration */ + __DAL_RTC_COARSE_CALIB_ENABLE(hrtc); + + /* Set the coarse calibration value */ + hrtc->Instance->DCAL = (uint32_t)(CalibSign | Value); + + /* Exit Initialization mode */ + status = RTC_ExitInitMode(hrtc); + } + + if (status == DAL_OK) + { + hrtc->State = DAL_RTC_STATE_READY; + } + + /* Enable the write protection for RTC registers */ + __DAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + /* Process Unlocked */ + __DAL_UNLOCK(hrtc); + + return status; +} + +/** + * @brief Deactivates the Coarse calibration parameters. + * @param hrtc pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_RTCEx_DeactivateCoarseCalib(RTC_HandleTypeDef *hrtc) +{ + DAL_StatusTypeDef status; + + /* Process Locked */ + __DAL_LOCK(hrtc); + + hrtc->State = DAL_RTC_STATE_BUSY; + + /* Disable the write protection for RTC registers */ + __DAL_RTC_WRITEPROTECTION_DISABLE(hrtc); + + /* Enter Initialization mode */ + status = RTC_EnterInitMode(hrtc); + + if (status == DAL_OK) + { + /* Disable the Coarse Calibration */ + __DAL_RTC_COARSE_CALIB_DISABLE(hrtc); + + /* Exit Initialization mode */ + status = RTC_ExitInitMode(hrtc); + } + + if (status == DAL_OK) + { + hrtc->State = DAL_RTC_STATE_READY; + } + + /* Enable the write protection for RTC registers */ + __DAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + /* Process Unlocked */ + __DAL_UNLOCK(hrtc); + + return status; +} + +/** + * @brief Sets the Smooth calibration parameters. + * @param hrtc pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @param SmoothCalibPeriod Select the Smooth Calibration Period. + * This parameter can be can be one of the following values: + * @arg RTC_SMOOTHCALIB_PERIOD_32SEC: The smooth calibration period is 32s. + * @arg RTC_SMOOTHCALIB_PERIOD_16SEC: The smooth calibration period is 16s. + * @arg RTC_SMOOTHCALIB_PERIOD_8SEC: The smooth calibration period is 8s. + * @param SmoothCalibPlusPulses Select to Set or reset the CALP bit. + * This parameter can be one of the following values: + * @arg RTC_SMOOTHCALIB_PLUSPULSES_SET: Add one RTCCLK pulse every 2*11 pulses. + * @arg RTC_SMOOTHCALIB_PLUSPULSES_RESET: No RTCCLK pulses are added. + * @param SmoothCalibMinusPulsesValue Select the value of CALM[8:0] bits. + * This parameter can be one any value from 0 to 0x000001FF. + * @note To deactivate the smooth calibration, the field SmoothCalibPlusPulses + * must be equal to SMOOTHCALIB_PLUSPULSES_RESET and the field + * SmoothCalibMinusPulsesValue must be equal to 0. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_RTCEx_SetSmoothCalib(RTC_HandleTypeDef *hrtc, uint32_t SmoothCalibPeriod, uint32_t SmoothCalibPlusPulses, uint32_t SmoothCalibMinusPulsesValue) +{ + uint32_t tickstart = 0U; + + /* Check the parameters */ + ASSERT_PARAM(IS_RTC_SMOOTH_CALIB_PERIOD(SmoothCalibPeriod)); + ASSERT_PARAM(IS_RTC_SMOOTH_CALIB_PLUS(SmoothCalibPlusPulses)); + ASSERT_PARAM(IS_RTC_SMOOTH_CALIB_MINUS(SmoothCalibMinusPulsesValue)); + + /* Process Locked */ + __DAL_LOCK(hrtc); + + hrtc->State = DAL_RTC_STATE_BUSY; + + /* Disable the write protection for RTC registers */ + __DAL_RTC_WRITEPROTECTION_DISABLE(hrtc); + + /* check if a calibration is pending*/ + if ((hrtc->Instance->STS & RTC_STS_RCALPFLG) != 0U) + { + /* Get tick */ + tickstart = DAL_GetTick(); + + /* check if a calibration is pending*/ + while ((hrtc->Instance->STS & RTC_STS_RCALPFLG) != 0U) + { + if ((DAL_GetTick() - tickstart) > RTC_TIMEOUT_VALUE) + { + /* Enable the write protection for RTC registers */ + __DAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + /* Change RTC state */ + hrtc->State = DAL_RTC_STATE_TIMEOUT; + + /* Process Unlocked */ + __DAL_UNLOCK(hrtc); + + return DAL_TIMEOUT; + } + } + } + + /* Configure the Smooth calibration settings */ + hrtc->Instance->CAL = (uint32_t)((uint32_t)SmoothCalibPeriod | \ + (uint32_t)SmoothCalibPlusPulses | \ + (uint32_t)SmoothCalibMinusPulsesValue); + + /* Enable the write protection for RTC registers */ + __DAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + /* Change RTC state */ + hrtc->State = DAL_RTC_STATE_READY; + + /* Process Unlocked */ + __DAL_UNLOCK(hrtc); + + return DAL_OK; +} + +/** + * @brief Configures the Synchronization Shift Control Settings. + * @note When REFCKON is set, firmware must not write to Shift control register. + * @param hrtc pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @param ShiftAdd1S Select to add or not 1 second to the time calendar. + * This parameter can be one of the following values: + * @arg RTC_SHIFTADD1S_SET: Add one second to the clock calendar. + * @arg RTC_SHIFTADD1S_RESET: No effect. + * @param ShiftSubFS Select the number of Second Fractions to substitute. + * This parameter can be one any value from 0 to 0x7FFF. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_RTCEx_SetSynchroShift(RTC_HandleTypeDef *hrtc, uint32_t ShiftAdd1S, uint32_t ShiftSubFS) +{ + uint32_t tickstart = 0U; + + /* Check the parameters */ + ASSERT_PARAM(IS_RTC_SHIFT_ADD1SECEN(ShiftAdd1S)); + ASSERT_PARAM(IS_RTC_SHIFT_SFSEC(ShiftSubFS)); + + /* Process Locked */ + __DAL_LOCK(hrtc); + + hrtc->State = DAL_RTC_STATE_BUSY; + + /* Disable the write protection for RTC registers */ + __DAL_RTC_WRITEPROTECTION_DISABLE(hrtc); + + /* Get tick */ + tickstart = DAL_GetTick(); + + /* Wait until the shift is completed */ + while ((hrtc->Instance->STS & RTC_STS_SOPFLG) != 0U) + { + if ((DAL_GetTick() - tickstart) > RTC_TIMEOUT_VALUE) + { + /* Enable the write protection for RTC registers */ + __DAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + hrtc->State = DAL_RTC_STATE_TIMEOUT; + + /* Process Unlocked */ + __DAL_UNLOCK(hrtc); + + return DAL_TIMEOUT; + } + } + + /* Check if the reference clock detection is disabled */ + if ((hrtc->Instance->CTRL & RTC_CTRL_RCLKDEN) == 0U) + { + /* Configure the Shift settings */ + hrtc->Instance->SHIFT = (uint32_t)(uint32_t)(ShiftSubFS) | (uint32_t)(ShiftAdd1S); + + /* If RTC_CTRL_RCMCFG bit = 0, wait for synchro else this check is not needed */ + if ((hrtc->Instance->CTRL & RTC_CTRL_RCMCFG) == 0U) + { + if (DAL_RTC_WaitForSynchro(hrtc) != DAL_OK) + { + /* Enable the write protection for RTC registers */ + __DAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + hrtc->State = DAL_RTC_STATE_ERROR; + + /* Process Unlocked */ + __DAL_UNLOCK(hrtc); + + return DAL_ERROR; + } + } + } + else + { + /* Enable the write protection for RTC registers */ + __DAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + /* Change RTC state */ + hrtc->State = DAL_RTC_STATE_ERROR; + + /* Process Unlocked */ + __DAL_UNLOCK(hrtc); + + return DAL_ERROR; + } + + /* Enable the write protection for RTC registers */ + __DAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + /* Change RTC state */ + hrtc->State = DAL_RTC_STATE_READY; + + /* Process Unlocked */ + __DAL_UNLOCK(hrtc); + + return DAL_OK; +} + +/** + * @brief Configures the Calibration Pinout (RTC_CALIB) Selection (1Hz or 512Hz). + * @param hrtc pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @param CalibOutput Select the Calibration output Selection. + * This parameter can be one of the following values: + * @arg RTC_CALIBOUTPUT_512HZ: A signal has a regular waveform at 512Hz. + * @arg RTC_CALIBOUTPUT_1HZ: A signal has a regular waveform at 1Hz. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_RTCEx_SetCalibrationOutPut(RTC_HandleTypeDef *hrtc, uint32_t CalibOutput) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_RTC_CALIB_OUTPUT(CalibOutput)); + + /* Process Locked */ + __DAL_LOCK(hrtc); + + hrtc->State = DAL_RTC_STATE_BUSY; + + /* Disable the write protection for RTC registers */ + __DAL_RTC_WRITEPROTECTION_DISABLE(hrtc); + + /* Clear flags before config */ + hrtc->Instance->CTRL &= (uint32_t)~RTC_CTRL_CALOSEL; + + /* Configure the RTC_CTRL register */ + hrtc->Instance->CTRL |= (uint32_t)CalibOutput; + + __DAL_RTC_DCALATION_OUTPUT_ENABLE(hrtc); + + /* Enable the write protection for RTC registers */ + __DAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + /* Change RTC state */ + hrtc->State = DAL_RTC_STATE_READY; + + /* Process Unlocked */ + __DAL_UNLOCK(hrtc); + + return DAL_OK; +} + +/** + * @brief Deactivates the Calibration Pinout (RTC_CALIB) Selection (1Hz or 512Hz). + * @param hrtc pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_RTCEx_DeactivateCalibrationOutPut(RTC_HandleTypeDef *hrtc) +{ + /* Process Locked */ + __DAL_LOCK(hrtc); + + hrtc->State = DAL_RTC_STATE_BUSY; + + /* Disable the write protection for RTC registers */ + __DAL_RTC_WRITEPROTECTION_DISABLE(hrtc); + + __DAL_RTC_DCALATION_OUTPUT_DISABLE(hrtc); + + /* Enable the write protection for RTC registers */ + __DAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + /* Change RTC state */ + hrtc->State = DAL_RTC_STATE_READY; + + /* Process Unlocked */ + __DAL_UNLOCK(hrtc); + + return DAL_OK; +} + +/** + * @brief Enables the RTC reference clock detection. + * @param hrtc pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_RTCEx_SetRefClock(RTC_HandleTypeDef *hrtc) +{ + DAL_StatusTypeDef status; + + /* Process Locked */ + __DAL_LOCK(hrtc); + + hrtc->State = DAL_RTC_STATE_BUSY; + + /* Disable the write protection for RTC registers */ + __DAL_RTC_WRITEPROTECTION_DISABLE(hrtc); + + /* Enter Initialization mode */ + status = RTC_EnterInitMode(hrtc); + + if (status == DAL_OK) + { + /* Enable the reference clock detection */ + __DAL_RTC_CLOCKREF_DETECTION_ENABLE(hrtc); + + /* Exit Initialization mode */ + status = RTC_ExitInitMode(hrtc); + } + + if (status == DAL_OK) + { + hrtc->State = DAL_RTC_STATE_READY; + } + + /* Enable the write protection for RTC registers */ + __DAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + /* Process Unlocked */ + __DAL_UNLOCK(hrtc); + + return status; +} + +/** + * @brief Disable the RTC reference clock detection. + * @param hrtc pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_RTCEx_DeactivateRefClock(RTC_HandleTypeDef *hrtc) +{ + DAL_StatusTypeDef status; + + /* Process Locked */ + __DAL_LOCK(hrtc); + + hrtc->State = DAL_RTC_STATE_BUSY; + + /* Disable the write protection for RTC registers */ + __DAL_RTC_WRITEPROTECTION_DISABLE(hrtc); + + /* Enter Initialization mode */ + status = RTC_EnterInitMode(hrtc); + + if (status == DAL_OK) + { + /* Disable the reference clock detection */ + __DAL_RTC_CLOCKREF_DETECTION_DISABLE(hrtc); + + /* Exit Initialization mode */ + status = RTC_ExitInitMode(hrtc); + } + + if (status == DAL_OK) + { + hrtc->State = DAL_RTC_STATE_READY; + } + + /* Enable the write protection for RTC registers */ + __DAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + /* Process Unlocked */ + __DAL_UNLOCK(hrtc); + + return status; +} + +/** + * @brief Enables the Bypass Shadow feature. + * @param hrtc pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @note When the Bypass Shadow is enabled the calendar value are taken + * directly from the Calendar counter. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_RTCEx_EnableBypassShadow(RTC_HandleTypeDef *hrtc) +{ + /* Process Locked */ + __DAL_LOCK(hrtc); + + hrtc->State = DAL_RTC_STATE_BUSY; + + /* Disable the write protection for RTC registers */ + __DAL_RTC_WRITEPROTECTION_DISABLE(hrtc); + + /* Set the BYPSHAD bit */ + hrtc->Instance->CTRL |= (uint8_t)RTC_CTRL_RCMCFG; + + /* Enable the write protection for RTC registers */ + __DAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + /* Change RTC state */ + hrtc->State = DAL_RTC_STATE_READY; + + /* Process Unlocked */ + __DAL_UNLOCK(hrtc); + + return DAL_OK; +} + +/** + * @brief Disables the Bypass Shadow feature. + * @param hrtc pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @note When the Bypass Shadow is enabled the calendar value are taken + * directly from the Calendar counter. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_RTCEx_DisableBypassShadow(RTC_HandleTypeDef *hrtc) +{ + /* Process Locked */ + __DAL_LOCK(hrtc); + + hrtc->State = DAL_RTC_STATE_BUSY; + + /* Disable the write protection for RTC registers */ + __DAL_RTC_WRITEPROTECTION_DISABLE(hrtc); + + /* Reset the RCMCFG bit */ + hrtc->Instance->CTRL &= (uint8_t)~RTC_CTRL_RCMCFG; + + /* Enable the write protection for RTC registers */ + __DAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + /* Change RTC state */ + hrtc->State = DAL_RTC_STATE_READY; + + /* Process Unlocked */ + __DAL_UNLOCK(hrtc); + + return DAL_OK; +} + +/** + * @} + */ + +/** @defgroup RTCEx_Exported_Functions_Group4 Extended features functions + * @brief Extended features functions + * +@verbatim + =============================================================================== + ##### Extended features functions ##### + =============================================================================== + [..] This section provides functions allowing to: + (+) RTC Alarm B callback + (+) RTC Poll for Alarm B request + +@endverbatim + * @{ + */ + +/** + * @brief Alarm B callback. + * @param hrtc pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @retval None + */ +__weak void DAL_RTCEx_AlarmBEventCallback(RTC_HandleTypeDef *hrtc) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hrtc); + + /* NOTE: This function should not be modified, when the callback is needed, + the DAL_RTCEx_AlarmBEventCallback could be implemented in the user file + */ +} + +/** + * @brief Handles Alarm B Polling request. + * @param hrtc pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @param Timeout Timeout duration + * @retval DAL status + */ +DAL_StatusTypeDef DAL_RTCEx_PollForAlarmBEvent(RTC_HandleTypeDef *hrtc, uint32_t Timeout) +{ + uint32_t tickstart = 0U; + + /* Get tick */ + tickstart = DAL_GetTick(); + + /* Wait till RTC ALRBF flag is set and if timeout is reached exit */ + while (__DAL_RTC_ALARM_GET_FLAG(hrtc, RTC_FLAG_ALRBF) == 0U) + { + if (Timeout != DAL_MAX_DELAY) + { + if ((Timeout == 0U) || ((DAL_GetTick() - tickstart) > Timeout)) + { + hrtc->State = DAL_RTC_STATE_TIMEOUT; + return DAL_TIMEOUT; + } + } + } + + /* Clear the Alarm flag */ + __DAL_RTC_ALARM_CLEAR_FLAG(hrtc, RTC_FLAG_ALRBF); + + /* Change RTC state */ + hrtc->State = DAL_RTC_STATE_READY; + + return DAL_OK; +} + +/** + * @} + */ + +/** + * @} + */ + +#endif /* DAL_RTC_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_sd.c b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_sd.c new file mode 100644 index 0000000000..e29941b005 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_sd.c @@ -0,0 +1,3302 @@ +/** + * + * @file apm32f4xx_dal_sd.c + * @brief SD card DAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the Secure Digital (SD) peripheral: + * + Initialization and de-initialization functions + * + IO operation functions + * + Peripheral Control functions + * + Peripheral State functions + * + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + * + @verbatim + ============================================================================== + ##### How to use this driver ##### + ============================================================================== + [..] + This driver implements a high level communication layer for read and write from/to + this memory. The needed APM32 hardware resources (SDIO and GPIO) are performed by + the user in DAL_SD_MspInit() function (MSP layer). + Basically, the MSP layer configuration should be the same as we provide in the + examples. + You can easily tailor this configuration according to hardware resources. + + [..] + This driver is a generic layered driver for SDIO memories which uses the DAL + SDIO driver functions to interface with SD and uSD cards devices. + It is used as follows: + + (#)Initialize the SDIO low level resources by implementing the DAL_SD_MspInit() API: + (##) Enable the SDIO interface clock using __DAL_RCM_SDIO_CLK_ENABLE(); + (##) SDIO pins configuration for SD card + (+++) Enable the clock for the SDIO GPIOs using the functions __DAL_RCM_GPIOx_CLK_ENABLE(); + (+++) Configure these SDIO pins as alternate function pull-up using DAL_GPIO_Init() + and according to your pin assignment; + (##) DMA configuration if you need to use DMA process (DAL_SD_ReadBlocks_DMA() + and DAL_SD_WriteBlocks_DMA() APIs). + (+++) Enable the DMAx interface clock using __DAL_RCM_DMAx_CLK_ENABLE(); + (+++) Configure the DMA using the function DAL_DMA_Init() with predeclared and filled. + (##) NVIC configuration if you need to use interrupt process when using DMA transfer. + (+++) Configure the SDIO and DMA interrupt priorities using functions + DAL_NVIC_SetPriority(); DMA priority is superior to SDIO's priority + (+++) Enable the NVIC DMA and SDIO IRQs using function DAL_NVIC_EnableIRQ() + (+++) SDIO interrupts are managed using the macros __DAL_SD_ENABLE_IT() + and __DAL_SD_DISABLE_IT() inside the communication process. + (+++) SDIO interrupts pending bits are managed using the macros __DAL_SD_GET_IT() + and __DAL_SD_CLEAR_IT() + (##) NVIC configuration if you need to use interrupt process (DAL_SD_ReadBlocks_IT() + and DAL_SD_WriteBlocks_IT() APIs). + (+++) Configure the SDIO interrupt priorities using function DAL_NVIC_SetPriority(); + (+++) Enable the NVIC SDIO IRQs using function DAL_NVIC_EnableIRQ() + (+++) SDIO interrupts are managed using the macros __DAL_SD_ENABLE_IT() + and __DAL_SD_DISABLE_IT() inside the communication process. + (+++) SDIO interrupts pending bits are managed using the macros __DAL_SD_GET_IT() + and __DAL_SD_CLEAR_IT() + (#) At this stage, you can perform SD read/write/erase operations after SD card initialization + + + *** SD Card Initialization and configuration *** + ================================================ + [..] + To initialize the SD Card, use the DAL_SD_Init() function. It Initializes + SDIO Peripheral(APM32 side) and the SD Card, and put it into StandBy State (Ready for data transfer). + This function provide the following operations: + + (#) Apply the SD Card initialization process at 400KHz and check the SD Card + type (Standard Capacity or High Capacity). You can change or adapt this + frequency by adjusting the "ClockDiv" field. + The SD Card frequency (SDIO_CK) is computed as follows: + + SDIO_CK = SDIOCLK / (ClockDiv + 2) + + In initialization mode and according to the SD Card standard, + make sure that the SDIO_CK frequency doesn't exceed 400KHz. + + This phase of initialization is done through SDIO_Init() and + SDIO_PowerState_ON() SDIO low level APIs. + + (#) Initialize the SD card. The API used is DAL_SD_InitCard(). + This phase allows the card initialization and identification + and check the SD Card type (Standard Capacity or High Capacity) + The initialization flow is compatible with SD standard. + + This API (DAL_SD_InitCard()) could be used also to reinitialize the card in case + of plug-off plug-in. + + (#) Configure the SD Card Data transfer frequency. You can change or adapt this + frequency by adjusting the "ClockDiv" field. + In transfer mode and according to the SD Card standard, make sure that the + SDIO_CK frequency doesn't exceed 25MHz and 50MHz in High-speed mode switch. + To be able to use a frequency higher than 24MHz, you should use the SDIO + peripheral in bypass mode. Refer to the corresponding reference manual + for more details. + + (#) Select the corresponding SD Card according to the address read with the step 2. + + (#) Configure the SD Card in wide bus mode: 4-bits data. + + *** SD Card Read operation *** + ============================== + [..] + (+) You can read from SD card in polling mode by using function DAL_SD_ReadBlocks(). + This function support only 512-bytes block length (the block size should be + chosen as 512 bytes). + You can choose either one block read operation or multiple block read operation + by adjusting the "NumberOfBlocks" parameter. + After this, you have to ensure that the transfer is done correctly. The check is done + through DAL_SD_GetCardState() function for SD card state. + + (+) You can read from SD card in DMA mode by using function DAL_SD_ReadBlocks_DMA(). + This function support only 512-bytes block length (the block size should be + chosen as 512 bytes). + You can choose either one block read operation or multiple block read operation + by adjusting the "NumberOfBlocks" parameter. + After this, you have to ensure that the transfer is done correctly. The check is done + through DAL_SD_GetCardState() function for SD card state. + You could also check the DMA transfer process through the SD Rx interrupt event. + + (+) You can read from SD card in Interrupt mode by using function DAL_SD_ReadBlocks_IT(). + This function support only 512-bytes block length (the block size should be + chosen as 512 bytes). + You can choose either one block read operation or multiple block read operation + by adjusting the "NumberOfBlocks" parameter. + After this, you have to ensure that the transfer is done correctly. The check is done + through DAL_SD_GetCardState() function for SD card state. + You could also check the IT transfer process through the SD Rx interrupt event. + + *** SD Card Write operation *** + =============================== + [..] + (+) You can write to SD card in polling mode by using function DAL_SD_WriteBlocks(). + This function support only 512-bytes block length (the block size should be + chosen as 512 bytes). + You can choose either one block read operation or multiple block read operation + by adjusting the "NumberOfBlocks" parameter. + After this, you have to ensure that the transfer is done correctly. The check is done + through DAL_SD_GetCardState() function for SD card state. + + (+) You can write to SD card in DMA mode by using function DAL_SD_WriteBlocks_DMA(). + This function support only 512-bytes block length (the block size should be + chosen as 512 bytes). + You can choose either one block read operation or multiple block read operation + by adjusting the "NumberOfBlocks" parameter. + After this, you have to ensure that the transfer is done correctly. The check is done + through DAL_SD_GetCardState() function for SD card state. + You could also check the DMA transfer process through the SD Tx interrupt event. + + (+) You can write to SD card in Interrupt mode by using function DAL_SD_WriteBlocks_IT(). + This function support only 512-bytes block length (the block size should be + chosen as 512 bytes). + You can choose either one block read operation or multiple block read operation + by adjusting the "NumberOfBlocks" parameter. + After this, you have to ensure that the transfer is done correctly. The check is done + through DAL_SD_GetCardState() function for SD card state. + You could also check the IT transfer process through the SD Tx interrupt event. + + *** SD card status *** + ====================== + [..] + (+) The SD Status contains status bits that are related to the SD Memory + Card proprietary features. To get SD card status use the DAL_SD_GetCardStatus(). + + *** SD card information *** + =========================== + [..] + (+) To get SD card information, you can use the function DAL_SD_GetCardInfo(). + It returns useful information about the SD card such as block size, card type, + block number ... + + *** SD card CSD register *** + ============================ + (+) The DAL_SD_GetCardCSD() API allows to get the parameters of the CSD register. + Some of the CSD parameters are useful for card initialization and identification. + + *** SD card CID register *** + ============================ + (+) The DAL_SD_GetCardCID() API allows to get the parameters of the CID register. + Some of the CSD parameters are useful for card initialization and identification. + + *** SD DAL driver macros list *** + ================================== + [..] + Below the list of most used macros in SD DAL driver. + + (+) __DAL_SD_ENABLE : Enable the SD device + (+) __DAL_SD_DISABLE : Disable the SD device + (+) __DAL_SD_DMA_ENABLE: Enable the SDIO DMA transfer + (+) __DAL_SD_DMA_DISABLE: Disable the SDIO DMA transfer + (+) __DAL_SD_ENABLE_IT: Enable the SD device interrupt + (+) __DAL_SD_DISABLE_IT: Disable the SD device interrupt + (+) __DAL_SD_GET_FLAG:Check whether the specified SD flag is set or not + (+) __DAL_SD_CLEAR_FLAG: Clear the SD's pending flags + + (@) You can refer to the SD DAL driver header file for more useful macros + + *** Callback registration *** + ============================================= + [..] + The compilation define USE_DAL_SD_REGISTER_CALLBACKS when set to 1 + allows the user to configure dynamically the driver callbacks. + + Use Functions DAL_SD_RegisterCallback() to register a user callback, + it allows to register following callbacks: + (+) TxCpltCallback : callback when a transmission transfer is completed. + (+) RxCpltCallback : callback when a reception transfer is completed. + (+) ErrorCallback : callback when error occurs. + (+) AbortCpltCallback : callback when abort is completed. + (+) MspInitCallback : SD MspInit. + (+) MspDeInitCallback : SD MspDeInit. + This function takes as parameters the DAL peripheral handle, the Callback ID + and a pointer to the user callback function. + + Use function DAL_SD_UnRegisterCallback() to reset a callback to the default + weak (surcharged) function. It allows to reset following callbacks: + (+) TxCpltCallback : callback when a transmission transfer is completed. + (+) RxCpltCallback : callback when a reception transfer is completed. + (+) ErrorCallback : callback when error occurs. + (+) AbortCpltCallback : callback when abort is completed. + (+) MspInitCallback : SD MspInit. + (+) MspDeInitCallback : SD MspDeInit. + This function) takes as parameters the DAL peripheral handle and the Callback ID. + + By default, after the DAL_SD_Init and if the state is DAL_SD_STATE_RESET + all callbacks are reset to the corresponding legacy weak (surcharged) functions. + Exception done for MspInit and MspDeInit callbacks that are respectively + reset to the legacy weak (surcharged) functions in the DAL_SD_Init + and DAL_SD_DeInit only when these callbacks are null (not registered beforehand). + If not, MspInit or MspDeInit are not null, the DAL_SD_Init and DAL_SD_DeInit + keep and use the user MspInit/MspDeInit callbacks (registered beforehand) + + Callbacks can be registered/unregistered in READY state only. + Exception done for MspInit/MspDeInit callbacks that can be registered/unregistered + in READY or RESET state, thus registered (user) MspInit/DeInit callbacks can be used + during the Init/DeInit. + In that case first register the MspInit/MspDeInit user callbacks + using DAL_SD_RegisterCallback before calling DAL_SD_DeInit + or DAL_SD_Init function. + + When The compilation define USE_DAL_SD_REGISTER_CALLBACKS is set to 0 or + not defined, the callback registering feature is not available + and weak (surcharged) callbacks are used. + + @endverbatim + * + */ + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal.h" + +#if defined(SDIO) + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @addtogroup SD + * @{ + */ + +#ifdef DAL_SD_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/** @addtogroup SD_Private_Defines + * @{ + */ + +/** + * @} + */ + +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ +/** @defgroup SD_Private_Functions SD Private Functions + * @{ + */ +static uint32_t SD_InitCard(SD_HandleTypeDef *hsd); +static uint32_t SD_PowerON(SD_HandleTypeDef *hsd); +static uint32_t SD_SendSDStatus(SD_HandleTypeDef *hsd, uint32_t *pSDstatus); +static uint32_t SD_SendStatus(SD_HandleTypeDef *hsd, uint32_t *pCardStatus); +static uint32_t SD_WideBus_Enable(SD_HandleTypeDef *hsd); +static uint32_t SD_WideBus_Disable(SD_HandleTypeDef *hsd); +static uint32_t SD_FindSCR(SD_HandleTypeDef *hsd, uint32_t *pSCR); +static void SD_PowerOFF(SD_HandleTypeDef *hsd); +static void SD_Write_IT(SD_HandleTypeDef *hsd); +static void SD_Read_IT(SD_HandleTypeDef *hsd); +static void SD_DMATransmitCplt(DMA_HandleTypeDef *hdma); +static void SD_DMAReceiveCplt(DMA_HandleTypeDef *hdma); +static void SD_DMAError(DMA_HandleTypeDef *hdma); +static void SD_DMATxAbort(DMA_HandleTypeDef *hdma); +static void SD_DMARxAbort(DMA_HandleTypeDef *hdma); +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup SD_Exported_Functions + * @{ + */ + +/** @addtogroup SD_Exported_Functions_Group1 + * @brief Initialization and de-initialization functions + * +@verbatim + ============================================================================== + ##### Initialization and de-initialization functions ##### + ============================================================================== + [..] + This section provides functions allowing to initialize/de-initialize the SD + card device to be ready for use. + +@endverbatim + * @{ + */ + +/** + * @brief Initializes the SD according to the specified parameters in the + SD_HandleTypeDef and create the associated handle. + * @param hsd: Pointer to the SD handle + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SD_Init(SD_HandleTypeDef *hsd) +{ + /* Check the SD handle allocation */ + if(hsd == NULL) + { + return DAL_ERROR; + } + + /* Check the parameters */ + ASSERT_PARAM(IS_SDIO_ALL_INSTANCE(hsd->Instance)); + ASSERT_PARAM(IS_SDIO_CLOCK_EDGE(hsd->Init.ClockEdge)); + ASSERT_PARAM(IS_SDIO_CLOCK_BYPASS(hsd->Init.ClockBypass)); + ASSERT_PARAM(IS_SDIO_CLOCK_POWER_SAVE(hsd->Init.ClockPowerSave)); + ASSERT_PARAM(IS_SDIO_BUS_WIDE(hsd->Init.BusWide)); + ASSERT_PARAM(IS_SDIO_HARDWARE_FLOW_CONTROL(hsd->Init.HardwareFlowControl)); + ASSERT_PARAM(IS_SDIO_CLKDIV(hsd->Init.ClockDiv)); + + if(hsd->State == DAL_SD_STATE_RESET) + { + /* Allocate lock resource and initialize it */ + hsd->Lock = DAL_UNLOCKED; +#if defined (USE_DAL_SD_REGISTER_CALLBACKS) && (USE_DAL_SD_REGISTER_CALLBACKS == 1U) + /* Reset Callback pointers in DAL_SD_STATE_RESET only */ + hsd->TxCpltCallback = DAL_SD_TxCpltCallback; + hsd->RxCpltCallback = DAL_SD_RxCpltCallback; + hsd->ErrorCallback = DAL_SD_ErrorCallback; + hsd->AbortCpltCallback = DAL_SD_AbortCallback; + + if(hsd->MspInitCallback == NULL) + { + hsd->MspInitCallback = DAL_SD_MspInit; + } + + /* Init the low level hardware */ + hsd->MspInitCallback(hsd); +#else + /* Init the low level hardware : GPIO, CLOCK, CORTEX...etc */ + DAL_SD_MspInit(hsd); +#endif /* USE_DAL_SD_REGISTER_CALLBACKS */ + } + + hsd->State = DAL_SD_STATE_BUSY; + + /* Initialize the Card parameters */ + if (DAL_SD_InitCard(hsd) != DAL_OK) + { + return DAL_ERROR; + } + + /* Initialize the error code */ + hsd->ErrorCode = DAL_SD_ERROR_NONE; + + /* Initialize the SD operation */ + hsd->Context = SD_CONTEXT_NONE; + + /* Initialize the SD state */ + hsd->State = DAL_SD_STATE_READY; + + return DAL_OK; +} + +/** + * @brief Initializes the SD Card. + * @param hsd: Pointer to SD handle + * @note This function initializes the SD card. It could be used when a card + re-initialization is needed. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SD_InitCard(SD_HandleTypeDef *hsd) +{ + uint32_t errorstate; + DAL_StatusTypeDef status; + SD_InitTypeDef Init; + + /* Default SDIO peripheral configuration for SD card initialization */ + Init.ClockEdge = SDIO_CLOCK_EDGE_RISING; + Init.ClockBypass = SDIO_CLOCK_BYPASS_DISABLE; + Init.ClockPowerSave = SDIO_CLOCK_POWER_SAVE_DISABLE; + Init.BusWide = SDIO_BUS_WIDE_1B; + Init.HardwareFlowControl = SDIO_HARDWARE_FLOW_CONTROL_DISABLE; + Init.ClockDiv = SDIO_INIT_CLK_DIV; + + /* Initialize SDIO peripheral interface with default configuration */ + status = SDIO_Init(hsd->Instance, Init); + if(status != DAL_OK) + { + return DAL_ERROR; + } + + /* Disable SDIO Clock */ + __DAL_SD_DISABLE(hsd); + + /* Set Power State to ON */ + (void)SDIO_PowerState_ON(hsd->Instance); + + /* Enable SDIO Clock */ + __DAL_SD_ENABLE(hsd); + + /* Required power up waiting time before starting the SD initialization sequence */ + DAL_Delay(2); + + /* Identify card operating voltage */ + errorstate = SD_PowerON(hsd); + if(errorstate != DAL_SD_ERROR_NONE) + { + hsd->State = DAL_SD_STATE_READY; + hsd->ErrorCode |= errorstate; + return DAL_ERROR; + } + + /* Card initialization */ + errorstate = SD_InitCard(hsd); + if(errorstate != DAL_SD_ERROR_NONE) + { + hsd->State = DAL_SD_STATE_READY; + hsd->ErrorCode |= errorstate; + return DAL_ERROR; + } + + /* Set Block Size for Card */ + errorstate = SDMMC_CmdBlockLength(hsd->Instance, BLOCKSIZE); + if(errorstate != DAL_SD_ERROR_NONE) + { + /* Clear all the static flags */ + __DAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); + hsd->ErrorCode |= errorstate; + hsd->State = DAL_SD_STATE_READY; + return DAL_ERROR; + } + + return DAL_OK; +} + +/** + * @brief De-Initializes the SD card. + * @param hsd: Pointer to SD handle + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SD_DeInit(SD_HandleTypeDef *hsd) +{ + /* Check the SD handle allocation */ + if(hsd == NULL) + { + return DAL_ERROR; + } + + /* Check the parameters */ + ASSERT_PARAM(IS_SDIO_ALL_INSTANCE(hsd->Instance)); + + hsd->State = DAL_SD_STATE_BUSY; + + /* Set SD power state to off */ + SD_PowerOFF(hsd); + +#if defined (USE_DAL_SD_REGISTER_CALLBACKS) && (USE_DAL_SD_REGISTER_CALLBACKS == 1U) + if(hsd->MspDeInitCallback == NULL) + { + hsd->MspDeInitCallback = DAL_SD_MspDeInit; + } + + /* DeInit the low level hardware */ + hsd->MspDeInitCallback(hsd); +#else + /* De-Initialize the MSP layer */ + DAL_SD_MspDeInit(hsd); +#endif /* USE_DAL_SD_REGISTER_CALLBACKS */ + + hsd->ErrorCode = DAL_SD_ERROR_NONE; + hsd->State = DAL_SD_STATE_RESET; + + return DAL_OK; +} + + +/** + * @brief Initializes the SD MSP. + * @param hsd: Pointer to SD handle + * @retval None + */ +__weak void DAL_SD_MspInit(SD_HandleTypeDef *hsd) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hsd); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_SD_MspInit could be implemented in the user file + */ +} + +/** + * @brief De-Initialize SD MSP. + * @param hsd: Pointer to SD handle + * @retval None + */ +__weak void DAL_SD_MspDeInit(SD_HandleTypeDef *hsd) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hsd); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_SD_MspDeInit could be implemented in the user file + */ +} + +/** + * @} + */ + +/** @addtogroup SD_Exported_Functions_Group2 + * @brief Data transfer functions + * +@verbatim + ============================================================================== + ##### IO operation functions ##### + ============================================================================== + [..] + This subsection provides a set of functions allowing to manage the data + transfer from/to SD card. + +@endverbatim + * @{ + */ + +/** + * @brief Reads block(s) from a specified address in a card. The Data transfer + * is managed by polling mode. + * @note This API should be followed by a check on the card state through + * DAL_SD_GetCardState(). + * @param hsd: Pointer to SD handle + * @param pData: pointer to the buffer that will contain the received data + * @param BlockAdd: Block Address from where data is to be read + * @param NumberOfBlocks: Number of SD blocks to read + * @param Timeout: Specify timeout value + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SD_ReadBlocks(SD_HandleTypeDef *hsd, uint8_t *pData, uint32_t BlockAdd, uint32_t NumberOfBlocks, uint32_t Timeout) +{ + SDIO_DataInitTypeDef config; + uint32_t errorstate; + uint32_t tickstart = DAL_GetTick(); + uint32_t count, data, dataremaining; + uint32_t add = BlockAdd; + uint8_t *tempbuff = pData; + + if(NULL == pData) + { + hsd->ErrorCode |= DAL_SD_ERROR_PARAM; + return DAL_ERROR; + } + + if(hsd->State == DAL_SD_STATE_READY) + { + hsd->ErrorCode = DAL_SD_ERROR_NONE; + + if((add + NumberOfBlocks) > (hsd->SdCard.LogBlockNbr)) + { + hsd->ErrorCode |= DAL_SD_ERROR_ADDR_OUT_OF_RANGE; + return DAL_ERROR; + } + + hsd->State = DAL_SD_STATE_BUSY; + + /* Initialize data control register */ + hsd->Instance->DCTRL = 0U; + + if(hsd->SdCard.CardType != CARD_SDHC_SDXC) + { + add *= 512U; + } + + /* Configure the SD DPSM (Data Path State Machine) */ + config.DataTimeOut = SDMMC_DATATIMEOUT; + config.DataLength = NumberOfBlocks * BLOCKSIZE; + config.DataBlockSize = SDIO_DATABLOCK_SIZE_512B; + config.TransferDir = SDIO_TRANSFER_DIR_TO_SDIO; + config.TransferMode = SDIO_TRANSFER_MODE_BLOCK; + config.DPSM = SDIO_DPSM_ENABLE; + (void)SDIO_ConfigData(hsd->Instance, &config); + + /* Read block(s) in polling mode */ + if(NumberOfBlocks > 1U) + { + hsd->Context = SD_CONTEXT_READ_MULTIPLE_BLOCK; + + /* Read Multi Block command */ + errorstate = SDMMC_CmdReadMultiBlock(hsd->Instance, add); + } + else + { + hsd->Context = SD_CONTEXT_READ_SINGLE_BLOCK; + + /* Read Single Block command */ + errorstate = SDMMC_CmdReadSingleBlock(hsd->Instance, add); + } + if(errorstate != DAL_SD_ERROR_NONE) + { + /* Clear all the static flags */ + __DAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); + hsd->ErrorCode |= errorstate; + hsd->State = DAL_SD_STATE_READY; + hsd->Context = SD_CONTEXT_NONE; + return DAL_ERROR; + } + + /* Poll on SDIO flags */ + dataremaining = config.DataLength; +#if defined(SDIO_STS_SBE) + while(!__DAL_SD_GET_FLAG(hsd, SDIO_FLAG_RXOVERR | SDIO_FLAG_DCRCFAIL | SDIO_FLAG_DTIMEOUT | SDIO_FLAG_DATAEND | SDIO_FLAG_STBITERR)) +#else /* SDIO_STS_SBE not defined */ + while(!__DAL_SD_GET_FLAG(hsd, SDIO_FLAG_RXOVERR | SDIO_FLAG_DCRCFAIL | SDIO_FLAG_DTIMEOUT | SDIO_FLAG_DATAEND)) +#endif /* SDIO_STS_SBE */ + { + if(__DAL_SD_GET_FLAG(hsd, SDIO_FLAG_RXFIFOHF) && (dataremaining > 0U)) + { + /* Read data from SDIO Rx FIFO */ + for(count = 0U; count < 8U; count++) + { + data = SDIO_ReadFIFO(hsd->Instance); + *tempbuff = (uint8_t)(data & 0xFFU); + tempbuff++; + dataremaining--; + *tempbuff = (uint8_t)((data >> 8U) & 0xFFU); + tempbuff++; + dataremaining--; + *tempbuff = (uint8_t)((data >> 16U) & 0xFFU); + tempbuff++; + dataremaining--; + *tempbuff = (uint8_t)((data >> 24U) & 0xFFU); + tempbuff++; + dataremaining--; + } + } + + if(((DAL_GetTick()-tickstart) >= Timeout) || (Timeout == 0U)) + { + /* Clear all the static flags */ + __DAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); + hsd->ErrorCode |= DAL_SD_ERROR_TIMEOUT; + hsd->State= DAL_SD_STATE_READY; + hsd->Context = SD_CONTEXT_NONE; + return DAL_TIMEOUT; + } + } + + /* Send stop transmission command in case of multiblock read */ + if(__DAL_SD_GET_FLAG(hsd, SDIO_FLAG_DATAEND) && (NumberOfBlocks > 1U)) + { + if(hsd->SdCard.CardType != CARD_SECURED) + { + /* Send stop transmission command */ + errorstate = SDMMC_CmdStopTransfer(hsd->Instance); + if(errorstate != DAL_SD_ERROR_NONE) + { + /* Clear all the static flags */ + __DAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); + hsd->ErrorCode |= errorstate; + hsd->State = DAL_SD_STATE_READY; + hsd->Context = SD_CONTEXT_NONE; + return DAL_ERROR; + } + } + } + + /* Get error state */ + if(__DAL_SD_GET_FLAG(hsd, SDIO_FLAG_DTIMEOUT)) + { + /* Clear all the static flags */ + __DAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); + hsd->ErrorCode |= DAL_SD_ERROR_DATA_TIMEOUT; + hsd->State = DAL_SD_STATE_READY; + hsd->Context = SD_CONTEXT_NONE; + return DAL_ERROR; + } + else if(__DAL_SD_GET_FLAG(hsd, SDIO_FLAG_DCRCFAIL)) + { + /* Clear all the static flags */ + __DAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); + hsd->ErrorCode |= DAL_SD_ERROR_DATA_CRC_FAIL; + hsd->State = DAL_SD_STATE_READY; + hsd->Context = SD_CONTEXT_NONE; + return DAL_ERROR; + } + else if(__DAL_SD_GET_FLAG(hsd, SDIO_FLAG_RXOVERR)) + { + /* Clear all the static flags */ + __DAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); + hsd->ErrorCode |= DAL_SD_ERROR_RX_OVERRUN; + hsd->State = DAL_SD_STATE_READY; + hsd->Context = SD_CONTEXT_NONE; + return DAL_ERROR; + } + else + { + /* Nothing to do */ + } + + /* Empty FIFO if there is still any data */ + while ((__DAL_SD_GET_FLAG(hsd, SDIO_FLAG_RXDAVL)) && (dataremaining > 0U)) + { + data = SDIO_ReadFIFO(hsd->Instance); + *tempbuff = (uint8_t)(data & 0xFFU); + tempbuff++; + dataremaining--; + *tempbuff = (uint8_t)((data >> 8U) & 0xFFU); + tempbuff++; + dataremaining--; + *tempbuff = (uint8_t)((data >> 16U) & 0xFFU); + tempbuff++; + dataremaining--; + *tempbuff = (uint8_t)((data >> 24U) & 0xFFU); + tempbuff++; + dataremaining--; + + if(((DAL_GetTick()-tickstart) >= Timeout) || (Timeout == 0U)) + { + /* Clear all the static flags */ + __DAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); + hsd->ErrorCode |= DAL_SD_ERROR_TIMEOUT; + hsd->State= DAL_SD_STATE_READY; + hsd->Context = SD_CONTEXT_NONE; + return DAL_ERROR; + } + } + + /* Clear all the static flags */ + __DAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_DATA_FLAGS); + + hsd->State = DAL_SD_STATE_READY; + + return DAL_OK; + } + else + { + hsd->ErrorCode |= DAL_SD_ERROR_BUSY; + return DAL_ERROR; + } +} + +/** + * @brief Allows to write block(s) to a specified address in a card. The Data + * transfer is managed by polling mode. + * @note This API should be followed by a check on the card state through + * DAL_SD_GetCardState(). + * @param hsd: Pointer to SD handle + * @param pData: pointer to the buffer that will contain the data to transmit + * @param BlockAdd: Block Address where data will be written + * @param NumberOfBlocks: Number of SD blocks to write + * @param Timeout: Specify timeout value + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SD_WriteBlocks(SD_HandleTypeDef *hsd, uint8_t *pData, uint32_t BlockAdd, uint32_t NumberOfBlocks, uint32_t Timeout) +{ + SDIO_DataInitTypeDef config; + uint32_t errorstate; + uint32_t tickstart = DAL_GetTick(); + uint32_t count, data, dataremaining; + uint32_t add = BlockAdd; + uint8_t *tempbuff = pData; + + if(NULL == pData) + { + hsd->ErrorCode |= DAL_SD_ERROR_PARAM; + return DAL_ERROR; + } + + if(hsd->State == DAL_SD_STATE_READY) + { + hsd->ErrorCode = DAL_SD_ERROR_NONE; + + if((add + NumberOfBlocks) > (hsd->SdCard.LogBlockNbr)) + { + hsd->ErrorCode |= DAL_SD_ERROR_ADDR_OUT_OF_RANGE; + return DAL_ERROR; + } + + hsd->State = DAL_SD_STATE_BUSY; + + /* Initialize data control register */ + hsd->Instance->DCTRL = 0U; + + if(hsd->SdCard.CardType != CARD_SDHC_SDXC) + { + add *= 512U; + } + + /* Configure the SD DPSM (Data Path State Machine) */ + config.DataTimeOut = SDMMC_DATATIMEOUT; + config.DataLength = NumberOfBlocks * BLOCKSIZE; + config.DataBlockSize = SDIO_DATABLOCK_SIZE_512B; + config.TransferDir = SDIO_TRANSFER_DIR_TO_CARD; + config.TransferMode = SDIO_TRANSFER_MODE_BLOCK; + config.DPSM = SDIO_DPSM_ENABLE; + (void)SDIO_ConfigData(hsd->Instance, &config); + + /* Write Blocks in Polling mode */ + if(NumberOfBlocks > 1U) + { + hsd->Context = SD_CONTEXT_WRITE_MULTIPLE_BLOCK; + + /* Write Multi Block command */ + errorstate = SDMMC_CmdWriteMultiBlock(hsd->Instance, add); + } + else + { + hsd->Context = SD_CONTEXT_WRITE_SINGLE_BLOCK; + + /* Write Single Block command */ + errorstate = SDMMC_CmdWriteSingleBlock(hsd->Instance, add); + } + if(errorstate != DAL_SD_ERROR_NONE) + { + /* Clear all the static flags */ + __DAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); + hsd->ErrorCode |= errorstate; + hsd->State = DAL_SD_STATE_READY; + hsd->Context = SD_CONTEXT_NONE; + return DAL_ERROR; + } + + /* Write block(s) in polling mode */ + dataremaining = config.DataLength; +#if defined(SDIO_STS_SBE) + while(!__DAL_SD_GET_FLAG(hsd, SDIO_FLAG_TXUNDERR | SDIO_FLAG_DCRCFAIL | SDIO_FLAG_DTIMEOUT | SDIO_FLAG_DATAEND | SDIO_FLAG_STBITERR)) +#else /* SDIO_STS_SBE not defined */ + while(!__DAL_SD_GET_FLAG(hsd, SDIO_FLAG_TXUNDERR | SDIO_FLAG_DCRCFAIL | SDIO_FLAG_DTIMEOUT | SDIO_FLAG_DATAEND)) +#endif /* SDIO_STS_SBE */ + { + if(__DAL_SD_GET_FLAG(hsd, SDIO_FLAG_TXFIFOHE) && (dataremaining > 0U)) + { + /* Write data to SDIO Tx FIFO */ + for(count = 0U; count < 8U; count++) + { + data = (uint32_t)(*tempbuff); + tempbuff++; + dataremaining--; + data |= ((uint32_t)(*tempbuff) << 8U); + tempbuff++; + dataremaining--; + data |= ((uint32_t)(*tempbuff) << 16U); + tempbuff++; + dataremaining--; + data |= ((uint32_t)(*tempbuff) << 24U); + tempbuff++; + dataremaining--; + (void)SDIO_WriteFIFO(hsd->Instance, &data); + } + } + + if(((DAL_GetTick()-tickstart) >= Timeout) || (Timeout == 0U)) + { + /* Clear all the static flags */ + __DAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); + hsd->ErrorCode |= errorstate; + hsd->State = DAL_SD_STATE_READY; + hsd->Context = SD_CONTEXT_NONE; + return DAL_TIMEOUT; + } + } + + /* Send stop transmission command in case of multiblock write */ + if(__DAL_SD_GET_FLAG(hsd, SDIO_FLAG_DATAEND) && (NumberOfBlocks > 1U)) + { + if(hsd->SdCard.CardType != CARD_SECURED) + { + /* Send stop transmission command */ + errorstate = SDMMC_CmdStopTransfer(hsd->Instance); + if(errorstate != DAL_SD_ERROR_NONE) + { + /* Clear all the static flags */ + __DAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); + hsd->ErrorCode |= errorstate; + hsd->State = DAL_SD_STATE_READY; + hsd->Context = SD_CONTEXT_NONE; + return DAL_ERROR; + } + } + } + + /* Get error state */ + if(__DAL_SD_GET_FLAG(hsd, SDIO_FLAG_DTIMEOUT)) + { + /* Clear all the static flags */ + __DAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); + hsd->ErrorCode |= DAL_SD_ERROR_DATA_TIMEOUT; + hsd->State = DAL_SD_STATE_READY; + hsd->Context = SD_CONTEXT_NONE; + return DAL_ERROR; + } + else if(__DAL_SD_GET_FLAG(hsd, SDIO_FLAG_DCRCFAIL)) + { + /* Clear all the static flags */ + __DAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); + hsd->ErrorCode |= DAL_SD_ERROR_DATA_CRC_FAIL; + hsd->State = DAL_SD_STATE_READY; + hsd->Context = SD_CONTEXT_NONE; + return DAL_ERROR; + } + else if(__DAL_SD_GET_FLAG(hsd, SDIO_FLAG_TXUNDERR)) + { + /* Clear all the static flags */ + __DAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); + hsd->ErrorCode |= DAL_SD_ERROR_TX_UNDERRUN; + hsd->State = DAL_SD_STATE_READY; + hsd->Context = SD_CONTEXT_NONE; + return DAL_ERROR; + } + else + { + /* Nothing to do */ + } + + /* Clear all the static flags */ + __DAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_DATA_FLAGS); + + hsd->State = DAL_SD_STATE_READY; + + return DAL_OK; + } + else + { + hsd->ErrorCode |= DAL_SD_ERROR_BUSY; + return DAL_ERROR; + } +} + +/** + * @brief Reads block(s) from a specified address in a card. The Data transfer + * is managed in interrupt mode. + * @note This API should be followed by a check on the card state through + * DAL_SD_GetCardState(). + * @note You could also check the IT transfer process through the SD Rx + * interrupt event. + * @param hsd: Pointer to SD handle + * @param pData: Pointer to the buffer that will contain the received data + * @param BlockAdd: Block Address from where data is to be read + * @param NumberOfBlocks: Number of blocks to read. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SD_ReadBlocks_IT(SD_HandleTypeDef *hsd, uint8_t *pData, uint32_t BlockAdd, uint32_t NumberOfBlocks) +{ + SDIO_DataInitTypeDef config; + uint32_t errorstate; + uint32_t add = BlockAdd; + + if(NULL == pData) + { + hsd->ErrorCode |= DAL_SD_ERROR_PARAM; + return DAL_ERROR; + } + + if(hsd->State == DAL_SD_STATE_READY) + { + hsd->ErrorCode = DAL_SD_ERROR_NONE; + + if((add + NumberOfBlocks) > (hsd->SdCard.LogBlockNbr)) + { + hsd->ErrorCode |= DAL_SD_ERROR_ADDR_OUT_OF_RANGE; + return DAL_ERROR; + } + + hsd->State = DAL_SD_STATE_BUSY; + + /* Initialize data control register */ + hsd->Instance->DCTRL = 0U; + + hsd->pRxBuffPtr = pData; + hsd->RxXferSize = BLOCKSIZE * NumberOfBlocks; + +#if defined(SDIO_STS_SBE) + __DAL_SD_ENABLE_IT(hsd, (SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT | SDIO_IT_RXOVERR | SDIO_IT_DATAEND | SDIO_FLAG_RXFIFOHF | SDIO_IT_STBITERR)); +#else /* SDIO_STS_SBE not defined */ + __DAL_SD_ENABLE_IT(hsd, (SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT | SDIO_IT_RXOVERR | SDIO_IT_DATAEND | SDIO_FLAG_RXFIFOHF)); +#endif /* SDIO_STS_SBE */ + + if(hsd->SdCard.CardType != CARD_SDHC_SDXC) + { + add *= 512U; + } + + /* Configure the SD DPSM (Data Path State Machine) */ + config.DataTimeOut = SDMMC_DATATIMEOUT; + config.DataLength = BLOCKSIZE * NumberOfBlocks; + config.DataBlockSize = SDIO_DATABLOCK_SIZE_512B; + config.TransferDir = SDIO_TRANSFER_DIR_TO_SDIO; + config.TransferMode = SDIO_TRANSFER_MODE_BLOCK; + config.DPSM = SDIO_DPSM_ENABLE; + (void)SDIO_ConfigData(hsd->Instance, &config); + + /* Read Blocks in IT mode */ + if(NumberOfBlocks > 1U) + { + hsd->Context = (SD_CONTEXT_READ_MULTIPLE_BLOCK | SD_CONTEXT_IT); + + /* Read Multi Block command */ + errorstate = SDMMC_CmdReadMultiBlock(hsd->Instance, add); + } + else + { + hsd->Context = (SD_CONTEXT_READ_SINGLE_BLOCK | SD_CONTEXT_IT); + + /* Read Single Block command */ + errorstate = SDMMC_CmdReadSingleBlock(hsd->Instance, add); + } + if(errorstate != DAL_SD_ERROR_NONE) + { + /* Clear all the static flags */ + __DAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); + hsd->ErrorCode |= errorstate; + hsd->State = DAL_SD_STATE_READY; + hsd->Context = SD_CONTEXT_NONE; + return DAL_ERROR; + } + + return DAL_OK; + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief Writes block(s) to a specified address in a card. The Data transfer + * is managed in interrupt mode. + * @note This API should be followed by a check on the card state through + * DAL_SD_GetCardState(). + * @note You could also check the IT transfer process through the SD Tx + * interrupt event. + * @param hsd: Pointer to SD handle + * @param pData: Pointer to the buffer that will contain the data to transmit + * @param BlockAdd: Block Address where data will be written + * @param NumberOfBlocks: Number of blocks to write + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SD_WriteBlocks_IT(SD_HandleTypeDef *hsd, uint8_t *pData, uint32_t BlockAdd, uint32_t NumberOfBlocks) +{ + SDIO_DataInitTypeDef config; + uint32_t errorstate; + uint32_t add = BlockAdd; + + if(NULL == pData) + { + hsd->ErrorCode |= DAL_SD_ERROR_PARAM; + return DAL_ERROR; + } + + if(hsd->State == DAL_SD_STATE_READY) + { + hsd->ErrorCode = DAL_SD_ERROR_NONE; + + if((add + NumberOfBlocks) > (hsd->SdCard.LogBlockNbr)) + { + hsd->ErrorCode |= DAL_SD_ERROR_ADDR_OUT_OF_RANGE; + return DAL_ERROR; + } + + hsd->State = DAL_SD_STATE_BUSY; + + /* Initialize data control register */ + hsd->Instance->DCTRL = 0U; + + hsd->pTxBuffPtr = pData; + hsd->TxXferSize = BLOCKSIZE * NumberOfBlocks; + + /* Enable transfer interrupts */ +#if defined(SDIO_STS_SBE) + __DAL_SD_ENABLE_IT(hsd, (SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT | SDIO_IT_TXUNDERR | SDIO_IT_DATAEND | SDIO_FLAG_TXFIFOHE | SDIO_IT_STBITERR)); +#else /* SDIO_STS_SBE not defined */ + __DAL_SD_ENABLE_IT(hsd, (SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT | SDIO_IT_TXUNDERR | SDIO_IT_DATAEND | SDIO_FLAG_TXFIFOHE)); +#endif /* SDIO_STS_SBE */ + + if(hsd->SdCard.CardType != CARD_SDHC_SDXC) + { + add *= 512U; + } + + /* Write Blocks in Polling mode */ + if(NumberOfBlocks > 1U) + { + hsd->Context = (SD_CONTEXT_WRITE_MULTIPLE_BLOCK| SD_CONTEXT_IT); + + /* Write Multi Block command */ + errorstate = SDMMC_CmdWriteMultiBlock(hsd->Instance, add); + } + else + { + hsd->Context = (SD_CONTEXT_WRITE_SINGLE_BLOCK | SD_CONTEXT_IT); + + /* Write Single Block command */ + errorstate = SDMMC_CmdWriteSingleBlock(hsd->Instance, add); + } + if(errorstate != DAL_SD_ERROR_NONE) + { + /* Clear all the static flags */ + __DAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); + hsd->ErrorCode |= errorstate; + hsd->State = DAL_SD_STATE_READY; + hsd->Context = SD_CONTEXT_NONE; + return DAL_ERROR; + } + + /* Configure the SD DPSM (Data Path State Machine) */ + config.DataTimeOut = SDMMC_DATATIMEOUT; + config.DataLength = BLOCKSIZE * NumberOfBlocks; + config.DataBlockSize = SDIO_DATABLOCK_SIZE_512B; + config.TransferDir = SDIO_TRANSFER_DIR_TO_CARD; + config.TransferMode = SDIO_TRANSFER_MODE_BLOCK; + config.DPSM = SDIO_DPSM_ENABLE; + (void)SDIO_ConfigData(hsd->Instance, &config); + + return DAL_OK; + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief Reads block(s) from a specified address in a card. The Data transfer + * is managed by DMA mode. + * @note This API should be followed by a check on the card state through + * DAL_SD_GetCardState(). + * @note You could also check the DMA transfer process through the SD Rx + * interrupt event. + * @param hsd: Pointer SD handle + * @param pData: Pointer to the buffer that will contain the received data + * @param BlockAdd: Block Address from where data is to be read + * @param NumberOfBlocks: Number of blocks to read. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SD_ReadBlocks_DMA(SD_HandleTypeDef *hsd, uint8_t *pData, uint32_t BlockAdd, uint32_t NumberOfBlocks) +{ + SDIO_DataInitTypeDef config; + uint32_t errorstate; + uint32_t add = BlockAdd; + + if(NULL == pData) + { + hsd->ErrorCode |= DAL_SD_ERROR_PARAM; + return DAL_ERROR; + } + + if(hsd->State == DAL_SD_STATE_READY) + { + hsd->ErrorCode = DAL_SD_ERROR_NONE; + + if((add + NumberOfBlocks) > (hsd->SdCard.LogBlockNbr)) + { + hsd->ErrorCode |= DAL_SD_ERROR_ADDR_OUT_OF_RANGE; + return DAL_ERROR; + } + + hsd->State = DAL_SD_STATE_BUSY; + + /* Initialize data control register */ + hsd->Instance->DCTRL = 0U; + +#if defined(SDIO_STS_SBE) + __DAL_SD_ENABLE_IT(hsd, (SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT | SDIO_IT_RXOVERR | SDIO_IT_DATAEND | SDIO_IT_STBITERR)); +#else /* SDIO_STS_SBE not defined */ + __DAL_SD_ENABLE_IT(hsd, (SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT | SDIO_IT_RXOVERR | SDIO_IT_DATAEND)); +#endif /* SDIO_STS_SBE */ + + /* Set the DMA transfer complete callback */ + hsd->hdmarx->XferCpltCallback = SD_DMAReceiveCplt; + + /* Set the DMA error callback */ + hsd->hdmarx->XferErrorCallback = SD_DMAError; + + /* Set the DMA Abort callback */ + hsd->hdmarx->XferAbortCallback = NULL; + + /* Force DMA Direction */ + hsd->hdmarx->Init.Direction = DMA_PERIPH_TO_MEMORY; + MODIFY_REG(hsd->hdmarx->Instance->SCFG, DMA_SCFGx_DIRCFG, hsd->hdmarx->Init.Direction); + + /* Enable the DMA Channel */ + if(DAL_DMA_Start_IT(hsd->hdmarx, (uint32_t)&hsd->Instance->FIFODATA, (uint32_t)pData, (uint32_t)(BLOCKSIZE * NumberOfBlocks)/4U) != DAL_OK) + { + __DAL_SD_DISABLE_IT(hsd, (SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT | SDIO_IT_RXOVERR | SDIO_IT_DATAEND)); + __DAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); + hsd->ErrorCode |= DAL_SD_ERROR_DMA; + hsd->State = DAL_SD_STATE_READY; + return DAL_ERROR; + } + else + { + /* Enable SD DMA transfer */ + __DAL_SD_DMA_ENABLE(hsd); + + if(hsd->SdCard.CardType != CARD_SDHC_SDXC) + { + add *= 512U; + } + + /* Configure the SD DPSM (Data Path State Machine) */ + config.DataTimeOut = SDMMC_DATATIMEOUT; + config.DataLength = BLOCKSIZE * NumberOfBlocks; + config.DataBlockSize = SDIO_DATABLOCK_SIZE_512B; + config.TransferDir = SDIO_TRANSFER_DIR_TO_SDIO; + config.TransferMode = SDIO_TRANSFER_MODE_BLOCK; + config.DPSM = SDIO_DPSM_ENABLE; + (void)SDIO_ConfigData(hsd->Instance, &config); + + /* Read Blocks in DMA mode */ + if(NumberOfBlocks > 1U) + { + hsd->Context = (SD_CONTEXT_READ_MULTIPLE_BLOCK | SD_CONTEXT_DMA); + + /* Read Multi Block command */ + errorstate = SDMMC_CmdReadMultiBlock(hsd->Instance, add); + } + else + { + hsd->Context = (SD_CONTEXT_READ_SINGLE_BLOCK | SD_CONTEXT_DMA); + + /* Read Single Block command */ + errorstate = SDMMC_CmdReadSingleBlock(hsd->Instance, add); + } + if(errorstate != DAL_SD_ERROR_NONE) + { + /* Clear all the static flags */ + __DAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); + hsd->ErrorCode |= errorstate; + hsd->State = DAL_SD_STATE_READY; + hsd->Context = SD_CONTEXT_NONE; + return DAL_ERROR; + } + + return DAL_OK; + } + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief Writes block(s) to a specified address in a card. The Data transfer + * is managed by DMA mode. + * @note This API should be followed by a check on the card state through + * DAL_SD_GetCardState(). + * @note You could also check the DMA transfer process through the SD Tx + * interrupt event. + * @param hsd: Pointer to SD handle + * @param pData: Pointer to the buffer that will contain the data to transmit + * @param BlockAdd: Block Address where data will be written + * @param NumberOfBlocks: Number of blocks to write + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SD_WriteBlocks_DMA(SD_HandleTypeDef *hsd, uint8_t *pData, uint32_t BlockAdd, uint32_t NumberOfBlocks) +{ + SDIO_DataInitTypeDef config; + uint32_t errorstate; + uint32_t add = BlockAdd; + + if(NULL == pData) + { + hsd->ErrorCode |= DAL_SD_ERROR_PARAM; + return DAL_ERROR; + } + + if(hsd->State == DAL_SD_STATE_READY) + { + hsd->ErrorCode = DAL_SD_ERROR_NONE; + + if((add + NumberOfBlocks) > (hsd->SdCard.LogBlockNbr)) + { + hsd->ErrorCode |= DAL_SD_ERROR_ADDR_OUT_OF_RANGE; + return DAL_ERROR; + } + + hsd->State = DAL_SD_STATE_BUSY; + + /* Initialize data control register */ + hsd->Instance->DCTRL = 0U; + + /* Enable SD Error interrupts */ +#if defined(SDIO_STS_SBE) + __DAL_SD_ENABLE_IT(hsd, (SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT | SDIO_IT_TXUNDERR | SDIO_IT_STBITERR)); +#else /* SDIO_STS_SBE not defined */ + __DAL_SD_ENABLE_IT(hsd, (SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT | SDIO_IT_TXUNDERR)); +#endif /* SDIO_STS_SBE */ + + /* Set the DMA transfer complete callback */ + hsd->hdmatx->XferCpltCallback = SD_DMATransmitCplt; + + /* Set the DMA error callback */ + hsd->hdmatx->XferErrorCallback = SD_DMAError; + + /* Set the DMA Abort callback */ + hsd->hdmatx->XferAbortCallback = NULL; + + if(hsd->SdCard.CardType != CARD_SDHC_SDXC) + { + add *= 512U; + } + + /* Write Blocks in Polling mode */ + if(NumberOfBlocks > 1U) + { + hsd->Context = (SD_CONTEXT_WRITE_MULTIPLE_BLOCK | SD_CONTEXT_DMA); + + /* Write Multi Block command */ + errorstate = SDMMC_CmdWriteMultiBlock(hsd->Instance, add); + } + else + { + hsd->Context = (SD_CONTEXT_WRITE_SINGLE_BLOCK | SD_CONTEXT_DMA); + + /* Write Single Block command */ + errorstate = SDMMC_CmdWriteSingleBlock(hsd->Instance, add); + } + if(errorstate != DAL_SD_ERROR_NONE) + { + /* Clear all the static flags */ + __DAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); + hsd->ErrorCode |= errorstate; + hsd->State = DAL_SD_STATE_READY; + hsd->Context = SD_CONTEXT_NONE; + return DAL_ERROR; + } + + /* Enable SDIO DMA transfer */ + __DAL_SD_DMA_ENABLE(hsd); + + /* Force DMA Direction */ + hsd->hdmatx->Init.Direction = DMA_MEMORY_TO_PERIPH; + MODIFY_REG(hsd->hdmatx->Instance->SCFG, DMA_SCFGx_DIRCFG, hsd->hdmatx->Init.Direction); + + /* Enable the DMA Channel */ + if(DAL_DMA_Start_IT(hsd->hdmatx, (uint32_t)pData, (uint32_t)&hsd->Instance->FIFODATA, (uint32_t)(BLOCKSIZE * NumberOfBlocks)/4U) != DAL_OK) + { +#if defined(SDIO_STS_SBE) + __DAL_SD_DISABLE_IT(hsd, (SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT | SDIO_IT_TXUNDERR | SDIO_IT_STBITERR)); +#else /* SDIO_STS_SBE not defined */ + __DAL_SD_DISABLE_IT(hsd, (SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT | SDIO_IT_TXUNDERR)); +#endif /* SDIO_STS_SBE */ + __DAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); + hsd->ErrorCode |= DAL_SD_ERROR_DMA; + hsd->State = DAL_SD_STATE_READY; + hsd->Context = SD_CONTEXT_NONE; + return DAL_ERROR; + } + else + { + /* Configure the SD DPSM (Data Path State Machine) */ + config.DataTimeOut = SDMMC_DATATIMEOUT; + config.DataLength = BLOCKSIZE * NumberOfBlocks; + config.DataBlockSize = SDIO_DATABLOCK_SIZE_512B; + config.TransferDir = SDIO_TRANSFER_DIR_TO_CARD; + config.TransferMode = SDIO_TRANSFER_MODE_BLOCK; + config.DPSM = SDIO_DPSM_ENABLE; + (void)SDIO_ConfigData(hsd->Instance, &config); + + return DAL_OK; + } + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief Erases the specified memory area of the given SD card. + * @note This API should be followed by a check on the card state through + * DAL_SD_GetCardState(). + * @param hsd: Pointer to SD handle + * @param BlockStartAdd: Start Block address + * @param BlockEndAdd: End Block address + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SD_Erase(SD_HandleTypeDef *hsd, uint32_t BlockStartAdd, uint32_t BlockEndAdd) +{ + uint32_t errorstate; + uint32_t start_add = BlockStartAdd; + uint32_t end_add = BlockEndAdd; + + if(hsd->State == DAL_SD_STATE_READY) + { + hsd->ErrorCode = DAL_SD_ERROR_NONE; + + if(end_add < start_add) + { + hsd->ErrorCode |= DAL_SD_ERROR_PARAM; + return DAL_ERROR; + } + + if(end_add > (hsd->SdCard.LogBlockNbr)) + { + hsd->ErrorCode |= DAL_SD_ERROR_ADDR_OUT_OF_RANGE; + return DAL_ERROR; + } + + hsd->State = DAL_SD_STATE_BUSY; + + /* Check if the card command class supports erase command */ + if(((hsd->SdCard.Class) & SDIO_CCCC_ERASE) == 0U) + { + /* Clear all the static flags */ + __DAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); + hsd->ErrorCode |= DAL_SD_ERROR_REQUEST_NOT_APPLICABLE; + hsd->State = DAL_SD_STATE_READY; + return DAL_ERROR; + } + + if((SDIO_GetResponse(hsd->Instance, SDIO_RES1) & SDMMC_CARD_LOCKED) == SDMMC_CARD_LOCKED) + { + /* Clear all the static flags */ + __DAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); + hsd->ErrorCode |= DAL_SD_ERROR_LOCK_UNLOCK_FAILED; + hsd->State = DAL_SD_STATE_READY; + return DAL_ERROR; + } + + /* Get start and end block for high capacity cards */ + if(hsd->SdCard.CardType != CARD_SDHC_SDXC) + { + start_add *= 512U; + end_add *= 512U; + } + + /* According to sd-card spec 1.0 ERASE_GROUP_START (CMD32) and erase_group_end(CMD33) */ + if(hsd->SdCard.CardType != CARD_SECURED) + { + /* Send CMD32 SD_ERASE_GRP_START with argument as addr */ + errorstate = SDMMC_CmdSDEraseStartAdd(hsd->Instance, start_add); + if(errorstate != DAL_SD_ERROR_NONE) + { + /* Clear all the static flags */ + __DAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); + hsd->ErrorCode |= errorstate; + hsd->State = DAL_SD_STATE_READY; + return DAL_ERROR; + } + + /* Send CMD33 SD_ERASE_GRP_END with argument as addr */ + errorstate = SDMMC_CmdSDEraseEndAdd(hsd->Instance, end_add); + if(errorstate != DAL_SD_ERROR_NONE) + { + /* Clear all the static flags */ + __DAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); + hsd->ErrorCode |= errorstate; + hsd->State = DAL_SD_STATE_READY; + return DAL_ERROR; + } + } + + /* Send CMD38 ERASE */ + errorstate = SDMMC_CmdErase(hsd->Instance); + if(errorstate != DAL_SD_ERROR_NONE) + { + /* Clear all the static flags */ + __DAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); + hsd->ErrorCode |= errorstate; + hsd->State = DAL_SD_STATE_READY; + return DAL_ERROR; + } + + hsd->State = DAL_SD_STATE_READY; + + return DAL_OK; + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief This function handles SD card interrupt request. + * @param hsd: Pointer to SD handle + * @retval None + */ +void DAL_SD_IRQHandler(SD_HandleTypeDef *hsd) +{ + uint32_t errorstate; + uint32_t context = hsd->Context; + + /* Check for SDIO interrupt flags */ + if((__DAL_SD_GET_FLAG(hsd, SDIO_FLAG_RXFIFOHF) != RESET) && ((context & SD_CONTEXT_IT) != 0U)) + { + SD_Read_IT(hsd); + } + + else if(__DAL_SD_GET_FLAG(hsd, SDIO_FLAG_DATAEND) != RESET) + { + __DAL_SD_CLEAR_FLAG(hsd, SDIO_FLAG_DATAEND); + +#if defined(SDIO_STS_SBE) + __DAL_SD_DISABLE_IT(hsd, SDIO_IT_DATAEND | SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT|\ + SDIO_IT_TXUNDERR | SDIO_IT_RXOVERR | SDIO_IT_TXFIFOHE |\ + SDIO_IT_RXFIFOHF | SDIO_IT_STBITERR); +#else /* SDIO_STS_SBE not defined */ + __DAL_SD_DISABLE_IT(hsd, SDIO_IT_DATAEND | SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT|\ + SDIO_IT_TXUNDERR | SDIO_IT_RXOVERR | SDIO_IT_TXFIFOHE |\ + SDIO_IT_RXFIFOHF); +#endif /* SDIO_STS_SBE */ + + hsd->Instance->DCTRL &= ~(SDIO_DCTRL_DTEN); + + if((context & SD_CONTEXT_IT) != 0U) + { + if(((context & SD_CONTEXT_READ_MULTIPLE_BLOCK) != 0U) || ((context & SD_CONTEXT_WRITE_MULTIPLE_BLOCK) != 0U)) + { + errorstate = SDMMC_CmdStopTransfer(hsd->Instance); + if(errorstate != DAL_SD_ERROR_NONE) + { + hsd->ErrorCode |= errorstate; +#if defined (USE_DAL_SD_REGISTER_CALLBACKS) && (USE_DAL_SD_REGISTER_CALLBACKS == 1U) + hsd->ErrorCallback(hsd); +#else + DAL_SD_ErrorCallback(hsd); +#endif /* USE_DAL_SD_REGISTER_CALLBACKS */ + } + } + + /* Clear all the static flags */ + __DAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_DATA_FLAGS); + + hsd->State = DAL_SD_STATE_READY; + hsd->Context = SD_CONTEXT_NONE; + if(((context & SD_CONTEXT_READ_SINGLE_BLOCK) != 0U) || ((context & SD_CONTEXT_READ_MULTIPLE_BLOCK) != 0U)) + { +#if defined (USE_DAL_SD_REGISTER_CALLBACKS) && (USE_DAL_SD_REGISTER_CALLBACKS == 1U) + hsd->RxCpltCallback(hsd); +#else + DAL_SD_RxCpltCallback(hsd); +#endif /* USE_DAL_SD_REGISTER_CALLBACKS */ + } + else + { +#if defined (USE_DAL_SD_REGISTER_CALLBACKS) && (USE_DAL_SD_REGISTER_CALLBACKS == 1U) + hsd->TxCpltCallback(hsd); +#else + DAL_SD_TxCpltCallback(hsd); +#endif /* USE_DAL_SD_REGISTER_CALLBACKS */ + } + } + else if((context & SD_CONTEXT_DMA) != 0U) + { + if((context & SD_CONTEXT_WRITE_MULTIPLE_BLOCK) != 0U) + { + errorstate = SDMMC_CmdStopTransfer(hsd->Instance); + if(errorstate != DAL_SD_ERROR_NONE) + { + hsd->ErrorCode |= errorstate; +#if defined (USE_DAL_SD_REGISTER_CALLBACKS) && (USE_DAL_SD_REGISTER_CALLBACKS == 1U) + hsd->ErrorCallback(hsd); +#else + DAL_SD_ErrorCallback(hsd); +#endif /* USE_DAL_SD_REGISTER_CALLBACKS */ + } + } + if(((context & SD_CONTEXT_READ_SINGLE_BLOCK) == 0U) && ((context & SD_CONTEXT_READ_MULTIPLE_BLOCK) == 0U)) + { + /* Disable the DMA transfer for transmit request by setting the DMAEN bit + in the SD DCTRL register */ + hsd->Instance->DCTRL &= (uint32_t)~((uint32_t)SDIO_DCTRL_DMAEN); + + hsd->State = DAL_SD_STATE_READY; + +#if defined (USE_DAL_SD_REGISTER_CALLBACKS) && (USE_DAL_SD_REGISTER_CALLBACKS == 1U) + hsd->TxCpltCallback(hsd); +#else + DAL_SD_TxCpltCallback(hsd); +#endif /* USE_DAL_SD_REGISTER_CALLBACKS */ + } + } + else + { + /* Nothing to do */ + } + } + + else if((__DAL_SD_GET_FLAG(hsd, SDIO_FLAG_TXFIFOHE) != RESET) && ((context & SD_CONTEXT_IT) != 0U)) + { + SD_Write_IT(hsd); + } + +#if defined(SDIO_STS_SBE) + else if(__DAL_SD_GET_FLAG(hsd, SDIO_FLAG_DCRCFAIL | SDIO_FLAG_DTIMEOUT | SDIO_FLAG_RXOVERR | SDIO_FLAG_TXUNDERR | SDIO_FLAG_STBITERR) != RESET) +#else /* SDIO_STS_SBE not defined */ + else if(__DAL_SD_GET_FLAG(hsd, SDIO_FLAG_DCRCFAIL | SDIO_FLAG_DTIMEOUT | SDIO_FLAG_RXOVERR | SDIO_FLAG_TXUNDERR) != RESET) +#endif /* SDIO_STS_SBE */ + { + /* Set Error code */ + if(__DAL_SD_GET_FLAG(hsd, SDIO_FLAG_DCRCFAIL) != RESET) + { + hsd->ErrorCode |= DAL_SD_ERROR_DATA_CRC_FAIL; + } + if(__DAL_SD_GET_FLAG(hsd, SDIO_FLAG_DTIMEOUT) != RESET) + { + hsd->ErrorCode |= DAL_SD_ERROR_DATA_TIMEOUT; + } + if(__DAL_SD_GET_FLAG(hsd, SDIO_FLAG_RXOVERR) != RESET) + { + hsd->ErrorCode |= DAL_SD_ERROR_RX_OVERRUN; + } + if(__DAL_SD_GET_FLAG(hsd, SDIO_FLAG_TXUNDERR) != RESET) + { + hsd->ErrorCode |= DAL_SD_ERROR_TX_UNDERRUN; + } +#if defined(SDIO_STS_SBE) + if(__DAL_SD_GET_FLAG(hsd, SDIO_FLAG_STBITERR) != RESET) + { + hsd->ErrorCode |= DAL_SD_ERROR_DATA_TIMEOUT; + } +#endif /* SDIO_STS_SBE */ + +#if defined(SDIO_STS_SBE) + /* Clear All flags */ + __DAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_DATA_FLAGS | SDIO_FLAG_STBITERR); + + /* Disable all interrupts */ + __DAL_SD_DISABLE_IT(hsd, SDIO_IT_DATAEND | SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT|\ + SDIO_IT_TXUNDERR| SDIO_IT_RXOVERR | SDIO_IT_STBITERR); +#else /* SDIO_STS_SBE not defined */ + /* Clear All flags */ + __DAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_DATA_FLAGS); + + /* Disable all interrupts */ + __DAL_SD_DISABLE_IT(hsd, SDIO_IT_DATAEND | SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT|\ + SDIO_IT_TXUNDERR| SDIO_IT_RXOVERR); +#endif /* SDIO_STS_SBE */ + + hsd->ErrorCode |= SDMMC_CmdStopTransfer(hsd->Instance); + + if((context & SD_CONTEXT_IT) != 0U) + { + /* Set the SD state to ready to be able to start again the process */ + hsd->State = DAL_SD_STATE_READY; + hsd->Context = SD_CONTEXT_NONE; +#if defined (USE_DAL_SD_REGISTER_CALLBACKS) && (USE_DAL_SD_REGISTER_CALLBACKS == 1U) + hsd->ErrorCallback(hsd); +#else + DAL_SD_ErrorCallback(hsd); +#endif /* USE_DAL_SD_REGISTER_CALLBACKS */ + } + else if((context & SD_CONTEXT_DMA) != 0U) + { + /* Abort the SD DMA channel */ + if(((context & SD_CONTEXT_WRITE_SINGLE_BLOCK) != 0U) || ((context & SD_CONTEXT_WRITE_MULTIPLE_BLOCK) != 0U)) + { + /* Set the DMA Tx abort callback */ + hsd->hdmatx->XferAbortCallback = SD_DMATxAbort; + /* Abort DMA in IT mode */ + if(DAL_DMA_Abort_IT(hsd->hdmatx) != DAL_OK) + { + SD_DMATxAbort(hsd->hdmatx); + } + } + else if(((context & SD_CONTEXT_READ_SINGLE_BLOCK) != 0U) || ((context & SD_CONTEXT_READ_MULTIPLE_BLOCK) != 0U)) + { + /* Set the DMA Rx abort callback */ + hsd->hdmarx->XferAbortCallback = SD_DMARxAbort; + /* Abort DMA in IT mode */ + if(DAL_DMA_Abort_IT(hsd->hdmarx) != DAL_OK) + { + SD_DMARxAbort(hsd->hdmarx); + } + } + else + { + hsd->ErrorCode = DAL_SD_ERROR_NONE; + hsd->State = DAL_SD_STATE_READY; + hsd->Context = SD_CONTEXT_NONE; +#if defined (USE_DAL_SD_REGISTER_CALLBACKS) && (USE_DAL_SD_REGISTER_CALLBACKS == 1U) + hsd->AbortCpltCallback(hsd); +#else + DAL_SD_AbortCallback(hsd); +#endif /* USE_DAL_SD_REGISTER_CALLBACKS */ + } + } + else + { + /* Nothing to do */ + } + } + else + { + /* Nothing to do */ + } +} + +/** + * @brief return the SD state + * @param hsd: Pointer to sd handle + * @retval DAL state + */ +DAL_SD_StateTypeDef DAL_SD_GetState(SD_HandleTypeDef *hsd) +{ + return hsd->State; +} + +/** +* @brief Return the SD error code +* @param hsd : Pointer to a SD_HandleTypeDef structure that contains + * the configuration information. +* @retval SD Error Code +*/ +uint32_t DAL_SD_GetError(SD_HandleTypeDef *hsd) +{ + return hsd->ErrorCode; +} + +/** + * @brief Tx Transfer completed callbacks + * @param hsd: Pointer to SD handle + * @retval None + */ +__weak void DAL_SD_TxCpltCallback(SD_HandleTypeDef *hsd) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hsd); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_SD_TxCpltCallback can be implemented in the user file + */ +} + +/** + * @brief Rx Transfer completed callbacks + * @param hsd: Pointer SD handle + * @retval None + */ +__weak void DAL_SD_RxCpltCallback(SD_HandleTypeDef *hsd) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hsd); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_SD_RxCpltCallback can be implemented in the user file + */ +} + +/** + * @brief SD error callbacks + * @param hsd: Pointer SD handle + * @retval None + */ +__weak void DAL_SD_ErrorCallback(SD_HandleTypeDef *hsd) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hsd); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_SD_ErrorCallback can be implemented in the user file + */ +} + +/** + * @brief SD Abort callbacks + * @param hsd: Pointer SD handle + * @retval None + */ +__weak void DAL_SD_AbortCallback(SD_HandleTypeDef *hsd) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hsd); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_SD_AbortCallback can be implemented in the user file + */ +} + +#if defined (USE_DAL_SD_REGISTER_CALLBACKS) && (USE_DAL_SD_REGISTER_CALLBACKS == 1U) +/** + * @brief Register a User SD Callback + * To be used instead of the weak (surcharged) predefined callback + * @param hsd : SD handle + * @param CallbackID : ID of the callback to be registered + * This parameter can be one of the following values: + * @arg @ref DAL_SD_TX_CPLT_CB_ID SD Tx Complete Callback ID + * @arg @ref DAL_SD_RX_CPLT_CB_ID SD Rx Complete Callback ID + * @arg @ref DAL_SD_ERROR_CB_ID SD Error Callback ID + * @arg @ref DAL_SD_ABORT_CB_ID SD Abort Callback ID + * @arg @ref DAL_SD_MSP_INIT_CB_ID SD MspInit Callback ID + * @arg @ref DAL_SD_MSP_DEINIT_CB_ID SD MspDeInit Callback ID + * @param pCallback : pointer to the Callback function + * @retval status + */ +DAL_StatusTypeDef DAL_SD_RegisterCallback(SD_HandleTypeDef *hsd, DAL_SD_CallbackIDTypeDef CallbackID, pSD_CallbackTypeDef pCallback) +{ + DAL_StatusTypeDef status = DAL_OK; + + if(pCallback == NULL) + { + /* Update the error code */ + hsd->ErrorCode |= DAL_SD_ERROR_INVALID_CALLBACK; + return DAL_ERROR; + } + + /* Process locked */ + __DAL_LOCK(hsd); + + if(hsd->State == DAL_SD_STATE_READY) + { + switch (CallbackID) + { + case DAL_SD_TX_CPLT_CB_ID : + hsd->TxCpltCallback = pCallback; + break; + case DAL_SD_RX_CPLT_CB_ID : + hsd->RxCpltCallback = pCallback; + break; + case DAL_SD_ERROR_CB_ID : + hsd->ErrorCallback = pCallback; + break; + case DAL_SD_ABORT_CB_ID : + hsd->AbortCpltCallback = pCallback; + break; + case DAL_SD_MSP_INIT_CB_ID : + hsd->MspInitCallback = pCallback; + break; + case DAL_SD_MSP_DEINIT_CB_ID : + hsd->MspDeInitCallback = pCallback; + break; + default : + /* Update the error code */ + hsd->ErrorCode |= DAL_SD_ERROR_INVALID_CALLBACK; + /* update return status */ + status = DAL_ERROR; + break; + } + } + else if (hsd->State == DAL_SD_STATE_RESET) + { + switch (CallbackID) + { + case DAL_SD_MSP_INIT_CB_ID : + hsd->MspInitCallback = pCallback; + break; + case DAL_SD_MSP_DEINIT_CB_ID : + hsd->MspDeInitCallback = pCallback; + break; + default : + /* Update the error code */ + hsd->ErrorCode |= DAL_SD_ERROR_INVALID_CALLBACK; + /* update return status */ + status = DAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + hsd->ErrorCode |= DAL_SD_ERROR_INVALID_CALLBACK; + /* update return status */ + status = DAL_ERROR; + } + + /* Release Lock */ + __DAL_UNLOCK(hsd); + return status; +} + +/** + * @brief Unregister a User SD Callback + * SD Callback is redirected to the weak (surcharged) predefined callback + * @param hsd : SD handle + * @param CallbackID : ID of the callback to be unregistered + * This parameter can be one of the following values: + * @arg @ref DAL_SD_TX_CPLT_CB_ID SD Tx Complete Callback ID + * @arg @ref DAL_SD_RX_CPLT_CB_ID SD Rx Complete Callback ID + * @arg @ref DAL_SD_ERROR_CB_ID SD Error Callback ID + * @arg @ref DAL_SD_ABORT_CB_ID SD Abort Callback ID + * @arg @ref DAL_SD_MSP_INIT_CB_ID SD MspInit Callback ID + * @arg @ref DAL_SD_MSP_DEINIT_CB_ID SD MspDeInit Callback ID + * @retval status + */ +DAL_StatusTypeDef DAL_SD_UnRegisterCallback(SD_HandleTypeDef *hsd, DAL_SD_CallbackIDTypeDef CallbackID) +{ + DAL_StatusTypeDef status = DAL_OK; + + /* Process locked */ + __DAL_LOCK(hsd); + + if(hsd->State == DAL_SD_STATE_READY) + { + switch (CallbackID) + { + case DAL_SD_TX_CPLT_CB_ID : + hsd->TxCpltCallback = DAL_SD_TxCpltCallback; + break; + case DAL_SD_RX_CPLT_CB_ID : + hsd->RxCpltCallback = DAL_SD_RxCpltCallback; + break; + case DAL_SD_ERROR_CB_ID : + hsd->ErrorCallback = DAL_SD_ErrorCallback; + break; + case DAL_SD_ABORT_CB_ID : + hsd->AbortCpltCallback = DAL_SD_AbortCallback; + break; + case DAL_SD_MSP_INIT_CB_ID : + hsd->MspInitCallback = DAL_SD_MspInit; + break; + case DAL_SD_MSP_DEINIT_CB_ID : + hsd->MspDeInitCallback = DAL_SD_MspDeInit; + break; + default : + /* Update the error code */ + hsd->ErrorCode |= DAL_SD_ERROR_INVALID_CALLBACK; + /* update return status */ + status = DAL_ERROR; + break; + } + } + else if (hsd->State == DAL_SD_STATE_RESET) + { + switch (CallbackID) + { + case DAL_SD_MSP_INIT_CB_ID : + hsd->MspInitCallback = DAL_SD_MspInit; + break; + case DAL_SD_MSP_DEINIT_CB_ID : + hsd->MspDeInitCallback = DAL_SD_MspDeInit; + break; + default : + /* Update the error code */ + hsd->ErrorCode |= DAL_SD_ERROR_INVALID_CALLBACK; + /* update return status */ + status = DAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + hsd->ErrorCode |= DAL_SD_ERROR_INVALID_CALLBACK; + /* update return status */ + status = DAL_ERROR; + } + + /* Release Lock */ + __DAL_UNLOCK(hsd); + return status; +} +#endif /* USE_DAL_SD_REGISTER_CALLBACKS */ + +/** + * @} + */ + +/** @addtogroup SD_Exported_Functions_Group3 + * @brief management functions + * +@verbatim + ============================================================================== + ##### Peripheral Control functions ##### + ============================================================================== + [..] + This subsection provides a set of functions allowing to control the SD card + operations and get the related information + +@endverbatim + * @{ + */ + +/** + * @brief Returns information the information of the card which are stored on + * the CID register. + * @param hsd: Pointer to SD handle + * @param pCID: Pointer to a DAL_SD_CardCIDTypeDef structure that + * contains all CID register parameters + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SD_GetCardCID(SD_HandleTypeDef *hsd, DAL_SD_CardCIDTypeDef *pCID) +{ + pCID->ManufacturerID = (uint8_t)((hsd->CID[0] & 0xFF000000U) >> 24U); + + pCID->OEM_AppliID = (uint16_t)((hsd->CID[0] & 0x00FFFF00U) >> 8U); + + pCID->ProdName1 = (((hsd->CID[0] & 0x000000FFU) << 24U) | ((hsd->CID[1] & 0xFFFFFF00U) >> 8U)); + + pCID->ProdName2 = (uint8_t)(hsd->CID[1] & 0x000000FFU); + + pCID->ProdRev = (uint8_t)((hsd->CID[2] & 0xFF000000U) >> 24U); + + pCID->ProdSN = (((hsd->CID[2] & 0x00FFFFFFU) << 8U) | ((hsd->CID[3] & 0xFF000000U) >> 24U)); + + pCID->Reserved1 = (uint8_t)((hsd->CID[3] & 0x00F00000U) >> 20U); + + pCID->ManufactDate = (uint16_t)((hsd->CID[3] & 0x000FFF00U) >> 8U); + + pCID->CID_CRC = (uint8_t)((hsd->CID[3] & 0x000000FEU) >> 1U); + + pCID->Reserved2 = 1U; + + return DAL_OK; +} + +/** + * @brief Returns information the information of the card which are stored on + * the CSD register. + * @param hsd: Pointer to SD handle + * @param pCSD: Pointer to a DAL_SD_CardCSDTypeDef structure that + * contains all CSD register parameters + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SD_GetCardCSD(SD_HandleTypeDef *hsd, DAL_SD_CardCSDTypeDef *pCSD) +{ + pCSD->CSDStruct = (uint8_t)((hsd->CSD[0] & 0xC0000000U) >> 30U); + + pCSD->SysSpecVersion = (uint8_t)((hsd->CSD[0] & 0x3C000000U) >> 26U); + + pCSD->Reserved1 = (uint8_t)((hsd->CSD[0] & 0x03000000U) >> 24U); + + pCSD->TAAC = (uint8_t)((hsd->CSD[0] & 0x00FF0000U) >> 16U); + + pCSD->NSAC = (uint8_t)((hsd->CSD[0] & 0x0000FF00U) >> 8U); + + pCSD->MaxBusClkFrec = (uint8_t)(hsd->CSD[0] & 0x000000FFU); + + pCSD->CardComdClasses = (uint16_t)((hsd->CSD[1] & 0xFFF00000U) >> 20U); + + pCSD->RdBlockLen = (uint8_t)((hsd->CSD[1] & 0x000F0000U) >> 16U); + + pCSD->PartBlockRead = (uint8_t)((hsd->CSD[1] & 0x00008000U) >> 15U); + + pCSD->WrBlockMisalign = (uint8_t)((hsd->CSD[1] & 0x00004000U) >> 14U); + + pCSD->RdBlockMisalign = (uint8_t)((hsd->CSD[1] & 0x00002000U) >> 13U); + + pCSD->DSRImpl = (uint8_t)((hsd->CSD[1] & 0x00001000U) >> 12U); + + pCSD->Reserved2 = 0U; /*!< Reserved */ + + if(hsd->SdCard.CardType == CARD_SDSC) + { + pCSD->DeviceSize = (((hsd->CSD[1] & 0x000003FFU) << 2U) | ((hsd->CSD[2] & 0xC0000000U) >> 30U)); + + pCSD->MaxRdCurrentVDDMin = (uint8_t)((hsd->CSD[2] & 0x38000000U) >> 27U); + + pCSD->MaxRdCurrentVDDMax = (uint8_t)((hsd->CSD[2] & 0x07000000U) >> 24U); + + pCSD->MaxWrCurrentVDDMin = (uint8_t)((hsd->CSD[2] & 0x00E00000U) >> 21U); + + pCSD->MaxWrCurrentVDDMax = (uint8_t)((hsd->CSD[2] & 0x001C0000U) >> 18U); + + pCSD->DeviceSizeMul = (uint8_t)((hsd->CSD[2] & 0x00038000U) >> 15U); + + hsd->SdCard.BlockNbr = (pCSD->DeviceSize + 1U) ; + hsd->SdCard.BlockNbr *= (1UL << ((pCSD->DeviceSizeMul & 0x07U) + 2U)); + hsd->SdCard.BlockSize = (1UL << (pCSD->RdBlockLen & 0x0FU)); + + hsd->SdCard.LogBlockNbr = (hsd->SdCard.BlockNbr) * ((hsd->SdCard.BlockSize) / 512U); + hsd->SdCard.LogBlockSize = 512U; + } + else if(hsd->SdCard.CardType == CARD_SDHC_SDXC) + { + /* Byte 7 */ + pCSD->DeviceSize = (((hsd->CSD[1] & 0x0000003FU) << 16U) | ((hsd->CSD[2] & 0xFFFF0000U) >> 16U)); + + hsd->SdCard.BlockNbr = ((pCSD->DeviceSize + 1U) * 1024U); + hsd->SdCard.LogBlockNbr = hsd->SdCard.BlockNbr; + hsd->SdCard.BlockSize = 512U; + hsd->SdCard.LogBlockSize = hsd->SdCard.BlockSize; + } + else + { + /* Clear all the static flags */ + __DAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); + hsd->ErrorCode |= DAL_SD_ERROR_UNSUPPORTED_FEATURE; + hsd->State = DAL_SD_STATE_READY; + return DAL_ERROR; + } + + pCSD->EraseGrSize = (uint8_t)((hsd->CSD[2] & 0x00004000U) >> 14U); + + pCSD->EraseGrMul = (uint8_t)((hsd->CSD[2] & 0x00003F80U) >> 7U); + + pCSD->WrProtectGrSize = (uint8_t)(hsd->CSD[2] & 0x0000007FU); + + pCSD->WrProtectGrEnable = (uint8_t)((hsd->CSD[3] & 0x80000000U) >> 31U); + + pCSD->ManDeflECC = (uint8_t)((hsd->CSD[3] & 0x60000000U) >> 29U); + + pCSD->WrSpeedFact = (uint8_t)((hsd->CSD[3] & 0x1C000000U) >> 26U); + + pCSD->MaxWrBlockLen= (uint8_t)((hsd->CSD[3] & 0x03C00000U) >> 22U); + + pCSD->WriteBlockPaPartial = (uint8_t)((hsd->CSD[3] & 0x00200000U) >> 21U); + + pCSD->Reserved3 = 0; + + pCSD->ContentProtectAppli = (uint8_t)((hsd->CSD[3] & 0x00010000U) >> 16U); + + pCSD->FileFormatGroup = (uint8_t)((hsd->CSD[3] & 0x00008000U) >> 15U); + + pCSD->CopyFlag = (uint8_t)((hsd->CSD[3] & 0x00004000U) >> 14U); + + pCSD->PermWrProtect = (uint8_t)((hsd->CSD[3] & 0x00002000U) >> 13U); + + pCSD->TempWrProtect = (uint8_t)((hsd->CSD[3] & 0x00001000U) >> 12U); + + pCSD->FileFormat = (uint8_t)((hsd->CSD[3] & 0x00000C00U) >> 10U); + + pCSD->ECC= (uint8_t)((hsd->CSD[3] & 0x00000300U) >> 8U); + + pCSD->CSD_CRC = (uint8_t)((hsd->CSD[3] & 0x000000FEU) >> 1U); + + pCSD->Reserved4 = 1; + + return DAL_OK; +} + +/** + * @brief Gets the SD status info. + * @param hsd: Pointer to SD handle + * @param pStatus: Pointer to the DAL_SD_CardStatusTypeDef structure that + * will contain the SD card status information + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SD_GetCardStatus(SD_HandleTypeDef *hsd, DAL_SD_CardStatusTypeDef *pStatus) +{ + uint32_t sd_status[16]; + uint32_t errorstate; + DAL_StatusTypeDef status = DAL_OK; + + errorstate = SD_SendSDStatus(hsd, sd_status); + if(errorstate != DAL_SD_ERROR_NONE) + { + /* Clear all the static flags */ + __DAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); + hsd->ErrorCode |= errorstate; + hsd->State = DAL_SD_STATE_READY; + status = DAL_ERROR; + } + else + { + pStatus->DataBusWidth = (uint8_t)((sd_status[0] & 0xC0U) >> 6U); + + pStatus->SecuredMode = (uint8_t)((sd_status[0] & 0x20U) >> 5U); + + pStatus->CardType = (uint16_t)(((sd_status[0] & 0x00FF0000U) >> 8U) | ((sd_status[0] & 0xFF000000U) >> 24U)); + + pStatus->ProtectedAreaSize = (((sd_status[1] & 0xFFU) << 24U) | ((sd_status[1] & 0xFF00U) << 8U) | + ((sd_status[1] & 0xFF0000U) >> 8U) | ((sd_status[1] & 0xFF000000U) >> 24U)); + + pStatus->SpeedClass = (uint8_t)(sd_status[2] & 0xFFU); + + pStatus->PerformanceMove = (uint8_t)((sd_status[2] & 0xFF00U) >> 8U); + + pStatus->AllocationUnitSize = (uint8_t)((sd_status[2] & 0xF00000U) >> 20U); + + pStatus->EraseSize = (uint16_t)(((sd_status[2] & 0xFF000000U) >> 16U) | (sd_status[3] & 0xFFU)); + + pStatus->EraseTimeout = (uint8_t)((sd_status[3] & 0xFC00U) >> 10U); + + pStatus->EraseOffset = (uint8_t)((sd_status[3] & 0x0300U) >> 8U); + } + + /* Set Block Size for Card */ + errorstate = SDMMC_CmdBlockLength(hsd->Instance, BLOCKSIZE); + if(errorstate != DAL_SD_ERROR_NONE) + { + /* Clear all the static flags */ + __DAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); + hsd->ErrorCode = errorstate; + hsd->State = DAL_SD_STATE_READY; + status = DAL_ERROR; + } + + return status; +} + +/** + * @brief Gets the SD card info. + * @param hsd: Pointer to SD handle + * @param pCardInfo: Pointer to the DAL_SD_CardInfoTypeDef structure that + * will contain the SD card status information + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SD_GetCardInfo(SD_HandleTypeDef *hsd, DAL_SD_CardInfoTypeDef *pCardInfo) +{ + pCardInfo->CardType = (uint32_t)(hsd->SdCard.CardType); + pCardInfo->CardVersion = (uint32_t)(hsd->SdCard.CardVersion); + pCardInfo->Class = (uint32_t)(hsd->SdCard.Class); + pCardInfo->RelCardAdd = (uint32_t)(hsd->SdCard.RelCardAdd); + pCardInfo->BlockNbr = (uint32_t)(hsd->SdCard.BlockNbr); + pCardInfo->BlockSize = (uint32_t)(hsd->SdCard.BlockSize); + pCardInfo->LogBlockNbr = (uint32_t)(hsd->SdCard.LogBlockNbr); + pCardInfo->LogBlockSize = (uint32_t)(hsd->SdCard.LogBlockSize); + + return DAL_OK; +} + +/** + * @brief Enables wide bus operation for the requested card if supported by + * card. + * @param hsd: Pointer to SD handle + * @param WideMode: Specifies the SD card wide bus mode + * This parameter can be one of the following values: + * @arg SDIO_BUS_WIDE_8B: 8-bit data transfer + * @arg SDIO_BUS_WIDE_4B: 4-bit data transfer + * @arg SDIO_BUS_WIDE_1B: 1-bit data transfer + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SD_ConfigWideBusOperation(SD_HandleTypeDef *hsd, uint32_t WideMode) +{ + SDIO_InitTypeDef Init; + uint32_t errorstate; + DAL_StatusTypeDef status = DAL_OK; + + /* Check the parameters */ + ASSERT_PARAM(IS_SDIO_BUS_WIDE(WideMode)); + + /* Change State */ + hsd->State = DAL_SD_STATE_BUSY; + + if(hsd->SdCard.CardType != CARD_SECURED) + { + if(WideMode == SDIO_BUS_WIDE_8B) + { + hsd->ErrorCode |= DAL_SD_ERROR_UNSUPPORTED_FEATURE; + } + else if(WideMode == SDIO_BUS_WIDE_4B) + { + errorstate = SD_WideBus_Enable(hsd); + + hsd->ErrorCode |= errorstate; + } + else if(WideMode == SDIO_BUS_WIDE_1B) + { + errorstate = SD_WideBus_Disable(hsd); + + hsd->ErrorCode |= errorstate; + } + else + { + /* WideMode is not a valid argument*/ + hsd->ErrorCode |= DAL_SD_ERROR_PARAM; + } + } + else + { + /* MMC Card does not support this feature */ + hsd->ErrorCode |= DAL_SD_ERROR_UNSUPPORTED_FEATURE; + } + + if(hsd->ErrorCode != DAL_SD_ERROR_NONE) + { + /* Clear all the static flags */ + __DAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); + hsd->State = DAL_SD_STATE_READY; + status = DAL_ERROR; + } + else + { + /* Configure the SDIO peripheral */ + Init.ClockEdge = hsd->Init.ClockEdge; + Init.ClockBypass = hsd->Init.ClockBypass; + Init.ClockPowerSave = hsd->Init.ClockPowerSave; + Init.BusWide = WideMode; + Init.HardwareFlowControl = hsd->Init.HardwareFlowControl; + Init.ClockDiv = hsd->Init.ClockDiv; + (void)SDIO_Init(hsd->Instance, Init); + } + + /* Set Block Size for Card */ + errorstate = SDMMC_CmdBlockLength(hsd->Instance, BLOCKSIZE); + if(errorstate != DAL_SD_ERROR_NONE) + { + /* Clear all the static flags */ + __DAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); + hsd->ErrorCode |= errorstate; + status = DAL_ERROR; + } + + /* Change State */ + hsd->State = DAL_SD_STATE_READY; + + return status; +} + +/** + * @brief Gets the current sd card data state. + * @param hsd: pointer to SD handle + * @retval Card state + */ +DAL_SD_CardStateTypeDef DAL_SD_GetCardState(SD_HandleTypeDef *hsd) +{ + uint32_t cardstate; + uint32_t errorstate; + uint32_t resp1 = 0; + + errorstate = SD_SendStatus(hsd, &resp1); + if(errorstate != DAL_SD_ERROR_NONE) + { + hsd->ErrorCode |= errorstate; + } + + cardstate = ((resp1 >> 9U) & 0x0FU); + + return (DAL_SD_CardStateTypeDef)cardstate; +} + +/** + * @brief Abort the current transfer and disable the SD. + * @param hsd: pointer to a SD_HandleTypeDef structure that contains + * the configuration information for SD module. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SD_Abort(SD_HandleTypeDef *hsd) +{ + DAL_SD_CardStateTypeDef CardState; + uint32_t context = hsd->Context; + + /* DIsable All interrupts */ + __DAL_SD_DISABLE_IT(hsd, SDIO_IT_DATAEND | SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT|\ + SDIO_IT_TXUNDERR| SDIO_IT_RXOVERR); + + /* Clear All flags */ + __DAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_DATA_FLAGS); + + CLEAR_BIT(hsd->Instance->DCTRL, SDIO_DCTRL_DTEN); + + if ((context & SD_CONTEXT_DMA) != 0U) + { + /* Disable the SD DMA request */ + hsd->Instance->DCTRL &= (uint32_t)~((uint32_t)SDIO_DCTRL_DMAEN); + + /* Abort the SD DMA Tx channel */ + if (((context & SD_CONTEXT_WRITE_SINGLE_BLOCK) != 0U) || ((context & SD_CONTEXT_WRITE_MULTIPLE_BLOCK) != 0U)) + { + if(DAL_DMA_Abort(hsd->hdmatx) != DAL_OK) + { + hsd->ErrorCode |= DAL_SD_ERROR_DMA; + } + } + /* Abort the SD DMA Rx channel */ + else if (((context & SD_CONTEXT_READ_SINGLE_BLOCK) != 0U) || ((context & SD_CONTEXT_READ_MULTIPLE_BLOCK) != 0U)) + { + if(DAL_DMA_Abort(hsd->hdmarx) != DAL_OK) + { + hsd->ErrorCode |= DAL_SD_ERROR_DMA; + } + } + else + { + /* Nothing to do */ + } + } + + hsd->State = DAL_SD_STATE_READY; + + /* Initialize the SD operation */ + hsd->Context = SD_CONTEXT_NONE; + + CardState = DAL_SD_GetCardState(hsd); + if((CardState == DAL_SD_CARD_RECEIVING) || (CardState == DAL_SD_CARD_SENDING)) + { + hsd->ErrorCode = SDMMC_CmdStopTransfer(hsd->Instance); + } + if(hsd->ErrorCode != DAL_SD_ERROR_NONE) + { + return DAL_ERROR; + } + return DAL_OK; +} + +/** + * @brief Abort the current transfer and disable the SD (IT mode). + * @param hsd: pointer to a SD_HandleTypeDef structure that contains + * the configuration information for SD module. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SD_Abort_IT(SD_HandleTypeDef *hsd) +{ + DAL_SD_CardStateTypeDef CardState; + uint32_t context = hsd->Context; + + /* Disable All interrupts */ + __DAL_SD_DISABLE_IT(hsd, SDIO_IT_DATAEND | SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT|\ + SDIO_IT_TXUNDERR| SDIO_IT_RXOVERR); + + CLEAR_BIT(hsd->Instance->DCTRL, SDIO_DCTRL_DTEN); + + if ((context & SD_CONTEXT_DMA) != 0U) + { + /* Disable the SD DMA request */ + hsd->Instance->DCTRL &= (uint32_t)~((uint32_t)SDIO_DCTRL_DMAEN); + + /* Abort the SD DMA Tx channel */ + if (((context & SD_CONTEXT_WRITE_SINGLE_BLOCK) != 0U) || ((context & SD_CONTEXT_WRITE_MULTIPLE_BLOCK) != 0U)) + { + hsd->hdmatx->XferAbortCallback = SD_DMATxAbort; + if(DAL_DMA_Abort_IT(hsd->hdmatx) != DAL_OK) + { + hsd->hdmatx = NULL; + } + } + /* Abort the SD DMA Rx channel */ + else if (((context & SD_CONTEXT_READ_SINGLE_BLOCK) != 0U) || ((context & SD_CONTEXT_READ_MULTIPLE_BLOCK) != 0U)) + { + hsd->hdmarx->XferAbortCallback = SD_DMARxAbort; + if(DAL_DMA_Abort_IT(hsd->hdmarx) != DAL_OK) + { + hsd->hdmarx = NULL; + } + } + else + { + /* Nothing to do */ + } + } + /* No transfer ongoing on both DMA channels*/ + else + { + /* Clear All flags */ + __DAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_DATA_FLAGS); + + CardState = DAL_SD_GetCardState(hsd); + hsd->State = DAL_SD_STATE_READY; + hsd->Context = SD_CONTEXT_NONE; + if((CardState == DAL_SD_CARD_RECEIVING) || (CardState == DAL_SD_CARD_SENDING)) + { + hsd->ErrorCode = SDMMC_CmdStopTransfer(hsd->Instance); + } + if(hsd->ErrorCode != DAL_SD_ERROR_NONE) + { + return DAL_ERROR; + } + else + { +#if defined (USE_DAL_SD_REGISTER_CALLBACKS) && (USE_DAL_SD_REGISTER_CALLBACKS == 1U) + hsd->AbortCpltCallback(hsd); +#else + DAL_SD_AbortCallback(hsd); +#endif /* USE_DAL_SD_REGISTER_CALLBACKS */ + } + } + + return DAL_OK; +} + +/** + * @} + */ + +/** + * @} + */ + +/* Private function ----------------------------------------------------------*/ +/** @addtogroup SD_Private_Functions + * @{ + */ + +/** + * @brief DMA SD transmit process complete callback + * @param hdma: DMA handle + * @retval None + */ +static void SD_DMATransmitCplt(DMA_HandleTypeDef *hdma) +{ + SD_HandleTypeDef* hsd = (SD_HandleTypeDef* )(hdma->Parent); + + /* Enable DATAEND Interrupt */ + __DAL_SD_ENABLE_IT(hsd, (SDIO_IT_DATAEND)); +} + +/** + * @brief DMA SD receive process complete callback + * @param hdma: DMA handle + * @retval None + */ +static void SD_DMAReceiveCplt(DMA_HandleTypeDef *hdma) +{ + SD_HandleTypeDef* hsd = (SD_HandleTypeDef* )(hdma->Parent); + uint32_t errorstate; + + /* Send stop command in multiblock write */ + if(hsd->Context == (SD_CONTEXT_READ_MULTIPLE_BLOCK | SD_CONTEXT_DMA)) + { + errorstate = SDMMC_CmdStopTransfer(hsd->Instance); + if(errorstate != DAL_SD_ERROR_NONE) + { + hsd->ErrorCode |= errorstate; +#if (USE_DAL_SD_REGISTER_CALLBACKS == 1) + hsd->ErrorCallback(hsd); +#else + DAL_SD_ErrorCallback(hsd); +#endif + } + } + + /* Disable the DMA transfer for transmit request by setting the DMAEN bit + in the SD DCTRL register */ + hsd->Instance->DCTRL &= (uint32_t)~((uint32_t)SDIO_DCTRL_DMAEN); + + /* Clear all the static flags */ + __DAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_DATA_FLAGS); + + hsd->State = DAL_SD_STATE_READY; + hsd->Context = SD_CONTEXT_NONE; + +#if (USE_DAL_SD_REGISTER_CALLBACKS == 1) + hsd->RxCpltCallback(hsd); +#else + DAL_SD_RxCpltCallback(hsd); +#endif +} + +/** + * @brief DMA SD communication error callback + * @param hdma: DMA handle + * @retval None + */ +static void SD_DMAError(DMA_HandleTypeDef *hdma) +{ + SD_HandleTypeDef* hsd = (SD_HandleTypeDef* )(hdma->Parent); + DAL_SD_CardStateTypeDef CardState; + uint32_t RxErrorCode, TxErrorCode; + + /* if DMA error is FIFO error ignore it */ + if(DAL_DMA_GetError(hdma) != DAL_DMA_ERROR_FE) + { + RxErrorCode = hsd->hdmarx->ErrorCode; + TxErrorCode = hsd->hdmatx->ErrorCode; + if((RxErrorCode == DAL_DMA_ERROR_TE) || (TxErrorCode == DAL_DMA_ERROR_TE)) + { + /* Clear All flags */ + __DAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); + + /* Disable All interrupts */ + __DAL_SD_DISABLE_IT(hsd, SDIO_IT_DATAEND | SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT|\ + SDIO_IT_TXUNDERR| SDIO_IT_RXOVERR); + + hsd->ErrorCode |= DAL_SD_ERROR_DMA; + CardState = DAL_SD_GetCardState(hsd); + if((CardState == DAL_SD_CARD_RECEIVING) || (CardState == DAL_SD_CARD_SENDING)) + { + hsd->ErrorCode |= SDMMC_CmdStopTransfer(hsd->Instance); + } + + hsd->State= DAL_SD_STATE_READY; + hsd->Context = SD_CONTEXT_NONE; + } + +#if (USE_DAL_SD_REGISTER_CALLBACKS == 1) + hsd->ErrorCallback(hsd); +#else + DAL_SD_ErrorCallback(hsd); +#endif + } +} + +/** + * @brief DMA SD Tx Abort callback + * @param hdma: DMA handle + * @retval None + */ +static void SD_DMATxAbort(DMA_HandleTypeDef *hdma) +{ + SD_HandleTypeDef* hsd = (SD_HandleTypeDef* )(hdma->Parent); + DAL_SD_CardStateTypeDef CardState; + + /* Clear All flags */ + __DAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_DATA_FLAGS); + + CardState = DAL_SD_GetCardState(hsd); + hsd->State = DAL_SD_STATE_READY; + hsd->Context = SD_CONTEXT_NONE; + if((CardState == DAL_SD_CARD_RECEIVING) || (CardState == DAL_SD_CARD_SENDING)) + { + hsd->ErrorCode |= SDMMC_CmdStopTransfer(hsd->Instance); + } + + if(hsd->ErrorCode == DAL_SD_ERROR_NONE) + { +#if (USE_DAL_SD_REGISTER_CALLBACKS == 1) + hsd->AbortCpltCallback(hsd); +#else + DAL_SD_AbortCallback(hsd); +#endif + } + else + { +#if (USE_DAL_SD_REGISTER_CALLBACKS == 1) + hsd->ErrorCallback(hsd); +#else + DAL_SD_ErrorCallback(hsd); +#endif + } +} + +/** + * @brief DMA SD Rx Abort callback + * @param hdma: DMA handle + * @retval None + */ +static void SD_DMARxAbort(DMA_HandleTypeDef *hdma) +{ + SD_HandleTypeDef* hsd = (SD_HandleTypeDef* )(hdma->Parent); + DAL_SD_CardStateTypeDef CardState; + + /* Clear All flags */ + __DAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_DATA_FLAGS); + + CardState = DAL_SD_GetCardState(hsd); + hsd->State = DAL_SD_STATE_READY; + hsd->Context = SD_CONTEXT_NONE; + if((CardState == DAL_SD_CARD_RECEIVING) || (CardState == DAL_SD_CARD_SENDING)) + { + hsd->ErrorCode |= SDMMC_CmdStopTransfer(hsd->Instance); + } + + if(hsd->ErrorCode == DAL_SD_ERROR_NONE) + { +#if (USE_DAL_SD_REGISTER_CALLBACKS == 1) + hsd->AbortCpltCallback(hsd); +#else + DAL_SD_AbortCallback(hsd); +#endif + } + else + { +#if (USE_DAL_SD_REGISTER_CALLBACKS == 1) + hsd->ErrorCallback(hsd); +#else + DAL_SD_ErrorCallback(hsd); +#endif + } +} + +/** + * @brief Initializes the sd card. + * @param hsd: Pointer to SD handle + * @retval SD Card error state + */ +static uint32_t SD_InitCard(SD_HandleTypeDef *hsd) +{ + DAL_SD_CardCSDTypeDef CSD; + uint32_t errorstate; + uint16_t sd_rca = 1U; + + /* Check the power State */ + if(SDIO_GetPowerState(hsd->Instance) == 0U) + { + /* Power off */ + return DAL_SD_ERROR_REQUEST_NOT_APPLICABLE; + } + + if(hsd->SdCard.CardType != CARD_SECURED) + { + /* Send CMD2 ALL_SEND_CID */ + errorstate = SDMMC_CmdSendCID(hsd->Instance); + if(errorstate != DAL_SD_ERROR_NONE) + { + return errorstate; + } + else + { + /* Get Card identification number data */ + hsd->CID[0U] = SDIO_GetResponse(hsd->Instance, SDIO_RES1); + hsd->CID[1U] = SDIO_GetResponse(hsd->Instance, SDIO_RES2); + hsd->CID[2U] = SDIO_GetResponse(hsd->Instance, SDIO_RES3); + hsd->CID[3U] = SDIO_GetResponse(hsd->Instance, SDIO_RES4); + } + } + + if(hsd->SdCard.CardType != CARD_SECURED) + { + /* Send CMD3 SET_REL_ADDR with argument 0 */ + /* SD Card publishes its RCA. */ + errorstate = SDMMC_CmdSetRelAdd(hsd->Instance, &sd_rca); + if(errorstate != DAL_SD_ERROR_NONE) + { + return errorstate; + } + } + if(hsd->SdCard.CardType != CARD_SECURED) + { + /* Get the SD card RCA */ + hsd->SdCard.RelCardAdd = sd_rca; + + /* Send CMD9 SEND_CSD with argument as card's RCA */ + errorstate = SDMMC_CmdSendCSD(hsd->Instance, (uint32_t)(hsd->SdCard.RelCardAdd << 16U)); + if(errorstate != DAL_SD_ERROR_NONE) + { + return errorstate; + } + else + { + /* Get Card Specific Data */ + hsd->CSD[0U] = SDIO_GetResponse(hsd->Instance, SDIO_RES1); + hsd->CSD[1U] = SDIO_GetResponse(hsd->Instance, SDIO_RES2); + hsd->CSD[2U] = SDIO_GetResponse(hsd->Instance, SDIO_RES3); + hsd->CSD[3U] = SDIO_GetResponse(hsd->Instance, SDIO_RES4); + } + } + + /* Get the Card Class */ + hsd->SdCard.Class = (SDIO_GetResponse(hsd->Instance, SDIO_RES2) >> 20U); + + /* Get CSD parameters */ + if (DAL_SD_GetCardCSD(hsd, &CSD) != DAL_OK) + { + return DAL_SD_ERROR_UNSUPPORTED_FEATURE; + } + + /* Select the Card */ + errorstate = SDMMC_CmdSelDesel(hsd->Instance, (uint32_t)(((uint32_t)hsd->SdCard.RelCardAdd) << 16U)); + if(errorstate != DAL_SD_ERROR_NONE) + { + return errorstate; + } + + /* Configure SDIO peripheral interface */ + (void)SDIO_Init(hsd->Instance, hsd->Init); + + /* All cards are initialized */ + return DAL_SD_ERROR_NONE; +} + +/** + * @brief Enquires cards about their operating voltage and configures clock + * controls and stores SD information that will be needed in future + * in the SD handle. + * @param hsd: Pointer to SD handle + * @retval error state + */ +static uint32_t SD_PowerON(SD_HandleTypeDef *hsd) +{ + __IO uint32_t count = 0U; + uint32_t response = 0U, validvoltage = 0U; + uint32_t errorstate; + + /* CMD0: GO_IDLE_STATE */ + errorstate = SDMMC_CmdGoIdleState(hsd->Instance); + if(errorstate != DAL_SD_ERROR_NONE) + { + return errorstate; + } + + /* CMD8: SEND_IF_COND: Command available only on V2.0 cards */ + errorstate = SDMMC_CmdOperCond(hsd->Instance); + if(errorstate != DAL_SD_ERROR_NONE) + { + hsd->SdCard.CardVersion = CARD_V1_X; + /* CMD0: GO_IDLE_STATE */ + errorstate = SDMMC_CmdGoIdleState(hsd->Instance); + if(errorstate != DAL_SD_ERROR_NONE) + { + return errorstate; + } + + } + else + { + hsd->SdCard.CardVersion = CARD_V2_X; + } + + if( hsd->SdCard.CardVersion == CARD_V2_X) + { + /* SEND CMD55 APP_CMD with RCA as 0 */ + errorstate = SDMMC_CmdAppCommand(hsd->Instance, 0); + if(errorstate != DAL_SD_ERROR_NONE) + { + return DAL_SD_ERROR_UNSUPPORTED_FEATURE; + } + } + /* SD CARD */ + /* Send ACMD41 SD_APP_OP_COND with Argument 0x80100000 */ + while((count < SDMMC_MAX_VOLT_TRIAL) && (validvoltage == 0U)) + { + /* SEND CMD55 APP_CMD with RCA as 0 */ + errorstate = SDMMC_CmdAppCommand(hsd->Instance, 0); + if(errorstate != DAL_SD_ERROR_NONE) + { + return errorstate; + } + + /* Send CMD41 */ + errorstate = SDMMC_CmdAppOperCommand(hsd->Instance, SDMMC_VOLTAGE_WINDOW_SD | SDMMC_HIGH_CAPACITY | SD_SWITCH_1_8V_CAPACITY); + if(errorstate != DAL_SD_ERROR_NONE) + { + return DAL_SD_ERROR_UNSUPPORTED_FEATURE; + } + + /* Get command response */ + response = SDIO_GetResponse(hsd->Instance, SDIO_RES1); + + /* Get operating voltage*/ + validvoltage = (((response >> 31U) == 1U) ? 1U : 0U); + + count++; + } + + if(count >= SDMMC_MAX_VOLT_TRIAL) + { + return DAL_SD_ERROR_INVALID_VOLTRANGE; + } + + if((response & SDMMC_HIGH_CAPACITY) == SDMMC_HIGH_CAPACITY) /* (response &= SD_HIGH_CAPACITY) */ + { + hsd->SdCard.CardType = CARD_SDHC_SDXC; + } + else + { + hsd->SdCard.CardType = CARD_SDSC; + } + + + return DAL_SD_ERROR_NONE; +} + +/** + * @brief Turns the SDIO output signals off. + * @param hsd: Pointer to SD handle + * @retval None + */ +static void SD_PowerOFF(SD_HandleTypeDef *hsd) +{ + /* Set Power State to OFF */ + (void)SDIO_PowerState_OFF(hsd->Instance); +} + +/** + * @brief Send Status info command. + * @param hsd: pointer to SD handle + * @param pSDstatus: Pointer to the buffer that will contain the SD card status + * SD Status register) + * @retval error state + */ +static uint32_t SD_SendSDStatus(SD_HandleTypeDef *hsd, uint32_t *pSDstatus) +{ + SDIO_DataInitTypeDef config; + uint32_t errorstate; + uint32_t tickstart = DAL_GetTick(); + uint32_t count; + uint32_t *pData = pSDstatus; + + /* Check SD response */ + if((SDIO_GetResponse(hsd->Instance, SDIO_RES1) & SDMMC_CARD_LOCKED) == SDMMC_CARD_LOCKED) + { + return DAL_SD_ERROR_LOCK_UNLOCK_FAILED; + } + + /* Set block size for card if it is not equal to current block size for card */ + errorstate = SDMMC_CmdBlockLength(hsd->Instance, 64U); + if(errorstate != DAL_SD_ERROR_NONE) + { + hsd->ErrorCode |= DAL_SD_ERROR_NONE; + return errorstate; + } + + /* Send CMD55 */ + errorstate = SDMMC_CmdAppCommand(hsd->Instance, (uint32_t)(hsd->SdCard.RelCardAdd << 16U)); + if(errorstate != DAL_SD_ERROR_NONE) + { + hsd->ErrorCode |= DAL_SD_ERROR_NONE; + return errorstate; + } + + /* Configure the SD DPSM (Data Path State Machine) */ + config.DataTimeOut = SDMMC_DATATIMEOUT; + config.DataLength = 64U; + config.DataBlockSize = SDIO_DATABLOCK_SIZE_64B; + config.TransferDir = SDIO_TRANSFER_DIR_TO_SDIO; + config.TransferMode = SDIO_TRANSFER_MODE_BLOCK; + config.DPSM = SDIO_DPSM_ENABLE; + (void)SDIO_ConfigData(hsd->Instance, &config); + + /* Send ACMD13 (SD_APP_STAUS) with argument as card's RCA */ + errorstate = SDMMC_CmdStatusRegister(hsd->Instance); + if(errorstate != DAL_SD_ERROR_NONE) + { + hsd->ErrorCode |= DAL_SD_ERROR_NONE; + return errorstate; + } + + /* Get status data */ + while(!__DAL_SD_GET_FLAG(hsd, SDIO_FLAG_RXOVERR | SDIO_FLAG_DCRCFAIL | SDIO_FLAG_DTIMEOUT | SDIO_FLAG_DBCKEND)) + { + if(__DAL_SD_GET_FLAG(hsd, SDIO_FLAG_RXFIFOHF)) + { + for(count = 0U; count < 8U; count++) + { + *pData = SDIO_ReadFIFO(hsd->Instance); + pData++; + } + } + + if((DAL_GetTick() - tickstart) >= SDMMC_DATATIMEOUT) + { + return DAL_SD_ERROR_TIMEOUT; + } + } + + if(__DAL_SD_GET_FLAG(hsd, SDIO_FLAG_DTIMEOUT)) + { + return DAL_SD_ERROR_DATA_TIMEOUT; + } + else if(__DAL_SD_GET_FLAG(hsd, SDIO_FLAG_DCRCFAIL)) + { + return DAL_SD_ERROR_DATA_CRC_FAIL; + } + else if(__DAL_SD_GET_FLAG(hsd, SDIO_FLAG_RXOVERR)) + { + return DAL_SD_ERROR_RX_OVERRUN; + } + else + { + /* Nothing to do */ + } + + while ((__DAL_SD_GET_FLAG(hsd, SDIO_FLAG_RXDAVL))) + { + *pData = SDIO_ReadFIFO(hsd->Instance); + pData++; + + if((DAL_GetTick() - tickstart) >= SDMMC_DATATIMEOUT) + { + return DAL_SD_ERROR_TIMEOUT; + } + } + + /* Clear all the static status flags*/ + __DAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_DATA_FLAGS); + + return DAL_SD_ERROR_NONE; +} + +/** + * @brief Returns the current card's status. + * @param hsd: Pointer to SD handle + * @param pCardStatus: pointer to the buffer that will contain the SD card + * status (Card Status register) + * @retval error state + */ +static uint32_t SD_SendStatus(SD_HandleTypeDef *hsd, uint32_t *pCardStatus) +{ + uint32_t errorstate; + + if(pCardStatus == NULL) + { + return DAL_SD_ERROR_PARAM; + } + + /* Send Status command */ + errorstate = SDMMC_CmdSendStatus(hsd->Instance, (uint32_t)(hsd->SdCard.RelCardAdd << 16U)); + if(errorstate != DAL_SD_ERROR_NONE) + { + return errorstate; + } + + /* Get SD card status */ + *pCardStatus = SDIO_GetResponse(hsd->Instance, SDIO_RES1); + + return DAL_SD_ERROR_NONE; +} + +/** + * @brief Enables the SDIO wide bus mode. + * @param hsd: pointer to SD handle + * @retval error state + */ +static uint32_t SD_WideBus_Enable(SD_HandleTypeDef *hsd) +{ + uint32_t scr[2U] = {0U, 0U}; + uint32_t errorstate; + + if((SDIO_GetResponse(hsd->Instance, SDIO_RES1) & SDMMC_CARD_LOCKED) == SDMMC_CARD_LOCKED) + { + return DAL_SD_ERROR_LOCK_UNLOCK_FAILED; + } + + /* Get SCR Register */ + errorstate = SD_FindSCR(hsd, scr); + if(errorstate != DAL_SD_ERROR_NONE) + { + return errorstate; + } + + /* If requested card supports wide bus operation */ + if((scr[1U] & SDMMC_WIDE_BUS_SUPPORT) != SDMMC_ALLZERO) + { + /* Send CMD55 APP_CMD with argument as card's RCA.*/ + errorstate = SDMMC_CmdAppCommand(hsd->Instance, (uint32_t)(hsd->SdCard.RelCardAdd << 16U)); + if(errorstate != DAL_SD_ERROR_NONE) + { + return errorstate; + } + + /* Send ACMD6 APP_CMD with argument as 2 for wide bus mode */ + errorstate = SDMMC_CmdBusWidth(hsd->Instance, 2U); + if(errorstate != DAL_SD_ERROR_NONE) + { + return errorstate; + } + + return DAL_SD_ERROR_NONE; + } + else + { + return DAL_SD_ERROR_REQUEST_NOT_APPLICABLE; + } +} + +/** + * @brief Disables the SDIO wide bus mode. + * @param hsd: Pointer to SD handle + * @retval error state + */ +static uint32_t SD_WideBus_Disable(SD_HandleTypeDef *hsd) +{ + uint32_t scr[2U] = {0U, 0U}; + uint32_t errorstate; + + if((SDIO_GetResponse(hsd->Instance, SDIO_RES1) & SDMMC_CARD_LOCKED) == SDMMC_CARD_LOCKED) + { + return DAL_SD_ERROR_LOCK_UNLOCK_FAILED; + } + + /* Get SCR Register */ + errorstate = SD_FindSCR(hsd, scr); + if(errorstate != DAL_SD_ERROR_NONE) + { + return errorstate; + } + + /* If requested card supports 1 bit mode operation */ + if((scr[1U] & SDMMC_SINGLE_BUS_SUPPORT) != SDMMC_ALLZERO) + { + /* Send CMD55 APP_CMD with argument as card's RCA */ + errorstate = SDMMC_CmdAppCommand(hsd->Instance, (uint32_t)(hsd->SdCard.RelCardAdd << 16U)); + if(errorstate != DAL_SD_ERROR_NONE) + { + return errorstate; + } + + /* Send ACMD6 APP_CMD with argument as 0 for single bus mode */ + errorstate = SDMMC_CmdBusWidth(hsd->Instance, 0U); + if(errorstate != DAL_SD_ERROR_NONE) + { + return errorstate; + } + + return DAL_SD_ERROR_NONE; + } + else + { + return DAL_SD_ERROR_REQUEST_NOT_APPLICABLE; + } +} + + +/** + * @brief Finds the SD card SCR register value. + * @param hsd: Pointer to SD handle + * @param pSCR: pointer to the buffer that will contain the SCR value + * @retval error state + */ +static uint32_t SD_FindSCR(SD_HandleTypeDef *hsd, uint32_t *pSCR) +{ + SDIO_DataInitTypeDef config; + uint32_t errorstate; + uint32_t tickstart = DAL_GetTick(); + uint32_t index = 0U; + uint32_t tempscr[2U] = {0U, 0U}; + uint32_t *scr = pSCR; + + /* Set Block Size To 8 Bytes */ + errorstate = SDMMC_CmdBlockLength(hsd->Instance, 8U); + if(errorstate != DAL_SD_ERROR_NONE) + { + return errorstate; + } + + /* Send CMD55 APP_CMD with argument as card's RCA */ + errorstate = SDMMC_CmdAppCommand(hsd->Instance, (uint32_t)((hsd->SdCard.RelCardAdd) << 16U)); + if(errorstate != DAL_SD_ERROR_NONE) + { + return errorstate; + } + + config.DataTimeOut = SDMMC_DATATIMEOUT; + config.DataLength = 8U; + config.DataBlockSize = SDIO_DATABLOCK_SIZE_8B; + config.TransferDir = SDIO_TRANSFER_DIR_TO_SDIO; + config.TransferMode = SDIO_TRANSFER_MODE_BLOCK; + config.DPSM = SDIO_DPSM_ENABLE; + (void)SDIO_ConfigData(hsd->Instance, &config); + + /* Send ACMD51 SD_APP_SEND_SCR with argument as 0 */ + errorstate = SDMMC_CmdSendSCR(hsd->Instance); + if(errorstate != DAL_SD_ERROR_NONE) + { + return errorstate; + } + + while(!__DAL_SD_GET_FLAG(hsd, SDIO_FLAG_RXOVERR | SDIO_FLAG_DCRCFAIL | SDIO_FLAG_DTIMEOUT)) + { + if(__DAL_SD_GET_FLAG(hsd, SDIO_FLAG_RXDAVL)) + { + *(tempscr + index) = SDIO_ReadFIFO(hsd->Instance); + index++; + } + else if(!__DAL_SD_GET_FLAG(hsd, SDIO_FLAG_RXACT)) + { + break; + } + + if((DAL_GetTick() - tickstart) >= SDMMC_DATATIMEOUT) + { + return DAL_SD_ERROR_TIMEOUT; + } + } + + if(__DAL_SD_GET_FLAG(hsd, SDIO_FLAG_DTIMEOUT)) + { + __DAL_SD_CLEAR_FLAG(hsd, SDIO_FLAG_DTIMEOUT); + + return DAL_SD_ERROR_DATA_TIMEOUT; + } + else if(__DAL_SD_GET_FLAG(hsd, SDIO_FLAG_DCRCFAIL)) + { + __DAL_SD_CLEAR_FLAG(hsd, SDIO_FLAG_DCRCFAIL); + + return DAL_SD_ERROR_DATA_CRC_FAIL; + } + else if(__DAL_SD_GET_FLAG(hsd, SDIO_FLAG_RXOVERR)) + { + __DAL_SD_CLEAR_FLAG(hsd, SDIO_FLAG_RXOVERR); + + return DAL_SD_ERROR_RX_OVERRUN; + } + else + { + /* No error flag set */ + /* Clear all the static flags */ + __DAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_DATA_FLAGS); + + *scr = (((tempscr[1] & SDMMC_0TO7BITS) << 24) | ((tempscr[1] & SDMMC_8TO15BITS) << 8) |\ + ((tempscr[1] & SDMMC_16TO23BITS) >> 8) | ((tempscr[1] & SDMMC_24TO31BITS) >> 24)); + scr++; + *scr = (((tempscr[0] & SDMMC_0TO7BITS) << 24) | ((tempscr[0] & SDMMC_8TO15BITS) << 8) |\ + ((tempscr[0] & SDMMC_16TO23BITS) >> 8) | ((tempscr[0] & SDMMC_24TO31BITS) >> 24)); + + } + + return DAL_SD_ERROR_NONE; +} + +/** + * @brief Wrap up reading in non-blocking mode. + * @param hsd: pointer to a SD_HandleTypeDef structure that contains + * the configuration information. + * @retval None + */ +static void SD_Read_IT(SD_HandleTypeDef *hsd) +{ + uint32_t count, data, dataremaining; + uint8_t* tmp; + + tmp = hsd->pRxBuffPtr; + dataremaining = hsd->RxXferSize; + + if (dataremaining > 0U) + { + /* Read data from SDIO Rx FIFO */ + for(count = 0U; count < 8U; count++) + { + data = SDIO_ReadFIFO(hsd->Instance); + *tmp = (uint8_t)(data & 0xFFU); + tmp++; + dataremaining--; + *tmp = (uint8_t)((data >> 8U) & 0xFFU); + tmp++; + dataremaining--; + *tmp = (uint8_t)((data >> 16U) & 0xFFU); + tmp++; + dataremaining--; + *tmp = (uint8_t)((data >> 24U) & 0xFFU); + tmp++; + dataremaining--; + } + + hsd->pRxBuffPtr = tmp; + hsd->RxXferSize = dataremaining; + } +} + +/** + * @brief Wrap up writing in non-blocking mode. + * @param hsd: pointer to a SD_HandleTypeDef structure that contains + * the configuration information. + * @retval None + */ +static void SD_Write_IT(SD_HandleTypeDef *hsd) +{ + uint32_t count, data, dataremaining; + uint8_t* tmp; + + tmp = hsd->pTxBuffPtr; + dataremaining = hsd->TxXferSize; + + if (dataremaining > 0U) + { + /* Write data to SDIO Tx FIFO */ + for(count = 0U; count < 8U; count++) + { + data = (uint32_t)(*tmp); + tmp++; + dataremaining--; + data |= ((uint32_t)(*tmp) << 8U); + tmp++; + dataremaining--; + data |= ((uint32_t)(*tmp) << 16U); + tmp++; + dataremaining--; + data |= ((uint32_t)(*tmp) << 24U); + tmp++; + dataremaining--; + (void)SDIO_WriteFIFO(hsd->Instance, &data); + } + + hsd->pTxBuffPtr = tmp; + hsd->TxXferSize = dataremaining; + } +} + +/** + * @} + */ + +#endif /* DAL_SD_MODULE_ENABLED */ + +/** + * @} + */ + +/** + * @} + */ + +#endif /* SDIO */ diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_sdram.c b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_sdram.c new file mode 100644 index 0000000000..97c4556a26 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_sdram.c @@ -0,0 +1,1169 @@ +/** + * + * @file apm32f4xx_dal_sdram.c + * @brief SDRAM DAL module driver. + * This file provides a generic firmware to drive SDRAM memories + * mounted as external device. + * + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + * + @verbatim + ============================================================================== + ##### How to use this driver ##### + ============================================================================== + [..] + This driver is a generic layered driver which contains a set of APIs used to + control SDRAM memories. It uses the DMC layer functions to interface + with SDRAM devices. + The following sequence should be followed to configure the DMC to interface + with SDRAM memories: + + (#) Declare a SDRAM_HandleTypeDef handle structure, for example: + SDRAM_HandleTypeDef hsdram + + (++) Fill the SDRAM_HandleTypeDef handle "Init" field with the allowed + values of the structure member. + + (++) Fill the SDRAM_HandleTypeDef handle "Instance" field with a predefined + base register instance for SDRAM device + + (#) Declare a DMC_SDRAM_TimingTypeDef structure; for example: + DMC_SDRAM_TimingTypeDef Timing; + and fill its fields with the allowed values of the structure member. + + (#) Initialize the SDRAM Controller by calling the function DAL_SDRAM_Init(). This function + performs the following sequence: + + (##) MSP hardware layer configuration using the function DAL_SDRAM_MspInit() + (##) Control register configuration using the DMC SDRAM interface function + DMC_SDRAM_Init() + (##) Timing register configuration using the DMC SDRAM interface function + DMC_SDRAM_Timing_Init() + (##) Program the SDRAM external device by applying its initialization sequence + according to the device plugged in your hardware. This step is mandatory + for accessing the SDRAM device. + + (#) At this stage you can perform read/write accesses from/to the memory connected + to the SDRAM Bank. You can perform either polling or DMA transfer using the + following APIs: + (++) DAL_SDRAM_Read()/DAL_SDRAM_Write() for polling read/write access + (++) DAL_SDRAM_Read_DMA()/DAL_SDRAM_Write_DMA() for DMA read/write transfer + + (#) You can continuously monitor the SDRAM device DAL state by calling the function + DAL_SDRAM_GetState() + + *** Callback registration *** + ============================================= + [..] + The compilation define USE_DAL_SDRAM_REGISTER_CALLBACKS when set to 1 + allows the user to configure dynamically the driver callbacks. + + Use Functions DAL_SDRAM_RegisterCallback() to register a user callback, + it allows to register following callbacks: + (+) MspInitCallback : SDRAM MspInit. + (+) MspDeInitCallback : SDRAM MspDeInit. + This function takes as parameters the DAL peripheral handle, the Callback ID + and a pointer to the user callback function. + + Use function DAL_SDRAM_UnRegisterCallback() to reset a callback to the default + weak (surcharged) function. It allows to reset following callbacks: + (+) MspInitCallback : SDRAM MspInit. + (+) MspDeInitCallback : SDRAM MspDeInit. + This function) takes as parameters the DAL peripheral handle and the Callback ID. + + By default, after the DAL_SDRAM_Init and if the state is DAL_SDRAM_STATE_RESET + all callbacks are reset to the corresponding legacy weak (surcharged) functions. + Exception done for MspInit and MspDeInit callbacks that are respectively + reset to the legacy weak (surcharged) functions in the DAL_SDRAM_Init + and DAL_SDRAM_DeInit only when these callbacks are null (not registered beforehand). + If not, MspInit or MspDeInit are not null, the DAL_SDRAM_Init and DAL_SDRAM_DeInit + keep and use the user MspInit/MspDeInit callbacks (registered beforehand) + + Callbacks can be registered/unregistered in READY state only. + Exception done for MspInit/MspDeInit callbacks that can be registered/unregistered + in READY or RESET state, thus registered (user) MspInit/DeInit callbacks can be used + during the Init/DeInit. + In that case first register the MspInit/MspDeInit user callbacks + using DAL_SDRAM_RegisterCallback before calling DAL_SDRAM_DeInit + or DAL_SDRAM_Init function. + + When The compilation define USE_DAL_SDRAM_REGISTER_CALLBACKS is set to 0 or + not defined, the callback registering feature is not available + and weak (surcharged) callbacks are used. + + @endverbatim + * + */ + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal.h" + +#if defined(DMC) + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +#ifdef DAL_SDRAM_MODULE_ENABLED + +/** @defgroup SDRAM SDRAM + * @brief SDRAM driver modules + * @{ + */ + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +static void SDRAM_DMACplt(DMA_HandleTypeDef *hdma); +static void SDRAM_DMACpltProt(DMA_HandleTypeDef *hdma); +static void SDRAM_DMAError(DMA_HandleTypeDef *hdma); + +/* Exported functions --------------------------------------------------------*/ +/** @defgroup SDRAM_Exported_Functions SDRAM Exported Functions + * @{ + */ + +/** @defgroup SDRAM_Exported_Functions_Group1 Initialization and de-initialization functions + * @brief Initialization and Configuration functions + * + @verbatim + ============================================================================== + ##### SDRAM Initialization and de_initialization functions ##### + ============================================================================== + [..] + This section provides functions allowing to initialize/de-initialize + the SDRAM memory + +@endverbatim + * @{ + */ + +/** + * @brief Performs the SDRAM device initialization sequence. + * @param hsdram pointer to a SDRAM_HandleTypeDef structure that contains + * the configuration information for SDRAM module. + * @param Timing Pointer to SDRAM control timing structure + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SDRAM_Init(SDRAM_HandleTypeDef *hsdram, DMC_SDRAM_TimingTypeDef *Timing) +{ + /* Check the SDRAM handle parameter */ + if (hsdram == NULL) + { + return DAL_ERROR; + } + + if (hsdram->State == DAL_SDRAM_STATE_RESET) + { + /* Allocate lock resource and initialize it */ + hsdram->Lock = DAL_UNLOCKED; +#if (USE_DAL_SDRAM_REGISTER_CALLBACKS == 1) + if (hsdram->MspInitCallback == NULL) + { + hsdram->MspInitCallback = DAL_SDRAM_MspInit; + } + hsdram->DmaXferCpltCallback = DAL_SDRAM_DMA_XferCpltCallback; + hsdram->DmaXferErrorCallback = DAL_SDRAM_DMA_XferErrorCallback; + + /* Init the low level hardware */ + hsdram->MspInitCallback(hsdram); +#else + /* Initialize the low level hardware (MSP) */ + DAL_SDRAM_MspInit(hsdram); +#endif /* USE_DAL_SDRAM_REGISTER_CALLBACKS */ + } + + /* Initialize the SDRAM controller state */ + hsdram->State = DAL_SDRAM_STATE_BUSY; + + /* Initialize SDRAM control Interface */ + (void)DMC_SDRAM_Init(hsdram->Instance, &(hsdram->Init)); + + /* Initialize SDRAM timing Interface */ + (void)DMC_SDRAM_Timing_Init(hsdram->Instance, Timing); + /* Update the SDRAM controller state */ + hsdram->State = DAL_SDRAM_STATE_READY; + + return DAL_OK; +} + +/** + * @brief Perform the SDRAM device initialization sequence. + * @param hsdram pointer to a SDRAM_HandleTypeDef structure that contains + * the configuration information for SDRAM module. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SDRAM_DeInit(SDRAM_HandleTypeDef *hsdram) +{ +#if (USE_DAL_SDRAM_REGISTER_CALLBACKS == 1) + if (hsdram->MspDeInitCallback == NULL) + { + hsdram->MspDeInitCallback = DAL_SDRAM_MspDeInit; + } + + /* DeInit the low level hardware */ + hsdram->MspDeInitCallback(hsdram); +#else + /* Initialize the low level hardware (MSP) */ + DAL_SDRAM_MspDeInit(hsdram); +#endif /* USE_DAL_SDRAM_REGISTER_CALLBACKS */ + + /* Configure the SDRAM registers with their reset values */ + (void)DMC_SDRAM_DeInit(hsdram->Instance); + + /* Reset the SDRAM controller state */ + hsdram->State = DAL_SDRAM_STATE_RESET; + + /* Release Lock */ + __DAL_UNLOCK(hsdram); + + return DAL_OK; +} + +/** + * @brief SDRAM MSP Init. + * @param hsdram pointer to a SDRAM_HandleTypeDef structure that contains + * the configuration information for SDRAM module. + * @retval None + */ +__weak void DAL_SDRAM_MspInit(SDRAM_HandleTypeDef *hsdram) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hsdram); + + /* NOTE: This function Should not be modified, when the callback is needed, + the DAL_SDRAM_MspInit could be implemented in the user file + */ +} + +/** + * @brief SDRAM MSP DeInit. + * @param hsdram pointer to a SDRAM_HandleTypeDef structure that contains + * the configuration information for SDRAM module. + * @retval None + */ +__weak void DAL_SDRAM_MspDeInit(SDRAM_HandleTypeDef *hsdram) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hsdram); + + /* NOTE: This function Should not be modified, when the callback is needed, + the DAL_SDRAM_MspDeInit could be implemented in the user file + */ +} + +/** + * @brief DMA transfer complete callback. + * @param hdma pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +__weak void DAL_SDRAM_DMA_XferCpltCallback(DMA_HandleTypeDef *hdma) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hdma); + + /* NOTE: This function Should not be modified, when the callback is needed, + the DAL_SDRAM_DMA_XferCpltCallback could be implemented in the user file + */ +} + +/** + * @brief DMA transfer complete error callback. + * @param hdma DMA handle + * @retval None + */ +__weak void DAL_SDRAM_DMA_XferErrorCallback(DMA_HandleTypeDef *hdma) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hdma); + + /* NOTE: This function Should not be modified, when the callback is needed, + the DAL_SDRAM_DMA_XferErrorCallback could be implemented in the user file + */ +} + +/** + * @} + */ + +/** @defgroup SDRAM_Exported_Functions_Group2 Input and Output functions + * @brief Input Output and memory control functions + * + @verbatim + ============================================================================== + ##### SDRAM Input and Output functions ##### + ============================================================================== + [..] + This section provides functions allowing to use and control the SDRAM memory + +@endverbatim + * @{ + */ + +/** + * @brief Reads 8-bit data buffer from the SDRAM memory. + * @param hsdram pointer to a SDRAM_HandleTypeDef structure that contains + * the configuration information for SDRAM module. + * @param pAddress Pointer to read start address + * @param pDstBuffer Pointer to destination buffer + * @param BufferSize Size of the buffer to read from memory + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SDRAM_Read_8b(SDRAM_HandleTypeDef *hsdram, uint32_t *pAddress, uint8_t *pDstBuffer, + uint32_t BufferSize) +{ + uint32_t size; + __IO uint8_t *pSdramAddress = (uint8_t *)pAddress; + uint8_t *pdestbuff = pDstBuffer; + DAL_SDRAM_StateTypeDef state = hsdram->State; + + /* Check the SDRAM controller state */ + if (state == DAL_SDRAM_STATE_BUSY) + { + return DAL_BUSY; + } + else if (state == DAL_SDRAM_STATE_READY) + { + /* Process Locked */ + __DAL_LOCK(hsdram); + + /* Update the SDRAM controller state */ + hsdram->State = DAL_SDRAM_STATE_BUSY; + + /* Read data from source */ + for (size = BufferSize; size != 0U; size--) + { + *pdestbuff = *(__IO uint8_t *)pSdramAddress; + pdestbuff++; + pSdramAddress++; + } + + /* Update the SDRAM controller state */ + hsdram->State = state; + + /* Process Unlocked */ + __DAL_UNLOCK(hsdram); + } + else + { + return DAL_ERROR; + } + + return DAL_OK; +} + +/** + * @brief Writes 8-bit data buffer to SDRAM memory. + * @param hsdram pointer to a SDRAM_HandleTypeDef structure that contains + * the configuration information for SDRAM module. + * @param pAddress Pointer to write start address + * @param pSrcBuffer Pointer to source buffer to write + * @param BufferSize Size of the buffer to write to memory + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SDRAM_Write_8b(SDRAM_HandleTypeDef *hsdram, uint32_t *pAddress, uint8_t *pSrcBuffer, + uint32_t BufferSize) +{ + uint32_t size; + __IO uint8_t *pSdramAddress = (uint8_t *)pAddress; + uint8_t *psrcbuff = pSrcBuffer; + + /* Check the SDRAM controller state */ + if (hsdram->State == DAL_SDRAM_STATE_BUSY) + { + return DAL_BUSY; + } + else if (hsdram->State == DAL_SDRAM_STATE_READY) + { + /* Process Locked */ + __DAL_LOCK(hsdram); + + /* Update the SDRAM controller state */ + hsdram->State = DAL_SDRAM_STATE_BUSY; + + /* Write data to memory */ + for (size = BufferSize; size != 0U; size--) + { + *(__IO uint8_t *)pSdramAddress = *psrcbuff; + psrcbuff++; + pSdramAddress++; + } + + /* Update the SDRAM controller state */ + hsdram->State = DAL_SDRAM_STATE_READY; + + /* Process Unlocked */ + __DAL_UNLOCK(hsdram); + } + else + { + return DAL_ERROR; + } + + return DAL_OK; +} + +/** + * @brief Reads 16-bit data buffer from the SDRAM memory. + * @param hsdram pointer to a SDRAM_HandleTypeDef structure that contains + * the configuration information for SDRAM module. + * @param pAddress Pointer to read start address + * @param pDstBuffer Pointer to destination buffer + * @param BufferSize Size of the buffer to read from memory + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SDRAM_Read_16b(SDRAM_HandleTypeDef *hsdram, uint32_t *pAddress, uint16_t *pDstBuffer, + uint32_t BufferSize) +{ + uint32_t size; + __IO uint32_t *pSdramAddress = pAddress; + uint16_t *pdestbuff = pDstBuffer; + DAL_SDRAM_StateTypeDef state = hsdram->State; + + /* Check the SDRAM controller state */ + if (state == DAL_SDRAM_STATE_BUSY) + { + return DAL_BUSY; + } + else if (state == DAL_SDRAM_STATE_READY) + { + /* Process Locked */ + __DAL_LOCK(hsdram); + + /* Update the SDRAM controller state */ + hsdram->State = DAL_SDRAM_STATE_BUSY; + + /* Read data from memory */ + for (size = BufferSize; size >= 2U ; size -= 2U) + { + *pdestbuff = (uint16_t)((*pSdramAddress) & 0x0000FFFFU); + pdestbuff++; + *pdestbuff = (uint16_t)(((*pSdramAddress) & 0xFFFF0000U) >> 16U); + pdestbuff++; + pSdramAddress++; + } + + /* Read last 16-bits if size is not 32-bits multiple */ + if ((BufferSize % 2U) != 0U) + { + *pdestbuff = (uint16_t)((*pSdramAddress) & 0x0000FFFFU); + } + + /* Update the SDRAM controller state */ + hsdram->State = state; + + /* Process Unlocked */ + __DAL_UNLOCK(hsdram); + } + else + { + return DAL_ERROR; + } + + return DAL_OK; +} + +/** + * @brief Writes 16-bit data buffer to SDRAM memory. + * @param hsdram pointer to a SDRAM_HandleTypeDef structure that contains + * the configuration information for SDRAM module. + * @param pAddress Pointer to write start address + * @param pSrcBuffer Pointer to source buffer to write + * @param BufferSize Size of the buffer to write to memory + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SDRAM_Write_16b(SDRAM_HandleTypeDef *hsdram, uint32_t *pAddress, uint16_t *pSrcBuffer, + uint32_t BufferSize) +{ + uint32_t size; + __IO uint32_t *psdramaddress = pAddress; + uint16_t *psrcbuff = pSrcBuffer; + + /* Check the SDRAM controller state */ + if (hsdram->State == DAL_SDRAM_STATE_BUSY) + { + return DAL_BUSY; + } + else if (hsdram->State == DAL_SDRAM_STATE_READY) + { + /* Process Locked */ + __DAL_LOCK(hsdram); + + /* Update the SDRAM controller state */ + hsdram->State = DAL_SDRAM_STATE_BUSY; + + /* Write data to memory */ + for (size = BufferSize; size >= 2U ; size -= 2U) + { + *psdramaddress = (uint32_t)(*psrcbuff); + psrcbuff++; + *psdramaddress |= ((uint32_t)(*psrcbuff) << 16U); + psrcbuff++; + psdramaddress++; + } + + /* Write last 16-bits if size is not 32-bits multiple */ + if ((BufferSize % 2U) != 0U) + { + *psdramaddress = ((uint32_t)(*psrcbuff) & 0x0000FFFFU) | ((*psdramaddress) & 0xFFFF0000U); + } + + /* Update the SDRAM controller state */ + hsdram->State = DAL_SDRAM_STATE_READY; + + /* Process Unlocked */ + __DAL_UNLOCK(hsdram); + } + else + { + return DAL_ERROR; + } + + return DAL_OK; +} + +/** + * @brief Reads 32-bit data buffer from the SDRAM memory. + * @param hsdram pointer to a SDRAM_HandleTypeDef structure that contains + * the configuration information for SDRAM module. + * @param pAddress Pointer to read start address + * @param pDstBuffer Pointer to destination buffer + * @param BufferSize Size of the buffer to read from memory + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SDRAM_Read_32b(SDRAM_HandleTypeDef *hsdram, uint32_t *pAddress, uint32_t *pDstBuffer, + uint32_t BufferSize) +{ + uint32_t size; + __IO uint32_t *pSdramAddress = (uint32_t *)pAddress; + uint32_t *pdestbuff = pDstBuffer; + DAL_SDRAM_StateTypeDef state = hsdram->State; + + /* Check the SDRAM controller state */ + if (state == DAL_SDRAM_STATE_BUSY) + { + return DAL_BUSY; + } + else if (state == DAL_SDRAM_STATE_READY) + { + /* Process Locked */ + __DAL_LOCK(hsdram); + + /* Update the SDRAM controller state */ + hsdram->State = DAL_SDRAM_STATE_BUSY; + + /* Read data from source */ + for (size = BufferSize; size != 0U; size--) + { + *pdestbuff = *(__IO uint32_t *)pSdramAddress; + pdestbuff++; + pSdramAddress++; + } + + /* Update the SDRAM controller state */ + hsdram->State = state; + + /* Process Unlocked */ + __DAL_UNLOCK(hsdram); + } + else + { + return DAL_ERROR; + } + + return DAL_OK; +} + +/** + * @brief Writes 32-bit data buffer to SDRAM memory. + * @param hsdram pointer to a SDRAM_HandleTypeDef structure that contains + * the configuration information for SDRAM module. + * @param pAddress Pointer to write start address + * @param pSrcBuffer Pointer to source buffer to write + * @param BufferSize Size of the buffer to write to memory + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SDRAM_Write_32b(SDRAM_HandleTypeDef *hsdram, uint32_t *pAddress, uint32_t *pSrcBuffer, + uint32_t BufferSize) +{ + uint32_t size; + __IO uint32_t *pSdramAddress = pAddress; + uint32_t *psrcbuff = pSrcBuffer; + + /* Check the SDRAM controller state */ + if (hsdram->State == DAL_SDRAM_STATE_BUSY) + { + return DAL_BUSY; + } + else if (hsdram->State == DAL_SDRAM_STATE_READY) + { + /* Process Locked */ + __DAL_LOCK(hsdram); + + /* Update the SDRAM controller state */ + hsdram->State = DAL_SDRAM_STATE_BUSY; + + /* Write data to memory */ + for (size = BufferSize; size != 0U; size--) + { + *pSdramAddress = *psrcbuff; + psrcbuff++; + pSdramAddress++; + } + + /* Update the SDRAM controller state */ + hsdram->State = DAL_SDRAM_STATE_READY; + + /* Process Unlocked */ + __DAL_UNLOCK(hsdram); + } + else + { + return DAL_ERROR; + } + + return DAL_OK; +} + +/** + * @brief Reads a Words data from the SDRAM memory using DMA transfer. + * @param hsdram pointer to a SDRAM_HandleTypeDef structure that contains + * the configuration information for SDRAM module. + * @param pAddress Pointer to read start address + * @param pDstBuffer Pointer to destination buffer + * @param BufferSize Size of the buffer to read from memory + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SDRAM_Read_DMA(SDRAM_HandleTypeDef *hsdram, uint32_t *pAddress, uint32_t *pDstBuffer, + uint32_t BufferSize) +{ + DAL_StatusTypeDef status; + DAL_SDRAM_StateTypeDef state = hsdram->State; + + /* Check the SDRAM controller state */ + if (state == DAL_SDRAM_STATE_BUSY) + { + status = DAL_BUSY; + } + else if (state == DAL_SDRAM_STATE_READY) + { + /* Process Locked */ + __DAL_LOCK(hsdram); + + /* Update the SDRAM controller state */ + hsdram->State = DAL_SDRAM_STATE_BUSY; + + /* Configure DMA user callbacks */ + if (state == DAL_SDRAM_STATE_READY) + { + hsdram->hdma->XferCpltCallback = SDRAM_DMACplt; + } + else + { + hsdram->hdma->XferCpltCallback = SDRAM_DMACpltProt; + } + hsdram->hdma->XferErrorCallback = SDRAM_DMAError; + + /* Enable the DMA Stream */ + status = DAL_DMA_Start_IT(hsdram->hdma, (uint32_t)pAddress, (uint32_t)pDstBuffer, (uint32_t)BufferSize); + + /* Process Unlocked */ + __DAL_UNLOCK(hsdram); + } + else + { + status = DAL_ERROR; + } + + return status; +} + +/** + * @brief Writes a Words data buffer to SDRAM memory using DMA transfer. + * @param hsdram pointer to a SDRAM_HandleTypeDef structure that contains + * the configuration information for SDRAM module. + * @param pAddress Pointer to write start address + * @param pSrcBuffer Pointer to source buffer to write + * @param BufferSize Size of the buffer to write to memory + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SDRAM_Write_DMA(SDRAM_HandleTypeDef *hsdram, uint32_t *pAddress, uint32_t *pSrcBuffer, + uint32_t BufferSize) +{ + DAL_StatusTypeDef status; + + /* Check the SDRAM controller state */ + if (hsdram->State == DAL_SDRAM_STATE_BUSY) + { + status = DAL_BUSY; + } + else if (hsdram->State == DAL_SDRAM_STATE_READY) + { + /* Process Locked */ + __DAL_LOCK(hsdram); + + /* Update the SDRAM controller state */ + hsdram->State = DAL_SDRAM_STATE_BUSY; + + /* Configure DMA user callbacks */ + hsdram->hdma->XferCpltCallback = SDRAM_DMACplt; + hsdram->hdma->XferErrorCallback = SDRAM_DMAError; + + /* Enable the DMA Stream */ + status = DAL_DMA_Start_IT(hsdram->hdma, (uint32_t)pSrcBuffer, (uint32_t)pAddress, (uint32_t)BufferSize); + + /* Process Unlocked */ + __DAL_UNLOCK(hsdram); + } + else + { + status = DAL_ERROR; + } + + return status; +} + +#if (USE_DAL_SDRAM_REGISTER_CALLBACKS == 1) +/** + * @brief Register a User SDRAM Callback + * To be used instead of the weak (surcharged) predefined callback + * @param hsdram : SDRAM handle + * @param CallbackId : ID of the callback to be registered + * This parameter can be one of the following values: + * @arg @ref DAL_SDRAM_MSP_INIT_CB_ID SDRAM MspInit callback ID + * @arg @ref DAL_SDRAM_MSP_DEINIT_CB_ID SDRAM MspDeInit callback ID + * @param pCallback : pointer to the Callback function + * @retval status + */ +DAL_StatusTypeDef DAL_SDRAM_RegisterCallback(SDRAM_HandleTypeDef *hsdram, DAL_SDRAM_CallbackIDTypeDef CallbackId, + pSDRAM_CallbackTypeDef pCallback) +{ + DAL_StatusTypeDef status = DAL_OK; + DAL_SDRAM_StateTypeDef state; + + if (pCallback == NULL) + { + return DAL_ERROR; + } + + /* Process locked */ + __DAL_LOCK(hsdram); + + state = hsdram->State; + if (state == DAL_SDRAM_STATE_READY) + { + switch (CallbackId) + { + case DAL_SDRAM_MSP_INIT_CB_ID : + hsdram->MspInitCallback = pCallback; + break; + case DAL_SDRAM_MSP_DEINIT_CB_ID : + hsdram->MspDeInitCallback = pCallback; + break; + default : + /* update return status */ + status = DAL_ERROR; + break; + } + } + else if (hsdram->State == DAL_SDRAM_STATE_RESET) + { + switch (CallbackId) + { + case DAL_SDRAM_MSP_INIT_CB_ID : + hsdram->MspInitCallback = pCallback; + break; + case DAL_SDRAM_MSP_DEINIT_CB_ID : + hsdram->MspDeInitCallback = pCallback; + break; + default : + /* update return status */ + status = DAL_ERROR; + break; + } + } + else + { + /* update return status */ + status = DAL_ERROR; + } + + /* Release Lock */ + __DAL_UNLOCK(hsdram); + return status; +} + +/** + * @brief Unregister a User SDRAM Callback + * SDRAM Callback is redirected to the weak (surcharged) predefined callback + * @param hsdram : SDRAM handle + * @param CallbackId : ID of the callback to be unregistered + * This parameter can be one of the following values: + * @arg @ref DAL_SDRAM_MSP_INIT_CB_ID SDRAM MspInit callback ID + * @arg @ref DAL_SDRAM_MSP_DEINIT_CB_ID SDRAM MspDeInit callback ID + * @arg @ref DAL_SDRAM_DMA_XFER_CPLT_CB_ID SDRAM DMA Xfer Complete callback ID + * @arg @ref DAL_SDRAM_DMA_XFER_ERR_CB_ID SDRAM DMA Xfer Error callback ID + * @retval status + */ +DAL_StatusTypeDef DAL_SDRAM_UnRegisterCallback(SDRAM_HandleTypeDef *hsdram, DAL_SDRAM_CallbackIDTypeDef CallbackId) +{ + DAL_StatusTypeDef status = DAL_OK; + DAL_SDRAM_StateTypeDef state; + + /* Process locked */ + __DAL_LOCK(hsdram); + + state = hsdram->State; + if (state == DAL_SDRAM_STATE_READY) + { + switch (CallbackId) + { + case DAL_SDRAM_MSP_INIT_CB_ID : + hsdram->MspInitCallback = DAL_SDRAM_MspInit; + break; + case DAL_SDRAM_MSP_DEINIT_CB_ID : + hsdram->MspDeInitCallback = DAL_SDRAM_MspDeInit; + break; + case DAL_SDRAM_DMA_XFER_CPLT_CB_ID : + hsdram->DmaXferCpltCallback = DAL_SDRAM_DMA_XferCpltCallback; + break; + case DAL_SDRAM_DMA_XFER_ERR_CB_ID : + hsdram->DmaXferErrorCallback = DAL_SDRAM_DMA_XferErrorCallback; + break; + default : + /* update return status */ + status = DAL_ERROR; + break; + } + } + else if (hsdram->State == DAL_SDRAM_STATE_RESET) + { + switch (CallbackId) + { + case DAL_SDRAM_MSP_INIT_CB_ID : + hsdram->MspInitCallback = DAL_SDRAM_MspInit; + break; + case DAL_SDRAM_MSP_DEINIT_CB_ID : + hsdram->MspDeInitCallback = DAL_SDRAM_MspDeInit; + break; + default : + /* update return status */ + status = DAL_ERROR; + break; + } + } + else + { + /* update return status */ + status = DAL_ERROR; + } + + /* Release Lock */ + __DAL_UNLOCK(hsdram); + return status; +} + +/** + * @brief Register a User SDRAM Callback for DMA transfers + * To be used instead of the weak (surcharged) predefined callback + * @param hsdram : SDRAM handle + * @param CallbackId : ID of the callback to be registered + * This parameter can be one of the following values: + * @arg @ref DAL_SDRAM_DMA_XFER_CPLT_CB_ID SDRAM DMA Xfer Complete callback ID + * @arg @ref DAL_SDRAM_DMA_XFER_ERR_CB_ID SDRAM DMA Xfer Error callback ID + * @param pCallback : pointer to the Callback function + * @retval status + */ +DAL_StatusTypeDef DAL_SDRAM_RegisterDmaCallback(SDRAM_HandleTypeDef *hsdram, DAL_SDRAM_CallbackIDTypeDef CallbackId, + pSDRAM_DmaCallbackTypeDef pCallback) +{ + DAL_StatusTypeDef status = DAL_OK; + DAL_SDRAM_StateTypeDef state; + + if (pCallback == NULL) + { + return DAL_ERROR; + } + + /* Process locked */ + __DAL_LOCK(hsdram); + + state = hsdram->State; + if (state == DAL_SDRAM_STATE_READY) + { + switch (CallbackId) + { + case DAL_SDRAM_DMA_XFER_CPLT_CB_ID : + hsdram->DmaXferCpltCallback = pCallback; + break; + case DAL_SDRAM_DMA_XFER_ERR_CB_ID : + hsdram->DmaXferErrorCallback = pCallback; + break; + default : + /* update return status */ + status = DAL_ERROR; + break; + } + } + else + { + /* update return status */ + status = DAL_ERROR; + } + + /* Release Lock */ + __DAL_UNLOCK(hsdram); + return status; +} +#endif /* USE_DAL_SDRAM_REGISTER_CALLBACKS */ + +/** + * @} + */ + +/** @defgroup SDRAM_Exported_Functions_Group3 Control functions + * @brief management functions + * +@verbatim + ============================================================================== + ##### SDRAM Control functions ##### + ============================================================================== + [..] + This subsection provides a set of functions allowing to control dynamically + the SDRAM interface. + +@endverbatim + * @{ + */ + +/** + * @brief Programs the SDRAM Memory Refresh period. + * @param hsdram pointer to a SDRAM_HandleTypeDef structure that contains + * the configuration information for SDRAM module. + * @param RefreshPeriod The SDRAM refresh period value + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SDRAM_ProgramRefreshPeriod(SDRAM_HandleTypeDef *hsdram, uint32_t RefreshPeriod) +{ + /* Check the SDRAM controller state */ + if (hsdram->State == DAL_SDRAM_STATE_BUSY) + { + return DAL_BUSY; + } + else if (hsdram->State == DAL_SDRAM_STATE_READY) + { + /* Update the SDRAM state */ + hsdram->State = DAL_SDRAM_STATE_BUSY; + + /* Program the refresh period */ + (void)DMC_SDRAM_ProgramRefreshPeriod(hsdram->Instance, RefreshPeriod); + + /* Update the SDRAM state */ + hsdram->State = DAL_SDRAM_STATE_READY; + } + else + { + return DAL_ERROR; + } + + return DAL_OK; +} + +/** + * @brief Sets the Number of consecutive SDRAM Memory open bank. + * @param hsdram pointer to a SDRAM_HandleTypeDef structure that contains + * the configuration information for SDRAM module. + * @param OpenBankNumber The SDRAM open bank number + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SDRAM_SetOpenBankNumber(SDRAM_HandleTypeDef *hsdram, uint32_t OpenBankNumber) +{ + /* Check the SDRAM controller state */ + if (hsdram->State == DAL_SDRAM_STATE_BUSY) + { + return DAL_BUSY; + } + else if (hsdram->State == DAL_SDRAM_STATE_READY) + { + /* Update the SDRAM state */ + hsdram->State = DAL_SDRAM_STATE_BUSY; + + /* Set the open bank number */ + (void)DMC_SDRAM_SetOpenBankNumber(hsdram->Instance, OpenBankNumber); + + /* Update the SDRAM state */ + hsdram->State = DAL_SDRAM_STATE_READY; + } + else + { + return DAL_ERROR; + } + + return DAL_OK; +} + +/** + * @brief Returns the SDRAM memory current mode. + * @param hsdram pointer to a SDRAM_HandleTypeDef structure that contains + * the configuration information for SDRAM module. + * @retval The SDRAM memory mode. + */ +uint32_t DAL_SDRAM_GetModeStatus(SDRAM_HandleTypeDef *hsdram) +{ + /* Return the SDRAM memory current mode */ + return (DMC_SDRAM_GetModeStatus(hsdram->Instance)); +} + +/** + * @} + */ + +/** @defgroup SDRAM_Exported_Functions_Group4 State functions + * @brief Peripheral State functions + * +@verbatim + ============================================================================== + ##### SDRAM State functions ##### + ============================================================================== + [..] + This subsection permits to get in run-time the status of the SDRAM controller + and the data flow. + +@endverbatim + * @{ + */ + +/** + * @brief Returns the SDRAM state. + * @param hsdram pointer to a SDRAM_HandleTypeDef structure that contains + * the configuration information for SDRAM module. + * @retval DAL state + */ +DAL_SDRAM_StateTypeDef DAL_SDRAM_GetState(SDRAM_HandleTypeDef *hsdram) +{ + return hsdram->State; +} + +/** + * @} + */ + +/** + * @} + */ + +/** + * @brief DMA SDRAM process complete callback. + * @param hdma : DMA handle + * @retval None + */ +static void SDRAM_DMACplt(DMA_HandleTypeDef *hdma) +{ + SDRAM_HandleTypeDef *hsdram = (SDRAM_HandleTypeDef *)(hdma->Parent); + + /* Disable the DMA channel */ + __DAL_DMA_DISABLE(hdma); + + /* Update the SDRAM controller state */ + hsdram->State = DAL_SDRAM_STATE_READY; + +#if (USE_DAL_SDRAM_REGISTER_CALLBACKS == 1) + hsdram->DmaXferCpltCallback(hdma); +#else + DAL_SDRAM_DMA_XferCpltCallback(hdma); +#endif /* USE_DAL_SDRAM_REGISTER_CALLBACKS */ +} + +/** + * @brief DMA SRAM process complete callback. + * @param hdma : DMA handle + * @retval None + */ +static void SDRAM_DMACpltProt(DMA_HandleTypeDef *hdma) +{ + SDRAM_HandleTypeDef *hsdram = (SDRAM_HandleTypeDef *)(hdma->Parent); + + /* Disable the DMA channel */ + __DAL_DMA_DISABLE(hdma); + + /* Update the SDRAM controller state */ + hsdram->State = DAL_SDRAM_STATE_WRITE_PROTECTED; + +#if (USE_DAL_SDRAM_REGISTER_CALLBACKS == 1) + hsdram->DmaXferCpltCallback(hdma); +#else + DAL_SDRAM_DMA_XferCpltCallback(hdma); +#endif /* USE_DAL_SDRAM_REGISTER_CALLBACKS */ +} + +/** + * @brief DMA SDRAM error callback. + * @param hdma : DMA handle + * @retval None + */ +static void SDRAM_DMAError(DMA_HandleTypeDef *hdma) +{ + SDRAM_HandleTypeDef *hsdram = (SDRAM_HandleTypeDef *)(hdma->Parent); + + /* Disable the DMA channel */ + __DAL_DMA_DISABLE(hdma); + + /* Update the SDRAM controller state */ + hsdram->State = DAL_SDRAM_STATE_ERROR; + +#if (USE_DAL_SDRAM_REGISTER_CALLBACKS == 1) + hsdram->DmaXferErrorCallback(hdma); +#else + DAL_SDRAM_DMA_XferErrorCallback(hdma); +#endif /* USE_DAL_SDRAM_REGISTER_CALLBACKS */ +} + +/** + * @} + */ + +#endif /* DAL_SDRAM_MODULE_ENABLED */ + +/** + * @} + */ + +#endif /* DMC */ diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_smartcard.c b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_smartcard.c new file mode 100644 index 0000000000..0da779de34 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_smartcard.c @@ -0,0 +1,2385 @@ +/** + * + * @file apm32f4xx_dal_smartcard.c + * @brief SMARTCARD DAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the SMARTCARD peripheral: + * + Initialization and de-initialization functions + * + IO operation functions + * + Peripheral Control functions + * + Peripheral State and Error functions + * + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + * + @verbatim + ============================================================================== + ##### How to use this driver ##### + ============================================================================== + [..] + The SMARTCARD DAL driver can be used as follows: + + (#) Declare a SMARTCARD_HandleTypeDef handle structure. + (#) Initialize the SMARTCARD low level resources by implementing the DAL_SMARTCARD_MspInit() API: + (##) Enable the interface clock of the USARTx associated to the SMARTCARD. + (##) SMARTCARD pins configuration: + (+++) Enable the clock for the SMARTCARD GPIOs. + (+++) Configure SMARTCARD pins as alternate function pull-up. + (##) NVIC configuration if you need to use interrupt process (DAL_SMARTCARD_Transmit_IT() + and DAL_SMARTCARD_Receive_IT() APIs): + (+++) Configure the USARTx interrupt priority. + (+++) Enable the NVIC USART IRQ handle. + (##) DMA Configuration if you need to use DMA process (DAL_SMARTCARD_Transmit_DMA() + and DAL_SMARTCARD_Receive_DMA() APIs): + (+++) Declare a DMA handle structure for the Tx/Rx stream. + (+++) Enable the DMAx interface clock. + (+++) Configure the declared DMA handle structure with the required Tx/Rx parameters. + (+++) Configure the DMA Tx/Rx stream. + (+++) Associate the initialized DMA handle to the SMARTCARD DMA Tx/Rx handle. + (+++) Configure the priority and enable the NVIC for the transfer complete interrupt on the DMA Tx/Rx stream. + (+++) Configure the USARTx interrupt priority and enable the NVIC USART IRQ handle + (used for last byte sending completion detection in DMA non circular mode) + + (#) Program the Baud Rate, Word Length , Stop Bit, Parity, Hardware + flow control and Mode(Receiver/Transmitter) in the SMARTCARD Init structure. + + (#) Initialize the SMARTCARD registers by calling the DAL_SMARTCARD_Init() API: + (++) These APIs configure also the low level Hardware GPIO, CLOCK, CORTEX...etc) + by calling the customized DAL_SMARTCARD_MspInit() API. + [..] + (@) The specific SMARTCARD interrupts (Transmission complete interrupt, + RXNE interrupt and Error Interrupts) will be managed using the macros + __DAL_SMARTCARD_ENABLE_IT() and __DAL_SMARTCARD_DISABLE_IT() inside the transmit and receive process. + + [..] + Three operation modes are available within this driver : + + *** Polling mode IO operation *** + ================================= + [..] + (+) Send an amount of data in blocking mode using DAL_SMARTCARD_Transmit() + (+) Receive an amount of data in blocking mode using DAL_SMARTCARD_Receive() + + *** Interrupt mode IO operation *** + =================================== + [..] + (+) Send an amount of data in non blocking mode using DAL_SMARTCARD_Transmit_IT() + (+) At transmission end of transfer DAL_SMARTCARD_TxCpltCallback is executed and user can + add his own code by customization of function pointer DAL_SMARTCARD_TxCpltCallback + (+) Receive an amount of data in non blocking mode using DAL_SMARTCARD_Receive_IT() + (+) At reception end of transfer DAL_SMARTCARD_RxCpltCallback is executed and user can + add his own code by customization of function pointer DAL_SMARTCARD_RxCpltCallback + (+) In case of transfer Error, DAL_SMARTCARD_ErrorCallback() function is executed and user can + add his own code by customization of function pointer DAL_SMARTCARD_ErrorCallback + + *** DMA mode IO operation *** + ============================== + [..] + (+) Send an amount of data in non blocking mode (DMA) using DAL_SMARTCARD_Transmit_DMA() + (+) At transmission end of transfer DAL_SMARTCARD_TxCpltCallback is executed and user can + add his own code by customization of function pointer DAL_SMARTCARD_TxCpltCallback + (+) Receive an amount of data in non blocking mode (DMA) using DAL_SMARTCARD_Receive_DMA() + (+) At reception end of transfer DAL_SMARTCARD_RxCpltCallback is executed and user can + add his own code by customization of function pointer DAL_SMARTCARD_RxCpltCallback + (+) In case of transfer Error, DAL_SMARTCARD_ErrorCallback() function is executed and user can + add his own code by customization of function pointer DAL_SMARTCARD_ErrorCallback + + *** SMARTCARD DAL driver macros list *** + ======================================== + [..] + Below the list of most used macros in SMARTCARD DAL driver. + + (+) __DAL_SMARTCARD_ENABLE: Enable the SMARTCARD peripheral + (+) __DAL_SMARTCARD_DISABLE: Disable the SMARTCARD peripheral + (+) __DAL_SMARTCARD_GET_FLAG : Check whether the specified SMARTCARD flag is set or not + (+) __DAL_SMARTCARD_CLEAR_FLAG : Clear the specified SMARTCARD pending flag + (+) __DAL_SMARTCARD_ENABLE_IT: Enable the specified SMARTCARD interrupt + (+) __DAL_SMARTCARD_DISABLE_IT: Disable the specified SMARTCARD interrupt + + [..] + (@) You can refer to the SMARTCARD DAL driver header file for more useful macros + + ##### Callback registration ##### + ================================== + + [..] + The compilation define USE_DAL_SMARTCARD_REGISTER_CALLBACKS when set to 1 + allows the user to configure dynamically the driver callbacks. + + [..] + Use Function DAL_SMARTCARD_RegisterCallback() to register a user callback. + Function DAL_SMARTCARD_RegisterCallback() allows to register following callbacks: + (+) TxCpltCallback : Tx Complete Callback. + (+) RxCpltCallback : Rx Complete Callback. + (+) ErrorCallback : Error Callback. + (+) AbortCpltCallback : Abort Complete Callback. + (+) AbortTransmitCpltCallback : Abort Transmit Complete Callback. + (+) AbortReceiveCpltCallback : Abort Receive Complete Callback. + (+) MspInitCallback : SMARTCARD MspInit. + (+) MspDeInitCallback : SMARTCARD MspDeInit. + This function takes as parameters the DAL peripheral handle, the Callback ID + and a pointer to the user callback function. + + [..] + Use function DAL_SMARTCARD_UnRegisterCallback() to reset a callback to the default + weak (surcharged) function. + DAL_SMARTCARD_UnRegisterCallback() takes as parameters the DAL peripheral handle, + and the Callback ID. + This function allows to reset following callbacks: + (+) TxCpltCallback : Tx Complete Callback. + (+) RxCpltCallback : Rx Complete Callback. + (+) ErrorCallback : Error Callback. + (+) AbortCpltCallback : Abort Complete Callback. + (+) AbortTransmitCpltCallback : Abort Transmit Complete Callback. + (+) AbortReceiveCpltCallback : Abort Receive Complete Callback. + (+) MspInitCallback : SMARTCARD MspInit. + (+) MspDeInitCallback : SMARTCARD MspDeInit. + + [..] + By default, after the DAL_SMARTCARD_Init() and when the state is DAL_SMARTCARD_STATE_RESET + all callbacks are set to the corresponding weak (surcharged) functions: + examples DAL_SMARTCARD_TxCpltCallback(), DAL_SMARTCARD_RxCpltCallback(). + Exception done for MspInit and MspDeInit functions that are respectively + reset to the legacy weak (surcharged) functions in the DAL_SMARTCARD_Init() + and DAL_SMARTCARD_DeInit() only when these callbacks are null (not registered beforehand). + If not, MspInit or MspDeInit are not null, the DAL_SMARTCARD_Init() and DAL_SMARTCARD_DeInit() + keep and use the user MspInit/MspDeInit callbacks (registered beforehand). + + [..] + Callbacks can be registered/unregistered in DAL_SMARTCARD_STATE_READY state only. + Exception done MspInit/MspDeInit that can be registered/unregistered + in DAL_SMARTCARD_STATE_READY or DAL_SMARTCARD_STATE_RESET state, thus registered (user) + MspInit/DeInit callbacks can be used during the Init/DeInit. + In that case first register the MspInit/MspDeInit user callbacks + using DAL_SMARTCARD_RegisterCallback() before calling DAL_SMARTCARD_DeInit() + or DAL_SMARTCARD_Init() function. + + [..] + When The compilation define USE_DAL_SMARTCARD_REGISTER_CALLBACKS is set to 0 or + not defined, the callback registration feature is not available + and weak (surcharged) callbacks are used. + + @endverbatim + * + */ + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @defgroup SMARTCARD SMARTCARD + * @brief DAL SMARTCARD module driver + * @{ + */ +#ifdef DAL_SMARTCARD_MODULE_ENABLED +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/** @addtogroup SMARTCARD_Private_Constants + * @{ + */ +/** + * @} + */ + +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/** @addtogroup SMARTCARD_Private_Functions + * @{ + */ +#if (USE_DAL_SMARTCARD_REGISTER_CALLBACKS == 1) +void SMARTCARD_InitCallbacksToDefault(SMARTCARD_HandleTypeDef *hsc); +#endif /* USE_DAL_SMARTCARD_REGISTER_CALLBACKS */ +static void SMARTCARD_EndTxTransfer(SMARTCARD_HandleTypeDef *hsc); +static void SMARTCARD_EndRxTransfer(SMARTCARD_HandleTypeDef *hsc); +static void SMARTCARD_SetConfig (SMARTCARD_HandleTypeDef *hsc); +static DAL_StatusTypeDef SMARTCARD_Transmit_IT(SMARTCARD_HandleTypeDef *hsc); +static DAL_StatusTypeDef SMARTCARD_EndTransmit_IT(SMARTCARD_HandleTypeDef *hsc); +static DAL_StatusTypeDef SMARTCARD_Receive_IT(SMARTCARD_HandleTypeDef *hsc); +static void SMARTCARD_DMATransmitCplt(DMA_HandleTypeDef *hdma); +static void SMARTCARD_DMAReceiveCplt(DMA_HandleTypeDef *hdma); +static void SMARTCARD_DMAError(DMA_HandleTypeDef *hdma); +static void SMARTCARD_DMAAbortOnError(DMA_HandleTypeDef *hdma); +static void SMARTCARD_DMATxAbortCallback(DMA_HandleTypeDef *hdma); +static void SMARTCARD_DMARxAbortCallback(DMA_HandleTypeDef *hdma); +static void SMARTCARD_DMATxOnlyAbortCallback(DMA_HandleTypeDef *hdma); +static void SMARTCARD_DMARxOnlyAbortCallback(DMA_HandleTypeDef *hdma); +static DAL_StatusTypeDef SMARTCARD_WaitOnFlagUntilTimeout(SMARTCARD_HandleTypeDef *hsc, uint32_t Flag, FlagStatus Status, uint32_t Tickstart, uint32_t Timeout); +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +/** @defgroup SMARTCARD_Exported_Functions SMARTCARD Exported Functions + * @{ + */ + +/** @defgroup SMARTCARD_Exported_Functions_Group1 SmartCard Initialization and de-initialization functions + * @brief Initialization and Configuration functions + * +@verbatim + ============================================================================== + ##### Initialization and Configuration functions ##### + ============================================================================== + [..] + This subsection provides a set of functions allowing to initialize the USART + in Smartcard mode. + [..] + The Smartcard interface is designed to support asynchronous protocol Smartcards as + defined in the ISO 7816-3 standard. + [..] + The USART can provide a clock to the smartcard through the SCLK output. + In smartcard mode, SCLK is not associated to the communication but is simply derived + from the internal peripheral input clock through a 5-bit prescaler. + [..] + (+) For the Smartcard mode only these parameters can be configured: + (++) Baud Rate + (++) Word Length => Should be 9 bits (8 bits + parity) + (++) Stop Bit + (++) Parity: => Should be enabled + (++) USART polarity + (++) USART phase + (++) USART LastBit + (++) Receiver/transmitter modes + (++) Prescaler + (++) GuardTime + (++) NACKState: The Smartcard NACK state + + (+) Recommended SmartCard interface configuration to get the Answer to Reset from the Card: + (++) Word Length = 9 Bits + (++) 1.5 Stop Bit + (++) Even parity + (++) BaudRate = 12096 baud + (++) Tx and Rx enabled + [..] + Please refer to the ISO 7816-3 specification for more details. + + [..] + (@) It is also possible to choose 0.5 stop bit for receiving but it is recommended + to use 1.5 stop bits for both transmitting and receiving to avoid switching + between the two configurations. + [..] + The DAL_SMARTCARD_Init() function follows the USART SmartCard configuration + procedures (details for the procedures are available in reference manual). + +@endverbatim + + The SMARTCARD frame format is given in the following table: + +-------------------------------------------------------------+ + | M bit | PCE bit | SMARTCARD frame | + |---------------------|---------------------------------------| + | 1 | 1 | | SB | 8 bit data | PB | STB | | + +-------------------------------------------------------------+ + * @{ + */ + +/** + * @brief Initializes the SmartCard mode according to the specified + * parameters in the SMARTCARD_InitTypeDef and create the associated handle. + * @param hsc Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for SMARTCARD module. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SMARTCARD_Init(SMARTCARD_HandleTypeDef *hsc) +{ + /* Check the SMARTCARD handle allocation */ + if(hsc == NULL) + { + return DAL_ERROR; + } + + /* Check the parameters */ + ASSERT_PARAM(IS_SMARTCARD_INSTANCE(hsc->Instance)); + ASSERT_PARAM(IS_SMARTCARD_NACK_STATE(hsc->Init.NACKState)); + + if(hsc->gState == DAL_SMARTCARD_STATE_RESET) + { + /* Allocate lock resource and initialize it */ + hsc->Lock = DAL_UNLOCKED; + +#if USE_DAL_SMARTCARD_REGISTER_CALLBACKS == 1 + SMARTCARD_InitCallbacksToDefault(hsc); + + if (hsc->MspInitCallback == NULL) + { + hsc->MspInitCallback = DAL_SMARTCARD_MspInit; + } + + /* Init the low level hardware */ + hsc->MspInitCallback(hsc); +#else + /* Init the low level hardware : GPIO, CLOCK */ + DAL_SMARTCARD_MspInit(hsc); +#endif /* USE_DAL_SMARTCARD_REGISTER_CALLBACKS */ + } + + hsc->gState = DAL_SMARTCARD_STATE_BUSY; + + /* Set the Prescaler */ + MODIFY_REG(hsc->Instance->GTPSC, USART_GTPSC_PSC, hsc->Init.Prescaler); + + /* Set the Guard Time */ + MODIFY_REG(hsc->Instance->GTPSC, USART_GTPSC_GRDT, ((hsc->Init.GuardTime)<<8U)); + + /* Set the Smartcard Communication parameters */ + SMARTCARD_SetConfig(hsc); + + /* In SmartCard mode, the following bits must be kept cleared: + - LINEN bit in the USART_CTRL2 register + - HDSEL and IREN bits in the USART_CTRL3 register.*/ + CLEAR_BIT(hsc->Instance->CTRL2, USART_CTRL2_LINMEN); + CLEAR_BIT(hsc->Instance->CTRL3, (USART_CTRL3_IREN | USART_CTRL3_HDEN)); + + /* Enable the SMARTCARD Parity Error Interrupt */ + SET_BIT(hsc->Instance->CTRL1, USART_CTRL1_PEIEN); + + /* Enable the SMARTCARD Framing Error Interrupt */ + SET_BIT(hsc->Instance->CTRL3, USART_CTRL3_ERRIEN); + + /* Enable the Peripheral */ + __DAL_SMARTCARD_ENABLE(hsc); + + /* Configure the Smartcard NACK state */ + MODIFY_REG(hsc->Instance->CTRL3, USART_CTRL3_SCNACKEN, hsc->Init.NACKState); + + /* Enable the SC mode by setting the SCEN bit in the CTRL3 register */ + hsc->Instance->CTRL3 |= (USART_CTRL3_SCEN); + + /* Initialize the SMARTCARD state*/ + hsc->ErrorCode = DAL_SMARTCARD_ERROR_NONE; + hsc->gState= DAL_SMARTCARD_STATE_READY; + hsc->RxState= DAL_SMARTCARD_STATE_READY; + + return DAL_OK; +} + +/** + * @brief DeInitializes the USART SmartCard peripheral + * @param hsc Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for SMARTCARD module. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SMARTCARD_DeInit(SMARTCARD_HandleTypeDef *hsc) +{ + /* Check the SMARTCARD handle allocation */ + if(hsc == NULL) + { + return DAL_ERROR; + } + + /* Check the parameters */ + ASSERT_PARAM(IS_SMARTCARD_INSTANCE(hsc->Instance)); + + hsc->gState = DAL_SMARTCARD_STATE_BUSY; + + /* Disable the Peripheral */ + __DAL_SMARTCARD_DISABLE(hsc); + + /* DeInit the low level hardware */ +#if USE_DAL_SMARTCARD_REGISTER_CALLBACKS == 1 + if (hsc->MspDeInitCallback == NULL) + { + hsc->MspDeInitCallback = DAL_SMARTCARD_MspDeInit; + } + /* DeInit the low level hardware */ + hsc->MspDeInitCallback(hsc); +#else + DAL_SMARTCARD_MspDeInit(hsc); +#endif /* USE_DAL_SMARTCARD_REGISTER_CALLBACKS */ + + hsc->ErrorCode = DAL_SMARTCARD_ERROR_NONE; + hsc->gState = DAL_SMARTCARD_STATE_RESET; + hsc->RxState = DAL_SMARTCARD_STATE_RESET; + + /* Release Lock */ + __DAL_UNLOCK(hsc); + + return DAL_OK; +} + +/** + * @brief SMARTCARD MSP Init + * @param hsc Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for SMARTCARD module. + * @retval None + */ +__weak void DAL_SMARTCARD_MspInit(SMARTCARD_HandleTypeDef *hsc) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hsc); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_SMARTCARD_MspInit can be implemented in the user file + */ +} + +/** + * @brief SMARTCARD MSP DeInit + * @param hsc Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for SMARTCARD module. + * @retval None + */ +__weak void DAL_SMARTCARD_MspDeInit(SMARTCARD_HandleTypeDef *hsc) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hsc); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_SMARTCARD_MspDeInit can be implemented in the user file + */ +} + +#if (USE_DAL_SMARTCARD_REGISTER_CALLBACKS == 1) +/** + * @brief Register a User SMARTCARD Callback + * To be used instead of the weak predefined callback + * @param hsc smartcard handle + * @param CallbackID ID of the callback to be registered + * This parameter can be one of the following values: + * @arg @ref DAL_SMARTCARD_TX_COMPLETE_CB_ID Tx Complete Callback ID + * @arg @ref DAL_SMARTCARD_RX_COMPLETE_CB_ID Rx Complete Callback ID + * @arg @ref DAL_SMARTCARD_ERROR_CB_ID Error Callback ID + * @arg @ref DAL_SMARTCARD_ABORT_COMPLETE_CB_ID Abort Complete Callback ID + * @arg @ref DAL_SMARTCARD_ABORT_TRANSMIT_COMPLETE_CB_ID Abort Transmit Complete Callback ID + * @arg @ref DAL_SMARTCARD_ABORT_RECEIVE_COMPLETE_CB_ID Abort Receive Complete Callback ID + * @arg @ref DAL_SMARTCARD_MSPINIT_CB_ID MspInit Callback ID + * @arg @ref DAL_SMARTCARD_MSPDEINIT_CB_ID MspDeInit Callback ID + * @param pCallback pointer to the Callback function + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SMARTCARD_RegisterCallback(SMARTCARD_HandleTypeDef *hsc, DAL_SMARTCARD_CallbackIDTypeDef CallbackID, pSMARTCARD_CallbackTypeDef pCallback) +{ + DAL_StatusTypeDef status = DAL_OK; + + if (pCallback == NULL) + { + /* Update the error code */ + hsc->ErrorCode |= DAL_SMARTCARD_ERROR_INVALID_CALLBACK; + + return DAL_ERROR; + } + /* Process locked */ + __DAL_LOCK(hsc); + + if (hsc->gState == DAL_SMARTCARD_STATE_READY) + { + switch (CallbackID) + { + + case DAL_SMARTCARD_TX_COMPLETE_CB_ID : + hsc->TxCpltCallback = pCallback; + break; + + case DAL_SMARTCARD_RX_COMPLETE_CB_ID : + hsc->RxCpltCallback = pCallback; + break; + + case DAL_SMARTCARD_ERROR_CB_ID : + hsc->ErrorCallback = pCallback; + break; + + case DAL_SMARTCARD_ABORT_COMPLETE_CB_ID : + hsc->AbortCpltCallback = pCallback; + break; + + case DAL_SMARTCARD_ABORT_TRANSMIT_COMPLETE_CB_ID : + hsc->AbortTransmitCpltCallback = pCallback; + break; + + case DAL_SMARTCARD_ABORT_RECEIVE_COMPLETE_CB_ID : + hsc->AbortReceiveCpltCallback = pCallback; + break; + + + case DAL_SMARTCARD_MSPINIT_CB_ID : + hsc->MspInitCallback = pCallback; + break; + + case DAL_SMARTCARD_MSPDEINIT_CB_ID : + hsc->MspDeInitCallback = pCallback; + break; + + default : + /* Update the error code */ + hsc->ErrorCode |= DAL_SMARTCARD_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = DAL_ERROR; + break; + } + } + else if (hsc->gState == DAL_SMARTCARD_STATE_RESET) + { + switch (CallbackID) + { + case DAL_SMARTCARD_MSPINIT_CB_ID : + hsc->MspInitCallback = pCallback; + break; + + case DAL_SMARTCARD_MSPDEINIT_CB_ID : + hsc->MspDeInitCallback = pCallback; + break; + + default : + /* Update the error code */ + hsc->ErrorCode |= DAL_SMARTCARD_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = DAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + hsc->ErrorCode |= DAL_SMARTCARD_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = DAL_ERROR; + } + + /* Release Lock */ + __DAL_UNLOCK(hsc); + + return status; +} + +/** + * @brief Unregister an SMARTCARD callback + * SMARTCARD callback is redirected to the weak predefined callback + * @param hsc smartcard handle + * @param CallbackID ID of the callback to be unregistered + * This parameter can be one of the following values: + * @arg @ref DAL_SMARTCARD_TX_COMPLETE_CB_ID Tx Complete Callback ID + * @arg @ref DAL_SMARTCARD_RX_COMPLETE_CB_ID Rx Complete Callback ID + * @arg @ref DAL_SMARTCARD_ERROR_CB_ID Error Callback ID + * @arg @ref DAL_SMARTCARD_ABORT_COMPLETE_CB_ID Abort Complete Callback ID + * @arg @ref DAL_SMARTCARD_ABORT_TRANSMIT_COMPLETE_CB_ID Abort Transmit Complete Callback ID + * @arg @ref DAL_SMARTCARD_ABORT_RECEIVE_COMPLETE_CB_ID Abort Receive Complete Callback ID + * @arg @ref DAL_SMARTCARD_MSPINIT_CB_ID MspInit Callback ID + * @arg @ref DAL_SMARTCARD_MSPDEINIT_CB_ID MspDeInit Callback ID + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SMARTCARD_UnRegisterCallback(SMARTCARD_HandleTypeDef *hsc, DAL_SMARTCARD_CallbackIDTypeDef CallbackID) +{ + DAL_StatusTypeDef status = DAL_OK; + + /* Process locked */ + __DAL_LOCK(hsc); + + if (DAL_SMARTCARD_STATE_READY == hsc->gState) + { + switch (CallbackID) + { + case DAL_SMARTCARD_TX_COMPLETE_CB_ID : + hsc->TxCpltCallback = DAL_SMARTCARD_TxCpltCallback; /* Legacy weak TxCpltCallback */ + break; + + case DAL_SMARTCARD_RX_COMPLETE_CB_ID : + hsc->RxCpltCallback = DAL_SMARTCARD_RxCpltCallback; /* Legacy weak RxCpltCallback */ + break; + + case DAL_SMARTCARD_ERROR_CB_ID : + hsc->ErrorCallback = DAL_SMARTCARD_ErrorCallback; /* Legacy weak ErrorCallback */ + break; + + case DAL_SMARTCARD_ABORT_COMPLETE_CB_ID : + hsc->AbortCpltCallback = DAL_SMARTCARD_AbortCpltCallback; /* Legacy weak AbortCpltCallback */ + break; + + case DAL_SMARTCARD_ABORT_TRANSMIT_COMPLETE_CB_ID : + hsc->AbortTransmitCpltCallback = DAL_SMARTCARD_AbortTransmitCpltCallback; /* Legacy weak AbortTransmitCpltCallback */ + break; + + case DAL_SMARTCARD_ABORT_RECEIVE_COMPLETE_CB_ID : + hsc->AbortReceiveCpltCallback = DAL_SMARTCARD_AbortReceiveCpltCallback; /* Legacy weak AbortReceiveCpltCallback */ + break; + + + case DAL_SMARTCARD_MSPINIT_CB_ID : + hsc->MspInitCallback = DAL_SMARTCARD_MspInit; /* Legacy weak MspInitCallback */ + break; + + case DAL_SMARTCARD_MSPDEINIT_CB_ID : + hsc->MspDeInitCallback = DAL_SMARTCARD_MspDeInit; /* Legacy weak MspDeInitCallback */ + break; + + default : + /* Update the error code */ + hsc->ErrorCode |= DAL_SMARTCARD_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = DAL_ERROR; + break; + } + } + else if (DAL_SMARTCARD_STATE_RESET == hsc->gState) + { + switch (CallbackID) + { + case DAL_SMARTCARD_MSPINIT_CB_ID : + hsc->MspInitCallback = DAL_SMARTCARD_MspInit; + break; + + case DAL_SMARTCARD_MSPDEINIT_CB_ID : + hsc->MspDeInitCallback = DAL_SMARTCARD_MspDeInit; + break; + + default : + /* Update the error code */ + hsc->ErrorCode |= DAL_SMARTCARD_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = DAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + hsc->ErrorCode |= DAL_SMARTCARD_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = DAL_ERROR; + } + + /* Release Lock */ + __DAL_UNLOCK(hsc); + + return status; +} +#endif /* USE_DAL_SMARTCARD_REGISTER_CALLBACKS */ + +/** + * @} + */ + +/** @defgroup SMARTCARD_Exported_Functions_Group2 IO operation functions + * @brief SMARTCARD Transmit and Receive functions + * +@verbatim + =============================================================================== + ##### IO operation functions ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to manage the SMARTCARD data transfers. + + [..] + (#) Smartcard is a single wire half duplex communication protocol. + The Smartcard interface is designed to support asynchronous protocol Smartcards as + defined in the ISO 7816-3 standard. + (#) The USART should be configured as: + (++) 8 bits plus parity: where M=1 and PCE=1 in the USART_CTRL1 register + (++) 1.5 stop bits when transmitting and receiving: where STOP=11 in the USART_CTRL2 register. + + (#) There are two modes of transfer: + (++) Blocking mode: The communication is performed in polling mode. + The DAL status of all data processing is returned by the same function + after finishing transfer. + (++) Non Blocking mode: The communication is performed using Interrupts + or DMA, These APIs return the DAL status. + The end of the data processing will be indicated through the + dedicated SMARTCARD IRQ when using Interrupt mode or the DMA IRQ when + using DMA mode. + The DAL_SMARTCARD_TxCpltCallback(), DAL_SMARTCARD_RxCpltCallback() user callbacks + will be executed respectively at the end of the Transmit or Receive process + The DAL_SMARTCARD_ErrorCallback() user callback will be executed when a communication error is detected + + (#) Blocking mode APIs are : + (++) DAL_SMARTCARD_Transmit() + (++) DAL_SMARTCARD_Receive() + + (#) Non Blocking mode APIs with Interrupt are : + (++) DAL_SMARTCARD_Transmit_IT() + (++) DAL_SMARTCARD_Receive_IT() + (++) DAL_SMARTCARD_IRQHandler() + + (#) Non Blocking mode functions with DMA are : + (++) DAL_SMARTCARD_Transmit_DMA() + (++) DAL_SMARTCARD_Receive_DMA() + + (#) A set of Transfer Complete Callbacks are provided in non Blocking mode: + (++) DAL_SMARTCARD_TxCpltCallback() + (++) DAL_SMARTCARD_RxCpltCallback() + (++) DAL_SMARTCARD_ErrorCallback() + + (#) Non-Blocking mode transfers could be aborted using Abort API's : + (+) DAL_SMARTCARD_Abort() + (+) DAL_SMARTCARD_AbortTransmit() + (+) DAL_SMARTCARD_AbortReceive() + (+) DAL_SMARTCARD_Abort_IT() + (+) DAL_SMARTCARD_AbortTransmit_IT() + (+) DAL_SMARTCARD_AbortReceive_IT() + + (#) For Abort services based on interrupts (DAL_SMARTCARD_Abortxxx_IT), a set of Abort Complete Callbacks are provided: + (+) DAL_SMARTCARD_AbortCpltCallback() + (+) DAL_SMARTCARD_AbortTransmitCpltCallback() + (+) DAL_SMARTCARD_AbortReceiveCpltCallback() + + (#) In Non-Blocking mode transfers, possible errors are split into 2 categories. + Errors are handled as follows : + (+) Error is considered as Recoverable and non blocking : Transfer could go till end, but error severity is + to be evaluated by user : this concerns Frame Error, Parity Error or Noise Error in Interrupt mode reception . + Received character is then retrieved and stored in Rx buffer, Error code is set to allow user to identify error type, + and DAL_SMARTCARD_ErrorCallback() user callback is executed. Transfer is kept ongoing on SMARTCARD side. + If user wants to abort it, Abort services should be called by user. + (+) Error is considered as Blocking : Transfer could not be completed properly and is aborted. + This concerns Frame Error in Interrupt mode transmission, Overrun Error in Interrupt mode reception and all errors in DMA mode. + Error code is set to allow user to identify error type, and DAL_SMARTCARD_ErrorCallback() user callback is executed. + +@endverbatim + * @{ + */ + +/** + * @brief Send an amount of data in blocking mode + * @param hsc Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for SMARTCARD module. + * @param pData Pointer to data buffer + * @param Size Amount of data to be sent + * @param Timeout Timeout duration + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SMARTCARD_Transmit(SMARTCARD_HandleTypeDef *hsc, const uint8_t *pData, uint16_t Size, uint32_t Timeout) +{ + const uint8_t *tmp = pData; + uint32_t tickstart = 0U; + + if(hsc->gState == DAL_SMARTCARD_STATE_READY) + { + if((pData == NULL) || (Size == 0U)) + { + return DAL_ERROR; + } + + /* Process Locked */ + __DAL_LOCK(hsc); + + hsc->ErrorCode = DAL_SMARTCARD_ERROR_NONE; + hsc->gState = DAL_SMARTCARD_STATE_BUSY_TX; + + /* Init tickstart for timeout management */ + tickstart = DAL_GetTick(); + + hsc->TxXferSize = Size; + hsc->TxXferCount = Size; + while(hsc->TxXferCount > 0U) + { + hsc->TxXferCount--; + if(SMARTCARD_WaitOnFlagUntilTimeout(hsc, SMARTCARD_FLAG_TXE, RESET, tickstart, Timeout) != DAL_OK) + { + return DAL_TIMEOUT; + } + hsc->Instance->DATA = (uint8_t)(*tmp & 0xFFU); + tmp++; + } + + if(SMARTCARD_WaitOnFlagUntilTimeout(hsc, SMARTCARD_FLAG_TC, RESET, tickstart, Timeout) != DAL_OK) + { + return DAL_TIMEOUT; + } + + /* At end of Tx process, restore hsc->gState to Ready */ + hsc->gState = DAL_SMARTCARD_STATE_READY; + + /* Process Unlocked */ + __DAL_UNLOCK(hsc); + + return DAL_OK; + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief Receive an amount of data in blocking mode + * @param hsc Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for SMARTCARD module. + * @param pData Pointer to data buffer + * @param Size Amount of data to be received + * @param Timeout Timeout duration + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SMARTCARD_Receive(SMARTCARD_HandleTypeDef *hsc, uint8_t *pData, uint16_t Size, uint32_t Timeout) +{ + uint8_t *tmp = pData; + uint32_t tickstart = 0U; + + if(hsc->RxState == DAL_SMARTCARD_STATE_READY) + { + if((pData == NULL) || (Size == 0U)) + { + return DAL_ERROR; + } + + /* Process Locked */ + __DAL_LOCK(hsc); + + hsc->ErrorCode = DAL_SMARTCARD_ERROR_NONE; + hsc->RxState = DAL_SMARTCARD_STATE_BUSY_RX; + + /* Init tickstart for timeout management */ + tickstart = DAL_GetTick(); + + hsc->RxXferSize = Size; + hsc->RxXferCount = Size; + + /* Check the remain data to be received */ + while(hsc->RxXferCount > 0U) + { + hsc->RxXferCount--; + if(SMARTCARD_WaitOnFlagUntilTimeout(hsc, SMARTCARD_FLAG_RXNE, RESET, tickstart, Timeout) != DAL_OK) + { + return DAL_TIMEOUT; + } + *tmp = (uint8_t)(hsc->Instance->DATA & (uint8_t)0xFFU); + tmp++; + } + + /* At end of Rx process, restore hsc->RxState to Ready */ + hsc->RxState = DAL_SMARTCARD_STATE_READY; + + /* Process Unlocked */ + __DAL_UNLOCK(hsc); + + return DAL_OK; + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief Send an amount of data in non blocking mode + * @param hsc Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for SMARTCARD module. + * @param pData Pointer to data buffer + * @param Size Amount of data to be sent + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SMARTCARD_Transmit_IT(SMARTCARD_HandleTypeDef *hsc, const uint8_t *pData, uint16_t Size) +{ + /* Check that a Tx process is not already ongoing */ + if(hsc->gState == DAL_SMARTCARD_STATE_READY) + { + if((pData == NULL) || (Size == 0U)) + { + return DAL_ERROR; + } + + /* Process Locked */ + __DAL_LOCK(hsc); + + hsc->pTxBuffPtr = pData; + hsc->TxXferSize = Size; + hsc->TxXferCount = Size; + + hsc->ErrorCode = DAL_SMARTCARD_ERROR_NONE; + hsc->gState = DAL_SMARTCARD_STATE_BUSY_TX; + + /* Process Unlocked */ + __DAL_UNLOCK(hsc); + + /* Enable the SMARTCARD Parity Error Interrupt */ + SET_BIT(hsc->Instance->CTRL1, USART_CTRL1_PEIEN); + + /* Disable the SMARTCARD Error Interrupt: (Frame error, noise error, overrun error) */ + CLEAR_BIT(hsc->Instance->CTRL3, USART_CTRL3_ERRIEN); + + /* Enable the SMARTCARD Transmit data register empty Interrupt */ + SET_BIT(hsc->Instance->CTRL1, USART_CTRL1_TXBEIEN); + + return DAL_OK; + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief Receive an amount of data in non blocking mode + * @param hsc Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for SMARTCARD module. + * @param pData Pointer to data buffer + * @param Size Amount of data to be received + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SMARTCARD_Receive_IT(SMARTCARD_HandleTypeDef *hsc, uint8_t *pData, uint16_t Size) +{ + /* Check that a Rx process is not already ongoing */ + if(hsc->RxState == DAL_SMARTCARD_STATE_READY) + { + if((pData == NULL) || (Size == 0U)) + { + return DAL_ERROR; + } + + /* Process Locked */ + __DAL_LOCK(hsc); + + hsc->pRxBuffPtr = pData; + hsc->RxXferSize = Size; + hsc->RxXferCount = Size; + + hsc->ErrorCode = DAL_SMARTCARD_ERROR_NONE; + hsc->RxState = DAL_SMARTCARD_STATE_BUSY_RX; + + /* Process Unlocked */ + __DAL_UNLOCK(hsc); + + /* Enable the SMARTCARD Parity Error and Data Register not empty Interrupts */ + SET_BIT(hsc->Instance->CTRL1, USART_CTRL1_PEIEN| USART_CTRL1_RXBNEIEN); + + /* Enable the SMARTCARD Error Interrupt: (Frame error, noise error, overrun error) */ + SET_BIT(hsc->Instance->CTRL3, USART_CTRL3_ERRIEN); + + return DAL_OK; + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief Send an amount of data in non blocking mode + * @param hsc Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for SMARTCARD module. + * @param pData Pointer to data buffer + * @param Size Amount of data to be sent + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SMARTCARD_Transmit_DMA(SMARTCARD_HandleTypeDef *hsc, const uint8_t *pData, uint16_t Size) +{ + const uint32_t *tmp; + + /* Check that a Tx process is not already ongoing */ + if(hsc->gState == DAL_SMARTCARD_STATE_READY) + { + if((pData == NULL) || (Size == 0U)) + { + return DAL_ERROR; + } + + /* Process Locked */ + __DAL_LOCK(hsc); + + hsc->pTxBuffPtr = pData; + hsc->TxXferSize = Size; + hsc->TxXferCount = Size; + + hsc->ErrorCode = DAL_SMARTCARD_ERROR_NONE; + hsc->gState = DAL_SMARTCARD_STATE_BUSY_TX; + + /* Set the SMARTCARD DMA transfer complete callback */ + hsc->hdmatx->XferCpltCallback = SMARTCARD_DMATransmitCplt; + + /* Set the DMA error callback */ + hsc->hdmatx->XferErrorCallback = SMARTCARD_DMAError; + + /* Set the DMA abort callback */ + hsc->hdmatx->XferAbortCallback = NULL; + + /* Enable the SMARTCARD transmit DMA stream */ + tmp = (const uint32_t*)&pData; + DAL_DMA_Start_IT(hsc->hdmatx, *(const uint32_t*)tmp, (uint32_t)&hsc->Instance->DATA, Size); + + /* Clear the TC flag in the STS register by writing 0 to it */ + __DAL_SMARTCARD_CLEAR_FLAG(hsc, SMARTCARD_FLAG_TC); + + /* Process Unlocked */ + __DAL_UNLOCK(hsc); + + /* Enable the DMA transfer for transmit request by setting the DMAT bit + in the SMARTCARD CTRL3 register */ + SET_BIT(hsc->Instance->CTRL3, USART_CTRL3_DMATXEN); + + return DAL_OK; + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief Receive an amount of data in non blocking mode + * @param hsc Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for SMARTCARD module. + * @param pData Pointer to data buffer + * @param Size Amount of data to be received + * @note When the SMARTCARD parity is enabled (PCE = 1) the data received contain the parity bit.s + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SMARTCARD_Receive_DMA(SMARTCARD_HandleTypeDef *hsc, uint8_t *pData, uint16_t Size) +{ + uint32_t *tmp; + + /* Check that a Rx process is not already ongoing */ + if(hsc->RxState == DAL_SMARTCARD_STATE_READY) + { + if((pData == NULL) || (Size == 0U)) + { + return DAL_ERROR; + } + + /* Process Locked */ + __DAL_LOCK(hsc); + + hsc->pRxBuffPtr = pData; + hsc->RxXferSize = Size; + + hsc->ErrorCode = DAL_SMARTCARD_ERROR_NONE; + hsc->RxState = DAL_SMARTCARD_STATE_BUSY_RX; + + /* Set the SMARTCARD DMA transfer complete callback */ + hsc->hdmarx->XferCpltCallback = SMARTCARD_DMAReceiveCplt; + + /* Set the DMA error callback */ + hsc->hdmarx->XferErrorCallback = SMARTCARD_DMAError; + + /* Set the DMA abort callback */ + hsc->hdmatx->XferAbortCallback = NULL; + + /* Enable the DMA stream */ + tmp = (uint32_t*)&pData; + DAL_DMA_Start_IT(hsc->hdmarx, (uint32_t)&hsc->Instance->DATA, *(uint32_t*)tmp, Size); + + /* Clear the Overrun flag just before enabling the DMA Rx request: can be mandatory for the second transfer */ + __DAL_SMARTCARD_CLEAR_OREFLAG(hsc); + + /* Process Unlocked */ + __DAL_UNLOCK(hsc); + + /* Enable the SMARTCARD Parity Error Interrupt */ + SET_BIT(hsc->Instance->CTRL1, USART_CTRL1_PEIEN); + + /* Enable the SMARTCARD Error Interrupt: (Frame error, noise error, overrun error) */ + SET_BIT(hsc->Instance->CTRL3, USART_CTRL3_ERRIEN); + + /* Enable the DMA transfer for the receiver request by setting the DMAR bit + in the SMARTCARD CTRL3 register */ + SET_BIT(hsc->Instance->CTRL3, USART_CTRL3_DMARXEN); + + return DAL_OK; + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief Abort ongoing transfers (blocking mode). + * @param hsc SMARTCARD handle. + * @note This procedure could be used for aborting any ongoing transfer started in Interrupt or DMA mode. + * This procedure performs following operations : + * - Disable PPP Interrupts + * - Disable the DMA transfer in the peripheral register (if enabled) + * - Abort DMA transfer by calling DAL_DMA_Abort (in case of transfer in DMA mode) + * - Set handle State to READY + * @note This procedure is executed in blocking mode : when exiting function, Abort is considered as completed. + * @retval DAL status +*/ +DAL_StatusTypeDef DAL_SMARTCARD_Abort(SMARTCARD_HandleTypeDef *hsc) +{ + /* Disable TXBEIEN, TXCIEN, RXBNEIEN, PEIEN and ERRIEN (Frame error, noise error, overrun error) interrupts */ + CLEAR_BIT(hsc->Instance->CTRL1, (USART_CTRL1_RXBNEIEN | USART_CTRL1_PEIEN | USART_CTRL1_TXBEIEN | USART_CTRL1_TXCIEN)); + CLEAR_BIT(hsc->Instance->CTRL3, USART_CTRL3_ERRIEN); + + /* Disable the SMARTCARD DMA Tx request if enabled */ + if(DAL_IS_BIT_SET(hsc->Instance->CTRL3, USART_CTRL3_DMATXEN)) + { + CLEAR_BIT(hsc->Instance->CTRL3, USART_CTRL3_DMATXEN); + + /* Abort the SMARTCARD DMA Tx channel : use blocking DMA Abort API (no callback) */ + if(hsc->hdmatx != NULL) + { + /* Set the SMARTCARD DMA Abort callback to Null. + No call back execution at end of DMA abort procedure */ + hsc->hdmatx->XferAbortCallback = NULL; + + DAL_DMA_Abort(hsc->hdmatx); + } + } + + /* Disable the SMARTCARD DMA Rx request if enabled */ + if(DAL_IS_BIT_SET(hsc->Instance->CTRL3, USART_CTRL3_DMARXEN)) + { + CLEAR_BIT(hsc->Instance->CTRL3, USART_CTRL3_DMARXEN); + + /* Abort the SMARTCARD DMA Rx channel : use blocking DMA Abort API (no callback) */ + if(hsc->hdmarx != NULL) + { + /* Set the SMARTCARD DMA Abort callback to Null. + No call back execution at end of DMA abort procedure */ + hsc->hdmarx->XferAbortCallback = NULL; + + DAL_DMA_Abort(hsc->hdmarx); + } + } + + /* Reset Tx and Rx transfer counters */ + hsc->TxXferCount = 0x00U; + hsc->RxXferCount = 0x00U; + + /* Reset ErrorCode */ + hsc->ErrorCode = DAL_SMARTCARD_ERROR_NONE; + + /* Restore hsc->RxState and hsc->gState to Ready */ + hsc->RxState = DAL_SMARTCARD_STATE_READY; + hsc->gState = DAL_SMARTCARD_STATE_READY; + + return DAL_OK; +} + +/** + * @brief Abort ongoing Transmit transfer (blocking mode). + * @param hsc SMARTCARD handle. + * @note This procedure could be used for aborting any ongoing transfer started in Interrupt or DMA mode. + * This procedure performs following operations : + * - Disable SMARTCARD Interrupts (Tx) + * - Disable the DMA transfer in the peripheral register (if enabled) + * - Abort DMA transfer by calling DAL_DMA_Abort (in case of transfer in DMA mode) + * - Set handle State to READY + * @note This procedure is executed in blocking mode : when exiting function, Abort is considered as completed. + * @retval DAL status +*/ +DAL_StatusTypeDef DAL_SMARTCARD_AbortTransmit(SMARTCARD_HandleTypeDef *hsc) +{ + /* Disable TXEIE and TCIE interrupts */ + CLEAR_BIT(hsc->Instance->CTRL1, (USART_CTRL1_TXBEIEN | USART_CTRL1_TXCIEN)); + + /* Disable the SMARTCARD DMA Tx request if enabled */ + if(DAL_IS_BIT_SET(hsc->Instance->CTRL3, USART_CTRL3_DMATXEN)) + { + CLEAR_BIT(hsc->Instance->CTRL3, USART_CTRL3_DMATXEN); + + /* Abort the SMARTCARD DMA Tx channel : use blocking DMA Abort API (no callback) */ + if(hsc->hdmatx != NULL) + { + /* Set the SMARTCARD DMA Abort callback to Null. + No call back execution at end of DMA abort procedure */ + hsc->hdmatx->XferAbortCallback = NULL; + + DAL_DMA_Abort(hsc->hdmatx); + } + } + + /* Reset Tx transfer counter */ + hsc->TxXferCount = 0x00U; + + /* Restore hsc->gState to Ready */ + hsc->gState = DAL_SMARTCARD_STATE_READY; + + return DAL_OK; +} + +/** + * @brief Abort ongoing Receive transfer (blocking mode). + * @param hsc SMARTCARD handle. + * @note This procedure could be used for aborting any ongoing transfer started in Interrupt or DMA mode. + * This procedure performs following operations : + * - Disable PPP Interrupts + * - Disable the DMA transfer in the peripheral register (if enabled) + * - Abort DMA transfer by calling DAL_DMA_Abort (in case of transfer in DMA mode) + * - Set handle State to READY + * @note This procedure is executed in blocking mode : when exiting function, Abort is considered as completed. + * @retval DAL status +*/ +DAL_StatusTypeDef DAL_SMARTCARD_AbortReceive(SMARTCARD_HandleTypeDef *hsc) +{ + /* Disable RXBNEIEN, PEIEN and ERRIEN (Frame error, noise error, overrun error) interrupts */ + CLEAR_BIT(hsc->Instance->CTRL1, (USART_CTRL1_RXBNEIEN | USART_CTRL1_PEIEN)); + CLEAR_BIT(hsc->Instance->CTRL3, USART_CTRL3_ERRIEN); + + /* Disable the SMARTCARD DMA Rx request if enabled */ + if(DAL_IS_BIT_SET(hsc->Instance->CTRL3, USART_CTRL3_DMARXEN)) + { + CLEAR_BIT(hsc->Instance->CTRL3, USART_CTRL3_DMARXEN); + + /* Abort the SMARTCARD DMA Rx channel : use blocking DMA Abort API (no callback) */ + if(hsc->hdmarx != NULL) + { + /* Set the SMARTCARD DMA Abort callback to Null. + No call back execution at end of DMA abort procedure */ + hsc->hdmarx->XferAbortCallback = NULL; + + DAL_DMA_Abort(hsc->hdmarx); + } + } + + /* Reset Rx transfer counter */ + hsc->RxXferCount = 0x00U; + + /* Restore hsc->RxState to Ready */ + hsc->RxState = DAL_SMARTCARD_STATE_READY; + + return DAL_OK; +} + +/** + * @brief Abort ongoing transfers (Interrupt mode). + * @param hsc SMARTCARD handle. + * @note This procedure could be used for aborting any ongoing transfer started in Interrupt or DMA mode. + * This procedure performs following operations : + * - Disable PPP Interrupts + * - Disable the DMA transfer in the peripheral register (if enabled) + * - Abort DMA transfer by calling DAL_DMA_Abort_IT (in case of transfer in DMA mode) + * - Set handle State to READY + * - At abort completion, call user abort complete callback + * @note This procedure is executed in Interrupt mode, meaning that abort procedure could be + * considered as completed only when user abort complete callback is executed (not when exiting function). + * @retval DAL status +*/ +DAL_StatusTypeDef DAL_SMARTCARD_Abort_IT(SMARTCARD_HandleTypeDef *hsc) +{ + uint32_t AbortCplt = 0x01U; + + /* Disable TXBEIEN, TXCIEN, RXBNEIEN, PEIEN and ERRIEN (Frame error, noise error, overrun error) interrupts */ + CLEAR_BIT(hsc->Instance->CTRL1, (USART_CTRL1_RXBNEIEN | USART_CTRL1_PEIEN | USART_CTRL1_TXBEIEN | USART_CTRL1_TXCIEN)); + CLEAR_BIT(hsc->Instance->CTRL3, USART_CTRL3_ERRIEN); + + /* If DMA Tx and/or DMA Rx Handles are associated to SMARTCARD Handle, DMA Abort complete callbacks should be initialised + before any call to DMA Abort functions */ + /* DMA Tx Handle is valid */ + if(hsc->hdmatx != NULL) + { + /* Set DMA Abort Complete callback if SMARTCARD DMA Tx request if enabled. + Otherwise, set it to NULL */ + if(DAL_IS_BIT_SET(hsc->Instance->CTRL3, USART_CTRL3_DMATXEN)) + { + hsc->hdmatx->XferAbortCallback = SMARTCARD_DMATxAbortCallback; + } + else + { + hsc->hdmatx->XferAbortCallback = NULL; + } + } + /* DMA Rx Handle is valid */ + if(hsc->hdmarx != NULL) + { + /* Set DMA Abort Complete callback if SMARTCARD DMA Rx request if enabled. + Otherwise, set it to NULL */ + if(DAL_IS_BIT_SET(hsc->Instance->CTRL3, USART_CTRL3_DMARXEN)) + { + hsc->hdmarx->XferAbortCallback = SMARTCARD_DMARxAbortCallback; + } + else + { + hsc->hdmarx->XferAbortCallback = NULL; + } + } + + /* Disable the SMARTCARD DMA Tx request if enabled */ + if(DAL_IS_BIT_SET(hsc->Instance->CTRL3, USART_CTRL3_DMATXEN)) + { + /* Disable DMA Tx at SMARTCARD level */ + CLEAR_BIT(hsc->Instance->CTRL3, USART_CTRL3_DMATXEN); + + /* Abort the SMARTCARD DMA Tx channel : use non blocking DMA Abort API (callback) */ + if(hsc->hdmatx != NULL) + { + /* SMARTCARD Tx DMA Abort callback has already been initialised : + will lead to call DAL_SMARTCARD_AbortCpltCallback() at end of DMA abort procedure */ + + /* Abort DMA TX */ + if(DAL_DMA_Abort_IT(hsc->hdmatx) != DAL_OK) + { + hsc->hdmatx->XferAbortCallback = NULL; + } + else + { + AbortCplt = 0x00U; + } + } + } + + /* Disable the SMARTCARD DMA Rx request if enabled */ + if(DAL_IS_BIT_SET(hsc->Instance->CTRL3, USART_CTRL3_DMARXEN)) + { + CLEAR_BIT(hsc->Instance->CTRL3, USART_CTRL3_DMARXEN); + + /* Abort the SMARTCARD DMA Rx channel : use non blocking DMA Abort API (callback) */ + if(hsc->hdmarx != NULL) + { + /* SMARTCARD Rx DMA Abort callback has already been initialised : + will lead to call DAL_SMARTCARD_AbortCpltCallback() at end of DMA abort procedure */ + + /* Abort DMA RX */ + if(DAL_DMA_Abort_IT(hsc->hdmarx) != DAL_OK) + { + hsc->hdmarx->XferAbortCallback = NULL; + AbortCplt = 0x01U; + } + else + { + AbortCplt = 0x00U; + } + } + } + + /* if no DMA abort complete callback execution is required => call user Abort Complete callback */ + if(AbortCplt == 0x01U) + { + /* Reset Tx and Rx transfer counters */ + hsc->TxXferCount = 0x00U; + hsc->RxXferCount = 0x00U; + + /* Reset ErrorCode */ + hsc->ErrorCode = DAL_SMARTCARD_ERROR_NONE; + + /* Restore hsc->gState and hsc->RxState to Ready */ + hsc->gState = DAL_SMARTCARD_STATE_READY; + hsc->RxState = DAL_SMARTCARD_STATE_READY; + + /* As no DMA to be aborted, call directly user Abort complete callback */ +#if (USE_DAL_SMARTCARD_REGISTER_CALLBACKS == 1) + /* Call registered Abort complete callback */ + hsc->AbortCpltCallback(hsc); +#else + /* Call legacy weak Abort complete callback */ + DAL_SMARTCARD_AbortCpltCallback(hsc); +#endif /* USE_DAL_SMARTCARD_REGISTER_CALLBACK */ + } + return DAL_OK; +} + +/** + * @brief Abort ongoing Transmit transfer (Interrupt mode). + * @param hsc SMARTCARD handle. + * @note This procedure could be used for aborting any ongoing transfer started in Interrupt or DMA mode. + * This procedure performs following operations : + * - Disable SMARTCARD Interrupts (Tx) + * - Disable the DMA transfer in the peripheral register (if enabled) + * - Abort DMA transfer by calling DAL_DMA_Abort_IT (in case of transfer in DMA mode) + * - Set handle State to READY + * - At abort completion, call user abort complete callback + * @note This procedure is executed in Interrupt mode, meaning that abort procedure could be + * considered as completed only when user abort complete callback is executed (not when exiting function). + * @retval DAL status +*/ +DAL_StatusTypeDef DAL_SMARTCARD_AbortTransmit_IT(SMARTCARD_HandleTypeDef *hsc) +{ + /* Disable TXEIE and TCIE interrupts */ + CLEAR_BIT(hsc->Instance->CTRL1, (USART_CTRL1_TXBEIEN | USART_CTRL1_TXCIEN)); + + /* Disable the SMARTCARD DMA Tx request if enabled */ + if(DAL_IS_BIT_SET(hsc->Instance->CTRL3, USART_CTRL3_DMATXEN)) + { + CLEAR_BIT(hsc->Instance->CTRL3, USART_CTRL3_DMATXEN); + + /* Abort the SMARTCARD DMA Tx channel : use blocking DMA Abort API (no callback) */ + if(hsc->hdmatx != NULL) + { + /* Set the SMARTCARD DMA Abort callback : + will lead to call DAL_SMARTCARD_AbortCpltCallback() at end of DMA abort procedure */ + hsc->hdmatx->XferAbortCallback = SMARTCARD_DMATxOnlyAbortCallback; + + /* Abort DMA TX */ + if(DAL_DMA_Abort_IT(hsc->hdmatx) != DAL_OK) + { + /* Call Directly hsc->hdmatx->XferAbortCallback function in case of error */ + hsc->hdmatx->XferAbortCallback(hsc->hdmatx); + } + } + else + { + /* Reset Tx transfer counter */ + hsc->TxXferCount = 0x00U; + + /* Restore hsc->gState to Ready */ + hsc->gState = DAL_SMARTCARD_STATE_READY; + + /* As no DMA to be aborted, call directly user Abort complete callback */ +#if (USE_DAL_SMARTCARD_REGISTER_CALLBACKS == 1) + /* Call registered Abort Transmit Complete Callback */ + hsc->AbortTransmitCpltCallback(hsc); +#else + /* Call legacy weak Abort Transmit Complete Callback */ + DAL_SMARTCARD_AbortTransmitCpltCallback(hsc); +#endif /* USE_DAL_SMARTCARD_REGISTER_CALLBACK */ + } + } + else + { + /* Reset Tx transfer counter */ + hsc->TxXferCount = 0x00U; + + /* Restore hsc->gState to Ready */ + hsc->gState = DAL_SMARTCARD_STATE_READY; + + /* As no DMA to be aborted, call directly user Abort complete callback */ +#if (USE_DAL_SMARTCARD_REGISTER_CALLBACKS == 1) + /* Call registered Abort Transmit Complete Callback */ + hsc->AbortTransmitCpltCallback(hsc); +#else + /* Call legacy weak Abort Transmit Complete Callback */ + DAL_SMARTCARD_AbortTransmitCpltCallback(hsc); +#endif /* USE_DAL_SMARTCARD_REGISTER_CALLBACK */ + } + + return DAL_OK; +} + +/** + * @brief Abort ongoing Receive transfer (Interrupt mode). + * @param hsc SMARTCARD handle. + * @note This procedure could be used for aborting any ongoing transfer started in Interrupt or DMA mode. + * This procedure performs following operations : + * - Disable SMARTCARD Interrupts (Rx) + * - Disable the DMA transfer in the peripheral register (if enabled) + * - Abort DMA transfer by calling DAL_DMA_Abort_IT (in case of transfer in DMA mode) + * - Set handle State to READY + * - At abort completion, call user abort complete callback + * @note This procedure is executed in Interrupt mode, meaning that abort procedure could be + * considered as completed only when user abort complete callback is executed (not when exiting function). + * @retval DAL status +*/ +DAL_StatusTypeDef DAL_SMARTCARD_AbortReceive_IT(SMARTCARD_HandleTypeDef *hsc) +{ + /* Disable RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts */ + CLEAR_BIT(hsc->Instance->CTRL1, (USART_CTRL1_RXBNEIEN | USART_CTRL1_PEIEN)); + CLEAR_BIT(hsc->Instance->CTRL3, USART_CTRL3_ERRIEN); + + /* Disable the SMARTCARD DMA Rx request if enabled */ + if(DAL_IS_BIT_SET(hsc->Instance->CTRL3, USART_CTRL3_DMARXEN)) + { + CLEAR_BIT(hsc->Instance->CTRL3, USART_CTRL3_DMARXEN); + + /* Abort the SMARTCARD DMA Rx channel : use blocking DMA Abort API (no callback) */ + if(hsc->hdmarx != NULL) + { + /* Set the SMARTCARD DMA Abort callback : + will lead to call DAL_SMARTCARD_AbortCpltCallback() at end of DMA abort procedure */ + hsc->hdmarx->XferAbortCallback = SMARTCARD_DMARxOnlyAbortCallback; + + /* Abort DMA RX */ + if(DAL_DMA_Abort_IT(hsc->hdmarx) != DAL_OK) + { + /* Call Directly hsc->hdmarx->XferAbortCallback function in case of error */ + hsc->hdmarx->XferAbortCallback(hsc->hdmarx); + } + } + else + { + /* Reset Rx transfer counter */ + hsc->RxXferCount = 0x00U; + + /* Restore hsc->RxState to Ready */ + hsc->RxState = DAL_SMARTCARD_STATE_READY; + + /* As no DMA to be aborted, call directly user Abort complete callback */ +#if (USE_DAL_SMARTCARD_REGISTER_CALLBACKS == 1) + /* Call registered Abort Receive Complete Callback */ + hsc->AbortReceiveCpltCallback(hsc); +#else + /* Call legacy weak Abort Receive Complete Callback */ + DAL_SMARTCARD_AbortReceiveCpltCallback(hsc); +#endif /* USE_DAL_SMARTCARD_REGISTER_CALLBACK */ + } + } + else + { + /* Reset Rx transfer counter */ + hsc->RxXferCount = 0x00U; + + /* Restore hsc->RxState to Ready */ + hsc->RxState = DAL_SMARTCARD_STATE_READY; + + /* As no DMA to be aborted, call directly user Abort complete callback */ +#if (USE_DAL_SMARTCARD_REGISTER_CALLBACKS == 1) + /* Call registered Abort Receive Complete Callback */ + hsc->AbortReceiveCpltCallback(hsc); +#else + /* Call legacy weak Abort Receive Complete Callback */ + DAL_SMARTCARD_AbortReceiveCpltCallback(hsc); +#endif /* USE_DAL_SMARTCARD_REGISTER_CALLBACK */ + } + + return DAL_OK; +} + +/** + * @brief This function handles SMARTCARD interrupt request. + * @param hsc Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for SMARTCARD module. + * @retval None + */ +void DAL_SMARTCARD_IRQHandler(SMARTCARD_HandleTypeDef *hsc) +{ + uint32_t isrflags = READ_REG(hsc->Instance->STS); + uint32_t cr1its = READ_REG(hsc->Instance->CTRL1); + uint32_t cr3its = READ_REG(hsc->Instance->CTRL3); + uint32_t dmarequest = 0x00U; + uint32_t errorflags = 0x00U; + + /* If no error occurs */ + errorflags = (isrflags & (uint32_t)(USART_STS_PEFLG | USART_STS_FEFLG | USART_STS_OVREFLG | USART_STS_NEFLG)); + if(errorflags == RESET) + { + /* SMARTCARD in mode Receiver -------------------------------------------------*/ + if(((isrflags & USART_STS_RXBNEFLG) != RESET) && ((cr1its & USART_CTRL1_RXBNEIEN) != RESET)) + { + SMARTCARD_Receive_IT(hsc); + return; + } + } + + /* If some errors occur */ + if((errorflags != RESET) && (((cr3its & USART_CTRL3_ERRIEN) != RESET) || ((cr1its & (USART_CTRL1_RXBNEIEN | USART_CTRL1_PEIEN)) != RESET))) + { + /* SMARTCARD parity error interrupt occurred ---------------------------*/ + if(((isrflags & SMARTCARD_FLAG_PE) != RESET) && ((cr1its & USART_CTRL1_PEIEN) != RESET)) + { + hsc->ErrorCode |= DAL_SMARTCARD_ERROR_PE; + } + + /* SMARTCARD frame error interrupt occurred ----------------------------*/ + if(((isrflags & SMARTCARD_FLAG_FE) != RESET) && ((cr3its & USART_CTRL3_ERRIEN) != RESET)) + { + hsc->ErrorCode |= DAL_SMARTCARD_ERROR_FE; + } + + /* SMARTCARD noise error interrupt occurred ----------------------------*/ + if(((isrflags & SMARTCARD_FLAG_NE) != RESET) && ((cr3its & USART_CTRL3_ERRIEN) != RESET)) + { + hsc->ErrorCode |= DAL_SMARTCARD_ERROR_NE; + } + + /* SMARTCARD Over-Run interrupt occurred -------------------------------*/ + if(((isrflags & SMARTCARD_FLAG_ORE) != RESET) && (((cr1its & USART_CTRL1_RXBNEIEN) != RESET) || ((cr3its & USART_CTRL3_ERRIEN) != RESET))) + { + hsc->ErrorCode |= DAL_SMARTCARD_ERROR_ORE; + } + /* Call the Error call Back in case of Errors --------------------------*/ + if(hsc->ErrorCode != DAL_SMARTCARD_ERROR_NONE) + { + /* SMARTCARD in mode Receiver ----------------------------------------*/ + if(((isrflags & USART_STS_RXBNEFLG) != RESET) && ((cr1its & USART_CTRL1_RXBNEIEN) != RESET)) + { + SMARTCARD_Receive_IT(hsc); + } + + /* If Overrun error occurs, or if any error occurs in DMA mode reception, + consider error as blocking */ + dmarequest = DAL_IS_BIT_SET(hsc->Instance->CTRL3, USART_CTRL3_DMARXEN); + if(((hsc->ErrorCode & DAL_SMARTCARD_ERROR_ORE) != RESET) || dmarequest) + { + /* Blocking error : transfer is aborted + Set the SMARTCARD state ready to be able to start again the process, + Disable Rx Interrupts, and disable Rx DMA request, if ongoing */ + SMARTCARD_EndRxTransfer(hsc); + /* Disable the SMARTCARD DMA Rx request if enabled */ + if(DAL_IS_BIT_SET(hsc->Instance->CTRL3, USART_CTRL3_DMARXEN)) + { + CLEAR_BIT(hsc->Instance->CTRL3, USART_CTRL3_DMARXEN); + + /* Abort the SMARTCARD DMA Rx channel */ + if(hsc->hdmarx != NULL) + { + /* Set the SMARTCARD DMA Abort callback : + will lead to call DAL_SMARTCARD_ErrorCallback() at end of DMA abort procedure */ + hsc->hdmarx->XferAbortCallback = SMARTCARD_DMAAbortOnError; + + if(DAL_DMA_Abort_IT(hsc->hdmarx) != DAL_OK) + { + /* Call Directly XferAbortCallback function in case of error */ + hsc->hdmarx->XferAbortCallback(hsc->hdmarx); + } + } + else + { +#if (USE_DAL_SMARTCARD_REGISTER_CALLBACKS == 1) + /* Call registered user error callback */ + hsc->ErrorCallback(hsc); +#else + /* Call legacy weak user error callback */ + DAL_SMARTCARD_ErrorCallback(hsc); +#endif /* USE_DAL_SMARTCARD_REGISTER_CALLBACK */ + } + } + else + { +#if (USE_DAL_SMARTCARD_REGISTER_CALLBACKS == 1) + /* Call registered user error callback */ + hsc->ErrorCallback(hsc); +#else + /* Call legacy weak user error callback */ + DAL_SMARTCARD_ErrorCallback(hsc); +#endif /* USE_DAL_SMARTCARD_REGISTER_CALLBACK */ + } + } + else + { + /* Non Blocking error : transfer could go on. + Error is notified to user through user error callback */ +#if (USE_DAL_SMARTCARD_REGISTER_CALLBACKS == 1) + /* Call registered user error callback */ + hsc->ErrorCallback(hsc); +#else + /* Call legacy weak user error callback */ + DAL_SMARTCARD_ErrorCallback(hsc); +#endif /* USE_DAL_SMARTCARD_REGISTER_CALLBACK */ + hsc->ErrorCode = DAL_SMARTCARD_ERROR_NONE; + } + } + return; + } /* End if some error occurs */ + + /* SMARTCARD in mode Transmitter ------------------------------------------*/ + if(((isrflags & SMARTCARD_FLAG_TXE) != RESET) && ((cr1its & USART_CTRL1_TXBEIEN) != RESET)) + { + SMARTCARD_Transmit_IT(hsc); + return; + } + + /* SMARTCARD in mode Transmitter (transmission end) -----------------------*/ + if(((isrflags & SMARTCARD_FLAG_TC) != RESET) && ((cr1its & USART_CTRL1_TXCIEN) != RESET)) + { + SMARTCARD_EndTransmit_IT(hsc); + return; + } +} + +/** + * @brief Tx Transfer completed callbacks + * @param hsc Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for SMARTCARD module. + * @retval None + */ +__weak void DAL_SMARTCARD_TxCpltCallback(SMARTCARD_HandleTypeDef *hsc) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hsc); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_SMARTCARD_TxCpltCallback can be implemented in the user file. + */ +} + +/** + * @brief Rx Transfer completed callback + * @param hsc Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for SMARTCARD module. + * @retval None + */ +__weak void DAL_SMARTCARD_RxCpltCallback(SMARTCARD_HandleTypeDef *hsc) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hsc); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_SMARTCARD_RxCpltCallback can be implemented in the user file. + */ +} + +/** + * @brief SMARTCARD error callback + * @param hsc Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for SMARTCARD module. + * @retval None + */ +__weak void DAL_SMARTCARD_ErrorCallback(SMARTCARD_HandleTypeDef *hsc) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hsc); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_SMARTCARD_ErrorCallback can be implemented in the user file. + */ +} + +/** + * @brief SMARTCARD Abort Complete callback. + * @param hsc SMARTCARD handle. + * @retval None + */ +__weak void DAL_SMARTCARD_AbortCpltCallback (SMARTCARD_HandleTypeDef *hsc) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hsc); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_SMARTCARD_AbortCpltCallback can be implemented in the user file. + */ +} + +/** + * @brief SMARTCARD Abort Transmit Complete callback. + * @param hsc SMARTCARD handle. + * @retval None + */ +__weak void DAL_SMARTCARD_AbortTransmitCpltCallback (SMARTCARD_HandleTypeDef *hsc) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hsc); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_SMARTCARD_AbortTransmitCpltCallback can be implemented in the user file. + */ +} + +/** + * @brief SMARTCARD Abort Receive Complete callback. + * @param hsc SMARTCARD handle. + * @retval None + */ +__weak void DAL_SMARTCARD_AbortReceiveCpltCallback (SMARTCARD_HandleTypeDef *hsc) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hsc); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_SMARTCARD_AbortReceiveCpltCallback can be implemented in the user file. + */ +} + +/** + * @} + */ + +/** @defgroup SMARTCARD_Exported_Functions_Group3 Peripheral State and Errors functions + * @brief SMARTCARD State and Errors functions + * +@verbatim + =============================================================================== + ##### Peripheral State and Errors functions ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to control the SmartCard. + (+) DAL_SMARTCARD_GetState() API can be helpful to check in run-time the state of the SmartCard peripheral. + (+) DAL_SMARTCARD_GetError() check in run-time errors that could be occurred during communication. +@endverbatim + * @{ + */ + +/** + * @brief Return the SMARTCARD handle state + * @param hsc Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for SMARTCARD module. + * @retval DAL state + */ +DAL_SMARTCARD_StateTypeDef DAL_SMARTCARD_GetState(SMARTCARD_HandleTypeDef *hsc) +{ + uint32_t temp1= 0x00U, temp2 = 0x00U; + temp1 = hsc->gState; + temp2 = hsc->RxState; + + return (DAL_SMARTCARD_StateTypeDef)(temp1 | temp2); +} + +/** + * @brief Return the SMARTCARD error code + * @param hsc Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for the specified SMARTCARD. + * @retval SMARTCARD Error Code + */ +uint32_t DAL_SMARTCARD_GetError(SMARTCARD_HandleTypeDef *hsc) +{ + return hsc->ErrorCode; +} + +/** + * @} + */ + +/** + * @} + */ + +/** @defgroup SMARTCARD_Private_Functions SMARTCARD Private Functions + * @{ + */ + +#if (USE_DAL_SMARTCARD_REGISTER_CALLBACKS == 1) +/** + * @brief Initialize the callbacks to their default values. + * @param hsc SMARTCARD handle. + * @retval none + */ +void SMARTCARD_InitCallbacksToDefault(SMARTCARD_HandleTypeDef *hsc) +{ + /* Init the SMARTCARD Callback settings */ + hsc->TxCpltCallback = DAL_SMARTCARD_TxCpltCallback; /* Legacy weak TxCpltCallback */ + hsc->RxCpltCallback = DAL_SMARTCARD_RxCpltCallback; /* Legacy weak RxCpltCallback */ + hsc->ErrorCallback = DAL_SMARTCARD_ErrorCallback; /* Legacy weak ErrorCallback */ + hsc->AbortCpltCallback = DAL_SMARTCARD_AbortCpltCallback; /* Legacy weak AbortCpltCallback */ + hsc->AbortTransmitCpltCallback = DAL_SMARTCARD_AbortTransmitCpltCallback; /* Legacy weak AbortTransmitCpltCallback */ + hsc->AbortReceiveCpltCallback = DAL_SMARTCARD_AbortReceiveCpltCallback; /* Legacy weak AbortReceiveCpltCallback */ + +} +#endif /* USE_DAL_SMARTCARD_REGISTER_CALLBACKS */ + +/** + * @brief DMA SMARTCARD transmit process complete callback + * @param hdma Pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +static void SMARTCARD_DMATransmitCplt(DMA_HandleTypeDef *hdma) +{ + SMARTCARD_HandleTypeDef* hsc = ( SMARTCARD_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + + hsc->TxXferCount = 0U; + + /* Disable the DMA transfer for transmit request by setting the DMAT bit + in the USART CTRL3 register */ + CLEAR_BIT(hsc->Instance->CTRL3, USART_CTRL3_DMATXEN); + + /* Enable the SMARTCARD Transmit Complete Interrupt */ + SET_BIT(hsc->Instance->CTRL1, USART_CTRL1_TXCIEN); +} + +/** + * @brief DMA SMARTCARD receive process complete callback + * @param hdma Pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +static void SMARTCARD_DMAReceiveCplt(DMA_HandleTypeDef *hdma) +{ + SMARTCARD_HandleTypeDef* hsc = ( SMARTCARD_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + + hsc->RxXferCount = 0U; + + /* Disable RXBNEIEN, PEIEN and ERRIEN (Frame error, noise error, overrun error) interrupts */ + CLEAR_BIT(hsc->Instance->CTRL1, (USART_CTRL1_RXBNEIEN | USART_CTRL1_PEIEN)); + CLEAR_BIT(hsc->Instance->CTRL3, USART_CTRL3_ERRIEN); + + /* Disable the DMA transfer for the receiver request by setting the DMAR bit + in the USART CTRL3 register */ + CLEAR_BIT(hsc->Instance->CTRL3, USART_CTRL3_DMARXEN); + + /* At end of Rx process, restore hsc->RxState to Ready */ + hsc->RxState = DAL_SMARTCARD_STATE_READY; + +#if (USE_DAL_SMARTCARD_REGISTER_CALLBACKS == 1) + /* Call registered Rx complete callback */ + hsc->RxCpltCallback(hsc); +#else + /* Call legacy weak Rx complete callback */ + DAL_SMARTCARD_RxCpltCallback(hsc); +#endif /* USE_DAL_SMARTCARD_REGISTER_CALLBACK */ +} + +/** + * @brief DMA SMARTCARD communication error callback + * @param hdma Pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +static void SMARTCARD_DMAError(DMA_HandleTypeDef *hdma) +{ + uint32_t dmarequest = 0x00U; + SMARTCARD_HandleTypeDef* hsc = ( SMARTCARD_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + hsc->RxXferCount = 0U; + hsc->TxXferCount = 0U; + hsc->ErrorCode = DAL_SMARTCARD_ERROR_DMA; + + /* Stop SMARTCARD DMA Tx request if ongoing */ + dmarequest = DAL_IS_BIT_SET(hsc->Instance->CTRL3, USART_CTRL3_DMATXEN); + if((hsc->gState == DAL_SMARTCARD_STATE_BUSY_TX) && dmarequest) + { + SMARTCARD_EndTxTransfer(hsc); + } + + /* Stop SMARTCARD DMA Rx request if ongoing */ + dmarequest = DAL_IS_BIT_SET(hsc->Instance->CTRL3, USART_CTRL3_DMARXEN); + if((hsc->RxState == DAL_SMARTCARD_STATE_BUSY_RX) && dmarequest) + { + SMARTCARD_EndRxTransfer(hsc); + } + +#if (USE_DAL_SMARTCARD_REGISTER_CALLBACKS == 1) + /* Call registered user error callback */ + hsc->ErrorCallback(hsc); +#else + /* Call legacy weak user error callback */ + DAL_SMARTCARD_ErrorCallback(hsc); +#endif /* USE_DAL_SMARTCARD_REGISTER_CALLBACK */ +} + +/** + * @brief This function handles SMARTCARD Communication Timeout. It waits + * until a flag is no longer in the specified status. + * @param hsc Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for SMARTCARD module. + * @param Flag Specifies the SMARTCARD flag to check. + * @param Status The actual Flag status (SET or RESET). + * @param Timeout Timeout duration + * @param Tickstart Tick start value + * @retval DAL status + */ +static DAL_StatusTypeDef SMARTCARD_WaitOnFlagUntilTimeout(SMARTCARD_HandleTypeDef *hsc, uint32_t Flag, FlagStatus Status, uint32_t Tickstart, uint32_t Timeout) +{ + /* Wait until flag is set */ + while((__DAL_SMARTCARD_GET_FLAG(hsc, Flag) ? SET : RESET) == Status) + { + /* Check for the Timeout */ + if(Timeout != DAL_MAX_DELAY) + { + if((Timeout == 0U)||((DAL_GetTick() - Tickstart ) > Timeout)) + { + /* Disable TXBEIEN and RXBNEIEN interrupts for the interrupt process */ + CLEAR_BIT(hsc->Instance->CTRL1, USART_CTRL1_TXBEIEN); + CLEAR_BIT(hsc->Instance->CTRL1, USART_CTRL1_RXBNEIEN); + + hsc->gState= DAL_SMARTCARD_STATE_READY; + hsc->RxState= DAL_SMARTCARD_STATE_READY; + + /* Process Unlocked */ + __DAL_UNLOCK(hsc); + + return DAL_TIMEOUT; + } + } + } + return DAL_OK; +} + +/** + * @brief End ongoing Tx transfer on SMARTCARD peripheral (following error detection or Transmit completion). + * @param hsc Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for SMARTCARD module. + * @retval None + */ +static void SMARTCARD_EndTxTransfer(SMARTCARD_HandleTypeDef *hsc) +{ + /* At end of Tx process, restore hsc->gState to Ready */ + hsc->gState = DAL_SMARTCARD_STATE_READY; + + /* Disable TXBEIEN and TXCIEN interrupts */ + CLEAR_BIT(hsc->Instance->CTRL1, (USART_CTRL1_TXBEIEN | USART_CTRL1_TXCIEN)); +} + + +/** + * @brief End ongoing Rx transfer on SMARTCARD peripheral (following error detection or Reception completion). + * @param hsc Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for SMARTCARD module. + * @retval None + */ +static void SMARTCARD_EndRxTransfer(SMARTCARD_HandleTypeDef *hsc) +{ + /* At end of Rx process, restore hsc->RxState to Ready */ + hsc->RxState = DAL_SMARTCARD_STATE_READY; + + /* Disable RXBNEIEN, PEIEN and ERRIEN (Frame error, noise error, overrun error) interrupts */ + CLEAR_BIT(hsc->Instance->CTRL1, (USART_CTRL1_RXBNEIEN | USART_CTRL1_PEIEN)); + CLEAR_BIT(hsc->Instance->CTRL3, USART_CTRL3_ERRIEN); +} + +/** + * @brief Send an amount of data in non blocking mode + * @param hsc Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for SMARTCARD module. + * @retval DAL status + */ +static DAL_StatusTypeDef SMARTCARD_Transmit_IT(SMARTCARD_HandleTypeDef *hsc) +{ + + /* Check that a Tx process is ongoing */ + if(hsc->gState == DAL_SMARTCARD_STATE_BUSY_TX) + { + hsc->Instance->DATA = (uint8_t)(*hsc->pTxBuffPtr & 0xFFU); + hsc->pTxBuffPtr++; + + if(--hsc->TxXferCount == 0U) + { + /* Disable the SMARTCARD Transmit data register empty Interrupt */ + CLEAR_BIT(hsc->Instance->CTRL1, USART_CTRL1_TXBEIEN); + + /* Enable the SMARTCARD Transmit Complete Interrupt */ + SET_BIT(hsc->Instance->CTRL1, USART_CTRL1_TXCIEN); + } + + return DAL_OK; + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief Wraps up transmission in non blocking mode. + * @param hsc Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for the specified SMARTCARD module. + * @retval DAL status + */ +static DAL_StatusTypeDef SMARTCARD_EndTransmit_IT(SMARTCARD_HandleTypeDef *hsc) +{ + /* Disable the SMARTCARD Transmit Complete Interrupt */ + CLEAR_BIT(hsc->Instance->CTRL1, USART_CTRL1_TXCIEN); + + /* Disable the SMARTCARD Error Interrupt: (Frame error, noise error, overrun error) */ + CLEAR_BIT(hsc->Instance->CTRL3, USART_CTRL3_ERRIEN); + + /* Tx process is ended, restore hsc->gState to Ready */ + hsc->gState = DAL_SMARTCARD_STATE_READY; + +#if (USE_DAL_SMARTCARD_REGISTER_CALLBACKS == 1) + /* Call registered Tx complete callback */ + hsc->TxCpltCallback(hsc); +#else + /* Call legacy weak Tx complete callback */ + DAL_SMARTCARD_TxCpltCallback(hsc); +#endif /* USE_DAL_SMARTCARD_REGISTER_CALLBACK */ + + return DAL_OK; +} + +/** + * @brief Receive an amount of data in non blocking mode + * @param hsc Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for SMARTCARD module. + * @retval DAL status + */ +static DAL_StatusTypeDef SMARTCARD_Receive_IT(SMARTCARD_HandleTypeDef *hsc) +{ + + /* Check that a Rx process is ongoing */ + if(hsc->RxState == DAL_SMARTCARD_STATE_BUSY_RX) + { + *hsc->pRxBuffPtr = (uint8_t)(hsc->Instance->DATA & (uint8_t)0xFFU); + hsc->pRxBuffPtr++; + + if(--hsc->RxXferCount == 0U) + { + CLEAR_BIT(hsc->Instance->CTRL1, USART_CTRL1_RXBNEIEN); + + /* Disable the SMARTCARD Parity Error Interrupt */ + CLEAR_BIT(hsc->Instance->CTRL1, USART_CTRL1_PEIEN); + + /* Disable the SMARTCARD Error Interrupt: (Frame error, noise error, overrun error) */ + CLEAR_BIT(hsc->Instance->CTRL3, USART_CTRL3_ERRIEN); + + /* Rx process is completed, restore hsc->RxState to Ready */ + hsc->RxState = DAL_SMARTCARD_STATE_READY; + +#if (USE_DAL_SMARTCARD_REGISTER_CALLBACKS == 1) + /* Call registered Rx complete callback */ + hsc->RxCpltCallback(hsc); +#else + /* Call legacy weak Rx complete callback */ + DAL_SMARTCARD_RxCpltCallback(hsc); +#endif /* USE_DAL_SMARTCARD_REGISTER_CALLBACK */ + + return DAL_OK; + } + return DAL_OK; + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief DMA SMARTCARD communication abort callback, when initiated by DAL services on Error + * (To be called at end of DMA Abort procedure following error occurrence). + * @param hdma DMA handle. + * @retval None + */ +static void SMARTCARD_DMAAbortOnError(DMA_HandleTypeDef *hdma) +{ + SMARTCARD_HandleTypeDef* hsc = (SMARTCARD_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + hsc->RxXferCount = 0x00U; + hsc->TxXferCount = 0x00U; + +#if (USE_DAL_SMARTCARD_REGISTER_CALLBACKS == 1) + /* Call registered user error callback */ + hsc->ErrorCallback(hsc); +#else + /* Call legacy weak user error callback */ + DAL_SMARTCARD_ErrorCallback(hsc); +#endif /* USE_DAL_SMARTCARD_REGISTER_CALLBACK */ +} + +/** + * @brief DMA SMARTCARD Tx communication abort callback, when initiated by user + * (To be called at end of DMA Tx Abort procedure following user abort request). + * @note When this callback is executed, User Abort complete call back is called only if no + * Abort still ongoing for Rx DMA Handle. + * @param hdma DMA handle. + * @retval None + */ +static void SMARTCARD_DMATxAbortCallback(DMA_HandleTypeDef *hdma) +{ + SMARTCARD_HandleTypeDef* hsc = ( SMARTCARD_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + + hsc->hdmatx->XferAbortCallback = NULL; + + /* Check if an Abort process is still ongoing */ + if(hsc->hdmarx != NULL) + { + if(hsc->hdmarx->XferAbortCallback != NULL) + { + return; + } + } + + /* No Abort process still ongoing : All DMA channels are aborted, call user Abort Complete callback */ + hsc->TxXferCount = 0x00U; + hsc->RxXferCount = 0x00U; + + /* Reset ErrorCode */ + hsc->ErrorCode = DAL_SMARTCARD_ERROR_NONE; + + /* Restore hsc->gState and hsc->RxState to Ready */ + hsc->gState = DAL_SMARTCARD_STATE_READY; + hsc->RxState = DAL_SMARTCARD_STATE_READY; + +#if (USE_DAL_SMARTCARD_REGISTER_CALLBACKS == 1) + /* Call registered Abort complete callback */ + hsc->AbortCpltCallback(hsc); +#else + /* Call legacy weak Abort complete callback */ + DAL_SMARTCARD_AbortCpltCallback(hsc); +#endif /* USE_DAL_SMARTCARD_REGISTER_CALLBACK */ +} + +/** + * @brief DMA SMARTCARD Rx communication abort callback, when initiated by user + * (To be called at end of DMA Rx Abort procedure following user abort request). + * @note When this callback is executed, User Abort complete call back is called only if no + * Abort still ongoing for Tx DMA Handle. + * @param hdma DMA handle. + * @retval None + */ +static void SMARTCARD_DMARxAbortCallback(DMA_HandleTypeDef *hdma) +{ + SMARTCARD_HandleTypeDef* hsc = ( SMARTCARD_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + + hsc->hdmarx->XferAbortCallback = NULL; + + /* Check if an Abort process is still ongoing */ + if(hsc->hdmatx != NULL) + { + if(hsc->hdmatx->XferAbortCallback != NULL) + { + return; + } + } + + /* No Abort process still ongoing : All DMA channels are aborted, call user Abort Complete callback */ + hsc->TxXferCount = 0x00U; + hsc->RxXferCount = 0x00U; + + /* Reset ErrorCode */ + hsc->ErrorCode = DAL_SMARTCARD_ERROR_NONE; + + /* Restore hsc->gState and hsc->RxState to Ready */ + hsc->gState = DAL_SMARTCARD_STATE_READY; + hsc->RxState = DAL_SMARTCARD_STATE_READY; + +#if (USE_DAL_SMARTCARD_REGISTER_CALLBACKS == 1) + /* Call registered Abort complete callback */ + hsc->AbortCpltCallback(hsc); +#else + /* Call legacy weak Abort complete callback */ + DAL_SMARTCARD_AbortCpltCallback(hsc); +#endif /* USE_DAL_SMARTCARD_REGISTER_CALLBACK */ +} + +/** + * @brief DMA SMARTCARD Tx communication abort callback, when initiated by user by a call to + * DAL_SMARTCARD_AbortTransmit_IT API (Abort only Tx transfer) + * (This callback is executed at end of DMA Tx Abort procedure following user abort request, + * and leads to user Tx Abort Complete callback execution). + * @param hdma DMA handle. + * @retval None + */ +static void SMARTCARD_DMATxOnlyAbortCallback(DMA_HandleTypeDef *hdma) +{ + SMARTCARD_HandleTypeDef* hsc = ( SMARTCARD_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + + hsc->TxXferCount = 0x00U; + + /* Restore hsc->gState to Ready */ + hsc->gState = DAL_SMARTCARD_STATE_READY; + +#if (USE_DAL_SMARTCARD_REGISTER_CALLBACKS == 1) + /* Call registered Abort Transmit Complete Callback */ + hsc->AbortTransmitCpltCallback(hsc); +#else + /* Call legacy weak Abort Transmit Complete Callback */ + DAL_SMARTCARD_AbortTransmitCpltCallback(hsc); +#endif /* USE_DAL_SMARTCARD_REGISTER_CALLBACK */ +} + +/** + * @brief DMA SMARTCARD Rx communication abort callback, when initiated by user by a call to + * DAL_SMARTCARD_AbortReceive_IT API (Abort only Rx transfer) + * (This callback is executed at end of DMA Rx Abort procedure following user abort request, + * and leads to user Rx Abort Complete callback execution). + * @param hdma DMA handle. + * @retval None + */ +static void SMARTCARD_DMARxOnlyAbortCallback(DMA_HandleTypeDef *hdma) +{ + SMARTCARD_HandleTypeDef* hsc = ( SMARTCARD_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + + hsc->RxXferCount = 0x00U; + + /* Restore hsc->RxState to Ready */ + hsc->RxState = DAL_SMARTCARD_STATE_READY; + +#if (USE_DAL_SMARTCARD_REGISTER_CALLBACKS == 1) + /* Call registered Abort Receive Complete Callback */ + hsc->AbortReceiveCpltCallback(hsc); +#else + /* Call legacy weak Abort Receive Complete Callback */ + DAL_SMARTCARD_AbortReceiveCpltCallback(hsc); +#endif /* USE_DAL_SMARTCARD_REGISTER_CALLBACK */ +} + +/** + * @brief Configure the SMARTCARD peripheral + * @param hsc Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for SMARTCARD module. + * @retval None + */ +static void SMARTCARD_SetConfig(SMARTCARD_HandleTypeDef *hsc) +{ + uint32_t tmpreg = 0x00U; + uint32_t pclk; + + /* Check the parameters */ + ASSERT_PARAM(IS_SMARTCARD_INSTANCE(hsc->Instance)); + ASSERT_PARAM(IS_SMARTCARD_POLARITY(hsc->Init.CLKPolarity)); + ASSERT_PARAM(IS_SMARTCARD_PHASE(hsc->Init.CLKPhase)); + ASSERT_PARAM(IS_SMARTCARD_LASTBIT(hsc->Init.CLKLastBit)); + ASSERT_PARAM(IS_SMARTCARD_BAUDRATE(hsc->Init.BaudRate)); + ASSERT_PARAM(IS_SMARTCARD_WORD_LENGTH(hsc->Init.WordLength)); + ASSERT_PARAM(IS_SMARTCARD_STOPBITS(hsc->Init.StopBits)); + ASSERT_PARAM(IS_SMARTCARD_PARITY(hsc->Init.Parity)); + ASSERT_PARAM(IS_SMARTCARD_MODE(hsc->Init.Mode)); + ASSERT_PARAM(IS_SMARTCARD_NACK_STATE(hsc->Init.NACKState)); + + /* The LBCL, CPOL and CPHA bits have to be selected when both the transmitter and the + receiver are disabled (TE=RE=0) to ensure that the clock pulses function correctly. */ + CLEAR_BIT(hsc->Instance->CTRL1, (USART_CTRL1_TXEN | USART_CTRL1_RXEN)); + + /*---------------------------- USART CTRL2 Configuration ---------------------*/ + tmpreg = hsc->Instance->CTRL2; + /* Clear CLKEN, CPOL, CPHA and LBCPOEN bits */ + tmpreg &= (uint32_t)~((uint32_t)(USART_CTRL2_CPHA | USART_CTRL2_CPOL | USART_CTRL2_CLKEN | USART_CTRL2_LBCPOEN)); + /* Configure the SMARTCARD Clock, CPOL, CPHA and LastBit -----------------------*/ + /* Set CPOL bit according to hsc->Init.CLKPolarity value */ + /* Set CPHA bit according to hsc->Init.CLKPhase value */ + /* Set LBCL bit according to hsc->Init.CLKLastBit value */ + /* Set Stop Bits: Set STOP[13:12] bits according to hsc->Init.StopBits value */ + tmpreg |= (uint32_t)(USART_CTRL2_CLKEN | hsc->Init.CLKPolarity | + hsc->Init.CLKPhase| hsc->Init.CLKLastBit | hsc->Init.StopBits); + /* Write to USART CTRL2 */ + WRITE_REG(hsc->Instance->CTRL2, (uint32_t)tmpreg); + + tmpreg = hsc->Instance->CTRL2; + + /* Clear STOP[13:12] bits */ + tmpreg &= (uint32_t)~((uint32_t)USART_CTRL2_STOPCFG); + + /* Set Stop Bits: Set STOP[13:12] bits according to hsc->Init.StopBits value */ + tmpreg |= (uint32_t)(hsc->Init.StopBits); + + /* Write to USART CTRL2 */ + WRITE_REG(hsc->Instance->CTRL2, (uint32_t)tmpreg); + + /*-------------------------- USART CTRL1 Configuration -----------------------*/ + tmpreg = hsc->Instance->CTRL1; + + /* Clear M, PCE, PS, TE and RE bits */ + tmpreg &= (uint32_t)~((uint32_t)(USART_CTRL1_DBLCFG | USART_CTRL1_PCEN | USART_CTRL1_PCFG | USART_CTRL1_TXEN | \ + USART_CTRL1_RXEN)); + + /* Configure the SMARTCARD Word Length, Parity and mode: + Set the M bits according to hsc->Init.WordLength value + Set PCE and PS bits according to hsc->Init.Parity value + Set TE and RE bits according to hsc->Init.Mode value */ + tmpreg |= (uint32_t)hsc->Init.WordLength | hsc->Init.Parity | hsc->Init.Mode; + + /* Write to USART CTRL1 */ + WRITE_REG(hsc->Instance->CTRL1, (uint32_t)tmpreg); + + /*-------------------------- USART CTRL3 Configuration -----------------------*/ + /* Clear CTSEN and RTSEN bits */ + CLEAR_BIT(hsc->Instance->CTRL3, (USART_CTRL3_RTSEN | USART_CTRL3_CTSEN)); + + /*-------------------------- USART BR Configuration -----------------------*/ +#if defined(USART6) + if((hsc->Instance == USART1) || (hsc->Instance == USART6)) + { + pclk = DAL_RCM_GetPCLK2Freq(); + hsc->Instance->BR = SMARTCARD_BR(pclk, hsc->Init.BaudRate); + } +#else + if(hsc->Instance == USART1) + { + pclk = DAL_RCM_GetPCLK2Freq(); + hsc->Instance->BR = SMARTCARD_BR(pclk, hsc->Init.BaudRate); + } +#endif /* USART6 */ + else + { + pclk = DAL_RCM_GetPCLK1Freq(); + hsc->Instance->BR = SMARTCARD_BR(pclk, hsc->Init.BaudRate); + } +} + +/** + * @} + */ + +#endif /* DAL_SMARTCARD_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_smbus.c b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_smbus.c new file mode 100644 index 0000000000..8476c8d81a --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_smbus.c @@ -0,0 +1,2809 @@ +/** + * + * @file apm32f4xx_dal_smbus.c + * @brief SMBUS DAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the System Management Bus (SMBus) peripheral, + * based on SMBUS principals of operation : + * + Initialization and de-initialization functions + * + IO operation functions + * + Peripheral State, Mode and Error functions + * + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + * + @verbatim + ============================================================================== + ##### How to use this driver ##### + ============================================================================== + [..] + The SMBUS DAL driver can be used as follows: + + (#) Declare a SMBUS_HandleTypeDef handle structure, for example: + SMBUS_HandleTypeDef hsmbus; + + (#)Initialize the SMBUS low level resources by implementing the DAL_SMBUS_MspInit() API: + (##) Enable the SMBUSx interface clock + (##) SMBUS pins configuration + (+++) Enable the clock for the SMBUS GPIOs + (+++) Configure SMBUS pins as alternate function open-drain + (##) NVIC configuration if you need to use interrupt process + (+++) Configure the SMBUSx interrupt priority + (+++) Enable the NVIC SMBUS IRQ Channel + + (#) Configure the Communication Speed, Duty cycle, Addressing mode, Own Address1, + Dual Addressing mode, Own Address2, General call and Nostretch mode in the hsmbus Init structure. + + (#) Initialize the SMBUS registers by calling the DAL_SMBUS_Init(), configures also the low level Hardware + (GPIO, CLOCK, NVIC...etc) by calling the customized DAL_SMBUS_MspInit(&hsmbus) API. + + (#) To check if target device is ready for communication, use the function DAL_SMBUS_IsDeviceReady() + + (#) For SMBUS IO operations, only one mode of operations is available within this driver : + + + *** Interrupt mode IO operation *** + =================================== + + [..] + (+) Transmit in master/host SMBUS mode an amount of data in non blocking mode using DAL_SMBUS_Master_Transmit_IT() + (++) At transmission end of transfer DAL_SMBUS_MasterTxCpltCallback() is executed and user can + add his own code by customization of function pointer DAL_SMBUS_MasterTxCpltCallback() + (+) Receive in master/host SMBUS mode an amount of data in non blocking mode using DAL_SMBUS_Master_Receive_IT() + (++) At reception end of transfer DAL_SMBUS_MasterRxCpltCallback() is executed and user can + add his own code by customization of function pointer DAL_SMBUS_MasterRxCpltCallback() + (+) Abort a master/Host SMBUS process communication with Interrupt using DAL_SMBUS_Master_Abort_IT() + (++) End of abort process, DAL_SMBUS_AbortCpltCallback() is executed and user can + add his own code by customization of function pointer DAL_SMBUS_AbortCpltCallback() + (+) Enable/disable the Address listen mode in slave/device or host/slave SMBUS mode + using DAL_SMBUS_EnableListen_IT() DAL_SMBUS_DisableListen_IT() + (++) When address slave/device SMBUS match, DAL_SMBUS_AddrCallback() is executed and user can + add his own code to check the Address Match Code and the transmission direction request by master/host (Write/Read). + (++) At Listen mode end DAL_SMBUS_ListenCpltCallback() is executed and user can + add his own code by customization of function pointer DAL_SMBUS_ListenCpltCallback() + (+) Transmit in slave/device SMBUS mode an amount of data in non blocking mode using DAL_SMBUS_Slave_Transmit_IT() + (++) At transmission end of transfer DAL_SMBUS_SlaveTxCpltCallback() is executed and user can + add his own code by customization of function pointer DAL_SMBUS_SlaveTxCpltCallback() + (+) Receive in slave/device SMBUS mode an amount of data in non blocking mode using DAL_SMBUS_Slave_Receive_IT() + (++) At reception end of transfer DAL_SMBUS_SlaveRxCpltCallback() is executed and user can + add his own code by customization of function pointer DAL_SMBUS_SlaveRxCpltCallback() + (+) Enable/Disable the SMBUS alert mode using DAL_SMBUS_EnableAlert_IT() and DAL_SMBUS_DisableAlert_IT() + (++) When SMBUS Alert is generated DAL_SMBUS_ErrorCallback() is executed and user can + add his own code by customization of function pointer DAL_SMBUS_ErrorCallback() + to check the Alert Error Code using function DAL_SMBUS_GetError() + (+) Get DAL state machine or error values using DAL_SMBUS_GetState() or DAL_SMBUS_GetError() + (+) In case of transfer Error, DAL_SMBUS_ErrorCallback() function is executed and user can + add his own code by customization of function pointer DAL_SMBUS_ErrorCallback() + to check the Error Code using function DAL_SMBUS_GetError() + + + *** SMBUS DAL driver macros list *** + ================================== + [..] + Below the list of most used macros in SMBUS DAL driver. + + (+) __DAL_SMBUS_ENABLE : Enable the SMBUS peripheral + (+) __DAL_SMBUS_DISABLE : Disable the SMBUS peripheral + (+) __DAL_SMBUS_GET_FLAG : Checks whether the specified SMBUS flag is set or not + (+) __DAL_SMBUS_CLEAR_FLAG: Clear the specified SMBUS pending flag + (+) __DAL_SMBUS_ENABLE_IT : Enable the specified SMBUS interrupt + (+) __DAL_SMBUS_DISABLE_IT: Disable the specified SMBUS interrupt + + [..] + (@) You can refer to the SMBUS DAL driver header file for more useful macros + + *** Callback registration *** + ============================================= + [..] + The compilation flag USE_DAL_SMBUS_REGISTER_CALLBACKS when set to 1 + allows the user to configure dynamically the driver callbacks. + Use Functions DAL_SMBUS_RegisterCallback() or DAL_SMBUS_RegisterXXXCallback() + to register an interrupt callback. + + Function DAL_SMBUS_RegisterCallback() allows to register following callbacks: + (+) MasterTxCpltCallback : callback for Master transmission end of transfer. + (+) MasterRxCpltCallback : callback for Master reception end of transfer. + (+) SlaveTxCpltCallback : callback for Slave transmission end of transfer. + (+) SlaveRxCpltCallback : callback for Slave reception end of transfer. + (+) ListenCpltCallback : callback for end of listen mode. + (+) ErrorCallback : callback for error detection. + (+) AbortCpltCallback : callback for abort completion process. + (+) MspInitCallback : callback for Msp Init. + (+) MspDeInitCallback : callback for Msp DeInit. + This function takes as parameters the DAL peripheral handle, the Callback ID + and a pointer to the user callback function. + [..] + For specific callback AddrCallback use dedicated register callbacks : DAL_SMBUS_RegisterAddrCallback(). + [..] + Use function DAL_SMBUS_UnRegisterCallback to reset a callback to the default + weak function. + DAL_SMBUS_UnRegisterCallback takes as parameters the DAL peripheral handle, + and the Callback ID. + This function allows to reset following callbacks: + (+) MasterTxCpltCallback : callback for Master transmission end of transfer. + (+) MasterRxCpltCallback : callback for Master reception end of transfer. + (+) SlaveTxCpltCallback : callback for Slave transmission end of transfer. + (+) SlaveRxCpltCallback : callback for Slave reception end of transfer. + (+) ListenCpltCallback : callback for end of listen mode. + (+) ErrorCallback : callback for error detection. + (+) AbortCpltCallback : callback for abort completion process. + (+) MspInitCallback : callback for Msp Init. + (+) MspDeInitCallback : callback for Msp DeInit. + [..] + For callback AddrCallback use dedicated register callbacks : DAL_SMBUS_UnRegisterAddrCallback(). + [..] + By default, after the DAL_SMBUS_Init() and when the state is DAL_SMBUS_STATE_RESET + all callbacks are set to the corresponding weak functions: + examples DAL_SMBUS_MasterTxCpltCallback(), DAL_SMBUS_MasterRxCpltCallback(). + Exception done for MspInit and MspDeInit functions that are + reset to the legacy weak functions in the DAL_SMBUS_Init()/ DAL_SMBUS_DeInit() only when + these callbacks are null (not registered beforehand). + If MspInit or MspDeInit are not null, the DAL_SMBUS_Init()/ DAL_SMBUS_DeInit() + keep and use the user MspInit/MspDeInit callbacks (registered beforehand) whatever the state. + [..] + Callbacks can be registered/unregistered in DAL_SMBUS_STATE_READY state only. + Exception done MspInit/MspDeInit functions that can be registered/unregistered + in DAL_SMBUS_STATE_READY or DAL_SMBUS_STATE_RESET state, + thus registered (user) MspInit/DeInit callbacks can be used during the Init/DeInit. + Then, the user first registers the MspInit/MspDeInit user callbacks + using DAL_SMBUS_RegisterCallback() before calling DAL_SMBUS_DeInit() + or DAL_SMBUS_Init() function. + [..] + When the compilation flag USE_DAL_SMBUS_REGISTER_CALLBACKS is set to 0 or + not defined, the callback registration feature is not available and all callbacks + are set to the corresponding weak functions. + + @endverbatim + */ + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @defgroup SMBUS SMBUS + * @brief SMBUS DAL module driver + * @{ + */ + +#ifdef DAL_SMBUS_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/** @addtogroup SMBUS_Private_Define + * @{ + */ +#define SMBUS_TIMEOUT_FLAG 35U /*!< Timeout 35 ms */ +#define SMBUS_TIMEOUT_BUSY_FLAG 25U /*!< Timeout 25 ms */ +#define SMBUS_NO_OPTION_FRAME 0xFFFF0000U /*!< XferOptions default value */ + +#define SMBUS_SENDPEC_MODE I2C_CTRL1_PEC +#define SMBUS_GET_PEC(__HANDLE__) (((__HANDLE__)->Instance->STS2 & I2C_STS2_PECVALUE) >> 8) + +/* Private define for @ref PreviousState usage */ +#define SMBUS_STATE_MSK ((uint32_t)((DAL_SMBUS_STATE_BUSY_TX | DAL_SMBUS_STATE_BUSY_RX) & (~(uint32_t)DAL_SMBUS_STATE_READY))) /*!< Mask State define, keep only RX and TX bits */ +#define SMBUS_STATE_NONE ((uint32_t)(DAL_SMBUS_MODE_NONE)) /*!< Default Value */ +#define SMBUS_STATE_MASTER_BUSY_TX ((uint32_t)((DAL_SMBUS_STATE_BUSY_TX & SMBUS_STATE_MSK) | DAL_SMBUS_MODE_MASTER)) /*!< Master Busy TX, combinaison of State LSB and Mode enum */ +#define SMBUS_STATE_MASTER_BUSY_RX ((uint32_t)((DAL_SMBUS_STATE_BUSY_RX & SMBUS_STATE_MSK) | DAL_SMBUS_MODE_MASTER)) /*!< Master Busy RX, combinaison of State LSB and Mode enum */ +#define SMBUS_STATE_SLAVE_BUSY_TX ((uint32_t)((DAL_SMBUS_STATE_BUSY_TX & SMBUS_STATE_MSK) | DAL_SMBUS_MODE_SLAVE)) /*!< Slave Busy TX, combinaison of State LSB and Mode enum */ +#define SMBUS_STATE_SLAVE_BUSY_RX ((uint32_t)((DAL_SMBUS_STATE_BUSY_RX & SMBUS_STATE_MSK) | DAL_SMBUS_MODE_SLAVE)) /*!< Slave Busy RX, combinaison of State LSB and Mode enum */ + +/** + * @} + */ + +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ + +/** @addtogroup SMBUS_Private_Functions + * @{ + */ + +static DAL_StatusTypeDef SMBUS_WaitOnFlagUntilTimeout(SMBUS_HandleTypeDef *hsmbus, uint32_t Flag, FlagStatus Status, uint32_t Timeout, uint32_t Tickstart); +static void SMBUS_ITError(SMBUS_HandleTypeDef *hsmbus); + +/* Private functions for SMBUS transfer IRQ handler */ +static DAL_StatusTypeDef SMBUS_MasterTransmit_TXE(SMBUS_HandleTypeDef *hsmbus); +static DAL_StatusTypeDef SMBUS_MasterTransmit_BTF(SMBUS_HandleTypeDef *hsmbus); +static DAL_StatusTypeDef SMBUS_MasterReceive_RXNE(SMBUS_HandleTypeDef *hsmbus); +static DAL_StatusTypeDef SMBUS_MasterReceive_BTF(SMBUS_HandleTypeDef *hsmbus); +static DAL_StatusTypeDef SMBUS_Master_SB(SMBUS_HandleTypeDef *hsmbus); +static DAL_StatusTypeDef SMBUS_Master_ADD10(SMBUS_HandleTypeDef *hsmbus); +static DAL_StatusTypeDef SMBUS_Master_ADDR(SMBUS_HandleTypeDef *hsmbus); + +static DAL_StatusTypeDef SMBUS_SlaveTransmit_TXE(SMBUS_HandleTypeDef *hsmbus); +static DAL_StatusTypeDef SMBUS_SlaveTransmit_BTF(SMBUS_HandleTypeDef *hsmbus); +static DAL_StatusTypeDef SMBUS_SlaveReceive_RXNE(SMBUS_HandleTypeDef *hsmbus); +static DAL_StatusTypeDef SMBUS_SlaveReceive_BTF(SMBUS_HandleTypeDef *hsmbus); +static DAL_StatusTypeDef SMBUS_Slave_ADDR(SMBUS_HandleTypeDef *hsmbus); +static DAL_StatusTypeDef SMBUS_Slave_STOPF(SMBUS_HandleTypeDef *hsmbus); +static DAL_StatusTypeDef SMBUS_Slave_AF(SMBUS_HandleTypeDef *hsmbus); +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +/** @defgroup SMBUS_Exported_Functions SMBUS Exported Functions + * @{ + */ + +/** @defgroup SMBUS_Exported_Functions_Group1 Initialization and de-initialization functions + * @brief Initialization and Configuration functions + * +@verbatim + =============================================================================== + ##### Initialization and de-initialization functions ##### + =============================================================================== + [..] This subsection provides a set of functions allowing to initialize and + deinitialize the SMBUSx peripheral: + + (+) User must Implement DAL_SMBUS_MspInit() function in which he configures + all related peripherals resources (CLOCK, GPIO, IT and NVIC). + + (+) Call the function DAL_SMBUS_Init() to configure the selected device with + the selected configuration: + (++) Communication Speed + (++) Addressing mode + (++) Own Address 1 + (++) Dual Addressing mode + (++) Own Address 2 + (++) General call mode + (++) Nostretch mode + (++) Packet Error Check mode + (++) Peripheral mode + + (+) Call the function DAL_SMBUS_DeInit() to restore the default configuration + of the selected SMBUSx peripheral. + +@endverbatim + * @{ + */ + +/** + * @brief Initializes the SMBUS according to the specified parameters + * in the SMBUS_InitTypeDef and initialize the associated handle. + * @param hsmbus pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SMBUS_Init(SMBUS_HandleTypeDef *hsmbus) +{ + uint32_t freqrange = 0U; + uint32_t pclk1 = 0U; + + /* Check the SMBUS handle allocation */ + if (hsmbus == NULL) + { + return DAL_ERROR; + } + + /* Check the parameters */ + ASSERT_PARAM(IS_SMBUS_ALL_INSTANCE(hsmbus->Instance)); +#if defined(I2C_FILTER_ANFDIS) + ASSERT_PARAM(IS_SMBUS_ANALOG_FILTER(hsmbus->Init.AnalogFilter)); +#endif + ASSERT_PARAM(IS_SMBUS_CLOCK_SPEED(hsmbus->Init.ClockSpeed)); + ASSERT_PARAM(IS_SMBUS_OWN_ADDRESS1(hsmbus->Init.OwnAddress1)); + ASSERT_PARAM(IS_SMBUS_ADDRESSING_MODE(hsmbus->Init.AddressingMode)); + ASSERT_PARAM(IS_SMBUS_DUAL_ADDRESS(hsmbus->Init.DualAddressMode)); + ASSERT_PARAM(IS_SMBUS_OWN_ADDRESS2(hsmbus->Init.OwnAddress2)); + ASSERT_PARAM(IS_SMBUS_GENERAL_CALL(hsmbus->Init.GeneralCallMode)); + ASSERT_PARAM(IS_SMBUS_NO_STRETCH(hsmbus->Init.NoStretchMode)); + ASSERT_PARAM(IS_SMBUS_PEC(hsmbus->Init.PacketErrorCheckMode)); + ASSERT_PARAM(IS_SMBUS_PERIPHERAL_MODE(hsmbus->Init.PeripheralMode)); + + if (hsmbus->State == DAL_SMBUS_STATE_RESET) + { + /* Allocate lock resource and initialize it */ + hsmbus->Lock = DAL_UNLOCKED; + /* Init the low level hardware : GPIO, CLOCK, NVIC */ +#if (USE_DAL_SMBUS_REGISTER_CALLBACKS == 1) + /* Init the SMBUS Callback settings */ + hsmbus->MasterTxCpltCallback = DAL_SMBUS_MasterTxCpltCallback; /* Legacy weak MasterTxCpltCallback */ + hsmbus->MasterRxCpltCallback = DAL_SMBUS_MasterRxCpltCallback; /* Legacy weak MasterRxCpltCallback */ + hsmbus->SlaveTxCpltCallback = DAL_SMBUS_SlaveTxCpltCallback; /* Legacy weak SlaveTxCpltCallback */ + hsmbus->SlaveRxCpltCallback = DAL_SMBUS_SlaveRxCpltCallback; /* Legacy weak SlaveRxCpltCallback */ + hsmbus->ListenCpltCallback = DAL_SMBUS_ListenCpltCallback; /* Legacy weak ListenCpltCallback */ + hsmbus->ErrorCallback = DAL_SMBUS_ErrorCallback; /* Legacy weak ErrorCallback */ + hsmbus->AbortCpltCallback = DAL_SMBUS_AbortCpltCallback; /* Legacy weak AbortCpltCallback */ + hsmbus->AddrCallback = DAL_SMBUS_AddrCallback; /* Legacy weak AddrCallback */ + + if (hsmbus->MspInitCallback == NULL) + { + hsmbus->MspInitCallback = DAL_SMBUS_MspInit; /* Legacy weak MspInit */ + } + + /* Init the low level hardware : GPIO, CLOCK, NVIC */ + hsmbus->MspInitCallback(hsmbus); +#else + /* Init the low level hardware : GPIO, CLOCK, NVIC */ + DAL_SMBUS_MspInit(hsmbus); +#endif /* USE_DAL_SMBUS_REGISTER_CALLBACKS */ + } + + hsmbus->State = DAL_SMBUS_STATE_BUSY; + + /* Disable the selected SMBUS peripheral */ + __DAL_SMBUS_DISABLE(hsmbus); + + /* Get PCLK1 frequency */ + pclk1 = DAL_RCM_GetPCLK1Freq(); + + /* Calculate frequency range */ + freqrange = SMBUS_FREQRANGE(pclk1); + + /*---------------------------- SMBUSx CTRL2 Configuration ----------------------*/ + /* Configure SMBUSx: Frequency range */ + MODIFY_REG(hsmbus->Instance->CTRL2, I2C_CTRL2_CLKFCFG, freqrange); + + /*---------------------------- SMBUSx RISETMAX Configuration --------------------*/ + /* Configure SMBUSx: Rise Time */ + MODIFY_REG(hsmbus->Instance->RISETMAX, I2C_RISETMAX_RISETMAX, SMBUS_RISE_TIME(freqrange)); + + /*---------------------------- SMBUSx CLKCTRL Configuration ----------------------*/ + /* Configure SMBUSx: Speed */ + MODIFY_REG(hsmbus->Instance->CLKCTRL, (I2C_CLKCTRL_SPEEDCFG | I2C_CLKCTRL_FDUTYCFG | I2C_CLKCTRL_CLKS), SMBUS_SPEED_STANDARD(pclk1, hsmbus->Init.ClockSpeed)); + + /*---------------------------- SMBUSx CTRL1 Configuration ----------------------*/ + /* Configure SMBUSx: Generalcall , PEC , Peripheral mode and NoStretch mode */ + MODIFY_REG(hsmbus->Instance->CTRL1, (I2C_CTRL1_CLKSTRETCHD | I2C_CTRL1_SRBEN | I2C_CTRL1_PECEN | I2C_CTRL1_ARPEN | I2C_CTRL1_SMBTCFG | I2C_CTRL1_SMBEN), (hsmbus->Init.NoStretchMode | hsmbus->Init.GeneralCallMode | hsmbus->Init.PacketErrorCheckMode | hsmbus->Init.PeripheralMode)); + + /*---------------------------- SMBUSx SADDR1 Configuration ---------------------*/ + /* Configure SMBUSx: Own Address1 and addressing mode */ + MODIFY_REG(hsmbus->Instance->SADDR1, (I2C_SADDR1_ADDRLEN | I2C_SADDR1_ADDR8_9 | I2C_SADDR1_ADDR1_7 | I2C_SADDR1_ADDR0), (hsmbus->Init.AddressingMode | hsmbus->Init.OwnAddress1)); + + /*---------------------------- SMBUSx SADDR2 Configuration ---------------------*/ + /* Configure SMBUSx: Dual mode and Own Address2 */ + MODIFY_REG(hsmbus->Instance->SADDR2, (I2C_SADDR2_ADDRNUM | I2C_SADDR2_ADDR2), (hsmbus->Init.DualAddressMode | hsmbus->Init.OwnAddress2)); +#if defined(I2C_FILTER_ANFDIS) + /*---------------------------- SMBUSx FLTR Configuration ------------------------*/ + /* Configure SMBUSx: Analog noise filter */ + SET_BIT(hsmbus->Instance->FILTER, hsmbus->Init.AnalogFilter); +#endif + + /* Enable the selected SMBUS peripheral */ + __DAL_SMBUS_ENABLE(hsmbus); + + hsmbus->ErrorCode = DAL_SMBUS_ERROR_NONE; + hsmbus->State = DAL_SMBUS_STATE_READY; + hsmbus->PreviousState = SMBUS_STATE_NONE; + hsmbus->Mode = DAL_SMBUS_MODE_NONE; + hsmbus->XferPEC = 0x00; + + return DAL_OK; +} + +/** + * @brief DeInitializes the SMBUS peripheral. + * @param hsmbus pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SMBUS_DeInit(SMBUS_HandleTypeDef *hsmbus) +{ + /* Check the SMBUS handle allocation */ + if (hsmbus == NULL) + { + return DAL_ERROR; + } + + /* Check the parameters */ + ASSERT_PARAM(IS_SMBUS_ALL_INSTANCE(hsmbus->Instance)); + + hsmbus->State = DAL_SMBUS_STATE_BUSY; + + /* Disable the SMBUS Peripheral Clock */ + __DAL_SMBUS_DISABLE(hsmbus); + +#if (USE_DAL_SMBUS_REGISTER_CALLBACKS == 1) + if (hsmbus->MspDeInitCallback == NULL) + { + hsmbus->MspDeInitCallback = DAL_SMBUS_MspDeInit; /* Legacy weak MspDeInit */ + } + + /* DeInit the low level hardware: GPIO, CLOCK, NVIC */ + hsmbus->MspDeInitCallback(hsmbus); +#else + /* DeInit the low level hardware: GPIO, CLOCK, NVIC */ + DAL_SMBUS_MspDeInit(hsmbus); +#endif /* USE_DAL_SMBUS_REGISTER_CALLBACKS */ + + hsmbus->ErrorCode = DAL_SMBUS_ERROR_NONE; + hsmbus->State = DAL_SMBUS_STATE_RESET; + hsmbus->PreviousState = SMBUS_STATE_NONE; + hsmbus->Mode = DAL_SMBUS_MODE_NONE; + + /* Release Lock */ + __DAL_UNLOCK(hsmbus); + + return DAL_OK; +} + +/** + * @brief Initialize the SMBUS MSP. + * @param hsmbus pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS + * @retval None + */ +__weak void DAL_SMBUS_MspInit(SMBUS_HandleTypeDef *hsmbus) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hsmbus); + /* NOTE : This function Should not be modified, when the callback is needed, + the DAL_SMBUS_MspInit could be implemented in the user file + */ +} + +/** + * @brief DeInitialize the SMBUS MSP. + * @param hsmbus pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS + * @retval None + */ +__weak void DAL_SMBUS_MspDeInit(SMBUS_HandleTypeDef *hsmbus) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hsmbus); + /* NOTE : This function Should not be modified, when the callback is needed, + the DAL_SMBUS_MspDeInit could be implemented in the user file + */ +} + +#if defined(I2C_FILTER_ANFDIS) && defined(I2C_FILTER_DNFCFG) +/** + * @brief Configures SMBUS Analog noise filter. + * @param hsmbus pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUSx peripheral. + * @param AnalogFilter new state of the Analog filter. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SMBUS_ConfigAnalogFilter(SMBUS_HandleTypeDef *hsmbus, uint32_t AnalogFilter) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_SMBUS_ALL_INSTANCE(hsmbus->Instance)); + ASSERT_PARAM(IS_SMBUS_ANALOG_FILTER(AnalogFilter)); + + if (hsmbus->State == DAL_SMBUS_STATE_READY) + { + hsmbus->State = DAL_SMBUS_STATE_BUSY; + + /* Disable the selected SMBUS peripheral */ + __DAL_SMBUS_DISABLE(hsmbus); + + /* Reset SMBUSx ANFDIS bit */ + hsmbus->Instance->FILTER &= ~(I2C_FILTER_ANFDIS); + + /* Disable the analog filter */ + hsmbus->Instance->FILTER |= AnalogFilter; + + __DAL_SMBUS_ENABLE(hsmbus); + + hsmbus->State = DAL_SMBUS_STATE_READY; + + return DAL_OK; + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief Configures SMBUS Digital noise filter. + * @param hsmbus pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUSx peripheral. + * @param DigitalFilter Coefficient of digital noise filter between 0x00 and 0x0F. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SMBUS_ConfigDigitalFilter(SMBUS_HandleTypeDef *hsmbus, uint32_t DigitalFilter) +{ + uint16_t tmpreg = 0; + + /* Check the parameters */ + ASSERT_PARAM(IS_SMBUS_ALL_INSTANCE(hsmbus->Instance)); + ASSERT_PARAM(IS_SMBUS_DIGITAL_FILTER(DigitalFilter)); + + if (hsmbus->State == DAL_SMBUS_STATE_READY) + { + hsmbus->State = DAL_SMBUS_STATE_BUSY; + + /* Disable the selected SMBUS peripheral */ + __DAL_SMBUS_DISABLE(hsmbus); + + /* Get the old register value */ + tmpreg = hsmbus->Instance->FILTER; + + /* Reset SMBUSx DNFCFG bit [3:0] */ + tmpreg &= ~(I2C_FILTER_DNFCFG); + + /* Set SMBUSx DNFCFG coefficient */ + tmpreg |= DigitalFilter; + + /* Store the new register value */ + hsmbus->Instance->FILTER = tmpreg; + + __DAL_SMBUS_ENABLE(hsmbus); + + hsmbus->State = DAL_SMBUS_STATE_READY; + + return DAL_OK; + } + else + { + return DAL_BUSY; + } +} +#endif /* I2C_FILTER_ANFDIS && I2C_FILTER_DNFCFG */ +#if (USE_DAL_SMBUS_REGISTER_CALLBACKS == 1) +/** + * @brief Register a User SMBUS Callback + * To be used instead of the weak predefined callback + * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @param CallbackID ID of the callback to be registered + * This parameter can be one of the following values: + * @arg @ref DAL_SMBUS_MASTER_TX_COMPLETE_CB_ID Master Tx Transfer completed callback ID + * @arg @ref DAL_SMBUS_MASTER_RX_COMPLETE_CB_ID Master Rx Transfer completed callback ID + * @arg @ref DAL_SMBUS_SLAVE_TX_COMPLETE_CB_ID Slave Tx Transfer completed callback ID + * @arg @ref DAL_SMBUS_SLAVE_RX_COMPLETE_CB_ID Slave Rx Transfer completed callback ID + * @arg @ref DAL_SMBUS_LISTEN_COMPLETE_CB_ID Listen Complete callback ID + * @arg @ref DAL_SMBUS_ERROR_CB_ID Error callback ID + * @arg @ref DAL_SMBUS_ABORT_CB_ID Abort callback ID + * @arg @ref DAL_SMBUS_MSPINIT_CB_ID MspInit callback ID + * @arg @ref DAL_SMBUS_MSPDEINIT_CB_ID MspDeInit callback ID + * @param pCallback pointer to the Callback function + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SMBUS_RegisterCallback(SMBUS_HandleTypeDef *hsmbus, DAL_SMBUS_CallbackIDTypeDef CallbackID, pSMBUS_CallbackTypeDef pCallback) +{ + DAL_StatusTypeDef status = DAL_OK; + + if (pCallback == NULL) + { + /* Update the error code */ + hsmbus->ErrorCode |= DAL_SMBUS_ERROR_INVALID_CALLBACK; + + return DAL_ERROR; + } + /* Process locked */ + __DAL_LOCK(hsmbus); + + if (DAL_SMBUS_STATE_READY == hsmbus->State) + { + switch (CallbackID) + { + case DAL_SMBUS_MASTER_TX_COMPLETE_CB_ID : + hsmbus->MasterTxCpltCallback = pCallback; + break; + + case DAL_SMBUS_MASTER_RX_COMPLETE_CB_ID : + hsmbus->MasterRxCpltCallback = pCallback; + break; + + case DAL_SMBUS_SLAVE_TX_COMPLETE_CB_ID : + hsmbus->SlaveTxCpltCallback = pCallback; + break; + + case DAL_SMBUS_SLAVE_RX_COMPLETE_CB_ID : + hsmbus->SlaveRxCpltCallback = pCallback; + break; + + case DAL_SMBUS_LISTEN_COMPLETE_CB_ID : + hsmbus->ListenCpltCallback = pCallback; + break; + + case DAL_SMBUS_ERROR_CB_ID : + hsmbus->ErrorCallback = pCallback; + break; + + case DAL_SMBUS_ABORT_CB_ID : + hsmbus->AbortCpltCallback = pCallback; + break; + + case DAL_SMBUS_MSPINIT_CB_ID : + hsmbus->MspInitCallback = pCallback; + break; + + case DAL_SMBUS_MSPDEINIT_CB_ID : + hsmbus->MspDeInitCallback = pCallback; + break; + + default : + /* Update the error code */ + hsmbus->ErrorCode |= DAL_SMBUS_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = DAL_ERROR; + break; + } + } + else if (DAL_SMBUS_STATE_RESET == hsmbus->State) + { + switch (CallbackID) + { + case DAL_SMBUS_MSPINIT_CB_ID : + hsmbus->MspInitCallback = pCallback; + break; + + case DAL_SMBUS_MSPDEINIT_CB_ID : + hsmbus->MspDeInitCallback = pCallback; + break; + + default : + /* Update the error code */ + hsmbus->ErrorCode |= DAL_SMBUS_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = DAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + hsmbus->ErrorCode |= DAL_SMBUS_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = DAL_ERROR; + } + + /* Release Lock */ + __DAL_UNLOCK(hsmbus); + return status; +} + +/** + * @brief Unregister an SMBUS Callback + * SMBUS callback is redirected to the weak predefined callback + * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @param CallbackID ID of the callback to be unregistered + * This parameter can be one of the following values: + * This parameter can be one of the following values: + * @arg @ref DAL_SMBUS_MASTER_TX_COMPLETE_CB_ID Master Tx Transfer completed callback ID + * @arg @ref DAL_SMBUS_MASTER_RX_COMPLETE_CB_ID Master Rx Transfer completed callback ID + * @arg @ref DAL_SMBUS_SLAVE_TX_COMPLETE_CB_ID Slave Tx Transfer completed callback ID + * @arg @ref DAL_SMBUS_SLAVE_RX_COMPLETE_CB_ID Slave Rx Transfer completed callback ID + * @arg @ref DAL_SMBUS_LISTEN_COMPLETE_CB_ID Listen Complete callback ID + * @arg @ref DAL_SMBUS_ERROR_CB_ID Error callback ID + * @arg @ref DAL_SMBUS_ABORT_CB_ID Abort callback ID + * @arg @ref DAL_SMBUS_MSPINIT_CB_ID MspInit callback ID + * @arg @ref DAL_SMBUS_MSPDEINIT_CB_ID MspDeInit callback ID + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SMBUS_UnRegisterCallback(SMBUS_HandleTypeDef *hsmbus, DAL_SMBUS_CallbackIDTypeDef CallbackID) +{ + DAL_StatusTypeDef status = DAL_OK; + + /* Process locked */ + __DAL_LOCK(hsmbus); + + if (DAL_SMBUS_STATE_READY == hsmbus->State) + { + switch (CallbackID) + { + case DAL_SMBUS_MASTER_TX_COMPLETE_CB_ID : + hsmbus->MasterTxCpltCallback = DAL_SMBUS_MasterTxCpltCallback; /* Legacy weak MasterTxCpltCallback */ + break; + + case DAL_SMBUS_MASTER_RX_COMPLETE_CB_ID : + hsmbus->MasterRxCpltCallback = DAL_SMBUS_MasterRxCpltCallback; /* Legacy weak MasterRxCpltCallback */ + break; + + case DAL_SMBUS_SLAVE_TX_COMPLETE_CB_ID : + hsmbus->SlaveTxCpltCallback = DAL_SMBUS_SlaveTxCpltCallback; /* Legacy weak SlaveTxCpltCallback */ + break; + + case DAL_SMBUS_SLAVE_RX_COMPLETE_CB_ID : + hsmbus->SlaveRxCpltCallback = DAL_SMBUS_SlaveRxCpltCallback; /* Legacy weak SlaveRxCpltCallback */ + break; + + case DAL_SMBUS_LISTEN_COMPLETE_CB_ID : + hsmbus->ListenCpltCallback = DAL_SMBUS_ListenCpltCallback; /* Legacy weak ListenCpltCallback */ + break; + + case DAL_SMBUS_ERROR_CB_ID : + hsmbus->ErrorCallback = DAL_SMBUS_ErrorCallback; /* Legacy weak ErrorCallback */ + break; + + case DAL_SMBUS_ABORT_CB_ID : + hsmbus->AbortCpltCallback = DAL_SMBUS_AbortCpltCallback; /* Legacy weak AbortCpltCallback */ + break; + + case DAL_SMBUS_MSPINIT_CB_ID : + hsmbus->MspInitCallback = DAL_SMBUS_MspInit; /* Legacy weak MspInit */ + break; + + case DAL_SMBUS_MSPDEINIT_CB_ID : + hsmbus->MspDeInitCallback = DAL_SMBUS_MspDeInit; /* Legacy weak MspDeInit */ + break; + + default : + /* Update the error code */ + hsmbus->ErrorCode |= DAL_SMBUS_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = DAL_ERROR; + break; + } + } + else if (DAL_SMBUS_STATE_RESET == hsmbus->State) + { + switch (CallbackID) + { + case DAL_SMBUS_MSPINIT_CB_ID : + hsmbus->MspInitCallback = DAL_SMBUS_MspInit; /* Legacy weak MspInit */ + break; + + case DAL_SMBUS_MSPDEINIT_CB_ID : + hsmbus->MspDeInitCallback = DAL_SMBUS_MspDeInit; /* Legacy weak MspDeInit */ + break; + + default : + /* Update the error code */ + hsmbus->ErrorCode |= DAL_SMBUS_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = DAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + hsmbus->ErrorCode |= DAL_SMBUS_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = DAL_ERROR; + } + + /* Release Lock */ + __DAL_UNLOCK(hsmbus); + return status; +} + +/** + * @brief Register the Slave Address Match SMBUS Callback + * To be used instead of the weak DAL_SMBUS_AddrCallback() predefined callback + * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @param pCallback pointer to the Address Match Callback function + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SMBUS_RegisterAddrCallback(SMBUS_HandleTypeDef *hsmbus, pSMBUS_AddrCallbackTypeDef pCallback) +{ + DAL_StatusTypeDef status = DAL_OK; + + if (pCallback == NULL) + { + return DAL_ERROR; + } + /* Process locked */ + __DAL_LOCK(hsmbus); + + if (DAL_SMBUS_STATE_READY == hsmbus->State) + { + hsmbus->AddrCallback = pCallback; + } + else + { + /* Update the error code */ + hsmbus->ErrorCode |= DAL_SMBUS_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = DAL_ERROR; + } + + /* Release Lock */ + __DAL_UNLOCK(hsmbus); + return status; +} + +/** + * @brief UnRegister the Slave Address Match SMBUS Callback + * Info Ready SMBUS Callback is redirected to the weak DAL_SMBUS_AddrCallback() predefined callback + * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SMBUS_UnRegisterAddrCallback(SMBUS_HandleTypeDef *hsmbus) +{ + DAL_StatusTypeDef status = DAL_OK; + + /* Process locked */ + __DAL_LOCK(hsmbus); + + if (DAL_SMBUS_STATE_READY == hsmbus->State) + { + hsmbus->AddrCallback = DAL_SMBUS_AddrCallback; /* Legacy weak AddrCallback */ + } + else + { + /* Update the error code */ + hsmbus->ErrorCode |= DAL_SMBUS_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = DAL_ERROR; + } + + /* Release Lock */ + __DAL_UNLOCK(hsmbus); + return status; +} + +#endif /* USE_DAL_SMBUS_REGISTER_CALLBACKS */ + +/** + * @} + */ + +/** @defgroup SMBUS_Exported_Functions_Group2 Input and Output operation functions + * @brief Data transfers functions + * +@verbatim + =============================================================================== + ##### IO operation functions ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to manage the SMBUS data + transfers. + + (#) Blocking mode function to check if device is ready for usage is : + (++) DAL_SMBUS_IsDeviceReady() + + (#) There is only one mode of transfer: + (++) Non Blocking mode : The communication is performed using Interrupts. + These functions return the status of the transfer startup. + The end of the data processing will be indicated through the + dedicated SMBUS IRQ when using Interrupt mode. + + (#) Non Blocking mode functions with Interrupt are : + (++) DAL_SMBUS_Master_Transmit_IT() + (++) DAL_SMBUS_Master_Receive_IT() + (++) DAL_SMBUS_Master_Abort_IT() + (++) DAL_SMBUS_Slave_Transmit_IT() + (++) DAL_SMBUS_Slave_Receive_IT() + (++) DAL_SMBUS_EnableAlert_IT() + (++) DAL_SMBUS_DisableAlert_IT() + + (#) A set of Transfer Complete Callbacks are provided in No_Blocking mode: + (++) DAL_SMBUS_MasterTxCpltCallback() + (++) DAL_SMBUS_MasterRxCpltCallback() + (++) DAL_SMBUS_SlaveTxCpltCallback() + (++) DAL_SMBUS_SlaveRxCpltCallback() + (++) DAL_SMBUS_AddrCallback() + (++) DAL_SMBUS_ListenCpltCallback() + (++) DAL_SMBUS_ErrorCallback() + (++) DAL_SMBUS_AbortCpltCallback() + +@endverbatim + * @{ + */ + +/** + * @brief Transmits in master mode an amount of data in blocking mode. + * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @param DevAddress Target device address The device 7 bits address value + * in datasheet must be shifted to the left before calling the interface + * @param pData Pointer to data buffer + * @param Size Amount of data to be sent + * @param XferOptions Options of Transfer + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SMBUS_Master_Transmit_IT(SMBUS_HandleTypeDef *hsmbus, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t XferOptions) +{ + uint32_t count = 0x00U; + + /* Check the parameters */ + ASSERT_PARAM(IS_SMBUS_TRANSFER_OPTIONS_REQUEST(XferOptions)); + + if (hsmbus->State == DAL_SMBUS_STATE_READY) + { + /* Check Busy Flag only if FIRST call of Master interface */ + if ((XferOptions == SMBUS_FIRST_AND_LAST_FRAME_NO_PEC) || (XferOptions == SMBUS_FIRST_AND_LAST_FRAME_WITH_PEC) || (XferOptions == SMBUS_FIRST_FRAME)) + { + /* Wait until BUSY flag is reset */ + count = SMBUS_TIMEOUT_BUSY_FLAG * (SystemCoreClock / 25U / 1000U); + do + { + if (count-- == 0U) + { + hsmbus->PreviousState = SMBUS_STATE_NONE; + hsmbus->State = DAL_SMBUS_STATE_READY; + + /* Process Unlocked */ + __DAL_UNLOCK(hsmbus); + + return DAL_TIMEOUT; + } + } + while (__DAL_SMBUS_GET_FLAG(hsmbus, SMBUS_FLAG_BUSY) != RESET); + } + + /* Process Locked */ + __DAL_LOCK(hsmbus); + + /* Check if the SMBUS is already enabled */ + if ((hsmbus->Instance->CTRL1 & I2C_CTRL1_I2CEN) != I2C_CTRL1_I2CEN) + { + /* Enable SMBUS peripheral */ + __DAL_SMBUS_ENABLE(hsmbus); + } + + /* Disable Pos */ + CLEAR_BIT(hsmbus->Instance->CTRL1, I2C_CTRL1_ACKPOS); + + hsmbus->State = DAL_SMBUS_STATE_BUSY_TX; + hsmbus->ErrorCode = DAL_SMBUS_ERROR_NONE; + hsmbus->Mode = DAL_SMBUS_MODE_MASTER; + + /* Prepare transfer parameters */ + hsmbus->pBuffPtr = pData; + hsmbus->XferCount = Size; + hsmbus->XferOptions = XferOptions; + hsmbus->XferSize = hsmbus->XferCount; + hsmbus->Devaddress = DevAddress; + + /* Generate Start */ + SET_BIT(hsmbus->Instance->CTRL1, I2C_CTRL1_START); + + /* Process Unlocked */ + __DAL_UNLOCK(hsmbus); + + /* Note : The SMBUS interrupts must be enabled after unlocking current process + to avoid the risk of hsmbus interrupt handle execution before current + process unlock */ + + /* Enable EVT, BUF and ERR interrupt */ + __DAL_SMBUS_ENABLE_IT(hsmbus, SMBUS_IT_EVT | SMBUS_IT_BUF | SMBUS_IT_ERR); + + return DAL_OK; + } + else + { + return DAL_BUSY; + } +} +/** + * @brief Receive in master/host SMBUS mode an amount of data in non blocking mode with Interrupt. + * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @param DevAddress Target device address The device 7 bits address value + * in datasheet must be shifted to the left before calling the interface + * @param pData Pointer to data buffer + * @param Size Amount of data to be sent + * @param XferOptions Options of Transfer, value of @ref SMBUS_XferOptions_definition + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SMBUS_Master_Receive_IT(SMBUS_HandleTypeDef *hsmbus, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t XferOptions) +{ + __IO uint32_t count = 0U; + + /* Check the parameters */ + ASSERT_PARAM(IS_SMBUS_TRANSFER_OPTIONS_REQUEST(XferOptions)); + + if (hsmbus->State == DAL_SMBUS_STATE_READY) + { + /* Check Busy Flag only if FIRST call of Master interface */ + if ((XferOptions == SMBUS_FIRST_AND_LAST_FRAME_NO_PEC) || (XferOptions == SMBUS_FIRST_AND_LAST_FRAME_WITH_PEC) || (XferOptions == SMBUS_FIRST_FRAME)) + { + /* Wait until BUSY flag is reset */ + count = SMBUS_TIMEOUT_BUSY_FLAG * (SystemCoreClock / 25U / 1000U); + do + { + if (count-- == 0U) + { + hsmbus->PreviousState = SMBUS_STATE_NONE; + hsmbus->State = DAL_SMBUS_STATE_READY; + + /* Process Unlocked */ + __DAL_UNLOCK(hsmbus); + + return DAL_TIMEOUT; + } + } + while (__DAL_SMBUS_GET_FLAG(hsmbus, SMBUS_FLAG_BUSY) != RESET); + } + + /* Process Locked */ + __DAL_LOCK(hsmbus); + + /* Check if the SMBUS is already enabled */ + if ((hsmbus->Instance->CTRL1 & I2C_CTRL1_I2CEN) != I2C_CTRL1_I2CEN) + { + /* Enable SMBUS peripheral */ + __DAL_SMBUS_ENABLE(hsmbus); + } + + /* Disable Pos */ + CLEAR_BIT(hsmbus->Instance->CTRL1, I2C_CTRL1_ACKPOS); + + hsmbus->State = DAL_SMBUS_STATE_BUSY_RX; + hsmbus->ErrorCode = DAL_SMBUS_ERROR_NONE; + hsmbus->Mode = DAL_SMBUS_MODE_MASTER; + + /* Prepare transfer parameters */ + hsmbus->pBuffPtr = pData; + hsmbus->XferCount = Size; + hsmbus->XferOptions = XferOptions; + hsmbus->XferSize = hsmbus->XferCount; + hsmbus->Devaddress = DevAddress; + + if ((hsmbus->PreviousState == SMBUS_STATE_MASTER_BUSY_TX) || (hsmbus->PreviousState == SMBUS_STATE_NONE)) + { + /* Generate Start condition if first transfer */ + if ((XferOptions == SMBUS_NEXT_FRAME) || (XferOptions == SMBUS_FIRST_AND_LAST_FRAME_NO_PEC) || (XferOptions == SMBUS_FIRST_AND_LAST_FRAME_WITH_PEC) || (XferOptions == SMBUS_FIRST_FRAME) || (XferOptions == SMBUS_NO_OPTION_FRAME)) + { + /* Enable Acknowledge */ + SET_BIT(hsmbus->Instance->CTRL1, I2C_CTRL1_ACKEN); + + /* Generate Start */ + SET_BIT(hsmbus->Instance->CTRL1, I2C_CTRL1_START); + } + + if ((XferOptions == SMBUS_LAST_FRAME_NO_PEC) || (XferOptions == SMBUS_LAST_FRAME_WITH_PEC)) + { + if (hsmbus->PreviousState == SMBUS_STATE_NONE) + { + /* Enable Acknowledge */ + SET_BIT(hsmbus->Instance->CTRL1, I2C_CTRL1_ACKEN); + } + + if (hsmbus->PreviousState == SMBUS_STATE_MASTER_BUSY_TX) + { + /* Enable Acknowledge */ + SET_BIT(hsmbus->Instance->CTRL1, I2C_CTRL1_ACKEN); + + /* Generate Start */ + SET_BIT(hsmbus->Instance->CTRL1, I2C_CTRL1_START); + } + } + } + + + + /* Process Unlocked */ + __DAL_UNLOCK(hsmbus); + + /* Note : The SMBUS interrupts must be enabled after unlocking current process + to avoid the risk of SMBUS interrupt handle execution before current + process unlock */ + + /* Enable EVT, BUF and ERR interrupt */ + __DAL_SMBUS_ENABLE_IT(hsmbus, SMBUS_IT_EVT | SMBUS_IT_BUF | SMBUS_IT_ERR); + + return DAL_OK; + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief Abort a master/host SMBUS process communication with Interrupt. + * @note This abort can be called only if state is ready + * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @param DevAddress Target device address The device 7 bits address value + * in datasheet must be shifted to the left before calling the interface + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SMBUS_Master_Abort_IT(SMBUS_HandleTypeDef *hsmbus, uint16_t DevAddress) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(DevAddress); + if (hsmbus->Init.PeripheralMode == SMBUS_PERIPHERAL_MODE_SMBUS_HOST) + { + /* Process Locked */ + __DAL_LOCK(hsmbus); + + hsmbus->ErrorCode = DAL_SMBUS_ERROR_NONE; + + hsmbus->PreviousState = SMBUS_STATE_NONE; + hsmbus->State = DAL_SMBUS_STATE_ABORT; + + + /* Disable Acknowledge */ + CLEAR_BIT(hsmbus->Instance->CTRL1, I2C_CTRL1_ACKEN); + + /* Generate Stop */ + SET_BIT(hsmbus->Instance->CTRL1, I2C_CTRL1_STOP); + + hsmbus->XferCount = 0U; + + /* Disable EVT, BUF and ERR interrupt */ + __DAL_SMBUS_DISABLE_IT(hsmbus, SMBUS_IT_EVT | SMBUS_IT_BUF | SMBUS_IT_ERR); + + /* Process Unlocked */ + __DAL_UNLOCK(hsmbus); + + /* Call the corresponding callback to inform upper layer of End of Transfer */ + SMBUS_ITError(hsmbus); + + return DAL_OK; + } + else + { + return DAL_BUSY; + } +} + + +/** + * @brief Transmit in slave/device SMBUS mode an amount of data in non blocking mode with Interrupt. + * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @param pData Pointer to data buffer + * @param Size Amount of data to be sent + * @param XferOptions Options of Transfer, value of @ref SMBUS_XferOptions_definition + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SMBUS_Slave_Transmit_IT(SMBUS_HandleTypeDef *hsmbus, uint8_t *pData, uint16_t Size, uint32_t XferOptions) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_SMBUS_TRANSFER_OPTIONS_REQUEST(XferOptions)); + + if (hsmbus->State == DAL_SMBUS_STATE_LISTEN) + { + if ((pData == NULL) || (Size == 0U)) + { + return DAL_ERROR; + } + + /* Process Locked */ + __DAL_LOCK(hsmbus); + + /* Check if the SMBUS is already enabled */ + if ((hsmbus->Instance->CTRL1 & I2C_CTRL1_I2CEN) != I2C_CTRL1_I2CEN) + { + /* Enable SMBUS peripheral */ + __DAL_SMBUS_ENABLE(hsmbus); + } + + /* Disable Pos */ + CLEAR_BIT(hsmbus->Instance->CTRL1, I2C_CTRL1_ACKPOS); + + hsmbus->State = DAL_SMBUS_STATE_BUSY_TX_LISTEN; + hsmbus->ErrorCode = DAL_SMBUS_ERROR_NONE; + hsmbus->Mode = DAL_SMBUS_MODE_SLAVE; + + /* Prepare transfer parameters */ + hsmbus->pBuffPtr = pData; + hsmbus->XferCount = Size; + hsmbus->XferOptions = XferOptions; + hsmbus->XferSize = hsmbus->XferCount; + + /* Clear ADDR flag after prepare the transfer parameters */ + /* This action will generate an acknowledge to the HOST */ + __DAL_SMBUS_CLEAR_ADDRFLAG(hsmbus); + + /* Process Unlocked */ + __DAL_UNLOCK(hsmbus); + + /* Note : The SMBUS interrupts must be enabled after unlocking current process + to avoid the risk of SMBUS interrupt handle execution before current + process unlock */ + + /* Enable EVT, BUF and ERR interrupt */ + __DAL_SMBUS_ENABLE_IT(hsmbus, SMBUS_IT_EVT | SMBUS_IT_BUF | SMBUS_IT_ERR); + + return DAL_OK; + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief Enable the Address listen mode with Interrupt. + * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @param pData Pointer to data buffer + * @param Size Amount of data to be sent + * @param XferOptions Options of Transfer, value of @ref SMBUS_XferOptions_definition + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SMBUS_Slave_Receive_IT(SMBUS_HandleTypeDef *hsmbus, uint8_t *pData, uint16_t Size, uint32_t XferOptions) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_SMBUS_TRANSFER_OPTIONS_REQUEST(XferOptions)); + + if (hsmbus->State == DAL_SMBUS_STATE_LISTEN) + { + if ((pData == NULL) || (Size == 0U)) + { + return DAL_ERROR; + } + + /* Process Locked */ + __DAL_LOCK(hsmbus); + + /* Check if the SMBUS is already enabled */ + if ((hsmbus->Instance->CTRL1 & I2C_CTRL1_I2CEN) != I2C_CTRL1_I2CEN) + { + /* Enable SMBUS peripheral */ + __DAL_SMBUS_ENABLE(hsmbus); + } + + /* Disable Pos */ + CLEAR_BIT(hsmbus->Instance->CTRL1, I2C_CTRL1_ACKPOS); + + hsmbus->State = DAL_SMBUS_STATE_BUSY_RX_LISTEN; + hsmbus->ErrorCode = DAL_SMBUS_ERROR_NONE; + hsmbus->Mode = DAL_SMBUS_MODE_SLAVE; + + + + /* Prepare transfer parameters */ + hsmbus->pBuffPtr = pData; + hsmbus->XferCount = Size; + hsmbus->XferOptions = XferOptions; + hsmbus->XferSize = hsmbus->XferCount; + + __DAL_SMBUS_CLEAR_ADDRFLAG(hsmbus); + + /* Process Unlocked */ + __DAL_UNLOCK(hsmbus); + + /* Note : The SMBUS interrupts must be enabled after unlocking current process + to avoid the risk of SMBUS interrupt handle execution before current + process unlock */ + + /* Enable EVT, BUF and ERR interrupt */ + __DAL_SMBUS_ENABLE_IT(hsmbus, SMBUS_IT_EVT | SMBUS_IT_BUF | SMBUS_IT_ERR); + + return DAL_OK; + } + else + { + return DAL_BUSY; + } +} + + +/** + * @brief Enable the Address listen mode with Interrupt. + * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SMBUS_EnableListen_IT(SMBUS_HandleTypeDef *hsmbus) +{ + if (hsmbus->State == DAL_SMBUS_STATE_READY) + { + hsmbus->State = DAL_SMBUS_STATE_LISTEN; + + /* Check if the SMBUS is already enabled */ + if ((hsmbus->Instance->CTRL1 & I2C_CTRL1_I2CEN) != I2C_CTRL1_I2CEN) + { + /* Enable SMBUS peripheral */ + __DAL_SMBUS_ENABLE(hsmbus); + } + + /* Enable Address Acknowledge */ + SET_BIT(hsmbus->Instance->CTRL1, I2C_CTRL1_ACKEN); + + /* Enable EVT and ERR interrupt */ + __DAL_SMBUS_ENABLE_IT(hsmbus, SMBUS_IT_EVT | SMBUS_IT_ERR); + + return DAL_OK; + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief Disable the Address listen mode with Interrupt. + * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SMBUS_DisableListen_IT(SMBUS_HandleTypeDef *hsmbus) +{ + /* Declaration of tmp to prevent undefined behavior of volatile usage */ + uint32_t tmp; + + /* Disable Address listen mode only if a transfer is not ongoing */ + if (hsmbus->State == DAL_SMBUS_STATE_LISTEN) + { + tmp = (uint32_t)(hsmbus->State) & SMBUS_STATE_MSK; + hsmbus->PreviousState = tmp | (uint32_t)(hsmbus->Mode); + hsmbus->State = DAL_SMBUS_STATE_READY; + hsmbus->Mode = DAL_SMBUS_MODE_NONE; + + /* Disable Address Acknowledge */ + CLEAR_BIT(hsmbus->Instance->CTRL1, I2C_CTRL1_ACKEN); + + /* Disable EVT and ERR interrupt */ + __DAL_SMBUS_DISABLE_IT(hsmbus, SMBUS_IT_EVT | SMBUS_IT_ERR); + + return DAL_OK; + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief Enable the SMBUS alert mode with Interrupt. + * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUSx peripheral. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SMBUS_EnableAlert_IT(SMBUS_HandleTypeDef *hsmbus) +{ + /* Enable SMBus alert */ + SET_BIT(hsmbus->Instance->CTRL1, I2C_CTRL1_ALERTEN); + + /* Clear ALERT flag */ + __DAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_SMBALERT); + + /* Enable Alert Interrupt */ + __DAL_SMBUS_ENABLE_IT(hsmbus, SMBUS_IT_ERR); + + return DAL_OK; +} +/** + * @brief Disable the SMBUS alert mode with Interrupt. + * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUSx peripheral. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SMBUS_DisableAlert_IT(SMBUS_HandleTypeDef *hsmbus) +{ + /* Disable SMBus alert */ + CLEAR_BIT(hsmbus->Instance->CTRL1, I2C_CTRL1_ALERTEN); + + /* Disable Alert Interrupt */ + __DAL_SMBUS_DISABLE_IT(hsmbus, SMBUS_IT_ERR); + + return DAL_OK; +} + + +/** + * @brief Check if target device is ready for communication. + * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @param DevAddress Target device address The device 7 bits address value + * in datasheet must be shifted to the left before calling the interface + * @param Trials Number of trials + * @param Timeout Timeout duration + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SMBUS_IsDeviceReady(SMBUS_HandleTypeDef *hsmbus, uint16_t DevAddress, uint32_t Trials, uint32_t Timeout) +{ + uint32_t tickstart = 0U, tmp1 = 0U, tmp2 = 0U, tmp3 = 0U, SMBUS_Trials = 1U; + + /* Get tick */ + tickstart = DAL_GetTick(); + + if (hsmbus->State == DAL_SMBUS_STATE_READY) + { + /* Wait until BUSY flag is reset */ + if (SMBUS_WaitOnFlagUntilTimeout(hsmbus, SMBUS_FLAG_BUSY, SET, SMBUS_TIMEOUT_BUSY_FLAG, tickstart) != DAL_OK) + { + return DAL_BUSY; + } + + /* Process Locked */ + __DAL_LOCK(hsmbus); + + /* Check if the SMBUS is already enabled */ + if ((hsmbus->Instance->CTRL1 & I2C_CTRL1_I2CEN) != I2C_CTRL1_I2CEN) + { + /* Enable SMBUS peripheral */ + __DAL_SMBUS_ENABLE(hsmbus); + } + + /* Disable Pos */ + CLEAR_BIT(hsmbus->Instance->CTRL1, I2C_CTRL1_ACKPOS); + + hsmbus->State = DAL_SMBUS_STATE_BUSY; + hsmbus->ErrorCode = DAL_SMBUS_ERROR_NONE; + hsmbus->XferOptions = SMBUS_NO_OPTION_FRAME; + + do + { + /* Generate Start */ + SET_BIT(hsmbus->Instance->CTRL1, I2C_CTRL1_START); + + /* Wait until SB flag is set */ + if (SMBUS_WaitOnFlagUntilTimeout(hsmbus, SMBUS_FLAG_SB, RESET, Timeout, tickstart) != DAL_OK) + { + return DAL_TIMEOUT; + } + + /* Send slave address */ + hsmbus->Instance->DATA = SMBUS_7BIT_ADD_WRITE(DevAddress); + + /* Wait until ADDR or AF flag are set */ + /* Get tick */ + tickstart = DAL_GetTick(); + + tmp1 = __DAL_SMBUS_GET_FLAG(hsmbus, SMBUS_FLAG_ADDR); + tmp2 = __DAL_SMBUS_GET_FLAG(hsmbus, SMBUS_FLAG_AF); + tmp3 = hsmbus->State; + while ((tmp1 == RESET) && (tmp2 == RESET) && (tmp3 != DAL_SMBUS_STATE_TIMEOUT)) + { + if ((Timeout == 0U) || ((DAL_GetTick() - tickstart) > Timeout)) + { + hsmbus->State = DAL_SMBUS_STATE_TIMEOUT; + } + tmp1 = __DAL_SMBUS_GET_FLAG(hsmbus, SMBUS_FLAG_ADDR); + tmp2 = __DAL_SMBUS_GET_FLAG(hsmbus, SMBUS_FLAG_AF); + tmp3 = hsmbus->State; + } + + hsmbus->State = DAL_SMBUS_STATE_READY; + + /* Check if the ADDR flag has been set */ + if (__DAL_SMBUS_GET_FLAG(hsmbus, SMBUS_FLAG_ADDR) == SET) + { + /* Generate Stop */ + SET_BIT(hsmbus->Instance->CTRL1, I2C_CTRL1_STOP); + + /* Clear ADDR Flag */ + __DAL_SMBUS_CLEAR_ADDRFLAG(hsmbus); + + /* Wait until BUSY flag is reset */ + if (SMBUS_WaitOnFlagUntilTimeout(hsmbus, SMBUS_FLAG_BUSY, SET, SMBUS_TIMEOUT_BUSY_FLAG, tickstart) != DAL_OK) + { + return DAL_TIMEOUT; + } + + hsmbus->State = DAL_SMBUS_STATE_READY; + + /* Process Unlocked */ + __DAL_UNLOCK(hsmbus); + + return DAL_OK; + } + else + { + /* Generate Stop */ + SET_BIT(hsmbus->Instance->CTRL1, I2C_CTRL1_STOP); + + /* Clear AF Flag */ + __DAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_AF); + + /* Wait until BUSY flag is reset */ + if (SMBUS_WaitOnFlagUntilTimeout(hsmbus, SMBUS_FLAG_BUSY, SET, SMBUS_TIMEOUT_BUSY_FLAG, tickstart) != DAL_OK) + { + return DAL_TIMEOUT; + } + } + } + while (SMBUS_Trials++ < Trials); + + hsmbus->State = DAL_SMBUS_STATE_READY; + + /* Process Unlocked */ + __DAL_UNLOCK(hsmbus); + + return DAL_ERROR; + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief This function handles SMBUS event interrupt request. + * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @retval None + */ +void DAL_SMBUS_EV_IRQHandler(SMBUS_HandleTypeDef *hsmbus) +{ + uint32_t sr2itflags = READ_REG(hsmbus->Instance->STS2); + uint32_t sr1itflags = READ_REG(hsmbus->Instance->STS1); + uint32_t itsources = READ_REG(hsmbus->Instance->CTRL2); + + uint32_t CurrentMode = hsmbus->Mode; + + /* Master mode selected */ + if (CurrentMode == DAL_SMBUS_MODE_MASTER) + { + /* SB Set ----------------------------------------------------------------*/ + if (((sr1itflags & SMBUS_FLAG_SB) != RESET) && ((itsources & SMBUS_IT_EVT) != RESET)) + { + SMBUS_Master_SB(hsmbus); + } + /* ADD10 Set -------------------------------------------------------------*/ + else if (((sr1itflags & SMBUS_FLAG_ADD10) != RESET) && ((itsources & SMBUS_IT_EVT) != RESET)) + { + SMBUS_Master_ADD10(hsmbus); + } + /* ADDR Set --------------------------------------------------------------*/ + else if (((sr1itflags & SMBUS_FLAG_ADDR) != RESET) && ((itsources & SMBUS_IT_EVT) != RESET)) + { + SMBUS_Master_ADDR(hsmbus); + } + /* SMBUS in mode Transmitter -----------------------------------------------*/ + if ((sr2itflags & SMBUS_FLAG_TRA) != RESET) + { + /* TXE set and BTF reset -----------------------------------------------*/ + if (((sr1itflags & SMBUS_FLAG_TXE) != RESET) && ((itsources & SMBUS_IT_BUF) != RESET) && ((sr1itflags & SMBUS_FLAG_BTF) == RESET)) + { + SMBUS_MasterTransmit_TXE(hsmbus); + } + /* BTF set -------------------------------------------------------------*/ + else if (((sr1itflags & SMBUS_FLAG_BTF) != RESET) && ((itsources & SMBUS_IT_EVT) != RESET)) + { + SMBUS_MasterTransmit_BTF(hsmbus); + } + } + /* SMBUS in mode Receiver --------------------------------------------------*/ + else + { + /* RXNE set and BTF reset -----------------------------------------------*/ + if (((sr1itflags & SMBUS_FLAG_RXNE) != RESET) && ((itsources & SMBUS_IT_BUF) != RESET) && ((sr1itflags & SMBUS_FLAG_BTF) == RESET)) + { + SMBUS_MasterReceive_RXNE(hsmbus); + } + /* BTF set -------------------------------------------------------------*/ + else if (((sr1itflags & SMBUS_FLAG_BTF) != RESET) && ((itsources & SMBUS_IT_EVT) != RESET)) + { + SMBUS_MasterReceive_BTF(hsmbus); + } + } + } + /* Slave mode selected */ + else + { + /* ADDR set --------------------------------------------------------------*/ + if (((sr1itflags & SMBUS_FLAG_ADDR) != RESET) && ((itsources & SMBUS_IT_EVT) != RESET)) + { + SMBUS_Slave_ADDR(hsmbus); + } + /* STOPF set --------------------------------------------------------------*/ + else if (((sr1itflags & SMBUS_FLAG_STOPF) != RESET) && ((itsources & SMBUS_IT_EVT) != RESET)) + { + SMBUS_Slave_STOPF(hsmbus); + } + /* SMBUS in mode Transmitter -----------------------------------------------*/ + else if ((sr2itflags & SMBUS_FLAG_TRA) != RESET) + { + /* TXE set and BTF reset -----------------------------------------------*/ + if (((sr1itflags & SMBUS_FLAG_TXE) != RESET) && ((itsources & SMBUS_IT_BUF) != RESET) && ((sr1itflags & SMBUS_FLAG_BTF) == RESET)) + { + SMBUS_SlaveTransmit_TXE(hsmbus); + } + /* BTF set -------------------------------------------------------------*/ + else if (((sr1itflags & SMBUS_FLAG_BTF) != RESET) && ((itsources & SMBUS_IT_EVT) != RESET)) + { + SMBUS_SlaveTransmit_BTF(hsmbus); + } + } + /* SMBUS in mode Receiver --------------------------------------------------*/ + else + { + /* RXNE set and BTF reset ----------------------------------------------*/ + if (((sr1itflags & SMBUS_FLAG_RXNE) != RESET) && ((itsources & SMBUS_IT_BUF) != RESET) && ((sr1itflags & SMBUS_FLAG_BTF) == RESET)) + { + SMBUS_SlaveReceive_RXNE(hsmbus); + } + /* BTF set -------------------------------------------------------------*/ + else if (((sr1itflags & SMBUS_FLAG_BTF) != RESET) && ((itsources & SMBUS_IT_EVT) != RESET)) + { + SMBUS_SlaveReceive_BTF(hsmbus); + } + } + } +} + +/** + * @brief This function handles SMBUS error interrupt request. + * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @retval None + */ +void DAL_SMBUS_ER_IRQHandler(SMBUS_HandleTypeDef *hsmbus) +{ + uint32_t tmp1 = 0U, tmp2 = 0U, tmp3 = 0U, tmp4 = 0U; + uint32_t sr1itflags = READ_REG(hsmbus->Instance->STS1); + uint32_t itsources = READ_REG(hsmbus->Instance->CTRL2); + + /* SMBUS Bus error interrupt occurred ------------------------------------*/ + if (((sr1itflags & SMBUS_FLAG_BERR) != RESET) && ((itsources & SMBUS_IT_ERR) != RESET)) + { + hsmbus->ErrorCode |= DAL_SMBUS_ERROR_BERR; + + /* Clear BERR flag */ + __DAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_BERR); + + } + + /* SMBUS Over-Run/Under-Run interrupt occurred ----------------------------------------*/ + if (((sr1itflags & SMBUS_FLAG_OVR) != RESET) && ((itsources & SMBUS_IT_ERR) != RESET)) + { + hsmbus->ErrorCode |= DAL_SMBUS_ERROR_OVR; + + /* Clear OVR flag */ + __DAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_OVR); + } + + /* SMBUS Arbitration Loss error interrupt occurred ------------------------------------*/ + if (((sr1itflags & SMBUS_FLAG_ARLO) != RESET) && ((itsources & SMBUS_IT_ERR) != RESET)) + { + hsmbus->ErrorCode |= DAL_SMBUS_ERROR_ARLO; + + /* Clear ARLO flag */ + __DAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_ARLO); + } + + /* SMBUS Acknowledge failure error interrupt occurred ------------------------------------*/ + if (((sr1itflags & SMBUS_FLAG_AF) != RESET) && ((itsources & SMBUS_IT_ERR) != RESET)) + { + tmp1 = hsmbus->Mode; + tmp2 = hsmbus->XferCount; + tmp3 = hsmbus->State; + tmp4 = hsmbus->PreviousState; + + if ((tmp1 == DAL_SMBUS_MODE_SLAVE) && (tmp2 == 0U) && \ + ((tmp3 == DAL_SMBUS_STATE_BUSY_TX) || (tmp3 == DAL_SMBUS_STATE_BUSY_TX_LISTEN) || \ + ((tmp3 == DAL_SMBUS_STATE_LISTEN) && (tmp4 == SMBUS_STATE_SLAVE_BUSY_TX)))) + { + SMBUS_Slave_AF(hsmbus); + } + else + { + hsmbus->ErrorCode |= DAL_SMBUS_ERROR_AF; + + /* Do not generate a STOP in case of Slave receive non acknowledge during transfer (mean not at the end of transfer) */ + if (hsmbus->Mode == DAL_SMBUS_MODE_MASTER) + { + /* Generate Stop */ + SET_BIT(hsmbus->Instance->CTRL1, I2C_CTRL1_STOP); + + } + + /* Clear AF flag */ + __DAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_AF); + } + } + + /* SMBUS Timeout error interrupt occurred ---------------------------------------------*/ + if (((sr1itflags & SMBUS_FLAG_TIMEOUT) != RESET) && ((itsources & SMBUS_IT_ERR) != RESET)) + { + hsmbus->ErrorCode |= DAL_SMBUS_ERROR_TIMEOUT; + + /* Clear TIMEOUT flag */ + __DAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_TIMEOUT); + + } + + /* SMBUS Alert error interrupt occurred -----------------------------------------------*/ + if (((sr1itflags & SMBUS_FLAG_SMBALERT) != RESET) && ((itsources & SMBUS_IT_ERR) != RESET)) + { + hsmbus->ErrorCode |= DAL_SMBUS_ERROR_ALERT; + + /* Clear ALERT flag */ + __DAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_SMBALERT); + } + + /* SMBUS Packet Error Check error interrupt occurred ----------------------------------*/ + if (((sr1itflags & SMBUS_FLAG_PECERR) != RESET) && ((itsources & SMBUS_IT_ERR) != RESET)) + { + hsmbus->ErrorCode |= DAL_SMBUS_ERROR_PECERR; + + /* Clear PEC error flag */ + __DAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_PECERR); + } + + /* Call the Error Callback in case of Error detected -----------------------*/ + if (hsmbus->ErrorCode != DAL_SMBUS_ERROR_NONE) + { + SMBUS_ITError(hsmbus); + } +} + +/** + * @brief Master Tx Transfer completed callback. + * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @retval None + */ +__weak void DAL_SMBUS_MasterTxCpltCallback(SMBUS_HandleTypeDef *hsmbus) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hsmbus); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_SMBUS_MasterTxCpltCallback can be implemented in the user file + */ +} + +/** + * @brief Master Rx Transfer completed callback. + * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @retval None + */ +__weak void DAL_SMBUS_MasterRxCpltCallback(SMBUS_HandleTypeDef *hsmbus) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hsmbus); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_SMBUS_MasterRxCpltCallback can be implemented in the user file + */ +} + +/** @brief Slave Tx Transfer completed callback. + * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @retval None + */ +__weak void DAL_SMBUS_SlaveTxCpltCallback(SMBUS_HandleTypeDef *hsmbus) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hsmbus); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_SMBUS_SlaveTxCpltCallback can be implemented in the user file + */ +} + +/** + * @brief Slave Rx Transfer completed callback. + * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @retval None + */ +__weak void DAL_SMBUS_SlaveRxCpltCallback(SMBUS_HandleTypeDef *hsmbus) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hsmbus); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_SMBUS_SlaveRxCpltCallback can be implemented in the user file + */ +} + +/** + * @brief Slave Address Match callback. + * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @param TransferDirection Master request Transfer Direction (Write/Read), value of @ref SMBUS_XferOptions_definition + * @param AddrMatchCode Address Match Code + * @retval None + */ +__weak void DAL_SMBUS_AddrCallback(SMBUS_HandleTypeDef *hsmbus, uint8_t TransferDirection, uint16_t AddrMatchCode) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hsmbus); + UNUSED(TransferDirection); + UNUSED(AddrMatchCode); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_SMBUS_AddrCallback can be implemented in the user file + */ +} + +/** + * @brief Listen Complete callback. + * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @retval None + */ +__weak void DAL_SMBUS_ListenCpltCallback(SMBUS_HandleTypeDef *hsmbus) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hsmbus); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_SMBUS_ListenCpltCallback can be implemented in the user file + */ +} + +/** + * @brief SMBUS error callback. + * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @retval None + */ +__weak void DAL_SMBUS_ErrorCallback(SMBUS_HandleTypeDef *hsmbus) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hsmbus); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_SMBUS_ErrorCallback can be implemented in the user file + */ +} + +/** + * @brief SMBUS abort callback. + * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @retval None + */ +__weak void DAL_SMBUS_AbortCpltCallback(SMBUS_HandleTypeDef *hsmbus) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hsmbus); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_SMBUS_AbortCpltCallback could be implemented in the user file + */ +} + +/** + * @} + */ + +/** @defgroup SMBUS_Exported_Functions_Group3 Peripheral State, Mode and Error functions + * @brief Peripheral State and Errors functions + * +@verbatim + =============================================================================== + ##### Peripheral State, Mode and Error functions ##### + =============================================================================== + [..] + This subsection permits to get in run-time the status of the peripheral + and the data flow. + +@endverbatim + * @{ + */ + +/** + * @brief Return the SMBUS handle state. + * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @retval DAL state + */ +DAL_SMBUS_StateTypeDef DAL_SMBUS_GetState(SMBUS_HandleTypeDef *hsmbus) +{ + /* Return SMBUS handle state */ + return hsmbus->State; +} + +/** + * @brief Return the SMBUS Master, Slave or no mode. + * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for SMBUS module + * @retval DAL mode + */ +DAL_SMBUS_ModeTypeDef DAL_SMBUS_GetMode(SMBUS_HandleTypeDef *hsmbus) +{ + return hsmbus->Mode; +} + +/** + * @brief Return the SMBUS error code + * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @retval SMBUS Error Code + */ +uint32_t DAL_SMBUS_GetError(SMBUS_HandleTypeDef *hsmbus) +{ + return hsmbus->ErrorCode; +} + +/** + * @} + */ + +/** + * @} + */ + +/** @addtogroup SMBUS_Private_Functions + * @{ + */ + +/** + * @brief Handle TXE flag for Master + * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for SMBUS module + * @retval DAL status + */ +static DAL_StatusTypeDef SMBUS_MasterTransmit_TXE(SMBUS_HandleTypeDef *hsmbus) +{ + /* Declaration of temporary variables to prevent undefined behavior of volatile usage */ + uint32_t CurrentState = hsmbus->State; + uint32_t CurrentXferOptions = hsmbus->XferOptions; + + if ((hsmbus->XferSize == 0U) && (CurrentState == DAL_SMBUS_STATE_BUSY_TX)) + { + /* Call TxCpltCallback() directly if no stop mode is set */ + if (((CurrentXferOptions == SMBUS_FIRST_FRAME) || (CurrentXferOptions == SMBUS_NEXT_FRAME)) && (CurrentXferOptions != SMBUS_NO_OPTION_FRAME)) + { + __DAL_SMBUS_DISABLE_IT(hsmbus, SMBUS_IT_EVT | SMBUS_IT_BUF | SMBUS_IT_ERR); + + hsmbus->PreviousState = SMBUS_STATE_MASTER_BUSY_TX; + hsmbus->Mode = DAL_SMBUS_MODE_NONE; + hsmbus->State = DAL_SMBUS_STATE_READY; + +#if (USE_DAL_SMBUS_REGISTER_CALLBACKS == 1) + hsmbus->MasterTxCpltCallback(hsmbus); +#else + DAL_SMBUS_MasterTxCpltCallback(hsmbus); +#endif /* USE_DAL_SMBUS_REGISTER_CALLBACKS */ + } + else /* Generate Stop condition then Call TxCpltCallback() */ + { + /* Disable EVT, BUF and ERR interrupt */ + __DAL_SMBUS_DISABLE_IT(hsmbus, SMBUS_IT_EVT | SMBUS_IT_BUF | SMBUS_IT_ERR); + + /* Generate Stop */ + SET_BIT(hsmbus->Instance->CTRL1, I2C_CTRL1_STOP); + + hsmbus->PreviousState = DAL_SMBUS_STATE_READY; + hsmbus->State = DAL_SMBUS_STATE_READY; + + hsmbus->Mode = DAL_SMBUS_MODE_NONE; +#if (USE_DAL_SMBUS_REGISTER_CALLBACKS == 1) + hsmbus->MasterTxCpltCallback(hsmbus); +#else + DAL_SMBUS_MasterTxCpltCallback(hsmbus); +#endif /* USE_DAL_SMBUS_REGISTER_CALLBACKS */ + } + } + else if (CurrentState == DAL_SMBUS_STATE_BUSY_TX) + { + + if ((hsmbus->XferCount == 2U) && (SMBUS_GET_PEC_MODE(hsmbus) == SMBUS_PEC_ENABLE) && ((hsmbus->XferOptions == SMBUS_FIRST_AND_LAST_FRAME_WITH_PEC) || (hsmbus->XferOptions == SMBUS_LAST_FRAME_WITH_PEC))) + { + hsmbus->XferCount--; + } + + if (hsmbus->XferCount == 0U) + { + + /* Disable BUF interrupt */ + __DAL_SMBUS_DISABLE_IT(hsmbus, SMBUS_IT_BUF); + + if ((SMBUS_GET_PEC_MODE(hsmbus) == SMBUS_PEC_ENABLE) && ((hsmbus->XferOptions == SMBUS_FIRST_AND_LAST_FRAME_WITH_PEC) || (hsmbus->XferOptions == SMBUS_LAST_FRAME_WITH_PEC))) + { + SET_BIT(hsmbus->Instance->CTRL1, I2C_CTRL1_PEC); + } + + } + else + { + /* Write data to DATA */ + hsmbus->Instance->DATA = (*hsmbus->pBuffPtr++); + hsmbus->XferCount--; + } + } + return DAL_OK; +} + +/** + * @brief Handle BTF flag for Master transmitter + * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for SMBUS module + * @retval DAL status + */ +static DAL_StatusTypeDef SMBUS_MasterTransmit_BTF(SMBUS_HandleTypeDef *hsmbus) +{ + /* Declaration of temporary variables to prevent undefined behavior of volatile usage */ + uint32_t CurrentXferOptions = hsmbus->XferOptions; + + if (hsmbus->State == DAL_SMBUS_STATE_BUSY_TX) + { + if (hsmbus->XferCount != 0U) + { + /* Write data to DATA */ + hsmbus->Instance->DATA = (*hsmbus->pBuffPtr++); + hsmbus->XferCount--; + } + else + { + /* Call TxCpltCallback() directly if no stop mode is set */ + if (((CurrentXferOptions == SMBUS_FIRST_FRAME) || (CurrentXferOptions == SMBUS_NEXT_FRAME)) && (CurrentXferOptions != SMBUS_NO_OPTION_FRAME)) + { + __DAL_SMBUS_DISABLE_IT(hsmbus, SMBUS_IT_EVT | SMBUS_IT_BUF | SMBUS_IT_ERR); + + hsmbus->PreviousState = SMBUS_STATE_MASTER_BUSY_TX; + hsmbus->Mode = DAL_SMBUS_MODE_NONE; + hsmbus->State = DAL_SMBUS_STATE_READY; + +#if (USE_DAL_SMBUS_REGISTER_CALLBACKS == 1) + hsmbus->MasterTxCpltCallback(hsmbus); +#else + DAL_SMBUS_MasterTxCpltCallback(hsmbus); +#endif /* USE_DAL_SMBUS_REGISTER_CALLBACKS */ + } + else /* Generate Stop condition then Call TxCpltCallback() */ + { + /* Disable EVT, BUF and ERR interrupt */ + __DAL_SMBUS_DISABLE_IT(hsmbus, SMBUS_IT_EVT | SMBUS_IT_BUF | SMBUS_IT_ERR); + + /* Generate Stop */ + SET_BIT(hsmbus->Instance->CTRL1, I2C_CTRL1_STOP); + + hsmbus->PreviousState = DAL_SMBUS_STATE_READY; + hsmbus->State = DAL_SMBUS_STATE_READY; + hsmbus->Mode = DAL_SMBUS_MODE_NONE; +#if (USE_DAL_SMBUS_REGISTER_CALLBACKS == 1) + hsmbus->MasterTxCpltCallback(hsmbus); +#else + DAL_SMBUS_MasterTxCpltCallback(hsmbus); +#endif /* USE_DAL_SMBUS_REGISTER_CALLBACKS */ + } + } + } + return DAL_OK; +} + +/** + * @brief Handle RXNE flag for Master + * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for SMBUS module + * @retval DAL status + */ +static DAL_StatusTypeDef SMBUS_MasterReceive_RXNE(SMBUS_HandleTypeDef *hsmbus) +{ + /* Declaration of temporary variables to prevent undefined behavior of volatile usage */ + uint32_t CurrentXferOptions = hsmbus->XferOptions; + + if (hsmbus->State == DAL_SMBUS_STATE_BUSY_RX) + { + uint32_t tmp = hsmbus->XferCount; + + if (tmp > 3U) + { + /* Read data from DATA */ + (*hsmbus->pBuffPtr++) = hsmbus->Instance->DATA; + hsmbus->XferCount--; + + if (hsmbus->XferCount == 3) + { + /* Disable BUF interrupt, this help to treat correctly the last 4 bytes + on BTF subroutine */ + /* Disable BUF interrupt */ + __DAL_SMBUS_DISABLE_IT(hsmbus, SMBUS_IT_BUF); + } + } + + else if (tmp == 2U) + { + + /* Read data from DATA */ + (*hsmbus->pBuffPtr++) = hsmbus->Instance->DATA; + hsmbus->XferCount--; + + if ((CurrentXferOptions == SMBUS_FIRST_AND_LAST_FRAME_WITH_PEC) || (CurrentXferOptions == SMBUS_LAST_FRAME_WITH_PEC)) + { + /* PEC of slave */ + hsmbus->XferPEC = SMBUS_GET_PEC(hsmbus); + + } + /* Generate Stop */ + SET_BIT(hsmbus->Instance->CTRL1, I2C_CTRL1_STOP); + } + + else if ((tmp == 1U) || (tmp == 0U)) + { + /* Disable Acknowledge */ + CLEAR_BIT(hsmbus->Instance->CTRL1, I2C_CTRL1_ACKEN); + + /* Disable EVT, BUF and ERR interrupt */ + __DAL_SMBUS_DISABLE_IT(hsmbus, SMBUS_IT_EVT | SMBUS_IT_BUF | SMBUS_IT_ERR); + + /* Read data from DATA */ + (*hsmbus->pBuffPtr++) = hsmbus->Instance->DATA; + hsmbus->XferCount--; + + hsmbus->State = DAL_SMBUS_STATE_READY; + hsmbus->PreviousState = SMBUS_STATE_NONE; + hsmbus->Mode = DAL_SMBUS_MODE_NONE; + +#if (USE_DAL_SMBUS_REGISTER_CALLBACKS == 1) + hsmbus->MasterRxCpltCallback(hsmbus); +#else + DAL_SMBUS_MasterRxCpltCallback(hsmbus); +#endif /* USE_DAL_SMBUS_REGISTER_CALLBACKS */ + } + } + + return DAL_OK; +} + +/** + * @brief Handle BTF flag for Master receiver + * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for SMBUS module + * @retval DAL status + */ +static DAL_StatusTypeDef SMBUS_MasterReceive_BTF(SMBUS_HandleTypeDef *hsmbus) +{ + /* Declaration of temporary variables to prevent undefined behavior of volatile usage */ + uint32_t CurrentXferOptions = hsmbus->XferOptions; + + if (hsmbus->XferCount == 4U) + { + /* Disable BUF interrupt, this help to treat correctly the last 2 bytes + on BTF subroutine if there is a reception delay between N-1 and N byte */ + __DAL_SMBUS_DISABLE_IT(hsmbus, SMBUS_IT_BUF); + + /* Read data from DATA */ + (*hsmbus->pBuffPtr++) = hsmbus->Instance->DATA; + hsmbus->XferCount--; + hsmbus->XferPEC = SMBUS_GET_PEC(hsmbus); + } + else if (hsmbus->XferCount == 3U) + { + /* Disable BUF interrupt, this help to treat correctly the last 2 bytes + on BTF subroutine if there is a reception delay between N-1 and N byte */ + __DAL_SMBUS_DISABLE_IT(hsmbus, SMBUS_IT_BUF); + + /* Disable Acknowledge */ + CLEAR_BIT(hsmbus->Instance->CTRL1, I2C_CTRL1_ACKEN); + + /* Read data from DATA */ + (*hsmbus->pBuffPtr++) = hsmbus->Instance->DATA; + hsmbus->XferCount--; + hsmbus->XferPEC = SMBUS_GET_PEC(hsmbus); + } + else if (hsmbus->XferCount == 2U) + { + /* Prepare next transfer or stop current transfer */ + if ((CurrentXferOptions == SMBUS_NEXT_FRAME) || (CurrentXferOptions == SMBUS_FIRST_FRAME)) + { + /* Disable Acknowledge */ + CLEAR_BIT(hsmbus->Instance->CTRL1, I2C_CTRL1_ACKEN); + + /* Generate ReStart */ + SET_BIT(hsmbus->Instance->CTRL1, I2C_CTRL1_START); + } + else + { + /* Generate Stop */ + SET_BIT(hsmbus->Instance->CTRL1, I2C_CTRL1_STOP); + } + + /* Read data from DATA */ + (*hsmbus->pBuffPtr++) = hsmbus->Instance->DATA; + hsmbus->XferCount--; + + /* Read data from DATA */ + (*hsmbus->pBuffPtr++) = hsmbus->Instance->DATA; + hsmbus->XferCount--; + + /* Disable EVT and ERR interrupt */ + __DAL_SMBUS_DISABLE_IT(hsmbus, SMBUS_IT_EVT | SMBUS_IT_ERR); + + hsmbus->State = DAL_SMBUS_STATE_READY; + hsmbus->PreviousState = SMBUS_STATE_NONE; + hsmbus->Mode = DAL_SMBUS_MODE_NONE; +#if (USE_DAL_SMBUS_REGISTER_CALLBACKS == 1) + hsmbus->MasterRxCpltCallback(hsmbus); +#else + DAL_SMBUS_MasterRxCpltCallback(hsmbus); +#endif /* USE_DAL_SMBUS_REGISTER_CALLBACKS */ + } + else + { + /* Read data from DATA */ + (*hsmbus->pBuffPtr++) = hsmbus->Instance->DATA; + hsmbus->XferCount--; + } + return DAL_OK; +} + +/** + * @brief Handle SB flag for Master + * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for SMBUS module + * @retval DAL status + */ +static DAL_StatusTypeDef SMBUS_Master_SB(SMBUS_HandleTypeDef *hsmbus) +{ + if (hsmbus->Init.AddressingMode == SMBUS_ADDRESSINGMODE_7BIT) + { + /* Send slave 7 Bits address */ + if (hsmbus->State == DAL_SMBUS_STATE_BUSY_TX) + { + hsmbus->Instance->DATA = SMBUS_7BIT_ADD_WRITE(hsmbus->Devaddress); + } + else + { + hsmbus->Instance->DATA = SMBUS_7BIT_ADD_READ(hsmbus->Devaddress); + } + } + else + { + if (hsmbus->EventCount == 0U) + { + /* Send header of slave address */ + hsmbus->Instance->DATA = SMBUS_10BIT_HEADER_WRITE(hsmbus->Devaddress); + } + else if (hsmbus->EventCount == 1U) + { + /* Send header of slave address */ + hsmbus->Instance->DATA = SMBUS_10BIT_HEADER_READ(hsmbus->Devaddress); + } + } + return DAL_OK; +} + +/** + * @brief Handle ADD10 flag for Master + * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for SMBUS module + * @retval DAL status + */ +static DAL_StatusTypeDef SMBUS_Master_ADD10(SMBUS_HandleTypeDef *hsmbus) +{ + /* Send slave address */ + hsmbus->Instance->DATA = SMBUS_10BIT_ADDRESS(hsmbus->Devaddress); + + return DAL_OK; +} + +/** + * @brief Handle ADDR flag for Master + * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for SMBUS module + * @retval DAL status + */ +static DAL_StatusTypeDef SMBUS_Master_ADDR(SMBUS_HandleTypeDef *hsmbus) +{ + /* Declaration of temporary variable to prevent undefined behavior of volatile usage */ + uint32_t Prev_State = hsmbus->PreviousState; + + if (hsmbus->State == DAL_SMBUS_STATE_BUSY_RX) + { + if ((hsmbus->EventCount == 0U) && (hsmbus->Init.AddressingMode == SMBUS_ADDRESSINGMODE_10BIT)) + { + /* Clear ADDR flag */ + __DAL_SMBUS_CLEAR_ADDRFLAG(hsmbus); + + /* Generate Restart */ + SET_BIT(hsmbus->Instance->CTRL1, I2C_CTRL1_START); + + hsmbus->EventCount++; + } + else + { + /* In the case of the Quick Command, the ADDR flag is cleared and a stop is generated */ + if (hsmbus->XferCount == 0U) + { + /* Clear ADDR flag */ + __DAL_SMBUS_CLEAR_ADDRFLAG(hsmbus); + + /* Generate Stop */ + SET_BIT(hsmbus->Instance->CTRL1, I2C_CTRL1_STOP); + } + else if (hsmbus->XferCount == 1U) + { + /* Prepare next transfer or stop current transfer */ + if ((hsmbus->XferOptions == SMBUS_FIRST_FRAME) && (Prev_State != SMBUS_STATE_MASTER_BUSY_RX)) + { + /* Disable Acknowledge */ + CLEAR_BIT(hsmbus->Instance->CTRL1, I2C_CTRL1_ACKEN); + + /* Clear ADDR flag */ + __DAL_SMBUS_CLEAR_ADDRFLAG(hsmbus); + } + else if ((hsmbus->XferOptions == SMBUS_NEXT_FRAME) && (Prev_State != SMBUS_STATE_MASTER_BUSY_RX)) + { + /* Enable Acknowledge */ + SET_BIT(hsmbus->Instance->CTRL1, I2C_CTRL1_ACKEN); + + /* Clear ADDR flag */ + __DAL_SMBUS_CLEAR_ADDRFLAG(hsmbus); + } + else + { + /* Disable Acknowledge */ + CLEAR_BIT(hsmbus->Instance->CTRL1, I2C_CTRL1_ACKEN); + + /* Clear ADDR flag */ + __DAL_SMBUS_CLEAR_ADDRFLAG(hsmbus); + + /* Generate Stop */ + SET_BIT(hsmbus->Instance->CTRL1, I2C_CTRL1_STOP); + } + } + else if (hsmbus->XferCount == 2U) + { + if (hsmbus->XferOptions != SMBUS_NEXT_FRAME) + { + /* Disable Acknowledge */ + CLEAR_BIT(hsmbus->Instance->CTRL1, I2C_CTRL1_ACKEN); + + /* Enable Pos */ + SET_BIT(hsmbus->Instance->CTRL1, I2C_CTRL1_ACKPOS); + + + } + else + { + /* Enable Acknowledge */ + SET_BIT(hsmbus->Instance->CTRL1, I2C_CTRL1_ACKEN); + } + + /* Clear ADDR flag */ + __DAL_SMBUS_CLEAR_ADDRFLAG(hsmbus); + } + else + { + /* Enable Acknowledge */ + SET_BIT(hsmbus->Instance->CTRL1, I2C_CTRL1_ACKEN); + + /* Clear ADDR flag */ + __DAL_SMBUS_CLEAR_ADDRFLAG(hsmbus); + } + + /* Reset Event counter */ + hsmbus->EventCount = 0U; + } + } + else + { + /* Clear ADDR flag */ + __DAL_SMBUS_CLEAR_ADDRFLAG(hsmbus); + } + + return DAL_OK; +} + +/** + * @brief Handle TXE flag for Slave + * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for SMBUS module + * @retval DAL status + */ +static DAL_StatusTypeDef SMBUS_SlaveTransmit_TXE(SMBUS_HandleTypeDef *hsmbus) +{ + /* Declaration of temporary variables to prevent undefined behavior of volatile usage */ + uint32_t CurrentState = hsmbus->State; + + if (hsmbus->XferCount != 0U) + { + /* Write data to DATA */ + hsmbus->Instance->DATA = (*hsmbus->pBuffPtr++); + hsmbus->XferCount--; + + if ((hsmbus->XferCount == 2U) && (SMBUS_GET_PEC_MODE(hsmbus) == SMBUS_PEC_ENABLE) && ((hsmbus->XferOptions == SMBUS_FIRST_AND_LAST_FRAME_WITH_PEC) || (hsmbus->XferOptions == SMBUS_LAST_FRAME_WITH_PEC))) + { + hsmbus->XferCount--; + } + + if ((hsmbus->XferCount == 0U) && (CurrentState == (DAL_SMBUS_STATE_BUSY_TX_LISTEN))) + { + /* Last Byte is received, disable Interrupt */ + __DAL_SMBUS_DISABLE_IT(hsmbus, SMBUS_IT_BUF); + + /* Set state at DAL_SMBUS_STATE_LISTEN */ + hsmbus->PreviousState = SMBUS_STATE_SLAVE_BUSY_TX; + hsmbus->State = DAL_SMBUS_STATE_LISTEN; + + /* Call the corresponding callback to inform upper layer of End of Transfer */ +#if (USE_DAL_SMBUS_REGISTER_CALLBACKS == 1) + hsmbus->SlaveTxCpltCallback(hsmbus); +#else + DAL_SMBUS_SlaveTxCpltCallback(hsmbus); +#endif /* USE_DAL_SMBUS_REGISTER_CALLBACKS */ + } + } + return DAL_OK; +} + +/** + * @brief Handle BTF flag for Slave transmitter + * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for SMBUS module + * @retval DAL status + */ +static DAL_StatusTypeDef SMBUS_SlaveTransmit_BTF(SMBUS_HandleTypeDef *hsmbus) +{ + if (hsmbus->XferCount != 0U) + { + /* Write data to DATA */ + hsmbus->Instance->DATA = (*hsmbus->pBuffPtr++); + hsmbus->XferCount--; + } + + + + else if ((hsmbus->XferCount == 0U) && (SMBUS_GET_PEC_MODE(hsmbus) == SMBUS_PEC_ENABLE) && ((hsmbus->XferOptions == SMBUS_FIRST_AND_LAST_FRAME_WITH_PEC) || (hsmbus->XferOptions == SMBUS_LAST_FRAME_WITH_PEC))) + { + SET_BIT(hsmbus->Instance->CTRL1, I2C_CTRL1_PEC); + } + return DAL_OK; +} + +/** + * @brief Handle RXNE flag for Slave + * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for SMBUS module + * @retval DAL status + */ +static DAL_StatusTypeDef SMBUS_SlaveReceive_RXNE(SMBUS_HandleTypeDef *hsmbus) +{ + /* Declaration of temporary variables to prevent undefined behavior of volatile usage */ + uint32_t CurrentState = hsmbus->State; + + if (hsmbus->XferCount != 0U) + { + /* Read data from DATA */ + (*hsmbus->pBuffPtr++) = hsmbus->Instance->DATA; + hsmbus->XferCount--; + + if ((hsmbus->XferCount == 1U) && (SMBUS_GET_PEC_MODE(hsmbus) == SMBUS_PEC_ENABLE) && ((hsmbus->XferOptions == SMBUS_FIRST_AND_LAST_FRAME_WITH_PEC) || (hsmbus->XferOptions == SMBUS_LAST_FRAME_WITH_PEC))) + { + SET_BIT(hsmbus->Instance->CTRL1, I2C_CTRL1_PEC); + hsmbus->XferPEC = SMBUS_GET_PEC(hsmbus); + } + if ((hsmbus->XferCount == 0U) && (CurrentState == DAL_SMBUS_STATE_BUSY_RX_LISTEN)) + { + /* Last Byte is received, disable Interrupt */ + __DAL_SMBUS_DISABLE_IT(hsmbus, SMBUS_IT_BUF); + + /* Set state at DAL_SMBUS_STATE_LISTEN */ + hsmbus->PreviousState = SMBUS_STATE_SLAVE_BUSY_RX; + hsmbus->State = DAL_SMBUS_STATE_LISTEN; + + /* Call the corresponding callback to inform upper layer of End of Transfer */ +#if (USE_DAL_SMBUS_REGISTER_CALLBACKS == 1) + hsmbus->SlaveRxCpltCallback(hsmbus); +#else + DAL_SMBUS_SlaveRxCpltCallback(hsmbus); +#endif /* USE_DAL_SMBUS_REGISTER_CALLBACKS */ + } + } + return DAL_OK; +} + +/** + * @brief Handle BTF flag for Slave receiver + * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for SMBUS module + * @retval DAL status + */ +static DAL_StatusTypeDef SMBUS_SlaveReceive_BTF(SMBUS_HandleTypeDef *hsmbus) +{ + if (hsmbus->XferCount != 0U) + { + /* Read data from DATA */ + (*hsmbus->pBuffPtr++) = hsmbus->Instance->DATA; + hsmbus->XferCount--; + } + + return DAL_OK; +} + +/** + * @brief Handle ADD flag for Slave + * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for SMBUS module + * @retval DAL status + */ +static DAL_StatusTypeDef SMBUS_Slave_ADDR(SMBUS_HandleTypeDef *hsmbus) +{ + uint8_t TransferDirection = SMBUS_DIRECTION_RECEIVE ; + uint16_t SlaveAddrCode = 0U; + + /* Transfer Direction requested by Master */ + if (__DAL_SMBUS_GET_FLAG(hsmbus, SMBUS_FLAG_TRA) == RESET) + { + TransferDirection = SMBUS_DIRECTION_TRANSMIT; + } + + if (__DAL_SMBUS_GET_FLAG(hsmbus, SMBUS_FLAG_DUALF) == RESET) + { + SlaveAddrCode = hsmbus->Init.OwnAddress1; + } + else + { + SlaveAddrCode = hsmbus->Init.OwnAddress2; + } + + /* Call Slave Addr callback */ +#if (USE_DAL_SMBUS_REGISTER_CALLBACKS == 1) + hsmbus->AddrCallback(hsmbus, TransferDirection, SlaveAddrCode); +#else + DAL_SMBUS_AddrCallback(hsmbus, TransferDirection, SlaveAddrCode); +#endif /* USE_DAL_SMBUS_REGISTER_CALLBACKS */ + + return DAL_OK; +} + +/** + * @brief Handle STOPF flag for Slave + * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for SMBUS module + * @retval DAL status + */ +static DAL_StatusTypeDef SMBUS_Slave_STOPF(SMBUS_HandleTypeDef *hsmbus) +{ + /* Declaration of temporary variable to prevent undefined behavior of volatile usage */ + uint32_t CurrentState = hsmbus->State; + + /* Disable EVT, BUF and ERR interrupt */ + __DAL_SMBUS_DISABLE_IT(hsmbus, SMBUS_IT_EVT | SMBUS_IT_BUF | SMBUS_IT_ERR); + + /* Clear STOPF flag */ + __DAL_SMBUS_CLEAR_STOPFLAG(hsmbus); + + /* Disable Acknowledge */ + CLEAR_BIT(hsmbus->Instance->CTRL1, I2C_CTRL1_ACKEN); + + /* All data are not transferred, so set error code accordingly */ + if (hsmbus->XferCount != 0U) + { + /* Store Last receive data if any */ + if (__DAL_SMBUS_GET_FLAG(hsmbus, SMBUS_FLAG_BTF) == SET) + { + /* Read data from DATA */ + (*hsmbus->pBuffPtr++) = hsmbus->Instance->DATA; + + if (hsmbus->XferCount > 0) + { + hsmbus->XferSize--; + hsmbus->XferCount--; + } + } + + /* Store Last receive data if any */ + if (__DAL_SMBUS_GET_FLAG(hsmbus, SMBUS_FLAG_RXNE) == SET) + { + /* Read data from DATA */ + (*hsmbus->pBuffPtr++) = hsmbus->Instance->DATA; + + if (hsmbus->XferCount > 0) + { + hsmbus->XferSize--; + hsmbus->XferCount--; + } + } + } + + if (hsmbus->ErrorCode != DAL_SMBUS_ERROR_NONE) + { + /* Call the corresponding callback to inform upper layer of End of Transfer */ + SMBUS_ITError(hsmbus); + } + else + { + if ((CurrentState == DAL_SMBUS_STATE_LISTEN) || (CurrentState == DAL_SMBUS_STATE_BUSY_RX_LISTEN) || \ + (CurrentState == DAL_SMBUS_STATE_BUSY_TX_LISTEN)) + { + hsmbus->XferOptions = SMBUS_NO_OPTION_FRAME; + hsmbus->PreviousState = DAL_SMBUS_STATE_READY; + hsmbus->State = DAL_SMBUS_STATE_READY; + hsmbus->Mode = DAL_SMBUS_MODE_NONE; + +#if (USE_DAL_SMBUS_REGISTER_CALLBACKS == 1) + hsmbus->ListenCpltCallback(hsmbus); +#else + DAL_SMBUS_ListenCpltCallback(hsmbus); +#endif /* USE_DAL_SMBUS_REGISTER_CALLBACKS */ + } + } + return DAL_OK; +} + +/** + * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for SMBUS module + * @retval DAL status + */ +static DAL_StatusTypeDef SMBUS_Slave_AF(SMBUS_HandleTypeDef *hsmbus) +{ + /* Declaration of temporary variables to prevent undefined behavior of volatile usage */ + uint32_t CurrentState = hsmbus->State; + uint32_t CurrentXferOptions = hsmbus->XferOptions; + + if (((CurrentXferOptions == SMBUS_FIRST_AND_LAST_FRAME_NO_PEC) || (CurrentXferOptions == SMBUS_FIRST_AND_LAST_FRAME_WITH_PEC) || \ + (CurrentXferOptions == SMBUS_LAST_FRAME_NO_PEC) || (CurrentXferOptions == SMBUS_LAST_FRAME_WITH_PEC)) && \ + (CurrentState == DAL_SMBUS_STATE_LISTEN)) + { + hsmbus->XferOptions = SMBUS_NO_OPTION_FRAME; + + /* Disable EVT, BUF and ERR interrupt */ + __DAL_SMBUS_DISABLE_IT(hsmbus, SMBUS_IT_EVT | SMBUS_IT_BUF | SMBUS_IT_ERR); + + /* Clear AF flag */ + __DAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_AF); + + /* Disable Acknowledge */ + CLEAR_BIT(hsmbus->Instance->CTRL1, I2C_CTRL1_ACKEN); + + hsmbus->PreviousState = DAL_SMBUS_STATE_READY; + hsmbus->State = DAL_SMBUS_STATE_READY; + hsmbus->Mode = DAL_SMBUS_MODE_NONE; + + /* Call the Listen Complete callback, to inform upper layer of the end of Listen usecase */ +#if (USE_DAL_SMBUS_REGISTER_CALLBACKS == 1) + hsmbus->ListenCpltCallback(hsmbus); +#else + DAL_SMBUS_ListenCpltCallback(hsmbus); +#endif /* USE_DAL_SMBUS_REGISTER_CALLBACKS */ + } + return DAL_OK; +} + + + +/** + * @brief SMBUS interrupts error process + * @param hsmbus SMBUS handle. + * @retval None + */ +static void SMBUS_ITError(SMBUS_HandleTypeDef *hsmbus) +{ + /* Declaration of temporary variable to prevent undefined behavior of volatile usage */ + uint32_t CurrentState = hsmbus->State; + + if ((CurrentState == DAL_SMBUS_STATE_BUSY_TX_LISTEN) || (CurrentState == DAL_SMBUS_STATE_BUSY_RX_LISTEN)) + { + /* keep DAL_SMBUS_STATE_LISTEN */ + hsmbus->PreviousState = SMBUS_STATE_NONE; + hsmbus->State = DAL_SMBUS_STATE_LISTEN; + } + else + { + /* If state is an abort treatment on going, don't change state */ + /* This change will be done later */ + if (hsmbus->State != DAL_SMBUS_STATE_ABORT) + { + hsmbus->State = DAL_SMBUS_STATE_READY; + } + hsmbus->PreviousState = SMBUS_STATE_NONE; + hsmbus->Mode = DAL_SMBUS_MODE_NONE; + } + + /* Disable Pos bit in SMBUS CR1 when error occurred in Master/Mem Receive IT Process */ + CLEAR_BIT(hsmbus->Instance->CTRL1, I2C_CTRL1_ACKPOS); + + if (hsmbus->State == DAL_SMBUS_STATE_ABORT) + { + hsmbus->State = DAL_SMBUS_STATE_READY; + hsmbus->ErrorCode = DAL_SMBUS_ERROR_NONE; + + /* Store Last receive data if any */ + if (__DAL_SMBUS_GET_FLAG(hsmbus, SMBUS_FLAG_RXNE) == SET) + { + /* Read data from DATA */ + (*hsmbus->pBuffPtr++) = hsmbus->Instance->DATA; + } + + /* Disable SMBUS peripheral to prevent dummy data in buffer */ + __DAL_SMBUS_DISABLE(hsmbus); + + /* Call the corresponding callback to inform upper layer of End of Transfer */ +#if (USE_DAL_SMBUS_REGISTER_CALLBACKS == 1) + hsmbus->AbortCpltCallback(hsmbus); +#else + DAL_SMBUS_AbortCpltCallback(hsmbus); +#endif /* USE_DAL_SMBUS_REGISTER_CALLBACKS */ + } + else + { + /* Store Last receive data if any */ + if (__DAL_SMBUS_GET_FLAG(hsmbus, SMBUS_FLAG_RXNE) == SET) + { + /* Read data from DATA */ + (*hsmbus->pBuffPtr++) = hsmbus->Instance->DATA; + } + + /* Call user error callback */ +#if (USE_DAL_SMBUS_REGISTER_CALLBACKS == 1) + hsmbus->ErrorCallback(hsmbus); +#else + DAL_SMBUS_ErrorCallback(hsmbus); +#endif /* USE_DAL_SMBUS_REGISTER_CALLBACKS */ + } + /* STOP Flag is not set after a NACK reception */ + /* So may inform upper layer that listen phase is stopped */ + /* during NACK error treatment */ + if ((hsmbus->State == DAL_SMBUS_STATE_LISTEN) && ((hsmbus->ErrorCode & DAL_SMBUS_ERROR_AF) == DAL_SMBUS_ERROR_AF)) + { + hsmbus->XferOptions = SMBUS_NO_OPTION_FRAME; + hsmbus->PreviousState = SMBUS_STATE_NONE; + hsmbus->State = DAL_SMBUS_STATE_READY; + hsmbus->Mode = DAL_SMBUS_MODE_NONE; + + /* Call the Listen Complete callback, to inform upper layer of the end of Listen usecase */ +#if (USE_DAL_SMBUS_REGISTER_CALLBACKS == 1) + hsmbus->ListenCpltCallback(hsmbus); +#else + DAL_SMBUS_ListenCpltCallback(hsmbus); +#endif /* USE_DAL_SMBUS_REGISTER_CALLBACKS */ + } +} + +/** + * @brief This function handles SMBUS Communication Timeout. + * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for SMBUS module + * @param Flag specifies the SMBUS flag to check. + * @param Status The new Flag status (SET or RESET). + * @param Timeout Timeout duration + * @param Tickstart Tick start value + * @retval DAL status + */ +static DAL_StatusTypeDef SMBUS_WaitOnFlagUntilTimeout(SMBUS_HandleTypeDef *hsmbus, uint32_t Flag, FlagStatus Status, uint32_t Timeout, uint32_t Tickstart) +{ + /* Wait until flag is set */ + if (Status == RESET) + { + while (__DAL_SMBUS_GET_FLAG(hsmbus, Flag) == RESET) + { + /* Check for the Timeout */ + if (Timeout != DAL_MAX_DELAY) + { + if ((Timeout == 0U) || ((DAL_GetTick() - Tickstart) > Timeout)) + { + hsmbus->PreviousState = SMBUS_STATE_NONE; + hsmbus->State = DAL_SMBUS_STATE_READY; + hsmbus->Mode = DAL_SMBUS_MODE_NONE; + + /* Process Unlocked */ + __DAL_UNLOCK(hsmbus); + return DAL_TIMEOUT; + } + } + } + } + return DAL_OK; +} + +/** + * @} + */ + + +#endif /* DAL_SMBUS_MODULE_ENABLED */ + +/** + * @} + */ + +/** + * @} + */ + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_spi.c b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_spi.c new file mode 100644 index 0000000000..c868498990 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_spi.c @@ -0,0 +1,3940 @@ +/** + * + * @file apm32f4xx_dal_spi.c + * @brief SPI DAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the Serial Peripheral Interface (SPI) peripheral: + * + Initialization and de-initialization functions + * + IO operation functions + * + Peripheral Control functions + * + Peripheral State functions + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + * + @verbatim + ============================================================================== + ##### How to use this driver ##### + ============================================================================== + [..] + The SPI DAL driver can be used as follows: + + (#) Declare a SPI_HandleTypeDef handle structure, for example: + SPI_HandleTypeDef hspi; + + (#)Initialize the SPI low level resources by implementing the DAL_SPI_MspInit() API: + (##) Enable the SPIx interface clock + (##) SPI pins configuration + (+++) Enable the clock for the SPI GPIOs + (+++) Configure these SPI pins as alternate function push-pull + (##) NVIC configuration if you need to use interrupt process + (+++) Configure the SPIx interrupt priority + (+++) Enable the NVIC SPI IRQ handle + (##) DMA Configuration if you need to use DMA process + (+++) Declare a DMA_HandleTypeDef handle structure for the transmit or receive Stream/Channel + (+++) Enable the DMAx clock + (+++) Configure the DMA handle parameters + (+++) Configure the DMA Tx or Rx Stream/Channel + (+++) Associate the initialized hdma_tx(or _rx) handle to the hspi DMA Tx or Rx handle + (+++) Configure the priority and enable the NVIC for the transfer complete interrupt on the DMA Tx or Rx Stream/Channel + + (#) Program the Mode, BidirectionalMode , Data size, Baudrate Prescaler, NSS + management, Clock polarity and phase, FirstBit and CRC configuration in the hspi Init structure. + + (#) Initialize the SPI registers by calling the DAL_SPI_Init() API: + (++) This API configures also the low level Hardware GPIO, CLOCK, CORTEX...etc) + by calling the customized DAL_SPI_MspInit() API. + [..] + Circular mode restriction: + (#) The DMA circular mode cannot be used when the SPI is configured in these modes: + (##) Master 2Lines RxOnly + (##) Master 1Line Rx + (#) The CRC feature is not managed when the DMA circular mode is enabled + (#) When the SPI DMA Pause/Stop features are used, we must use the following APIs + the DAL_SPI_DMAPause()/ DAL_SPI_DMAStop() only under the SPI callbacks + [..] + Master Receive mode restriction: + (#) In Master unidirectional receive-only mode (MSTR =1, BIDIMODE=0, RXONLY=1) or + bidirectional receive mode (MSTR=1, BIDIMODE=1, BIDIOE=0), to ensure that the SPI + does not initiate a new transfer the following procedure has to be respected: + (##) DAL_SPI_DeInit() + (##) DAL_SPI_Init() + [..] + Callback registration: + + (#) The compilation flag USE_DAL_SPI_REGISTER_CALLBACKS when set to 1U + allows the user to configure dynamically the driver callbacks. + Use Functions DAL_SPI_RegisterCallback() to register an interrupt callback. + + Function DAL_SPI_RegisterCallback() allows to register following callbacks: + (++) TxCpltCallback : SPI Tx Completed callback + (++) RxCpltCallback : SPI Rx Completed callback + (++) TxRxCpltCallback : SPI TxRx Completed callback + (++) TxHalfCpltCallback : SPI Tx Half Completed callback + (++) RxHalfCpltCallback : SPI Rx Half Completed callback + (++) TxRxHalfCpltCallback : SPI TxRx Half Completed callback + (++) ErrorCallback : SPI Error callback + (++) AbortCpltCallback : SPI Abort callback + (++) MspInitCallback : SPI Msp Init callback + (++) MspDeInitCallback : SPI Msp DeInit callback + This function takes as parameters the DAL peripheral handle, the Callback ID + and a pointer to the user callback function. + + + (#) Use function DAL_SPI_UnRegisterCallback to reset a callback to the default + weak function. + DAL_SPI_UnRegisterCallback takes as parameters the DAL peripheral handle, + and the Callback ID. + This function allows to reset following callbacks: + (++) TxCpltCallback : SPI Tx Completed callback + (++) RxCpltCallback : SPI Rx Completed callback + (++) TxRxCpltCallback : SPI TxRx Completed callback + (++) TxHalfCpltCallback : SPI Tx Half Completed callback + (++) RxHalfCpltCallback : SPI Rx Half Completed callback + (++) TxRxHalfCpltCallback : SPI TxRx Half Completed callback + (++) ErrorCallback : SPI Error callback + (++) AbortCpltCallback : SPI Abort callback + (++) MspInitCallback : SPI Msp Init callback + (++) MspDeInitCallback : SPI Msp DeInit callback + + [..] + By default, after the DAL_SPI_Init() and when the state is DAL_SPI_STATE_RESET + all callbacks are set to the corresponding weak functions: + examples DAL_SPI_MasterTxCpltCallback(), DAL_SPI_MasterRxCpltCallback(). + Exception done for MspInit and MspDeInit functions that are + reset to the legacy weak functions in the DAL_SPI_Init()/ DAL_SPI_DeInit() only when + these callbacks are null (not registered beforehand). + If MspInit or MspDeInit are not null, the DAL_SPI_Init()/ DAL_SPI_DeInit() + keep and use the user MspInit/MspDeInit callbacks (registered beforehand) whatever the state. + + [..] + Callbacks can be registered/unregistered in DAL_SPI_STATE_READY state only. + Exception done MspInit/MspDeInit functions that can be registered/unregistered + in DAL_SPI_STATE_READY or DAL_SPI_STATE_RESET state, + thus registered (user) MspInit/DeInit callbacks can be used during the Init/DeInit. + Then, the user first registers the MspInit/MspDeInit user callbacks + using DAL_SPI_RegisterCallback() before calling DAL_SPI_DeInit() + or DAL_SPI_Init() function. + + [..] + When the compilation define USE_DAL_PPP_REGISTER_CALLBACKS is set to 0 or + not defined, the callback registering feature is not available + and weak (surcharged) callbacks are used. + + [..] + Using the DAL it is not possible to reach all supported SPI frequency with the different SPI Modes, + the following table resume the max SPI frequency reached with data size 8bits/16bits, + according to frequency of the APBx Peripheral Clock (fPCLK) used by the SPI instance. + + @endverbatim + + Additional table : + + DataSize = SPI_DATASIZE_8BIT: + +----------------------------------------------------------------------------------------------+ + | | | 2Lines Fullduplex | 2Lines RxOnly | 1Line | + | Process | Transfer mode |---------------------|----------------------|----------------------| + | | | Master | Slave | Master | Slave | Master | Slave | + |==============================================================================================| + | T | Polling | Fpclk/2 | Fpclk/2 | NA | NA | NA | NA | + | X |----------------|----------|----------|-----------|----------|-----------|----------| + | / | Interrupt | Fpclk/4 | Fpclk/8 | NA | NA | NA | NA | + | R |----------------|----------|----------|-----------|----------|-----------|----------| + | X | DMA | Fpclk/2 | Fpclk/2 | NA | NA | NA | NA | + |=========|================|==========|==========|===========|==========|===========|==========| + | | Polling | Fpclk/2 | Fpclk/2 | Fpclk/64 | Fpclk/2 | Fpclk/64 | Fpclk/2 | + | |----------------|----------|----------|-----------|----------|-----------|----------| + | R | Interrupt | Fpclk/8 | Fpclk/8 | Fpclk/64 | Fpclk/2 | Fpclk/64 | Fpclk/2 | + | X |----------------|----------|----------|-----------|----------|-----------|----------| + | | DMA | Fpclk/2 | Fpclk/2 | Fpclk/64 | Fpclk/2 | Fpclk/128 | Fpclk/2 | + |=========|================|==========|==========|===========|==========|===========|==========| + | | Polling | Fpclk/2 | Fpclk/4 | NA | NA | Fpclk/2 | Fpclk/64 | + | |----------------|----------|----------|-----------|----------|-----------|----------| + | T | Interrupt | Fpclk/2 | Fpclk/4 | NA | NA | Fpclk/2 | Fpclk/64 | + | X |----------------|----------|----------|-----------|----------|-----------|----------| + | | DMA | Fpclk/2 | Fpclk/2 | NA | NA | Fpclk/2 | Fpclk/128| + +----------------------------------------------------------------------------------------------+ + + DataSize = SPI_DATASIZE_16BIT: + +----------------------------------------------------------------------------------------------+ + | | | 2Lines Fullduplex | 2Lines RxOnly | 1Line | + | Process | Transfer mode |---------------------|----------------------|----------------------| + | | | Master | Slave | Master | Slave | Master | Slave | + |==============================================================================================| + | T | Polling | Fpclk/2 | Fpclk/2 | NA | NA | NA | NA | + | X |----------------|----------|----------|-----------|----------|-----------|----------| + | / | Interrupt | Fpclk/4 | Fpclk/4 | NA | NA | NA | NA | + | R |----------------|----------|----------|-----------|----------|-----------|----------| + | X | DMA | Fpclk/2 | Fpclk/2 | NA | NA | NA | NA | + |=========|================|==========|==========|===========|==========|===========|==========| + | | Polling | Fpclk/2 | Fpclk/2 | Fpclk/64 | Fpclk/2 | Fpclk/32 | Fpclk/2 | + | |----------------|----------|----------|-----------|----------|-----------|----------| + | R | Interrupt | Fpclk/4 | Fpclk/4 | Fpclk/64 | Fpclk/2 | Fpclk/64 | Fpclk/2 | + | X |----------------|----------|----------|-----------|----------|-----------|----------| + | | DMA | Fpclk/2 | Fpclk/2 | Fpclk/64 | Fpclk/2 | Fpclk/128 | Fpclk/2 | + |=========|================|==========|==========|===========|==========|===========|==========| + | | Polling | Fpclk/2 | Fpclk/2 | NA | NA | Fpclk/2 | Fpclk/32 | + | |----------------|----------|----------|-----------|----------|-----------|----------| + | T | Interrupt | Fpclk/2 | Fpclk/2 | NA | NA | Fpclk/2 | Fpclk/64 | + | X |----------------|----------|----------|-----------|----------|-----------|----------| + | | DMA | Fpclk/2 | Fpclk/2 | NA | NA | Fpclk/2 | Fpclk/128| + +----------------------------------------------------------------------------------------------+ + @note The max SPI frequency depend on SPI data size (8bits, 16bits), + SPI mode(2 Lines fullduplex, 2 lines RxOnly, 1 line TX/RX) and Process mode (Polling, IT, DMA). + @note + (#) TX/RX processes are DAL_SPI_TransmitReceive(), DAL_SPI_TransmitReceive_IT() and DAL_SPI_TransmitReceive_DMA() + (#) RX processes are DAL_SPI_Receive(), DAL_SPI_Receive_IT() and DAL_SPI_Receive_DMA() + (#) TX processes are DAL_SPI_Transmit(), DAL_SPI_Transmit_IT() and DAL_SPI_Transmit_DMA() + + */ + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @defgroup SPI SPI + * @brief SPI DAL module driver + * @{ + */ +#ifdef DAL_SPI_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private defines -----------------------------------------------------------*/ +/** @defgroup SPI_Private_Constants SPI Private Constants + * @{ + */ +#define SPI_DEFAULT_TIMEOUT 100U +#define SPI_BSY_FLAG_WORKAROUND_TIMEOUT 1000U /*!< Timeout 1000 ��s */ +/** + * @} + */ + +/* Private macros ------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/** @defgroup SPI_Private_Functions SPI Private Functions + * @{ + */ +static void SPI_DMATransmitCplt(DMA_HandleTypeDef *hdma); +static void SPI_DMAReceiveCplt(DMA_HandleTypeDef *hdma); +static void SPI_DMATransmitReceiveCplt(DMA_HandleTypeDef *hdma); +static void SPI_DMAHalfTransmitCplt(DMA_HandleTypeDef *hdma); +static void SPI_DMAHalfReceiveCplt(DMA_HandleTypeDef *hdma); +static void SPI_DMAHalfTransmitReceiveCplt(DMA_HandleTypeDef *hdma); +static void SPI_DMAError(DMA_HandleTypeDef *hdma); +static void SPI_DMAAbortOnError(DMA_HandleTypeDef *hdma); +static void SPI_DMATxAbortCallback(DMA_HandleTypeDef *hdma); +static void SPI_DMARxAbortCallback(DMA_HandleTypeDef *hdma); +static DAL_StatusTypeDef SPI_WaitFlagStateUntilTimeout(SPI_HandleTypeDef *hspi, uint32_t Flag, FlagStatus State, + uint32_t Timeout, uint32_t Tickstart); +static void SPI_TxISR_8BIT(struct __SPI_HandleTypeDef *hspi); +static void SPI_TxISR_16BIT(struct __SPI_HandleTypeDef *hspi); +static void SPI_RxISR_8BIT(struct __SPI_HandleTypeDef *hspi); +static void SPI_RxISR_16BIT(struct __SPI_HandleTypeDef *hspi); +static void SPI_2linesRxISR_8BIT(struct __SPI_HandleTypeDef *hspi); +static void SPI_2linesTxISR_8BIT(struct __SPI_HandleTypeDef *hspi); +static void SPI_2linesTxISR_16BIT(struct __SPI_HandleTypeDef *hspi); +static void SPI_2linesRxISR_16BIT(struct __SPI_HandleTypeDef *hspi); +#if (USE_SPI_CRC != 0U) +static void SPI_RxISR_8BITCRC(struct __SPI_HandleTypeDef *hspi); +static void SPI_RxISR_16BITCRC(struct __SPI_HandleTypeDef *hspi); +static void SPI_2linesRxISR_8BITCRC(struct __SPI_HandleTypeDef *hspi); +static void SPI_2linesRxISR_16BITCRC(struct __SPI_HandleTypeDef *hspi); +#endif /* USE_SPI_CRC */ +static void SPI_AbortRx_ISR(SPI_HandleTypeDef *hspi); +static void SPI_AbortTx_ISR(SPI_HandleTypeDef *hspi); +static void SPI_CloseRxTx_ISR(SPI_HandleTypeDef *hspi); +static void SPI_CloseRx_ISR(SPI_HandleTypeDef *hspi); +static void SPI_CloseTx_ISR(SPI_HandleTypeDef *hspi); +static DAL_StatusTypeDef SPI_EndRxTransaction(SPI_HandleTypeDef *hspi, uint32_t Timeout, uint32_t Tickstart); +static DAL_StatusTypeDef SPI_EndRxTxTransaction(SPI_HandleTypeDef *hspi, uint32_t Timeout, uint32_t Tickstart); +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +/** @defgroup SPI_Exported_Functions SPI Exported Functions + * @{ + */ + +/** @defgroup SPI_Exported_Functions_Group1 Initialization and de-initialization functions + * @brief Initialization and Configuration functions + * +@verbatim + =============================================================================== + ##### Initialization and de-initialization functions ##### + =============================================================================== + [..] This subsection provides a set of functions allowing to initialize and + de-initialize the SPIx peripheral: + + (+) User must implement DAL_SPI_MspInit() function in which he configures + all related peripherals resources (CLOCK, GPIO, DMA, IT and NVIC ). + + (+) Call the function DAL_SPI_Init() to configure the selected device with + the selected configuration: + (++) Mode + (++) Direction + (++) Data Size + (++) Clock Polarity and Phase + (++) NSS Management + (++) BaudRate Prescaler + (++) FirstBit + (++) TIMode + (++) CRC Calculation + (++) CRC Polynomial if CRC enabled + + (+) Call the function DAL_SPI_DeInit() to restore the default configuration + of the selected SPIx peripheral. + +@endverbatim + * @{ + */ + +/** + * @brief Initialize the SPI according to the specified parameters + * in the SPI_InitTypeDef and initialize the associated handle. + * @param hspi pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SPI_Init(SPI_HandleTypeDef *hspi) +{ + /* Check the SPI handle allocation */ + if (hspi == NULL) + { + return DAL_ERROR; + } + + /* Check the parameters */ + ASSERT_PARAM(IS_SPI_ALL_INSTANCE(hspi->Instance)); + ASSERT_PARAM(IS_SPI_MODE(hspi->Init.Mode)); + ASSERT_PARAM(IS_SPI_DIRECTION(hspi->Init.Direction)); + ASSERT_PARAM(IS_SPI_DATASIZE(hspi->Init.DataSize)); + ASSERT_PARAM(IS_SPI_NSS(hspi->Init.NSS)); + ASSERT_PARAM(IS_SPI_BAUDRATE_PRESCALER(hspi->Init.BaudRatePrescaler)); + ASSERT_PARAM(IS_SPI_FIRST_BIT(hspi->Init.FirstBit)); + ASSERT_PARAM(IS_SPI_TIMODE(hspi->Init.TIMode)); + if (hspi->Init.TIMode == SPI_TIMODE_DISABLE) + { + ASSERT_PARAM(IS_SPI_CPOL(hspi->Init.CLKPolarity)); + ASSERT_PARAM(IS_SPI_CPHA(hspi->Init.CLKPhase)); + + if (hspi->Init.Mode == SPI_MODE_MASTER) + { + ASSERT_PARAM(IS_SPI_BAUDRATE_PRESCALER(hspi->Init.BaudRatePrescaler)); + } + else + { + /* Baudrate prescaler not use in Motoraola Slave mode. force to default value */ + hspi->Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_2; + } + } + else + { + ASSERT_PARAM(IS_SPI_BAUDRATE_PRESCALER(hspi->Init.BaudRatePrescaler)); + + /* Force polarity and phase to TI protocaol requirements */ + hspi->Init.CLKPolarity = SPI_POLARITY_LOW; + hspi->Init.CLKPhase = SPI_PHASE_1EDGE; + } +#if (USE_SPI_CRC != 0U) + ASSERT_PARAM(IS_SPI_CRC_CALCULATION(hspi->Init.CRCCalculation)); + if (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) + { + ASSERT_PARAM(IS_SPI_CRC_POLYNOMIAL(hspi->Init.CRCPolynomial)); + } +#else + hspi->Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE; +#endif /* USE_SPI_CRC */ + + if (hspi->State == DAL_SPI_STATE_RESET) + { + /* Allocate lock resource and initialize it */ + hspi->Lock = DAL_UNLOCKED; + +#if (USE_DAL_SPI_REGISTER_CALLBACKS == 1U) + /* Init the SPI Callback settings */ + hspi->TxCpltCallback = DAL_SPI_TxCpltCallback; /* Legacy weak TxCpltCallback */ + hspi->RxCpltCallback = DAL_SPI_RxCpltCallback; /* Legacy weak RxCpltCallback */ + hspi->TxRxCpltCallback = DAL_SPI_TxRxCpltCallback; /* Legacy weak TxRxCpltCallback */ + hspi->TxHalfCpltCallback = DAL_SPI_TxHalfCpltCallback; /* Legacy weak TxHalfCpltCallback */ + hspi->RxHalfCpltCallback = DAL_SPI_RxHalfCpltCallback; /* Legacy weak RxHalfCpltCallback */ + hspi->TxRxHalfCpltCallback = DAL_SPI_TxRxHalfCpltCallback; /* Legacy weak TxRxHalfCpltCallback */ + hspi->ErrorCallback = DAL_SPI_ErrorCallback; /* Legacy weak ErrorCallback */ + hspi->AbortCpltCallback = DAL_SPI_AbortCpltCallback; /* Legacy weak AbortCpltCallback */ + + if (hspi->MspInitCallback == NULL) + { + hspi->MspInitCallback = DAL_SPI_MspInit; /* Legacy weak MspInit */ + } + + /* Init the low level hardware : GPIO, CLOCK, NVIC... */ + hspi->MspInitCallback(hspi); +#else + /* Init the low level hardware : GPIO, CLOCK, NVIC... */ + DAL_SPI_MspInit(hspi); +#endif /* USE_DAL_SPI_REGISTER_CALLBACKS */ + } + + hspi->State = DAL_SPI_STATE_BUSY; + + /* Disable the selected SPI peripheral */ + __DAL_SPI_DISABLE(hspi); + + /*----------------------- SPIx CTRL1 & CTRL2 Configuration ---------------------*/ + /* Configure : SPI Mode, Communication Mode, Data size, Clock polarity and phase, NSS management, + Communication speed, First bit and CRC calculation state */ + WRITE_REG(hspi->Instance->CTRL1, ((hspi->Init.Mode & (SPI_CTRL1_MSMCFG | SPI_CTRL1_ISSEL)) | + (hspi->Init.Direction & (SPI_CTRL1_RXOMEN | SPI_CTRL1_BMEN)) | + (hspi->Init.DataSize & SPI_CTRL1_DFLSEL) | + (hspi->Init.CLKPolarity & SPI_CTRL1_CPOL) | + (hspi->Init.CLKPhase & SPI_CTRL1_CPHA) | + (hspi->Init.NSS & SPI_CTRL1_SSEN) | + (hspi->Init.BaudRatePrescaler & SPI_CTRL1_BRSEL_Msk) | + (hspi->Init.FirstBit & SPI_CTRL1_LSBSEL) | + (hspi->Init.CRCCalculation & SPI_CTRL1_CRCEN))); + + /* Configure : NSS management, TI Mode */ + WRITE_REG(hspi->Instance->CTRL2, (((hspi->Init.NSS >> 16U) & SPI_CTRL2_SSOEN) | (hspi->Init.TIMode & SPI_CTRL2_FRFCFG))); + +#if (USE_SPI_CRC != 0U) + /*---------------------------- SPIx CRCPOLY Configuration ------------------*/ + /* Configure : CRC Polynomial */ + if (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) + { + WRITE_REG(hspi->Instance->CRCPOLY, (hspi->Init.CRCPolynomial & SPI_CRCPOLY_CRCPOLY_Msk)); + } +#endif /* USE_SPI_CRC */ + +#if defined(SPI_I2SCFG_MODESEL) + /* Activate the SPI mode (Make sure that I2SMOD bit in I2SCFGR register is reset) */ + CLEAR_BIT(hspi->Instance->I2SCFG, SPI_I2SCFG_MODESEL); +#endif /* SPI_I2SCFG_MODESEL */ + + hspi->ErrorCode = DAL_SPI_ERROR_NONE; + hspi->State = DAL_SPI_STATE_READY; + + return DAL_OK; +} + +/** + * @brief De-Initialize the SPI peripheral. + * @param hspi pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SPI_DeInit(SPI_HandleTypeDef *hspi) +{ + /* Check the SPI handle allocation */ + if (hspi == NULL) + { + return DAL_ERROR; + } + + /* Check SPI Instance parameter */ + ASSERT_PARAM(IS_SPI_ALL_INSTANCE(hspi->Instance)); + + hspi->State = DAL_SPI_STATE_BUSY; + + /* Disable the SPI Peripheral Clock */ + __DAL_SPI_DISABLE(hspi); + +#if (USE_DAL_SPI_REGISTER_CALLBACKS == 1U) + if (hspi->MspDeInitCallback == NULL) + { + hspi->MspDeInitCallback = DAL_SPI_MspDeInit; /* Legacy weak MspDeInit */ + } + + /* DeInit the low level hardware: GPIO, CLOCK, NVIC... */ + hspi->MspDeInitCallback(hspi); +#else + /* DeInit the low level hardware: GPIO, CLOCK, NVIC... */ + DAL_SPI_MspDeInit(hspi); +#endif /* USE_DAL_SPI_REGISTER_CALLBACKS */ + + hspi->ErrorCode = DAL_SPI_ERROR_NONE; + hspi->State = DAL_SPI_STATE_RESET; + + /* Release Lock */ + __DAL_UNLOCK(hspi); + + return DAL_OK; +} + +/** + * @brief Initialize the SPI MSP. + * @param hspi pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @retval None + */ +__weak void DAL_SPI_MspInit(SPI_HandleTypeDef *hspi) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hspi); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_SPI_MspInit should be implemented in the user file + */ +} + +/** + * @brief De-Initialize the SPI MSP. + * @param hspi pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @retval None + */ +__weak void DAL_SPI_MspDeInit(SPI_HandleTypeDef *hspi) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hspi); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_SPI_MspDeInit should be implemented in the user file + */ +} + +#if (USE_DAL_SPI_REGISTER_CALLBACKS == 1U) +/** + * @brief Register a User SPI Callback + * To be used instead of the weak predefined callback + * @param hspi Pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for the specified SPI. + * @param CallbackID ID of the callback to be registered + * @param pCallback pointer to the Callback function + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SPI_RegisterCallback(SPI_HandleTypeDef *hspi, DAL_SPI_CallbackIDTypeDef CallbackID, + pSPI_CallbackTypeDef pCallback) +{ + DAL_StatusTypeDef status = DAL_OK; + + if (pCallback == NULL) + { + /* Update the error code */ + hspi->ErrorCode |= DAL_SPI_ERROR_INVALID_CALLBACK; + + return DAL_ERROR; + } + /* Process locked */ + __DAL_LOCK(hspi); + + if (DAL_SPI_STATE_READY == hspi->State) + { + switch (CallbackID) + { + case DAL_SPI_TX_COMPLETE_CB_ID : + hspi->TxCpltCallback = pCallback; + break; + + case DAL_SPI_RX_COMPLETE_CB_ID : + hspi->RxCpltCallback = pCallback; + break; + + case DAL_SPI_TX_RX_COMPLETE_CB_ID : + hspi->TxRxCpltCallback = pCallback; + break; + + case DAL_SPI_TX_HALF_COMPLETE_CB_ID : + hspi->TxHalfCpltCallback = pCallback; + break; + + case DAL_SPI_RX_HALF_COMPLETE_CB_ID : + hspi->RxHalfCpltCallback = pCallback; + break; + + case DAL_SPI_TX_RX_HALF_COMPLETE_CB_ID : + hspi->TxRxHalfCpltCallback = pCallback; + break; + + case DAL_SPI_ERROR_CB_ID : + hspi->ErrorCallback = pCallback; + break; + + case DAL_SPI_ABORT_CB_ID : + hspi->AbortCpltCallback = pCallback; + break; + + case DAL_SPI_MSPINIT_CB_ID : + hspi->MspInitCallback = pCallback; + break; + + case DAL_SPI_MSPDEINIT_CB_ID : + hspi->MspDeInitCallback = pCallback; + break; + + default : + /* Update the error code */ + SET_BIT(hspi->ErrorCode, DAL_SPI_ERROR_INVALID_CALLBACK); + + /* Return error status */ + status = DAL_ERROR; + break; + } + } + else if (DAL_SPI_STATE_RESET == hspi->State) + { + switch (CallbackID) + { + case DAL_SPI_MSPINIT_CB_ID : + hspi->MspInitCallback = pCallback; + break; + + case DAL_SPI_MSPDEINIT_CB_ID : + hspi->MspDeInitCallback = pCallback; + break; + + default : + /* Update the error code */ + SET_BIT(hspi->ErrorCode, DAL_SPI_ERROR_INVALID_CALLBACK); + + /* Return error status */ + status = DAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + SET_BIT(hspi->ErrorCode, DAL_SPI_ERROR_INVALID_CALLBACK); + + /* Return error status */ + status = DAL_ERROR; + } + + /* Release Lock */ + __DAL_UNLOCK(hspi); + return status; +} + +/** + * @brief Unregister an SPI Callback + * SPI callback is redirected to the weak predefined callback + * @param hspi Pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for the specified SPI. + * @param CallbackID ID of the callback to be unregistered + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SPI_UnRegisterCallback(SPI_HandleTypeDef *hspi, DAL_SPI_CallbackIDTypeDef CallbackID) +{ + DAL_StatusTypeDef status = DAL_OK; + + /* Process locked */ + __DAL_LOCK(hspi); + + if (DAL_SPI_STATE_READY == hspi->State) + { + switch (CallbackID) + { + case DAL_SPI_TX_COMPLETE_CB_ID : + hspi->TxCpltCallback = DAL_SPI_TxCpltCallback; /* Legacy weak TxCpltCallback */ + break; + + case DAL_SPI_RX_COMPLETE_CB_ID : + hspi->RxCpltCallback = DAL_SPI_RxCpltCallback; /* Legacy weak RxCpltCallback */ + break; + + case DAL_SPI_TX_RX_COMPLETE_CB_ID : + hspi->TxRxCpltCallback = DAL_SPI_TxRxCpltCallback; /* Legacy weak TxRxCpltCallback */ + break; + + case DAL_SPI_TX_HALF_COMPLETE_CB_ID : + hspi->TxHalfCpltCallback = DAL_SPI_TxHalfCpltCallback; /* Legacy weak TxHalfCpltCallback */ + break; + + case DAL_SPI_RX_HALF_COMPLETE_CB_ID : + hspi->RxHalfCpltCallback = DAL_SPI_RxHalfCpltCallback; /* Legacy weak RxHalfCpltCallback */ + break; + + case DAL_SPI_TX_RX_HALF_COMPLETE_CB_ID : + hspi->TxRxHalfCpltCallback = DAL_SPI_TxRxHalfCpltCallback; /* Legacy weak TxRxHalfCpltCallback */ + break; + + case DAL_SPI_ERROR_CB_ID : + hspi->ErrorCallback = DAL_SPI_ErrorCallback; /* Legacy weak ErrorCallback */ + break; + + case DAL_SPI_ABORT_CB_ID : + hspi->AbortCpltCallback = DAL_SPI_AbortCpltCallback; /* Legacy weak AbortCpltCallback */ + break; + + case DAL_SPI_MSPINIT_CB_ID : + hspi->MspInitCallback = DAL_SPI_MspInit; /* Legacy weak MspInit */ + break; + + case DAL_SPI_MSPDEINIT_CB_ID : + hspi->MspDeInitCallback = DAL_SPI_MspDeInit; /* Legacy weak MspDeInit */ + break; + + default : + /* Update the error code */ + SET_BIT(hspi->ErrorCode, DAL_SPI_ERROR_INVALID_CALLBACK); + + /* Return error status */ + status = DAL_ERROR; + break; + } + } + else if (DAL_SPI_STATE_RESET == hspi->State) + { + switch (CallbackID) + { + case DAL_SPI_MSPINIT_CB_ID : + hspi->MspInitCallback = DAL_SPI_MspInit; /* Legacy weak MspInit */ + break; + + case DAL_SPI_MSPDEINIT_CB_ID : + hspi->MspDeInitCallback = DAL_SPI_MspDeInit; /* Legacy weak MspDeInit */ + break; + + default : + /* Update the error code */ + SET_BIT(hspi->ErrorCode, DAL_SPI_ERROR_INVALID_CALLBACK); + + /* Return error status */ + status = DAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + SET_BIT(hspi->ErrorCode, DAL_SPI_ERROR_INVALID_CALLBACK); + + /* Return error status */ + status = DAL_ERROR; + } + + /* Release Lock */ + __DAL_UNLOCK(hspi); + return status; +} +#endif /* USE_DAL_SPI_REGISTER_CALLBACKS */ +/** + * @} + */ + +/** @defgroup SPI_Exported_Functions_Group2 IO operation functions + * @brief Data transfers functions + * +@verbatim + ============================================================================== + ##### IO operation functions ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to manage the SPI + data transfers. + + [..] The SPI supports master and slave mode : + + (#) There are two modes of transfer: + (++) Blocking mode: The communication is performed in polling mode. + The DAL status of all data processing is returned by the same function + after finishing transfer. + (++) No-Blocking mode: The communication is performed using Interrupts + or DMA, These APIs return the DAL status. + The end of the data processing will be indicated through the + dedicated SPI IRQ when using Interrupt mode or the DMA IRQ when + using DMA mode. + The DAL_SPI_TxCpltCallback(), DAL_SPI_RxCpltCallback() and DAL_SPI_TxRxCpltCallback() user callbacks + will be executed respectively at the end of the transmit or Receive process + The DAL_SPI_ErrorCallback()user callback will be executed when a communication error is detected + + (#) APIs provided for these 2 transfer modes (Blocking mode or Non blocking mode using either Interrupt or DMA) + exist for 1Line (simplex) and 2Lines (full duplex) modes. + +@endverbatim + * @{ + */ + +/** + * @brief Transmit an amount of data in blocking mode. + * @param hspi pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @param pData pointer to data buffer + * @param Size amount of data to be sent + * @param Timeout Timeout duration + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SPI_Transmit(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size, uint32_t Timeout) +{ + uint32_t tickstart; + DAL_StatusTypeDef errorcode = DAL_OK; + uint16_t initial_TxXferCount; + + /* Check Direction parameter */ + ASSERT_PARAM(IS_SPI_DIRECTION_2LINES_OR_1LINE(hspi->Init.Direction)); + + /* Process Locked */ + __DAL_LOCK(hspi); + + /* Init tickstart for timeout management*/ + tickstart = DAL_GetTick(); + initial_TxXferCount = Size; + + if (hspi->State != DAL_SPI_STATE_READY) + { + errorcode = DAL_BUSY; + goto error; + } + + if ((pData == NULL) || (Size == 0U)) + { + errorcode = DAL_ERROR; + goto error; + } + + /* Set the transaction information */ + hspi->State = DAL_SPI_STATE_BUSY_TX; + hspi->ErrorCode = DAL_SPI_ERROR_NONE; + hspi->pTxBuffPtr = (uint8_t *)pData; + hspi->TxXferSize = Size; + hspi->TxXferCount = Size; + + /*Init field not used in handle to zero */ + hspi->pRxBuffPtr = (uint8_t *)NULL; + hspi->RxXferSize = 0U; + hspi->RxXferCount = 0U; + hspi->TxISR = NULL; + hspi->RxISR = NULL; + + /* Configure communication direction : 1Line */ + if (hspi->Init.Direction == SPI_DIRECTION_1LINE) + { + /* Disable SPI Peripheral before set 1Line direction (BIDIOE bit) */ + __DAL_SPI_DISABLE(hspi); + SPI_1LINE_TX(hspi); + } + +#if (USE_SPI_CRC != 0U) + /* Reset CRC Calculation */ + if (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) + { + SPI_RESET_CRC(hspi); + } +#endif /* USE_SPI_CRC */ + + /* Check if the SPI is already enabled */ + if ((hspi->Instance->CTRL1 & SPI_CTRL1_SPIEN) != SPI_CTRL1_SPIEN) + { + /* Enable SPI peripheral */ + __DAL_SPI_ENABLE(hspi); + } + + /* Transmit data in 16 Bit mode */ + if (hspi->Init.DataSize == SPI_DATASIZE_16BIT) + { + if ((hspi->Init.Mode == SPI_MODE_SLAVE) || (initial_TxXferCount == 0x01U)) + { + hspi->Instance->DATA = *((uint16_t *)hspi->pTxBuffPtr); + hspi->pTxBuffPtr += sizeof(uint16_t); + hspi->TxXferCount--; + } + /* Transmit data in 16 Bit mode */ + while (hspi->TxXferCount > 0U) + { + /* Wait until TXE flag is set to send data */ + if (__DAL_SPI_GET_FLAG(hspi, SPI_FLAG_TXE)) + { + hspi->Instance->DATA = *((uint16_t *)hspi->pTxBuffPtr); + hspi->pTxBuffPtr += sizeof(uint16_t); + hspi->TxXferCount--; + } + else + { + /* Timeout management */ + if ((((DAL_GetTick() - tickstart) >= Timeout) && (Timeout != DAL_MAX_DELAY)) || (Timeout == 0U)) + { + errorcode = DAL_TIMEOUT; + goto error; + } + } + } + } + /* Transmit data in 8 Bit mode */ + else + { + if ((hspi->Init.Mode == SPI_MODE_SLAVE) || (initial_TxXferCount == 0x01U)) + { + *((__IO uint8_t *)&hspi->Instance->DATA) = (*hspi->pTxBuffPtr); + hspi->pTxBuffPtr += sizeof(uint8_t); + hspi->TxXferCount--; + } + while (hspi->TxXferCount > 0U) + { + /* Wait until TXE flag is set to send data */ + if (__DAL_SPI_GET_FLAG(hspi, SPI_FLAG_TXE)) + { + *((__IO uint8_t *)&hspi->Instance->DATA) = (*hspi->pTxBuffPtr); + hspi->pTxBuffPtr += sizeof(uint8_t); + hspi->TxXferCount--; + } + else + { + /* Timeout management */ + if ((((DAL_GetTick() - tickstart) >= Timeout) && (Timeout != DAL_MAX_DELAY)) || (Timeout == 0U)) + { + errorcode = DAL_TIMEOUT; + goto error; + } + } + } + } +#if (USE_SPI_CRC != 0U) + /* Enable CRC Transmission */ + if (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) + { + SET_BIT(hspi->Instance->CTRL1, SPI_CTRL1_CRCNXT); + } +#endif /* USE_SPI_CRC */ + + /* Check the end of the transaction */ + if (SPI_EndRxTxTransaction(hspi, Timeout, tickstart) != DAL_OK) + { + hspi->ErrorCode = DAL_SPI_ERROR_FLAG; + } + + /* Clear overrun flag in 2 Lines communication mode because received is not read */ + if (hspi->Init.Direction == SPI_DIRECTION_2LINES) + { + __DAL_SPI_CLEAR_OVRFLAG(hspi); + } + + if (hspi->ErrorCode != DAL_SPI_ERROR_NONE) + { + errorcode = DAL_ERROR; + } + +error: + hspi->State = DAL_SPI_STATE_READY; + /* Process Unlocked */ + __DAL_UNLOCK(hspi); + return errorcode; +} + +/** + * @brief Receive an amount of data in blocking mode. + * @param hspi pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @param pData pointer to data buffer + * @param Size amount of data to be received + * @param Timeout Timeout duration + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SPI_Receive(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size, uint32_t Timeout) +{ +#if (USE_SPI_CRC != 0U) + __IO uint32_t tmpreg = 0U; +#endif /* USE_SPI_CRC */ + uint32_t tickstart; + DAL_StatusTypeDef errorcode = DAL_OK; + + if ((hspi->Init.Mode == SPI_MODE_MASTER) && (hspi->Init.Direction == SPI_DIRECTION_2LINES)) + { + hspi->State = DAL_SPI_STATE_BUSY_RX; + /* Call transmit-receive function to send Dummy data on Tx line and generate clock on CLK line */ + return DAL_SPI_TransmitReceive(hspi, pData, pData, Size, Timeout); + } + + /* Process Locked */ + __DAL_LOCK(hspi); + + /* Init tickstart for timeout management*/ + tickstart = DAL_GetTick(); + + if (hspi->State != DAL_SPI_STATE_READY) + { + errorcode = DAL_BUSY; + goto error; + } + + if ((pData == NULL) || (Size == 0U)) + { + errorcode = DAL_ERROR; + goto error; + } + + /* Set the transaction information */ + hspi->State = DAL_SPI_STATE_BUSY_RX; + hspi->ErrorCode = DAL_SPI_ERROR_NONE; + hspi->pRxBuffPtr = (uint8_t *)pData; + hspi->RxXferSize = Size; + hspi->RxXferCount = Size; + + /*Init field not used in handle to zero */ + hspi->pTxBuffPtr = (uint8_t *)NULL; + hspi->TxXferSize = 0U; + hspi->TxXferCount = 0U; + hspi->RxISR = NULL; + hspi->TxISR = NULL; + +#if (USE_SPI_CRC != 0U) + /* Reset CRC Calculation */ + if (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) + { + SPI_RESET_CRC(hspi); + /* this is done to handle the CRCNEXT before the latest data */ + hspi->RxXferCount--; + } +#endif /* USE_SPI_CRC */ + + /* Configure communication direction: 1Line */ + if (hspi->Init.Direction == SPI_DIRECTION_1LINE) + { + /* Disable SPI Peripheral before set 1Line direction (BIDIOE bit) */ + __DAL_SPI_DISABLE(hspi); + SPI_1LINE_RX(hspi); + } + + /* Check if the SPI is already enabled */ + if ((hspi->Instance->CTRL1 & SPI_CTRL1_SPIEN) != SPI_CTRL1_SPIEN) + { + /* Enable SPI peripheral */ + __DAL_SPI_ENABLE(hspi); + } + + /* Receive data in 8 Bit mode */ + if (hspi->Init.DataSize == SPI_DATASIZE_8BIT) + { + /* Transfer loop */ + while (hspi->RxXferCount > 0U) + { + /* Check the RXNE flag */ + if (__DAL_SPI_GET_FLAG(hspi, SPI_FLAG_RXNE)) + { + /* read the received data */ + (* (uint8_t *)hspi->pRxBuffPtr) = *(__IO uint8_t *)&hspi->Instance->DATA; + hspi->pRxBuffPtr += sizeof(uint8_t); + hspi->RxXferCount--; + } + else + { + /* Timeout management */ + if ((((DAL_GetTick() - tickstart) >= Timeout) && (Timeout != DAL_MAX_DELAY)) || (Timeout == 0U)) + { + errorcode = DAL_TIMEOUT; + goto error; + } + } + } + } + else + { + /* Transfer loop */ + while (hspi->RxXferCount > 0U) + { + /* Check the RXNE flag */ + if (__DAL_SPI_GET_FLAG(hspi, SPI_FLAG_RXNE)) + { + *((uint16_t *)hspi->pRxBuffPtr) = (uint16_t)hspi->Instance->DATA; + hspi->pRxBuffPtr += sizeof(uint16_t); + hspi->RxXferCount--; + } + else + { + /* Timeout management */ + if ((((DAL_GetTick() - tickstart) >= Timeout) && (Timeout != DAL_MAX_DELAY)) || (Timeout == 0U)) + { + errorcode = DAL_TIMEOUT; + goto error; + } + } + } + } + +#if (USE_SPI_CRC != 0U) + /* Handle the CRC Transmission */ + if (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) + { + /* freeze the CRC before the latest data */ + SET_BIT(hspi->Instance->CTRL1, SPI_CTRL1_CRCNXT); + + /* Read the latest data */ + if (SPI_WaitFlagStateUntilTimeout(hspi, SPI_FLAG_RXNE, SET, Timeout, tickstart) != DAL_OK) + { + /* the latest data has not been received */ + errorcode = DAL_TIMEOUT; + goto error; + } + + /* Receive last data in 16 Bit mode */ + if (hspi->Init.DataSize == SPI_DATASIZE_16BIT) + { + *((uint16_t *)hspi->pRxBuffPtr) = (uint16_t)hspi->Instance->DATA; + } + /* Receive last data in 8 Bit mode */ + else + { + (*(uint8_t *)hspi->pRxBuffPtr) = *(__IO uint8_t *)&hspi->Instance->DATA; + } + + /* Wait the CRC data */ + if (SPI_WaitFlagStateUntilTimeout(hspi, SPI_FLAG_RXNE, SET, Timeout, tickstart) != DAL_OK) + { + SET_BIT(hspi->ErrorCode, DAL_SPI_ERROR_CRC); + errorcode = DAL_TIMEOUT; + goto error; + } + + /* Read CRC to Flush DATA and RXNE flag */ + tmpreg = READ_REG(hspi->Instance->DATA); + /* To avoid GCC warning */ + UNUSED(tmpreg); + } +#endif /* USE_SPI_CRC */ + + /* Check the end of the transaction */ + if (SPI_EndRxTransaction(hspi, Timeout, tickstart) != DAL_OK) + { + hspi->ErrorCode = DAL_SPI_ERROR_FLAG; + } + +#if (USE_SPI_CRC != 0U) + /* Check if CRC error occurred */ + if (__DAL_SPI_GET_FLAG(hspi, SPI_FLAG_CRCERR)) + { + SET_BIT(hspi->ErrorCode, DAL_SPI_ERROR_CRC); + __DAL_SPI_CLEAR_CRCERRFLAG(hspi); + } +#endif /* USE_SPI_CRC */ + + if (hspi->ErrorCode != DAL_SPI_ERROR_NONE) + { + errorcode = DAL_ERROR; + } + +error : + hspi->State = DAL_SPI_STATE_READY; + __DAL_UNLOCK(hspi); + return errorcode; +} + +/** + * @brief Transmit and Receive an amount of data in blocking mode. + * @param hspi pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @param pTxData pointer to transmission data buffer + * @param pRxData pointer to reception data buffer + * @param Size amount of data to be sent and received + * @param Timeout Timeout duration + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SPI_TransmitReceive(SPI_HandleTypeDef *hspi, uint8_t *pTxData, uint8_t *pRxData, uint16_t Size, + uint32_t Timeout) +{ + uint16_t initial_TxXferCount; + uint32_t tmp_mode; + DAL_SPI_StateTypeDef tmp_state; + uint32_t tickstart; +#if (USE_SPI_CRC != 0U) + __IO uint32_t tmpreg = 0U; +#endif /* USE_SPI_CRC */ + + /* Variable used to alternate Rx and Tx during transfer */ + uint32_t txallowed = 1U; + DAL_StatusTypeDef errorcode = DAL_OK; + + /* Check Direction parameter */ + ASSERT_PARAM(IS_SPI_DIRECTION_2LINES(hspi->Init.Direction)); + + /* Process Locked */ + __DAL_LOCK(hspi); + + /* Init tickstart for timeout management*/ + tickstart = DAL_GetTick(); + + /* Init temporary variables */ + tmp_state = hspi->State; + tmp_mode = hspi->Init.Mode; + initial_TxXferCount = Size; + + if (!((tmp_state == DAL_SPI_STATE_READY) || \ + ((tmp_mode == SPI_MODE_MASTER) && (hspi->Init.Direction == SPI_DIRECTION_2LINES) && (tmp_state == DAL_SPI_STATE_BUSY_RX)))) + { + errorcode = DAL_BUSY; + goto error; + } + + if ((pTxData == NULL) || (pRxData == NULL) || (Size == 0U)) + { + errorcode = DAL_ERROR; + goto error; + } + + /* Don't overwrite in case of DAL_SPI_STATE_BUSY_RX */ + if (hspi->State != DAL_SPI_STATE_BUSY_RX) + { + hspi->State = DAL_SPI_STATE_BUSY_TX_RX; + } + + /* Set the transaction information */ + hspi->ErrorCode = DAL_SPI_ERROR_NONE; + hspi->pRxBuffPtr = (uint8_t *)pRxData; + hspi->RxXferCount = Size; + hspi->RxXferSize = Size; + hspi->pTxBuffPtr = (uint8_t *)pTxData; + hspi->TxXferCount = Size; + hspi->TxXferSize = Size; + + /*Init field not used in handle to zero */ + hspi->RxISR = NULL; + hspi->TxISR = NULL; + +#if (USE_SPI_CRC != 0U) + /* Reset CRC Calculation */ + if (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) + { + SPI_RESET_CRC(hspi); + } +#endif /* USE_SPI_CRC */ + + /* Check if the SPI is already enabled */ + if ((hspi->Instance->CTRL1 & SPI_CTRL1_SPIEN) != SPI_CTRL1_SPIEN) + { + /* Enable SPI peripheral */ + __DAL_SPI_ENABLE(hspi); + } + + /* Transmit and Receive data in 16 Bit mode */ + if (hspi->Init.DataSize == SPI_DATASIZE_16BIT) + { + if ((hspi->Init.Mode == SPI_MODE_SLAVE) || (initial_TxXferCount == 0x01U)) + { + hspi->Instance->DATA = *((uint16_t *)hspi->pTxBuffPtr); + hspi->pTxBuffPtr += sizeof(uint16_t); + hspi->TxXferCount--; + } + while ((hspi->TxXferCount > 0U) || (hspi->RxXferCount > 0U)) + { + /* Check TXE flag */ + if ((__DAL_SPI_GET_FLAG(hspi, SPI_FLAG_TXE)) && (hspi->TxXferCount > 0U) && (txallowed == 1U)) + { + hspi->Instance->DATA = *((uint16_t *)hspi->pTxBuffPtr); + hspi->pTxBuffPtr += sizeof(uint16_t); + hspi->TxXferCount--; + /* Next Data is a reception (Rx). Tx not allowed */ + txallowed = 0U; + +#if (USE_SPI_CRC != 0U) + /* Enable CRC Transmission */ + if ((hspi->TxXferCount == 0U) && (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE)) + { + SET_BIT(hspi->Instance->CTRL1, SPI_CTRL1_CRCNXT); + } +#endif /* USE_SPI_CRC */ + } + + /* Check RXNE flag */ + if ((__DAL_SPI_GET_FLAG(hspi, SPI_FLAG_RXNE)) && (hspi->RxXferCount > 0U)) + { + *((uint16_t *)hspi->pRxBuffPtr) = (uint16_t)hspi->Instance->DATA; + hspi->pRxBuffPtr += sizeof(uint16_t); + hspi->RxXferCount--; + /* Next Data is a Transmission (Tx). Tx is allowed */ + txallowed = 1U; + } + if (((DAL_GetTick() - tickstart) >= Timeout) && (Timeout != DAL_MAX_DELAY)) + { + errorcode = DAL_TIMEOUT; + goto error; + } + } + } + /* Transmit and Receive data in 8 Bit mode */ + else + { + if ((hspi->Init.Mode == SPI_MODE_SLAVE) || (initial_TxXferCount == 0x01U)) + { + *((__IO uint8_t *)&hspi->Instance->DATA) = (*hspi->pTxBuffPtr); + hspi->pTxBuffPtr += sizeof(uint8_t); + hspi->TxXferCount--; + } + while ((hspi->TxXferCount > 0U) || (hspi->RxXferCount > 0U)) + { + /* Check TXE flag */ + if ((__DAL_SPI_GET_FLAG(hspi, SPI_FLAG_TXE)) && (hspi->TxXferCount > 0U) && (txallowed == 1U)) + { + *(__IO uint8_t *)&hspi->Instance->DATA = (*hspi->pTxBuffPtr); + hspi->pTxBuffPtr++; + hspi->TxXferCount--; + /* Next Data is a reception (Rx). Tx not allowed */ + txallowed = 0U; + +#if (USE_SPI_CRC != 0U) + /* Enable CRC Transmission */ + if ((hspi->TxXferCount == 0U) && (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE)) + { + SET_BIT(hspi->Instance->CTRL1, SPI_CTRL1_CRCNXT); + } +#endif /* USE_SPI_CRC */ + } + + /* Wait until RXNE flag is reset */ + if ((__DAL_SPI_GET_FLAG(hspi, SPI_FLAG_RXNE)) && (hspi->RxXferCount > 0U)) + { + (*(uint8_t *)hspi->pRxBuffPtr) = hspi->Instance->DATA; + hspi->pRxBuffPtr++; + hspi->RxXferCount--; + /* Next Data is a Transmission (Tx). Tx is allowed */ + txallowed = 1U; + } + if ((((DAL_GetTick() - tickstart) >= Timeout) && ((Timeout != DAL_MAX_DELAY))) || (Timeout == 0U)) + { + errorcode = DAL_TIMEOUT; + goto error; + } + } + } + +#if (USE_SPI_CRC != 0U) + /* Read CRC from DATA to close CRC calculation process */ + if (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) + { + /* Wait until TXE flag */ + if (SPI_WaitFlagStateUntilTimeout(hspi, SPI_FLAG_RXNE, SET, Timeout, tickstart) != DAL_OK) + { + /* Error on the CRC reception */ + SET_BIT(hspi->ErrorCode, DAL_SPI_ERROR_CRC); + errorcode = DAL_TIMEOUT; + goto error; + } + /* Read CRC */ + tmpreg = READ_REG(hspi->Instance->DATA); + /* To avoid GCC warning */ + UNUSED(tmpreg); + } + + /* Check if CRC error occurred */ + if (__DAL_SPI_GET_FLAG(hspi, SPI_FLAG_CRCERR)) + { + SET_BIT(hspi->ErrorCode, DAL_SPI_ERROR_CRC); + /* Clear CRC Flag */ + __DAL_SPI_CLEAR_CRCERRFLAG(hspi); + + errorcode = DAL_ERROR; + } +#endif /* USE_SPI_CRC */ + + /* Check the end of the transaction */ + if (SPI_EndRxTxTransaction(hspi, Timeout, tickstart) != DAL_OK) + { + errorcode = DAL_ERROR; + hspi->ErrorCode = DAL_SPI_ERROR_FLAG; + goto error; + } + + /* Clear overrun flag in 2 Lines communication mode because received is not read */ + if (hspi->Init.Direction == SPI_DIRECTION_2LINES) + { + __DAL_SPI_CLEAR_OVRFLAG(hspi); + } + +error : + hspi->State = DAL_SPI_STATE_READY; + __DAL_UNLOCK(hspi); + return errorcode; +} + +/** + * @brief Transmit an amount of data in non-blocking mode with Interrupt. + * @param hspi pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @param pData pointer to data buffer + * @param Size amount of data to be sent + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SPI_Transmit_IT(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size) +{ + DAL_StatusTypeDef errorcode = DAL_OK; + + /* Check Direction parameter */ + ASSERT_PARAM(IS_SPI_DIRECTION_2LINES_OR_1LINE(hspi->Init.Direction)); + + /* Process Locked */ + __DAL_LOCK(hspi); + + if ((pData == NULL) || (Size == 0U)) + { + errorcode = DAL_ERROR; + goto error; + } + + if (hspi->State != DAL_SPI_STATE_READY) + { + errorcode = DAL_BUSY; + goto error; + } + + /* Set the transaction information */ + hspi->State = DAL_SPI_STATE_BUSY_TX; + hspi->ErrorCode = DAL_SPI_ERROR_NONE; + hspi->pTxBuffPtr = (uint8_t *)pData; + hspi->TxXferSize = Size; + hspi->TxXferCount = Size; + + /* Init field not used in handle to zero */ + hspi->pRxBuffPtr = (uint8_t *)NULL; + hspi->RxXferSize = 0U; + hspi->RxXferCount = 0U; + hspi->RxISR = NULL; + + /* Set the function for IT treatment */ + if (hspi->Init.DataSize > SPI_DATASIZE_8BIT) + { + hspi->TxISR = SPI_TxISR_16BIT; + } + else + { + hspi->TxISR = SPI_TxISR_8BIT; + } + + /* Configure communication direction : 1Line */ + if (hspi->Init.Direction == SPI_DIRECTION_1LINE) + { + /* Disable SPI Peripheral before set 1Line direction (BIDIOE bit) */ + __DAL_SPI_DISABLE(hspi); + SPI_1LINE_TX(hspi); + } + +#if (USE_SPI_CRC != 0U) + /* Reset CRC Calculation */ + if (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) + { + SPI_RESET_CRC(hspi); + } +#endif /* USE_SPI_CRC */ + + /* Enable TXE and ERR interrupt */ + __DAL_SPI_ENABLE_IT(hspi, (SPI_IT_TXE | SPI_IT_ERR)); + + + /* Check if the SPI is already enabled */ + if ((hspi->Instance->CTRL1 & SPI_CTRL1_SPIEN) != SPI_CTRL1_SPIEN) + { + /* Enable SPI peripheral */ + __DAL_SPI_ENABLE(hspi); + } + +error : + __DAL_UNLOCK(hspi); + return errorcode; +} + +/** + * @brief Receive an amount of data in non-blocking mode with Interrupt. + * @param hspi pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @param pData pointer to data buffer + * @param Size amount of data to be sent + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SPI_Receive_IT(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size) +{ + DAL_StatusTypeDef errorcode = DAL_OK; + + if ((hspi->Init.Direction == SPI_DIRECTION_2LINES) && (hspi->Init.Mode == SPI_MODE_MASTER)) + { + hspi->State = DAL_SPI_STATE_BUSY_RX; + /* Call transmit-receive function to send Dummy data on Tx line and generate clock on CLK line */ + return DAL_SPI_TransmitReceive_IT(hspi, pData, pData, Size); + } + + /* Process Locked */ + __DAL_LOCK(hspi); + + if (hspi->State != DAL_SPI_STATE_READY) + { + errorcode = DAL_BUSY; + goto error; + } + + if ((pData == NULL) || (Size == 0U)) + { + errorcode = DAL_ERROR; + goto error; + } + + /* Set the transaction information */ + hspi->State = DAL_SPI_STATE_BUSY_RX; + hspi->ErrorCode = DAL_SPI_ERROR_NONE; + hspi->pRxBuffPtr = (uint8_t *)pData; + hspi->RxXferSize = Size; + hspi->RxXferCount = Size; + + /* Init field not used in handle to zero */ + hspi->pTxBuffPtr = (uint8_t *)NULL; + hspi->TxXferSize = 0U; + hspi->TxXferCount = 0U; + hspi->TxISR = NULL; + + /* Set the function for IT treatment */ + if (hspi->Init.DataSize > SPI_DATASIZE_8BIT) + { + hspi->RxISR = SPI_RxISR_16BIT; + } + else + { + hspi->RxISR = SPI_RxISR_8BIT; + } + + /* Configure communication direction : 1Line */ + if (hspi->Init.Direction == SPI_DIRECTION_1LINE) + { + /* Disable SPI Peripheral before set 1Line direction (BIDIOE bit) */ + __DAL_SPI_DISABLE(hspi); + SPI_1LINE_RX(hspi); + } + +#if (USE_SPI_CRC != 0U) + /* Reset CRC Calculation */ + if (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) + { + SPI_RESET_CRC(hspi); + } +#endif /* USE_SPI_CRC */ + + /* Enable TXE and ERR interrupt */ + __DAL_SPI_ENABLE_IT(hspi, (SPI_IT_RXNE | SPI_IT_ERR)); + + /* Note : The SPI must be enabled after unlocking current process + to avoid the risk of SPI interrupt handle execution before current + process unlock */ + + /* Check if the SPI is already enabled */ + if ((hspi->Instance->CTRL1 & SPI_CTRL1_SPIEN) != SPI_CTRL1_SPIEN) + { + /* Enable SPI peripheral */ + __DAL_SPI_ENABLE(hspi); + } + +error : + /* Process Unlocked */ + __DAL_UNLOCK(hspi); + return errorcode; +} + +/** + * @brief Transmit and Receive an amount of data in non-blocking mode with Interrupt. + * @param hspi pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @param pTxData pointer to transmission data buffer + * @param pRxData pointer to reception data buffer + * @param Size amount of data to be sent and received + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SPI_TransmitReceive_IT(SPI_HandleTypeDef *hspi, uint8_t *pTxData, uint8_t *pRxData, uint16_t Size) +{ + uint32_t tmp_mode; + DAL_SPI_StateTypeDef tmp_state; + DAL_StatusTypeDef errorcode = DAL_OK; + + /* Check Direction parameter */ + ASSERT_PARAM(IS_SPI_DIRECTION_2LINES(hspi->Init.Direction)); + + /* Process locked */ + __DAL_LOCK(hspi); + + /* Init temporary variables */ + tmp_state = hspi->State; + tmp_mode = hspi->Init.Mode; + + if (!((tmp_state == DAL_SPI_STATE_READY) || \ + ((tmp_mode == SPI_MODE_MASTER) && (hspi->Init.Direction == SPI_DIRECTION_2LINES) && (tmp_state == DAL_SPI_STATE_BUSY_RX)))) + { + errorcode = DAL_BUSY; + goto error; + } + + if ((pTxData == NULL) || (pRxData == NULL) || (Size == 0U)) + { + errorcode = DAL_ERROR; + goto error; + } + + /* Don't overwrite in case of DAL_SPI_STATE_BUSY_RX */ + if (hspi->State != DAL_SPI_STATE_BUSY_RX) + { + hspi->State = DAL_SPI_STATE_BUSY_TX_RX; + } + + /* Set the transaction information */ + hspi->ErrorCode = DAL_SPI_ERROR_NONE; + hspi->pTxBuffPtr = (uint8_t *)pTxData; + hspi->TxXferSize = Size; + hspi->TxXferCount = Size; + hspi->pRxBuffPtr = (uint8_t *)pRxData; + hspi->RxXferSize = Size; + hspi->RxXferCount = Size; + + /* Set the function for IT treatment */ + if (hspi->Init.DataSize > SPI_DATASIZE_8BIT) + { + hspi->RxISR = SPI_2linesRxISR_16BIT; + hspi->TxISR = SPI_2linesTxISR_16BIT; + } + else + { + hspi->RxISR = SPI_2linesRxISR_8BIT; + hspi->TxISR = SPI_2linesTxISR_8BIT; + } + +#if (USE_SPI_CRC != 0U) + /* Reset CRC Calculation */ + if (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) + { + SPI_RESET_CRC(hspi); + } +#endif /* USE_SPI_CRC */ + + /* Enable TXE, RXNE and ERR interrupt */ + __DAL_SPI_ENABLE_IT(hspi, (SPI_IT_TXE | SPI_IT_RXNE | SPI_IT_ERR)); + + /* Check if the SPI is already enabled */ + if ((hspi->Instance->CTRL1 & SPI_CTRL1_SPIEN) != SPI_CTRL1_SPIEN) + { + /* Enable SPI peripheral */ + __DAL_SPI_ENABLE(hspi); + } + +error : + /* Process Unlocked */ + __DAL_UNLOCK(hspi); + return errorcode; +} + +/** + * @brief Transmit an amount of data in non-blocking mode with DMA. + * @param hspi pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @param pData pointer to data buffer + * @param Size amount of data to be sent + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SPI_Transmit_DMA(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size) +{ + DAL_StatusTypeDef errorcode = DAL_OK; + + /* Check tx dma handle */ + ASSERT_PARAM(IS_SPI_DMA_HANDLE(hspi->hdmatx)); + + /* Check Direction parameter */ + ASSERT_PARAM(IS_SPI_DIRECTION_2LINES_OR_1LINE(hspi->Init.Direction)); + + /* Process Locked */ + __DAL_LOCK(hspi); + + if (hspi->State != DAL_SPI_STATE_READY) + { + errorcode = DAL_BUSY; + goto error; + } + + if ((pData == NULL) || (Size == 0U)) + { + errorcode = DAL_ERROR; + goto error; + } + + /* Set the transaction information */ + hspi->State = DAL_SPI_STATE_BUSY_TX; + hspi->ErrorCode = DAL_SPI_ERROR_NONE; + hspi->pTxBuffPtr = (uint8_t *)pData; + hspi->TxXferSize = Size; + hspi->TxXferCount = Size; + + /* Init field not used in handle to zero */ + hspi->pRxBuffPtr = (uint8_t *)NULL; + hspi->TxISR = NULL; + hspi->RxISR = NULL; + hspi->RxXferSize = 0U; + hspi->RxXferCount = 0U; + + /* Configure communication direction : 1Line */ + if (hspi->Init.Direction == SPI_DIRECTION_1LINE) + { + /* Disable SPI Peripheral before set 1Line direction (BIDIOE bit) */ + __DAL_SPI_DISABLE(hspi); + SPI_1LINE_TX(hspi); + } + +#if (USE_SPI_CRC != 0U) + /* Reset CRC Calculation */ + if (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) + { + SPI_RESET_CRC(hspi); + } +#endif /* USE_SPI_CRC */ + + /* Set the SPI TxDMA Half transfer complete callback */ + hspi->hdmatx->XferHalfCpltCallback = SPI_DMAHalfTransmitCplt; + + /* Set the SPI TxDMA transfer complete callback */ + hspi->hdmatx->XferCpltCallback = SPI_DMATransmitCplt; + + /* Set the DMA error callback */ + hspi->hdmatx->XferErrorCallback = SPI_DMAError; + + /* Set the DMA AbortCpltCallback */ + hspi->hdmatx->XferAbortCallback = NULL; + + /* Enable the Tx DMA Stream/Channel */ + if (DAL_OK != DAL_DMA_Start_IT(hspi->hdmatx, (uint32_t)hspi->pTxBuffPtr, (uint32_t)&hspi->Instance->DATA, + hspi->TxXferCount)) + { + /* Update SPI error code */ + SET_BIT(hspi->ErrorCode, DAL_SPI_ERROR_DMA); + errorcode = DAL_ERROR; + + hspi->State = DAL_SPI_STATE_READY; + goto error; + } + + /* Check if the SPI is already enabled */ + if ((hspi->Instance->CTRL1 & SPI_CTRL1_SPIEN) != SPI_CTRL1_SPIEN) + { + /* Enable SPI peripheral */ + __DAL_SPI_ENABLE(hspi); + } + + /* Enable the SPI Error Interrupt Bit */ + __DAL_SPI_ENABLE_IT(hspi, (SPI_IT_ERR)); + + /* Enable Tx DMA Request */ + SET_BIT(hspi->Instance->CTRL2, SPI_CTRL2_TXDEN); + +error : + /* Process Unlocked */ + __DAL_UNLOCK(hspi); + return errorcode; +} + +/** + * @brief Receive an amount of data in non-blocking mode with DMA. + * @note In case of MASTER mode and SPI_DIRECTION_2LINES direction, hdmatx shall be defined. + * @param hspi pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @param pData pointer to data buffer + * @note When the CRC feature is enabled the pData Length must be Size + 1. + * @param Size amount of data to be sent + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SPI_Receive_DMA(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size) +{ + DAL_StatusTypeDef errorcode = DAL_OK; + + /* Check rx dma handle */ + ASSERT_PARAM(IS_SPI_DMA_HANDLE(hspi->hdmarx)); + + if ((hspi->Init.Direction == SPI_DIRECTION_2LINES) && (hspi->Init.Mode == SPI_MODE_MASTER)) + { + hspi->State = DAL_SPI_STATE_BUSY_RX; + + /* Check tx dma handle */ + ASSERT_PARAM(IS_SPI_DMA_HANDLE(hspi->hdmatx)); + + /* Call transmit-receive function to send Dummy data on Tx line and generate clock on CLK line */ + return DAL_SPI_TransmitReceive_DMA(hspi, pData, pData, Size); + } + + /* Process Locked */ + __DAL_LOCK(hspi); + + if (hspi->State != DAL_SPI_STATE_READY) + { + errorcode = DAL_BUSY; + goto error; + } + + if ((pData == NULL) || (Size == 0U)) + { + errorcode = DAL_ERROR; + goto error; + } + + /* Set the transaction information */ + hspi->State = DAL_SPI_STATE_BUSY_RX; + hspi->ErrorCode = DAL_SPI_ERROR_NONE; + hspi->pRxBuffPtr = (uint8_t *)pData; + hspi->RxXferSize = Size; + hspi->RxXferCount = Size; + + /*Init field not used in handle to zero */ + hspi->RxISR = NULL; + hspi->TxISR = NULL; + hspi->TxXferSize = 0U; + hspi->TxXferCount = 0U; + + /* Configure communication direction : 1Line */ + if (hspi->Init.Direction == SPI_DIRECTION_1LINE) + { + /* Disable SPI Peripheral before set 1Line direction (BIDIOE bit) */ + __DAL_SPI_DISABLE(hspi); + SPI_1LINE_RX(hspi); + } + +#if (USE_SPI_CRC != 0U) + /* Reset CRC Calculation */ + if (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) + { + SPI_RESET_CRC(hspi); + } +#endif /* USE_SPI_CRC */ + + /* Set the SPI RxDMA Half transfer complete callback */ + hspi->hdmarx->XferHalfCpltCallback = SPI_DMAHalfReceiveCplt; + + /* Set the SPI Rx DMA transfer complete callback */ + hspi->hdmarx->XferCpltCallback = SPI_DMAReceiveCplt; + + /* Set the DMA error callback */ + hspi->hdmarx->XferErrorCallback = SPI_DMAError; + + /* Set the DMA AbortCpltCallback */ + hspi->hdmarx->XferAbortCallback = NULL; + + /* Enable the Rx DMA Stream/Channel */ + if (DAL_OK != DAL_DMA_Start_IT(hspi->hdmarx, (uint32_t)&hspi->Instance->DATA, (uint32_t)hspi->pRxBuffPtr, + hspi->RxXferCount)) + { + /* Update SPI error code */ + SET_BIT(hspi->ErrorCode, DAL_SPI_ERROR_DMA); + errorcode = DAL_ERROR; + + hspi->State = DAL_SPI_STATE_READY; + goto error; + } + + /* Check if the SPI is already enabled */ + if ((hspi->Instance->CTRL1 & SPI_CTRL1_SPIEN) != SPI_CTRL1_SPIEN) + { + /* Enable SPI peripheral */ + __DAL_SPI_ENABLE(hspi); + } + + /* Enable the SPI Error Interrupt Bit */ + __DAL_SPI_ENABLE_IT(hspi, (SPI_IT_ERR)); + + /* Enable Rx DMA Request */ + SET_BIT(hspi->Instance->CTRL2, SPI_CTRL2_RXDEN); + +error: + /* Process Unlocked */ + __DAL_UNLOCK(hspi); + return errorcode; +} + +/** + * @brief Transmit and Receive an amount of data in non-blocking mode with DMA. + * @param hspi pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @param pTxData pointer to transmission data buffer + * @param pRxData pointer to reception data buffer + * @note When the CRC feature is enabled the pRxData Length must be Size + 1 + * @param Size amount of data to be sent + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SPI_TransmitReceive_DMA(SPI_HandleTypeDef *hspi, uint8_t *pTxData, uint8_t *pRxData, + uint16_t Size) +{ + uint32_t tmp_mode; + DAL_SPI_StateTypeDef tmp_state; + DAL_StatusTypeDef errorcode = DAL_OK; + + /* Check rx & tx dma handles */ + ASSERT_PARAM(IS_SPI_DMA_HANDLE(hspi->hdmarx)); + ASSERT_PARAM(IS_SPI_DMA_HANDLE(hspi->hdmatx)); + + /* Check Direction parameter */ + ASSERT_PARAM(IS_SPI_DIRECTION_2LINES(hspi->Init.Direction)); + + /* Process locked */ + __DAL_LOCK(hspi); + + /* Init temporary variables */ + tmp_state = hspi->State; + tmp_mode = hspi->Init.Mode; + + if (!((tmp_state == DAL_SPI_STATE_READY) || + ((tmp_mode == SPI_MODE_MASTER) && (hspi->Init.Direction == SPI_DIRECTION_2LINES) && (tmp_state == DAL_SPI_STATE_BUSY_RX)))) + { + errorcode = DAL_BUSY; + goto error; + } + + if ((pTxData == NULL) || (pRxData == NULL) || (Size == 0U)) + { + errorcode = DAL_ERROR; + goto error; + } + + /* Don't overwrite in case of DAL_SPI_STATE_BUSY_RX */ + if (hspi->State != DAL_SPI_STATE_BUSY_RX) + { + hspi->State = DAL_SPI_STATE_BUSY_TX_RX; + } + + /* Set the transaction information */ + hspi->ErrorCode = DAL_SPI_ERROR_NONE; + hspi->pTxBuffPtr = (uint8_t *)pTxData; + hspi->TxXferSize = Size; + hspi->TxXferCount = Size; + hspi->pRxBuffPtr = (uint8_t *)pRxData; + hspi->RxXferSize = Size; + hspi->RxXferCount = Size; + + /* Init field not used in handle to zero */ + hspi->RxISR = NULL; + hspi->TxISR = NULL; + +#if (USE_SPI_CRC != 0U) + /* Reset CRC Calculation */ + if (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) + { + SPI_RESET_CRC(hspi); + } +#endif /* USE_SPI_CRC */ + + /* Check if we are in Rx only or in Rx/Tx Mode and configure the DMA transfer complete callback */ + if (hspi->State == DAL_SPI_STATE_BUSY_RX) + { + /* Set the SPI Rx DMA Half transfer complete callback */ + hspi->hdmarx->XferHalfCpltCallback = SPI_DMAHalfReceiveCplt; + hspi->hdmarx->XferCpltCallback = SPI_DMAReceiveCplt; + } + else + { + /* Set the SPI Tx/Rx DMA Half transfer complete callback */ + hspi->hdmarx->XferHalfCpltCallback = SPI_DMAHalfTransmitReceiveCplt; + hspi->hdmarx->XferCpltCallback = SPI_DMATransmitReceiveCplt; + } + + /* Set the DMA error callback */ + hspi->hdmarx->XferErrorCallback = SPI_DMAError; + + /* Set the DMA AbortCpltCallback */ + hspi->hdmarx->XferAbortCallback = NULL; + + /* Enable the Rx DMA Stream/Channel */ + if (DAL_OK != DAL_DMA_Start_IT(hspi->hdmarx, (uint32_t)&hspi->Instance->DATA, (uint32_t)hspi->pRxBuffPtr, + hspi->RxXferCount)) + { + /* Update SPI error code */ + SET_BIT(hspi->ErrorCode, DAL_SPI_ERROR_DMA); + errorcode = DAL_ERROR; + + hspi->State = DAL_SPI_STATE_READY; + goto error; + } + + /* Enable Rx DMA Request */ + SET_BIT(hspi->Instance->CTRL2, SPI_CTRL2_RXDEN); + + /* Set the SPI Tx DMA transfer complete callback as NULL because the communication closing + is performed in DMA reception complete callback */ + hspi->hdmatx->XferHalfCpltCallback = NULL; + hspi->hdmatx->XferCpltCallback = NULL; + hspi->hdmatx->XferErrorCallback = NULL; + hspi->hdmatx->XferAbortCallback = NULL; + + /* Enable the Tx DMA Stream/Channel */ + if (DAL_OK != DAL_DMA_Start_IT(hspi->hdmatx, (uint32_t)hspi->pTxBuffPtr, (uint32_t)&hspi->Instance->DATA, + hspi->TxXferCount)) + { + /* Update SPI error code */ + SET_BIT(hspi->ErrorCode, DAL_SPI_ERROR_DMA); + errorcode = DAL_ERROR; + + hspi->State = DAL_SPI_STATE_READY; + goto error; + } + + /* Check if the SPI is already enabled */ + if ((hspi->Instance->CTRL1 & SPI_CTRL1_SPIEN) != SPI_CTRL1_SPIEN) + { + /* Enable SPI peripheral */ + __DAL_SPI_ENABLE(hspi); + } + /* Enable the SPI Error Interrupt Bit */ + __DAL_SPI_ENABLE_IT(hspi, (SPI_IT_ERR)); + + /* Enable Tx DMA Request */ + SET_BIT(hspi->Instance->CTRL2, SPI_CTRL2_TXDEN); + +error : + /* Process Unlocked */ + __DAL_UNLOCK(hspi); + return errorcode; +} + +/** + * @brief Abort ongoing transfer (blocking mode). + * @param hspi SPI handle. + * @note This procedure could be used for aborting any ongoing transfer (Tx and Rx), + * started in Interrupt or DMA mode. + * This procedure performs following operations : + * - Disable SPI Interrupts (depending of transfer direction) + * - Disable the DMA transfer in the peripheral register (if enabled) + * - Abort DMA transfer by calling DAL_DMA_Abort (in case of transfer in DMA mode) + * - Set handle State to READY + * @note This procedure is executed in blocking mode : when exiting function, Abort is considered as completed. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SPI_Abort(SPI_HandleTypeDef *hspi) +{ + DAL_StatusTypeDef errorcode; + __IO uint32_t count; + __IO uint32_t resetcount; + + /* Initialized local variable */ + errorcode = DAL_OK; + resetcount = SPI_DEFAULT_TIMEOUT * (SystemCoreClock / 24U / 1000U); + count = resetcount; + + /* Clear ERRIEN interrupt to avoid error interrupts generation during Abort procedure */ + CLEAR_BIT(hspi->Instance->CTRL2, SPI_CTRL2_ERRIEN); + + /* Disable TXBEIEN, RXBNEIEN and ERRIEN(mode fault event, overrun error, TI frame error) interrupts */ + if (DAL_IS_BIT_SET(hspi->Instance->CTRL2, SPI_CTRL2_TXBEIEN)) + { + hspi->TxISR = SPI_AbortTx_ISR; + /* Wait DAL_SPI_STATE_ABORT state */ + do + { + if (count == 0U) + { + SET_BIT(hspi->ErrorCode, DAL_SPI_ERROR_ABORT); + break; + } + count--; + } while (hspi->State != DAL_SPI_STATE_ABORT); + /* Reset Timeout Counter */ + count = resetcount; + } + + if (DAL_IS_BIT_SET(hspi->Instance->CTRL2, SPI_CTRL2_RXBNEIEN)) + { + hspi->RxISR = SPI_AbortRx_ISR; + /* Wait DAL_SPI_STATE_ABORT state */ + do + { + if (count == 0U) + { + SET_BIT(hspi->ErrorCode, DAL_SPI_ERROR_ABORT); + break; + } + count--; + } while (hspi->State != DAL_SPI_STATE_ABORT); + /* Reset Timeout Counter */ + count = resetcount; + } + + /* Disable the SPI DMA Tx request if enabled */ + if (DAL_IS_BIT_SET(hspi->Instance->CTRL2, SPI_CTRL2_TXDEN)) + { + /* Abort the SPI DMA Tx Stream/Channel : use blocking DMA Abort API (no callback) */ + if (hspi->hdmatx != NULL) + { + /* Set the SPI DMA Abort callback : + will lead to call DAL_SPI_AbortCpltCallback() at end of DMA abort procedure */ + hspi->hdmatx->XferAbortCallback = NULL; + + /* Abort DMA Tx Handle linked to SPI Peripheral */ + if (DAL_DMA_Abort(hspi->hdmatx) != DAL_OK) + { + hspi->ErrorCode = DAL_SPI_ERROR_ABORT; + } + + /* Disable Tx DMA Request */ + CLEAR_BIT(hspi->Instance->CTRL2, (SPI_CTRL2_TXDEN)); + + /* Wait until TXE flag is set */ + do + { + if (count == 0U) + { + SET_BIT(hspi->ErrorCode, DAL_SPI_ERROR_ABORT); + break; + } + count--; + } while ((hspi->Instance->STS & SPI_FLAG_TXE) == RESET); + } + } + + /* Disable the SPI DMA Rx request if enabled */ + if (DAL_IS_BIT_SET(hspi->Instance->CTRL2, SPI_CTRL2_RXDEN)) + { + /* Abort the SPI DMA Rx Stream/Channel : use blocking DMA Abort API (no callback) */ + if (hspi->hdmarx != NULL) + { + /* Set the SPI DMA Abort callback : + will lead to call DAL_SPI_AbortCpltCallback() at end of DMA abort procedure */ + hspi->hdmarx->XferAbortCallback = NULL; + + /* Abort DMA Rx Handle linked to SPI Peripheral */ + if (DAL_DMA_Abort(hspi->hdmarx) != DAL_OK) + { + hspi->ErrorCode = DAL_SPI_ERROR_ABORT; + } + + /* Disable peripheral */ + __DAL_SPI_DISABLE(hspi); + + /* Disable Rx DMA Request */ + CLEAR_BIT(hspi->Instance->CTRL2, (SPI_CTRL2_RXDEN)); + } + } + /* Reset Tx and Rx transfer counters */ + hspi->RxXferCount = 0U; + hspi->TxXferCount = 0U; + + /* Check error during Abort procedure */ + if (hspi->ErrorCode == DAL_SPI_ERROR_ABORT) + { + /* return DAL_Error in case of error during Abort procedure */ + errorcode = DAL_ERROR; + } + else + { + /* Reset errorCode */ + hspi->ErrorCode = DAL_SPI_ERROR_NONE; + } + + /* Clear the Error flags in the SR register */ + __DAL_SPI_CLEAR_OVRFLAG(hspi); + __DAL_SPI_CLEAR_FREFLAG(hspi); + + /* Restore hspi->state to ready */ + hspi->State = DAL_SPI_STATE_READY; + + return errorcode; +} + +/** + * @brief Abort ongoing transfer (Interrupt mode). + * @param hspi SPI handle. + * @note This procedure could be used for aborting any ongoing transfer (Tx and Rx), + * started in Interrupt or DMA mode. + * This procedure performs following operations : + * - Disable SPI Interrupts (depending of transfer direction) + * - Disable the DMA transfer in the peripheral register (if enabled) + * - Abort DMA transfer by calling DAL_DMA_Abort_IT (in case of transfer in DMA mode) + * - Set handle State to READY + * - At abort completion, call user abort complete callback + * @note This procedure is executed in Interrupt mode, meaning that abort procedure could be + * considered as completed only when user abort complete callback is executed (not when exiting function). + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SPI_Abort_IT(SPI_HandleTypeDef *hspi) +{ + DAL_StatusTypeDef errorcode; + uint32_t abortcplt ; + __IO uint32_t count; + __IO uint32_t resetcount; + + /* Initialized local variable */ + errorcode = DAL_OK; + abortcplt = 1U; + resetcount = SPI_DEFAULT_TIMEOUT * (SystemCoreClock / 24U / 1000U); + count = resetcount; + + /* Clear ERRIE interrupt to avoid error interrupts generation during Abort procedure */ + CLEAR_BIT(hspi->Instance->CTRL2, SPI_CTRL2_ERRIEN); + + /* Change Rx and Tx Irq Handler to Disable TXEIE, RXNEIE and ERRIE interrupts */ + if (DAL_IS_BIT_SET(hspi->Instance->CTRL2, SPI_CTRL2_TXBEIEN)) + { + hspi->TxISR = SPI_AbortTx_ISR; + /* Wait DAL_SPI_STATE_ABORT state */ + do + { + if (count == 0U) + { + SET_BIT(hspi->ErrorCode, DAL_SPI_ERROR_ABORT); + break; + } + count--; + } while (hspi->State != DAL_SPI_STATE_ABORT); + /* Reset Timeout Counter */ + count = resetcount; + } + + if (DAL_IS_BIT_SET(hspi->Instance->CTRL2, SPI_CTRL2_RXBNEIEN)) + { + hspi->RxISR = SPI_AbortRx_ISR; + /* Wait DAL_SPI_STATE_ABORT state */ + do + { + if (count == 0U) + { + SET_BIT(hspi->ErrorCode, DAL_SPI_ERROR_ABORT); + break; + } + count--; + } while (hspi->State != DAL_SPI_STATE_ABORT); + /* Reset Timeout Counter */ + count = resetcount; + } + + /* If DMA Tx and/or DMA Rx Handles are associated to SPI Handle, DMA Abort complete callbacks should be initialised + before any call to DMA Abort functions */ + /* DMA Tx Handle is valid */ + if (hspi->hdmatx != NULL) + { + /* Set DMA Abort Complete callback if UART DMA Tx request if enabled. + Otherwise, set it to NULL */ + if (DAL_IS_BIT_SET(hspi->Instance->CTRL2, SPI_CTRL2_TXDEN)) + { + hspi->hdmatx->XferAbortCallback = SPI_DMATxAbortCallback; + } + else + { + hspi->hdmatx->XferAbortCallback = NULL; + } + } + /* DMA Rx Handle is valid */ + if (hspi->hdmarx != NULL) + { + /* Set DMA Abort Complete callback if UART DMA Rx request if enabled. + Otherwise, set it to NULL */ + if (DAL_IS_BIT_SET(hspi->Instance->CTRL2, SPI_CTRL2_RXDEN)) + { + hspi->hdmarx->XferAbortCallback = SPI_DMARxAbortCallback; + } + else + { + hspi->hdmarx->XferAbortCallback = NULL; + } + } + + /* Disable the SPI DMA Tx request if enabled */ + if (DAL_IS_BIT_SET(hspi->Instance->CTRL2, SPI_CTRL2_TXDEN)) + { + /* Abort the SPI DMA Tx Stream/Channel */ + if (hspi->hdmatx != NULL) + { + /* Abort DMA Tx Handle linked to SPI Peripheral */ + if (DAL_DMA_Abort_IT(hspi->hdmatx) != DAL_OK) + { + hspi->hdmatx->XferAbortCallback = NULL; + hspi->ErrorCode = DAL_SPI_ERROR_ABORT; + } + else + { + abortcplt = 0U; + } + } + } + /* Disable the SPI DMA Rx request if enabled */ + if (DAL_IS_BIT_SET(hspi->Instance->CTRL2, SPI_CTRL2_RXDEN)) + { + /* Abort the SPI DMA Rx Stream/Channel */ + if (hspi->hdmarx != NULL) + { + /* Abort DMA Rx Handle linked to SPI Peripheral */ + if (DAL_DMA_Abort_IT(hspi->hdmarx) != DAL_OK) + { + hspi->hdmarx->XferAbortCallback = NULL; + hspi->ErrorCode = DAL_SPI_ERROR_ABORT; + } + else + { + abortcplt = 0U; + } + } + } + + if (abortcplt == 1U) + { + /* Reset Tx and Rx transfer counters */ + hspi->RxXferCount = 0U; + hspi->TxXferCount = 0U; + + /* Check error during Abort procedure */ + if (hspi->ErrorCode == DAL_SPI_ERROR_ABORT) + { + /* return DAL_Error in case of error during Abort procedure */ + errorcode = DAL_ERROR; + } + else + { + /* Reset errorCode */ + hspi->ErrorCode = DAL_SPI_ERROR_NONE; + } + + /* Clear the Error flags in the SR register */ + __DAL_SPI_CLEAR_OVRFLAG(hspi); + __DAL_SPI_CLEAR_FREFLAG(hspi); + + /* Restore hspi->State to Ready */ + hspi->State = DAL_SPI_STATE_READY; + + /* As no DMA to be aborted, call directly user Abort complete callback */ +#if (USE_DAL_SPI_REGISTER_CALLBACKS == 1U) + hspi->AbortCpltCallback(hspi); +#else + DAL_SPI_AbortCpltCallback(hspi); +#endif /* USE_DAL_SPI_REGISTER_CALLBACKS */ + } + + return errorcode; +} + +/** + * @brief Pause the DMA Transfer. + * @param hspi pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for the specified SPI module. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SPI_DMAPause(SPI_HandleTypeDef *hspi) +{ + /* Process Locked */ + __DAL_LOCK(hspi); + + /* Disable the SPI DMA Tx & Rx requests */ + CLEAR_BIT(hspi->Instance->CTRL2, SPI_CTRL2_TXDEN | SPI_CTRL2_RXDEN); + + /* Process Unlocked */ + __DAL_UNLOCK(hspi); + + return DAL_OK; +} + +/** + * @brief Resume the DMA Transfer. + * @param hspi pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for the specified SPI module. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SPI_DMAResume(SPI_HandleTypeDef *hspi) +{ + /* Process Locked */ + __DAL_LOCK(hspi); + + /* Enable the SPI DMA Tx & Rx requests */ + SET_BIT(hspi->Instance->CTRL2, SPI_CTRL2_TXDEN | SPI_CTRL2_RXDEN); + + /* Process Unlocked */ + __DAL_UNLOCK(hspi); + + return DAL_OK; +} + +/** + * @brief Stop the DMA Transfer. + * @param hspi pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for the specified SPI module. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SPI_DMAStop(SPI_HandleTypeDef *hspi) +{ + DAL_StatusTypeDef errorcode = DAL_OK; + /* The Lock is not implemented on this API to allow the user application + to call the DAL SPI API under callbacks DAL_SPI_TxCpltCallback() or DAL_SPI_RxCpltCallback() or DAL_SPI_TxRxCpltCallback(): + when calling DAL_DMA_Abort() API the DMA TX/RX Transfer complete interrupt is generated + and the correspond call back is executed DAL_SPI_TxCpltCallback() or DAL_SPI_RxCpltCallback() or DAL_SPI_TxRxCpltCallback() + */ + + /* Abort the SPI DMA tx Stream/Channel */ + if (hspi->hdmatx != NULL) + { + if (DAL_OK != DAL_DMA_Abort(hspi->hdmatx)) + { + SET_BIT(hspi->ErrorCode, DAL_SPI_ERROR_DMA); + errorcode = DAL_ERROR; + } + } + /* Abort the SPI DMA rx Stream/Channel */ + if (hspi->hdmarx != NULL) + { + if (DAL_OK != DAL_DMA_Abort(hspi->hdmarx)) + { + SET_BIT(hspi->ErrorCode, DAL_SPI_ERROR_DMA); + errorcode = DAL_ERROR; + } + } + + /* Disable the SPI DMA Tx & Rx requests */ + CLEAR_BIT(hspi->Instance->CTRL2, SPI_CTRL2_TXDEN | SPI_CTRL2_RXDEN); + hspi->State = DAL_SPI_STATE_READY; + return errorcode; +} + +/** + * @brief Handle SPI interrupt request. + * @param hspi pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for the specified SPI module. + * @retval None + */ +void DAL_SPI_IRQHandler(SPI_HandleTypeDef *hspi) +{ + uint32_t itsource = hspi->Instance->CTRL2; + uint32_t itflag = hspi->Instance->STS; + + /* SPI in mode Receiver ----------------------------------------------------*/ + if ((SPI_CHECK_FLAG(itflag, SPI_FLAG_OVR) == RESET) && + (SPI_CHECK_FLAG(itflag, SPI_FLAG_RXNE) != RESET) && (SPI_CHECK_IT_SOURCE(itsource, SPI_IT_RXNE) != RESET)) + { + hspi->RxISR(hspi); + return; + } + + /* SPI in mode Transmitter -------------------------------------------------*/ + if ((SPI_CHECK_FLAG(itflag, SPI_FLAG_TXE) != RESET) && (SPI_CHECK_IT_SOURCE(itsource, SPI_IT_TXE) != RESET)) + { + hspi->TxISR(hspi); + return; + } + + /* SPI in Error Treatment --------------------------------------------------*/ + if (((SPI_CHECK_FLAG(itflag, SPI_FLAG_MODF) != RESET) || (SPI_CHECK_FLAG(itflag, SPI_FLAG_OVR) != RESET) + || (SPI_CHECK_FLAG(itflag, SPI_FLAG_FRE) != RESET)) && (SPI_CHECK_IT_SOURCE(itsource, SPI_IT_ERR) != RESET)) + { + /* SPI Overrun error interrupt occurred ----------------------------------*/ + if (SPI_CHECK_FLAG(itflag, SPI_FLAG_OVR) != RESET) + { + if (hspi->State != DAL_SPI_STATE_BUSY_TX) + { + SET_BIT(hspi->ErrorCode, DAL_SPI_ERROR_OVR); + __DAL_SPI_CLEAR_OVRFLAG(hspi); + } + else + { + __DAL_SPI_CLEAR_OVRFLAG(hspi); + return; + } + } + + /* SPI Mode Fault error interrupt occurred -------------------------------*/ + if (SPI_CHECK_FLAG(itflag, SPI_FLAG_MODF) != RESET) + { + SET_BIT(hspi->ErrorCode, DAL_SPI_ERROR_MODF); + __DAL_SPI_CLEAR_MODFFLAG(hspi); + } + + /* SPI Frame error interrupt occurred ------------------------------------*/ + if (SPI_CHECK_FLAG(itflag, SPI_FLAG_FRE) != RESET) + { + SET_BIT(hspi->ErrorCode, DAL_SPI_ERROR_FRE); + __DAL_SPI_CLEAR_FREFLAG(hspi); + } + + if (hspi->ErrorCode != DAL_SPI_ERROR_NONE) + { + /* Disable all interrupts */ + __DAL_SPI_DISABLE_IT(hspi, SPI_IT_RXNE | SPI_IT_TXE | SPI_IT_ERR); + + hspi->State = DAL_SPI_STATE_READY; + /* Disable the SPI DMA requests if enabled */ + if ((DAL_IS_BIT_SET(itsource, SPI_CTRL2_TXDEN)) || (DAL_IS_BIT_SET(itsource, SPI_CTRL2_RXDEN))) + { + CLEAR_BIT(hspi->Instance->CTRL2, (SPI_CTRL2_TXDEN | SPI_CTRL2_RXDEN)); + + /* Abort the SPI DMA Rx channel */ + if (hspi->hdmarx != NULL) + { + /* Set the SPI DMA Abort callback : + will lead to call DAL_SPI_ErrorCallback() at end of DMA abort procedure */ + hspi->hdmarx->XferAbortCallback = SPI_DMAAbortOnError; + if (DAL_OK != DAL_DMA_Abort_IT(hspi->hdmarx)) + { + SET_BIT(hspi->ErrorCode, DAL_SPI_ERROR_ABORT); + } + } + /* Abort the SPI DMA Tx channel */ + if (hspi->hdmatx != NULL) + { + /* Set the SPI DMA Abort callback : + will lead to call DAL_SPI_ErrorCallback() at end of DMA abort procedure */ + hspi->hdmatx->XferAbortCallback = SPI_DMAAbortOnError; + if (DAL_OK != DAL_DMA_Abort_IT(hspi->hdmatx)) + { + SET_BIT(hspi->ErrorCode, DAL_SPI_ERROR_ABORT); + } + } + } + else + { + /* Call user error callback */ +#if (USE_DAL_SPI_REGISTER_CALLBACKS == 1U) + hspi->ErrorCallback(hspi); +#else + DAL_SPI_ErrorCallback(hspi); +#endif /* USE_DAL_SPI_REGISTER_CALLBACKS */ + } + } + return; + } +} + +/** + * @brief Tx Transfer completed callback. + * @param hspi pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @retval None + */ +__weak void DAL_SPI_TxCpltCallback(SPI_HandleTypeDef *hspi) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hspi); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_SPI_TxCpltCallback should be implemented in the user file + */ +} + +/** + * @brief Rx Transfer completed callback. + * @param hspi pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @retval None + */ +__weak void DAL_SPI_RxCpltCallback(SPI_HandleTypeDef *hspi) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hspi); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_SPI_RxCpltCallback should be implemented in the user file + */ +} + +/** + * @brief Tx and Rx Transfer completed callback. + * @param hspi pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @retval None + */ +__weak void DAL_SPI_TxRxCpltCallback(SPI_HandleTypeDef *hspi) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hspi); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_SPI_TxRxCpltCallback should be implemented in the user file + */ +} + +/** + * @brief Tx Half Transfer completed callback. + * @param hspi pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @retval None + */ +__weak void DAL_SPI_TxHalfCpltCallback(SPI_HandleTypeDef *hspi) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hspi); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_SPI_TxHalfCpltCallback should be implemented in the user file + */ +} + +/** + * @brief Rx Half Transfer completed callback. + * @param hspi pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @retval None + */ +__weak void DAL_SPI_RxHalfCpltCallback(SPI_HandleTypeDef *hspi) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hspi); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_SPI_RxHalfCpltCallback() should be implemented in the user file + */ +} + +/** + * @brief Tx and Rx Half Transfer callback. + * @param hspi pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @retval None + */ +__weak void DAL_SPI_TxRxHalfCpltCallback(SPI_HandleTypeDef *hspi) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hspi); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_SPI_TxRxHalfCpltCallback() should be implemented in the user file + */ +} + +/** + * @brief SPI error callback. + * @param hspi pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @retval None + */ +__weak void DAL_SPI_ErrorCallback(SPI_HandleTypeDef *hspi) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hspi); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_SPI_ErrorCallback should be implemented in the user file + */ + /* NOTE : The ErrorCode parameter in the hspi handle is updated by the SPI processes + and user can use DAL_SPI_GetError() API to check the latest error occurred + */ +} + +/** + * @brief SPI Abort Complete callback. + * @param hspi SPI handle. + * @retval None + */ +__weak void DAL_SPI_AbortCpltCallback(SPI_HandleTypeDef *hspi) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hspi); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_SPI_AbortCpltCallback can be implemented in the user file. + */ +} + +/** + * @} + */ + +/** @defgroup SPI_Exported_Functions_Group3 Peripheral State and Errors functions + * @brief SPI control functions + * +@verbatim + =============================================================================== + ##### Peripheral State and Errors functions ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to control the SPI. + (+) DAL_SPI_GetState() API can be helpful to check in run-time the state of the SPI peripheral + (+) DAL_SPI_GetError() check in run-time Errors occurring during communication +@endverbatim + * @{ + */ + +/** + * @brief Return the SPI handle state. + * @param hspi pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @retval SPI state + */ +DAL_SPI_StateTypeDef DAL_SPI_GetState(SPI_HandleTypeDef *hspi) +{ + /* Return SPI handle state */ + return hspi->State; +} + +/** + * @brief Return the SPI error code. + * @param hspi pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @retval SPI error code in bitmap format + */ +uint32_t DAL_SPI_GetError(SPI_HandleTypeDef *hspi) +{ + /* Return SPI ErrorCode */ + return hspi->ErrorCode; +} + +/** + * @} + */ + +/** + * @} + */ + +/** @addtogroup SPI_Private_Functions + * @brief Private functions + * @{ + */ + +/** + * @brief DMA SPI transmit process complete callback. + * @param hdma pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +static void SPI_DMATransmitCplt(DMA_HandleTypeDef *hdma) +{ + SPI_HandleTypeDef *hspi = (SPI_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent); /* Derogation MISRAC2012-Rule-11.5 */ + uint32_t tickstart; + + /* Init tickstart for timeout management*/ + tickstart = DAL_GetTick(); + + /* DMA Normal Mode */ + if ((hdma->Instance->SCFG & DMA_SCFGx_CIRCMEN) != DMA_SCFGx_CIRCMEN) + { + /* Disable ERR interrupt */ + __DAL_SPI_DISABLE_IT(hspi, SPI_IT_ERR); + + /* Disable Tx DMA Request */ + CLEAR_BIT(hspi->Instance->CTRL2, SPI_CTRL2_TXDEN); + + /* Check the end of the transaction */ + if (SPI_EndRxTxTransaction(hspi, SPI_DEFAULT_TIMEOUT, tickstart) != DAL_OK) + { + SET_BIT(hspi->ErrorCode, DAL_SPI_ERROR_FLAG); + } + + /* Clear overrun flag in 2 Lines communication mode because received data is not read */ + if (hspi->Init.Direction == SPI_DIRECTION_2LINES) + { + __DAL_SPI_CLEAR_OVRFLAG(hspi); + } + + hspi->TxXferCount = 0U; + hspi->State = DAL_SPI_STATE_READY; + + if (hspi->ErrorCode != DAL_SPI_ERROR_NONE) + { + /* Call user error callback */ +#if (USE_DAL_SPI_REGISTER_CALLBACKS == 1U) + hspi->ErrorCallback(hspi); +#else + DAL_SPI_ErrorCallback(hspi); +#endif /* USE_DAL_SPI_REGISTER_CALLBACKS */ + return; + } + } + /* Call user Tx complete callback */ +#if (USE_DAL_SPI_REGISTER_CALLBACKS == 1U) + hspi->TxCpltCallback(hspi); +#else + DAL_SPI_TxCpltCallback(hspi); +#endif /* USE_DAL_SPI_REGISTER_CALLBACKS */ +} + +/** + * @brief DMA SPI receive process complete callback. + * @param hdma pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +static void SPI_DMAReceiveCplt(DMA_HandleTypeDef *hdma) +{ + SPI_HandleTypeDef *hspi = (SPI_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent); /* Derogation MISRAC2012-Rule-11.5 */ + uint32_t tickstart; +#if (USE_SPI_CRC != 0U) + __IO uint32_t tmpreg = 0U; +#endif /* USE_SPI_CRC */ + + /* Init tickstart for timeout management*/ + tickstart = DAL_GetTick(); + + /* DMA Normal Mode */ + if ((hdma->Instance->SCFG & DMA_SCFGx_CIRCMEN) != DMA_SCFGx_CIRCMEN) + { + /* Disable ERR interrupt */ + __DAL_SPI_DISABLE_IT(hspi, SPI_IT_ERR); + +#if (USE_SPI_CRC != 0U) + /* CRC handling */ + if (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) + { + /* Wait until RXNE flag */ + if (SPI_WaitFlagStateUntilTimeout(hspi, SPI_FLAG_RXNE, SET, SPI_DEFAULT_TIMEOUT, tickstart) != DAL_OK) + { + /* Error on the CRC reception */ + SET_BIT(hspi->ErrorCode, DAL_SPI_ERROR_CRC); + } + /* Read CRC */ + tmpreg = READ_REG(hspi->Instance->DATA); + /* To avoid GCC warning */ + UNUSED(tmpreg); + } +#endif /* USE_SPI_CRC */ + + /* Check if we are in Master RX 2 line mode */ + if ((hspi->Init.Direction == SPI_DIRECTION_2LINES) && (hspi->Init.Mode == SPI_MODE_MASTER)) + { + /* Disable Rx/Tx DMA Request (done by default to handle the case master rx direction 2 lines) */ + CLEAR_BIT(hspi->Instance->CTRL2, SPI_CTRL2_TXDEN | SPI_CTRL2_RXDEN); + } + else + { + /* Normal case */ + CLEAR_BIT(hspi->Instance->CTRL2, SPI_CTRL2_RXDEN); + } + + /* Check the end of the transaction */ + if (SPI_EndRxTransaction(hspi, SPI_DEFAULT_TIMEOUT, tickstart) != DAL_OK) + { + hspi->ErrorCode = DAL_SPI_ERROR_FLAG; + } + + hspi->RxXferCount = 0U; + hspi->State = DAL_SPI_STATE_READY; + +#if (USE_SPI_CRC != 0U) + /* Check if CRC error occurred */ + if (__DAL_SPI_GET_FLAG(hspi, SPI_FLAG_CRCERR)) + { + SET_BIT(hspi->ErrorCode, DAL_SPI_ERROR_CRC); + __DAL_SPI_CLEAR_CRCERRFLAG(hspi); + } +#endif /* USE_SPI_CRC */ + + if (hspi->ErrorCode != DAL_SPI_ERROR_NONE) + { + /* Call user error callback */ +#if (USE_DAL_SPI_REGISTER_CALLBACKS == 1U) + hspi->ErrorCallback(hspi); +#else + DAL_SPI_ErrorCallback(hspi); +#endif /* USE_DAL_SPI_REGISTER_CALLBACKS */ + return; + } + } + /* Call user Rx complete callback */ +#if (USE_DAL_SPI_REGISTER_CALLBACKS == 1U) + hspi->RxCpltCallback(hspi); +#else + DAL_SPI_RxCpltCallback(hspi); +#endif /* USE_DAL_SPI_REGISTER_CALLBACKS */ +} + +/** + * @brief DMA SPI transmit receive process complete callback. + * @param hdma pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +static void SPI_DMATransmitReceiveCplt(DMA_HandleTypeDef *hdma) +{ + SPI_HandleTypeDef *hspi = (SPI_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent); /* Derogation MISRAC2012-Rule-11.5 */ + uint32_t tickstart; +#if (USE_SPI_CRC != 0U) + __IO uint32_t tmpreg = 0U; +#endif /* USE_SPI_CRC */ + + /* Init tickstart for timeout management*/ + tickstart = DAL_GetTick(); + + /* DMA Normal Mode */ + if ((hdma->Instance->SCFG & DMA_SCFGx_CIRCMEN) != DMA_SCFGx_CIRCMEN) + { + /* Disable ERR interrupt */ + __DAL_SPI_DISABLE_IT(hspi, SPI_IT_ERR); + +#if (USE_SPI_CRC != 0U) + /* CRC handling */ + if (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) + { + /* Wait the CRC data */ + if (SPI_WaitFlagStateUntilTimeout(hspi, SPI_FLAG_RXNE, SET, SPI_DEFAULT_TIMEOUT, tickstart) != DAL_OK) + { + SET_BIT(hspi->ErrorCode, DAL_SPI_ERROR_CRC); + } + /* Read CRC to Flush DATA and RXNE flag */ + tmpreg = READ_REG(hspi->Instance->DATA); + /* To avoid GCC warning */ + UNUSED(tmpreg); + } +#endif /* USE_SPI_CRC */ + + /* Check the end of the transaction */ + if (SPI_EndRxTxTransaction(hspi, SPI_DEFAULT_TIMEOUT, tickstart) != DAL_OK) + { + SET_BIT(hspi->ErrorCode, DAL_SPI_ERROR_FLAG); + } + + /* Disable Rx/Tx DMA Request */ + CLEAR_BIT(hspi->Instance->CTRL2, SPI_CTRL2_TXDEN | SPI_CTRL2_RXDEN); + + hspi->TxXferCount = 0U; + hspi->RxXferCount = 0U; + hspi->State = DAL_SPI_STATE_READY; + +#if (USE_SPI_CRC != 0U) + /* Check if CRC error occurred */ + if (__DAL_SPI_GET_FLAG(hspi, SPI_FLAG_CRCERR)) + { + SET_BIT(hspi->ErrorCode, DAL_SPI_ERROR_CRC); + __DAL_SPI_CLEAR_CRCERRFLAG(hspi); + } +#endif /* USE_SPI_CRC */ + + if (hspi->ErrorCode != DAL_SPI_ERROR_NONE) + { + /* Call user error callback */ +#if (USE_DAL_SPI_REGISTER_CALLBACKS == 1U) + hspi->ErrorCallback(hspi); +#else + DAL_SPI_ErrorCallback(hspi); +#endif /* USE_DAL_SPI_REGISTER_CALLBACKS */ + return; + } + } + /* Call user TxRx complete callback */ +#if (USE_DAL_SPI_REGISTER_CALLBACKS == 1U) + hspi->TxRxCpltCallback(hspi); +#else + DAL_SPI_TxRxCpltCallback(hspi); +#endif /* USE_DAL_SPI_REGISTER_CALLBACKS */ +} + +/** + * @brief DMA SPI half transmit process complete callback. + * @param hdma pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +static void SPI_DMAHalfTransmitCplt(DMA_HandleTypeDef *hdma) +{ + SPI_HandleTypeDef *hspi = (SPI_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent); /* Derogation MISRAC2012-Rule-11.5 */ + + /* Call user Tx half complete callback */ +#if (USE_DAL_SPI_REGISTER_CALLBACKS == 1U) + hspi->TxHalfCpltCallback(hspi); +#else + DAL_SPI_TxHalfCpltCallback(hspi); +#endif /* USE_DAL_SPI_REGISTER_CALLBACKS */ +} + +/** + * @brief DMA SPI half receive process complete callback + * @param hdma pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +static void SPI_DMAHalfReceiveCplt(DMA_HandleTypeDef *hdma) +{ + SPI_HandleTypeDef *hspi = (SPI_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent); /* Derogation MISRAC2012-Rule-11.5 */ + + /* Call user Rx half complete callback */ +#if (USE_DAL_SPI_REGISTER_CALLBACKS == 1U) + hspi->RxHalfCpltCallback(hspi); +#else + DAL_SPI_RxHalfCpltCallback(hspi); +#endif /* USE_DAL_SPI_REGISTER_CALLBACKS */ +} + +/** + * @brief DMA SPI half transmit receive process complete callback. + * @param hdma pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +static void SPI_DMAHalfTransmitReceiveCplt(DMA_HandleTypeDef *hdma) +{ + SPI_HandleTypeDef *hspi = (SPI_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent); /* Derogation MISRAC2012-Rule-11.5 */ + + /* Call user TxRx half complete callback */ +#if (USE_DAL_SPI_REGISTER_CALLBACKS == 1U) + hspi->TxRxHalfCpltCallback(hspi); +#else + DAL_SPI_TxRxHalfCpltCallback(hspi); +#endif /* USE_DAL_SPI_REGISTER_CALLBACKS */ +} + +/** + * @brief DMA SPI communication error callback. + * @param hdma pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +static void SPI_DMAError(DMA_HandleTypeDef *hdma) +{ + SPI_HandleTypeDef *hspi = (SPI_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent); /* Derogation MISRAC2012-Rule-11.5 */ + + /* Stop the disable DMA transfer on SPI side */ + CLEAR_BIT(hspi->Instance->CTRL2, SPI_CTRL2_TXDEN | SPI_CTRL2_RXDEN); + + SET_BIT(hspi->ErrorCode, DAL_SPI_ERROR_DMA); + hspi->State = DAL_SPI_STATE_READY; + /* Call user error callback */ +#if (USE_DAL_SPI_REGISTER_CALLBACKS == 1U) + hspi->ErrorCallback(hspi); +#else + DAL_SPI_ErrorCallback(hspi); +#endif /* USE_DAL_SPI_REGISTER_CALLBACKS */ +} + +/** + * @brief DMA SPI communication abort callback, when initiated by DAL services on Error + * (To be called at end of DMA Abort procedure following error occurrence). + * @param hdma DMA handle. + * @retval None + */ +static void SPI_DMAAbortOnError(DMA_HandleTypeDef *hdma) +{ + SPI_HandleTypeDef *hspi = (SPI_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent); /* Derogation MISRAC2012-Rule-11.5 */ + hspi->RxXferCount = 0U; + hspi->TxXferCount = 0U; + + /* Call user error callback */ +#if (USE_DAL_SPI_REGISTER_CALLBACKS == 1U) + hspi->ErrorCallback(hspi); +#else + DAL_SPI_ErrorCallback(hspi); +#endif /* USE_DAL_SPI_REGISTER_CALLBACKS */ +} + +/** + * @brief DMA SPI Tx communication abort callback, when initiated by user + * (To be called at end of DMA Tx Abort procedure following user abort request). + * @note When this callback is executed, User Abort complete call back is called only if no + * Abort still ongoing for Rx DMA Handle. + * @param hdma DMA handle. + * @retval None + */ +static void SPI_DMATxAbortCallback(DMA_HandleTypeDef *hdma) +{ + SPI_HandleTypeDef *hspi = (SPI_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent); /* Derogation MISRAC2012-Rule-11.5 */ + __IO uint32_t count; + + hspi->hdmatx->XferAbortCallback = NULL; + count = SPI_DEFAULT_TIMEOUT * (SystemCoreClock / 24U / 1000U); + + /* Disable Tx DMA Request */ + CLEAR_BIT(hspi->Instance->CTRL2, SPI_CTRL2_TXDEN); + + /* Wait until TXE flag is set */ + do + { + if (count == 0U) + { + SET_BIT(hspi->ErrorCode, DAL_SPI_ERROR_ABORT); + break; + } + count--; + } while ((hspi->Instance->STS & SPI_FLAG_TXE) == RESET); + + /* Check if an Abort process is still ongoing */ + if (hspi->hdmarx != NULL) + { + if (hspi->hdmarx->XferAbortCallback != NULL) + { + return; + } + } + + /* No Abort process still ongoing : All DMA Stream/Channel are aborted, call user Abort Complete callback */ + hspi->RxXferCount = 0U; + hspi->TxXferCount = 0U; + + /* Check no error during Abort procedure */ + if (hspi->ErrorCode != DAL_SPI_ERROR_ABORT) + { + /* Reset errorCode */ + hspi->ErrorCode = DAL_SPI_ERROR_NONE; + } + + /* Clear the Error flags in the STS register */ + __DAL_SPI_CLEAR_OVRFLAG(hspi); + __DAL_SPI_CLEAR_FREFLAG(hspi); + + /* Restore hspi->State to Ready */ + hspi->State = DAL_SPI_STATE_READY; + + /* Call user Abort complete callback */ +#if (USE_DAL_SPI_REGISTER_CALLBACKS == 1U) + hspi->AbortCpltCallback(hspi); +#else + DAL_SPI_AbortCpltCallback(hspi); +#endif /* USE_DAL_SPI_REGISTER_CALLBACKS */ +} + +/** + * @brief DMA SPI Rx communication abort callback, when initiated by user + * (To be called at end of DMA Rx Abort procedure following user abort request). + * @note When this callback is executed, User Abort complete call back is called only if no + * Abort still ongoing for Tx DMA Handle. + * @param hdma DMA handle. + * @retval None + */ +static void SPI_DMARxAbortCallback(DMA_HandleTypeDef *hdma) +{ + SPI_HandleTypeDef *hspi = (SPI_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent); /* Derogation MISRAC2012-Rule-11.5 */ + + /* Disable SPI Peripheral */ + __DAL_SPI_DISABLE(hspi); + + hspi->hdmarx->XferAbortCallback = NULL; + + /* Disable Rx DMA Request */ + CLEAR_BIT(hspi->Instance->CTRL2, SPI_CTRL2_RXDEN); + + /* Check Busy flag */ + if (SPI_EndRxTxTransaction(hspi, SPI_DEFAULT_TIMEOUT, DAL_GetTick()) != DAL_OK) + { + SET_BIT(hspi->ErrorCode, DAL_SPI_ERROR_ABORT); + } + + /* Check if an Abort process is still ongoing */ + if (hspi->hdmatx != NULL) + { + if (hspi->hdmatx->XferAbortCallback != NULL) + { + return; + } + } + + /* No Abort process still ongoing : All DMA Stream/Channel are aborted, call user Abort Complete callback */ + hspi->RxXferCount = 0U; + hspi->TxXferCount = 0U; + + /* Check no error during Abort procedure */ + if (hspi->ErrorCode != DAL_SPI_ERROR_ABORT) + { + /* Reset errorCode */ + hspi->ErrorCode = DAL_SPI_ERROR_NONE; + } + + /* Clear the Error flags in the STS register */ + __DAL_SPI_CLEAR_OVRFLAG(hspi); + __DAL_SPI_CLEAR_FREFLAG(hspi); + + /* Restore hspi->State to Ready */ + hspi->State = DAL_SPI_STATE_READY; + + /* Call user Abort complete callback */ +#if (USE_DAL_SPI_REGISTER_CALLBACKS == 1U) + hspi->AbortCpltCallback(hspi); +#else + DAL_SPI_AbortCpltCallback(hspi); +#endif /* USE_DAL_SPI_REGISTER_CALLBACKS */ +} + +/** + * @brief Rx 8-bit handler for Transmit and Receive in Interrupt mode. + * @param hspi pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @retval None + */ +static void SPI_2linesRxISR_8BIT(struct __SPI_HandleTypeDef *hspi) +{ + /* Receive data in 8bit mode */ + *hspi->pRxBuffPtr = *((__IO uint8_t *)&hspi->Instance->DATA); + hspi->pRxBuffPtr++; + hspi->RxXferCount--; + + /* Check end of the reception */ + if (hspi->RxXferCount == 0U) + { +#if (USE_SPI_CRC != 0U) + if (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) + { + hspi->RxISR = SPI_2linesRxISR_8BITCRC; + return; + } +#endif /* USE_SPI_CRC */ + + /* Disable RXNE and ERR interrupt */ + __DAL_SPI_DISABLE_IT(hspi, (SPI_IT_RXNE | SPI_IT_ERR)); + + if (hspi->TxXferCount == 0U) + { + SPI_CloseRxTx_ISR(hspi); + } + } +} + +#if (USE_SPI_CRC != 0U) +/** + * @brief Rx 8-bit handler for Transmit and Receive in Interrupt mode. + * @param hspi pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @retval None + */ +static void SPI_2linesRxISR_8BITCRC(struct __SPI_HandleTypeDef *hspi) +{ + __IO uint8_t *ptmpreg8; + __IO uint8_t tmpreg8 = 0; + + /* Initialize the 8bit temporary pointer */ + ptmpreg8 = (__IO uint8_t *)&hspi->Instance->DATA; + /* Read 8bit CRC to flush Data Register */ + tmpreg8 = *ptmpreg8; + /* To avoid GCC warning */ + UNUSED(tmpreg8); + + /* Disable RXNE and ERR interrupt */ + __DAL_SPI_DISABLE_IT(hspi, (SPI_IT_RXNE | SPI_IT_ERR)); + + if (hspi->TxXferCount == 0U) + { + SPI_CloseRxTx_ISR(hspi); + } +} +#endif /* USE_SPI_CRC */ + +/** + * @brief Tx 8-bit handler for Transmit and Receive in Interrupt mode. + * @param hspi pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @retval None + */ +static void SPI_2linesTxISR_8BIT(struct __SPI_HandleTypeDef *hspi) +{ + *(__IO uint8_t *)&hspi->Instance->DATA = (*hspi->pTxBuffPtr); + hspi->pTxBuffPtr++; + hspi->TxXferCount--; + + /* Check the end of the transmission */ + if (hspi->TxXferCount == 0U) + { +#if (USE_SPI_CRC != 0U) + if (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) + { + /* Set CRC Next Bit to send CRC */ + SET_BIT(hspi->Instance->CTRL1, SPI_CTRL1_CRCNXT); + /* Disable TXE interrupt */ + __DAL_SPI_DISABLE_IT(hspi, SPI_IT_TXE); + return; + } +#endif /* USE_SPI_CRC */ + + /* Disable TXE interrupt */ + __DAL_SPI_DISABLE_IT(hspi, SPI_IT_TXE); + + if (hspi->RxXferCount == 0U) + { + SPI_CloseRxTx_ISR(hspi); + } + } +} + +/** + * @brief Rx 16-bit handler for Transmit and Receive in Interrupt mode. + * @param hspi pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @retval None + */ +static void SPI_2linesRxISR_16BIT(struct __SPI_HandleTypeDef *hspi) +{ + /* Receive data in 16 Bit mode */ + *((uint16_t *)hspi->pRxBuffPtr) = (uint16_t)(hspi->Instance->DATA); + hspi->pRxBuffPtr += sizeof(uint16_t); + hspi->RxXferCount--; + + if (hspi->RxXferCount == 0U) + { +#if (USE_SPI_CRC != 0U) + if (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) + { + hspi->RxISR = SPI_2linesRxISR_16BITCRC; + return; + } +#endif /* USE_SPI_CRC */ + + /* Disable RXNE interrupt */ + __DAL_SPI_DISABLE_IT(hspi, SPI_IT_RXNE); + + if (hspi->TxXferCount == 0U) + { + SPI_CloseRxTx_ISR(hspi); + } + } +} + +#if (USE_SPI_CRC != 0U) +/** + * @brief Manage the CRC 16-bit receive for Transmit and Receive in Interrupt mode. + * @param hspi pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @retval None + */ +static void SPI_2linesRxISR_16BITCRC(struct __SPI_HandleTypeDef *hspi) +{ + __IO uint32_t tmpreg = 0U; + + /* Read 16bit CRC to flush Data Register */ + tmpreg = READ_REG(hspi->Instance->DATA); + /* To avoid GCC warning */ + UNUSED(tmpreg); + + /* Disable RXNE interrupt */ + __DAL_SPI_DISABLE_IT(hspi, SPI_IT_RXNE); + + SPI_CloseRxTx_ISR(hspi); +} +#endif /* USE_SPI_CRC */ + +/** + * @brief Tx 16-bit handler for Transmit and Receive in Interrupt mode. + * @param hspi pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @retval None + */ +static void SPI_2linesTxISR_16BIT(struct __SPI_HandleTypeDef *hspi) +{ + /* Transmit data in 16 Bit mode */ + hspi->Instance->DATA = *((uint16_t *)hspi->pTxBuffPtr); + hspi->pTxBuffPtr += sizeof(uint16_t); + hspi->TxXferCount--; + + /* Enable CRC Transmission */ + if (hspi->TxXferCount == 0U) + { +#if (USE_SPI_CRC != 0U) + if (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) + { + /* Set CRC Next Bit to send CRC */ + SET_BIT(hspi->Instance->CTRL1, SPI_CTRL1_CRCNXT); + /* Disable TXE interrupt */ + __DAL_SPI_DISABLE_IT(hspi, SPI_IT_TXE); + return; + } +#endif /* USE_SPI_CRC */ + + /* Disable TXE interrupt */ + __DAL_SPI_DISABLE_IT(hspi, SPI_IT_TXE); + + if (hspi->RxXferCount == 0U) + { + SPI_CloseRxTx_ISR(hspi); + } + } +} + +#if (USE_SPI_CRC != 0U) +/** + * @brief Manage the CRC 8-bit receive in Interrupt context. + * @param hspi pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @retval None + */ +static void SPI_RxISR_8BITCRC(struct __SPI_HandleTypeDef *hspi) +{ + __IO uint8_t *ptmpreg8; + __IO uint8_t tmpreg8 = 0; + + /* Initialize the 8bit temporary pointer */ + ptmpreg8 = (__IO uint8_t *)&hspi->Instance->DATA; + /* Read 8bit CRC to flush Data Register */ + tmpreg8 = *ptmpreg8; + /* To avoid GCC warning */ + UNUSED(tmpreg8); + + SPI_CloseRx_ISR(hspi); +} +#endif /* USE_SPI_CRC */ + +/** + * @brief Manage the receive 8-bit in Interrupt context. + * @param hspi pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @retval None + */ +static void SPI_RxISR_8BIT(struct __SPI_HandleTypeDef *hspi) +{ + *hspi->pRxBuffPtr = (*(__IO uint8_t *)&hspi->Instance->DATA); + hspi->pRxBuffPtr++; + hspi->RxXferCount--; + +#if (USE_SPI_CRC != 0U) + /* Enable CRC Transmission */ + if ((hspi->RxXferCount == 1U) && (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE)) + { + SET_BIT(hspi->Instance->CTRL1, SPI_CTRL1_CRCNXT); + } +#endif /* USE_SPI_CRC */ + + if (hspi->RxXferCount == 0U) + { +#if (USE_SPI_CRC != 0U) + if (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) + { + hspi->RxISR = SPI_RxISR_8BITCRC; + return; + } +#endif /* USE_SPI_CRC */ + SPI_CloseRx_ISR(hspi); + } +} + +#if (USE_SPI_CRC != 0U) +/** + * @brief Manage the CRC 16-bit receive in Interrupt context. + * @param hspi pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @retval None + */ +static void SPI_RxISR_16BITCRC(struct __SPI_HandleTypeDef *hspi) +{ + __IO uint32_t tmpreg = 0U; + + /* Read 16bit CRC to flush Data Register */ + tmpreg = READ_REG(hspi->Instance->DATA); + /* To avoid GCC warning */ + UNUSED(tmpreg); + + /* Disable RXNE and ERR interrupt */ + __DAL_SPI_DISABLE_IT(hspi, (SPI_IT_RXNE | SPI_IT_ERR)); + + SPI_CloseRx_ISR(hspi); +} +#endif /* USE_SPI_CRC */ + +/** + * @brief Manage the 16-bit receive in Interrupt context. + * @param hspi pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @retval None + */ +static void SPI_RxISR_16BIT(struct __SPI_HandleTypeDef *hspi) +{ + *((uint16_t *)hspi->pRxBuffPtr) = (uint16_t)(hspi->Instance->DATA); + hspi->pRxBuffPtr += sizeof(uint16_t); + hspi->RxXferCount--; + +#if (USE_SPI_CRC != 0U) + /* Enable CRC Transmission */ + if ((hspi->RxXferCount == 1U) && (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE)) + { + SET_BIT(hspi->Instance->CTRL1, SPI_CTRL1_CRCNXT); + } +#endif /* USE_SPI_CRC */ + + if (hspi->RxXferCount == 0U) + { +#if (USE_SPI_CRC != 0U) + if (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) + { + hspi->RxISR = SPI_RxISR_16BITCRC; + return; + } +#endif /* USE_SPI_CRC */ + SPI_CloseRx_ISR(hspi); + } +} + +/** + * @brief Handle the data 8-bit transmit in Interrupt mode. + * @param hspi pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @retval None + */ +static void SPI_TxISR_8BIT(struct __SPI_HandleTypeDef *hspi) +{ + *(__IO uint8_t *)&hspi->Instance->DATA = (*hspi->pTxBuffPtr); + hspi->pTxBuffPtr++; + hspi->TxXferCount--; + + if (hspi->TxXferCount == 0U) + { +#if (USE_SPI_CRC != 0U) + if (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) + { + /* Enable CRC Transmission */ + SET_BIT(hspi->Instance->CTRL1, SPI_CTRL1_CRCNXT); + } +#endif /* USE_SPI_CRC */ + SPI_CloseTx_ISR(hspi); + } +} + +/** + * @brief Handle the data 16-bit transmit in Interrupt mode. + * @param hspi pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @retval None + */ +static void SPI_TxISR_16BIT(struct __SPI_HandleTypeDef *hspi) +{ + /* Transmit data in 16 Bit mode */ + hspi->Instance->DATA = *((uint16_t *)hspi->pTxBuffPtr); + hspi->pTxBuffPtr += sizeof(uint16_t); + hspi->TxXferCount--; + + if (hspi->TxXferCount == 0U) + { +#if (USE_SPI_CRC != 0U) + if (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) + { + /* Enable CRC Transmission */ + SET_BIT(hspi->Instance->CTRL1, SPI_CTRL1_CRCNXT); + } +#endif /* USE_SPI_CRC */ + SPI_CloseTx_ISR(hspi); + } +} + +/** + * @brief Handle SPI Communication Timeout. + * @param hspi pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @param Flag SPI flag to check + * @param State flag state to check + * @param Timeout Timeout duration + * @param Tickstart tick start value + * @retval DAL status + */ +static DAL_StatusTypeDef SPI_WaitFlagStateUntilTimeout(SPI_HandleTypeDef *hspi, uint32_t Flag, FlagStatus State, + uint32_t Timeout, uint32_t Tickstart) +{ + __IO uint32_t count; + uint32_t tmp_timeout; + uint32_t tmp_tickstart; + + /* Adjust Timeout value in case of end of transfer */ + tmp_timeout = Timeout - (DAL_GetTick() - Tickstart); + tmp_tickstart = DAL_GetTick(); + + /* Calculate Timeout based on a software loop to avoid blocking issue if Systick is disabled */ + count = tmp_timeout * ((SystemCoreClock * 32U) >> 20U); + + while ((__DAL_SPI_GET_FLAG(hspi, Flag) ? SET : RESET) != State) + { + if (Timeout != DAL_MAX_DELAY) + { + if (((DAL_GetTick() - tmp_tickstart) >= tmp_timeout) || (tmp_timeout == 0U)) + { + /* Disable the SPI and reset the CRC: the CRC value should be cleared + on both master and slave sides in order to resynchronize the master + and slave for their respective CRC calculation */ + + /* Disable TXE, RXNE and ERR interrupts for the interrupt process */ + __DAL_SPI_DISABLE_IT(hspi, (SPI_IT_TXE | SPI_IT_RXNE | SPI_IT_ERR)); + + if ((hspi->Init.Mode == SPI_MODE_MASTER) && ((hspi->Init.Direction == SPI_DIRECTION_1LINE) + || (hspi->Init.Direction == SPI_DIRECTION_2LINES_RXONLY))) + { + /* Disable SPI peripheral */ + __DAL_SPI_DISABLE(hspi); + } + + /* Reset CRC Calculation */ + if (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) + { + SPI_RESET_CRC(hspi); + } + + hspi->State = DAL_SPI_STATE_READY; + + /* Process Unlocked */ + __DAL_UNLOCK(hspi); + + return DAL_TIMEOUT; + } + /* If Systick is disabled or not incremented, deactivate timeout to go in disable loop procedure */ + if (count == 0U) + { + tmp_timeout = 0U; + } + count--; + } + } + + return DAL_OK; +} + +/** + * @brief Handle the check of the RX transaction complete. + * @param hspi pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @param Timeout Timeout duration + * @param Tickstart tick start value + * @retval DAL status + */ +static DAL_StatusTypeDef SPI_EndRxTransaction(SPI_HandleTypeDef *hspi, uint32_t Timeout, uint32_t Tickstart) +{ + if ((hspi->Init.Mode == SPI_MODE_MASTER) && ((hspi->Init.Direction == SPI_DIRECTION_1LINE) + || (hspi->Init.Direction == SPI_DIRECTION_2LINES_RXONLY))) + { + /* Disable SPI peripheral */ + __DAL_SPI_DISABLE(hspi); + } + + /* Erratasheet: BSY bit may stay high at the end of a data transfer in Slave mode */ + if (hspi->Init.Mode == SPI_MODE_MASTER) + { + if (hspi->Init.Direction != SPI_DIRECTION_2LINES_RXONLY) + { + /* Control the BSY flag */ + if (SPI_WaitFlagStateUntilTimeout(hspi, SPI_FLAG_BSY, RESET, Timeout, Tickstart) != DAL_OK) + { + SET_BIT(hspi->ErrorCode, DAL_SPI_ERROR_FLAG); + return DAL_TIMEOUT; + } + } + else + { + /* Wait the RXNE reset */ + if (SPI_WaitFlagStateUntilTimeout(hspi, SPI_FLAG_RXNE, RESET, Timeout, Tickstart) != DAL_OK) + { + SET_BIT(hspi->ErrorCode, DAL_SPI_ERROR_FLAG); + return DAL_TIMEOUT; + } + } + } + else + { + /* Wait the RXNE reset */ + if (SPI_WaitFlagStateUntilTimeout(hspi, SPI_FLAG_RXNE, RESET, Timeout, Tickstart) != DAL_OK) + { + SET_BIT(hspi->ErrorCode, DAL_SPI_ERROR_FLAG); + return DAL_TIMEOUT; + } + } + return DAL_OK; +} + +/** + * @brief Handle the check of the RXTX or TX transaction complete. + * @param hspi SPI handle + * @param Timeout Timeout duration + * @param Tickstart tick start value + * @retval DAL status + */ +static DAL_StatusTypeDef SPI_EndRxTxTransaction(SPI_HandleTypeDef *hspi, uint32_t Timeout, uint32_t Tickstart) +{ + /* Timeout in ��s */ + __IO uint32_t count = SPI_BSY_FLAG_WORKAROUND_TIMEOUT * (SystemCoreClock / 24U / 1000000U); + /* Erratasheet: BSY bit may stay high at the end of a data transfer in Slave mode */ + if (hspi->Init.Mode == SPI_MODE_MASTER) + { + /* Control the BSY flag */ + if (SPI_WaitFlagStateUntilTimeout(hspi, SPI_FLAG_BSY, RESET, Timeout, Tickstart) != DAL_OK) + { + SET_BIT(hspi->ErrorCode, DAL_SPI_ERROR_FLAG); + return DAL_TIMEOUT; + } + } + else + { + /* Wait BSY flag during 1 Byte time transfer in case of Full-Duplex and Tx transfer + * If Timeout is reached, the transfer is considered as finish. + * User have to calculate the timeout value to fit with the time of 1 byte transfer. + * This time is directly link with the SPI clock from Master device. + */ + do + { + if (count == 0U) + { + break; + } + count--; + } while (__DAL_SPI_GET_FLAG(hspi, SPI_FLAG_BSY) != RESET); + } + + return DAL_OK; +} + +/** + * @brief Handle the end of the RXTX transaction. + * @param hspi pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @retval None + */ +static void SPI_CloseRxTx_ISR(SPI_HandleTypeDef *hspi) +{ + uint32_t tickstart; + __IO uint32_t count = SPI_DEFAULT_TIMEOUT * (SystemCoreClock / 24U / 1000U); + + /* Init tickstart for timeout management */ + tickstart = DAL_GetTick(); + + /* Disable ERR interrupt */ + __DAL_SPI_DISABLE_IT(hspi, SPI_IT_ERR); + + /* Wait until TXE flag is set */ + do + { + if (count == 0U) + { + SET_BIT(hspi->ErrorCode, DAL_SPI_ERROR_FLAG); + break; + } + count--; + } while ((hspi->Instance->STS & SPI_FLAG_TXE) == RESET); + + /* Check the end of the transaction */ + if (SPI_EndRxTxTransaction(hspi, SPI_DEFAULT_TIMEOUT, tickstart) != DAL_OK) + { + SET_BIT(hspi->ErrorCode, DAL_SPI_ERROR_FLAG); + } + + /* Clear overrun flag in 2 Lines communication mode because received is not read */ + if (hspi->Init.Direction == SPI_DIRECTION_2LINES) + { + __DAL_SPI_CLEAR_OVRFLAG(hspi); + } + +#if (USE_SPI_CRC != 0U) + /* Check if CRC error occurred */ + if (__DAL_SPI_GET_FLAG(hspi, SPI_FLAG_CRCERR) != RESET) + { + hspi->State = DAL_SPI_STATE_READY; + SET_BIT(hspi->ErrorCode, DAL_SPI_ERROR_CRC); + __DAL_SPI_CLEAR_CRCERRFLAG(hspi); + /* Call user error callback */ +#if (USE_DAL_SPI_REGISTER_CALLBACKS == 1U) + hspi->ErrorCallback(hspi); +#else + DAL_SPI_ErrorCallback(hspi); +#endif /* USE_DAL_SPI_REGISTER_CALLBACKS */ + } + else + { +#endif /* USE_SPI_CRC */ + if (hspi->ErrorCode == DAL_SPI_ERROR_NONE) + { + if (hspi->State == DAL_SPI_STATE_BUSY_RX) + { + hspi->State = DAL_SPI_STATE_READY; + /* Call user Rx complete callback */ +#if (USE_DAL_SPI_REGISTER_CALLBACKS == 1U) + hspi->RxCpltCallback(hspi); +#else + DAL_SPI_RxCpltCallback(hspi); +#endif /* USE_DAL_SPI_REGISTER_CALLBACKS */ + } + else + { + hspi->State = DAL_SPI_STATE_READY; + /* Call user TxRx complete callback */ +#if (USE_DAL_SPI_REGISTER_CALLBACKS == 1U) + hspi->TxRxCpltCallback(hspi); +#else + DAL_SPI_TxRxCpltCallback(hspi); +#endif /* USE_DAL_SPI_REGISTER_CALLBACKS */ + } + } + else + { + hspi->State = DAL_SPI_STATE_READY; + /* Call user error callback */ +#if (USE_DAL_SPI_REGISTER_CALLBACKS == 1U) + hspi->ErrorCallback(hspi); +#else + DAL_SPI_ErrorCallback(hspi); +#endif /* USE_DAL_SPI_REGISTER_CALLBACKS */ + } +#if (USE_SPI_CRC != 0U) + } +#endif /* USE_SPI_CRC */ +} + +/** + * @brief Handle the end of the RX transaction. + * @param hspi pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @retval None + */ +static void SPI_CloseRx_ISR(SPI_HandleTypeDef *hspi) +{ + /* Disable RXNE and ERR interrupt */ + __DAL_SPI_DISABLE_IT(hspi, (SPI_IT_RXNE | SPI_IT_ERR)); + + /* Check the end of the transaction */ + if (SPI_EndRxTransaction(hspi, SPI_DEFAULT_TIMEOUT, DAL_GetTick()) != DAL_OK) + { + SET_BIT(hspi->ErrorCode, DAL_SPI_ERROR_FLAG); + } + + /* Clear overrun flag in 2 Lines communication mode because received is not read */ + if (hspi->Init.Direction == SPI_DIRECTION_2LINES) + { + __DAL_SPI_CLEAR_OVRFLAG(hspi); + } + hspi->State = DAL_SPI_STATE_READY; + +#if (USE_SPI_CRC != 0U) + /* Check if CRC error occurred */ + if (__DAL_SPI_GET_FLAG(hspi, SPI_FLAG_CRCERR) != RESET) + { + SET_BIT(hspi->ErrorCode, DAL_SPI_ERROR_CRC); + __DAL_SPI_CLEAR_CRCERRFLAG(hspi); + /* Call user error callback */ +#if (USE_DAL_SPI_REGISTER_CALLBACKS == 1U) + hspi->ErrorCallback(hspi); +#else + DAL_SPI_ErrorCallback(hspi); +#endif /* USE_DAL_SPI_REGISTER_CALLBACKS */ + } + else + { +#endif /* USE_SPI_CRC */ + if (hspi->ErrorCode == DAL_SPI_ERROR_NONE) + { + /* Call user Rx complete callback */ +#if (USE_DAL_SPI_REGISTER_CALLBACKS == 1U) + hspi->RxCpltCallback(hspi); +#else + DAL_SPI_RxCpltCallback(hspi); +#endif /* USE_DAL_SPI_REGISTER_CALLBACKS */ + } + else + { + /* Call user error callback */ +#if (USE_DAL_SPI_REGISTER_CALLBACKS == 1U) + hspi->ErrorCallback(hspi); +#else + DAL_SPI_ErrorCallback(hspi); +#endif /* USE_DAL_SPI_REGISTER_CALLBACKS */ + } +#if (USE_SPI_CRC != 0U) + } +#endif /* USE_SPI_CRC */ +} + +/** + * @brief Handle the end of the TX transaction. + * @param hspi pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @retval None + */ +static void SPI_CloseTx_ISR(SPI_HandleTypeDef *hspi) +{ + uint32_t tickstart; + __IO uint32_t count = SPI_DEFAULT_TIMEOUT * (SystemCoreClock / 24U / 1000U); + + /* Init tickstart for timeout management*/ + tickstart = DAL_GetTick(); + + /* Wait until TXE flag is set */ + do + { + if (count == 0U) + { + SET_BIT(hspi->ErrorCode, DAL_SPI_ERROR_FLAG); + break; + } + count--; + } while ((hspi->Instance->STS & SPI_FLAG_TXE) == RESET); + + /* Disable TXE and ERR interrupt */ + __DAL_SPI_DISABLE_IT(hspi, (SPI_IT_TXE | SPI_IT_ERR)); + + /* Check the end of the transaction */ + if (SPI_EndRxTxTransaction(hspi, SPI_DEFAULT_TIMEOUT, tickstart) != DAL_OK) + { + SET_BIT(hspi->ErrorCode, DAL_SPI_ERROR_FLAG); + } + + /* Clear overrun flag in 2 Lines communication mode because received is not read */ + if (hspi->Init.Direction == SPI_DIRECTION_2LINES) + { + __DAL_SPI_CLEAR_OVRFLAG(hspi); + } + + hspi->State = DAL_SPI_STATE_READY; + if (hspi->ErrorCode != DAL_SPI_ERROR_NONE) + { + /* Call user error callback */ +#if (USE_DAL_SPI_REGISTER_CALLBACKS == 1U) + hspi->ErrorCallback(hspi); +#else + DAL_SPI_ErrorCallback(hspi); +#endif /* USE_DAL_SPI_REGISTER_CALLBACKS */ + } + else + { + /* Call user Rx complete callback */ +#if (USE_DAL_SPI_REGISTER_CALLBACKS == 1U) + hspi->TxCpltCallback(hspi); +#else + DAL_SPI_TxCpltCallback(hspi); +#endif /* USE_DAL_SPI_REGISTER_CALLBACKS */ + } +} + +/** + * @brief Handle abort a Rx transaction. + * @param hspi pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @retval None + */ +static void SPI_AbortRx_ISR(SPI_HandleTypeDef *hspi) +{ + __IO uint32_t tmpreg = 0U; + __IO uint32_t count = SPI_DEFAULT_TIMEOUT * (SystemCoreClock / 24U / 1000U); + + /* Wait until TXE flag is set */ + do + { + if (count == 0U) + { + SET_BIT(hspi->ErrorCode, DAL_SPI_ERROR_ABORT); + break; + } + count--; + } while ((hspi->Instance->STS & SPI_FLAG_TXE) == RESET); + + /* Disable SPI Peripheral */ + __DAL_SPI_DISABLE(hspi); + + /* Disable TXBEIEN, RXBNEIEN and ERRIEN(mode fault event, overrun error, TI frame error) interrupts */ + CLEAR_BIT(hspi->Instance->CTRL2, (SPI_CTRL2_TXBEIEN | SPI_CTRL2_RXBNEIEN | SPI_CTRL2_ERRIEN)); + + /* Flush Data Register by a blank read */ + tmpreg = READ_REG(hspi->Instance->DATA); + /* To avoid GCC warning */ + UNUSED(tmpreg); + + hspi->State = DAL_SPI_STATE_ABORT; +} + +/** + * @brief Handle abort a Tx or Rx/Tx transaction. + * @param hspi pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @retval None + */ +static void SPI_AbortTx_ISR(SPI_HandleTypeDef *hspi) +{ + /* Disable TXBEIEN interrupt */ + CLEAR_BIT(hspi->Instance->CTRL2, (SPI_CTRL2_TXBEIEN)); + + /* Disable SPI Peripheral */ + __DAL_SPI_DISABLE(hspi); + + hspi->State = DAL_SPI_STATE_ABORT; +} + +/** + * @} + */ + +#endif /* DAL_SPI_MODULE_ENABLED */ + +/** + * @} + */ + +/** + * @} + */ + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_sram.c b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_sram.c new file mode 100644 index 0000000000..df2117bc26 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_sram.c @@ -0,0 +1,1135 @@ +/** + * + * @file apm32f4xx_dal_sram.c + * @brief SRAM DAL module driver. + * This file provides a generic firmware to drive SRAM memories + * mounted as external device. + * + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + * + @verbatim + ============================================================================== + ##### How to use this driver ##### + ============================================================================== + [..] + This driver is a generic layered driver which contains a set of APIs used to + control SRAM memories. It uses the FMC layer functions to interface + with SRAM devices. + The following sequence should be followed to configure the FMC/EMMC to interface + with SRAM/PSRAM memories: + + (#) Declare a SRAM_HandleTypeDef handle structure, for example: + SRAM_HandleTypeDef hsram; and: + + (++) Fill the SRAM_HandleTypeDef handle "Init" field with the allowed + values of the structure member. + + (++) Fill the SRAM_HandleTypeDef handle "Instance" field with a predefined + base register instance for NOR or SRAM device + + (++) Fill the SRAM_HandleTypeDef handle "Extended" field with a predefined + base register instance for NOR or SRAM extended mode + + (#) Declare two FMC_NORSRAM_TimingTypeDef structures, for both normal and extended + mode timings; for example: + FMC_NORSRAM_TimingTypeDef Timing and FMC_NORSRAM_TimingTypeDef ExTiming; + and fill its fields with the allowed values of the structure member. + + (#) Initialize the SRAM Controller by calling the function DAL_SRAM_Init(). This function + performs the following sequence: + + (##) MSP hardware layer configuration using the function DAL_SRAM_MspInit() + (##) Control register configuration using the FMC NORSRAM interface function + FMC_NORSRAM_Init() + (##) Timing register configuration using the FMC NORSRAM interface function + FMC_NORSRAM_Timing_Init() + (##) Extended mode Timing register configuration using the FMC NORSRAM interface function + FMC_NORSRAM_Extended_Timing_Init() + (##) Enable the SRAM device using the macro __FMC_NORSRAM_ENABLE() + + (#) At this stage you can perform read/write accesses from/to the memory connected + to the NOR/SRAM Bank. You can perform either polling or DMA transfer using the + following APIs: + (++) DAL_SRAM_Read()/DAL_SRAM_Write() for polling read/write access + (++) DAL_SRAM_Read_DMA()/DAL_SRAM_Write_DMA() for DMA read/write transfer + + (#) You can also control the SRAM device by calling the control APIs DAL_SRAM_WriteOperation_Enable()/ + DAL_SRAM_WriteOperation_Disable() to respectively enable/disable the SRAM write operation + + (#) You can continuously monitor the SRAM device DAL state by calling the function + DAL_SRAM_GetState() + + *** Callback registration *** + ============================================= + [..] + The compilation define USE_DAL_SRAM_REGISTER_CALLBACKS when set to 1 + allows the user to configure dynamically the driver callbacks. + + Use Functions DAL_SRAM_RegisterCallback() to register a user callback, + it allows to register following callbacks: + (+) MspInitCallback : SRAM MspInit. + (+) MspDeInitCallback : SRAM MspDeInit. + This function takes as parameters the DAL peripheral handle, the Callback ID + and a pointer to the user callback function. + + Use function DAL_SRAM_UnRegisterCallback() to reset a callback to the default + weak (surcharged) function. It allows to reset following callbacks: + (+) MspInitCallback : SRAM MspInit. + (+) MspDeInitCallback : SRAM MspDeInit. + This function) takes as parameters the DAL peripheral handle and the Callback ID. + + By default, after the DAL_SRAM_Init and if the state is DAL_SRAM_STATE_RESET + all callbacks are reset to the corresponding legacy weak (surcharged) functions. + Exception done for MspInit and MspDeInit callbacks that are respectively + reset to the legacy weak (surcharged) functions in the DAL_SRAM_Init + and DAL_SRAM_DeInit only when these callbacks are null (not registered beforehand). + If not, MspInit or MspDeInit are not null, the DAL_SRAM_Init and DAL_SRAM_DeInit + keep and use the user MspInit/MspDeInit callbacks (registered beforehand) + + Callbacks can be registered/unregistered in READY state only. + Exception done for MspInit/MspDeInit callbacks that can be registered/unregistered + in READY or RESET state, thus registered (user) MspInit/DeInit callbacks can be used + during the Init/DeInit. + In that case first register the MspInit/MspDeInit user callbacks + using DAL_SRAM_RegisterCallback before calling DAL_SRAM_DeInit + or DAL_SRAM_Init function. + + When The compilation define USE_DAL_SRAM_REGISTER_CALLBACKS is set to 0 or + not defined, the callback registering feature is not available + and weak (surcharged) callbacks are used. + + @endverbatim + * + */ + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal.h" + +#if defined(SMC_Bank1) + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +#ifdef DAL_SRAM_MODULE_ENABLED + +/** @defgroup SRAM SRAM + * @brief SRAM driver modules + * @{ + */ + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +static void SRAM_DMACplt(DMA_HandleTypeDef *hdma); +static void SRAM_DMACpltProt(DMA_HandleTypeDef *hdma); +static void SRAM_DMAError(DMA_HandleTypeDef *hdma); + +/* Exported functions --------------------------------------------------------*/ + +/** @defgroup SRAM_Exported_Functions SRAM Exported Functions + * @{ + */ + +/** @defgroup SRAM_Exported_Functions_Group1 Initialization and de-initialization functions + * @brief Initialization and Configuration functions. + * + @verbatim + ============================================================================== + ##### SRAM Initialization and de_initialization functions ##### + ============================================================================== + [..] This section provides functions allowing to initialize/de-initialize + the SRAM memory + +@endverbatim + * @{ + */ + +/** + * @brief Performs the SRAM device initialization sequence + * @param hsram pointer to a SRAM_HandleTypeDef structure that contains + * the configuration information for SRAM module. + * @param Timing Pointer to SRAM control timing structure + * @param ExtTiming Pointer to SRAM extended mode timing structure + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SRAM_Init(SRAM_HandleTypeDef *hsram, FMC_NORSRAM_TimingTypeDef *Timing, + FMC_NORSRAM_TimingTypeDef *ExtTiming) +{ + /* Check the SRAM handle parameter */ + if (hsram == NULL) + { + return DAL_ERROR; + } + + if (hsram->State == DAL_SRAM_STATE_RESET) + { + /* Allocate lock resource and initialize it */ + hsram->Lock = DAL_UNLOCKED; + +#if (USE_DAL_SRAM_REGISTER_CALLBACKS == 1) + if (hsram->MspInitCallback == NULL) + { + hsram->MspInitCallback = DAL_SRAM_MspInit; + } + hsram->DmaXferCpltCallback = DAL_SRAM_DMA_XferCpltCallback; + hsram->DmaXferErrorCallback = DAL_SRAM_DMA_XferErrorCallback; + + /* Init the low level hardware */ + hsram->MspInitCallback(hsram); +#else + /* Initialize the low level hardware (MSP) */ + DAL_SRAM_MspInit(hsram); +#endif /* USE_DAL_SRAM_REGISTER_CALLBACKS */ + } + + /* Initialize SRAM control Interface */ + (void)FMC_NORSRAM_Init(hsram->Instance, &(hsram->Init)); + + /* Initialize SRAM timing Interface */ + (void)FMC_NORSRAM_Timing_Init(hsram->Instance, Timing, hsram->Init.NSBank); + + /* Initialize SRAM extended mode timing Interface */ + (void)FMC_NORSRAM_Extended_Timing_Init(hsram->Extended, ExtTiming, hsram->Init.NSBank, + hsram->Init.ExtendedMode); + + /* Enable the NORSRAM device */ + __FMC_NORSRAM_ENABLE(hsram->Instance, hsram->Init.NSBank); + + /* Initialize the SRAM controller state */ + hsram->State = DAL_SRAM_STATE_READY; + + return DAL_OK; +} + +/** + * @brief Performs the SRAM device De-initialization sequence. + * @param hsram pointer to a SRAM_HandleTypeDef structure that contains + * the configuration information for SRAM module. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SRAM_DeInit(SRAM_HandleTypeDef *hsram) +{ +#if (USE_DAL_SRAM_REGISTER_CALLBACKS == 1) + if (hsram->MspDeInitCallback == NULL) + { + hsram->MspDeInitCallback = DAL_SRAM_MspDeInit; + } + + /* DeInit the low level hardware */ + hsram->MspDeInitCallback(hsram); +#else + /* De-Initialize the low level hardware (MSP) */ + DAL_SRAM_MspDeInit(hsram); +#endif /* USE_DAL_SRAM_REGISTER_CALLBACKS */ + + /* Configure the SRAM registers with their reset values */ + (void)FMC_NORSRAM_DeInit(hsram->Instance, hsram->Extended, hsram->Init.NSBank); + + /* Reset the SRAM controller state */ + hsram->State = DAL_SRAM_STATE_RESET; + + /* Release Lock */ + __DAL_UNLOCK(hsram); + + return DAL_OK; +} + +/** + * @brief SRAM MSP Init. + * @param hsram pointer to a SRAM_HandleTypeDef structure that contains + * the configuration information for SRAM module. + * @retval None + */ +__weak void DAL_SRAM_MspInit(SRAM_HandleTypeDef *hsram) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hsram); + + /* NOTE : This function Should not be modified, when the callback is needed, + the DAL_SRAM_MspInit could be implemented in the user file + */ +} + +/** + * @brief SRAM MSP DeInit. + * @param hsram pointer to a SRAM_HandleTypeDef structure that contains + * the configuration information for SRAM module. + * @retval None + */ +__weak void DAL_SRAM_MspDeInit(SRAM_HandleTypeDef *hsram) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hsram); + + /* NOTE : This function Should not be modified, when the callback is needed, + the DAL_SRAM_MspDeInit could be implemented in the user file + */ +} + +/** + * @brief DMA transfer complete callback. + * @param hdma pointer to a SRAM_HandleTypeDef structure that contains + * the configuration information for SRAM module. + * @retval None + */ +__weak void DAL_SRAM_DMA_XferCpltCallback(DMA_HandleTypeDef *hdma) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hdma); + + /* NOTE : This function Should not be modified, when the callback is needed, + the DAL_SRAM_DMA_XferCpltCallback could be implemented in the user file + */ +} + +/** + * @brief DMA transfer complete error callback. + * @param hdma pointer to a SRAM_HandleTypeDef structure that contains + * the configuration information for SRAM module. + * @retval None + */ +__weak void DAL_SRAM_DMA_XferErrorCallback(DMA_HandleTypeDef *hdma) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hdma); + + /* NOTE : This function Should not be modified, when the callback is needed, + the DAL_SRAM_DMA_XferErrorCallback could be implemented in the user file + */ +} + +/** + * @} + */ + +/** @defgroup SRAM_Exported_Functions_Group2 Input Output and memory control functions + * @brief Input Output and memory control functions + * + @verbatim + ============================================================================== + ##### SRAM Input and Output functions ##### + ============================================================================== + [..] + This section provides functions allowing to use and control the SRAM memory + +@endverbatim + * @{ + */ + +/** + * @brief Reads 8-bit buffer from SRAM memory. + * @param hsram pointer to a SRAM_HandleTypeDef structure that contains + * the configuration information for SRAM module. + * @param pAddress Pointer to read start address + * @param pDstBuffer Pointer to destination buffer + * @param BufferSize Size of the buffer to read from memory + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SRAM_Read_8b(SRAM_HandleTypeDef *hsram, uint32_t *pAddress, uint8_t *pDstBuffer, + uint32_t BufferSize) +{ + uint32_t size; + __IO uint8_t *psramaddress = (uint8_t *)pAddress; + uint8_t *pdestbuff = pDstBuffer; + DAL_SRAM_StateTypeDef state = hsram->State; + + /* Check the SRAM controller state */ + if ((state == DAL_SRAM_STATE_READY) || (state == DAL_SRAM_STATE_PROTECTED)) + { + /* Process Locked */ + __DAL_LOCK(hsram); + + /* Update the SRAM controller state */ + hsram->State = DAL_SRAM_STATE_BUSY; + + /* Read data from memory */ + for (size = BufferSize; size != 0U; size--) + { + *pdestbuff = *psramaddress; + pdestbuff++; + psramaddress++; + } + + /* Update the SRAM controller state */ + hsram->State = state; + + /* Process unlocked */ + __DAL_UNLOCK(hsram); + } + else + { + return DAL_ERROR; + } + + return DAL_OK; +} + +/** + * @brief Writes 8-bit buffer to SRAM memory. + * @param hsram pointer to a SRAM_HandleTypeDef structure that contains + * the configuration information for SRAM module. + * @param pAddress Pointer to write start address + * @param pSrcBuffer Pointer to source buffer to write + * @param BufferSize Size of the buffer to write to memory + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SRAM_Write_8b(SRAM_HandleTypeDef *hsram, uint32_t *pAddress, uint8_t *pSrcBuffer, + uint32_t BufferSize) +{ + uint32_t size; + __IO uint8_t *psramaddress = (uint8_t *)pAddress; + uint8_t *psrcbuff = pSrcBuffer; + + /* Check the SRAM controller state */ + if (hsram->State == DAL_SRAM_STATE_READY) + { + /* Process Locked */ + __DAL_LOCK(hsram); + + /* Update the SRAM controller state */ + hsram->State = DAL_SRAM_STATE_BUSY; + + /* Write data to memory */ + for (size = BufferSize; size != 0U; size--) + { + *psramaddress = *psrcbuff; + psrcbuff++; + psramaddress++; + } + + /* Update the SRAM controller state */ + hsram->State = DAL_SRAM_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hsram); + } + else + { + return DAL_ERROR; + } + + return DAL_OK; +} + +/** + * @brief Reads 16-bit buffer from SRAM memory. + * @param hsram pointer to a SRAM_HandleTypeDef structure that contains + * the configuration information for SRAM module. + * @param pAddress Pointer to read start address + * @param pDstBuffer Pointer to destination buffer + * @param BufferSize Size of the buffer to read from memory + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SRAM_Read_16b(SRAM_HandleTypeDef *hsram, uint32_t *pAddress, uint16_t *pDstBuffer, + uint32_t BufferSize) +{ + uint32_t size; + __IO uint32_t *psramaddress = pAddress; + uint16_t *pdestbuff = pDstBuffer; + uint8_t limit; + DAL_SRAM_StateTypeDef state = hsram->State; + + /* Check the SRAM controller state */ + if ((state == DAL_SRAM_STATE_READY) || (state == DAL_SRAM_STATE_PROTECTED)) + { + /* Process Locked */ + __DAL_LOCK(hsram); + + /* Update the SRAM controller state */ + hsram->State = DAL_SRAM_STATE_BUSY; + + /* Check if the size is a 32-bits multiple */ + limit = (((BufferSize % 2U) != 0U) ? 1U : 0U); + + /* Read data from memory */ + for (size = BufferSize; size != limit; size -= 2U) + { + *pdestbuff = (uint16_t)((*psramaddress) & 0x0000FFFFU); + pdestbuff++; + *pdestbuff = (uint16_t)(((*psramaddress) & 0xFFFF0000U) >> 16U); + pdestbuff++; + psramaddress++; + } + + /* Read last 16-bits if size is not 32-bits multiple */ + if (limit != 0U) + { + *pdestbuff = (uint16_t)((*psramaddress) & 0x0000FFFFU); + } + + /* Update the SRAM controller state */ + hsram->State = state; + + /* Process unlocked */ + __DAL_UNLOCK(hsram); + } + else + { + return DAL_ERROR; + } + + return DAL_OK; +} + +/** + * @brief Writes 16-bit buffer to SRAM memory. + * @param hsram pointer to a SRAM_HandleTypeDef structure that contains + * the configuration information for SRAM module. + * @param pAddress Pointer to write start address + * @param pSrcBuffer Pointer to source buffer to write + * @param BufferSize Size of the buffer to write to memory + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SRAM_Write_16b(SRAM_HandleTypeDef *hsram, uint32_t *pAddress, uint16_t *pSrcBuffer, + uint32_t BufferSize) +{ + uint32_t size; + __IO uint32_t *psramaddress = pAddress; + uint16_t *psrcbuff = pSrcBuffer; + uint8_t limit; + + /* Check the SRAM controller state */ + if (hsram->State == DAL_SRAM_STATE_READY) + { + /* Process Locked */ + __DAL_LOCK(hsram); + + /* Update the SRAM controller state */ + hsram->State = DAL_SRAM_STATE_BUSY; + + /* Check if the size is a 32-bits multiple */ + limit = (((BufferSize % 2U) != 0U) ? 1U : 0U); + + /* Write data to memory */ + for (size = BufferSize; size != limit; size -= 2U) + { + *psramaddress = (uint32_t)(*psrcbuff); + psrcbuff++; + *psramaddress |= ((uint32_t)(*psrcbuff) << 16U); + psrcbuff++; + psramaddress++; + } + + /* Write last 16-bits if size is not 32-bits multiple */ + if (limit != 0U) + { + *psramaddress = ((uint32_t)(*psrcbuff) & 0x0000FFFFU) | ((*psramaddress) & 0xFFFF0000U); + } + + /* Update the SRAM controller state */ + hsram->State = DAL_SRAM_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hsram); + } + else + { + return DAL_ERROR; + } + + return DAL_OK; +} + +/** + * @brief Reads 32-bit buffer from SRAM memory. + * @param hsram pointer to a SRAM_HandleTypeDef structure that contains + * the configuration information for SRAM module. + * @param pAddress Pointer to read start address + * @param pDstBuffer Pointer to destination buffer + * @param BufferSize Size of the buffer to read from memory + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SRAM_Read_32b(SRAM_HandleTypeDef *hsram, uint32_t *pAddress, uint32_t *pDstBuffer, + uint32_t BufferSize) +{ + uint32_t size; + __IO uint32_t *psramaddress = pAddress; + uint32_t *pdestbuff = pDstBuffer; + DAL_SRAM_StateTypeDef state = hsram->State; + + /* Check the SRAM controller state */ + if ((state == DAL_SRAM_STATE_READY) || (state == DAL_SRAM_STATE_PROTECTED)) + { + /* Process Locked */ + __DAL_LOCK(hsram); + + /* Update the SRAM controller state */ + hsram->State = DAL_SRAM_STATE_BUSY; + + /* Read data from memory */ + for (size = BufferSize; size != 0U; size--) + { + *pdestbuff = *psramaddress; + pdestbuff++; + psramaddress++; + } + + /* Update the SRAM controller state */ + hsram->State = state; + + /* Process unlocked */ + __DAL_UNLOCK(hsram); + } + else + { + return DAL_ERROR; + } + + return DAL_OK; +} + +/** + * @brief Writes 32-bit buffer to SRAM memory. + * @param hsram pointer to a SRAM_HandleTypeDef structure that contains + * the configuration information for SRAM module. + * @param pAddress Pointer to write start address + * @param pSrcBuffer Pointer to source buffer to write + * @param BufferSize Size of the buffer to write to memory + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SRAM_Write_32b(SRAM_HandleTypeDef *hsram, uint32_t *pAddress, uint32_t *pSrcBuffer, + uint32_t BufferSize) +{ + uint32_t size; + __IO uint32_t *psramaddress = pAddress; + uint32_t *psrcbuff = pSrcBuffer; + + /* Check the SRAM controller state */ + if (hsram->State == DAL_SRAM_STATE_READY) + { + /* Process Locked */ + __DAL_LOCK(hsram); + + /* Update the SRAM controller state */ + hsram->State = DAL_SRAM_STATE_BUSY; + + /* Write data to memory */ + for (size = BufferSize; size != 0U; size--) + { + *psramaddress = *psrcbuff; + psrcbuff++; + psramaddress++; + } + + /* Update the SRAM controller state */ + hsram->State = DAL_SRAM_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hsram); + } + else + { + return DAL_ERROR; + } + + return DAL_OK; +} + +/** + * @brief Reads a Words data from the SRAM memory using DMA transfer. + * @param hsram pointer to a SRAM_HandleTypeDef structure that contains + * the configuration information for SRAM module. + * @param pAddress Pointer to read start address + * @param pDstBuffer Pointer to destination buffer + * @param BufferSize Size of the buffer to read from memory + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SRAM_Read_DMA(SRAM_HandleTypeDef *hsram, uint32_t *pAddress, uint32_t *pDstBuffer, + uint32_t BufferSize) +{ + DAL_StatusTypeDef status; + DAL_SRAM_StateTypeDef state = hsram->State; + + /* Check the SRAM controller state */ + if ((state == DAL_SRAM_STATE_READY) || (state == DAL_SRAM_STATE_PROTECTED)) + { + /* Process Locked */ + __DAL_LOCK(hsram); + + /* Update the SRAM controller state */ + hsram->State = DAL_SRAM_STATE_BUSY; + + /* Configure DMA user callbacks */ + if (state == DAL_SRAM_STATE_READY) + { + hsram->hdma->XferCpltCallback = SRAM_DMACplt; + } + else + { + hsram->hdma->XferCpltCallback = SRAM_DMACpltProt; + } + hsram->hdma->XferErrorCallback = SRAM_DMAError; + + /* Enable the DMA Stream */ + status = DAL_DMA_Start_IT(hsram->hdma, (uint32_t)pAddress, (uint32_t)pDstBuffer, (uint32_t)BufferSize); + + /* Process unlocked */ + __DAL_UNLOCK(hsram); + } + else + { + status = DAL_ERROR; + } + + return status; +} + +/** + * @brief Writes a Words data buffer to SRAM memory using DMA transfer. + * @param hsram pointer to a SRAM_HandleTypeDef structure that contains + * the configuration information for SRAM module. + * @param pAddress Pointer to write start address + * @param pSrcBuffer Pointer to source buffer to write + * @param BufferSize Size of the buffer to write to memory + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SRAM_Write_DMA(SRAM_HandleTypeDef *hsram, uint32_t *pAddress, uint32_t *pSrcBuffer, + uint32_t BufferSize) +{ + DAL_StatusTypeDef status; + + /* Check the SRAM controller state */ + if (hsram->State == DAL_SRAM_STATE_READY) + { + /* Process Locked */ + __DAL_LOCK(hsram); + + /* Update the SRAM controller state */ + hsram->State = DAL_SRAM_STATE_BUSY; + + /* Configure DMA user callbacks */ + hsram->hdma->XferCpltCallback = SRAM_DMACplt; + hsram->hdma->XferErrorCallback = SRAM_DMAError; + + /* Enable the DMA Stream */ + status = DAL_DMA_Start_IT(hsram->hdma, (uint32_t)pSrcBuffer, (uint32_t)pAddress, (uint32_t)BufferSize); + + /* Process unlocked */ + __DAL_UNLOCK(hsram); + } + else + { + status = DAL_ERROR; + } + + return status; +} + +#if (USE_DAL_SRAM_REGISTER_CALLBACKS == 1) +/** + * @brief Register a User SRAM Callback + * To be used instead of the weak (surcharged) predefined callback + * @param hsram : SRAM handle + * @param CallbackId : ID of the callback to be registered + * This parameter can be one of the following values: + * @arg @ref DAL_SRAM_MSP_INIT_CB_ID SRAM MspInit callback ID + * @arg @ref DAL_SRAM_MSP_DEINIT_CB_ID SRAM MspDeInit callback ID + * @param pCallback : pointer to the Callback function + * @retval status + */ +DAL_StatusTypeDef DAL_SRAM_RegisterCallback(SRAM_HandleTypeDef *hsram, DAL_SRAM_CallbackIDTypeDef CallbackId, + pSRAM_CallbackTypeDef pCallback) +{ + DAL_StatusTypeDef status = DAL_OK; + DAL_SRAM_StateTypeDef state; + + if (pCallback == NULL) + { + return DAL_ERROR; + } + + /* Process locked */ + __DAL_LOCK(hsram); + + state = hsram->State; + if ((state == DAL_SRAM_STATE_READY) || (state == DAL_SRAM_STATE_RESET) || (state == DAL_SRAM_STATE_PROTECTED)) + { + switch (CallbackId) + { + case DAL_SRAM_MSP_INIT_CB_ID : + hsram->MspInitCallback = pCallback; + break; + case DAL_SRAM_MSP_DEINIT_CB_ID : + hsram->MspDeInitCallback = pCallback; + break; + default : + /* update return status */ + status = DAL_ERROR; + break; + } + } + else + { + /* update return status */ + status = DAL_ERROR; + } + + /* Release Lock */ + __DAL_UNLOCK(hsram); + return status; +} + +/** + * @brief Unregister a User SRAM Callback + * SRAM Callback is redirected to the weak (surcharged) predefined callback + * @param hsram : SRAM handle + * @param CallbackId : ID of the callback to be unregistered + * This parameter can be one of the following values: + * @arg @ref DAL_SRAM_MSP_INIT_CB_ID SRAM MspInit callback ID + * @arg @ref DAL_SRAM_MSP_DEINIT_CB_ID SRAM MspDeInit callback ID + * @arg @ref DAL_SRAM_DMA_XFER_CPLT_CB_ID SRAM DMA Xfer Complete callback ID + * @arg @ref DAL_SRAM_DMA_XFER_ERR_CB_ID SRAM DMA Xfer Error callback ID + * @retval status + */ +DAL_StatusTypeDef DAL_SRAM_UnRegisterCallback(SRAM_HandleTypeDef *hsram, DAL_SRAM_CallbackIDTypeDef CallbackId) +{ + DAL_StatusTypeDef status = DAL_OK; + DAL_SRAM_StateTypeDef state; + + /* Process locked */ + __DAL_LOCK(hsram); + + state = hsram->State; + if ((state == DAL_SRAM_STATE_READY) || (state == DAL_SRAM_STATE_PROTECTED)) + { + switch (CallbackId) + { + case DAL_SRAM_MSP_INIT_CB_ID : + hsram->MspInitCallback = DAL_SRAM_MspInit; + break; + case DAL_SRAM_MSP_DEINIT_CB_ID : + hsram->MspDeInitCallback = DAL_SRAM_MspDeInit; + break; + case DAL_SRAM_DMA_XFER_CPLT_CB_ID : + hsram->DmaXferCpltCallback = DAL_SRAM_DMA_XferCpltCallback; + break; + case DAL_SRAM_DMA_XFER_ERR_CB_ID : + hsram->DmaXferErrorCallback = DAL_SRAM_DMA_XferErrorCallback; + break; + default : + /* update return status */ + status = DAL_ERROR; + break; + } + } + else if (state == DAL_SRAM_STATE_RESET) + { + switch (CallbackId) + { + case DAL_SRAM_MSP_INIT_CB_ID : + hsram->MspInitCallback = DAL_SRAM_MspInit; + break; + case DAL_SRAM_MSP_DEINIT_CB_ID : + hsram->MspDeInitCallback = DAL_SRAM_MspDeInit; + break; + default : + /* update return status */ + status = DAL_ERROR; + break; + } + } + else + { + /* update return status */ + status = DAL_ERROR; + } + + /* Release Lock */ + __DAL_UNLOCK(hsram); + return status; +} + +/** + * @brief Register a User SRAM Callback for DMA transfers + * To be used instead of the weak (surcharged) predefined callback + * @param hsram : SRAM handle + * @param CallbackId : ID of the callback to be registered + * This parameter can be one of the following values: + * @arg @ref DAL_SRAM_DMA_XFER_CPLT_CB_ID SRAM DMA Xfer Complete callback ID + * @arg @ref DAL_SRAM_DMA_XFER_ERR_CB_ID SRAM DMA Xfer Error callback ID + * @param pCallback : pointer to the Callback function + * @retval status + */ +DAL_StatusTypeDef DAL_SRAM_RegisterDmaCallback(SRAM_HandleTypeDef *hsram, DAL_SRAM_CallbackIDTypeDef CallbackId, + pSRAM_DmaCallbackTypeDef pCallback) +{ + DAL_StatusTypeDef status = DAL_OK; + DAL_SRAM_StateTypeDef state; + + if (pCallback == NULL) + { + return DAL_ERROR; + } + + /* Process locked */ + __DAL_LOCK(hsram); + + state = hsram->State; + if ((state == DAL_SRAM_STATE_READY) || (state == DAL_SRAM_STATE_PROTECTED)) + { + switch (CallbackId) + { + case DAL_SRAM_DMA_XFER_CPLT_CB_ID : + hsram->DmaXferCpltCallback = pCallback; + break; + case DAL_SRAM_DMA_XFER_ERR_CB_ID : + hsram->DmaXferErrorCallback = pCallback; + break; + default : + /* update return status */ + status = DAL_ERROR; + break; + } + } + else + { + /* update return status */ + status = DAL_ERROR; + } + + /* Release Lock */ + __DAL_UNLOCK(hsram); + return status; +} +#endif /* USE_DAL_SRAM_REGISTER_CALLBACKS */ + +/** + * @} + */ + +/** @defgroup SRAM_Exported_Functions_Group3 Control functions + * @brief Control functions + * +@verbatim + ============================================================================== + ##### SRAM Control functions ##### + ============================================================================== + [..] + This subsection provides a set of functions allowing to control dynamically + the SRAM interface. + +@endverbatim + * @{ + */ + +/** + * @brief Enables dynamically SRAM write operation. + * @param hsram pointer to a SRAM_HandleTypeDef structure that contains + * the configuration information for SRAM module. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SRAM_WriteOperation_Enable(SRAM_HandleTypeDef *hsram) +{ + /* Check the SRAM controller state */ + if (hsram->State == DAL_SRAM_STATE_PROTECTED) + { + /* Process Locked */ + __DAL_LOCK(hsram); + + /* Update the SRAM controller state */ + hsram->State = DAL_SRAM_STATE_BUSY; + + /* Enable write operation */ + (void)FMC_NORSRAM_WriteOperation_Enable(hsram->Instance, hsram->Init.NSBank); + + /* Update the SRAM controller state */ + hsram->State = DAL_SRAM_STATE_READY; + + /* Process unlocked */ + __DAL_UNLOCK(hsram); + } + else + { + return DAL_ERROR; + } + + return DAL_OK; +} + +/** + * @brief Disables dynamically SRAM write operation. + * @param hsram pointer to a SRAM_HandleTypeDef structure that contains + * the configuration information for SRAM module. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_SRAM_WriteOperation_Disable(SRAM_HandleTypeDef *hsram) +{ + /* Check the SRAM controller state */ + if (hsram->State == DAL_SRAM_STATE_READY) + { + /* Process Locked */ + __DAL_LOCK(hsram); + + /* Update the SRAM controller state */ + hsram->State = DAL_SRAM_STATE_BUSY; + + /* Disable write operation */ + (void)FMC_NORSRAM_WriteOperation_Disable(hsram->Instance, hsram->Init.NSBank); + + /* Update the SRAM controller state */ + hsram->State = DAL_SRAM_STATE_PROTECTED; + + /* Process unlocked */ + __DAL_UNLOCK(hsram); + } + else + { + return DAL_ERROR; + } + + return DAL_OK; +} + +/** + * @} + */ + +/** @defgroup SRAM_Exported_Functions_Group4 Peripheral State functions + * @brief Peripheral State functions + * +@verbatim + ============================================================================== + ##### SRAM State functions ##### + ============================================================================== + [..] + This subsection permits to get in run-time the status of the SRAM controller + and the data flow. + +@endverbatim + * @{ + */ + +/** + * @brief Returns the SRAM controller state + * @param hsram pointer to a SRAM_HandleTypeDef structure that contains + * the configuration information for SRAM module. + * @retval DAL state + */ +DAL_SRAM_StateTypeDef DAL_SRAM_GetState(SRAM_HandleTypeDef *hsram) +{ + return hsram->State; +} + +/** + * @} + */ + +/** + * @} + */ + +/** + * @brief DMA SRAM process complete callback. + * @param hdma : DMA handle + * @retval None + */ +static void SRAM_DMACplt(DMA_HandleTypeDef *hdma) +{ + SRAM_HandleTypeDef *hsram = (SRAM_HandleTypeDef *)(hdma->Parent); + + /* Disable the DMA channel */ + __DAL_DMA_DISABLE(hdma); + + /* Update the SRAM controller state */ + hsram->State = DAL_SRAM_STATE_READY; + +#if (USE_DAL_SRAM_REGISTER_CALLBACKS == 1) + hsram->DmaXferCpltCallback(hdma); +#else + DAL_SRAM_DMA_XferCpltCallback(hdma); +#endif /* USE_DAL_SRAM_REGISTER_CALLBACKS */ +} + +/** + * @brief DMA SRAM process complete callback. + * @param hdma : DMA handle + * @retval None + */ +static void SRAM_DMACpltProt(DMA_HandleTypeDef *hdma) +{ + SRAM_HandleTypeDef *hsram = (SRAM_HandleTypeDef *)(hdma->Parent); + + /* Disable the DMA channel */ + __DAL_DMA_DISABLE(hdma); + + /* Update the SRAM controller state */ + hsram->State = DAL_SRAM_STATE_PROTECTED; + +#if (USE_DAL_SRAM_REGISTER_CALLBACKS == 1) + hsram->DmaXferCpltCallback(hdma); +#else + DAL_SRAM_DMA_XferCpltCallback(hdma); +#endif /* USE_DAL_SRAM_REGISTER_CALLBACKS */ +} + +/** + * @brief DMA SRAM error callback. + * @param hdma : DMA handle + * @retval None + */ +static void SRAM_DMAError(DMA_HandleTypeDef *hdma) +{ + SRAM_HandleTypeDef *hsram = (SRAM_HandleTypeDef *)(hdma->Parent); + + /* Disable the DMA channel */ + __DAL_DMA_DISABLE(hdma); + + /* Update the SRAM controller state */ + hsram->State = DAL_SRAM_STATE_ERROR; + +#if (USE_DAL_SRAM_REGISTER_CALLBACKS == 1) + hsram->DmaXferErrorCallback(hdma); +#else + DAL_SRAM_DMA_XferErrorCallback(hdma); +#endif /* USE_DAL_SRAM_REGISTER_CALLBACKS */ +} + +/** + * @} + */ + +#endif /* DAL_SRAM_MODULE_ENABLED */ + +/** + * @} + */ + +#endif /* SMC_Bank1 */ diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_timebase_rtc_alarm_template.c b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_timebase_rtc_alarm_template.c new file mode 100644 index 0000000000..2c6302e5f1 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_timebase_rtc_alarm_template.c @@ -0,0 +1,343 @@ +/** + * + * @file apm32f4xx_dal_timebase_rtc_alarm_template.c + * @brief DAL time base based on the hardware RTC_ALARM Template. + * + * This file override the native DAL time base functions (defined as weak) + * to use the RTC ALARM for time base generation: + * + Intializes the RTC peripheral to increment the seconds registers each 1ms + * + The alarm is configured to assert an interrupt when the RTC reaches 1ms + * + DAL_IncTick is called at each Alarm event and the time is reset to 00:00:00 + * + HSE (default), LSE or LSI can be selected as RTC clock source + * + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2017 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + * + @verbatim + ============================================================================== + ##### How to use this driver ##### + ============================================================================== + [..] + This file must be copied to the application folder and modified as follows: + (#) Rename it to 'apm32f4xx_dal_timebase_rtc_alarm.c' + (#) Add this file and the RTC DAL drivers to your project and uncomment + DAL_RTC_MODULE_ENABLED define in apm32f4xx_dal_cfg.h + + [..] + (@) DAL RTC alarm and DAL RTC wakeup drivers can not be used with low power modes: + The wake up capability of the RTC may be intrusive in case of prior low power mode + configuration requiring different wake up sources. + Application/Example behavior is no more guaranteed + (@) The apm32f4xx_dal_timebase_tim use is recommended for the Applications/Examples + requiring low power modes + + @endverbatim + * + */ + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal.h" +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @defgroup DAL_TimeBase_RTC_Alarm_Template DAL TimeBase RTC Alarm Template + * @{ + */ + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ + +/* Uncomment the line below to select the appropriate RTC Clock source for your application: + + RTC_CLOCK_SOURCE_HSE: can be selected for applications requiring timing precision. + + RTC_CLOCK_SOURCE_LSE: can be selected for applications with low constraint on timing + precision. + + RTC_CLOCK_SOURCE_LSI: can be selected for applications with low constraint on timing + precision. + */ +#define RTC_CLOCK_SOURCE_HSE +/* #define RTC_CLOCK_SOURCE_LSE */ +/* #define RTC_CLOCK_SOURCE_LSI */ + +#ifdef RTC_CLOCK_SOURCE_HSE + #define RTC_ASYNCH_PREDIV 99U + #define RTC_SYNCH_PREDIV 9U + #define RCM_RTCCLKSOURCE_1MHZ ((uint32_t)((uint32_t)RCM_BDCTRL_RTCSRCSEL | (uint32_t)((HSE_VALUE/1000000U) << 16U))) +#else /* RTC_CLOCK_SOURCE_LSE || RTC_CLOCK_SOURCE_LSI */ + #define RTC_ASYNCH_PREDIV 0U + #define RTC_SYNCH_PREDIV 31U +#endif /* RTC_CLOCK_SOURCE_HSE */ + +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +RTC_HandleTypeDef hRTC_Handle; +/* Private function prototypes -----------------------------------------------*/ +void RTC_Alarm_IRQHandler(void); +/* Private functions ---------------------------------------------------------*/ + +/** + * @brief This function configures the RTC_ALARMA as a time base source. + * The time source is configured to have 1ms time base with a dedicated + * Tick interrupt priority. + * @note This function is called automatically at the beginning of program after + * reset by DAL_Init() or at any time when clock is configured, by DAL_RCM_ClockConfig(). + * @param TickPriority Tick interrupt priority. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_InitTick(uint32_t TickPriority) +{ + __IO uint32_t counter = 0U; + + RCM_OscInitTypeDef RCM_OscInitStruct; + RCM_PeriphCLKInitTypeDef PeriphClkInitStruct; + DAL_StatusTypeDef status; + +#ifdef RTC_CLOCK_SOURCE_LSE + /* Configue LSE as RTC clock soucre */ + RCM_OscInitStruct.OscillatorType = RCM_OSCILLATORTYPE_LSE; + RCM_OscInitStruct.PLL.PLLState = RCM_PLL_NONE; + RCM_OscInitStruct.LSEState = RCM_LSE_ON; + PeriphClkInitStruct.RTCClockSelection = RCM_RTCCLKSOURCE_LSE; +#elif defined (RTC_CLOCK_SOURCE_LSI) + /* Configue LSI as RTC clock soucre */ + RCM_OscInitStruct.OscillatorType = RCM_OSCILLATORTYPE_LSI; + RCM_OscInitStruct.PLL.PLLState = RCM_PLL_NONE; + RCM_OscInitStruct.LSIState = RCM_LSI_ON; + PeriphClkInitStruct.RTCClockSelection = RCM_RTCCLKSOURCE_LSI; +#elif defined (RTC_CLOCK_SOURCE_HSE) + /* Configue HSE as RTC clock soucre */ + RCM_OscInitStruct.OscillatorType = RCM_OSCILLATORTYPE_HSE; + RCM_OscInitStruct.PLL.PLLState = RCM_PLL_NONE; + RCM_OscInitStruct.HSEState = RCM_HSE_ON; + /* Ensure that RTC is clocked by 1MHz */ + PeriphClkInitStruct.RTCClockSelection = RCM_RTCCLKSOURCE_1MHZ; +#else +#error Please select the RTC Clock source +#endif /* RTC_CLOCK_SOURCE_LSE */ + + status = DAL_RCM_OscConfig(&RCM_OscInitStruct); + if (status == DAL_OK) + { + PeriphClkInitStruct.PeriphClockSelection = RCM_PERIPHCLK_RTC; + status = DAL_RCMEx_PeriphCLKConfig(&PeriphClkInitStruct); + } + if (status == DAL_OK) + { + /* Enable RTC Clock */ + __DAL_RCM_RTC_ENABLE(); + /* The time base should be 1ms + Time base = ((RTC_ASYNCH_PREDIV + 1) * (RTC_SYNCH_PREDIV + 1)) / RTC_CLOCK + HSE as RTC clock + Time base = ((99 + 1) * (9 + 1)) / 1MHz + = 1ms + LSE as RTC clock + Time base = ((31 + 1) * (0 + 1)) / 32.768KHz + = ~1ms + LSI as RTC clock + Time base = ((31 + 1) * (0 + 1)) / 32KHz + = 1ms + */ + hRTC_Handle.Instance = RTC; + hRTC_Handle.Init.HourFormat = RTC_HOURFORMAT_24; + hRTC_Handle.Init.AsynchPrediv = RTC_ASYNCH_PREDIV; + hRTC_Handle.Init.SynchPrediv = RTC_SYNCH_PREDIV; + hRTC_Handle.Init.OutPut = RTC_OUTPUT_DISABLE; + hRTC_Handle.Init.OutPutPolarity = RTC_OUTPUT_POLARITY_HIGH; + hRTC_Handle.Init.OutPutType = RTC_OUTPUT_TYPE_OPENDRAIN; + status = DAL_RTC_Init(&hRTC_Handle); + } + if (status == DAL_OK) + { + /* Disable the write protection for RTC registers */ + __DAL_RTC_WRITEPROTECTION_DISABLE(&hRTC_Handle); + + /* Disable the Alarm A interrupt */ + __DAL_RTC_ALARMA_DISABLE(&hRTC_Handle); + + /* Clear flag alarm A */ + __DAL_RTC_ALARM_CLEAR_FLAG(&hRTC_Handle, RTC_FLAG_ALRAF); + + counter = 0U; + /* Wait till RTC ALRAWF flag is set and if Time out is reached exit */ + while (__DAL_RTC_ALARM_GET_FLAG(&hRTC_Handle, RTC_FLAG_ALRAWF) == RESET) + { + if (counter++ == (SystemCoreClock / 48U)) /* Timeout = ~ 1s */ + { + status = DAL_ERROR; + } + } + } + if (status == DAL_OK) + { + hRTC_Handle.Instance->ALRMA = (uint32_t)0x01U; + + /* Configure the Alarm state: Enable Alarm */ + __DAL_RTC_ALARMA_ENABLE(&hRTC_Handle); + /* Configure the Alarm interrupt */ + __DAL_RTC_ALARM_ENABLE_IT(&hRTC_Handle, RTC_IT_ALRA); + + /* RTC Alarm Interrupt Configuration: EXTI configuration */ + __DAL_RTC_ALARM_EINT_ENABLE_IT(); + __DAL_RTC_ALARM_EINT_ENABLE_RISING_EDGE(); + + /* Check if the Initialization mode is set */ + if ((hRTC_Handle.Instance->STS & RTC_STS_RINITFLG) == (uint32_t)RESET) + { + /* Set the Initialization mode */ + hRTC_Handle.Instance->STS = (uint32_t)RTC_INIT_MASK; + counter = 0U; + while ((hRTC_Handle.Instance->STS & RTC_STS_RINITFLG) == (uint32_t)RESET) + { + if (counter++ == (SystemCoreClock / 48U)) /* Timeout = ~ 1s */ + { + status = DAL_ERROR; + } + } + } + } + if (status == DAL_OK) + { + hRTC_Handle.Instance->DATE = 0U; + hRTC_Handle.Instance->TIME = 0U; + + hRTC_Handle.Instance->STS &= (uint32_t)~RTC_STS_INITEN; + + /* Enable the write protection for RTC registers */ + __DAL_RTC_WRITEPROTECTION_ENABLE(&hRTC_Handle); + + /* Enable the RTC Alarm Interrupt */ + DAL_NVIC_EnableIRQ(RTC_Alarm_IRQn); + + /* Configure the SysTick IRQ priority */ + if (TickPriority < (1UL << __NVIC_PRIO_BITS)) + { + DAL_NVIC_SetPriority(RTC_Alarm_IRQn, TickPriority, 0U); + uwTickPrio = TickPriority; + } + else + { + status = DAL_ERROR; + } + + } + return status; +} + +/** + * @brief Suspend Tick increment. + * @note Disable the tick increment by disabling RTC ALARM interrupt. + * @retval None + */ +void DAL_SuspendTick(void) +{ + /* Disable the write protection for RTC registers */ + __DAL_RTC_WRITEPROTECTION_DISABLE(&hRTC_Handle); + /* Disable RTC ALARM update Interrupt */ + __DAL_RTC_ALARM_DISABLE_IT(&hRTC_Handle, RTC_IT_ALRA); + /* Enable the write protection for RTC registers */ + __DAL_RTC_WRITEPROTECTION_ENABLE(&hRTC_Handle); +} + +/** + * @brief Resume Tick increment. + * @note Enable the tick increment by Enabling RTC ALARM interrupt. + * @retval None + */ +void DAL_ResumeTick(void) +{ + /* Disable the write protection for RTC registers */ + __DAL_RTC_WRITEPROTECTION_DISABLE(&hRTC_Handle); + /* Enable RTC ALARM Update interrupt */ + __DAL_RTC_ALARM_ENABLE_IT(&hRTC_Handle, RTC_IT_ALRA); + /* Enable the write protection for RTC registers */ + __DAL_RTC_WRITEPROTECTION_ENABLE(&hRTC_Handle); +} + +/** + * @brief ALARM A Event Callback in non blocking mode + * @note This function is called when RTC_ALARM interrupt took place, inside + * RTC_ALARM_IRQHandler(). It makes a direct call to DAL_IncTick() to increment + * a global variable "uwTick" used as application time base. + * @param hrtc RTC handle + * @retval None + */ +void DAL_RTC_AlarmAEventCallback(RTC_HandleTypeDef *hrtc) +{ + __IO uint32_t counter = 0U; + + DAL_IncTick(); + + __DAL_RTC_WRITEPROTECTION_DISABLE(hrtc); + + /* Set the Initialization mode */ + hrtc->Instance->STS = (uint32_t)RTC_INIT_MASK; + + while((hrtc->Instance->STS & RTC_STS_RINITFLG) == (uint32_t)RESET) + { + if(counter++ == (SystemCoreClock /48U)) /* Timeout = ~ 1s */ + { + break; + } + } + + hrtc->Instance->DATE = 0U; + hrtc->Instance->TIME = 0U; + + hrtc->Instance->STS &= (uint32_t)~RTC_STS_INITEN; + + /* Enable the write protection for RTC registers */ + __DAL_RTC_WRITEPROTECTION_ENABLE(hrtc); +} + +/** + * @brief This function handles RTC ALARM interrupt request. + * @retval None + */ +void RTC_Alarm_IRQHandler(void) +{ + DAL_RTC_AlarmIRQHandler(&hRTC_Handle); +} + +/** + * @} + */ + +/** + * @} + */ + + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_timebase_rtc_wakeup_template.c b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_timebase_rtc_wakeup_template.c new file mode 100644 index 0000000000..bb29c3f579 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_timebase_rtc_wakeup_template.c @@ -0,0 +1,318 @@ +/** + * + * @file apm32f4xx_dal_timebase_rtc_wakeup_template.c + * @brief DAL time base based on the hardware RTC_WAKEUP Template. + * + * This file overrides the native DAL time base functions (defined as weak) + * to use the RTC WAKEUP for the time base generation: + * + Intializes the RTC peripheral and configures the wakeup timer to be + * incremented each 1ms + * + The wakeup feature is configured to assert an interrupt each 1ms + * + DAL_IncTick is called inside the DAL_RTCEx_WakeUpTimerEventCallback + * + HSE (default), LSE or LSI can be selected as RTC clock source + * + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2017 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + * + @verbatim + ============================================================================== + ##### How to use this driver ##### + ============================================================================== + [..] + This file must be copied to the application folder and modified as follows: + (#) Rename it to 'apm32f4xx_dal_timebase_rtc_wakeup.c' + (#) Add this file and the RTC DAL drivers to your project and uncomment + DAL_RTC_MODULE_ENABLED define in apm32f4xx_dal_cfg.h + + [..] + (@) DAL RTC alarm and DAL RTC wakeup drivers can not be used with low power modes: + The wake up capability of the RTC may be intrusive in case of prior low power mode + configuration requiring different wake up sources. + Application/Example behavior is no more guaranteed + (@) The apm32f4xx_dal_timebase_tim use is recommended for the Applications/Examples + requiring low power modes + + @endverbatim + * + */ + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal.h" +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @defgroup DAL_TimeBase_RTC_WakeUp_Template DAL TimeBase RTC WakeUp Template + * @{ + */ + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ + +/* Uncomment the line below to select the appropriate RTC Clock source for your application: + + RTC_CLOCK_SOURCE_HSE: can be selected for applications requiring timing precision. + + RTC_CLOCK_SOURCE_LSE: can be selected for applications with low constraint on timing + precision. + + RTC_CLOCK_SOURCE_LSI: can be selected for applications with low constraint on timing + precision. + */ +#define RTC_CLOCK_SOURCE_HSE +/* #define RTC_CLOCK_SOURCE_LSE */ +/* #define RTC_CLOCK_SOURCE_LSI */ + +#ifdef RTC_CLOCK_SOURCE_HSE + #define RTC_ASYNCH_PREDIV 99U + #define RTC_SYNCH_PREDIV 9U + #define RCM_RTCCLKSOURCE_1MHZ ((uint32_t)((uint32_t)RCM_BDCTRL_RTCSRCSEL | (uint32_t)((HSE_VALUE/1000000U) << 16U))) +#else /* RTC_CLOCK_SOURCE_LSE || RTC_CLOCK_SOURCE_LSI */ + #define RTC_ASYNCH_PREDIV 0U + #define RTC_SYNCH_PREDIV 31U +#endif /* RTC_CLOCK_SOURCE_HSE */ + +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +RTC_HandleTypeDef hRTC_Handle; + +/* Private function prototypes -----------------------------------------------*/ +void RTC_WKUP_IRQHandler(void); + +/* Private functions ---------------------------------------------------------*/ + +/** + * @brief This function configures the RTC_WKUP as a time base source. + * The time source is configured to have 1ms time base with a dedicated + * Tick interrupt priority. + * Wakeup Time base = ((RTC_ASYNCH_PREDIV + 1) * (RTC_SYNCH_PREDIV + 1)) / RTC_CLOCK + = 1ms + * Wakeup Time = WakeupTimebase * WakeUpCounter (0 + 1) + = 1 ms + * @note This function is called automatically at the beginning of program after + * reset by DAL_Init() or at any time when clock is configured, by DAL_RCM_ClockConfig(). + * @param TickPriority Tick interrupt priority. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_InitTick (uint32_t TickPriority) +{ + __IO uint32_t counter = 0U; + + RCM_OscInitTypeDef RCM_OscInitStruct; + RCM_PeriphCLKInitTypeDef PeriphClkInitStruct; + DAL_StatusTypeDef status; + +#ifdef RTC_CLOCK_SOURCE_LSE + /* Configue LSE as RTC clock soucre */ + RCM_OscInitStruct.OscillatorType = RCM_OSCILLATORTYPE_LSE; + RCM_OscInitStruct.PLL.PLLState = RCM_PLL_NONE; + RCM_OscInitStruct.LSEState = RCM_LSE_ON; + PeriphClkInitStruct.RTCClockSelection = RCM_RTCCLKSOURCE_LSE; +#elif defined (RTC_CLOCK_SOURCE_LSI) + /* Configue LSI as RTC clock soucre */ + RCM_OscInitStruct.OscillatorType = RCM_OSCILLATORTYPE_LSI; + RCM_OscInitStruct.PLL.PLLState = RCM_PLL_NONE; + RCM_OscInitStruct.LSIState = RCM_LSI_ON; + PeriphClkInitStruct.RTCClockSelection = RCM_RTCCLKSOURCE_LSI; +#elif defined (RTC_CLOCK_SOURCE_HSE) + /* Configue HSE as RTC clock soucre */ + RCM_OscInitStruct.OscillatorType = RCM_OSCILLATORTYPE_HSE; + RCM_OscInitStruct.PLL.PLLState = RCM_PLL_NONE; + RCM_OscInitStruct.HSEState = RCM_HSE_ON; + /* Ensure that RTC is clocked by 1MHz */ + PeriphClkInitStruct.RTCClockSelection = RCM_RTCCLKSOURCE_1MHZ; +#else +#error Please select the RTC Clock source +#endif /* RTC_CLOCK_SOURCE_LSE */ + + status = DAL_RCM_OscConfig(&RCM_OscInitStruct); + if (status == DAL_OK) + { + PeriphClkInitStruct.PeriphClockSelection = RCM_PERIPHCLK_RTC; + status = DAL_RCMEx_PeriphCLKConfig(&PeriphClkInitStruct); + } + if (status == DAL_OK) + { + /* Enable RTC Clock */ + __DAL_RCM_RTC_ENABLE(); + /* The time base should be 1ms + Time base = ((RTC_ASYNCH_PREDIV + 1) * (RTC_SYNCH_PREDIV + 1)) / RTC_CLOCK + HSE as RTC clock + Time base = ((99 + 1) * (9 + 1)) / 1Mhz + = 1ms + LSE as RTC clock + Time base = ((31 + 1) * (0 + 1)) / 32.768Khz + = ~1ms + LSI as RTC clock + Time base = ((31 + 1) * (0 + 1)) / 32Khz + = 1ms + */ + hRTC_Handle.Instance = RTC; + hRTC_Handle.Init.HourFormat = RTC_HOURFORMAT_24; + hRTC_Handle.Init.AsynchPrediv = RTC_ASYNCH_PREDIV; + hRTC_Handle.Init.SynchPrediv = RTC_SYNCH_PREDIV; + hRTC_Handle.Init.OutPut = RTC_OUTPUT_DISABLE; + hRTC_Handle.Init.OutPutPolarity = RTC_OUTPUT_POLARITY_HIGH; + hRTC_Handle.Init.OutPutType = RTC_OUTPUT_TYPE_OPENDRAIN; + status = DAL_RTC_Init(&hRTC_Handle); + } + if (status == DAL_OK) + { + /* Disable the write protection for RTC registers */ + __DAL_RTC_WRITEPROTECTION_DISABLE(&hRTC_Handle); + + /* Disable the Wake-up Timer */ + __DAL_RTC_WAKEUPTIMER_DISABLE(&hRTC_Handle); + + /* In case of interrupt mode is used, the interrupt source must disabled */ + __DAL_RTC_WAKEUPTIMER_DISABLE_IT(&hRTC_Handle, RTC_IT_WUT); + + /* Wait till RTC WUTWF flag is set */ + while (__DAL_RTC_WAKEUPTIMER_GET_FLAG(&hRTC_Handle, RTC_FLAG_WUTWF) == RESET) + { + if (counter++ == (SystemCoreClock / 48U)) + { + status = DAL_ERROR; + } + } + } + if (status == DAL_OK) + { + /* Clear PMU wake up Flag */ + __DAL_PMU_CLEAR_FLAG(PMU_FLAG_WU); + + /* Clear RTC Wake Up timer Flag */ + __DAL_RTC_WAKEUPTIMER_CLEAR_FLAG(&hRTC_Handle, RTC_FLAG_WUTF); + + /* Configure the Wake-up Timer counter */ + hRTC_Handle.Instance->AUTORLD = 0U; + + /* Clear the Wake-up Timer clock source bits in CTRL register */ + hRTC_Handle.Instance->CTRL &= (uint32_t)~RTC_CTRL_WUCLKSEL; + + /* Configure the clock source */ + hRTC_Handle.Instance->CTRL |= (uint32_t)RTC_WAKEUPCLOCK_CK_SPRE_16BITS; + + /* RTC WakeUpTimer Interrupt Configuration: EXTI configuration */ + __DAL_RTC_WAKEUPTIMER_EINT_ENABLE_IT(); + + __DAL_RTC_WAKEUPTIMER_EINT_ENABLE_RISING_EDGE(); + + /* Configure the Interrupt in the RTC_CTRL register */ + __DAL_RTC_WAKEUPTIMER_ENABLE_IT(&hRTC_Handle,RTC_IT_WUT); + + /* Enable the Wake-up Timer */ + __DAL_RTC_WAKEUPTIMER_ENABLE(&hRTC_Handle); + + /* Enable the write protection for RTC registers */ + __DAL_RTC_WRITEPROTECTION_ENABLE(&hRTC_Handle); + + /* Enable the RTC global Interrupt */ + DAL_NVIC_EnableIRQ(RTC_WKUP_IRQn); + + /* Configure the SysTick IRQ priority */ + if (TickPriority < (1UL << __NVIC_PRIO_BITS)) + { + DAL_NVIC_SetPriority(RTC_WKUP_IRQn, TickPriority, 0U); + uwTickPrio = TickPriority; + } + else + { + status = DAL_ERROR; + } + } + return status; +} + +/** + * @brief Suspend Tick increment. + * @note Disable the tick increment by disabling RTC_WKUP interrupt. + * @retval None + */ +void DAL_SuspendTick(void) +{ + /* Disable the write protection for RTC registers */ + __DAL_RTC_WRITEPROTECTION_DISABLE(&hRTC_Handle); + /* Disable WAKE UP TIMER Interrupt */ + __DAL_RTC_WAKEUPTIMER_DISABLE_IT(&hRTC_Handle, RTC_IT_WUT); + /* Enable the write protection for RTC registers */ + __DAL_RTC_WRITEPROTECTION_ENABLE(&hRTC_Handle); +} + +/** + * @brief Resume Tick increment. + * @note Enable the tick increment by Enabling RTC_WKUP interrupt. + * @retval None + */ +void DAL_ResumeTick(void) +{ + /* Disable the write protection for RTC registers */ + __DAL_RTC_WRITEPROTECTION_DISABLE(&hRTC_Handle); + /* Enable WAKE UP TIMER interrupt */ + __DAL_RTC_WAKEUPTIMER_ENABLE_IT(&hRTC_Handle, RTC_IT_WUT); + /* Enable the write protection for RTC registers */ + __DAL_RTC_WRITEPROTECTION_ENABLE(&hRTC_Handle); +} + +/** + * @brief Wake Up Timer Event Callback in non blocking mode + * @note This function is called when RTC_WKUP interrupt took place, inside + * RTC_WKUP_IRQHandler(). It makes a direct call to DAL_IncTick() to increment + * a global variable "uwTick" used as application time base. + * @param hrtc RTC handle + * @retval None + */ +void DAL_RTCEx_WakeUpTimerEventCallback(RTC_HandleTypeDef *hrtc) +{ + DAL_IncTick(); +} + +/** + * @brief This function handles WAKE UP TIMER interrupt request. + * @retval None + */ +void RTC_WKUP_IRQHandler(void) +{ + DAL_RTCEx_WakeUpTimerIRQHandler(&hRTC_Handle); +} + +/** + * @} + */ + +/** + * @} + */ + + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_timebase_tmr_template.c b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_timebase_tmr_template.c new file mode 100644 index 0000000000..173e72862c --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_timebase_tmr_template.c @@ -0,0 +1,202 @@ +/** + * + * @file apm32f4xx_dal_timebase_tmr_template.c + * @brief DAL time base based on the hardware TMR Template. + * + * This file overrides the native DAL time base functions (defined as weak) + * the TMR time base: + * + Intializes the TMR peripheral generate a Period elapsed Event each 1ms + * + DAL_IncTick is called inside DAL_TMR_PeriodElapsedCallback ie each 1ms + * + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2017 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + * + */ + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @addtogroup DAL_TimeBase_TMR + * @{ + */ + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +TMR_HandleTypeDef TmrHandle; +/* Private function prototypes -----------------------------------------------*/ +void TMR6_DAC_IRQHandler(void); +/* Private functions ---------------------------------------------------------*/ + +/** + * @brief This function configures the TMR6 as a time base source. + * The time source is configured to have 1ms time base with a dedicated + * Tick interrupt priority. + * @note This function is called automatically at the beginning of program after + * reset by DAL_Init() or at any time when clock is configured, by DAL_RCM_ClockConfig(). + * @param TickPriority Tick interrupt priority. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_InitTick (uint32_t TickPriority) +{ + RCM_ClkInitTypeDef clkconfig; + uint32_t uwTimclock, uwAPB1Prescaler = 0U; + uint32_t uwPrescalerValue = 0U; + uint32_t pFLatency; + DAL_StatusTypeDef status; + + /* Enable TMR6 clock */ + __DAL_RCM_TMR6_CLK_ENABLE(); + + /* Get clock configuration */ + DAL_RCM_GetClockConfig(&clkconfig, &pFLatency); + + /* Get APB1 prescaler */ + uwAPB1Prescaler = clkconfig.APB1CLKDivider; + + /* Compute TMR6 clock */ + if (uwAPB1Prescaler == RCM_HCLK_DIV1) + { + uwTimclock = DAL_RCM_GetPCLK1Freq(); + } + else + { + uwTimclock = 2 * DAL_RCM_GetPCLK1Freq(); + } + + /* Compute the prescaler value to have TMR6 counter clock equal to 1MHz */ + uwPrescalerValue = (uint32_t) ((uwTimclock / 1000000U) - 1U); + + /* Initialize TMR6 */ + TmrHandle.Instance = TMR6; + + /* Initialize TMRx peripheral as follow: + + Period = [(TMR6CLK/1000) - 1]. to have a (1/1000) s time base. + + Prescaler = (uwTimclock/1000000 - 1) to have a 1MHz counter clock. + + ClockDivision = 0 + + Counter direction = Up + */ + TmrHandle.Init.Period = (1000000U / 1000U) - 1U; + TmrHandle.Init.Prescaler = uwPrescalerValue; + TmrHandle.Init.ClockDivision = 0U; + TmrHandle.Init.CounterMode = TMR_COUNTERMODE_UP; + TmrHandle.Init.AutoReloadPreload = TMR_AUTORELOAD_PRELOAD_DISABLE; + status = DAL_TMR_Base_Init(&TmrHandle); + if (status == DAL_OK) + { + /* Start the TMR time Base generation in interrupt mode */ + status = DAL_TMR_Base_Start_IT(&TmrHandle); + if (status == DAL_OK) + { + /* Enable the TMR6 global Interrupt */ + DAL_NVIC_EnableIRQ(TMR6_DAC_IRQn); + + if (TickPriority < (1UL << __NVIC_PRIO_BITS)) + { + /* Enable the TMR6 global Interrupt */ + DAL_NVIC_SetPriority(TMR6_DAC_IRQn, TickPriority, 0); + uwTickPrio = TickPriority; + } + else + { + status = DAL_ERROR; + } + } + } + + /* Return function status */ + return status; +} + +/** + * @brief Suspend Tick increment. + * @note Disable the tick increment by disabling TMR6 update interrupt. + * @retval None + */ +void DAL_SuspendTick(void) +{ + /* Disable TMR6 update Interrupt */ + __DAL_TMR_DISABLE_IT(&TmrHandle, TMR_IT_UPDATE); +} + +/** + * @brief Resume Tick increment. + * @note Enable the tick increment by Enabling TMR6 update interrupt. + * @retval None + */ +void DAL_ResumeTick(void) +{ + /* Enable TMR6 Update interrupt */ + __DAL_TMR_ENABLE_IT(&TmrHandle, TMR_IT_UPDATE); +} + +/** + * @brief Period elapsed callback in non blocking mode + * @note This function is called when TMR6 interrupt took place, inside + * DAL_TMR_IRQHandler(). It makes a direct call to DAL_IncTick() to increment + * a global variable "uwTick" used as application time base. + * @param htmr TMR handle + * @retval None + */ +void DAL_TMR_PeriodElapsedCallback(TMR_HandleTypeDef *htmr) +{ + DAL_IncTick(); +} + +/** + * @brief This function handles TMR interrupt request. + * @retval None + */ +void TMR6_DAC_IRQHandler(void) +{ + DAL_TMR_IRQHandler(&TmrHandle); +} + +/** + * @} + */ + +/** + * @} + */ + + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_tmr.c b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_tmr.c new file mode 100644 index 0000000000..c7d39ba85e --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_tmr.c @@ -0,0 +1,7645 @@ +/** + * + * @file apm32f4xx_dal_tmr.c + * @brief TMR DAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the Timer (TMR) peripheral: + * + TMR Time Base Initialization + * + TMR Time Base Start + * + TMR Time Base Start Interruption + * + TMR Time Base Start DMA + * + TMR Output Compare/PWM Initialization + * + TMR Output Compare/PWM Channel Configuration + * + TMR Output Compare/PWM Start + * + TMR Output Compare/PWM Start Interruption + * + TMR Output Compare/PWM Start DMA + * + TMR Input Capture Initialization + * + TMR Input Capture Channel Configuration + * + TMR Input Capture Start + * + TMR Input Capture Start Interruption + * + TMR Input Capture Start DMA + * + TMR One Pulse Initialization + * + TMR One Pulse Channel Configuration + * + TMR One Pulse Start + * + TMR Encoder Interface Initialization + * + TMR Encoder Interface Start + * + TMR Encoder Interface Start Interruption + * + TMR Encoder Interface Start DMA + * + Commutation Event configuration with Interruption and DMA + * + TMR OCRef clear configuration + * + TMR External Clock configuration + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + * + @verbatim + ============================================================================== + ##### TMRER Generic features ##### + ============================================================================== + [..] The Timer features include: + (#) 16-bit up, down, up/down auto-reload counter. + (#) 16-bit programmable prescaler allowing dividing (also on the fly) the + counter clock frequency either by any factor between 1 and 65536. + (#) Up to 4 independent channels for: + (++) Input Capture + (++) Output Compare + (++) PWM generation (Edge and Center-aligned Mode) + (++) One-pulse mode output + (#) Synchronization circuit to control the timer with external signals and to interconnect + several timers together. + (#) Supports incremental encoder for positioning purposes + + ##### How to use this driver ##### + ============================================================================== + [..] + (#) Initialize the TMR low level resources by implementing the following functions + depending on the selected feature: + (++) Time Base : DAL_TMR_Base_MspInit() + (++) Input Capture : DAL_TMR_IC_MspInit() + (++) Output Compare : DAL_TMR_OC_MspInit() + (++) PWM generation : DAL_TMR_PWM_MspInit() + (++) One-pulse mode output : DAL_TMR_OnePulse_MspInit() + (++) Encoder mode output : DAL_TMR_Encoder_MspInit() + + (#) Initialize the TMR low level resources : + (##) Enable the TMR interface clock using __DAL_RCM_TMRx_CLK_ENABLE(); + (##) TMR pins configuration + (+++) Enable the clock for the TMR GPIOs using the following function: + __DAL_RCM_GPIOx_CLK_ENABLE(); + (+++) Configure these TMR pins in Alternate function mode using DAL_GPIO_Init(); + + (#) The external Clock can be configured, if needed (the default clock is the + internal clock from the APBx), using the following function: + DAL_TMR_ConfigClockSource, the clock configuration should be done before + any start function. + + (#) Configure the TMR in the desired functioning mode using one of the + Initialization function of this driver: + (++) DAL_TMR_Base_Init: to use the Timer to generate a simple time base + (++) DAL_TMR_OC_Init and DAL_TMR_OC_ConfigChannel: to use the Timer to generate an + Output Compare signal. + (++) DAL_TMR_PWM_Init and DAL_TMR_PWM_ConfigChannel: to use the Timer to generate a + PWM signal. + (++) DAL_TMR_IC_Init and DAL_TMR_IC_ConfigChannel: to use the Timer to measure an + external signal. + (++) DAL_TMR_OnePulse_Init and DAL_TMR_OnePulse_ConfigChannel: to use the Timer + in One Pulse Mode. + (++) DAL_TMR_Encoder_Init: to use the Timer Encoder Interface. + + (#) Activate the TMR peripheral using one of the start functions depending from the feature used: + (++) Time Base : DAL_TMR_Base_Start(), DAL_TMR_Base_Start_DMA(), DAL_TMR_Base_Start_IT() + (++) Input Capture : DAL_TMR_IC_Start(), DAL_TMR_IC_Start_DMA(), DAL_TMR_IC_Start_IT() + (++) Output Compare : DAL_TMR_OC_Start(), DAL_TMR_OC_Start_DMA(), DAL_TMR_OC_Start_IT() + (++) PWM generation : DAL_TMR_PWM_Start(), DAL_TMR_PWM_Start_DMA(), DAL_TMR_PWM_Start_IT() + (++) One-pulse mode output : DAL_TMR_OnePulse_Start(), DAL_TMR_OnePulse_Start_IT() + (++) Encoder mode output : DAL_TMR_Encoder_Start(), DAL_TMR_Encoder_Start_DMA(), DAL_TMR_Encoder_Start_IT(). + + (#) The DMA Burst is managed with the two following functions: + DAL_TMR_DMABurst_WriteStart() + DAL_TMR_DMABurst_ReadStart() + + *** Callback registration *** + ============================================= + + [..] + The compilation define USE_DAL_TMR_REGISTER_CALLBACKS when set to 1 + allows the user to configure dynamically the driver callbacks. + + [..] + Use Function DAL_TMR_RegisterCallback() to register a callback. + DAL_TMR_RegisterCallback() takes as parameters the DAL peripheral handle, + the Callback ID and a pointer to the user callback function. + + [..] + Use function DAL_TMR_UnRegisterCallback() to reset a callback to the default + weak function. + DAL_TMR_UnRegisterCallback takes as parameters the DAL peripheral handle, + and the Callback ID. + + [..] + These functions allow to register/unregister following callbacks: + (+) Base_MspInitCallback : TMR Base Msp Init Callback. + (+) Base_MspDeInitCallback : TMR Base Msp DeInit Callback. + (+) IC_MspInitCallback : TMR IC Msp Init Callback. + (+) IC_MspDeInitCallback : TMR IC Msp DeInit Callback. + (+) OC_MspInitCallback : TMR OC Msp Init Callback. + (+) OC_MspDeInitCallback : TMR OC Msp DeInit Callback. + (+) PWM_MspInitCallback : TMR PWM Msp Init Callback. + (+) PWM_MspDeInitCallback : TMR PWM Msp DeInit Callback. + (+) OnePulse_MspInitCallback : TMR One Pulse Msp Init Callback. + (+) OnePulse_MspDeInitCallback : TMR One Pulse Msp DeInit Callback. + (+) Encoder_MspInitCallback : TMR Encoder Msp Init Callback. + (+) Encoder_MspDeInitCallback : TMR Encoder Msp DeInit Callback. + (+) HallSensor_MspInitCallback : TMR Hall Sensor Msp Init Callback. + (+) HallSensor_MspDeInitCallback : TMR Hall Sensor Msp DeInit Callback. + (+) PeriodElapsedCallback : TMR Period Elapsed Callback. + (+) PeriodElapsedHalfCpltCallback : TMR Period Elapsed half complete Callback. + (+) TriggerCallback : TMR Trigger Callback. + (+) TriggerHalfCpltCallback : TMR Trigger half complete Callback. + (+) IC_CaptureCallback : TMR Input Capture Callback. + (+) IC_CaptureHalfCpltCallback : TMR Input Capture half complete Callback. + (+) OC_DelayElapsedCallback : TMR Output Compare Delay Elapsed Callback. + (+) PWM_PulseFinishedCallback : TMR PWM Pulse Finished Callback. + (+) PWM_PulseFinishedHalfCpltCallback : TMR PWM Pulse Finished half complete Callback. + (+) ErrorCallback : TMR Error Callback. + (+) CommutationCallback : TMR Commutation Callback. + (+) CommutationHalfCpltCallback : TMR Commutation half complete Callback. + (+) BreakCallback : TMR Break Callback. + + [..] +By default, after the Init and when the state is DAL_TMR_STATE_RESET +all interrupt callbacks are set to the corresponding weak functions: + examples DAL_TMR_TriggerCallback(), DAL_TMR_ErrorCallback(). + + [..] + Exception done for MspInit and MspDeInit functions that are reset to the legacy weak + functionalities in the Init / DeInit only when these callbacks are null + (not registered beforehand). If not, MspInit or MspDeInit are not null, the Init / DeInit + keep and use the user MspInit / MspDeInit callbacks(registered beforehand) + + [..] + Callbacks can be registered / unregistered in DAL_TMR_STATE_READY state only. + Exception done MspInit / MspDeInit that can be registered / unregistered + in DAL_TMR_STATE_READY or DAL_TMR_STATE_RESET state, + thus registered(user) MspInit / DeInit callbacks can be used during the Init / DeInit. + In that case first register the MspInit/MspDeInit user callbacks + using DAL_TMR_RegisterCallback() before calling DeInit or Init function. + + [..] + When The compilation define USE_DAL_TMR_REGISTER_CALLBACKS is set to 0 or + not defined, the callback registration feature is not available and all callbacks + are set to the corresponding weak functions. + + @endverbatim + * + */ + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @defgroup TMR TMR + * @brief TMR DAL module driver + * @{ + */ + +#ifdef DAL_TMR_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macros ------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/** @addtogroup TMR_Private_Functions + * @{ + */ +static void TMR_OC1_SetConfig(TMR_TypeDef *TMRx, TMR_OC_InitTypeDef *OC_Config); +static void TMR_OC3_SetConfig(TMR_TypeDef *TMRx, TMR_OC_InitTypeDef *OC_Config); +static void TMR_OC4_SetConfig(TMR_TypeDef *TMRx, TMR_OC_InitTypeDef *OC_Config); +static void TMR_TI1_ConfigInputStage(TMR_TypeDef *TMRx, uint32_t TMR_ICPolarity, uint32_t TMR_ICFilter); +static void TMR_TI2_SetConfig(TMR_TypeDef *TMRx, uint32_t TMR_ICPolarity, uint32_t TMR_ICSelection, + uint32_t TMR_ICFilter); +static void TMR_TI2_ConfigInputStage(TMR_TypeDef *TMRx, uint32_t TMR_ICPolarity, uint32_t TMR_ICFilter); +static void TMR_TI3_SetConfig(TMR_TypeDef *TMRx, uint32_t TMR_ICPolarity, uint32_t TMR_ICSelection, + uint32_t TMR_ICFilter); +static void TMR_TI4_SetConfig(TMR_TypeDef *TMRx, uint32_t TMR_ICPolarity, uint32_t TMR_ICSelection, + uint32_t TMR_ICFilter); +static void TMR_ITRx_SetConfig(TMR_TypeDef *TMRx, uint32_t InputTriggerSource); +static void TMR_DMAPeriodElapsedCplt(DMA_HandleTypeDef *hdma); +static void TMR_DMAPeriodElapsedHalfCplt(DMA_HandleTypeDef *hdma); +static void TMR_DMATriggerCplt(DMA_HandleTypeDef *hdma); +static void TMR_DMATriggerHalfCplt(DMA_HandleTypeDef *hdma); +static DAL_StatusTypeDef TMR_SlaveTimer_SetConfig(TMR_HandleTypeDef *htmr, + TMR_SlaveConfigTypeDef *sSlaveConfig); +/** + * @} + */ +/* Exported functions --------------------------------------------------------*/ + +/** @defgroup TMR_Exported_Functions TMR Exported Functions + * @{ + */ + +/** @defgroup TMR_Exported_Functions_Group1 TMR Time Base functions + * @brief Time Base functions + * +@verbatim + ============================================================================== + ##### Time Base functions ##### + ============================================================================== + [..] + This section provides functions allowing to: + (+) Initialize and configure the TMR base. + (+) De-initialize the TMR base. + (+) Start the Time Base. + (+) Stop the Time Base. + (+) Start the Time Base and enable interrupt. + (+) Stop the Time Base and disable interrupt. + (+) Start the Time Base and enable DMA transfer. + (+) Stop the Time Base and disable DMA transfer. + +@endverbatim + * @{ + */ +/** + * @brief Initializes the TMR Time base Unit according to the specified + * parameters in the TMR_HandleTypeDef and initialize the associated handle. + * @note Switching from Center Aligned counter mode to Edge counter mode (or reverse) + * requires a timer reset to avoid unexpected direction + * due to DIR bit readonly in center aligned mode. + * Ex: call @ref DAL_TMR_Base_DeInit() before DAL_TMR_Base_Init() + * @param htmr TMR Base handle + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMR_Base_Init(TMR_HandleTypeDef *htmr) +{ + /* Check the TMR handle allocation */ + if (htmr == NULL) + { + return DAL_ERROR; + } + + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_INSTANCE(htmr->Instance)); + ASSERT_PARAM(IS_TMR_COUNTER_MODE(htmr->Init.CounterMode)); + ASSERT_PARAM(IS_TMR_CLOCKDIVISION_DIV(htmr->Init.ClockDivision)); + ASSERT_PARAM(IS_TMR_AUTORELOAD_PRELOAD(htmr->Init.AutoReloadPreload)); + + if (htmr->State == DAL_TMR_STATE_RESET) + { + /* Allocate lock resource and initialize it */ + htmr->Lock = DAL_UNLOCKED; + +#if (USE_DAL_TMR_REGISTER_CALLBACKS == 1) + /* Reset interrupt callbacks to legacy weak callbacks */ + TMR_ResetCallback(htmr); + + if (htmr->Base_MspInitCallback == NULL) + { + htmr->Base_MspInitCallback = DAL_TMR_Base_MspInit; + } + /* Init the low level hardware : GPIO, CLOCK, NVIC */ + htmr->Base_MspInitCallback(htmr); +#else + /* Init the low level hardware : GPIO, CLOCK, NVIC */ + DAL_TMR_Base_MspInit(htmr); +#endif /* USE_DAL_TMR_REGISTER_CALLBACKS */ + } + + /* Set the TMR state */ + htmr->State = DAL_TMR_STATE_BUSY; + + /* Set the Time Base configuration */ + TMR_Base_SetConfig(htmr->Instance, &htmr->Init); + + /* Initialize the DMA burst operation state */ + htmr->DMABurstState = DAL_DMA_BURST_STATE_READY; + + /* Initialize the TMR channels state */ + TMR_CHANNEL_STATE_SET_ALL(htmr, DAL_TMR_CHANNEL_STATE_READY); + TMR_CHANNEL_N_STATE_SET_ALL(htmr, DAL_TMR_CHANNEL_STATE_READY); + + /* Initialize the TMR state*/ + htmr->State = DAL_TMR_STATE_READY; + + return DAL_OK; +} + +/** + * @brief DeInitializes the TMR Base peripheral + * @param htmr TMR Base handle + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMR_Base_DeInit(TMR_HandleTypeDef *htmr) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_INSTANCE(htmr->Instance)); + + htmr->State = DAL_TMR_STATE_BUSY; + + /* Disable the TMR Peripheral Clock */ + __DAL_TMR_DISABLE(htmr); + +#if (USE_DAL_TMR_REGISTER_CALLBACKS == 1) + if (htmr->Base_MspDeInitCallback == NULL) + { + htmr->Base_MspDeInitCallback = DAL_TMR_Base_MspDeInit; + } + /* DeInit the low level hardware */ + htmr->Base_MspDeInitCallback(htmr); +#else + /* DeInit the low level hardware: GPIO, CLOCK, NVIC */ + DAL_TMR_Base_MspDeInit(htmr); +#endif /* USE_DAL_TMR_REGISTER_CALLBACKS */ + + /* Change the DMA burst operation state */ + htmr->DMABurstState = DAL_DMA_BURST_STATE_RESET; + + /* Change the TMR channels state */ + TMR_CHANNEL_STATE_SET_ALL(htmr, DAL_TMR_CHANNEL_STATE_RESET); + TMR_CHANNEL_N_STATE_SET_ALL(htmr, DAL_TMR_CHANNEL_STATE_RESET); + + /* Change TMR state */ + htmr->State = DAL_TMR_STATE_RESET; + + /* Release Lock */ + __DAL_UNLOCK(htmr); + + return DAL_OK; +} + +/** + * @brief Initializes the TMR Base MSP. + * @param htmr TMR Base handle + * @retval None + */ +__weak void DAL_TMR_Base_MspInit(TMR_HandleTypeDef *htmr) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(htmr); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_TMR_Base_MspInit could be implemented in the user file + */ +} + +/** + * @brief DeInitializes TMR Base MSP. + * @param htmr TMR Base handle + * @retval None + */ +__weak void DAL_TMR_Base_MspDeInit(TMR_HandleTypeDef *htmr) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(htmr); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_TMR_Base_MspDeInit could be implemented in the user file + */ +} + + +/** + * @brief Starts the TMR Base generation. + * @param htmr TMR Base handle + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMR_Base_Start(TMR_HandleTypeDef *htmr) +{ + uint32_t tmpsmcr; + + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_INSTANCE(htmr->Instance)); + + /* Check the TMR state */ + if (htmr->State != DAL_TMR_STATE_READY) + { + return DAL_ERROR; + } + + /* Set the TMR state */ + htmr->State = DAL_TMR_STATE_BUSY; + + /* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */ + if (IS_TMR_SLAVE_INSTANCE(htmr->Instance)) + { + tmpsmcr = htmr->Instance->SMCTRL & TMR_SMCTRL_SMFSEL; + if (!IS_TMR_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr)) + { + __DAL_TMR_ENABLE(htmr); + } + } + else + { + __DAL_TMR_ENABLE(htmr); + } + + /* Return function status */ + return DAL_OK; +} + +/** + * @brief Stops the TMR Base generation. + * @param htmr TMR Base handle + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMR_Base_Stop(TMR_HandleTypeDef *htmr) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_INSTANCE(htmr->Instance)); + + /* Disable the Peripheral */ + __DAL_TMR_DISABLE(htmr); + + /* Set the TMR state */ + htmr->State = DAL_TMR_STATE_READY; + + /* Return function status */ + return DAL_OK; +} + +/** + * @brief Starts the TMR Base generation in interrupt mode. + * @param htmr TMR Base handle + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMR_Base_Start_IT(TMR_HandleTypeDef *htmr) +{ + uint32_t tmpsmcr; + + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_INSTANCE(htmr->Instance)); + + /* Check the TMR state */ + if (htmr->State != DAL_TMR_STATE_READY) + { + return DAL_ERROR; + } + + /* Set the TMR state */ + htmr->State = DAL_TMR_STATE_BUSY; + + /* Enable the TMR Update interrupt */ + __DAL_TMR_ENABLE_IT(htmr, TMR_IT_UPDATE); + + /* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */ + if (IS_TMR_SLAVE_INSTANCE(htmr->Instance)) + { + tmpsmcr = htmr->Instance->SMCTRL & TMR_SMCTRL_SMFSEL; + if (!IS_TMR_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr)) + { + __DAL_TMR_ENABLE(htmr); + } + } + else + { + __DAL_TMR_ENABLE(htmr); + } + + /* Return function status */ + return DAL_OK; +} + +/** + * @brief Stops the TMR Base generation in interrupt mode. + * @param htmr TMR Base handle + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMR_Base_Stop_IT(TMR_HandleTypeDef *htmr) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_INSTANCE(htmr->Instance)); + + /* Disable the TMR Update interrupt */ + __DAL_TMR_DISABLE_IT(htmr, TMR_IT_UPDATE); + + /* Disable the Peripheral */ + __DAL_TMR_DISABLE(htmr); + + /* Set the TMR state */ + htmr->State = DAL_TMR_STATE_READY; + + /* Return function status */ + return DAL_OK; +} + +/** + * @brief Starts the TMR Base generation in DMA mode. + * @param htmr TMR Base handle + * @param pData The source Buffer address. + * @param Length The length of data to be transferred from memory to peripheral. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMR_Base_Start_DMA(TMR_HandleTypeDef *htmr, uint32_t *pData, uint16_t Length) +{ + uint32_t tmpsmcr; + + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_DMA_INSTANCE(htmr->Instance)); + + /* Set the TMR state */ + if (htmr->State == DAL_TMR_STATE_BUSY) + { + return DAL_BUSY; + } + else if (htmr->State == DAL_TMR_STATE_READY) + { + if ((pData == NULL) && (Length > 0U)) + { + return DAL_ERROR; + } + else + { + htmr->State = DAL_TMR_STATE_BUSY; + } + } + else + { + return DAL_ERROR; + } + + /* Set the DMA Period elapsed callbacks */ + htmr->hdma[TMR_DMA_ID_UPDATE]->XferCpltCallback = TMR_DMAPeriodElapsedCplt; + htmr->hdma[TMR_DMA_ID_UPDATE]->XferHalfCpltCallback = TMR_DMAPeriodElapsedHalfCplt; + + /* Set the DMA error callback */ + htmr->hdma[TMR_DMA_ID_UPDATE]->XferErrorCallback = TMR_DMAError ; + + /* Enable the DMA stream */ + if (DAL_DMA_Start_IT(htmr->hdma[TMR_DMA_ID_UPDATE], (uint32_t)pData, (uint32_t)&htmr->Instance->AUTORLD, + Length) != DAL_OK) + { + /* Return error status */ + return DAL_ERROR; + } + + /* Enable the TMR Update DMA request */ + __DAL_TMR_ENABLE_DMA(htmr, TMR_DMA_UPDATE); + + /* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */ + if (IS_TMR_SLAVE_INSTANCE(htmr->Instance)) + { + tmpsmcr = htmr->Instance->SMCTRL & TMR_SMCTRL_SMFSEL; + if (!IS_TMR_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr)) + { + __DAL_TMR_ENABLE(htmr); + } + } + else + { + __DAL_TMR_ENABLE(htmr); + } + + /* Return function status */ + return DAL_OK; +} + +/** + * @brief Stops the TMR Base generation in DMA mode. + * @param htmr TMR Base handle + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMR_Base_Stop_DMA(TMR_HandleTypeDef *htmr) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_DMA_INSTANCE(htmr->Instance)); + + /* Disable the TMR Update DMA request */ + __DAL_TMR_DISABLE_DMA(htmr, TMR_DMA_UPDATE); + + (void)DAL_DMA_Abort_IT(htmr->hdma[TMR_DMA_ID_UPDATE]); + + /* Disable the Peripheral */ + __DAL_TMR_DISABLE(htmr); + + /* Set the TMR state */ + htmr->State = DAL_TMR_STATE_READY; + + /* Return function status */ + return DAL_OK; +} + +/** + * @} + */ + +/** @defgroup TMR_Exported_Functions_Group2 TMR Output Compare functions + * @brief TMR Output Compare functions + * +@verbatim + ============================================================================== + ##### TMR Output Compare functions ##### + ============================================================================== + [..] + This section provides functions allowing to: + (+) Initialize and configure the TMR Output Compare. + (+) De-initialize the TMR Output Compare. + (+) Start the TMR Output Compare. + (+) Stop the TMR Output Compare. + (+) Start the TMR Output Compare and enable interrupt. + (+) Stop the TMR Output Compare and disable interrupt. + (+) Start the TMR Output Compare and enable DMA transfer. + (+) Stop the TMR Output Compare and disable DMA transfer. + +@endverbatim + * @{ + */ +/** + * @brief Initializes the TMR Output Compare according to the specified + * parameters in the TMR_HandleTypeDef and initializes the associated handle. + * @note Switching from Center Aligned counter mode to Edge counter mode (or reverse) + * requires a timer reset to avoid unexpected direction + * due to DIR bit readonly in center aligned mode. + * Ex: call @ref DAL_TMR_OC_DeInit() before DAL_TMR_OC_Init() + * @param htmr TMR Output Compare handle + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMR_OC_Init(TMR_HandleTypeDef *htmr) +{ + /* Check the TMR handle allocation */ + if (htmr == NULL) + { + return DAL_ERROR; + } + + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_INSTANCE(htmr->Instance)); + ASSERT_PARAM(IS_TMR_COUNTER_MODE(htmr->Init.CounterMode)); + ASSERT_PARAM(IS_TMR_CLOCKDIVISION_DIV(htmr->Init.ClockDivision)); + ASSERT_PARAM(IS_TMR_AUTORELOAD_PRELOAD(htmr->Init.AutoReloadPreload)); + + if (htmr->State == DAL_TMR_STATE_RESET) + { + /* Allocate lock resource and initialize it */ + htmr->Lock = DAL_UNLOCKED; + +#if (USE_DAL_TMR_REGISTER_CALLBACKS == 1) + /* Reset interrupt callbacks to legacy weak callbacks */ + TMR_ResetCallback(htmr); + + if (htmr->OC_MspInitCallback == NULL) + { + htmr->OC_MspInitCallback = DAL_TMR_OC_MspInit; + } + /* Init the low level hardware : GPIO, CLOCK, NVIC */ + htmr->OC_MspInitCallback(htmr); +#else + /* Init the low level hardware : GPIO, CLOCK, NVIC and DMA */ + DAL_TMR_OC_MspInit(htmr); +#endif /* USE_DAL_TMR_REGISTER_CALLBACKS */ + } + + /* Set the TMR state */ + htmr->State = DAL_TMR_STATE_BUSY; + + /* Init the base time for the Output Compare */ + TMR_Base_SetConfig(htmr->Instance, &htmr->Init); + + /* Initialize the DMA burst operation state */ + htmr->DMABurstState = DAL_DMA_BURST_STATE_READY; + + /* Initialize the TMR channels state */ + TMR_CHANNEL_STATE_SET_ALL(htmr, DAL_TMR_CHANNEL_STATE_READY); + TMR_CHANNEL_N_STATE_SET_ALL(htmr, DAL_TMR_CHANNEL_STATE_READY); + + /* Initialize the TMR state*/ + htmr->State = DAL_TMR_STATE_READY; + + return DAL_OK; +} + +/** + * @brief DeInitializes the TMR peripheral + * @param htmr TMR Output Compare handle + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMR_OC_DeInit(TMR_HandleTypeDef *htmr) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_INSTANCE(htmr->Instance)); + + htmr->State = DAL_TMR_STATE_BUSY; + + /* Disable the TMR Peripheral Clock */ + __DAL_TMR_DISABLE(htmr); + +#if (USE_DAL_TMR_REGISTER_CALLBACKS == 1) + if (htmr->OC_MspDeInitCallback == NULL) + { + htmr->OC_MspDeInitCallback = DAL_TMR_OC_MspDeInit; + } + /* DeInit the low level hardware */ + htmr->OC_MspDeInitCallback(htmr); +#else + /* DeInit the low level hardware: GPIO, CLOCK, NVIC and DMA */ + DAL_TMR_OC_MspDeInit(htmr); +#endif /* USE_DAL_TMR_REGISTER_CALLBACKS */ + + /* Change the DMA burst operation state */ + htmr->DMABurstState = DAL_DMA_BURST_STATE_RESET; + + /* Change the TMR channels state */ + TMR_CHANNEL_STATE_SET_ALL(htmr, DAL_TMR_CHANNEL_STATE_RESET); + TMR_CHANNEL_N_STATE_SET_ALL(htmr, DAL_TMR_CHANNEL_STATE_RESET); + + /* Change TMR state */ + htmr->State = DAL_TMR_STATE_RESET; + + /* Release Lock */ + __DAL_UNLOCK(htmr); + + return DAL_OK; +} + +/** + * @brief Initializes the TMR Output Compare MSP. + * @param htmr TMR Output Compare handle + * @retval None + */ +__weak void DAL_TMR_OC_MspInit(TMR_HandleTypeDef *htmr) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(htmr); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_TMR_OC_MspInit could be implemented in the user file + */ +} + +/** + * @brief DeInitializes TMR Output Compare MSP. + * @param htmr TMR Output Compare handle + * @retval None + */ +__weak void DAL_TMR_OC_MspDeInit(TMR_HandleTypeDef *htmr) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(htmr); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_TMR_OC_MspDeInit could be implemented in the user file + */ +} + +/** + * @brief Starts the TMR Output Compare signal generation. + * @param htmr TMR Output Compare handle + * @param Channel TMR Channel to be enabled + * This parameter can be one of the following values: + * @arg TMR_CHANNEL_1: TMR Channel 1 selected + * @arg TMR_CHANNEL_2: TMR Channel 2 selected + * @arg TMR_CHANNEL_3: TMR Channel 3 selected + * @arg TMR_CHANNEL_4: TMR Channel 4 selected + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMR_OC_Start(TMR_HandleTypeDef *htmr, uint32_t Channel) +{ + uint32_t tmpsmcr; + + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_CCX_INSTANCE(htmr->Instance, Channel)); + + /* Check the TMR channel state */ + if (TMR_CHANNEL_STATE_GET(htmr, Channel) != DAL_TMR_CHANNEL_STATE_READY) + { + return DAL_ERROR; + } + + /* Set the TMR channel state */ + TMR_CHANNEL_STATE_SET(htmr, Channel, DAL_TMR_CHANNEL_STATE_BUSY); + + /* Enable the Output compare channel */ + TMR_CCxChannelCmd(htmr->Instance, Channel, TMR_CCx_ENABLE); + + if (IS_TMR_BREAK_INSTANCE(htmr->Instance) != RESET) + { + /* Enable the main output */ + __DAL_TMR_MOE_ENABLE(htmr); + } + + /* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */ + if (IS_TMR_SLAVE_INSTANCE(htmr->Instance)) + { + tmpsmcr = htmr->Instance->SMCTRL & TMR_SMCTRL_SMFSEL; + if (!IS_TMR_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr)) + { + __DAL_TMR_ENABLE(htmr); + } + } + else + { + __DAL_TMR_ENABLE(htmr); + } + + /* Return function status */ + return DAL_OK; +} + +/** + * @brief Stops the TMR Output Compare signal generation. + * @param htmr TMR Output Compare handle + * @param Channel TMR Channel to be disabled + * This parameter can be one of the following values: + * @arg TMR_CHANNEL_1: TMR Channel 1 selected + * @arg TMR_CHANNEL_2: TMR Channel 2 selected + * @arg TMR_CHANNEL_3: TMR Channel 3 selected + * @arg TMR_CHANNEL_4: TMR Channel 4 selected + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMR_OC_Stop(TMR_HandleTypeDef *htmr, uint32_t Channel) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_CCX_INSTANCE(htmr->Instance, Channel)); + + /* Disable the Output compare channel */ + TMR_CCxChannelCmd(htmr->Instance, Channel, TMR_CCx_DISABLE); + + if (IS_TMR_BREAK_INSTANCE(htmr->Instance) != RESET) + { + /* Disable the Main Output */ + __DAL_TMR_MOE_DISABLE(htmr); + } + + /* Disable the Peripheral */ + __DAL_TMR_DISABLE(htmr); + + /* Set the TMR channel state */ + TMR_CHANNEL_STATE_SET(htmr, Channel, DAL_TMR_CHANNEL_STATE_READY); + + /* Return function status */ + return DAL_OK; +} + +/** + * @brief Starts the TMR Output Compare signal generation in interrupt mode. + * @param htmr TMR Output Compare handle + * @param Channel TMR Channel to be enabled + * This parameter can be one of the following values: + * @arg TMR_CHANNEL_1: TMR Channel 1 selected + * @arg TMR_CHANNEL_2: TMR Channel 2 selected + * @arg TMR_CHANNEL_3: TMR Channel 3 selected + * @arg TMR_CHANNEL_4: TMR Channel 4 selected + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMR_OC_Start_IT(TMR_HandleTypeDef *htmr, uint32_t Channel) +{ + DAL_StatusTypeDef status = DAL_OK; + uint32_t tmpsmcr; + + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_CCX_INSTANCE(htmr->Instance, Channel)); + + /* Check the TMR channel state */ + if (TMR_CHANNEL_STATE_GET(htmr, Channel) != DAL_TMR_CHANNEL_STATE_READY) + { + return DAL_ERROR; + } + + /* Set the TMR channel state */ + TMR_CHANNEL_STATE_SET(htmr, Channel, DAL_TMR_CHANNEL_STATE_BUSY); + + switch (Channel) + { + case TMR_CHANNEL_1: + { + /* Enable the TMR Capture/Compare 1 interrupt */ + __DAL_TMR_ENABLE_IT(htmr, TMR_IT_CC1); + break; + } + + case TMR_CHANNEL_2: + { + /* Enable the TMR Capture/Compare 2 interrupt */ + __DAL_TMR_ENABLE_IT(htmr, TMR_IT_CC2); + break; + } + + case TMR_CHANNEL_3: + { + /* Enable the TMR Capture/Compare 3 interrupt */ + __DAL_TMR_ENABLE_IT(htmr, TMR_IT_CC3); + break; + } + + case TMR_CHANNEL_4: + { + /* Enable the TMR Capture/Compare 4 interrupt */ + __DAL_TMR_ENABLE_IT(htmr, TMR_IT_CC4); + break; + } + + default: + status = DAL_ERROR; + break; + } + + if (status == DAL_OK) + { + /* Enable the Output compare channel */ + TMR_CCxChannelCmd(htmr->Instance, Channel, TMR_CCx_ENABLE); + + if (IS_TMR_BREAK_INSTANCE(htmr->Instance) != RESET) + { + /* Enable the main output */ + __DAL_TMR_MOE_ENABLE(htmr); + } + + /* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */ + if (IS_TMR_SLAVE_INSTANCE(htmr->Instance)) + { + tmpsmcr = htmr->Instance->SMCTRL & TMR_SMCTRL_SMFSEL; + if (!IS_TMR_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr)) + { + __DAL_TMR_ENABLE(htmr); + } + } + else + { + __DAL_TMR_ENABLE(htmr); + } + } + + /* Return function status */ + return status; +} + +/** + * @brief Stops the TMR Output Compare signal generation in interrupt mode. + * @param htmr TMR Output Compare handle + * @param Channel TMR Channel to be disabled + * This parameter can be one of the following values: + * @arg TMR_CHANNEL_1: TMR Channel 1 selected + * @arg TMR_CHANNEL_2: TMR Channel 2 selected + * @arg TMR_CHANNEL_3: TMR Channel 3 selected + * @arg TMR_CHANNEL_4: TMR Channel 4 selected + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMR_OC_Stop_IT(TMR_HandleTypeDef *htmr, uint32_t Channel) +{ + DAL_StatusTypeDef status = DAL_OK; + + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_CCX_INSTANCE(htmr->Instance, Channel)); + + switch (Channel) + { + case TMR_CHANNEL_1: + { + /* Disable the TMR Capture/Compare 1 interrupt */ + __DAL_TMR_DISABLE_IT(htmr, TMR_IT_CC1); + break; + } + + case TMR_CHANNEL_2: + { + /* Disable the TMR Capture/Compare 2 interrupt */ + __DAL_TMR_DISABLE_IT(htmr, TMR_IT_CC2); + break; + } + + case TMR_CHANNEL_3: + { + /* Disable the TMR Capture/Compare 3 interrupt */ + __DAL_TMR_DISABLE_IT(htmr, TMR_IT_CC3); + break; + } + + case TMR_CHANNEL_4: + { + /* Disable the TMR Capture/Compare 4 interrupt */ + __DAL_TMR_DISABLE_IT(htmr, TMR_IT_CC4); + break; + } + + default: + status = DAL_ERROR; + break; + } + + if (status == DAL_OK) + { + /* Disable the Output compare channel */ + TMR_CCxChannelCmd(htmr->Instance, Channel, TMR_CCx_DISABLE); + + if (IS_TMR_BREAK_INSTANCE(htmr->Instance) != RESET) + { + /* Disable the Main Output */ + __DAL_TMR_MOE_DISABLE(htmr); + } + + /* Disable the Peripheral */ + __DAL_TMR_DISABLE(htmr); + + /* Set the TMR channel state */ + TMR_CHANNEL_STATE_SET(htmr, Channel, DAL_TMR_CHANNEL_STATE_READY); + } + + /* Return function status */ + return status; +} + +/** + * @brief Starts the TMR Output Compare signal generation in DMA mode. + * @param htmr TMR Output Compare handle + * @param Channel TMR Channel to be enabled + * This parameter can be one of the following values: + * @arg TMR_CHANNEL_1: TMR Channel 1 selected + * @arg TMR_CHANNEL_2: TMR Channel 2 selected + * @arg TMR_CHANNEL_3: TMR Channel 3 selected + * @arg TMR_CHANNEL_4: TMR Channel 4 selected + * @param pData The source Buffer address. + * @param Length The length of data to be transferred from memory to TMR peripheral + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMR_OC_Start_DMA(TMR_HandleTypeDef *htmr, uint32_t Channel, uint32_t *pData, uint16_t Length) +{ + DAL_StatusTypeDef status = DAL_OK; + uint32_t tmpsmcr; + + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_CCX_INSTANCE(htmr->Instance, Channel)); + + /* Set the TMR channel state */ + if (TMR_CHANNEL_STATE_GET(htmr, Channel) == DAL_TMR_CHANNEL_STATE_BUSY) + { + return DAL_BUSY; + } + else if (TMR_CHANNEL_STATE_GET(htmr, Channel) == DAL_TMR_CHANNEL_STATE_READY) + { + if ((pData == NULL) && (Length > 0U)) + { + return DAL_ERROR; + } + else + { + TMR_CHANNEL_STATE_SET(htmr, Channel, DAL_TMR_CHANNEL_STATE_BUSY); + } + } + else + { + return DAL_ERROR; + } + + switch (Channel) + { + case TMR_CHANNEL_1: + { + /* Set the DMA compare callbacks */ + htmr->hdma[TMR_DMA_ID_CC1]->XferCpltCallback = TMR_DMADelayPulseCplt; + htmr->hdma[TMR_DMA_ID_CC1]->XferHalfCpltCallback = TMR_DMADelayPulseHalfCplt; + + /* Set the DMA error callback */ + htmr->hdma[TMR_DMA_ID_CC1]->XferErrorCallback = TMR_DMAError ; + + /* Enable the DMA stream */ + if (DAL_DMA_Start_IT(htmr->hdma[TMR_DMA_ID_CC1], (uint32_t)pData, (uint32_t)&htmr->Instance->CC1, + Length) != DAL_OK) + { + /* Return error status */ + return DAL_ERROR; + } + + /* Enable the TMR Capture/Compare 1 DMA request */ + __DAL_TMR_ENABLE_DMA(htmr, TMR_DMA_CC1); + break; + } + + case TMR_CHANNEL_2: + { + /* Set the DMA compare callbacks */ + htmr->hdma[TMR_DMA_ID_CC2]->XferCpltCallback = TMR_DMADelayPulseCplt; + htmr->hdma[TMR_DMA_ID_CC2]->XferHalfCpltCallback = TMR_DMADelayPulseHalfCplt; + + /* Set the DMA error callback */ + htmr->hdma[TMR_DMA_ID_CC2]->XferErrorCallback = TMR_DMAError ; + + /* Enable the DMA stream */ + if (DAL_DMA_Start_IT(htmr->hdma[TMR_DMA_ID_CC2], (uint32_t)pData, (uint32_t)&htmr->Instance->CC2, + Length) != DAL_OK) + { + /* Return error status */ + return DAL_ERROR; + } + + /* Enable the TMR Capture/Compare 2 DMA request */ + __DAL_TMR_ENABLE_DMA(htmr, TMR_DMA_CC2); + break; + } + + case TMR_CHANNEL_3: + { + /* Set the DMA compare callbacks */ + htmr->hdma[TMR_DMA_ID_CC3]->XferCpltCallback = TMR_DMADelayPulseCplt; + htmr->hdma[TMR_DMA_ID_CC3]->XferHalfCpltCallback = TMR_DMADelayPulseHalfCplt; + + /* Set the DMA error callback */ + htmr->hdma[TMR_DMA_ID_CC3]->XferErrorCallback = TMR_DMAError ; + + /* Enable the DMA stream */ + if (DAL_DMA_Start_IT(htmr->hdma[TMR_DMA_ID_CC3], (uint32_t)pData, (uint32_t)&htmr->Instance->CC3, + Length) != DAL_OK) + { + /* Return error status */ + return DAL_ERROR; + } + /* Enable the TMR Capture/Compare 3 DMA request */ + __DAL_TMR_ENABLE_DMA(htmr, TMR_DMA_CC3); + break; + } + + case TMR_CHANNEL_4: + { + /* Set the DMA compare callbacks */ + htmr->hdma[TMR_DMA_ID_CC4]->XferCpltCallback = TMR_DMADelayPulseCplt; + htmr->hdma[TMR_DMA_ID_CC4]->XferHalfCpltCallback = TMR_DMADelayPulseHalfCplt; + + /* Set the DMA error callback */ + htmr->hdma[TMR_DMA_ID_CC4]->XferErrorCallback = TMR_DMAError ; + + /* Enable the DMA stream */ + if (DAL_DMA_Start_IT(htmr->hdma[TMR_DMA_ID_CC4], (uint32_t)pData, (uint32_t)&htmr->Instance->CC4, + Length) != DAL_OK) + { + /* Return error status */ + return DAL_ERROR; + } + /* Enable the TMR Capture/Compare 4 DMA request */ + __DAL_TMR_ENABLE_DMA(htmr, TMR_DMA_CC4); + break; + } + + default: + status = DAL_ERROR; + break; + } + + if (status == DAL_OK) + { + /* Enable the Output compare channel */ + TMR_CCxChannelCmd(htmr->Instance, Channel, TMR_CCx_ENABLE); + + if (IS_TMR_BREAK_INSTANCE(htmr->Instance) != RESET) + { + /* Enable the main output */ + __DAL_TMR_MOE_ENABLE(htmr); + } + + /* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */ + if (IS_TMR_SLAVE_INSTANCE(htmr->Instance)) + { + tmpsmcr = htmr->Instance->SMCTRL & TMR_SMCTRL_SMFSEL; + if (!IS_TMR_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr)) + { + __DAL_TMR_ENABLE(htmr); + } + } + else + { + __DAL_TMR_ENABLE(htmr); + } + } + + /* Return function status */ + return status; +} + +/** + * @brief Stops the TMR Output Compare signal generation in DMA mode. + * @param htmr TMR Output Compare handle + * @param Channel TMR Channel to be disabled + * This parameter can be one of the following values: + * @arg TMR_CHANNEL_1: TMR Channel 1 selected + * @arg TMR_CHANNEL_2: TMR Channel 2 selected + * @arg TMR_CHANNEL_3: TMR Channel 3 selected + * @arg TMR_CHANNEL_4: TMR Channel 4 selected + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMR_OC_Stop_DMA(TMR_HandleTypeDef *htmr, uint32_t Channel) +{ + DAL_StatusTypeDef status = DAL_OK; + + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_CCX_INSTANCE(htmr->Instance, Channel)); + + switch (Channel) + { + case TMR_CHANNEL_1: + { + /* Disable the TMR Capture/Compare 1 DMA request */ + __DAL_TMR_DISABLE_DMA(htmr, TMR_DMA_CC1); + (void)DAL_DMA_Abort_IT(htmr->hdma[TMR_DMA_ID_CC1]); + break; + } + + case TMR_CHANNEL_2: + { + /* Disable the TMR Capture/Compare 2 DMA request */ + __DAL_TMR_DISABLE_DMA(htmr, TMR_DMA_CC2); + (void)DAL_DMA_Abort_IT(htmr->hdma[TMR_DMA_ID_CC2]); + break; + } + + case TMR_CHANNEL_3: + { + /* Disable the TMR Capture/Compare 3 DMA request */ + __DAL_TMR_DISABLE_DMA(htmr, TMR_DMA_CC3); + (void)DAL_DMA_Abort_IT(htmr->hdma[TMR_DMA_ID_CC3]); + break; + } + + case TMR_CHANNEL_4: + { + /* Disable the TMR Capture/Compare 4 interrupt */ + __DAL_TMR_DISABLE_DMA(htmr, TMR_DMA_CC4); + (void)DAL_DMA_Abort_IT(htmr->hdma[TMR_DMA_ID_CC4]); + break; + } + + default: + status = DAL_ERROR; + break; + } + + if (status == DAL_OK) + { + /* Disable the Output compare channel */ + TMR_CCxChannelCmd(htmr->Instance, Channel, TMR_CCx_DISABLE); + + if (IS_TMR_BREAK_INSTANCE(htmr->Instance) != RESET) + { + /* Disable the Main Output */ + __DAL_TMR_MOE_DISABLE(htmr); + } + + /* Disable the Peripheral */ + __DAL_TMR_DISABLE(htmr); + + /* Set the TMR channel state */ + TMR_CHANNEL_STATE_SET(htmr, Channel, DAL_TMR_CHANNEL_STATE_READY); + } + + /* Return function status */ + return status; +} + +/** + * @} + */ + +/** @defgroup TMR_Exported_Functions_Group3 TMR PWM functions + * @brief TMR PWM functions + * +@verbatim + ============================================================================== + ##### TMR PWM functions ##### + ============================================================================== + [..] + This section provides functions allowing to: + (+) Initialize and configure the TMR PWM. + (+) De-initialize the TMR PWM. + (+) Start the TMR PWM. + (+) Stop the TMR PWM. + (+) Start the TMR PWM and enable interrupt. + (+) Stop the TMR PWM and disable interrupt. + (+) Start the TMR PWM and enable DMA transfer. + (+) Stop the TMR PWM and disable DMA transfer. + +@endverbatim + * @{ + */ +/** + * @brief Initializes the TMR PWM Time Base according to the specified + * parameters in the TMR_HandleTypeDef and initializes the associated handle. + * @note Switching from Center Aligned counter mode to Edge counter mode (or reverse) + * requires a timer reset to avoid unexpected direction + * due to DIR bit readonly in center aligned mode. + * Ex: call @ref DAL_TMR_PWM_DeInit() before DAL_TMR_PWM_Init() + * @param htmr TMR PWM handle + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMR_PWM_Init(TMR_HandleTypeDef *htmr) +{ + /* Check the TMR handle allocation */ + if (htmr == NULL) + { + return DAL_ERROR; + } + + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_INSTANCE(htmr->Instance)); + ASSERT_PARAM(IS_TMR_COUNTER_MODE(htmr->Init.CounterMode)); + ASSERT_PARAM(IS_TMR_CLOCKDIVISION_DIV(htmr->Init.ClockDivision)); + ASSERT_PARAM(IS_TMR_AUTORELOAD_PRELOAD(htmr->Init.AutoReloadPreload)); + + if (htmr->State == DAL_TMR_STATE_RESET) + { + /* Allocate lock resource and initialize it */ + htmr->Lock = DAL_UNLOCKED; + +#if (USE_DAL_TMR_REGISTER_CALLBACKS == 1) + /* Reset interrupt callbacks to legacy weak callbacks */ + TMR_ResetCallback(htmr); + + if (htmr->PWM_MspInitCallback == NULL) + { + htmr->PWM_MspInitCallback = DAL_TMR_PWM_MspInit; + } + /* Init the low level hardware : GPIO, CLOCK, NVIC */ + htmr->PWM_MspInitCallback(htmr); +#else + /* Init the low level hardware : GPIO, CLOCK, NVIC and DMA */ + DAL_TMR_PWM_MspInit(htmr); +#endif /* USE_DAL_TMR_REGISTER_CALLBACKS */ + } + + /* Set the TMR state */ + htmr->State = DAL_TMR_STATE_BUSY; + + /* Init the base time for the PWM */ + TMR_Base_SetConfig(htmr->Instance, &htmr->Init); + + /* Initialize the DMA burst operation state */ + htmr->DMABurstState = DAL_DMA_BURST_STATE_READY; + + /* Initialize the TMR channels state */ + TMR_CHANNEL_STATE_SET_ALL(htmr, DAL_TMR_CHANNEL_STATE_READY); + TMR_CHANNEL_N_STATE_SET_ALL(htmr, DAL_TMR_CHANNEL_STATE_READY); + + /* Initialize the TMR state*/ + htmr->State = DAL_TMR_STATE_READY; + + return DAL_OK; +} + +/** + * @brief DeInitializes the TMR peripheral + * @param htmr TMR PWM handle + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMR_PWM_DeInit(TMR_HandleTypeDef *htmr) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_INSTANCE(htmr->Instance)); + + htmr->State = DAL_TMR_STATE_BUSY; + + /* Disable the TMR Peripheral Clock */ + __DAL_TMR_DISABLE(htmr); + +#if (USE_DAL_TMR_REGISTER_CALLBACKS == 1) + if (htmr->PWM_MspDeInitCallback == NULL) + { + htmr->PWM_MspDeInitCallback = DAL_TMR_PWM_MspDeInit; + } + /* DeInit the low level hardware */ + htmr->PWM_MspDeInitCallback(htmr); +#else + /* DeInit the low level hardware: GPIO, CLOCK, NVIC and DMA */ + DAL_TMR_PWM_MspDeInit(htmr); +#endif /* USE_DAL_TMR_REGISTER_CALLBACKS */ + + /* Change the DMA burst operation state */ + htmr->DMABurstState = DAL_DMA_BURST_STATE_RESET; + + /* Change the TMR channels state */ + TMR_CHANNEL_STATE_SET_ALL(htmr, DAL_TMR_CHANNEL_STATE_RESET); + TMR_CHANNEL_N_STATE_SET_ALL(htmr, DAL_TMR_CHANNEL_STATE_RESET); + + /* Change TMR state */ + htmr->State = DAL_TMR_STATE_RESET; + + /* Release Lock */ + __DAL_UNLOCK(htmr); + + return DAL_OK; +} + +/** + * @brief Initializes the TMR PWM MSP. + * @param htmr TMR PWM handle + * @retval None + */ +__weak void DAL_TMR_PWM_MspInit(TMR_HandleTypeDef *htmr) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(htmr); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_TMR_PWM_MspInit could be implemented in the user file + */ +} + +/** + * @brief DeInitializes TMR PWM MSP. + * @param htmr TMR PWM handle + * @retval None + */ +__weak void DAL_TMR_PWM_MspDeInit(TMR_HandleTypeDef *htmr) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(htmr); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_TMR_PWM_MspDeInit could be implemented in the user file + */ +} + +/** + * @brief Starts the PWM signal generation. + * @param htmr TMR handle + * @param Channel TMR Channels to be enabled + * This parameter can be one of the following values: + * @arg TMR_CHANNEL_1: TMR Channel 1 selected + * @arg TMR_CHANNEL_2: TMR Channel 2 selected + * @arg TMR_CHANNEL_3: TMR Channel 3 selected + * @arg TMR_CHANNEL_4: TMR Channel 4 selected + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMR_PWM_Start(TMR_HandleTypeDef *htmr, uint32_t Channel) +{ + uint32_t tmpsmcr; + + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_CCX_INSTANCE(htmr->Instance, Channel)); + + /* Check the TMR channel state */ + if (TMR_CHANNEL_STATE_GET(htmr, Channel) != DAL_TMR_CHANNEL_STATE_READY) + { + return DAL_ERROR; + } + + /* Set the TMR channel state */ + TMR_CHANNEL_STATE_SET(htmr, Channel, DAL_TMR_CHANNEL_STATE_BUSY); + + /* Enable the Capture compare channel */ + TMR_CCxChannelCmd(htmr->Instance, Channel, TMR_CCx_ENABLE); + + if (IS_TMR_BREAK_INSTANCE(htmr->Instance) != RESET) + { + /* Enable the main output */ + __DAL_TMR_MOE_ENABLE(htmr); + } + + /* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */ + if (IS_TMR_SLAVE_INSTANCE(htmr->Instance)) + { + tmpsmcr = htmr->Instance->SMCTRL & TMR_SMCTRL_SMFSEL; + if (!IS_TMR_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr)) + { + __DAL_TMR_ENABLE(htmr); + } + } + else + { + __DAL_TMR_ENABLE(htmr); + } + + /* Return function status */ + return DAL_OK; +} + +/** + * @brief Stops the PWM signal generation. + * @param htmr TMR PWM handle + * @param Channel TMR Channels to be disabled + * This parameter can be one of the following values: + * @arg TMR_CHANNEL_1: TMR Channel 1 selected + * @arg TMR_CHANNEL_2: TMR Channel 2 selected + * @arg TMR_CHANNEL_3: TMR Channel 3 selected + * @arg TMR_CHANNEL_4: TMR Channel 4 selected + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMR_PWM_Stop(TMR_HandleTypeDef *htmr, uint32_t Channel) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_CCX_INSTANCE(htmr->Instance, Channel)); + + /* Disable the Capture compare channel */ + TMR_CCxChannelCmd(htmr->Instance, Channel, TMR_CCx_DISABLE); + + if (IS_TMR_BREAK_INSTANCE(htmr->Instance) != RESET) + { + /* Disable the Main Output */ + __DAL_TMR_MOE_DISABLE(htmr); + } + + /* Disable the Peripheral */ + __DAL_TMR_DISABLE(htmr); + + /* Set the TMR channel state */ + TMR_CHANNEL_STATE_SET(htmr, Channel, DAL_TMR_CHANNEL_STATE_READY); + + /* Return function status */ + return DAL_OK; +} + +/** + * @brief Starts the PWM signal generation in interrupt mode. + * @param htmr TMR PWM handle + * @param Channel TMR Channel to be enabled + * This parameter can be one of the following values: + * @arg TMR_CHANNEL_1: TMR Channel 1 selected + * @arg TMR_CHANNEL_2: TMR Channel 2 selected + * @arg TMR_CHANNEL_3: TMR Channel 3 selected + * @arg TMR_CHANNEL_4: TMR Channel 4 selected + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMR_PWM_Start_IT(TMR_HandleTypeDef *htmr, uint32_t Channel) +{ + DAL_StatusTypeDef status = DAL_OK; + uint32_t tmpsmcr; + + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_CCX_INSTANCE(htmr->Instance, Channel)); + + /* Check the TMR channel state */ + if (TMR_CHANNEL_STATE_GET(htmr, Channel) != DAL_TMR_CHANNEL_STATE_READY) + { + return DAL_ERROR; + } + + /* Set the TMR channel state */ + TMR_CHANNEL_STATE_SET(htmr, Channel, DAL_TMR_CHANNEL_STATE_BUSY); + + switch (Channel) + { + case TMR_CHANNEL_1: + { + /* Enable the TMR Capture/Compare 1 interrupt */ + __DAL_TMR_ENABLE_IT(htmr, TMR_IT_CC1); + break; + } + + case TMR_CHANNEL_2: + { + /* Enable the TMR Capture/Compare 2 interrupt */ + __DAL_TMR_ENABLE_IT(htmr, TMR_IT_CC2); + break; + } + + case TMR_CHANNEL_3: + { + /* Enable the TMR Capture/Compare 3 interrupt */ + __DAL_TMR_ENABLE_IT(htmr, TMR_IT_CC3); + break; + } + + case TMR_CHANNEL_4: + { + /* Enable the TMR Capture/Compare 4 interrupt */ + __DAL_TMR_ENABLE_IT(htmr, TMR_IT_CC4); + break; + } + + default: + status = DAL_ERROR; + break; + } + + if (status == DAL_OK) + { + /* Enable the Capture compare channel */ + TMR_CCxChannelCmd(htmr->Instance, Channel, TMR_CCx_ENABLE); + + if (IS_TMR_BREAK_INSTANCE(htmr->Instance) != RESET) + { + /* Enable the main output */ + __DAL_TMR_MOE_ENABLE(htmr); + } + + /* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */ + if (IS_TMR_SLAVE_INSTANCE(htmr->Instance)) + { + tmpsmcr = htmr->Instance->SMCTRL & TMR_SMCTRL_SMFSEL; + if (!IS_TMR_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr)) + { + __DAL_TMR_ENABLE(htmr); + } + } + else + { + __DAL_TMR_ENABLE(htmr); + } + } + + /* Return function status */ + return status; +} + +/** + * @brief Stops the PWM signal generation in interrupt mode. + * @param htmr TMR PWM handle + * @param Channel TMR Channels to be disabled + * This parameter can be one of the following values: + * @arg TMR_CHANNEL_1: TMR Channel 1 selected + * @arg TMR_CHANNEL_2: TMR Channel 2 selected + * @arg TMR_CHANNEL_3: TMR Channel 3 selected + * @arg TMR_CHANNEL_4: TMR Channel 4 selected + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMR_PWM_Stop_IT(TMR_HandleTypeDef *htmr, uint32_t Channel) +{ + DAL_StatusTypeDef status = DAL_OK; + + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_CCX_INSTANCE(htmr->Instance, Channel)); + + switch (Channel) + { + case TMR_CHANNEL_1: + { + /* Disable the TMR Capture/Compare 1 interrupt */ + __DAL_TMR_DISABLE_IT(htmr, TMR_IT_CC1); + break; + } + + case TMR_CHANNEL_2: + { + /* Disable the TMR Capture/Compare 2 interrupt */ + __DAL_TMR_DISABLE_IT(htmr, TMR_IT_CC2); + break; + } + + case TMR_CHANNEL_3: + { + /* Disable the TMR Capture/Compare 3 interrupt */ + __DAL_TMR_DISABLE_IT(htmr, TMR_IT_CC3); + break; + } + + case TMR_CHANNEL_4: + { + /* Disable the TMR Capture/Compare 4 interrupt */ + __DAL_TMR_DISABLE_IT(htmr, TMR_IT_CC4); + break; + } + + default: + status = DAL_ERROR; + break; + } + + if (status == DAL_OK) + { + /* Disable the Capture compare channel */ + TMR_CCxChannelCmd(htmr->Instance, Channel, TMR_CCx_DISABLE); + + if (IS_TMR_BREAK_INSTANCE(htmr->Instance) != RESET) + { + /* Disable the Main Output */ + __DAL_TMR_MOE_DISABLE(htmr); + } + + /* Disable the Peripheral */ + __DAL_TMR_DISABLE(htmr); + + /* Set the TMR channel state */ + TMR_CHANNEL_STATE_SET(htmr, Channel, DAL_TMR_CHANNEL_STATE_READY); + } + + /* Return function status */ + return status; +} + +/** + * @brief Starts the TMR PWM signal generation in DMA mode. + * @param htmr TMR PWM handle + * @param Channel TMR Channels to be enabled + * This parameter can be one of the following values: + * @arg TMR_CHANNEL_1: TMR Channel 1 selected + * @arg TMR_CHANNEL_2: TMR Channel 2 selected + * @arg TMR_CHANNEL_3: TMR Channel 3 selected + * @arg TMR_CHANNEL_4: TMR Channel 4 selected + * @param pData The source Buffer address. + * @param Length The length of data to be transferred from memory to TMR peripheral + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMR_PWM_Start_DMA(TMR_HandleTypeDef *htmr, uint32_t Channel, uint32_t *pData, uint16_t Length) +{ + DAL_StatusTypeDef status = DAL_OK; + uint32_t tmpsmcr; + + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_CCX_INSTANCE(htmr->Instance, Channel)); + + /* Set the TMR channel state */ + if (TMR_CHANNEL_STATE_GET(htmr, Channel) == DAL_TMR_CHANNEL_STATE_BUSY) + { + return DAL_BUSY; + } + else if (TMR_CHANNEL_STATE_GET(htmr, Channel) == DAL_TMR_CHANNEL_STATE_READY) + { + if ((pData == NULL) && (Length > 0U)) + { + return DAL_ERROR; + } + else + { + TMR_CHANNEL_STATE_SET(htmr, Channel, DAL_TMR_CHANNEL_STATE_BUSY); + } + } + else + { + return DAL_ERROR; + } + + switch (Channel) + { + case TMR_CHANNEL_1: + { + /* Set the DMA compare callbacks */ + htmr->hdma[TMR_DMA_ID_CC1]->XferCpltCallback = TMR_DMADelayPulseCplt; + htmr->hdma[TMR_DMA_ID_CC1]->XferHalfCpltCallback = TMR_DMADelayPulseHalfCplt; + + /* Set the DMA error callback */ + htmr->hdma[TMR_DMA_ID_CC1]->XferErrorCallback = TMR_DMAError ; + + /* Enable the DMA stream */ + if (DAL_DMA_Start_IT(htmr->hdma[TMR_DMA_ID_CC1], (uint32_t)pData, (uint32_t)&htmr->Instance->CC1, + Length) != DAL_OK) + { + /* Return error status */ + return DAL_ERROR; + } + + /* Enable the TMR Capture/Compare 1 DMA request */ + __DAL_TMR_ENABLE_DMA(htmr, TMR_DMA_CC1); + break; + } + + case TMR_CHANNEL_2: + { + /* Set the DMA compare callbacks */ + htmr->hdma[TMR_DMA_ID_CC2]->XferCpltCallback = TMR_DMADelayPulseCplt; + htmr->hdma[TMR_DMA_ID_CC2]->XferHalfCpltCallback = TMR_DMADelayPulseHalfCplt; + + /* Set the DMA error callback */ + htmr->hdma[TMR_DMA_ID_CC2]->XferErrorCallback = TMR_DMAError ; + + /* Enable the DMA stream */ + if (DAL_DMA_Start_IT(htmr->hdma[TMR_DMA_ID_CC2], (uint32_t)pData, (uint32_t)&htmr->Instance->CC2, + Length) != DAL_OK) + { + /* Return error status */ + return DAL_ERROR; + } + /* Enable the TMR Capture/Compare 2 DMA request */ + __DAL_TMR_ENABLE_DMA(htmr, TMR_DMA_CC2); + break; + } + + case TMR_CHANNEL_3: + { + /* Set the DMA compare callbacks */ + htmr->hdma[TMR_DMA_ID_CC3]->XferCpltCallback = TMR_DMADelayPulseCplt; + htmr->hdma[TMR_DMA_ID_CC3]->XferHalfCpltCallback = TMR_DMADelayPulseHalfCplt; + + /* Set the DMA error callback */ + htmr->hdma[TMR_DMA_ID_CC3]->XferErrorCallback = TMR_DMAError ; + + /* Enable the DMA stream */ + if (DAL_DMA_Start_IT(htmr->hdma[TMR_DMA_ID_CC3], (uint32_t)pData, (uint32_t)&htmr->Instance->CC3, + Length) != DAL_OK) + { + /* Return error status */ + return DAL_ERROR; + } + /* Enable the TMR Output Capture/Compare 3 request */ + __DAL_TMR_ENABLE_DMA(htmr, TMR_DMA_CC3); + break; + } + + case TMR_CHANNEL_4: + { + /* Set the DMA compare callbacks */ + htmr->hdma[TMR_DMA_ID_CC4]->XferCpltCallback = TMR_DMADelayPulseCplt; + htmr->hdma[TMR_DMA_ID_CC4]->XferHalfCpltCallback = TMR_DMADelayPulseHalfCplt; + + /* Set the DMA error callback */ + htmr->hdma[TMR_DMA_ID_CC4]->XferErrorCallback = TMR_DMAError ; + + /* Enable the DMA stream */ + if (DAL_DMA_Start_IT(htmr->hdma[TMR_DMA_ID_CC4], (uint32_t)pData, (uint32_t)&htmr->Instance->CC4, + Length) != DAL_OK) + { + /* Return error status */ + return DAL_ERROR; + } + /* Enable the TMR Capture/Compare 4 DMA request */ + __DAL_TMR_ENABLE_DMA(htmr, TMR_DMA_CC4); + break; + } + + default: + status = DAL_ERROR; + break; + } + + if (status == DAL_OK) + { + /* Enable the Capture compare channel */ + TMR_CCxChannelCmd(htmr->Instance, Channel, TMR_CCx_ENABLE); + + if (IS_TMR_BREAK_INSTANCE(htmr->Instance) != RESET) + { + /* Enable the main output */ + __DAL_TMR_MOE_ENABLE(htmr); + } + + /* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */ + if (IS_TMR_SLAVE_INSTANCE(htmr->Instance)) + { + tmpsmcr = htmr->Instance->SMCTRL & TMR_SMCTRL_SMFSEL; + if (!IS_TMR_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr)) + { + __DAL_TMR_ENABLE(htmr); + } + } + else + { + __DAL_TMR_ENABLE(htmr); + } + } + + /* Return function status */ + return status; +} + +/** + * @brief Stops the TMR PWM signal generation in DMA mode. + * @param htmr TMR PWM handle + * @param Channel TMR Channels to be disabled + * This parameter can be one of the following values: + * @arg TMR_CHANNEL_1: TMR Channel 1 selected + * @arg TMR_CHANNEL_2: TMR Channel 2 selected + * @arg TMR_CHANNEL_3: TMR Channel 3 selected + * @arg TMR_CHANNEL_4: TMR Channel 4 selected + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMR_PWM_Stop_DMA(TMR_HandleTypeDef *htmr, uint32_t Channel) +{ + DAL_StatusTypeDef status = DAL_OK; + + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_CCX_INSTANCE(htmr->Instance, Channel)); + + switch (Channel) + { + case TMR_CHANNEL_1: + { + /* Disable the TMR Capture/Compare 1 DMA request */ + __DAL_TMR_DISABLE_DMA(htmr, TMR_DMA_CC1); + (void)DAL_DMA_Abort_IT(htmr->hdma[TMR_DMA_ID_CC1]); + break; + } + + case TMR_CHANNEL_2: + { + /* Disable the TMR Capture/Compare 2 DMA request */ + __DAL_TMR_DISABLE_DMA(htmr, TMR_DMA_CC2); + (void)DAL_DMA_Abort_IT(htmr->hdma[TMR_DMA_ID_CC2]); + break; + } + + case TMR_CHANNEL_3: + { + /* Disable the TMR Capture/Compare 3 DMA request */ + __DAL_TMR_DISABLE_DMA(htmr, TMR_DMA_CC3); + (void)DAL_DMA_Abort_IT(htmr->hdma[TMR_DMA_ID_CC3]); + break; + } + + case TMR_CHANNEL_4: + { + /* Disable the TMR Capture/Compare 4 interrupt */ + __DAL_TMR_DISABLE_DMA(htmr, TMR_DMA_CC4); + (void)DAL_DMA_Abort_IT(htmr->hdma[TMR_DMA_ID_CC4]); + break; + } + + default: + status = DAL_ERROR; + break; + } + + if (status == DAL_OK) + { + /* Disable the Capture compare channel */ + TMR_CCxChannelCmd(htmr->Instance, Channel, TMR_CCx_DISABLE); + + if (IS_TMR_BREAK_INSTANCE(htmr->Instance) != RESET) + { + /* Disable the Main Output */ + __DAL_TMR_MOE_DISABLE(htmr); + } + + /* Disable the Peripheral */ + __DAL_TMR_DISABLE(htmr); + + /* Set the TMR channel state */ + TMR_CHANNEL_STATE_SET(htmr, Channel, DAL_TMR_CHANNEL_STATE_READY); + } + + /* Return function status */ + return status; +} + +/** + * @} + */ + +/** @defgroup TMR_Exported_Functions_Group4 TMR Input Capture functions + * @brief TMR Input Capture functions + * +@verbatim + ============================================================================== + ##### TMR Input Capture functions ##### + ============================================================================== + [..] + This section provides functions allowing to: + (+) Initialize and configure the TMR Input Capture. + (+) De-initialize the TMR Input Capture. + (+) Start the TMR Input Capture. + (+) Stop the TMR Input Capture. + (+) Start the TMR Input Capture and enable interrupt. + (+) Stop the TMR Input Capture and disable interrupt. + (+) Start the TMR Input Capture and enable DMA transfer. + (+) Stop the TMR Input Capture and disable DMA transfer. + +@endverbatim + * @{ + */ +/** + * @brief Initializes the TMR Input Capture Time base according to the specified + * parameters in the TMR_HandleTypeDef and initializes the associated handle. + * @note Switching from Center Aligned counter mode to Edge counter mode (or reverse) + * requires a timer reset to avoid unexpected direction + * due to DIR bit readonly in center aligned mode. + * Ex: call @ref DAL_TMR_IC_DeInit() before DAL_TMR_IC_Init() + * @param htmr TMR Input Capture handle + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMR_IC_Init(TMR_HandleTypeDef *htmr) +{ + /* Check the TMR handle allocation */ + if (htmr == NULL) + { + return DAL_ERROR; + } + + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_INSTANCE(htmr->Instance)); + ASSERT_PARAM(IS_TMR_COUNTER_MODE(htmr->Init.CounterMode)); + ASSERT_PARAM(IS_TMR_CLOCKDIVISION_DIV(htmr->Init.ClockDivision)); + ASSERT_PARAM(IS_TMR_AUTORELOAD_PRELOAD(htmr->Init.AutoReloadPreload)); + + if (htmr->State == DAL_TMR_STATE_RESET) + { + /* Allocate lock resource and initialize it */ + htmr->Lock = DAL_UNLOCKED; + +#if (USE_DAL_TMR_REGISTER_CALLBACKS == 1) + /* Reset interrupt callbacks to legacy weak callbacks */ + TMR_ResetCallback(htmr); + + if (htmr->IC_MspInitCallback == NULL) + { + htmr->IC_MspInitCallback = DAL_TMR_IC_MspInit; + } + /* Init the low level hardware : GPIO, CLOCK, NVIC */ + htmr->IC_MspInitCallback(htmr); +#else + /* Init the low level hardware : GPIO, CLOCK, NVIC and DMA */ + DAL_TMR_IC_MspInit(htmr); +#endif /* USE_DAL_TMR_REGISTER_CALLBACKS */ + } + + /* Set the TMR state */ + htmr->State = DAL_TMR_STATE_BUSY; + + /* Init the base time for the input capture */ + TMR_Base_SetConfig(htmr->Instance, &htmr->Init); + + /* Initialize the DMA burst operation state */ + htmr->DMABurstState = DAL_DMA_BURST_STATE_READY; + + /* Initialize the TMR channels state */ + TMR_CHANNEL_STATE_SET_ALL(htmr, DAL_TMR_CHANNEL_STATE_READY); + TMR_CHANNEL_N_STATE_SET_ALL(htmr, DAL_TMR_CHANNEL_STATE_READY); + + /* Initialize the TMR state*/ + htmr->State = DAL_TMR_STATE_READY; + + return DAL_OK; +} + +/** + * @brief DeInitializes the TMR peripheral + * @param htmr TMR Input Capture handle + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMR_IC_DeInit(TMR_HandleTypeDef *htmr) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_INSTANCE(htmr->Instance)); + + htmr->State = DAL_TMR_STATE_BUSY; + + /* Disable the TMR Peripheral Clock */ + __DAL_TMR_DISABLE(htmr); + +#if (USE_DAL_TMR_REGISTER_CALLBACKS == 1) + if (htmr->IC_MspDeInitCallback == NULL) + { + htmr->IC_MspDeInitCallback = DAL_TMR_IC_MspDeInit; + } + /* DeInit the low level hardware */ + htmr->IC_MspDeInitCallback(htmr); +#else + /* DeInit the low level hardware: GPIO, CLOCK, NVIC and DMA */ + DAL_TMR_IC_MspDeInit(htmr); +#endif /* USE_DAL_TMR_REGISTER_CALLBACKS */ + + /* Change the DMA burst operation state */ + htmr->DMABurstState = DAL_DMA_BURST_STATE_RESET; + + /* Change the TMR channels state */ + TMR_CHANNEL_STATE_SET_ALL(htmr, DAL_TMR_CHANNEL_STATE_RESET); + TMR_CHANNEL_N_STATE_SET_ALL(htmr, DAL_TMR_CHANNEL_STATE_RESET); + + /* Change TMR state */ + htmr->State = DAL_TMR_STATE_RESET; + + /* Release Lock */ + __DAL_UNLOCK(htmr); + + return DAL_OK; +} + +/** + * @brief Initializes the TMR Input Capture MSP. + * @param htmr TMR Input Capture handle + * @retval None + */ +__weak void DAL_TMR_IC_MspInit(TMR_HandleTypeDef *htmr) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(htmr); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_TMR_IC_MspInit could be implemented in the user file + */ +} + +/** + * @brief DeInitializes TMR Input Capture MSP. + * @param htmr TMR handle + * @retval None + */ +__weak void DAL_TMR_IC_MspDeInit(TMR_HandleTypeDef *htmr) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(htmr); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_TMR_IC_MspDeInit could be implemented in the user file + */ +} + +/** + * @brief Starts the TMR Input Capture measurement. + * @param htmr TMR Input Capture handle + * @param Channel TMR Channels to be enabled + * This parameter can be one of the following values: + * @arg TMR_CHANNEL_1: TMR Channel 1 selected + * @arg TMR_CHANNEL_2: TMR Channel 2 selected + * @arg TMR_CHANNEL_3: TMR Channel 3 selected + * @arg TMR_CHANNEL_4: TMR Channel 4 selected + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMR_IC_Start(TMR_HandleTypeDef *htmr, uint32_t Channel) +{ + uint32_t tmpsmcr; + DAL_TMR_ChannelStateTypeDef channel_state = TMR_CHANNEL_STATE_GET(htmr, Channel); + DAL_TMR_ChannelStateTypeDef complementary_channel_state = TMR_CHANNEL_N_STATE_GET(htmr, Channel); + + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_CCX_INSTANCE(htmr->Instance, Channel)); + + /* Check the TMR channel state */ + if ((channel_state != DAL_TMR_CHANNEL_STATE_READY) + || (complementary_channel_state != DAL_TMR_CHANNEL_STATE_READY)) + { + return DAL_ERROR; + } + + /* Set the TMR channel state */ + TMR_CHANNEL_STATE_SET(htmr, Channel, DAL_TMR_CHANNEL_STATE_BUSY); + TMR_CHANNEL_N_STATE_SET(htmr, Channel, DAL_TMR_CHANNEL_STATE_BUSY); + + /* Enable the Input Capture channel */ + TMR_CCxChannelCmd(htmr->Instance, Channel, TMR_CCx_ENABLE); + + /* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */ + if (IS_TMR_SLAVE_INSTANCE(htmr->Instance)) + { + tmpsmcr = htmr->Instance->SMCTRL & TMR_SMCTRL_SMFSEL; + if (!IS_TMR_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr)) + { + __DAL_TMR_ENABLE(htmr); + } + } + else + { + __DAL_TMR_ENABLE(htmr); + } + + /* Return function status */ + return DAL_OK; +} + +/** + * @brief Stops the TMR Input Capture measurement. + * @param htmr TMR Input Capture handle + * @param Channel TMR Channels to be disabled + * This parameter can be one of the following values: + * @arg TMR_CHANNEL_1: TMR Channel 1 selected + * @arg TMR_CHANNEL_2: TMR Channel 2 selected + * @arg TMR_CHANNEL_3: TMR Channel 3 selected + * @arg TMR_CHANNEL_4: TMR Channel 4 selected + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMR_IC_Stop(TMR_HandleTypeDef *htmr, uint32_t Channel) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_CCX_INSTANCE(htmr->Instance, Channel)); + + /* Disable the Input Capture channel */ + TMR_CCxChannelCmd(htmr->Instance, Channel, TMR_CCx_DISABLE); + + /* Disable the Peripheral */ + __DAL_TMR_DISABLE(htmr); + + /* Set the TMR channel state */ + TMR_CHANNEL_STATE_SET(htmr, Channel, DAL_TMR_CHANNEL_STATE_READY); + TMR_CHANNEL_N_STATE_SET(htmr, Channel, DAL_TMR_CHANNEL_STATE_READY); + + /* Return function status */ + return DAL_OK; +} + +/** + * @brief Starts the TMR Input Capture measurement in interrupt mode. + * @param htmr TMR Input Capture handle + * @param Channel TMR Channels to be enabled + * This parameter can be one of the following values: + * @arg TMR_CHANNEL_1: TMR Channel 1 selected + * @arg TMR_CHANNEL_2: TMR Channel 2 selected + * @arg TMR_CHANNEL_3: TMR Channel 3 selected + * @arg TMR_CHANNEL_4: TMR Channel 4 selected + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMR_IC_Start_IT(TMR_HandleTypeDef *htmr, uint32_t Channel) +{ + DAL_StatusTypeDef status = DAL_OK; + uint32_t tmpsmcr; + + DAL_TMR_ChannelStateTypeDef channel_state = TMR_CHANNEL_STATE_GET(htmr, Channel); + DAL_TMR_ChannelStateTypeDef complementary_channel_state = TMR_CHANNEL_N_STATE_GET(htmr, Channel); + + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_CCX_INSTANCE(htmr->Instance, Channel)); + + /* Check the TMR channel state */ + if ((channel_state != DAL_TMR_CHANNEL_STATE_READY) + || (complementary_channel_state != DAL_TMR_CHANNEL_STATE_READY)) + { + return DAL_ERROR; + } + + /* Set the TMR channel state */ + TMR_CHANNEL_STATE_SET(htmr, Channel, DAL_TMR_CHANNEL_STATE_BUSY); + TMR_CHANNEL_N_STATE_SET(htmr, Channel, DAL_TMR_CHANNEL_STATE_BUSY); + + switch (Channel) + { + case TMR_CHANNEL_1: + { + /* Enable the TMR Capture/Compare 1 interrupt */ + __DAL_TMR_ENABLE_IT(htmr, TMR_IT_CC1); + break; + } + + case TMR_CHANNEL_2: + { + /* Enable the TMR Capture/Compare 2 interrupt */ + __DAL_TMR_ENABLE_IT(htmr, TMR_IT_CC2); + break; + } + + case TMR_CHANNEL_3: + { + /* Enable the TMR Capture/Compare 3 interrupt */ + __DAL_TMR_ENABLE_IT(htmr, TMR_IT_CC3); + break; + } + + case TMR_CHANNEL_4: + { + /* Enable the TMR Capture/Compare 4 interrupt */ + __DAL_TMR_ENABLE_IT(htmr, TMR_IT_CC4); + break; + } + + default: + status = DAL_ERROR; + break; + } + + if (status == DAL_OK) + { + /* Enable the Input Capture channel */ + TMR_CCxChannelCmd(htmr->Instance, Channel, TMR_CCx_ENABLE); + + /* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */ + if (IS_TMR_SLAVE_INSTANCE(htmr->Instance)) + { + tmpsmcr = htmr->Instance->SMCTRL & TMR_SMCTRL_SMFSEL; + if (!IS_TMR_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr)) + { + __DAL_TMR_ENABLE(htmr); + } + } + else + { + __DAL_TMR_ENABLE(htmr); + } + } + + /* Return function status */ + return status; +} + +/** + * @brief Stops the TMR Input Capture measurement in interrupt mode. + * @param htmr TMR Input Capture handle + * @param Channel TMR Channels to be disabled + * This parameter can be one of the following values: + * @arg TMR_CHANNEL_1: TMR Channel 1 selected + * @arg TMR_CHANNEL_2: TMR Channel 2 selected + * @arg TMR_CHANNEL_3: TMR Channel 3 selected + * @arg TMR_CHANNEL_4: TMR Channel 4 selected + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMR_IC_Stop_IT(TMR_HandleTypeDef *htmr, uint32_t Channel) +{ + DAL_StatusTypeDef status = DAL_OK; + + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_CCX_INSTANCE(htmr->Instance, Channel)); + + switch (Channel) + { + case TMR_CHANNEL_1: + { + /* Disable the TMR Capture/Compare 1 interrupt */ + __DAL_TMR_DISABLE_IT(htmr, TMR_IT_CC1); + break; + } + + case TMR_CHANNEL_2: + { + /* Disable the TMR Capture/Compare 2 interrupt */ + __DAL_TMR_DISABLE_IT(htmr, TMR_IT_CC2); + break; + } + + case TMR_CHANNEL_3: + { + /* Disable the TMR Capture/Compare 3 interrupt */ + __DAL_TMR_DISABLE_IT(htmr, TMR_IT_CC3); + break; + } + + case TMR_CHANNEL_4: + { + /* Disable the TMR Capture/Compare 4 interrupt */ + __DAL_TMR_DISABLE_IT(htmr, TMR_IT_CC4); + break; + } + + default: + status = DAL_ERROR; + break; + } + + if (status == DAL_OK) + { + /* Disable the Input Capture channel */ + TMR_CCxChannelCmd(htmr->Instance, Channel, TMR_CCx_DISABLE); + + /* Disable the Peripheral */ + __DAL_TMR_DISABLE(htmr); + + /* Set the TMR channel state */ + TMR_CHANNEL_STATE_SET(htmr, Channel, DAL_TMR_CHANNEL_STATE_READY); + TMR_CHANNEL_N_STATE_SET(htmr, Channel, DAL_TMR_CHANNEL_STATE_READY); + } + + /* Return function status */ + return status; +} + +/** + * @brief Starts the TMR Input Capture measurement in DMA mode. + * @param htmr TMR Input Capture handle + * @param Channel TMR Channels to be enabled + * This parameter can be one of the following values: + * @arg TMR_CHANNEL_1: TMR Channel 1 selected + * @arg TMR_CHANNEL_2: TMR Channel 2 selected + * @arg TMR_CHANNEL_3: TMR Channel 3 selected + * @arg TMR_CHANNEL_4: TMR Channel 4 selected + * @param pData The destination Buffer address. + * @param Length The length of data to be transferred from TMR peripheral to memory. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMR_IC_Start_DMA(TMR_HandleTypeDef *htmr, uint32_t Channel, uint32_t *pData, uint16_t Length) +{ + DAL_StatusTypeDef status = DAL_OK; + uint32_t tmpsmcr; + + DAL_TMR_ChannelStateTypeDef channel_state = TMR_CHANNEL_STATE_GET(htmr, Channel); + DAL_TMR_ChannelStateTypeDef complementary_channel_state = TMR_CHANNEL_N_STATE_GET(htmr, Channel); + + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_CCX_INSTANCE(htmr->Instance, Channel)); + ASSERT_PARAM(IS_TMR_DMA_CC_INSTANCE(htmr->Instance)); + + /* Set the TMR channel state */ + if ((channel_state == DAL_TMR_CHANNEL_STATE_BUSY) + || (complementary_channel_state == DAL_TMR_CHANNEL_STATE_BUSY)) + { + return DAL_BUSY; + } + else if ((channel_state == DAL_TMR_CHANNEL_STATE_READY) + && (complementary_channel_state == DAL_TMR_CHANNEL_STATE_READY)) + { + if ((pData == NULL) && (Length > 0U)) + { + return DAL_ERROR; + } + else + { + TMR_CHANNEL_STATE_SET(htmr, Channel, DAL_TMR_CHANNEL_STATE_BUSY); + TMR_CHANNEL_N_STATE_SET(htmr, Channel, DAL_TMR_CHANNEL_STATE_BUSY); + } + } + else + { + return DAL_ERROR; + } + + /* Enable the Input Capture channel */ + TMR_CCxChannelCmd(htmr->Instance, Channel, TMR_CCx_ENABLE); + + switch (Channel) + { + case TMR_CHANNEL_1: + { + /* Set the DMA capture callbacks */ + htmr->hdma[TMR_DMA_ID_CC1]->XferCpltCallback = TMR_DMACaptureCplt; + htmr->hdma[TMR_DMA_ID_CC1]->XferHalfCpltCallback = TMR_DMACaptureHalfCplt; + + /* Set the DMA error callback */ + htmr->hdma[TMR_DMA_ID_CC1]->XferErrorCallback = TMR_DMAError ; + + /* Enable the DMA stream */ + if (DAL_DMA_Start_IT(htmr->hdma[TMR_DMA_ID_CC1], (uint32_t)&htmr->Instance->CC1, (uint32_t)pData, + Length) != DAL_OK) + { + /* Return error status */ + return DAL_ERROR; + } + /* Enable the TMR Capture/Compare 1 DMA request */ + __DAL_TMR_ENABLE_DMA(htmr, TMR_DMA_CC1); + break; + } + + case TMR_CHANNEL_2: + { + /* Set the DMA capture callbacks */ + htmr->hdma[TMR_DMA_ID_CC2]->XferCpltCallback = TMR_DMACaptureCplt; + htmr->hdma[TMR_DMA_ID_CC2]->XferHalfCpltCallback = TMR_DMACaptureHalfCplt; + + /* Set the DMA error callback */ + htmr->hdma[TMR_DMA_ID_CC2]->XferErrorCallback = TMR_DMAError ; + + /* Enable the DMA stream */ + if (DAL_DMA_Start_IT(htmr->hdma[TMR_DMA_ID_CC2], (uint32_t)&htmr->Instance->CC2, (uint32_t)pData, + Length) != DAL_OK) + { + /* Return error status */ + return DAL_ERROR; + } + /* Enable the TMR Capture/Compare 2 DMA request */ + __DAL_TMR_ENABLE_DMA(htmr, TMR_DMA_CC2); + break; + } + + case TMR_CHANNEL_3: + { + /* Set the DMA capture callbacks */ + htmr->hdma[TMR_DMA_ID_CC3]->XferCpltCallback = TMR_DMACaptureCplt; + htmr->hdma[TMR_DMA_ID_CC3]->XferHalfCpltCallback = TMR_DMACaptureHalfCplt; + + /* Set the DMA error callback */ + htmr->hdma[TMR_DMA_ID_CC3]->XferErrorCallback = TMR_DMAError ; + + /* Enable the DMA stream */ + if (DAL_DMA_Start_IT(htmr->hdma[TMR_DMA_ID_CC3], (uint32_t)&htmr->Instance->CC3, (uint32_t)pData, + Length) != DAL_OK) + { + /* Return error status */ + return DAL_ERROR; + } + /* Enable the TMR Capture/Compare 3 DMA request */ + __DAL_TMR_ENABLE_DMA(htmr, TMR_DMA_CC3); + break; + } + + case TMR_CHANNEL_4: + { + /* Set the DMA capture callbacks */ + htmr->hdma[TMR_DMA_ID_CC4]->XferCpltCallback = TMR_DMACaptureCplt; + htmr->hdma[TMR_DMA_ID_CC4]->XferHalfCpltCallback = TMR_DMACaptureHalfCplt; + + /* Set the DMA error callback */ + htmr->hdma[TMR_DMA_ID_CC4]->XferErrorCallback = TMR_DMAError ; + + /* Enable the DMA stream */ + if (DAL_DMA_Start_IT(htmr->hdma[TMR_DMA_ID_CC4], (uint32_t)&htmr->Instance->CC4, (uint32_t)pData, + Length) != DAL_OK) + { + /* Return error status */ + return DAL_ERROR; + } + /* Enable the TMR Capture/Compare 4 DMA request */ + __DAL_TMR_ENABLE_DMA(htmr, TMR_DMA_CC4); + break; + } + + default: + status = DAL_ERROR; + break; + } + + /* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */ + if (IS_TMR_SLAVE_INSTANCE(htmr->Instance)) + { + tmpsmcr = htmr->Instance->SMCTRL & TMR_SMCTRL_SMFSEL; + if (!IS_TMR_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr)) + { + __DAL_TMR_ENABLE(htmr); + } + } + else + { + __DAL_TMR_ENABLE(htmr); + } + + /* Return function status */ + return status; +} + +/** + * @brief Stops the TMR Input Capture measurement in DMA mode. + * @param htmr TMR Input Capture handle + * @param Channel TMR Channels to be disabled + * This parameter can be one of the following values: + * @arg TMR_CHANNEL_1: TMR Channel 1 selected + * @arg TMR_CHANNEL_2: TMR Channel 2 selected + * @arg TMR_CHANNEL_3: TMR Channel 3 selected + * @arg TMR_CHANNEL_4: TMR Channel 4 selected + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMR_IC_Stop_DMA(TMR_HandleTypeDef *htmr, uint32_t Channel) +{ + DAL_StatusTypeDef status = DAL_OK; + + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_CCX_INSTANCE(htmr->Instance, Channel)); + ASSERT_PARAM(IS_TMR_DMA_CC_INSTANCE(htmr->Instance)); + + /* Disable the Input Capture channel */ + TMR_CCxChannelCmd(htmr->Instance, Channel, TMR_CCx_DISABLE); + + switch (Channel) + { + case TMR_CHANNEL_1: + { + /* Disable the TMR Capture/Compare 1 DMA request */ + __DAL_TMR_DISABLE_DMA(htmr, TMR_DMA_CC1); + (void)DAL_DMA_Abort_IT(htmr->hdma[TMR_DMA_ID_CC1]); + break; + } + + case TMR_CHANNEL_2: + { + /* Disable the TMR Capture/Compare 2 DMA request */ + __DAL_TMR_DISABLE_DMA(htmr, TMR_DMA_CC2); + (void)DAL_DMA_Abort_IT(htmr->hdma[TMR_DMA_ID_CC2]); + break; + } + + case TMR_CHANNEL_3: + { + /* Disable the TMR Capture/Compare 3 DMA request */ + __DAL_TMR_DISABLE_DMA(htmr, TMR_DMA_CC3); + (void)DAL_DMA_Abort_IT(htmr->hdma[TMR_DMA_ID_CC3]); + break; + } + + case TMR_CHANNEL_4: + { + /* Disable the TMR Capture/Compare 4 DMA request */ + __DAL_TMR_DISABLE_DMA(htmr, TMR_DMA_CC4); + (void)DAL_DMA_Abort_IT(htmr->hdma[TMR_DMA_ID_CC4]); + break; + } + + default: + status = DAL_ERROR; + break; + } + + if (status == DAL_OK) + { + /* Disable the Peripheral */ + __DAL_TMR_DISABLE(htmr); + + /* Set the TMR channel state */ + TMR_CHANNEL_STATE_SET(htmr, Channel, DAL_TMR_CHANNEL_STATE_READY); + TMR_CHANNEL_N_STATE_SET(htmr, Channel, DAL_TMR_CHANNEL_STATE_READY); + } + + /* Return function status */ + return status; +} +/** + * @} + */ + +/** @defgroup TMR_Exported_Functions_Group5 TMR One Pulse functions + * @brief TMR One Pulse functions + * +@verbatim + ============================================================================== + ##### TMR One Pulse functions ##### + ============================================================================== + [..] + This section provides functions allowing to: + (+) Initialize and configure the TMR One Pulse. + (+) De-initialize the TMR One Pulse. + (+) Start the TMR One Pulse. + (+) Stop the TMR One Pulse. + (+) Start the TMR One Pulse and enable interrupt. + (+) Stop the TMR One Pulse and disable interrupt. + (+) Start the TMR One Pulse and enable DMA transfer. + (+) Stop the TMR One Pulse and disable DMA transfer. + +@endverbatim + * @{ + */ +/** + * @brief Initializes the TMR One Pulse Time Base according to the specified + * parameters in the TMR_HandleTypeDef and initializes the associated handle. + * @note Switching from Center Aligned counter mode to Edge counter mode (or reverse) + * requires a timer reset to avoid unexpected direction + * due to DIR bit readonly in center aligned mode. + * Ex: call @ref DAL_TMR_OnePulse_DeInit() before DAL_TMR_OnePulse_Init() + * @note When the timer instance is initialized in One Pulse mode, timer + * channels 1 and channel 2 are reserved and cannot be used for other + * purpose. + * @param htmr TMR One Pulse handle + * @param OnePulseMode Select the One pulse mode. + * This parameter can be one of the following values: + * @arg TMR_OPMODE_SINGLE: Only one pulse will be generated. + * @arg TMR_OPMODE_REPETITIVE: Repetitive pulses will be generated. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMR_OnePulse_Init(TMR_HandleTypeDef *htmr, uint32_t OnePulseMode) +{ + /* Check the TMR handle allocation */ + if (htmr == NULL) + { + return DAL_ERROR; + } + + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_INSTANCE(htmr->Instance)); + ASSERT_PARAM(IS_TMR_COUNTER_MODE(htmr->Init.CounterMode)); + ASSERT_PARAM(IS_TMR_CLOCKDIVISION_DIV(htmr->Init.ClockDivision)); + ASSERT_PARAM(IS_TMR_OPM_MODE(OnePulseMode)); + ASSERT_PARAM(IS_TMR_AUTORELOAD_PRELOAD(htmr->Init.AutoReloadPreload)); + + if (htmr->State == DAL_TMR_STATE_RESET) + { + /* Allocate lock resource and initialize it */ + htmr->Lock = DAL_UNLOCKED; + +#if (USE_DAL_TMR_REGISTER_CALLBACKS == 1) + /* Reset interrupt callbacks to legacy weak callbacks */ + TMR_ResetCallback(htmr); + + if (htmr->OnePulse_MspInitCallback == NULL) + { + htmr->OnePulse_MspInitCallback = DAL_TMR_OnePulse_MspInit; + } + /* Init the low level hardware : GPIO, CLOCK, NVIC */ + htmr->OnePulse_MspInitCallback(htmr); +#else + /* Init the low level hardware : GPIO, CLOCK, NVIC and DMA */ + DAL_TMR_OnePulse_MspInit(htmr); +#endif /* USE_DAL_TMR_REGISTER_CALLBACKS */ + } + + /* Set the TMR state */ + htmr->State = DAL_TMR_STATE_BUSY; + + /* Configure the Time base in the One Pulse Mode */ + TMR_Base_SetConfig(htmr->Instance, &htmr->Init); + + /* Reset the OPM Bit */ + htmr->Instance->CTRL1 &= ~TMR_CTRL1_SPMEN; + + /* Configure the OPM Mode */ + htmr->Instance->CTRL1 |= OnePulseMode; + + /* Initialize the DMA burst operation state */ + htmr->DMABurstState = DAL_DMA_BURST_STATE_READY; + + /* Initialize the TMR channels state */ + TMR_CHANNEL_STATE_SET(htmr, TMR_CHANNEL_1, DAL_TMR_CHANNEL_STATE_READY); + TMR_CHANNEL_STATE_SET(htmr, TMR_CHANNEL_2, DAL_TMR_CHANNEL_STATE_READY); + TMR_CHANNEL_N_STATE_SET(htmr, TMR_CHANNEL_1, DAL_TMR_CHANNEL_STATE_READY); + TMR_CHANNEL_N_STATE_SET(htmr, TMR_CHANNEL_2, DAL_TMR_CHANNEL_STATE_READY); + + /* Initialize the TMR state*/ + htmr->State = DAL_TMR_STATE_READY; + + return DAL_OK; +} + +/** + * @brief DeInitializes the TMR One Pulse + * @param htmr TMR One Pulse handle + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMR_OnePulse_DeInit(TMR_HandleTypeDef *htmr) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_INSTANCE(htmr->Instance)); + + htmr->State = DAL_TMR_STATE_BUSY; + + /* Disable the TMR Peripheral Clock */ + __DAL_TMR_DISABLE(htmr); + +#if (USE_DAL_TMR_REGISTER_CALLBACKS == 1) + if (htmr->OnePulse_MspDeInitCallback == NULL) + { + htmr->OnePulse_MspDeInitCallback = DAL_TMR_OnePulse_MspDeInit; + } + /* DeInit the low level hardware */ + htmr->OnePulse_MspDeInitCallback(htmr); +#else + /* DeInit the low level hardware: GPIO, CLOCK, NVIC */ + DAL_TMR_OnePulse_MspDeInit(htmr); +#endif /* USE_DAL_TMR_REGISTER_CALLBACKS */ + + /* Change the DMA burst operation state */ + htmr->DMABurstState = DAL_DMA_BURST_STATE_RESET; + + /* Set the TMR channel state */ + TMR_CHANNEL_STATE_SET(htmr, TMR_CHANNEL_1, DAL_TMR_CHANNEL_STATE_RESET); + TMR_CHANNEL_STATE_SET(htmr, TMR_CHANNEL_2, DAL_TMR_CHANNEL_STATE_RESET); + TMR_CHANNEL_N_STATE_SET(htmr, TMR_CHANNEL_1, DAL_TMR_CHANNEL_STATE_RESET); + TMR_CHANNEL_N_STATE_SET(htmr, TMR_CHANNEL_2, DAL_TMR_CHANNEL_STATE_RESET); + + /* Change TMR state */ + htmr->State = DAL_TMR_STATE_RESET; + + /* Release Lock */ + __DAL_UNLOCK(htmr); + + return DAL_OK; +} + +/** + * @brief Initializes the TMR One Pulse MSP. + * @param htmr TMR One Pulse handle + * @retval None + */ +__weak void DAL_TMR_OnePulse_MspInit(TMR_HandleTypeDef *htmr) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(htmr); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_TMR_OnePulse_MspInit could be implemented in the user file + */ +} + +/** + * @brief DeInitializes TMR One Pulse MSP. + * @param htmr TMR One Pulse handle + * @retval None + */ +__weak void DAL_TMR_OnePulse_MspDeInit(TMR_HandleTypeDef *htmr) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(htmr); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_TMR_OnePulse_MspDeInit could be implemented in the user file + */ +} + +/** + * @brief Starts the TMR One Pulse signal generation. + * @note Though OutputChannel parameter is deprecated and ignored by the function + * it has been kept to avoid DAL_TMR API compatibility break. + * @note The pulse output channel is determined when calling + * @ref DAL_TMR_OnePulse_ConfigChannel(). + * @param htmr TMR One Pulse handle + * @param OutputChannel See note above + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMR_OnePulse_Start(TMR_HandleTypeDef *htmr, uint32_t OutputChannel) +{ + DAL_TMR_ChannelStateTypeDef channel_1_state = TMR_CHANNEL_STATE_GET(htmr, TMR_CHANNEL_1); + DAL_TMR_ChannelStateTypeDef channel_2_state = TMR_CHANNEL_STATE_GET(htmr, TMR_CHANNEL_2); + DAL_TMR_ChannelStateTypeDef complementary_channel_1_state = TMR_CHANNEL_N_STATE_GET(htmr, TMR_CHANNEL_1); + DAL_TMR_ChannelStateTypeDef complementary_channel_2_state = TMR_CHANNEL_N_STATE_GET(htmr, TMR_CHANNEL_2); + + /* Prevent unused argument(s) compilation warning */ + UNUSED(OutputChannel); + + /* Check the TMR channels state */ + if ((channel_1_state != DAL_TMR_CHANNEL_STATE_READY) + || (channel_2_state != DAL_TMR_CHANNEL_STATE_READY) + || (complementary_channel_1_state != DAL_TMR_CHANNEL_STATE_READY) + || (complementary_channel_2_state != DAL_TMR_CHANNEL_STATE_READY)) + { + return DAL_ERROR; + } + + /* Set the TMR channels state */ + TMR_CHANNEL_STATE_SET(htmr, TMR_CHANNEL_1, DAL_TMR_CHANNEL_STATE_BUSY); + TMR_CHANNEL_STATE_SET(htmr, TMR_CHANNEL_2, DAL_TMR_CHANNEL_STATE_BUSY); + TMR_CHANNEL_N_STATE_SET(htmr, TMR_CHANNEL_1, DAL_TMR_CHANNEL_STATE_BUSY); + TMR_CHANNEL_N_STATE_SET(htmr, TMR_CHANNEL_2, DAL_TMR_CHANNEL_STATE_BUSY); + + /* Enable the Capture compare and the Input Capture channels + (in the OPM Mode the two possible channels that can be used are TMR_CHANNEL_1 and TMR_CHANNEL_2) + if TMR_CHANNEL_1 is used as output, the TMR_CHANNEL_2 will be used as input and + if TMR_CHANNEL_1 is used as input, the TMR_CHANNEL_2 will be used as output + whatever the combination, the TMR_CHANNEL_1 and TMR_CHANNEL_2 should be enabled together + + No need to enable the counter, it's enabled automatically by hardware + (the counter starts in response to a stimulus and generate a pulse */ + + TMR_CCxChannelCmd(htmr->Instance, TMR_CHANNEL_1, TMR_CCx_ENABLE); + TMR_CCxChannelCmd(htmr->Instance, TMR_CHANNEL_2, TMR_CCx_ENABLE); + + if (IS_TMR_BREAK_INSTANCE(htmr->Instance) != RESET) + { + /* Enable the main output */ + __DAL_TMR_MOE_ENABLE(htmr); + } + + /* Return function status */ + return DAL_OK; +} + +/** + * @brief Stops the TMR One Pulse signal generation. + * @note Though OutputChannel parameter is deprecated and ignored by the function + * it has been kept to avoid DAL_TMR API compatibility break. + * @note The pulse output channel is determined when calling + * @ref DAL_TMR_OnePulse_ConfigChannel(). + * @param htmr TMR One Pulse handle + * @param OutputChannel See note above + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMR_OnePulse_Stop(TMR_HandleTypeDef *htmr, uint32_t OutputChannel) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(OutputChannel); + + /* Disable the Capture compare and the Input Capture channels + (in the OPM Mode the two possible channels that can be used are TMR_CHANNEL_1 and TMR_CHANNEL_2) + if TMR_CHANNEL_1 is used as output, the TMR_CHANNEL_2 will be used as input and + if TMR_CHANNEL_1 is used as input, the TMR_CHANNEL_2 will be used as output + whatever the combination, the TMR_CHANNEL_1 and TMR_CHANNEL_2 should be disabled together */ + + TMR_CCxChannelCmd(htmr->Instance, TMR_CHANNEL_1, TMR_CCx_DISABLE); + TMR_CCxChannelCmd(htmr->Instance, TMR_CHANNEL_2, TMR_CCx_DISABLE); + + if (IS_TMR_BREAK_INSTANCE(htmr->Instance) != RESET) + { + /* Disable the Main Output */ + __DAL_TMR_MOE_DISABLE(htmr); + } + + /* Disable the Peripheral */ + __DAL_TMR_DISABLE(htmr); + + /* Set the TMR channels state */ + TMR_CHANNEL_STATE_SET(htmr, TMR_CHANNEL_1, DAL_TMR_CHANNEL_STATE_READY); + TMR_CHANNEL_STATE_SET(htmr, TMR_CHANNEL_2, DAL_TMR_CHANNEL_STATE_READY); + TMR_CHANNEL_N_STATE_SET(htmr, TMR_CHANNEL_1, DAL_TMR_CHANNEL_STATE_READY); + TMR_CHANNEL_N_STATE_SET(htmr, TMR_CHANNEL_2, DAL_TMR_CHANNEL_STATE_READY); + + /* Return function status */ + return DAL_OK; +} + +/** + * @brief Starts the TMR One Pulse signal generation in interrupt mode. + * @note Though OutputChannel parameter is deprecated and ignored by the function + * it has been kept to avoid DAL_TMR API compatibility break. + * @note The pulse output channel is determined when calling + * @ref DAL_TMR_OnePulse_ConfigChannel(). + * @param htmr TMR One Pulse handle + * @param OutputChannel See note above + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMR_OnePulse_Start_IT(TMR_HandleTypeDef *htmr, uint32_t OutputChannel) +{ + DAL_TMR_ChannelStateTypeDef channel_1_state = TMR_CHANNEL_STATE_GET(htmr, TMR_CHANNEL_1); + DAL_TMR_ChannelStateTypeDef channel_2_state = TMR_CHANNEL_STATE_GET(htmr, TMR_CHANNEL_2); + DAL_TMR_ChannelStateTypeDef complementary_channel_1_state = TMR_CHANNEL_N_STATE_GET(htmr, TMR_CHANNEL_1); + DAL_TMR_ChannelStateTypeDef complementary_channel_2_state = TMR_CHANNEL_N_STATE_GET(htmr, TMR_CHANNEL_2); + + /* Prevent unused argument(s) compilation warning */ + UNUSED(OutputChannel); + + /* Check the TMR channels state */ + if ((channel_1_state != DAL_TMR_CHANNEL_STATE_READY) + || (channel_2_state != DAL_TMR_CHANNEL_STATE_READY) + || (complementary_channel_1_state != DAL_TMR_CHANNEL_STATE_READY) + || (complementary_channel_2_state != DAL_TMR_CHANNEL_STATE_READY)) + { + return DAL_ERROR; + } + + /* Set the TMR channels state */ + TMR_CHANNEL_STATE_SET(htmr, TMR_CHANNEL_1, DAL_TMR_CHANNEL_STATE_BUSY); + TMR_CHANNEL_STATE_SET(htmr, TMR_CHANNEL_2, DAL_TMR_CHANNEL_STATE_BUSY); + TMR_CHANNEL_N_STATE_SET(htmr, TMR_CHANNEL_1, DAL_TMR_CHANNEL_STATE_BUSY); + TMR_CHANNEL_N_STATE_SET(htmr, TMR_CHANNEL_2, DAL_TMR_CHANNEL_STATE_BUSY); + + /* Enable the Capture compare and the Input Capture channels + (in the OPM Mode the two possible channels that can be used are TMR_CHANNEL_1 and TMR_CHANNEL_2) + if TMR_CHANNEL_1 is used as output, the TMR_CHANNEL_2 will be used as input and + if TMR_CHANNEL_1 is used as input, the TMR_CHANNEL_2 will be used as output + whatever the combination, the TMR_CHANNEL_1 and TMR_CHANNEL_2 should be enabled together + + No need to enable the counter, it's enabled automatically by hardware + (the counter starts in response to a stimulus and generate a pulse */ + + /* Enable the TMR Capture/Compare 1 interrupt */ + __DAL_TMR_ENABLE_IT(htmr, TMR_IT_CC1); + + /* Enable the TMR Capture/Compare 2 interrupt */ + __DAL_TMR_ENABLE_IT(htmr, TMR_IT_CC2); + + TMR_CCxChannelCmd(htmr->Instance, TMR_CHANNEL_1, TMR_CCx_ENABLE); + TMR_CCxChannelCmd(htmr->Instance, TMR_CHANNEL_2, TMR_CCx_ENABLE); + + if (IS_TMR_BREAK_INSTANCE(htmr->Instance) != RESET) + { + /* Enable the main output */ + __DAL_TMR_MOE_ENABLE(htmr); + } + + /* Return function status */ + return DAL_OK; +} + +/** + * @brief Stops the TMR One Pulse signal generation in interrupt mode. + * @note Though OutputChannel parameter is deprecated and ignored by the function + * it has been kept to avoid DAL_TMR API compatibility break. + * @note The pulse output channel is determined when calling + * @ref DAL_TMR_OnePulse_ConfigChannel(). + * @param htmr TMR One Pulse handle + * @param OutputChannel See note above + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMR_OnePulse_Stop_IT(TMR_HandleTypeDef *htmr, uint32_t OutputChannel) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(OutputChannel); + + /* Disable the TMR Capture/Compare 1 interrupt */ + __DAL_TMR_DISABLE_IT(htmr, TMR_IT_CC1); + + /* Disable the TMR Capture/Compare 2 interrupt */ + __DAL_TMR_DISABLE_IT(htmr, TMR_IT_CC2); + + /* Disable the Capture compare and the Input Capture channels + (in the OPM Mode the two possible channels that can be used are TMR_CHANNEL_1 and TMR_CHANNEL_2) + if TMR_CHANNEL_1 is used as output, the TMR_CHANNEL_2 will be used as input and + if TMR_CHANNEL_1 is used as input, the TMR_CHANNEL_2 will be used as output + whatever the combination, the TMR_CHANNEL_1 and TMR_CHANNEL_2 should be disabled together */ + TMR_CCxChannelCmd(htmr->Instance, TMR_CHANNEL_1, TMR_CCx_DISABLE); + TMR_CCxChannelCmd(htmr->Instance, TMR_CHANNEL_2, TMR_CCx_DISABLE); + + if (IS_TMR_BREAK_INSTANCE(htmr->Instance) != RESET) + { + /* Disable the Main Output */ + __DAL_TMR_MOE_DISABLE(htmr); + } + + /* Disable the Peripheral */ + __DAL_TMR_DISABLE(htmr); + + /* Set the TMR channels state */ + TMR_CHANNEL_STATE_SET(htmr, TMR_CHANNEL_1, DAL_TMR_CHANNEL_STATE_READY); + TMR_CHANNEL_STATE_SET(htmr, TMR_CHANNEL_2, DAL_TMR_CHANNEL_STATE_READY); + TMR_CHANNEL_N_STATE_SET(htmr, TMR_CHANNEL_1, DAL_TMR_CHANNEL_STATE_READY); + TMR_CHANNEL_N_STATE_SET(htmr, TMR_CHANNEL_2, DAL_TMR_CHANNEL_STATE_READY); + + /* Return function status */ + return DAL_OK; +} + +/** + * @} + */ + +/** @defgroup TMR_Exported_Functions_Group6 TMR Encoder functions + * @brief TMR Encoder functions + * +@verbatim + ============================================================================== + ##### TMR Encoder functions ##### + ============================================================================== + [..] + This section provides functions allowing to: + (+) Initialize and configure the TMR Encoder. + (+) De-initialize the TMR Encoder. + (+) Start the TMR Encoder. + (+) Stop the TMR Encoder. + (+) Start the TMR Encoder and enable interrupt. + (+) Stop the TMR Encoder and disable interrupt. + (+) Start the TMR Encoder and enable DMA transfer. + (+) Stop the TMR Encoder and disable DMA transfer. + +@endverbatim + * @{ + */ +/** + * @brief Initializes the TMR Encoder Interface and initialize the associated handle. + * @note Switching from Center Aligned counter mode to Edge counter mode (or reverse) + * requires a timer reset to avoid unexpected direction + * due to DIR bit readonly in center aligned mode. + * Ex: call @ref DAL_TMR_Encoder_DeInit() before DAL_TMR_Encoder_Init() + * @note Encoder mode and External clock mode 2 are not compatible and must not be selected together + * Ex: A call for @ref DAL_TMR_Encoder_Init will erase the settings of @ref DAL_TMR_ConfigClockSource + * using TMR_CLOCKSOURCE_ETRMODE2 and vice versa + * @note When the timer instance is initialized in Encoder mode, timer + * channels 1 and channel 2 are reserved and cannot be used for other + * purpose. + * @param htmr TMR Encoder Interface handle + * @param sConfig TMR Encoder Interface configuration structure + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMR_Encoder_Init(TMR_HandleTypeDef *htmr, TMR_Encoder_InitTypeDef *sConfig) +{ + uint32_t tmpsmcr; + uint32_t tmpccmr1; + uint32_t tmpccer; + + /* Check the TMR handle allocation */ + if (htmr == NULL) + { + return DAL_ERROR; + } + + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_ENCODER_INTERFACE_INSTANCE(htmr->Instance)); + ASSERT_PARAM(IS_TMR_COUNTER_MODE(htmr->Init.CounterMode)); + ASSERT_PARAM(IS_TMR_CLOCKDIVISION_DIV(htmr->Init.ClockDivision)); + ASSERT_PARAM(IS_TMR_AUTORELOAD_PRELOAD(htmr->Init.AutoReloadPreload)); + ASSERT_PARAM(IS_TMR_ENCODER_MODE(sConfig->EncoderMode)); + ASSERT_PARAM(IS_TMR_IC_SELECTION(sConfig->IC1Selection)); + ASSERT_PARAM(IS_TMR_IC_SELECTION(sConfig->IC2Selection)); + ASSERT_PARAM(IS_TMR_ENCODERINPUT_POLARITY(sConfig->IC1Polarity)); + ASSERT_PARAM(IS_TMR_ENCODERINPUT_POLARITY(sConfig->IC2Polarity)); + ASSERT_PARAM(IS_TMR_IC_PRESCALER(sConfig->IC1Prescaler)); + ASSERT_PARAM(IS_TMR_IC_PRESCALER(sConfig->IC2Prescaler)); + ASSERT_PARAM(IS_TMR_IC_FILTER(sConfig->IC1Filter)); + ASSERT_PARAM(IS_TMR_IC_FILTER(sConfig->IC2Filter)); + + if (htmr->State == DAL_TMR_STATE_RESET) + { + /* Allocate lock resource and initialize it */ + htmr->Lock = DAL_UNLOCKED; + +#if (USE_DAL_TMR_REGISTER_CALLBACKS == 1) + /* Reset interrupt callbacks to legacy weak callbacks */ + TMR_ResetCallback(htmr); + + if (htmr->Encoder_MspInitCallback == NULL) + { + htmr->Encoder_MspInitCallback = DAL_TMR_Encoder_MspInit; + } + /* Init the low level hardware : GPIO, CLOCK, NVIC */ + htmr->Encoder_MspInitCallback(htmr); +#else + /* Init the low level hardware : GPIO, CLOCK, NVIC and DMA */ + DAL_TMR_Encoder_MspInit(htmr); +#endif /* USE_DAL_TMR_REGISTER_CALLBACKS */ + } + + /* Set the TMR state */ + htmr->State = DAL_TMR_STATE_BUSY; + + /* Reset the SMFSEL and ECEN bits */ + htmr->Instance->SMCTRL &= ~(TMR_SMCTRL_SMFSEL | TMR_SMCTRL_ECEN); + + /* Configure the Time base in the Encoder Mode */ + TMR_Base_SetConfig(htmr->Instance, &htmr->Init); + + /* Get the TMRx SMCTRL register value */ + tmpsmcr = htmr->Instance->SMCTRL; + + /* Get the TMRx CCM1 register value */ + tmpccmr1 = htmr->Instance->CCM1; + + /* Get the TMRx CCEN register value */ + tmpccer = htmr->Instance->CCEN; + + /* Set the encoder Mode */ + tmpsmcr |= sConfig->EncoderMode; + + /* Select the Capture Compare 1 and the Capture Compare 2 as input */ + tmpccmr1 &= ~(TMR_CCM1_CC1SEL | TMR_CCM1_CC2SEL); + tmpccmr1 |= (sConfig->IC1Selection | (sConfig->IC2Selection << 8U)); + + /* Set the Capture Compare 1 and the Capture Compare 2 prescalers and filters */ + tmpccmr1 &= ~(TMR_CCM1_IC1PSC | TMR_CCM1_IC2PSC); + tmpccmr1 &= ~(TMR_CCM1_IC1F | TMR_CCM1_IC2F); + tmpccmr1 |= sConfig->IC1Prescaler | (sConfig->IC2Prescaler << 8U); + tmpccmr1 |= (sConfig->IC1Filter << 4U) | (sConfig->IC2Filter << 12U); + + /* Set the TI1 and the TI2 Polarities */ + tmpccer &= ~(TMR_CCEN_CC1POL | TMR_CCEN_CC2POL); + tmpccer &= ~(TMR_CCEN_CC1NPOL | TMR_CCEN_CC2NPOL); + tmpccer |= sConfig->IC1Polarity | (sConfig->IC2Polarity << 4U); + + /* Write to TMRx SMCTRL */ + htmr->Instance->SMCTRL = tmpsmcr; + + /* Write to TMRx CCM1 */ + htmr->Instance->CCM1 = tmpccmr1; + + /* Write to TMRx CCEN */ + htmr->Instance->CCEN = tmpccer; + + /* Initialize the DMA burst operation state */ + htmr->DMABurstState = DAL_DMA_BURST_STATE_READY; + + /* Set the TMR channels state */ + TMR_CHANNEL_STATE_SET(htmr, TMR_CHANNEL_1, DAL_TMR_CHANNEL_STATE_READY); + TMR_CHANNEL_STATE_SET(htmr, TMR_CHANNEL_2, DAL_TMR_CHANNEL_STATE_READY); + TMR_CHANNEL_N_STATE_SET(htmr, TMR_CHANNEL_1, DAL_TMR_CHANNEL_STATE_READY); + TMR_CHANNEL_N_STATE_SET(htmr, TMR_CHANNEL_2, DAL_TMR_CHANNEL_STATE_READY); + + /* Initialize the TMR state*/ + htmr->State = DAL_TMR_STATE_READY; + + return DAL_OK; +} + + +/** + * @brief DeInitializes the TMR Encoder interface + * @param htmr TMR Encoder Interface handle + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMR_Encoder_DeInit(TMR_HandleTypeDef *htmr) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_INSTANCE(htmr->Instance)); + + htmr->State = DAL_TMR_STATE_BUSY; + + /* Disable the TMR Peripheral Clock */ + __DAL_TMR_DISABLE(htmr); + +#if (USE_DAL_TMR_REGISTER_CALLBACKS == 1) + if (htmr->Encoder_MspDeInitCallback == NULL) + { + htmr->Encoder_MspDeInitCallback = DAL_TMR_Encoder_MspDeInit; + } + /* DeInit the low level hardware */ + htmr->Encoder_MspDeInitCallback(htmr); +#else + /* DeInit the low level hardware: GPIO, CLOCK, NVIC */ + DAL_TMR_Encoder_MspDeInit(htmr); +#endif /* USE_DAL_TMR_REGISTER_CALLBACKS */ + + /* Change the DMA burst operation state */ + htmr->DMABurstState = DAL_DMA_BURST_STATE_RESET; + + /* Set the TMR channels state */ + TMR_CHANNEL_STATE_SET(htmr, TMR_CHANNEL_1, DAL_TMR_CHANNEL_STATE_RESET); + TMR_CHANNEL_STATE_SET(htmr, TMR_CHANNEL_2, DAL_TMR_CHANNEL_STATE_RESET); + TMR_CHANNEL_N_STATE_SET(htmr, TMR_CHANNEL_1, DAL_TMR_CHANNEL_STATE_RESET); + TMR_CHANNEL_N_STATE_SET(htmr, TMR_CHANNEL_2, DAL_TMR_CHANNEL_STATE_RESET); + + /* Change TMR state */ + htmr->State = DAL_TMR_STATE_RESET; + + /* Release Lock */ + __DAL_UNLOCK(htmr); + + return DAL_OK; +} + +/** + * @brief Initializes the TMR Encoder Interface MSP. + * @param htmr TMR Encoder Interface handle + * @retval None + */ +__weak void DAL_TMR_Encoder_MspInit(TMR_HandleTypeDef *htmr) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(htmr); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_TMR_Encoder_MspInit could be implemented in the user file + */ +} + +/** + * @brief DeInitializes TMR Encoder Interface MSP. + * @param htmr TMR Encoder Interface handle + * @retval None + */ +__weak void DAL_TMR_Encoder_MspDeInit(TMR_HandleTypeDef *htmr) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(htmr); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_TMR_Encoder_MspDeInit could be implemented in the user file + */ +} + +/** + * @brief Starts the TMR Encoder Interface. + * @param htmr TMR Encoder Interface handle + * @param Channel TMR Channels to be enabled + * This parameter can be one of the following values: + * @arg TMR_CHANNEL_1: TMR Channel 1 selected + * @arg TMR_CHANNEL_2: TMR Channel 2 selected + * @arg TMR_CHANNEL_ALL: TMR Channel 1 and TMR Channel 2 are selected + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMR_Encoder_Start(TMR_HandleTypeDef *htmr, uint32_t Channel) +{ + DAL_TMR_ChannelStateTypeDef channel_1_state = TMR_CHANNEL_STATE_GET(htmr, TMR_CHANNEL_1); + DAL_TMR_ChannelStateTypeDef channel_2_state = TMR_CHANNEL_STATE_GET(htmr, TMR_CHANNEL_2); + DAL_TMR_ChannelStateTypeDef complementary_channel_1_state = TMR_CHANNEL_N_STATE_GET(htmr, TMR_CHANNEL_1); + DAL_TMR_ChannelStateTypeDef complementary_channel_2_state = TMR_CHANNEL_N_STATE_GET(htmr, TMR_CHANNEL_2); + + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_ENCODER_INTERFACE_INSTANCE(htmr->Instance)); + + /* Set the TMR channel(s) state */ + if (Channel == TMR_CHANNEL_1) + { + if ((channel_1_state != DAL_TMR_CHANNEL_STATE_READY) + || (complementary_channel_1_state != DAL_TMR_CHANNEL_STATE_READY)) + { + return DAL_ERROR; + } + else + { + TMR_CHANNEL_STATE_SET(htmr, TMR_CHANNEL_1, DAL_TMR_CHANNEL_STATE_BUSY); + TMR_CHANNEL_N_STATE_SET(htmr, TMR_CHANNEL_1, DAL_TMR_CHANNEL_STATE_BUSY); + } + } + else if (Channel == TMR_CHANNEL_2) + { + if ((channel_2_state != DAL_TMR_CHANNEL_STATE_READY) + || (complementary_channel_2_state != DAL_TMR_CHANNEL_STATE_READY)) + { + return DAL_ERROR; + } + else + { + TMR_CHANNEL_STATE_SET(htmr, TMR_CHANNEL_2, DAL_TMR_CHANNEL_STATE_BUSY); + TMR_CHANNEL_N_STATE_SET(htmr, TMR_CHANNEL_2, DAL_TMR_CHANNEL_STATE_BUSY); + } + } + else + { + if ((channel_1_state != DAL_TMR_CHANNEL_STATE_READY) + || (channel_2_state != DAL_TMR_CHANNEL_STATE_READY) + || (complementary_channel_1_state != DAL_TMR_CHANNEL_STATE_READY) + || (complementary_channel_2_state != DAL_TMR_CHANNEL_STATE_READY)) + { + return DAL_ERROR; + } + else + { + TMR_CHANNEL_STATE_SET(htmr, TMR_CHANNEL_1, DAL_TMR_CHANNEL_STATE_BUSY); + TMR_CHANNEL_STATE_SET(htmr, TMR_CHANNEL_2, DAL_TMR_CHANNEL_STATE_BUSY); + TMR_CHANNEL_N_STATE_SET(htmr, TMR_CHANNEL_1, DAL_TMR_CHANNEL_STATE_BUSY); + TMR_CHANNEL_N_STATE_SET(htmr, TMR_CHANNEL_2, DAL_TMR_CHANNEL_STATE_BUSY); + } + } + + /* Enable the encoder interface channels */ + switch (Channel) + { + case TMR_CHANNEL_1: + { + TMR_CCxChannelCmd(htmr->Instance, TMR_CHANNEL_1, TMR_CCx_ENABLE); + break; + } + + case TMR_CHANNEL_2: + { + TMR_CCxChannelCmd(htmr->Instance, TMR_CHANNEL_2, TMR_CCx_ENABLE); + break; + } + + default : + { + TMR_CCxChannelCmd(htmr->Instance, TMR_CHANNEL_1, TMR_CCx_ENABLE); + TMR_CCxChannelCmd(htmr->Instance, TMR_CHANNEL_2, TMR_CCx_ENABLE); + break; + } + } + /* Enable the Peripheral */ + __DAL_TMR_ENABLE(htmr); + + /* Return function status */ + return DAL_OK; +} + +/** + * @brief Stops the TMR Encoder Interface. + * @param htmr TMR Encoder Interface handle + * @param Channel TMR Channels to be disabled + * This parameter can be one of the following values: + * @arg TMR_CHANNEL_1: TMR Channel 1 selected + * @arg TMR_CHANNEL_2: TMR Channel 2 selected + * @arg TMR_CHANNEL_ALL: TMR Channel 1 and TMR Channel 2 are selected + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMR_Encoder_Stop(TMR_HandleTypeDef *htmr, uint32_t Channel) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_ENCODER_INTERFACE_INSTANCE(htmr->Instance)); + + /* Disable the Input Capture channels 1 and 2 + (in the EncoderInterface the two possible channels that can be used are TMR_CHANNEL_1 and TMR_CHANNEL_2) */ + switch (Channel) + { + case TMR_CHANNEL_1: + { + TMR_CCxChannelCmd(htmr->Instance, TMR_CHANNEL_1, TMR_CCx_DISABLE); + break; + } + + case TMR_CHANNEL_2: + { + TMR_CCxChannelCmd(htmr->Instance, TMR_CHANNEL_2, TMR_CCx_DISABLE); + break; + } + + default : + { + TMR_CCxChannelCmd(htmr->Instance, TMR_CHANNEL_1, TMR_CCx_DISABLE); + TMR_CCxChannelCmd(htmr->Instance, TMR_CHANNEL_2, TMR_CCx_DISABLE); + break; + } + } + + /* Disable the Peripheral */ + __DAL_TMR_DISABLE(htmr); + + /* Set the TMR channel(s) state */ + if ((Channel == TMR_CHANNEL_1) || (Channel == TMR_CHANNEL_2)) + { + TMR_CHANNEL_STATE_SET(htmr, Channel, DAL_TMR_CHANNEL_STATE_READY); + TMR_CHANNEL_N_STATE_SET(htmr, Channel, DAL_TMR_CHANNEL_STATE_READY); + } + else + { + TMR_CHANNEL_STATE_SET(htmr, TMR_CHANNEL_1, DAL_TMR_CHANNEL_STATE_READY); + TMR_CHANNEL_STATE_SET(htmr, TMR_CHANNEL_2, DAL_TMR_CHANNEL_STATE_READY); + TMR_CHANNEL_N_STATE_SET(htmr, TMR_CHANNEL_1, DAL_TMR_CHANNEL_STATE_READY); + TMR_CHANNEL_N_STATE_SET(htmr, TMR_CHANNEL_2, DAL_TMR_CHANNEL_STATE_READY); + } + + /* Return function status */ + return DAL_OK; +} + +/** + * @brief Starts the TMR Encoder Interface in interrupt mode. + * @param htmr TMR Encoder Interface handle + * @param Channel TMR Channels to be enabled + * This parameter can be one of the following values: + * @arg TMR_CHANNEL_1: TMR Channel 1 selected + * @arg TMR_CHANNEL_2: TMR Channel 2 selected + * @arg TMR_CHANNEL_ALL: TMR Channel 1 and TMR Channel 2 are selected + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMR_Encoder_Start_IT(TMR_HandleTypeDef *htmr, uint32_t Channel) +{ + DAL_TMR_ChannelStateTypeDef channel_1_state = TMR_CHANNEL_STATE_GET(htmr, TMR_CHANNEL_1); + DAL_TMR_ChannelStateTypeDef channel_2_state = TMR_CHANNEL_STATE_GET(htmr, TMR_CHANNEL_2); + DAL_TMR_ChannelStateTypeDef complementary_channel_1_state = TMR_CHANNEL_N_STATE_GET(htmr, TMR_CHANNEL_1); + DAL_TMR_ChannelStateTypeDef complementary_channel_2_state = TMR_CHANNEL_N_STATE_GET(htmr, TMR_CHANNEL_2); + + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_ENCODER_INTERFACE_INSTANCE(htmr->Instance)); + + /* Set the TMR channel(s) state */ + if (Channel == TMR_CHANNEL_1) + { + if ((channel_1_state != DAL_TMR_CHANNEL_STATE_READY) + || (complementary_channel_1_state != DAL_TMR_CHANNEL_STATE_READY)) + { + return DAL_ERROR; + } + else + { + TMR_CHANNEL_STATE_SET(htmr, TMR_CHANNEL_1, DAL_TMR_CHANNEL_STATE_BUSY); + TMR_CHANNEL_N_STATE_SET(htmr, TMR_CHANNEL_1, DAL_TMR_CHANNEL_STATE_BUSY); + } + } + else if (Channel == TMR_CHANNEL_2) + { + if ((channel_2_state != DAL_TMR_CHANNEL_STATE_READY) + || (complementary_channel_2_state != DAL_TMR_CHANNEL_STATE_READY)) + { + return DAL_ERROR; + } + else + { + TMR_CHANNEL_STATE_SET(htmr, TMR_CHANNEL_2, DAL_TMR_CHANNEL_STATE_BUSY); + TMR_CHANNEL_N_STATE_SET(htmr, TMR_CHANNEL_2, DAL_TMR_CHANNEL_STATE_BUSY); + } + } + else + { + if ((channel_1_state != DAL_TMR_CHANNEL_STATE_READY) + || (channel_2_state != DAL_TMR_CHANNEL_STATE_READY) + || (complementary_channel_1_state != DAL_TMR_CHANNEL_STATE_READY) + || (complementary_channel_2_state != DAL_TMR_CHANNEL_STATE_READY)) + { + return DAL_ERROR; + } + else + { + TMR_CHANNEL_STATE_SET(htmr, TMR_CHANNEL_1, DAL_TMR_CHANNEL_STATE_BUSY); + TMR_CHANNEL_STATE_SET(htmr, TMR_CHANNEL_2, DAL_TMR_CHANNEL_STATE_BUSY); + TMR_CHANNEL_N_STATE_SET(htmr, TMR_CHANNEL_1, DAL_TMR_CHANNEL_STATE_BUSY); + TMR_CHANNEL_N_STATE_SET(htmr, TMR_CHANNEL_2, DAL_TMR_CHANNEL_STATE_BUSY); + } + } + + /* Enable the encoder interface channels */ + /* Enable the capture compare Interrupts 1 and/or 2 */ + switch (Channel) + { + case TMR_CHANNEL_1: + { + TMR_CCxChannelCmd(htmr->Instance, TMR_CHANNEL_1, TMR_CCx_ENABLE); + __DAL_TMR_ENABLE_IT(htmr, TMR_IT_CC1); + break; + } + + case TMR_CHANNEL_2: + { + TMR_CCxChannelCmd(htmr->Instance, TMR_CHANNEL_2, TMR_CCx_ENABLE); + __DAL_TMR_ENABLE_IT(htmr, TMR_IT_CC2); + break; + } + + default : + { + TMR_CCxChannelCmd(htmr->Instance, TMR_CHANNEL_1, TMR_CCx_ENABLE); + TMR_CCxChannelCmd(htmr->Instance, TMR_CHANNEL_2, TMR_CCx_ENABLE); + __DAL_TMR_ENABLE_IT(htmr, TMR_IT_CC1); + __DAL_TMR_ENABLE_IT(htmr, TMR_IT_CC2); + break; + } + } + + /* Enable the Peripheral */ + __DAL_TMR_ENABLE(htmr); + + /* Return function status */ + return DAL_OK; +} + +/** + * @brief Stops the TMR Encoder Interface in interrupt mode. + * @param htmr TMR Encoder Interface handle + * @param Channel TMR Channels to be disabled + * This parameter can be one of the following values: + * @arg TMR_CHANNEL_1: TMR Channel 1 selected + * @arg TMR_CHANNEL_2: TMR Channel 2 selected + * @arg TMR_CHANNEL_ALL: TMR Channel 1 and TMR Channel 2 are selected + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMR_Encoder_Stop_IT(TMR_HandleTypeDef *htmr, uint32_t Channel) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_ENCODER_INTERFACE_INSTANCE(htmr->Instance)); + + /* Disable the Input Capture channels 1 and 2 + (in the EncoderInterface the two possible channels that can be used are TMR_CHANNEL_1 and TMR_CHANNEL_2) */ + if (Channel == TMR_CHANNEL_1) + { + TMR_CCxChannelCmd(htmr->Instance, TMR_CHANNEL_1, TMR_CCx_DISABLE); + + /* Disable the capture compare Interrupts 1 */ + __DAL_TMR_DISABLE_IT(htmr, TMR_IT_CC1); + } + else if (Channel == TMR_CHANNEL_2) + { + TMR_CCxChannelCmd(htmr->Instance, TMR_CHANNEL_2, TMR_CCx_DISABLE); + + /* Disable the capture compare Interrupts 2 */ + __DAL_TMR_DISABLE_IT(htmr, TMR_IT_CC2); + } + else + { + TMR_CCxChannelCmd(htmr->Instance, TMR_CHANNEL_1, TMR_CCx_DISABLE); + TMR_CCxChannelCmd(htmr->Instance, TMR_CHANNEL_2, TMR_CCx_DISABLE); + + /* Disable the capture compare Interrupts 1 and 2 */ + __DAL_TMR_DISABLE_IT(htmr, TMR_IT_CC1); + __DAL_TMR_DISABLE_IT(htmr, TMR_IT_CC2); + } + + /* Disable the Peripheral */ + __DAL_TMR_DISABLE(htmr); + + /* Set the TMR channel(s) state */ + if ((Channel == TMR_CHANNEL_1) || (Channel == TMR_CHANNEL_2)) + { + TMR_CHANNEL_STATE_SET(htmr, Channel, DAL_TMR_CHANNEL_STATE_READY); + TMR_CHANNEL_N_STATE_SET(htmr, Channel, DAL_TMR_CHANNEL_STATE_READY); + } + else + { + TMR_CHANNEL_STATE_SET(htmr, TMR_CHANNEL_1, DAL_TMR_CHANNEL_STATE_READY); + TMR_CHANNEL_STATE_SET(htmr, TMR_CHANNEL_2, DAL_TMR_CHANNEL_STATE_READY); + TMR_CHANNEL_N_STATE_SET(htmr, TMR_CHANNEL_1, DAL_TMR_CHANNEL_STATE_READY); + TMR_CHANNEL_N_STATE_SET(htmr, TMR_CHANNEL_2, DAL_TMR_CHANNEL_STATE_READY); + } + + /* Return function status */ + return DAL_OK; +} + +/** + * @brief Starts the TMR Encoder Interface in DMA mode. + * @param htmr TMR Encoder Interface handle + * @param Channel TMR Channels to be enabled + * This parameter can be one of the following values: + * @arg TMR_CHANNEL_1: TMR Channel 1 selected + * @arg TMR_CHANNEL_2: TMR Channel 2 selected + * @arg TMR_CHANNEL_ALL: TMR Channel 1 and TMR Channel 2 are selected + * @param pData1 The destination Buffer address for IC1. + * @param pData2 The destination Buffer address for IC2. + * @param Length The length of data to be transferred from TMR peripheral to memory. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMR_Encoder_Start_DMA(TMR_HandleTypeDef *htmr, uint32_t Channel, uint32_t *pData1, + uint32_t *pData2, uint16_t Length) +{ + DAL_TMR_ChannelStateTypeDef channel_1_state = TMR_CHANNEL_STATE_GET(htmr, TMR_CHANNEL_1); + DAL_TMR_ChannelStateTypeDef channel_2_state = TMR_CHANNEL_STATE_GET(htmr, TMR_CHANNEL_2); + DAL_TMR_ChannelStateTypeDef complementary_channel_1_state = TMR_CHANNEL_N_STATE_GET(htmr, TMR_CHANNEL_1); + DAL_TMR_ChannelStateTypeDef complementary_channel_2_state = TMR_CHANNEL_N_STATE_GET(htmr, TMR_CHANNEL_2); + + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_ENCODER_INTERFACE_INSTANCE(htmr->Instance)); + + /* Set the TMR channel(s) state */ + if (Channel == TMR_CHANNEL_1) + { + if ((channel_1_state == DAL_TMR_CHANNEL_STATE_BUSY) + || (complementary_channel_1_state == DAL_TMR_CHANNEL_STATE_BUSY)) + { + return DAL_BUSY; + } + else if ((channel_1_state == DAL_TMR_CHANNEL_STATE_READY) + && (complementary_channel_1_state == DAL_TMR_CHANNEL_STATE_READY)) + { + if ((pData1 == NULL) && (Length > 0U)) + { + return DAL_ERROR; + } + else + { + TMR_CHANNEL_STATE_SET(htmr, TMR_CHANNEL_1, DAL_TMR_CHANNEL_STATE_BUSY); + TMR_CHANNEL_N_STATE_SET(htmr, TMR_CHANNEL_1, DAL_TMR_CHANNEL_STATE_BUSY); + } + } + else + { + return DAL_ERROR; + } + } + else if (Channel == TMR_CHANNEL_2) + { + if ((channel_2_state == DAL_TMR_CHANNEL_STATE_BUSY) + || (complementary_channel_2_state == DAL_TMR_CHANNEL_STATE_BUSY)) + { + return DAL_BUSY; + } + else if ((channel_2_state == DAL_TMR_CHANNEL_STATE_READY) + && (complementary_channel_2_state == DAL_TMR_CHANNEL_STATE_READY)) + { + if ((pData2 == NULL) && (Length > 0U)) + { + return DAL_ERROR; + } + else + { + TMR_CHANNEL_STATE_SET(htmr, TMR_CHANNEL_2, DAL_TMR_CHANNEL_STATE_BUSY); + TMR_CHANNEL_N_STATE_SET(htmr, TMR_CHANNEL_2, DAL_TMR_CHANNEL_STATE_BUSY); + } + } + else + { + return DAL_ERROR; + } + } + else + { + if ((channel_1_state == DAL_TMR_CHANNEL_STATE_BUSY) + || (channel_2_state == DAL_TMR_CHANNEL_STATE_BUSY) + || (complementary_channel_1_state == DAL_TMR_CHANNEL_STATE_BUSY) + || (complementary_channel_2_state == DAL_TMR_CHANNEL_STATE_BUSY)) + { + return DAL_BUSY; + } + else if ((channel_1_state == DAL_TMR_CHANNEL_STATE_READY) + && (channel_2_state == DAL_TMR_CHANNEL_STATE_READY) + && (complementary_channel_1_state == DAL_TMR_CHANNEL_STATE_READY) + && (complementary_channel_2_state == DAL_TMR_CHANNEL_STATE_READY)) + { + if ((((pData1 == NULL) || (pData2 == NULL))) && (Length > 0U)) + { + return DAL_ERROR; + } + else + { + TMR_CHANNEL_STATE_SET(htmr, TMR_CHANNEL_1, DAL_TMR_CHANNEL_STATE_BUSY); + TMR_CHANNEL_STATE_SET(htmr, TMR_CHANNEL_2, DAL_TMR_CHANNEL_STATE_BUSY); + TMR_CHANNEL_N_STATE_SET(htmr, TMR_CHANNEL_1, DAL_TMR_CHANNEL_STATE_BUSY); + TMR_CHANNEL_N_STATE_SET(htmr, TMR_CHANNEL_2, DAL_TMR_CHANNEL_STATE_BUSY); + } + } + else + { + return DAL_ERROR; + } + } + + switch (Channel) + { + case TMR_CHANNEL_1: + { + /* Set the DMA capture callbacks */ + htmr->hdma[TMR_DMA_ID_CC1]->XferCpltCallback = TMR_DMACaptureCplt; + htmr->hdma[TMR_DMA_ID_CC1]->XferHalfCpltCallback = TMR_DMACaptureHalfCplt; + + /* Set the DMA error callback */ + htmr->hdma[TMR_DMA_ID_CC1]->XferErrorCallback = TMR_DMAError ; + + /* Enable the DMA stream */ + if (DAL_DMA_Start_IT(htmr->hdma[TMR_DMA_ID_CC1], (uint32_t)&htmr->Instance->CC1, (uint32_t)pData1, + Length) != DAL_OK) + { + /* Return error status */ + return DAL_ERROR; + } + /* Enable the TMR Input Capture DMA request */ + __DAL_TMR_ENABLE_DMA(htmr, TMR_DMA_CC1); + + /* Enable the Capture compare channel */ + TMR_CCxChannelCmd(htmr->Instance, TMR_CHANNEL_1, TMR_CCx_ENABLE); + + /* Enable the Peripheral */ + __DAL_TMR_ENABLE(htmr); + + break; + } + + case TMR_CHANNEL_2: + { + /* Set the DMA capture callbacks */ + htmr->hdma[TMR_DMA_ID_CC2]->XferCpltCallback = TMR_DMACaptureCplt; + htmr->hdma[TMR_DMA_ID_CC2]->XferHalfCpltCallback = TMR_DMACaptureHalfCplt; + + /* Set the DMA error callback */ + htmr->hdma[TMR_DMA_ID_CC2]->XferErrorCallback = TMR_DMAError; + /* Enable the DMA stream */ + if (DAL_DMA_Start_IT(htmr->hdma[TMR_DMA_ID_CC2], (uint32_t)&htmr->Instance->CC2, (uint32_t)pData2, + Length) != DAL_OK) + { + /* Return error status */ + return DAL_ERROR; + } + /* Enable the TMR Input Capture DMA request */ + __DAL_TMR_ENABLE_DMA(htmr, TMR_DMA_CC2); + + /* Enable the Capture compare channel */ + TMR_CCxChannelCmd(htmr->Instance, TMR_CHANNEL_2, TMR_CCx_ENABLE); + + /* Enable the Peripheral */ + __DAL_TMR_ENABLE(htmr); + + break; + } + + default: + { + /* Set the DMA capture callbacks */ + htmr->hdma[TMR_DMA_ID_CC1]->XferCpltCallback = TMR_DMACaptureCplt; + htmr->hdma[TMR_DMA_ID_CC1]->XferHalfCpltCallback = TMR_DMACaptureHalfCplt; + + /* Set the DMA error callback */ + htmr->hdma[TMR_DMA_ID_CC1]->XferErrorCallback = TMR_DMAError ; + + /* Enable the DMA stream */ + if (DAL_DMA_Start_IT(htmr->hdma[TMR_DMA_ID_CC1], (uint32_t)&htmr->Instance->CC1, (uint32_t)pData1, + Length) != DAL_OK) + { + /* Return error status */ + return DAL_ERROR; + } + + /* Set the DMA capture callbacks */ + htmr->hdma[TMR_DMA_ID_CC2]->XferCpltCallback = TMR_DMACaptureCplt; + htmr->hdma[TMR_DMA_ID_CC2]->XferHalfCpltCallback = TMR_DMACaptureHalfCplt; + + /* Set the DMA error callback */ + htmr->hdma[TMR_DMA_ID_CC2]->XferErrorCallback = TMR_DMAError ; + + /* Enable the DMA stream */ + if (DAL_DMA_Start_IT(htmr->hdma[TMR_DMA_ID_CC2], (uint32_t)&htmr->Instance->CC2, (uint32_t)pData2, + Length) != DAL_OK) + { + /* Return error status */ + return DAL_ERROR; + } + + /* Enable the TMR Input Capture DMA request */ + __DAL_TMR_ENABLE_DMA(htmr, TMR_DMA_CC1); + /* Enable the TMR Input Capture DMA request */ + __DAL_TMR_ENABLE_DMA(htmr, TMR_DMA_CC2); + + /* Enable the Capture compare channel */ + TMR_CCxChannelCmd(htmr->Instance, TMR_CHANNEL_1, TMR_CCx_ENABLE); + TMR_CCxChannelCmd(htmr->Instance, TMR_CHANNEL_2, TMR_CCx_ENABLE); + + /* Enable the Peripheral */ + __DAL_TMR_ENABLE(htmr); + + break; + } + } + + /* Return function status */ + return DAL_OK; +} + +/** + * @brief Stops the TMR Encoder Interface in DMA mode. + * @param htmr TMR Encoder Interface handle + * @param Channel TMR Channels to be enabled + * This parameter can be one of the following values: + * @arg TMR_CHANNEL_1: TMR Channel 1 selected + * @arg TMR_CHANNEL_2: TMR Channel 2 selected + * @arg TMR_CHANNEL_ALL: TMR Channel 1 and TMR Channel 2 are selected + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMR_Encoder_Stop_DMA(TMR_HandleTypeDef *htmr, uint32_t Channel) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_ENCODER_INTERFACE_INSTANCE(htmr->Instance)); + + /* Disable the Input Capture channels 1 and 2 + (in the EncoderInterface the two possible channels that can be used are TMR_CHANNEL_1 and TMR_CHANNEL_2) */ + if (Channel == TMR_CHANNEL_1) + { + TMR_CCxChannelCmd(htmr->Instance, TMR_CHANNEL_1, TMR_CCx_DISABLE); + + /* Disable the capture compare DMA Request 1 */ + __DAL_TMR_DISABLE_DMA(htmr, TMR_DMA_CC1); + (void)DAL_DMA_Abort_IT(htmr->hdma[TMR_DMA_ID_CC1]); + } + else if (Channel == TMR_CHANNEL_2) + { + TMR_CCxChannelCmd(htmr->Instance, TMR_CHANNEL_2, TMR_CCx_DISABLE); + + /* Disable the capture compare DMA Request 2 */ + __DAL_TMR_DISABLE_DMA(htmr, TMR_DMA_CC2); + (void)DAL_DMA_Abort_IT(htmr->hdma[TMR_DMA_ID_CC2]); + } + else + { + TMR_CCxChannelCmd(htmr->Instance, TMR_CHANNEL_1, TMR_CCx_DISABLE); + TMR_CCxChannelCmd(htmr->Instance, TMR_CHANNEL_2, TMR_CCx_DISABLE); + + /* Disable the capture compare DMA Request 1 and 2 */ + __DAL_TMR_DISABLE_DMA(htmr, TMR_DMA_CC1); + __DAL_TMR_DISABLE_DMA(htmr, TMR_DMA_CC2); + (void)DAL_DMA_Abort_IT(htmr->hdma[TMR_DMA_ID_CC1]); + (void)DAL_DMA_Abort_IT(htmr->hdma[TMR_DMA_ID_CC2]); + } + + /* Disable the Peripheral */ + __DAL_TMR_DISABLE(htmr); + + /* Set the TMR channel(s) state */ + if ((Channel == TMR_CHANNEL_1) || (Channel == TMR_CHANNEL_2)) + { + TMR_CHANNEL_STATE_SET(htmr, Channel, DAL_TMR_CHANNEL_STATE_READY); + TMR_CHANNEL_N_STATE_SET(htmr, Channel, DAL_TMR_CHANNEL_STATE_READY); + } + else + { + TMR_CHANNEL_STATE_SET(htmr, TMR_CHANNEL_1, DAL_TMR_CHANNEL_STATE_READY); + TMR_CHANNEL_STATE_SET(htmr, TMR_CHANNEL_2, DAL_TMR_CHANNEL_STATE_READY); + TMR_CHANNEL_N_STATE_SET(htmr, TMR_CHANNEL_1, DAL_TMR_CHANNEL_STATE_READY); + TMR_CHANNEL_N_STATE_SET(htmr, TMR_CHANNEL_2, DAL_TMR_CHANNEL_STATE_READY); + } + + /* Return function status */ + return DAL_OK; +} + +/** + * @} + */ +/** @defgroup TMR_Exported_Functions_Group7 TMR IRQ handler management + * @brief TMR IRQ handler management + * +@verbatim + ============================================================================== + ##### IRQ handler management ##### + ============================================================================== + [..] + This section provides Timer IRQ handler function. + +@endverbatim + * @{ + */ +/** + * @brief This function handles TMR interrupts requests. + * @param htmr TMR handle + * @retval None + */ +void DAL_TMR_IRQHandler(TMR_HandleTypeDef *htmr) +{ + /* Capture compare 1 event */ + if (__DAL_TMR_GET_FLAG(htmr, TMR_FLAG_CC1) != RESET) + { + if (__DAL_TMR_GET_IT_SOURCE(htmr, TMR_IT_CC1) != RESET) + { + { + __DAL_TMR_CLEAR_IT(htmr, TMR_IT_CC1); + htmr->Channel = DAL_TMR_ACTIVE_CHANNEL_1; + + /* Input capture event */ + if ((htmr->Instance->CCM1 & TMR_CCM1_CC1SEL) != 0x00U) + { +#if (USE_DAL_TMR_REGISTER_CALLBACKS == 1) + htmr->IC_CaptureCallback(htmr); +#else + DAL_TMR_IC_CaptureCallback(htmr); +#endif /* USE_DAL_TMR_REGISTER_CALLBACKS */ + } + /* Output compare event */ + else + { +#if (USE_DAL_TMR_REGISTER_CALLBACKS == 1) + htmr->OC_DelayElapsedCallback(htmr); + htmr->PWM_PulseFinishedCallback(htmr); +#else + DAL_TMR_OC_DelayElapsedCallback(htmr); + DAL_TMR_PWM_PulseFinishedCallback(htmr); +#endif /* USE_DAL_TMR_REGISTER_CALLBACKS */ + } + htmr->Channel = DAL_TMR_ACTIVE_CHANNEL_CLEARED; + } + } + } + /* Capture compare 2 event */ + if (__DAL_TMR_GET_FLAG(htmr, TMR_FLAG_CC2) != RESET) + { + if (__DAL_TMR_GET_IT_SOURCE(htmr, TMR_IT_CC2) != RESET) + { + __DAL_TMR_CLEAR_IT(htmr, TMR_IT_CC2); + htmr->Channel = DAL_TMR_ACTIVE_CHANNEL_2; + /* Input capture event */ + if ((htmr->Instance->CCM1 & TMR_CCM1_CC2SEL) != 0x00U) + { +#if (USE_DAL_TMR_REGISTER_CALLBACKS == 1) + htmr->IC_CaptureCallback(htmr); +#else + DAL_TMR_IC_CaptureCallback(htmr); +#endif /* USE_DAL_TMR_REGISTER_CALLBACKS */ + } + /* Output compare event */ + else + { +#if (USE_DAL_TMR_REGISTER_CALLBACKS == 1) + htmr->OC_DelayElapsedCallback(htmr); + htmr->PWM_PulseFinishedCallback(htmr); +#else + DAL_TMR_OC_DelayElapsedCallback(htmr); + DAL_TMR_PWM_PulseFinishedCallback(htmr); +#endif /* USE_DAL_TMR_REGISTER_CALLBACKS */ + } + htmr->Channel = DAL_TMR_ACTIVE_CHANNEL_CLEARED; + } + } + /* Capture compare 3 event */ + if (__DAL_TMR_GET_FLAG(htmr, TMR_FLAG_CC3) != RESET) + { + if (__DAL_TMR_GET_IT_SOURCE(htmr, TMR_IT_CC3) != RESET) + { + __DAL_TMR_CLEAR_IT(htmr, TMR_IT_CC3); + htmr->Channel = DAL_TMR_ACTIVE_CHANNEL_3; + /* Input capture event */ + if ((htmr->Instance->CCM2 & TMR_CCM2_CC3SEL) != 0x00U) + { +#if (USE_DAL_TMR_REGISTER_CALLBACKS == 1) + htmr->IC_CaptureCallback(htmr); +#else + DAL_TMR_IC_CaptureCallback(htmr); +#endif /* USE_DAL_TMR_REGISTER_CALLBACKS */ + } + /* Output compare event */ + else + { +#if (USE_DAL_TMR_REGISTER_CALLBACKS == 1) + htmr->OC_DelayElapsedCallback(htmr); + htmr->PWM_PulseFinishedCallback(htmr); +#else + DAL_TMR_OC_DelayElapsedCallback(htmr); + DAL_TMR_PWM_PulseFinishedCallback(htmr); +#endif /* USE_DAL_TMR_REGISTER_CALLBACKS */ + } + htmr->Channel = DAL_TMR_ACTIVE_CHANNEL_CLEARED; + } + } + /* Capture compare 4 event */ + if (__DAL_TMR_GET_FLAG(htmr, TMR_FLAG_CC4) != RESET) + { + if (__DAL_TMR_GET_IT_SOURCE(htmr, TMR_IT_CC4) != RESET) + { + __DAL_TMR_CLEAR_IT(htmr, TMR_IT_CC4); + htmr->Channel = DAL_TMR_ACTIVE_CHANNEL_4; + /* Input capture event */ + if ((htmr->Instance->CCM2 & TMR_CCM2_CC4SEL) != 0x00U) + { +#if (USE_DAL_TMR_REGISTER_CALLBACKS == 1) + htmr->IC_CaptureCallback(htmr); +#else + DAL_TMR_IC_CaptureCallback(htmr); +#endif /* USE_DAL_TMR_REGISTER_CALLBACKS */ + } + /* Output compare event */ + else + { +#if (USE_DAL_TMR_REGISTER_CALLBACKS == 1) + htmr->OC_DelayElapsedCallback(htmr); + htmr->PWM_PulseFinishedCallback(htmr); +#else + DAL_TMR_OC_DelayElapsedCallback(htmr); + DAL_TMR_PWM_PulseFinishedCallback(htmr); +#endif /* USE_DAL_TMR_REGISTER_CALLBACKS */ + } + htmr->Channel = DAL_TMR_ACTIVE_CHANNEL_CLEARED; + } + } + /* TMR Update event */ + if (__DAL_TMR_GET_FLAG(htmr, TMR_FLAG_UPDATE) != RESET) + { + if (__DAL_TMR_GET_IT_SOURCE(htmr, TMR_IT_UPDATE) != RESET) + { + __DAL_TMR_CLEAR_IT(htmr, TMR_IT_UPDATE); +#if (USE_DAL_TMR_REGISTER_CALLBACKS == 1) + htmr->PeriodElapsedCallback(htmr); +#else + DAL_TMR_PeriodElapsedCallback(htmr); +#endif /* USE_DAL_TMR_REGISTER_CALLBACKS */ + } + } + /* TMR Break input event */ + if (__DAL_TMR_GET_FLAG(htmr, TMR_FLAG_BREAK) != RESET) + { + if (__DAL_TMR_GET_IT_SOURCE(htmr, TMR_IT_BREAK) != RESET) + { + __DAL_TMR_CLEAR_IT(htmr, TMR_IT_BREAK); +#if (USE_DAL_TMR_REGISTER_CALLBACKS == 1) + htmr->BreakCallback(htmr); +#else + DAL_TMREx_BreakCallback(htmr); +#endif /* USE_DAL_TMR_REGISTER_CALLBACKS */ + } + } + /* TMR Trigger detection event */ + if (__DAL_TMR_GET_FLAG(htmr, TMR_FLAG_TRIGGER) != RESET) + { + if (__DAL_TMR_GET_IT_SOURCE(htmr, TMR_IT_TRIGGER) != RESET) + { + __DAL_TMR_CLEAR_IT(htmr, TMR_IT_TRIGGER); +#if (USE_DAL_TMR_REGISTER_CALLBACKS == 1) + htmr->TriggerCallback(htmr); +#else + DAL_TMR_TriggerCallback(htmr); +#endif /* USE_DAL_TMR_REGISTER_CALLBACKS */ + } + } + /* TMR commutation event */ + if (__DAL_TMR_GET_FLAG(htmr, TMR_FLAG_COM) != RESET) + { + if (__DAL_TMR_GET_IT_SOURCE(htmr, TMR_IT_COM) != RESET) + { + __DAL_TMR_CLEAR_IT(htmr, TMR_FLAG_COM); +#if (USE_DAL_TMR_REGISTER_CALLBACKS == 1) + htmr->CommutationCallback(htmr); +#else + DAL_TMREx_CommutCallback(htmr); +#endif /* USE_DAL_TMR_REGISTER_CALLBACKS */ + } + } +} + +/** + * @} + */ + +/** @defgroup TMR_Exported_Functions_Group8 TMR Peripheral Control functions + * @brief TMR Peripheral Control functions + * +@verbatim + ============================================================================== + ##### Peripheral Control functions ##### + ============================================================================== + [..] + This section provides functions allowing to: + (+) Configure The Input Output channels for OC, PWM, IC or One Pulse mode. + (+) Configure External Clock source. + (+) Configure Complementary channels, break features and dead time. + (+) Configure Master and the Slave synchronization. + (+) Configure the DMA Burst Mode. + +@endverbatim + * @{ + */ + +/** + * @brief Initializes the TMR Output Compare Channels according to the specified + * parameters in the TMR_OC_InitTypeDef. + * @param htmr TMR Output Compare handle + * @param sConfig TMR Output Compare configuration structure + * @param Channel TMR Channels to configure + * This parameter can be one of the following values: + * @arg TMR_CHANNEL_1: TMR Channel 1 selected + * @arg TMR_CHANNEL_2: TMR Channel 2 selected + * @arg TMR_CHANNEL_3: TMR Channel 3 selected + * @arg TMR_CHANNEL_4: TMR Channel 4 selected + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMR_OC_ConfigChannel(TMR_HandleTypeDef *htmr, + TMR_OC_InitTypeDef *sConfig, + uint32_t Channel) +{ + DAL_StatusTypeDef status = DAL_OK; + + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_CHANNELS(Channel)); + ASSERT_PARAM(IS_TMR_OC_MODE(sConfig->OCMode)); + ASSERT_PARAM(IS_TMR_OC_POLARITY(sConfig->OCPolarity)); + + /* Process Locked */ + __DAL_LOCK(htmr); + + switch (Channel) + { + case TMR_CHANNEL_1: + { + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_CC1_INSTANCE(htmr->Instance)); + + /* Configure the TMR Channel 1 in Output Compare */ + TMR_OC1_SetConfig(htmr->Instance, sConfig); + break; + } + + case TMR_CHANNEL_2: + { + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_CC2_INSTANCE(htmr->Instance)); + + /* Configure the TMR Channel 2 in Output Compare */ + TMR_OC2_SetConfig(htmr->Instance, sConfig); + break; + } + + case TMR_CHANNEL_3: + { + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_CC3_INSTANCE(htmr->Instance)); + + /* Configure the TMR Channel 3 in Output Compare */ + TMR_OC3_SetConfig(htmr->Instance, sConfig); + break; + } + + case TMR_CHANNEL_4: + { + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_CC4_INSTANCE(htmr->Instance)); + + /* Configure the TMR Channel 4 in Output Compare */ + TMR_OC4_SetConfig(htmr->Instance, sConfig); + break; + } + + default: + status = DAL_ERROR; + break; + } + + __DAL_UNLOCK(htmr); + + return status; +} + +/** + * @brief Initializes the TMR Input Capture Channels according to the specified + * parameters in the TMR_IC_InitTypeDef. + * @param htmr TMR IC handle + * @param sConfig TMR Input Capture configuration structure + * @param Channel TMR Channel to configure + * This parameter can be one of the following values: + * @arg TMR_CHANNEL_1: TMR Channel 1 selected + * @arg TMR_CHANNEL_2: TMR Channel 2 selected + * @arg TMR_CHANNEL_3: TMR Channel 3 selected + * @arg TMR_CHANNEL_4: TMR Channel 4 selected + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMR_IC_ConfigChannel(TMR_HandleTypeDef *htmr, TMR_IC_InitTypeDef *sConfig, uint32_t Channel) +{ + DAL_StatusTypeDef status = DAL_OK; + + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_CC1_INSTANCE(htmr->Instance)); + ASSERT_PARAM(IS_TMR_IC_POLARITY(sConfig->ICPolarity)); + ASSERT_PARAM(IS_TMR_IC_SELECTION(sConfig->ICSelection)); + ASSERT_PARAM(IS_TMR_IC_PRESCALER(sConfig->ICPrescaler)); + ASSERT_PARAM(IS_TMR_IC_FILTER(sConfig->ICFilter)); + + /* Process Locked */ + __DAL_LOCK(htmr); + + if (Channel == TMR_CHANNEL_1) + { + /* TI1 Configuration */ + TMR_TI1_SetConfig(htmr->Instance, + sConfig->ICPolarity, + sConfig->ICSelection, + sConfig->ICFilter); + + /* Reset the IC1PSC Bits */ + htmr->Instance->CCM1 &= ~TMR_CCM1_IC1PSC; + + /* Set the IC1PSC value */ + htmr->Instance->CCM1 |= sConfig->ICPrescaler; + } + else if (Channel == TMR_CHANNEL_2) + { + /* TI2 Configuration */ + ASSERT_PARAM(IS_TMR_CC2_INSTANCE(htmr->Instance)); + + TMR_TI2_SetConfig(htmr->Instance, + sConfig->ICPolarity, + sConfig->ICSelection, + sConfig->ICFilter); + + /* Reset the IC2PSC Bits */ + htmr->Instance->CCM1 &= ~TMR_CCM1_IC2PSC; + + /* Set the IC2PSC value */ + htmr->Instance->CCM1 |= (sConfig->ICPrescaler << 8U); + } + else if (Channel == TMR_CHANNEL_3) + { + /* TI3 Configuration */ + ASSERT_PARAM(IS_TMR_CC3_INSTANCE(htmr->Instance)); + + TMR_TI3_SetConfig(htmr->Instance, + sConfig->ICPolarity, + sConfig->ICSelection, + sConfig->ICFilter); + + /* Reset the IC3PSC Bits */ + htmr->Instance->CCM2 &= ~TMR_CCM2_IC3PSC; + + /* Set the IC3PSC value */ + htmr->Instance->CCM2 |= sConfig->ICPrescaler; + } + else if (Channel == TMR_CHANNEL_4) + { + /* TI4 Configuration */ + ASSERT_PARAM(IS_TMR_CC4_INSTANCE(htmr->Instance)); + + TMR_TI4_SetConfig(htmr->Instance, + sConfig->ICPolarity, + sConfig->ICSelection, + sConfig->ICFilter); + + /* Reset the IC4PSC Bits */ + htmr->Instance->CCM2 &= ~TMR_CCM2_IC4PSC; + + /* Set the IC4PSC value */ + htmr->Instance->CCM2 |= (sConfig->ICPrescaler << 8U); + } + else + { + status = DAL_ERROR; + } + + __DAL_UNLOCK(htmr); + + return status; +} + +/** + * @brief Initializes the TMR PWM channels according to the specified + * parameters in the TMR_OC_InitTypeDef. + * @param htmr TMR PWM handle + * @param sConfig TMR PWM configuration structure + * @param Channel TMR Channels to be configured + * This parameter can be one of the following values: + * @arg TMR_CHANNEL_1: TMR Channel 1 selected + * @arg TMR_CHANNEL_2: TMR Channel 2 selected + * @arg TMR_CHANNEL_3: TMR Channel 3 selected + * @arg TMR_CHANNEL_4: TMR Channel 4 selected + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMR_PWM_ConfigChannel(TMR_HandleTypeDef *htmr, + TMR_OC_InitTypeDef *sConfig, + uint32_t Channel) +{ + DAL_StatusTypeDef status = DAL_OK; + + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_CHANNELS(Channel)); + ASSERT_PARAM(IS_TMR_PWM_MODE(sConfig->OCMode)); + ASSERT_PARAM(IS_TMR_OC_POLARITY(sConfig->OCPolarity)); + ASSERT_PARAM(IS_TMR_FAST_STATE(sConfig->OCFastMode)); + + /* Process Locked */ + __DAL_LOCK(htmr); + + switch (Channel) + { + case TMR_CHANNEL_1: + { + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_CC1_INSTANCE(htmr->Instance)); + + /* Configure the Channel 1 in PWM mode */ + TMR_OC1_SetConfig(htmr->Instance, sConfig); + + /* Set the Preload enable bit for channel1 */ + htmr->Instance->CCM1 |= TMR_CCM1_OC1PEN; + + /* Configure the Output Fast mode */ + htmr->Instance->CCM1 &= ~TMR_CCM1_OC1FEN; + htmr->Instance->CCM1 |= sConfig->OCFastMode; + break; + } + + case TMR_CHANNEL_2: + { + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_CC2_INSTANCE(htmr->Instance)); + + /* Configure the Channel 2 in PWM mode */ + TMR_OC2_SetConfig(htmr->Instance, sConfig); + + /* Set the Preload enable bit for channel2 */ + htmr->Instance->CCM1 |= TMR_CCM1_OC2PEN; + + /* Configure the Output Fast mode */ + htmr->Instance->CCM1 &= ~TMR_CCM1_OC2FEN; + htmr->Instance->CCM1 |= sConfig->OCFastMode << 8U; + break; + } + + case TMR_CHANNEL_3: + { + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_CC3_INSTANCE(htmr->Instance)); + + /* Configure the Channel 3 in PWM mode */ + TMR_OC3_SetConfig(htmr->Instance, sConfig); + + /* Set the Preload enable bit for channel3 */ + htmr->Instance->CCM2 |= TMR_CCM2_OC3PEN; + + /* Configure the Output Fast mode */ + htmr->Instance->CCM2 &= ~TMR_CCM2_OC3FEN; + htmr->Instance->CCM2 |= sConfig->OCFastMode; + break; + } + + case TMR_CHANNEL_4: + { + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_CC4_INSTANCE(htmr->Instance)); + + /* Configure the Channel 4 in PWM mode */ + TMR_OC4_SetConfig(htmr->Instance, sConfig); + + /* Set the Preload enable bit for channel4 */ + htmr->Instance->CCM2 |= TMR_CCM2_OC4PEN; + + /* Configure the Output Fast mode */ + htmr->Instance->CCM2 &= ~TMR_CCM2_OC4FEN; + htmr->Instance->CCM2 |= sConfig->OCFastMode << 8U; + break; + } + + default: + status = DAL_ERROR; + break; + } + + __DAL_UNLOCK(htmr); + + return status; +} + +/** + * @brief Initializes the TMR One Pulse Channels according to the specified + * parameters in the TMR_OnePulse_InitTypeDef. + * @param htmr TMR One Pulse handle + * @param sConfig TMR One Pulse configuration structure + * @param OutputChannel TMR output channel to configure + * This parameter can be one of the following values: + * @arg TMR_CHANNEL_1: TMR Channel 1 selected + * @arg TMR_CHANNEL_2: TMR Channel 2 selected + * @param InputChannel TMR input Channel to configure + * This parameter can be one of the following values: + * @arg TMR_CHANNEL_1: TMR Channel 1 selected + * @arg TMR_CHANNEL_2: TMR Channel 2 selected + * @note To output a waveform with a minimum delay user can enable the fast + * mode by calling the @ref __DAL_TMR_ENABLE_OCxFAST macro. Then CCx + * output is forced in response to the edge detection on TIx input, + * without taking in account the comparison. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMR_OnePulse_ConfigChannel(TMR_HandleTypeDef *htmr, TMR_OnePulse_InitTypeDef *sConfig, + uint32_t OutputChannel, uint32_t InputChannel) +{ + DAL_StatusTypeDef status = DAL_OK; + TMR_OC_InitTypeDef temp1; + + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_OPM_CHANNELS(OutputChannel)); + ASSERT_PARAM(IS_TMR_OPM_CHANNELS(InputChannel)); + + if (OutputChannel != InputChannel) + { + /* Process Locked */ + __DAL_LOCK(htmr); + + htmr->State = DAL_TMR_STATE_BUSY; + + /* Extract the Output compare configuration from sConfig structure */ + temp1.OCMode = sConfig->OCMode; + temp1.Pulse = sConfig->Pulse; + temp1.OCPolarity = sConfig->OCPolarity; + temp1.OCNPolarity = sConfig->OCNPolarity; + temp1.OCIdleState = sConfig->OCIdleState; + temp1.OCNIdleState = sConfig->OCNIdleState; + + switch (OutputChannel) + { + case TMR_CHANNEL_1: + { + ASSERT_PARAM(IS_TMR_CC1_INSTANCE(htmr->Instance)); + + TMR_OC1_SetConfig(htmr->Instance, &temp1); + break; + } + + case TMR_CHANNEL_2: + { + ASSERT_PARAM(IS_TMR_CC2_INSTANCE(htmr->Instance)); + + TMR_OC2_SetConfig(htmr->Instance, &temp1); + break; + } + + default: + status = DAL_ERROR; + break; + } + + if (status == DAL_OK) + { + switch (InputChannel) + { + case TMR_CHANNEL_1: + { + ASSERT_PARAM(IS_TMR_CC1_INSTANCE(htmr->Instance)); + + TMR_TI1_SetConfig(htmr->Instance, sConfig->ICPolarity, + sConfig->ICSelection, sConfig->ICFilter); + + /* Reset the IC1PSC Bits */ + htmr->Instance->CCM1 &= ~TMR_CCM1_IC1PSC; + + /* Select the Trigger source */ + htmr->Instance->SMCTRL &= ~TMR_SMCTRL_TRGSEL; + htmr->Instance->SMCTRL |= TMR_TS_TI1FP1; + + /* Select the Slave Mode */ + htmr->Instance->SMCTRL &= ~TMR_SMCTRL_SMFSEL; + htmr->Instance->SMCTRL |= TMR_SLAVEMODE_TRIGGER; + break; + } + + case TMR_CHANNEL_2: + { + ASSERT_PARAM(IS_TMR_CC2_INSTANCE(htmr->Instance)); + + TMR_TI2_SetConfig(htmr->Instance, sConfig->ICPolarity, + sConfig->ICSelection, sConfig->ICFilter); + + /* Reset the IC2PSC Bits */ + htmr->Instance->CCM1 &= ~TMR_CCM1_IC2PSC; + + /* Select the Trigger source */ + htmr->Instance->SMCTRL &= ~TMR_SMCTRL_TRGSEL; + htmr->Instance->SMCTRL |= TMR_TS_TI2FP2; + + /* Select the Slave Mode */ + htmr->Instance->SMCTRL &= ~TMR_SMCTRL_SMFSEL; + htmr->Instance->SMCTRL |= TMR_SLAVEMODE_TRIGGER; + break; + } + + default: + status = DAL_ERROR; + break; + } + } + + htmr->State = DAL_TMR_STATE_READY; + + __DAL_UNLOCK(htmr); + + return status; + } + else + { + return DAL_ERROR; + } +} + +/** + * @brief Configure the DMA Burst to transfer Data from the memory to the TMR peripheral + * @param htmr TMR handle + * @param BurstBaseAddress TMR Base address from where the DMA will start the Data write + * This parameter can be one of the following values: + * @arg TMR_DMABASE_CTRL1 + * @arg TMR_DMABASE_CTRL2 + * @arg TMR_DMABASE_SMCTRL + * @arg TMR_DMABASE_DIEN + * @arg TMR_DMABASE_STS + * @arg TMR_DMABASE_CEG + * @arg TMR_DMABASE_CCM1 + * @arg TMR_DMABASE_CCM2 + * @arg TMR_DMABASE_CCEN + * @arg TMR_DMABASE_CNT + * @arg TMR_DMABASE_PSC + * @arg TMR_DMABASE_AUTORLD + * @arg TMR_DMABASE_REPCNT + * @arg TMR_DMABASE_CC1 + * @arg TMR_DMABASE_CC2 + * @arg TMR_DMABASE_CC3 + * @arg TMR_DMABASE_CC4 + * @arg TMR_DMABASE_BDT + * @param BurstRequestSrc TMR DMA Request sources + * This parameter can be one of the following values: + * @arg TMR_DMA_UPDATE: TMR update Interrupt source + * @arg TMR_DMA_CC1: TMR Capture Compare 1 DMA source + * @arg TMR_DMA_CC2: TMR Capture Compare 2 DMA source + * @arg TMR_DMA_CC3: TMR Capture Compare 3 DMA source + * @arg TMR_DMA_CC4: TMR Capture Compare 4 DMA source + * @arg TMR_DMA_COM: TMR Commutation DMA source + * @arg TMR_DMA_TRIGGER: TMR Trigger DMA source + * @param BurstBuffer The Buffer address. + * @param BurstLength DMA Burst length. This parameter can be one value + * between: TMR_DMABURSTLENGTH_1TRANSFER and TMR_DMABURSTLENGTH_18TRANSFERS. + * @note This function should be used only when BurstLength is equal to DMA data transfer length. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMR_DMABurst_WriteStart(TMR_HandleTypeDef *htmr, uint32_t BurstBaseAddress, + uint32_t BurstRequestSrc, uint32_t *BurstBuffer, uint32_t BurstLength) +{ + DAL_StatusTypeDef status; + + status = DAL_TMR_DMABurst_MultiWriteStart(htmr, BurstBaseAddress, BurstRequestSrc, BurstBuffer, BurstLength, + ((BurstLength) >> 8U) + 1U); + + + + return status; +} + +/** + * @brief Configure the DMA Burst to transfer multiple Data from the memory to the TMR peripheral + * @param htmr TMR handle + * @param BurstBaseAddress TMR Base address from where the DMA will start the Data write + * This parameter can be one of the following values: + * @arg TMR_DMABASE_CTRL1 + * @arg TMR_DMABASE_CTRL2 + * @arg TMR_DMABASE_SMCTRL + * @arg TMR_DMABASE_DIEN + * @arg TMR_DMABASE_STS + * @arg TMR_DMABASE_CEG + * @arg TMR_DMABASE_CCM1 + * @arg TMR_DMABASE_CCM2 + * @arg TMR_DMABASE_CCEN + * @arg TMR_DMABASE_CNT + * @arg TMR_DMABASE_PSC + * @arg TMR_DMABASE_AUTORLD + * @arg TMR_DMABASE_REPCNT + * @arg TMR_DMABASE_CC1 + * @arg TMR_DMABASE_CC2 + * @arg TMR_DMABASE_CC3 + * @arg TMR_DMABASE_CC4 + * @arg TMR_DMABASE_BDT + * @param BurstRequestSrc TMR DMA Request sources + * This parameter can be one of the following values: + * @arg TMR_DMA_UPDATE: TMR update Interrupt source + * @arg TMR_DMA_CC1: TMR Capture Compare 1 DMA source + * @arg TMR_DMA_CC2: TMR Capture Compare 2 DMA source + * @arg TMR_DMA_CC3: TMR Capture Compare 3 DMA source + * @arg TMR_DMA_CC4: TMR Capture Compare 4 DMA source + * @arg TMR_DMA_COM: TMR Commutation DMA source + * @arg TMR_DMA_TRIGGER: TMR Trigger DMA source + * @param BurstBuffer The Buffer address. + * @param BurstLength DMA Burst length. This parameter can be one value + * between: TMR_DMABURSTLENGTH_1TRANSFER and TMR_DMABURSTLENGTH_18TRANSFERS. + * @param DataLength Data length. This parameter can be one value + * between 1 and 0xFFFF. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMR_DMABurst_MultiWriteStart(TMR_HandleTypeDef *htmr, uint32_t BurstBaseAddress, + uint32_t BurstRequestSrc, uint32_t *BurstBuffer, + uint32_t BurstLength, uint32_t DataLength) +{ + DAL_StatusTypeDef status = DAL_OK; + + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_DMABURST_INSTANCE(htmr->Instance)); + ASSERT_PARAM(IS_TMR_DMA_BASE(BurstBaseAddress)); + ASSERT_PARAM(IS_TMR_DMA_SOURCE(BurstRequestSrc)); + ASSERT_PARAM(IS_TMR_DMA_LENGTH(BurstLength)); + ASSERT_PARAM(IS_TMR_DMA_DATA_LENGTH(DataLength)); + + if (htmr->DMABurstState == DAL_DMA_BURST_STATE_BUSY) + { + return DAL_BUSY; + } + else if (htmr->DMABurstState == DAL_DMA_BURST_STATE_READY) + { + if ((BurstBuffer == NULL) && (BurstLength > 0U)) + { + return DAL_ERROR; + } + else + { + htmr->DMABurstState = DAL_DMA_BURST_STATE_BUSY; + } + } + else + { + /* nothing to do */ + } + + switch (BurstRequestSrc) + { + case TMR_DMA_UPDATE: + { + /* Set the DMA Period elapsed callbacks */ + htmr->hdma[TMR_DMA_ID_UPDATE]->XferCpltCallback = TMR_DMAPeriodElapsedCplt; + htmr->hdma[TMR_DMA_ID_UPDATE]->XferHalfCpltCallback = TMR_DMAPeriodElapsedHalfCplt; + + /* Set the DMA error callback */ + htmr->hdma[TMR_DMA_ID_UPDATE]->XferErrorCallback = TMR_DMAError ; + + /* Enable the DMA stream */ + if (DAL_DMA_Start_IT(htmr->hdma[TMR_DMA_ID_UPDATE], (uint32_t)BurstBuffer, + (uint32_t)&htmr->Instance->DMAR, DataLength) != DAL_OK) + { + /* Return error status */ + return DAL_ERROR; + } + break; + } + case TMR_DMA_CC1: + { + /* Set the DMA compare callbacks */ + htmr->hdma[TMR_DMA_ID_CC1]->XferCpltCallback = TMR_DMADelayPulseCplt; + htmr->hdma[TMR_DMA_ID_CC1]->XferHalfCpltCallback = TMR_DMADelayPulseHalfCplt; + + /* Set the DMA error callback */ + htmr->hdma[TMR_DMA_ID_CC1]->XferErrorCallback = TMR_DMAError ; + + /* Enable the DMA stream */ + if (DAL_DMA_Start_IT(htmr->hdma[TMR_DMA_ID_CC1], (uint32_t)BurstBuffer, + (uint32_t)&htmr->Instance->DMAR, DataLength) != DAL_OK) + { + /* Return error status */ + return DAL_ERROR; + } + break; + } + case TMR_DMA_CC2: + { + /* Set the DMA compare callbacks */ + htmr->hdma[TMR_DMA_ID_CC2]->XferCpltCallback = TMR_DMADelayPulseCplt; + htmr->hdma[TMR_DMA_ID_CC2]->XferHalfCpltCallback = TMR_DMADelayPulseHalfCplt; + + /* Set the DMA error callback */ + htmr->hdma[TMR_DMA_ID_CC2]->XferErrorCallback = TMR_DMAError ; + + /* Enable the DMA stream */ + if (DAL_DMA_Start_IT(htmr->hdma[TMR_DMA_ID_CC2], (uint32_t)BurstBuffer, + (uint32_t)&htmr->Instance->DMAR, DataLength) != DAL_OK) + { + /* Return error status */ + return DAL_ERROR; + } + break; + } + case TMR_DMA_CC3: + { + /* Set the DMA compare callbacks */ + htmr->hdma[TMR_DMA_ID_CC3]->XferCpltCallback = TMR_DMADelayPulseCplt; + htmr->hdma[TMR_DMA_ID_CC3]->XferHalfCpltCallback = TMR_DMADelayPulseHalfCplt; + + /* Set the DMA error callback */ + htmr->hdma[TMR_DMA_ID_CC3]->XferErrorCallback = TMR_DMAError ; + + /* Enable the DMA stream */ + if (DAL_DMA_Start_IT(htmr->hdma[TMR_DMA_ID_CC3], (uint32_t)BurstBuffer, + (uint32_t)&htmr->Instance->DMAR, DataLength) != DAL_OK) + { + /* Return error status */ + return DAL_ERROR; + } + break; + } + case TMR_DMA_CC4: + { + /* Set the DMA compare callbacks */ + htmr->hdma[TMR_DMA_ID_CC4]->XferCpltCallback = TMR_DMADelayPulseCplt; + htmr->hdma[TMR_DMA_ID_CC4]->XferHalfCpltCallback = TMR_DMADelayPulseHalfCplt; + + /* Set the DMA error callback */ + htmr->hdma[TMR_DMA_ID_CC4]->XferErrorCallback = TMR_DMAError ; + + /* Enable the DMA stream */ + if (DAL_DMA_Start_IT(htmr->hdma[TMR_DMA_ID_CC4], (uint32_t)BurstBuffer, + (uint32_t)&htmr->Instance->DMAR, DataLength) != DAL_OK) + { + /* Return error status */ + return DAL_ERROR; + } + break; + } + case TMR_DMA_COM: + { + /* Set the DMA commutation callbacks */ + htmr->hdma[TMR_DMA_ID_COMMUTATION]->XferCpltCallback = TMREx_DMACommutationCplt; + htmr->hdma[TMR_DMA_ID_COMMUTATION]->XferHalfCpltCallback = TMREx_DMACommutationHalfCplt; + + /* Set the DMA error callback */ + htmr->hdma[TMR_DMA_ID_COMMUTATION]->XferErrorCallback = TMR_DMAError ; + + /* Enable the DMA stream */ + if (DAL_DMA_Start_IT(htmr->hdma[TMR_DMA_ID_COMMUTATION], (uint32_t)BurstBuffer, + (uint32_t)&htmr->Instance->DMAR, DataLength) != DAL_OK) + { + /* Return error status */ + return DAL_ERROR; + } + break; + } + case TMR_DMA_TRIGGER: + { + /* Set the DMA trigger callbacks */ + htmr->hdma[TMR_DMA_ID_TRIGGER]->XferCpltCallback = TMR_DMATriggerCplt; + htmr->hdma[TMR_DMA_ID_TRIGGER]->XferHalfCpltCallback = TMR_DMATriggerHalfCplt; + + /* Set the DMA error callback */ + htmr->hdma[TMR_DMA_ID_TRIGGER]->XferErrorCallback = TMR_DMAError ; + + /* Enable the DMA stream */ + if (DAL_DMA_Start_IT(htmr->hdma[TMR_DMA_ID_TRIGGER], (uint32_t)BurstBuffer, + (uint32_t)&htmr->Instance->DMAR, DataLength) != DAL_OK) + { + /* Return error status */ + return DAL_ERROR; + } + break; + } + default: + status = DAL_ERROR; + break; + } + + if (status == DAL_OK) + { + /* Configure the DMA Burst Mode */ + htmr->Instance->DCTRL = (BurstBaseAddress | BurstLength); + /* Enable the TMR DMA Request */ + __DAL_TMR_ENABLE_DMA(htmr, BurstRequestSrc); + } + + /* Return function status */ + return status; +} + +/** + * @brief Stops the TMR DMA Burst mode + * @param htmr TMR handle + * @param BurstRequestSrc TMR DMA Request sources to disable + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMR_DMABurst_WriteStop(TMR_HandleTypeDef *htmr, uint32_t BurstRequestSrc) +{ + DAL_StatusTypeDef status = DAL_OK; + + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_DMA_SOURCE(BurstRequestSrc)); + + /* Abort the DMA transfer (at least disable the DMA stream) */ + switch (BurstRequestSrc) + { + case TMR_DMA_UPDATE: + { + (void)DAL_DMA_Abort_IT(htmr->hdma[TMR_DMA_ID_UPDATE]); + break; + } + case TMR_DMA_CC1: + { + (void)DAL_DMA_Abort_IT(htmr->hdma[TMR_DMA_ID_CC1]); + break; + } + case TMR_DMA_CC2: + { + (void)DAL_DMA_Abort_IT(htmr->hdma[TMR_DMA_ID_CC2]); + break; + } + case TMR_DMA_CC3: + { + (void)DAL_DMA_Abort_IT(htmr->hdma[TMR_DMA_ID_CC3]); + break; + } + case TMR_DMA_CC4: + { + (void)DAL_DMA_Abort_IT(htmr->hdma[TMR_DMA_ID_CC4]); + break; + } + case TMR_DMA_COM: + { + (void)DAL_DMA_Abort_IT(htmr->hdma[TMR_DMA_ID_COMMUTATION]); + break; + } + case TMR_DMA_TRIGGER: + { + (void)DAL_DMA_Abort_IT(htmr->hdma[TMR_DMA_ID_TRIGGER]); + break; + } + default: + status = DAL_ERROR; + break; + } + + if (status == DAL_OK) + { + /* Disable the TMR Update DMA request */ + __DAL_TMR_DISABLE_DMA(htmr, BurstRequestSrc); + + /* Change the DMA burst operation state */ + htmr->DMABurstState = DAL_DMA_BURST_STATE_READY; + } + + /* Return function status */ + return status; +} + +/** + * @brief Configure the DMA Burst to transfer Data from the TMR peripheral to the memory + * @param htmr TMR handle + * @param BurstBaseAddress TMR Base address from where the DMA will start the Data read + * This parameter can be one of the following values: + * @arg TMR_DMABASE_CTRL1 + * @arg TMR_DMABASE_CTRL2 + * @arg TMR_DMABASE_SMCTRL + * @arg TMR_DMABASE_DIEN + * @arg TMR_DMABASE_STS + * @arg TMR_DMABASE_CEG + * @arg TMR_DMABASE_CCM1 + * @arg TMR_DMABASE_CCM2 + * @arg TMR_DMABASE_CCEN + * @arg TMR_DMABASE_CNT + * @arg TMR_DMABASE_PSC + * @arg TMR_DMABASE_AUTORLD + * @arg TMR_DMABASE_REPCNT + * @arg TMR_DMABASE_CC1 + * @arg TMR_DMABASE_CC2 + * @arg TMR_DMABASE_CC3 + * @arg TMR_DMABASE_CC4 + * @arg TMR_DMABASE_BDT + * @param BurstRequestSrc TMR DMA Request sources + * This parameter can be one of the following values: + * @arg TMR_DMA_UPDATE: TMR update Interrupt source + * @arg TMR_DMA_CC1: TMR Capture Compare 1 DMA source + * @arg TMR_DMA_CC2: TMR Capture Compare 2 DMA source + * @arg TMR_DMA_CC3: TMR Capture Compare 3 DMA source + * @arg TMR_DMA_CC4: TMR Capture Compare 4 DMA source + * @arg TMR_DMA_COM: TMR Commutation DMA source + * @arg TMR_DMA_TRIGGER: TMR Trigger DMA source + * @param BurstBuffer The Buffer address. + * @param BurstLength DMA Burst length. This parameter can be one value + * between: TMR_DMABURSTLENGTH_1TRANSFER and TMR_DMABURSTLENGTH_18TRANSFERS. + * @note This function should be used only when BurstLength is equal to DMA data transfer length. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMR_DMABurst_ReadStart(TMR_HandleTypeDef *htmr, uint32_t BurstBaseAddress, + uint32_t BurstRequestSrc, uint32_t *BurstBuffer, uint32_t BurstLength) +{ + DAL_StatusTypeDef status; + + status = DAL_TMR_DMABurst_MultiReadStart(htmr, BurstBaseAddress, BurstRequestSrc, BurstBuffer, BurstLength, + ((BurstLength) >> 8U) + 1U); + + + return status; +} + +/** + * @brief Configure the DMA Burst to transfer Data from the TMR peripheral to the memory + * @param htmr TMR handle + * @param BurstBaseAddress TMR Base address from where the DMA will start the Data read + * This parameter can be one of the following values: + * @arg TMR_DMABASE_CTRL1 + * @arg TMR_DMABASE_CTRL2 + * @arg TMR_DMABASE_SMCTRL + * @arg TMR_DMABASE_DIEN + * @arg TMR_DMABASE_STS + * @arg TMR_DMABASE_CEG + * @arg TMR_DMABASE_CCM1 + * @arg TMR_DMABASE_CCM2 + * @arg TMR_DMABASE_CCEN + * @arg TMR_DMABASE_CNT + * @arg TMR_DMABASE_PSC + * @arg TMR_DMABASE_AUTORLD + * @arg TMR_DMABASE_REPCNT + * @arg TMR_DMABASE_CC1 + * @arg TMR_DMABASE_CC2 + * @arg TMR_DMABASE_CC3 + * @arg TMR_DMABASE_CC4 + * @arg TMR_DMABASE_BDT + * @param BurstRequestSrc TMR DMA Request sources + * This parameter can be one of the following values: + * @arg TMR_DMA_UPDATE: TMR update Interrupt source + * @arg TMR_DMA_CC1: TMR Capture Compare 1 DMA source + * @arg TMR_DMA_CC2: TMR Capture Compare 2 DMA source + * @arg TMR_DMA_CC3: TMR Capture Compare 3 DMA source + * @arg TMR_DMA_CC4: TMR Capture Compare 4 DMA source + * @arg TMR_DMA_COM: TMR Commutation DMA source + * @arg TMR_DMA_TRIGGER: TMR Trigger DMA source + * @param BurstBuffer The Buffer address. + * @param BurstLength DMA Burst length. This parameter can be one value + * between: TMR_DMABURSTLENGTH_1TRANSFER and TMR_DMABURSTLENGTH_18TRANSFERS. + * @param DataLength Data length. This parameter can be one value + * between 1 and 0xFFFF. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMR_DMABurst_MultiReadStart(TMR_HandleTypeDef *htmr, uint32_t BurstBaseAddress, + uint32_t BurstRequestSrc, uint32_t *BurstBuffer, + uint32_t BurstLength, uint32_t DataLength) +{ + DAL_StatusTypeDef status = DAL_OK; + + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_DMABURST_INSTANCE(htmr->Instance)); + ASSERT_PARAM(IS_TMR_DMA_BASE(BurstBaseAddress)); + ASSERT_PARAM(IS_TMR_DMA_SOURCE(BurstRequestSrc)); + ASSERT_PARAM(IS_TMR_DMA_LENGTH(BurstLength)); + ASSERT_PARAM(IS_TMR_DMA_DATA_LENGTH(DataLength)); + + if (htmr->DMABurstState == DAL_DMA_BURST_STATE_BUSY) + { + return DAL_BUSY; + } + else if (htmr->DMABurstState == DAL_DMA_BURST_STATE_READY) + { + if ((BurstBuffer == NULL) && (BurstLength > 0U)) + { + return DAL_ERROR; + } + else + { + htmr->DMABurstState = DAL_DMA_BURST_STATE_BUSY; + } + } + else + { + /* nothing to do */ + } + switch (BurstRequestSrc) + { + case TMR_DMA_UPDATE: + { + /* Set the DMA Period elapsed callbacks */ + htmr->hdma[TMR_DMA_ID_UPDATE]->XferCpltCallback = TMR_DMAPeriodElapsedCplt; + htmr->hdma[TMR_DMA_ID_UPDATE]->XferHalfCpltCallback = TMR_DMAPeriodElapsedHalfCplt; + + /* Set the DMA error callback */ + htmr->hdma[TMR_DMA_ID_UPDATE]->XferErrorCallback = TMR_DMAError ; + + /* Enable the DMA stream */ + if (DAL_DMA_Start_IT(htmr->hdma[TMR_DMA_ID_UPDATE], (uint32_t)&htmr->Instance->DMAR, (uint32_t)BurstBuffer, + DataLength) != DAL_OK) + { + /* Return error status */ + return DAL_ERROR; + } + break; + } + case TMR_DMA_CC1: + { + /* Set the DMA capture callbacks */ + htmr->hdma[TMR_DMA_ID_CC1]->XferCpltCallback = TMR_DMACaptureCplt; + htmr->hdma[TMR_DMA_ID_CC1]->XferHalfCpltCallback = TMR_DMACaptureHalfCplt; + + /* Set the DMA error callback */ + htmr->hdma[TMR_DMA_ID_CC1]->XferErrorCallback = TMR_DMAError ; + + /* Enable the DMA stream */ + if (DAL_DMA_Start_IT(htmr->hdma[TMR_DMA_ID_CC1], (uint32_t)&htmr->Instance->DMAR, (uint32_t)BurstBuffer, + DataLength) != DAL_OK) + { + /* Return error status */ + return DAL_ERROR; + } + break; + } + case TMR_DMA_CC2: + { + /* Set the DMA capture callbacks */ + htmr->hdma[TMR_DMA_ID_CC2]->XferCpltCallback = TMR_DMACaptureCplt; + htmr->hdma[TMR_DMA_ID_CC2]->XferHalfCpltCallback = TMR_DMACaptureHalfCplt; + + /* Set the DMA error callback */ + htmr->hdma[TMR_DMA_ID_CC2]->XferErrorCallback = TMR_DMAError ; + + /* Enable the DMA stream */ + if (DAL_DMA_Start_IT(htmr->hdma[TMR_DMA_ID_CC2], (uint32_t)&htmr->Instance->DMAR, (uint32_t)BurstBuffer, + DataLength) != DAL_OK) + { + /* Return error status */ + return DAL_ERROR; + } + break; + } + case TMR_DMA_CC3: + { + /* Set the DMA capture callbacks */ + htmr->hdma[TMR_DMA_ID_CC3]->XferCpltCallback = TMR_DMACaptureCplt; + htmr->hdma[TMR_DMA_ID_CC3]->XferHalfCpltCallback = TMR_DMACaptureHalfCplt; + + /* Set the DMA error callback */ + htmr->hdma[TMR_DMA_ID_CC3]->XferErrorCallback = TMR_DMAError ; + + /* Enable the DMA stream */ + if (DAL_DMA_Start_IT(htmr->hdma[TMR_DMA_ID_CC3], (uint32_t)&htmr->Instance->DMAR, (uint32_t)BurstBuffer, + DataLength) != DAL_OK) + { + /* Return error status */ + return DAL_ERROR; + } + break; + } + case TMR_DMA_CC4: + { + /* Set the DMA capture callbacks */ + htmr->hdma[TMR_DMA_ID_CC4]->XferCpltCallback = TMR_DMACaptureCplt; + htmr->hdma[TMR_DMA_ID_CC4]->XferHalfCpltCallback = TMR_DMACaptureHalfCplt; + + /* Set the DMA error callback */ + htmr->hdma[TMR_DMA_ID_CC4]->XferErrorCallback = TMR_DMAError ; + + /* Enable the DMA stream */ + if (DAL_DMA_Start_IT(htmr->hdma[TMR_DMA_ID_CC4], (uint32_t)&htmr->Instance->DMAR, (uint32_t)BurstBuffer, + DataLength) != DAL_OK) + { + /* Return error status */ + return DAL_ERROR; + } + break; + } + case TMR_DMA_COM: + { + /* Set the DMA commutation callbacks */ + htmr->hdma[TMR_DMA_ID_COMMUTATION]->XferCpltCallback = TMREx_DMACommutationCplt; + htmr->hdma[TMR_DMA_ID_COMMUTATION]->XferHalfCpltCallback = TMREx_DMACommutationHalfCplt; + + /* Set the DMA error callback */ + htmr->hdma[TMR_DMA_ID_COMMUTATION]->XferErrorCallback = TMR_DMAError ; + + /* Enable the DMA stream */ + if (DAL_DMA_Start_IT(htmr->hdma[TMR_DMA_ID_COMMUTATION], (uint32_t)&htmr->Instance->DMAR, (uint32_t)BurstBuffer, + DataLength) != DAL_OK) + { + /* Return error status */ + return DAL_ERROR; + } + break; + } + case TMR_DMA_TRIGGER: + { + /* Set the DMA trigger callbacks */ + htmr->hdma[TMR_DMA_ID_TRIGGER]->XferCpltCallback = TMR_DMATriggerCplt; + htmr->hdma[TMR_DMA_ID_TRIGGER]->XferHalfCpltCallback = TMR_DMATriggerHalfCplt; + + /* Set the DMA error callback */ + htmr->hdma[TMR_DMA_ID_TRIGGER]->XferErrorCallback = TMR_DMAError ; + + /* Enable the DMA stream */ + if (DAL_DMA_Start_IT(htmr->hdma[TMR_DMA_ID_TRIGGER], (uint32_t)&htmr->Instance->DMAR, (uint32_t)BurstBuffer, + DataLength) != DAL_OK) + { + /* Return error status */ + return DAL_ERROR; + } + break; + } + default: + status = DAL_ERROR; + break; + } + + if (status == DAL_OK) + { + /* Configure the DMA Burst Mode */ + htmr->Instance->DCTRL = (BurstBaseAddress | BurstLength); + + /* Enable the TMR DMA Request */ + __DAL_TMR_ENABLE_DMA(htmr, BurstRequestSrc); + } + + /* Return function status */ + return status; +} + +/** + * @brief Stop the DMA burst reading + * @param htmr TMR handle + * @param BurstRequestSrc TMR DMA Request sources to disable. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMR_DMABurst_ReadStop(TMR_HandleTypeDef *htmr, uint32_t BurstRequestSrc) +{ + DAL_StatusTypeDef status = DAL_OK; + + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_DMA_SOURCE(BurstRequestSrc)); + + /* Abort the DMA transfer (at least disable the DMA stream) */ + switch (BurstRequestSrc) + { + case TMR_DMA_UPDATE: + { + (void)DAL_DMA_Abort_IT(htmr->hdma[TMR_DMA_ID_UPDATE]); + break; + } + case TMR_DMA_CC1: + { + (void)DAL_DMA_Abort_IT(htmr->hdma[TMR_DMA_ID_CC1]); + break; + } + case TMR_DMA_CC2: + { + (void)DAL_DMA_Abort_IT(htmr->hdma[TMR_DMA_ID_CC2]); + break; + } + case TMR_DMA_CC3: + { + (void)DAL_DMA_Abort_IT(htmr->hdma[TMR_DMA_ID_CC3]); + break; + } + case TMR_DMA_CC4: + { + (void)DAL_DMA_Abort_IT(htmr->hdma[TMR_DMA_ID_CC4]); + break; + } + case TMR_DMA_COM: + { + (void)DAL_DMA_Abort_IT(htmr->hdma[TMR_DMA_ID_COMMUTATION]); + break; + } + case TMR_DMA_TRIGGER: + { + (void)DAL_DMA_Abort_IT(htmr->hdma[TMR_DMA_ID_TRIGGER]); + break; + } + default: + status = DAL_ERROR; + break; + } + + if (status == DAL_OK) + { + /* Disable the TMR Update DMA request */ + __DAL_TMR_DISABLE_DMA(htmr, BurstRequestSrc); + + /* Change the DMA burst operation state */ + htmr->DMABurstState = DAL_DMA_BURST_STATE_READY; + } + + /* Return function status */ + return status; +} + +/** + * @brief Generate a software event + * @param htmr TMR handle + * @param EventSource specifies the event source. + * This parameter can be one of the following values: + * @arg TMR_EVENTSOURCE_UPDATE: Timer update Event source + * @arg TMR_EVENTSOURCE_CC1: Timer Capture Compare 1 Event source + * @arg TMR_EVENTSOURCE_CC2: Timer Capture Compare 2 Event source + * @arg TMR_EVENTSOURCE_CC3: Timer Capture Compare 3 Event source + * @arg TMR_EVENTSOURCE_CC4: Timer Capture Compare 4 Event source + * @arg TMR_EVENTSOURCE_COM: Timer COM event source + * @arg TMR_EVENTSOURCE_TRIGGER: Timer Trigger Event source + * @arg TMR_EVENTSOURCE_BREAK: Timer Break event source + * @note Basic timers can only generate an update event. + * @note TMR_EVENTSOURCE_COM is relevant only with advanced timer instances. + * @note TMR_EVENTSOURCE_BREAK are relevant only for timer instances + * supporting a break input. + * @retval DAL status + */ + +DAL_StatusTypeDef DAL_TMR_GenerateEvent(TMR_HandleTypeDef *htmr, uint32_t EventSource) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_INSTANCE(htmr->Instance)); + ASSERT_PARAM(IS_TMR_EVENT_SOURCE(EventSource)); + + /* Process Locked */ + __DAL_LOCK(htmr); + + /* Change the TMR state */ + htmr->State = DAL_TMR_STATE_BUSY; + + /* Set the event sources */ + htmr->Instance->CEG = EventSource; + + /* Change the TMR state */ + htmr->State = DAL_TMR_STATE_READY; + + __DAL_UNLOCK(htmr); + + /* Return function status */ + return DAL_OK; +} + +/** + * @brief Configures the OCRef clear feature + * @param htmr TMR handle + * @param sClearInputConfig pointer to a TMR_ClearInputConfigTypeDef structure that + * contains the OCREF clear feature and parameters for the TMR peripheral. + * @param Channel specifies the TMR Channel + * This parameter can be one of the following values: + * @arg TMR_CHANNEL_1: TMR Channel 1 + * @arg TMR_CHANNEL_2: TMR Channel 2 + * @arg TMR_CHANNEL_3: TMR Channel 3 + * @arg TMR_CHANNEL_4: TMR Channel 4 + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMR_ConfigOCrefClear(TMR_HandleTypeDef *htmr, + TMR_ClearInputConfigTypeDef *sClearInputConfig, + uint32_t Channel) +{ + DAL_StatusTypeDef status = DAL_OK; + + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_OCXREF_CLEAR_INSTANCE(htmr->Instance)); + ASSERT_PARAM(IS_TMR_CLEARINPUT_SOURCE(sClearInputConfig->ClearInputSource)); + + /* Process Locked */ + __DAL_LOCK(htmr); + + htmr->State = DAL_TMR_STATE_BUSY; + + switch (sClearInputConfig->ClearInputSource) + { + case TMR_CLEARINPUTSOURCE_NONE: + { + /* Clear the OCREF clear selection bit and the the ETR Bits */ + CLEAR_BIT(htmr->Instance->SMCTRL, (TMR_SMCTRL_ETFCFG | TMR_SMCTRL_ETPCFG | TMR_SMCTRL_ECEN | TMR_SMCTRL_ETPOL)); + break; + } + + case TMR_CLEARINPUTSOURCE_ETR: + { + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_CLEARINPUT_POLARITY(sClearInputConfig->ClearInputPolarity)); + ASSERT_PARAM(IS_TMR_CLEARINPUT_PRESCALER(sClearInputConfig->ClearInputPrescaler)); + ASSERT_PARAM(IS_TMR_CLEARINPUT_FILTER(sClearInputConfig->ClearInputFilter)); + + /* When OCRef clear feature is used with ETR source, ETR prescaler must be off */ + if (sClearInputConfig->ClearInputPrescaler != TMR_CLEARINPUTPRESCALER_DIV1) + { + htmr->State = DAL_TMR_STATE_READY; + __DAL_UNLOCK(htmr); + return DAL_ERROR; + } + + TMR_ETR_SetConfig(htmr->Instance, + sClearInputConfig->ClearInputPrescaler, + sClearInputConfig->ClearInputPolarity, + sClearInputConfig->ClearInputFilter); + break; + } + + default: + status = DAL_ERROR; + break; + } + + if (status == DAL_OK) + { + switch (Channel) + { + case TMR_CHANNEL_1: + { + if (sClearInputConfig->ClearInputState != (uint32_t)DISABLE) + { + /* Enable the OCREF clear feature for Channel 1 */ + SET_BIT(htmr->Instance->CCM1, TMR_CCM1_OC1CEN); + } + else + { + /* Disable the OCREF clear feature for Channel 1 */ + CLEAR_BIT(htmr->Instance->CCM1, TMR_CCM1_OC1CEN); + } + break; + } + case TMR_CHANNEL_2: + { + if (sClearInputConfig->ClearInputState != (uint32_t)DISABLE) + { + /* Enable the OCREF clear feature for Channel 2 */ + SET_BIT(htmr->Instance->CCM1, TMR_CCM1_OC2CEN); + } + else + { + /* Disable the OCREF clear feature for Channel 2 */ + CLEAR_BIT(htmr->Instance->CCM1, TMR_CCM1_OC2CEN); + } + break; + } + case TMR_CHANNEL_3: + { + if (sClearInputConfig->ClearInputState != (uint32_t)DISABLE) + { + /* Enable the OCREF clear feature for Channel 3 */ + SET_BIT(htmr->Instance->CCM2, TMR_CCM2_OC3CEN); + } + else + { + /* Disable the OCREF clear feature for Channel 3 */ + CLEAR_BIT(htmr->Instance->CCM2, TMR_CCM2_OC3CEN); + } + break; + } + case TMR_CHANNEL_4: + { + if (sClearInputConfig->ClearInputState != (uint32_t)DISABLE) + { + /* Enable the OCREF clear feature for Channel 4 */ + SET_BIT(htmr->Instance->CCM2, TMR_CCM2_OC4CEN); + } + else + { + /* Disable the OCREF clear feature for Channel 4 */ + CLEAR_BIT(htmr->Instance->CCM2, TMR_CCM2_OC4CEN); + } + break; + } + default: + break; + } + } + + htmr->State = DAL_TMR_STATE_READY; + + __DAL_UNLOCK(htmr); + + return status; +} + +/** + * @brief Configures the clock source to be used + * @param htmr TMR handle + * @param sClockSourceConfig pointer to a TMR_ClockConfigTypeDef structure that + * contains the clock source information for the TMR peripheral. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMR_ConfigClockSource(TMR_HandleTypeDef *htmr, TMR_ClockConfigTypeDef *sClockSourceConfig) +{ + DAL_StatusTypeDef status = DAL_OK; + uint32_t tmpsmcr; + + /* Process Locked */ + __DAL_LOCK(htmr); + + htmr->State = DAL_TMR_STATE_BUSY; + + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_CLOCKSOURCE(sClockSourceConfig->ClockSource)); + + /* Reset the SMFSEL, TRGSEL, ETFCFG, ETPCFG and ECEN bits */ + tmpsmcr = htmr->Instance->SMCTRL; + tmpsmcr &= ~(TMR_SMCTRL_SMFSEL | TMR_SMCTRL_TRGSEL); + tmpsmcr &= ~(TMR_SMCTRL_ETFCFG | TMR_SMCTRL_ETPCFG | TMR_SMCTRL_ECEN | TMR_SMCTRL_ETPOL); + htmr->Instance->SMCTRL = tmpsmcr; + + switch (sClockSourceConfig->ClockSource) + { + case TMR_CLOCKSOURCE_INTERNAL: + { + ASSERT_PARAM(IS_TMR_INSTANCE(htmr->Instance)); + break; + } + + case TMR_CLOCKSOURCE_ETRMODE1: + { + /* Check whether or not the timer instance supports external trigger input mode 1 (ETRF)*/ + ASSERT_PARAM(IS_TMR_CLOCKSOURCE_ETRMODE1_INSTANCE(htmr->Instance)); + + /* Check ETR input conditioning related parameters */ + ASSERT_PARAM(IS_TMR_CLOCKPRESCALER(sClockSourceConfig->ClockPrescaler)); + ASSERT_PARAM(IS_TMR_CLOCKPOLARITY(sClockSourceConfig->ClockPolarity)); + ASSERT_PARAM(IS_TMR_CLOCKFILTER(sClockSourceConfig->ClockFilter)); + + /* Configure the ETR Clock source */ + TMR_ETR_SetConfig(htmr->Instance, + sClockSourceConfig->ClockPrescaler, + sClockSourceConfig->ClockPolarity, + sClockSourceConfig->ClockFilter); + + /* Select the External clock mode1 and the ETRF trigger */ + tmpsmcr = htmr->Instance->SMCTRL; + tmpsmcr |= (TMR_SLAVEMODE_EXTERNAL1 | TMR_CLOCKSOURCE_ETRMODE1); + /* Write to TMRx SMCTRL */ + htmr->Instance->SMCTRL = tmpsmcr; + break; + } + + case TMR_CLOCKSOURCE_ETRMODE2: + { + /* Check whether or not the timer instance supports external trigger input mode 2 (ETRF)*/ + ASSERT_PARAM(IS_TMR_CLOCKSOURCE_ETRMODE2_INSTANCE(htmr->Instance)); + + /* Check ETR input conditioning related parameters */ + ASSERT_PARAM(IS_TMR_CLOCKPRESCALER(sClockSourceConfig->ClockPrescaler)); + ASSERT_PARAM(IS_TMR_CLOCKPOLARITY(sClockSourceConfig->ClockPolarity)); + ASSERT_PARAM(IS_TMR_CLOCKFILTER(sClockSourceConfig->ClockFilter)); + + /* Configure the ETR Clock source */ + TMR_ETR_SetConfig(htmr->Instance, + sClockSourceConfig->ClockPrescaler, + sClockSourceConfig->ClockPolarity, + sClockSourceConfig->ClockFilter); + /* Enable the External clock mode2 */ + htmr->Instance->SMCTRL |= TMR_SMCTRL_ECEN; + break; + } + + case TMR_CLOCKSOURCE_TI1: + { + /* Check whether or not the timer instance supports external clock mode 1 */ + ASSERT_PARAM(IS_TMR_CLOCKSOURCE_TIX_INSTANCE(htmr->Instance)); + + /* Check TI1 input conditioning related parameters */ + ASSERT_PARAM(IS_TMR_CLOCKPOLARITY(sClockSourceConfig->ClockPolarity)); + ASSERT_PARAM(IS_TMR_CLOCKFILTER(sClockSourceConfig->ClockFilter)); + + TMR_TI1_ConfigInputStage(htmr->Instance, + sClockSourceConfig->ClockPolarity, + sClockSourceConfig->ClockFilter); + TMR_ITRx_SetConfig(htmr->Instance, TMR_CLOCKSOURCE_TI1); + break; + } + + case TMR_CLOCKSOURCE_TI2: + { + /* Check whether or not the timer instance supports external clock mode 1 (ETRF)*/ + ASSERT_PARAM(IS_TMR_CLOCKSOURCE_TIX_INSTANCE(htmr->Instance)); + + /* Check TI2 input conditioning related parameters */ + ASSERT_PARAM(IS_TMR_CLOCKPOLARITY(sClockSourceConfig->ClockPolarity)); + ASSERT_PARAM(IS_TMR_CLOCKFILTER(sClockSourceConfig->ClockFilter)); + + TMR_TI2_ConfigInputStage(htmr->Instance, + sClockSourceConfig->ClockPolarity, + sClockSourceConfig->ClockFilter); + TMR_ITRx_SetConfig(htmr->Instance, TMR_CLOCKSOURCE_TI2); + break; + } + + case TMR_CLOCKSOURCE_TI1ED: + { + /* Check whether or not the timer instance supports external clock mode 1 */ + ASSERT_PARAM(IS_TMR_CLOCKSOURCE_TIX_INSTANCE(htmr->Instance)); + + /* Check TI1 input conditioning related parameters */ + ASSERT_PARAM(IS_TMR_CLOCKPOLARITY(sClockSourceConfig->ClockPolarity)); + ASSERT_PARAM(IS_TMR_CLOCKFILTER(sClockSourceConfig->ClockFilter)); + + TMR_TI1_ConfigInputStage(htmr->Instance, + sClockSourceConfig->ClockPolarity, + sClockSourceConfig->ClockFilter); + TMR_ITRx_SetConfig(htmr->Instance, TMR_CLOCKSOURCE_TI1ED); + break; + } + + case TMR_CLOCKSOURCE_ITR0: + case TMR_CLOCKSOURCE_ITR1: + case TMR_CLOCKSOURCE_ITR2: + case TMR_CLOCKSOURCE_ITR3: + { + /* Check whether or not the timer instance supports internal trigger input */ + ASSERT_PARAM(IS_TMR_CLOCKSOURCE_ITRX_INSTANCE(htmr->Instance)); + + TMR_ITRx_SetConfig(htmr->Instance, sClockSourceConfig->ClockSource); + break; + } + + default: + status = DAL_ERROR; + break; + } + htmr->State = DAL_TMR_STATE_READY; + + __DAL_UNLOCK(htmr); + + return status; +} + +/** + * @brief Selects the signal connected to the TI1 input: direct from CH1_input + * or a XOR combination between CH1_input, CH2_input & CH3_input + * @param htmr TMR handle. + * @param TI1_Selection Indicate whether or not channel 1 is connected to the + * output of a XOR gate. + * This parameter can be one of the following values: + * @arg TMR_TI1SELECTION_CH1: The TMRx_CH1 pin is connected to TI1 input + * @arg TMR_TI1SELECTION_XORCOMBINATION: The TMRx_CH1, CH2 and CH3 + * pins are connected to the TI1 input (XOR combination) + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMR_ConfigTI1Input(TMR_HandleTypeDef *htmr, uint32_t TI1_Selection) +{ + uint32_t tmpcr2; + + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_XOR_INSTANCE(htmr->Instance)); + ASSERT_PARAM(IS_TMR_TI1SELECTION(TI1_Selection)); + + /* Get the TMRx CTRL2 register value */ + tmpcr2 = htmr->Instance->CTRL2; + + /* Reset the TI1 selection */ + tmpcr2 &= ~TMR_CTRL2_TI1SEL; + + /* Set the TI1 selection */ + tmpcr2 |= TI1_Selection; + + /* Write to TMRx CTRL2 */ + htmr->Instance->CTRL2 = tmpcr2; + + return DAL_OK; +} + +/** + * @brief Configures the TMR in Slave mode + * @param htmr TMR handle. + * @param sSlaveConfig pointer to a TMR_SlaveConfigTypeDef structure that + * contains the selected trigger (internal trigger input, filtered + * timer input or external trigger input) and the Slave mode + * (Disable, Reset, Gated, Trigger, External clock mode 1). + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMR_SlaveConfigSynchro(TMR_HandleTypeDef *htmr, TMR_SlaveConfigTypeDef *sSlaveConfig) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_SLAVE_INSTANCE(htmr->Instance)); + ASSERT_PARAM(IS_TMR_SLAVE_MODE(sSlaveConfig->SlaveMode)); + ASSERT_PARAM(IS_TMR_TRIGGER_SELECTION(sSlaveConfig->InputTrigger)); + + __DAL_LOCK(htmr); + + htmr->State = DAL_TMR_STATE_BUSY; + + if (TMR_SlaveTimer_SetConfig(htmr, sSlaveConfig) != DAL_OK) + { + htmr->State = DAL_TMR_STATE_READY; + __DAL_UNLOCK(htmr); + return DAL_ERROR; + } + + /* Disable Trigger Interrupt */ + __DAL_TMR_DISABLE_IT(htmr, TMR_IT_TRIGGER); + + /* Disable Trigger DMA request */ + __DAL_TMR_DISABLE_DMA(htmr, TMR_DMA_TRIGGER); + + htmr->State = DAL_TMR_STATE_READY; + + __DAL_UNLOCK(htmr); + + return DAL_OK; +} + +/** + * @brief Configures the TMR in Slave mode in interrupt mode + * @param htmr TMR handle. + * @param sSlaveConfig pointer to a TMR_SlaveConfigTypeDef structure that + * contains the selected trigger (internal trigger input, filtered + * timer input or external trigger input) and the Slave mode + * (Disable, Reset, Gated, Trigger, External clock mode 1). + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMR_SlaveConfigSynchro_IT(TMR_HandleTypeDef *htmr, + TMR_SlaveConfigTypeDef *sSlaveConfig) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_SLAVE_INSTANCE(htmr->Instance)); + ASSERT_PARAM(IS_TMR_SLAVE_MODE(sSlaveConfig->SlaveMode)); + ASSERT_PARAM(IS_TMR_TRIGGER_SELECTION(sSlaveConfig->InputTrigger)); + + __DAL_LOCK(htmr); + + htmr->State = DAL_TMR_STATE_BUSY; + + if (TMR_SlaveTimer_SetConfig(htmr, sSlaveConfig) != DAL_OK) + { + htmr->State = DAL_TMR_STATE_READY; + __DAL_UNLOCK(htmr); + return DAL_ERROR; + } + + /* Enable Trigger Interrupt */ + __DAL_TMR_ENABLE_IT(htmr, TMR_IT_TRIGGER); + + /* Disable Trigger DMA request */ + __DAL_TMR_DISABLE_DMA(htmr, TMR_DMA_TRIGGER); + + htmr->State = DAL_TMR_STATE_READY; + + __DAL_UNLOCK(htmr); + + return DAL_OK; +} + +/** + * @brief Read the captured value from Capture Compare unit + * @param htmr TMR handle. + * @param Channel TMR Channels to be enabled + * This parameter can be one of the following values: + * @arg TMR_CHANNEL_1: TMR Channel 1 selected + * @arg TMR_CHANNEL_2: TMR Channel 2 selected + * @arg TMR_CHANNEL_3: TMR Channel 3 selected + * @arg TMR_CHANNEL_4: TMR Channel 4 selected + * @retval Captured value + */ +uint32_t DAL_TMR_ReadCapturedValue(TMR_HandleTypeDef *htmr, uint32_t Channel) +{ + uint32_t tmpreg = 0U; + + switch (Channel) + { + case TMR_CHANNEL_1: + { + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_CC1_INSTANCE(htmr->Instance)); + + /* Return the capture 1 value */ + tmpreg = htmr->Instance->CC1; + + break; + } + case TMR_CHANNEL_2: + { + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_CC2_INSTANCE(htmr->Instance)); + + /* Return the capture 2 value */ + tmpreg = htmr->Instance->CC2; + + break; + } + + case TMR_CHANNEL_3: + { + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_CC3_INSTANCE(htmr->Instance)); + + /* Return the capture 3 value */ + tmpreg = htmr->Instance->CC3; + + break; + } + + case TMR_CHANNEL_4: + { + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_CC4_INSTANCE(htmr->Instance)); + + /* Return the capture 4 value */ + tmpreg = htmr->Instance->CC4; + + break; + } + + default: + break; + } + + return tmpreg; +} + +/** + * @} + */ + +/** @defgroup TMR_Exported_Functions_Group9 TMR Callbacks functions + * @brief TMR Callbacks functions + * +@verbatim + ============================================================================== + ##### TMR Callbacks functions ##### + ============================================================================== + [..] + This section provides TMR callback functions: + (+) TMR Period elapsed callback + (+) TMR Output Compare callback + (+) TMR Input capture callback + (+) TMR Trigger callback + (+) TMR Error callback + +@endverbatim + * @{ + */ + +/** + * @brief Period elapsed callback in non-blocking mode + * @param htmr TMR handle + * @retval None + */ +__weak void DAL_TMR_PeriodElapsedCallback(TMR_HandleTypeDef *htmr) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(htmr); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_TMR_PeriodElapsedCallback could be implemented in the user file + */ +} + +/** + * @brief Period elapsed half complete callback in non-blocking mode + * @param htmr TMR handle + * @retval None + */ +__weak void DAL_TMR_PeriodElapsedHalfCpltCallback(TMR_HandleTypeDef *htmr) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(htmr); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_TMR_PeriodElapsedHalfCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Output Compare callback in non-blocking mode + * @param htmr TMR OC handle + * @retval None + */ +__weak void DAL_TMR_OC_DelayElapsedCallback(TMR_HandleTypeDef *htmr) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(htmr); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_TMR_OC_DelayElapsedCallback could be implemented in the user file + */ +} + +/** + * @brief Input Capture callback in non-blocking mode + * @param htmr TMR IC handle + * @retval None + */ +__weak void DAL_TMR_IC_CaptureCallback(TMR_HandleTypeDef *htmr) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(htmr); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_TMR_IC_CaptureCallback could be implemented in the user file + */ +} + +/** + * @brief Input Capture half complete callback in non-blocking mode + * @param htmr TMR IC handle + * @retval None + */ +__weak void DAL_TMR_IC_CaptureHalfCpltCallback(TMR_HandleTypeDef *htmr) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(htmr); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_TMR_IC_CaptureHalfCpltCallback could be implemented in the user file + */ +} + +/** + * @brief PWM Pulse finished callback in non-blocking mode + * @param htmr TMR handle + * @retval None + */ +__weak void DAL_TMR_PWM_PulseFinishedCallback(TMR_HandleTypeDef *htmr) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(htmr); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_TMR_PWM_PulseFinishedCallback could be implemented in the user file + */ +} + +/** + * @brief PWM Pulse finished half complete callback in non-blocking mode + * @param htmr TMR handle + * @retval None + */ +__weak void DAL_TMR_PWM_PulseFinishedHalfCpltCallback(TMR_HandleTypeDef *htmr) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(htmr); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_TMR_PWM_PulseFinishedHalfCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Hall Trigger detection callback in non-blocking mode + * @param htmr TMR handle + * @retval None + */ +__weak void DAL_TMR_TriggerCallback(TMR_HandleTypeDef *htmr) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(htmr); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_TMR_TriggerCallback could be implemented in the user file + */ +} + +/** + * @brief Hall Trigger detection half complete callback in non-blocking mode + * @param htmr TMR handle + * @retval None + */ +__weak void DAL_TMR_TriggerHalfCpltCallback(TMR_HandleTypeDef *htmr) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(htmr); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_TMR_TriggerHalfCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Timer error callback in non-blocking mode + * @param htmr TMR handle + * @retval None + */ +__weak void DAL_TMR_ErrorCallback(TMR_HandleTypeDef *htmr) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(htmr); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_TMR_ErrorCallback could be implemented in the user file + */ +} + +#if (USE_DAL_TMR_REGISTER_CALLBACKS == 1) +/** + * @brief Register a User TMR callback to be used instead of the weak predefined callback + * @param htmr tim handle + * @param CallbackID ID of the callback to be registered + * This parameter can be one of the following values: + * @arg @ref DAL_TMR_BASE_MSPINIT_CB_ID Base MspInit Callback ID + * @arg @ref DAL_TMR_BASE_MSPDEINIT_CB_ID Base MspDeInit Callback ID + * @arg @ref DAL_TMR_IC_MSPINIT_CB_ID IC MspInit Callback ID + * @arg @ref DAL_TMR_IC_MSPDEINIT_CB_ID IC MspDeInit Callback ID + * @arg @ref DAL_TMR_OC_MSPINIT_CB_ID OC MspInit Callback ID + * @arg @ref DAL_TMR_OC_MSPDEINIT_CB_ID OC MspDeInit Callback ID + * @arg @ref DAL_TMR_PWM_MSPINIT_CB_ID PWM MspInit Callback ID + * @arg @ref DAL_TMR_PWM_MSPDEINIT_CB_ID PWM MspDeInit Callback ID + * @arg @ref DAL_TMR_ONE_PULSE_MSPINIT_CB_ID One Pulse MspInit Callback ID + * @arg @ref DAL_TMR_ONE_PULSE_MSPDEINIT_CB_ID One Pulse MspDeInit Callback ID + * @arg @ref DAL_TMR_ENCODER_MSPINIT_CB_ID Encoder MspInit Callback ID + * @arg @ref DAL_TMR_ENCODER_MSPDEINIT_CB_ID Encoder MspDeInit Callback ID + * @arg @ref DAL_TMR_HALL_SENSOR_MSPINIT_CB_ID Hall Sensor MspInit Callback ID + * @arg @ref DAL_TMR_HALL_SENSOR_MSPDEINIT_CB_ID Hall Sensor MspDeInit Callback ID + * @arg @ref DAL_TMR_PERIOD_ELAPSED_CB_ID Period Elapsed Callback ID + * @arg @ref DAL_TMR_PERIOD_ELAPSED_HALF_CB_ID Period Elapsed half complete Callback ID + * @arg @ref DAL_TMR_TRIGGER_CB_ID Trigger Callback ID + * @arg @ref DAL_TMR_TRIGGER_HALF_CB_ID Trigger half complete Callback ID + * @arg @ref DAL_TMR_IC_CAPTURE_CB_ID Input Capture Callback ID + * @arg @ref DAL_TMR_IC_CAPTURE_HALF_CB_ID Input Capture half complete Callback ID + * @arg @ref DAL_TMR_OC_DELAY_ELAPSED_CB_ID Output Compare Delay Elapsed Callback ID + * @arg @ref DAL_TMR_PWM_PULSE_FINISHED_CB_ID PWM Pulse Finished Callback ID + * @arg @ref DAL_TMR_PWM_PULSE_FINISHED_HALF_CB_ID PWM Pulse Finished half complete Callback ID + * @arg @ref DAL_TMR_ERROR_CB_ID Error Callback ID + * @arg @ref DAL_TMR_COMMUTATION_CB_ID Commutation Callback ID + * @arg @ref DAL_TMR_COMMUTATION_HALF_CB_ID Commutation half complete Callback ID + * @arg @ref DAL_TMR_BREAK_CB_ID Break Callback ID + * @param pCallback pointer to the callback function + * @retval status + */ +DAL_StatusTypeDef DAL_TMR_RegisterCallback(TMR_HandleTypeDef *htmr, DAL_TMR_CallbackIDTypeDef CallbackID, + pTMR_CallbackTypeDef pCallback) +{ + DAL_StatusTypeDef status = DAL_OK; + + if (pCallback == NULL) + { + return DAL_ERROR; + } + /* Process locked */ + __DAL_LOCK(htmr); + + if (htmr->State == DAL_TMR_STATE_READY) + { + switch (CallbackID) + { + case DAL_TMR_BASE_MSPINIT_CB_ID : + htmr->Base_MspInitCallback = pCallback; + break; + + case DAL_TMR_BASE_MSPDEINIT_CB_ID : + htmr->Base_MspDeInitCallback = pCallback; + break; + + case DAL_TMR_IC_MSPINIT_CB_ID : + htmr->IC_MspInitCallback = pCallback; + break; + + case DAL_TMR_IC_MSPDEINIT_CB_ID : + htmr->IC_MspDeInitCallback = pCallback; + break; + + case DAL_TMR_OC_MSPINIT_CB_ID : + htmr->OC_MspInitCallback = pCallback; + break; + + case DAL_TMR_OC_MSPDEINIT_CB_ID : + htmr->OC_MspDeInitCallback = pCallback; + break; + + case DAL_TMR_PWM_MSPINIT_CB_ID : + htmr->PWM_MspInitCallback = pCallback; + break; + + case DAL_TMR_PWM_MSPDEINIT_CB_ID : + htmr->PWM_MspDeInitCallback = pCallback; + break; + + case DAL_TMR_ONE_PULSE_MSPINIT_CB_ID : + htmr->OnePulse_MspInitCallback = pCallback; + break; + + case DAL_TMR_ONE_PULSE_MSPDEINIT_CB_ID : + htmr->OnePulse_MspDeInitCallback = pCallback; + break; + + case DAL_TMR_ENCODER_MSPINIT_CB_ID : + htmr->Encoder_MspInitCallback = pCallback; + break; + + case DAL_TMR_ENCODER_MSPDEINIT_CB_ID : + htmr->Encoder_MspDeInitCallback = pCallback; + break; + + case DAL_TMR_HALL_SENSOR_MSPINIT_CB_ID : + htmr->HallSensor_MspInitCallback = pCallback; + break; + + case DAL_TMR_HALL_SENSOR_MSPDEINIT_CB_ID : + htmr->HallSensor_MspDeInitCallback = pCallback; + break; + + case DAL_TMR_PERIOD_ELAPSED_CB_ID : + htmr->PeriodElapsedCallback = pCallback; + break; + + case DAL_TMR_PERIOD_ELAPSED_HALF_CB_ID : + htmr->PeriodElapsedHalfCpltCallback = pCallback; + break; + + case DAL_TMR_TRIGGER_CB_ID : + htmr->TriggerCallback = pCallback; + break; + + case DAL_TMR_TRIGGER_HALF_CB_ID : + htmr->TriggerHalfCpltCallback = pCallback; + break; + + case DAL_TMR_IC_CAPTURE_CB_ID : + htmr->IC_CaptureCallback = pCallback; + break; + + case DAL_TMR_IC_CAPTURE_HALF_CB_ID : + htmr->IC_CaptureHalfCpltCallback = pCallback; + break; + + case DAL_TMR_OC_DELAY_ELAPSED_CB_ID : + htmr->OC_DelayElapsedCallback = pCallback; + break; + + case DAL_TMR_PWM_PULSE_FINISHED_CB_ID : + htmr->PWM_PulseFinishedCallback = pCallback; + break; + + case DAL_TMR_PWM_PULSE_FINISHED_HALF_CB_ID : + htmr->PWM_PulseFinishedHalfCpltCallback = pCallback; + break; + + case DAL_TMR_ERROR_CB_ID : + htmr->ErrorCallback = pCallback; + break; + + case DAL_TMR_COMMUTATION_CB_ID : + htmr->CommutationCallback = pCallback; + break; + + case DAL_TMR_COMMUTATION_HALF_CB_ID : + htmr->CommutationHalfCpltCallback = pCallback; + break; + + case DAL_TMR_BREAK_CB_ID : + htmr->BreakCallback = pCallback; + break; + + default : + /* Return error status */ + status = DAL_ERROR; + break; + } + } + else if (htmr->State == DAL_TMR_STATE_RESET) + { + switch (CallbackID) + { + case DAL_TMR_BASE_MSPINIT_CB_ID : + htmr->Base_MspInitCallback = pCallback; + break; + + case DAL_TMR_BASE_MSPDEINIT_CB_ID : + htmr->Base_MspDeInitCallback = pCallback; + break; + + case DAL_TMR_IC_MSPINIT_CB_ID : + htmr->IC_MspInitCallback = pCallback; + break; + + case DAL_TMR_IC_MSPDEINIT_CB_ID : + htmr->IC_MspDeInitCallback = pCallback; + break; + + case DAL_TMR_OC_MSPINIT_CB_ID : + htmr->OC_MspInitCallback = pCallback; + break; + + case DAL_TMR_OC_MSPDEINIT_CB_ID : + htmr->OC_MspDeInitCallback = pCallback; + break; + + case DAL_TMR_PWM_MSPINIT_CB_ID : + htmr->PWM_MspInitCallback = pCallback; + break; + + case DAL_TMR_PWM_MSPDEINIT_CB_ID : + htmr->PWM_MspDeInitCallback = pCallback; + break; + + case DAL_TMR_ONE_PULSE_MSPINIT_CB_ID : + htmr->OnePulse_MspInitCallback = pCallback; + break; + + case DAL_TMR_ONE_PULSE_MSPDEINIT_CB_ID : + htmr->OnePulse_MspDeInitCallback = pCallback; + break; + + case DAL_TMR_ENCODER_MSPINIT_CB_ID : + htmr->Encoder_MspInitCallback = pCallback; + break; + + case DAL_TMR_ENCODER_MSPDEINIT_CB_ID : + htmr->Encoder_MspDeInitCallback = pCallback; + break; + + case DAL_TMR_HALL_SENSOR_MSPINIT_CB_ID : + htmr->HallSensor_MspInitCallback = pCallback; + break; + + case DAL_TMR_HALL_SENSOR_MSPDEINIT_CB_ID : + htmr->HallSensor_MspDeInitCallback = pCallback; + break; + + default : + /* Return error status */ + status = DAL_ERROR; + break; + } + } + else + { + /* Return error status */ + status = DAL_ERROR; + } + + /* Release Lock */ + __DAL_UNLOCK(htmr); + + return status; +} + +/** + * @brief Unregister a TMR callback + * TMR callback is redirected to the weak predefined callback + * @param htmr tim handle + * @param CallbackID ID of the callback to be unregistered + * This parameter can be one of the following values: + * @arg @ref DAL_TMR_BASE_MSPINIT_CB_ID Base MspInit Callback ID + * @arg @ref DAL_TMR_BASE_MSPDEINIT_CB_ID Base MspDeInit Callback ID + * @arg @ref DAL_TMR_IC_MSPINIT_CB_ID IC MspInit Callback ID + * @arg @ref DAL_TMR_IC_MSPDEINIT_CB_ID IC MspDeInit Callback ID + * @arg @ref DAL_TMR_OC_MSPINIT_CB_ID OC MspInit Callback ID + * @arg @ref DAL_TMR_OC_MSPDEINIT_CB_ID OC MspDeInit Callback ID + * @arg @ref DAL_TMR_PWM_MSPINIT_CB_ID PWM MspInit Callback ID + * @arg @ref DAL_TMR_PWM_MSPDEINIT_CB_ID PWM MspDeInit Callback ID + * @arg @ref DAL_TMR_ONE_PULSE_MSPINIT_CB_ID One Pulse MspInit Callback ID + * @arg @ref DAL_TMR_ONE_PULSE_MSPDEINIT_CB_ID One Pulse MspDeInit Callback ID + * @arg @ref DAL_TMR_ENCODER_MSPINIT_CB_ID Encoder MspInit Callback ID + * @arg @ref DAL_TMR_ENCODER_MSPDEINIT_CB_ID Encoder MspDeInit Callback ID + * @arg @ref DAL_TMR_HALL_SENSOR_MSPINIT_CB_ID Hall Sensor MspInit Callback ID + * @arg @ref DAL_TMR_HALL_SENSOR_MSPDEINIT_CB_ID Hall Sensor MspDeInit Callback ID + * @arg @ref DAL_TMR_PERIOD_ELAPSED_CB_ID Period Elapsed Callback ID + * @arg @ref DAL_TMR_PERIOD_ELAPSED_HALF_CB_ID Period Elapsed half complete Callback ID + * @arg @ref DAL_TMR_TRIGGER_CB_ID Trigger Callback ID + * @arg @ref DAL_TMR_TRIGGER_HALF_CB_ID Trigger half complete Callback ID + * @arg @ref DAL_TMR_IC_CAPTURE_CB_ID Input Capture Callback ID + * @arg @ref DAL_TMR_IC_CAPTURE_HALF_CB_ID Input Capture half complete Callback ID + * @arg @ref DAL_TMR_OC_DELAY_ELAPSED_CB_ID Output Compare Delay Elapsed Callback ID + * @arg @ref DAL_TMR_PWM_PULSE_FINISHED_CB_ID PWM Pulse Finished Callback ID + * @arg @ref DAL_TMR_PWM_PULSE_FINISHED_HALF_CB_ID PWM Pulse Finished half complete Callback ID + * @arg @ref DAL_TMR_ERROR_CB_ID Error Callback ID + * @arg @ref DAL_TMR_COMMUTATION_CB_ID Commutation Callback ID + * @arg @ref DAL_TMR_COMMUTATION_HALF_CB_ID Commutation half complete Callback ID + * @arg @ref DAL_TMR_BREAK_CB_ID Break Callback ID + * @retval status + */ +DAL_StatusTypeDef DAL_TMR_UnRegisterCallback(TMR_HandleTypeDef *htmr, DAL_TMR_CallbackIDTypeDef CallbackID) +{ + DAL_StatusTypeDef status = DAL_OK; + + /* Process locked */ + __DAL_LOCK(htmr); + + if (htmr->State == DAL_TMR_STATE_READY) + { + switch (CallbackID) + { + case DAL_TMR_BASE_MSPINIT_CB_ID : + /* Legacy weak Base MspInit Callback */ + htmr->Base_MspInitCallback = DAL_TMR_Base_MspInit; + break; + + case DAL_TMR_BASE_MSPDEINIT_CB_ID : + /* Legacy weak Base Msp DeInit Callback */ + htmr->Base_MspDeInitCallback = DAL_TMR_Base_MspDeInit; + break; + + case DAL_TMR_IC_MSPINIT_CB_ID : + /* Legacy weak IC Msp Init Callback */ + htmr->IC_MspInitCallback = DAL_TMR_IC_MspInit; + break; + + case DAL_TMR_IC_MSPDEINIT_CB_ID : + /* Legacy weak IC Msp DeInit Callback */ + htmr->IC_MspDeInitCallback = DAL_TMR_IC_MspDeInit; + break; + + case DAL_TMR_OC_MSPINIT_CB_ID : + /* Legacy weak OC Msp Init Callback */ + htmr->OC_MspInitCallback = DAL_TMR_OC_MspInit; + break; + + case DAL_TMR_OC_MSPDEINIT_CB_ID : + /* Legacy weak OC Msp DeInit Callback */ + htmr->OC_MspDeInitCallback = DAL_TMR_OC_MspDeInit; + break; + + case DAL_TMR_PWM_MSPINIT_CB_ID : + /* Legacy weak PWM Msp Init Callback */ + htmr->PWM_MspInitCallback = DAL_TMR_PWM_MspInit; + break; + + case DAL_TMR_PWM_MSPDEINIT_CB_ID : + /* Legacy weak PWM Msp DeInit Callback */ + htmr->PWM_MspDeInitCallback = DAL_TMR_PWM_MspDeInit; + break; + + case DAL_TMR_ONE_PULSE_MSPINIT_CB_ID : + /* Legacy weak One Pulse Msp Init Callback */ + htmr->OnePulse_MspInitCallback = DAL_TMR_OnePulse_MspInit; + break; + + case DAL_TMR_ONE_PULSE_MSPDEINIT_CB_ID : + /* Legacy weak One Pulse Msp DeInit Callback */ + htmr->OnePulse_MspDeInitCallback = DAL_TMR_OnePulse_MspDeInit; + break; + + case DAL_TMR_ENCODER_MSPINIT_CB_ID : + /* Legacy weak Encoder Msp Init Callback */ + htmr->Encoder_MspInitCallback = DAL_TMR_Encoder_MspInit; + break; + + case DAL_TMR_ENCODER_MSPDEINIT_CB_ID : + /* Legacy weak Encoder Msp DeInit Callback */ + htmr->Encoder_MspDeInitCallback = DAL_TMR_Encoder_MspDeInit; + break; + + case DAL_TMR_HALL_SENSOR_MSPINIT_CB_ID : + /* Legacy weak Hall Sensor Msp Init Callback */ + htmr->HallSensor_MspInitCallback = DAL_TMREx_HallSensor_MspInit; + break; + + case DAL_TMR_HALL_SENSOR_MSPDEINIT_CB_ID : + /* Legacy weak Hall Sensor Msp DeInit Callback */ + htmr->HallSensor_MspDeInitCallback = DAL_TMREx_HallSensor_MspDeInit; + break; + + case DAL_TMR_PERIOD_ELAPSED_CB_ID : + /* Legacy weak Period Elapsed Callback */ + htmr->PeriodElapsedCallback = DAL_TMR_PeriodElapsedCallback; + break; + + case DAL_TMR_PERIOD_ELAPSED_HALF_CB_ID : + /* Legacy weak Period Elapsed half complete Callback */ + htmr->PeriodElapsedHalfCpltCallback = DAL_TMR_PeriodElapsedHalfCpltCallback; + break; + + case DAL_TMR_TRIGGER_CB_ID : + /* Legacy weak Trigger Callback */ + htmr->TriggerCallback = DAL_TMR_TriggerCallback; + break; + + case DAL_TMR_TRIGGER_HALF_CB_ID : + /* Legacy weak Trigger half complete Callback */ + htmr->TriggerHalfCpltCallback = DAL_TMR_TriggerHalfCpltCallback; + break; + + case DAL_TMR_IC_CAPTURE_CB_ID : + /* Legacy weak IC Capture Callback */ + htmr->IC_CaptureCallback = DAL_TMR_IC_CaptureCallback; + break; + + case DAL_TMR_IC_CAPTURE_HALF_CB_ID : + /* Legacy weak IC Capture half complete Callback */ + htmr->IC_CaptureHalfCpltCallback = DAL_TMR_IC_CaptureHalfCpltCallback; + break; + + case DAL_TMR_OC_DELAY_ELAPSED_CB_ID : + /* Legacy weak OC Delay Elapsed Callback */ + htmr->OC_DelayElapsedCallback = DAL_TMR_OC_DelayElapsedCallback; + break; + + case DAL_TMR_PWM_PULSE_FINISHED_CB_ID : + /* Legacy weak PWM Pulse Finished Callback */ + htmr->PWM_PulseFinishedCallback = DAL_TMR_PWM_PulseFinishedCallback; + break; + + case DAL_TMR_PWM_PULSE_FINISHED_HALF_CB_ID : + /* Legacy weak PWM Pulse Finished half complete Callback */ + htmr->PWM_PulseFinishedHalfCpltCallback = DAL_TMR_PWM_PulseFinishedHalfCpltCallback; + break; + + case DAL_TMR_ERROR_CB_ID : + /* Legacy weak Error Callback */ + htmr->ErrorCallback = DAL_TMR_ErrorCallback; + break; + + case DAL_TMR_COMMUTATION_CB_ID : + /* Legacy weak Commutation Callback */ + htmr->CommutationCallback = DAL_TMREx_CommutCallback; + break; + + case DAL_TMR_COMMUTATION_HALF_CB_ID : + /* Legacy weak Commutation half complete Callback */ + htmr->CommutationHalfCpltCallback = DAL_TMREx_CommutHalfCpltCallback; + break; + + case DAL_TMR_BREAK_CB_ID : + /* Legacy weak Break Callback */ + htmr->BreakCallback = DAL_TMREx_BreakCallback; + break; + + default : + /* Return error status */ + status = DAL_ERROR; + break; + } + } + else if (htmr->State == DAL_TMR_STATE_RESET) + { + switch (CallbackID) + { + case DAL_TMR_BASE_MSPINIT_CB_ID : + /* Legacy weak Base MspInit Callback */ + htmr->Base_MspInitCallback = DAL_TMR_Base_MspInit; + break; + + case DAL_TMR_BASE_MSPDEINIT_CB_ID : + /* Legacy weak Base Msp DeInit Callback */ + htmr->Base_MspDeInitCallback = DAL_TMR_Base_MspDeInit; + break; + + case DAL_TMR_IC_MSPINIT_CB_ID : + /* Legacy weak IC Msp Init Callback */ + htmr->IC_MspInitCallback = DAL_TMR_IC_MspInit; + break; + + case DAL_TMR_IC_MSPDEINIT_CB_ID : + /* Legacy weak IC Msp DeInit Callback */ + htmr->IC_MspDeInitCallback = DAL_TMR_IC_MspDeInit; + break; + + case DAL_TMR_OC_MSPINIT_CB_ID : + /* Legacy weak OC Msp Init Callback */ + htmr->OC_MspInitCallback = DAL_TMR_OC_MspInit; + break; + + case DAL_TMR_OC_MSPDEINIT_CB_ID : + /* Legacy weak OC Msp DeInit Callback */ + htmr->OC_MspDeInitCallback = DAL_TMR_OC_MspDeInit; + break; + + case DAL_TMR_PWM_MSPINIT_CB_ID : + /* Legacy weak PWM Msp Init Callback */ + htmr->PWM_MspInitCallback = DAL_TMR_PWM_MspInit; + break; + + case DAL_TMR_PWM_MSPDEINIT_CB_ID : + /* Legacy weak PWM Msp DeInit Callback */ + htmr->PWM_MspDeInitCallback = DAL_TMR_PWM_MspDeInit; + break; + + case DAL_TMR_ONE_PULSE_MSPINIT_CB_ID : + /* Legacy weak One Pulse Msp Init Callback */ + htmr->OnePulse_MspInitCallback = DAL_TMR_OnePulse_MspInit; + break; + + case DAL_TMR_ONE_PULSE_MSPDEINIT_CB_ID : + /* Legacy weak One Pulse Msp DeInit Callback */ + htmr->OnePulse_MspDeInitCallback = DAL_TMR_OnePulse_MspDeInit; + break; + + case DAL_TMR_ENCODER_MSPINIT_CB_ID : + /* Legacy weak Encoder Msp Init Callback */ + htmr->Encoder_MspInitCallback = DAL_TMR_Encoder_MspInit; + break; + + case DAL_TMR_ENCODER_MSPDEINIT_CB_ID : + /* Legacy weak Encoder Msp DeInit Callback */ + htmr->Encoder_MspDeInitCallback = DAL_TMR_Encoder_MspDeInit; + break; + + case DAL_TMR_HALL_SENSOR_MSPINIT_CB_ID : + /* Legacy weak Hall Sensor Msp Init Callback */ + htmr->HallSensor_MspInitCallback = DAL_TMREx_HallSensor_MspInit; + break; + + case DAL_TMR_HALL_SENSOR_MSPDEINIT_CB_ID : + /* Legacy weak Hall Sensor Msp DeInit Callback */ + htmr->HallSensor_MspDeInitCallback = DAL_TMREx_HallSensor_MspDeInit; + break; + + default : + /* Return error status */ + status = DAL_ERROR; + break; + } + } + else + { + /* Return error status */ + status = DAL_ERROR; + } + + /* Release Lock */ + __DAL_UNLOCK(htmr); + + return status; +} +#endif /* USE_DAL_TMR_REGISTER_CALLBACKS */ + +/** + * @} + */ + +/** @defgroup TMR_Exported_Functions_Group10 TMR Peripheral State functions + * @brief TMR Peripheral State functions + * +@verbatim + ============================================================================== + ##### Peripheral State functions ##### + ============================================================================== + [..] + This subsection permits to get in run-time the status of the peripheral + and the data flow. + +@endverbatim + * @{ + */ + +/** + * @brief Return the TMR Base handle state. + * @param htmr TMR Base handle + * @retval DAL state + */ +DAL_TMR_StateTypeDef DAL_TMR_Base_GetState(TMR_HandleTypeDef *htmr) +{ + return htmr->State; +} + +/** + * @brief Return the TMR OC handle state. + * @param htmr TMR Output Compare handle + * @retval DAL state + */ +DAL_TMR_StateTypeDef DAL_TMR_OC_GetState(TMR_HandleTypeDef *htmr) +{ + return htmr->State; +} + +/** + * @brief Return the TMR PWM handle state. + * @param htmr TMR handle + * @retval DAL state + */ +DAL_TMR_StateTypeDef DAL_TMR_PWM_GetState(TMR_HandleTypeDef *htmr) +{ + return htmr->State; +} + +/** + * @brief Return the TMR Input Capture handle state. + * @param htmr TMR IC handle + * @retval DAL state + */ +DAL_TMR_StateTypeDef DAL_TMR_IC_GetState(TMR_HandleTypeDef *htmr) +{ + return htmr->State; +} + +/** + * @brief Return the TMR One Pulse Mode handle state. + * @param htmr TMR OPM handle + * @retval DAL state + */ +DAL_TMR_StateTypeDef DAL_TMR_OnePulse_GetState(TMR_HandleTypeDef *htmr) +{ + return htmr->State; +} + +/** + * @brief Return the TMR Encoder Mode handle state. + * @param htmr TMR Encoder Interface handle + * @retval DAL state + */ +DAL_TMR_StateTypeDef DAL_TMR_Encoder_GetState(TMR_HandleTypeDef *htmr) +{ + return htmr->State; +} + +/** + * @brief Return the TMR Encoder Mode handle state. + * @param htmr TMR handle + * @retval Active channel + */ +DAL_TMR_ActiveChannel DAL_TMR_GetActiveChannel(TMR_HandleTypeDef *htmr) +{ + return htmr->Channel; +} + +/** + * @brief Return actual state of the TMR channel. + * @param htmr TMR handle + * @param Channel TMR Channel + * This parameter can be one of the following values: + * @arg TMR_CHANNEL_1: TMR Channel 1 + * @arg TMR_CHANNEL_2: TMR Channel 2 + * @arg TMR_CHANNEL_3: TMR Channel 3 + * @arg TMR_CHANNEL_4: TMR Channel 4 + * @arg TMR_CHANNEL_5: TMR Channel 5 + * @arg TMR_CHANNEL_6: TMR Channel 6 + * @retval TMR Channel state + */ +DAL_TMR_ChannelStateTypeDef DAL_TMR_GetChannelState(TMR_HandleTypeDef *htmr, uint32_t Channel) +{ + DAL_TMR_ChannelStateTypeDef channel_state; + + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_CCX_INSTANCE(htmr->Instance, Channel)); + + channel_state = TMR_CHANNEL_STATE_GET(htmr, Channel); + + return channel_state; +} + +/** + * @brief Return actual state of a DMA burst operation. + * @param htmr TMR handle + * @retval DMA burst state + */ +DAL_TMR_DMABurstStateTypeDef DAL_TMR_DMABurstState(TMR_HandleTypeDef *htmr) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_DMABURST_INSTANCE(htmr->Instance)); + + return htmr->DMABurstState; +} + +/** + * @} + */ + +/** + * @} + */ + +/** @defgroup TMR_Private_Functions TMR Private Functions + * @{ + */ + +/** + * @brief TMR DMA error callback + * @param hdma pointer to DMA handle. + * @retval None + */ +void TMR_DMAError(DMA_HandleTypeDef *hdma) +{ + TMR_HandleTypeDef *htmr = (TMR_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + + if (hdma == htmr->hdma[TMR_DMA_ID_CC1]) + { + htmr->Channel = DAL_TMR_ACTIVE_CHANNEL_1; + TMR_CHANNEL_STATE_SET(htmr, TMR_CHANNEL_1, DAL_TMR_CHANNEL_STATE_READY); + } + else if (hdma == htmr->hdma[TMR_DMA_ID_CC2]) + { + htmr->Channel = DAL_TMR_ACTIVE_CHANNEL_2; + TMR_CHANNEL_STATE_SET(htmr, TMR_CHANNEL_2, DAL_TMR_CHANNEL_STATE_READY); + } + else if (hdma == htmr->hdma[TMR_DMA_ID_CC3]) + { + htmr->Channel = DAL_TMR_ACTIVE_CHANNEL_3; + TMR_CHANNEL_STATE_SET(htmr, TMR_CHANNEL_3, DAL_TMR_CHANNEL_STATE_READY); + } + else if (hdma == htmr->hdma[TMR_DMA_ID_CC4]) + { + htmr->Channel = DAL_TMR_ACTIVE_CHANNEL_4; + TMR_CHANNEL_STATE_SET(htmr, TMR_CHANNEL_4, DAL_TMR_CHANNEL_STATE_READY); + } + else + { + htmr->State = DAL_TMR_STATE_READY; + } + +#if (USE_DAL_TMR_REGISTER_CALLBACKS == 1) + htmr->ErrorCallback(htmr); +#else + DAL_TMR_ErrorCallback(htmr); +#endif /* USE_DAL_TMR_REGISTER_CALLBACKS */ + + htmr->Channel = DAL_TMR_ACTIVE_CHANNEL_CLEARED; +} + +/** + * @brief TMR DMA Delay Pulse complete callback. + * @param hdma pointer to DMA handle. + * @retval None + */ +void TMR_DMADelayPulseCplt(DMA_HandleTypeDef *hdma) +{ + TMR_HandleTypeDef *htmr = (TMR_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + + if (hdma == htmr->hdma[TMR_DMA_ID_CC1]) + { + htmr->Channel = DAL_TMR_ACTIVE_CHANNEL_1; + + if (hdma->Init.Mode == DMA_NORMAL) + { + TMR_CHANNEL_STATE_SET(htmr, TMR_CHANNEL_1, DAL_TMR_CHANNEL_STATE_READY); + } + } + else if (hdma == htmr->hdma[TMR_DMA_ID_CC2]) + { + htmr->Channel = DAL_TMR_ACTIVE_CHANNEL_2; + + if (hdma->Init.Mode == DMA_NORMAL) + { + TMR_CHANNEL_STATE_SET(htmr, TMR_CHANNEL_2, DAL_TMR_CHANNEL_STATE_READY); + } + } + else if (hdma == htmr->hdma[TMR_DMA_ID_CC3]) + { + htmr->Channel = DAL_TMR_ACTIVE_CHANNEL_3; + + if (hdma->Init.Mode == DMA_NORMAL) + { + TMR_CHANNEL_STATE_SET(htmr, TMR_CHANNEL_3, DAL_TMR_CHANNEL_STATE_READY); + } + } + else if (hdma == htmr->hdma[TMR_DMA_ID_CC4]) + { + htmr->Channel = DAL_TMR_ACTIVE_CHANNEL_4; + + if (hdma->Init.Mode == DMA_NORMAL) + { + TMR_CHANNEL_STATE_SET(htmr, TMR_CHANNEL_4, DAL_TMR_CHANNEL_STATE_READY); + } + } + else + { + /* nothing to do */ + } + +#if (USE_DAL_TMR_REGISTER_CALLBACKS == 1) + htmr->PWM_PulseFinishedCallback(htmr); +#else + DAL_TMR_PWM_PulseFinishedCallback(htmr); +#endif /* USE_DAL_TMR_REGISTER_CALLBACKS */ + + htmr->Channel = DAL_TMR_ACTIVE_CHANNEL_CLEARED; +} + +/** + * @brief TMR DMA Delay Pulse half complete callback. + * @param hdma pointer to DMA handle. + * @retval None + */ +void TMR_DMADelayPulseHalfCplt(DMA_HandleTypeDef *hdma) +{ + TMR_HandleTypeDef *htmr = (TMR_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + + if (hdma == htmr->hdma[TMR_DMA_ID_CC1]) + { + htmr->Channel = DAL_TMR_ACTIVE_CHANNEL_1; + } + else if (hdma == htmr->hdma[TMR_DMA_ID_CC2]) + { + htmr->Channel = DAL_TMR_ACTIVE_CHANNEL_2; + } + else if (hdma == htmr->hdma[TMR_DMA_ID_CC3]) + { + htmr->Channel = DAL_TMR_ACTIVE_CHANNEL_3; + } + else if (hdma == htmr->hdma[TMR_DMA_ID_CC4]) + { + htmr->Channel = DAL_TMR_ACTIVE_CHANNEL_4; + } + else + { + /* nothing to do */ + } + +#if (USE_DAL_TMR_REGISTER_CALLBACKS == 1) + htmr->PWM_PulseFinishedHalfCpltCallback(htmr); +#else + DAL_TMR_PWM_PulseFinishedHalfCpltCallback(htmr); +#endif /* USE_DAL_TMR_REGISTER_CALLBACKS */ + + htmr->Channel = DAL_TMR_ACTIVE_CHANNEL_CLEARED; +} + +/** + * @brief TMR DMA Capture complete callback. + * @param hdma pointer to DMA handle. + * @retval None + */ +void TMR_DMACaptureCplt(DMA_HandleTypeDef *hdma) +{ + TMR_HandleTypeDef *htmr = (TMR_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + + if (hdma == htmr->hdma[TMR_DMA_ID_CC1]) + { + htmr->Channel = DAL_TMR_ACTIVE_CHANNEL_1; + + if (hdma->Init.Mode == DMA_NORMAL) + { + TMR_CHANNEL_STATE_SET(htmr, TMR_CHANNEL_1, DAL_TMR_CHANNEL_STATE_READY); + TMR_CHANNEL_N_STATE_SET(htmr, TMR_CHANNEL_1, DAL_TMR_CHANNEL_STATE_READY); + } + } + else if (hdma == htmr->hdma[TMR_DMA_ID_CC2]) + { + htmr->Channel = DAL_TMR_ACTIVE_CHANNEL_2; + + if (hdma->Init.Mode == DMA_NORMAL) + { + TMR_CHANNEL_STATE_SET(htmr, TMR_CHANNEL_2, DAL_TMR_CHANNEL_STATE_READY); + TMR_CHANNEL_N_STATE_SET(htmr, TMR_CHANNEL_2, DAL_TMR_CHANNEL_STATE_READY); + } + } + else if (hdma == htmr->hdma[TMR_DMA_ID_CC3]) + { + htmr->Channel = DAL_TMR_ACTIVE_CHANNEL_3; + + if (hdma->Init.Mode == DMA_NORMAL) + { + TMR_CHANNEL_STATE_SET(htmr, TMR_CHANNEL_3, DAL_TMR_CHANNEL_STATE_READY); + TMR_CHANNEL_N_STATE_SET(htmr, TMR_CHANNEL_3, DAL_TMR_CHANNEL_STATE_READY); + } + } + else if (hdma == htmr->hdma[TMR_DMA_ID_CC4]) + { + htmr->Channel = DAL_TMR_ACTIVE_CHANNEL_4; + + if (hdma->Init.Mode == DMA_NORMAL) + { + TMR_CHANNEL_STATE_SET(htmr, TMR_CHANNEL_4, DAL_TMR_CHANNEL_STATE_READY); + TMR_CHANNEL_N_STATE_SET(htmr, TMR_CHANNEL_4, DAL_TMR_CHANNEL_STATE_READY); + } + } + else + { + /* nothing to do */ + } + +#if (USE_DAL_TMR_REGISTER_CALLBACKS == 1) + htmr->IC_CaptureCallback(htmr); +#else + DAL_TMR_IC_CaptureCallback(htmr); +#endif /* USE_DAL_TMR_REGISTER_CALLBACKS */ + + htmr->Channel = DAL_TMR_ACTIVE_CHANNEL_CLEARED; +} + +/** + * @brief TMR DMA Capture half complete callback. + * @param hdma pointer to DMA handle. + * @retval None + */ +void TMR_DMACaptureHalfCplt(DMA_HandleTypeDef *hdma) +{ + TMR_HandleTypeDef *htmr = (TMR_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + + if (hdma == htmr->hdma[TMR_DMA_ID_CC1]) + { + htmr->Channel = DAL_TMR_ACTIVE_CHANNEL_1; + } + else if (hdma == htmr->hdma[TMR_DMA_ID_CC2]) + { + htmr->Channel = DAL_TMR_ACTIVE_CHANNEL_2; + } + else if (hdma == htmr->hdma[TMR_DMA_ID_CC3]) + { + htmr->Channel = DAL_TMR_ACTIVE_CHANNEL_3; + } + else if (hdma == htmr->hdma[TMR_DMA_ID_CC4]) + { + htmr->Channel = DAL_TMR_ACTIVE_CHANNEL_4; + } + else + { + /* nothing to do */ + } + +#if (USE_DAL_TMR_REGISTER_CALLBACKS == 1) + htmr->IC_CaptureHalfCpltCallback(htmr); +#else + DAL_TMR_IC_CaptureHalfCpltCallback(htmr); +#endif /* USE_DAL_TMR_REGISTER_CALLBACKS */ + + htmr->Channel = DAL_TMR_ACTIVE_CHANNEL_CLEARED; +} + +/** + * @brief TMR DMA Period Elapse complete callback. + * @param hdma pointer to DMA handle. + * @retval None + */ +static void TMR_DMAPeriodElapsedCplt(DMA_HandleTypeDef *hdma) +{ + TMR_HandleTypeDef *htmr = (TMR_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + + if (htmr->hdma[TMR_DMA_ID_UPDATE]->Init.Mode == DMA_NORMAL) + { + htmr->State = DAL_TMR_STATE_READY; + } + +#if (USE_DAL_TMR_REGISTER_CALLBACKS == 1) + htmr->PeriodElapsedCallback(htmr); +#else + DAL_TMR_PeriodElapsedCallback(htmr); +#endif /* USE_DAL_TMR_REGISTER_CALLBACKS */ +} + +/** + * @brief TMR DMA Period Elapse half complete callback. + * @param hdma pointer to DMA handle. + * @retval None + */ +static void TMR_DMAPeriodElapsedHalfCplt(DMA_HandleTypeDef *hdma) +{ + TMR_HandleTypeDef *htmr = (TMR_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + +#if (USE_DAL_TMR_REGISTER_CALLBACKS == 1) + htmr->PeriodElapsedHalfCpltCallback(htmr); +#else + DAL_TMR_PeriodElapsedHalfCpltCallback(htmr); +#endif /* USE_DAL_TMR_REGISTER_CALLBACKS */ +} + +/** + * @brief TMR DMA Trigger callback. + * @param hdma pointer to DMA handle. + * @retval None + */ +static void TMR_DMATriggerCplt(DMA_HandleTypeDef *hdma) +{ + TMR_HandleTypeDef *htmr = (TMR_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + + if (htmr->hdma[TMR_DMA_ID_TRIGGER]->Init.Mode == DMA_NORMAL) + { + htmr->State = DAL_TMR_STATE_READY; + } + +#if (USE_DAL_TMR_REGISTER_CALLBACKS == 1) + htmr->TriggerCallback(htmr); +#else + DAL_TMR_TriggerCallback(htmr); +#endif /* USE_DAL_TMR_REGISTER_CALLBACKS */ +} + +/** + * @brief TMR DMA Trigger half complete callback. + * @param hdma pointer to DMA handle. + * @retval None + */ +static void TMR_DMATriggerHalfCplt(DMA_HandleTypeDef *hdma) +{ + TMR_HandleTypeDef *htmr = (TMR_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + +#if (USE_DAL_TMR_REGISTER_CALLBACKS == 1) + htmr->TriggerHalfCpltCallback(htmr); +#else + DAL_TMR_TriggerHalfCpltCallback(htmr); +#endif /* USE_DAL_TMR_REGISTER_CALLBACKS */ +} + +/** + * @brief Time Base configuration + * @param TMRx TMR peripheral + * @param Structure TMR Base configuration structure + * @retval None + */ +void TMR_Base_SetConfig(TMR_TypeDef *TMRx, TMR_Base_InitTypeDef *Structure) +{ + uint32_t tmpcr1; + tmpcr1 = TMRx->CTRL1; + + /* Set TMR Time Base Unit parameters ---------------------------------------*/ + if (IS_TMR_COUNTER_MODE_SELECT_INSTANCE(TMRx)) + { + /* Select the Counter Mode */ + tmpcr1 &= ~(TMR_CTRL1_CNTDIR | TMR_CTRL1_CAMSEL); + tmpcr1 |= Structure->CounterMode; + } + + if (IS_TMR_CLOCK_DIVISION_INSTANCE(TMRx)) + { + /* Set the clock division */ + tmpcr1 &= ~TMR_CTRL1_CLKDIV; + tmpcr1 |= (uint32_t)Structure->ClockDivision; + } + + /* Set the auto-reload preload */ + MODIFY_REG(tmpcr1, TMR_CTRL1_ARPEN, Structure->AutoReloadPreload); + + TMRx->CTRL1 = tmpcr1; + + /* Set the Autoreload value */ + TMRx->AUTORLD = (uint32_t)Structure->Period ; + + /* Set the Prescaler value */ + TMRx->PSC = Structure->Prescaler; + + if (IS_TMR_REPETITION_COUNTER_INSTANCE(TMRx)) + { + /* Set the Repetition Counter value */ + TMRx->REPCNT = Structure->RepetitionCounter; + } + + /* Generate an update event to reload the Prescaler + and the repetition counter (only for advanced timer) value immediately */ + TMRx->CEG = TMR_CEG_UEG; +} + +/** + * @brief Timer Output Compare 1 configuration + * @param TMRx to select the TMR peripheral + * @param OC_Config The output configuration structure + * @retval None + */ +static void TMR_OC1_SetConfig(TMR_TypeDef *TMRx, TMR_OC_InitTypeDef *OC_Config) +{ + uint32_t tmpccmrx; + uint32_t tmpccer; + uint32_t tmpcr2; + + /* Disable the Channel 1: Reset the CC1EN Bit */ + TMRx->CCEN &= ~TMR_CCEN_CC1EN; + + /* Get the TMRx CCEN register value */ + tmpccer = TMRx->CCEN; + /* Get the TMRx CTRL2 register value */ + tmpcr2 = TMRx->CTRL2; + + /* Get the TMRx CCM1 register value */ + tmpccmrx = TMRx->CCM1; + + /* Reset the Output Compare Mode Bits */ + tmpccmrx &= ~TMR_CCM1_OC1MOD; + tmpccmrx &= ~TMR_CCM1_CC1SEL; + /* Select the Output Compare Mode */ + tmpccmrx |= OC_Config->OCMode; + + /* Reset the Output Polarity level */ + tmpccer &= ~TMR_CCEN_CC1POL; + /* Set the Output Compare Polarity */ + tmpccer |= OC_Config->OCPolarity; + + if (IS_TMR_CCXN_INSTANCE(TMRx, TMR_CHANNEL_1)) + { + /* Check parameters */ + ASSERT_PARAM(IS_TMR_OCN_POLARITY(OC_Config->OCNPolarity)); + + /* Reset the Output N Polarity level */ + tmpccer &= ~TMR_CCEN_CC1NPOL; + /* Set the Output N Polarity */ + tmpccer |= OC_Config->OCNPolarity; + /* Reset the Output N State */ + tmpccer &= ~TMR_CCEN_CC1NEN; + } + + if (IS_TMR_BREAK_INSTANCE(TMRx)) + { + /* Check parameters */ + ASSERT_PARAM(IS_TMR_OCNIDLE_STATE(OC_Config->OCNIdleState)); + ASSERT_PARAM(IS_TMR_OCIDLE_STATE(OC_Config->OCIdleState)); + + /* Reset the Output Compare and Output Compare N IDLE State */ + tmpcr2 &= ~TMR_CTRL2_OC1OIS; + tmpcr2 &= ~TMR_CTRL2_OC1NOIS; + /* Set the Output Idle state */ + tmpcr2 |= OC_Config->OCIdleState; + /* Set the Output N Idle state */ + tmpcr2 |= OC_Config->OCNIdleState; + } + + /* Write to TMRx CTRL2 */ + TMRx->CTRL2 = tmpcr2; + + /* Write to TMRx CCM1 */ + TMRx->CCM1 = tmpccmrx; + + /* Set the Capture Compare Register value */ + TMRx->CC1 = OC_Config->Pulse; + + /* Write to TMRx CCEN */ + TMRx->CCEN = tmpccer; +} + +/** + * @brief Timer Output Compare 2 configuration + * @param TMRx to select the TMR peripheral + * @param OC_Config The output configuration structure + * @retval None + */ +void TMR_OC2_SetConfig(TMR_TypeDef *TMRx, TMR_OC_InitTypeDef *OC_Config) +{ + uint32_t tmpccmrx; + uint32_t tmpccer; + uint32_t tmpcr2; + + /* Disable the Channel 2: Reset the CC2EN Bit */ + TMRx->CCEN &= ~TMR_CCEN_CC2EN; + + /* Get the TMRx CCEN register value */ + tmpccer = TMRx->CCEN; + /* Get the TMRx CTRL2 register value */ + tmpcr2 = TMRx->CTRL2; + + /* Get the TMRx CCM1 register value */ + tmpccmrx = TMRx->CCM1; + + /* Reset the Output Compare mode and Capture/Compare selection Bits */ + tmpccmrx &= ~TMR_CCM1_OC2MOD; + tmpccmrx &= ~TMR_CCM1_CC2SEL; + + /* Select the Output Compare Mode */ + tmpccmrx |= (OC_Config->OCMode << 8U); + + /* Reset the Output Polarity level */ + tmpccer &= ~TMR_CCEN_CC2POL; + /* Set the Output Compare Polarity */ + tmpccer |= (OC_Config->OCPolarity << 4U); + + if (IS_TMR_CCXN_INSTANCE(TMRx, TMR_CHANNEL_2)) + { + ASSERT_PARAM(IS_TMR_OCN_POLARITY(OC_Config->OCNPolarity)); + + /* Reset the Output N Polarity level */ + tmpccer &= ~TMR_CCEN_CC2NPOL; + /* Set the Output N Polarity */ + tmpccer |= (OC_Config->OCNPolarity << 4U); + /* Reset the Output N State */ + tmpccer &= ~TMR_CCEN_CC2NEN; + + } + + if (IS_TMR_BREAK_INSTANCE(TMRx)) + { + /* Check parameters */ + ASSERT_PARAM(IS_TMR_OCNIDLE_STATE(OC_Config->OCNIdleState)); + ASSERT_PARAM(IS_TMR_OCIDLE_STATE(OC_Config->OCIdleState)); + + /* Reset the Output Compare and Output Compare N IDLE State */ + tmpcr2 &= ~TMR_CTRL2_OC2OIS; + tmpcr2 &= ~TMR_CTRL2_OC2NOIS; + /* Set the Output Idle state */ + tmpcr2 |= (OC_Config->OCIdleState << 2U); + /* Set the Output N Idle state */ + tmpcr2 |= (OC_Config->OCNIdleState << 2U); + } + + /* Write to TMRx CTRL2 */ + TMRx->CTRL2 = tmpcr2; + + /* Write to TMRx CCM1 */ + TMRx->CCM1 = tmpccmrx; + + /* Set the Capture Compare Register value */ + TMRx->CC2 = OC_Config->Pulse; + + /* Write to TMRx CCEN */ + TMRx->CCEN = tmpccer; +} + +/** + * @brief Timer Output Compare 3 configuration + * @param TMRx to select the TMR peripheral + * @param OC_Config The output configuration structure + * @retval None + */ +static void TMR_OC3_SetConfig(TMR_TypeDef *TMRx, TMR_OC_InitTypeDef *OC_Config) +{ + uint32_t tmpccmrx; + uint32_t tmpccer; + uint32_t tmpcr2; + + /* Disable the Channel 3: Reset the CC3EN Bit */ + TMRx->CCEN &= ~TMR_CCEN_CC3EN; + + /* Get the TMRx CCEN register value */ + tmpccer = TMRx->CCEN; + /* Get the TMRx CTRL2 register value */ + tmpcr2 = TMRx->CTRL2; + + /* Get the TMRx CCM2 register value */ + tmpccmrx = TMRx->CCM2; + + /* Reset the Output Compare mode and Capture/Compare selection Bits */ + tmpccmrx &= ~TMR_CCM2_OC3MOD; + tmpccmrx &= ~TMR_CCM2_CC3SEL; + /* Select the Output Compare Mode */ + tmpccmrx |= OC_Config->OCMode; + + /* Reset the Output Polarity level */ + tmpccer &= ~TMR_CCEN_CC3POL; + /* Set the Output Compare Polarity */ + tmpccer |= (OC_Config->OCPolarity << 8U); + + if (IS_TMR_CCXN_INSTANCE(TMRx, TMR_CHANNEL_3)) + { + ASSERT_PARAM(IS_TMR_OCN_POLARITY(OC_Config->OCNPolarity)); + + /* Reset the Output N Polarity level */ + tmpccer &= ~TMR_CCEN_CC3NPOL; + /* Set the Output N Polarity */ + tmpccer |= (OC_Config->OCNPolarity << 8U); + /* Reset the Output N State */ + tmpccer &= ~TMR_CCEN_CC3NEN; + } + + if (IS_TMR_BREAK_INSTANCE(TMRx)) + { + /* Check parameters */ + ASSERT_PARAM(IS_TMR_OCNIDLE_STATE(OC_Config->OCNIdleState)); + ASSERT_PARAM(IS_TMR_OCIDLE_STATE(OC_Config->OCIdleState)); + + /* Reset the Output Compare and Output Compare N IDLE State */ + tmpcr2 &= ~TMR_CTRL2_OC3OIS; + tmpcr2 &= ~TMR_CTRL2_OC3NOIS; + /* Set the Output Idle state */ + tmpcr2 |= (OC_Config->OCIdleState << 4U); + /* Set the Output N Idle state */ + tmpcr2 |= (OC_Config->OCNIdleState << 4U); + } + + /* Write to TMRx CTRL2 */ + TMRx->CTRL2 = tmpcr2; + + /* Write to TMRx CCM2 */ + TMRx->CCM2 = tmpccmrx; + + /* Set the Capture Compare Register value */ + TMRx->CC3 = OC_Config->Pulse; + + /* Write to TMRx CCEN */ + TMRx->CCEN = tmpccer; +} + +/** + * @brief Timer Output Compare 4 configuration + * @param TMRx to select the TMR peripheral + * @param OC_Config The output configuration structure + * @retval None + */ +static void TMR_OC4_SetConfig(TMR_TypeDef *TMRx, TMR_OC_InitTypeDef *OC_Config) +{ + uint32_t tmpccmrx; + uint32_t tmpccer; + uint32_t tmpcr2; + + /* Disable the Channel 4: Reset the CC4EN Bit */ + TMRx->CCEN &= ~TMR_CCEN_CC4EN; + + /* Get the TMRx CCEN register value */ + tmpccer = TMRx->CCEN; + /* Get the TMRx CTRL2 register value */ + tmpcr2 = TMRx->CTRL2; + + /* Get the TMRx CCM2 register value */ + tmpccmrx = TMRx->CCM2; + + /* Reset the Output Compare mode and Capture/Compare selection Bits */ + tmpccmrx &= ~TMR_CCM2_OC4MOD; + tmpccmrx &= ~TMR_CCM2_CC4SEL; + + /* Select the Output Compare Mode */ + tmpccmrx |= (OC_Config->OCMode << 8U); + + /* Reset the Output Polarity level */ + tmpccer &= ~TMR_CCEN_CC4POL; + /* Set the Output Compare Polarity */ + tmpccer |= (OC_Config->OCPolarity << 12U); + + if (IS_TMR_BREAK_INSTANCE(TMRx)) + { + /* Check parameters */ + ASSERT_PARAM(IS_TMR_OCIDLE_STATE(OC_Config->OCIdleState)); + + /* Reset the Output Compare IDLE State */ + tmpcr2 &= ~TMR_CTRL2_OC4OIS; + + /* Set the Output Idle state */ + tmpcr2 |= (OC_Config->OCIdleState << 6U); + } + + /* Write to TMRx CTRL2 */ + TMRx->CTRL2 = tmpcr2; + + /* Write to TMRx CCM2 */ + TMRx->CCM2 = tmpccmrx; + + /* Set the Capture Compare Register value */ + TMRx->CC4 = OC_Config->Pulse; + + /* Write to TMRx CCEN */ + TMRx->CCEN = tmpccer; +} + +/** + * @brief Slave Timer configuration function + * @param htmr TMR handle + * @param sSlaveConfig Slave timer configuration + * @retval None + */ +static DAL_StatusTypeDef TMR_SlaveTimer_SetConfig(TMR_HandleTypeDef *htmr, + TMR_SlaveConfigTypeDef *sSlaveConfig) +{ + DAL_StatusTypeDef status = DAL_OK; + uint32_t tmpsmcr; + uint32_t tmpccmr1; + uint32_t tmpccer; + + /* Get the TMRx SMCTRL register value */ + tmpsmcr = htmr->Instance->SMCTRL; + + /* Reset the Trigger Selection Bits */ + tmpsmcr &= ~TMR_SMCTRL_TRGSEL; + /* Set the Input Trigger source */ + tmpsmcr |= sSlaveConfig->InputTrigger; + + /* Reset the slave mode Bits */ + tmpsmcr &= ~TMR_SMCTRL_SMFSEL; + /* Set the slave mode */ + tmpsmcr |= sSlaveConfig->SlaveMode; + + /* Write to TMRx SMCTRL */ + htmr->Instance->SMCTRL = tmpsmcr; + + /* Configure the trigger prescaler, filter, and polarity */ + switch (sSlaveConfig->InputTrigger) + { + case TMR_TS_ETRF: + { + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_CLOCKSOURCE_ETRMODE1_INSTANCE(htmr->Instance)); + ASSERT_PARAM(IS_TMR_TRIGGERPRESCALER(sSlaveConfig->TriggerPrescaler)); + ASSERT_PARAM(IS_TMR_TRIGGERPOLARITY(sSlaveConfig->TriggerPolarity)); + ASSERT_PARAM(IS_TMR_TRIGGERFILTER(sSlaveConfig->TriggerFilter)); + /* Configure the ETR Trigger source */ + TMR_ETR_SetConfig(htmr->Instance, + sSlaveConfig->TriggerPrescaler, + sSlaveConfig->TriggerPolarity, + sSlaveConfig->TriggerFilter); + break; + } + + case TMR_TS_TI1F_ED: + { + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_CC1_INSTANCE(htmr->Instance)); + ASSERT_PARAM(IS_TMR_TRIGGERFILTER(sSlaveConfig->TriggerFilter)); + + if (sSlaveConfig->SlaveMode == TMR_SLAVEMODE_GATED) + { + return DAL_ERROR; + } + + /* Disable the Channel 1: Reset the CC1EN Bit */ + tmpccer = htmr->Instance->CCEN; + htmr->Instance->CCEN &= ~TMR_CCEN_CC1EN; + tmpccmr1 = htmr->Instance->CCM1; + + /* Set the filter */ + tmpccmr1 &= ~TMR_CCM1_IC1F; + tmpccmr1 |= ((sSlaveConfig->TriggerFilter) << 4U); + + /* Write to TMRx CCM1 and CCEN registers */ + htmr->Instance->CCM1 = tmpccmr1; + htmr->Instance->CCEN = tmpccer; + break; + } + + case TMR_TS_TI1FP1: + { + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_CC1_INSTANCE(htmr->Instance)); + ASSERT_PARAM(IS_TMR_TRIGGERPOLARITY(sSlaveConfig->TriggerPolarity)); + ASSERT_PARAM(IS_TMR_TRIGGERFILTER(sSlaveConfig->TriggerFilter)); + + /* Configure TI1 Filter and Polarity */ + TMR_TI1_ConfigInputStage(htmr->Instance, + sSlaveConfig->TriggerPolarity, + sSlaveConfig->TriggerFilter); + break; + } + + case TMR_TS_TI2FP2: + { + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_CC2_INSTANCE(htmr->Instance)); + ASSERT_PARAM(IS_TMR_TRIGGERPOLARITY(sSlaveConfig->TriggerPolarity)); + ASSERT_PARAM(IS_TMR_TRIGGERFILTER(sSlaveConfig->TriggerFilter)); + + /* Configure TI2 Filter and Polarity */ + TMR_TI2_ConfigInputStage(htmr->Instance, + sSlaveConfig->TriggerPolarity, + sSlaveConfig->TriggerFilter); + break; + } + + case TMR_TS_ITR0: + case TMR_TS_ITR1: + case TMR_TS_ITR2: + case TMR_TS_ITR3: + { + /* Check the parameter */ + ASSERT_PARAM(IS_TMR_CC2_INSTANCE(htmr->Instance)); + break; + } + + default: + status = DAL_ERROR; + break; + } + + return status; +} + +/** + * @brief Configure the TI1 as Input. + * @param TMRx to select the TMR peripheral. + * @param TMR_ICPolarity The Input Polarity. + * This parameter can be one of the following values: + * @arg TMR_ICPOLARITY_RISING + * @arg TMR_ICPOLARITY_FALLING + * @arg TMR_ICPOLARITY_BOTHEDGE + * @param TMR_ICSelection specifies the input to be used. + * This parameter can be one of the following values: + * @arg TMR_ICSELECTION_DIRECTTI: TMR Input 1 is selected to be connected to IC1. + * @arg TMR_ICSELECTION_INDIRECTTI: TMR Input 1 is selected to be connected to IC2. + * @arg TMR_ICSELECTION_TRC: TMR Input 1 is selected to be connected to TRC. + * @param TMR_ICFilter Specifies the Input Capture Filter. + * This parameter must be a value between 0x00 and 0x0F. + * @retval None + * @note TMR_ICFilter and TMR_ICPolarity are not used in INDIRECT mode as TI2FP1 + * (on channel2 path) is used as the input signal. Therefore CCMR1 must be + * protected against un-initialized filter and polarity values. + */ +void TMR_TI1_SetConfig(TMR_TypeDef *TMRx, uint32_t TMR_ICPolarity, uint32_t TMR_ICSelection, + uint32_t TMR_ICFilter) +{ + uint32_t tmpccmr1; + uint32_t tmpccer; + + /* Disable the Channel 1: Reset the CC1EN Bit */ + TMRx->CCEN &= ~TMR_CCEN_CC1EN; + tmpccmr1 = TMRx->CCM1; + tmpccer = TMRx->CCEN; + + /* Select the Input */ + if (IS_TMR_CC2_INSTANCE(TMRx) != RESET) + { + tmpccmr1 &= ~TMR_CCM1_CC1SEL; + tmpccmr1 |= TMR_ICSelection; + } + else + { + tmpccmr1 |= TMR_CCM1_CC1SEL_0; + } + + /* Set the filter */ + tmpccmr1 &= ~TMR_CCM1_IC1F; + tmpccmr1 |= ((TMR_ICFilter << 4U) & TMR_CCM1_IC1F); + + /* Select the Polarity and set the CC1EN Bit */ + tmpccer &= ~(TMR_CCEN_CC1POL | TMR_CCEN_CC1NPOL); + tmpccer |= (TMR_ICPolarity & (TMR_CCEN_CC1POL | TMR_CCEN_CC1NPOL)); + + /* Write to TMRx CCM1 and CCEN registers */ + TMRx->CCM1 = tmpccmr1; + TMRx->CCEN = tmpccer; +} + +/** + * @brief Configure the Polarity and Filter for TI1. + * @param TMRx to select the TMR peripheral. + * @param TMR_ICPolarity The Input Polarity. + * This parameter can be one of the following values: + * @arg TMR_ICPOLARITY_RISING + * @arg TMR_ICPOLARITY_FALLING + * @arg TMR_ICPOLARITY_BOTHEDGE + * @param TMR_ICFilter Specifies the Input Capture Filter. + * This parameter must be a value between 0x00 and 0x0F. + * @retval None + */ +static void TMR_TI1_ConfigInputStage(TMR_TypeDef *TMRx, uint32_t TMR_ICPolarity, uint32_t TMR_ICFilter) +{ + uint32_t tmpccmr1; + uint32_t tmpccer; + + /* Disable the Channel 1: Reset the CC1EN Bit */ + tmpccer = TMRx->CCEN; + TMRx->CCEN &= ~TMR_CCEN_CC1EN; + tmpccmr1 = TMRx->CCM1; + + /* Set the filter */ + tmpccmr1 &= ~TMR_CCM1_IC1F; + tmpccmr1 |= (TMR_ICFilter << 4U); + + /* Select the Polarity and set the CC1EN Bit */ + tmpccer &= ~(TMR_CCEN_CC1POL | TMR_CCEN_CC1NPOL); + tmpccer |= TMR_ICPolarity; + + /* Write to TMRx CCM1 and CCEN registers */ + TMRx->CCM1 = tmpccmr1; + TMRx->CCEN = tmpccer; +} + +/** + * @brief Configure the TI2 as Input. + * @param TMRx to select the TMR peripheral + * @param TMR_ICPolarity The Input Polarity. + * This parameter can be one of the following values: + * @arg TMR_ICPOLARITY_RISING + * @arg TMR_ICPOLARITY_FALLING + * @arg TMR_ICPOLARITY_BOTHEDGE + * @param TMR_ICSelection specifies the input to be used. + * This parameter can be one of the following values: + * @arg TMR_ICSELECTION_DIRECTTI: TMR Input 2 is selected to be connected to IC2. + * @arg TMR_ICSELECTION_INDIRECTTI: TMR Input 2 is selected to be connected to IC1. + * @arg TMR_ICSELECTION_TRC: TMR Input 2 is selected to be connected to TRC. + * @param TMR_ICFilter Specifies the Input Capture Filter. + * This parameter must be a value between 0x00 and 0x0F. + * @retval None + * @note TMR_ICFilter and TMR_ICPolarity are not used in INDIRECT mode as TI1FP2 + * (on channel1 path) is used as the input signal. Therefore CCMR1 must be + * protected against un-initialized filter and polarity values. + */ +static void TMR_TI2_SetConfig(TMR_TypeDef *TMRx, uint32_t TMR_ICPolarity, uint32_t TMR_ICSelection, + uint32_t TMR_ICFilter) +{ + uint32_t tmpccmr1; + uint32_t tmpccer; + + /* Disable the Channel 2: Reset the CC2EN Bit */ + TMRx->CCEN &= ~TMR_CCEN_CC2EN; + tmpccmr1 = TMRx->CCM1; + tmpccer = TMRx->CCEN; + + /* Select the Input */ + tmpccmr1 &= ~TMR_CCM1_CC2SEL; + tmpccmr1 |= (TMR_ICSelection << 8U); + + /* Set the filter */ + tmpccmr1 &= ~TMR_CCM1_IC2F; + tmpccmr1 |= ((TMR_ICFilter << 12U) & TMR_CCM1_IC2F); + + /* Select the Polarity and set the CC2EN Bit */ + tmpccer &= ~(TMR_CCEN_CC2POL | TMR_CCEN_CC2NPOL); + tmpccer |= ((TMR_ICPolarity << 4U) & (TMR_CCEN_CC2POL | TMR_CCEN_CC2NPOL)); + + /* Write to TMRx CCM1 and CCEN registers */ + TMRx->CCM1 = tmpccmr1 ; + TMRx->CCEN = tmpccer; +} + +/** + * @brief Configure the Polarity and Filter for TI2. + * @param TMRx to select the TMR peripheral. + * @param TMR_ICPolarity The Input Polarity. + * This parameter can be one of the following values: + * @arg TMR_ICPOLARITY_RISING + * @arg TMR_ICPOLARITY_FALLING + * @arg TMR_ICPOLARITY_BOTHEDGE + * @param TMR_ICFilter Specifies the Input Capture Filter. + * This parameter must be a value between 0x00 and 0x0F. + * @retval None + */ +static void TMR_TI2_ConfigInputStage(TMR_TypeDef *TMRx, uint32_t TMR_ICPolarity, uint32_t TMR_ICFilter) +{ + uint32_t tmpccmr1; + uint32_t tmpccer; + + /* Disable the Channel 2: Reset the CC2EN Bit */ + TMRx->CCEN &= ~TMR_CCEN_CC2EN; + tmpccmr1 = TMRx->CCM1; + tmpccer = TMRx->CCEN; + + /* Set the filter */ + tmpccmr1 &= ~TMR_CCM1_IC2F; + tmpccmr1 |= (TMR_ICFilter << 12U); + + /* Select the Polarity and set the CC2EN Bit */ + tmpccer &= ~(TMR_CCEN_CC2POL | TMR_CCEN_CC2NPOL); + tmpccer |= (TMR_ICPolarity << 4U); + + /* Write to TMRx CCM1 and CCEN registers */ + TMRx->CCM1 = tmpccmr1 ; + TMRx->CCEN = tmpccer; +} + +/** + * @brief Configure the TI3 as Input. + * @param TMRx to select the TMR peripheral + * @param TMR_ICPolarity The Input Polarity. + * This parameter can be one of the following values: + * @arg TMR_ICPOLARITY_RISING + * @arg TMR_ICPOLARITY_FALLING + * @arg TMR_ICPOLARITY_BOTHEDGE + * @param TMR_ICSelection specifies the input to be used. + * This parameter can be one of the following values: + * @arg TMR_ICSELECTION_DIRECTTI: TMR Input 3 is selected to be connected to IC3. + * @arg TMR_ICSELECTION_INDIRECTTI: TMR Input 3 is selected to be connected to IC4. + * @arg TMR_ICSELECTION_TRC: TMR Input 3 is selected to be connected to TRC. + * @param TMR_ICFilter Specifies the Input Capture Filter. + * This parameter must be a value between 0x00 and 0x0F. + * @retval None + * @note TMR_ICFilter and TMR_ICPolarity are not used in INDIRECT mode as TI3FP4 + * (on channel1 path) is used as the input signal. Therefore CCMR2 must be + * protected against un-initialized filter and polarity values. + */ +static void TMR_TI3_SetConfig(TMR_TypeDef *TMRx, uint32_t TMR_ICPolarity, uint32_t TMR_ICSelection, + uint32_t TMR_ICFilter) +{ + uint32_t tmpccmr2; + uint32_t tmpccer; + + /* Disable the Channel 3: Reset the CC3EN Bit */ + TMRx->CCEN &= ~TMR_CCEN_CC3EN; + tmpccmr2 = TMRx->CCM2; + tmpccer = TMRx->CCEN; + + /* Select the Input */ + tmpccmr2 &= ~TMR_CCM2_CC3SEL; + tmpccmr2 |= TMR_ICSelection; + + /* Set the filter */ + tmpccmr2 &= ~TMR_CCM2_IC3F; + tmpccmr2 |= ((TMR_ICFilter << 4U) & TMR_CCM2_IC3F); + + /* Select the Polarity and set the CC3EN Bit */ + tmpccer &= ~(TMR_CCEN_CC3POL | TMR_CCEN_CC3NPOL); + tmpccer |= ((TMR_ICPolarity << 8U) & (TMR_CCEN_CC3POL | TMR_CCEN_CC3NPOL)); + + /* Write to TMRx CCM2 and CCEN registers */ + TMRx->CCM2 = tmpccmr2; + TMRx->CCEN = tmpccer; +} + +/** + * @brief Configure the TI4 as Input. + * @param TMRx to select the TMR peripheral + * @param TMR_ICPolarity The Input Polarity. + * This parameter can be one of the following values: + * @arg TMR_ICPOLARITY_RISING + * @arg TMR_ICPOLARITY_FALLING + * @arg TMR_ICPOLARITY_BOTHEDGE + * @param TMR_ICSelection specifies the input to be used. + * This parameter can be one of the following values: + * @arg TMR_ICSELECTION_DIRECTTI: TMR Input 4 is selected to be connected to IC4. + * @arg TMR_ICSELECTION_INDIRECTTI: TMR Input 4 is selected to be connected to IC3. + * @arg TMR_ICSELECTION_TRC: TMR Input 4 is selected to be connected to TRC. + * @param TMR_ICFilter Specifies the Input Capture Filter. + * This parameter must be a value between 0x00 and 0x0F. + * @note TMR_ICFilter and TMR_ICPolarity are not used in INDIRECT mode as TI4FP3 + * (on channel1 path) is used as the input signal. Therefore CCMR2 must be + * protected against un-initialized filter and polarity values. + * @retval None + */ +static void TMR_TI4_SetConfig(TMR_TypeDef *TMRx, uint32_t TMR_ICPolarity, uint32_t TMR_ICSelection, + uint32_t TMR_ICFilter) +{ + uint32_t tmpccmr2; + uint32_t tmpccer; + + /* Disable the Channel 4: Reset the CC4EN Bit */ + TMRx->CCEN &= ~TMR_CCEN_CC4EN; + tmpccmr2 = TMRx->CCM2; + tmpccer = TMRx->CCEN; + + /* Select the Input */ + tmpccmr2 &= ~TMR_CCM2_CC4SEL; + tmpccmr2 |= (TMR_ICSelection << 8U); + + /* Set the filter */ + tmpccmr2 &= ~TMR_CCM2_IC4F; + tmpccmr2 |= ((TMR_ICFilter << 12U) & TMR_CCM2_IC4F); + + /* Select the Polarity and set the CC4EN Bit */ + tmpccer &= ~(TMR_CCEN_CC4POL | TMR_CCEN_CC4NPOL); + tmpccer |= ((TMR_ICPolarity << 12U) & (TMR_CCEN_CC4POL | TMR_CCEN_CC4NPOL)); + + /* Write to TMRx CCM2 and CCEN registers */ + TMRx->CCM2 = tmpccmr2; + TMRx->CCEN = tmpccer ; +} + +/** + * @brief Selects the Input Trigger source + * @param TMRx to select the TMR peripheral + * @param InputTriggerSource The Input Trigger source. + * This parameter can be one of the following values: + * @arg TMR_TS_ITR0: Internal Trigger 0 + * @arg TMR_TS_ITR1: Internal Trigger 1 + * @arg TMR_TS_ITR2: Internal Trigger 2 + * @arg TMR_TS_ITR3: Internal Trigger 3 + * @arg TMR_TS_TI1F_ED: TI1 Edge Detector + * @arg TMR_TS_TI1FP1: Filtered Timer Input 1 + * @arg TMR_TS_TI2FP2: Filtered Timer Input 2 + * @arg TMR_TS_ETRF: External Trigger input + * @retval None + */ +static void TMR_ITRx_SetConfig(TMR_TypeDef *TMRx, uint32_t InputTriggerSource) +{ + uint32_t tmpsmcr; + + /* Get the TMRx SMCTRL register value */ + tmpsmcr = TMRx->SMCTRL; + /* Reset the TS Bits */ + tmpsmcr &= ~TMR_SMCTRL_TRGSEL; + /* Set the Input Trigger source and the slave mode*/ + tmpsmcr |= (InputTriggerSource | TMR_SLAVEMODE_EXTERNAL1); + /* Write to TMRx SMCTRL */ + TMRx->SMCTRL = tmpsmcr; +} +/** + * @brief Configures the TMRx External Trigger (ETR). + * @param TMRx to select the TMR peripheral + * @param TMR_ExtTRGPrescaler The external Trigger Prescaler. + * This parameter can be one of the following values: + * @arg TMR_ETRPRESCALER_DIV1: ETRP Prescaler OFF. + * @arg TMR_ETRPRESCALER_DIV2: ETRP frequency divided by 2. + * @arg TMR_ETRPRESCALER_DIV4: ETRP frequency divided by 4. + * @arg TMR_ETRPRESCALER_DIV8: ETRP frequency divided by 8. + * @param TMR_ExtTRGPolarity The external Trigger Polarity. + * This parameter can be one of the following values: + * @arg TMR_ETRPOLARITY_INVERTED: active low or falling edge active. + * @arg TMR_ETRPOLARITY_NONINVERTED: active high or rising edge active. + * @param ExtTRGFilter External Trigger Filter. + * This parameter must be a value between 0x00 and 0x0F + * @retval None + */ +void TMR_ETR_SetConfig(TMR_TypeDef *TMRx, uint32_t TMR_ExtTRGPrescaler, + uint32_t TMR_ExtTRGPolarity, uint32_t ExtTRGFilter) +{ + uint32_t tmpsmcr; + + tmpsmcr = TMRx->SMCTRL; + + /* Reset the ETR Bits */ + tmpsmcr &= ~(TMR_SMCTRL_ETFCFG | TMR_SMCTRL_ETPCFG | TMR_SMCTRL_ECEN | TMR_SMCTRL_ETPOL); + + /* Set the Prescaler, the Filter value and the Polarity */ + tmpsmcr |= (uint32_t)(TMR_ExtTRGPrescaler | (TMR_ExtTRGPolarity | (ExtTRGFilter << 8U))); + + /* Write to TMRx SMCTRL */ + TMRx->SMCTRL = tmpsmcr; +} + +/** + * @brief Enables or disables the TMR Capture Compare Channel x. + * @param TMRx to select the TMR peripheral + * @param Channel specifies the TMR Channel + * This parameter can be one of the following values: + * @arg TMR_CHANNEL_1: TMR Channel 1 + * @arg TMR_CHANNEL_2: TMR Channel 2 + * @arg TMR_CHANNEL_3: TMR Channel 3 + * @arg TMR_CHANNEL_4: TMR Channel 4 + * @param ChannelState specifies the TMR Channel CCxE bit new state. + * This parameter can be: TMR_CCx_ENABLE or TMR_CCx_DISABLE. + * @retval None + */ +void TMR_CCxChannelCmd(TMR_TypeDef *TMRx, uint32_t Channel, uint32_t ChannelState) +{ + uint32_t tmp; + + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_CC1_INSTANCE(TMRx)); + ASSERT_PARAM(IS_TMR_CHANNELS(Channel)); + + tmp = TMR_CCEN_CC1EN << (Channel & 0x1FU); /* 0x1FU = 31 bits max shift */ + + /* Reset the CCxEN Bit */ + TMRx->CCEN &= ~tmp; + + /* Set or reset the CCxEN Bit */ + TMRx->CCEN |= (uint32_t)(ChannelState << (Channel & 0x1FU)); /* 0x1FU = 31 bits max shift */ +} + +#if (USE_DAL_TMR_REGISTER_CALLBACKS == 1) +/** + * @brief Reset interrupt callbacks to the legacy weak callbacks. + * @param htmr pointer to a TMR_HandleTypeDef structure that contains + * the configuration information for TMR module. + * @retval None + */ +void TMR_ResetCallback(TMR_HandleTypeDef *htmr) +{ + /* Reset the TMR callback to the legacy weak callbacks */ + htmr->PeriodElapsedCallback = DAL_TMR_PeriodElapsedCallback; + htmr->PeriodElapsedHalfCpltCallback = DAL_TMR_PeriodElapsedHalfCpltCallback; + htmr->TriggerCallback = DAL_TMR_TriggerCallback; + htmr->TriggerHalfCpltCallback = DAL_TMR_TriggerHalfCpltCallback; + htmr->IC_CaptureCallback = DAL_TMR_IC_CaptureCallback; + htmr->IC_CaptureHalfCpltCallback = DAL_TMR_IC_CaptureHalfCpltCallback; + htmr->OC_DelayElapsedCallback = DAL_TMR_OC_DelayElapsedCallback; + htmr->PWM_PulseFinishedCallback = DAL_TMR_PWM_PulseFinishedCallback; + htmr->PWM_PulseFinishedHalfCpltCallback = DAL_TMR_PWM_PulseFinishedHalfCpltCallback; + htmr->ErrorCallback = DAL_TMR_ErrorCallback; + htmr->CommutationCallback = DAL_TMREx_CommutCallback; + htmr->CommutationHalfCpltCallback = DAL_TMREx_CommutHalfCpltCallback; + htmr->BreakCallback = DAL_TMREx_BreakCallback; +} +#endif /* USE_DAL_TMR_REGISTER_CALLBACKS */ + +/** + * @} + */ + +#endif /* DAL_TMR_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_tmr_ex.c b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_tmr_ex.c new file mode 100644 index 0000000000..cfe0295b91 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_tmr_ex.c @@ -0,0 +1,2453 @@ +/** + * + * @file apm32f4xx_dal_tmr_ex.c + * @brief TMR DAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the Timer Extended peripheral: + * + Time Hall Sensor Interface Initialization + * + Time Hall Sensor Interface Start + * + Time Complementary signal break and dead time configuration + * + Time Master and Slave synchronization configuration + * + Timer remapping capabilities configuration + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + * + @verbatim + ============================================================================== + ##### TMRER Extended features ##### + ============================================================================== + [..] + The Timer Extended features include: + (#) Complementary outputs with programmable dead-time for : + (++) Output Compare + (++) PWM generation (Edge and Center-aligned Mode) + (++) One-pulse mode output + (#) Synchronization circuit to control the timer with external signals and to + interconnect several timers together. + (#) Break input to put the timer output signals in reset state or in a known state. + (#) Supports incremental (quadrature) encoder and hall-sensor circuitry for + positioning purposes + + ##### How to use this driver ##### + ============================================================================== + [..] + (#) Initialize the TMR low level resources by implementing the following functions + depending on the selected feature: + (++) Hall Sensor output : DAL_TMREx_HallSensor_MspInit() + + (#) Initialize the TMR low level resources : + (##) Enable the TMR interface clock using __DAL_RCM_TMRx_CLK_ENABLE(); + (##) TMR pins configuration + (+++) Enable the clock for the TMR GPIOs using the following function: + __DAL_RCM_GPIOx_CLK_ENABLE(); + (+++) Configure these TMR pins in Alternate function mode using DAL_GPIO_Init(); + + (#) The external Clock can be configured, if needed (the default clock is the + internal clock from the APBx), using the following function: + DAL_TMR_ConfigClockSource, the clock configuration should be done before + any start function. + + (#) Configure the TMR in the desired functioning mode using one of the + initialization function of this driver: + (++) DAL_TMREx_HallSensor_Init() and DAL_TMREx_ConfigCommutEvent(): to use the + Timer Hall Sensor Interface and the commutation event with the corresponding + Interrupt and DMA request if needed (Note that One Timer is used to interface + with the Hall sensor Interface and another Timer should be used to use + the commutation event). + + (#) Activate the TMR peripheral using one of the start functions: + (++) Complementary Output Compare : DAL_TMREx_OCN_Start(), DAL_TMREx_OCN_Start_DMA(), + DAL_TMREx_OCN_Start_IT() + (++) Complementary PWM generation : DAL_TMREx_PWMN_Start(), DAL_TMREx_PWMN_Start_DMA(), + DAL_TMREx_PWMN_Start_IT() + (++) Complementary One-pulse mode output : DAL_TMREx_OnePulseN_Start(), DAL_TMREx_OnePulseN_Start_IT() + (++) Hall Sensor output : DAL_TMREx_HallSensor_Start(), DAL_TMREx_HallSensor_Start_DMA(), + DAL_TMREx_HallSensor_Start_IT(). + + @endverbatim + * + */ + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @defgroup TMREx TMREx + * @brief TMR Extended DAL module driver + * @{ + */ + +#ifdef DAL_TMR_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macros ------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +static void TMR_DMADelayPulseNCplt(DMA_HandleTypeDef *hdma); +static void TMR_DMAErrorCCxN(DMA_HandleTypeDef *hdma); +static void TMR_CCxNChannelCmd(TMR_TypeDef *TMRx, uint32_t Channel, uint32_t ChannelNState); + +/* Exported functions --------------------------------------------------------*/ +/** @defgroup TMREx_Exported_Functions TMR Extended Exported Functions + * @{ + */ + +/** @defgroup TMREx_Exported_Functions_Group1 Extended Timer Hall Sensor functions + * @brief Timer Hall Sensor functions + * +@verbatim + ============================================================================== + ##### Timer Hall Sensor functions ##### + ============================================================================== + [..] + This section provides functions allowing to: + (+) Initialize and configure TMR DAL Sensor. + (+) De-initialize TMR DAL Sensor. + (+) Start the Hall Sensor Interface. + (+) Stop the Hall Sensor Interface. + (+) Start the Hall Sensor Interface and enable interrupts. + (+) Stop the Hall Sensor Interface and disable interrupts. + (+) Start the Hall Sensor Interface and enable DMA transfers. + (+) Stop the Hall Sensor Interface and disable DMA transfers. + +@endverbatim + * @{ + */ +/** + * @brief Initializes the TMR Hall Sensor Interface and initialize the associated handle. + * @note When the timer instance is initialized in Hall Sensor Interface mode, + * timer channels 1 and channel 2 are reserved and cannot be used for + * other purpose. + * @param htmr TMR Hall Sensor Interface handle + * @param sConfig TMR Hall Sensor configuration structure + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMREx_HallSensor_Init(TMR_HandleTypeDef *htmr, TMR_HallSensor_InitTypeDef *sConfig) +{ + TMR_OC_InitTypeDef OC_Config; + + /* Check the TMR handle allocation */ + if (htmr == NULL) + { + return DAL_ERROR; + } + + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_HALL_SENSOR_INTERFACE_INSTANCE(htmr->Instance)); + ASSERT_PARAM(IS_TMR_COUNTER_MODE(htmr->Init.CounterMode)); + ASSERT_PARAM(IS_TMR_CLOCKDIVISION_DIV(htmr->Init.ClockDivision)); + ASSERT_PARAM(IS_TMR_AUTORELOAD_PRELOAD(htmr->Init.AutoReloadPreload)); + ASSERT_PARAM(IS_TMR_IC_POLARITY(sConfig->IC1Polarity)); + ASSERT_PARAM(IS_TMR_IC_PRESCALER(sConfig->IC1Prescaler)); + ASSERT_PARAM(IS_TMR_IC_FILTER(sConfig->IC1Filter)); + + if (htmr->State == DAL_TMR_STATE_RESET) + { + /* Allocate lock resource and initialize it */ + htmr->Lock = DAL_UNLOCKED; + +#if (USE_DAL_TMR_REGISTER_CALLBACKS == 1) + /* Reset interrupt callbacks to legacy week callbacks */ + TMR_ResetCallback(htmr); + + if (htmr->HallSensor_MspInitCallback == NULL) + { + htmr->HallSensor_MspInitCallback = DAL_TMREx_HallSensor_MspInit; + } + /* Init the low level hardware : GPIO, CLOCK, NVIC */ + htmr->HallSensor_MspInitCallback(htmr); +#else + /* Init the low level hardware : GPIO, CLOCK, NVIC and DMA */ + DAL_TMREx_HallSensor_MspInit(htmr); +#endif /* USE_DAL_TMR_REGISTER_CALLBACKS */ + } + + /* Set the TMR state */ + htmr->State = DAL_TMR_STATE_BUSY; + + /* Configure the Time base in the Encoder Mode */ + TMR_Base_SetConfig(htmr->Instance, &htmr->Init); + + /* Configure the Channel 1 as Input Channel to interface with the three Outputs of the Hall sensor */ + TMR_TI1_SetConfig(htmr->Instance, sConfig->IC1Polarity, TMR_ICSELECTION_TRC, sConfig->IC1Filter); + + /* Reset the IC1PSC Bits */ + htmr->Instance->CCM1 &= ~TMR_CCM1_IC1PSC; + /* Set the IC1PSC value */ + htmr->Instance->CCM1 |= sConfig->IC1Prescaler; + + /* Enable the Hall sensor interface (XOR function of the three inputs) */ + htmr->Instance->CTRL2 |= TMR_CTRL2_TI1SEL; + + /* Select the TMR_TS_TI1F_ED signal as Input trigger for the TMR */ + htmr->Instance->SMCTRL &= ~TMR_SMCTRL_TRGSEL; + htmr->Instance->SMCTRL |= TMR_TS_TI1F_ED; + + /* Use the TMR_TS_TI1F_ED signal to reset the TMR counter each edge detection */ + htmr->Instance->SMCTRL &= ~TMR_SMCTRL_SMFSEL; + htmr->Instance->SMCTRL |= TMR_SLAVEMODE_RESET; + + /* Program channel 2 in PWM 2 mode with the desired Commutation_Delay*/ + OC_Config.OCFastMode = TMR_OCFAST_DISABLE; + OC_Config.OCIdleState = TMR_OCIDLESTATE_RESET; + OC_Config.OCMode = TMR_OCMODE_PWM2; + OC_Config.OCNIdleState = TMR_OCNIDLESTATE_RESET; + OC_Config.OCNPolarity = TMR_OCNPOLARITY_HIGH; + OC_Config.OCPolarity = TMR_OCPOLARITY_HIGH; + OC_Config.Pulse = sConfig->Commutation_Delay; + + TMR_OC2_SetConfig(htmr->Instance, &OC_Config); + + /* Select OC2REF as trigger output on TRGO: write the MMS bits in the TMRx_CTRL2 + register to 101 */ + htmr->Instance->CTRL2 &= ~TMR_CTRL2_MMSEL; + htmr->Instance->CTRL2 |= TMR_TRGO_OC2REF; + + /* Initialize the DMA burst operation state */ + htmr->DMABurstState = DAL_DMA_BURST_STATE_READY; + + /* Initialize the TMR channels state */ + TMR_CHANNEL_STATE_SET(htmr, TMR_CHANNEL_1, DAL_TMR_CHANNEL_STATE_READY); + TMR_CHANNEL_STATE_SET(htmr, TMR_CHANNEL_2, DAL_TMR_CHANNEL_STATE_READY); + TMR_CHANNEL_N_STATE_SET(htmr, TMR_CHANNEL_1, DAL_TMR_CHANNEL_STATE_READY); + TMR_CHANNEL_N_STATE_SET(htmr, TMR_CHANNEL_2, DAL_TMR_CHANNEL_STATE_READY); + + /* Initialize the TMR state*/ + htmr->State = DAL_TMR_STATE_READY; + + return DAL_OK; +} + +/** + * @brief DeInitializes the TMR Hall Sensor interface + * @param htmr TMR Hall Sensor Interface handle + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMREx_HallSensor_DeInit(TMR_HandleTypeDef *htmr) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_INSTANCE(htmr->Instance)); + + htmr->State = DAL_TMR_STATE_BUSY; + + /* Disable the TMR Peripheral Clock */ + __DAL_TMR_DISABLE(htmr); + +#if (USE_DAL_TMR_REGISTER_CALLBACKS == 1) + if (htmr->HallSensor_MspDeInitCallback == NULL) + { + htmr->HallSensor_MspDeInitCallback = DAL_TMREx_HallSensor_MspDeInit; + } + /* DeInit the low level hardware */ + htmr->HallSensor_MspDeInitCallback(htmr); +#else + /* DeInit the low level hardware: GPIO, CLOCK, NVIC */ + DAL_TMREx_HallSensor_MspDeInit(htmr); +#endif /* USE_DAL_TMR_REGISTER_CALLBACKS */ + + /* Change the DMA burst operation state */ + htmr->DMABurstState = DAL_DMA_BURST_STATE_RESET; + + /* Change the TMR channels state */ + TMR_CHANNEL_STATE_SET(htmr, TMR_CHANNEL_1, DAL_TMR_CHANNEL_STATE_RESET); + TMR_CHANNEL_STATE_SET(htmr, TMR_CHANNEL_2, DAL_TMR_CHANNEL_STATE_RESET); + TMR_CHANNEL_N_STATE_SET(htmr, TMR_CHANNEL_1, DAL_TMR_CHANNEL_STATE_RESET); + TMR_CHANNEL_N_STATE_SET(htmr, TMR_CHANNEL_2, DAL_TMR_CHANNEL_STATE_RESET); + + /* Change TMR state */ + htmr->State = DAL_TMR_STATE_RESET; + + /* Release Lock */ + __DAL_UNLOCK(htmr); + + return DAL_OK; +} + +/** + * @brief Initializes the TMR Hall Sensor MSP. + * @param htmr TMR Hall Sensor Interface handle + * @retval None + */ +__weak void DAL_TMREx_HallSensor_MspInit(TMR_HandleTypeDef *htmr) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(htmr); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_TMREx_HallSensor_MspInit could be implemented in the user file + */ +} + +/** + * @brief DeInitializes TMR Hall Sensor MSP. + * @param htmr TMR Hall Sensor Interface handle + * @retval None + */ +__weak void DAL_TMREx_HallSensor_MspDeInit(TMR_HandleTypeDef *htmr) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(htmr); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_TMREx_HallSensor_MspDeInit could be implemented in the user file + */ +} + +/** + * @brief Starts the TMR Hall Sensor Interface. + * @param htmr TMR Hall Sensor Interface handle + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMREx_HallSensor_Start(TMR_HandleTypeDef *htmr) +{ + uint32_t tmpsmcr; + DAL_TMR_ChannelStateTypeDef channel_1_state = TMR_CHANNEL_STATE_GET(htmr, TMR_CHANNEL_1); + DAL_TMR_ChannelStateTypeDef channel_2_state = TMR_CHANNEL_STATE_GET(htmr, TMR_CHANNEL_2); + DAL_TMR_ChannelStateTypeDef complementary_channel_1_state = TMR_CHANNEL_N_STATE_GET(htmr, TMR_CHANNEL_1); + DAL_TMR_ChannelStateTypeDef complementary_channel_2_state = TMR_CHANNEL_N_STATE_GET(htmr, TMR_CHANNEL_2); + + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_HALL_SENSOR_INTERFACE_INSTANCE(htmr->Instance)); + + /* Check the TMR channels state */ + if ((channel_1_state != DAL_TMR_CHANNEL_STATE_READY) + || (channel_2_state != DAL_TMR_CHANNEL_STATE_READY) + || (complementary_channel_1_state != DAL_TMR_CHANNEL_STATE_READY) + || (complementary_channel_2_state != DAL_TMR_CHANNEL_STATE_READY)) + { + return DAL_ERROR; + } + + /* Set the TMR channels state */ + TMR_CHANNEL_STATE_SET(htmr, TMR_CHANNEL_1, DAL_TMR_CHANNEL_STATE_BUSY); + TMR_CHANNEL_STATE_SET(htmr, TMR_CHANNEL_2, DAL_TMR_CHANNEL_STATE_BUSY); + TMR_CHANNEL_N_STATE_SET(htmr, TMR_CHANNEL_1, DAL_TMR_CHANNEL_STATE_BUSY); + TMR_CHANNEL_N_STATE_SET(htmr, TMR_CHANNEL_2, DAL_TMR_CHANNEL_STATE_BUSY); + + /* Enable the Input Capture channel 1 + (in the Hall Sensor Interface the three possible channels that can be used are TMR_CHANNEL_1, + TMR_CHANNEL_2 and TMR_CHANNEL_3) */ + TMR_CCxChannelCmd(htmr->Instance, TMR_CHANNEL_1, TMR_CCx_ENABLE); + + /* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */ + if (IS_TMR_SLAVE_INSTANCE(htmr->Instance)) + { + tmpsmcr = htmr->Instance->SMCTRL & TMR_SMCTRL_SMFSEL; + if (!IS_TMR_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr)) + { + __DAL_TMR_ENABLE(htmr); + } + } + else + { + __DAL_TMR_ENABLE(htmr); + } + + /* Return function status */ + return DAL_OK; +} + +/** + * @brief Stops the TMR Hall sensor Interface. + * @param htmr TMR Hall Sensor Interface handle + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMREx_HallSensor_Stop(TMR_HandleTypeDef *htmr) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_HALL_SENSOR_INTERFACE_INSTANCE(htmr->Instance)); + + /* Disable the Input Capture channels 1, 2 and 3 + (in the Hall Sensor Interface the three possible channels that can be used are TMR_CHANNEL_1, + TMR_CHANNEL_2 and TMR_CHANNEL_3) */ + TMR_CCxChannelCmd(htmr->Instance, TMR_CHANNEL_1, TMR_CCx_DISABLE); + + /* Disable the Peripheral */ + __DAL_TMR_DISABLE(htmr); + + /* Set the TMR channels state */ + TMR_CHANNEL_STATE_SET(htmr, TMR_CHANNEL_1, DAL_TMR_CHANNEL_STATE_READY); + TMR_CHANNEL_STATE_SET(htmr, TMR_CHANNEL_2, DAL_TMR_CHANNEL_STATE_READY); + TMR_CHANNEL_N_STATE_SET(htmr, TMR_CHANNEL_1, DAL_TMR_CHANNEL_STATE_READY); + TMR_CHANNEL_N_STATE_SET(htmr, TMR_CHANNEL_2, DAL_TMR_CHANNEL_STATE_READY); + + /* Return function status */ + return DAL_OK; +} + +/** + * @brief Starts the TMR Hall Sensor Interface in interrupt mode. + * @param htmr TMR Hall Sensor Interface handle + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMREx_HallSensor_Start_IT(TMR_HandleTypeDef *htmr) +{ + uint32_t tmpsmcr; + DAL_TMR_ChannelStateTypeDef channel_1_state = TMR_CHANNEL_STATE_GET(htmr, TMR_CHANNEL_1); + DAL_TMR_ChannelStateTypeDef channel_2_state = TMR_CHANNEL_STATE_GET(htmr, TMR_CHANNEL_2); + DAL_TMR_ChannelStateTypeDef complementary_channel_1_state = TMR_CHANNEL_N_STATE_GET(htmr, TMR_CHANNEL_1); + DAL_TMR_ChannelStateTypeDef complementary_channel_2_state = TMR_CHANNEL_N_STATE_GET(htmr, TMR_CHANNEL_2); + + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_HALL_SENSOR_INTERFACE_INSTANCE(htmr->Instance)); + + /* Check the TMR channels state */ + if ((channel_1_state != DAL_TMR_CHANNEL_STATE_READY) + || (channel_2_state != DAL_TMR_CHANNEL_STATE_READY) + || (complementary_channel_1_state != DAL_TMR_CHANNEL_STATE_READY) + || (complementary_channel_2_state != DAL_TMR_CHANNEL_STATE_READY)) + { + return DAL_ERROR; + } + + /* Set the TMR channels state */ + TMR_CHANNEL_STATE_SET(htmr, TMR_CHANNEL_1, DAL_TMR_CHANNEL_STATE_BUSY); + TMR_CHANNEL_STATE_SET(htmr, TMR_CHANNEL_2, DAL_TMR_CHANNEL_STATE_BUSY); + TMR_CHANNEL_N_STATE_SET(htmr, TMR_CHANNEL_1, DAL_TMR_CHANNEL_STATE_BUSY); + TMR_CHANNEL_N_STATE_SET(htmr, TMR_CHANNEL_2, DAL_TMR_CHANNEL_STATE_BUSY); + + /* Enable the capture compare Interrupts 1 event */ + __DAL_TMR_ENABLE_IT(htmr, TMR_IT_CC1); + + /* Enable the Input Capture channel 1 + (in the Hall Sensor Interface the three possible channels that can be used are TMR_CHANNEL_1, + TMR_CHANNEL_2 and TMR_CHANNEL_3) */ + TMR_CCxChannelCmd(htmr->Instance, TMR_CHANNEL_1, TMR_CCx_ENABLE); + + /* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */ + if (IS_TMR_SLAVE_INSTANCE(htmr->Instance)) + { + tmpsmcr = htmr->Instance->SMCTRL & TMR_SMCTRL_SMFSEL; + if (!IS_TMR_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr)) + { + __DAL_TMR_ENABLE(htmr); + } + } + else + { + __DAL_TMR_ENABLE(htmr); + } + + /* Return function status */ + return DAL_OK; +} + +/** + * @brief Stops the TMR Hall Sensor Interface in interrupt mode. + * @param htmr TMR Hall Sensor Interface handle + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMREx_HallSensor_Stop_IT(TMR_HandleTypeDef *htmr) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_HALL_SENSOR_INTERFACE_INSTANCE(htmr->Instance)); + + /* Disable the Input Capture channel 1 + (in the Hall Sensor Interface the three possible channels that can be used are TMR_CHANNEL_1, + TMR_CHANNEL_2 and TMR_CHANNEL_3) */ + TMR_CCxChannelCmd(htmr->Instance, TMR_CHANNEL_1, TMR_CCx_DISABLE); + + /* Disable the capture compare Interrupts event */ + __DAL_TMR_DISABLE_IT(htmr, TMR_IT_CC1); + + /* Disable the Peripheral */ + __DAL_TMR_DISABLE(htmr); + + /* Set the TMR channels state */ + TMR_CHANNEL_STATE_SET(htmr, TMR_CHANNEL_1, DAL_TMR_CHANNEL_STATE_READY); + TMR_CHANNEL_STATE_SET(htmr, TMR_CHANNEL_2, DAL_TMR_CHANNEL_STATE_READY); + TMR_CHANNEL_N_STATE_SET(htmr, TMR_CHANNEL_1, DAL_TMR_CHANNEL_STATE_READY); + TMR_CHANNEL_N_STATE_SET(htmr, TMR_CHANNEL_2, DAL_TMR_CHANNEL_STATE_READY); + + /* Return function status */ + return DAL_OK; +} + +/** + * @brief Starts the TMR Hall Sensor Interface in DMA mode. + * @param htmr TMR Hall Sensor Interface handle + * @param pData The destination Buffer address. + * @param Length The length of data to be transferred from TMR peripheral to memory. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMREx_HallSensor_Start_DMA(TMR_HandleTypeDef *htmr, uint32_t *pData, uint16_t Length) +{ + uint32_t tmpsmcr; + DAL_TMR_ChannelStateTypeDef channel_1_state = TMR_CHANNEL_STATE_GET(htmr, TMR_CHANNEL_1); + DAL_TMR_ChannelStateTypeDef complementary_channel_1_state = TMR_CHANNEL_N_STATE_GET(htmr, TMR_CHANNEL_1); + + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_HALL_SENSOR_INTERFACE_INSTANCE(htmr->Instance)); + + /* Set the TMR channel state */ + if ((channel_1_state == DAL_TMR_CHANNEL_STATE_BUSY) + || (complementary_channel_1_state == DAL_TMR_CHANNEL_STATE_BUSY)) + { + return DAL_BUSY; + } + else if ((channel_1_state == DAL_TMR_CHANNEL_STATE_READY) + && (complementary_channel_1_state == DAL_TMR_CHANNEL_STATE_READY)) + { + if ((pData == NULL) && (Length > 0U)) + { + return DAL_ERROR; + } + else + { + TMR_CHANNEL_STATE_SET(htmr, TMR_CHANNEL_1, DAL_TMR_CHANNEL_STATE_BUSY); + TMR_CHANNEL_N_STATE_SET(htmr, TMR_CHANNEL_1, DAL_TMR_CHANNEL_STATE_BUSY); + } + } + else + { + return DAL_ERROR; + } + + /* Enable the Input Capture channel 1 + (in the Hall Sensor Interface the three possible channels that can be used are TMR_CHANNEL_1, + TMR_CHANNEL_2 and TMR_CHANNEL_3) */ + TMR_CCxChannelCmd(htmr->Instance, TMR_CHANNEL_1, TMR_CCx_ENABLE); + + /* Set the DMA Input Capture 1 Callbacks */ + htmr->hdma[TMR_DMA_ID_CC1]->XferCpltCallback = TMR_DMACaptureCplt; + htmr->hdma[TMR_DMA_ID_CC1]->XferHalfCpltCallback = TMR_DMACaptureHalfCplt; + /* Set the DMA error callback */ + htmr->hdma[TMR_DMA_ID_CC1]->XferErrorCallback = TMR_DMAError ; + + /* Enable the DMA stream for Capture 1*/ + if (DAL_DMA_Start_IT(htmr->hdma[TMR_DMA_ID_CC1], (uint32_t)&htmr->Instance->CC1, (uint32_t)pData, Length) != DAL_OK) + { + /* Return error status */ + return DAL_ERROR; + } + /* Enable the capture compare 1 Interrupt */ + __DAL_TMR_ENABLE_DMA(htmr, TMR_DMA_CC1); + + /* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */ + if (IS_TMR_SLAVE_INSTANCE(htmr->Instance)) + { + tmpsmcr = htmr->Instance->SMCTRL & TMR_SMCTRL_SMFSEL; + if (!IS_TMR_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr)) + { + __DAL_TMR_ENABLE(htmr); + } + } + else + { + __DAL_TMR_ENABLE(htmr); + } + + /* Return function status */ + return DAL_OK; +} + +/** + * @brief Stops the TMR Hall Sensor Interface in DMA mode. + * @param htmr TMR Hall Sensor Interface handle + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMREx_HallSensor_Stop_DMA(TMR_HandleTypeDef *htmr) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_HALL_SENSOR_INTERFACE_INSTANCE(htmr->Instance)); + + /* Disable the Input Capture channel 1 + (in the Hall Sensor Interface the three possible channels that can be used are TMR_CHANNEL_1, + TMR_CHANNEL_2 and TMR_CHANNEL_3) */ + TMR_CCxChannelCmd(htmr->Instance, TMR_CHANNEL_1, TMR_CCx_DISABLE); + + + /* Disable the capture compare Interrupts 1 event */ + __DAL_TMR_DISABLE_DMA(htmr, TMR_DMA_CC1); + + (void)DAL_DMA_Abort_IT(htmr->hdma[TMR_DMA_ID_CC1]); + + /* Disable the Peripheral */ + __DAL_TMR_DISABLE(htmr); + + /* Set the TMR channel state */ + TMR_CHANNEL_STATE_SET(htmr, TMR_CHANNEL_1, DAL_TMR_CHANNEL_STATE_READY); + TMR_CHANNEL_N_STATE_SET(htmr, TMR_CHANNEL_1, DAL_TMR_CHANNEL_STATE_READY); + + /* Return function status */ + return DAL_OK; +} + +/** + * @} + */ + +/** @defgroup TMREx_Exported_Functions_Group2 Extended Timer Complementary Output Compare functions + * @brief Timer Complementary Output Compare functions + * +@verbatim + ============================================================================== + ##### Timer Complementary Output Compare functions ##### + ============================================================================== + [..] + This section provides functions allowing to: + (+) Start the Complementary Output Compare/PWM. + (+) Stop the Complementary Output Compare/PWM. + (+) Start the Complementary Output Compare/PWM and enable interrupts. + (+) Stop the Complementary Output Compare/PWM and disable interrupts. + (+) Start the Complementary Output Compare/PWM and enable DMA transfers. + (+) Stop the Complementary Output Compare/PWM and disable DMA transfers. + +@endverbatim + * @{ + */ + +/** + * @brief Starts the TMR Output Compare signal generation on the complementary + * output. + * @param htmr TMR Output Compare handle + * @param Channel TMR Channel to be enabled + * This parameter can be one of the following values: + * @arg TMR_CHANNEL_1: TMR Channel 1 selected + * @arg TMR_CHANNEL_2: TMR Channel 2 selected + * @arg TMR_CHANNEL_3: TMR Channel 3 selected + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMREx_OCN_Start(TMR_HandleTypeDef *htmr, uint32_t Channel) +{ + uint32_t tmpsmcr; + + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_CCXN_INSTANCE(htmr->Instance, Channel)); + + /* Check the TMR complementary channel state */ + if (TMR_CHANNEL_N_STATE_GET(htmr, Channel) != DAL_TMR_CHANNEL_STATE_READY) + { + return DAL_ERROR; + } + + /* Set the TMR complementary channel state */ + TMR_CHANNEL_N_STATE_SET(htmr, Channel, DAL_TMR_CHANNEL_STATE_BUSY); + + /* Enable the Capture compare channel N */ + TMR_CCxNChannelCmd(htmr->Instance, Channel, TMR_CCxN_ENABLE); + + /* Enable the Main Output */ + __DAL_TMR_MOE_ENABLE(htmr); + + /* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */ + if (IS_TMR_SLAVE_INSTANCE(htmr->Instance)) + { + tmpsmcr = htmr->Instance->SMCTRL & TMR_SMCTRL_SMFSEL; + if (!IS_TMR_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr)) + { + __DAL_TMR_ENABLE(htmr); + } + } + else + { + __DAL_TMR_ENABLE(htmr); + } + + /* Return function status */ + return DAL_OK; +} + +/** + * @brief Stops the TMR Output Compare signal generation on the complementary + * output. + * @param htmr TMR handle + * @param Channel TMR Channel to be disabled + * This parameter can be one of the following values: + * @arg TMR_CHANNEL_1: TMR Channel 1 selected + * @arg TMR_CHANNEL_2: TMR Channel 2 selected + * @arg TMR_CHANNEL_3: TMR Channel 3 selected + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMREx_OCN_Stop(TMR_HandleTypeDef *htmr, uint32_t Channel) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_CCXN_INSTANCE(htmr->Instance, Channel)); + + /* Disable the Capture compare channel N */ + TMR_CCxNChannelCmd(htmr->Instance, Channel, TMR_CCxN_DISABLE); + + /* Disable the Main Output */ + __DAL_TMR_MOE_DISABLE(htmr); + + /* Disable the Peripheral */ + __DAL_TMR_DISABLE(htmr); + + /* Set the TMR complementary channel state */ + TMR_CHANNEL_N_STATE_SET(htmr, Channel, DAL_TMR_CHANNEL_STATE_READY); + + /* Return function status */ + return DAL_OK; +} + +/** + * @brief Starts the TMR Output Compare signal generation in interrupt mode + * on the complementary output. + * @param htmr TMR OC handle + * @param Channel TMR Channel to be enabled + * This parameter can be one of the following values: + * @arg TMR_CHANNEL_1: TMR Channel 1 selected + * @arg TMR_CHANNEL_2: TMR Channel 2 selected + * @arg TMR_CHANNEL_3: TMR Channel 3 selected + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMREx_OCN_Start_IT(TMR_HandleTypeDef *htmr, uint32_t Channel) +{ + DAL_StatusTypeDef status = DAL_OK; + uint32_t tmpsmcr; + + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_CCXN_INSTANCE(htmr->Instance, Channel)); + + /* Check the TMR complementary channel state */ + if (TMR_CHANNEL_N_STATE_GET(htmr, Channel) != DAL_TMR_CHANNEL_STATE_READY) + { + return DAL_ERROR; + } + + /* Set the TMR complementary channel state */ + TMR_CHANNEL_N_STATE_SET(htmr, Channel, DAL_TMR_CHANNEL_STATE_BUSY); + + switch (Channel) + { + case TMR_CHANNEL_1: + { + /* Enable the TMR Output Compare interrupt */ + __DAL_TMR_ENABLE_IT(htmr, TMR_IT_CC1); + break; + } + + case TMR_CHANNEL_2: + { + /* Enable the TMR Output Compare interrupt */ + __DAL_TMR_ENABLE_IT(htmr, TMR_IT_CC2); + break; + } + + case TMR_CHANNEL_3: + { + /* Enable the TMR Output Compare interrupt */ + __DAL_TMR_ENABLE_IT(htmr, TMR_IT_CC3); + break; + } + + + default: + status = DAL_ERROR; + break; + } + + if (status == DAL_OK) + { + /* Enable the TMR Break interrupt */ + __DAL_TMR_ENABLE_IT(htmr, TMR_IT_BREAK); + + /* Enable the Capture compare channel N */ + TMR_CCxNChannelCmd(htmr->Instance, Channel, TMR_CCxN_ENABLE); + + /* Enable the Main Output */ + __DAL_TMR_MOE_ENABLE(htmr); + + /* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */ + if (IS_TMR_SLAVE_INSTANCE(htmr->Instance)) + { + tmpsmcr = htmr->Instance->SMCTRL & TMR_SMCTRL_SMFSEL; + if (!IS_TMR_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr)) + { + __DAL_TMR_ENABLE(htmr); + } + } + else + { + __DAL_TMR_ENABLE(htmr); + } + } + + /* Return function status */ + return status; +} + +/** + * @brief Stops the TMR Output Compare signal generation in interrupt mode + * on the complementary output. + * @param htmr TMR Output Compare handle + * @param Channel TMR Channel to be disabled + * This parameter can be one of the following values: + * @arg TMR_CHANNEL_1: TMR Channel 1 selected + * @arg TMR_CHANNEL_2: TMR Channel 2 selected + * @arg TMR_CHANNEL_3: TMR Channel 3 selected + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMREx_OCN_Stop_IT(TMR_HandleTypeDef *htmr, uint32_t Channel) +{ + DAL_StatusTypeDef status = DAL_OK; + uint32_t tmpccer; + + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_CCXN_INSTANCE(htmr->Instance, Channel)); + + switch (Channel) + { + case TMR_CHANNEL_1: + { + /* Disable the TMR Output Compare interrupt */ + __DAL_TMR_DISABLE_IT(htmr, TMR_IT_CC1); + break; + } + + case TMR_CHANNEL_2: + { + /* Disable the TMR Output Compare interrupt */ + __DAL_TMR_DISABLE_IT(htmr, TMR_IT_CC2); + break; + } + + case TMR_CHANNEL_3: + { + /* Disable the TMR Output Compare interrupt */ + __DAL_TMR_DISABLE_IT(htmr, TMR_IT_CC3); + break; + } + + default: + status = DAL_ERROR; + break; + } + + if (status == DAL_OK) + { + /* Disable the Capture compare channel N */ + TMR_CCxNChannelCmd(htmr->Instance, Channel, TMR_CCxN_DISABLE); + + /* Disable the TMR Break interrupt (only if no more channel is active) */ + tmpccer = htmr->Instance->CCEN; + if ((tmpccer & (TMR_CCEN_CC1NEN | TMR_CCEN_CC2NEN | TMR_CCEN_CC3NEN)) == (uint32_t)RESET) + { + __DAL_TMR_DISABLE_IT(htmr, TMR_IT_BREAK); + } + + /* Disable the Main Output */ + __DAL_TMR_MOE_DISABLE(htmr); + + /* Disable the Peripheral */ + __DAL_TMR_DISABLE(htmr); + + /* Set the TMR complementary channel state */ + TMR_CHANNEL_N_STATE_SET(htmr, Channel, DAL_TMR_CHANNEL_STATE_READY); + } + + /* Return function status */ + return status; +} + +/** + * @brief Starts the TMR Output Compare signal generation in DMA mode + * on the complementary output. + * @param htmr TMR Output Compare handle + * @param Channel TMR Channel to be enabled + * This parameter can be one of the following values: + * @arg TMR_CHANNEL_1: TMR Channel 1 selected + * @arg TMR_CHANNEL_2: TMR Channel 2 selected + * @arg TMR_CHANNEL_3: TMR Channel 3 selected + * @param pData The source Buffer address. + * @param Length The length of data to be transferred from memory to TMR peripheral + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMREx_OCN_Start_DMA(TMR_HandleTypeDef *htmr, uint32_t Channel, uint32_t *pData, uint16_t Length) +{ + DAL_StatusTypeDef status = DAL_OK; + uint32_t tmpsmcr; + + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_CCXN_INSTANCE(htmr->Instance, Channel)); + + /* Set the TMR complementary channel state */ + if (TMR_CHANNEL_N_STATE_GET(htmr, Channel) == DAL_TMR_CHANNEL_STATE_BUSY) + { + return DAL_BUSY; + } + else if (TMR_CHANNEL_N_STATE_GET(htmr, Channel) == DAL_TMR_CHANNEL_STATE_READY) + { + if ((pData == NULL) && (Length > 0U)) + { + return DAL_ERROR; + } + else + { + TMR_CHANNEL_N_STATE_SET(htmr, Channel, DAL_TMR_CHANNEL_STATE_BUSY); + } + } + else + { + return DAL_ERROR; + } + + switch (Channel) + { + case TMR_CHANNEL_1: + { + /* Set the DMA compare callbacks */ + htmr->hdma[TMR_DMA_ID_CC1]->XferCpltCallback = TMR_DMADelayPulseNCplt; + htmr->hdma[TMR_DMA_ID_CC1]->XferHalfCpltCallback = TMR_DMADelayPulseHalfCplt; + + /* Set the DMA error callback */ + htmr->hdma[TMR_DMA_ID_CC1]->XferErrorCallback = TMR_DMAErrorCCxN ; + + /* Enable the DMA stream */ + if (DAL_DMA_Start_IT(htmr->hdma[TMR_DMA_ID_CC1], (uint32_t)pData, (uint32_t)&htmr->Instance->CC1, + Length) != DAL_OK) + { + /* Return error status */ + return DAL_ERROR; + } + /* Enable the TMR Output Compare DMA request */ + __DAL_TMR_ENABLE_DMA(htmr, TMR_DMA_CC1); + break; + } + + case TMR_CHANNEL_2: + { + /* Set the DMA compare callbacks */ + htmr->hdma[TMR_DMA_ID_CC2]->XferCpltCallback = TMR_DMADelayPulseNCplt; + htmr->hdma[TMR_DMA_ID_CC2]->XferHalfCpltCallback = TMR_DMADelayPulseHalfCplt; + + /* Set the DMA error callback */ + htmr->hdma[TMR_DMA_ID_CC2]->XferErrorCallback = TMR_DMAErrorCCxN ; + + /* Enable the DMA stream */ + if (DAL_DMA_Start_IT(htmr->hdma[TMR_DMA_ID_CC2], (uint32_t)pData, (uint32_t)&htmr->Instance->CC2, + Length) != DAL_OK) + { + /* Return error status */ + return DAL_ERROR; + } + /* Enable the TMR Output Compare DMA request */ + __DAL_TMR_ENABLE_DMA(htmr, TMR_DMA_CC2); + break; + } + + case TMR_CHANNEL_3: + { + /* Set the DMA compare callbacks */ + htmr->hdma[TMR_DMA_ID_CC3]->XferCpltCallback = TMR_DMADelayPulseNCplt; + htmr->hdma[TMR_DMA_ID_CC3]->XferHalfCpltCallback = TMR_DMADelayPulseHalfCplt; + + /* Set the DMA error callback */ + htmr->hdma[TMR_DMA_ID_CC3]->XferErrorCallback = TMR_DMAErrorCCxN ; + + /* Enable the DMA stream */ + if (DAL_DMA_Start_IT(htmr->hdma[TMR_DMA_ID_CC3], (uint32_t)pData, (uint32_t)&htmr->Instance->CC3, + Length) != DAL_OK) + { + /* Return error status */ + return DAL_ERROR; + } + /* Enable the TMR Output Compare DMA request */ + __DAL_TMR_ENABLE_DMA(htmr, TMR_DMA_CC3); + break; + } + + default: + status = DAL_ERROR; + break; + } + + if (status == DAL_OK) + { + /* Enable the Capture compare channel N */ + TMR_CCxNChannelCmd(htmr->Instance, Channel, TMR_CCxN_ENABLE); + + /* Enable the Main Output */ + __DAL_TMR_MOE_ENABLE(htmr); + + /* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */ + if (IS_TMR_SLAVE_INSTANCE(htmr->Instance)) + { + tmpsmcr = htmr->Instance->SMCTRL & TMR_SMCTRL_SMFSEL; + if (!IS_TMR_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr)) + { + __DAL_TMR_ENABLE(htmr); + } + } + else + { + __DAL_TMR_ENABLE(htmr); + } + } + + /* Return function status */ + return status; +} + +/** + * @brief Stops the TMR Output Compare signal generation in DMA mode + * on the complementary output. + * @param htmr TMR Output Compare handle + * @param Channel TMR Channel to be disabled + * This parameter can be one of the following values: + * @arg TMR_CHANNEL_1: TMR Channel 1 selected + * @arg TMR_CHANNEL_2: TMR Channel 2 selected + * @arg TMR_CHANNEL_3: TMR Channel 3 selected + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMREx_OCN_Stop_DMA(TMR_HandleTypeDef *htmr, uint32_t Channel) +{ + DAL_StatusTypeDef status = DAL_OK; + + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_CCXN_INSTANCE(htmr->Instance, Channel)); + + switch (Channel) + { + case TMR_CHANNEL_1: + { + /* Disable the TMR Output Compare DMA request */ + __DAL_TMR_DISABLE_DMA(htmr, TMR_DMA_CC1); + (void)DAL_DMA_Abort_IT(htmr->hdma[TMR_DMA_ID_CC1]); + break; + } + + case TMR_CHANNEL_2: + { + /* Disable the TMR Output Compare DMA request */ + __DAL_TMR_DISABLE_DMA(htmr, TMR_DMA_CC2); + (void)DAL_DMA_Abort_IT(htmr->hdma[TMR_DMA_ID_CC2]); + break; + } + + case TMR_CHANNEL_3: + { + /* Disable the TMR Output Compare DMA request */ + __DAL_TMR_DISABLE_DMA(htmr, TMR_DMA_CC3); + (void)DAL_DMA_Abort_IT(htmr->hdma[TMR_DMA_ID_CC3]); + break; + } + + default: + status = DAL_ERROR; + break; + } + + if (status == DAL_OK) + { + /* Disable the Capture compare channel N */ + TMR_CCxNChannelCmd(htmr->Instance, Channel, TMR_CCxN_DISABLE); + + /* Disable the Main Output */ + __DAL_TMR_MOE_DISABLE(htmr); + + /* Disable the Peripheral */ + __DAL_TMR_DISABLE(htmr); + + /* Set the TMR complementary channel state */ + TMR_CHANNEL_N_STATE_SET(htmr, Channel, DAL_TMR_CHANNEL_STATE_READY); + } + + /* Return function status */ + return status; +} + +/** + * @} + */ + +/** @defgroup TMREx_Exported_Functions_Group3 Extended Timer Complementary PWM functions + * @brief Timer Complementary PWM functions + * +@verbatim + ============================================================================== + ##### Timer Complementary PWM functions ##### + ============================================================================== + [..] + This section provides functions allowing to: + (+) Start the Complementary PWM. + (+) Stop the Complementary PWM. + (+) Start the Complementary PWM and enable interrupts. + (+) Stop the Complementary PWM and disable interrupts. + (+) Start the Complementary PWM and enable DMA transfers. + (+) Stop the Complementary PWM and disable DMA transfers. + (+) Start the Complementary Input Capture measurement. + (+) Stop the Complementary Input Capture. + (+) Start the Complementary Input Capture and enable interrupts. + (+) Stop the Complementary Input Capture and disable interrupts. + (+) Start the Complementary Input Capture and enable DMA transfers. + (+) Stop the Complementary Input Capture and disable DMA transfers. + (+) Start the Complementary One Pulse generation. + (+) Stop the Complementary One Pulse. + (+) Start the Complementary One Pulse and enable interrupts. + (+) Stop the Complementary One Pulse and disable interrupts. + +@endverbatim + * @{ + */ + +/** + * @brief Starts the PWM signal generation on the complementary output. + * @param htmr TMR handle + * @param Channel TMR Channel to be enabled + * This parameter can be one of the following values: + * @arg TMR_CHANNEL_1: TMR Channel 1 selected + * @arg TMR_CHANNEL_2: TMR Channel 2 selected + * @arg TMR_CHANNEL_3: TMR Channel 3 selected + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMREx_PWMN_Start(TMR_HandleTypeDef *htmr, uint32_t Channel) +{ + uint32_t tmpsmcr; + + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_CCXN_INSTANCE(htmr->Instance, Channel)); + + /* Check the TMR complementary channel state */ + if (TMR_CHANNEL_N_STATE_GET(htmr, Channel) != DAL_TMR_CHANNEL_STATE_READY) + { + return DAL_ERROR; + } + + /* Set the TMR complementary channel state */ + TMR_CHANNEL_N_STATE_SET(htmr, Channel, DAL_TMR_CHANNEL_STATE_BUSY); + + /* Enable the complementary PWM output */ + TMR_CCxNChannelCmd(htmr->Instance, Channel, TMR_CCxN_ENABLE); + + /* Enable the Main Output */ + __DAL_TMR_MOE_ENABLE(htmr); + + /* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */ + if (IS_TMR_SLAVE_INSTANCE(htmr->Instance)) + { + tmpsmcr = htmr->Instance->SMCTRL & TMR_SMCTRL_SMFSEL; + if (!IS_TMR_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr)) + { + __DAL_TMR_ENABLE(htmr); + } + } + else + { + __DAL_TMR_ENABLE(htmr); + } + + /* Return function status */ + return DAL_OK; +} + +/** + * @brief Stops the PWM signal generation on the complementary output. + * @param htmr TMR handle + * @param Channel TMR Channel to be disabled + * This parameter can be one of the following values: + * @arg TMR_CHANNEL_1: TMR Channel 1 selected + * @arg TMR_CHANNEL_2: TMR Channel 2 selected + * @arg TMR_CHANNEL_3: TMR Channel 3 selected + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMREx_PWMN_Stop(TMR_HandleTypeDef *htmr, uint32_t Channel) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_CCXN_INSTANCE(htmr->Instance, Channel)); + + /* Disable the complementary PWM output */ + TMR_CCxNChannelCmd(htmr->Instance, Channel, TMR_CCxN_DISABLE); + + /* Disable the Main Output */ + __DAL_TMR_MOE_DISABLE(htmr); + + /* Disable the Peripheral */ + __DAL_TMR_DISABLE(htmr); + + /* Set the TMR complementary channel state */ + TMR_CHANNEL_N_STATE_SET(htmr, Channel, DAL_TMR_CHANNEL_STATE_READY); + + /* Return function status */ + return DAL_OK; +} + +/** + * @brief Starts the PWM signal generation in interrupt mode on the + * complementary output. + * @param htmr TMR handle + * @param Channel TMR Channel to be disabled + * This parameter can be one of the following values: + * @arg TMR_CHANNEL_1: TMR Channel 1 selected + * @arg TMR_CHANNEL_2: TMR Channel 2 selected + * @arg TMR_CHANNEL_3: TMR Channel 3 selected + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMREx_PWMN_Start_IT(TMR_HandleTypeDef *htmr, uint32_t Channel) +{ + DAL_StatusTypeDef status = DAL_OK; + uint32_t tmpsmcr; + + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_CCXN_INSTANCE(htmr->Instance, Channel)); + + /* Check the TMR complementary channel state */ + if (TMR_CHANNEL_N_STATE_GET(htmr, Channel) != DAL_TMR_CHANNEL_STATE_READY) + { + return DAL_ERROR; + } + + /* Set the TMR complementary channel state */ + TMR_CHANNEL_N_STATE_SET(htmr, Channel, DAL_TMR_CHANNEL_STATE_BUSY); + + switch (Channel) + { + case TMR_CHANNEL_1: + { + /* Enable the TMR Capture/Compare 1 interrupt */ + __DAL_TMR_ENABLE_IT(htmr, TMR_IT_CC1); + break; + } + + case TMR_CHANNEL_2: + { + /* Enable the TMR Capture/Compare 2 interrupt */ + __DAL_TMR_ENABLE_IT(htmr, TMR_IT_CC2); + break; + } + + case TMR_CHANNEL_3: + { + /* Enable the TMR Capture/Compare 3 interrupt */ + __DAL_TMR_ENABLE_IT(htmr, TMR_IT_CC3); + break; + } + + default: + status = DAL_ERROR; + break; + } + + if (status == DAL_OK) + { + /* Enable the TMR Break interrupt */ + __DAL_TMR_ENABLE_IT(htmr, TMR_IT_BREAK); + + /* Enable the complementary PWM output */ + TMR_CCxNChannelCmd(htmr->Instance, Channel, TMR_CCxN_ENABLE); + + /* Enable the Main Output */ + __DAL_TMR_MOE_ENABLE(htmr); + + /* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */ + if (IS_TMR_SLAVE_INSTANCE(htmr->Instance)) + { + tmpsmcr = htmr->Instance->SMCTRL & TMR_SMCTRL_SMFSEL; + if (!IS_TMR_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr)) + { + __DAL_TMR_ENABLE(htmr); + } + } + else + { + __DAL_TMR_ENABLE(htmr); + } + } + + /* Return function status */ + return status; +} + +/** + * @brief Stops the PWM signal generation in interrupt mode on the + * complementary output. + * @param htmr TMR handle + * @param Channel TMR Channel to be disabled + * This parameter can be one of the following values: + * @arg TMR_CHANNEL_1: TMR Channel 1 selected + * @arg TMR_CHANNEL_2: TMR Channel 2 selected + * @arg TMR_CHANNEL_3: TMR Channel 3 selected + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMREx_PWMN_Stop_IT(TMR_HandleTypeDef *htmr, uint32_t Channel) +{ + DAL_StatusTypeDef status = DAL_OK; + uint32_t tmpccer; + + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_CCXN_INSTANCE(htmr->Instance, Channel)); + + switch (Channel) + { + case TMR_CHANNEL_1: + { + /* Disable the TMR Capture/Compare 1 interrupt */ + __DAL_TMR_DISABLE_IT(htmr, TMR_IT_CC1); + break; + } + + case TMR_CHANNEL_2: + { + /* Disable the TMR Capture/Compare 2 interrupt */ + __DAL_TMR_DISABLE_IT(htmr, TMR_IT_CC2); + break; + } + + case TMR_CHANNEL_3: + { + /* Disable the TMR Capture/Compare 3 interrupt */ + __DAL_TMR_DISABLE_IT(htmr, TMR_IT_CC3); + break; + } + + default: + status = DAL_ERROR; + break; + } + + if (status == DAL_OK) + { + /* Disable the complementary PWM output */ + TMR_CCxNChannelCmd(htmr->Instance, Channel, TMR_CCxN_DISABLE); + + /* Disable the TMR Break interrupt (only if no more channel is active) */ + tmpccer = htmr->Instance->CCEN; + if ((tmpccer & (TMR_CCEN_CC1NEN | TMR_CCEN_CC2NEN | TMR_CCEN_CC3NEN)) == (uint32_t)RESET) + { + __DAL_TMR_DISABLE_IT(htmr, TMR_IT_BREAK); + } + + /* Disable the Main Output */ + __DAL_TMR_MOE_DISABLE(htmr); + + /* Disable the Peripheral */ + __DAL_TMR_DISABLE(htmr); + + /* Set the TMR complementary channel state */ + TMR_CHANNEL_N_STATE_SET(htmr, Channel, DAL_TMR_CHANNEL_STATE_READY); + } + + /* Return function status */ + return status; +} + +/** + * @brief Starts the TMR PWM signal generation in DMA mode on the + * complementary output + * @param htmr TMR handle + * @param Channel TMR Channel to be enabled + * This parameter can be one of the following values: + * @arg TMR_CHANNEL_1: TMR Channel 1 selected + * @arg TMR_CHANNEL_2: TMR Channel 2 selected + * @arg TMR_CHANNEL_3: TMR Channel 3 selected + * @param pData The source Buffer address. + * @param Length The length of data to be transferred from memory to TMR peripheral + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMREx_PWMN_Start_DMA(TMR_HandleTypeDef *htmr, uint32_t Channel, uint32_t *pData, uint16_t Length) +{ + DAL_StatusTypeDef status = DAL_OK; + uint32_t tmpsmcr; + + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_CCXN_INSTANCE(htmr->Instance, Channel)); + + /* Set the TMR complementary channel state */ + if (TMR_CHANNEL_N_STATE_GET(htmr, Channel) == DAL_TMR_CHANNEL_STATE_BUSY) + { + return DAL_BUSY; + } + else if (TMR_CHANNEL_N_STATE_GET(htmr, Channel) == DAL_TMR_CHANNEL_STATE_READY) + { + if ((pData == NULL) && (Length > 0U)) + { + return DAL_ERROR; + } + else + { + TMR_CHANNEL_N_STATE_SET(htmr, Channel, DAL_TMR_CHANNEL_STATE_BUSY); + } + } + else + { + return DAL_ERROR; + } + + switch (Channel) + { + case TMR_CHANNEL_1: + { + /* Set the DMA compare callbacks */ + htmr->hdma[TMR_DMA_ID_CC1]->XferCpltCallback = TMR_DMADelayPulseNCplt; + htmr->hdma[TMR_DMA_ID_CC1]->XferHalfCpltCallback = TMR_DMADelayPulseHalfCplt; + + /* Set the DMA error callback */ + htmr->hdma[TMR_DMA_ID_CC1]->XferErrorCallback = TMR_DMAErrorCCxN ; + + /* Enable the DMA stream */ + if (DAL_DMA_Start_IT(htmr->hdma[TMR_DMA_ID_CC1], (uint32_t)pData, (uint32_t)&htmr->Instance->CC1, + Length) != DAL_OK) + { + /* Return error status */ + return DAL_ERROR; + } + /* Enable the TMR Capture/Compare 1 DMA request */ + __DAL_TMR_ENABLE_DMA(htmr, TMR_DMA_CC1); + break; + } + + case TMR_CHANNEL_2: + { + /* Set the DMA compare callbacks */ + htmr->hdma[TMR_DMA_ID_CC2]->XferCpltCallback = TMR_DMADelayPulseNCplt; + htmr->hdma[TMR_DMA_ID_CC2]->XferHalfCpltCallback = TMR_DMADelayPulseHalfCplt; + + /* Set the DMA error callback */ + htmr->hdma[TMR_DMA_ID_CC2]->XferErrorCallback = TMR_DMAErrorCCxN ; + + /* Enable the DMA stream */ + if (DAL_DMA_Start_IT(htmr->hdma[TMR_DMA_ID_CC2], (uint32_t)pData, (uint32_t)&htmr->Instance->CC2, + Length) != DAL_OK) + { + /* Return error status */ + return DAL_ERROR; + } + /* Enable the TMR Capture/Compare 2 DMA request */ + __DAL_TMR_ENABLE_DMA(htmr, TMR_DMA_CC2); + break; + } + + case TMR_CHANNEL_3: + { + /* Set the DMA compare callbacks */ + htmr->hdma[TMR_DMA_ID_CC3]->XferCpltCallback = TMR_DMADelayPulseNCplt; + htmr->hdma[TMR_DMA_ID_CC3]->XferHalfCpltCallback = TMR_DMADelayPulseHalfCplt; + + /* Set the DMA error callback */ + htmr->hdma[TMR_DMA_ID_CC3]->XferErrorCallback = TMR_DMAErrorCCxN ; + + /* Enable the DMA stream */ + if (DAL_DMA_Start_IT(htmr->hdma[TMR_DMA_ID_CC3], (uint32_t)pData, (uint32_t)&htmr->Instance->CC3, + Length) != DAL_OK) + { + /* Return error status */ + return DAL_ERROR; + } + /* Enable the TMR Capture/Compare 3 DMA request */ + __DAL_TMR_ENABLE_DMA(htmr, TMR_DMA_CC3); + break; + } + + default: + status = DAL_ERROR; + break; + } + + if (status == DAL_OK) + { + /* Enable the complementary PWM output */ + TMR_CCxNChannelCmd(htmr->Instance, Channel, TMR_CCxN_ENABLE); + + /* Enable the Main Output */ + __DAL_TMR_MOE_ENABLE(htmr); + + /* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */ + if (IS_TMR_SLAVE_INSTANCE(htmr->Instance)) + { + tmpsmcr = htmr->Instance->SMCTRL & TMR_SMCTRL_SMFSEL; + if (!IS_TMR_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr)) + { + __DAL_TMR_ENABLE(htmr); + } + } + else + { + __DAL_TMR_ENABLE(htmr); + } + } + + /* Return function status */ + return status; +} + +/** + * @brief Stops the TMR PWM signal generation in DMA mode on the complementary + * output + * @param htmr TMR handle + * @param Channel TMR Channel to be disabled + * This parameter can be one of the following values: + * @arg TMR_CHANNEL_1: TMR Channel 1 selected + * @arg TMR_CHANNEL_2: TMR Channel 2 selected + * @arg TMR_CHANNEL_3: TMR Channel 3 selected + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMREx_PWMN_Stop_DMA(TMR_HandleTypeDef *htmr, uint32_t Channel) +{ + DAL_StatusTypeDef status = DAL_OK; + + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_CCXN_INSTANCE(htmr->Instance, Channel)); + + switch (Channel) + { + case TMR_CHANNEL_1: + { + /* Disable the TMR Capture/Compare 1 DMA request */ + __DAL_TMR_DISABLE_DMA(htmr, TMR_DMA_CC1); + (void)DAL_DMA_Abort_IT(htmr->hdma[TMR_DMA_ID_CC1]); + break; + } + + case TMR_CHANNEL_2: + { + /* Disable the TMR Capture/Compare 2 DMA request */ + __DAL_TMR_DISABLE_DMA(htmr, TMR_DMA_CC2); + (void)DAL_DMA_Abort_IT(htmr->hdma[TMR_DMA_ID_CC2]); + break; + } + + case TMR_CHANNEL_3: + { + /* Disable the TMR Capture/Compare 3 DMA request */ + __DAL_TMR_DISABLE_DMA(htmr, TMR_DMA_CC3); + (void)DAL_DMA_Abort_IT(htmr->hdma[TMR_DMA_ID_CC3]); + break; + } + + default: + status = DAL_ERROR; + break; + } + + if (status == DAL_OK) + { + /* Disable the complementary PWM output */ + TMR_CCxNChannelCmd(htmr->Instance, Channel, TMR_CCxN_DISABLE); + + /* Disable the Main Output */ + __DAL_TMR_MOE_DISABLE(htmr); + + /* Disable the Peripheral */ + __DAL_TMR_DISABLE(htmr); + + /* Set the TMR complementary channel state */ + TMR_CHANNEL_N_STATE_SET(htmr, Channel, DAL_TMR_CHANNEL_STATE_READY); + } + + /* Return function status */ + return status; +} + +/** + * @} + */ + +/** @defgroup TMREx_Exported_Functions_Group4 Extended Timer Complementary One Pulse functions + * @brief Timer Complementary One Pulse functions + * +@verbatim + ============================================================================== + ##### Timer Complementary One Pulse functions ##### + ============================================================================== + [..] + This section provides functions allowing to: + (+) Start the Complementary One Pulse generation. + (+) Stop the Complementary One Pulse. + (+) Start the Complementary One Pulse and enable interrupts. + (+) Stop the Complementary One Pulse and disable interrupts. + +@endverbatim + * @{ + */ + +/** + * @brief Starts the TMR One Pulse signal generation on the complementary + * output. + * @note OutputChannel must match the pulse output channel chosen when calling + * @ref DAL_TMR_OnePulse_ConfigChannel(). + * @param htmr TMR One Pulse handle + * @param OutputChannel pulse output channel to enable + * This parameter can be one of the following values: + * @arg TMR_CHANNEL_1: TMR Channel 1 selected + * @arg TMR_CHANNEL_2: TMR Channel 2 selected + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMREx_OnePulseN_Start(TMR_HandleTypeDef *htmr, uint32_t OutputChannel) +{ + uint32_t input_channel = (OutputChannel == TMR_CHANNEL_1) ? TMR_CHANNEL_2 : TMR_CHANNEL_1; + DAL_TMR_ChannelStateTypeDef channel_1_state = TMR_CHANNEL_STATE_GET(htmr, TMR_CHANNEL_1); + DAL_TMR_ChannelStateTypeDef channel_2_state = TMR_CHANNEL_STATE_GET(htmr, TMR_CHANNEL_2); + DAL_TMR_ChannelStateTypeDef complementary_channel_1_state = TMR_CHANNEL_N_STATE_GET(htmr, TMR_CHANNEL_1); + DAL_TMR_ChannelStateTypeDef complementary_channel_2_state = TMR_CHANNEL_N_STATE_GET(htmr, TMR_CHANNEL_2); + + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_CCXN_INSTANCE(htmr->Instance, OutputChannel)); + + /* Check the TMR channels state */ + if ((channel_1_state != DAL_TMR_CHANNEL_STATE_READY) + || (channel_2_state != DAL_TMR_CHANNEL_STATE_READY) + || (complementary_channel_1_state != DAL_TMR_CHANNEL_STATE_READY) + || (complementary_channel_2_state != DAL_TMR_CHANNEL_STATE_READY)) + { + return DAL_ERROR; + } + + /* Set the TMR channels state */ + TMR_CHANNEL_STATE_SET(htmr, TMR_CHANNEL_1, DAL_TMR_CHANNEL_STATE_BUSY); + TMR_CHANNEL_STATE_SET(htmr, TMR_CHANNEL_2, DAL_TMR_CHANNEL_STATE_BUSY); + TMR_CHANNEL_N_STATE_SET(htmr, TMR_CHANNEL_1, DAL_TMR_CHANNEL_STATE_BUSY); + TMR_CHANNEL_N_STATE_SET(htmr, TMR_CHANNEL_2, DAL_TMR_CHANNEL_STATE_BUSY); + + /* Enable the complementary One Pulse output channel and the Input Capture channel */ + TMR_CCxNChannelCmd(htmr->Instance, OutputChannel, TMR_CCxN_ENABLE); + TMR_CCxChannelCmd(htmr->Instance, input_channel, TMR_CCx_ENABLE); + + /* Enable the Main Output */ + __DAL_TMR_MOE_ENABLE(htmr); + + /* Return function status */ + return DAL_OK; +} + +/** + * @brief Stops the TMR One Pulse signal generation on the complementary + * output. + * @note OutputChannel must match the pulse output channel chosen when calling + * @ref DAL_TMR_OnePulse_ConfigChannel(). + * @param htmr TMR One Pulse handle + * @param OutputChannel pulse output channel to disable + * This parameter can be one of the following values: + * @arg TMR_CHANNEL_1: TMR Channel 1 selected + * @arg TMR_CHANNEL_2: TMR Channel 2 selected + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMREx_OnePulseN_Stop(TMR_HandleTypeDef *htmr, uint32_t OutputChannel) +{ + uint32_t input_channel = (OutputChannel == TMR_CHANNEL_1) ? TMR_CHANNEL_2 : TMR_CHANNEL_1; + + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_CCXN_INSTANCE(htmr->Instance, OutputChannel)); + + /* Disable the complementary One Pulse output channel and the Input Capture channel */ + TMR_CCxNChannelCmd(htmr->Instance, OutputChannel, TMR_CCxN_DISABLE); + TMR_CCxChannelCmd(htmr->Instance, input_channel, TMR_CCx_DISABLE); + + /* Disable the Main Output */ + __DAL_TMR_MOE_DISABLE(htmr); + + /* Disable the Peripheral */ + __DAL_TMR_DISABLE(htmr); + + /* Set the TMR channels state */ + TMR_CHANNEL_STATE_SET(htmr, TMR_CHANNEL_1, DAL_TMR_CHANNEL_STATE_READY); + TMR_CHANNEL_STATE_SET(htmr, TMR_CHANNEL_2, DAL_TMR_CHANNEL_STATE_READY); + TMR_CHANNEL_N_STATE_SET(htmr, TMR_CHANNEL_1, DAL_TMR_CHANNEL_STATE_READY); + TMR_CHANNEL_N_STATE_SET(htmr, TMR_CHANNEL_2, DAL_TMR_CHANNEL_STATE_READY); + + /* Return function status */ + return DAL_OK; +} + +/** + * @brief Starts the TMR One Pulse signal generation in interrupt mode on the + * complementary channel. + * @note OutputChannel must match the pulse output channel chosen when calling + * @ref DAL_TMR_OnePulse_ConfigChannel(). + * @param htmr TMR One Pulse handle + * @param OutputChannel pulse output channel to enable + * This parameter can be one of the following values: + * @arg TMR_CHANNEL_1: TMR Channel 1 selected + * @arg TMR_CHANNEL_2: TMR Channel 2 selected + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMREx_OnePulseN_Start_IT(TMR_HandleTypeDef *htmr, uint32_t OutputChannel) +{ + uint32_t input_channel = (OutputChannel == TMR_CHANNEL_1) ? TMR_CHANNEL_2 : TMR_CHANNEL_1; + DAL_TMR_ChannelStateTypeDef channel_1_state = TMR_CHANNEL_STATE_GET(htmr, TMR_CHANNEL_1); + DAL_TMR_ChannelStateTypeDef channel_2_state = TMR_CHANNEL_STATE_GET(htmr, TMR_CHANNEL_2); + DAL_TMR_ChannelStateTypeDef complementary_channel_1_state = TMR_CHANNEL_N_STATE_GET(htmr, TMR_CHANNEL_1); + DAL_TMR_ChannelStateTypeDef complementary_channel_2_state = TMR_CHANNEL_N_STATE_GET(htmr, TMR_CHANNEL_2); + + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_CCXN_INSTANCE(htmr->Instance, OutputChannel)); + + /* Check the TMR channels state */ + if ((channel_1_state != DAL_TMR_CHANNEL_STATE_READY) + || (channel_2_state != DAL_TMR_CHANNEL_STATE_READY) + || (complementary_channel_1_state != DAL_TMR_CHANNEL_STATE_READY) + || (complementary_channel_2_state != DAL_TMR_CHANNEL_STATE_READY)) + { + return DAL_ERROR; + } + + /* Set the TMR channels state */ + TMR_CHANNEL_STATE_SET(htmr, TMR_CHANNEL_1, DAL_TMR_CHANNEL_STATE_BUSY); + TMR_CHANNEL_STATE_SET(htmr, TMR_CHANNEL_2, DAL_TMR_CHANNEL_STATE_BUSY); + TMR_CHANNEL_N_STATE_SET(htmr, TMR_CHANNEL_1, DAL_TMR_CHANNEL_STATE_BUSY); + TMR_CHANNEL_N_STATE_SET(htmr, TMR_CHANNEL_2, DAL_TMR_CHANNEL_STATE_BUSY); + + /* Enable the TMR Capture/Compare 1 interrupt */ + __DAL_TMR_ENABLE_IT(htmr, TMR_IT_CC1); + + /* Enable the TMR Capture/Compare 2 interrupt */ + __DAL_TMR_ENABLE_IT(htmr, TMR_IT_CC2); + + /* Enable the complementary One Pulse output channel and the Input Capture channel */ + TMR_CCxNChannelCmd(htmr->Instance, OutputChannel, TMR_CCxN_ENABLE); + TMR_CCxChannelCmd(htmr->Instance, input_channel, TMR_CCx_ENABLE); + + /* Enable the Main Output */ + __DAL_TMR_MOE_ENABLE(htmr); + + /* Return function status */ + return DAL_OK; +} + +/** + * @brief Stops the TMR One Pulse signal generation in interrupt mode on the + * complementary channel. + * @note OutputChannel must match the pulse output channel chosen when calling + * @ref DAL_TMR_OnePulse_ConfigChannel(). + * @param htmr TMR One Pulse handle + * @param OutputChannel pulse output channel to disable + * This parameter can be one of the following values: + * @arg TMR_CHANNEL_1: TMR Channel 1 selected + * @arg TMR_CHANNEL_2: TMR Channel 2 selected + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMREx_OnePulseN_Stop_IT(TMR_HandleTypeDef *htmr, uint32_t OutputChannel) +{ + uint32_t input_channel = (OutputChannel == TMR_CHANNEL_1) ? TMR_CHANNEL_2 : TMR_CHANNEL_1; + + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_CCXN_INSTANCE(htmr->Instance, OutputChannel)); + + /* Disable the TMR Capture/Compare 1 interrupt */ + __DAL_TMR_DISABLE_IT(htmr, TMR_IT_CC1); + + /* Disable the TMR Capture/Compare 2 interrupt */ + __DAL_TMR_DISABLE_IT(htmr, TMR_IT_CC2); + + /* Disable the complementary One Pulse output channel and the Input Capture channel */ + TMR_CCxNChannelCmd(htmr->Instance, OutputChannel, TMR_CCxN_DISABLE); + TMR_CCxChannelCmd(htmr->Instance, input_channel, TMR_CCx_DISABLE); + + /* Disable the Main Output */ + __DAL_TMR_MOE_DISABLE(htmr); + + /* Disable the Peripheral */ + __DAL_TMR_DISABLE(htmr); + + /* Set the TMR channels state */ + TMR_CHANNEL_STATE_SET(htmr, TMR_CHANNEL_1, DAL_TMR_CHANNEL_STATE_READY); + TMR_CHANNEL_STATE_SET(htmr, TMR_CHANNEL_2, DAL_TMR_CHANNEL_STATE_READY); + TMR_CHANNEL_N_STATE_SET(htmr, TMR_CHANNEL_1, DAL_TMR_CHANNEL_STATE_READY); + TMR_CHANNEL_N_STATE_SET(htmr, TMR_CHANNEL_2, DAL_TMR_CHANNEL_STATE_READY); + + /* Return function status */ + return DAL_OK; +} + +/** + * @} + */ + +/** @defgroup TMREx_Exported_Functions_Group5 Extended Peripheral Control functions + * @brief Peripheral Control functions + * +@verbatim + ============================================================================== + ##### Peripheral Control functions ##### + ============================================================================== + [..] + This section provides functions allowing to: + (+) Configure the commutation event in case of use of the Hall sensor interface. + (+) Configure Output channels for OC and PWM mode. + + (+) Configure Complementary channels, break features and dead time. + (+) Configure Master synchronization. + (+) Configure timer remapping capabilities. + +@endverbatim + * @{ + */ + +/** + * @brief Configure the TMR commutation event sequence. + * @note This function is mandatory to use the commutation event in order to + * update the configuration at each commutation detection on the TRGI input of the Timer, + * the typical use of this feature is with the use of another Timer(interface Timer) + * configured in Hall sensor interface, this interface Timer will generate the + * commutation at its TRGO output (connected to Timer used in this function) each time + * the TI1 of the Interface Timer detect a commutation at its input TI1. + * @param htmr TMR handle + * @param InputTrigger the Internal trigger corresponding to the Timer Interfacing with the Hall sensor + * This parameter can be one of the following values: + * @arg TMR_TS_ITR0: Internal trigger 0 selected + * @arg TMR_TS_ITR1: Internal trigger 1 selected + * @arg TMR_TS_ITR2: Internal trigger 2 selected + * @arg TMR_TS_ITR3: Internal trigger 3 selected + * @arg TMR_TS_NONE: No trigger is needed + * @param CommutationSource the Commutation Event source + * This parameter can be one of the following values: + * @arg TMR_COMMUTATION_TRGI: Commutation source is the TRGI of the Interface Timer + * @arg TMR_COMMUTATION_SOFTWARE: Commutation source is set by software using the COMG bit + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMREx_ConfigCommutEvent(TMR_HandleTypeDef *htmr, uint32_t InputTrigger, + uint32_t CommutationSource) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_COMMUTATION_EVENT_INSTANCE(htmr->Instance)); + ASSERT_PARAM(IS_TMR_INTERNAL_TRIGGEREVENT_SELECTION(InputTrigger)); + + __DAL_LOCK(htmr); + + if ((InputTrigger == TMR_TS_ITR0) || (InputTrigger == TMR_TS_ITR1) || + (InputTrigger == TMR_TS_ITR2) || (InputTrigger == TMR_TS_ITR3)) + { + /* Select the Input trigger */ + htmr->Instance->SMCTRL &= ~TMR_SMCTRL_TRGSEL; + htmr->Instance->SMCTRL |= InputTrigger; + } + + /* Select the Capture Compare preload feature */ + htmr->Instance->CTRL2 |= TMR_CTRL2_CCPEN; + /* Select the Commutation event source */ + htmr->Instance->CTRL2 &= ~TMR_CTRL2_CCUSEL; + htmr->Instance->CTRL2 |= CommutationSource; + + /* Disable Commutation Interrupt */ + __DAL_TMR_DISABLE_IT(htmr, TMR_IT_COM); + + /* Disable Commutation DMA request */ + __DAL_TMR_DISABLE_DMA(htmr, TMR_DMA_COM); + + __DAL_UNLOCK(htmr); + + return DAL_OK; +} + +/** + * @brief Configure the TMR commutation event sequence with interrupt. + * @note This function is mandatory to use the commutation event in order to + * update the configuration at each commutation detection on the TRGI input of the Timer, + * the typical use of this feature is with the use of another Timer(interface Timer) + * configured in Hall sensor interface, this interface Timer will generate the + * commutation at its TRGO output (connected to Timer used in this function) each time + * the TI1 of the Interface Timer detect a commutation at its input TI1. + * @param htmr TMR handle + * @param InputTrigger the Internal trigger corresponding to the Timer Interfacing with the Hall sensor + * This parameter can be one of the following values: + * @arg TMR_TS_ITR0: Internal trigger 0 selected + * @arg TMR_TS_ITR1: Internal trigger 1 selected + * @arg TMR_TS_ITR2: Internal trigger 2 selected + * @arg TMR_TS_ITR3: Internal trigger 3 selected + * @arg TMR_TS_NONE: No trigger is needed + * @param CommutationSource the Commutation Event source + * This parameter can be one of the following values: + * @arg TMR_COMMUTATION_TRGI: Commutation source is the TRGI of the Interface Timer + * @arg TMR_COMMUTATION_SOFTWARE: Commutation source is set by software using the COMG bit + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMREx_ConfigCommutEvent_IT(TMR_HandleTypeDef *htmr, uint32_t InputTrigger, + uint32_t CommutationSource) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_COMMUTATION_EVENT_INSTANCE(htmr->Instance)); + ASSERT_PARAM(IS_TMR_INTERNAL_TRIGGEREVENT_SELECTION(InputTrigger)); + + __DAL_LOCK(htmr); + + if ((InputTrigger == TMR_TS_ITR0) || (InputTrigger == TMR_TS_ITR1) || + (InputTrigger == TMR_TS_ITR2) || (InputTrigger == TMR_TS_ITR3)) + { + /* Select the Input trigger */ + htmr->Instance->SMCTRL &= ~TMR_SMCTRL_TRGSEL; + htmr->Instance->SMCTRL |= InputTrigger; + } + + /* Select the Capture Compare preload feature */ + htmr->Instance->CTRL2 |= TMR_CTRL2_CCPEN; + /* Select the Commutation event source */ + htmr->Instance->CTRL2 &= ~TMR_CTRL2_CCUSEL; + htmr->Instance->CTRL2 |= CommutationSource; + + /* Disable Commutation DMA request */ + __DAL_TMR_DISABLE_DMA(htmr, TMR_DMA_COM); + + /* Enable the Commutation Interrupt */ + __DAL_TMR_ENABLE_IT(htmr, TMR_IT_COM); + + __DAL_UNLOCK(htmr); + + return DAL_OK; +} + +/** + * @brief Configure the TMR commutation event sequence with DMA. + * @note This function is mandatory to use the commutation event in order to + * update the configuration at each commutation detection on the TRGI input of the Timer, + * the typical use of this feature is with the use of another Timer(interface Timer) + * configured in Hall sensor interface, this interface Timer will generate the + * commutation at its TRGO output (connected to Timer used in this function) each time + * the TI1 of the Interface Timer detect a commutation at its input TI1. + * @note The user should configure the DMA in his own software, in This function only the COMDE bit is set + * @param htmr TMR handle + * @param InputTrigger the Internal trigger corresponding to the Timer Interfacing with the Hall sensor + * This parameter can be one of the following values: + * @arg TMR_TS_ITR0: Internal trigger 0 selected + * @arg TMR_TS_ITR1: Internal trigger 1 selected + * @arg TMR_TS_ITR2: Internal trigger 2 selected + * @arg TMR_TS_ITR3: Internal trigger 3 selected + * @arg TMR_TS_NONE: No trigger is needed + * @param CommutationSource the Commutation Event source + * This parameter can be one of the following values: + * @arg TMR_COMMUTATION_TRGI: Commutation source is the TRGI of the Interface Timer + * @arg TMR_COMMUTATION_SOFTWARE: Commutation source is set by software using the COMG bit + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMREx_ConfigCommutEvent_DMA(TMR_HandleTypeDef *htmr, uint32_t InputTrigger, + uint32_t CommutationSource) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_COMMUTATION_EVENT_INSTANCE(htmr->Instance)); + ASSERT_PARAM(IS_TMR_INTERNAL_TRIGGEREVENT_SELECTION(InputTrigger)); + + __DAL_LOCK(htmr); + + if ((InputTrigger == TMR_TS_ITR0) || (InputTrigger == TMR_TS_ITR1) || + (InputTrigger == TMR_TS_ITR2) || (InputTrigger == TMR_TS_ITR3)) + { + /* Select the Input trigger */ + htmr->Instance->SMCTRL &= ~TMR_SMCTRL_TRGSEL; + htmr->Instance->SMCTRL |= InputTrigger; + } + + /* Select the Capture Compare preload feature */ + htmr->Instance->CTRL2 |= TMR_CTRL2_CCPEN; + /* Select the Commutation event source */ + htmr->Instance->CTRL2 &= ~TMR_CTRL2_CCUSEL; + htmr->Instance->CTRL2 |= CommutationSource; + + /* Enable the Commutation DMA Request */ + /* Set the DMA Commutation Callback */ + htmr->hdma[TMR_DMA_ID_COMMUTATION]->XferCpltCallback = TMREx_DMACommutationCplt; + htmr->hdma[TMR_DMA_ID_COMMUTATION]->XferHalfCpltCallback = TMREx_DMACommutationHalfCplt; + /* Set the DMA error callback */ + htmr->hdma[TMR_DMA_ID_COMMUTATION]->XferErrorCallback = TMR_DMAError; + + /* Disable Commutation Interrupt */ + __DAL_TMR_DISABLE_IT(htmr, TMR_IT_COM); + + /* Enable the Commutation DMA Request */ + __DAL_TMR_ENABLE_DMA(htmr, TMR_DMA_COM); + + __DAL_UNLOCK(htmr); + + return DAL_OK; +} + +/** + * @brief Configures the TMR in master mode. + * @param htmr TMR handle. + * @param sMasterConfig pointer to a TMR_MasterConfigTypeDef structure that + * contains the selected trigger output (TRGO) and the Master/Slave + * mode. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMREx_MasterConfigSynchronization(TMR_HandleTypeDef *htmr, + TMR_MasterConfigTypeDef *sMasterConfig) +{ + uint32_t tmpcr2; + uint32_t tmpsmcr; + + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_MASTER_INSTANCE(htmr->Instance)); + ASSERT_PARAM(IS_TMR_TRGO_SOURCE(sMasterConfig->MasterOutputTrigger)); + ASSERT_PARAM(IS_TMR_MSM_STATE(sMasterConfig->MasterSlaveMode)); + + /* Check input state */ + __DAL_LOCK(htmr); + + /* Change the handler state */ + htmr->State = DAL_TMR_STATE_BUSY; + + /* Get the TMRx CTRL2 register value */ + tmpcr2 = htmr->Instance->CTRL2; + + /* Get the TMRx SMCTRL register value */ + tmpsmcr = htmr->Instance->SMCTRL; + + /* Reset the MMS Bits */ + tmpcr2 &= ~TMR_CTRL2_MMSEL; + /* Select the TRGO source */ + tmpcr2 |= sMasterConfig->MasterOutputTrigger; + + /* Update TMRx CTRL2 */ + htmr->Instance->CTRL2 = tmpcr2; + + if (IS_TMR_SLAVE_INSTANCE(htmr->Instance)) + { + /* Reset the MSM Bit */ + tmpsmcr &= ~TMR_SMCTRL_MSMEN; + /* Set master mode */ + tmpsmcr |= sMasterConfig->MasterSlaveMode; + + /* Update TMRx SMCTRL */ + htmr->Instance->SMCTRL = tmpsmcr; + } + + /* Change the htmr state */ + htmr->State = DAL_TMR_STATE_READY; + + __DAL_UNLOCK(htmr); + + return DAL_OK; +} + +/** + * @brief Configures the Break feature, dead time, Lock level, OSSI/OSSR State + * and the AOE(automatic output enable). + * @param htmr TMR handle + * @param sBreakDeadTimeConfig pointer to a TMR_ConfigBreakDeadConfigTypeDef structure that + * contains the BDTR Register configuration information for the TMR peripheral. + * @note Interrupts can be generated when an active level is detected on the + * break input, the break 2 input or the system break input. Break + * interrupt can be enabled by calling the @ref __DAL_TMR_ENABLE_IT macro. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMREx_ConfigBreakDeadTime(TMR_HandleTypeDef *htmr, + TMR_BreakDeadTimeConfigTypeDef *sBreakDeadTimeConfig) +{ + /* Keep this variable initialized to 0 as it is used to configure BDTR register */ + uint32_t tmpbdtr = 0U; + + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_BREAK_INSTANCE(htmr->Instance)); + ASSERT_PARAM(IS_TMR_OSSR_STATE(sBreakDeadTimeConfig->OffStateRunMode)); + ASSERT_PARAM(IS_TMR_OSSI_STATE(sBreakDeadTimeConfig->OffStateIDLEMode)); + ASSERT_PARAM(IS_TMR_LOCK_LEVEL(sBreakDeadTimeConfig->LockLevel)); + ASSERT_PARAM(IS_TMR_DEADTIME(sBreakDeadTimeConfig->DeadTime)); + ASSERT_PARAM(IS_TMR_BREAK_STATE(sBreakDeadTimeConfig->BreakState)); + ASSERT_PARAM(IS_TMR_BREAK_POLARITY(sBreakDeadTimeConfig->BreakPolarity)); + ASSERT_PARAM(IS_TMR_AUTOMATIC_OUTPUT_STATE(sBreakDeadTimeConfig->AutomaticOutput)); + + /* Check input state */ + __DAL_LOCK(htmr); + + /* Set the Lock level, the Break enable Bit and the Polarity, the OSSR State, + the OSSI State, the dead time value and the Automatic Output Enable Bit */ + + /* Set the BDT bits */ + MODIFY_REG(tmpbdtr, TMR_BDT_DTS, sBreakDeadTimeConfig->DeadTime); + MODIFY_REG(tmpbdtr, TMR_BDT_LOCKCFG, sBreakDeadTimeConfig->LockLevel); + MODIFY_REG(tmpbdtr, TMR_BDT_IMOS, sBreakDeadTimeConfig->OffStateIDLEMode); + MODIFY_REG(tmpbdtr, TMR_BDT_RMOS, sBreakDeadTimeConfig->OffStateRunMode); + MODIFY_REG(tmpbdtr, TMR_BDT_BRKEN, sBreakDeadTimeConfig->BreakState); + MODIFY_REG(tmpbdtr, TMR_BDT_BRKPOL, sBreakDeadTimeConfig->BreakPolarity); + MODIFY_REG(tmpbdtr, TMR_BDT_AOEN, sBreakDeadTimeConfig->AutomaticOutput); + + + /* Set TMRx_BDT */ + htmr->Instance->BDT = tmpbdtr; + + __DAL_UNLOCK(htmr); + + return DAL_OK; +} + +/** + * @brief Configures the TMRx Remapping input capabilities. + * @param htmr TMR handle. + * @param Remap specifies the TMR remapping source. + * For TMR1, the parameter can have the following values: (**) + * @arg TMR_TMR1_TMR3_TRGO: TMR1 ITR2 is connected to TMR3 TRGO + * @arg TMR_TMR1_LPTMR: TMR1 ITR2 is connected to LPTMR1 output + * + * For TMR2, the parameter can have the following values: (**) + * @arg TMR_TMR2_TMR8_TRGO: TMR2 ITR1 is connected to TMR8 TRGO (*) + * @arg TMR_TMR2_ETH_PTP: TMR2 ITR1 is connected to PTP trigger output (*) + * @arg TMR_TMR2_USBFS_SOF: TMR2 ITR1 is connected to OTG FS SOF + * @arg TMR_TMR2_USBHS_SOF: TMR2 ITR1 is connected to OTG FS SOF + * + * For TMR5, the parameter can have the following values: + * @arg TMR_TMR5_GPIO: TMR5 TI4 is connected to GPIO + * @arg TMR_TMR5_LSI: TMR5 TI4 is connected to LSI + * @arg TMR_TMR5_LSE: TMR5 TI4 is connected to LSE + * @arg TMR_TMR5_RTC: TMR5 TI4 is connected to the RTC wakeup interrupt + * @arg TMR_TMR5_TMR3_TRGO: TMR5 ITR1 is connected to TMR3 TRGO (*) + * @arg TMR_TMR5_LPTMR: TMR5 ITR1 is connected to LPTMR1 output (*) + * + * For TMR9, the parameter can have the following values: (**) + * @arg TMR_TMR9_TMR3_TRGO: TMR9 ITR1 is connected to TMR3 TRGO + * @arg TMR_TMR9_LPTMR: TMR9 ITR1 is connected to LPTMR1 output + * + * For TMR11, the parameter can have the following values: + * @arg TMR_TMR11_GPIO: TMR11 TI1 is connected to GPIO + * @arg TMR_TMR11_HSE: TMR11 TI1 is connected to HSE_RTC clock + * @arg TMR_TMR11_SPDIFRX: TMR11 TI1 is connected to SPDIFRX_FRAME_SYNC (*) + * + * (*) Value not defined in all devices. \n + * (**) Register not available in all devices. + * + * @retval DAL status + */ +DAL_StatusTypeDef DAL_TMREx_RemapConfig(TMR_HandleTypeDef *htmr, uint32_t Remap) +{ + + /* Check parameters */ + ASSERT_PARAM(IS_TMR_REMAP(htmr->Instance, Remap)); + + __DAL_LOCK(htmr); + +#if defined(LPTMR_OR_TMR1_ITR2_RMP) && defined(LPTMR_OR_TMR5_ITR1_RMP) && defined(LPTMR_OR_TMR9_ITR1_RMP) + if ((Remap & LPTMR_REMAP_MASK) == LPTMR_REMAP_MASK) + { + /* Connect TMRx internal trigger to LPTMR1 output */ + __DAL_RCM_LPTMR1_CLK_ENABLE(); + MODIFY_REG(LPTMR1->OR, + (LPTMR_OR_TMR1_ITR2_RMP | LPTMR_OR_TMR5_ITR1_RMP | LPTMR_OR_TMR9_ITR1_RMP), + Remap & ~(LPTMR_REMAP_MASK)); + } + else + { + /* Set the Timer remapping configuration */ + WRITE_REG(htmr->Instance->OR, Remap); + } +#else + /* Set the Timer remapping configuration */ + WRITE_REG(htmr->Instance->OR, Remap); +#endif /* LPTMR_OR_TMR1_ITR2_RMP && LPTMR_OR_TMR5_ITR1_RMP && LPTMR_OR_TMR9_ITR1_RMP */ + + __DAL_UNLOCK(htmr); + + return DAL_OK; +} + +/** + * @} + */ + +/** @defgroup TMREx_Exported_Functions_Group6 Extended Callbacks functions + * @brief Extended Callbacks functions + * +@verbatim + ============================================================================== + ##### Extended Callbacks functions ##### + ============================================================================== + [..] + This section provides Extended TMR callback functions: + (+) Timer Commutation callback + (+) Timer Break callback + +@endverbatim + * @{ + */ + +/** + * @brief Hall commutation changed callback in non-blocking mode + * @param htmr TMR handle + * @retval None + */ +__weak void DAL_TMREx_CommutCallback(TMR_HandleTypeDef *htmr) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(htmr); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_TMREx_CommutCallback could be implemented in the user file + */ +} +/** + * @brief Hall commutation changed half complete callback in non-blocking mode + * @param htmr TMR handle + * @retval None + */ +__weak void DAL_TMREx_CommutHalfCpltCallback(TMR_HandleTypeDef *htmr) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(htmr); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_TMREx_CommutHalfCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Hall Break detection callback in non-blocking mode + * @param htmr TMR handle + * @retval None + */ +__weak void DAL_TMREx_BreakCallback(TMR_HandleTypeDef *htmr) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(htmr); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_TMREx_BreakCallback could be implemented in the user file + */ +} +/** + * @} + */ + +/** @defgroup TMREx_Exported_Functions_Group7 Extended Peripheral State functions + * @brief Extended Peripheral State functions + * +@verbatim + ============================================================================== + ##### Extended Peripheral State functions ##### + ============================================================================== + [..] + This subsection permits to get in run-time the status of the peripheral + and the data flow. + +@endverbatim + * @{ + */ + +/** + * @brief Return the TMR Hall Sensor interface handle state. + * @param htmr TMR Hall Sensor handle + * @retval DAL state + */ +DAL_TMR_StateTypeDef DAL_TMREx_HallSensor_GetState(TMR_HandleTypeDef *htmr) +{ + return htmr->State; +} + +/** + * @brief Return actual state of the TMR complementary channel. + * @param htmr TMR handle + * @param ChannelN TMR Complementary channel + * This parameter can be one of the following values: + * @arg TMR_CHANNEL_1: TMR Channel 1 + * @arg TMR_CHANNEL_2: TMR Channel 2 + * @arg TMR_CHANNEL_3: TMR Channel 3 + * @retval TMR Complementary channel state + */ +DAL_TMR_ChannelStateTypeDef DAL_TMREx_GetChannelNState(TMR_HandleTypeDef *htmr, uint32_t ChannelN) +{ + DAL_TMR_ChannelStateTypeDef channel_state; + + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_CCXN_INSTANCE(htmr->Instance, ChannelN)); + + channel_state = TMR_CHANNEL_N_STATE_GET(htmr, ChannelN); + + return channel_state; +} +/** + * @} + */ + +/** + * @} + */ + +/* Private functions ---------------------------------------------------------*/ +/** @defgroup TMREx_Private_Functions TMR Extended Private Functions + * @{ + */ + +/** + * @brief TMR DMA Commutation callback. + * @param hdma pointer to DMA handle. + * @retval None + */ +void TMREx_DMACommutationCplt(DMA_HandleTypeDef *hdma) +{ + TMR_HandleTypeDef *htmr = (TMR_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + + /* Change the htmr state */ + htmr->State = DAL_TMR_STATE_READY; + +#if (USE_DAL_TMR_REGISTER_CALLBACKS == 1) + htmr->CommutationCallback(htmr); +#else + DAL_TMREx_CommutCallback(htmr); +#endif /* USE_DAL_TMR_REGISTER_CALLBACKS */ +} + +/** + * @brief TMR DMA Commutation half complete callback. + * @param hdma pointer to DMA handle. + * @retval None + */ +void TMREx_DMACommutationHalfCplt(DMA_HandleTypeDef *hdma) +{ + TMR_HandleTypeDef *htmr = (TMR_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + + /* Change the htmr state */ + htmr->State = DAL_TMR_STATE_READY; + +#if (USE_DAL_TMR_REGISTER_CALLBACKS == 1) + htmr->CommutationHalfCpltCallback(htmr); +#else + DAL_TMREx_CommutHalfCpltCallback(htmr); +#endif /* USE_DAL_TMR_REGISTER_CALLBACKS */ +} + + +/** + * @brief TMR DMA Delay Pulse complete callback (complementary channel). + * @param hdma pointer to DMA handle. + * @retval None + */ +static void TMR_DMADelayPulseNCplt(DMA_HandleTypeDef *hdma) +{ + TMR_HandleTypeDef *htmr = (TMR_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + + if (hdma == htmr->hdma[TMR_DMA_ID_CC1]) + { + htmr->Channel = DAL_TMR_ACTIVE_CHANNEL_1; + + if (hdma->Init.Mode == DMA_NORMAL) + { + TMR_CHANNEL_N_STATE_SET(htmr, TMR_CHANNEL_1, DAL_TMR_CHANNEL_STATE_READY); + } + } + else if (hdma == htmr->hdma[TMR_DMA_ID_CC2]) + { + htmr->Channel = DAL_TMR_ACTIVE_CHANNEL_2; + + if (hdma->Init.Mode == DMA_NORMAL) + { + TMR_CHANNEL_N_STATE_SET(htmr, TMR_CHANNEL_2, DAL_TMR_CHANNEL_STATE_READY); + } + } + else if (hdma == htmr->hdma[TMR_DMA_ID_CC3]) + { + htmr->Channel = DAL_TMR_ACTIVE_CHANNEL_3; + + if (hdma->Init.Mode == DMA_NORMAL) + { + TMR_CHANNEL_N_STATE_SET(htmr, TMR_CHANNEL_3, DAL_TMR_CHANNEL_STATE_READY); + } + } + else if (hdma == htmr->hdma[TMR_DMA_ID_CC4]) + { + htmr->Channel = DAL_TMR_ACTIVE_CHANNEL_4; + + if (hdma->Init.Mode == DMA_NORMAL) + { + TMR_CHANNEL_N_STATE_SET(htmr, TMR_CHANNEL_4, DAL_TMR_CHANNEL_STATE_READY); + } + } + else + { + /* nothing to do */ + } + +#if (USE_DAL_TMR_REGISTER_CALLBACKS == 1) + htmr->PWM_PulseFinishedCallback(htmr); +#else + DAL_TMR_PWM_PulseFinishedCallback(htmr); +#endif /* USE_DAL_TMR_REGISTER_CALLBACKS */ + + htmr->Channel = DAL_TMR_ACTIVE_CHANNEL_CLEARED; +} + +/** + * @brief TMR DMA error callback (complementary channel) + * @param hdma pointer to DMA handle. + * @retval None + */ +static void TMR_DMAErrorCCxN(DMA_HandleTypeDef *hdma) +{ + TMR_HandleTypeDef *htmr = (TMR_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + + if (hdma == htmr->hdma[TMR_DMA_ID_CC1]) + { + htmr->Channel = DAL_TMR_ACTIVE_CHANNEL_1; + TMR_CHANNEL_N_STATE_SET(htmr, TMR_CHANNEL_1, DAL_TMR_CHANNEL_STATE_READY); + } + else if (hdma == htmr->hdma[TMR_DMA_ID_CC2]) + { + htmr->Channel = DAL_TMR_ACTIVE_CHANNEL_2; + TMR_CHANNEL_N_STATE_SET(htmr, TMR_CHANNEL_2, DAL_TMR_CHANNEL_STATE_READY); + } + else if (hdma == htmr->hdma[TMR_DMA_ID_CC3]) + { + htmr->Channel = DAL_TMR_ACTIVE_CHANNEL_3; + TMR_CHANNEL_N_STATE_SET(htmr, TMR_CHANNEL_3, DAL_TMR_CHANNEL_STATE_READY); + } + else + { + /* nothing to do */ + } + +#if (USE_DAL_TMR_REGISTER_CALLBACKS == 1) + htmr->ErrorCallback(htmr); +#else + DAL_TMR_ErrorCallback(htmr); +#endif /* USE_DAL_TMR_REGISTER_CALLBACKS */ + + htmr->Channel = DAL_TMR_ACTIVE_CHANNEL_CLEARED; +} + +/** + * @brief Enables or disables the TMR Capture Compare Channel xN. + * @param TMRx to select the TMR peripheral + * @param Channel specifies the TMR Channel + * This parameter can be one of the following values: + * @arg TMR_CHANNEL_1: TMR Channel 1 + * @arg TMR_CHANNEL_2: TMR Channel 2 + * @arg TMR_CHANNEL_3: TMR Channel 3 + * @param ChannelNState specifies the TMR Channel CCxNE bit new state. + * This parameter can be: TMR_CCxN_ENABLE or TMR_CCxN_Disable. + * @retval None + */ +static void TMR_CCxNChannelCmd(TMR_TypeDef *TMRx, uint32_t Channel, uint32_t ChannelNState) +{ + uint32_t tmp; + + tmp = TMR_CCEN_CC1NEN << (Channel & 0x1FU); /* 0x1FU = 31 bits max shift */ + + /* Reset the CCxNE Bit */ + TMRx->CCEN &= ~tmp; + + /* Set or reset the CCxNE Bit */ + TMRx->CCEN |= (uint32_t)(ChannelNState << (Channel & 0x1FU)); /* 0x1FU = 31 bits max shift */ +} +/** + * @} + */ + +#endif /* DAL_TMR_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_uart.c b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_uart.c new file mode 100644 index 0000000000..e39ee0016a --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_uart.c @@ -0,0 +1,3772 @@ +/** + * + * @file apm32f4xx_dal_uart.c + * @brief UART DAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the Universal Asynchronous Receiver Transmitter Peripheral (UART). + * + Initialization and de-initialization functions + * + IO operation functions + * + Peripheral Control functions + * + Peripheral State and Errors functions + * + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + * + @verbatim + ============================================================================== + ##### How to use this driver ##### + ============================================================================== + [..] + The UART DAL driver can be used as follows: + + (#) Declare a UART_HandleTypeDef handle structure (eg. UART_HandleTypeDef huart). + (#) Initialize the UART low level resources by implementing the DAL_UART_MspInit() API: + (##) Enable the USARTx interface clock. + (##) UART pins configuration: + (+++) Enable the clock for the UART GPIOs. + (+++) Configure the UART TX/RX pins as alternate function pull-up. + (##) NVIC configuration if you need to use interrupt process (DAL_UART_Transmit_IT() + and DAL_UART_Receive_IT() APIs): + (+++) Configure the USARTx interrupt priority. + (+++) Enable the NVIC USART IRQ handle. + (##) DMA Configuration if you need to use DMA process (DAL_UART_Transmit_DMA() + and DAL_UART_Receive_DMA() APIs): + (+++) Declare a DMA handle structure for the Tx/Rx stream. + (+++) Enable the DMAx interface clock. + (+++) Configure the declared DMA handle structure with the required + Tx/Rx parameters. + (+++) Configure the DMA Tx/Rx stream. + (+++) Associate the initialized DMA handle to the UART DMA Tx/Rx handle. + (+++) Configure the priority and enable the NVIC for the transfer complete + interrupt on the DMA Tx/Rx stream. + (+++) Configure the USARTx interrupt priority and enable the NVIC USART IRQ handle + (used for last byte sending completion detection in DMA non circular mode) + + (#) Program the Baud Rate, Word Length, Stop Bit, Parity, Hardware + flow control and Mode(Receiver/Transmitter) in the huart Init structure. + + (#) For the UART asynchronous mode, initialize the UART registers by calling + the DAL_UART_Init() API. + + (#) For the UART Half duplex mode, initialize the UART registers by calling + the DAL_HalfDuplex_Init() API. + + (#) For the LIN mode, initialize the UART registers by calling the DAL_LIN_Init() API. + + (#) For the Multi-Processor mode, initialize the UART registers by calling + the DAL_MultiProcessor_Init() API. + + [..] + (@) The specific UART interrupts (Transmission complete interrupt, + RXNE interrupt and Error Interrupts) will be managed using the macros + __DAL_UART_ENABLE_IT() and __DAL_UART_DISABLE_IT() inside the transmit + and receive process. + + [..] + (@) These APIs (DAL_UART_Init() and DAL_HalfDuplex_Init()) configure also the + low level Hardware GPIO, CLOCK, CORTEX...etc) by calling the customized + DAL_UART_MspInit() API. + + ##### Callback registration ##### + ================================== + + [..] + The compilation define USE_DAL_UART_REGISTER_CALLBACKS when set to 1 + allows the user to configure dynamically the driver callbacks. + + [..] + Use Function DAL_UART_RegisterCallback() to register a user callback. + Function DAL_UART_RegisterCallback() allows to register following callbacks: + (+) TxHalfCpltCallback : Tx Half Complete Callback. + (+) TxCpltCallback : Tx Complete Callback. + (+) RxHalfCpltCallback : Rx Half Complete Callback. + (+) RxCpltCallback : Rx Complete Callback. + (+) ErrorCallback : Error Callback. + (+) AbortCpltCallback : Abort Complete Callback. + (+) AbortTransmitCpltCallback : Abort Transmit Complete Callback. + (+) AbortReceiveCpltCallback : Abort Receive Complete Callback. + (+) MspInitCallback : UART MspInit. + (+) MspDeInitCallback : UART MspDeInit. + This function takes as parameters the DAL peripheral handle, the Callback ID + and a pointer to the user callback function. + + [..] + Use function DAL_UART_UnRegisterCallback() to reset a callback to the default + weak (surcharged) function. + DAL_UART_UnRegisterCallback() takes as parameters the DAL peripheral handle, + and the Callback ID. + This function allows to reset following callbacks: + (+) TxHalfCpltCallback : Tx Half Complete Callback. + (+) TxCpltCallback : Tx Complete Callback. + (+) RxHalfCpltCallback : Rx Half Complete Callback. + (+) RxCpltCallback : Rx Complete Callback. + (+) ErrorCallback : Error Callback. + (+) AbortCpltCallback : Abort Complete Callback. + (+) AbortTransmitCpltCallback : Abort Transmit Complete Callback. + (+) AbortReceiveCpltCallback : Abort Receive Complete Callback. + (+) MspInitCallback : UART MspInit. + (+) MspDeInitCallback : UART MspDeInit. + + [..] + For specific callback RxEventCallback, use dedicated registration/reset functions: + respectively DAL_UART_RegisterRxEventCallback() , DAL_UART_UnRegisterRxEventCallback(). + + [..] + By default, after the DAL_UART_Init() and when the state is DAL_UART_STATE_RESET + all callbacks are set to the corresponding weak (surcharged) functions: + examples DAL_UART_TxCpltCallback(), DAL_UART_RxHalfCpltCallback(). + Exception done for MspInit and MspDeInit functions that are respectively + reset to the legacy weak (surcharged) functions in the DAL_UART_Init() + and DAL_UART_DeInit() only when these callbacks are null (not registered beforehand). + If not, MspInit or MspDeInit are not null, the DAL_UART_Init() and DAL_UART_DeInit() + keep and use the user MspInit/MspDeInit callbacks (registered beforehand). + + [..] + Callbacks can be registered/unregistered in DAL_UART_STATE_READY state only. + Exception done MspInit/MspDeInit that can be registered/unregistered + in DAL_UART_STATE_READY or DAL_UART_STATE_RESET state, thus registered (user) + MspInit/DeInit callbacks can be used during the Init/DeInit. + In that case first register the MspInit/MspDeInit user callbacks + using DAL_UART_RegisterCallback() before calling DAL_UART_DeInit() + or DAL_UART_Init() function. + + [..] + When The compilation define USE_DAL_UART_REGISTER_CALLBACKS is set to 0 or + not defined, the callback registration feature is not available + and weak (surcharged) callbacks are used. + + [..] + Three operation modes are available within this driver : + + *** Polling mode IO operation *** + ================================= + [..] + (+) Send an amount of data in blocking mode using DAL_UART_Transmit() + (+) Receive an amount of data in blocking mode using DAL_UART_Receive() + + *** Interrupt mode IO operation *** + =================================== + [..] + (+) Send an amount of data in non blocking mode using DAL_UART_Transmit_IT() + (+) At transmission end of transfer DAL_UART_TxCpltCallback is executed and user can + add his own code by customization of function pointer DAL_UART_TxCpltCallback + (+) Receive an amount of data in non blocking mode using DAL_UART_Receive_IT() + (+) At reception end of transfer DAL_UART_RxCpltCallback is executed and user can + add his own code by customization of function pointer DAL_UART_RxCpltCallback + (+) In case of transfer Error, DAL_UART_ErrorCallback() function is executed and user can + add his own code by customization of function pointer DAL_UART_ErrorCallback + + *** DMA mode IO operation *** + ============================== + [..] + (+) Send an amount of data in non blocking mode (DMA) using DAL_UART_Transmit_DMA() + (+) At transmission end of half transfer DAL_UART_TxHalfCpltCallback is executed and user can + add his own code by customization of function pointer DAL_UART_TxHalfCpltCallback + (+) At transmission end of transfer DAL_UART_TxCpltCallback is executed and user can + add his own code by customization of function pointer DAL_UART_TxCpltCallback + (+) Receive an amount of data in non blocking mode (DMA) using DAL_UART_Receive_DMA() + (+) At reception end of half transfer DAL_UART_RxHalfCpltCallback is executed and user can + add his own code by customization of function pointer DAL_UART_RxHalfCpltCallback + (+) At reception end of transfer DAL_UART_RxCpltCallback is executed and user can + add his own code by customization of function pointer DAL_UART_RxCpltCallback + (+) In case of transfer Error, DAL_UART_ErrorCallback() function is executed and user can + add his own code by customization of function pointer DAL_UART_ErrorCallback + (+) Pause the DMA Transfer using DAL_UART_DMAPause() + (+) Resume the DMA Transfer using DAL_UART_DMAResume() + (+) Stop the DMA Transfer using DAL_UART_DMAStop() + + + [..] This subsection also provides a set of additional functions providing enhanced reception + services to user. (For example, these functions allow application to handle use cases + where number of data to be received is unknown). + + (#) Compared to standard reception services which only consider number of received + data elements as reception completion criteria, these functions also consider additional events + as triggers for updating reception status to caller : + (+) Detection of inactivity period (RX line has not been active for a given period). + (++) RX inactivity detected by IDLE event, i.e. RX line has been in idle state (normally high state) + for 1 frame time, after last received byte. + + (#) There are two mode of transfer: + (+) Blocking mode: The reception is performed in polling mode, until either expected number of data is received, + or till IDLE event occurs. Reception is handled only during function execution. + When function exits, no data reception could occur. DAL status and number of actually received data elements, + are returned by function after finishing transfer. + (+) Non-Blocking mode: The reception is performed using Interrupts or DMA. + These API's return the DAL status. + The end of the data processing will be indicated through the + dedicated UART IRQ when using Interrupt mode or the DMA IRQ when using DMA mode. + The DAL_UARTEx_RxEventCallback() user callback will be executed during Receive process + The DAL_UART_ErrorCallback()user callback will be executed when a reception error is detected. + + (#) Blocking mode API: + (+) DAL_UARTEx_ReceiveToIdle() + + (#) Non-Blocking mode API with Interrupt: + (+) DAL_UARTEx_ReceiveToIdle_IT() + + (#) Non-Blocking mode API with DMA: + (+) DAL_UARTEx_ReceiveToIdle_DMA() + + + *** UART DAL driver macros list *** + ============================================= + [..] + Below the list of most used macros in UART DAL driver. + + (+) __DAL_UART_ENABLE: Enable the UART peripheral + (+) __DAL_UART_DISABLE: Disable the UART peripheral + (+) __DAL_UART_GET_FLAG : Check whether the specified UART flag is set or not + (+) __DAL_UART_CLEAR_FLAG : Clear the specified UART pending flag + (+) __DAL_UART_ENABLE_IT: Enable the specified UART interrupt + (+) __DAL_UART_DISABLE_IT: Disable the specified UART interrupt + (+) __DAL_UART_GET_IT_SOURCE: Check whether the specified UART interrupt has occurred or not + + [..] + (@) You can refer to the UART DAL driver header file for more useful macros + + @endverbatim + [..] + (@) Additional remark: If the parity is enabled, then the MSB bit of the data written + in the data register is transmitted but is changed by the parity bit. + Depending on the frame length defined by the M bit (8-bits or 9-bits), + the possible UART frame formats are as listed in the following table: + +-------------------------------------------------------------+ + | M bit | PCE bit | UART frame | + |---------------------|---------------------------------------| + | 0 | 0 | | SB | 8 bit data | STB | | + |---------|-----------|---------------------------------------| + | 0 | 1 | | SB | 7 bit data | PB | STB | | + |---------|-----------|---------------------------------------| + | 1 | 0 | | SB | 9 bit data | STB | | + |---------|-----------|---------------------------------------| + | 1 | 1 | | SB | 8 bit data | PB | STB | | + +-------------------------------------------------------------+ + * + */ + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @defgroup UART UART + * @brief DAL UART module driver + * @{ + */ +#ifdef DAL_UART_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/** @addtogroup UART_Private_Constants + * @{ + */ +/** + * @} + */ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/** @addtogroup UART_Private_Functions UART Private Functions + * @{ + */ + +#if (USE_DAL_UART_REGISTER_CALLBACKS == 1) +void UART_InitCallbacksToDefault(UART_HandleTypeDef *huart); +#endif /* USE_DAL_UART_REGISTER_CALLBACKS */ +static void UART_EndTxTransfer(UART_HandleTypeDef *huart); +static void UART_EndRxTransfer(UART_HandleTypeDef *huart); +static void UART_DMATransmitCplt(DMA_HandleTypeDef *hdma); +static void UART_DMAReceiveCplt(DMA_HandleTypeDef *hdma); +static void UART_DMATxHalfCplt(DMA_HandleTypeDef *hdma); +static void UART_DMARxHalfCplt(DMA_HandleTypeDef *hdma); +static void UART_DMAError(DMA_HandleTypeDef *hdma); +static void UART_DMAAbortOnError(DMA_HandleTypeDef *hdma); +static void UART_DMATxAbortCallback(DMA_HandleTypeDef *hdma); +static void UART_DMARxAbortCallback(DMA_HandleTypeDef *hdma); +static void UART_DMATxOnlyAbortCallback(DMA_HandleTypeDef *hdma); +static void UART_DMARxOnlyAbortCallback(DMA_HandleTypeDef *hdma); +static DAL_StatusTypeDef UART_Transmit_IT(UART_HandleTypeDef *huart); +static DAL_StatusTypeDef UART_EndTransmit_IT(UART_HandleTypeDef *huart); +static DAL_StatusTypeDef UART_Receive_IT(UART_HandleTypeDef *huart); +static DAL_StatusTypeDef UART_WaitOnFlagUntilTimeout(UART_HandleTypeDef *huart, uint32_t Flag, FlagStatus Status, + uint32_t Tickstart, uint32_t Timeout); +static void UART_SetConfig(UART_HandleTypeDef *huart); + +/** + * @} + */ + +/* Exported functions ---------------------------------------------------------*/ +/** @defgroup UART_Exported_Functions UART Exported Functions + * @{ + */ + +/** @defgroup UART_Exported_Functions_Group1 Initialization and de-initialization functions + * @brief Initialization and Configuration functions + * +@verbatim + =============================================================================== + ##### Initialization and Configuration functions ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to initialize the USARTx or the UARTy + in asynchronous mode. + (+) For the asynchronous mode only these parameters can be configured: + (++) Baud Rate + (++) Word Length + (++) Stop Bit + (++) Parity: If the parity is enabled, then the MSB bit of the data written + in the data register is transmitted but is changed by the parity bit. + Depending on the frame length defined by the M bit (8-bits or 9-bits), + please refer to Reference manual for possible UART frame formats. + (++) Hardware flow control + (++) Receiver/transmitter modes + (++) Over Sampling Method + [..] + The DAL_UART_Init(), DAL_HalfDuplex_Init(), DAL_LIN_Init() and DAL_MultiProcessor_Init() APIs + follow respectively the UART asynchronous, UART Half duplex, LIN and Multi-Processor configuration + procedures (details for the procedures are available in reference manual). + +@endverbatim + * @{ + */ + +/** + * @brief Initializes the UART mode according to the specified parameters in + * the UART_InitTypeDef and create the associated handle. + * @param huart Pointer to a UART_HandleTypeDef structure that contains + * the configuration information for the specified UART module. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_UART_Init(UART_HandleTypeDef *huart) +{ + /* Check the UART handle allocation */ + if (huart == NULL) + { + return DAL_ERROR; + } + + /* Check the parameters */ + if (huart->Init.HwFlowCtl != UART_HWCONTROL_NONE) + { + /* The hardware flow control is available only for USART1, USART2, USART3 and USART6. + Except for APM32F446xx devices, that is available for USART1, USART2, USART3, USART6, UART4 and UART5. + */ + ASSERT_PARAM(IS_UART_HWFLOW_INSTANCE(huart->Instance)); + ASSERT_PARAM(IS_UART_HARDWARE_FLOW_CONTROL(huart->Init.HwFlowCtl)); + } + else + { + ASSERT_PARAM(IS_UART_INSTANCE(huart->Instance)); + } + ASSERT_PARAM(IS_UART_WORD_LENGTH(huart->Init.WordLength)); + ASSERT_PARAM(IS_UART_OVERSAMPLING(huart->Init.OverSampling)); + + if (huart->gState == DAL_UART_STATE_RESET) + { + /* Allocate lock resource and initialize it */ + huart->Lock = DAL_UNLOCKED; + +#if (USE_DAL_UART_REGISTER_CALLBACKS == 1) + UART_InitCallbacksToDefault(huart); + + if (huart->MspInitCallback == NULL) + { + huart->MspInitCallback = DAL_UART_MspInit; + } + + /* Init the low level hardware */ + huart->MspInitCallback(huart); +#else + /* Init the low level hardware : GPIO, CLOCK */ + DAL_UART_MspInit(huart); +#endif /* (USE_DAL_UART_REGISTER_CALLBACKS) */ + } + + huart->gState = DAL_UART_STATE_BUSY; + + /* Disable the peripheral */ + __DAL_UART_DISABLE(huart); + + /* Set the UART Communication parameters */ + UART_SetConfig(huart); + + /* In asynchronous mode, the following bits must be kept cleared: + - LINEN and CLKEN bits in the USART_CTRL2 register, + - SCEN, HDSEL and IREN bits in the USART_CTRL3 register.*/ + CLEAR_BIT(huart->Instance->CTRL2, (USART_CTRL2_LINMEN | USART_CTRL2_CLKEN)); + CLEAR_BIT(huart->Instance->CTRL3, (USART_CTRL3_SCEN | USART_CTRL3_HDEN | USART_CTRL3_IREN)); + + /* Enable the peripheral */ + __DAL_UART_ENABLE(huart); + + /* Initialize the UART state */ + huart->ErrorCode = DAL_UART_ERROR_NONE; + huart->gState = DAL_UART_STATE_READY; + huart->RxState = DAL_UART_STATE_READY; + + return DAL_OK; +} + +/** + * @brief Initializes the half-duplex mode according to the specified + * parameters in the UART_InitTypeDef and create the associated handle. + * @param huart Pointer to a UART_HandleTypeDef structure that contains + * the configuration information for the specified UART module. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_HalfDuplex_Init(UART_HandleTypeDef *huart) +{ + /* Check the UART handle allocation */ + if (huart == NULL) + { + return DAL_ERROR; + } + + /* Check the parameters */ + ASSERT_PARAM(IS_UART_HALFDUPLEX_INSTANCE(huart->Instance)); + ASSERT_PARAM(IS_UART_WORD_LENGTH(huart->Init.WordLength)); + ASSERT_PARAM(IS_UART_OVERSAMPLING(huart->Init.OverSampling)); + + if (huart->gState == DAL_UART_STATE_RESET) + { + /* Allocate lock resource and initialize it */ + huart->Lock = DAL_UNLOCKED; + +#if (USE_DAL_UART_REGISTER_CALLBACKS == 1) + UART_InitCallbacksToDefault(huart); + + if (huart->MspInitCallback == NULL) + { + huart->MspInitCallback = DAL_UART_MspInit; + } + + /* Init the low level hardware */ + huart->MspInitCallback(huart); +#else + /* Init the low level hardware : GPIO, CLOCK */ + DAL_UART_MspInit(huart); +#endif /* (USE_DAL_UART_REGISTER_CALLBACKS) */ + } + + huart->gState = DAL_UART_STATE_BUSY; + + /* Disable the peripheral */ + __DAL_UART_DISABLE(huart); + + /* Set the UART Communication parameters */ + UART_SetConfig(huart); + + /* In half-duplex mode, the following bits must be kept cleared: + - LINEN and CLKEN bits in the USART_CTRL2 register, + - SCEN and IREN bits in the USART_CTRL3 register.*/ + CLEAR_BIT(huart->Instance->CTRL2, (USART_CTRL2_LINMEN | USART_CTRL2_CLKEN)); + CLEAR_BIT(huart->Instance->CTRL3, (USART_CTRL3_IREN | USART_CTRL3_SCEN)); + + /* Enable the Half-Duplex mode by setting the HDSEL bit in the CTRL3 register */ + SET_BIT(huart->Instance->CTRL3, USART_CTRL3_HDEN); + + /* Enable the peripheral */ + __DAL_UART_ENABLE(huart); + + /* Initialize the UART state*/ + huart->ErrorCode = DAL_UART_ERROR_NONE; + huart->gState = DAL_UART_STATE_READY; + huart->RxState = DAL_UART_STATE_READY; + + return DAL_OK; +} + +/** + * @brief Initializes the LIN mode according to the specified + * parameters in the UART_InitTypeDef and create the associated handle. + * @param huart Pointer to a UART_HandleTypeDef structure that contains + * the configuration information for the specified UART module. + * @param BreakDetectLength Specifies the LIN break detection length. + * This parameter can be one of the following values: + * @arg UART_LINBREAKDETECTLENGTH_10B: 10-bit break detection + * @arg UART_LINBREAKDETECTLENGTH_11B: 11-bit break detection + * @retval DAL status + */ +DAL_StatusTypeDef DAL_LIN_Init(UART_HandleTypeDef *huart, uint32_t BreakDetectLength) +{ + /* Check the UART handle allocation */ + if (huart == NULL) + { + return DAL_ERROR; + } + + /* Check the LIN UART instance */ + ASSERT_PARAM(IS_UART_LIN_INSTANCE(huart->Instance)); + + /* Check the Break detection length parameter */ + ASSERT_PARAM(IS_UART_LIN_BREAK_DETECT_LENGTH(BreakDetectLength)); + ASSERT_PARAM(IS_UART_LIN_WORD_LENGTH(huart->Init.WordLength)); + ASSERT_PARAM(IS_UART_LIN_OVERSAMPLING(huart->Init.OverSampling)); + + if (huart->gState == DAL_UART_STATE_RESET) + { + /* Allocate lock resource and initialize it */ + huart->Lock = DAL_UNLOCKED; + +#if (USE_DAL_UART_REGISTER_CALLBACKS == 1) + UART_InitCallbacksToDefault(huart); + + if (huart->MspInitCallback == NULL) + { + huart->MspInitCallback = DAL_UART_MspInit; + } + + /* Init the low level hardware */ + huart->MspInitCallback(huart); +#else + /* Init the low level hardware : GPIO, CLOCK */ + DAL_UART_MspInit(huart); +#endif /* (USE_DAL_UART_REGISTER_CALLBACKS) */ + } + + huart->gState = DAL_UART_STATE_BUSY; + + /* Disable the peripheral */ + __DAL_UART_DISABLE(huart); + + /* Set the UART Communication parameters */ + UART_SetConfig(huart); + + /* In LIN mode, the following bits must be kept cleared: + - CLKEN bits in the USART_CTRL2 register, + - SCEN, HDSEL and IREN bits in the USART_CTRL3 register.*/ + CLEAR_BIT(huart->Instance->CTRL2, (USART_CTRL2_CLKEN)); + CLEAR_BIT(huart->Instance->CTRL3, (USART_CTRL3_HDEN | USART_CTRL3_IREN | USART_CTRL3_SCEN)); + + /* Enable the LIN mode by setting the LINEN bit in the CTRL2 register */ + SET_BIT(huart->Instance->CTRL2, USART_CTRL2_LINMEN); + + /* Set the USART LIN Break detection length. */ + CLEAR_BIT(huart->Instance->CTRL2, USART_CTRL2_LBDLCFG); + SET_BIT(huart->Instance->CTRL2, BreakDetectLength); + + /* Enable the peripheral */ + __DAL_UART_ENABLE(huart); + + /* Initialize the UART state*/ + huart->ErrorCode = DAL_UART_ERROR_NONE; + huart->gState = DAL_UART_STATE_READY; + huart->RxState = DAL_UART_STATE_READY; + + return DAL_OK; +} + +/** + * @brief Initializes the Multi-Processor mode according to the specified + * parameters in the UART_InitTypeDef and create the associated handle. + * @param huart Pointer to a UART_HandleTypeDef structure that contains + * the configuration information for the specified UART module. + * @param Address USART address + * @param WakeUpMethod specifies the USART wake-up method. + * This parameter can be one of the following values: + * @arg UART_WAKEUPMETHOD_IDLELINE: Wake-up by an idle line detection + * @arg UART_WAKEUPMETHOD_ADDRESSMARK: Wake-up by an address mark + * @retval DAL status + */ +DAL_StatusTypeDef DAL_MultiProcessor_Init(UART_HandleTypeDef *huart, uint8_t Address, uint32_t WakeUpMethod) +{ + /* Check the UART handle allocation */ + if (huart == NULL) + { + return DAL_ERROR; + } + + /* Check the parameters */ + ASSERT_PARAM(IS_UART_INSTANCE(huart->Instance)); + + /* Check the Address & wake up method parameters */ + ASSERT_PARAM(IS_UART_WAKEUPMETHOD(WakeUpMethod)); + ASSERT_PARAM(IS_UART_ADDRESS(Address)); + ASSERT_PARAM(IS_UART_WORD_LENGTH(huart->Init.WordLength)); + ASSERT_PARAM(IS_UART_OVERSAMPLING(huart->Init.OverSampling)); + + if (huart->gState == DAL_UART_STATE_RESET) + { + /* Allocate lock resource and initialize it */ + huart->Lock = DAL_UNLOCKED; + +#if (USE_DAL_UART_REGISTER_CALLBACKS == 1) + UART_InitCallbacksToDefault(huart); + + if (huart->MspInitCallback == NULL) + { + huart->MspInitCallback = DAL_UART_MspInit; + } + + /* Init the low level hardware */ + huart->MspInitCallback(huart); +#else + /* Init the low level hardware : GPIO, CLOCK */ + DAL_UART_MspInit(huart); +#endif /* (USE_DAL_UART_REGISTER_CALLBACKS) */ + } + + huart->gState = DAL_UART_STATE_BUSY; + + /* Disable the peripheral */ + __DAL_UART_DISABLE(huart); + + /* Set the UART Communication parameters */ + UART_SetConfig(huart); + + /* In Multi-Processor mode, the following bits must be kept cleared: + - LINEN and CLKEN bits in the USART_CTRL2 register, + - SCEN, HDSEL and IREN bits in the USART_CTRL3 register */ + CLEAR_BIT(huart->Instance->CTRL2, (USART_CTRL2_LINMEN | USART_CTRL2_CLKEN)); + CLEAR_BIT(huart->Instance->CTRL3, (USART_CTRL3_SCEN | USART_CTRL3_HDEN | USART_CTRL3_IREN)); + + /* Set the USART address node */ + CLEAR_BIT(huart->Instance->CTRL2, USART_CTRL2_ADDR); + SET_BIT(huart->Instance->CTRL2, Address); + + /* Set the wake up method by setting the WAKE bit in the CTRL1 register */ + CLEAR_BIT(huart->Instance->CTRL1, USART_CTRL1_WUPMCFG); + SET_BIT(huart->Instance->CTRL1, WakeUpMethod); + + /* Enable the peripheral */ + __DAL_UART_ENABLE(huart); + + /* Initialize the UART state */ + huart->ErrorCode = DAL_UART_ERROR_NONE; + huart->gState = DAL_UART_STATE_READY; + huart->RxState = DAL_UART_STATE_READY; + + return DAL_OK; +} + +/** + * @brief DeInitializes the UART peripheral. + * @param huart Pointer to a UART_HandleTypeDef structure that contains + * the configuration information for the specified UART module. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_UART_DeInit(UART_HandleTypeDef *huart) +{ + /* Check the UART handle allocation */ + if (huart == NULL) + { + return DAL_ERROR; + } + + /* Check the parameters */ + ASSERT_PARAM(IS_UART_INSTANCE(huart->Instance)); + + huart->gState = DAL_UART_STATE_BUSY; + + /* Disable the Peripheral */ + __DAL_UART_DISABLE(huart); + +#if (USE_DAL_UART_REGISTER_CALLBACKS == 1) + if (huart->MspDeInitCallback == NULL) + { + huart->MspDeInitCallback = DAL_UART_MspDeInit; + } + /* DeInit the low level hardware */ + huart->MspDeInitCallback(huart); +#else + /* DeInit the low level hardware */ + DAL_UART_MspDeInit(huart); +#endif /* (USE_DAL_UART_REGISTER_CALLBACKS) */ + + huart->ErrorCode = DAL_UART_ERROR_NONE; + huart->gState = DAL_UART_STATE_RESET; + huart->RxState = DAL_UART_STATE_RESET; + huart->ReceptionType = DAL_UART_RECEPTION_STANDARD; + + /* Process Unlock */ + __DAL_UNLOCK(huart); + + return DAL_OK; +} + +/** + * @brief UART MSP Init. + * @param huart Pointer to a UART_HandleTypeDef structure that contains + * the configuration information for the specified UART module. + * @retval None + */ +__weak void DAL_UART_MspInit(UART_HandleTypeDef *huart) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(huart); + /* NOTE: This function should not be modified, when the callback is needed, + the DAL_UART_MspInit could be implemented in the user file + */ +} + +/** + * @brief UART MSP DeInit. + * @param huart Pointer to a UART_HandleTypeDef structure that contains + * the configuration information for the specified UART module. + * @retval None + */ +__weak void DAL_UART_MspDeInit(UART_HandleTypeDef *huart) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(huart); + /* NOTE: This function should not be modified, when the callback is needed, + the DAL_UART_MspDeInit could be implemented in the user file + */ +} + +#if (USE_DAL_UART_REGISTER_CALLBACKS == 1) +/** + * @brief Register a User UART Callback + * To be used instead of the weak predefined callback + * @param huart uart handle + * @param CallbackID ID of the callback to be registered + * This parameter can be one of the following values: + * @arg @ref DAL_UART_TX_HALFCOMPLETE_CB_ID Tx Half Complete Callback ID + * @arg @ref DAL_UART_TX_COMPLETE_CB_ID Tx Complete Callback ID + * @arg @ref DAL_UART_RX_HALFCOMPLETE_CB_ID Rx Half Complete Callback ID + * @arg @ref DAL_UART_RX_COMPLETE_CB_ID Rx Complete Callback ID + * @arg @ref DAL_UART_ERROR_CB_ID Error Callback ID + * @arg @ref DAL_UART_ABORT_COMPLETE_CB_ID Abort Complete Callback ID + * @arg @ref DAL_UART_ABORT_TRANSMIT_COMPLETE_CB_ID Abort Transmit Complete Callback ID + * @arg @ref DAL_UART_ABORT_RECEIVE_COMPLETE_CB_ID Abort Receive Complete Callback ID + * @arg @ref DAL_UART_MSPINIT_CB_ID MspInit Callback ID + * @arg @ref DAL_UART_MSPDEINIT_CB_ID MspDeInit Callback ID + * @param pCallback pointer to the Callback function + * @retval DAL status + */ +DAL_StatusTypeDef DAL_UART_RegisterCallback(UART_HandleTypeDef *huart, DAL_UART_CallbackIDTypeDef CallbackID, + pUART_CallbackTypeDef pCallback) +{ + DAL_StatusTypeDef status = DAL_OK; + + if (pCallback == NULL) + { + /* Update the error code */ + huart->ErrorCode |= DAL_UART_ERROR_INVALID_CALLBACK; + + return DAL_ERROR; + } + /* Process locked */ + __DAL_LOCK(huart); + + if (huart->gState == DAL_UART_STATE_READY) + { + switch (CallbackID) + { + case DAL_UART_TX_HALFCOMPLETE_CB_ID : + huart->TxHalfCpltCallback = pCallback; + break; + + case DAL_UART_TX_COMPLETE_CB_ID : + huart->TxCpltCallback = pCallback; + break; + + case DAL_UART_RX_HALFCOMPLETE_CB_ID : + huart->RxHalfCpltCallback = pCallback; + break; + + case DAL_UART_RX_COMPLETE_CB_ID : + huart->RxCpltCallback = pCallback; + break; + + case DAL_UART_ERROR_CB_ID : + huart->ErrorCallback = pCallback; + break; + + case DAL_UART_ABORT_COMPLETE_CB_ID : + huart->AbortCpltCallback = pCallback; + break; + + case DAL_UART_ABORT_TRANSMIT_COMPLETE_CB_ID : + huart->AbortTransmitCpltCallback = pCallback; + break; + + case DAL_UART_ABORT_RECEIVE_COMPLETE_CB_ID : + huart->AbortReceiveCpltCallback = pCallback; + break; + + case DAL_UART_MSPINIT_CB_ID : + huart->MspInitCallback = pCallback; + break; + + case DAL_UART_MSPDEINIT_CB_ID : + huart->MspDeInitCallback = pCallback; + break; + + default : + /* Update the error code */ + huart->ErrorCode |= DAL_UART_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = DAL_ERROR; + break; + } + } + else if (huart->gState == DAL_UART_STATE_RESET) + { + switch (CallbackID) + { + case DAL_UART_MSPINIT_CB_ID : + huart->MspInitCallback = pCallback; + break; + + case DAL_UART_MSPDEINIT_CB_ID : + huart->MspDeInitCallback = pCallback; + break; + + default : + /* Update the error code */ + huart->ErrorCode |= DAL_UART_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = DAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + huart->ErrorCode |= DAL_UART_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = DAL_ERROR; + } + + /* Release Lock */ + __DAL_UNLOCK(huart); + + return status; +} + +/** + * @brief Unregister an UART Callback + * UART callaback is redirected to the weak predefined callback + * @param huart uart handle + * @param CallbackID ID of the callback to be unregistered + * This parameter can be one of the following values: + * @arg @ref DAL_UART_TX_HALFCOMPLETE_CB_ID Tx Half Complete Callback ID + * @arg @ref DAL_UART_TX_COMPLETE_CB_ID Tx Complete Callback ID + * @arg @ref DAL_UART_RX_HALFCOMPLETE_CB_ID Rx Half Complete Callback ID + * @arg @ref DAL_UART_RX_COMPLETE_CB_ID Rx Complete Callback ID + * @arg @ref DAL_UART_ERROR_CB_ID Error Callback ID + * @arg @ref DAL_UART_ABORT_COMPLETE_CB_ID Abort Complete Callback ID + * @arg @ref DAL_UART_ABORT_TRANSMIT_COMPLETE_CB_ID Abort Transmit Complete Callback ID + * @arg @ref DAL_UART_ABORT_RECEIVE_COMPLETE_CB_ID Abort Receive Complete Callback ID + * @arg @ref DAL_UART_MSPINIT_CB_ID MspInit Callback ID + * @arg @ref DAL_UART_MSPDEINIT_CB_ID MspDeInit Callback ID + * @retval DAL status + */ +DAL_StatusTypeDef DAL_UART_UnRegisterCallback(UART_HandleTypeDef *huart, DAL_UART_CallbackIDTypeDef CallbackID) +{ + DAL_StatusTypeDef status = DAL_OK; + + /* Process locked */ + __DAL_LOCK(huart); + + if (DAL_UART_STATE_READY == huart->gState) + { + switch (CallbackID) + { + case DAL_UART_TX_HALFCOMPLETE_CB_ID : + huart->TxHalfCpltCallback = DAL_UART_TxHalfCpltCallback; /* Legacy weak TxHalfCpltCallback */ + break; + + case DAL_UART_TX_COMPLETE_CB_ID : + huart->TxCpltCallback = DAL_UART_TxCpltCallback; /* Legacy weak TxCpltCallback */ + break; + + case DAL_UART_RX_HALFCOMPLETE_CB_ID : + huart->RxHalfCpltCallback = DAL_UART_RxHalfCpltCallback; /* Legacy weak RxHalfCpltCallback */ + break; + + case DAL_UART_RX_COMPLETE_CB_ID : + huart->RxCpltCallback = DAL_UART_RxCpltCallback; /* Legacy weak RxCpltCallback */ + break; + + case DAL_UART_ERROR_CB_ID : + huart->ErrorCallback = DAL_UART_ErrorCallback; /* Legacy weak ErrorCallback */ + break; + + case DAL_UART_ABORT_COMPLETE_CB_ID : + huart->AbortCpltCallback = DAL_UART_AbortCpltCallback; /* Legacy weak AbortCpltCallback */ + break; + + case DAL_UART_ABORT_TRANSMIT_COMPLETE_CB_ID : + huart->AbortTransmitCpltCallback = DAL_UART_AbortTransmitCpltCallback; /* Legacy weak AbortTransmitCpltCallback */ + break; + + case DAL_UART_ABORT_RECEIVE_COMPLETE_CB_ID : + huart->AbortReceiveCpltCallback = DAL_UART_AbortReceiveCpltCallback; /* Legacy weak AbortReceiveCpltCallback */ + break; + + case DAL_UART_MSPINIT_CB_ID : + huart->MspInitCallback = DAL_UART_MspInit; /* Legacy weak MspInitCallback */ + break; + + case DAL_UART_MSPDEINIT_CB_ID : + huart->MspDeInitCallback = DAL_UART_MspDeInit; /* Legacy weak MspDeInitCallback */ + break; + + default : + /* Update the error code */ + huart->ErrorCode |= DAL_UART_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = DAL_ERROR; + break; + } + } + else if (DAL_UART_STATE_RESET == huart->gState) + { + switch (CallbackID) + { + case DAL_UART_MSPINIT_CB_ID : + huart->MspInitCallback = DAL_UART_MspInit; + break; + + case DAL_UART_MSPDEINIT_CB_ID : + huart->MspDeInitCallback = DAL_UART_MspDeInit; + break; + + default : + /* Update the error code */ + huart->ErrorCode |= DAL_UART_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = DAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + huart->ErrorCode |= DAL_UART_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = DAL_ERROR; + } + + /* Release Lock */ + __DAL_UNLOCK(huart); + + return status; +} + +/** + * @brief Register a User UART Rx Event Callback + * To be used instead of the weak predefined callback + * @param huart Uart handle + * @param pCallback Pointer to the Rx Event Callback function + * @retval DAL status + */ +DAL_StatusTypeDef DAL_UART_RegisterRxEventCallback(UART_HandleTypeDef *huart, pUART_RxEventCallbackTypeDef pCallback) +{ + DAL_StatusTypeDef status = DAL_OK; + + if (pCallback == NULL) + { + huart->ErrorCode |= DAL_UART_ERROR_INVALID_CALLBACK; + + return DAL_ERROR; + } + + /* Process locked */ + __DAL_LOCK(huart); + + if (huart->gState == DAL_UART_STATE_READY) + { + huart->RxEventCallback = pCallback; + } + else + { + huart->ErrorCode |= DAL_UART_ERROR_INVALID_CALLBACK; + + status = DAL_ERROR; + } + + /* Release Lock */ + __DAL_UNLOCK(huart); + + return status; +} + +/** + * @brief UnRegister the UART Rx Event Callback + * UART Rx Event Callback is redirected to the weak DAL_UARTEx_RxEventCallback() predefined callback + * @param huart Uart handle + * @retval DAL status + */ +DAL_StatusTypeDef DAL_UART_UnRegisterRxEventCallback(UART_HandleTypeDef *huart) +{ + DAL_StatusTypeDef status = DAL_OK; + + /* Process locked */ + __DAL_LOCK(huart); + + if (huart->gState == DAL_UART_STATE_READY) + { + huart->RxEventCallback = DAL_UARTEx_RxEventCallback; /* Legacy weak UART Rx Event Callback */ + } + else + { + huart->ErrorCode |= DAL_UART_ERROR_INVALID_CALLBACK; + + status = DAL_ERROR; + } + + /* Release Lock */ + __DAL_UNLOCK(huart); + return status; +} +#endif /* USE_DAL_UART_REGISTER_CALLBACKS */ + +/** + * @} + */ + +/** @defgroup UART_Exported_Functions_Group2 IO operation functions + * @brief UART Transmit and Receive functions + * +@verbatim + =============================================================================== + ##### IO operation functions ##### + =============================================================================== + This subsection provides a set of functions allowing to manage the UART asynchronous + and Half duplex data transfers. + + (#) There are two modes of transfer: + (+) Blocking mode: The communication is performed in polling mode. + The DAL status of all data processing is returned by the same function + after finishing transfer. + (+) Non-Blocking mode: The communication is performed using Interrupts + or DMA, these API's return the DAL status. + The end of the data processing will be indicated through the + dedicated UART IRQ when using Interrupt mode or the DMA IRQ when + using DMA mode. + The DAL_UART_TxCpltCallback(), DAL_UART_RxCpltCallback() user callbacks + will be executed respectively at the end of the transmit or receive process + The DAL_UART_ErrorCallback()user callback will be executed when a communication error is detected. + + (#) Blocking mode API's are : + (+) DAL_UART_Transmit() + (+) DAL_UART_Receive() + + (#) Non-Blocking mode API's with Interrupt are : + (+) DAL_UART_Transmit_IT() + (+) DAL_UART_Receive_IT() + (+) DAL_UART_IRQHandler() + + (#) Non-Blocking mode API's with DMA are : + (+) DAL_UART_Transmit_DMA() + (+) DAL_UART_Receive_DMA() + (+) DAL_UART_DMAPause() + (+) DAL_UART_DMAResume() + (+) DAL_UART_DMAStop() + + (#) A set of Transfer Complete Callbacks are provided in Non_Blocking mode: + (+) DAL_UART_TxHalfCpltCallback() + (+) DAL_UART_TxCpltCallback() + (+) DAL_UART_RxHalfCpltCallback() + (+) DAL_UART_RxCpltCallback() + (+) DAL_UART_ErrorCallback() + + (#) Non-Blocking mode transfers could be aborted using Abort API's : + (+) DAL_UART_Abort() + (+) DAL_UART_AbortTransmit() + (+) DAL_UART_AbortReceive() + (+) DAL_UART_Abort_IT() + (+) DAL_UART_AbortTransmit_IT() + (+) DAL_UART_AbortReceive_IT() + + (#) For Abort services based on interrupts (DAL_UART_Abortxxx_IT), a set of Abort Complete Callbacks are provided: + (+) DAL_UART_AbortCpltCallback() + (+) DAL_UART_AbortTransmitCpltCallback() + (+) DAL_UART_AbortReceiveCpltCallback() + + (#) A Rx Event Reception Callback (Rx event notification) is available for Non_Blocking modes of enhanced reception services: + (+) DAL_UARTEx_RxEventCallback() + + (#) In Non-Blocking mode transfers, possible errors are split into 2 categories. + Errors are handled as follows : + (+) Error is considered as Recoverable and non blocking : Transfer could go till end, but error severity is + to be evaluated by user : this concerns Frame Error, Parity Error or Noise Error in Interrupt mode reception . + Received character is then retrieved and stored in Rx buffer, Error code is set to allow user to identify error type, + and DAL_UART_ErrorCallback() user callback is executed. Transfer is kept ongoing on UART side. + If user wants to abort it, Abort services should be called by user. + (+) Error is considered as Blocking : Transfer could not be completed properly and is aborted. + This concerns Overrun Error In Interrupt mode reception and all errors in DMA mode. + Error code is set to allow user to identify error type, and DAL_UART_ErrorCallback() user callback is executed. + + -@- In the Half duplex communication, it is forbidden to run the transmit + and receive process in parallel, the UART state DAL_UART_STATE_BUSY_TX_RX can't be useful. + +@endverbatim + * @{ + */ + +/** + * @brief Sends an amount of data in blocking mode. + * @note When UART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), + * the sent data is handled as a set of u16. In this case, Size must indicate the number + * of u16 provided through pData. + * @param huart Pointer to a UART_HandleTypeDef structure that contains + * the configuration information for the specified UART module. + * @param pData Pointer to data buffer (u8 or u16 data elements). + * @param Size Amount of data elements (u8 or u16) to be sent + * @param Timeout Timeout duration + * @retval DAL status + */ +DAL_StatusTypeDef DAL_UART_Transmit(UART_HandleTypeDef *huart, const uint8_t *pData, uint16_t Size, uint32_t Timeout) +{ + const uint8_t *pdata8bits; + const uint16_t *pdata16bits; + uint32_t tickstart = 0U; + + /* Check that a Tx process is not already ongoing */ + if (huart->gState == DAL_UART_STATE_READY) + { + if ((pData == NULL) || (Size == 0U)) + { + return DAL_ERROR; + } + + /* Process Locked */ + __DAL_LOCK(huart); + + huart->ErrorCode = DAL_UART_ERROR_NONE; + huart->gState = DAL_UART_STATE_BUSY_TX; + + /* Init tickstart for timeout management */ + tickstart = DAL_GetTick(); + + huart->TxXferSize = Size; + huart->TxXferCount = Size; + + /* In case of 9bits/No Parity transfer, pData needs to be handled as a uint16_t pointer */ + if ((huart->Init.WordLength == UART_WORDLENGTH_9B) && (huart->Init.Parity == UART_PARITY_NONE)) + { + pdata8bits = NULL; + pdata16bits = (const uint16_t *) pData; + } + else + { + pdata8bits = pData; + pdata16bits = NULL; + } + + /* Process Unlocked */ + __DAL_UNLOCK(huart); + + while (huart->TxXferCount > 0U) + { + if (UART_WaitOnFlagUntilTimeout(huart, UART_FLAG_TXE, RESET, tickstart, Timeout) != DAL_OK) + { + return DAL_TIMEOUT; + } + if (pdata8bits == NULL) + { + huart->Instance->DATA = (uint16_t)(*pdata16bits & 0x01FFU); + pdata16bits++; + } + else + { + huart->Instance->DATA = (uint8_t)(*pdata8bits & 0xFFU); + pdata8bits++; + } + huart->TxXferCount--; + } + + if (UART_WaitOnFlagUntilTimeout(huart, UART_FLAG_TC, RESET, tickstart, Timeout) != DAL_OK) + { + return DAL_TIMEOUT; + } + + /* At end of Tx process, restore huart->gState to Ready */ + huart->gState = DAL_UART_STATE_READY; + + return DAL_OK; + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief Receives an amount of data in blocking mode. + * @note When UART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), + * the received data is handled as a set of u16. In this case, Size must indicate the number + * of u16 available through pData. + * @param huart Pointer to a UART_HandleTypeDef structure that contains + * the configuration information for the specified UART module. + * @param pData Pointer to data buffer (u8 or u16 data elements). + * @param Size Amount of data elements (u8 or u16) to be received. + * @param Timeout Timeout duration + * @retval DAL status + */ +DAL_StatusTypeDef DAL_UART_Receive(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size, uint32_t Timeout) +{ + uint8_t *pdata8bits; + uint16_t *pdata16bits; + uint32_t tickstart = 0U; + + /* Check that a Rx process is not already ongoing */ + if (huart->RxState == DAL_UART_STATE_READY) + { + if ((pData == NULL) || (Size == 0U)) + { + return DAL_ERROR; + } + + /* Process Locked */ + __DAL_LOCK(huart); + + huart->ErrorCode = DAL_UART_ERROR_NONE; + huart->RxState = DAL_UART_STATE_BUSY_RX; + huart->ReceptionType = DAL_UART_RECEPTION_STANDARD; + + /* Init tickstart for timeout management */ + tickstart = DAL_GetTick(); + + huart->RxXferSize = Size; + huart->RxXferCount = Size; + + /* In case of 9bits/No Parity transfer, pRxData needs to be handled as a uint16_t pointer */ + if ((huart->Init.WordLength == UART_WORDLENGTH_9B) && (huart->Init.Parity == UART_PARITY_NONE)) + { + pdata8bits = NULL; + pdata16bits = (uint16_t *) pData; + } + else + { + pdata8bits = pData; + pdata16bits = NULL; + } + + /* Process Unlocked */ + __DAL_UNLOCK(huart); + + /* Check the remain data to be received */ + while (huart->RxXferCount > 0U) + { + if (UART_WaitOnFlagUntilTimeout(huart, UART_FLAG_RXNE, RESET, tickstart, Timeout) != DAL_OK) + { + return DAL_TIMEOUT; + } + if (pdata8bits == NULL) + { + *pdata16bits = (uint16_t)(huart->Instance->DATA & 0x01FF); + pdata16bits++; + } + else + { + if ((huart->Init.WordLength == UART_WORDLENGTH_9B) || ((huart->Init.WordLength == UART_WORDLENGTH_8B) && (huart->Init.Parity == UART_PARITY_NONE))) + { + *pdata8bits = (uint8_t)(huart->Instance->DATA & (uint8_t)0x00FF); + } + else + { + *pdata8bits = (uint8_t)(huart->Instance->DATA & (uint8_t)0x007F); + } + pdata8bits++; + } + huart->RxXferCount--; + } + + /* At end of Rx process, restore huart->RxState to Ready */ + huart->RxState = DAL_UART_STATE_READY; + + return DAL_OK; + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief Sends an amount of data in non blocking mode. + * @note When UART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), + * the sent data is handled as a set of u16. In this case, Size must indicate the number + * of u16 provided through pData. + * @param huart Pointer to a UART_HandleTypeDef structure that contains + * the configuration information for the specified UART module. + * @param pData Pointer to data buffer (u8 or u16 data elements). + * @param Size Amount of data elements (u8 or u16) to be sent + * @retval DAL status + */ +DAL_StatusTypeDef DAL_UART_Transmit_IT(UART_HandleTypeDef *huart, const uint8_t *pData, uint16_t Size) +{ + /* Check that a Tx process is not already ongoing */ + if (huart->gState == DAL_UART_STATE_READY) + { + if ((pData == NULL) || (Size == 0U)) + { + return DAL_ERROR; + } + + /* Process Locked */ + __DAL_LOCK(huart); + + huart->pTxBuffPtr = pData; + huart->TxXferSize = Size; + huart->TxXferCount = Size; + + huart->ErrorCode = DAL_UART_ERROR_NONE; + huart->gState = DAL_UART_STATE_BUSY_TX; + + /* Process Unlocked */ + __DAL_UNLOCK(huart); + + /* Enable the UART Transmit data register empty Interrupt */ + __DAL_UART_ENABLE_IT(huart, UART_IT_TXE); + + return DAL_OK; + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief Receives an amount of data in non blocking mode. + * @note When UART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), + * the received data is handled as a set of u16. In this case, Size must indicate the number + * of u16 available through pData. + * @param huart Pointer to a UART_HandleTypeDef structure that contains + * the configuration information for the specified UART module. + * @param pData Pointer to data buffer (u8 or u16 data elements). + * @param Size Amount of data elements (u8 or u16) to be received. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_UART_Receive_IT(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size) +{ + /* Check that a Rx process is not already ongoing */ + if (huart->RxState == DAL_UART_STATE_READY) + { + if ((pData == NULL) || (Size == 0U)) + { + return DAL_ERROR; + } + + /* Process Locked */ + __DAL_LOCK(huart); + + /* Set Reception type to Standard reception */ + huart->ReceptionType = DAL_UART_RECEPTION_STANDARD; + + return (UART_Start_Receive_IT(huart, pData, Size)); + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief Sends an amount of data in DMA mode. + * @note When UART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), + * the sent data is handled as a set of u16. In this case, Size must indicate the number + * of u16 provided through pData. + * @param huart Pointer to a UART_HandleTypeDef structure that contains + * the configuration information for the specified UART module. + * @param pData Pointer to data buffer (u8 or u16 data elements). + * @param Size Amount of data elements (u8 or u16) to be sent + * @retval DAL status + */ +DAL_StatusTypeDef DAL_UART_Transmit_DMA(UART_HandleTypeDef *huart, const uint8_t *pData, uint16_t Size) +{ + const uint32_t *tmp; + + /* Check that a Tx process is not already ongoing */ + if (huart->gState == DAL_UART_STATE_READY) + { + if ((pData == NULL) || (Size == 0U)) + { + return DAL_ERROR; + } + + /* Process Locked */ + __DAL_LOCK(huart); + + huart->pTxBuffPtr = pData; + huart->TxXferSize = Size; + huart->TxXferCount = Size; + + huart->ErrorCode = DAL_UART_ERROR_NONE; + huart->gState = DAL_UART_STATE_BUSY_TX; + + /* Set the UART DMA transfer complete callback */ + huart->hdmatx->XferCpltCallback = UART_DMATransmitCplt; + + /* Set the UART DMA Half transfer complete callback */ + huart->hdmatx->XferHalfCpltCallback = UART_DMATxHalfCplt; + + /* Set the DMA error callback */ + huart->hdmatx->XferErrorCallback = UART_DMAError; + + /* Set the DMA abort callback */ + huart->hdmatx->XferAbortCallback = NULL; + + /* Enable the UART transmit DMA stream */ + tmp = (const uint32_t *)&pData; + DAL_DMA_Start_IT(huart->hdmatx, *(const uint32_t *)tmp, (uint32_t)&huart->Instance->DATA, Size); + + /* Clear the TC flag in the STS register by writing 0 to it */ + __DAL_UART_CLEAR_FLAG(huart, UART_FLAG_TC); + + /* Process Unlocked */ + __DAL_UNLOCK(huart); + + /* Enable the DMA transfer for transmit request by setting the DMAT bit + in the UART CTRL3 register */ + ATOMIC_SET_BIT(huart->Instance->CTRL3, USART_CTRL3_DMATXEN); + + return DAL_OK; + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief Receives an amount of data in DMA mode. + * @note When UART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), + * the received data is handled as a set of u16. In this case, Size must indicate the number + * of u16 available through pData. + * @param huart Pointer to a UART_HandleTypeDef structure that contains + * the configuration information for the specified UART module. + * @param pData Pointer to data buffer (u8 or u16 data elements). + * @param Size Amount of data elements (u8 or u16) to be received. + * @note When the UART parity is enabled (PCE = 1) the received data contains the parity bit. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_UART_Receive_DMA(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size) +{ + /* Check that a Rx process is not already ongoing */ + if (huart->RxState == DAL_UART_STATE_READY) + { + if ((pData == NULL) || (Size == 0U)) + { + return DAL_ERROR; + } + + /* Process Locked */ + __DAL_LOCK(huart); + + /* Set Reception type to Standard reception */ + huart->ReceptionType = DAL_UART_RECEPTION_STANDARD; + + return (UART_Start_Receive_DMA(huart, pData, Size)); + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief Pauses the DMA Transfer. + * @param huart Pointer to a UART_HandleTypeDef structure that contains + * the configuration information for the specified UART module. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_UART_DMAPause(UART_HandleTypeDef *huart) +{ + uint32_t dmarequest = 0x00U; + + /* Process Locked */ + __DAL_LOCK(huart); + + dmarequest = DAL_IS_BIT_SET(huart->Instance->CTRL3, USART_CTRL3_DMATXEN); + if ((huart->gState == DAL_UART_STATE_BUSY_TX) && dmarequest) + { + /* Disable the UART DMA Tx request */ + ATOMIC_CLEAR_BIT(huart->Instance->CTRL3, USART_CTRL3_DMATXEN); + } + + dmarequest = DAL_IS_BIT_SET(huart->Instance->CTRL3, USART_CTRL3_DMARXEN); + if ((huart->RxState == DAL_UART_STATE_BUSY_RX) && dmarequest) + { + /* Disable RXNE, PEIEN and ERRIEN (Frame error, noise error, overrun error) interrupts */ + ATOMIC_CLEAR_BIT(huart->Instance->CTRL1, USART_CTRL1_PEIEN); + ATOMIC_CLEAR_BIT(huart->Instance->CTRL3, USART_CTRL3_ERRIEN); + + /* Disable the UART DMA Rx request */ + ATOMIC_CLEAR_BIT(huart->Instance->CTRL3, USART_CTRL3_DMARXEN); + } + + /* Process Unlocked */ + __DAL_UNLOCK(huart); + + return DAL_OK; +} + +/** + * @brief Resumes the DMA Transfer. + * @param huart Pointer to a UART_HandleTypeDef structure that contains + * the configuration information for the specified UART module. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_UART_DMAResume(UART_HandleTypeDef *huart) +{ + /* Process Locked */ + __DAL_LOCK(huart); + + if (huart->gState == DAL_UART_STATE_BUSY_TX) + { + /* Enable the UART DMA Tx request */ + ATOMIC_SET_BIT(huart->Instance->CTRL3, USART_CTRL3_DMATXEN); + } + + if (huart->RxState == DAL_UART_STATE_BUSY_RX) + { + /* Clear the Overrun flag before resuming the Rx transfer*/ + __DAL_UART_CLEAR_OREFLAG(huart); + + /* Re-enable PEIEN and ERRIEN (Frame error, noise error, overrun error) interrupts */ + if (huart->Init.Parity != UART_PARITY_NONE) + { + ATOMIC_SET_BIT(huart->Instance->CTRL1, USART_CTRL1_PEIEN); + } + ATOMIC_SET_BIT(huart->Instance->CTRL3, USART_CTRL3_ERRIEN); + + /* Enable the UART DMA Rx request */ + ATOMIC_SET_BIT(huart->Instance->CTRL3, USART_CTRL3_DMARXEN); + } + + /* Process Unlocked */ + __DAL_UNLOCK(huart); + + return DAL_OK; +} + +/** + * @brief Stops the DMA Transfer. + * @param huart Pointer to a UART_HandleTypeDef structure that contains + * the configuration information for the specified UART module. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_UART_DMAStop(UART_HandleTypeDef *huart) +{ + uint32_t dmarequest = 0x00U; + /* The Lock is not implemented on this API to allow the user application + to call the DAL UART API under callbacks DAL_UART_TxCpltCallback() / DAL_UART_RxCpltCallback(): + when calling DAL_DMA_Abort() API the DMA TX/RX Transfer complete interrupt is generated + and the correspond call back is executed DAL_UART_TxCpltCallback() / DAL_UART_RxCpltCallback() + */ + + /* Stop UART DMA Tx request if ongoing */ + dmarequest = DAL_IS_BIT_SET(huart->Instance->CTRL3, USART_CTRL3_DMATXEN); + if ((huart->gState == DAL_UART_STATE_BUSY_TX) && dmarequest) + { + ATOMIC_CLEAR_BIT(huart->Instance->CTRL3, USART_CTRL3_DMATXEN); + + /* Abort the UART DMA Tx stream */ + if (huart->hdmatx != NULL) + { + DAL_DMA_Abort(huart->hdmatx); + } + UART_EndTxTransfer(huart); + } + + /* Stop UART DMA Rx request if ongoing */ + dmarequest = DAL_IS_BIT_SET(huart->Instance->CTRL3, USART_CTRL3_DMARXEN); + if ((huart->RxState == DAL_UART_STATE_BUSY_RX) && dmarequest) + { + ATOMIC_CLEAR_BIT(huart->Instance->CTRL3, USART_CTRL3_DMARXEN); + + /* Abort the UART DMA Rx stream */ + if (huart->hdmarx != NULL) + { + DAL_DMA_Abort(huart->hdmarx); + } + UART_EndRxTransfer(huart); + } + + return DAL_OK; +} + +/** + * @brief Receive an amount of data in blocking mode till either the expected number of data is received or an IDLE event occurs. + * @note DAL_OK is returned if reception is completed (expected number of data has been received) + * or if reception is stopped after IDLE event (less than the expected number of data has been received) + * In this case, RxLen output parameter indicates number of data available in reception buffer. + * @note When UART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M = 01), + * the received data is handled as a set of uint16_t. In this case, Size must indicate the number + * of uint16_t available through pData. + * @param huart UART handle. + * @param pData Pointer to data buffer (uint8_t or uint16_t data elements). + * @param Size Amount of data elements (uint8_t or uint16_t) to be received. + * @param RxLen Number of data elements finally received (could be lower than Size, in case reception ends on IDLE event) + * @param Timeout Timeout duration expressed in ms (covers the whole reception sequence). + * @retval DAL status + */ +DAL_StatusTypeDef DAL_UARTEx_ReceiveToIdle(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size, uint16_t *RxLen, + uint32_t Timeout) +{ + uint8_t *pdata8bits; + uint16_t *pdata16bits; + uint32_t tickstart; + + /* Check that a Rx process is not already ongoing */ + if (huart->RxState == DAL_UART_STATE_READY) + { + if ((pData == NULL) || (Size == 0U)) + { + return DAL_ERROR; + } + + __DAL_LOCK(huart); + + huart->ErrorCode = DAL_UART_ERROR_NONE; + huart->RxState = DAL_UART_STATE_BUSY_RX; + huart->ReceptionType = DAL_UART_RECEPTION_TOIDLE; + + /* Init tickstart for timeout management */ + tickstart = DAL_GetTick(); + + huart->RxXferSize = Size; + huart->RxXferCount = Size; + + /* In case of 9bits/No Parity transfer, pRxData needs to be handled as a uint16_t pointer */ + if ((huart->Init.WordLength == UART_WORDLENGTH_9B) && (huart->Init.Parity == UART_PARITY_NONE)) + { + pdata8bits = NULL; + pdata16bits = (uint16_t *) pData; + } + else + { + pdata8bits = pData; + pdata16bits = NULL; + } + + __DAL_UNLOCK(huart); + + /* Initialize output number of received elements */ + *RxLen = 0U; + + /* as long as data have to be received */ + while (huart->RxXferCount > 0U) + { + /* Check if IDLE flag is set */ + if (__DAL_UART_GET_FLAG(huart, UART_FLAG_IDLE)) + { + /* Clear IDLE flag in ISR */ + __DAL_UART_CLEAR_IDLEFLAG(huart); + + /* If Set, but no data ever received, clear flag without exiting loop */ + /* If Set, and data has already been received, this means Idle Event is valid : End reception */ + if (*RxLen > 0U) + { + huart->RxState = DAL_UART_STATE_READY; + + return DAL_OK; + } + } + + /* Check if RXNE flag is set */ + if (__DAL_UART_GET_FLAG(huart, UART_FLAG_RXNE)) + { + if (pdata8bits == NULL) + { + *pdata16bits = (uint16_t)(huart->Instance->DATA & (uint16_t)0x01FF); + pdata16bits++; + } + else + { + if ((huart->Init.WordLength == UART_WORDLENGTH_9B) || ((huart->Init.WordLength == UART_WORDLENGTH_8B) && (huart->Init.Parity == UART_PARITY_NONE))) + { + *pdata8bits = (uint8_t)(huart->Instance->DATA & (uint8_t)0x00FF); + } + else + { + *pdata8bits = (uint8_t)(huart->Instance->DATA & (uint8_t)0x007F); + } + + pdata8bits++; + } + /* Increment number of received elements */ + *RxLen += 1U; + huart->RxXferCount--; + } + + /* Check for the Timeout */ + if (Timeout != DAL_MAX_DELAY) + { + if (((DAL_GetTick() - tickstart) > Timeout) || (Timeout == 0U)) + { + huart->RxState = DAL_UART_STATE_READY; + + return DAL_TIMEOUT; + } + } + } + + /* Set number of received elements in output parameter : RxLen */ + *RxLen = huart->RxXferSize - huart->RxXferCount; + /* At end of Rx process, restore huart->RxState to Ready */ + huart->RxState = DAL_UART_STATE_READY; + + return DAL_OK; + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief Receive an amount of data in interrupt mode till either the expected number of data is received or an IDLE event occurs. + * @note Reception is initiated by this function call. Further progress of reception is achieved thanks + * to UART interrupts raised by RXNE and IDLE events. Callback is called at end of reception indicating + * number of received data elements. + * @note When UART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M = 01), + * the received data is handled as a set of uint16_t. In this case, Size must indicate the number + * of uint16_t available through pData. + * @param huart UART handle. + * @param pData Pointer to data buffer (uint8_t or uint16_t data elements). + * @param Size Amount of data elements (uint8_t or uint16_t) to be received. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_UARTEx_ReceiveToIdle_IT(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size) +{ + DAL_StatusTypeDef status; + + /* Check that a Rx process is not already ongoing */ + if (huart->RxState == DAL_UART_STATE_READY) + { + if ((pData == NULL) || (Size == 0U)) + { + return DAL_ERROR; + } + + __DAL_LOCK(huart); + + /* Set Reception type to reception till IDLE Event*/ + huart->ReceptionType = DAL_UART_RECEPTION_TOIDLE; + + status = UART_Start_Receive_IT(huart, pData, Size); + + /* Check Rx process has been successfully started */ + if (status == DAL_OK) + { + if (huart->ReceptionType == DAL_UART_RECEPTION_TOIDLE) + { + __DAL_UART_CLEAR_IDLEFLAG(huart); + ATOMIC_SET_BIT(huart->Instance->CTRL1, USART_CTRL1_IDLEIEN); + } + else + { + /* In case of errors already pending when reception is started, + Interrupts may have already been raised and lead to reception abortion. + (Overrun error for instance). + In such case Reception Type has been reset to DAL_UART_RECEPTION_STANDARD. */ + status = DAL_ERROR; + } + } + + return status; + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief Receive an amount of data in DMA mode till either the expected number of data is received or an IDLE event occurs. + * @note Reception is initiated by this function call. Further progress of reception is achieved thanks + * to DMA services, transferring automatically received data elements in user reception buffer and + * calling registered callbacks at half/end of reception. UART IDLE events are also used to consider + * reception phase as ended. In all cases, callback execution will indicate number of received data elements. + * @note When the UART parity is enabled (PCE = 1), the received data contain + * the parity bit (MSB position). + * @note When UART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M = 01), + * the received data is handled as a set of uint16_t. In this case, Size must indicate the number + * of uint16_t available through pData. + * @param huart UART handle. + * @param pData Pointer to data buffer (uint8_t or uint16_t data elements). + * @param Size Amount of data elements (uint8_t or uint16_t) to be received. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_UARTEx_ReceiveToIdle_DMA(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size) +{ + DAL_StatusTypeDef status; + + /* Check that a Rx process is not already ongoing */ + if (huart->RxState == DAL_UART_STATE_READY) + { + if ((pData == NULL) || (Size == 0U)) + { + return DAL_ERROR; + } + + __DAL_LOCK(huart); + + /* Set Reception type to reception till IDLE Event*/ + huart->ReceptionType = DAL_UART_RECEPTION_TOIDLE; + + status = UART_Start_Receive_DMA(huart, pData, Size); + + /* Check Rx process has been successfully started */ + if (status == DAL_OK) + { + if (huart->ReceptionType == DAL_UART_RECEPTION_TOIDLE) + { + __DAL_UART_CLEAR_IDLEFLAG(huart); + ATOMIC_SET_BIT(huart->Instance->CTRL1, USART_CTRL1_IDLEIEN); + } + else + { + /* In case of errors already pending when reception is started, + Interrupts may have already been raised and lead to reception abortion. + (Overrun error for instance). + In such case Reception Type has been reset to DAL_UART_RECEPTION_STANDARD. */ + status = DAL_ERROR; + } + } + + return status; + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief Abort ongoing transfers (blocking mode). + * @param huart UART handle. + * @note This procedure could be used for aborting any ongoing transfer started in Interrupt or DMA mode. + * This procedure performs following operations : + * - Disable UART Interrupts (Tx and Rx) + * - Disable the DMA transfer in the peripheral register (if enabled) + * - Abort DMA transfer by calling DAL_DMA_Abort (in case of transfer in DMA mode) + * - Set handle State to READY + * @note This procedure is executed in blocking mode : when exiting function, Abort is considered as completed. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_UART_Abort(UART_HandleTypeDef *huart) +{ + /* Disable TXBEIEN, TXCIEN, RXBNEIEN, PEIEN and ERRIEN (Frame error, noise error, overrun error) interrupts */ + ATOMIC_CLEAR_BIT(huart->Instance->CTRL1, (USART_CTRL1_RXBNEIEN | USART_CTRL1_PEIEN | USART_CTRL1_TXBEIEN | USART_CTRL1_TXCIEN)); + ATOMIC_CLEAR_BIT(huart->Instance->CTRL3, USART_CTRL3_ERRIEN); + + /* If Reception till IDLE event was ongoing, disable IDLEIEN interrupt */ + if (huart->ReceptionType == DAL_UART_RECEPTION_TOIDLE) + { + ATOMIC_CLEAR_BIT(huart->Instance->CTRL1, (USART_CTRL1_IDLEIEN)); + } + + /* Disable the UART DMA Tx request if enabled */ + if (DAL_IS_BIT_SET(huart->Instance->CTRL3, USART_CTRL3_DMATXEN)) + { + ATOMIC_CLEAR_BIT(huart->Instance->CTRL3, USART_CTRL3_DMATXEN); + + /* Abort the UART DMA Tx stream: use blocking DMA Abort API (no callback) */ + if (huart->hdmatx != NULL) + { + /* Set the UART DMA Abort callback to Null. + No call back execution at end of DMA abort procedure */ + huart->hdmatx->XferAbortCallback = NULL; + + if (DAL_DMA_Abort(huart->hdmatx) != DAL_OK) + { + if (DAL_DMA_GetError(huart->hdmatx) == DAL_DMA_ERROR_TIMEOUT) + { + /* Set error code to DMA */ + huart->ErrorCode = DAL_UART_ERROR_DMA; + + return DAL_TIMEOUT; + } + } + } + } + + /* Disable the UART DMA Rx request if enabled */ + if (DAL_IS_BIT_SET(huart->Instance->CTRL3, USART_CTRL3_DMARXEN)) + { + ATOMIC_CLEAR_BIT(huart->Instance->CTRL3, USART_CTRL3_DMARXEN); + + /* Abort the UART DMA Rx stream: use blocking DMA Abort API (no callback) */ + if (huart->hdmarx != NULL) + { + /* Set the UART DMA Abort callback to Null. + No call back execution at end of DMA abort procedure */ + huart->hdmarx->XferAbortCallback = NULL; + + if (DAL_DMA_Abort(huart->hdmarx) != DAL_OK) + { + if (DAL_DMA_GetError(huart->hdmarx) == DAL_DMA_ERROR_TIMEOUT) + { + /* Set error code to DMA */ + huart->ErrorCode = DAL_UART_ERROR_DMA; + + return DAL_TIMEOUT; + } + } + } + } + + /* Reset Tx and Rx transfer counters */ + huart->TxXferCount = 0x00U; + huart->RxXferCount = 0x00U; + + /* Reset ErrorCode */ + huart->ErrorCode = DAL_UART_ERROR_NONE; + + /* Restore huart->RxState and huart->gState to Ready */ + huart->RxState = DAL_UART_STATE_READY; + huart->gState = DAL_UART_STATE_READY; + huart->ReceptionType = DAL_UART_RECEPTION_STANDARD; + + return DAL_OK; +} + +/** + * @brief Abort ongoing Transmit transfer (blocking mode). + * @param huart UART handle. + * @note This procedure could be used for aborting any ongoing Tx transfer started in Interrupt or DMA mode. + * This procedure performs following operations : + * - Disable UART Interrupts (Tx) + * - Disable the DMA transfer in the peripheral register (if enabled) + * - Abort DMA transfer by calling DAL_DMA_Abort (in case of transfer in DMA mode) + * - Set handle State to READY + * @note This procedure is executed in blocking mode : when exiting function, Abort is considered as completed. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_UART_AbortTransmit(UART_HandleTypeDef *huart) +{ + /* Disable TXBEIEN and TXCIEN interrupts */ + ATOMIC_CLEAR_BIT(huart->Instance->CTRL1, (USART_CTRL1_TXBEIEN | USART_CTRL1_TXCIEN)); + + /* Disable the UART DMA Tx request if enabled */ + if (DAL_IS_BIT_SET(huart->Instance->CTRL3, USART_CTRL3_DMATXEN)) + { + ATOMIC_CLEAR_BIT(huart->Instance->CTRL3, USART_CTRL3_DMATXEN); + + /* Abort the UART DMA Tx stream : use blocking DMA Abort API (no callback) */ + if (huart->hdmatx != NULL) + { + /* Set the UART DMA Abort callback to Null. + No call back execution at end of DMA abort procedure */ + huart->hdmatx->XferAbortCallback = NULL; + + if (DAL_DMA_Abort(huart->hdmatx) != DAL_OK) + { + if (DAL_DMA_GetError(huart->hdmatx) == DAL_DMA_ERROR_TIMEOUT) + { + /* Set error code to DMA */ + huart->ErrorCode = DAL_UART_ERROR_DMA; + + return DAL_TIMEOUT; + } + } + } + } + + /* Reset Tx transfer counter */ + huart->TxXferCount = 0x00U; + + /* Restore huart->gState to Ready */ + huart->gState = DAL_UART_STATE_READY; + + return DAL_OK; +} + +/** + * @brief Abort ongoing Receive transfer (blocking mode). + * @param huart UART handle. + * @note This procedure could be used for aborting any ongoing Rx transfer started in Interrupt or DMA mode. + * This procedure performs following operations : + * - Disable UART Interrupts (Rx) + * - Disable the DMA transfer in the peripheral register (if enabled) + * - Abort DMA transfer by calling DAL_DMA_Abort (in case of transfer in DMA mode) + * - Set handle State to READY + * @note This procedure is executed in blocking mode : when exiting function, Abort is considered as completed. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_UART_AbortReceive(UART_HandleTypeDef *huart) +{ + /* Disable RXBNEIEN, PEIEN and ERRIEN (Frame error, noise error, overrun error) interrupts */ + ATOMIC_CLEAR_BIT(huart->Instance->CTRL1, (USART_CTRL1_RXBNEIEN | USART_CTRL1_PEIEN)); + ATOMIC_CLEAR_BIT(huart->Instance->CTRL3, USART_CTRL3_ERRIEN); + + /* If Reception till IDLE event was ongoing, disable IDLEIEN interrupt */ + if (huart->ReceptionType == DAL_UART_RECEPTION_TOIDLE) + { + ATOMIC_CLEAR_BIT(huart->Instance->CTRL1, (USART_CTRL1_IDLEIEN)); + } + + /* Disable the UART DMA Rx request if enabled */ + if (DAL_IS_BIT_SET(huart->Instance->CTRL3, USART_CTRL3_DMARXEN)) + { + ATOMIC_CLEAR_BIT(huart->Instance->CTRL3, USART_CTRL3_DMARXEN); + + /* Abort the UART DMA Rx stream : use blocking DMA Abort API (no callback) */ + if (huart->hdmarx != NULL) + { + /* Set the UART DMA Abort callback to Null. + No call back execution at end of DMA abort procedure */ + huart->hdmarx->XferAbortCallback = NULL; + + if (DAL_DMA_Abort(huart->hdmarx) != DAL_OK) + { + if (DAL_DMA_GetError(huart->hdmarx) == DAL_DMA_ERROR_TIMEOUT) + { + /* Set error code to DMA */ + huart->ErrorCode = DAL_UART_ERROR_DMA; + + return DAL_TIMEOUT; + } + } + } + } + + /* Reset Rx transfer counter */ + huart->RxXferCount = 0x00U; + + /* Restore huart->RxState to Ready */ + huart->RxState = DAL_UART_STATE_READY; + huart->ReceptionType = DAL_UART_RECEPTION_STANDARD; + + return DAL_OK; +} + +/** + * @brief Abort ongoing transfers (Interrupt mode). + * @param huart UART handle. + * @note This procedure could be used for aborting any ongoing transfer started in Interrupt or DMA mode. + * This procedure performs following operations : + * - Disable UART Interrupts (Tx and Rx) + * - Disable the DMA transfer in the peripheral register (if enabled) + * - Abort DMA transfer by calling DAL_DMA_Abort_IT (in case of transfer in DMA mode) + * - Set handle State to READY + * - At abort completion, call user abort complete callback + * @note This procedure is executed in Interrupt mode, meaning that abort procedure could be + * considered as completed only when user abort complete callback is executed (not when exiting function). + * @retval DAL status + */ +DAL_StatusTypeDef DAL_UART_Abort_IT(UART_HandleTypeDef *huart) +{ + uint32_t AbortCplt = 0x01U; + + /* Disable TXBEIEN, TXCIEN, RXBNEIEN, PEIEN and ERRIEN (Frame error, noise error, overrun error) interrupts */ + ATOMIC_CLEAR_BIT(huart->Instance->CTRL1, (USART_CTRL1_RXBNEIEN | USART_CTRL1_PEIEN | USART_CTRL1_TXBEIEN | USART_CTRL1_TXCIEN)); + ATOMIC_CLEAR_BIT(huart->Instance->CTRL3, USART_CTRL3_ERRIEN); + + /* If Reception till IDLE event was ongoing, disable IDLEIEN interrupt */ + if (huart->ReceptionType == DAL_UART_RECEPTION_TOIDLE) + { + ATOMIC_CLEAR_BIT(huart->Instance->CTRL1, (USART_CTRL1_IDLEIEN)); + } + + /* If DMA Tx and/or DMA Rx Handles are associated to UART Handle, DMA Abort complete callbacks should be initialised + before any call to DMA Abort functions */ + /* DMA Tx Handle is valid */ + if (huart->hdmatx != NULL) + { + /* Set DMA Abort Complete callback if UART DMA Tx request if enabled. + Otherwise, set it to NULL */ + if (DAL_IS_BIT_SET(huart->Instance->CTRL3, USART_CTRL3_DMATXEN)) + { + huart->hdmatx->XferAbortCallback = UART_DMATxAbortCallback; + } + else + { + huart->hdmatx->XferAbortCallback = NULL; + } + } + /* DMA Rx Handle is valid */ + if (huart->hdmarx != NULL) + { + /* Set DMA Abort Complete callback if UART DMA Rx request if enabled. + Otherwise, set it to NULL */ + if (DAL_IS_BIT_SET(huart->Instance->CTRL3, USART_CTRL3_DMARXEN)) + { + huart->hdmarx->XferAbortCallback = UART_DMARxAbortCallback; + } + else + { + huart->hdmarx->XferAbortCallback = NULL; + } + } + + /* Disable the UART DMA Tx request if enabled */ + if (DAL_IS_BIT_SET(huart->Instance->CTRL3, USART_CTRL3_DMATXEN)) + { + /* Disable DMA Tx at UART level */ + ATOMIC_CLEAR_BIT(huart->Instance->CTRL3, USART_CTRL3_DMATXEN); + + /* Abort the UART DMA Tx stream : use non blocking DMA Abort API (callback) */ + if (huart->hdmatx != NULL) + { + /* UART Tx DMA Abort callback has already been initialised : + will lead to call DAL_UART_AbortCpltCallback() at end of DMA abort procedure */ + + /* Abort DMA TX */ + if (DAL_DMA_Abort_IT(huart->hdmatx) != DAL_OK) + { + huart->hdmatx->XferAbortCallback = NULL; + } + else + { + AbortCplt = 0x00U; + } + } + } + + /* Disable the UART DMA Rx request if enabled */ + if (DAL_IS_BIT_SET(huart->Instance->CTRL3, USART_CTRL3_DMARXEN)) + { + ATOMIC_CLEAR_BIT(huart->Instance->CTRL3, USART_CTRL3_DMARXEN); + + /* Abort the UART DMA Rx stream : use non blocking DMA Abort API (callback) */ + if (huart->hdmarx != NULL) + { + /* UART Rx DMA Abort callback has already been initialised : + will lead to call DAL_UART_AbortCpltCallback() at end of DMA abort procedure */ + + /* Abort DMA RX */ + if (DAL_DMA_Abort_IT(huart->hdmarx) != DAL_OK) + { + huart->hdmarx->XferAbortCallback = NULL; + AbortCplt = 0x01U; + } + else + { + AbortCplt = 0x00U; + } + } + } + + /* if no DMA abort complete callback execution is required => call user Abort Complete callback */ + if (AbortCplt == 0x01U) + { + /* Reset Tx and Rx transfer counters */ + huart->TxXferCount = 0x00U; + huart->RxXferCount = 0x00U; + + /* Reset ErrorCode */ + huart->ErrorCode = DAL_UART_ERROR_NONE; + + /* Restore huart->gState and huart->RxState to Ready */ + huart->gState = DAL_UART_STATE_READY; + huart->RxState = DAL_UART_STATE_READY; + huart->ReceptionType = DAL_UART_RECEPTION_STANDARD; + + /* As no DMA to be aborted, call directly user Abort complete callback */ +#if (USE_DAL_UART_REGISTER_CALLBACKS == 1) + /* Call registered Abort complete callback */ + huart->AbortCpltCallback(huart); +#else + /* Call legacy weak Abort complete callback */ + DAL_UART_AbortCpltCallback(huart); +#endif /* USE_DAL_UART_REGISTER_CALLBACKS */ + } + + return DAL_OK; +} + +/** + * @brief Abort ongoing Transmit transfer (Interrupt mode). + * @param huart UART handle. + * @note This procedure could be used for aborting any ongoing Tx transfer started in Interrupt or DMA mode. + * This procedure performs following operations : + * - Disable UART Interrupts (Tx) + * - Disable the DMA transfer in the peripheral register (if enabled) + * - Abort DMA transfer by calling DAL_DMA_Abort_IT (in case of transfer in DMA mode) + * - Set handle State to READY + * - At abort completion, call user abort complete callback + * @note This procedure is executed in Interrupt mode, meaning that abort procedure could be + * considered as completed only when user abort complete callback is executed (not when exiting function). + * @retval DAL status + */ +DAL_StatusTypeDef DAL_UART_AbortTransmit_IT(UART_HandleTypeDef *huart) +{ + /* Disable TXBEIEN and TXCIEN interrupts */ + ATOMIC_CLEAR_BIT(huart->Instance->CTRL1, (USART_CTRL1_TXBEIEN | USART_CTRL1_TXCIEN)); + + /* Disable the UART DMA Tx request if enabled */ + if (DAL_IS_BIT_SET(huart->Instance->CTRL3, USART_CTRL3_DMATXEN)) + { + ATOMIC_CLEAR_BIT(huart->Instance->CTRL3, USART_CTRL3_DMATXEN); + + /* Abort the UART DMA Tx stream : use blocking DMA Abort API (no callback) */ + if (huart->hdmatx != NULL) + { + /* Set the UART DMA Abort callback : + will lead to call DAL_UART_AbortCpltCallback() at end of DMA abort procedure */ + huart->hdmatx->XferAbortCallback = UART_DMATxOnlyAbortCallback; + + /* Abort DMA TX */ + if (DAL_DMA_Abort_IT(huart->hdmatx) != DAL_OK) + { + /* Call Directly huart->hdmatx->XferAbortCallback function in case of error */ + huart->hdmatx->XferAbortCallback(huart->hdmatx); + } + } + else + { + /* Reset Tx transfer counter */ + huart->TxXferCount = 0x00U; + + /* Restore huart->gState to Ready */ + huart->gState = DAL_UART_STATE_READY; + + /* As no DMA to be aborted, call directly user Abort complete callback */ +#if (USE_DAL_UART_REGISTER_CALLBACKS == 1) + /* Call registered Abort Transmit Complete Callback */ + huart->AbortTransmitCpltCallback(huart); +#else + /* Call legacy weak Abort Transmit Complete Callback */ + DAL_UART_AbortTransmitCpltCallback(huart); +#endif /* USE_DAL_UART_REGISTER_CALLBACKS */ + } + } + else + { + /* Reset Tx transfer counter */ + huart->TxXferCount = 0x00U; + + /* Restore huart->gState to Ready */ + huart->gState = DAL_UART_STATE_READY; + + /* As no DMA to be aborted, call directly user Abort complete callback */ +#if (USE_DAL_UART_REGISTER_CALLBACKS == 1) + /* Call registered Abort Transmit Complete Callback */ + huart->AbortTransmitCpltCallback(huart); +#else + /* Call legacy weak Abort Transmit Complete Callback */ + DAL_UART_AbortTransmitCpltCallback(huart); +#endif /* USE_DAL_UART_REGISTER_CALLBACKS */ + } + + return DAL_OK; +} + +/** + * @brief Abort ongoing Receive transfer (Interrupt mode). + * @param huart UART handle. + * @note This procedure could be used for aborting any ongoing Rx transfer started in Interrupt or DMA mode. + * This procedure performs following operations : + * - Disable UART Interrupts (Rx) + * - Disable the DMA transfer in the peripheral register (if enabled) + * - Abort DMA transfer by calling DAL_DMA_Abort_IT (in case of transfer in DMA mode) + * - Set handle State to READY + * - At abort completion, call user abort complete callback + * @note This procedure is executed in Interrupt mode, meaning that abort procedure could be + * considered as completed only when user abort complete callback is executed (not when exiting function). + * @retval DAL status + */ +DAL_StatusTypeDef DAL_UART_AbortReceive_IT(UART_HandleTypeDef *huart) +{ + /* Disable RXBNEIEN, PEIEN and ERRIEN (Frame error, noise error, overrun error) interrupts */ + ATOMIC_CLEAR_BIT(huart->Instance->CTRL1, (USART_CTRL1_RXBNEIEN | USART_CTRL1_PEIEN)); + ATOMIC_CLEAR_BIT(huart->Instance->CTRL3, USART_CTRL3_ERRIEN); + + /* If Reception till IDLE event was ongoing, disable IDLEIEN interrupt */ + if (huart->ReceptionType == DAL_UART_RECEPTION_TOIDLE) + { + ATOMIC_CLEAR_BIT(huart->Instance->CTRL1, (USART_CTRL1_IDLEIEN)); + } + + /* Disable the UART DMA Rx request if enabled */ + if (DAL_IS_BIT_SET(huart->Instance->CTRL3, USART_CTRL3_DMARXEN)) + { + ATOMIC_CLEAR_BIT(huart->Instance->CTRL3, USART_CTRL3_DMARXEN); + + /* Abort the UART DMA Rx stream : use blocking DMA Abort API (no callback) */ + if (huart->hdmarx != NULL) + { + /* Set the UART DMA Abort callback : + will lead to call DAL_UART_AbortCpltCallback() at end of DMA abort procedure */ + huart->hdmarx->XferAbortCallback = UART_DMARxOnlyAbortCallback; + + /* Abort DMA RX */ + if (DAL_DMA_Abort_IT(huart->hdmarx) != DAL_OK) + { + /* Call Directly huart->hdmarx->XferAbortCallback function in case of error */ + huart->hdmarx->XferAbortCallback(huart->hdmarx); + } + } + else + { + /* Reset Rx transfer counter */ + huart->RxXferCount = 0x00U; + + /* Restore huart->RxState to Ready */ + huart->RxState = DAL_UART_STATE_READY; + huart->ReceptionType = DAL_UART_RECEPTION_STANDARD; + + /* As no DMA to be aborted, call directly user Abort complete callback */ +#if (USE_DAL_UART_REGISTER_CALLBACKS == 1) + /* Call registered Abort Receive Complete Callback */ + huart->AbortReceiveCpltCallback(huart); +#else + /* Call legacy weak Abort Receive Complete Callback */ + DAL_UART_AbortReceiveCpltCallback(huart); +#endif /* USE_DAL_UART_REGISTER_CALLBACKS */ + } + } + else + { + /* Reset Rx transfer counter */ + huart->RxXferCount = 0x00U; + + /* Restore huart->RxState to Ready */ + huart->RxState = DAL_UART_STATE_READY; + huart->ReceptionType = DAL_UART_RECEPTION_STANDARD; + + /* As no DMA to be aborted, call directly user Abort complete callback */ +#if (USE_DAL_UART_REGISTER_CALLBACKS == 1) + /* Call registered Abort Receive Complete Callback */ + huart->AbortReceiveCpltCallback(huart); +#else + /* Call legacy weak Abort Receive Complete Callback */ + DAL_UART_AbortReceiveCpltCallback(huart); +#endif /* USE_DAL_UART_REGISTER_CALLBACKS */ + } + + return DAL_OK; +} + +/** + * @brief This function handles UART interrupt request. + * @param huart Pointer to a UART_HandleTypeDef structure that contains + * the configuration information for the specified UART module. + * @retval None + */ +void DAL_UART_IRQHandler(UART_HandleTypeDef *huart) +{ + uint32_t isrflags = READ_REG(huart->Instance->STS); + uint32_t cr1its = READ_REG(huart->Instance->CTRL1); + uint32_t cr3its = READ_REG(huart->Instance->CTRL3); + uint32_t errorflags = 0x00U; + uint32_t dmarequest = 0x00U; + + /* If no error occurs */ + errorflags = (isrflags & (uint32_t)(USART_STS_PEFLG | USART_STS_FEFLG | USART_STS_OVREFLG | USART_STS_NEFLG)); + if (errorflags == RESET) + { + /* UART in mode Receiver -------------------------------------------------*/ + if (((isrflags & USART_STS_RXBNEFLG) != RESET) && ((cr1its & USART_CTRL1_RXBNEIEN) != RESET)) + { + UART_Receive_IT(huart); + return; + } + } + + /* If some errors occur */ + if ((errorflags != RESET) && (((cr3its & USART_CTRL3_ERRIEN) != RESET) + || ((cr1its & (USART_CTRL1_RXBNEIEN | USART_CTRL1_PEIEN)) != RESET))) + { + /* UART parity error interrupt occurred ----------------------------------*/ + if (((isrflags & USART_STS_PEFLG) != RESET) && ((cr1its & USART_CTRL1_PEIEN) != RESET)) + { + huart->ErrorCode |= DAL_UART_ERROR_PE; + } + + /* UART noise error interrupt occurred -----------------------------------*/ + if (((isrflags & USART_STS_NEFLG) != RESET) && ((cr3its & USART_CTRL3_ERRIEN) != RESET)) + { + huart->ErrorCode |= DAL_UART_ERROR_NE; + } + + /* UART frame error interrupt occurred -----------------------------------*/ + if (((isrflags & USART_STS_FEFLG) != RESET) && ((cr3its & USART_CTRL3_ERRIEN) != RESET)) + { + huart->ErrorCode |= DAL_UART_ERROR_FE; + } + + /* UART Over-Run interrupt occurred --------------------------------------*/ + if (((isrflags & USART_STS_OVREFLG) != RESET) && (((cr1its & USART_CTRL1_RXBNEIEN) != RESET) + || ((cr3its & USART_CTRL3_ERRIEN) != RESET))) + { + huart->ErrorCode |= DAL_UART_ERROR_ORE; + } + + /* Call UART Error Call back function if need be --------------------------*/ + if (huart->ErrorCode != DAL_UART_ERROR_NONE) + { + /* UART in mode Receiver -----------------------------------------------*/ + if (((isrflags & USART_STS_RXBNEFLG) != RESET) && ((cr1its & USART_CTRL1_RXBNEIEN) != RESET)) + { + UART_Receive_IT(huart); + } + + /* If Overrun error occurs, or if any error occurs in DMA mode reception, + consider error as blocking */ + dmarequest = DAL_IS_BIT_SET(huart->Instance->CTRL3, USART_CTRL3_DMARXEN); + if (((huart->ErrorCode & DAL_UART_ERROR_ORE) != RESET) || dmarequest) + { + /* Blocking error : transfer is aborted + Set the UART state ready to be able to start again the process, + Disable Rx Interrupts, and disable Rx DMA request, if ongoing */ + UART_EndRxTransfer(huart); + + /* Disable the UART DMA Rx request if enabled */ + if (DAL_IS_BIT_SET(huart->Instance->CTRL3, USART_CTRL3_DMARXEN)) + { + ATOMIC_CLEAR_BIT(huart->Instance->CTRL3, USART_CTRL3_DMARXEN); + + /* Abort the UART DMA Rx stream */ + if (huart->hdmarx != NULL) + { + /* Set the UART DMA Abort callback : + will lead to call DAL_UART_ErrorCallback() at end of DMA abort procedure */ + huart->hdmarx->XferAbortCallback = UART_DMAAbortOnError; + if (DAL_DMA_Abort_IT(huart->hdmarx) != DAL_OK) + { + /* Call Directly XferAbortCallback function in case of error */ + huart->hdmarx->XferAbortCallback(huart->hdmarx); + } + } + else + { + /* Call user error callback */ +#if (USE_DAL_UART_REGISTER_CALLBACKS == 1) + /*Call registered error callback*/ + huart->ErrorCallback(huart); +#else + /*Call legacy weak error callback*/ + DAL_UART_ErrorCallback(huart); +#endif /* USE_DAL_UART_REGISTER_CALLBACKS */ + } + } + else + { + /* Call user error callback */ +#if (USE_DAL_UART_REGISTER_CALLBACKS == 1) + /*Call registered error callback*/ + huart->ErrorCallback(huart); +#else + /*Call legacy weak error callback*/ + DAL_UART_ErrorCallback(huart); +#endif /* USE_DAL_UART_REGISTER_CALLBACKS */ + } + } + else + { + /* Non Blocking error : transfer could go on. + Error is notified to user through user error callback */ +#if (USE_DAL_UART_REGISTER_CALLBACKS == 1) + /*Call registered error callback*/ + huart->ErrorCallback(huart); +#else + /*Call legacy weak error callback*/ + DAL_UART_ErrorCallback(huart); +#endif /* USE_DAL_UART_REGISTER_CALLBACKS */ + + huart->ErrorCode = DAL_UART_ERROR_NONE; + } + } + return; + } /* End if some error occurs */ + + /* Check current reception Mode : + If Reception till IDLE event has been selected : */ + if ((huart->ReceptionType == DAL_UART_RECEPTION_TOIDLE) + && ((isrflags & USART_STS_IDLEFLG) != 0U) + && ((cr1its & USART_STS_IDLEFLG) != 0U)) + { + __DAL_UART_CLEAR_IDLEFLAG(huart); + + /* Check if DMA mode is enabled in UART */ + if (DAL_IS_BIT_SET(huart->Instance->CTRL3, USART_CTRL3_DMARXEN)) + { + /* DMA mode enabled */ + /* Check received length : If all expected data are received, do nothing, + (DMA cplt callback will be called). + Otherwise, if at least one data has already been received, IDLE event is to be notified to user */ + uint16_t nb_remaining_rx_data = (uint16_t) __DAL_DMA_GET_COUNTER(huart->hdmarx); + if ((nb_remaining_rx_data > 0U) + && (nb_remaining_rx_data < huart->RxXferSize)) + { + /* Reception is not complete */ + huart->RxXferCount = nb_remaining_rx_data; + + /* In Normal mode, end DMA xfer and DAL UART Rx process*/ + if (huart->hdmarx->Init.Mode != DMA_CIRCULAR) + { + /* Disable PEIEN and ERRIEN (Frame error, noise error, overrun error) interrupts */ + ATOMIC_CLEAR_BIT(huart->Instance->CTRL1, USART_CTRL1_PEIEN); + ATOMIC_CLEAR_BIT(huart->Instance->CTRL3, USART_CTRL3_ERRIEN); + + /* Disable the DMA transfer for the receiver request by resetting the DMAR bit + in the UART CTRL3 register */ + ATOMIC_CLEAR_BIT(huart->Instance->CTRL3, USART_CTRL3_DMARXEN); + + /* At end of Rx process, restore huart->RxState to Ready */ + huart->RxState = DAL_UART_STATE_READY; + huart->ReceptionType = DAL_UART_RECEPTION_STANDARD; + + ATOMIC_CLEAR_BIT(huart->Instance->CTRL1, USART_CTRL1_IDLEIEN); + + /* Last bytes received, so no need as the abort is immediate */ + (void)DAL_DMA_Abort(huart->hdmarx); + } +#if (USE_DAL_UART_REGISTER_CALLBACKS == 1) + /*Call registered Rx Event callback*/ + huart->RxEventCallback(huart, (huart->RxXferSize - huart->RxXferCount)); +#else + /*Call legacy weak Rx Event callback*/ + DAL_UARTEx_RxEventCallback(huart, (huart->RxXferSize - huart->RxXferCount)); +#endif /* USE_DAL_UART_REGISTER_CALLBACKS */ + } + return; + } + else + { + /* DMA mode not enabled */ + /* Check received length : If all expected data are received, do nothing. + Otherwise, if at least one data has already been received, IDLE event is to be notified to user */ + uint16_t nb_rx_data = huart->RxXferSize - huart->RxXferCount; + if ((huart->RxXferCount > 0U) + && (nb_rx_data > 0U)) + { + /* Disable the UART Parity Error Interrupt and RXBNEIEN interrupts */ + ATOMIC_CLEAR_BIT(huart->Instance->CTRL1, (USART_CTRL1_RXBNEIEN | USART_CTRL1_PEIEN)); + + /* Disable the UART Error Interrupt: (Frame error, noise error, overrun error) */ + ATOMIC_CLEAR_BIT(huart->Instance->CTRL3, USART_CTRL3_ERRIEN); + + /* Rx process is completed, restore huart->RxState to Ready */ + huart->RxState = DAL_UART_STATE_READY; + huart->ReceptionType = DAL_UART_RECEPTION_STANDARD; + + ATOMIC_CLEAR_BIT(huart->Instance->CTRL1, USART_CTRL1_IDLEIEN); +#if (USE_DAL_UART_REGISTER_CALLBACKS == 1) + /*Call registered Rx complete callback*/ + huart->RxEventCallback(huart, nb_rx_data); +#else + /*Call legacy weak Rx Event callback*/ + DAL_UARTEx_RxEventCallback(huart, nb_rx_data); +#endif /* USE_DAL_UART_REGISTER_CALLBACKS */ + } + return; + } + } + + /* UART in mode Transmitter ------------------------------------------------*/ + if (((isrflags & USART_STS_TXBEFLG) != RESET) && ((cr1its & USART_CTRL1_TXBEIEN) != RESET)) + { + UART_Transmit_IT(huart); + return; + } + + /* UART in mode Transmitter end --------------------------------------------*/ + if (((isrflags & USART_STS_TXCFLG) != RESET) && ((cr1its & USART_CTRL1_TXCIEN) != RESET)) + { + UART_EndTransmit_IT(huart); + return; + } +} + +/** + * @brief Tx Transfer completed callbacks. + * @param huart Pointer to a UART_HandleTypeDef structure that contains + * the configuration information for the specified UART module. + * @retval None + */ +__weak void DAL_UART_TxCpltCallback(UART_HandleTypeDef *huart) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(huart); + /* NOTE: This function should not be modified, when the callback is needed, + the DAL_UART_TxCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Tx Half Transfer completed callbacks. + * @param huart Pointer to a UART_HandleTypeDef structure that contains + * the configuration information for the specified UART module. + * @retval None + */ +__weak void DAL_UART_TxHalfCpltCallback(UART_HandleTypeDef *huart) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(huart); + /* NOTE: This function should not be modified, when the callback is needed, + the DAL_UART_TxHalfCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Rx Transfer completed callbacks. + * @param huart Pointer to a UART_HandleTypeDef structure that contains + * the configuration information for the specified UART module. + * @retval None + */ +__weak void DAL_UART_RxCpltCallback(UART_HandleTypeDef *huart) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(huart); + /* NOTE: This function should not be modified, when the callback is needed, + the DAL_UART_RxCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Rx Half Transfer completed callbacks. + * @param huart Pointer to a UART_HandleTypeDef structure that contains + * the configuration information for the specified UART module. + * @retval None + */ +__weak void DAL_UART_RxHalfCpltCallback(UART_HandleTypeDef *huart) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(huart); + /* NOTE: This function should not be modified, when the callback is needed, + the DAL_UART_RxHalfCpltCallback could be implemented in the user file + */ +} + +/** + * @brief UART error callbacks. + * @param huart Pointer to a UART_HandleTypeDef structure that contains + * the configuration information for the specified UART module. + * @retval None + */ +__weak void DAL_UART_ErrorCallback(UART_HandleTypeDef *huart) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(huart); + /* NOTE: This function should not be modified, when the callback is needed, + the DAL_UART_ErrorCallback could be implemented in the user file + */ +} + +/** + * @brief UART Abort Complete callback. + * @param huart UART handle. + * @retval None + */ +__weak void DAL_UART_AbortCpltCallback(UART_HandleTypeDef *huart) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(huart); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_UART_AbortCpltCallback can be implemented in the user file. + */ +} + +/** + * @brief UART Abort Complete callback. + * @param huart UART handle. + * @retval None + */ +__weak void DAL_UART_AbortTransmitCpltCallback(UART_HandleTypeDef *huart) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(huart); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_UART_AbortTransmitCpltCallback can be implemented in the user file. + */ +} + +/** + * @brief UART Abort Receive Complete callback. + * @param huart UART handle. + * @retval None + */ +__weak void DAL_UART_AbortReceiveCpltCallback(UART_HandleTypeDef *huart) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(huart); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_UART_AbortReceiveCpltCallback can be implemented in the user file. + */ +} + +/** + * @brief Reception Event Callback (Rx event notification called after use of advanced reception service). + * @param huart UART handle + * @param Size Number of data available in application reception buffer (indicates a position in + * reception buffer until which, data are available) + * @retval None + */ +__weak void DAL_UARTEx_RxEventCallback(UART_HandleTypeDef *huart, uint16_t Size) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(huart); + UNUSED(Size); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_UARTEx_RxEventCallback can be implemented in the user file. + */ +} + +/** + * @} + */ + +/** @defgroup UART_Exported_Functions_Group3 Peripheral Control functions + * @brief UART control functions + * +@verbatim + ============================================================================== + ##### Peripheral Control functions ##### + ============================================================================== + [..] + This subsection provides a set of functions allowing to control the UART: + (+) DAL_LIN_SendBreak() API can be helpful to transmit the break character. + (+) DAL_MultiProcessor_EnterMuteMode() API can be helpful to enter the UART in mute mode. + (+) DAL_MultiProcessor_ExitMuteMode() API can be helpful to exit the UART mute mode by software. + (+) DAL_HalfDuplex_EnableTransmitter() API to enable the UART transmitter and disables the UART receiver in Half Duplex mode + (+) DAL_HalfDuplex_EnableReceiver() API to enable the UART receiver and disables the UART transmitter in Half Duplex mode + +@endverbatim + * @{ + */ + +/** + * @brief Transmits break characters. + * @param huart Pointer to a UART_HandleTypeDef structure that contains + * the configuration information for the specified UART module. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_LIN_SendBreak(UART_HandleTypeDef *huart) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_UART_INSTANCE(huart->Instance)); + + /* Process Locked */ + __DAL_LOCK(huart); + + huart->gState = DAL_UART_STATE_BUSY; + + /* Send break characters */ + ATOMIC_SET_BIT(huart->Instance->CTRL1, USART_CTRL1_TXBF); + + huart->gState = DAL_UART_STATE_READY; + + /* Process Unlocked */ + __DAL_UNLOCK(huart); + + return DAL_OK; +} + +/** + * @brief Enters the UART in mute mode. + * @param huart Pointer to a UART_HandleTypeDef structure that contains + * the configuration information for the specified UART module. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_MultiProcessor_EnterMuteMode(UART_HandleTypeDef *huart) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_UART_INSTANCE(huart->Instance)); + + /* Process Locked */ + __DAL_LOCK(huart); + + huart->gState = DAL_UART_STATE_BUSY; + + /* Enable the USART mute mode by setting the RWU bit in the CTRL1 register */ + ATOMIC_SET_BIT(huart->Instance->CTRL1, USART_CTRL1_RXMUTEEN); + + huart->gState = DAL_UART_STATE_READY; + + /* Process Unlocked */ + __DAL_UNLOCK(huart); + + return DAL_OK; +} + +/** + * @brief Exits the UART mute mode: wake up software. + * @param huart Pointer to a UART_HandleTypeDef structure that contains + * the configuration information for the specified UART module. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_MultiProcessor_ExitMuteMode(UART_HandleTypeDef *huart) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_UART_INSTANCE(huart->Instance)); + + /* Process Locked */ + __DAL_LOCK(huart); + + huart->gState = DAL_UART_STATE_BUSY; + + /* Disable the USART mute mode by clearing the RWU bit in the CTRL1 register */ + ATOMIC_CLEAR_BIT(huart->Instance->CTRL1, USART_CTRL1_RXMUTEEN); + + huart->gState = DAL_UART_STATE_READY; + + /* Process Unlocked */ + __DAL_UNLOCK(huart); + + return DAL_OK; +} + +/** + * @brief Enables the UART transmitter and disables the UART receiver. + * @param huart Pointer to a UART_HandleTypeDef structure that contains + * the configuration information for the specified UART module. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_HalfDuplex_EnableTransmitter(UART_HandleTypeDef *huart) +{ + uint32_t tmpreg = 0x00U; + + /* Process Locked */ + __DAL_LOCK(huart); + + huart->gState = DAL_UART_STATE_BUSY; + + /*-------------------------- USART CTRL1 Configuration -----------------------*/ + tmpreg = huart->Instance->CTRL1; + + /* Clear TE and RE bits */ + tmpreg &= (uint32_t)~((uint32_t)(USART_CTRL1_TXEN | USART_CTRL1_RXEN)); + + /* Enable the USART's transmit interface by setting the TE bit in the USART CTRL1 register */ + tmpreg |= (uint32_t)USART_CTRL1_TXEN; + + /* Write to USART CTRL1 */ + WRITE_REG(huart->Instance->CTRL1, (uint32_t)tmpreg); + + huart->gState = DAL_UART_STATE_READY; + + /* Process Unlocked */ + __DAL_UNLOCK(huart); + + return DAL_OK; +} + +/** + * @brief Enables the UART receiver and disables the UART transmitter. + * @param huart Pointer to a UART_HandleTypeDef structure that contains + * the configuration information for the specified UART module. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_HalfDuplex_EnableReceiver(UART_HandleTypeDef *huart) +{ + uint32_t tmpreg = 0x00U; + + /* Process Locked */ + __DAL_LOCK(huart); + + huart->gState = DAL_UART_STATE_BUSY; + + /*-------------------------- USART CTRL1 Configuration -----------------------*/ + tmpreg = huart->Instance->CTRL1; + + /* Clear TE and RE bits */ + tmpreg &= (uint32_t)~((uint32_t)(USART_CTRL1_TXEN | USART_CTRL1_RXEN)); + + /* Enable the USART's receive interface by setting the RE bit in the USART CTRL1 register */ + tmpreg |= (uint32_t)USART_CTRL1_RXEN; + + /* Write to USART CTRL1 */ + WRITE_REG(huart->Instance->CTRL1, (uint32_t)tmpreg); + + huart->gState = DAL_UART_STATE_READY; + + /* Process Unlocked */ + __DAL_UNLOCK(huart); + + return DAL_OK; +} + +/** + * @} + */ + +/** @defgroup UART_Exported_Functions_Group4 Peripheral State and Errors functions + * @brief UART State and Errors functions + * +@verbatim + ============================================================================== + ##### Peripheral State and Errors functions ##### + ============================================================================== + [..] + This subsection provides a set of functions allowing to return the State of + UART communication process, return Peripheral Errors occurred during communication + process + (+) DAL_UART_GetState() API can be helpful to check in run-time the state of the UART peripheral. + (+) DAL_UART_GetError() check in run-time errors that could be occurred during communication. + +@endverbatim + * @{ + */ + +/** + * @brief Returns the UART state. + * @param huart Pointer to a UART_HandleTypeDef structure that contains + * the configuration information for the specified UART module. + * @retval DAL state + */ +DAL_UART_StateTypeDef DAL_UART_GetState(UART_HandleTypeDef *huart) +{ + uint32_t temp1 = 0x00U, temp2 = 0x00U; + temp1 = huart->gState; + temp2 = huart->RxState; + + return (DAL_UART_StateTypeDef)(temp1 | temp2); +} + +/** + * @brief Return the UART error code + * @param huart Pointer to a UART_HandleTypeDef structure that contains + * the configuration information for the specified UART. + * @retval UART Error Code + */ +uint32_t DAL_UART_GetError(UART_HandleTypeDef *huart) +{ + return huart->ErrorCode; +} + +/** + * @} + */ + +/** + * @} + */ + +/** @defgroup UART_Private_Functions UART Private Functions + * @{ + */ + +/** + * @brief Initialize the callbacks to their default values. + * @param huart UART handle. + * @retval none + */ +#if (USE_DAL_UART_REGISTER_CALLBACKS == 1) +void UART_InitCallbacksToDefault(UART_HandleTypeDef *huart) +{ + /* Init the UART Callback settings */ + huart->TxHalfCpltCallback = DAL_UART_TxHalfCpltCallback; /* Legacy weak TxHalfCpltCallback */ + huart->TxCpltCallback = DAL_UART_TxCpltCallback; /* Legacy weak TxCpltCallback */ + huart->RxHalfCpltCallback = DAL_UART_RxHalfCpltCallback; /* Legacy weak RxHalfCpltCallback */ + huart->RxCpltCallback = DAL_UART_RxCpltCallback; /* Legacy weak RxCpltCallback */ + huart->ErrorCallback = DAL_UART_ErrorCallback; /* Legacy weak ErrorCallback */ + huart->AbortCpltCallback = DAL_UART_AbortCpltCallback; /* Legacy weak AbortCpltCallback */ + huart->AbortTransmitCpltCallback = DAL_UART_AbortTransmitCpltCallback; /* Legacy weak AbortTransmitCpltCallback */ + huart->AbortReceiveCpltCallback = DAL_UART_AbortReceiveCpltCallback; /* Legacy weak AbortReceiveCpltCallback */ + huart->RxEventCallback = DAL_UARTEx_RxEventCallback; /* Legacy weak RxEventCallback */ + +} +#endif /* USE_DAL_UART_REGISTER_CALLBACKS */ + +/** + * @brief DMA UART transmit process complete callback. + * @param hdma Pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +static void UART_DMATransmitCplt(DMA_HandleTypeDef *hdma) +{ + UART_HandleTypeDef *huart = (UART_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + /* DMA Normal mode*/ + if ((hdma->Instance->SCFG & DMA_SCFGx_CIRCMEN) == 0U) + { + huart->TxXferCount = 0x00U; + + /* Disable the DMA transfer for transmit request by setting the DMAT bit + in the UART CTRL3 register */ + ATOMIC_CLEAR_BIT(huart->Instance->CTRL3, USART_CTRL3_DMATXEN); + + /* Enable the UART Transmit Complete Interrupt */ + ATOMIC_SET_BIT(huart->Instance->CTRL1, USART_CTRL1_TXCIEN); + + } + /* DMA Circular mode */ + else + { +#if (USE_DAL_UART_REGISTER_CALLBACKS == 1) + /*Call registered Tx complete callback*/ + huart->TxCpltCallback(huart); +#else + /*Call legacy weak Tx complete callback*/ + DAL_UART_TxCpltCallback(huart); +#endif /* USE_DAL_UART_REGISTER_CALLBACKS */ + } +} + +/** + * @brief DMA UART transmit process half complete callback + * @param hdma Pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +static void UART_DMATxHalfCplt(DMA_HandleTypeDef *hdma) +{ + UART_HandleTypeDef *huart = (UART_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + +#if (USE_DAL_UART_REGISTER_CALLBACKS == 1) + /*Call registered Tx complete callback*/ + huart->TxHalfCpltCallback(huart); +#else + /*Call legacy weak Tx complete callback*/ + DAL_UART_TxHalfCpltCallback(huart); +#endif /* USE_DAL_UART_REGISTER_CALLBACKS */ +} + +/** + * @brief DMA UART receive process complete callback. + * @param hdma Pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +static void UART_DMAReceiveCplt(DMA_HandleTypeDef *hdma) +{ + UART_HandleTypeDef *huart = (UART_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + /* DMA Normal mode*/ + if ((hdma->Instance->SCFG & DMA_SCFGx_CIRCMEN) == 0U) + { + huart->RxXferCount = 0U; + + /* Disable RXBNEIEN, PEIEN and ERRIEN (Frame error, noise error, overrun error) interrupts */ + ATOMIC_CLEAR_BIT(huart->Instance->CTRL1, USART_CTRL1_PEIEN); + ATOMIC_CLEAR_BIT(huart->Instance->CTRL3, USART_CTRL3_ERRIEN); + + /* Disable the DMA transfer for the receiver request by setting the DMAR bit + in the UART CTRL3 register */ + ATOMIC_CLEAR_BIT(huart->Instance->CTRL3, USART_CTRL3_DMARXEN); + + /* At end of Rx process, restore huart->RxState to Ready */ + huart->RxState = DAL_UART_STATE_READY; + + /* If Reception till IDLE event has been selected, Disable IDLE Interrupt */ + if (huart->ReceptionType == DAL_UART_RECEPTION_TOIDLE) + { + ATOMIC_CLEAR_BIT(huart->Instance->CTRL1, USART_CTRL1_IDLEIEN); + } + } + + /* Check current reception Mode : + If Reception till IDLE event has been selected : use Rx Event callback */ + if (huart->ReceptionType == DAL_UART_RECEPTION_TOIDLE) + { +#if (USE_DAL_UART_REGISTER_CALLBACKS == 1) + /*Call registered Rx Event callback*/ + huart->RxEventCallback(huart, huart->RxXferSize); +#else + /*Call legacy weak Rx Event callback*/ + DAL_UARTEx_RxEventCallback(huart, huart->RxXferSize); +#endif /* USE_DAL_UART_REGISTER_CALLBACKS */ + } + else + { + /* In other cases : use Rx Complete callback */ +#if (USE_DAL_UART_REGISTER_CALLBACKS == 1) + /*Call registered Rx complete callback*/ + huart->RxCpltCallback(huart); +#else + /*Call legacy weak Rx complete callback*/ + DAL_UART_RxCpltCallback(huart); +#endif /* USE_DAL_UART_REGISTER_CALLBACKS */ + } +} + +/** + * @brief DMA UART receive process half complete callback + * @param hdma Pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +static void UART_DMARxHalfCplt(DMA_HandleTypeDef *hdma) +{ + UART_HandleTypeDef *huart = (UART_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + + /* Check current reception Mode : + If Reception till IDLE event has been selected : use Rx Event callback */ + if (huart->ReceptionType == DAL_UART_RECEPTION_TOIDLE) + { +#if (USE_DAL_UART_REGISTER_CALLBACKS == 1) + /*Call registered Rx Event callback*/ + huart->RxEventCallback(huart, huart->RxXferSize / 2U); +#else + /*Call legacy weak Rx Event callback*/ + DAL_UARTEx_RxEventCallback(huart, huart->RxXferSize / 2U); +#endif /* USE_DAL_UART_REGISTER_CALLBACKS */ + } + else + { + /* In other cases : use Rx Half Complete callback */ +#if (USE_DAL_UART_REGISTER_CALLBACKS == 1) + /*Call registered Rx Half complete callback*/ + huart->RxHalfCpltCallback(huart); +#else + /*Call legacy weak Rx Half complete callback*/ + DAL_UART_RxHalfCpltCallback(huart); +#endif /* USE_DAL_UART_REGISTER_CALLBACKS */ + } +} + +/** + * @brief DMA UART communication error callback. + * @param hdma Pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +static void UART_DMAError(DMA_HandleTypeDef *hdma) +{ + uint32_t dmarequest = 0x00U; + UART_HandleTypeDef *huart = (UART_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + + /* Stop UART DMA Tx request if ongoing */ + dmarequest = DAL_IS_BIT_SET(huart->Instance->CTRL3, USART_CTRL3_DMATXEN); + if ((huart->gState == DAL_UART_STATE_BUSY_TX) && dmarequest) + { + huart->TxXferCount = 0x00U; + UART_EndTxTransfer(huart); + } + + /* Stop UART DMA Rx request if ongoing */ + dmarequest = DAL_IS_BIT_SET(huart->Instance->CTRL3, USART_CTRL3_DMARXEN); + if ((huart->RxState == DAL_UART_STATE_BUSY_RX) && dmarequest) + { + huart->RxXferCount = 0x00U; + UART_EndRxTransfer(huart); + } + + huart->ErrorCode |= DAL_UART_ERROR_DMA; +#if (USE_DAL_UART_REGISTER_CALLBACKS == 1) + /*Call registered error callback*/ + huart->ErrorCallback(huart); +#else + /*Call legacy weak error callback*/ + DAL_UART_ErrorCallback(huart); +#endif /* USE_DAL_UART_REGISTER_CALLBACKS */ +} + +/** + * @brief This function handles UART Communication Timeout. It waits + * until a flag is no longer in the specified status. + * @param huart Pointer to a UART_HandleTypeDef structure that contains + * the configuration information for the specified UART module. + * @param Flag specifies the UART flag to check. + * @param Status The actual Flag status (SET or RESET). + * @param Tickstart Tick start value + * @param Timeout Timeout duration + * @retval DAL status + */ +static DAL_StatusTypeDef UART_WaitOnFlagUntilTimeout(UART_HandleTypeDef *huart, uint32_t Flag, FlagStatus Status, + uint32_t Tickstart, uint32_t Timeout) +{ + /* Wait until flag is set */ + while ((__DAL_UART_GET_FLAG(huart, Flag) ? SET : RESET) == Status) + { + /* Check for the Timeout */ + if (Timeout != DAL_MAX_DELAY) + { + if ((Timeout == 0U) || ((DAL_GetTick() - Tickstart) > Timeout)) + { + /* Disable TXBEIEN, RXBNEIEN, PEIEN and ERRIEN (Frame error, noise error, overrun error) interrupts for the interrupt process */ + ATOMIC_CLEAR_BIT(huart->Instance->CTRL1, (USART_CTRL1_RXBNEIEN | USART_CTRL1_PEIEN | USART_CTRL1_TXBEIEN)); + ATOMIC_CLEAR_BIT(huart->Instance->CTRL3, USART_CTRL3_ERRIEN); + + huart->gState = DAL_UART_STATE_READY; + huart->RxState = DAL_UART_STATE_READY; + + /* Process Unlocked */ + __DAL_UNLOCK(huart); + + return DAL_TIMEOUT; + } + } + } + return DAL_OK; +} + +/** + * @brief Start Receive operation in interrupt mode. + * @note This function could be called by all DAL UART API providing reception in Interrupt mode. + * @note When calling this function, parameters validity is considered as already checked, + * i.e. Rx State, buffer address, ... + * UART Handle is assumed as Locked. + * @param huart UART handle. + * @param pData Pointer to data buffer (u8 or u16 data elements). + * @param Size Amount of data elements (u8 or u16) to be received. + * @retval DAL status + */ +DAL_StatusTypeDef UART_Start_Receive_IT(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size) +{ + huart->pRxBuffPtr = pData; + huart->RxXferSize = Size; + huart->RxXferCount = Size; + + huart->ErrorCode = DAL_UART_ERROR_NONE; + huart->RxState = DAL_UART_STATE_BUSY_RX; + + /* Process Unlocked */ + __DAL_UNLOCK(huart); + + if (huart->Init.Parity != UART_PARITY_NONE) + { + /* Enable the UART Parity Error Interrupt */ + __DAL_UART_ENABLE_IT(huart, UART_IT_PE); + } + + /* Enable the UART Error Interrupt: (Frame error, noise error, overrun error) */ + __DAL_UART_ENABLE_IT(huart, UART_IT_ERR); + + /* Enable the UART Data Register not empty Interrupt */ + __DAL_UART_ENABLE_IT(huart, UART_IT_RXNE); + + return DAL_OK; +} + +/** + * @brief Start Receive operation in DMA mode. + * @note This function could be called by all DAL UART API providing reception in DMA mode. + * @note When calling this function, parameters validity is considered as already checked, + * i.e. Rx State, buffer address, ... + * UART Handle is assumed as Locked. + * @param huart UART handle. + * @param pData Pointer to data buffer (u8 or u16 data elements). + * @param Size Amount of data elements (u8 or u16) to be received. + * @retval DAL status + */ +DAL_StatusTypeDef UART_Start_Receive_DMA(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size) +{ + uint32_t *tmp; + + huart->pRxBuffPtr = pData; + huart->RxXferSize = Size; + + huart->ErrorCode = DAL_UART_ERROR_NONE; + huart->RxState = DAL_UART_STATE_BUSY_RX; + + /* Set the UART DMA transfer complete callback */ + huart->hdmarx->XferCpltCallback = UART_DMAReceiveCplt; + + /* Set the UART DMA Half transfer complete callback */ + huart->hdmarx->XferHalfCpltCallback = UART_DMARxHalfCplt; + + /* Set the DMA error callback */ + huart->hdmarx->XferErrorCallback = UART_DMAError; + + /* Set the DMA abort callback */ + huart->hdmarx->XferAbortCallback = NULL; + + /* Enable the DMA stream */ + tmp = (uint32_t *)&pData; + DAL_DMA_Start_IT(huart->hdmarx, (uint32_t)&huart->Instance->DATA, *(uint32_t *)tmp, Size); + + /* Clear the Overrun flag just before enabling the DMA Rx request: can be mandatory for the second transfer */ + __DAL_UART_CLEAR_OREFLAG(huart); + + /* Process Unlocked */ + __DAL_UNLOCK(huart); + + if (huart->Init.Parity != UART_PARITY_NONE) + { + /* Enable the UART Parity Error Interrupt */ + ATOMIC_SET_BIT(huart->Instance->CTRL1, USART_CTRL1_PEIEN); + } + + /* Enable the UART Error Interrupt: (Frame error, noise error, overrun error) */ + ATOMIC_SET_BIT(huart->Instance->CTRL3, USART_CTRL3_ERRIEN); + + /* Enable the DMA transfer for the receiver request by setting the DMAR bit + in the UART CTRL3 register */ + ATOMIC_SET_BIT(huart->Instance->CTRL3, USART_CTRL3_DMARXEN); + + return DAL_OK; +} + +/** + * @brief End ongoing Tx transfer on UART peripheral (following error detection or Transmit completion). + * @param huart UART handle. + * @retval None + */ +static void UART_EndTxTransfer(UART_HandleTypeDef *huart) +{ + /* Disable TXBEIEN and TXCIEN interrupts */ + ATOMIC_CLEAR_BIT(huart->Instance->CTRL1, (USART_CTRL1_TXBEIEN | USART_CTRL1_TXCIEN)); + + /* At end of Tx process, restore huart->gState to Ready */ + huart->gState = DAL_UART_STATE_READY; +} + +/** + * @brief End ongoing Rx transfer on UART peripheral (following error detection or Reception completion). + * @param huart UART handle. + * @retval None + */ +static void UART_EndRxTransfer(UART_HandleTypeDef *huart) +{ + /* Disable RXBNEIEN, PEIEN and ERRIEN (Frame error, noise error, overrun error) interrupts */ + ATOMIC_CLEAR_BIT(huart->Instance->CTRL1, (USART_CTRL1_RXBNEIEN | USART_CTRL1_PEIEN)); + ATOMIC_CLEAR_BIT(huart->Instance->CTRL3, USART_CTRL3_ERRIEN); + + /* In case of reception waiting for IDLE event, disable also the IDLE IE interrupt source */ + if (huart->ReceptionType == DAL_UART_RECEPTION_TOIDLE) + { + ATOMIC_CLEAR_BIT(huart->Instance->CTRL1, USART_CTRL1_IDLEIEN); + } + + /* At end of Rx process, restore huart->RxState to Ready */ + huart->RxState = DAL_UART_STATE_READY; + huart->ReceptionType = DAL_UART_RECEPTION_STANDARD; +} + +/** + * @brief DMA UART communication abort callback, when initiated by DAL services on Error + * (To be called at end of DMA Abort procedure following error occurrence). + * @param hdma Pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +static void UART_DMAAbortOnError(DMA_HandleTypeDef *hdma) +{ + UART_HandleTypeDef *huart = (UART_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + huart->RxXferCount = 0x00U; + huart->TxXferCount = 0x00U; + +#if (USE_DAL_UART_REGISTER_CALLBACKS == 1) + /*Call registered error callback*/ + huart->ErrorCallback(huart); +#else + /*Call legacy weak error callback*/ + DAL_UART_ErrorCallback(huart); +#endif /* USE_DAL_UART_REGISTER_CALLBACKS */ +} + +/** + * @brief DMA UART Tx communication abort callback, when initiated by user + * (To be called at end of DMA Tx Abort procedure following user abort request). + * @note When this callback is executed, User Abort complete call back is called only if no + * Abort still ongoing for Rx DMA Handle. + * @param hdma Pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +static void UART_DMATxAbortCallback(DMA_HandleTypeDef *hdma) +{ + UART_HandleTypeDef *huart = (UART_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + + huart->hdmatx->XferAbortCallback = NULL; + + /* Check if an Abort process is still ongoing */ + if (huart->hdmarx != NULL) + { + if (huart->hdmarx->XferAbortCallback != NULL) + { + return; + } + } + + /* No Abort process still ongoing : All DMA channels are aborted, call user Abort Complete callback */ + huart->TxXferCount = 0x00U; + huart->RxXferCount = 0x00U; + + /* Reset ErrorCode */ + huart->ErrorCode = DAL_UART_ERROR_NONE; + + /* Restore huart->gState and huart->RxState to Ready */ + huart->gState = DAL_UART_STATE_READY; + huart->RxState = DAL_UART_STATE_READY; + huart->ReceptionType = DAL_UART_RECEPTION_STANDARD; + + /* Call user Abort complete callback */ +#if (USE_DAL_UART_REGISTER_CALLBACKS == 1) + /* Call registered Abort complete callback */ + huart->AbortCpltCallback(huart); +#else + /* Call legacy weak Abort complete callback */ + DAL_UART_AbortCpltCallback(huart); +#endif /* USE_DAL_UART_REGISTER_CALLBACKS */ +} + +/** + * @brief DMA UART Rx communication abort callback, when initiated by user + * (To be called at end of DMA Rx Abort procedure following user abort request). + * @note When this callback is executed, User Abort complete call back is called only if no + * Abort still ongoing for Tx DMA Handle. + * @param hdma Pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +static void UART_DMARxAbortCallback(DMA_HandleTypeDef *hdma) +{ + UART_HandleTypeDef *huart = (UART_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + + huart->hdmarx->XferAbortCallback = NULL; + + /* Check if an Abort process is still ongoing */ + if (huart->hdmatx != NULL) + { + if (huart->hdmatx->XferAbortCallback != NULL) + { + return; + } + } + + /* No Abort process still ongoing : All DMA channels are aborted, call user Abort Complete callback */ + huart->TxXferCount = 0x00U; + huart->RxXferCount = 0x00U; + + /* Reset ErrorCode */ + huart->ErrorCode = DAL_UART_ERROR_NONE; + + /* Restore huart->gState and huart->RxState to Ready */ + huart->gState = DAL_UART_STATE_READY; + huart->RxState = DAL_UART_STATE_READY; + huart->ReceptionType = DAL_UART_RECEPTION_STANDARD; + + /* Call user Abort complete callback */ +#if (USE_DAL_UART_REGISTER_CALLBACKS == 1) + /* Call registered Abort complete callback */ + huart->AbortCpltCallback(huart); +#else + /* Call legacy weak Abort complete callback */ + DAL_UART_AbortCpltCallback(huart); +#endif /* USE_DAL_UART_REGISTER_CALLBACKS */ +} + +/** + * @brief DMA UART Tx communication abort callback, when initiated by user by a call to + * DAL_UART_AbortTransmit_IT API (Abort only Tx transfer) + * (This callback is executed at end of DMA Tx Abort procedure following user abort request, + * and leads to user Tx Abort Complete callback execution). + * @param hdma Pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +static void UART_DMATxOnlyAbortCallback(DMA_HandleTypeDef *hdma) +{ + UART_HandleTypeDef *huart = (UART_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + + huart->TxXferCount = 0x00U; + + /* Restore huart->gState to Ready */ + huart->gState = DAL_UART_STATE_READY; + + /* Call user Abort complete callback */ +#if (USE_DAL_UART_REGISTER_CALLBACKS == 1) + /* Call registered Abort Transmit Complete Callback */ + huart->AbortTransmitCpltCallback(huart); +#else + /* Call legacy weak Abort Transmit Complete Callback */ + DAL_UART_AbortTransmitCpltCallback(huart); +#endif /* USE_DAL_UART_REGISTER_CALLBACKS */ +} + +/** + * @brief DMA UART Rx communication abort callback, when initiated by user by a call to + * DAL_UART_AbortReceive_IT API (Abort only Rx transfer) + * (This callback is executed at end of DMA Rx Abort procedure following user abort request, + * and leads to user Rx Abort Complete callback execution). + * @param hdma Pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +static void UART_DMARxOnlyAbortCallback(DMA_HandleTypeDef *hdma) +{ + UART_HandleTypeDef *huart = (UART_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + + huart->RxXferCount = 0x00U; + + /* Restore huart->RxState to Ready */ + huart->RxState = DAL_UART_STATE_READY; + huart->ReceptionType = DAL_UART_RECEPTION_STANDARD; + + /* Call user Abort complete callback */ +#if (USE_DAL_UART_REGISTER_CALLBACKS == 1) + /* Call registered Abort Receive Complete Callback */ + huart->AbortReceiveCpltCallback(huart); +#else + /* Call legacy weak Abort Receive Complete Callback */ + DAL_UART_AbortReceiveCpltCallback(huart); +#endif /* USE_DAL_UART_REGISTER_CALLBACKS */ +} + +/** + * @brief Sends an amount of data in non blocking mode. + * @param huart Pointer to a UART_HandleTypeDef structure that contains + * the configuration information for the specified UART module. + * @retval DAL status + */ +static DAL_StatusTypeDef UART_Transmit_IT(UART_HandleTypeDef *huart) +{ + const uint16_t *tmp; + + /* Check that a Tx process is ongoing */ + if (huart->gState == DAL_UART_STATE_BUSY_TX) + { + if ((huart->Init.WordLength == UART_WORDLENGTH_9B) && (huart->Init.Parity == UART_PARITY_NONE)) + { + tmp = (const uint16_t *) huart->pTxBuffPtr; + huart->Instance->DATA = (uint16_t)(*tmp & (uint16_t)0x01FF); + huart->pTxBuffPtr += 2U; + } + else + { + huart->Instance->DATA = (uint8_t)(*huart->pTxBuffPtr++ & (uint8_t)0x00FF); + } + + if (--huart->TxXferCount == 0U) + { + /* Disable the UART Transmit Data Register Empty Interrupt */ + __DAL_UART_DISABLE_IT(huart, UART_IT_TXE); + + /* Enable the UART Transmit Complete Interrupt */ + __DAL_UART_ENABLE_IT(huart, UART_IT_TC); + } + return DAL_OK; + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief Wraps up transmission in non blocking mode. + * @param huart Pointer to a UART_HandleTypeDef structure that contains + * the configuration information for the specified UART module. + * @retval DAL status + */ +static DAL_StatusTypeDef UART_EndTransmit_IT(UART_HandleTypeDef *huart) +{ + /* Disable the UART Transmit Complete Interrupt */ + __DAL_UART_DISABLE_IT(huart, UART_IT_TC); + + /* Tx process is ended, restore huart->gState to Ready */ + huart->gState = DAL_UART_STATE_READY; + +#if (USE_DAL_UART_REGISTER_CALLBACKS == 1) + /*Call registered Tx complete callback*/ + huart->TxCpltCallback(huart); +#else + /*Call legacy weak Tx complete callback*/ + DAL_UART_TxCpltCallback(huart); +#endif /* USE_DAL_UART_REGISTER_CALLBACKS */ + + return DAL_OK; +} + +/** + * @brief Receives an amount of data in non blocking mode + * @param huart Pointer to a UART_HandleTypeDef structure that contains + * the configuration information for the specified UART module. + * @retval DAL status + */ +static DAL_StatusTypeDef UART_Receive_IT(UART_HandleTypeDef *huart) +{ + uint8_t *pdata8bits; + uint16_t *pdata16bits; + + /* Check that a Rx process is ongoing */ + if (huart->RxState == DAL_UART_STATE_BUSY_RX) + { + if ((huart->Init.WordLength == UART_WORDLENGTH_9B) && (huart->Init.Parity == UART_PARITY_NONE)) + { + pdata8bits = NULL; + pdata16bits = (uint16_t *) huart->pRxBuffPtr; + *pdata16bits = (uint16_t)(huart->Instance->DATA & (uint16_t)0x01FF); + huart->pRxBuffPtr += 2U; + } + else + { + pdata8bits = (uint8_t *) huart->pRxBuffPtr; + pdata16bits = NULL; + + if ((huart->Init.WordLength == UART_WORDLENGTH_9B) || ((huart->Init.WordLength == UART_WORDLENGTH_8B) && (huart->Init.Parity == UART_PARITY_NONE))) + { + *pdata8bits = (uint8_t)(huart->Instance->DATA & (uint8_t)0x00FF); + } + else + { + *pdata8bits = (uint8_t)(huart->Instance->DATA & (uint8_t)0x007F); + } + huart->pRxBuffPtr += 1U; + } + + if (--huart->RxXferCount == 0U) + { + /* Disable the UART Data Register not empty Interrupt */ + __DAL_UART_DISABLE_IT(huart, UART_IT_RXNE); + + /* Disable the UART Parity Error Interrupt */ + __DAL_UART_DISABLE_IT(huart, UART_IT_PE); + + /* Disable the UART Error Interrupt: (Frame error, noise error, overrun error) */ + __DAL_UART_DISABLE_IT(huart, UART_IT_ERR); + + /* Rx process is completed, restore huart->RxState to Ready */ + huart->RxState = DAL_UART_STATE_READY; + + /* Check current reception Mode : + If Reception till IDLE event has been selected : */ + if (huart->ReceptionType == DAL_UART_RECEPTION_TOIDLE) + { + /* Set reception type to Standard */ + huart->ReceptionType = DAL_UART_RECEPTION_STANDARD; + + /* Disable IDLE interrupt */ + ATOMIC_CLEAR_BIT(huart->Instance->CTRL1, USART_CTRL1_IDLEIEN); + + /* Check if IDLE flag is set */ + if (__DAL_UART_GET_FLAG(huart, UART_FLAG_IDLE)) + { + /* Clear IDLE flag in ISR */ + __DAL_UART_CLEAR_IDLEFLAG(huart); + } + +#if (USE_DAL_UART_REGISTER_CALLBACKS == 1) + /*Call registered Rx Event callback*/ + huart->RxEventCallback(huart, huart->RxXferSize); +#else + /*Call legacy weak Rx Event callback*/ + DAL_UARTEx_RxEventCallback(huart, huart->RxXferSize); +#endif /* USE_DAL_UART_REGISTER_CALLBACKS */ + } + else + { + /* Standard reception API called */ +#if (USE_DAL_UART_REGISTER_CALLBACKS == 1) + /*Call registered Rx complete callback*/ + huart->RxCpltCallback(huart); +#else + /*Call legacy weak Rx complete callback*/ + DAL_UART_RxCpltCallback(huart); +#endif /* USE_DAL_UART_REGISTER_CALLBACKS */ + } + + return DAL_OK; + } + return DAL_OK; + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief Configures the UART peripheral. + * @param huart Pointer to a UART_HandleTypeDef structure that contains + * the configuration information for the specified UART module. + * @retval None + */ +static void UART_SetConfig(UART_HandleTypeDef *huart) +{ + uint32_t tmpreg; + uint32_t pclk; + + /* Check the parameters */ + ASSERT_PARAM(IS_UART_BAUDRATE(huart->Init.BaudRate)); + ASSERT_PARAM(IS_UART_STOPBITS(huart->Init.StopBits)); + ASSERT_PARAM(IS_UART_PARITY(huart->Init.Parity)); + ASSERT_PARAM(IS_UART_MODE(huart->Init.Mode)); + + /*-------------------------- USART CTRL2 Configuration -----------------------*/ + /* Configure the UART Stop Bits: Set STOP[13:12] bits + according to huart->Init.StopBits value */ + MODIFY_REG(huart->Instance->CTRL2, USART_CTRL2_STOPCFG, huart->Init.StopBits); + + /*-------------------------- USART CTRL1 Configuration -----------------------*/ + /* Configure the UART Word Length, Parity and mode: + Set the M bits according to huart->Init.WordLength value + Set PCE and PS bits according to huart->Init.Parity value + Set TE and RE bits according to huart->Init.Mode value + Set OVER8 bit according to huart->Init.OverSampling value */ + + tmpreg = (uint32_t)huart->Init.WordLength | huart->Init.Parity | huart->Init.Mode | huart->Init.OverSampling; + MODIFY_REG(huart->Instance->CTRL1, + (uint32_t)(USART_CTRL1_DBLCFG | USART_CTRL1_PCEN | USART_CTRL1_PCFG | USART_CTRL1_TXEN | USART_CTRL1_RXEN | USART_CTRL1_OSMCFG), + tmpreg); + + /*-------------------------- USART CTRL3 Configuration -----------------------*/ + /* Configure the UART HFC: Set CTSE and RTSE bits according to huart->Init.HwFlowCtl value */ + MODIFY_REG(huart->Instance->CTRL3, (USART_CTRL3_RTSEN | USART_CTRL3_CTSEN), huart->Init.HwFlowCtl); + + +#if defined(USART6) && defined(UART9) && defined(UART10) + if ((huart->Instance == USART1) || (huart->Instance == USART6) || (huart->Instance == UART9) || (huart->Instance == UART10)) + { + pclk = DAL_RCM_GetPCLK2Freq(); + } +#elif defined(USART6) + if ((huart->Instance == USART1) || (huart->Instance == USART6)) + { + pclk = DAL_RCM_GetPCLK2Freq(); + } +#else + if (huart->Instance == USART1) + { + pclk = DAL_RCM_GetPCLK2Freq(); + } +#endif /* USART6 */ + else + { + pclk = DAL_RCM_GetPCLK1Freq(); + } + /*-------------------------- USART BR Configuration ---------------------*/ + if (huart->Init.OverSampling == UART_OVERSAMPLING_8) + { + huart->Instance->BR = UART_BR_SAMPLING8(pclk, huart->Init.BaudRate); + } + else + { + huart->Instance->BR = UART_BR_SAMPLING16(pclk, huart->Init.BaudRate); + } +} + +/** + * @} + */ + +#endif /* DAL_UART_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_usart.c b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_usart.c new file mode 100644 index 0000000000..2bee268d5c --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_usart.c @@ -0,0 +1,2859 @@ +/** + * + * @file apm32f4xx_dal_usart.c + * @brief USART DAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the Universal Synchronous/Asynchronous Receiver Transmitter + * Peripheral (USART). + * + Initialization and de-initialization functions + * + IO operation functions + * + Peripheral Control functions + * + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + * + @verbatim + ============================================================================== + ##### How to use this driver ##### + ============================================================================== + [..] + The USART DAL driver can be used as follows: + + (#) Declare a USART_HandleTypeDef handle structure (eg. USART_HandleTypeDef husart). + (#) Initialize the USART low level resources by implementing the DAL_USART_MspInit() API: + (##) Enable the USARTx interface clock. + (##) USART pins configuration: + (+++) Enable the clock for the USART GPIOs. + (+++) Configure the USART pins as alternate function pull-up. + (##) NVIC configuration if you need to use interrupt process (DAL_USART_Transmit_IT(), + DAL_USART_Receive_IT() and DAL_USART_TransmitReceive_IT() APIs): + (+++) Configure the USARTx interrupt priority. + (+++) Enable the NVIC USART IRQ handle. + (##) DMA Configuration if you need to use DMA process (DAL_USART_Transmit_DMA() + DAL_USART_Receive_DMA() and DAL_USART_TransmitReceive_DMA() APIs): + (+++) Declare a DMA handle structure for the Tx/Rx stream. + (+++) Enable the DMAx interface clock. + (+++) Configure the declared DMA handle structure with the required Tx/Rx parameters. + (+++) Configure the DMA Tx/Rx stream. + (+++) Associate the initialized DMA handle to the USART DMA Tx/Rx handle. + (+++) Configure the priority and enable the NVIC for the transfer complete interrupt on the DMA Tx/Rx stream. + (+++) Configure the USARTx interrupt priority and enable the NVIC USART IRQ handle + (used for last byte sending completion detection in DMA non circular mode) + + (#) Program the Baud Rate, Word Length, Stop Bit, Parity, Hardware + flow control and Mode(Receiver/Transmitter) in the husart Init structure. + + (#) Initialize the USART registers by calling the DAL_USART_Init() API: + (++) These APIs configures also the low level Hardware GPIO, CLOCK, CORTEX...etc) + by calling the customized DAL_USART_MspInit(&husart) API. + + -@@- The specific USART interrupts (Transmission complete interrupt, + RXNE interrupt and Error Interrupts) will be managed using the macros + __DAL_USART_ENABLE_IT() and __DAL_USART_DISABLE_IT() inside the transmit and receive process. + + (#) Three operation modes are available within this driver : + + *** Polling mode IO operation *** + ================================= + [..] + (+) Send an amount of data in blocking mode using DAL_USART_Transmit() + (+) Receive an amount of data in blocking mode using DAL_USART_Receive() + + *** Interrupt mode IO operation *** + =================================== + [..] + (+) Send an amount of data in non blocking mode using DAL_USART_Transmit_IT() + (+) At transmission end of transfer DAL_USART_TxHalfCpltCallback is executed and user can + add his own code by customization of function pointer DAL_USART_TxCpltCallback + (+) Receive an amount of data in non blocking mode using DAL_USART_Receive_IT() + (+) At reception end of transfer DAL_USART_RxCpltCallback is executed and user can + add his own code by customization of function pointer DAL_USART_RxCpltCallback + (+) In case of transfer Error, DAL_USART_ErrorCallback() function is executed and user can + add his own code by customization of function pointer DAL_USART_ErrorCallback + + *** DMA mode IO operation *** + ============================== + [..] + (+) Send an amount of data in non blocking mode (DMA) using DAL_USART_Transmit_DMA() + (+) At transmission end of half transfer DAL_USART_TxHalfCpltCallback is executed and user can + add his own code by customization of function pointer DAL_USART_TxHalfCpltCallback + (+) At transmission end of transfer DAL_USART_TxCpltCallback is executed and user can + add his own code by customization of function pointer DAL_USART_TxCpltCallback + (+) Receive an amount of data in non blocking mode (DMA) using DAL_USART_Receive_DMA() + (+) At reception end of half transfer DAL_USART_RxHalfCpltCallback is executed and user can + add his own code by customization of function pointer DAL_USART_RxHalfCpltCallback + (+) At reception end of transfer DAL_USART_RxCpltCallback is executed and user can + add his own code by customization of function pointer DAL_USART_RxCpltCallback + (+) In case of transfer Error, DAL_USART_ErrorCallback() function is executed and user can + add his own code by customization of function pointer DAL_USART_ErrorCallback + (+) Pause the DMA Transfer using DAL_USART_DMAPause() + (+) Resume the DMA Transfer using DAL_USART_DMAResume() + (+) Stop the DMA Transfer using DAL_USART_DMAStop() + + *** USART DAL driver macros list *** + ============================================= + [..] + Below the list of most used macros in USART DAL driver. + + (+) __DAL_USART_ENABLE: Enable the USART peripheral + (+) __DAL_USART_DISABLE: Disable the USART peripheral + (+) __DAL_USART_GET_FLAG : Check whether the specified USART flag is set or not + (+) __DAL_USART_CLEAR_FLAG : Clear the specified USART pending flag + (+) __DAL_USART_ENABLE_IT: Enable the specified USART interrupt + (+) __DAL_USART_DISABLE_IT: Disable the specified USART interrupt + + [..] + (@) You can refer to the USART DAL driver header file for more useful macros + + ##### Callback registration ##### + ================================== + + [..] + The compilation define USE_DAL_USART_REGISTER_CALLBACKS when set to 1 + allows the user to configure dynamically the driver callbacks. + + [..] + Use Function @ref DAL_USART_RegisterCallback() to register a user callback. + Function @ref DAL_USART_RegisterCallback() allows to register following callbacks: + (+) TxHalfCpltCallback : Tx Half Complete Callback. + (+) TxCpltCallback : Tx Complete Callback. + (+) RxHalfCpltCallback : Rx Half Complete Callback. + (+) RxCpltCallback : Rx Complete Callback. + (+) TxRxCpltCallback : Tx Rx Complete Callback. + (+) ErrorCallback : Error Callback. + (+) AbortCpltCallback : Abort Complete Callback. + (+) MspInitCallback : USART MspInit. + (+) MspDeInitCallback : USART MspDeInit. + This function takes as parameters the DAL peripheral handle, the Callback ID + and a pointer to the user callback function. + + [..] + Use function @ref DAL_USART_UnRegisterCallback() to reset a callback to the default + weak (surcharged) function. + @ref DAL_USART_UnRegisterCallback() takes as parameters the DAL peripheral handle, + and the Callback ID. + This function allows to reset following callbacks: + (+) TxHalfCpltCallback : Tx Half Complete Callback. + (+) TxCpltCallback : Tx Complete Callback. + (+) RxHalfCpltCallback : Rx Half Complete Callback. + (+) RxCpltCallback : Rx Complete Callback. + (+) TxRxCpltCallback : Tx Rx Complete Callback. + (+) ErrorCallback : Error Callback. + (+) AbortCpltCallback : Abort Complete Callback. + (+) MspInitCallback : USART MspInit. + (+) MspDeInitCallback : USART MspDeInit. + + [..] + By default, after the @ref DAL_USART_Init() and when the state is DAL_USART_STATE_RESET + all callbacks are set to the corresponding weak (surcharged) functions: + examples @ref DAL_USART_TxCpltCallback(), @ref DAL_USART_RxHalfCpltCallback(). + Exception done for MspInit and MspDeInit functions that are respectively + reset to the legacy weak (surcharged) functions in the @ref DAL_USART_Init() + and @ref DAL_USART_DeInit() only when these callbacks are null (not registered beforehand). + If not, MspInit or MspDeInit are not null, the @ref DAL_USART_Init() and @ref DAL_USART_DeInit() + keep and use the user MspInit/MspDeInit callbacks (registered beforehand). + + [..] + Callbacks can be registered/unregistered in DAL_USART_STATE_READY state only. + Exception done MspInit/MspDeInit that can be registered/unregistered + in DAL_USART_STATE_READY or DAL_USART_STATE_RESET state, thus registered (user) + MspInit/DeInit callbacks can be used during the Init/DeInit. + In that case first register the MspInit/MspDeInit user callbacks + using @ref DAL_USART_RegisterCallback() before calling @ref DAL_USART_DeInit() + or @ref DAL_USART_Init() function. + + [..] + When The compilation define USE_DAL_USART_REGISTER_CALLBACKS is set to 0 or + not defined, the callback registration feature is not available + and weak (surcharged) callbacks are used. + + @endverbatim + [..] + (@) Additional remark: If the parity is enabled, then the MSB bit of the data written + in the data register is transmitted but is changed by the parity bit. + Depending on the frame length defined by the M bit (8-bits or 9-bits), + the possible USART frame formats are as listed in the following table: + +-------------------------------------------------------------+ + | M bit | PCE bit | USART frame | + |---------------------|---------------------------------------| + | 0 | 0 | | SB | 8 bit data | STB | | + |---------|-----------|---------------------------------------| + | 0 | 1 | | SB | 7 bit data | PB | STB | | + |---------|-----------|---------------------------------------| + | 1 | 0 | | SB | 9 bit data | STB | | + |---------|-----------|---------------------------------------| + | 1 | 1 | | SB | 8 bit data | PB | STB | | + +-------------------------------------------------------------+ + * + */ + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @defgroup USART USART + * @brief DAL USART Synchronous module driver + * @{ + */ +#ifdef DAL_USART_MODULE_ENABLED +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/** @addtogroup USART_Private_Constants + * @{ + */ +#define DUMMY_DATA 0xFFFFU +#define USART_TIMEOUT_VALUE 22000U +/** + * @} + */ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ +/** @addtogroup USART_Private_Functions + * @{ + */ +#if (USE_DAL_USART_REGISTER_CALLBACKS == 1) +void USART_InitCallbacksToDefault(USART_HandleTypeDef *husart); +#endif /* USE_DAL_USART_REGISTER_CALLBACKS */ +static void USART_EndTxTransfer(USART_HandleTypeDef *husart); +static void USART_EndRxTransfer(USART_HandleTypeDef *husart); +static DAL_StatusTypeDef USART_Transmit_IT(USART_HandleTypeDef *husart); +static DAL_StatusTypeDef USART_EndTransmit_IT(USART_HandleTypeDef *husart); +static DAL_StatusTypeDef USART_Receive_IT(USART_HandleTypeDef *husart); +static DAL_StatusTypeDef USART_TransmitReceive_IT(USART_HandleTypeDef *husart); +static void USART_SetConfig(USART_HandleTypeDef *husart); +static void USART_DMATransmitCplt(DMA_HandleTypeDef *hdma); +static void USART_DMATxHalfCplt(DMA_HandleTypeDef *hdma); +static void USART_DMAReceiveCplt(DMA_HandleTypeDef *hdma); +static void USART_DMARxHalfCplt(DMA_HandleTypeDef *hdma); +static void USART_DMAError(DMA_HandleTypeDef *hdma); +static void USART_DMAAbortOnError(DMA_HandleTypeDef *hdma); +static void USART_DMATxAbortCallback(DMA_HandleTypeDef *hdma); +static void USART_DMARxAbortCallback(DMA_HandleTypeDef *hdma); + +static DAL_StatusTypeDef USART_WaitOnFlagUntilTimeout(USART_HandleTypeDef *husart, uint32_t Flag, FlagStatus Status, + uint32_t Tickstart, uint32_t Timeout); +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +/** @defgroup USART_Exported_Functions USART Exported Functions + * @{ + */ + +/** @defgroup USART_Exported_Functions_Group1 USART Initialization and de-initialization functions + * @brief Initialization and Configuration functions + * +@verbatim + ============================================================================== + ##### Initialization and Configuration functions ##### + ============================================================================== + [..] + This subsection provides a set of functions allowing to initialize the USART + in asynchronous and in synchronous modes. + (+) For the asynchronous mode only these parameters can be configured: + (++) Baud Rate + (++) Word Length + (++) Stop Bit + (++) Parity: If the parity is enabled, then the MSB bit of the data written + in the data register is transmitted but is changed by the parity bit. + Depending on the frame length defined by the M bit (8-bits or 9-bits), + please refer to Reference manual for possible USART frame formats. + (++) USART polarity + (++) USART phase + (++) USART LastBit + (++) Receiver/transmitter modes + + [..] + The DAL_USART_Init() function follows the USART synchronous configuration + procedures (details for the procedures are available in reference manual). + +@endverbatim + * @{ + */ + +/** + * @brief Initialize the USART mode according to the specified + * parameters in the USART_InitTypeDef and initialize the associated handle. + * @param husart Pointer to a USART_HandleTypeDef structure that contains + * the configuration information for the specified USART module. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_USART_Init(USART_HandleTypeDef *husart) +{ + /* Check the USART handle allocation */ + if (husart == NULL) + { + return DAL_ERROR; + } + + /* Check the parameters */ + ASSERT_PARAM(IS_USART_INSTANCE(husart->Instance)); + + if (husart->State == DAL_USART_STATE_RESET) + { + /* Allocate lock resource and initialize it */ + husart->Lock = DAL_UNLOCKED; + +#if (USE_DAL_USART_REGISTER_CALLBACKS == 1) + USART_InitCallbacksToDefault(husart); + + if (husart->MspInitCallback == NULL) + { + husart->MspInitCallback = DAL_USART_MspInit; + } + + /* Init the low level hardware */ + husart->MspInitCallback(husart); +#else + /* Init the low level hardware : GPIO, CLOCK */ + DAL_USART_MspInit(husart); +#endif /* USE_DAL_USART_REGISTER_CALLBACKS */ + } + + husart->State = DAL_USART_STATE_BUSY; + + /* Set the USART Communication parameters */ + USART_SetConfig(husart); + + /* In USART mode, the following bits must be kept cleared: + - LINEN bit in the USART_CTRL2 register + - HDSEL, SCEN and IREN bits in the USART_CTRL3 register */ + CLEAR_BIT(husart->Instance->CTRL2, USART_CTRL2_LINMEN); + CLEAR_BIT(husart->Instance->CTRL3, (USART_CTRL3_SCEN | USART_CTRL3_HDEN | USART_CTRL3_IREN)); + + /* Enable the Peripheral */ + __DAL_USART_ENABLE(husart); + + /* Initialize the USART state */ + husart->ErrorCode = DAL_USART_ERROR_NONE; + husart->State = DAL_USART_STATE_READY; + + return DAL_OK; +} + +/** + * @brief DeInitializes the USART peripheral. + * @param husart Pointer to a USART_HandleTypeDef structure that contains + * the configuration information for the specified USART module. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_USART_DeInit(USART_HandleTypeDef *husart) +{ + /* Check the USART handle allocation */ + if (husart == NULL) + { + return DAL_ERROR; + } + + /* Check the parameters */ + ASSERT_PARAM(IS_USART_INSTANCE(husart->Instance)); + + husart->State = DAL_USART_STATE_BUSY; + + /* Disable the Peripheral */ + __DAL_USART_DISABLE(husart); + +#if (USE_DAL_USART_REGISTER_CALLBACKS == 1) + if (husart->MspDeInitCallback == NULL) + { + husart->MspDeInitCallback = DAL_USART_MspDeInit; + } + /* DeInit the low level hardware */ + husart->MspDeInitCallback(husart); +#else + /* DeInit the low level hardware */ + DAL_USART_MspDeInit(husart); +#endif /* USE_DAL_USART_REGISTER_CALLBACKS */ + + husart->ErrorCode = DAL_USART_ERROR_NONE; + husart->State = DAL_USART_STATE_RESET; + + /* Release Lock */ + __DAL_UNLOCK(husart); + + return DAL_OK; +} + +/** + * @brief USART MSP Init. + * @param husart Pointer to a USART_HandleTypeDef structure that contains + * the configuration information for the specified USART module. + * @retval None + */ +__weak void DAL_USART_MspInit(USART_HandleTypeDef *husart) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(husart); + /* NOTE: This function should not be modified, when the callback is needed, + the DAL_USART_MspInit could be implemented in the user file + */ +} + +/** + * @brief USART MSP DeInit. + * @param husart Pointer to a USART_HandleTypeDef structure that contains + * the configuration information for the specified USART module. + * @retval None + */ +__weak void DAL_USART_MspDeInit(USART_HandleTypeDef *husart) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(husart); + /* NOTE: This function should not be modified, when the callback is needed, + the DAL_USART_MspDeInit could be implemented in the user file + */ +} + +#if (USE_DAL_USART_REGISTER_CALLBACKS == 1) +/** + * @brief Register a User USART Callback + * To be used instead of the weak predefined callback + * @param husart usart handle + * @param CallbackID ID of the callback to be registered + * This parameter can be one of the following values: + * @arg @ref DAL_USART_TX_HALFCOMPLETE_CB_ID Tx Half Complete Callback ID + * @arg @ref DAL_USART_TX_COMPLETE_CB_ID Tx Complete Callback ID + * @arg @ref DAL_USART_RX_HALFCOMPLETE_CB_ID Rx Half Complete Callback ID + * @arg @ref DAL_USART_RX_COMPLETE_CB_ID Rx Complete Callback ID + * @arg @ref DAL_USART_TX_RX_COMPLETE_CB_ID Rx Complete Callback ID + * @arg @ref DAL_USART_ERROR_CB_ID Error Callback ID + * @arg @ref DAL_USART_ABORT_COMPLETE_CB_ID Abort Complete Callback ID + * @arg @ref DAL_USART_MSPINIT_CB_ID MspInit Callback ID + * @arg @ref DAL_USART_MSPDEINIT_CB_ID MspDeInit Callback ID + * @param pCallback pointer to the Callback function + * @retval DAL status ++ */ +DAL_StatusTypeDef DAL_USART_RegisterCallback(USART_HandleTypeDef *husart, DAL_USART_CallbackIDTypeDef CallbackID, + pUSART_CallbackTypeDef pCallback) +{ + DAL_StatusTypeDef status = DAL_OK; + + if (pCallback == NULL) + { + /* Update the error code */ + husart->ErrorCode |= DAL_USART_ERROR_INVALID_CALLBACK; + + return DAL_ERROR; + } + /* Process locked */ + __DAL_LOCK(husart); + + if (husart->State == DAL_USART_STATE_READY) + { + switch (CallbackID) + { + case DAL_USART_TX_HALFCOMPLETE_CB_ID : + husart->TxHalfCpltCallback = pCallback; + break; + + case DAL_USART_TX_COMPLETE_CB_ID : + husart->TxCpltCallback = pCallback; + break; + + case DAL_USART_RX_HALFCOMPLETE_CB_ID : + husart->RxHalfCpltCallback = pCallback; + break; + + case DAL_USART_RX_COMPLETE_CB_ID : + husart->RxCpltCallback = pCallback; + break; + + case DAL_USART_TX_RX_COMPLETE_CB_ID : + husart->TxRxCpltCallback = pCallback; + break; + + case DAL_USART_ERROR_CB_ID : + husart->ErrorCallback = pCallback; + break; + + case DAL_USART_ABORT_COMPLETE_CB_ID : + husart->AbortCpltCallback = pCallback; + break; + + case DAL_USART_MSPINIT_CB_ID : + husart->MspInitCallback = pCallback; + break; + + case DAL_USART_MSPDEINIT_CB_ID : + husart->MspDeInitCallback = pCallback; + break; + + default : + /* Update the error code */ + husart->ErrorCode |= DAL_USART_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = DAL_ERROR; + break; + } + } + else if (husart->State == DAL_USART_STATE_RESET) + { + switch (CallbackID) + { + case DAL_USART_MSPINIT_CB_ID : + husart->MspInitCallback = pCallback; + break; + + case DAL_USART_MSPDEINIT_CB_ID : + husart->MspDeInitCallback = pCallback; + break; + + default : + /* Update the error code */ + husart->ErrorCode |= DAL_USART_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = DAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + husart->ErrorCode |= DAL_USART_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = DAL_ERROR; + } + + /* Release Lock */ + __DAL_UNLOCK(husart); + + return status; +} + +/** + * @brief Unregister an USART Callback + * USART callaback is redirected to the weak predefined callback + * @param husart usart handle + * @param CallbackID ID of the callback to be unregistered + * This parameter can be one of the following values: + * @arg @ref DAL_USART_TX_HALFCOMPLETE_CB_ID Tx Half Complete Callback ID + * @arg @ref DAL_USART_TX_COMPLETE_CB_ID Tx Complete Callback ID + * @arg @ref DAL_USART_RX_HALFCOMPLETE_CB_ID Rx Half Complete Callback ID + * @arg @ref DAL_USART_RX_COMPLETE_CB_ID Rx Complete Callback ID + * @arg @ref DAL_USART_TX_RX_COMPLETE_CB_ID Rx Complete Callback ID + * @arg @ref DAL_USART_ERROR_CB_ID Error Callback ID + * @arg @ref DAL_USART_ABORT_COMPLETE_CB_ID Abort Complete Callback ID + * @arg @ref DAL_USART_MSPINIT_CB_ID MspInit Callback ID + * @arg @ref DAL_USART_MSPDEINIT_CB_ID MspDeInit Callback ID + * @retval DAL status + */ +DAL_StatusTypeDef DAL_USART_UnRegisterCallback(USART_HandleTypeDef *husart, DAL_USART_CallbackIDTypeDef CallbackID) +{ + DAL_StatusTypeDef status = DAL_OK; + + /* Process locked */ + __DAL_LOCK(husart); + + if (husart->State == DAL_USART_STATE_READY) + { + switch (CallbackID) + { + case DAL_USART_TX_HALFCOMPLETE_CB_ID : + husart->TxHalfCpltCallback = DAL_USART_TxHalfCpltCallback; /* Legacy weak TxHalfCpltCallback */ + break; + + case DAL_USART_TX_COMPLETE_CB_ID : + husart->TxCpltCallback = DAL_USART_TxCpltCallback; /* Legacy weak TxCpltCallback */ + break; + + case DAL_USART_RX_HALFCOMPLETE_CB_ID : + husart->RxHalfCpltCallback = DAL_USART_RxHalfCpltCallback; /* Legacy weak RxHalfCpltCallback */ + break; + + case DAL_USART_RX_COMPLETE_CB_ID : + husart->RxCpltCallback = DAL_USART_RxCpltCallback; /* Legacy weak RxCpltCallback */ + break; + + case DAL_USART_TX_RX_COMPLETE_CB_ID : + husart->TxRxCpltCallback = DAL_USART_TxRxCpltCallback; /* Legacy weak TxRxCpltCallback */ + break; + + case DAL_USART_ERROR_CB_ID : + husart->ErrorCallback = DAL_USART_ErrorCallback; /* Legacy weak ErrorCallback */ + break; + + case DAL_USART_ABORT_COMPLETE_CB_ID : + husart->AbortCpltCallback = DAL_USART_AbortCpltCallback; /* Legacy weak AbortCpltCallback */ + break; + + case DAL_USART_MSPINIT_CB_ID : + husart->MspInitCallback = DAL_USART_MspInit; /* Legacy weak MspInitCallback */ + break; + + case DAL_USART_MSPDEINIT_CB_ID : + husart->MspDeInitCallback = DAL_USART_MspDeInit; /* Legacy weak MspDeInitCallback */ + break; + + default : + /* Update the error code */ + husart->ErrorCode |= DAL_USART_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = DAL_ERROR; + break; + } + } + else if (husart->State == DAL_USART_STATE_RESET) + { + switch (CallbackID) + { + case DAL_USART_MSPINIT_CB_ID : + husart->MspInitCallback = DAL_USART_MspInit; + break; + + case DAL_USART_MSPDEINIT_CB_ID : + husart->MspDeInitCallback = DAL_USART_MspDeInit; + break; + + default : + /* Update the error code */ + husart->ErrorCode |= DAL_USART_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = DAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + husart->ErrorCode |= DAL_USART_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = DAL_ERROR; + } + + /* Release Lock */ + __DAL_UNLOCK(husart); + + return status; +} +#endif /* USE_DAL_USART_REGISTER_CALLBACKS */ + +/** + * @} + */ + +/** @defgroup USART_Exported_Functions_Group2 IO operation functions + * @brief USART Transmit and Receive functions + * +@verbatim + ============================================================================== + ##### IO operation functions ##### + ============================================================================== + [..] + This subsection provides a set of functions allowing to manage the USART synchronous + data transfers. + + [..] + The USART supports master mode only: it cannot receive or send data related to an input + clock (SCLK is always an output). + + (#) There are two modes of transfer: + (++) Blocking mode: The communication is performed in polling mode. + The DAL status of all data processing is returned by the same function + after finishing transfer. + (++) No-Blocking mode: The communication is performed using Interrupts + or DMA, These API's return the DAL status. + The end of the data processing will be indicated through the + dedicated USART IRQ when using Interrupt mode or the DMA IRQ when + using DMA mode. + The DAL_USART_TxCpltCallback(), DAL_USART_RxCpltCallback() and DAL_USART_TxRxCpltCallback() + user callbacks + will be executed respectively at the end of the transmit or Receive process + The DAL_USART_ErrorCallback() user callback will be executed when a communication + error is detected + + (#) Blocking mode APIs are : + (++) DAL_USART_Transmit() in simplex mode + (++) DAL_USART_Receive() in full duplex receive only + (++) DAL_USART_TransmitReceive() in full duplex mode + + (#) Non Blocking mode APIs with Interrupt are : + (++) DAL_USART_Transmit_IT()in simplex mode + (++) DAL_USART_Receive_IT() in full duplex receive only + (++) DAL_USART_TransmitReceive_IT() in full duplex mode + (++) DAL_USART_IRQHandler() + + (#) Non Blocking mode functions with DMA are : + (++) DAL_USART_Transmit_DMA()in simplex mode + (++) DAL_USART_Receive_DMA() in full duplex receive only + (++) DAL_USART_TransmitReceive_DMA() in full duplex mode + (++) DAL_USART_DMAPause() + (++) DAL_USART_DMAResume() + (++) DAL_USART_DMAStop() + + (#) A set of Transfer Complete Callbacks are provided in non Blocking mode: + (++) DAL_USART_TxHalfCpltCallback() + (++) DAL_USART_TxCpltCallback() + (++) DAL_USART_RxHalfCpltCallback() + (++) DAL_USART_RxCpltCallback() + (++) DAL_USART_ErrorCallback() + (++) DAL_USART_TxRxCpltCallback() + + (#) Non-Blocking mode transfers could be aborted using Abort API's : + (++) DAL_USART_Abort() + (++) DAL_USART_Abort_IT() + + (#) For Abort services based on interrupts (DAL_USART_Abort_IT), a Abort Complete Callbacks is provided: + (++) DAL_USART_AbortCpltCallback() + + (#) In Non-Blocking mode transfers, possible errors are split into 2 categories. + Errors are handled as follows : + (++) Error is considered as Recoverable and non blocking : Transfer could go till end, but error severity is + to be evaluated by user : this concerns Frame Error, Parity Error or Noise Error in Interrupt mode reception . + Received character is then retrieved and stored in Rx buffer, Error code is set to allow user to identify error type, + and DAL_USART_ErrorCallback() user callback is executed. Transfer is kept ongoing on USART side. + If user wants to abort it, Abort services should be called by user. + (++) Error is considered as Blocking : Transfer could not be completed properly and is aborted. + This concerns Overrun Error In Interrupt mode reception and all errors in DMA mode. + Error code is set to allow user to identify error type, and DAL_USART_ErrorCallback() user callback is executed. + +@endverbatim + * @{ + */ + +/** + * @brief Simplex Send an amount of data in blocking mode. + * @note When USART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), + * the sent data is handled as a set of u16. In this case, Size must indicate the number + * of u16 provided through pTxData. + * @param husart Pointer to a USART_HandleTypeDef structure that contains + * the configuration information for the specified USART module. + * @param pTxData Pointer to data buffer (u8 or u16 data elements). + * @param Size Amount of data elements (u8 or u16) to be sent. + * @param Timeout Timeout duration. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_USART_Transmit(USART_HandleTypeDef *husart, const uint8_t *pTxData, uint16_t Size, uint32_t Timeout) +{ + const uint8_t *ptxdata8bits; + const uint16_t *ptxdata16bits; + uint32_t tickstart; + + if (husart->State == DAL_USART_STATE_READY) + { + if ((pTxData == NULL) || (Size == 0)) + { + return DAL_ERROR; + } + + /* Process Locked */ + __DAL_LOCK(husart); + + husart->ErrorCode = DAL_USART_ERROR_NONE; + husart->State = DAL_USART_STATE_BUSY_TX; + + /* Init tickstart for timeout management */ + tickstart = DAL_GetTick(); + + husart->TxXferSize = Size; + husart->TxXferCount = Size; + + /* In case of 9bits/No Parity transfer, pTxData needs to be handled as a uint16_t pointer */ + if ((husart->Init.WordLength == USART_WORDLENGTH_9B) && (husart->Init.Parity == USART_PARITY_NONE)) + { + ptxdata8bits = NULL; + ptxdata16bits = (const uint16_t *) pTxData; + } + else + { + ptxdata8bits = pTxData; + ptxdata16bits = NULL; + } + + while (husart->TxXferCount > 0U) + { + /* Wait for TXE flag in order to write data in DATA */ + if (USART_WaitOnFlagUntilTimeout(husart, USART_FLAG_TXE, RESET, tickstart, Timeout) != DAL_OK) + { + return DAL_TIMEOUT; + } + if (ptxdata8bits == NULL) + { + husart->Instance->DATA = (uint16_t)(*ptxdata16bits & (uint16_t)0x01FF); + ptxdata16bits++; + } + else + { + husart->Instance->DATA = (uint8_t)(*ptxdata8bits & (uint8_t)0xFF); + ptxdata8bits++; + } + + husart->TxXferCount--; + } + + if (USART_WaitOnFlagUntilTimeout(husart, USART_FLAG_TC, RESET, tickstart, Timeout) != DAL_OK) + { + return DAL_TIMEOUT; + } + + husart->State = DAL_USART_STATE_READY; + + /* Process Unlocked */ + __DAL_UNLOCK(husart); + + return DAL_OK; + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief Full-Duplex Receive an amount of data in blocking mode. + * @note To receive synchronous data, dummy data are simultaneously transmitted. + * @note When USART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), + * the received data is handled as a set of u16. In this case, Size must indicate the number + * of u16 available through pRxData. + * @param husart Pointer to a USART_HandleTypeDef structure that contains + * the configuration information for the specified USART module. + * @param pRxData Pointer to data buffer (u8 or u16 data elements). + * @param Size Amount of data elements (u8 or u16) to be received. + * @param Timeout Timeout duration. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_USART_Receive(USART_HandleTypeDef *husart, uint8_t *pRxData, uint16_t Size, uint32_t Timeout) +{ + uint8_t *prxdata8bits; + uint16_t *prxdata16bits; + uint32_t tickstart; + + if (husart->State == DAL_USART_STATE_READY) + { + if ((pRxData == NULL) || (Size == 0)) + { + return DAL_ERROR; + } + /* Process Locked */ + __DAL_LOCK(husart); + + husart->ErrorCode = DAL_USART_ERROR_NONE; + husart->State = DAL_USART_STATE_BUSY_RX; + + /* Init tickstart for timeout management */ + tickstart = DAL_GetTick(); + + husart->RxXferSize = Size; + husart->RxXferCount = Size; + + /* In case of 9bits/No Parity transfer, pRxData needs to be handled as a uint16_t pointer */ + if ((husart->Init.WordLength == USART_WORDLENGTH_9B) && (husart->Init.Parity == USART_PARITY_NONE)) + { + prxdata8bits = NULL; + prxdata16bits = (uint16_t *) pRxData; + } + else + { + prxdata8bits = pRxData; + prxdata16bits = NULL; + } + + /* Check the remain data to be received */ + while (husart->RxXferCount > 0U) + { + /* Wait until TXE flag is set to send dummy byte in order to generate the + * clock for the slave to send data. + * Whatever the frame length (7, 8 or 9-bit long), the same dummy value + * can be written for all the cases. */ + if (USART_WaitOnFlagUntilTimeout(husart, USART_FLAG_TXE, RESET, tickstart, Timeout) != DAL_OK) + { + return DAL_TIMEOUT; + } + husart->Instance->DATA = (DUMMY_DATA & (uint16_t)0x0FF); + + /* Wait until RXNE flag is set to receive the byte */ + if (USART_WaitOnFlagUntilTimeout(husart, USART_FLAG_RXNE, RESET, tickstart, Timeout) != DAL_OK) + { + return DAL_TIMEOUT; + } + + if (prxdata8bits == NULL) + { + *prxdata16bits = (uint16_t)(husart->Instance->DATA & (uint16_t)0x01FF); + prxdata16bits++; + } + else + { + if ((husart->Init.WordLength == USART_WORDLENGTH_9B) || ((husart->Init.WordLength == USART_WORDLENGTH_8B) && (husart->Init.Parity == USART_PARITY_NONE))) + { + *prxdata8bits = (uint8_t)(husart->Instance->DATA & (uint8_t)0x0FF); + } + else + { + *prxdata8bits = (uint8_t)(husart->Instance->DATA & (uint8_t)0x07F); + } + prxdata8bits++; + } + husart->RxXferCount--; + } + + husart->State = DAL_USART_STATE_READY; + + /* Process Unlocked */ + __DAL_UNLOCK(husart); + + return DAL_OK; + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief Full-Duplex Send and Receive an amount of data in full-duplex mode (blocking mode). + * @note When USART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), + * the sent data and the received data are handled as sets of u16. In this case, Size must indicate the number + * of u16 available through pTxData and through pRxData. + * @param husart Pointer to a USART_HandleTypeDef structure that contains + * the configuration information for the specified USART module. + * @param pTxData Pointer to TX data buffer (u8 or u16 data elements). + * @param pRxData Pointer to RX data buffer (u8 or u16 data elements). + * @param Size Amount of data elements (u8 or u16) to be sent (same amount to be received). + * @param Timeout Timeout duration + * @retval DAL status + */ +DAL_StatusTypeDef DAL_USART_TransmitReceive(USART_HandleTypeDef *husart, const uint8_t *pTxData, uint8_t *pRxData, + uint16_t Size, uint32_t Timeout) +{ + uint8_t *prxdata8bits; + uint16_t *prxdata16bits; + const uint8_t *ptxdata8bits; + const uint16_t *ptxdata16bits; + uint16_t rxdatacount; + uint32_t tickstart; + + if (husart->State == DAL_USART_STATE_READY) + { + if ((pTxData == NULL) || (pRxData == NULL) || (Size == 0)) + { + return DAL_ERROR; + } + + /* In case of 9bits/No Parity transfer, pTxData and pRxData buffers provided as input parameter + should be aligned on a u16 frontier, as data to be filled into TDATA/retrieved from RDATA will be + handled through a u16 cast. */ + if ((husart->Init.WordLength == USART_WORDLENGTH_9B) && (husart->Init.Parity == USART_PARITY_NONE)) + { + if (((((uint32_t)pTxData) & 1U) != 0U) || ((((uint32_t)pRxData) & 1U) != 0U)) + { + return DAL_ERROR; + } + } + /* Process Locked */ + __DAL_LOCK(husart); + + husart->ErrorCode = DAL_USART_ERROR_NONE; + husart->State = DAL_USART_STATE_BUSY_RX; + + /* Init tickstart for timeout management */ + tickstart = DAL_GetTick(); + + husart->RxXferSize = Size; + husart->TxXferSize = Size; + husart->TxXferCount = Size; + husart->RxXferCount = Size; + + /* In case of 9bits/No Parity transfer, pRxData needs to be handled as a uint16_t pointer */ + if ((husart->Init.WordLength == USART_WORDLENGTH_9B) && (husart->Init.Parity == USART_PARITY_NONE)) + { + prxdata8bits = NULL; + ptxdata8bits = NULL; + ptxdata16bits = (const uint16_t *) pTxData; + prxdata16bits = (uint16_t *) pRxData; + } + else + { + prxdata8bits = pRxData; + ptxdata8bits = pTxData; + ptxdata16bits = NULL; + prxdata16bits = NULL; + } + + /* Check the remain data to be received */ + /* rxdatacount is a temporary variable for MISRAC2012-Rule-13.5 */ + rxdatacount = husart->RxXferCount; + while ((husart->TxXferCount > 0U) || (rxdatacount > 0U)) + { + if (husart->TxXferCount > 0U) + { + /* Wait for TXE flag in order to write data in DATA */ + if (USART_WaitOnFlagUntilTimeout(husart, USART_FLAG_TXE, RESET, tickstart, Timeout) != DAL_OK) + { + return DAL_TIMEOUT; + } + + if (ptxdata8bits == NULL) + { + husart->Instance->DATA = (uint16_t)(*ptxdata16bits & (uint16_t)0x01FF); + ptxdata16bits++; + } + else + { + husart->Instance->DATA = (uint8_t)(*ptxdata8bits & (uint8_t)0xFF); + ptxdata8bits++; + } + + husart->TxXferCount--; + } + + if (husart->RxXferCount > 0U) + { + /* Wait for RXNE Flag */ + if (USART_WaitOnFlagUntilTimeout(husart, USART_FLAG_RXNE, RESET, tickstart, Timeout) != DAL_OK) + { + return DAL_TIMEOUT; + } + if (prxdata8bits == NULL) + { + *prxdata16bits = (uint16_t)(husart->Instance->DATA & (uint16_t)0x01FF); + prxdata16bits++; + } + else + { + if ((husart->Init.WordLength == USART_WORDLENGTH_9B) || ((husart->Init.WordLength == USART_WORDLENGTH_8B) && (husart->Init.Parity == USART_PARITY_NONE))) + { + *prxdata8bits = (uint8_t)(husart->Instance->DATA & (uint8_t)0x0FF); + } + else + { + *prxdata8bits = (uint8_t)(husart->Instance->DATA & (uint8_t)0x07F); + } + + prxdata8bits++; + } + + husart->RxXferCount--; + } + rxdatacount = husart->RxXferCount; + } + + husart->State = DAL_USART_STATE_READY; + + /* Process Unlocked */ + __DAL_UNLOCK(husart); + + return DAL_OK; + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief Simplex Send an amount of data in non-blocking mode. + * @note When USART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), + * the sent data is handled as a set of u16. In this case, Size must indicate the number + * of u16 provided through pTxData. + * @param husart Pointer to a USART_HandleTypeDef structure that contains + * the configuration information for the specified USART module. + * @param pTxData Pointer to data buffer (u8 or u16 data elements). + * @param Size Amount of data elements (u8 or u16) to be sent. + * @retval DAL status + * @note The USART errors are not managed to avoid the overrun error. + */ +DAL_StatusTypeDef DAL_USART_Transmit_IT(USART_HandleTypeDef *husart, const uint8_t *pTxData, uint16_t Size) +{ + if (husart->State == DAL_USART_STATE_READY) + { + if ((pTxData == NULL) || (Size == 0)) + { + return DAL_ERROR; + } + + /* Process Locked */ + __DAL_LOCK(husart); + + husart->pTxBuffPtr = pTxData; + husart->TxXferSize = Size; + husart->TxXferCount = Size; + + husart->ErrorCode = DAL_USART_ERROR_NONE; + husart->State = DAL_USART_STATE_BUSY_TX; + + /* The USART Error Interrupts: (Frame error, Noise error, Overrun error) + are not managed by the USART transmit process to avoid the overrun interrupt + when the USART mode is configured for transmit and receive "USART_MODE_TX_RX" + to benefit for the frame error and noise interrupts the USART mode should be + configured only for transmit "USART_MODE_TX" + The __DAL_USART_ENABLE_IT(husart, USART_IT_ERR) can be used to enable the Frame error, + Noise error interrupt */ + + /* Process Unlocked */ + __DAL_UNLOCK(husart); + + /* Enable the USART Transmit Data Register Empty Interrupt */ + SET_BIT(husart->Instance->CTRL1, USART_CTRL1_TXBEIEN); + + return DAL_OK; + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief Simplex Receive an amount of data in non-blocking mode. + * @note To receive synchronous data, dummy data are simultaneously transmitted. + * @note When USART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), + * the received data is handled as a set of u16. In this case, Size must indicate the number + * of u16 available through pRxData. + * @param husart Pointer to a USART_HandleTypeDef structure that contains + * the configuration information for the specified USART module. + * @param pRxData Pointer to data buffer (u8 or u16 data elements). + * @param Size Amount of data elements (u8 or u16) to be received. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_USART_Receive_IT(USART_HandleTypeDef *husart, uint8_t *pRxData, uint16_t Size) +{ + if (husart->State == DAL_USART_STATE_READY) + { + if ((pRxData == NULL) || (Size == 0)) + { + return DAL_ERROR; + } + /* Process Locked */ + __DAL_LOCK(husart); + + husart->pRxBuffPtr = pRxData; + husart->RxXferSize = Size; + husart->RxXferCount = Size; + + husart->ErrorCode = DAL_USART_ERROR_NONE; + husart->State = DAL_USART_STATE_BUSY_RX; + + /* Process Unlocked */ + __DAL_UNLOCK(husart); + + if (husart->Init.Parity != USART_PARITY_NONE) + { + /* Enable the USART Parity Error and Data Register not empty Interrupts */ + SET_BIT(husart->Instance->CTRL1, USART_CTRL1_PEIEN | USART_CTRL1_RXBNEIEN); + } + else + { + /* Enable the USART Data Register not empty Interrupts */ + SET_BIT(husart->Instance->CTRL1, USART_CTRL1_RXBNEIEN); + } + + /* Enable the USART Error Interrupt: (Frame error, noise error, overrun error) */ + SET_BIT(husart->Instance->CTRL3, USART_CTRL3_ERRIEN); + + /* Send dummy byte in order to generate the clock for the slave to send data */ + husart->Instance->DATA = (DUMMY_DATA & (uint16_t)0x01FF); + + return DAL_OK; + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief Full-Duplex Send and Receive an amount of data in full-duplex mode (non-blocking). + * @note When USART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), + * the sent data and the received data are handled as sets of u16. In this case, Size must indicate the number + * of u16 available through pTxData and through pRxData. + * @param husart Pointer to a USART_HandleTypeDef structure that contains + * the configuration information for the specified USART module. + * @param pTxData Pointer to TX data buffer (u8 or u16 data elements). + * @param pRxData Pointer to RX data buffer (u8 or u16 data elements). + * @param Size Amount of data elements (u8 or u16) to be sent (same amount to be received). + * @retval DAL status + */ +DAL_StatusTypeDef DAL_USART_TransmitReceive_IT(USART_HandleTypeDef *husart, const uint8_t *pTxData, uint8_t *pRxData, + uint16_t Size) +{ + if (husart->State == DAL_USART_STATE_READY) + { + if ((pTxData == NULL) || (pRxData == NULL) || (Size == 0)) + { + return DAL_ERROR; + } + /* Process Locked */ + __DAL_LOCK(husart); + + husart->pRxBuffPtr = pRxData; + husart->RxXferSize = Size; + husart->RxXferCount = Size; + husart->pTxBuffPtr = pTxData; + husart->TxXferSize = Size; + husart->TxXferCount = Size; + + husart->ErrorCode = DAL_USART_ERROR_NONE; + husart->State = DAL_USART_STATE_BUSY_TX_RX; + + /* Process Unlocked */ + __DAL_UNLOCK(husart); + + /* Enable the USART Data Register not empty Interrupt */ + SET_BIT(husart->Instance->CTRL1, USART_CTRL1_RXBNEIEN); + + if (husart->Init.Parity != USART_PARITY_NONE) + { + /* Enable the USART Parity Error Interrupt */ + SET_BIT(husart->Instance->CTRL1, USART_CTRL1_PEIEN); + } + + /* Enable the USART Error Interrupt: (Frame error, noise error, overrun error) */ + SET_BIT(husart->Instance->CTRL3, USART_CTRL3_ERRIEN); + + /* Enable the USART Transmit Data Register Empty Interrupt */ + SET_BIT(husart->Instance->CTRL1, USART_CTRL1_TXBEIEN); + + return DAL_OK; + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief Simplex Send an amount of data in DMA mode. + * @note When USART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), + * the sent data is handled as a set of u16. In this case, Size must indicate the number + * of u16 provided through pTxData. + * @param husart Pointer to a USART_HandleTypeDef structure that contains + * the configuration information for the specified USART module. + * @param pTxData Pointer to data buffer (u8 or u16 data elements). + * @param Size Amount of data elements (u8 or u16) to be sent. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_USART_Transmit_DMA(USART_HandleTypeDef *husart, const uint8_t *pTxData, uint16_t Size) +{ + const uint32_t *tmp; + + if (husart->State == DAL_USART_STATE_READY) + { + if ((pTxData == NULL) || (Size == 0)) + { + return DAL_ERROR; + } + /* Process Locked */ + __DAL_LOCK(husart); + + husart->pTxBuffPtr = pTxData; + husart->TxXferSize = Size; + husart->TxXferCount = Size; + + husart->ErrorCode = DAL_USART_ERROR_NONE; + husart->State = DAL_USART_STATE_BUSY_TX; + + /* Set the USART DMA transfer complete callback */ + husart->hdmatx->XferCpltCallback = USART_DMATransmitCplt; + + /* Set the USART DMA Half transfer complete callback */ + husart->hdmatx->XferHalfCpltCallback = USART_DMATxHalfCplt; + + /* Set the DMA error callback */ + husart->hdmatx->XferErrorCallback = USART_DMAError; + + /* Set the DMA abort callback */ + husart->hdmatx->XferAbortCallback = NULL; + + /* Enable the USART transmit DMA stream */ + tmp = (const uint32_t *)&pTxData; + DAL_DMA_Start_IT(husart->hdmatx, *(const uint32_t *)tmp, (uint32_t)&husart->Instance->DATA, Size); + + /* Clear the TC flag in the STS register by writing 0 to it */ + __DAL_USART_CLEAR_FLAG(husart, USART_FLAG_TC); + + /* Process Unlocked */ + __DAL_UNLOCK(husart); + + /* Enable the DMA transfer for transmit request by setting the DMAT bit + in the USART CTRL3 register */ + SET_BIT(husart->Instance->CTRL3, USART_CTRL3_DMATXEN); + + return DAL_OK; + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief Full-Duplex Receive an amount of data in DMA mode. + * @note When USART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), + * the received data is handled as a set of u16. In this case, Size must indicate the number + * of u16 available through pRxData. + * @param husart Pointer to a USART_HandleTypeDef structure that contains + * the configuration information for the specified USART module. + * @param pRxData Pointer to data buffer (u8 or u16 data elements). + * @param Size Amount of data elements (u8 or u16) to be received. + * @retval DAL status + * @note The USART DMA transmit stream must be configured in order to generate the clock for the slave. + * @note When the USART parity is enabled (PCE = 1) the data received contain the parity bit. + */ +DAL_StatusTypeDef DAL_USART_Receive_DMA(USART_HandleTypeDef *husart, uint8_t *pRxData, uint16_t Size) +{ + uint32_t *tmp; + + if (husart->State == DAL_USART_STATE_READY) + { + if ((pRxData == NULL) || (Size == 0)) + { + return DAL_ERROR; + } + + /* Process Locked */ + __DAL_LOCK(husart); + + husart->pRxBuffPtr = pRxData; + husart->RxXferSize = Size; + husart->pTxBuffPtr = pRxData; + husart->TxXferSize = Size; + + husart->ErrorCode = DAL_USART_ERROR_NONE; + husart->State = DAL_USART_STATE_BUSY_RX; + + /* Set the USART DMA Rx transfer complete callback */ + husart->hdmarx->XferCpltCallback = USART_DMAReceiveCplt; + + /* Set the USART DMA Half transfer complete callback */ + husart->hdmarx->XferHalfCpltCallback = USART_DMARxHalfCplt; + + /* Set the USART DMA Rx transfer error callback */ + husart->hdmarx->XferErrorCallback = USART_DMAError; + + /* Set the DMA abort callback */ + husart->hdmarx->XferAbortCallback = NULL; + + /* Set the USART Tx DMA transfer complete callback as NULL because the communication closing + is performed in DMA reception complete callback */ + husart->hdmatx->XferHalfCpltCallback = NULL; + husart->hdmatx->XferCpltCallback = NULL; + + /* Set the DMA error callback */ + husart->hdmatx->XferErrorCallback = USART_DMAError; + + /* Set the DMA AbortCpltCallback */ + husart->hdmatx->XferAbortCallback = NULL; + + /* Enable the USART receive DMA stream */ + tmp = (uint32_t *)&pRxData; + DAL_DMA_Start_IT(husart->hdmarx, (uint32_t)&husart->Instance->DATA, *(uint32_t *)tmp, Size); + + /* Enable the USART transmit DMA stream: the transmit stream is used in order + to generate in the non-blocking mode the clock to the slave device, + this mode isn't a simplex receive mode but a full-duplex receive one */ + DAL_DMA_Start_IT(husart->hdmatx, *(uint32_t *)tmp, (uint32_t)&husart->Instance->DATA, Size); + + /* Clear the Overrun flag just before enabling the DMA Rx request: mandatory for the second transfer */ + __DAL_USART_CLEAR_OREFLAG(husart); + + /* Process Unlocked */ + __DAL_UNLOCK(husart); + + if (husart->Init.Parity != USART_PARITY_NONE) + { + /* Enable the USART Parity Error Interrupt */ + SET_BIT(husart->Instance->CTRL1, USART_CTRL1_PEIEN); + } + + /* Enable the USART Error Interrupt: (Frame error, noise error, overrun error) */ + SET_BIT(husart->Instance->CTRL3, USART_CTRL3_ERRIEN); + + /* Enable the DMA transfer for the receiver request by setting the DMAR bit + in the USART CTRL3 register */ + SET_BIT(husart->Instance->CTRL3, USART_CTRL3_DMARXEN); + + /* Enable the DMA transfer for transmit request by setting the DMAT bit + in the USART CTRL3 register */ + SET_BIT(husart->Instance->CTRL3, USART_CTRL3_DMATXEN); + + return DAL_OK; + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief Full-Duplex Transmit Receive an amount of data in DMA mode. + * @note When USART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), + * the sent data and the received data are handled as sets of u16. In this case, Size must indicate the number + * of u16 available through pTxData and through pRxData. + * @param husart Pointer to a USART_HandleTypeDef structure that contains + * the configuration information for the specified USART module. + * @param pTxData Pointer to TX data buffer (u8 or u16 data elements). + * @param pRxData Pointer to RX data buffer (u8 or u16 data elements). + * @param Size Amount of data elements (u8 or u16) to be received/sent. + * @note When the USART parity is enabled (PCE = 1) the data received contain the parity bit. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_USART_TransmitReceive_DMA(USART_HandleTypeDef *husart, const uint8_t *pTxData, uint8_t *pRxData, + uint16_t Size) +{ + const uint32_t *tmp; + + if (husart->State == DAL_USART_STATE_READY) + { + if ((pTxData == NULL) || (pRxData == NULL) || (Size == 0)) + { + return DAL_ERROR; + } + /* Process Locked */ + __DAL_LOCK(husart); + + husart->pRxBuffPtr = pRxData; + husart->RxXferSize = Size; + husart->pTxBuffPtr = pTxData; + husart->TxXferSize = Size; + + husart->ErrorCode = DAL_USART_ERROR_NONE; + husart->State = DAL_USART_STATE_BUSY_TX_RX; + + /* Set the USART DMA Rx transfer complete callback */ + husart->hdmarx->XferCpltCallback = USART_DMAReceiveCplt; + + /* Set the USART DMA Half transfer complete callback */ + husart->hdmarx->XferHalfCpltCallback = USART_DMARxHalfCplt; + + /* Set the USART DMA Tx transfer complete callback */ + husart->hdmatx->XferCpltCallback = USART_DMATransmitCplt; + + /* Set the USART DMA Half transfer complete callback */ + husart->hdmatx->XferHalfCpltCallback = USART_DMATxHalfCplt; + + /* Set the USART DMA Tx transfer error callback */ + husart->hdmatx->XferErrorCallback = USART_DMAError; + + /* Set the USART DMA Rx transfer error callback */ + husart->hdmarx->XferErrorCallback = USART_DMAError; + + /* Set the DMA abort callback */ + husart->hdmarx->XferAbortCallback = NULL; + + /* Enable the USART receive DMA stream */ + tmp = (uint32_t *)&pRxData; + DAL_DMA_Start_IT(husart->hdmarx, (uint32_t)&husart->Instance->DATA, *(const uint32_t *)tmp, Size); + + /* Enable the USART transmit DMA stream */ + tmp = (const uint32_t *)&pTxData; + DAL_DMA_Start_IT(husart->hdmatx, *(const uint32_t *)tmp, (uint32_t)&husart->Instance->DATA, Size); + + /* Clear the TC flag in the STS register by writing 0 to it */ + __DAL_USART_CLEAR_FLAG(husart, USART_FLAG_TC); + + /* Clear the Overrun flag: mandatory for the second transfer in circular mode */ + __DAL_USART_CLEAR_OREFLAG(husart); + + /* Process Unlocked */ + __DAL_UNLOCK(husart); + + if (husart->Init.Parity != USART_PARITY_NONE) + { + /* Enable the USART Parity Error Interrupt */ + SET_BIT(husart->Instance->CTRL1, USART_CTRL1_PEIEN); + } + + /* Enable the USART Error Interrupt: (Frame error, noise error, overrun error) */ + SET_BIT(husart->Instance->CTRL3, USART_CTRL3_ERRIEN); + + /* Enable the DMA transfer for the receiver request by setting the DMAR bit + in the USART CTRL3 register */ + SET_BIT(husart->Instance->CTRL3, USART_CTRL3_DMARXEN); + + /* Enable the DMA transfer for transmit request by setting the DMAT bit + in the USART CTRL3 register */ + SET_BIT(husart->Instance->CTRL3, USART_CTRL3_DMATXEN); + + return DAL_OK; + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief Pauses the DMA Transfer. + * @param husart Pointer to a USART_HandleTypeDef structure that contains + * the configuration information for the specified USART module. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_USART_DMAPause(USART_HandleTypeDef *husart) +{ + /* Process Locked */ + __DAL_LOCK(husart); + + /* Disable the USART DMA Tx request */ + CLEAR_BIT(husart->Instance->CTRL3, USART_CTRL3_DMATXEN); + + /* Process Unlocked */ + __DAL_UNLOCK(husart); + + return DAL_OK; +} + +/** + * @brief Resumes the DMA Transfer. + * @param husart Pointer to a USART_HandleTypeDef structure that contains + * the configuration information for the specified USART module. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_USART_DMAResume(USART_HandleTypeDef *husart) +{ + /* Process Locked */ + __DAL_LOCK(husart); + + /* Enable the USART DMA Tx request */ + SET_BIT(husart->Instance->CTRL3, USART_CTRL3_DMATXEN); + + /* Process Unlocked */ + __DAL_UNLOCK(husart); + + return DAL_OK; +} + +/** + * @brief Stops the DMA Transfer. + * @param husart Pointer to a USART_HandleTypeDef structure that contains + * the configuration information for the specified USART module. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_USART_DMAStop(USART_HandleTypeDef *husart) +{ + uint32_t dmarequest = 0x00U; + /* The Lock is not implemented on this API to allow the user application + to call the DAL USART API under callbacks DAL_USART_TxCpltCallback() / DAL_USART_RxCpltCallback(): + when calling DAL_DMA_Abort() API the DMA TX/RX Transfer complete interrupt is generated + and the correspond call back is executed DAL_USART_TxCpltCallback() / DAL_USART_RxCpltCallback() + */ + + /* Stop USART DMA Tx request if ongoing */ + dmarequest = DAL_IS_BIT_SET(husart->Instance->CTRL3, USART_CTRL3_DMATXEN); + if ((husart->State == DAL_USART_STATE_BUSY_TX) && dmarequest) + { + USART_EndTxTransfer(husart); + + /* Abort the USART DMA Tx channel */ + if (husart->hdmatx != NULL) + { + DAL_DMA_Abort(husart->hdmatx); + } + + /* Disable the USART Tx DMA request */ + CLEAR_BIT(husart->Instance->CTRL3, USART_CTRL3_DMATXEN); + } + + /* Stop USART DMA Rx request if ongoing */ + dmarequest = DAL_IS_BIT_SET(husart->Instance->CTRL3, USART_CTRL3_DMARXEN); + if ((husart->State == DAL_USART_STATE_BUSY_RX) && dmarequest) + { + USART_EndRxTransfer(husart); + + /* Abort the USART DMA Rx channel */ + if (husart->hdmarx != NULL) + { + DAL_DMA_Abort(husart->hdmarx); + } + + /* Disable the USART Rx DMA request */ + CLEAR_BIT(husart->Instance->CTRL3, USART_CTRL3_DMARXEN); + } + + return DAL_OK; +} + +/** + * @brief Abort ongoing transfer (blocking mode). + * @param husart USART handle. + * @note This procedure could be used for aborting any ongoing transfer (either Tx or Rx, + * as described by TransferType parameter) started in Interrupt or DMA mode. + * This procedure performs following operations : + * - Disable PPP Interrupts (depending of transfer direction) + * - Disable the DMA transfer in the peripheral register (if enabled) + * - Abort DMA transfer by calling DAL_DMA_Abort (in case of transfer in DMA mode) + * - Set handle State to READY + * @note This procedure is executed in blocking mode : when exiting function, Abort is considered as completed. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_USART_Abort(USART_HandleTypeDef *husart) +{ + /* Disable TXEIE, TCIE, RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts */ + CLEAR_BIT(husart->Instance->CTRL1, (USART_CTRL1_RXBNEIEN | USART_CTRL1_PEIEN | USART_CTRL1_TXBEIEN | USART_CTRL1_TXCIEN)); + CLEAR_BIT(husart->Instance->CTRL3, USART_CTRL3_ERRIEN); + + /* Disable the USART DMA Tx request if enabled */ + if (DAL_IS_BIT_SET(husart->Instance->CTRL3, USART_CTRL3_DMATXEN)) + { + CLEAR_BIT(husart->Instance->CTRL3, USART_CTRL3_DMATXEN); + + /* Abort the USART DMA Tx channel : use blocking DMA Abort API (no callback) */ + if (husart->hdmatx != NULL) + { + /* Set the USART DMA Abort callback to Null. + No call back execution at end of DMA abort procedure */ + husart->hdmatx->XferAbortCallback = NULL; + + DAL_DMA_Abort(husart->hdmatx); + } + } + + /* Disable the USART DMA Rx request if enabled */ + if (DAL_IS_BIT_SET(husart->Instance->CTRL3, USART_CTRL3_DMARXEN)) + { + CLEAR_BIT(husart->Instance->CTRL3, USART_CTRL3_DMARXEN); + + /* Abort the USART DMA Rx channel : use blocking DMA Abort API (no callback) */ + if (husart->hdmarx != NULL) + { + /* Set the USART DMA Abort callback to Null. + No call back execution at end of DMA abort procedure */ + husart->hdmarx->XferAbortCallback = NULL; + + DAL_DMA_Abort(husart->hdmarx); + } + } + + /* Reset Tx and Rx transfer counters */ + husart->TxXferCount = 0x00U; + husart->RxXferCount = 0x00U; + + /* Restore husart->State to Ready */ + husart->State = DAL_USART_STATE_READY; + + /* Reset Handle ErrorCode to No Error */ + husart->ErrorCode = DAL_USART_ERROR_NONE; + + return DAL_OK; +} + +/** + * @brief Abort ongoing transfer (Interrupt mode). + * @param husart USART handle. + * @note This procedure could be used for aborting any ongoing transfer (either Tx or Rx, + * as described by TransferType parameter) started in Interrupt or DMA mode. + * This procedure performs following operations : + * - Disable PPP Interrupts (depending of transfer direction) + * - Disable the DMA transfer in the peripheral register (if enabled) + * - Abort DMA transfer by calling DAL_DMA_Abort_IT (in case of transfer in DMA mode) + * - Set handle State to READY + * - At abort completion, call user abort complete callback + * @note This procedure is executed in Interrupt mode, meaning that abort procedure could be + * considered as completed only when user abort complete callback is executed (not when exiting function). + * @retval DAL status + */ +DAL_StatusTypeDef DAL_USART_Abort_IT(USART_HandleTypeDef *husart) +{ + uint32_t AbortCplt = 0x01U; + + /* Disable TXBEIEN, TXCIEN, RXBNEIEN, PEIEN and ERRIEN (Frame error, noise error, overrun error) interrupts */ + CLEAR_BIT(husart->Instance->CTRL1, (USART_CTRL1_RXBNEIEN | USART_CTRL1_PEIEN | USART_CTRL1_TXBEIEN | USART_CTRL1_TXCIEN)); + CLEAR_BIT(husart->Instance->CTRL3, USART_CTRL3_ERRIEN); + + /* If DMA Tx and/or DMA Rx Handles are associated to USART Handle, DMA Abort complete callbacks should be initialised + before any call to DMA Abort functions */ + /* DMA Tx Handle is valid */ + if (husart->hdmatx != NULL) + { + /* Set DMA Abort Complete callback if USART DMA Tx request if enabled. + Otherwise, set it to NULL */ + if (DAL_IS_BIT_SET(husart->Instance->CTRL3, USART_CTRL3_DMATXEN)) + { + husart->hdmatx->XferAbortCallback = USART_DMATxAbortCallback; + } + else + { + husart->hdmatx->XferAbortCallback = NULL; + } + } + /* DMA Rx Handle is valid */ + if (husart->hdmarx != NULL) + { + /* Set DMA Abort Complete callback if USART DMA Rx request if enabled. + Otherwise, set it to NULL */ + if (DAL_IS_BIT_SET(husart->Instance->CTRL3, USART_CTRL3_DMARXEN)) + { + husart->hdmarx->XferAbortCallback = USART_DMARxAbortCallback; + } + else + { + husart->hdmarx->XferAbortCallback = NULL; + } + } + + /* Disable the USART DMA Tx request if enabled */ + if (DAL_IS_BIT_SET(husart->Instance->CTRL3, USART_CTRL3_DMATXEN)) + { + /* Disable DMA Tx at USART level */ + CLEAR_BIT(husart->Instance->CTRL3, USART_CTRL3_DMATXEN); + + /* Abort the USART DMA Tx channel : use non blocking DMA Abort API (callback) */ + if (husart->hdmatx != NULL) + { + /* USART Tx DMA Abort callback has already been initialised : + will lead to call DAL_USART_AbortCpltCallback() at end of DMA abort procedure */ + + /* Abort DMA TX */ + if (DAL_DMA_Abort_IT(husart->hdmatx) != DAL_OK) + { + husart->hdmatx->XferAbortCallback = NULL; + } + else + { + AbortCplt = 0x00U; + } + } + } + + /* Disable the USART DMA Rx request if enabled */ + if (DAL_IS_BIT_SET(husart->Instance->CTRL3, USART_CTRL3_DMARXEN)) + { + CLEAR_BIT(husart->Instance->CTRL3, USART_CTRL3_DMARXEN); + + /* Abort the USART DMA Rx channel : use non blocking DMA Abort API (callback) */ + if (husart->hdmarx != NULL) + { + /* USART Rx DMA Abort callback has already been initialised : + will lead to call DAL_USART_AbortCpltCallback() at end of DMA abort procedure */ + + /* Abort DMA RX */ + if (DAL_DMA_Abort_IT(husart->hdmarx) != DAL_OK) + { + husart->hdmarx->XferAbortCallback = NULL; + AbortCplt = 0x01U; + } + else + { + AbortCplt = 0x00U; + } + } + } + + /* if no DMA abort complete callback execution is required => call user Abort Complete callback */ + if (AbortCplt == 0x01U) + { + /* Reset Tx and Rx transfer counters */ + husart->TxXferCount = 0x00U; + husart->RxXferCount = 0x00U; + + /* Reset errorCode */ + husart->ErrorCode = DAL_USART_ERROR_NONE; + + /* Restore husart->State to Ready */ + husart->State = DAL_USART_STATE_READY; + + /* As no DMA to be aborted, call directly user Abort complete callback */ +#if (USE_DAL_USART_REGISTER_CALLBACKS == 1) + /* Call registered Abort Complete Callback */ + husart->AbortCpltCallback(husart); +#else + /* Call legacy weak Abort Complete Callback */ + DAL_USART_AbortCpltCallback(husart); +#endif /* USE_DAL_USART_REGISTER_CALLBACKS */ + } + + return DAL_OK; +} + +/** + * @brief This function handles USART interrupt request. + * @param husart Pointer to a USART_HandleTypeDef structure that contains + * the configuration information for the specified USART module. + * @retval None + */ +void DAL_USART_IRQHandler(USART_HandleTypeDef *husart) +{ + uint32_t isrflags = READ_REG(husart->Instance->STS); + uint32_t cr1its = READ_REG(husart->Instance->CTRL1); + uint32_t cr3its = READ_REG(husart->Instance->CTRL3); + uint32_t errorflags = 0x00U; + uint32_t dmarequest = 0x00U; + + /* If no error occurs */ + errorflags = (isrflags & (uint32_t)(USART_STS_PEFLG | USART_STS_FEFLG | USART_STS_OVREFLG | USART_STS_NEFLG)); + if (errorflags == RESET) + { + /* USART in mode Receiver -------------------------------------------------*/ + if (((isrflags & USART_STS_RXBNEFLG) != RESET) && ((cr1its & USART_CTRL1_RXBNEIEN) != RESET)) + { + if (husart->State == DAL_USART_STATE_BUSY_RX) + { + USART_Receive_IT(husart); + } + else + { + USART_TransmitReceive_IT(husart); + } + return; + } + } + /* If some errors occur */ + if ((errorflags != RESET) && (((cr3its & USART_CTRL3_ERRIEN) != RESET) || ((cr1its & (USART_CTRL1_RXBNEIEN | USART_CTRL1_PEIEN)) != RESET))) + { + /* USART parity error interrupt occurred ----------------------------------*/ + if (((isrflags & USART_STS_PEFLG) != RESET) && ((cr1its & USART_CTRL1_PEIEN) != RESET)) + { + husart->ErrorCode |= DAL_USART_ERROR_PE; + } + + /* USART noise error interrupt occurred --------------------------------*/ + if (((isrflags & USART_STS_NEFLG) != RESET) && ((cr3its & USART_CTRL3_ERRIEN) != RESET)) + { + husart->ErrorCode |= DAL_USART_ERROR_NE; + } + + /* USART frame error interrupt occurred --------------------------------*/ + if (((isrflags & USART_STS_FEFLG) != RESET) && ((cr3its & USART_CTRL3_ERRIEN) != RESET)) + { + husart->ErrorCode |= DAL_USART_ERROR_FE; + } + + /* USART Over-Run interrupt occurred -----------------------------------*/ + if (((isrflags & USART_STS_OVREFLG) != RESET) && (((cr1its & USART_CTRL1_RXBNEIEN) != RESET) || ((cr3its & USART_CTRL3_ERRIEN) != RESET))) + { + husart->ErrorCode |= DAL_USART_ERROR_ORE; + } + + if (husart->ErrorCode != DAL_USART_ERROR_NONE) + { + /* USART in mode Receiver -----------------------------------------------*/ + if (((isrflags & USART_STS_RXBNEFLG) != RESET) && ((cr1its & USART_CTRL1_RXBNEIEN) != RESET)) + { + if (husart->State == DAL_USART_STATE_BUSY_RX) + { + USART_Receive_IT(husart); + } + else + { + USART_TransmitReceive_IT(husart); + } + } + /* If Overrun error occurs, or if any error occurs in DMA mode reception, + consider error as blocking */ + dmarequest = DAL_IS_BIT_SET(husart->Instance->CTRL3, USART_CTRL3_DMARXEN); + if (((husart->ErrorCode & DAL_USART_ERROR_ORE) != RESET) || dmarequest) + { + /* Set the USART state ready to be able to start again the process, + Disable Rx Interrupts, and disable Rx DMA request, if ongoing */ + USART_EndRxTransfer(husart); + + /* Disable the USART DMA Rx request if enabled */ + if (DAL_IS_BIT_SET(husart->Instance->CTRL3, USART_CTRL3_DMARXEN)) + { + CLEAR_BIT(husart->Instance->CTRL3, USART_CTRL3_DMARXEN); + + /* Abort the USART DMA Rx channel */ + if (husart->hdmarx != NULL) + { + /* Set the USART DMA Abort callback : + will lead to call DAL_USART_ErrorCallback() at end of DMA abort procedure */ + husart->hdmarx->XferAbortCallback = USART_DMAAbortOnError; + + if (DAL_DMA_Abort_IT(husart->hdmarx) != DAL_OK) + { + /* Call Directly XferAbortCallback function in case of error */ + husart->hdmarx->XferAbortCallback(husart->hdmarx); + } + } + else + { + /* Call user error callback */ +#if (USE_DAL_USART_REGISTER_CALLBACKS == 1) + /* Call registered Error Callback */ + husart->ErrorCallback(husart); +#else + /* Call legacy weak Error Callback */ + DAL_USART_ErrorCallback(husart); +#endif /* USE_DAL_USART_REGISTER_CALLBACKS */ + } + } + else + { + /* Call user error callback */ +#if (USE_DAL_USART_REGISTER_CALLBACKS == 1) + /* Call registered Error Callback */ + husart->ErrorCallback(husart); +#else + /* Call legacy weak Error Callback */ + DAL_USART_ErrorCallback(husart); +#endif /* USE_DAL_USART_REGISTER_CALLBACKS */ + } + } + else + { + /* Call user error callback */ +#if (USE_DAL_USART_REGISTER_CALLBACKS == 1) + /* Call registered Error Callback */ + husart->ErrorCallback(husart); +#else + /* Call legacy weak Error Callback */ + DAL_USART_ErrorCallback(husart); +#endif /* USE_DAL_USART_REGISTER_CALLBACKS */ + husart->ErrorCode = DAL_USART_ERROR_NONE; + } + } + return; + } + + /* USART in mode Transmitter -----------------------------------------------*/ + if (((isrflags & USART_STS_TXBEFLG) != RESET) && ((cr1its & USART_CTRL1_TXBEIEN) != RESET)) + { + if (husart->State == DAL_USART_STATE_BUSY_TX) + { + USART_Transmit_IT(husart); + } + else + { + USART_TransmitReceive_IT(husart); + } + return; + } + + /* USART in mode Transmitter (transmission end) ----------------------------*/ + if (((isrflags & USART_STS_TXCFLG) != RESET) && ((cr1its & USART_CTRL1_TXCIEN) != RESET)) + { + USART_EndTransmit_IT(husart); + return; + } +} + +/** + * @brief Tx Transfer completed callbacks. + * @param husart Pointer to a USART_HandleTypeDef structure that contains + * the configuration information for the specified USART module. + * @retval None + */ +__weak void DAL_USART_TxCpltCallback(USART_HandleTypeDef *husart) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(husart); + /* NOTE: This function should not be modified, when the callback is needed, + the DAL_USART_TxCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Tx Half Transfer completed callbacks. + * @param husart Pointer to a USART_HandleTypeDef structure that contains + * the configuration information for the specified USART module. + * @retval None + */ +__weak void DAL_USART_TxHalfCpltCallback(USART_HandleTypeDef *husart) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(husart); + /* NOTE: This function should not be modified, when the callback is needed, + the DAL_USART_TxHalfCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Rx Transfer completed callbacks. + * @param husart Pointer to a USART_HandleTypeDef structure that contains + * the configuration information for the specified USART module. + * @retval None + */ +__weak void DAL_USART_RxCpltCallback(USART_HandleTypeDef *husart) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(husart); + /* NOTE: This function should not be modified, when the callback is needed, + the DAL_USART_RxCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Rx Half Transfer completed callbacks. + * @param husart Pointer to a USART_HandleTypeDef structure that contains + * the configuration information for the specified USART module. + * @retval None + */ +__weak void DAL_USART_RxHalfCpltCallback(USART_HandleTypeDef *husart) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(husart); + /* NOTE: This function should not be modified, when the callback is needed, + the DAL_USART_RxHalfCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Tx/Rx Transfers completed callback for the non-blocking process. + * @param husart Pointer to a USART_HandleTypeDef structure that contains + * the configuration information for the specified USART module. + * @retval None + */ +__weak void DAL_USART_TxRxCpltCallback(USART_HandleTypeDef *husart) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(husart); + /* NOTE: This function should not be modified, when the callback is needed, + the DAL_USART_TxRxCpltCallback could be implemented in the user file + */ +} + +/** + * @brief USART error callbacks. + * @param husart Pointer to a USART_HandleTypeDef structure that contains + * the configuration information for the specified USART module. + * @retval None + */ +__weak void DAL_USART_ErrorCallback(USART_HandleTypeDef *husart) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(husart); + /* NOTE: This function should not be modified, when the callback is needed, + the DAL_USART_ErrorCallback could be implemented in the user file + */ +} + +/** + * @brief USART Abort Complete callback. + * @param husart USART handle. + * @retval None + */ +__weak void DAL_USART_AbortCpltCallback(USART_HandleTypeDef *husart) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(husart); + + /* NOTE : This function should not be modified, when the callback is needed, + the DAL_USART_AbortCpltCallback can be implemented in the user file. + */ +} + +/** + * @} + */ + +/** @defgroup USART_Exported_Functions_Group3 Peripheral State and Errors functions + * @brief USART State and Errors functions + * +@verbatim + ============================================================================== + ##### Peripheral State and Errors functions ##### + ============================================================================== + [..] + This subsection provides a set of functions allowing to return the State of + USART communication + process, return Peripheral Errors occurred during communication process + (+) DAL_USART_GetState() API can be helpful to check in run-time the state + of the USART peripheral. + (+) DAL_USART_GetError() check in run-time errors that could be occurred during + communication. +@endverbatim + * @{ + */ + +/** + * @brief Returns the USART state. + * @param husart Pointer to a USART_HandleTypeDef structure that contains + * the configuration information for the specified USART module. + * @retval DAL state + */ +DAL_USART_StateTypeDef DAL_USART_GetState(USART_HandleTypeDef *husart) +{ + return husart->State; +} + +/** + * @brief Return the USART error code + * @param husart Pointer to a USART_HandleTypeDef structure that contains + * the configuration information for the specified USART. + * @retval USART Error Code + */ +uint32_t DAL_USART_GetError(USART_HandleTypeDef *husart) +{ + return husart->ErrorCode; +} + +/** + * @} + */ + +/** @defgroup USART_Private_Functions USART Private Functions + * @{ + */ + +/** + * @brief Initialize the callbacks to their default values. + * @param husart USART handle. + * @retval none + */ +#if (USE_DAL_USART_REGISTER_CALLBACKS == 1) +void USART_InitCallbacksToDefault(USART_HandleTypeDef *husart) +{ + /* Init the USART Callback settings */ + husart->TxHalfCpltCallback = DAL_USART_TxHalfCpltCallback; /* Legacy weak TxHalfCpltCallback */ + husart->TxCpltCallback = DAL_USART_TxCpltCallback; /* Legacy weak TxCpltCallback */ + husart->RxHalfCpltCallback = DAL_USART_RxHalfCpltCallback; /* Legacy weak RxHalfCpltCallback */ + husart->RxCpltCallback = DAL_USART_RxCpltCallback; /* Legacy weak RxCpltCallback */ + husart->TxRxCpltCallback = DAL_USART_TxRxCpltCallback; /* Legacy weak TxRxCpltCallback */ + husart->ErrorCallback = DAL_USART_ErrorCallback; /* Legacy weak ErrorCallback */ + husart->AbortCpltCallback = DAL_USART_AbortCpltCallback; /* Legacy weak AbortCpltCallback */ +} +#endif /* USE_DAL_USART_REGISTER_CALLBACKS */ + +/** + * @brief DMA USART transmit process complete callback. + * @param hdma Pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +static void USART_DMATransmitCplt(DMA_HandleTypeDef *hdma) +{ + USART_HandleTypeDef *husart = (USART_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + /* DMA Normal mode */ + if ((hdma->Instance->SCFG & DMA_SCFGx_CIRCMEN) == 0U) + { + husart->TxXferCount = 0U; + if (husart->State == DAL_USART_STATE_BUSY_TX) + { + /* Disable the DMA transfer for transmit request by resetting the DMAT bit + in the USART CTRL3 register */ + CLEAR_BIT(husart->Instance->CTRL3, USART_CTRL3_DMATXEN); + + /* Enable the USART Transmit Complete Interrupt */ + SET_BIT(husart->Instance->CTRL1, USART_CTRL1_TXCIEN); + } + } + /* DMA Circular mode */ + else + { + if (husart->State == DAL_USART_STATE_BUSY_TX) + { +#if (USE_DAL_USART_REGISTER_CALLBACKS == 1) + /* Call registered Tx Complete Callback */ + husart->TxCpltCallback(husart); +#else + /* Call legacy weak Tx Complete Callback */ + DAL_USART_TxCpltCallback(husart); +#endif /* USE_DAL_USART_REGISTER_CALLBACKS */ + } + } +} + +/** + * @brief DMA USART transmit process half complete callback + * @param hdma Pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +static void USART_DMATxHalfCplt(DMA_HandleTypeDef *hdma) +{ + USART_HandleTypeDef *husart = (USART_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + +#if (USE_DAL_USART_REGISTER_CALLBACKS == 1) + /* Call registered Tx Half Complete Callback */ + husart->TxHalfCpltCallback(husart); +#else + /* Call legacy weak Tx Half Complete Callback */ + DAL_USART_TxHalfCpltCallback(husart); +#endif /* USE_DAL_USART_REGISTER_CALLBACKS */ +} + +/** + * @brief DMA USART receive process complete callback. + * @param hdma Pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +static void USART_DMAReceiveCplt(DMA_HandleTypeDef *hdma) +{ + USART_HandleTypeDef *husart = (USART_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + /* DMA Normal mode */ + if ((hdma->Instance->SCFG & DMA_SCFGx_CIRCMEN) == 0U) + { + husart->RxXferCount = 0x00U; + + /* Disable RXNE, PEIEN and ERRIEN (Frame error, noise error, overrun error) interrupts */ + CLEAR_BIT(husart->Instance->CTRL1, USART_CTRL1_PEIEN); + CLEAR_BIT(husart->Instance->CTRL3, USART_CTRL3_ERRIEN); + + /* Disable the DMA transfer for the Transmit/receiver request by clearing the DMAT/DMAR bit + in the USART CTRL3 register */ + CLEAR_BIT(husart->Instance->CTRL3, USART_CTRL3_DMARXEN); + CLEAR_BIT(husart->Instance->CTRL3, USART_CTRL3_DMATXEN); + + /* The USART state is DAL_USART_STATE_BUSY_RX */ + if (husart->State == DAL_USART_STATE_BUSY_RX) + { +#if (USE_DAL_USART_REGISTER_CALLBACKS == 1) + /* Call registered Rx Complete Callback */ + husart->RxCpltCallback(husart); +#else + /* Call legacy weak Rx Complete Callback */ + DAL_USART_RxCpltCallback(husart); +#endif /* USE_DAL_USART_REGISTER_CALLBACKS */ + } + /* The USART state is DAL_USART_STATE_BUSY_TX_RX */ + else + { +#if (USE_DAL_USART_REGISTER_CALLBACKS == 1) + /* Call registered Tx Rx Complete Callback */ + husart->TxRxCpltCallback(husart); +#else + /* Call legacy weak Tx Rx Complete Callback */ + DAL_USART_TxRxCpltCallback(husart); +#endif /* USE_DAL_USART_REGISTER_CALLBACKS */ + } + husart->State = DAL_USART_STATE_READY; + } + /* DMA circular mode */ + else + { + if (husart->State == DAL_USART_STATE_BUSY_RX) + { +#if (USE_DAL_USART_REGISTER_CALLBACKS == 1) + /* Call registered Rx Complete Callback */ + husart->RxCpltCallback(husart); +#else + /* Call legacy weak Rx Complete Callback */ + DAL_USART_RxCpltCallback(husart); +#endif /* USE_DAL_USART_REGISTER_CALLBACKS */ + } + /* The USART state is DAL_USART_STATE_BUSY_TX_RX */ + else + { +#if (USE_DAL_USART_REGISTER_CALLBACKS == 1) + /* Call registered Tx Rx Complete Callback */ + husart->TxRxCpltCallback(husart); +#else + /* Call legacy weak Tx Rx Complete Callback */ + DAL_USART_TxRxCpltCallback(husart); +#endif /* USE_DAL_USART_REGISTER_CALLBACKS */ + } + } +} + +/** + * @brief DMA USART receive process half complete callback + * @param hdma Pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +static void USART_DMARxHalfCplt(DMA_HandleTypeDef *hdma) +{ + USART_HandleTypeDef *husart = (USART_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + +#if (USE_DAL_USART_REGISTER_CALLBACKS == 1) + /* Call registered Rx Half Complete Callback */ + husart->RxHalfCpltCallback(husart); +#else + /* Call legacy weak Rx Half Complete Callback */ + DAL_USART_RxHalfCpltCallback(husart); +#endif /* USE_DAL_USART_REGISTER_CALLBACKS */ +} + +/** + * @brief DMA USART communication error callback. + * @param hdma Pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +static void USART_DMAError(DMA_HandleTypeDef *hdma) +{ + uint32_t dmarequest = 0x00U; + USART_HandleTypeDef *husart = (USART_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + husart->RxXferCount = 0x00U; + husart->TxXferCount = 0x00U; + + /* Stop USART DMA Tx request if ongoing */ + dmarequest = DAL_IS_BIT_SET(husart->Instance->CTRL3, USART_CTRL3_DMATXEN); + if ((husart->State == DAL_USART_STATE_BUSY_TX) && dmarequest) + { + USART_EndTxTransfer(husart); + } + + /* Stop USART DMA Rx request if ongoing */ + dmarequest = DAL_IS_BIT_SET(husart->Instance->CTRL3, USART_CTRL3_DMARXEN); + if ((husart->State == DAL_USART_STATE_BUSY_RX) && dmarequest) + { + USART_EndRxTransfer(husart); + } + + husart->ErrorCode |= DAL_USART_ERROR_DMA; + husart->State = DAL_USART_STATE_READY; + +#if (USE_DAL_USART_REGISTER_CALLBACKS == 1) + /* Call registered Error Callback */ + husart->ErrorCallback(husart); +#else + /* Call legacy weak Error Callback */ + DAL_USART_ErrorCallback(husart); +#endif /* USE_DAL_USART_REGISTER_CALLBACKS */ +} + +/** + * @brief This function handles USART Communication Timeout. It waits + * until a flag is no longer in the specified status. + * @param husart Pointer to a USART_HandleTypeDef structure that contains + * the configuration information for the specified USART module. + * @param Flag specifies the USART flag to check. + * @param Status The actual Flag status (SET or RESET). + * @param Tickstart Tick start value. + * @param Timeout Timeout duration. + * @retval DAL status + */ +static DAL_StatusTypeDef USART_WaitOnFlagUntilTimeout(USART_HandleTypeDef *husart, uint32_t Flag, FlagStatus Status, + uint32_t Tickstart, uint32_t Timeout) +{ + /* Wait until flag is set */ + while ((__DAL_USART_GET_FLAG(husart, Flag) ? SET : RESET) == Status) + { + /* Check for the Timeout */ + if (Timeout != DAL_MAX_DELAY) + { + if ((Timeout == 0U) || ((DAL_GetTick() - Tickstart) > Timeout)) + { + /* Disable the USART Transmit Complete Interrupt */ + CLEAR_BIT(husart->Instance->CTRL1, USART_CTRL1_TXBEIEN); + + /* Disable the USART RXNE Interrupt */ + CLEAR_BIT(husart->Instance->CTRL1, USART_CTRL1_RXBNEIEN); + + /* Disable the USART Parity Error Interrupt */ + CLEAR_BIT(husart->Instance->CTRL1, USART_CTRL1_PEIEN); + + /* Disable the USART Error Interrupt: (Frame error, noise error, overrun error) */ + CLEAR_BIT(husart->Instance->CTRL3, USART_CTRL3_ERRIEN); + + husart->State = DAL_USART_STATE_READY; + + /* Process Unlocked */ + __DAL_UNLOCK(husart); + + return DAL_TIMEOUT; + } + } + } + return DAL_OK; +} + +/** + * @brief End ongoing Tx transfer on USART peripheral (following error detection or Transmit completion). + * @param husart USART handle. + * @retval None + */ +static void USART_EndTxTransfer(USART_HandleTypeDef *husart) +{ + /* Disable TXBEIEN and TXCIEN interrupts */ + CLEAR_BIT(husart->Instance->CTRL1, (USART_CTRL1_TXBEIEN | USART_CTRL1_TXCIEN)); + + /* At end of Tx process, restore husart->State to Ready */ + husart->State = DAL_USART_STATE_READY; +} + +/** + * @brief End ongoing Rx transfer on USART peripheral (following error detection or Reception completion). + * @param husart USART handle. + * @retval None + */ +static void USART_EndRxTransfer(USART_HandleTypeDef *husart) +{ + /* Disable RXNE, PE and ERR interrupts */ + CLEAR_BIT(husart->Instance->CTRL1, (USART_CTRL1_RXBNEIEN | USART_CTRL1_PEIEN)); + CLEAR_BIT(husart->Instance->CTRL3, USART_CTRL3_ERRIEN); + + /* At end of Rx process, restore husart->State to Ready */ + husart->State = DAL_USART_STATE_READY; +} + +/** + * @brief DMA USART communication abort callback, when initiated by DAL services on Error + * (To be called at end of DMA Abort procedure following error occurrence). + * @param hdma DMA handle. + * @retval None + */ +static void USART_DMAAbortOnError(DMA_HandleTypeDef *hdma) +{ + USART_HandleTypeDef *husart = (USART_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + husart->RxXferCount = 0x00U; + husart->TxXferCount = 0x00U; + +#if (USE_DAL_USART_REGISTER_CALLBACKS == 1) + /* Call registered Error Callback */ + husart->ErrorCallback(husart); +#else + /* Call legacy weak Error Callback */ + DAL_USART_ErrorCallback(husart); +#endif /* USE_DAL_USART_REGISTER_CALLBACKS */ +} + +/** + * @brief DMA USART Tx communication abort callback, when initiated by user + * (To be called at end of DMA Tx Abort procedure following user abort request). + * @note When this callback is executed, User Abort complete call back is called only if no + * Abort still ongoing for Rx DMA Handle. + * @param hdma DMA handle. + * @retval None + */ +static void USART_DMATxAbortCallback(DMA_HandleTypeDef *hdma) +{ + USART_HandleTypeDef *husart = (USART_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + + husart->hdmatx->XferAbortCallback = NULL; + + /* Check if an Abort process is still ongoing */ + if (husart->hdmarx != NULL) + { + if (husart->hdmarx->XferAbortCallback != NULL) + { + return; + } + } + + /* No Abort process still ongoing : All DMA channels are aborted, call user Abort Complete callback */ + husart->TxXferCount = 0x00U; + husart->RxXferCount = 0x00U; + + /* Reset errorCode */ + husart->ErrorCode = DAL_USART_ERROR_NONE; + + /* Restore husart->State to Ready */ + husart->State = DAL_USART_STATE_READY; + + /* Call user Abort complete callback */ +#if (USE_DAL_USART_REGISTER_CALLBACKS == 1) + /* Call registered Abort Complete Callback */ + husart->AbortCpltCallback(husart); +#else + /* Call legacy weak Abort Complete Callback */ + DAL_USART_AbortCpltCallback(husart); +#endif /* USE_DAL_USART_REGISTER_CALLBACKS */ +} + +/** + * @brief DMA USART Rx communication abort callback, when initiated by user + * (To be called at end of DMA Rx Abort procedure following user abort request). + * @note When this callback is executed, User Abort complete call back is called only if no + * Abort still ongoing for Tx DMA Handle. + * @param hdma DMA handle. + * @retval None + */ +static void USART_DMARxAbortCallback(DMA_HandleTypeDef *hdma) +{ + USART_HandleTypeDef *husart = (USART_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + + husart->hdmarx->XferAbortCallback = NULL; + + /* Check if an Abort process is still ongoing */ + if (husart->hdmatx != NULL) + { + if (husart->hdmatx->XferAbortCallback != NULL) + { + return; + } + } + + /* No Abort process still ongoing : All DMA channels are aborted, call user Abort Complete callback */ + husart->TxXferCount = 0x00U; + husart->RxXferCount = 0x00U; + + /* Reset errorCode */ + husart->ErrorCode = DAL_USART_ERROR_NONE; + + /* Restore husart->State to Ready */ + husart->State = DAL_USART_STATE_READY; + + /* Call user Abort complete callback */ +#if (USE_DAL_USART_REGISTER_CALLBACKS == 1) + /* Call registered Abort Complete Callback */ + husart->AbortCpltCallback(husart); +#else + /* Call legacy weak Abort Complete Callback */ + DAL_USART_AbortCpltCallback(husart); +#endif /* USE_DAL_USART_REGISTER_CALLBACKS */ +} + +/** + * @brief Simplex Send an amount of data in non-blocking mode. + * @param husart Pointer to a USART_HandleTypeDef structure that contains + * the configuration information for the specified USART module. + * @retval DAL status + * @note The USART errors are not managed to avoid the overrun error. + */ +static DAL_StatusTypeDef USART_Transmit_IT(USART_HandleTypeDef *husart) +{ + const uint16_t *tmp; + + if (husart->State == DAL_USART_STATE_BUSY_TX) + { + if ((husart->Init.WordLength == USART_WORDLENGTH_9B) && (husart->Init.Parity == USART_PARITY_NONE)) + { + tmp = (const uint16_t *) husart->pTxBuffPtr; + husart->Instance->DATA = (uint16_t)(*tmp & (uint16_t)0x01FF); + husart->pTxBuffPtr += 2U; + } + else + { + husart->Instance->DATA = (uint8_t)(*husart->pTxBuffPtr++ & (uint8_t)0x00FF); + } + + if (--husart->TxXferCount == 0U) + { + /* Disable the USART Transmit data register empty Interrupt */ + CLEAR_BIT(husart->Instance->CTRL1, USART_CTRL1_TXBEIEN); + + /* Enable the USART Transmit Complete Interrupt */ + SET_BIT(husart->Instance->CTRL1, USART_CTRL1_TXCIEN); + } + return DAL_OK; + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief Wraps up transmission in non blocking mode. + * @param husart Pointer to a USART_HandleTypeDef structure that contains + * the configuration information for the specified USART module. + * @retval DAL status + */ +static DAL_StatusTypeDef USART_EndTransmit_IT(USART_HandleTypeDef *husart) +{ + /* Disable the USART Transmit Complete Interrupt */ + CLEAR_BIT(husart->Instance->CTRL1, USART_CTRL1_TXCIEN); + + /* Disable the USART Error Interrupt: (Frame error, noise error, overrun error) */ + CLEAR_BIT(husart->Instance->CTRL3, USART_CTRL3_ERRIEN); + + husart->State = DAL_USART_STATE_READY; + +#if (USE_DAL_USART_REGISTER_CALLBACKS == 1) + /* Call registered Tx Complete Callback */ + husart->TxCpltCallback(husart); +#else + /* Call legacy weak Tx Complete Callback */ + DAL_USART_TxCpltCallback(husart); +#endif /* USE_DAL_USART_REGISTER_CALLBACKS */ + + return DAL_OK; +} + +/** + * @brief Simplex Receive an amount of data in non-blocking mode. + * @param husart Pointer to a USART_HandleTypeDef structure that contains + * the configuration information for the specified USART module. + * @retval DAL status + */ +static DAL_StatusTypeDef USART_Receive_IT(USART_HandleTypeDef *husart) +{ + uint8_t *pdata8bits; + uint16_t *pdata16bits; + + if (husart->State == DAL_USART_STATE_BUSY_RX) + { + if ((husart->Init.WordLength == USART_WORDLENGTH_9B) && (husart->Init.Parity == USART_PARITY_NONE)) + { + pdata8bits = NULL; + pdata16bits = (uint16_t *) husart->pRxBuffPtr; + *pdata16bits = (uint16_t)(husart->Instance->DATA & (uint16_t)0x01FF); + husart->pRxBuffPtr += 2U; + } + else + { + pdata8bits = (uint8_t *) husart->pRxBuffPtr; + pdata16bits = NULL; + + if ((husart->Init.WordLength == USART_WORDLENGTH_9B) || ((husart->Init.WordLength == USART_WORDLENGTH_8B) && (husart->Init.Parity == USART_PARITY_NONE))) + { + *pdata8bits = (uint8_t)(husart->Instance->DATA & (uint8_t)0x00FF); + } + else + { + *pdata8bits = (uint8_t)(husart->Instance->DATA & (uint8_t)0x007F); + } + + husart->pRxBuffPtr += 1U; + } + + husart->RxXferCount--; + + if (husart->RxXferCount == 0U) + { + /* Disable the USART RXNE Interrupt */ + CLEAR_BIT(husart->Instance->CTRL1, USART_CTRL1_RXBNEIEN); + + /* Disable the USART Parity Error Interrupt */ + CLEAR_BIT(husart->Instance->CTRL1, USART_CTRL1_PEIEN); + + /* Disable the USART Error Interrupt: (Frame error, noise error, overrun error) */ + CLEAR_BIT(husart->Instance->CTRL3, USART_CTRL3_ERRIEN); + + husart->State = DAL_USART_STATE_READY; +#if (USE_DAL_USART_REGISTER_CALLBACKS == 1) + /* Call registered Rx Complete Callback */ + husart->RxCpltCallback(husart); +#else + /* Call legacy weak Rx Complete Callback */ + DAL_USART_RxCpltCallback(husart); +#endif /* USE_DAL_USART_REGISTER_CALLBACKS */ + + return DAL_OK; + } + else + { + /* Send dummy byte in order to generate the clock for the slave to send the next data. + * Whatever the frame length (7, 8 or 9-bit long), the same dummy value + * can be written for all the cases. */ + husart->Instance->DATA = (DUMMY_DATA & (uint16_t)0x0FF); + } + return DAL_OK; + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief Full-Duplex Send receive an amount of data in full-duplex mode (non-blocking). + * @param husart Pointer to a USART_HandleTypeDef structure that contains + * the configuration information for the specified USART module. + * @retval DAL status + */ +static DAL_StatusTypeDef USART_TransmitReceive_IT(USART_HandleTypeDef *husart) +{ + const uint16_t *pdatatx16bits; + uint16_t *pdatarx16bits; + + if (husart->State == DAL_USART_STATE_BUSY_TX_RX) + { + if (husart->TxXferCount != 0x00U) + { + if (__DAL_USART_GET_FLAG(husart, USART_FLAG_TXE) != RESET) + { + if ((husart->Init.WordLength == USART_WORDLENGTH_9B) && (husart->Init.Parity == USART_PARITY_NONE)) + { + pdatatx16bits = (const uint16_t *) husart->pTxBuffPtr; + husart->Instance->DATA = (uint16_t)(*pdatatx16bits & (uint16_t)0x01FF); + husart->pTxBuffPtr += 2U; + } + else + { + husart->Instance->DATA = (uint8_t)(*husart->pTxBuffPtr++ & (uint8_t)0x00FF); + } + + husart->TxXferCount--; + + /* Check the latest data transmitted */ + if (husart->TxXferCount == 0U) + { + CLEAR_BIT(husart->Instance->CTRL1, USART_CTRL1_TXBEIEN); + } + } + } + + if (husart->RxXferCount != 0x00U) + { + if (__DAL_USART_GET_FLAG(husart, USART_FLAG_RXNE) != RESET) + { + if ((husart->Init.WordLength == USART_WORDLENGTH_9B) && (husart->Init.Parity == USART_PARITY_NONE)) + { + pdatarx16bits = (uint16_t *) husart->pRxBuffPtr; + *pdatarx16bits = (uint16_t)(husart->Instance->DATA & (uint16_t)0x01FF); + husart->pRxBuffPtr += 2U; + } + else + { + if ((husart->Init.WordLength == USART_WORDLENGTH_9B) || ((husart->Init.WordLength == USART_WORDLENGTH_8B) && (husart->Init.Parity == USART_PARITY_NONE))) + { + *husart->pRxBuffPtr = (uint8_t)(husart->Instance->DATA & (uint8_t)0x00FF); + } + else + { + *husart->pRxBuffPtr = (uint8_t)(husart->Instance->DATA & (uint8_t)0x007F); + } + husart->pRxBuffPtr += 1U; + } + + husart->RxXferCount--; + } + } + + /* Check the latest data received */ + if (husart->RxXferCount == 0U) + { + /* Disable the USART RXBNEIEN Interrupt */ + CLEAR_BIT(husart->Instance->CTRL1, USART_CTRL1_RXBNEIEN); + + /* Disable the USART Parity Error Interrupt */ + CLEAR_BIT(husart->Instance->CTRL1, USART_CTRL1_PEIEN); + + /* Disable the USART Error Interrupt: (Frame error, noise error, overrun error) */ + CLEAR_BIT(husart->Instance->CTRL3, USART_CTRL3_ERRIEN); + + husart->State = DAL_USART_STATE_READY; + +#if (USE_DAL_USART_REGISTER_CALLBACKS == 1) + /* Call registered Tx Rx Complete Callback */ + husart->TxRxCpltCallback(husart); +#else + /* Call legacy weak Tx Rx Complete Callback */ + DAL_USART_TxRxCpltCallback(husart); +#endif /* USE_DAL_USART_REGISTER_CALLBACKS */ + + return DAL_OK; + } + + return DAL_OK; + } + else + { + return DAL_BUSY; + } +} + +/** + * @brief Configures the USART peripheral. + * @param husart Pointer to a USART_HandleTypeDef structure that contains + * the configuration information for the specified USART module. + * @retval None + */ +static void USART_SetConfig(USART_HandleTypeDef *husart) +{ + uint32_t tmpreg = 0x00U; + uint32_t pclk; + + /* Check the parameters */ + ASSERT_PARAM(IS_USART_INSTANCE(husart->Instance)); + ASSERT_PARAM(IS_USART_POLARITY(husart->Init.CLKPolarity)); + ASSERT_PARAM(IS_USART_PHASE(husart->Init.CLKPhase)); + ASSERT_PARAM(IS_USART_LASTBIT(husart->Init.CLKLastBit)); + ASSERT_PARAM(IS_USART_BAUDRATE(husart->Init.BaudRate)); + ASSERT_PARAM(IS_USART_WORD_LENGTH(husart->Init.WordLength)); + ASSERT_PARAM(IS_USART_STOPBITS(husart->Init.StopBits)); + ASSERT_PARAM(IS_USART_PARITY(husart->Init.Parity)); + ASSERT_PARAM(IS_USART_MODE(husart->Init.Mode)); + + /* The LBCL, CPOL and CPHA bits have to be selected when both the transmitter and the + receiver are disabled (TE=RE=0) to ensure that the clock pulses function correctly. */ + CLEAR_BIT(husart->Instance->CTRL1, (USART_CTRL1_TXEN | USART_CTRL1_RXEN)); + + /*---------------------------- USART CTRL2 Configuration ---------------------*/ + tmpreg = husart->Instance->CTRL2; + /* Clear CLKEN, CPOL, CPHA and LBCL bits */ + tmpreg &= (uint32_t)~((uint32_t)(USART_CTRL2_CPHA | USART_CTRL2_CPOL | USART_CTRL2_CLKEN | USART_CTRL2_LBCPOEN | USART_CTRL2_STOPCFG)); + /* Configure the USART Clock, CPOL, CPHA and LastBit -----------------------*/ + /* Set CPOL bit according to husart->Init.CLKPolarity value */ + /* Set CPHA bit according to husart->Init.CLKPhase value */ + /* Set LBCL bit according to husart->Init.CLKLastBit value */ + /* Set Stop Bits: Set STOP[13:12] bits according to husart->Init.StopBits value */ + tmpreg |= (uint32_t)(USART_CLOCK_ENABLE | husart->Init.CLKPolarity | + husart->Init.CLKPhase | husart->Init.CLKLastBit | husart->Init.StopBits); + /* Write to USART CTRL2 */ + WRITE_REG(husart->Instance->CTRL2, (uint32_t)tmpreg); + + /*-------------------------- USART CTRL1 Configuration -----------------------*/ + tmpreg = husart->Instance->CTRL1; + + /* Clear M, PCE, PS, TE, RE and OVER8 bits */ + tmpreg &= (uint32_t)~((uint32_t)(USART_CTRL1_DBLCFG | USART_CTRL1_PCEN | USART_CTRL1_PCFG | USART_CTRL1_TXEN | \ + USART_CTRL1_RXEN | USART_CTRL1_OSMCFG)); + + /* Configure the USART Word Length, Parity and mode: + Set the M bits according to husart->Init.WordLength value + Set PCE and PS bits according to husart->Init.Parity value + Set TE and RE bits according to husart->Init.Mode value + Force OVER8 bit to 1 in order to reach the max USART frequencies */ + tmpreg |= (uint32_t)husart->Init.WordLength | husart->Init.Parity | husart->Init.Mode | USART_CTRL1_OSMCFG; + + /* Write to USART CTRL1 */ + WRITE_REG(husart->Instance->CTRL1, (uint32_t)tmpreg); + + /*-------------------------- USART CTRL3 Configuration -----------------------*/ + /* Clear CTSEN and RTSEN bits */ + CLEAR_BIT(husart->Instance->CTRL3, (USART_CTRL3_RTSEN | USART_CTRL3_CTSEN)); + + /*-------------------------- USART BR Configuration -----------------------*/ +#if defined(USART6) && defined(UART9) && defined(UART10) + if ((husart->Instance == USART1) || (husart->Instance == USART6) || (husart->Instance == UART9) || (husart->Instance == UART10)) + { + pclk = DAL_RCM_GetPCLK2Freq(); + husart->Instance->BR = USART_BR(pclk, husart->Init.BaudRate); + } +#elif defined(USART6) + if((husart->Instance == USART1) || (husart->Instance == USART6)) + { + pclk = DAL_RCM_GetPCLK2Freq(); + husart->Instance->BR = USART_BR(pclk, husart->Init.BaudRate); + } +#else + if(husart->Instance == USART1) + { + pclk = DAL_RCM_GetPCLK2Freq(); + husart->Instance->BR = USART_BR(pclk, husart->Init.BaudRate); + } +#endif /* USART6 || UART9 || UART10 */ + else + { + pclk = DAL_RCM_GetPCLK1Freq(); + husart->Instance->BR = USART_BR(pclk, husart->Init.BaudRate); + } +} + +/** + * @} + */ + +/** + * @} + */ + +#endif /* DAL_USART_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_wwdt.c b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_wwdt.c new file mode 100644 index 0000000000..f1dc6d9af8 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_dal_wwdt.c @@ -0,0 +1,445 @@ +/** + * + * @file apm32f4xx_dal_wwdt.c + * @brief WWDT DAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the Window Watchdog (WWDT) peripheral: + * + Initialization and Configuration functions + * + IO operation functions + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + * + @verbatim + ============================================================================== + ##### WWDT Specific features ##### + ============================================================================== + [..] + Once enabled the WWDT generates a system reset on expiry of a programmed + time period, unless the program refreshes the counter (T[6;0] downcounter) + before reaching 0x3F value (i.e. a reset is generated when the counter + value rolls down from 0x40 to 0x3F). + + (+) An MCU reset is also generated if the counter value is refreshed + before the counter has reached the refresh window value. This + implies that the counter must be refreshed in a limited window. + (+) Once enabled the WWDT cannot be disabled except by a system reset. + (+) If required by application, an Early Wakeup Interrupt can be triggered + in order to be warned before WWDT expiration. The Early Wakeup Interrupt + (EWI) can be used if specific safety operations or data logging must + be performed before the actual reset is generated. When the downcounter + reaches 0x40, interrupt occurs. This mechanism requires WWDT interrupt + line to be enabled in NVIC. Once enabled, EWI interrupt cannot be + disabled except by a system reset. + (+) WWDTRST flag in RCC CSR register can be used to inform when a WWDT + reset occurs. + (+) The WWDT counter input clock is derived from the APB clock divided + by a programmable prescaler. + (+) WWDT clock (Hz) = PCLK1 / (4096 * Prescaler) + (+) WWDT timeout (mS) = 1000 * (T[5;0] + 1) / WWDT clock (Hz) + where T[5;0] are the lowest 6 bits of Counter. + (+) WWDT Counter refresh is allowed between the following limits : + (++) min time (mS) = 1000 * (Counter - Window) / WWDT clock + (++) max time (mS) = 1000 * (Counter - 0x40) / WWDT clock + (+) Typical values: + (++) Counter min (T[5;0] = 0x00) at 42MHz (PCLK1) with zero prescaler: + max timeout before reset: approximately 97.52us + (++) Counter max (T[5;0] = 0x3F) at 42MHz (PCLK1) with prescaler + dividing by 8: + max timeout before reset: approximately 49.93ms + + ##### How to use this driver ##### + ============================================================================== + + *** Common driver usage *** + =========================== + + [..] + (+) Enable WWDT APB1 clock using __DAL_RCM_WWDT_CLK_ENABLE(). + (+) Configure the WWDT prescaler, refresh window value, counter value and early + interrupt status using DAL_WWDT_Init() function. This will automatically + enable WWDT and start its downcounter. Time reference can be taken from + function exit. Care must be taken to provide a counter value + greater than 0x40 to prevent generation of immediate reset. + (+) If the Early Wakeup Interrupt (EWI) feature is enabled, an interrupt is + generated when the counter reaches 0x40. When DAL_WWDT_IRQHandler is + triggered by the interrupt service routine, flag will be automatically + cleared and DAL_WWDT_WakeupCallback user callback will be executed. User + can add his own code by customization of callback DAL_WWDT_WakeupCallback. + (+) Then the application program must refresh the WWDT counter at regular + intervals during normal operation to prevent an MCU reset, using + DAL_WWDT_Refresh() function. This operation must occur only when + the counter is lower than the refresh window value already programmed. + + *** Callback registration *** + ============================= + + [..] + The compilation define USE_DAL_WWDT_REGISTER_CALLBACKS when set to 1 allows + the user to configure dynamically the driver callbacks. Use Functions + DAL_WWDT_RegisterCallback() to register a user callback. + + (+) Function DAL_WWDT_RegisterCallback() allows to register following + callbacks: + (++) EwiCallback : callback for Early WakeUp Interrupt. + (++) MspInitCallback : WWDT MspInit. + This function takes as parameters the DAL peripheral handle, the Callback ID + and a pointer to the user callback function. + + (+) Use function DAL_WWDT_UnRegisterCallback() to reset a callback to + the default weak (surcharged) function. DAL_WWDT_UnRegisterCallback() + takes as parameters the DAL peripheral handle and the Callback ID. + This function allows to reset following callbacks: + (++) EwiCallback : callback for Early WakeUp Interrupt. + (++) MspInitCallback : WWDT MspInit. + + [..] + When calling DAL_WWDT_Init function, callbacks are reset to the + corresponding legacy weak (surcharged) functions: + DAL_WWDT_EarlyWakeupCallback() and DAL_WWDT_MspInit() only if they have + not been registered before. + + [..] + When compilation define USE_DAL_WWDT_REGISTER_CALLBACKS is set to 0 or + not defined, the callback registering feature is not available + and weak (surcharged) callbacks are used. + + *** WWDT DAL driver macros list *** + =================================== + [..] + Below the list of available macros in WWDT DAL driver. + (+) __DAL_WWDT_ENABLE: Enable the WWDT peripheral + (+) __DAL_WWDT_GET_FLAG: Get the selected WWDT's flag status + (+) __DAL_WWDT_CLEAR_FLAG: Clear the WWDT's pending flags + (+) __DAL_WWDT_ENABLE_IT: Enable the WWDT early wakeup interrupt + + @endverbatim + * + */ + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +#ifdef DAL_WWDT_MODULE_ENABLED +/** @defgroup WWDT WWDT + * @brief WWDT DAL module driver. + * @{ + */ + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Exported functions --------------------------------------------------------*/ + +/** @defgroup WWDT_Exported_Functions WWDT Exported Functions + * @{ + */ + +/** @defgroup WWDT_Exported_Functions_Group1 Initialization and Configuration functions + * @brief Initialization and Configuration functions. + * +@verbatim + ============================================================================== + ##### Initialization and Configuration functions ##### + ============================================================================== + [..] + This section provides functions allowing to: + (+) Initialize and start the WWDT according to the specified parameters + in the WWDT_InitTypeDef of associated handle. + (+) Initialize the WWDT MSP. + +@endverbatim + * @{ + */ + +/** + * @brief Initialize the WWDT according to the specified. + * parameters in the WWDT_InitTypeDef of associated handle. + * @param hwwdt pointer to a WWDT_HandleTypeDef structure that contains + * the configuration information for the specified WWDT module. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_WWDT_Init(WWDT_HandleTypeDef *hwwdt) +{ + /* Check the WWDT handle allocation */ + if (hwwdt == NULL) + { + return DAL_ERROR; + } + + /* Check the parameters */ + ASSERT_PARAM(IS_WWDT_ALL_INSTANCE(hwwdt->Instance)); + ASSERT_PARAM(IS_WWDT_PRESCALER(hwwdt->Init.Prescaler)); + ASSERT_PARAM(IS_WWDT_WINDOW(hwwdt->Init.Window)); + ASSERT_PARAM(IS_WWDT_COUNTER(hwwdt->Init.Counter)); + ASSERT_PARAM(IS_WWDT_EWI_MODE(hwwdt->Init.EWIMode)); + +#if (USE_DAL_WWDT_REGISTER_CALLBACKS == 1) + /* Reset Callback pointers */ + if (hwwdt->EwiCallback == NULL) + { + hwwdt->EwiCallback = DAL_WWDT_EarlyWakeupCallback; + } + + if (hwwdt->MspInitCallback == NULL) + { + hwwdt->MspInitCallback = DAL_WWDT_MspInit; + } + + /* Init the low level hardware */ + hwwdt->MspInitCallback(hwwdt); +#else + /* Init the low level hardware */ + DAL_WWDT_MspInit(hwwdt); +#endif /* USE_DAL_WWDT_REGISTER_CALLBACKS */ + + /* Set WWDT Counter */ + WRITE_REG(hwwdt->Instance->CTRL, (WWDT_CTRL_WWDTEN | hwwdt->Init.Counter)); + + /* Set WWDT Prescaler and Window */ + WRITE_REG(hwwdt->Instance->CFR, (hwwdt->Init.EWIMode | hwwdt->Init.Prescaler | hwwdt->Init.Window)); + + /* Return function status */ + return DAL_OK; +} + + +/** + * @brief Initialize the WWDT MSP. + * @param hwwdt pointer to a WWDT_HandleTypeDef structure that contains + * the configuration information for the specified WWDT module. + * @note When rewriting this function in user file, mechanism may be added + * to avoid multiple initialize when DAL_WWDT_Init function is called + * again to change parameters. + * @retval None + */ +__weak void DAL_WWDT_MspInit(WWDT_HandleTypeDef *hwwdt) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hwwdt); + + /* NOTE: This function should not be modified, when the callback is needed, + the DAL_WWDT_MspInit could be implemented in the user file + */ +} + + +#if (USE_DAL_WWDT_REGISTER_CALLBACKS == 1) +/** + * @brief Register a User WWDT Callback + * To be used instead of the weak (surcharged) predefined callback + * @param hwwdt WWDT handle + * @param CallbackID ID of the callback to be registered + * This parameter can be one of the following values: + * @arg @ref DAL_WWDT_EWI_CB_ID Early WakeUp Interrupt Callback ID + * @arg @ref DAL_WWDT_MSPINIT_CB_ID MspInit callback ID + * @param pCallback pointer to the Callback function + * @retval status + */ +DAL_StatusTypeDef DAL_WWDT_RegisterCallback(WWDT_HandleTypeDef *hwwdt, DAL_WWDT_CallbackIDTypeDef CallbackID, + pWWDT_CallbackTypeDef pCallback) +{ + DAL_StatusTypeDef status = DAL_OK; + + if (pCallback == NULL) + { + status = DAL_ERROR; + } + else + { + switch (CallbackID) + { + case DAL_WWDT_EWI_CB_ID: + hwwdt->EwiCallback = pCallback; + break; + + case DAL_WWDT_MSPINIT_CB_ID: + hwwdt->MspInitCallback = pCallback; + break; + + default: + status = DAL_ERROR; + break; + } + } + + return status; +} + + +/** + * @brief Unregister a WWDT Callback + * WWDT Callback is redirected to the weak (surcharged) predefined callback + * @param hwwdt WWDT handle + * @param CallbackID ID of the callback to be registered + * This parameter can be one of the following values: + * @arg @ref DAL_WWDT_EWI_CB_ID Early WakeUp Interrupt Callback ID + * @arg @ref DAL_WWDT_MSPINIT_CB_ID MspInit callback ID + * @retval status + */ +DAL_StatusTypeDef DAL_WWDT_UnRegisterCallback(WWDT_HandleTypeDef *hwwdt, DAL_WWDT_CallbackIDTypeDef CallbackID) +{ + DAL_StatusTypeDef status = DAL_OK; + + switch (CallbackID) + { + case DAL_WWDT_EWI_CB_ID: + hwwdt->EwiCallback = DAL_WWDT_EarlyWakeupCallback; + break; + + case DAL_WWDT_MSPINIT_CB_ID: + hwwdt->MspInitCallback = DAL_WWDT_MspInit; + break; + + default: + status = DAL_ERROR; + break; + } + + return status; +} +#endif /* USE_DAL_WWDT_REGISTER_CALLBACKS */ + +/** + * @} + */ + +/** @defgroup WWDT_Exported_Functions_Group2 IO operation functions + * @brief IO operation functions + * +@verbatim + ============================================================================== + ##### IO operation functions ##### + ============================================================================== + [..] + This section provides functions allowing to: + (+) Refresh the WWDT. + (+) Handle WWDT interrupt request and associated function callback. + +@endverbatim + * @{ + */ + +/** + * @brief Refresh the WWDT. + * @param hwwdt pointer to a WWDT_HandleTypeDef structure that contains + * the configuration information for the specified WWDT module. + * @retval DAL status + */ +DAL_StatusTypeDef DAL_WWDT_Refresh(WWDT_HandleTypeDef *hwwdt) +{ + /* Write to WWDT CTRL the WWDT Counter value to refresh with */ + WRITE_REG(hwwdt->Instance->CTRL, (hwwdt->Init.Counter)); + + /* Return function status */ + return DAL_OK; +} + +/** + * @brief Handle WWDT interrupt request. + * @note The Early Wakeup Interrupt (EWI) can be used if specific safety operations + * or data logging must be performed before the actual reset is generated. + * The EWI interrupt is enabled by calling DAL_WWDT_Init function with + * EWIMode set to WWDT_EWI_ENABLE. + * When the downcounter reaches the value 0x40, and EWI interrupt is + * generated and the corresponding Interrupt Service Routine (ISR) can + * be used to trigger specific actions (such as communications or data + * logging), before resetting the device. + * @param hwwdt pointer to a WWDT_HandleTypeDef structure that contains + * the configuration information for the specified WWDT module. + * @retval None + */ +void DAL_WWDT_IRQHandler(WWDT_HandleTypeDef *hwwdt) +{ + /* Check if Early Wakeup Interrupt is enable */ + if (__DAL_WWDT_GET_IT_SOURCE(hwwdt, WWDT_IT_EWI) != RESET) + { + /* Check if WWDT Early Wakeup Interrupt occurred */ + if (__DAL_WWDT_GET_FLAG(hwwdt, WWDT_FLAG_EWIF) != RESET) + { + /* Clear the WWDT Early Wakeup flag */ + __DAL_WWDT_CLEAR_FLAG(hwwdt, WWDT_FLAG_EWIF); + +#if (USE_DAL_WWDT_REGISTER_CALLBACKS == 1) + /* Early Wakeup registered callback */ + hwwdt->EwiCallback(hwwdt); +#else + /* Early Wakeup callback */ + DAL_WWDT_EarlyWakeupCallback(hwwdt); +#endif /* USE_DAL_WWDT_REGISTER_CALLBACKS */ + } + } +} + + +/** + * @brief WWDT Early Wakeup callback. + * @param hwwdt pointer to a WWDT_HandleTypeDef structure that contains + * the configuration information for the specified WWDT module. + * @retval None + */ +__weak void DAL_WWDT_EarlyWakeupCallback(WWDT_HandleTypeDef *hwwdt) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hwwdt); + + /* NOTE: This function should not be modified, when the callback is needed, + the DAL_WWDT_EarlyWakeupCallback could be implemented in the user file + */ +} + +/** + * @} + */ + +/** + * @} + */ + +#endif /* DAL_WWDT_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_ddl_adc.c b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_ddl_adc.c new file mode 100644 index 0000000000..ef26867f9d --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_ddl_adc.c @@ -0,0 +1,952 @@ +/** + * + * @file apm32f4xx_ddl_adc.c + * @brief ADC DDL module driver + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2017 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + */ +#if defined(USE_FULL_DDL_DRIVER) + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_ddl_adc.h" +#include "apm32f4xx_ddl_bus.h" + +#ifdef USE_FULL_ASSERT + #include "apm32_assert.h" +#else + #define ASSERT_PARAM(_PARAM_) ((void)(_PARAM_)) +#endif + +/** @addtogroup APM32F4xx_DDL_Driver + * @{ + */ + +#if defined (ADC1) || defined (ADC2) || defined (ADC3) + +/** @addtogroup ADC_DDL ADC + * @{ + */ + +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/* Private macros ------------------------------------------------------------*/ + +/** @addtogroup ADC_DDL_Private_Macros + * @{ + */ + +/* Check of parameters for configuration of ADC hierarchical scope: */ +/* common to several ADC instances. */ +#define IS_DDL_ADC_COMMON_CLOCK(__CLOCK__) \ + ( ((__CLOCK__) == DDL_ADC_CLOCK_SYNC_PCLK_DIV2) \ + || ((__CLOCK__) == DDL_ADC_CLOCK_SYNC_PCLK_DIV4) \ + || ((__CLOCK__) == DDL_ADC_CLOCK_SYNC_PCLK_DIV6) \ + || ((__CLOCK__) == DDL_ADC_CLOCK_SYNC_PCLK_DIV8) \ + ) + +/* Check of parameters for configuration of ADC hierarchical scope: */ +/* ADC instance. */ +#define IS_DDL_ADC_RESOLUTION(__RESOLUTION__) \ + ( ((__RESOLUTION__) == DDL_ADC_RESOLUTION_12B) \ + || ((__RESOLUTION__) == DDL_ADC_RESOLUTION_10B) \ + || ((__RESOLUTION__) == DDL_ADC_RESOLUTION_8B) \ + || ((__RESOLUTION__) == DDL_ADC_RESOLUTION_6B) \ + ) + +#define IS_DDL_ADC_DATA_ALIGN(__DATA_ALIGN__) \ + ( ((__DATA_ALIGN__) == DDL_ADC_DATA_ALIGN_RIGHT) \ + || ((__DATA_ALIGN__) == DDL_ADC_DATA_ALIGN_LEFT) \ + ) + +#define IS_DDL_ADC_SCAN_SELECTION(__SCAN_SELECTION__) \ + ( ((__SCAN_SELECTION__) == DDL_ADC_SEQ_SCAN_DISABLE) \ + || ((__SCAN_SELECTION__) == DDL_ADC_SEQ_SCAN_ENABLE) \ + ) + +#define IS_DDL_ADC_SEQ_SCAN_MODE(__SEQ_SCAN_MODE__) \ + ( ((__SCAN_MODE__) == DDL_ADC_SEQ_SCAN_DISABLE) \ + || ((__SCAN_MODE__) == DDL_ADC_SEQ_SCAN_ENABLE) \ + ) + +/* Check of parameters for configuration of ADC hierarchical scope: */ +/* ADC group regular */ +#define IS_DDL_ADC_REG_TRIG_SOURCE(__REG_TRIG_SOURCE__) \ + ( ((__REG_TRIG_SOURCE__) == DDL_ADC_REG_TRIG_SOFTWARE) \ + || ((__REG_TRIG_SOURCE__) == DDL_ADC_REG_TRIG_EXT_TMR1_CH1) \ + || ((__REG_TRIG_SOURCE__) == DDL_ADC_REG_TRIG_EXT_TMR1_CH2) \ + || ((__REG_TRIG_SOURCE__) == DDL_ADC_REG_TRIG_EXT_TMR1_CH3) \ + || ((__REG_TRIG_SOURCE__) == DDL_ADC_REG_TRIG_EXT_TMR2_CH2) \ + || ((__REG_TRIG_SOURCE__) == DDL_ADC_REG_TRIG_EXT_TMR2_CH3) \ + || ((__REG_TRIG_SOURCE__) == DDL_ADC_REG_TRIG_EXT_TMR2_CH4) \ + || ((__REG_TRIG_SOURCE__) == DDL_ADC_REG_TRIG_EXT_TMR2_TRGO) \ + || ((__REG_TRIG_SOURCE__) == DDL_ADC_REG_TRIG_EXT_TMR3_CH1) \ + || ((__REG_TRIG_SOURCE__) == DDL_ADC_REG_TRIG_EXT_TMR3_TRGO) \ + || ((__REG_TRIG_SOURCE__) == DDL_ADC_REG_TRIG_EXT_TMR4_CH4) \ + || ((__REG_TRIG_SOURCE__) == DDL_ADC_REG_TRIG_EXT_TMR5_CH1) \ + || ((__REG_TRIG_SOURCE__) == DDL_ADC_REG_TRIG_EXT_TMR5_CH2) \ + || ((__REG_TRIG_SOURCE__) == DDL_ADC_REG_TRIG_EXT_TMR5_CH3) \ + || ((__REG_TRIG_SOURCE__) == DDL_ADC_REG_TRIG_EXT_TMR8_CH1) \ + || ((__REG_TRIG_SOURCE__) == DDL_ADC_REG_TRIG_EXT_TMR8_TRGO) \ + || ((__REG_TRIG_SOURCE__) == DDL_ADC_REG_TRIG_EXT_EINT_LINE11) \ + ) +#define IS_DDL_ADC_REG_CONTINUOUS_MODE(__REG_CONTINUOUS_MODE__) \ + ( ((__REG_CONTINUOUS_MODE__) == DDL_ADC_REG_CONV_SINGLE) \ + || ((__REG_CONTINUOUS_MODE__) == DDL_ADC_REG_CONV_CONTINUOUS) \ + ) + +#define IS_DDL_ADC_REG_DMA_TRANSFER(__REG_DMA_TRANSFER__) \ + ( ((__REG_DMA_TRANSFER__) == DDL_ADC_REG_DMA_TRANSFER_NONE) \ + || ((__REG_DMA_TRANSFER__) == DDL_ADC_REG_DMA_TRANSFER_LIMITED) \ + || ((__REG_DMA_TRANSFER__) == DDL_ADC_REG_DMA_TRANSFER_UNLIMITED) \ + ) + +#define IS_DDL_ADC_REG_FLAG_EOC_SELECTION(__REG_FLAG_EOC_SELECTION__) \ + ( ((__REG_FLAG_EOC_SELECTION__) == DDL_ADC_REG_FLAG_EOC_SEQUENCE_CONV) \ + || ((__REG_FLAG_EOC_SELECTION__) == DDL_ADC_REG_FLAG_EOC_UNITARY_CONV) \ + ) + +#define IS_DDL_ADC_REG_SEQ_SCAN_LENGTH(__REG_SEQ_SCAN_LENGTH__) \ + ( ((__REG_SEQ_SCAN_LENGTH__) == DDL_ADC_REG_SEQ_SCAN_DISABLE) \ + || ((__REG_SEQ_SCAN_LENGTH__) == DDL_ADC_REG_SEQ_SCAN_ENABLE_2RANKS) \ + || ((__REG_SEQ_SCAN_LENGTH__) == DDL_ADC_REG_SEQ_SCAN_ENABLE_3RANKS) \ + || ((__REG_SEQ_SCAN_LENGTH__) == DDL_ADC_REG_SEQ_SCAN_ENABLE_4RANKS) \ + || ((__REG_SEQ_SCAN_LENGTH__) == DDL_ADC_REG_SEQ_SCAN_ENABLE_5RANKS) \ + || ((__REG_SEQ_SCAN_LENGTH__) == DDL_ADC_REG_SEQ_SCAN_ENABLE_6RANKS) \ + || ((__REG_SEQ_SCAN_LENGTH__) == DDL_ADC_REG_SEQ_SCAN_ENABLE_7RANKS) \ + || ((__REG_SEQ_SCAN_LENGTH__) == DDL_ADC_REG_SEQ_SCAN_ENABLE_8RANKS) \ + || ((__REG_SEQ_SCAN_LENGTH__) == DDL_ADC_REG_SEQ_SCAN_ENABLE_9RANKS) \ + || ((__REG_SEQ_SCAN_LENGTH__) == DDL_ADC_REG_SEQ_SCAN_ENABLE_10RANKS) \ + || ((__REG_SEQ_SCAN_LENGTH__) == DDL_ADC_REG_SEQ_SCAN_ENABLE_11RANKS) \ + || ((__REG_SEQ_SCAN_LENGTH__) == DDL_ADC_REG_SEQ_SCAN_ENABLE_12RANKS) \ + || ((__REG_SEQ_SCAN_LENGTH__) == DDL_ADC_REG_SEQ_SCAN_ENABLE_13RANKS) \ + || ((__REG_SEQ_SCAN_LENGTH__) == DDL_ADC_REG_SEQ_SCAN_ENABLE_14RANKS) \ + || ((__REG_SEQ_SCAN_LENGTH__) == DDL_ADC_REG_SEQ_SCAN_ENABLE_15RANKS) \ + || ((__REG_SEQ_SCAN_LENGTH__) == DDL_ADC_REG_SEQ_SCAN_ENABLE_16RANKS) \ + ) + +#define IS_DDL_ADC_REG_SEQ_SCAN_DISCONT_MODE(__REG_SEQ_DISCONT_MODE__) \ + ( ((__REG_SEQ_DISCONT_MODE__) == DDL_ADC_REG_SEQ_DISCONT_DISABLE) \ + || ((__REG_SEQ_DISCONT_MODE__) == DDL_ADC_REG_SEQ_DISCONT_1RANK) \ + || ((__REG_SEQ_DISCONT_MODE__) == DDL_ADC_REG_SEQ_DISCONT_2RANKS) \ + || ((__REG_SEQ_DISCONT_MODE__) == DDL_ADC_REG_SEQ_DISCONT_3RANKS) \ + || ((__REG_SEQ_DISCONT_MODE__) == DDL_ADC_REG_SEQ_DISCONT_4RANKS) \ + || ((__REG_SEQ_DISCONT_MODE__) == DDL_ADC_REG_SEQ_DISCONT_5RANKS) \ + || ((__REG_SEQ_DISCONT_MODE__) == DDL_ADC_REG_SEQ_DISCONT_6RANKS) \ + || ((__REG_SEQ_DISCONT_MODE__) == DDL_ADC_REG_SEQ_DISCONT_7RANKS) \ + || ((__REG_SEQ_DISCONT_MODE__) == DDL_ADC_REG_SEQ_DISCONT_8RANKS) \ + ) + +/* Check of parameters for configuration of ADC hierarchical scope: */ +/* ADC group injected */ +#define IS_DDL_ADC_INJ_TRIG_SOURCE(__INJ_TRIG_SOURCE__) \ + ( ((__INJ_TRIG_SOURCE__) == DDL_ADC_INJ_TRIG_SOFTWARE) \ + || ((__INJ_TRIG_SOURCE__) == DDL_ADC_INJ_TRIG_EXT_TMR1_CH4) \ + || ((__INJ_TRIG_SOURCE__) == DDL_ADC_INJ_TRIG_EXT_TMR1_TRGO) \ + || ((__INJ_TRIG_SOURCE__) == DDL_ADC_INJ_TRIG_EXT_TMR2_CH1) \ + || ((__INJ_TRIG_SOURCE__) == DDL_ADC_INJ_TRIG_EXT_TMR2_TRGO) \ + || ((__INJ_TRIG_SOURCE__) == DDL_ADC_INJ_TRIG_EXT_TMR3_CH2) \ + || ((__INJ_TRIG_SOURCE__) == DDL_ADC_INJ_TRIG_EXT_TMR3_CH4) \ + || ((__INJ_TRIG_SOURCE__) == DDL_ADC_INJ_TRIG_EXT_TMR4_CH1) \ + || ((__INJ_TRIG_SOURCE__) == DDL_ADC_INJ_TRIG_EXT_TMR4_CH2) \ + || ((__INJ_TRIG_SOURCE__) == DDL_ADC_INJ_TRIG_EXT_TMR4_CH3) \ + || ((__INJ_TRIG_SOURCE__) == DDL_ADC_INJ_TRIG_EXT_TMR4_TRGO) \ + || ((__INJ_TRIG_SOURCE__) == DDL_ADC_INJ_TRIG_EXT_TMR5_CH4) \ + || ((__INJ_TRIG_SOURCE__) == DDL_ADC_INJ_TRIG_EXT_TMR5_TRGO) \ + || ((__INJ_TRIG_SOURCE__) == DDL_ADC_INJ_TRIG_EXT_TMR8_CH2) \ + || ((__INJ_TRIG_SOURCE__) == DDL_ADC_INJ_TRIG_EXT_TMR8_CH3) \ + || ((__INJ_TRIG_SOURCE__) == DDL_ADC_INJ_TRIG_EXT_TMR8_CH4) \ + || ((__INJ_TRIG_SOURCE__) == DDL_ADC_INJ_TRIG_EXT_EXTI_LINE15) \ + ) + +#define IS_DDL_ADC_INJ_TRIG_EXT_EDGE(__INJ_TRIG_EXT_EDGE__) \ + ( ((__INJ_TRIG_EXT_EDGE__) == DDL_ADC_INJ_TRIG_EXT_RISING) \ + || ((__INJ_TRIG_EXT_EDGE__) == DDL_ADC_INJ_TRIG_EXT_FALLING) \ + || ((__INJ_TRIG_EXT_EDGE__) == DDL_ADC_INJ_TRIG_EXT_RISINGFALLING) \ + ) + +#define IS_DDL_ADC_INJ_TRIG_AUTO(__INJ_TRIG_AUTO__) \ + ( ((__INJ_TRIG_AUTO__) == DDL_ADC_INJ_TRIG_INDEPENDENT) \ + || ((__INJ_TRIG_AUTO__) == DDL_ADC_INJ_TRIG_FROM_GRP_REGULAR) \ + ) + +#define IS_DDL_ADC_INJ_SEQ_SCAN_LENGTH(__INJ_SEQ_SCAN_LENGTH__) \ + ( ((__INJ_SEQ_SCAN_LENGTH__) == DDL_ADC_INJ_SEQ_SCAN_DISABLE) \ + || ((__INJ_SEQ_SCAN_LENGTH__) == DDL_ADC_INJ_SEQ_SCAN_ENABLE_2RANKS) \ + || ((__INJ_SEQ_SCAN_LENGTH__) == DDL_ADC_INJ_SEQ_SCAN_ENABLE_3RANKS) \ + || ((__INJ_SEQ_SCAN_LENGTH__) == DDL_ADC_INJ_SEQ_SCAN_ENABLE_4RANKS) \ + ) + +#define IS_DDL_ADC_INJ_SEQ_SCAN_DISCONT_MODE(__INJ_SEQ_DISCONT_MODE__) \ + ( ((__INJ_SEQ_DISCONT_MODE__) == DDL_ADC_INJ_SEQ_DISCONT_DISABLE) \ + || ((__INJ_SEQ_DISCONT_MODE__) == DDL_ADC_INJ_SEQ_DISCONT_1RANK) \ + ) + +#if defined(ADC_MULTIMODE_SUPPORT) +/* Check of parameters for configuration of ADC hierarchical scope: */ +/* multimode. */ +#if defined(ADC3) +#define IS_DDL_ADC_MULTI_MODE(__MULTI_MODE__) \ + ( ((__MULTI_MODE__) == DDL_ADC_MULTI_INDEPENDENT) \ + || ((__MULTI_MODE__) == DDL_ADC_MULTI_DUAL_REG_SIMULT) \ + || ((__MULTI_MODE__) == DDL_ADC_MULTI_DUAL_REG_INTERL) \ + || ((__MULTI_MODE__) == DDL_ADC_MULTI_DUAL_INJ_SIMULT) \ + || ((__MULTI_MODE__) == DDL_ADC_MULTI_DUAL_INJ_ALTERN) \ + || ((__MULTI_MODE__) == DDL_ADC_MULTI_DUAL_REG_SIM_INJ_SIM) \ + || ((__MULTI_MODE__) == DDL_ADC_MULTI_DUAL_REG_SIM_INJ_ALT) \ + || ((__MULTI_MODE__) == DDL_ADC_MULTI_DUAL_REG_INT_INJ_SIM) \ + || ((__MULTI_MODE__) == DDL_ADC_MULTI_TRIPLE_REG_SIM_INJ_SIM) \ + || ((__MULTI_MODE__) == DDL_ADC_MULTI_TRIPLE_REG_SIM_INJ_ALT) \ + || ((__MULTI_MODE__) == DDL_ADC_MULTI_TRIPLE_INJ_SIMULT) \ + || ((__MULTI_MODE__) == DDL_ADC_MULTI_TRIPLE_REG_SIMULT) \ + || ((__MULTI_MODE__) == DDL_ADC_MULTI_TRIPLE_REG_INTERL) \ + || ((__MULTI_MODE__) == DDL_ADC_MULTI_TRIPLE_INJ_ALTERN) \ + ) +#else +#define IS_DDL_ADC_MULTI_MODE(__MULTI_MODE__) \ + ( ((__MULTI_MODE__) == DDL_ADC_MULTI_INDEPENDENT) \ + || ((__MULTI_MODE__) == DDL_ADC_MULTI_DUAL_REG_SIMULT) \ + || ((__MULTI_MODE__) == DDL_ADC_MULTI_DUAL_REG_INTERL) \ + || ((__MULTI_MODE__) == DDL_ADC_MULTI_DUAL_INJ_SIMULT) \ + || ((__MULTI_MODE__) == DDL_ADC_MULTI_DUAL_INJ_ALTERN) \ + || ((__MULTI_MODE__) == DDL_ADC_MULTI_DUAL_REG_SIM_INJ_SIM) \ + || ((__MULTI_MODE__) == DDL_ADC_MULTI_DUAL_REG_SIM_INJ_ALT) \ + || ((__MULTI_MODE__) == DDL_ADC_MULTI_DUAL_REG_INT_INJ_SIM) \ + ) +#endif + +#define IS_DDL_ADC_MULTI_DMA_TRANSFER(__MULTI_DMA_TRANSFER__) \ + ( ((__MULTI_DMA_TRANSFER__) == DDL_ADC_MULTI_REG_DMA_EACH_ADC) \ + || ((__MULTI_DMA_TRANSFER__) == DDL_ADC_MULTI_REG_DMA_LIMIT_1) \ + || ((__MULTI_DMA_TRANSFER__) == DDL_ADC_MULTI_REG_DMA_LIMIT_2) \ + || ((__MULTI_DMA_TRANSFER__) == DDL_ADC_MULTI_REG_DMA_LIMIT_3) \ + || ((__MULTI_DMA_TRANSFER__) == DDL_ADC_MULTI_REG_DMA_UNLMT_1) \ + || ((__MULTI_DMA_TRANSFER__) == DDL_ADC_MULTI_REG_DMA_UNLMT_2) \ + || ((__MULTI_DMA_TRANSFER__) == DDL_ADC_MULTI_REG_DMA_UNLMT_3) \ + ) + +#define IS_DDL_ADC_MULTI_TWOSMP_DELAY(__MULTI_TWOSMP_DELAY__) \ + ( ((__MULTI_TWOSMP_DELAY__) == DDL_ADC_MULTI_TWOSMP_DELAY_5CYCLES) \ + || ((__MULTI_TWOSMP_DELAY__) == DDL_ADC_MULTI_TWOSMP_DELAY_6CYCLES) \ + || ((__MULTI_TWOSMP_DELAY__) == DDL_ADC_MULTI_TWOSMP_DELAY_7CYCLES) \ + || ((__MULTI_TWOSMP_DELAY__) == DDL_ADC_MULTI_TWOSMP_DELAY_8CYCLES) \ + || ((__MULTI_TWOSMP_DELAY__) == DDL_ADC_MULTI_TWOSMP_DELAY_9CYCLES) \ + || ((__MULTI_TWOSMP_DELAY__) == DDL_ADC_MULTI_TWOSMP_DELAY_10CYCLES) \ + || ((__MULTI_TWOSMP_DELAY__) == DDL_ADC_MULTI_TWOSMP_DELAY_11CYCLES) \ + || ((__MULTI_TWOSMP_DELAY__) == DDL_ADC_MULTI_TWOSMP_DELAY_12CYCLES) \ + || ((__MULTI_TWOSMP_DELAY__) == DDL_ADC_MULTI_TWOSMP_DELAY_13CYCLES) \ + || ((__MULTI_TWOSMP_DELAY__) == DDL_ADC_MULTI_TWOSMP_DELAY_14CYCLES) \ + || ((__MULTI_TWOSMP_DELAY__) == DDL_ADC_MULTI_TWOSMP_DELAY_15CYCLES) \ + || ((__MULTI_TWOSMP_DELAY__) == DDL_ADC_MULTI_TWOSMP_DELAY_16CYCLES) \ + || ((__MULTI_TWOSMP_DELAY__) == DDL_ADC_MULTI_TWOSMP_DELAY_17CYCLES) \ + || ((__MULTI_TWOSMP_DELAY__) == DDL_ADC_MULTI_TWOSMP_DELAY_18CYCLES) \ + || ((__MULTI_TWOSMP_DELAY__) == DDL_ADC_MULTI_TWOSMP_DELAY_19CYCLES) \ + || ((__MULTI_TWOSMP_DELAY__) == DDL_ADC_MULTI_TWOSMP_DELAY_20CYCLES) \ + ) + +#define IS_DDL_ADC_MULTI_MASTER_SLAVE(__MULTI_MASTER_SLAVE__) \ + ( ((__MULTI_MASTER_SLAVE__) == DDL_ADC_MULTI_MASTER) \ + || ((__MULTI_MASTER_SLAVE__) == DDL_ADC_MULTI_SLAVE) \ + || ((__MULTI_MASTER_SLAVE__) == DDL_ADC_MULTI_MASTER_SLAVE) \ + ) + +#endif /* ADC_MULTIMODE_SUPPORT */ +/** + * @} + */ + + +/* Private function prototypes -----------------------------------------------*/ + +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup ADC_DDL_Exported_Functions + * @{ + */ + +/** @addtogroup ADC_DDL_EF_Init + * @{ + */ + +/** + * @brief De-initialize registers of all ADC instances belonging to + * the same ADC common instance to their default reset values. + * @param ADCxy_COMMON ADC common instance + * (can be set directly from CMSIS definition or by using helper macro @ref __DDL_ADC_COMMON_INSTANCE() ) + * @retval An ErrorStatus enumeration value: + * - SUCCESS: ADC common registers are de-initialized + * - ERROR: not applicable + */ +ErrorStatus DDL_ADC_CommonDeInit(ADC_Common_TypeDef *ADCxy_COMMON) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_ADC_COMMON_INSTANCE(ADCxy_COMMON)); + + + /* Force reset of ADC clock (core clock) */ + DDL_APB2_GRP1_ForceReset(DDL_APB2_GRP1_PERIPH_ADC); + + /* Release reset of ADC clock (core clock) */ + DDL_APB2_GRP1_ReleaseReset(DDL_APB2_GRP1_PERIPH_ADC); + + return SUCCESS; +} + +/** + * @brief Initialize some features of ADC common parameters + * (all ADC instances belonging to the same ADC common instance) + * and multimode (for devices with several ADC instances available). + * @note The setting of ADC common parameters is conditioned to + * ADC instances state: + * All ADC instances belonging to the same ADC common instance + * must be disabled. + * @param ADCxy_COMMON ADC common instance + * (can be set directly from CMSIS definition or by using helper macro @ref __DDL_ADC_COMMON_INSTANCE() ) + * @param ADC_CommonInitStruct Pointer to a @ref DDL_ADC_CommonInitTypeDef structure + * @retval An ErrorStatus enumeration value: + * - SUCCESS: ADC common registers are initialized + * - ERROR: ADC common registers are not initialized + */ +ErrorStatus DDL_ADC_CommonInit(ADC_Common_TypeDef *ADCxy_COMMON, DDL_ADC_CommonInitTypeDef *ADC_CommonInitStruct) +{ + ErrorStatus status = SUCCESS; + + /* Check the parameters */ + ASSERT_PARAM(IS_ADC_COMMON_INSTANCE(ADCxy_COMMON)); + ASSERT_PARAM(IS_DDL_ADC_COMMON_CLOCK(ADC_CommonInitStruct->CommonClock)); + +#if defined(ADC_MULTIMODE_SUPPORT) + ASSERT_PARAM(IS_DDL_ADC_MULTI_MODE(ADC_CommonInitStruct->Multimode)); + if(ADC_CommonInitStruct->Multimode != DDL_ADC_MULTI_INDEPENDENT) + { + ASSERT_PARAM(IS_DDL_ADC_MULTI_DMA_TRANSFER(ADC_CommonInitStruct->MultiDMATransfer)); + ASSERT_PARAM(IS_DDL_ADC_MULTI_TWOSMP_DELAY(ADC_CommonInitStruct->MultiTwoSamplingDelay)); + } +#endif /* ADC_MULTIMODE_SUPPORT */ + + /* Note: Hardware constraint (refer to description of functions */ + /* "DDL_ADC_SetCommonXXX()" and "DDL_ADC_SetMultiXXX()"): */ + /* On this APM32 series, setting of these features is conditioned to */ + /* ADC state: */ + /* All ADC instances of the ADC common group must be disabled. */ + if(__DDL_ADC_IS_ENABLED_ALL_COMMON_INSTANCE(ADCxy_COMMON) == 0UL) + { + /* Configuration of ADC hierarchical scope: */ + /* - common to several ADC */ + /* (all ADC instances belonging to the same ADC common instance) */ + /* - Set ADC clock (conversion clock) */ + /* - multimode (if several ADC instances available on the */ + /* selected device) */ + /* - Set ADC multimode configuration */ + /* - Set ADC multimode DMA transfer */ + /* - Set ADC multimode: delay between 2 sampling phases */ +#if defined(ADC_MULTIMODE_SUPPORT) + if(ADC_CommonInitStruct->Multimode != DDL_ADC_MULTI_INDEPENDENT) + { + MODIFY_REG(ADCxy_COMMON->CCTRL, + ADC_CCTRL_ADCPRE + | ADC_CCTRL_ADCMSEL + | ADC_CCTRL_DMAMODE + | ADC_CCTRL_DMAMODEDISSEL + | ADC_CCTRL_SMPDEL2 + , + ADC_CommonInitStruct->CommonClock + | ADC_CommonInitStruct->Multimode + | ADC_CommonInitStruct->MultiDMATransfer + | ADC_CommonInitStruct->MultiTwoSamplingDelay + ); + } + else + { + MODIFY_REG(ADCxy_COMMON->CCTRL, + ADC_CCTRL_ADCPRE + | ADC_CCTRL_ADCMSEL + | ADC_CCTRL_DMAMODE + | ADC_CCTRL_DMAMODEDISSEL + | ADC_CCTRL_SMPDEL2 + , + ADC_CommonInitStruct->CommonClock + | DDL_ADC_MULTI_INDEPENDENT + ); + } +#else + DDL_ADC_SetCommonClock(ADCxy_COMMON, ADC_CommonInitStruct->CommonClock); +#endif + } + else + { + /* Initialization error: One or several ADC instances belonging to */ + /* the same ADC common instance are not disabled. */ + status = ERROR; + } + + return status; +} + +/** + * @brief Set each @ref DDL_ADC_CommonInitTypeDef field to default value. + * @param ADC_CommonInitStruct Pointer to a @ref DDL_ADC_CommonInitTypeDef structure + * whose fields will be set to default values. + * @retval None + */ +void DDL_ADC_CommonStructInit(DDL_ADC_CommonInitTypeDef *ADC_CommonInitStruct) +{ + /* Set ADC_CommonInitStruct fields to default values */ + /* Set fields of ADC common */ + /* (all ADC instances belonging to the same ADC common instance) */ + ADC_CommonInitStruct->CommonClock = DDL_ADC_CLOCK_SYNC_PCLK_DIV2; + +#if defined(ADC_MULTIMODE_SUPPORT) + /* Set fields of ADC multimode */ + ADC_CommonInitStruct->Multimode = DDL_ADC_MULTI_INDEPENDENT; + ADC_CommonInitStruct->MultiDMATransfer = DDL_ADC_MULTI_REG_DMA_EACH_ADC; + ADC_CommonInitStruct->MultiTwoSamplingDelay = DDL_ADC_MULTI_TWOSMP_DELAY_5CYCLES; +#endif /* ADC_MULTIMODE_SUPPORT */ +} + +/** + * @brief De-initialize registers of the selected ADC instance + * to their default reset values. + * @note To reset all ADC instances quickly (perform a hard reset), + * use function @ref DDL_ADC_CommonDeInit(). + * @param ADCx ADC instance + * @retval An ErrorStatus enumeration value: + * - SUCCESS: ADC registers are de-initialized + * - ERROR: ADC registers are not de-initialized + */ +ErrorStatus DDL_ADC_DeInit(ADC_TypeDef *ADCx) +{ + ErrorStatus status = SUCCESS; + + /* Check the parameters */ + ASSERT_PARAM(IS_ADC_ALL_INSTANCE(ADCx)); + + /* Disable ADC instance if not already disabled. */ + if(DDL_ADC_IsEnabled(ADCx) == 1UL) + { + /* Set ADC group regular trigger source to SW start to ensure to not */ + /* have an external trigger event occurring during the conversion stop */ + /* ADC disable process. */ + DDL_ADC_REG_SetTriggerSource(ADCx, DDL_ADC_REG_TRIG_SOFTWARE); + + /* Set ADC group injected trigger source to SW start to ensure to not */ + /* have an external trigger event occurring during the conversion stop */ + /* ADC disable process. */ + DDL_ADC_INJ_SetTriggerSource(ADCx, DDL_ADC_INJ_TRIG_SOFTWARE); + + /* Disable the ADC instance */ + DDL_ADC_Disable(ADCx); + } + + /* Check whether ADC state is compliant with expected state */ + /* (hardware requirements of bits state to reset registers below) */ + if(READ_BIT(ADCx->CTRL2, ADC_CTRL2_ADCEN) == 0UL) + { + /* ========== Reset ADC registers ========== */ + /* Reset register STS */ + CLEAR_BIT(ADCx->STS, + ( DDL_ADC_FLAG_STRT + | DDL_ADC_FLAG_JSTRT + | DDL_ADC_FLAG_EOCS + | DDL_ADC_FLAG_OVR + | DDL_ADC_FLAG_JEOS + | DDL_ADC_FLAG_AWD1 ) + ); + + /* Reset register CTRL1 */ + CLEAR_BIT(ADCx->CTRL1, + ( ADC_CTRL1_OVRIEN | ADC_CTRL1_RESSEL | ADC_CTRL1_REGAWDEN + | ADC_CTRL1_INJAWDEN + | ADC_CTRL1_DISCNUMCFG | ADC_CTRL1_INJDISCEN | ADC_CTRL1_REGDISCEN + | ADC_CTRL1_INJGACEN | ADC_CTRL1_AWDSGLEN | ADC_CTRL1_SCANEN + | ADC_CTRL1_INJEOCIEN | ADC_CTRL1_AWDIEN | ADC_CTRL1_EOCIEN + | ADC_CTRL1_AWDCHSEL ) + ); + + /* Reset register CTRL2 */ + CLEAR_BIT(ADCx->CTRL2, + ( ADC_CTRL2_REGCHSC | ADC_CTRL2_REGEXTTRGEN | ADC_CTRL2_REGEXTTRGSEL + | ADC_CTRL2_INJSWSC | ADC_CTRL2_INJEXTTRGEN | ADC_CTRL2_INJGEXTTRGSEL + | ADC_CTRL2_DALIGNCFG | ADC_CTRL2_EOCSEL + | ADC_CTRL2_DMADISSEL | ADC_CTRL2_DMAEN + | ADC_CTRL2_CONTCEN | ADC_CTRL2_ADCEN ) + ); + + /* Reset register SMPTIM1 */ + CLEAR_BIT(ADCx->SMPTIM1, + ( ADC_SMPTIM1_SMPCYCCFG18 | ADC_SMPTIM1_SMPCYCCFG17 | ADC_SMPTIM1_SMPCYCCFG16 + | ADC_SMPTIM1_SMPCYCCFG15 | ADC_SMPTIM1_SMPCYCCFG14 | ADC_SMPTIM1_SMPCYCCFG13 + | ADC_SMPTIM1_SMPCYCCFG12 | ADC_SMPTIM1_SMPCYCCFG11 | ADC_SMPTIM1_SMPCYCCFG10) + ); + + /* Reset register SMPTIM2 */ + CLEAR_BIT(ADCx->SMPTIM2, + ( ADC_SMPTIM2_SMPCYCCFG9 + | ADC_SMPTIM2_SMPCYCCFG8 | ADC_SMPTIM2_SMPCYCCFG7 | ADC_SMPTIM2_SMPCYCCFG6 + | ADC_SMPTIM2_SMPCYCCFG5 | ADC_SMPTIM2_SMPCYCCFG4 | ADC_SMPTIM2_SMPCYCCFG3 + | ADC_SMPTIM2_SMPCYCCFG2 | ADC_SMPTIM2_SMPCYCCFG1 | ADC_SMPTIM2_SMPCYCCFG0) + ); + + /* Reset register INJDOF1 */ + CLEAR_BIT(ADCx->INJDOF1, ADC_INJDOF1_INJDOF1); + /* Reset register INJDOF2 */ + CLEAR_BIT(ADCx->INJDOF2, ADC_INJDOF2_INJDOF2); + /* Reset register INJDOF3 */ + CLEAR_BIT(ADCx->INJDOF3, ADC_INJDOF3_INJDOF3); + /* Reset register INJDOF4 */ + CLEAR_BIT(ADCx->INJDOF4, ADC_INJDOF4_INJDOF4); + + /* Reset register AWDHT */ + SET_BIT(ADCx->AWDHT, ADC_AWDHT_AWDHT); + /* Reset register AWDLT */ + CLEAR_BIT(ADCx->AWDLT, ADC_AWDLT_AWDLT); + + /* Reset register REGSEQ1 */ + CLEAR_BIT(ADCx->REGSEQ1, + ( ADC_REGSEQ1_REGSEQLEN + | ADC_REGSEQ1_REGSEQC16 + | ADC_REGSEQ1_REGSEQC15 | ADC_REGSEQ1_REGSEQC14 | ADC_REGSEQ1_REGSEQC13) + ); + + /* Reset register REGSEQ2 */ + CLEAR_BIT(ADCx->REGSEQ2, + ( ADC_REGSEQ2_REGSEQC12 | ADC_REGSEQ2_REGSEQC11 | ADC_REGSEQ2_REGSEQC10 + | ADC_REGSEQ2_REGSEQC9 | ADC_REGSEQ2_REGSEQC8 | ADC_REGSEQ2_REGSEQC7) + ); + + /* Reset register REGSEQ3 */ + CLEAR_BIT(ADCx->REGSEQ3, + ( ADC_REGSEQ3_REGSEQC6 | ADC_REGSEQ3_REGSEQC5 | ADC_REGSEQ3_REGSEQC4 + | ADC_REGSEQ3_REGSEQC3 | ADC_REGSEQ3_REGSEQC2 | ADC_REGSEQ3_REGSEQC1) + ); + + /* Reset register INJSEQ */ + CLEAR_BIT(ADCx->INJSEQ, + ( ADC_INJSEQ_INJSEQLEN + | ADC_INJSEQ_INJSEQC4 | ADC_INJSEQ_INJSEQC3 + | ADC_INJSEQ_INJSEQC2 | ADC_INJSEQ_INJSEQC1 ) + ); + + /* Reset register REGDATA */ + /* bits in access mode read only, no direct reset applicable */ + + /* Reset registers INJDATA1, INJDATA2, INJDATA3, INJDATA4 */ + /* bits in access mode read only, no direct reset applicable */ + + /* Reset register CCTRL */ +#if defined(ADC1) && defined(ADC2) && defined(ADC3) + CLEAR_BIT(ADC->CCTRL, ADC_CCTRL_TSVREFEN | ADC_CCTRL_ADCPRE); +#else + CLEAR_BIT(ADC1_C->CCTRL, ADC_CCTRL_TSVREFEN | ADC_CCTRL_ADCPRE); + CLEAR_BIT(ADC2_C->CCTRL, ADC_CCTRL_TSVREFEN | ADC_CCTRL_ADCPRE); +#endif /* ADC2 || ADC3 */ + } + + return status; +} + +/** + * @brief Initialize some features of ADC instance. + * @note These parameters have an impact on ADC scope: ADC instance. + * Affects both group regular and group injected (availability + * of ADC group injected depends on APM32 families). + * Refer to corresponding unitary functions into + * @ref ADC_DDL_EF_Configuration_ADC_Instance . + * @note The setting of these parameters by function @ref DDL_ADC_Init() + * is conditioned to ADC state: + * ADC instance must be disabled. + * This condition is applied to all ADC features, for efficiency + * and compatibility over all APM32 families. However, the different + * features can be set under different ADC state conditions + * (setting possible with ADC enabled without conversion on going, + * ADC enabled with conversion on going, ...) + * Each feature can be updated afterwards with a unitary function + * and potentially with ADC in a different state than disabled, + * refer to description of each function for setting + * conditioned to ADC state. + * @note After using this function, some other features must be configured + * using LL unitary functions. + * The minimum configuration remaining to be done is: + * - Set ADC group regular or group injected sequencer: + * map channel on the selected sequencer rank. + * Refer to function @ref DDL_ADC_REG_SetSequencerRanks(). + * - Set ADC channel sampling time + * Refer to function DDL_ADC_SetChannelSamplingTime(); + * @param ADCx ADC instance + * @param ADC_InitStruct Pointer to a @ref DDL_ADC_REG_InitTypeDef structure + * @retval An ErrorStatus enumeration value: + * - SUCCESS: ADC registers are initialized + * - ERROR: ADC registers are not initialized + */ +ErrorStatus DDL_ADC_Init(ADC_TypeDef *ADCx, DDL_ADC_InitTypeDef *ADC_InitStruct) +{ + ErrorStatus status = SUCCESS; + + /* Check the parameters */ + ASSERT_PARAM(IS_ADC_ALL_INSTANCE(ADCx)); + + ASSERT_PARAM(IS_DDL_ADC_RESOLUTION(ADC_InitStruct->Resolution)); + ASSERT_PARAM(IS_DDL_ADC_DATA_ALIGN(ADC_InitStruct->DataAlignment)); + ASSERT_PARAM(IS_DDL_ADC_SCAN_SELECTION(ADC_InitStruct->SequencersScanMode)); + + /* Note: Hardware constraint (refer to description of this function): */ + /* ADC instance must be disabled. */ + if(DDL_ADC_IsEnabled(ADCx) == 0UL) + { + /* Configuration of ADC hierarchical scope: */ + /* - ADC instance */ + /* - Set ADC data resolution */ + /* - Set ADC conversion data alignment */ + MODIFY_REG(ADCx->CTRL1, + ADC_CTRL1_RESSEL + | ADC_CTRL1_SCANEN + , + ADC_InitStruct->Resolution + | ADC_InitStruct->SequencersScanMode + ); + + MODIFY_REG(ADCx->CTRL2, + ADC_CTRL2_DALIGNCFG + , + ADC_InitStruct->DataAlignment + ); + + } + else + { + /* Initialization error: ADC instance is not disabled. */ + status = ERROR; + } + return status; +} + +/** + * @brief Set each @ref DDL_ADC_InitTypeDef field to default value. + * @param ADC_InitStruct Pointer to a @ref DDL_ADC_InitTypeDef structure + * whose fields will be set to default values. + * @retval None + */ +void DDL_ADC_StructInit(DDL_ADC_InitTypeDef *ADC_InitStruct) +{ + /* Set ADC_InitStruct fields to default values */ + /* Set fields of ADC instance */ + ADC_InitStruct->Resolution = DDL_ADC_RESOLUTION_12B; + ADC_InitStruct->DataAlignment = DDL_ADC_DATA_ALIGN_RIGHT; + + /* Enable scan mode to have a generic behavior with ADC of other */ + /* APM32 families, without this setting available: */ + /* ADC group regular sequencer and ADC group injected sequencer depend */ + /* only of their own configuration. */ + ADC_InitStruct->SequencersScanMode = DDL_ADC_SEQ_SCAN_ENABLE; + +} + +/** + * @brief Initialize some features of ADC group regular. + * @note These parameters have an impact on ADC scope: ADC group regular. + * Refer to corresponding unitary functions into + * @ref ADC_DDL_EF_Configuration_ADC_Group_Regular + * (functions with prefix "REG"). + * @note The setting of these parameters by function @ref DDL_ADC_Init() + * is conditioned to ADC state: + * ADC instance must be disabled. + * This condition is applied to all ADC features, for efficiency + * and compatibility over all APM32 families. However, the different + * features can be set under different ADC state conditions + * (setting possible with ADC enabled without conversion on going, + * ADC enabled with conversion on going, ...) + * Each feature can be updated afterwards with a unitary function + * and potentially with ADC in a different state than disabled, + * refer to description of each function for setting + * conditioned to ADC state. + * @note After using this function, other features must be configured + * using LL unitary functions. + * The minimum configuration remaining to be done is: + * - Set ADC group regular or group injected sequencer: + * map channel on the selected sequencer rank. + * Refer to function @ref DDL_ADC_REG_SetSequencerRanks(). + * - Set ADC channel sampling time + * Refer to function DDL_ADC_SetChannelSamplingTime(); + * @param ADCx ADC instance + * @param ADC_REG_InitStruct Pointer to a @ref DDL_ADC_REG_InitTypeDef structure + * @retval An ErrorStatus enumeration value: + * - SUCCESS: ADC registers are initialized + * - ERROR: ADC registers are not initialized + */ +ErrorStatus DDL_ADC_REG_Init(ADC_TypeDef *ADCx, DDL_ADC_REG_InitTypeDef *ADC_REG_InitStruct) +{ + ErrorStatus status = SUCCESS; + + /* Check the parameters */ + ASSERT_PARAM(IS_ADC_ALL_INSTANCE(ADCx)); + ASSERT_PARAM(IS_DDL_ADC_REG_TRIG_SOURCE(ADC_REG_InitStruct->TriggerSource)); + ASSERT_PARAM(IS_DDL_ADC_REG_SEQ_SCAN_LENGTH(ADC_REG_InitStruct->SequencerLength)); + if(ADC_REG_InitStruct->SequencerLength != DDL_ADC_REG_SEQ_SCAN_DISABLE) + { + ASSERT_PARAM(IS_DDL_ADC_REG_SEQ_SCAN_DISCONT_MODE(ADC_REG_InitStruct->SequencerDiscont)); + } + ASSERT_PARAM(IS_DDL_ADC_REG_CONTINUOUS_MODE(ADC_REG_InitStruct->ContinuousMode)); + ASSERT_PARAM(IS_DDL_ADC_REG_DMA_TRANSFER(ADC_REG_InitStruct->DMATransfer)); + + /* ADC group regular continuous mode and discontinuous mode */ + /* can not be enabled simultenaeously */ + ASSERT_PARAM((ADC_REG_InitStruct->ContinuousMode == DDL_ADC_REG_CONV_SINGLE) + || (ADC_REG_InitStruct->SequencerDiscont == DDL_ADC_REG_SEQ_DISCONT_DISABLE)); + + /* Note: Hardware constraint (refer to description of this function): */ + /* ADC instance must be disabled. */ + if(DDL_ADC_IsEnabled(ADCx) == 0UL) + { + /* Configuration of ADC hierarchical scope: */ + /* - ADC group regular */ + /* - Set ADC group regular trigger source */ + /* - Set ADC group regular sequencer length */ + /* - Set ADC group regular sequencer discontinuous mode */ + /* - Set ADC group regular continuous mode */ + /* - Set ADC group regular conversion data transfer: no transfer or */ + /* transfer by DMA, and DMA requests mode */ + /* Note: On this APM32 series, ADC trigger edge is set when starting */ + /* ADC conversion. */ + /* Refer to function @ref DDL_ADC_REG_StartConversionExtTrig(). */ + if(ADC_REG_InitStruct->SequencerLength != DDL_ADC_REG_SEQ_SCAN_DISABLE) + { + MODIFY_REG(ADCx->CTRL1, + ADC_CTRL1_REGDISCEN + | ADC_CTRL1_DISCNUMCFG + , + ADC_REG_InitStruct->SequencerDiscont + ); + } + else + { + MODIFY_REG(ADCx->CTRL1, + ADC_CTRL1_REGDISCEN + | ADC_CTRL1_DISCNUMCFG + , + DDL_ADC_REG_SEQ_DISCONT_DISABLE + ); + } + + MODIFY_REG(ADCx->CTRL2, + ADC_CTRL2_REGEXTTRGSEL + | ADC_CTRL2_REGEXTTRGEN + | ADC_CTRL2_CONTCEN + | ADC_CTRL2_DMAEN + | ADC_CTRL2_DMADISSEL + , + (ADC_REG_InitStruct->TriggerSource & ADC_CTRL2_REGEXTTRGSEL) + | ADC_REG_InitStruct->ContinuousMode + | ADC_REG_InitStruct->DMATransfer + ); + + /* Set ADC group regular sequencer length and scan direction */ + /* Note: Hardware constraint (refer to description of this function): */ + /* Note: If ADC instance feature scan mode is disabled */ + /* (refer to ADC instance initialization structure */ + /* parameter @ref SequencersScanMode */ + /* or function @ref DDL_ADC_SetSequencersScanMode() ), */ + /* this parameter is discarded. */ + DDL_ADC_REG_SetSequencerLength(ADCx, ADC_REG_InitStruct->SequencerLength); + } + else + { + /* Initialization error: ADC instance is not disabled. */ + status = ERROR; + } + return status; +} + +/** + * @brief Set each @ref DDL_ADC_REG_InitTypeDef field to default value. + * @param ADC_REG_InitStruct Pointer to a @ref DDL_ADC_REG_InitTypeDef structure + * whose fields will be set to default values. + * @retval None + */ +void DDL_ADC_REG_StructInit(DDL_ADC_REG_InitTypeDef *ADC_REG_InitStruct) +{ + /* Set ADC_REG_InitStruct fields to default values */ + /* Set fields of ADC group regular */ + /* Note: On this APM32 series, ADC trigger edge is set when starting */ + /* ADC conversion. */ + /* Refer to function @ref DDL_ADC_REG_StartConversionExtTrig(). */ + ADC_REG_InitStruct->TriggerSource = DDL_ADC_REG_TRIG_SOFTWARE; + ADC_REG_InitStruct->SequencerLength = DDL_ADC_REG_SEQ_SCAN_DISABLE; + ADC_REG_InitStruct->SequencerDiscont = DDL_ADC_REG_SEQ_DISCONT_DISABLE; + ADC_REG_InitStruct->ContinuousMode = DDL_ADC_REG_CONV_SINGLE; + ADC_REG_InitStruct->DMATransfer = DDL_ADC_REG_DMA_TRANSFER_NONE; +} + +/** + * @brief Initialize some features of ADC group injected. + * @note These parameters have an impact on ADC scope: ADC group injected. + * Refer to corresponding unitary functions into + * @ref ADC_DDL_EF_Configuration_ADC_Group_Regular + * (functions with prefix "INJ"). + * @note The setting of these parameters by function @ref DDL_ADC_Init() + * is conditioned to ADC state: + * ADC instance must be disabled. + * This condition is applied to all ADC features, for efficiency + * and compatibility over all APM32 families. However, the different + * features can be set under different ADC state conditions + * (setting possible with ADC enabled without conversion on going, + * ADC enabled with conversion on going, ...) + * Each feature can be updated afterwards with a unitary function + * and potentially with ADC in a different state than disabled, + * refer to description of each function for setting + * conditioned to ADC state. + * @note After using this function, other features must be configured + * using LL unitary functions. + * The minimum configuration remaining to be done is: + * - Set ADC group injected sequencer: + * map channel on the selected sequencer rank. + * Refer to function @ref DDL_ADC_INJ_SetSequencerRanks(). + * - Set ADC channel sampling time + * Refer to function DDL_ADC_SetChannelSamplingTime(); + * @param ADCx ADC instance + * @param ADC_INJ_InitStruct Pointer to a @ref DDL_ADC_INJ_InitTypeDef structure + * @retval An ErrorStatus enumeration value: + * - SUCCESS: ADC registers are initialized + * - ERROR: ADC registers are not initialized + */ +ErrorStatus DDL_ADC_INJ_Init(ADC_TypeDef *ADCx, DDL_ADC_INJ_InitTypeDef *ADC_INJ_InitStruct) +{ + ErrorStatus status = SUCCESS; + + /* Check the parameters */ + ASSERT_PARAM(IS_ADC_ALL_INSTANCE(ADCx)); + ASSERT_PARAM(IS_DDL_ADC_INJ_TRIG_SOURCE(ADC_INJ_InitStruct->TriggerSource)); + ASSERT_PARAM(IS_DDL_ADC_INJ_SEQ_SCAN_LENGTH(ADC_INJ_InitStruct->SequencerLength)); + if(ADC_INJ_InitStruct->SequencerLength != DDL_ADC_INJ_SEQ_SCAN_DISABLE) + { + ASSERT_PARAM(IS_DDL_ADC_INJ_SEQ_SCAN_DISCONT_MODE(ADC_INJ_InitStruct->SequencerDiscont)); + } + ASSERT_PARAM(IS_DDL_ADC_INJ_TRIG_AUTO(ADC_INJ_InitStruct->TrigAuto)); + + /* Note: Hardware constraint (refer to description of this function): */ + /* ADC instance must be disabled. */ + if(DDL_ADC_IsEnabled(ADCx) == 0UL) + { + /* Configuration of ADC hierarchical scope: */ + /* - ADC group injected */ + /* - Set ADC group injected trigger source */ + /* - Set ADC group injected sequencer length */ + /* - Set ADC group injected sequencer discontinuous mode */ + /* - Set ADC group injected conversion trigger: independent or */ + /* from ADC group regular */ + /* Note: On this APM32 series, ADC trigger edge is set when starting */ + /* ADC conversion. */ + /* Refer to function @ref DDL_ADC_INJ_StartConversionExtTrig(). */ + if(ADC_INJ_InitStruct->SequencerLength != DDL_ADC_REG_SEQ_SCAN_DISABLE) + { + MODIFY_REG(ADCx->CTRL1, + ADC_CTRL1_INJDISCEN + | ADC_CTRL1_INJGACEN + , + ADC_INJ_InitStruct->SequencerDiscont + | ADC_INJ_InitStruct->TrigAuto + ); + } + else + { + MODIFY_REG(ADCx->CTRL1, + ADC_CTRL1_INJDISCEN + | ADC_CTRL1_INJGACEN + , + DDL_ADC_REG_SEQ_DISCONT_DISABLE + | ADC_INJ_InitStruct->TrigAuto + ); + } + + MODIFY_REG(ADCx->CTRL2, + ADC_CTRL2_INJGEXTTRGSEL + | ADC_CTRL2_INJEXTTRGEN + , + (ADC_INJ_InitStruct->TriggerSource & ADC_CTRL2_INJGEXTTRGSEL) + ); + + /* Note: Hardware constraint (refer to description of this function): */ + /* Note: If ADC instance feature scan mode is disabled */ + /* (refer to ADC instance initialization structure */ + /* parameter @ref SequencersScanMode */ + /* or function @ref DDL_ADC_SetSequencersScanMode() ), */ + /* this parameter is discarded. */ + DDL_ADC_INJ_SetSequencerLength(ADCx, ADC_INJ_InitStruct->SequencerLength); + } + else + { + /* Initialization error: ADC instance is not disabled. */ + status = ERROR; + } + return status; +} + +/** + * @brief Set each @ref DDL_ADC_INJ_InitTypeDef field to default value. + * @param ADC_INJ_InitStruct Pointer to a @ref DDL_ADC_INJ_InitTypeDef structure + * whose fields will be set to default values. + * @retval None + */ +void DDL_ADC_INJ_StructInit(DDL_ADC_INJ_InitTypeDef *ADC_INJ_InitStruct) +{ + /* Set ADC_INJ_InitStruct fields to default values */ + /* Set fields of ADC group injected */ + ADC_INJ_InitStruct->TriggerSource = DDL_ADC_INJ_TRIG_SOFTWARE; + ADC_INJ_InitStruct->SequencerLength = DDL_ADC_INJ_SEQ_SCAN_DISABLE; + ADC_INJ_InitStruct->SequencerDiscont = DDL_ADC_INJ_SEQ_DISCONT_DISABLE; + ADC_INJ_InitStruct->TrigAuto = DDL_ADC_INJ_TRIG_INDEPENDENT; +} + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#endif /* ADC1 || ADC2 || ADC3 */ + +/** + * @} + */ + +#endif /* USE_FULL_DDL_DRIVER */ + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_ddl_comp.c b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_ddl_comp.c new file mode 100644 index 0000000000..d685da2c7b --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_ddl_comp.c @@ -0,0 +1,264 @@ +/** + * + * @file apm32f4xx_ddl_comp.c + * @brief COMP DDL module driver. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2017 STMicroelectronics. + * Copyright (C) 2023-2024 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + * + */ +#if defined(USE_FULL_DDL_DRIVER) + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_ddl_comp.h" +#include "apm32f4xx_ddl_bus.h" + +#ifdef USE_FULL_ASSERT +#include "apm32_assert.h" +#else +#define ASSERT_PARAM(_PARAM_) ((void)(_PARAM_)) +#endif /* USE_FULL_ASSERT */ + +/** @addtogroup APM32F4xx_DDL_Driver + * @{ + */ + +#if defined (COMP1) || defined (COMP2) + +/** @addtogroup COMP_DDL COMP + * @{ + */ + +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/* Private macros ------------------------------------------------------------*/ + +/** @defgroup COMP_DDL_Private_Macros COMP Private Macros + * @{ + */ + + /* Check of parameters for configuration of COMP hierarchical scope: */ + /* COMP instance. */ + +#define IS_DDL_COMP_MODE(__MODE__) \ + ( ((__MODE__) == DDL_COMP_SPEEDMODE_LOW) || \ + ((__MODE__) == DDL_COMP_SPEEDMODE_HIGH) \ + ) + +#define IS_DDL_COMP_INPUT_PLUS(__COMP_INSTANCE__, __INPUT_PLUS__) \ + ((__INPUT_PLUS__) == DDL_COMP_INPUT_PLUS_PC2) + +#define IS_DDL_COMP1_INPUT_MINUS(__COMP_INSTANCE__, __INPUT_MINUS__) \ + ( ((__INPUT_MINUS__) == DDL_COMP_INPUT_MINUS_VREFINT) || \ + ((__INPUT_MINUS__) == DDL_COMP_INPUT_MINUS_PC1) \ + ) + +#define IS_DDL_COMP2_INPUT_MINUS(__COMP_INSTANCE__, __INPUT_MINUS__) \ + ( ((__INPUT_MINUS__) == DDL_COMP_INPUT_MINUS_VREFINT) || \ + ((__INPUT_MINUS__) == DDL_COMP_INPUT_MINUS_PC3) || \ + ((__INPUT_MINUS__) == DDL_COMP_INPUT_MINUS_1_4_VREFINT) || \ + ((__INPUT_MINUS__) == DDL_COMP_INPUT_MINUS_1_2_VREFINT) || \ + ((__INPUT_MINUS__) == DDL_COMP_INPUT_MINUS_3_4_VREFINT) \ + ) + +#define IS_DDL_COMP_OUTPUT_POLARITY(__POLARITY__) \ + ( ((__POLARITY__) == DDL_COMP_OUTPUTPOL_NONINVERTED) || \ + ((__POLARITY__) == DDL_COMP_OUTPUTPOL_INVERTED) \ + ) + +#define IS_DDL_COMP_OUTPUT_MODE(__MODE__) \ + ( ((__MODE__) == DDL_COMP_OUTPUT_NONE) || \ + ((__MODE__) == DDL_COMP_OUTPUT_TMR1BKIN) || \ + ((__MODE__) == DDL_COMP_OUTPUT_TMR1IC1) || \ + ((__MODE__) == DDL_COMP_OUTPUT_TMR1ETRF) || \ + ((__MODE__) == DDL_COMP_OUTPUT_TMR8BKIN) || \ + ((__MODE__) == DDL_COMP_OUTPUT_TMR8IC1) || \ + ((__MODE__) == DDL_COMP_OUTPUT_TMR8ETRF) || \ + ((__MODE__) == DDL_COMP_OUTPUT_TMR2IC4) || \ + ((__MODE__) == DDL_COMP_OUTPUT_TMR2ETRF) || \ + ((__MODE__) == DDL_COMP_OUTPUT_TMR3IC1) || \ + ((__MODE__) == DDL_COMP_OUTPUT_TMR3ETRF) || \ + ((__MODE__) == DDL_COMP_OUTPUT_TMR4IC1) \ + ) + +/** + * @} + */ + +/* Private function prototypes -----------------------------------------------*/ + +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup COMP_DDL_Exported_Functions + * @{ + */ + +/** @addtogroup COMP_DDL_EF_Init + * @{ + */ + +/** + * @brief Initialize COMP function. + * @param COMPx COMP instance + * @param COMP_InitStruct Pointer to a @ref DDL_COMP_InitTypeDef structure + * @retval An ErrorStatus enumeration value: + * - SUCCESS: COMP registers are initialized + * - ERROR: COMP registers are not initialized + */ +ErrorStatus DDL_COMP_Init(COMP_TypeDef *COMPx, DDL_COMP_InitTypeDef *COMP_InitStruct) +{ + ErrorStatus status = SUCCESS; + + /* Check parameters */ + ASSERT_PARAM(IS_COMP_ALL_INSTANCE(COMPx)); + ASSERT_PARAM(IS_DDL_COMP_INPUT_PLUS(COMPx, COMP_InitStruct->InputPlus)); + ASSERT_PARAM(IS_DDL_COMP_OUTPUT_POLARITY(COMP_InitStruct->OutputPol)); + ASSERT_PARAM(IS_DDL_COMP_OUTPUT_MODE(COMP_InitStruct->Output)); + + if (COMPx == COMP1) + { + ASSERT_PARAM(IS_DDL_COMP1_INPUT_MINUS(COMPx, COMP_InitStruct->InputMinus)); + } + else + { + ASSERT_PARAM(IS_DDL_COMP_MODE(COMP_InitStruct->Mode)); + ASSERT_PARAM(IS_DDL_COMP2_INPUT_MINUS(COMPx, COMP_InitStruct->InputMinus)); + } + + /* COMP instance must not be locked */ + if (DDL_COMP_IsLocked(COMPx) == 0UL) + { + /* Configuration of comparator instance */ + if (COMPx == COMP1) + { + MODIFY_REG(COMPx->CSTS, + COMP_CSTS_INMCCFG | + COMP_CSTS_POLCFG | + COMP_CSTS_OUTSEL, + COMP_InitStruct->InputMinus | + COMP_InitStruct->OutputPol | + COMP_InitStruct->Output + ); + } + else + { + MODIFY_REG(COMPx->CSTS, + COMP_CSTS_SPEEDM | + COMP_CSTS_INMCCFG | + COMP_CSTS_POLCFG | + COMP_CSTS_OUTSEL, + COMP_InitStruct->Mode | + COMP_InitStruct->InputMinus | + COMP_InitStruct->OutputPol | + COMP_InitStruct->Output + ); + } + } + else + { + status = ERROR; + } + + return status; +} + +/** + * @brief De-Initialize COMP function. + * @param COMPx COMP instance + * @retval An ErrorStatus enumeration value: + * - SUCCESS: COMP registers are de-initialized + * - ERROR: COMP registers are not de-initialized + * @note If COMP instance is locked, de-initialization can't be performed. + * The only way to unlock the COMP instance is to perform a system reset. + */ +ErrorStatus DDL_COMP_DeInit(COMP_TypeDef *COMPx) +{ + ErrorStatus status = SUCCESS; + + /* Check parameters */ + ASSERT_PARAM(IS_COMP_ALL_INSTANCE(COMPx)); + + /* COMP instance must not be locked */ + if (DDL_COMP_IsLocked(COMPx) == 0UL) + { + /* De-initialize the COMP registers to the reset values */ + DDL_COMP_WriteReg((COMPx), CSTS, 0x00000000UL); + } + else + { + /* COMP instance is locked */ + /* The only way to unlock the COMP instance is to perform a system reset */ + status = ERROR; + } + + return status; +} + +/** + * @brief Set the fields of structure COMP_InitStruct to default values. + * @param COMP_InitStruct Pointer to a @ref DDL_COMP_InitTypeDef structure + * whose fields will be set to default values. + * @retval None + */ +void DDL_COMP_StructInit(DDL_COMP_InitTypeDef *COMP_InitStruct) +{ + /* Set COMP_InitStruct fields to default values */ + COMP_InitStruct->Mode = DDL_COMP_SPEEDMODE_LOW; + COMP_InitStruct->InputPlus = DDL_COMP_INPUT_PLUS_PC2; + COMP_InitStruct->InputMinus = DDL_COMP_INPUT_MINUS_VREFINT; + COMP_InitStruct->OutputPol = DDL_COMP_OUTPUTPOL_NONINVERTED; + COMP_InitStruct->Output = DDL_COMP_OUTPUT_NONE; +} + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#endif /* COMP1 || COMP2 */ + +/** + * @} + */ + +#endif /* USE_FULL_DDL_DRIVER */ diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_ddl_crc.c b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_ddl_crc.c new file mode 100644 index 0000000000..6debd10733 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_ddl_crc.c @@ -0,0 +1,128 @@ +/** + * + * @file apm32f4xx_ddl_crc.c + * @brief CRC DDL module driver. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + * + */ +#if defined(USE_FULL_DDL_DRIVER) + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_ddl_crc.h" +#include "apm32f4xx_ddl_bus.h" + +#ifdef USE_FULL_ASSERT +#include "apm32_assert.h" +#else +#define ASSERT_PARAM(_PARAM_) ((void)(_PARAM_)) +#endif /* USE_FULL_ASSERT */ + +/** @addtogroup APM32F4xx_DDL_Driver + * @{ + */ + +#if defined (CRC) + +/** @addtogroup CRC_DDL + * @{ + */ + +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/* Private macros ------------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ + +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup CRC_DDL_Exported_Functions + * @{ + */ + +/** @addtogroup CRC_DDL_EF_Init + * @{ + */ + +/** + * @brief De-initialize CRC registers (Registers restored to their default values). + * @param CRCx CRC Instance + * @retval An ErrorStatus enumeration value: + * - SUCCESS: CRC registers are de-initialized + * - ERROR: CRC registers are not de-initialized + */ +ErrorStatus DDL_CRC_DeInit(CRC_TypeDef *CRCx) +{ + ErrorStatus status = SUCCESS; + + /* Check the parameters */ + ASSERT_PARAM(IS_CRC_ALL_INSTANCE(CRCx)); + + if (CRCx == CRC) + { + /* Force CRC reset */ + DDL_AHB1_GRP1_ForceReset(DDL_AHB1_GRP1_PERIPH_CRC); + + /* Release CRC reset */ + DDL_AHB1_GRP1_ReleaseReset(DDL_AHB1_GRP1_PERIPH_CRC); + } + else + { + status = ERROR; + } + + return (status); +} + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#endif /* defined (CRC) */ + +/** + * @} + */ + +#endif /* USE_FULL_DDL_DRIVER */ diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_ddl_dac.c b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_ddl_dac.c new file mode 100644 index 0000000000..3d55cecafb --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_ddl_dac.c @@ -0,0 +1,305 @@ +/** + * + * @file apm32f4xx_ddl_dac.c + * @brief DAC DDL module driver + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + * + */ +#if defined(USE_FULL_DDL_DRIVER) + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_ddl_dac.h" +#include "apm32f4xx_ddl_bus.h" + +#if (USE_FULL_ASSERT == 1U) +#include "apm32_assert.h" +#else +#define ASSERT_PARAM(_PARAM_) ((void)(_PARAM_)) +#endif /* USE_FULL_ASSERT */ + +/** @addtogroup APM32F4xx_DDL_Driver + * @{ + */ + +#if defined(DAC) + +/** @addtogroup DAC_DDL DAC + * @{ + */ + +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/* Private macros ------------------------------------------------------------*/ + +/** @addtogroup DAC_DDL_Private_Macros + * @{ + */ +#if defined(DAC_CHANNEL2_SUPPORT) +#define IS_DDL_DAC_CHANNEL(__DACX__, __DAC_CHANNEL__) \ + ( \ + ((__DAC_CHANNEL__) == DDL_DAC_CHANNEL_1) \ + || ((__DAC_CHANNEL__) == DDL_DAC_CHANNEL_2) \ + ) +#else +#define IS_DDL_DAC_CHANNEL(__DACX__, __DAC_CHANNEL__) \ + ( \ + ((__DAC_CHANNEL__) == DDL_DAC_CHANNEL_1) \ + ) +#endif /* DAC_CHANNEL2_SUPPORT */ + +#define IS_DDL_DAC_TRIGGER_SOURCE(__TRIGGER_SOURCE__) \ + ( ((__TRIGGER_SOURCE__) == DDL_DAC_TRIG_SOFTWARE) \ + || ((__TRIGGER_SOURCE__) == DDL_DAC_TRIG_EXT_TMR2_TRGO) \ + || ((__TRIGGER_SOURCE__) == DDL_DAC_TRIG_EXT_TMR4_TRGO) \ + || ((__TRIGGER_SOURCE__) == DDL_DAC_TRIG_EXT_TMR5_TRGO) \ + || ((__TRIGGER_SOURCE__) == DDL_DAC_TRIG_EXT_TMR6_TRGO) \ + || ((__TRIGGER_SOURCE__) == DDL_DAC_TRIG_EXT_TMR7_TRGO) \ + || ((__TRIGGER_SOURCE__) == DDL_DAC_TRIG_EXT_TMR8_TRGO) \ + || ((__TRIGGER_SOURCE__) == DDL_DAC_TRIG_EXT_EINT_LINE9) \ + ) + +#define IS_DDL_DAC_WAVE_AUTO_GENER_MODE(__WAVE_AUTO_GENERATION_MODE__) \ + ( ((__WAVE_AUTO_GENERATION_MODE__) == DDL_DAC_WAVE_AUTO_GENERATION_NONE) \ + || ((__WAVE_AUTO_GENERATION_MODE__) == DDL_DAC_WAVE_AUTO_GENERATION_NOISE) \ + || ((__WAVE_AUTO_GENERATION_MODE__) == DDL_DAC_WAVE_AUTO_GENERATION_TRIANGLE) \ + ) + +#define IS_DDL_DAC_WAVE_AUTO_GENER_CONFIG(__WAVE_AUTO_GENERATION_MODE__, __WAVE_AUTO_GENERATION_CONFIG__) \ + ( (((__WAVE_AUTO_GENERATION_MODE__) == DDL_DAC_WAVE_AUTO_GENERATION_NOISE) \ + && ( ((__WAVE_AUTO_GENERATION_CONFIG__) == DDL_DAC_NOISE_LFSR_UNMASK_BIT0) \ + || ((__WAVE_AUTO_GENERATION_CONFIG__) == DDL_DAC_NOISE_LFSR_UNMASK_BITS1_0) \ + || ((__WAVE_AUTO_GENERATION_CONFIG__) == DDL_DAC_NOISE_LFSR_UNMASK_BITS2_0) \ + || ((__WAVE_AUTO_GENERATION_CONFIG__) == DDL_DAC_NOISE_LFSR_UNMASK_BITS3_0) \ + || ((__WAVE_AUTO_GENERATION_CONFIG__) == DDL_DAC_NOISE_LFSR_UNMASK_BITS4_0) \ + || ((__WAVE_AUTO_GENERATION_CONFIG__) == DDL_DAC_NOISE_LFSR_UNMASK_BITS5_0) \ + || ((__WAVE_AUTO_GENERATION_CONFIG__) == DDL_DAC_NOISE_LFSR_UNMASK_BITS6_0) \ + || ((__WAVE_AUTO_GENERATION_CONFIG__) == DDL_DAC_NOISE_LFSR_UNMASK_BITS7_0) \ + || ((__WAVE_AUTO_GENERATION_CONFIG__) == DDL_DAC_NOISE_LFSR_UNMASK_BITS8_0) \ + || ((__WAVE_AUTO_GENERATION_CONFIG__) == DDL_DAC_NOISE_LFSR_UNMASK_BITS9_0) \ + || ((__WAVE_AUTO_GENERATION_CONFIG__) == DDL_DAC_NOISE_LFSR_UNMASK_BITS10_0) \ + || ((__WAVE_AUTO_GENERATION_CONFIG__) == DDL_DAC_NOISE_LFSR_UNMASK_BITS11_0)) \ + ) \ + ||(((__WAVE_AUTO_GENERATION_MODE__) == DDL_DAC_WAVE_AUTO_GENERATION_TRIANGLE) \ + && ( ((__WAVE_AUTO_GENERATION_CONFIG__) == DDL_DAC_TRIANGLE_AMPLITUDE_1) \ + || ((__WAVE_AUTO_GENERATION_CONFIG__) == DDL_DAC_TRIANGLE_AMPLITUDE_3) \ + || ((__WAVE_AUTO_GENERATION_CONFIG__) == DDL_DAC_TRIANGLE_AMPLITUDE_7) \ + || ((__WAVE_AUTO_GENERATION_CONFIG__) == DDL_DAC_TRIANGLE_AMPLITUDE_15) \ + || ((__WAVE_AUTO_GENERATION_CONFIG__) == DDL_DAC_TRIANGLE_AMPLITUDE_31) \ + || ((__WAVE_AUTO_GENERATION_CONFIG__) == DDL_DAC_TRIANGLE_AMPLITUDE_63) \ + || ((__WAVE_AUTO_GENERATION_CONFIG__) == DDL_DAC_TRIANGLE_AMPLITUDE_127) \ + || ((__WAVE_AUTO_GENERATION_CONFIG__) == DDL_DAC_TRIANGLE_AMPLITUDE_255) \ + || ((__WAVE_AUTO_GENERATION_CONFIG__) == DDL_DAC_TRIANGLE_AMPLITUDE_511) \ + || ((__WAVE_AUTO_GENERATION_CONFIG__) == DDL_DAC_TRIANGLE_AMPLITUDE_1023) \ + || ((__WAVE_AUTO_GENERATION_CONFIG__) == DDL_DAC_TRIANGLE_AMPLITUDE_2047) \ + || ((__WAVE_AUTO_GENERATION_CONFIG__) == DDL_DAC_TRIANGLE_AMPLITUDE_4095)) \ + ) \ + ) + +#define IS_DDL_DAC_OUTPUT_BUFFER(__OUTPUT_BUFFER__) \ + ( ((__OUTPUT_BUFFER__) == DDL_DAC_OUTPUT_BUFFER_ENABLE) \ + || ((__OUTPUT_BUFFER__) == DDL_DAC_OUTPUT_BUFFER_DISABLE) \ + ) + +/** + * @} + */ + + +/* Private function prototypes -----------------------------------------------*/ + +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup DAC_DDL_Exported_Functions + * @{ + */ + +/** @addtogroup DAC_DDL_EF_Init + * @{ + */ + +/** + * @brief De-initialize registers of the selected DAC instance + * to their default reset values. + * @param DACx DAC instance + * @retval An ErrorStatus enumeration value: + * - SUCCESS: DAC registers are de-initialized + * - ERROR: not applicable + */ +ErrorStatus DDL_DAC_DeInit(DAC_TypeDef *DACx) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_DAC_ALL_INSTANCE(DACx)); + + /* Force reset of DAC clock */ + DDL_APB1_GRP1_ForceReset(DDL_APB1_GRP1_PERIPH_DAC1); + + /* Release reset of DAC clock */ + DDL_APB1_GRP1_ReleaseReset(DDL_APB1_GRP1_PERIPH_DAC1); + + return SUCCESS; +} + +/** + * @brief Initialize some features of DAC channel. + * @note @ref DDL_DAC_Init() aims to ease basic configuration of a DAC channel. + * Leaving it ready to be enabled and output: + * a level by calling one of + * @ref DDL_DAC_ConvertData12RightAligned + * @ref DDL_DAC_ConvertData12LeftAligned + * @ref DDL_DAC_ConvertData8RightAligned + * or one of the supported autogenerated wave. + * @note This function allows configuration of: + * - Output mode + * - Trigger + * - Wave generation + * @note The setting of these parameters by function @ref DDL_DAC_Init() + * is conditioned to DAC state: + * DAC channel must be disabled. + * @param DACx DAC instance + * @param DAC_Channel This parameter can be one of the following values: + * @arg @ref DDL_DAC_CHANNEL_1 + * @arg @ref DDL_DAC_CHANNEL_2 (1) + * + * (1) On this APM32 serie, parameter not available on all devices. + * Refer to device datasheet for channels availability. + * @param DAC_InitStruct Pointer to a @ref DDL_DAC_InitTypeDef structure + * @retval An ErrorStatus enumeration value: + * - SUCCESS: DAC registers are initialized + * - ERROR: DAC registers are not initialized + */ +ErrorStatus DDL_DAC_Init(DAC_TypeDef *DACx, uint32_t DAC_Channel, DDL_DAC_InitTypeDef *DAC_InitStruct) +{ + ErrorStatus status = SUCCESS; + + /* Check the parameters */ + ASSERT_PARAM(IS_DAC_ALL_INSTANCE(DACx)); + ASSERT_PARAM(IS_DDL_DAC_CHANNEL(DACx, DAC_Channel)); + ASSERT_PARAM(IS_DDL_DAC_TRIGGER_SOURCE(DAC_InitStruct->TriggerSource)); + ASSERT_PARAM(IS_DDL_DAC_OUTPUT_BUFFER(DAC_InitStruct->OutputBuffer)); + ASSERT_PARAM(IS_DDL_DAC_WAVE_AUTO_GENER_MODE(DAC_InitStruct->WaveAutoGeneration)); + if (DAC_InitStruct->WaveAutoGeneration != DDL_DAC_WAVE_AUTO_GENERATION_NONE) + { + ASSERT_PARAM(IS_DDL_DAC_WAVE_AUTO_GENER_CONFIG(DAC_InitStruct->WaveAutoGeneration, + DAC_InitStruct->WaveAutoGenerationConfig)); + } + + /* Note: Hardware constraint (refer to description of this function) */ + /* DAC instance must be disabled. */ + if (DDL_DAC_IsEnabled(DACx, DAC_Channel) == 0UL) + { + /* Configuration of DAC channel: */ + /* - TriggerSource */ + /* - WaveAutoGeneration */ + /* - OutputBuffer */ + /* - OutputMode */ + if (DAC_InitStruct->WaveAutoGeneration != DDL_DAC_WAVE_AUTO_GENERATION_NONE) + { + MODIFY_REG(DACx->CTRL, + (DAC_CTRL_TRGSELCH1 + | DAC_CTRL_WAVENCH1 + | DAC_CTRL_MAMPSELCH1 + | DAC_CTRL_BUFFDCH1 + ) << (DAC_Channel & DAC_CTRL_CHX_BITOFFSET_MASK) + , + (DAC_InitStruct->TriggerSource + | DAC_InitStruct->WaveAutoGeneration + | DAC_InitStruct->WaveAutoGenerationConfig + | DAC_InitStruct->OutputBuffer + ) << (DAC_Channel & DAC_CTRL_CHX_BITOFFSET_MASK) + ); + } + else + { + MODIFY_REG(DACx->CTRL, + (DAC_CTRL_TRGSELCH1 + | DAC_CTRL_WAVENCH1 + | DAC_CTRL_BUFFDCH1 + ) << (DAC_Channel & DAC_CTRL_CHX_BITOFFSET_MASK) + , + (DAC_InitStruct->TriggerSource + | DDL_DAC_WAVE_AUTO_GENERATION_NONE + | DAC_InitStruct->OutputBuffer + ) << (DAC_Channel & DAC_CTRL_CHX_BITOFFSET_MASK) + ); + } + } + else + { + /* Initialization error: DAC instance is not disabled. */ + status = ERROR; + } + return status; +} + +/** + * @brief Set each @ref DDL_DAC_InitTypeDef field to default value. + * @param DAC_InitStruct pointer to a @ref DDL_DAC_InitTypeDef structure + * whose fields will be set to default values. + * @retval None + */ +void DDL_DAC_StructInit(DDL_DAC_InitTypeDef *DAC_InitStruct) +{ + /* Set DAC_InitStruct fields to default values */ + DAC_InitStruct->TriggerSource = DDL_DAC_TRIG_SOFTWARE; + DAC_InitStruct->WaveAutoGeneration = DDL_DAC_WAVE_AUTO_GENERATION_NONE; + /* Note: Parameter discarded if wave auto generation is disabled, */ + /* set anyway to its default value. */ + DAC_InitStruct->WaveAutoGenerationConfig = DDL_DAC_NOISE_LFSR_UNMASK_BIT0; + DAC_InitStruct->OutputBuffer = DDL_DAC_OUTPUT_BUFFER_ENABLE; +} + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#endif /* DAC */ + +/** + * @} + */ + +#endif /* USE_FULL_DDL_DRIVER */ + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_ddl_dma.c b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_ddl_dma.c new file mode 100644 index 0000000000..86dfbb6ef1 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_ddl_dma.c @@ -0,0 +1,448 @@ +/** + * + * @file apm32f4xx_ddl_dma.c + * @brief DMA DDL module driver. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2017 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file in + * the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + * + */ +#if defined(USE_FULL_DDL_DRIVER) + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_ddl_dma.h" +#include "apm32f4xx_ddl_bus.h" +#ifdef USE_FULL_ASSERT +#include "apm32_assert.h" +#else +#define ASSERT_PARAM(_PARAM_) ((void)(_PARAM_)) +#endif + +/** @addtogroup APM32F4xx_DDL_Driver + * @{ + */ + +#if defined (DMA1) || defined (DMA2) + +/** @defgroup DMA_DDL DMA + * @{ + */ + +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/* Private macros ------------------------------------------------------------*/ +/** @addtogroup DMA_DDL_Private_Macros + * @{ + */ +#define IS_DDL_DMA_DIRECTION(__VALUE__) (((__VALUE__) == DDL_DMA_DIRECTION_PERIPH_TO_MEMORY) || \ + ((__VALUE__) == DDL_DMA_DIRECTION_MEMORY_TO_PERIPH) || \ + ((__VALUE__) == DDL_DMA_DIRECTION_MEMORY_TO_MEMORY)) + +#define IS_DDL_DMA_MODE(__VALUE__) (((__VALUE__) == DDL_DMA_MODE_NORMAL) || \ + ((__VALUE__) == DDL_DMA_MODE_CIRCULAR) || \ + ((__VALUE__) == DDL_DMA_MODE_PFCTRL)) + +#define IS_DDL_DMA_PERIPHINCMODE(__VALUE__) (((__VALUE__) == DDL_DMA_PERIPH_INCREMENT) || \ + ((__VALUE__) == DDL_DMA_PERIPH_NOINCREMENT)) + +#define IS_DDL_DMA_MEMORYINCMODE(__VALUE__) (((__VALUE__) == DDL_DMA_MEMORY_INCREMENT) || \ + ((__VALUE__) == DDL_DMA_MEMORY_NOINCREMENT)) + +#define IS_DDL_DMA_PERIPHDATASIZE(__VALUE__) (((__VALUE__) == DDL_DMA_PDATAALIGN_BYTE) || \ + ((__VALUE__) == DDL_DMA_PDATAALIGN_HALFWORD) || \ + ((__VALUE__) == DDL_DMA_PDATAALIGN_WORD)) + +#define IS_DDL_DMA_MEMORYDATASIZE(__VALUE__) (((__VALUE__) == DDL_DMA_MDATAALIGN_BYTE) || \ + ((__VALUE__) == DDL_DMA_MDATAALIGN_HALFWORD) || \ + ((__VALUE__) == DDL_DMA_MDATAALIGN_WORD)) + +#define IS_DDL_DMA_NBDATA(__VALUE__) ((__VALUE__) <= 0x0000FFFFU) + +#define IS_DDL_DMA_CHANNEL(__VALUE__) (((__VALUE__) == DDL_DMA_CHANNEL_0) || \ + ((__VALUE__) == DDL_DMA_CHANNEL_1) || \ + ((__VALUE__) == DDL_DMA_CHANNEL_2) || \ + ((__VALUE__) == DDL_DMA_CHANNEL_3) || \ + ((__VALUE__) == DDL_DMA_CHANNEL_4) || \ + ((__VALUE__) == DDL_DMA_CHANNEL_5) || \ + ((__VALUE__) == DDL_DMA_CHANNEL_6) || \ + ((__VALUE__) == DDL_DMA_CHANNEL_7)) + +#define IS_DDL_DMA_PRIORITY(__VALUE__) (((__VALUE__) == DDL_DMA_PRIORITY_LOW) || \ + ((__VALUE__) == DDL_DMA_PRIORITY_MEDIUM) || \ + ((__VALUE__) == DDL_DMA_PRIORITY_HIGH) || \ + ((__VALUE__) == DDL_DMA_PRIORITY_VERYHIGH)) + +#define IS_DDL_DMA_ALL_STREAM_INSTANCE(INSTANCE, STREAM) ((((INSTANCE) == DMA1) && \ + (((STREAM) == DDL_DMA_STREAM_0) || \ + ((STREAM) == DDL_DMA_STREAM_1) || \ + ((STREAM) == DDL_DMA_STREAM_2) || \ + ((STREAM) == DDL_DMA_STREAM_3) || \ + ((STREAM) == DDL_DMA_STREAM_4) || \ + ((STREAM) == DDL_DMA_STREAM_5) || \ + ((STREAM) == DDL_DMA_STREAM_6) || \ + ((STREAM) == DDL_DMA_STREAM_7) || \ + ((STREAM) == DDL_DMA_STREAM_ALL))) ||\ + (((INSTANCE) == DMA2) && \ + (((STREAM) == DDL_DMA_STREAM_0) || \ + ((STREAM) == DDL_DMA_STREAM_1) || \ + ((STREAM) == DDL_DMA_STREAM_2) || \ + ((STREAM) == DDL_DMA_STREAM_3) || \ + ((STREAM) == DDL_DMA_STREAM_4) || \ + ((STREAM) == DDL_DMA_STREAM_5) || \ + ((STREAM) == DDL_DMA_STREAM_6) || \ + ((STREAM) == DDL_DMA_STREAM_7) || \ + ((STREAM) == DDL_DMA_STREAM_ALL)))) + +#define IS_DDL_DMA_FIFO_MODE_STATE(STATE) (((STATE) == DDL_DMA_FIFOMODE_DISABLE ) || \ + ((STATE) == DDL_DMA_FIFOMODE_ENABLE)) + +#define IS_DDL_DMA_FIFO_THRESHOLD(THRESHOLD) (((THRESHOLD) == DDL_DMA_FIFOTHRESHOLD_1_4) || \ + ((THRESHOLD) == DDL_DMA_FIFOTHRESHOLD_1_2) || \ + ((THRESHOLD) == DDL_DMA_FIFOTHRESHOLD_3_4) || \ + ((THRESHOLD) == DDL_DMA_FIFOTHRESHOLD_FULL)) + +#define IS_DDL_DMA_MEMORY_BURST(BURST) (((BURST) == DDL_DMA_MBURST_SINGLE) || \ + ((BURST) == DDL_DMA_MBURST_INC4) || \ + ((BURST) == DDL_DMA_MBURST_INC8) || \ + ((BURST) == DDL_DMA_MBURST_INC16)) + +#define IS_DDL_DMA_PERIPHERAL_BURST(BURST) (((BURST) == DDL_DMA_PBURST_SINGLE) || \ + ((BURST) == DDL_DMA_PBURST_INC4) || \ + ((BURST) == DDL_DMA_PBURST_INC8) || \ + ((BURST) == DDL_DMA_PBURST_INC16)) + +/** + * @} + */ + +/* Private function prototypes -----------------------------------------------*/ + +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup DMA_DDL_Exported_Functions + * @{ + */ + +/** @addtogroup DMA_DDL_EF_Init + * @{ + */ + +/** + * @brief De-initialize the DMA registers to their default reset values. + * @param DMAx DMAx Instance + * @param Stream This parameter can be one of the following values: + * @arg @ref DDL_DMA_STREAM_0 + * @arg @ref DDL_DMA_STREAM_1 + * @arg @ref DDL_DMA_STREAM_2 + * @arg @ref DDL_DMA_STREAM_3 + * @arg @ref DDL_DMA_STREAM_4 + * @arg @ref DDL_DMA_STREAM_5 + * @arg @ref DDL_DMA_STREAM_6 + * @arg @ref DDL_DMA_STREAM_7 + * @arg @ref DDL_DMA_STREAM_ALL + * @retval An ErrorStatus enumeration value: + * - SUCCESS: DMA registers are de-initialized + * - ERROR: DMA registers are not de-initialized + */ +uint32_t DDL_DMA_DeInit(DMA_TypeDef *DMAx, uint32_t Stream) +{ + DMA_Stream_TypeDef *tmp = (DMA_Stream_TypeDef *)DMA1_Stream0; + ErrorStatus status = SUCCESS; + + /* Check the DMA Instance DMAx and Stream parameters*/ + ASSERT_PARAM(IS_DDL_DMA_ALL_STREAM_INSTANCE(DMAx, Stream)); + + if (Stream == DDL_DMA_STREAM_ALL) + { + if (DMAx == DMA1) + { + /* Force reset of DMA clock */ + DDL_AHB1_GRP1_ForceReset(DDL_AHB1_GRP1_PERIPH_DMA1); + + /* Release reset of DMA clock */ + DDL_AHB1_GRP1_ReleaseReset(DDL_AHB1_GRP1_PERIPH_DMA1); + } + else if (DMAx == DMA2) + { + /* Force reset of DMA clock */ + DDL_AHB1_GRP1_ForceReset(DDL_AHB1_GRP1_PERIPH_DMA2); + + /* Release reset of DMA clock */ + DDL_AHB1_GRP1_ReleaseReset(DDL_AHB1_GRP1_PERIPH_DMA2); + } + else + { + status = ERROR; + } + } + else + { + /* Disable the selected Stream */ + DDL_DMA_DisableStream(DMAx,Stream); + + /* Get the DMA Stream Instance */ + tmp = (DMA_Stream_TypeDef *)(__DDL_DMA_GET_STREAM_INSTANCE(DMAx, Stream)); + + /* Reset DMAx_Streamy configuration register */ + DDL_DMA_WriteReg(tmp, SCFG, 0U); + + /* Reset DMAx_Streamy remaining bytes register */ + DDL_DMA_WriteReg(tmp, NDATA, 0U); + + /* Reset DMAx_Streamy peripheral address register */ + DDL_DMA_WriteReg(tmp, PADDR, 0U); + + /* Reset DMAx_Streamy memory address register */ + DDL_DMA_WriteReg(tmp, M0ADDR, 0U); + + /* Reset DMAx_Streamy memory address register */ + DDL_DMA_WriteReg(tmp, M1ADDR, 0U); + + /* Reset DMAx_Streamy FIFO control register */ + DDL_DMA_WriteReg(tmp, FCTRL, 0x00000021U); + + /* Reset Channel register field for DMAx Stream*/ + DDL_DMA_SetChannelSelection(DMAx, Stream, DDL_DMA_CHANNEL_0); + + if(Stream == DDL_DMA_STREAM_0) + { + /* Reset the Stream0 pending flags */ + DMAx->LIFCLR = 0x0000003FU; + } + else if(Stream == DDL_DMA_STREAM_1) + { + /* Reset the Stream1 pending flags */ + DMAx->LIFCLR = 0x00000F40U; + } + else if(Stream == DDL_DMA_STREAM_2) + { + /* Reset the Stream2 pending flags */ + DMAx->LIFCLR = 0x003F0000U; + } + else if(Stream == DDL_DMA_STREAM_3) + { + /* Reset the Stream3 pending flags */ + DMAx->LIFCLR = 0x0F400000U; + } + else if(Stream == DDL_DMA_STREAM_4) + { + /* Reset the Stream4 pending flags */ + DMAx->HIFCLR = 0x0000003FU; + } + else if(Stream == DDL_DMA_STREAM_5) + { + /* Reset the Stream5 pending flags */ + DMAx->HIFCLR = 0x00000F40U; + } + else if(Stream == DDL_DMA_STREAM_6) + { + /* Reset the Stream6 pending flags */ + DMAx->HIFCLR = 0x003F0000U; + } + else if(Stream == DDL_DMA_STREAM_7) + { + /* Reset the Stream7 pending flags */ + DMAx->HIFCLR = 0x0F400000U; + } + else + { + status = ERROR; + } + } + + return status; +} + +/** + * @brief Initialize the DMA registers according to the specified parameters in DMA_InitStruct. + * @note To convert DMAx_Streamy Instance to DMAx Instance and Streamy, use helper macros : + * @arg @ref __DDL_DMA_GET_INSTANCE + * @arg @ref __DDL_DMA_GET_STREAM + * @param DMAx DMAx Instance + * @param Stream This parameter can be one of the following values: + * @arg @ref DDL_DMA_STREAM_0 + * @arg @ref DDL_DMA_STREAM_1 + * @arg @ref DDL_DMA_STREAM_2 + * @arg @ref DDL_DMA_STREAM_3 + * @arg @ref DDL_DMA_STREAM_4 + * @arg @ref DDL_DMA_STREAM_5 + * @arg @ref DDL_DMA_STREAM_6 + * @arg @ref DDL_DMA_STREAM_7 + * @param DMA_InitStruct pointer to a @ref DDL_DMA_InitTypeDef structure. + * @retval An ErrorStatus enumeration value: + * - SUCCESS: DMA registers are initialized + * - ERROR: Not applicable + */ +uint32_t DDL_DMA_Init(DMA_TypeDef *DMAx, uint32_t Stream, DDL_DMA_InitTypeDef *DMA_InitStruct) +{ + /* Check the DMA Instance DMAx and Stream parameters*/ + ASSERT_PARAM(IS_DDL_DMA_ALL_STREAM_INSTANCE(DMAx, Stream)); + + /* Check the DMA parameters from DMA_InitStruct */ + ASSERT_PARAM(IS_DDL_DMA_DIRECTION(DMA_InitStruct->Direction)); + ASSERT_PARAM(IS_DDL_DMA_MODE(DMA_InitStruct->Mode)); + ASSERT_PARAM(IS_DDL_DMA_PERIPHINCMODE(DMA_InitStruct->PeriphOrM2MSrcIncMode)); + ASSERT_PARAM(IS_DDL_DMA_MEMORYINCMODE(DMA_InitStruct->MemoryOrM2MDstIncMode)); + ASSERT_PARAM(IS_DDL_DMA_PERIPHDATASIZE(DMA_InitStruct->PeriphOrM2MSrcDataSize)); + ASSERT_PARAM(IS_DDL_DMA_MEMORYDATASIZE(DMA_InitStruct->MemoryOrM2MDstDataSize)); + ASSERT_PARAM(IS_DDL_DMA_NBDATA(DMA_InitStruct->NbData)); + ASSERT_PARAM(IS_DDL_DMA_CHANNEL(DMA_InitStruct->Channel)); + ASSERT_PARAM(IS_DDL_DMA_PRIORITY(DMA_InitStruct->Priority)); + ASSERT_PARAM(IS_DDL_DMA_FIFO_MODE_STATE(DMA_InitStruct->FIFOMode)); + /* Check the memory burst, peripheral burst and FIFO threshold parameters only + when FIFO mode is enabled */ + if(DMA_InitStruct->FIFOMode != DDL_DMA_FIFOMODE_DISABLE) + { + ASSERT_PARAM(IS_DDL_DMA_FIFO_THRESHOLD(DMA_InitStruct->FIFOThreshold)); + ASSERT_PARAM(IS_DDL_DMA_MEMORY_BURST(DMA_InitStruct->MemBurst)); + ASSERT_PARAM(IS_DDL_DMA_PERIPHERAL_BURST(DMA_InitStruct->PeriphBurst)); + } + + /*---------------------------- DMAx SCFGx Configuration ------------------------ + * Configure DMAx_Streamy: data transfer direction, data transfer mode, + * peripheral and memory increment mode, + * data size alignment and priority level with parameters : + * - Direction: DMA_SCFGx_DIRCFG[1:0] bits + * - Mode: DMA_SCFGx_CIRCMEN bit + * - PeriphOrM2MSrcIncMode: DMA_SCFGx_PERIM bit + * - MemoryOrM2MDstIncMode: DMA_SCFGx_MEMIM bit + * - PeriphOrM2MSrcDataSize: DMA_SCFGx_PERSIZECFG[1:0] bits + * - MemoryOrM2MDstDataSize: DMA_SCFGx_MEMSIZECFG[1:0] bits + * - Priority: DMA_SCFGx_PRILCFG[1:0] bits + */ + DDL_DMA_ConfigTransfer(DMAx, Stream, DMA_InitStruct->Direction | \ + DMA_InitStruct->Mode | \ + DMA_InitStruct->PeriphOrM2MSrcIncMode | \ + DMA_InitStruct->MemoryOrM2MDstIncMode | \ + DMA_InitStruct->PeriphOrM2MSrcDataSize | \ + DMA_InitStruct->MemoryOrM2MDstDataSize | \ + DMA_InitStruct->Priority + ); + + if(DMA_InitStruct->FIFOMode != DDL_DMA_FIFOMODE_DISABLE) + { + /*---------------------------- DMAx FCTRLx Configuration ------------------------ + * Configure DMAx_Streamy: fifo mode and fifo threshold with parameters : + * - FIFOMode: DMA_FCTRLx_DMDEN bit + * - FIFOThreshold: DMA_FCTRLx_FTHSEL[1:0] bits + */ + DDL_DMA_ConfigFifo(DMAx, Stream, DMA_InitStruct->FIFOMode, DMA_InitStruct->FIFOThreshold); + + /*---------------------------- DMAx SCFGx Configuration -------------------------- + * Configure DMAx_Streamy: memory burst transfer with parameters : + * - MemBurst: DMA_SCFGx_MBCFG[1:0] bits + */ + DDL_DMA_SetMemoryBurstxfer(DMAx,Stream,DMA_InitStruct->MemBurst); + + /*---------------------------- DMAx SCFGx Configuration -------------------------- + * Configure DMAx_Streamy: peripheral burst transfer with parameters : + * - PeriphBurst: DMA_SCFGx_PBCFG[1:0] bits + */ + DDL_DMA_SetPeriphBurstxfer(DMAx,Stream,DMA_InitStruct->PeriphBurst); + } + + /*-------------------------- DMAx M0ADDRx Configuration -------------------------- + * Configure the memory or destination base address with parameter : + * - MemoryOrM2MDstAddress: DMA_M0ADDRx_M0ADDR[31:0] bits + */ + DDL_DMA_SetMemoryAddress(DMAx, Stream, DMA_InitStruct->MemoryOrM2MDstAddress); + + /*-------------------------- DMAx PADDRx Configuration --------------------------- + * Configure the peripheral or source base address with parameter : + * - PeriphOrM2MSrcAddress: DMA_PADDRx_PADDR[31:0] bits + */ + DDL_DMA_SetPeriphAddress(DMAx, Stream, DMA_InitStruct->PeriphOrM2MSrcAddress); + + /*--------------------------- DMAx SxNDTR Configuration ------------------------- + * Configure the peripheral base address with parameter : + * - NbData: DMA_NDATAx[15:0] bits + */ + DDL_DMA_SetDataLength(DMAx, Stream, DMA_InitStruct->NbData); + + /*--------------------------- DMA SCFGx_CHSEL Configuration ---------------------- + * Configure the peripheral base address with parameter : + * - PeriphRequest: DMA_SCFGx_CHSEL[2:0] bits + */ + DDL_DMA_SetChannelSelection(DMAx, Stream, DMA_InitStruct->Channel); + + return SUCCESS; +} + +/** + * @brief Set each @ref DDL_DMA_InitTypeDef field to default value. + * @param DMA_InitStruct Pointer to a @ref DDL_DMA_InitTypeDef structure. + * @retval None + */ +void DDL_DMA_StructInit(DDL_DMA_InitTypeDef *DMA_InitStruct) +{ + /* Set DMA_InitStruct fields to default values */ + DMA_InitStruct->PeriphOrM2MSrcAddress = 0x00000000U; + DMA_InitStruct->MemoryOrM2MDstAddress = 0x00000000U; + DMA_InitStruct->Direction = DDL_DMA_DIRECTION_PERIPH_TO_MEMORY; + DMA_InitStruct->Mode = DDL_DMA_MODE_NORMAL; + DMA_InitStruct->PeriphOrM2MSrcIncMode = DDL_DMA_PERIPH_NOINCREMENT; + DMA_InitStruct->MemoryOrM2MDstIncMode = DDL_DMA_MEMORY_NOINCREMENT; + DMA_InitStruct->PeriphOrM2MSrcDataSize = DDL_DMA_PDATAALIGN_BYTE; + DMA_InitStruct->MemoryOrM2MDstDataSize = DDL_DMA_MDATAALIGN_BYTE; + DMA_InitStruct->NbData = 0x00000000U; + DMA_InitStruct->Channel = DDL_DMA_CHANNEL_0; + DMA_InitStruct->Priority = DDL_DMA_PRIORITY_LOW; + DMA_InitStruct->FIFOMode = DDL_DMA_FIFOMODE_DISABLE; + DMA_InitStruct->FIFOThreshold = DDL_DMA_FIFOTHRESHOLD_1_4; + DMA_InitStruct->MemBurst = DDL_DMA_MBURST_SINGLE; + DMA_InitStruct->PeriphBurst = DDL_DMA_PBURST_SINGLE; +} + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#endif /* DMA1 || DMA2 */ + +/** + * @} + */ + +#endif /* USE_FULL_DDL_DRIVER */ + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_ddl_dmc.c b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_ddl_dmc.c new file mode 100644 index 0000000000..da22483c0c --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_ddl_dmc.c @@ -0,0 +1,419 @@ +/** + * + * @file apm32f4xx_ddl_dmc.c + * @brief DMC Low Layer DDL module driver. + * + * This file provides firmware functions to manage the following + * functionalities of the Dynamic Memory Controller (DMC) peripheral memories: + * + Initialization/de-initialization functions + * + Peripheral Control functions + * + Peripheral State functions + * + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + * + @verbatim + ============================================================================== + ##### DMC peripheral features ##### + ============================================================================== + [..] The Dynamic memory controller (DMC) includes following memory controllers: + (+) The SDRAM memory controller + + @endverbatim + * + */ + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ +#if defined(DAL_SDRAM_MODULE_ENABLED) + +/** @defgroup DMC_DDL DMC Low Layer + * @brief DMC driver modules + * @{ + */ + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ + +/** @defgroup DMC_DDL_Private_Constants DMC Low Layer Private Constants + * @{ + */ + +/* ----------------------- DMC registers bit mask --------------------------- */ + +#if defined(DMC) + +/* --- CFG Register ---*/ +/* CFG register clear mask */ +#define CFG_CLEAR_MASK ((uint32_t)(DMC_CFG_BAWCFG | DMC_CFG_RAWCFG | \ + DMC_CFG_CAWCFG | DMC_CFG_DWCFG)) + +/* CTRL1 register clear mask */ +#define CTRL1_CLEAR_MASK ((uint32_t)(DMC_CTRL1_SRMEN | DMC_CTRL1_PDMEN | \ + DMC_CTRL1_FRBSREN | DMC_CTRL1_FRASREN | \ + DMC_CTRL1_RDNUMMCFG | DMC_CTRL1_BANKNUMCFG)) + +/* CTRL2 register clear mask */ +#define CTRL2_CLEAR_MASK ((uint32_t)(DMC_CTRL2_CPHACFG | DMC_CTRL2_RDDEN | \ + DMC_CTRL2_RDDCFG | DMC_CTRL2_WPEN | \ + DMC_CTRL2_BUFFEN | DMC_CTRL2_WRPBSEL)) + +/* TIM0 register clear mask */ +#define TIM0_CLEAR_MASK ((uint32_t)(DMC_TIM0_CASLSEL0 | DMC_TIM0_RASMINTSEL | \ + DMC_TIM0_DTIMSEL | DMC_TIM0_PCPSEL | \ + DMC_TIM0_WRTIMSEL | DMC_TIM0_ARPSEL | \ + DMC_TIM0_XSR0 | DMC_TIM0_ATACP | \ + DMC_TIM0_ECASLSEL1 | DMC_TIM0_EXSR1)) + +/* TIM1 register clear mask */ +#define TIM1_CLEAR_MASK ((uint32_t)(DMC_TIM1_STBTIM | DMC_TIM1_ARNUMCFG)) +#endif /* DMC */ + +/** + * @} + */ + +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Exported functions --------------------------------------------------------*/ + +/** @defgroup DMC_DDL_Exported_Functions DMC Low Layer Exported Functions + * @{ + */ + +#if defined(DMC) + +/** @defgroup DMC_DDL_SDRAM + * @brief SDRAM Controller functions + * + @verbatim + ============================================================================== + ##### How to use SDRAM device driver ##### + ============================================================================== + [..] + This driver contains a set of APIs to interface with the DMC SDRAM banks in order + to run the SDRAM external devices. + + (+) DMC SDRAM bank reset using the function DMC_SDRAM_DeInit() + (+) DMC SDRAM bank control configuration using the function DMC_SDRAM_Init() + (+) DMC SDRAM bank timing configuration using the function DMC_SDRAM_Timing_Init() + (+) DMC SDRAM bank enable/disable write operation using the functions + DMC_SDRAM_WriteOperation_Enable()/DMC_SDRAM_WriteOperation_Disable() + (+) DMC SDRAM bank send command using the function DMC_SDRAM_SendCommand() + +@endverbatim + * @{ + */ + +/** @addtogroup DMC_DDL_SDRAM_Private_Functions_Group1 + * @brief Initialization and Configuration functions + * +@verbatim + ============================================================================== + ##### Initialization and de_initialization functions ##### + ============================================================================== + [..] + This section provides functions allowing to: + (+) Initialize and configure the DMC SDRAM interface + (+) De-initialize the DMC SDRAM interface + (+) Configure the DMC clock and associated GPIOs + +@endverbatim + * @{ + */ + +/** + * @brief Initializes the DMC_SDRAM device according to the specified + * control parameters in the DMC_SDRAM_InitTypeDef + * @param Device Pointer to SDRAM device instance + * @param Init Pointer to SDRAM Initialization structure + * @retval DAL status + */ +DAL_StatusTypeDef DMC_SDRAM_Init(DMC_SDRAM_TypeDef *Device, DMC_SDRAM_InitTypeDef *Init) +{ + uint32_t tickstart; + + /* Check the parameters */ + ASSERT_PARAM(IS_DMC_SDRAM_DEVICE(Device)); + ASSERT_PARAM(IS_DMC_BANK_WIDTH(Init->BankWidth)); + ASSERT_PARAM(IS_DMC_COLUMNBITS_NUMBER(Init->ColumnBitsNumber)); + ASSERT_PARAM(IS_DMC_ROWBITS_NUMBER(Init->RowBitsNumber)); + ASSERT_PARAM(IS_DMC_MEMORY_WIDTH(Init->MemoryDataWidth)); + ASSERT_PARAM(IS_DMC_CLK_PHASE(Init->ClockPhase)); + ASSERT_PARAM(IS_DMC_RD_DELAY(Init->RDDelay)); + ASSERT_PARAM(IS_DMC_RD_DELAY_CLK(Init->RDDelayClk)); + ASSERT_PARAM(IS_DMC_WRITE_PIPE(Init->WritePipe)); + ASSERT_PARAM(IS_DMC_ACCELERATE_MODE(Init->AccelerateMode)); + ASSERT_PARAM(IS_DMC_WRAP_BURST(Init->WRAPBurstType)); + ASSERT_PARAM(IS_DMC_POWER_DOWN_MODE(Init->PowerDownMode)); + ASSERT_PARAM(IS_DMC_SELF_REFRESH_MODE(Init->SelfRefreshMode)); + ASSERT_PARAM(IS_DMC_REFRESH_TYPE(Init->RefreshTypeEnterSelfRefresh)); + ASSERT_PARAM(IS_DMC_REFRESH_TYPE(Init->RefreshTypeExitSelfRefresh)); + ASSERT_PARAM(IS_DMC_REG_INSERT_NUMBER(Init->RegisterInsertNumber)); + ASSERT_PARAM(IS_DMC_OPEN_BANK_NUMBER(Init->OpenBankNumber)); + + /* Switch to DMC controller */ + __DMC_SDRAM_ENABLE(Device); + + /* Get Start Tick */ + tickstart = DAL_GetTick(); + + /* Wait till DMC controller is ready */ + while((Device->CTRL1 & DMC_CTRL1_INIT) != RESET) + { + if((DAL_GetTick() - tickstart ) > DMC_TIMEOUT_VALUE) + { + return DAL_TIMEOUT; + } + } + + /* Set SDRAM CFG parameters */ + MODIFY_REG(Device->CFG, CFG_CLEAR_MASK, \ + (Init->BankWidth | \ + Init->ColumnBitsNumber | \ + Init->MemoryDataWidth | \ + Init->RowBitsNumber)); + + /* Set SDRAM CTRL1 parameters */ + MODIFY_REG(Device->CTRL1, CTRL1_CLEAR_MASK, \ + (Init->SelfRefreshMode | \ + Init->PowerDownMode | \ + ((Init->RefreshTypeEnterSelfRefresh) << DMC_CTRL1_FRBSREN_Pos) | \ + ((Init->RefreshTypeExitSelfRefresh) << DMC_CTRL1_FRASREN_Pos) | \ + ((Init->RegisterInsertNumber) << DMC_CTRL1_RDNUMMCFG_Pos) | \ + (((Init->OpenBankNumber) - 1U) << DMC_CTRL1_BANKNUMCFG_Pos))); + + /* Set SDRAM CTRL2 parameters */ + MODIFY_REG(Device->CTRL2, CTRL2_CLEAR_MASK, \ + (Init->ClockPhase | \ + Init->RDDelay | \ + (Init->RDDelayClk << DMC_CTRL2_RDDCFG_Pos) | \ + Init->WritePipe | \ + Init->AccelerateMode | \ + Init->WRAPBurstType)); + + /* Update mode setup */ + __DMC_SDRAM_UPDATE_MODE_SETUP(Device); + + return DAL_OK; +} + + +/** + * @brief Initializes the DMC_SDRAM device timing according to the specified + * parameters in the DMC_SDRAM_TimingTypeDef + * @param Device Pointer to SDRAM device instance + * @param Timing Pointer to SDRAM Timing structure + * @retval DAL status + */ +DAL_StatusTypeDef DMC_SDRAM_Timing_Init(DMC_SDRAM_TypeDef *Device, + DMC_SDRAM_TimingTypeDef *Timing) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_DMC_SDRAM_DEVICE(Device)); + ASSERT_PARAM(IS_DMC_CAS_LATENCY(Timing->CASLatency)); + ASSERT_PARAM(IS_DMC_RAS_TIME(Timing->RASTime)); + ASSERT_PARAM(IS_DMC_RAS_TO_CAS_DELAY(Timing->RASToCASDelay)); + ASSERT_PARAM(IS_DMC_PRECHARGE_MODE(Timing->PrechargeMode)); + ASSERT_PARAM(IS_DMC_PRECHARGE_PERIOD(Timing->PrechargePeriod)); + ASSERT_PARAM(IS_DMC_AUTO_REFRESH_TIME(Timing->AutoRefreshTime)); + ASSERT_PARAM(IS_DMC_WRITE_RECOVERY_TIME(Timing->WriteRecoveryTime)); + ASSERT_PARAM(IS_DMC_XSR_TIME(Timing->XSRTime)); + ASSERT_PARAM(IS_DMC_ACTIVE_COMMAND_TIME(Timing->ActiveCommandPeriod)); + ASSERT_PARAM(IS_DMC_REFRESH_PERIOD(Timing->RefreshPeriod)); + ASSERT_PARAM(IS_DMC_STABLE_TIME(Timing->StableTime)); + + /* Set SDRAM device CTRL1 parameters */ + MODIFY_REG(Device->CTRL1, DMC_CTRL1_PCACFG, Timing->PrechargeMode); + + /* Set SDRAM device timing 0 parameters */ + MODIFY_REG(Device->TIM0, TIM0_CLEAR_MASK, \ + (((Timing->CASLatency & 0x03U) << DMC_TIM0_CASLSEL0_Pos) | \ + (((Timing->CASLatency >> 0x02U) & 0x01U) << DMC_TIM0_ECASLSEL1_Pos) | \ + (((Timing->RASTime) - 1U) << DMC_TIM0_RASMINTSEL_Pos) | \ + (((Timing->RASToCASDelay) - 1U) << DMC_TIM0_DTIMSEL_Pos) | \ + (((Timing->PrechargePeriod) - 1U) << DMC_TIM0_PCPSEL_Pos) | \ + (((Timing->AutoRefreshTime) - 1U) << DMC_TIM0_ARPSEL_Pos) | \ + (((Timing->WriteRecoveryTime) - 1U) << DMC_TIM0_WRTIMSEL_Pos) | \ + (((Timing->ActiveCommandPeriod) - 1U) << DMC_TIM0_ATACP_Pos) | \ + (((Timing->XSRTime) & 0x0FU) << DMC_TIM0_XSR0_Pos) | \ + ((((Timing->XSRTime) >> 0x04U) & 0x1FU) << DMC_TIM0_EXSR1_Pos))); + + /* Set SDRAM device timing 1 parameters */ + MODIFY_REG(Device->TIM1, TIM1_CLEAR_MASK, \ + (((Timing->StableTime) << DMC_TIM1_STBTIM_Pos) | \ + (((Timing->AutoRefreshNumber) - 1U) << DMC_TIM1_ARNUMCFG_Pos))); + + /* Set SDRAM device refresh cycle */ + MODIFY_REG(Device->REF, DMC_REF_RCYCCFG, Timing->RefreshPeriod); + + return DAL_OK; +} + +/** + * @brief DeInitializes the DMC_SDRAM peripheral + * @param Device Pointer to SDRAM device instance + * @retval DAL status + */ +DAL_StatusTypeDef DMC_SDRAM_DeInit(DMC_SDRAM_TypeDef *Device) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_DMC_SDRAM_DEVICE(Device)); + + /* De-initialize the SDRAM device */ + Device->CFG = 0x00141388U; + Device->TIM0 = 0x019A5252U; + Device->TIM1 = 0x00074E20U; + Device->CTRL1 = 0x00003048U; + Device->CTRL2 = 0x0000002EU; + Device->REF = 0x000000C3U; + + return DAL_OK; +} + +/** + * @} + */ + +/** @addtogroup DMC_DDL_SDRAM_Private_Functions_Group2 + * @brief management functions + * +@verbatim + ============================================================================== + ##### DMC_SDRAM Control functions ##### + ============================================================================== + [..] + This subsection provides a set of functions allowing to control dynamically + the FMC SDRAM interface. + +@endverbatim + * @{ + */ + +/** + * @brief Program the SDRAM Memory Refresh period. + * @param Device Pointer to SDRAM device instance + * @param RefreshPeriod The SDRAM refresh period value. + * @retval DAL state + */ +DAL_StatusTypeDef DMC_SDRAM_ProgramRefreshPeriod(DMC_SDRAM_TypeDef *Device, uint32_t RefreshPeriod) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_DMC_SDRAM_DEVICE(Device)); + ASSERT_PARAM(IS_DMC_REFRESH_PERIOD(RefreshPeriod)); + + /* Set SDRAM device refresh cycle */ + MODIFY_REG(Device->REF, DMC_REF_RCYCCFG, RefreshPeriod); + + return DAL_OK; +} + +/** + * @brief Set the Number of consecutive SDRAM Memory open bank. + * @param Device Pointer to SDRAM device instance + * @param OpenBankNumber Specifies the open bank number. + * @retval None + */ +DAL_StatusTypeDef DMC_SDRAM_SetOpenBankNumber(DMC_SDRAM_TypeDef *Device, uint32_t OpenBankNumber) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_DMC_SDRAM_DEVICE(Device)); + ASSERT_PARAM(IS_DMC_OPEN_BANK_NUMBER(OpenBankNumber)); + + /* Set SDRAM CTRL1 parameters */ + MODIFY_REG(Device->CTRL1, DMC_CTRL1_BANKNUMCFG, (((OpenBankNumber) - 1U) << DMC_CTRL1_BANKNUMCFG_Pos)); + + return DAL_OK; +} + +/** + * @brief Returns the indicated DMC SDRAM mode status. + * @param Device Pointer to SDRAM device instance + * @retval The DMC SDRAM bank mode status, could be on of the following values: + * DMC_SDRAM_NORMAL_MODE, DMC_SDRAM_SELF_REFRESH_MODE or + * DMC_SDRAM_POWER_DOWN_MODE. + */ +uint32_t DMC_SDRAM_GetModeStatus(DMC_SDRAM_TypeDef *Device) +{ + uint32_t status = DMC_SDRAM_NORMAL_MODE; + + /* Check the parameters */ + ASSERT_PARAM(IS_DMC_SDRAM_DEVICE(Device)); + + if ((Device->CTRL1 & DMC_CTRL1_PDMEN) != RESET) + { + return DMC_SDRAM_POWER_DOWN_MODE; + } + else if ((Device->CTRL1 & DMC_CTRL1_SRMEN) && (Device->CTRL1 & DMC_CTRL1_FRBSREN) && \ + (Device->CTRL1 & DMC_CTRL1_SRMFLG)) + { + return DMC_SDRAM_SELF_REFRESH_MODE; + } + + return status; +} + +/** + * @} + */ + +/** + * @} + */ + +#endif /* DMC */ + +/** + * @} + */ + +/** + * @} + */ + +#endif /* DAL_SDRAM_MODULE_ENABLED */ +/** + * @} + */ +/** + * @} + */ diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_ddl_eint.c b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_ddl_eint.c new file mode 100644 index 0000000000..ce48da9cf4 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_ddl_eint.c @@ -0,0 +1,238 @@ +/** + * + * @file apm32f4xx_ddl_eint.c + * @author MCD Application Team + * @brief EINT DDL module driver. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS.Clause + * + * + */ +#if defined(USE_FULL_DDL_DRIVER) + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_ddl_eint.h" +#ifdef USE_FULL_ASSERT +#include "apm32_assert.h" +#else +#define ASSERT_PARAM(_PARAM_) ((void)(_PARAM_)) +#endif + +/** @addtogroup APM32F4xx_DDL_Driver + * @{ + */ + +#if defined (EINT) + +/** @defgroup EINT_DDL EINT + * @{ + */ + +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/* Private macros ------------------------------------------------------------*/ +/** @addtogroup EINT_DDL_Private_Macros + * @{ + */ + +#define IS_DDL_EINT_LINE_0_31(__VALUE__) (((__VALUE__) & ~DDL_EINT_LINE_ALL_0_31) == 0x00000000U) + +#define IS_DDL_EINT_MODE(__VALUE__) (((__VALUE__) == DDL_EINT_MODE_IT) \ + || ((__VALUE__) == DDL_EINT_MODE_EVENT) \ + || ((__VALUE__) == DDL_EINT_MODE_IT_EVENT)) + + +#define IS_DDL_EINT_TRIGGER(__VALUE__) (((__VALUE__) == DDL_EINT_TRIGGER_NONE) \ + || ((__VALUE__) == DDL_EINT_TRIGGER_RISING) \ + || ((__VALUE__) == DDL_EINT_TRIGGER_FALLING) \ + || ((__VALUE__) == DDL_EINT_TRIGGER_RISING_FALLING)) + +/** + * @} + */ + +/* Private function prototypes -----------------------------------------------*/ + +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup EINT_DDL_Exported_Functions + * @{ + */ + +/** @addtogroup EINT_DDL_EF_Init + * @{ + */ + +/** + * @brief De-initialize the EINT registers to their default reset values. + * @retval An ErrorStatus enumeration value: + * - SUCCESS: EINT registers are de-initialized + * - ERROR: not applicable + */ +uint32_t DDL_EINT_DeInit(void) +{ + /* Interrupt mask register set to default reset values */ + DDL_EINT_WriteReg(IMASK, 0x00000000U); + /* Event mask register set to default reset values */ + DDL_EINT_WriteReg(EMASK, 0x00000000U); + /* Rising Trigger selection register set to default reset values */ + DDL_EINT_WriteReg(RTEN, 0x00000000U); + /* Falling Trigger selection register set to default reset values */ + DDL_EINT_WriteReg(FTEN, 0x00000000U); + /* Software interrupt event register set to default reset values */ + DDL_EINT_WriteReg(SWINTE, 0x00000000U); + /* Pending register set to default reset values */ + DDL_EINT_WriteReg(IPEND, 0x00FFFFFFU); + + return SUCCESS; +} + +/** + * @brief Initialize the EINT registers according to the specified parameters in EINT_InitStruct. + * @param EINT_InitStruct pointer to a @ref DDL_EINT_InitTypeDef structure. + * @retval An ErrorStatus enumeration value: + * - SUCCESS: EINT registers are initialized + * - ERROR: not applicable + */ +uint32_t DDL_EINT_Init(DDL_EINT_InitTypeDef *EINT_InitStruct) +{ + ErrorStatus status = SUCCESS; + /* Check the parameters */ + ASSERT_PARAM(IS_DDL_EINT_LINE_0_31(EINT_InitStruct->Line_0_31)); + ASSERT_PARAM(IS_FUNCTIONAL_STATE(EINT_InitStruct->LineCommand)); + ASSERT_PARAM(IS_DDL_EINT_MODE(EINT_InitStruct->Mode)); + + /* ENABLE LineCommand */ + if (EINT_InitStruct->LineCommand != DISABLE) + { + ASSERT_PARAM(IS_DDL_EINT_TRIGGER(EINT_InitStruct->Trigger)); + + /* Configure EINT Lines in range from 0 to 31 */ + if (EINT_InitStruct->Line_0_31 != DDL_EINT_LINE_NONE) + { + switch (EINT_InitStruct->Mode) + { + case DDL_EINT_MODE_IT: + /* First Disable Event on provided Lines */ + DDL_EINT_DisableEvent_0_31(EINT_InitStruct->Line_0_31); + /* Then Enable IT on provided Lines */ + DDL_EINT_EnableIT_0_31(EINT_InitStruct->Line_0_31); + break; + case DDL_EINT_MODE_EVENT: + /* First Disable IT on provided Lines */ + DDL_EINT_DisableIT_0_31(EINT_InitStruct->Line_0_31); + /* Then Enable Event on provided Lines */ + DDL_EINT_EnableEvent_0_31(EINT_InitStruct->Line_0_31); + break; + case DDL_EINT_MODE_IT_EVENT: + /* Directly Enable IT & Event on provided Lines */ + DDL_EINT_EnableIT_0_31(EINT_InitStruct->Line_0_31); + DDL_EINT_EnableEvent_0_31(EINT_InitStruct->Line_0_31); + break; + default: + status = ERROR; + break; + } + if (EINT_InitStruct->Trigger != DDL_EINT_TRIGGER_NONE) + { + switch (EINT_InitStruct->Trigger) + { + case DDL_EINT_TRIGGER_RISING: + /* First Disable Falling Trigger on provided Lines */ + DDL_EINT_DisableFallingTrig_0_31(EINT_InitStruct->Line_0_31); + /* Then Enable Rising Trigger on provided Lines */ + DDL_EINT_EnableRisingTrig_0_31(EINT_InitStruct->Line_0_31); + break; + case DDL_EINT_TRIGGER_FALLING: + /* First Disable Rising Trigger on provided Lines */ + DDL_EINT_DisableRisingTrig_0_31(EINT_InitStruct->Line_0_31); + /* Then Enable Falling Trigger on provided Lines */ + DDL_EINT_EnableFallingTrig_0_31(EINT_InitStruct->Line_0_31); + break; + case DDL_EINT_TRIGGER_RISING_FALLING: + DDL_EINT_EnableRisingTrig_0_31(EINT_InitStruct->Line_0_31); + DDL_EINT_EnableFallingTrig_0_31(EINT_InitStruct->Line_0_31); + break; + default: + status = ERROR; + break; + } + } + } + } + /* DISABLE LineCommand */ + else + { + /* De-configure EINT Lines in range from 0 to 31 */ + DDL_EINT_DisableIT_0_31(EINT_InitStruct->Line_0_31); + DDL_EINT_DisableEvent_0_31(EINT_InitStruct->Line_0_31); + } + return status; +} + +/** + * @brief Set each @ref DDL_EINT_InitTypeDef field to default value. + * @param EINT_InitStruct Pointer to a @ref DDL_EINT_InitTypeDef structure. + * @retval None + */ +void DDL_EINT_StructInit(DDL_EINT_InitTypeDef *EINT_InitStruct) +{ + EINT_InitStruct->Line_0_31 = DDL_EINT_LINE_NONE; + EINT_InitStruct->LineCommand = DISABLE; + EINT_InitStruct->Mode = DDL_EINT_MODE_IT; + EINT_InitStruct->Trigger = DDL_EINT_TRIGGER_FALLING; +} + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#endif /* defined (EINT) */ + +/** + * @} + */ + +#endif /* USE_FULL_DDL_DRIVER */ + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_ddl_gpio.c b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_ddl_gpio.c new file mode 100644 index 0000000000..79987d8b2c --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_ddl_gpio.c @@ -0,0 +1,328 @@ +/** + * + * @file apm32f4xx_ddl_gpio.c + * @brief GPIO DDL module driver. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2017 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + * + */ +#if defined(USE_FULL_DDL_DRIVER) + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_ddl_gpio.h" +#include "apm32f4xx_ddl_bus.h" +#ifdef USE_FULL_ASSERT +#include "apm32_assert.h" +#else +#define ASSERT_PARAM(_PARAM_) ((void)(_PARAM_)) +#endif + +/** @addtogroup APM32F4xx_DDL_Driver + * @{ + */ + +#if defined (GPIOA) || defined (GPIOB) || defined (GPIOC) || defined (GPIOD) || defined (GPIOE) || defined (GPIOF) || defined (GPIOG) || defined (GPIOH) || defined (GPIOI) || defined (GPIOJ) || defined (GPIOK) + +/** @addtogroup GPIO_DDL + * @{ + */ + +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/* Private macros ------------------------------------------------------------*/ +/** @addtogroup GPIO_DDL_Private_Macros + * @{ + */ +#define IS_DDL_GPIO_PIN(__VALUE__) (((0x00000000U) < (__VALUE__)) && ((__VALUE__) <= (DDL_GPIO_PIN_ALL))) + +#define IS_DDL_GPIO_MODE(__VALUE__) (((__VALUE__) == DDL_GPIO_MODE_INPUT) ||\ + ((__VALUE__) == DDL_GPIO_MODE_OUTPUT) ||\ + ((__VALUE__) == DDL_GPIO_MODE_ALTERNATE) ||\ + ((__VALUE__) == DDL_GPIO_MODE_ANALOG)) + +#define IS_DDL_GPIO_OUTPUT_TYPE(__VALUE__) (((__VALUE__) == DDL_GPIO_OUTPUT_PUSHPULL) ||\ + ((__VALUE__) == DDL_GPIO_OUTPUT_OPENDRAIN)) + +#define IS_DDL_GPIO_SPEED(__VALUE__) (((__VALUE__) == DDL_GPIO_SPEED_FREQ_LOW) ||\ + ((__VALUE__) == DDL_GPIO_SPEED_FREQ_MEDIUM) ||\ + ((__VALUE__) == DDL_GPIO_SPEED_FREQ_HIGH) ||\ + ((__VALUE__) == DDL_GPIO_SPEED_FREQ_VERY_HIGH)) + +#define IS_DDL_GPIO_PULL(__VALUE__) (((__VALUE__) == DDL_GPIO_PULL_NO) ||\ + ((__VALUE__) == DDL_GPIO_PULL_UP) ||\ + ((__VALUE__) == DDL_GPIO_PULL_DOWN)) + +#define IS_DDL_GPIO_ALTERNATE(__VALUE__) (((__VALUE__) == DDL_GPIO_AF_0 ) ||\ + ((__VALUE__) == DDL_GPIO_AF_1 ) ||\ + ((__VALUE__) == DDL_GPIO_AF_2 ) ||\ + ((__VALUE__) == DDL_GPIO_AF_3 ) ||\ + ((__VALUE__) == DDL_GPIO_AF_4 ) ||\ + ((__VALUE__) == DDL_GPIO_AF_5 ) ||\ + ((__VALUE__) == DDL_GPIO_AF_6 ) ||\ + ((__VALUE__) == DDL_GPIO_AF_7 ) ||\ + ((__VALUE__) == DDL_GPIO_AF_8 ) ||\ + ((__VALUE__) == DDL_GPIO_AF_9 ) ||\ + ((__VALUE__) == DDL_GPIO_AF_10 ) ||\ + ((__VALUE__) == DDL_GPIO_AF_11 ) ||\ + ((__VALUE__) == DDL_GPIO_AF_12 ) ||\ + ((__VALUE__) == DDL_GPIO_AF_13 ) ||\ + ((__VALUE__) == DDL_GPIO_AF_14 ) ||\ + ((__VALUE__) == DDL_GPIO_AF_15 )) +/** + * @} + */ + +/* Private function prototypes -----------------------------------------------*/ + +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup GPIO_DDL_Exported_Functions + * @{ + */ + +/** @addtogroup GPIO_DDL_EF_Init + * @{ + */ + +/** + * @brief De-initialize GPIO registers (Registers restored to their default values). + * @param GPIOx GPIO Port + * @retval An ErrorStatus enumeration value: + * - SUCCESS: GPIO registers are de-initialized + * - ERROR: Wrong GPIO Port + */ +ErrorStatus DDL_GPIO_DeInit(GPIO_TypeDef *GPIOx) +{ + ErrorStatus status = SUCCESS; + + /* Check the parameters */ + ASSERT_PARAM(IS_GPIO_ALL_INSTANCE(GPIOx)); + + /* Force and Release reset on clock of GPIOx Port */ + if (GPIOx == GPIOA) + { + DDL_AHB1_GRP1_ForceReset(DDL_AHB1_GRP1_PERIPH_GPIOA); + DDL_AHB1_GRP1_ReleaseReset(DDL_AHB1_GRP1_PERIPH_GPIOA); + } + else if (GPIOx == GPIOB) + { + DDL_AHB1_GRP1_ForceReset(DDL_AHB1_GRP1_PERIPH_GPIOB); + DDL_AHB1_GRP1_ReleaseReset(DDL_AHB1_GRP1_PERIPH_GPIOB); + } + else if (GPIOx == GPIOC) + { + DDL_AHB1_GRP1_ForceReset(DDL_AHB1_GRP1_PERIPH_GPIOC); + DDL_AHB1_GRP1_ReleaseReset(DDL_AHB1_GRP1_PERIPH_GPIOC); + } +#if defined(GPIOD) + else if (GPIOx == GPIOD) + { + DDL_AHB1_GRP1_ForceReset(DDL_AHB1_GRP1_PERIPH_GPIOD); + DDL_AHB1_GRP1_ReleaseReset(DDL_AHB1_GRP1_PERIPH_GPIOD); + } +#endif /* GPIOD */ +#if defined(GPIOE) + else if (GPIOx == GPIOE) + { + DDL_AHB1_GRP1_ForceReset(DDL_AHB1_GRP1_PERIPH_GPIOE); + DDL_AHB1_GRP1_ReleaseReset(DDL_AHB1_GRP1_PERIPH_GPIOE); + } +#endif /* GPIOE */ +#if defined(GPIOF) + else if (GPIOx == GPIOF) + { + DDL_AHB1_GRP1_ForceReset(DDL_AHB1_GRP1_PERIPH_GPIOF); + DDL_AHB1_GRP1_ReleaseReset(DDL_AHB1_GRP1_PERIPH_GPIOF); + } +#endif /* GPIOF */ +#if defined(GPIOG) + else if (GPIOx == GPIOG) + { + DDL_AHB1_GRP1_ForceReset(DDL_AHB1_GRP1_PERIPH_GPIOG); + DDL_AHB1_GRP1_ReleaseReset(DDL_AHB1_GRP1_PERIPH_GPIOG); + } +#endif /* GPIOG */ +#if defined(GPIOH) + else if (GPIOx == GPIOH) + { + DDL_AHB1_GRP1_ForceReset(DDL_AHB1_GRP1_PERIPH_GPIOH); + DDL_AHB1_GRP1_ReleaseReset(DDL_AHB1_GRP1_PERIPH_GPIOH); + } +#endif /* GPIOH */ +#if defined(GPIOI) + else if (GPIOx == GPIOI) + { + DDL_AHB1_GRP1_ForceReset(DDL_AHB1_GRP1_PERIPH_GPIOI); + DDL_AHB1_GRP1_ReleaseReset(DDL_AHB1_GRP1_PERIPH_GPIOI); + } +#endif /* GPIOI */ +#if defined(GPIOJ) + else if (GPIOx == GPIOJ) + { + DDL_AHB1_GRP1_ForceReset(DDL_AHB1_GRP1_PERIPH_GPIOJ); + DDL_AHB1_GRP1_ReleaseReset(DDL_AHB1_GRP1_PERIPH_GPIOJ); + } +#endif /* GPIOJ */ +#if defined(GPIOK) + else if (GPIOx == GPIOK) + { + DDL_AHB1_GRP1_ForceReset(DDL_AHB1_GRP1_PERIPH_GPIOK); + DDL_AHB1_GRP1_ReleaseReset(DDL_AHB1_GRP1_PERIPH_GPIOK); + } +#endif /* GPIOK */ + else + { + status = ERROR; + } + + return (status); +} + +/** + * @brief Initialize GPIO registers according to the specified parameters in GPIO_InitStruct. + * @param GPIOx GPIO Port + * @param GPIO_InitStruct pointer to a @ref DDL_GPIO_InitTypeDef structure + * that contains the configuration information for the specified GPIO peripheral. + * @retval An ErrorStatus enumeration value: + * - SUCCESS: GPIO registers are initialized according to GPIO_InitStruct content + * - ERROR: Not applicable + */ +ErrorStatus DDL_GPIO_Init(GPIO_TypeDef *GPIOx, DDL_GPIO_InitTypeDef *GPIO_InitStruct) +{ + uint32_t pinpos = 0x00000000U; + uint32_t currentpin = 0x00000000U; + + /* Check the parameters */ + ASSERT_PARAM(IS_GPIO_ALL_INSTANCE(GPIOx)); + ASSERT_PARAM(IS_DDL_GPIO_PIN(GPIO_InitStruct->Pin)); + ASSERT_PARAM(IS_DDL_GPIO_MODE(GPIO_InitStruct->Mode)); + ASSERT_PARAM(IS_DDL_GPIO_PULL(GPIO_InitStruct->Pull)); + + /* ------------------------- Configure the port pins ---------------- */ + /* Initialize pinpos on first pin set */ + pinpos = POSITION_VAL(GPIO_InitStruct->Pin); + + /* Configure the port pins */ + while (((GPIO_InitStruct->Pin) >> pinpos) != 0x00000000U) + { + /* Get current io position */ + currentpin = (GPIO_InitStruct->Pin) & (0x00000001U << pinpos); + + if (currentpin) + { + + if ((GPIO_InitStruct->Mode == DDL_GPIO_MODE_OUTPUT) || (GPIO_InitStruct->Mode == DDL_GPIO_MODE_ALTERNATE)) + { + /* Check Speed mode parameters */ + ASSERT_PARAM(IS_DDL_GPIO_SPEED(GPIO_InitStruct->Speed)); + + /* Speed mode configuration */ + DDL_GPIO_SetPinSpeed(GPIOx, currentpin, GPIO_InitStruct->Speed); + + /* Check Output mode parameters */ + ASSERT_PARAM(IS_DDL_GPIO_OUTPUT_TYPE(GPIO_InitStruct->OutputType)); + + /* Output mode configuration*/ + DDL_GPIO_SetPinOutputType(GPIOx, currentpin, GPIO_InitStruct->OutputType); + } + + /* Pull-up Pull down resistor configuration*/ + DDL_GPIO_SetPinPull(GPIOx, currentpin, GPIO_InitStruct->Pull); + + if (GPIO_InitStruct->Mode == DDL_GPIO_MODE_ALTERNATE) + { + /* Check Alternate parameter */ + ASSERT_PARAM(IS_DDL_GPIO_ALTERNATE(GPIO_InitStruct->Alternate)); + + /* Speed mode configuration */ + if (POSITION_VAL(currentpin) < 0x00000008U) + { + DDL_GPIO_SetAFPin_0_7(GPIOx, currentpin, GPIO_InitStruct->Alternate); + } + else + { + DDL_GPIO_SetAFPin_8_15(GPIOx, currentpin, GPIO_InitStruct->Alternate); + } + } + + /* Pin Mode configuration */ + DDL_GPIO_SetPinMode(GPIOx, currentpin, GPIO_InitStruct->Mode); + } + pinpos++; + } + + return (SUCCESS); +} + +/** + * @brief Set each @ref DDL_GPIO_InitTypeDef field to default value. + * @param GPIO_InitStruct pointer to a @ref DDL_GPIO_InitTypeDef structure + * whose fields will be set to default values. + * @retval None + */ + +void DDL_GPIO_StructInit(DDL_GPIO_InitTypeDef *GPIO_InitStruct) +{ + /* Reset GPIO init structure parameters values */ + GPIO_InitStruct->Pin = DDL_GPIO_PIN_ALL; + GPIO_InitStruct->Mode = DDL_GPIO_MODE_ANALOG; + GPIO_InitStruct->Speed = DDL_GPIO_SPEED_FREQ_LOW; + GPIO_InitStruct->OutputType = DDL_GPIO_OUTPUT_PUSHPULL; + GPIO_InitStruct->Pull = DDL_GPIO_PULL_NO; + GPIO_InitStruct->Alternate = DDL_GPIO_AF_0; +} + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#endif /* defined (GPIOA) || defined (GPIOB) || defined (GPIOC) || defined (GPIOD) || defined (GPIOE) || defined (GPIOF) || defined (GPIOG) || defined (GPIOH) || defined (GPIOI) || defined (GPIOJ) || defined (GPIOK) */ + +/** + * @} + */ + +#endif /* USE_FULL_DDL_DRIVER */ + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_ddl_i2c.c b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_ddl_i2c.c new file mode 100644 index 0000000000..69edca787a --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_ddl_i2c.c @@ -0,0 +1,276 @@ +/** + * + * @file apm32f4xx_ddl_i2c.c + * @brief I2C DDL module driver. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + * + */ +#if defined(USE_FULL_DDL_DRIVER) + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_ddl_i2c.h" +#include "apm32f4xx_ddl_bus.h" +#include "apm32f4xx_ddl_rcm.h" +#ifdef USE_FULL_ASSERT +#include "apm32_assert.h" +#else +#define ASSERT_PARAM(_PARAM_) ((void)(_PARAM_)) +#endif + +/** @addtogroup APM32F4xx_DDL_Driver + * @{ + */ + +#if defined (I2C1) || defined (I2C2) || defined (I2C3) + +/** @defgroup I2C_DDL I2C + * @{ + */ + +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/* Private macros ------------------------------------------------------------*/ +/** @addtogroup I2C_DDL_Private_Macros + * @{ + */ + +#define IS_DDL_I2C_PERIPHERAL_MODE(__VALUE__) (((__VALUE__) == DDL_I2C_MODE_I2C) || \ + ((__VALUE__) == DDL_I2C_MODE_SMBUS_HOST) || \ + ((__VALUE__) == DDL_I2C_MODE_SMBUS_DEVICE) || \ + ((__VALUE__) == DDL_I2C_MODE_SMBUS_DEVICE_ARP)) + +#define IS_DDL_I2C_CLOCK_SPEED(__VALUE__) (((__VALUE__) > 0U) && ((__VALUE__) <= DDL_I2C_MAX_SPEED_FAST)) + +#define IS_DDL_I2C_DUTY_CYCLE(__VALUE__) (((__VALUE__) == DDL_I2C_DUTYCYCLE_2) || \ + ((__VALUE__) == DDL_I2C_DUTYCYCLE_16_9)) + +#if defined(I2C_FILTER_ANFDIS)&&defined(I2C_FILTER_DNFCFG) +#define IS_DDL_I2C_ANALOG_FILTER(__VALUE__) (((__VALUE__) == DDL_I2C_ANALOGFILTER_ENABLE) || \ + ((__VALUE__) == DDL_I2C_ANALOGFILTER_DISABLE)) + +#define IS_DDL_I2C_DIGITAL_FILTER(__VALUE__) ((__VALUE__) <= 0x0000000FU) + +#endif +#define IS_DDL_I2C_OWN_ADDRESS1(__VALUE__) ((__VALUE__) <= 0x000003FFU) + +#define IS_DDL_I2C_TYPE_ACKNOWLEDGE(__VALUE__) (((__VALUE__) == DDL_I2C_ACK) || \ + ((__VALUE__) == DDL_I2C_NACK)) + +#define IS_DDL_I2C_OWN_ADDRSIZE(__VALUE__) (((__VALUE__) == DDL_I2C_OWNADDRESS1_7BIT) || \ + ((__VALUE__) == DDL_I2C_OWNADDRESS1_10BIT)) +/** + * @} + */ + +/* Private function prototypes -----------------------------------------------*/ + +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup I2C_DDL_Exported_Functions + * @{ + */ + +/** @addtogroup I2C_DDL_EF_Init + * @{ + */ + +/** + * @brief De-initialize the I2C registers to their default reset values. + * @param I2Cx I2C Instance. + * @retval An ErrorStatus enumeration value: + * - SUCCESS I2C registers are de-initialized + * - ERROR I2C registers are not de-initialized + */ +uint32_t DDL_I2C_DeInit(I2C_TypeDef *I2Cx) +{ + ErrorStatus status = SUCCESS; + + /* Check the I2C Instance I2Cx */ + ASSERT_PARAM(IS_I2C_ALL_INSTANCE(I2Cx)); + + if (I2Cx == I2C1) + { + /* Force reset of I2C clock */ + DDL_APB1_GRP1_ForceReset(DDL_APB1_GRP1_PERIPH_I2C1); + + /* Release reset of I2C clock */ + DDL_APB1_GRP1_ReleaseReset(DDL_APB1_GRP1_PERIPH_I2C1); + } + else if (I2Cx == I2C2) + { + /* Force reset of I2C clock */ + DDL_APB1_GRP1_ForceReset(DDL_APB1_GRP1_PERIPH_I2C2); + + /* Release reset of I2C clock */ + DDL_APB1_GRP1_ReleaseReset(DDL_APB1_GRP1_PERIPH_I2C2); + + } +#if defined(I2C3) + else if (I2Cx == I2C3) + { + /* Force reset of I2C clock */ + DDL_APB1_GRP1_ForceReset(DDL_APB1_GRP1_PERIPH_I2C3); + + /* Release reset of I2C clock */ + DDL_APB1_GRP1_ReleaseReset(DDL_APB1_GRP1_PERIPH_I2C3); + } +#endif + else + { + status = ERROR; + } + + return status; +} + +/** + * @brief Initialize the I2C registers according to the specified parameters in I2C_InitStruct. + * @param I2Cx I2C Instance. + * @param I2C_InitStruct pointer to a @ref DDL_I2C_InitTypeDef structure. + * @retval An ErrorStatus enumeration value: + * - SUCCESS I2C registers are initialized + * - ERROR Not applicable + */ +uint32_t DDL_I2C_Init(I2C_TypeDef *I2Cx, DDL_I2C_InitTypeDef *I2C_InitStruct) +{ + DDL_RCM_ClocksTypeDef rcc_clocks; + + /* Check the I2C Instance I2Cx */ + ASSERT_PARAM(IS_I2C_ALL_INSTANCE(I2Cx)); + + /* Check the I2C parameters from I2C_InitStruct */ + ASSERT_PARAM(IS_DDL_I2C_PERIPHERAL_MODE(I2C_InitStruct->PeripheralMode)); + ASSERT_PARAM(IS_DDL_I2C_CLOCK_SPEED(I2C_InitStruct->ClockSpeed)); + ASSERT_PARAM(IS_DDL_I2C_DUTY_CYCLE(I2C_InitStruct->DutyCycle)); +#if defined(I2C_FILTER_ANFDIS)&&defined(I2C_FILTER_DNFCFG) + ASSERT_PARAM(IS_DDL_I2C_ANALOG_FILTER(I2C_InitStruct->AnalogFilter)); + ASSERT_PARAM(IS_DDL_I2C_DIGITAL_FILTER(I2C_InitStruct->DigitalFilter)); +#endif + ASSERT_PARAM(IS_DDL_I2C_OWN_ADDRESS1(I2C_InitStruct->OwnAddress1)); + ASSERT_PARAM(IS_DDL_I2C_TYPE_ACKNOWLEDGE(I2C_InitStruct->TypeAcknowledge)); + ASSERT_PARAM(IS_DDL_I2C_OWN_ADDRSIZE(I2C_InitStruct->OwnAddrSize)); + + /* Disable the selected I2Cx Peripheral */ + DDL_I2C_Disable(I2Cx); + + /* Retrieve Clock frequencies */ + DDL_RCM_GetSystemClocksFreq(&rcc_clocks); + +#if defined(I2C_FILTER_ANFDIS)&&defined(I2C_FILTER_DNFCFG) + /*---------------------------- I2Cx FLTR Configuration ----------------------- + * Configure the analog and digital noise filters with parameters : + * - AnalogFilter: I2C_FLTR_ANFOFF bit + * - DigitalFilter: I2C_FILTER_DNFCFG[3:0] bits + */ + DDL_I2C_ConfigFilters(I2Cx, I2C_InitStruct->AnalogFilter, I2C_InitStruct->DigitalFilter); + +#endif + /*---------------------------- I2Cx SCL Clock Speed Configuration ------------ + * Configure the SCL speed : + * - ClockSpeed: I2C_CTRL2_CLKFCFG[5:0], I2C_RISETMAX_RISETMAX[5:0], I2C_CLKCTRL_SPEEDCFG, + * and I2C_CLKCTRL_CLKS[11:0] bits + * - DutyCycle: I2C_CLKCTRL_FDUTYCFG[7:0] bits + */ + DDL_I2C_ConfigSpeed(I2Cx, rcc_clocks.PCLK1_Frequency, I2C_InitStruct->ClockSpeed, I2C_InitStruct->DutyCycle); + + /*---------------------------- I2Cx OAR1 Configuration ----------------------- + * Disable, Configure and Enable I2Cx device own address 1 with parameters : + * - OwnAddress1: I2C_SADDR1_ADDR[9:8], I2C_SADDR1_ADDR[7:1] and I2C_SADDR1_ADDR0 bits + * - OwnAddrSize: I2C_SADDR1_ADDRLEN bit + */ + DDL_I2C_SetOwnAddress1(I2Cx, I2C_InitStruct->OwnAddress1, I2C_InitStruct->OwnAddrSize); + + /*---------------------------- I2Cx MODE Configuration ----------------------- + * Configure I2Cx peripheral mode with parameter : + * - PeripheralMode: I2C_CTRL1_SMBEN, I2C_CTRL1_SMBTCFG and I2C_CTRL1_ARPEN bits + */ + DDL_I2C_SetMode(I2Cx, I2C_InitStruct->PeripheralMode); + + /* Enable the selected I2Cx Peripheral */ + DDL_I2C_Enable(I2Cx); + + /*---------------------------- I2Cx CTRL2 Configuration ------------------------ + * Configure the ACKnowledge or Non ACKnowledge condition + * after the address receive match code or next received byte with parameter : + * - TypeAcknowledge: I2C_CTRL2_NACK bit + */ + DDL_I2C_AcknowledgeNextData(I2Cx, I2C_InitStruct->TypeAcknowledge); + + return SUCCESS; +} + +/** + * @brief Set each @ref DDL_I2C_InitTypeDef field to default value. + * @param I2C_InitStruct Pointer to a @ref DDL_I2C_InitTypeDef structure. + * @retval None + */ +void DDL_I2C_StructInit(DDL_I2C_InitTypeDef *I2C_InitStruct) +{ + /* Set I2C_InitStruct fields to default values */ + I2C_InitStruct->PeripheralMode = DDL_I2C_MODE_I2C; + I2C_InitStruct->ClockSpeed = 5000U; + I2C_InitStruct->DutyCycle = DDL_I2C_DUTYCYCLE_2; +#if defined(I2C_FILTER_ANFDIS)&&defined(I2C_FILTER_DNFCFG) + I2C_InitStruct->AnalogFilter = DDL_I2C_ANALOGFILTER_ENABLE; + I2C_InitStruct->DigitalFilter = 0U; +#endif + I2C_InitStruct->OwnAddress1 = 0U; + I2C_InitStruct->TypeAcknowledge = DDL_I2C_NACK; + I2C_InitStruct->OwnAddrSize = DDL_I2C_OWNADDRESS1_7BIT; +} + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#endif /* I2C1 || I2C2 || I2C3 */ + +/** + * @} + */ + +#endif /* USE_FULL_DDL_DRIVER */ + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_ddl_pmu.c b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_ddl_pmu.c new file mode 100644 index 0000000000..9b8964fac4 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_ddl_pmu.c @@ -0,0 +1,106 @@ +/** + * + * @file apm32f4xx_ddl_pmu.c + * @brief PMU DDL module driver. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2017 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file in + * the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + */ +#if defined(USE_FULL_DDL_DRIVER) + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_ddl_pmu.h" +#include "apm32f4xx_ddl_bus.h" + +/** @addtogroup APM32F4xx_DDL_Driver + * @{ + */ + +#if defined(PMU) + +/** @defgroup PMU_DDL PMU + * @{ + */ + +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/* Private macros ------------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ + +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup PMU_DDL_Exported_Functions + * @{ + */ + +/** @addtogroup PMU_DDL_EF_Init + * @{ + */ + +/** + * @brief De-initialize the PMU registers to their default reset values. + * @retval An ErrorStatus enumeration value: + * - SUCCESS: PMU registers are de-initialized + * - ERROR: not applicable + */ +ErrorStatus DDL_PMU_DeInit(void) +{ + /* Force reset of PMU clock */ + DDL_APB1_GRP1_ForceReset(DDL_APB1_GRP1_PERIPH_PMU); + + /* Release reset of PMU clock */ + DDL_APB1_GRP1_ReleaseReset(DDL_APB1_GRP1_PERIPH_PMU); + + return SUCCESS; +} + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ +#endif /* defined(PMU) */ +/** + * @} + */ + +#endif /* USE_FULL_DDL_DRIVER */ diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_ddl_rcm.c b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_ddl_rcm.c new file mode 100644 index 0000000000..ff80de6f14 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_ddl_rcm.c @@ -0,0 +1,671 @@ +/** + * + * @file apm32f4xx_ddl_rcm.c + * @brief RCM DDL module driver. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2017 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file in + * the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + */ +#if defined(USE_FULL_DDL_DRIVER) + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_ddl_rcm.h" +#ifdef USE_FULL_ASSERT + #include "apm32_assert.h" +#else + #define ASSERT_PARAM(_PARAM_) ((void)(_PARAM_)) +#endif +/** @addtogroup APM32F4xx_DDL_Driver + * @{ + */ + +#if defined(RCM) + +/** @addtogroup RCM_DDL + * @{ + */ + +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/* Private macros ------------------------------------------------------------*/ +/** @addtogroup RCM_DDL_Private_Macros + * @{ + */ + +#if defined(SDIO) +#define IS_DDL_RCM_SDIO_CLKSOURCE(__VALUE__) (((__VALUE__) == DDL_RCM_SDIO_CLKSOURCE)) +#endif /* SDIO */ + +#if defined(RNG) +#define IS_DDL_RCM_RNG_CLKSOURCE(__VALUE__) (((__VALUE__) == DDL_RCM_RNG_CLKSOURCE)) +#endif /* RNG */ + +#if defined(USB_OTG_FS) || defined(USB_OTG_HS) +#define IS_DDL_RCM_USB_CLKSOURCE(__VALUE__) (((__VALUE__) == DDL_RCM_USB_CLKSOURCE)) +#endif /* USB_OTG_FS || USB_OTG_HS */ + +#if defined(RCM_DCKCFGR_I2S2SRC) +#define IS_DDL_RCM_I2S_CLKSOURCE(__VALUE__) (((__VALUE__) == DDL_RCM_I2S1_CLKSOURCE) \ + || ((__VALUE__) == DDL_RCM_I2S2_CLKSOURCE)) +#else +#define IS_DDL_RCM_I2S_CLKSOURCE(__VALUE__) (((__VALUE__) == DDL_RCM_I2S1_CLKSOURCE)) +#endif /* RCM_DCKCFGR_I2S2SRC */ + +/** + * @} + */ + +/* Private function prototypes -----------------------------------------------*/ +/** @defgroup RCM_DDL_Private_Functions RCM Private functions + * @{ + */ +uint32_t RCM_GetSystemClockFreq(void); +uint32_t RCM_GetHCLKClockFreq(uint32_t SYSCLK_Frequency); +uint32_t RCM_GetPCLK1ClockFreq(uint32_t HCLK_Frequency); +uint32_t RCM_GetPCLK2ClockFreq(uint32_t HCLK_Frequency); +uint32_t RCM_PLL_GetFreqDomain_SYS(uint32_t SYSCLK_Source); +uint32_t RCM_PLL_GetFreqDomain_48M(void); + +#if defined(RCM_PLLI2S_SUPPORT) +uint32_t RCM_PLLI2S_GetFreqDomain_I2S(void); +#endif /* RCM_PLLI2S_SUPPORT */ +/** + * @} + */ + + +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup RCM_DDL_Exported_Functions + * @{ + */ + +/** @addtogroup RCM_DDL_EF_Init + * @{ + */ + +/** + * @brief Reset the RCM clock configuration to the default reset state. + * @note The default reset state of the clock configuration is given below: + * - HSI ON and used as system clock source + * - HSE and PLL OFF + * - AHB, APB1 and APB2 prescaler set to 1. + * - CSS, MCO OFF + * - All interrupts disabled + * @note This function doesn't modify the configuration of the + * - Peripheral clocks + * - LSI, LSE and RTC clocks + * @retval An ErrorStatus enumeration value: + * - SUCCESS: RCM registers are de-initialized + * - ERROR: not applicable + */ +ErrorStatus DDL_RCM_DeInit(void) +{ + __IO uint32_t vl_mask; + + /* Set HSIEN bit */ + DDL_RCM_HSI_Enable(); + + /* Wait for HSI READY bit */ + while(DDL_RCM_HSI_IsReady() != 1U) + {} + + /* Reset CFG register */ + DDL_RCM_WriteReg(CFG, 0x00000000U); + + /* Read CTRL register */ + vl_mask = DDL_RCM_ReadReg(CTRL); + + /* Reset HSEEN, HSEBCFG, PLL1EN, CSSEN bits */ + CLEAR_BIT(vl_mask, + (RCM_CTRL_HSEEN | RCM_CTRL_HSEBCFG | RCM_CTRL_PLL1EN | RCM_CTRL_CSSEN)); + +#if defined(RCM_PLLI2S_SUPPORT) + /* Reset PLL2EN bit */ + CLEAR_BIT(vl_mask, RCM_CTRL_PLL2EN); +#endif /* RCM_PLLI2S_SUPPORT */ + + /* Write new value in CTRL register */ + DDL_RCM_WriteReg(CTRL, vl_mask); + + /* Set HSITRM bits to the reset value*/ + DDL_RCM_HSI_SetCalibTrimming(0x10U); + + /* Wait for PLL READY bit to be reset */ + while(DDL_RCM_PLL_IsReady() != 0U) + {} + + /* Reset PLL1CFG register */ + DDL_RCM_WriteReg(PLL1CFG, RCM_PLL1CFG_RST_VALUE); + +#if defined(RCM_PLLI2S_SUPPORT) + /* Reset PLL2CFG register */ + DDL_RCM_WriteReg(PLL2CFG, RCM_PLL2CFG_RST_VALUE); +#endif /* RCM_PLLI2S_SUPPORT */ + + /* Disable all interrupts */ + CLEAR_BIT(RCM->INT, RCM_INT_LSIRDYEN | RCM_INT_LSERDYEN | RCM_INT_HSIRDYEN | RCM_INT_HSERDYEN | RCM_INT_PLL1RDYEN); + +#if defined(RCM_INT_PLL2RDYEN) + CLEAR_BIT(RCM->INT, RCM_INT_PLL2RDYEN); +#endif /* RCM_INT_PLL2RDYEN */ + + /* Clear all interrupt flags */ + SET_BIT(RCM->INT, RCM_INT_LSIRDYCLR | RCM_INT_LSERDYCLR | RCM_INT_HSIRDYCLR | RCM_INT_HSERDYCLR | RCM_INT_PLL1RDYCLR | RCM_INT_CSSCLR); + +#if defined(RCM_INT_PLL2RDYCLR) + SET_BIT(RCM->INT, RCM_INT_PLL2RDYCLR); +#endif /* RCM_INT_PLL2RDYCLR */ + + /* Clear LSIEN bit */ + CLEAR_BIT(RCM->CSTS, RCM_CSTS_LSIEN); + + /* Reset all RSTFLGCLR flags */ + SET_BIT(RCM->CSTS, RCM_CSTS_RSTFLGCLR); + + return SUCCESS; +} + +/** + * @} + */ + +/** @addtogroup RCM_DDL_EF_Get_Freq + * @brief Return the frequencies of different on chip clocks; System, AHB, APB1 and APB2 buses clocks + * and different peripheral clocks available on the device. + * @note If SYSCLK source is HSI, function returns values based on HSI_VALUE(**) + * @note If SYSCLK source is HSE, function returns values based on HSE_VALUE(***) + * @note If SYSCLK source is PLL, function returns values based on HSE_VALUE(***) + * or HSI_VALUE(**) multiplied/divided by the PLL factors. + * @note (**) HSI_VALUE is a constant defined in this file (default value + * 16 MHz) but the real value may vary depending on the variations + * in voltage and temperature. + * @note (***) HSE_VALUE is a constant defined in this file (default value + * 25 MHz), user has to ensure that HSE_VALUE is same as the real + * frequency of the crystal used. Otherwise, this function may + * have wrong result. + * @note The result of this function could be incorrect when using fractional + * value for HSE crystal. + * @note This function can be used by the user application to compute the + * baud-rate for the communication peripherals or configure other parameters. + * @{ + */ + +/** + * @brief Return the frequencies of different on chip clocks; System, AHB, APB1 and APB2 buses clocks + * @note Each time SYSCLK, HCLK, PCLK1 and/or PCLK2 clock changes, this function + * must be called to update structure fields. Otherwise, any + * configuration based on this function will be incorrect. + * @param RCM_Clocks pointer to a @ref DDL_RCM_ClocksTypeDef structure which will hold the clocks frequencies + * @retval None + */ +void DDL_RCM_GetSystemClocksFreq(DDL_RCM_ClocksTypeDef *RCM_Clocks) +{ + /* Get SYSCLK frequency */ + RCM_Clocks->SYSCLK_Frequency = RCM_GetSystemClockFreq(); + + /* HCLK clock frequency */ + RCM_Clocks->HCLK_Frequency = RCM_GetHCLKClockFreq(RCM_Clocks->SYSCLK_Frequency); + + /* PCLK1 clock frequency */ + RCM_Clocks->PCLK1_Frequency = RCM_GetPCLK1ClockFreq(RCM_Clocks->HCLK_Frequency); + + /* PCLK2 clock frequency */ + RCM_Clocks->PCLK2_Frequency = RCM_GetPCLK2ClockFreq(RCM_Clocks->HCLK_Frequency); +} + +/** + * @brief Return I2Sx clock frequency + * @param I2SxSource This parameter can be one of the following values: + * @arg @ref DDL_RCM_I2S1_CLKSOURCE + * @arg @ref DDL_RCM_I2S2_CLKSOURCE (*) + * + * (*) value not defined in all devices. + * @retval I2S clock frequency (in Hz) + * - @ref DDL_RCM_PERIPH_FREQUENCY_NO indicates that oscillator is not ready + */ +uint32_t DDL_RCM_GetI2SClockFreq(uint32_t I2SxSource) +{ + uint32_t i2s_frequency = DDL_RCM_PERIPH_FREQUENCY_NO; + + /* Check parameter */ + ASSERT_PARAM(IS_DDL_RCM_I2S_CLKSOURCE(I2SxSource)); + + if (I2SxSource == DDL_RCM_I2S1_CLKSOURCE) + { + /* I2S1 CLK clock frequency */ + switch (DDL_RCM_GetI2SClockSource(I2SxSource)) + { +#if defined(RCM_PLLI2S_SUPPORT) + case DDL_RCM_I2S1_CLKSOURCE_PLLI2S: /* I2S1 Clock is PLLI2S */ + if (DDL_RCM_PLLI2S_IsReady()) + { + i2s_frequency = RCM_PLLI2S_GetFreqDomain_I2S(); + } + break; +#endif /* RCM_PLLI2S_SUPPORT */ + + case DDL_RCM_I2S1_CLKSOURCE_PIN: /* I2S1 Clock is External clock */ + default: + i2s_frequency = EXTERNAL_CLOCK_VALUE; + break; + } + } + + return i2s_frequency; +} + +#if defined(SDIO) +/** + * @brief Return SDIOx clock frequency + * @param SDIOxSource This parameter can be one of the following values: + * @arg @ref DDL_RCM_SDIO_CLKSOURCE + * @retval SDIO clock frequency (in Hz) + * - @ref DDL_RCM_PERIPH_FREQUENCY_NO indicates that oscillator is not ready + */ +uint32_t DDL_RCM_GetSDIOClockFreq(uint32_t SDIOxSource) +{ + uint32_t SDIO_frequency = DDL_RCM_PERIPH_FREQUENCY_NO; + + /* Check parameter */ + ASSERT_PARAM(IS_DDL_RCM_SDIO_CLKSOURCE(SDIOxSource)); + + if (SDIOxSource == DDL_RCM_SDIO_CLKSOURCE) + { +#if defined(RCM_DCKCFGR_SDIOSEL) || defined(RCM_DCKCFGR2_SDIOSEL) + /* SDIOCLK clock frequency */ + switch (DDL_RCM_GetSDIOClockSource(SDIOxSource)) + { + case DDL_RCM_SDIO_CLKSOURCE_PLL48CLK: /* PLL48M clock used as SDIO clock source */ + switch (DDL_RCM_GetCK48MClockSource(DDL_RCM_CK48M_CLKSOURCE)) + { + case DDL_RCM_CK48M_CLKSOURCE_PLL: /* PLL clock used as 48Mhz domain clock */ + if (DDL_RCM_PLL_IsReady()) + { + SDIO_frequency = RCM_PLL_GetFreqDomain_48M(); + } + break; + +#if defined(RCM_PLLSAI_SUPPORT) + case DDL_RCM_CK48M_CLKSOURCE_PLLSAI: /* PLLSAI clock used as 48Mhz domain clock */ + default: + if (DDL_RCM_PLLSAI_IsReady()) + { + SDIO_frequency = RCM_PLLSAI_GetFreqDomain_48M(); + } + break; +#endif /* RCM_PLLSAI_SUPPORT */ + +#if defined(RCM_PLL2CFG_PLLI2SQ) && !defined(RCM_DCKCFGR_PLLI2SDIVQ) + case DDL_RCM_CK48M_CLKSOURCE_PLLI2S: /* PLLI2S clock used as 48Mhz domain clock */ + default: + if (DDL_RCM_PLLI2S_IsReady()) + { + SDIO_frequency = RCM_PLLI2S_GetFreqDomain_48M(); + } + break; +#endif /* RCM_PLL2CFG_PLLI2SQ && !RCM_DCKCFGR_PLLI2SDIVQ */ + } + break; + + case DDL_RCM_SDIO_CLKSOURCE_SYSCLK: /* PLL clock used as SDIO clock source */ + default: + SDIO_frequency = RCM_GetSystemClockFreq(); + break; + } +#else + /* PLL clock used as 48Mhz domain clock */ + if (DDL_RCM_PLL_IsReady()) + { + SDIO_frequency = RCM_PLL_GetFreqDomain_48M(); + } +#endif /* RCM_DCKCFGR_SDIOSEL || RCM_DCKCFGR2_SDIOSEL */ + } + + return SDIO_frequency; +} +#endif /* SDIO */ + +#if defined(RNG) +/** + * @brief Return RNGx clock frequency + * @param RNGxSource This parameter can be one of the following values: + * @arg @ref DDL_RCM_RNG_CLKSOURCE + * @retval RNG clock frequency (in Hz) + * - @ref DDL_RCM_PERIPH_FREQUENCY_NO indicates that oscillator is not ready + */ +uint32_t DDL_RCM_GetRNGClockFreq(uint32_t RNGxSource) +{ + uint32_t rng_frequency = DDL_RCM_PERIPH_FREQUENCY_NO; + + /* Check parameter */ + ASSERT_PARAM(IS_DDL_RCM_RNG_CLKSOURCE(RNGxSource)); + +#if defined(RCM_DCKCFGR_CK48MSEL) || defined(RCM_DCKCFGR2_CK48MSEL) + /* RNGCLK clock frequency */ + switch (DDL_RCM_GetRNGClockSource(RNGxSource)) + { +#if defined(RCM_PLL2CFG_PLLI2SQ) && !defined(RCM_DCKCFGR_PLLI2SDIVQ) + case DDL_RCM_RNG_CLKSOURCE_PLLI2S: /* PLLI2S clock used as RNG clock source */ + if (DDL_RCM_PLLI2S_IsReady()) + { + rng_frequency = RCM_PLLI2S_GetFreqDomain_48M(); + } + break; +#endif /* RCM_PLL2CFG_PLLI2SQ && !RCM_DCKCFGR_PLLI2SDIVQ */ + +#if defined(RCM_PLLSAI_SUPPORT) + case DDL_RCM_RNG_CLKSOURCE_PLLSAI: /* PLLSAI clock used as RNG clock source */ + if (DDL_RCM_PLLSAI_IsReady()) + { + rng_frequency = RCM_PLLSAI_GetFreqDomain_48M(); + } + break; +#endif /* RCM_PLLSAI_SUPPORT */ + + case DDL_RCM_RNG_CLKSOURCE_PLL: /* PLL clock used as RNG clock source */ + default: + if (DDL_RCM_PLL_IsReady()) + { + rng_frequency = RCM_PLL_GetFreqDomain_48M(); + } + break; + } +#else + /* PLL clock used as RNG clock source */ + if (DDL_RCM_PLL_IsReady()) + { + rng_frequency = RCM_PLL_GetFreqDomain_48M(); + } +#endif /* RCM_DCKCFGR_CK48MSEL || RCM_DCKCFGR2_CK48MSEL */ + + return rng_frequency; +} +#endif /* RNG */ + +#if defined(USB_OTG_FS) || defined(USB_OTG_HS) +/** + * @brief Return USBx clock frequency + * @param USBxSource This parameter can be one of the following values: + * @arg @ref DDL_RCM_USB_CLKSOURCE + * @retval USB clock frequency (in Hz) + * - @ref DDL_RCM_PERIPH_FREQUENCY_NO indicates that oscillator is not ready + */ +uint32_t DDL_RCM_GetUSBClockFreq(uint32_t USBxSource) +{ + uint32_t usb_frequency = DDL_RCM_PERIPH_FREQUENCY_NO; + + /* Check parameter */ + ASSERT_PARAM(IS_DDL_RCM_USB_CLKSOURCE(USBxSource)); + +#if defined(RCM_DCKCFGR_CK48MSEL) || defined(RCM_DCKCFGR2_CK48MSEL) + /* USBCLK clock frequency */ + switch (DDL_RCM_GetUSBClockSource(USBxSource)) + { +#if defined(RCM_PLL2CFG_PLLI2SQ) && !defined(RCM_DCKCFGR_PLLI2SDIVQ) + case DDL_RCM_USB_CLKSOURCE_PLLI2S: /* PLLI2S clock used as USB clock source */ + if (DDL_RCM_PLLI2S_IsReady()) + { + usb_frequency = RCM_PLLI2S_GetFreqDomain_48M(); + } + break; + +#endif /* RCM_PLL2CFG_PLLI2SQ && !RCM_DCKCFGR_PLLI2SDIVQ */ + +#if defined(RCM_PLLSAI_SUPPORT) + case DDL_RCM_USB_CLKSOURCE_PLLSAI: /* PLLSAI clock used as USB clock source */ + if (DDL_RCM_PLLSAI_IsReady()) + { + usb_frequency = RCM_PLLSAI_GetFreqDomain_48M(); + } + break; +#endif /* RCM_PLLSAI_SUPPORT */ + + case DDL_RCM_USB_CLKSOURCE_PLL: /* PLL clock used as USB clock source */ + default: + if (DDL_RCM_PLL_IsReady()) + { + usb_frequency = RCM_PLL_GetFreqDomain_48M(); + } + break; + } +#else + /* PLL clock used as USB clock source */ + if (DDL_RCM_PLL_IsReady()) + { + usb_frequency = RCM_PLL_GetFreqDomain_48M(); + } +#endif /* RCM_DCKCFGR_CK48MSEL || RCM_DCKCFGR2_CK48MSEL */ + + return usb_frequency; +} +#endif /* USB_OTG_FS || USB_OTG_HS */ + +/** + * @} + */ + +/** + * @} + */ + +/** @addtogroup RCM_DDL_Private_Functions + * @{ + */ + +/** + * @brief Return SYSTEM clock frequency + * @retval SYSTEM clock frequency (in Hz) + */ +uint32_t RCM_GetSystemClockFreq(void) +{ + uint32_t frequency = 0U; + + /* Get SYSCLK source -------------------------------------------------------*/ + switch (DDL_RCM_GetSysClkSource()) + { + case DDL_RCM_SYS_CLKSOURCE_STATUS_HSI: /* HSI used as system clock source */ + frequency = HSI_VALUE; + break; + + case DDL_RCM_SYS_CLKSOURCE_STATUS_HSE: /* HSE used as system clock source */ + frequency = HSE_VALUE; + break; + + case DDL_RCM_SYS_CLKSOURCE_STATUS_PLL: /* PLL used as system clock source */ + frequency = RCM_PLL_GetFreqDomain_SYS(DDL_RCM_SYS_CLKSOURCE_STATUS_PLL); + break; + + default: + frequency = HSI_VALUE; + break; + } + + return frequency; +} + +/** + * @brief Return HCLK clock frequency + * @param SYSCLK_Frequency SYSCLK clock frequency + * @retval HCLK clock frequency (in Hz) + */ +uint32_t RCM_GetHCLKClockFreq(uint32_t SYSCLK_Frequency) +{ + /* HCLK clock frequency */ + return __DDL_RCM_CALC_HCLK_FREQ(SYSCLK_Frequency, DDL_RCM_GetAHBPrescaler()); +} + +/** + * @brief Return PCLK1 clock frequency + * @param HCLK_Frequency HCLK clock frequency + * @retval PCLK1 clock frequency (in Hz) + */ +uint32_t RCM_GetPCLK1ClockFreq(uint32_t HCLK_Frequency) +{ + /* PCLK1 clock frequency */ + return __DDL_RCM_CALC_PCLK1_FREQ(HCLK_Frequency, DDL_RCM_GetAPB1Prescaler()); +} + +/** + * @brief Return PCLK2 clock frequency + * @param HCLK_Frequency HCLK clock frequency + * @retval PCLK2 clock frequency (in Hz) + */ +uint32_t RCM_GetPCLK2ClockFreq(uint32_t HCLK_Frequency) +{ + /* PCLK2 clock frequency */ + return __DDL_RCM_CALC_PCLK2_FREQ(HCLK_Frequency, DDL_RCM_GetAPB2Prescaler()); +} + +/** + * @brief Return PLL clock frequency used for system domain + * @param SYSCLK_Source System clock source + * @retval PLL clock frequency (in Hz) + */ +uint32_t RCM_PLL_GetFreqDomain_SYS(uint32_t SYSCLK_Source) +{ + uint32_t pllinputfreq = 0U, pllsource = 0U, plloutputfreq = 0U; + + /* PLL_VCO = (HSE_VALUE or HSI_VALUE / PLLB) * PLL1A + SYSCLK = PLL_VCO / (PLL1C or PLLR) + */ + pllsource = DDL_RCM_PLL_GetMainSource(); + + switch (pllsource) + { + case DDL_RCM_PLLSOURCE_HSI: /* HSI used as PLL clock source */ + pllinputfreq = HSI_VALUE; + break; + + case DDL_RCM_PLLSOURCE_HSE: /* HSE used as PLL clock source */ + pllinputfreq = HSE_VALUE; + break; + + default: + pllinputfreq = HSI_VALUE; + break; + } + + if (SYSCLK_Source == DDL_RCM_SYS_CLKSOURCE_STATUS_PLL) + { + plloutputfreq = __DDL_RCM_CALC_PLLCLK_FREQ(pllinputfreq, DDL_RCM_PLL_GetDivider(), + DDL_RCM_PLL_GetN(), DDL_RCM_PLL_GetP()); + } + + return plloutputfreq; +} + +/** + * @brief Return PLL clock frequency used for 48 MHz domain + * @retval PLL clock frequency (in Hz) + */ +uint32_t RCM_PLL_GetFreqDomain_48M(void) +{ + uint32_t pllinputfreq = 0U, pllsource = 0U; + + /* PLL_VCO = (HSE_VALUE or HSI_VALUE / PLLB ) * PLL1A + 48M Domain clock = PLL_VCO / PLLD + */ + pllsource = DDL_RCM_PLL_GetMainSource(); + + switch (pllsource) + { + case DDL_RCM_PLLSOURCE_HSI: /* HSI used as PLL clock source */ + pllinputfreq = HSI_VALUE; + break; + + case DDL_RCM_PLLSOURCE_HSE: /* HSE used as PLL clock source */ + pllinputfreq = HSE_VALUE; + break; + + default: + pllinputfreq = HSI_VALUE; + break; + } + return __DDL_RCM_CALC_PLLCLK_48M_FREQ(pllinputfreq, DDL_RCM_PLL_GetDivider(), + DDL_RCM_PLL_GetN(), DDL_RCM_PLL_GetQ()); +} + +#if defined(RCM_PLLI2S_SUPPORT) + +/** + * @brief Return PLLI2S clock frequency used for I2S domain + * @retval PLLI2S clock frequency (in Hz) + */ +uint32_t RCM_PLLI2S_GetFreqDomain_I2S(void) +{ + uint32_t plli2sinputfreq = 0U, plli2ssource = 0U, plli2soutputfreq = 0U; + + /* PLLI2S_VCO = (HSE_VALUE or HSI_VALUE / PLL2B) * PLL2A + I2S Domain clock = PLLI2S_VCO / PLL2C + */ + plli2ssource = DDL_RCM_PLLI2S_GetMainSource(); + + switch (plli2ssource) + { + case DDL_RCM_PLLSOURCE_HSE: /* HSE used as PLLI2S clock source */ + plli2sinputfreq = HSE_VALUE; + break; + + case DDL_RCM_PLLSOURCE_HSI: /* HSI used as PLLI2S clock source */ + default: + plli2sinputfreq = HSI_VALUE; + break; + } + + plli2soutputfreq = __DDL_RCM_CALC_PLLI2S_I2S_FREQ(plli2sinputfreq, DDL_RCM_PLLI2S_GetDivider(), + DDL_RCM_PLLI2S_GetN(), DDL_RCM_PLLI2S_GetR()); + + return plli2soutputfreq; +} + +#endif /* RCM_PLLI2S_SUPPORT */ +/** + * @} + */ + +/** + * @} + */ + +#endif /* defined(RCM) */ + +/** + * @} + */ + +#endif /* USE_FULL_DDL_DRIVER */ + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_ddl_rng.c b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_ddl_rng.c new file mode 100644 index 0000000000..b91a43fb19 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_ddl_rng.c @@ -0,0 +1,136 @@ +/** + * + * @file apm32f4xx_ddl_rng.c + * @brief RNG DDL module driver. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + * + */ +#if defined(USE_FULL_DDL_DRIVER) + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_ddl_rng.h" +#include "apm32f4xx_ddl_bus.h" + +#ifdef USE_FULL_ASSERT +#include "apm32_assert.h" +#else +#define ASSERT_PARAM(_PARAM_) ((void)(_PARAM_)) +#endif /* USE_FULL_ASSERT */ + +/** @addtogroup APM32F4xx_DDL_Driver + * @{ + */ + +#if defined (RNG) + +/** @addtogroup RNG_DDL + * @{ + */ + +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/* Private macros ------------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ + +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup RNG_DDL_Exported_Functions + * @{ + */ + +/** @addtogroup RNG_DDL_EF_Init + * @{ + */ + +/** + * @brief De-initialize RNG registers (Registers restored to their default values). + * @param RNGx RNG Instance + * @retval An ErrorStatus enumeration value: + * - SUCCESS: RNG registers are de-initialized + * - ERROR: not applicable + */ +ErrorStatus DDL_RNG_DeInit(RNG_TypeDef *RNGx) +{ + ErrorStatus status = SUCCESS; + + /* Check the parameters */ + ASSERT_PARAM(IS_RNG_ALL_INSTANCE(RNGx)); + if (RNGx == RNG) + { +#if !defined(RCM_AHB2_SUPPORT) + /* Enable RNG reset state */ + DDL_AHB1_GRP1_ForceReset(DDL_AHB1_GRP1_PERIPH_RNG); + + /* Release RNG from reset state */ + DDL_AHB1_GRP1_ReleaseReset(DDL_AHB1_GRP1_PERIPH_RNG); +#else + /* Enable RNG reset state */ + DDL_AHB2_GRP1_ForceReset(DDL_AHB2_GRP1_PERIPH_RNG); + + /* Release RNG from reset state */ + DDL_AHB2_GRP1_ReleaseReset(DDL_AHB2_GRP1_PERIPH_RNG); +#endif /* !RCM_AHB2_SUPPORT */ + } + else + { + status = ERROR; + } + + return status; +} + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#endif /* RNG */ + +/** + * @} + */ + +#endif /* USE_FULL_DDL_DRIVER */ + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_ddl_rtc.c b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_ddl_rtc.c new file mode 100644 index 0000000000..4c37531fb3 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_ddl_rtc.c @@ -0,0 +1,863 @@ +/** + * + * @file apm32f4xx_ddl_rtc.c + * @brief RTC DDL module driver. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2017 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + * + */ +#if defined(USE_FULL_DDL_DRIVER) + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_ddl_rtc.h" +#include "apm32f4xx_ddl_cortex.h" +#ifdef USE_FULL_ASSERT +#include "apm32_assert.h" +#else +#define ASSERT_PARAM(_PARAM_) ((void)(_PARAM_)) +#endif + +/** @addtogroup APM32F4xx_DDL_Driver + * @{ + */ + +#if defined(RTC) + +/** @addtogroup RTC_DDL + * @{ + */ + +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/** @addtogroup RTC_DDL_Private_Constants + * @{ + */ +/* Default values used for prescaler */ +#define RTC_ASYNCH_PRESC_DEFAULT 0x0000007FU +#define RTC_SYNCH_PRESC_DEFAULT 0x000000FFU + +/* Values used for timeout */ +#define RTC_INITMODE_TIMEOUT 1000U /* 1s when tick set to 1ms */ +#define RTC_SYNCHRO_TIMEOUT 1000U /* 1s when tick set to 1ms */ +/** + * @} + */ + +/* Private macros ------------------------------------------------------------*/ +/** @addtogroup RTC_DDL_Private_Macros + * @{ + */ + +#define IS_DDL_RTC_HOURFORMAT(__VALUE__) (((__VALUE__) == DDL_RTC_HOURFORMAT_24HOUR) \ + || ((__VALUE__) == DDL_RTC_HOURFORMAT_AMPM)) + +#define IS_DDL_RTC_ASYNCH_PREDIV(__VALUE__) ((__VALUE__) <= 0x7FU) + +#define IS_DDL_RTC_SYNCH_PREDIV(__VALUE__) ((__VALUE__) <= 0x7FFFU) + +#define IS_DDL_RTC_FORMAT(__VALUE__) (((__VALUE__) == DDL_RTC_FORMAT_BIN) \ + || ((__VALUE__) == DDL_RTC_FORMAT_BCD)) + +#define IS_DDL_RTC_TIME_FORMAT(__VALUE__) (((__VALUE__) == DDL_RTC_TIME_FORMAT_AM_OR_24) \ + || ((__VALUE__) == DDL_RTC_TIME_FORMAT_PM)) + +#define IS_DDL_RTC_HOUR12(__HOUR__) (((__HOUR__) > 0U) && ((__HOUR__) <= 12U)) +#define IS_DDL_RTC_HOUR24(__HOUR__) ((__HOUR__) <= 23U) +#define IS_DDL_RTC_MINUTES(__MINUTES__) ((__MINUTES__) <= 59U) +#define IS_DDL_RTC_SECONDS(__SECONDS__) ((__SECONDS__) <= 59U) + +#define IS_DDL_RTC_WEEKDAY(__VALUE__) (((__VALUE__) == DDL_RTC_WEEKDAY_MONDAY) \ + || ((__VALUE__) == DDL_RTC_WEEKDAY_TUESDAY) \ + || ((__VALUE__) == DDL_RTC_WEEKDAY_WEDNESDAY) \ + || ((__VALUE__) == DDL_RTC_WEEKDAY_THURSDAY) \ + || ((__VALUE__) == DDL_RTC_WEEKDAY_FRIDAY) \ + || ((__VALUE__) == DDL_RTC_WEEKDAY_SATURDAY) \ + || ((__VALUE__) == DDL_RTC_WEEKDAY_SUNDAY)) + +#define IS_DDL_RTC_DAY(__DAY__) (((__DAY__) >= 1U) && ((__DAY__) <= 31U)) + +#define IS_DDL_RTC_MONTH(__MONTH__) (((__MONTH__) >= 1U) && ((__MONTH__) <= 12U)) + +#define IS_DDL_RTC_YEAR(__YEAR__) ((__YEAR__) <= 99U) + +#define IS_DDL_RTC_ALMA_MASK(__VALUE__) (((__VALUE__) == DDL_RTC_ALMA_MASK_NONE) \ + || ((__VALUE__) == DDL_RTC_ALMA_MASK_DATEWEEKDAY) \ + || ((__VALUE__) == DDL_RTC_ALMA_MASK_HOURS) \ + || ((__VALUE__) == DDL_RTC_ALMA_MASK_MINUTES) \ + || ((__VALUE__) == DDL_RTC_ALMA_MASK_SECONDS) \ + || ((__VALUE__) == DDL_RTC_ALMA_MASK_ALL)) + +#define IS_DDL_RTC_ALMB_MASK(__VALUE__) (((__VALUE__) == DDL_RTC_ALMB_MASK_NONE) \ + || ((__VALUE__) == DDL_RTC_ALMB_MASK_DATEWEEKDAY) \ + || ((__VALUE__) == DDL_RTC_ALMB_MASK_HOURS) \ + || ((__VALUE__) == DDL_RTC_ALMB_MASK_MINUTES) \ + || ((__VALUE__) == DDL_RTC_ALMB_MASK_SECONDS) \ + || ((__VALUE__) == DDL_RTC_ALMB_MASK_ALL)) + +#define IS_DDL_RTC_ALMA_DATE_WEEKDAY_SEL(__SEL__) (((__SEL__) == DDL_RTC_ALMA_DATEWEEKDAYSEL_DATE) || \ + ((__SEL__) == DDL_RTC_ALMA_DATEWEEKDAYSEL_WEEKDAY)) + +#define IS_DDL_RTC_ALMB_DATE_WEEKDAY_SEL(__SEL__) (((__SEL__) == DDL_RTC_ALMB_DATEWEEKDAYSEL_DATE) || \ + ((__SEL__) == DDL_RTC_ALMB_DATEWEEKDAYSEL_WEEKDAY)) + +/** + * @} + */ +/* Private function prototypes -----------------------------------------------*/ +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup RTC_DDL_Exported_Functions + * @{ + */ + +/** @addtogroup RTC_DDL_EF_Init + * @{ + */ + +/** + * @brief De-Initializes the RTC registers to their default reset values. + * @note This function does not reset the RTC Clock source and RTC Backup Data + * registers. + * @param RTCx RTC Instance + * @retval An ErrorStatus enumeration value: + * - SUCCESS: RTC registers are de-initialized + * - ERROR: RTC registers are not de-initialized + */ +ErrorStatus DDL_RTC_DeInit(RTC_TypeDef *RTCx) +{ + ErrorStatus status = ERROR; + + /* Check the parameter */ + ASSERT_PARAM(IS_RTC_ALL_INSTANCE(RTCx)); + + /* Disable the write protection for RTC registers */ + DDL_RTC_DisableWriteProtection(RTCx); + + /* Set Initialization mode */ + if (DDL_RTC_EnterInitMode(RTCx) != ERROR) + { + /* Reset TIME, DATE and CTRL registers */ + DDL_RTC_WriteReg(RTCx, TIME, 0x00000000U); + DDL_RTC_WriteReg(RTCx, AUTORLD, RTC_AUTORLD_WUAUTORE); + DDL_RTC_WriteReg(RTCx, DATE, (RTC_DATE_WEEKSEL_0 | RTC_DATE_MONU_0 | RTC_DATE_DAYU_0)); + + /* Reset All CTRL bits except CTRL[2:0] */ + DDL_RTC_WriteReg(RTCx, CTRL, (DDL_RTC_ReadReg(RTCx, CTRL) & RTC_CTRL_WUCLKSEL)); + + DDL_RTC_WriteReg(RTCx, PSC, (RTC_PSC_APSC | RTC_SYNCH_PRESC_DEFAULT)); + DDL_RTC_WriteReg(RTCx, ALRMA, 0x00000000U); + DDL_RTC_WriteReg(RTCx, ALRMB, 0x00000000U); + DDL_RTC_WriteReg(RTCx, CAL, 0x00000000U); + DDL_RTC_WriteReg(RTCx, SHIFT, 0x00000000U); + DDL_RTC_WriteReg(RTCx, ALRMASS, 0x00000000U); + DDL_RTC_WriteReg(RTCx, ALRMBSS, 0x00000000U); + + /* Reset STS register and exit initialization mode */ + DDL_RTC_WriteReg(RTCx, STS, 0x00000000U); + + /* Reset Tamper and alternate functions configuration register */ + DDL_RTC_WriteReg(RTCx, TACFG, 0x00000000U); + + /* Wait till the RTC RSF flag is set */ + status = DDL_RTC_WaitForSynchro(RTCx); + } + + /* Enable the write protection for RTC registers */ + DDL_RTC_EnableWriteProtection(RTCx); + + return status; +} + +/** + * @brief Initializes the RTC registers according to the specified parameters + * in RTC_InitStruct. + * @param RTCx RTC Instance + * @param RTC_InitStruct pointer to a @ref DDL_RTC_InitTypeDef structure that contains + * the configuration information for the RTC peripheral. + * @note The RTC Prescaler register is write protected and can be written in + * initialization mode only. + * @retval An ErrorStatus enumeration value: + * - SUCCESS: RTC registers are initialized + * - ERROR: RTC registers are not initialized + */ +ErrorStatus DDL_RTC_Init(RTC_TypeDef *RTCx, DDL_RTC_InitTypeDef *RTC_InitStruct) +{ + ErrorStatus status = ERROR; + + /* Check the parameters */ + ASSERT_PARAM(IS_RTC_ALL_INSTANCE(RTCx)); + ASSERT_PARAM(IS_DDL_RTC_HOURFORMAT(RTC_InitStruct->HourFormat)); + ASSERT_PARAM(IS_DDL_RTC_ASYNCH_PREDIV(RTC_InitStruct->AsynchPrescaler)); + ASSERT_PARAM(IS_DDL_RTC_SYNCH_PREDIV(RTC_InitStruct->SynchPrescaler)); + + /* Disable the write protection for RTC registers */ + DDL_RTC_DisableWriteProtection(RTCx); + + /* Set Initialization mode */ + if (DDL_RTC_EnterInitMode(RTCx) != ERROR) + { + /* Set Hour Format */ + DDL_RTC_SetHourFormat(RTCx, RTC_InitStruct->HourFormat); + + /* Configure Synchronous and Asynchronous prescaler factor */ + DDL_RTC_SetSynchPrescaler(RTCx, RTC_InitStruct->SynchPrescaler); + DDL_RTC_SetAsynchPrescaler(RTCx, RTC_InitStruct->AsynchPrescaler); + + /* Exit Initialization mode */ + DDL_RTC_DisableInitMode(RTCx); + + status = SUCCESS; + } + /* Enable the write protection for RTC registers */ + DDL_RTC_EnableWriteProtection(RTCx); + + return status; +} + +/** + * @brief Set each @ref DDL_RTC_InitTypeDef field to default value. + * @param RTC_InitStruct pointer to a @ref DDL_RTC_InitTypeDef structure which will be initialized. + * @retval None + */ +void DDL_RTC_StructInit(DDL_RTC_InitTypeDef *RTC_InitStruct) +{ + /* Set RTC_InitStruct fields to default values */ + RTC_InitStruct->HourFormat = DDL_RTC_HOURFORMAT_24HOUR; + RTC_InitStruct->AsynchPrescaler = RTC_ASYNCH_PRESC_DEFAULT; + RTC_InitStruct->SynchPrescaler = RTC_SYNCH_PRESC_DEFAULT; +} + +/** + * @brief Set the RTC current time. + * @param RTCx RTC Instance + * @param RTC_Format This parameter can be one of the following values: + * @arg @ref DDL_RTC_FORMAT_BIN + * @arg @ref DDL_RTC_FORMAT_BCD + * @param RTC_TimeStruct pointer to a RTC_TimeTypeDef structure that contains + * the time configuration information for the RTC. + * @retval An ErrorStatus enumeration value: + * - SUCCESS: RTC Time register is configured + * - ERROR: RTC Time register is not configured + */ +ErrorStatus DDL_RTC_TIME_Init(RTC_TypeDef *RTCx, uint32_t RTC_Format, DDL_RTC_TimeTypeDef *RTC_TimeStruct) +{ + ErrorStatus status = ERROR; + + /* Check the parameters */ + ASSERT_PARAM(IS_RTC_ALL_INSTANCE(RTCx)); + ASSERT_PARAM(IS_DDL_RTC_FORMAT(RTC_Format)); + + if (RTC_Format == DDL_RTC_FORMAT_BIN) + { + if (DDL_RTC_GetHourFormat(RTCx) != DDL_RTC_HOURFORMAT_24HOUR) + { + ASSERT_PARAM(IS_DDL_RTC_HOUR12(RTC_TimeStruct->Hours)); + ASSERT_PARAM(IS_DDL_RTC_TIME_FORMAT(RTC_TimeStruct->TimeFormat)); + } + else + { + RTC_TimeStruct->TimeFormat = 0x00U; + ASSERT_PARAM(IS_DDL_RTC_HOUR24(RTC_TimeStruct->Hours)); + } + ASSERT_PARAM(IS_DDL_RTC_MINUTES(RTC_TimeStruct->Minutes)); + ASSERT_PARAM(IS_DDL_RTC_SECONDS(RTC_TimeStruct->Seconds)); + } + else + { + if (DDL_RTC_GetHourFormat(RTCx) != DDL_RTC_HOURFORMAT_24HOUR) + { + ASSERT_PARAM(IS_DDL_RTC_HOUR12(__DDL_RTC_CONVERT_BCD2BIN(RTC_TimeStruct->Hours))); + ASSERT_PARAM(IS_DDL_RTC_TIME_FORMAT(RTC_TimeStruct->TimeFormat)); + } + else + { + RTC_TimeStruct->TimeFormat = 0x00U; + ASSERT_PARAM(IS_DDL_RTC_HOUR24(__DDL_RTC_CONVERT_BCD2BIN(RTC_TimeStruct->Hours))); + } + ASSERT_PARAM(IS_DDL_RTC_MINUTES(__DDL_RTC_CONVERT_BCD2BIN(RTC_TimeStruct->Minutes))); + ASSERT_PARAM(IS_DDL_RTC_SECONDS(__DDL_RTC_CONVERT_BCD2BIN(RTC_TimeStruct->Seconds))); + } + + /* Disable the write protection for RTC registers */ + DDL_RTC_DisableWriteProtection(RTCx); + + /* Set Initialization mode */ + if (DDL_RTC_EnterInitMode(RTCx) != ERROR) + { + /* Check the input parameters format */ + if (RTC_Format != DDL_RTC_FORMAT_BIN) + { + DDL_RTC_TIME_Config(RTCx, RTC_TimeStruct->TimeFormat, RTC_TimeStruct->Hours, + RTC_TimeStruct->Minutes, RTC_TimeStruct->Seconds); + } + else + { + DDL_RTC_TIME_Config(RTCx, RTC_TimeStruct->TimeFormat, __DDL_RTC_CONVERT_BIN2BCD(RTC_TimeStruct->Hours), + __DDL_RTC_CONVERT_BIN2BCD(RTC_TimeStruct->Minutes), + __DDL_RTC_CONVERT_BIN2BCD(RTC_TimeStruct->Seconds)); + } + + /* Exit Initialization mode */ + DDL_RTC_DisableInitMode(RTCx); + + /* If RTC_CTRL_RCMCFG bit = 0, wait for synchro else this check is not needed */ + if (DDL_RTC_IsShadowRegBypassEnabled(RTCx) == 0U) + { + status = DDL_RTC_WaitForSynchro(RTCx); + } + else + { + status = SUCCESS; + } + } + /* Enable the write protection for RTC registers */ + DDL_RTC_EnableWriteProtection(RTCx); + + return status; +} + +/** + * @brief Set each @ref DDL_RTC_TimeTypeDef field to default value (Time = 00h:00min:00sec). + * @param RTC_TimeStruct pointer to a @ref DDL_RTC_TimeTypeDef structure which will be initialized. + * @retval None + */ +void DDL_RTC_TIME_StructInit(DDL_RTC_TimeTypeDef *RTC_TimeStruct) +{ + /* Time = 00h:00min:00sec */ + RTC_TimeStruct->TimeFormat = DDL_RTC_TIME_FORMAT_AM_OR_24; + RTC_TimeStruct->Hours = 0U; + RTC_TimeStruct->Minutes = 0U; + RTC_TimeStruct->Seconds = 0U; +} + +/** + * @brief Set the RTC current date. + * @param RTCx RTC Instance + * @param RTC_Format This parameter can be one of the following values: + * @arg @ref DDL_RTC_FORMAT_BIN + * @arg @ref DDL_RTC_FORMAT_BCD + * @param RTC_DateStruct pointer to a RTC_DateTypeDef structure that contains + * the date configuration information for the RTC. + * @retval An ErrorStatus enumeration value: + * - SUCCESS: RTC Day register is configured + * - ERROR: RTC Day register is not configured + */ +ErrorStatus DDL_RTC_DATE_Init(RTC_TypeDef *RTCx, uint32_t RTC_Format, DDL_RTC_DateTypeDef *RTC_DateStruct) +{ + ErrorStatus status = ERROR; + + /* Check the parameters */ + ASSERT_PARAM(IS_RTC_ALL_INSTANCE(RTCx)); + ASSERT_PARAM(IS_DDL_RTC_FORMAT(RTC_Format)); + + if ((RTC_Format == DDL_RTC_FORMAT_BIN) && ((RTC_DateStruct->Month & 0x10U) == 0x10U)) + { + RTC_DateStruct->Month = (uint8_t)(RTC_DateStruct->Month & (uint8_t)~(0x10U)) + 0x0AU; + } + if (RTC_Format == DDL_RTC_FORMAT_BIN) + { + ASSERT_PARAM(IS_DDL_RTC_YEAR(RTC_DateStruct->Year)); + ASSERT_PARAM(IS_DDL_RTC_MONTH(RTC_DateStruct->Month)); + ASSERT_PARAM(IS_DDL_RTC_DAY(RTC_DateStruct->Day)); + } + else + { + ASSERT_PARAM(IS_DDL_RTC_YEAR(__DDL_RTC_CONVERT_BCD2BIN(RTC_DateStruct->Year))); + ASSERT_PARAM(IS_DDL_RTC_MONTH(__DDL_RTC_CONVERT_BCD2BIN(RTC_DateStruct->Month))); + ASSERT_PARAM(IS_DDL_RTC_DAY(__DDL_RTC_CONVERT_BCD2BIN(RTC_DateStruct->Day))); + } + ASSERT_PARAM(IS_DDL_RTC_WEEKDAY(RTC_DateStruct->WeekDay)); + + /* Disable the write protection for RTC registers */ + DDL_RTC_DisableWriteProtection(RTCx); + + /* Set Initialization mode */ + if (DDL_RTC_EnterInitMode(RTCx) != ERROR) + { + /* Check the input parameters format */ + if (RTC_Format != DDL_RTC_FORMAT_BIN) + { + DDL_RTC_DATE_Config(RTCx, RTC_DateStruct->WeekDay, RTC_DateStruct->Day, RTC_DateStruct->Month, RTC_DateStruct->Year); + } + else + { + DDL_RTC_DATE_Config(RTCx, RTC_DateStruct->WeekDay, __DDL_RTC_CONVERT_BIN2BCD(RTC_DateStruct->Day), + __DDL_RTC_CONVERT_BIN2BCD(RTC_DateStruct->Month), __DDL_RTC_CONVERT_BIN2BCD(RTC_DateStruct->Year)); + } + + /* Exit Initialization mode */ + DDL_RTC_DisableInitMode(RTCx); + + /* If RTC_CTRL_RCMCFG bit = 0, wait for synchro else this check is not needed */ + if (DDL_RTC_IsShadowRegBypassEnabled(RTCx) == 0U) + { + status = DDL_RTC_WaitForSynchro(RTCx); + } + else + { + status = SUCCESS; + } + } + /* Enable the write protection for RTC registers */ + DDL_RTC_EnableWriteProtection(RTCx); + + return status; +} + +/** + * @brief Set each @ref DDL_RTC_DateTypeDef field to default value (date = Monday, January 01 xx00) + * @param RTC_DateStruct pointer to a @ref DDL_RTC_DateTypeDef structure which will be initialized. + * @retval None + */ +void DDL_RTC_DATE_StructInit(DDL_RTC_DateTypeDef *RTC_DateStruct) +{ + /* Monday, January 01 xx00 */ + RTC_DateStruct->WeekDay = DDL_RTC_WEEKDAY_MONDAY; + RTC_DateStruct->Day = 1U; + RTC_DateStruct->Month = DDL_RTC_MONTH_JANUARY; + RTC_DateStruct->Year = 0U; +} + +/** + * @brief Set the RTC Alarm A. + * @note The Alarm register can only be written when the corresponding Alarm + * is disabled (Use @ref DDL_RTC_ALMA_Disable function). + * @param RTCx RTC Instance + * @param RTC_Format This parameter can be one of the following values: + * @arg @ref DDL_RTC_FORMAT_BIN + * @arg @ref DDL_RTC_FORMAT_BCD + * @param RTC_AlarmStruct pointer to a @ref DDL_RTC_AlarmTypeDef structure that + * contains the alarm configuration parameters. + * @retval An ErrorStatus enumeration value: + * - SUCCESS: ALARMA registers are configured + * - ERROR: ALARMA registers are not configured + */ +ErrorStatus DDL_RTC_ALMA_Init(RTC_TypeDef *RTCx, uint32_t RTC_Format, DDL_RTC_AlarmTypeDef *RTC_AlarmStruct) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_RTC_ALL_INSTANCE(RTCx)); + ASSERT_PARAM(IS_DDL_RTC_FORMAT(RTC_Format)); + ASSERT_PARAM(IS_DDL_RTC_ALMA_MASK(RTC_AlarmStruct->AlarmMask)); + ASSERT_PARAM(IS_DDL_RTC_ALMA_DATE_WEEKDAY_SEL(RTC_AlarmStruct->AlarmDateWeekDaySel)); + + if (RTC_Format == DDL_RTC_FORMAT_BIN) + { + if (DDL_RTC_GetHourFormat(RTCx) != DDL_RTC_HOURFORMAT_24HOUR) + { + ASSERT_PARAM(IS_DDL_RTC_HOUR12(RTC_AlarmStruct->AlarmTime.Hours)); + ASSERT_PARAM(IS_DDL_RTC_TIME_FORMAT(RTC_AlarmStruct->AlarmTime.TimeFormat)); + } + else + { + RTC_AlarmStruct->AlarmTime.TimeFormat = 0x00U; + ASSERT_PARAM(IS_DDL_RTC_HOUR24(RTC_AlarmStruct->AlarmTime.Hours)); + } + ASSERT_PARAM(IS_DDL_RTC_MINUTES(RTC_AlarmStruct->AlarmTime.Minutes)); + ASSERT_PARAM(IS_DDL_RTC_SECONDS(RTC_AlarmStruct->AlarmTime.Seconds)); + + if (RTC_AlarmStruct->AlarmDateWeekDaySel == DDL_RTC_ALMA_DATEWEEKDAYSEL_DATE) + { + ASSERT_PARAM(IS_DDL_RTC_DAY(RTC_AlarmStruct->AlarmDateWeekDay)); + } + else + { + ASSERT_PARAM(IS_DDL_RTC_WEEKDAY(RTC_AlarmStruct->AlarmDateWeekDay)); + } + } + else + { + if (DDL_RTC_GetHourFormat(RTCx) != DDL_RTC_HOURFORMAT_24HOUR) + { + ASSERT_PARAM(IS_DDL_RTC_HOUR12(__DDL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmTime.Hours))); + ASSERT_PARAM(IS_DDL_RTC_TIME_FORMAT(RTC_AlarmStruct->AlarmTime.TimeFormat)); + } + else + { + RTC_AlarmStruct->AlarmTime.TimeFormat = 0x00U; + ASSERT_PARAM(IS_DDL_RTC_HOUR24(__DDL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmTime.Hours))); + } + + ASSERT_PARAM(IS_DDL_RTC_MINUTES(__DDL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmTime.Minutes))); + ASSERT_PARAM(IS_DDL_RTC_SECONDS(__DDL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmTime.Seconds))); + + if (RTC_AlarmStruct->AlarmDateWeekDaySel == DDL_RTC_ALMA_DATEWEEKDAYSEL_DATE) + { + ASSERT_PARAM(IS_DDL_RTC_DAY(__DDL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmDateWeekDay))); + } + else + { + ASSERT_PARAM(IS_DDL_RTC_WEEKDAY(__DDL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmDateWeekDay))); + } + } + + /* Disable the write protection for RTC registers */ + DDL_RTC_DisableWriteProtection(RTCx); + + /* Select weekday selection */ + if (RTC_AlarmStruct->AlarmDateWeekDaySel == DDL_RTC_ALMA_DATEWEEKDAYSEL_DATE) + { + /* Set the date for ALARM */ + DDL_RTC_ALMA_DisableWeekday(RTCx); + if (RTC_Format != DDL_RTC_FORMAT_BIN) + { + DDL_RTC_ALMA_SetDay(RTCx, RTC_AlarmStruct->AlarmDateWeekDay); + } + else + { + DDL_RTC_ALMA_SetDay(RTCx, __DDL_RTC_CONVERT_BIN2BCD(RTC_AlarmStruct->AlarmDateWeekDay)); + } + } + else + { + /* Set the week day for ALARM */ + DDL_RTC_ALMA_EnableWeekday(RTCx); + DDL_RTC_ALMA_SetWeekDay(RTCx, RTC_AlarmStruct->AlarmDateWeekDay); + } + + /* Configure the Alarm register */ + if (RTC_Format != DDL_RTC_FORMAT_BIN) + { + DDL_RTC_ALMA_ConfigTime(RTCx, RTC_AlarmStruct->AlarmTime.TimeFormat, RTC_AlarmStruct->AlarmTime.Hours, + RTC_AlarmStruct->AlarmTime.Minutes, RTC_AlarmStruct->AlarmTime.Seconds); + } + else + { + DDL_RTC_ALMA_ConfigTime(RTCx, RTC_AlarmStruct->AlarmTime.TimeFormat, + __DDL_RTC_CONVERT_BIN2BCD(RTC_AlarmStruct->AlarmTime.Hours), + __DDL_RTC_CONVERT_BIN2BCD(RTC_AlarmStruct->AlarmTime.Minutes), + __DDL_RTC_CONVERT_BIN2BCD(RTC_AlarmStruct->AlarmTime.Seconds)); + } + /* Set ALARM mask */ + DDL_RTC_ALMA_SetMask(RTCx, RTC_AlarmStruct->AlarmMask); + + /* Enable the write protection for RTC registers */ + DDL_RTC_EnableWriteProtection(RTCx); + + return SUCCESS; +} + +/** + * @brief Set the RTC Alarm B. + * @note The Alarm register can only be written when the corresponding Alarm + * is disabled (@ref DDL_RTC_ALMB_Disable function). + * @param RTCx RTC Instance + * @param RTC_Format This parameter can be one of the following values: + * @arg @ref DDL_RTC_FORMAT_BIN + * @arg @ref DDL_RTC_FORMAT_BCD + * @param RTC_AlarmStruct pointer to a @ref DDL_RTC_AlarmTypeDef structure that + * contains the alarm configuration parameters. + * @retval An ErrorStatus enumeration value: + * - SUCCESS: ALARMB registers are configured + * - ERROR: ALARMB registers are not configured + */ +ErrorStatus DDL_RTC_ALMB_Init(RTC_TypeDef *RTCx, uint32_t RTC_Format, DDL_RTC_AlarmTypeDef *RTC_AlarmStruct) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_RTC_ALL_INSTANCE(RTCx)); + ASSERT_PARAM(IS_DDL_RTC_FORMAT(RTC_Format)); + ASSERT_PARAM(IS_DDL_RTC_ALMB_MASK(RTC_AlarmStruct->AlarmMask)); + ASSERT_PARAM(IS_DDL_RTC_ALMB_DATE_WEEKDAY_SEL(RTC_AlarmStruct->AlarmDateWeekDaySel)); + + if (RTC_Format == DDL_RTC_FORMAT_BIN) + { + if (DDL_RTC_GetHourFormat(RTCx) != DDL_RTC_HOURFORMAT_24HOUR) + { + ASSERT_PARAM(IS_DDL_RTC_HOUR12(RTC_AlarmStruct->AlarmTime.Hours)); + ASSERT_PARAM(IS_DDL_RTC_TIME_FORMAT(RTC_AlarmStruct->AlarmTime.TimeFormat)); + } + else + { + RTC_AlarmStruct->AlarmTime.TimeFormat = 0x00U; + ASSERT_PARAM(IS_DDL_RTC_HOUR24(RTC_AlarmStruct->AlarmTime.Hours)); + } + ASSERT_PARAM(IS_DDL_RTC_MINUTES(RTC_AlarmStruct->AlarmTime.Minutes)); + ASSERT_PARAM(IS_DDL_RTC_SECONDS(RTC_AlarmStruct->AlarmTime.Seconds)); + + if (RTC_AlarmStruct->AlarmDateWeekDaySel == DDL_RTC_ALMB_DATEWEEKDAYSEL_DATE) + { + ASSERT_PARAM(IS_DDL_RTC_DAY(RTC_AlarmStruct->AlarmDateWeekDay)); + } + else + { + ASSERT_PARAM(IS_DDL_RTC_WEEKDAY(RTC_AlarmStruct->AlarmDateWeekDay)); + } + } + else + { + if (DDL_RTC_GetHourFormat(RTCx) != DDL_RTC_HOURFORMAT_24HOUR) + { + ASSERT_PARAM(IS_DDL_RTC_HOUR12(__DDL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmTime.Hours))); + ASSERT_PARAM(IS_DDL_RTC_TIME_FORMAT(RTC_AlarmStruct->AlarmTime.TimeFormat)); + } + else + { + RTC_AlarmStruct->AlarmTime.TimeFormat = 0x00U; + ASSERT_PARAM(IS_DDL_RTC_HOUR24(__DDL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmTime.Hours))); + } + + ASSERT_PARAM(IS_DDL_RTC_MINUTES(__DDL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmTime.Minutes))); + ASSERT_PARAM(IS_DDL_RTC_SECONDS(__DDL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmTime.Seconds))); + + if (RTC_AlarmStruct->AlarmDateWeekDaySel == DDL_RTC_ALMB_DATEWEEKDAYSEL_DATE) + { + ASSERT_PARAM(IS_DDL_RTC_DAY(__DDL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmDateWeekDay))); + } + else + { + ASSERT_PARAM(IS_DDL_RTC_WEEKDAY(__DDL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmDateWeekDay))); + } + } + + /* Disable the write protection for RTC registers */ + DDL_RTC_DisableWriteProtection(RTCx); + + /* Select weekday selection */ + if (RTC_AlarmStruct->AlarmDateWeekDaySel == DDL_RTC_ALMB_DATEWEEKDAYSEL_DATE) + { + /* Set the date for ALARM */ + DDL_RTC_ALMB_DisableWeekday(RTCx); + if (RTC_Format != DDL_RTC_FORMAT_BIN) + { + DDL_RTC_ALMB_SetDay(RTCx, RTC_AlarmStruct->AlarmDateWeekDay); + } + else + { + DDL_RTC_ALMB_SetDay(RTCx, __DDL_RTC_CONVERT_BIN2BCD(RTC_AlarmStruct->AlarmDateWeekDay)); + } + } + else + { + /* Set the week day for ALARM */ + DDL_RTC_ALMB_EnableWeekday(RTCx); + DDL_RTC_ALMB_SetWeekDay(RTCx, RTC_AlarmStruct->AlarmDateWeekDay); + } + + /* Configure the Alarm register */ + if (RTC_Format != DDL_RTC_FORMAT_BIN) + { + DDL_RTC_ALMB_ConfigTime(RTCx, RTC_AlarmStruct->AlarmTime.TimeFormat, RTC_AlarmStruct->AlarmTime.Hours, + RTC_AlarmStruct->AlarmTime.Minutes, RTC_AlarmStruct->AlarmTime.Seconds); + } + else + { + DDL_RTC_ALMB_ConfigTime(RTCx, RTC_AlarmStruct->AlarmTime.TimeFormat, + __DDL_RTC_CONVERT_BIN2BCD(RTC_AlarmStruct->AlarmTime.Hours), + __DDL_RTC_CONVERT_BIN2BCD(RTC_AlarmStruct->AlarmTime.Minutes), + __DDL_RTC_CONVERT_BIN2BCD(RTC_AlarmStruct->AlarmTime.Seconds)); + } + /* Set ALARM mask */ + DDL_RTC_ALMB_SetMask(RTCx, RTC_AlarmStruct->AlarmMask); + + /* Enable the write protection for RTC registers */ + DDL_RTC_EnableWriteProtection(RTCx); + + return SUCCESS; +} + +/** + * @brief Set each @ref DDL_RTC_AlarmTypeDef of ALARMA field to default value (Time = 00h:00mn:00sec / + * Day = 1st day of the month/Mask = all fields are masked). + * @param RTC_AlarmStruct pointer to a @ref DDL_RTC_AlarmTypeDef structure which will be initialized. + * @retval None + */ +void DDL_RTC_ALMA_StructInit(DDL_RTC_AlarmTypeDef *RTC_AlarmStruct) +{ + /* Alarm Time Settings : Time = 00h:00mn:00sec */ + RTC_AlarmStruct->AlarmTime.TimeFormat = DDL_RTC_ALMA_TIME_FORMAT_AM; + RTC_AlarmStruct->AlarmTime.Hours = 0U; + RTC_AlarmStruct->AlarmTime.Minutes = 0U; + RTC_AlarmStruct->AlarmTime.Seconds = 0U; + + /* Alarm Day Settings : Day = 1st day of the month */ + RTC_AlarmStruct->AlarmDateWeekDaySel = DDL_RTC_ALMA_DATEWEEKDAYSEL_DATE; + RTC_AlarmStruct->AlarmDateWeekDay = 1U; + + /* Alarm Masks Settings : Mask = all fields are not masked */ + RTC_AlarmStruct->AlarmMask = DDL_RTC_ALMA_MASK_NONE; +} + +/** + * @brief Set each @ref DDL_RTC_AlarmTypeDef of ALARMA field to default value (Time = 00h:00mn:00sec / + * Day = 1st day of the month/Mask = all fields are masked). + * @param RTC_AlarmStruct pointer to a @ref DDL_RTC_AlarmTypeDef structure which will be initialized. + * @retval None + */ +void DDL_RTC_ALMB_StructInit(DDL_RTC_AlarmTypeDef *RTC_AlarmStruct) +{ + /* Alarm Time Settings : Time = 00h:00mn:00sec */ + RTC_AlarmStruct->AlarmTime.TimeFormat = DDL_RTC_ALMB_TIME_FORMAT_AM; + RTC_AlarmStruct->AlarmTime.Hours = 0U; + RTC_AlarmStruct->AlarmTime.Minutes = 0U; + RTC_AlarmStruct->AlarmTime.Seconds = 0U; + + /* Alarm Day Settings : Day = 1st day of the month */ + RTC_AlarmStruct->AlarmDateWeekDaySel = DDL_RTC_ALMB_DATEWEEKDAYSEL_DATE; + RTC_AlarmStruct->AlarmDateWeekDay = 1U; + + /* Alarm Masks Settings : Mask = all fields are not masked */ + RTC_AlarmStruct->AlarmMask = DDL_RTC_ALMB_MASK_NONE; +} + +/** + * @brief Enters the RTC Initialization mode. + * @note The RTC Initialization mode is write protected, use the + * @ref DDL_RTC_DisableWriteProtection before calling this function. + * @param RTCx RTC Instance + * @retval An ErrorStatus enumeration value: + * - SUCCESS: RTC is in Init mode + * - ERROR: RTC is not in Init mode + */ +ErrorStatus DDL_RTC_EnterInitMode(RTC_TypeDef *RTCx) +{ + __IO uint32_t timeout = RTC_INITMODE_TIMEOUT; + ErrorStatus status = SUCCESS; + uint32_t tmp = 0U; + + /* Check the parameter */ + ASSERT_PARAM(IS_RTC_ALL_INSTANCE(RTCx)); + + /* Check if the Initialization mode is set */ + if (DDL_RTC_IsActiveFlag_INIT(RTCx) == 0U) + { + /* Set the Initialization mode */ + DDL_RTC_EnableInitMode(RTCx); + + /* Wait till RTC is in INIT state and if Time out is reached exit */ + tmp = DDL_RTC_IsActiveFlag_INIT(RTCx); + while ((timeout != 0U) && (tmp != 1U)) + { + if (DDL_SYSTICK_IsActiveCounterFlag() == 1U) + { + timeout --; + } + tmp = DDL_RTC_IsActiveFlag_INIT(RTCx); + if (timeout == 0U) + { + status = ERROR; + } + } + } + return status; +} + +/** + * @brief Exit the RTC Initialization mode. + * @note When the initialization sequence is complete, the calendar restarts + * counting after 4 RTCCLK cycles. + * @note The RTC Initialization mode is write protected, use the + * @ref DDL_RTC_DisableWriteProtection before calling this function. + * @param RTCx RTC Instance + * @retval An ErrorStatus enumeration value: + * - SUCCESS: RTC exited from in Init mode + * - ERROR: Not applicable + */ +ErrorStatus DDL_RTC_ExitInitMode(RTC_TypeDef *RTCx) +{ + /* Check the parameter */ + ASSERT_PARAM(IS_RTC_ALL_INSTANCE(RTCx)); + + /* Disable initialization mode */ + DDL_RTC_DisableInitMode(RTCx); + + return SUCCESS; +} + +/** + * @brief Waits until the RTC Time and Day registers (RTC_TIME and RTC_DATE) are + * synchronized with RTC APB clock. + * @note The RTC Resynchronization mode is write protected, use the + * @ref DDL_RTC_DisableWriteProtection before calling this function. + * @note To read the calendar through the shadow registers after calendar + * initialization, calendar update or after wakeup from low power modes + * the software must first clear the RSF flag. + * The software must then wait until it is set again before reading + * the calendar, which means that the calendar registers have been + * correctly copied into the RTC_TIME and RTC_DATE shadow registers. + * @param RTCx RTC Instance + * @retval An ErrorStatus enumeration value: + * - SUCCESS: RTC registers are synchronised + * - ERROR: RTC registers are not synchronised + */ +ErrorStatus DDL_RTC_WaitForSynchro(RTC_TypeDef *RTCx) +{ + __IO uint32_t timeout = RTC_SYNCHRO_TIMEOUT; + ErrorStatus status = SUCCESS; + uint32_t tmp = 0U; + + /* Check the parameter */ + ASSERT_PARAM(IS_RTC_ALL_INSTANCE(RTCx)); + + /* Clear RSF flag */ + DDL_RTC_ClearFlag_RS(RTCx); + + /* Wait the registers to be synchronised */ + tmp = DDL_RTC_IsActiveFlag_RS(RTCx); + while ((timeout != 0U) && (tmp != 1U)) + { + if (DDL_SYSTICK_IsActiveCounterFlag() == 1U) + { + timeout--; + } + tmp = DDL_RTC_IsActiveFlag_RS(RTCx); + if (timeout == 0U) + { + status = ERROR; + } + } + + return (status); +} + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#endif /* defined(RTC) */ + +/** + * @} + */ + +#endif /* USE_FULL_DDL_DRIVER */ diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_ddl_sdmmc.c b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_ddl_sdmmc.c new file mode 100644 index 0000000000..15e405aa7b --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_ddl_sdmmc.c @@ -0,0 +1,1603 @@ +/** + * + * @file apm32f4xx_ddl_sdmmc.c + * @brief SDMMC Low Layer DDL module driver. + * + * This file provides firmware functions to manage the following + * functionalities of the SDMMC peripheral: + * + Initialization/de-initialization functions + * + I/O operation functions + * + Peripheral Control functions + * + Peripheral State functions + * + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + * + @verbatim + ============================================================================== + ##### SDMMC peripheral features ##### + ============================================================================== + [..] The SD/SDMMC MMC card host interface (SDMMC) provides an interface between the AHB + peripheral bus and MultiMedia cards (MMCs), SD memory cards, SDMMC cards and CE-ATA + devices. + + [..] The SDMMC features include the following: + (+) Full compliance with MultiMedia Card System Specification Version 4.2. Card support + for three different databus modes: 1-bit (default), 4-bit and 8-bit + (+) Full compatibility with previous versions of MultiMedia Cards (forward compatibility) + (+) Full compliance with SD Memory Card Specifications Version 2.0 + (+) Full compliance with SD I/O Card Specification Version 2.0: card support for two + different data bus modes: 1-bit (default) and 4-bit + (+) Full support of the CE-ATA features (full compliance with CE-ATA digital protocol + Rev1.1) + (+) Data transfer up to 48 MHz for the 8 bit mode + (+) Data and command output enable signals to control external bidirectional drivers + + ##### How to use this driver ##### + ============================================================================== + [..] + This driver is a considered as a driver of service for external devices drivers + that interfaces with the SDMMC peripheral. + According to the device used (SD card/ MMC card / SDMMC card ...), a set of APIs + is used in the device's driver to perform SDMMC operations and functionalities. + + This driver is almost transparent for the final user, it is only used to implement other + functionalities of the external device. + + [..] + (+) The SDMMC clock (SDMMCCLK = 48 MHz) is coming from a specific output (MSI, PLLUSB1CLK, + PLLUSB2CLK). Before start working with SDMMC peripheral make sure that the + PLL is well configured. + The SDMMC peripheral uses two clock signals: + (++) SDMMC adapter clock (SDMMCCLK = 48 MHz) + (++) APB2 bus clock (PCLK2) + + -@@- PCLK2 and SDMMC_CK clock frequencies must respect the following condition: + Frequency(PCLK2) >= (3 / 8 x Frequency(SDMMC_CK)) + + (+) Enable/Disable peripheral clock using RCC peripheral macros related to SDMMC + peripheral. + + (+) Enable the Power ON State using the SDIO_PowerState_ON() + function and disable it using the function SDIO_PowerState_OFF(). + + (+) Enable/Disable the clock using the __SDIO_ENABLE()/__SDIO_DISABLE() macros. + + (+) Enable/Disable the peripheral interrupts using the macros __SDIO_ENABLE_IT() + and __SDIO_DISABLE_IT() if you need to use interrupt mode. + + (+) When using the DMA mode + (++) Configure the DMA in the MSP layer of the external device + (++) Active the needed channel Request + (++) Enable the DMA using __SDIO_DMA_ENABLE() macro or Disable it using the macro + __SDIO_DMA_DISABLE(). + + (+) To control the CPSM (Command Path State Machine) and send + commands to the card use the SDIO_SendCommand(), + SDIO_GetCommandResponse() and SDIO_GetResponse() functions. First, user has + to fill the command structure (pointer to SDIO_CmdInitTypeDef) according + to the selected command to be sent. + The parameters that should be filled are: + (++) Command Argument + (++) Command Index + (++) Command Response type + (++) Command Wait + (++) CPSM Status (Enable or Disable). + + -@@- To check if the command is well received, read the SDIO_CMDRESP + register using the SDIO_GetCommandResponse(). + The SDMMC responses registers (SDIO_RES1 to SDIO_RES2), use the + SDIO_GetResponse() function. + + (+) To control the DPSM (Data Path State Machine) and send/receive + data to/from the card use the SDIO_DataConfig(), SDIO_GetDataCounter(), + SDIO_ReadFIFO(), SDIO_WriteFIFO() and SDIO_GetFIFOCount() functions. + + *** Read Operations *** + ======================= + [..] + (#) First, user has to fill the data structure (pointer to + SDIO_DataInitTypeDef) according to the selected data type to be received. + The parameters that should be filled are: + (++) Data TimeOut + (++) Data Length + (++) Data Block size + (++) Data Transfer direction: should be from card (To SDMMC) + (++) Data Transfer mode + (++) DPSM Status (Enable or Disable) + + (#) Configure the SDMMC resources to receive the data from the card + according to selected transfer mode (Refer to Step 8, 9 and 10). + + (#) Send the selected Read command (refer to step 11). + + (#) Use the SDIO flags/interrupts to check the transfer status. + + *** Write Operations *** + ======================== + [..] + (#) First, user has to fill the data structure (pointer to + SDIO_DataInitTypeDef) according to the selected data type to be received. + The parameters that should be filled are: + (++) Data TimeOut + (++) Data Length + (++) Data Block size + (++) Data Transfer direction: should be to card (To CARD) + (++) Data Transfer mode + (++) DPSM Status (Enable or Disable) + + (#) Configure the SDMMC resources to send the data to the card according to + selected transfer mode. + + (#) Send the selected Write command. + + (#) Use the SDIO flags/interrupts to check the transfer status. + + *** Command management operations *** + ===================================== + [..] + (#) The commands used for Read/Write/Erase operations are managed in + separate functions. + Each function allows to send the needed command with the related argument, + then check the response. + By the same approach, you could implement a command and check the response. + + @endverbatim + * + */ + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal.h" + +#if defined(SDIO) + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +/** @defgroup SDMMC_DDL SDMMC Low Layer + * @brief Low layer module for SD + * @{ + */ + +#if defined(DAL_SD_MODULE_ENABLED) || defined(DAL_MMC_MODULE_ENABLED) + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +static uint32_t SDMMC_GetCmdError(SDIO_TypeDef *SDIOx); + +/* Exported functions --------------------------------------------------------*/ + +/** @defgroup SDMMC_DDL_Exported_Functions SDMMC Low Layer Exported Functions + * @{ + */ + +/** @defgroup DAL_SDMMC_DDL_Group1 Initialization de-initialization functions + * @brief Initialization and Configuration functions + * +@verbatim + =============================================================================== + ##### Initialization/de-initialization functions ##### + =============================================================================== + [..] This section provides functions allowing to: + +@endverbatim + * @{ + */ + +/** + * @brief Initializes the SDMMC according to the specified + * parameters in the SDMMC_InitTypeDef and create the associated handle. + * @param SDIOx: Pointer to SDMMC register base + * @param Init: SDMMC initialization structure + * @retval DAL status + */ +DAL_StatusTypeDef SDIO_Init(SDIO_TypeDef *SDIOx, SDIO_InitTypeDef Init) +{ + uint32_t tmpreg = 0; + + /* Check the parameters */ + ASSERT_PARAM(IS_SDIO_ALL_INSTANCE(SDIOx)); + ASSERT_PARAM(IS_SDIO_CLOCK_EDGE(Init.ClockEdge)); + ASSERT_PARAM(IS_SDIO_CLOCK_BYPASS(Init.ClockBypass)); + ASSERT_PARAM(IS_SDIO_CLOCK_POWER_SAVE(Init.ClockPowerSave)); + ASSERT_PARAM(IS_SDIO_BUS_WIDE(Init.BusWide)); + ASSERT_PARAM(IS_SDIO_HARDWARE_FLOW_CONTROL(Init.HardwareFlowControl)); + ASSERT_PARAM(IS_SDIO_CLKDIV(Init.ClockDiv)); + + /* Set SDMMC configuration parameters */ + tmpreg |= (Init.ClockEdge |\ + Init.ClockBypass |\ + Init.ClockPowerSave |\ + Init.BusWide |\ + Init.HardwareFlowControl |\ + Init.ClockDiv + ); + + /* Write to SDMMC CLKCTRL */ + MODIFY_REG(SDIOx->CLKCTRL, CLKCTRL_CLEAR_MASK, tmpreg); + + return DAL_OK; +} + + +/** + * @} + */ + +/** @defgroup DAL_SDMMC_DDL_Group2 IO operation functions + * @brief Data transfers functions + * +@verbatim + =============================================================================== + ##### I/O operation functions ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to manage the SDMMC data + transfers. + +@endverbatim + * @{ + */ + +/** + * @brief Read data (word) from Rx FIFO in blocking mode (polling) + * @param SDIOx: Pointer to SDMMC register base + * @retval DAL status + */ +uint32_t SDIO_ReadFIFO(SDIO_TypeDef *SDIOx) +{ + /* Read data from Rx FIFO */ + return (SDIOx->FIFODATA); +} + +/** + * @brief Write data (word) to Tx FIFO in blocking mode (polling) + * @param SDIOx: Pointer to SDMMC register base + * @param pWriteData: pointer to data to write + * @retval DAL status + */ +DAL_StatusTypeDef SDIO_WriteFIFO(SDIO_TypeDef *SDIOx, uint32_t *pWriteData) +{ + /* Write data to FIFO */ + SDIOx->FIFODATA = *pWriteData; + + return DAL_OK; +} + +/** + * @} + */ + +/** @defgroup DAL_SDMMC_DDL_Group3 Peripheral Control functions + * @brief management functions + * +@verbatim + =============================================================================== + ##### Peripheral Control functions ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to control the SDMMC data + transfers. + +@endverbatim + * @{ + */ + +/** + * @brief Set SDMMC Power state to ON. + * @param SDIOx: Pointer to SDMMC register base + * @retval DAL status + */ +DAL_StatusTypeDef SDIO_PowerState_ON(SDIO_TypeDef *SDIOx) +{ + /* Set power state to ON */ + SDIOx->PWRCTRL = SDIO_PWRCTRL_PWRCTRL; + + return DAL_OK; +} + +/** + * @brief Set SDMMC Power state to OFF. + * @param SDIOx: Pointer to SDMMC register base + * @retval DAL status + */ +DAL_StatusTypeDef SDIO_PowerState_OFF(SDIO_TypeDef *SDIOx) +{ + /* Set power state to OFF */ + SDIOx->PWRCTRL = (uint32_t)0x00000000; + + return DAL_OK; +} + +/** + * @brief Get SDMMC Power state. + * @param SDIOx: Pointer to SDMMC register base + * @retval Power status of the controller. The returned value can be one of the + * following values: + * - 0x00: Power OFF + * - 0x02: Power UP + * - 0x03: Power ON + */ +uint32_t SDIO_GetPowerState(SDIO_TypeDef *SDIOx) +{ + return (SDIOx->PWRCTRL & SDIO_PWRCTRL_PWRCTRL); +} + +/** + * @brief Configure the SDMMC command path according to the specified parameters in + * SDIO_CmdInitTypeDef structure and send the command + * @param SDIOx: Pointer to SDMMC register base + * @param Command: pointer to a SDIO_CmdInitTypeDef structure that contains + * the configuration information for the SDMMC command + * @retval DAL status + */ +DAL_StatusTypeDef SDIO_SendCommand(SDIO_TypeDef *SDIOx, SDIO_CmdInitTypeDef *Command) +{ + uint32_t tmpreg = 0; + + /* Check the parameters */ + ASSERT_PARAM(IS_SDIO_CMD_INDEX(Command->CmdIndex)); + ASSERT_PARAM(IS_SDIO_RESPONSE(Command->Response)); + ASSERT_PARAM(IS_SDIO_WAIT(Command->WaitForInterrupt)); + ASSERT_PARAM(IS_SDIO_CPSM(Command->CPSM)); + + /* Set the SDMMC Argument value */ + SDIOx->ARG = Command->Argument; + + /* Set SDMMC command parameters */ + tmpreg |= (uint32_t)(Command->CmdIndex |\ + Command->Response |\ + Command->WaitForInterrupt |\ + Command->CPSM); + + /* Write to SDMMC CMD register */ + MODIFY_REG(SDIOx->CMD, CMD_CLEAR_MASK, tmpreg); + + return DAL_OK; +} + +/** + * @brief Return the command index of last command for which response received + * @param SDIOx: Pointer to SDMMC register base + * @retval Command index of the last command response received + */ +uint8_t SDIO_GetCommandResponse(SDIO_TypeDef *SDIOx) +{ + return (uint8_t)(SDIOx->CMDRES); +} + + +/** + * @brief Return the response received from the card for the last command + * @param SDIOx: Pointer to SDMMC register base + * @param Response: Specifies the SDMMC response register. + * This parameter can be one of the following values: + * @arg SDIO_RES1: Response Register 1 + * @arg SDIO_RES2: Response Register 2 + * @arg SDIO_RES3: Response Register 3 + * @arg SDIO_RES4: Response Register 4 + * @retval The Corresponding response register value + */ +uint32_t SDIO_GetResponse(SDIO_TypeDef *SDIOx, uint32_t Response) +{ + uint32_t tmp; + + /* Check the parameters */ + ASSERT_PARAM(IS_SDIO_RESP(Response)); + + /* Get the response */ + tmp = (uint32_t)(&(SDIOx->RES1)) + Response; + + return (*(__IO uint32_t *) tmp); +} + +/** + * @brief Configure the SDMMC data path according to the specified + * parameters in the SDIO_DataInitTypeDef. + * @param SDIOx: Pointer to SDIO register base + * @param Data : pointer to a SDIO_DataInitTypeDef structure + * that contains the configuration information for the SDMMC data. + * @retval DAL status + */ +DAL_StatusTypeDef SDIO_ConfigData(SDIO_TypeDef *SDIOx, SDIO_DataInitTypeDef* Data) +{ + uint32_t tmpreg = 0; + + /* Check the parameters */ + ASSERT_PARAM(IS_SDIO_DATA_LENGTH(Data->DataLength)); + ASSERT_PARAM(IS_SDIO_BLOCK_SIZE(Data->DataBlockSize)); + ASSERT_PARAM(IS_SDIO_TRANSFER_DIR(Data->TransferDir)); + ASSERT_PARAM(IS_SDIO_TRANSFER_MODE(Data->TransferMode)); + ASSERT_PARAM(IS_SDIO_DPSM(Data->DPSM)); + + /* Set the SDMMC Data TimeOut value */ + SDIOx->DATATIME = Data->DataTimeOut; + + /* Set the SDMMC DataLength value */ + SDIOx->DATALEN = Data->DataLength; + + /* Set the SDMMC data configuration parameters */ + tmpreg |= (uint32_t)(Data->DataBlockSize |\ + Data->TransferDir |\ + Data->TransferMode |\ + Data->DPSM); + + /* Write to SDMMC DCTRL */ + MODIFY_REG(SDIOx->DCTRL, DCTRL_CLEAR_MASK, tmpreg); + + return DAL_OK; + +} + +/** + * @brief Returns number of remaining data bytes to be transferred. + * @param SDIOx: Pointer to SDIO register base + * @retval Number of remaining data bytes to be transferred + */ +uint32_t SDIO_GetDataCounter(SDIO_TypeDef *SDIOx) +{ + return (SDIOx->DCNT); +} + +/** + * @brief Get the FIFO data + * @param SDIOx: Pointer to SDIO register base + * @retval Data received + */ +uint32_t SDIO_GetFIFOCount(SDIO_TypeDef *SDIOx) +{ + return (SDIOx->FIFODATA); +} + +/** + * @brief Sets one of the two options of inserting read wait interval. + * @param SDIOx: Pointer to SDIO register base + * @param SDIO_ReadWaitMode: SDMMC Read Wait operation mode. + * This parameter can be: + * @arg SDIO_READ_WAIT_MODE_CLK: Read Wait control by stopping SDMMCCLK + * @arg SDIO_READ_WAIT_MODE_DATA2: Read Wait control using SDMMC_DATA2 + * @retval None + */ +DAL_StatusTypeDef SDIO_SetSDMMCReadWaitMode(SDIO_TypeDef *SDIOx, uint32_t SDIO_ReadWaitMode) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_SDIO_READWAIT_MODE(SDIO_ReadWaitMode)); + + /* Set SDMMC read wait mode */ + MODIFY_REG(SDIOx->DCTRL, SDIO_DCTRL_RDWAIT, SDIO_ReadWaitMode); + + return DAL_OK; +} + +/** + * @} + */ + + +/** @defgroup DAL_SDMMC_DDL_Group4 Command management functions + * @brief Data transfers functions + * +@verbatim + =============================================================================== + ##### Commands management functions ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to manage the needed commands. + +@endverbatim + * @{ + */ + +/** + * @brief Send the Data Block Length command and check the response + * @param SDIOx: Pointer to SDIO register base + * @retval DAL status + */ +uint32_t SDMMC_CmdBlockLength(SDIO_TypeDef *SDIOx, uint32_t BlockSize) +{ + SDIO_CmdInitTypeDef sdmmc_cmdinit; + uint32_t errorstate; + + /* Set Block Size for Card */ + sdmmc_cmdinit.Argument = (uint32_t)BlockSize; + sdmmc_cmdinit.CmdIndex = SDMMC_CMD_SET_BLOCKLEN; + sdmmc_cmdinit.Response = SDIO_RESPONSE_SHORT; + sdmmc_cmdinit.WaitForInterrupt = SDIO_WAIT_NO; + sdmmc_cmdinit.CPSM = SDIO_CPSM_ENABLE; + (void)SDIO_SendCommand(SDIOx, &sdmmc_cmdinit); + + /* Check for error conditions */ + errorstate = SDMMC_GetCmdResp1(SDIOx, SDMMC_CMD_SET_BLOCKLEN, SDIO_CMDTIMEOUT); + + return errorstate; +} + +/** + * @brief Send the Read Single Block command and check the response + * @param SDIOx: Pointer to SDIO register base + * @retval DAL status + */ +uint32_t SDMMC_CmdReadSingleBlock(SDIO_TypeDef *SDIOx, uint32_t ReadAdd) +{ + SDIO_CmdInitTypeDef sdmmc_cmdinit; + uint32_t errorstate; + + /* Set Block Size for Card */ + sdmmc_cmdinit.Argument = (uint32_t)ReadAdd; + sdmmc_cmdinit.CmdIndex = SDMMC_CMD_READ_SINGLE_BLOCK; + sdmmc_cmdinit.Response = SDIO_RESPONSE_SHORT; + sdmmc_cmdinit.WaitForInterrupt = SDIO_WAIT_NO; + sdmmc_cmdinit.CPSM = SDIO_CPSM_ENABLE; + (void)SDIO_SendCommand(SDIOx, &sdmmc_cmdinit); + + /* Check for error conditions */ + errorstate = SDMMC_GetCmdResp1(SDIOx, SDMMC_CMD_READ_SINGLE_BLOCK, SDIO_CMDTIMEOUT); + + return errorstate; +} + +/** + * @brief Send the Read Multi Block command and check the response + * @param SDIOx: Pointer to SDIO register base + * @retval DAL status + */ +uint32_t SDMMC_CmdReadMultiBlock(SDIO_TypeDef *SDIOx, uint32_t ReadAdd) +{ + SDIO_CmdInitTypeDef sdmmc_cmdinit; + uint32_t errorstate; + + /* Set Block Size for Card */ + sdmmc_cmdinit.Argument = (uint32_t)ReadAdd; + sdmmc_cmdinit.CmdIndex = SDMMC_CMD_READ_MULT_BLOCK; + sdmmc_cmdinit.Response = SDIO_RESPONSE_SHORT; + sdmmc_cmdinit.WaitForInterrupt = SDIO_WAIT_NO; + sdmmc_cmdinit.CPSM = SDIO_CPSM_ENABLE; + (void)SDIO_SendCommand(SDIOx, &sdmmc_cmdinit); + + /* Check for error conditions */ + errorstate = SDMMC_GetCmdResp1(SDIOx, SDMMC_CMD_READ_MULT_BLOCK, SDIO_CMDTIMEOUT); + + return errorstate; +} + +/** + * @brief Send the Write Single Block command and check the response + * @param SDIOx: Pointer to SDIO register base + * @retval DAL status + */ +uint32_t SDMMC_CmdWriteSingleBlock(SDIO_TypeDef *SDIOx, uint32_t WriteAdd) +{ + SDIO_CmdInitTypeDef sdmmc_cmdinit; + uint32_t errorstate; + + /* Set Block Size for Card */ + sdmmc_cmdinit.Argument = (uint32_t)WriteAdd; + sdmmc_cmdinit.CmdIndex = SDMMC_CMD_WRITE_SINGLE_BLOCK; + sdmmc_cmdinit.Response = SDIO_RESPONSE_SHORT; + sdmmc_cmdinit.WaitForInterrupt = SDIO_WAIT_NO; + sdmmc_cmdinit.CPSM = SDIO_CPSM_ENABLE; + (void)SDIO_SendCommand(SDIOx, &sdmmc_cmdinit); + + /* Check for error conditions */ + errorstate = SDMMC_GetCmdResp1(SDIOx, SDMMC_CMD_WRITE_SINGLE_BLOCK, SDIO_CMDTIMEOUT); + + return errorstate; +} + +/** + * @brief Send the Write Multi Block command and check the response + * @param SDIOx: Pointer to SDIO register base + * @retval DAL status + */ +uint32_t SDMMC_CmdWriteMultiBlock(SDIO_TypeDef *SDIOx, uint32_t WriteAdd) +{ + SDIO_CmdInitTypeDef sdmmc_cmdinit; + uint32_t errorstate; + + /* Set Block Size for Card */ + sdmmc_cmdinit.Argument = (uint32_t)WriteAdd; + sdmmc_cmdinit.CmdIndex = SDMMC_CMD_WRITE_MULT_BLOCK; + sdmmc_cmdinit.Response = SDIO_RESPONSE_SHORT; + sdmmc_cmdinit.WaitForInterrupt = SDIO_WAIT_NO; + sdmmc_cmdinit.CPSM = SDIO_CPSM_ENABLE; + (void)SDIO_SendCommand(SDIOx, &sdmmc_cmdinit); + + /* Check for error conditions */ + errorstate = SDMMC_GetCmdResp1(SDIOx, SDMMC_CMD_WRITE_MULT_BLOCK, SDIO_CMDTIMEOUT); + + return errorstate; +} + +/** + * @brief Send the Start Address Erase command for SD and check the response + * @param SDIOx: Pointer to SDIO register base + * @retval DAL status + */ +uint32_t SDMMC_CmdSDEraseStartAdd(SDIO_TypeDef *SDIOx, uint32_t StartAdd) +{ + SDIO_CmdInitTypeDef sdmmc_cmdinit; + uint32_t errorstate; + + /* Set Block Size for Card */ + sdmmc_cmdinit.Argument = (uint32_t)StartAdd; + sdmmc_cmdinit.CmdIndex = SDMMC_CMD_SD_ERASE_GRP_START; + sdmmc_cmdinit.Response = SDIO_RESPONSE_SHORT; + sdmmc_cmdinit.WaitForInterrupt = SDIO_WAIT_NO; + sdmmc_cmdinit.CPSM = SDIO_CPSM_ENABLE; + (void)SDIO_SendCommand(SDIOx, &sdmmc_cmdinit); + + /* Check for error conditions */ + errorstate = SDMMC_GetCmdResp1(SDIOx, SDMMC_CMD_SD_ERASE_GRP_START, SDIO_CMDTIMEOUT); + + return errorstate; +} + +/** + * @brief Send the End Address Erase command for SD and check the response + * @param SDIOx: Pointer to SDIO register base + * @retval DAL status + */ +uint32_t SDMMC_CmdSDEraseEndAdd(SDIO_TypeDef *SDIOx, uint32_t EndAdd) +{ + SDIO_CmdInitTypeDef sdmmc_cmdinit; + uint32_t errorstate; + + /* Set Block Size for Card */ + sdmmc_cmdinit.Argument = (uint32_t)EndAdd; + sdmmc_cmdinit.CmdIndex = SDMMC_CMD_SD_ERASE_GRP_END; + sdmmc_cmdinit.Response = SDIO_RESPONSE_SHORT; + sdmmc_cmdinit.WaitForInterrupt = SDIO_WAIT_NO; + sdmmc_cmdinit.CPSM = SDIO_CPSM_ENABLE; + (void)SDIO_SendCommand(SDIOx, &sdmmc_cmdinit); + + /* Check for error conditions */ + errorstate = SDMMC_GetCmdResp1(SDIOx, SDMMC_CMD_SD_ERASE_GRP_END, SDIO_CMDTIMEOUT); + + return errorstate; +} + +/** + * @brief Send the Start Address Erase command and check the response + * @param SDIOx: Pointer to SDIO register base + * @retval DAL status + */ +uint32_t SDMMC_CmdEraseStartAdd(SDIO_TypeDef *SDIOx, uint32_t StartAdd) +{ + SDIO_CmdInitTypeDef sdmmc_cmdinit; + uint32_t errorstate; + + /* Set Block Size for Card */ + sdmmc_cmdinit.Argument = (uint32_t)StartAdd; + sdmmc_cmdinit.CmdIndex = SDMMC_CMD_ERASE_GRP_START; + sdmmc_cmdinit.Response = SDIO_RESPONSE_SHORT; + sdmmc_cmdinit.WaitForInterrupt = SDIO_WAIT_NO; + sdmmc_cmdinit.CPSM = SDIO_CPSM_ENABLE; + (void)SDIO_SendCommand(SDIOx, &sdmmc_cmdinit); + + /* Check for error conditions */ + errorstate = SDMMC_GetCmdResp1(SDIOx, SDMMC_CMD_ERASE_GRP_START, SDIO_CMDTIMEOUT); + + return errorstate; +} + +/** + * @brief Send the End Address Erase command and check the response + * @param SDIOx: Pointer to SDIO register base + * @retval DAL status + */ +uint32_t SDMMC_CmdEraseEndAdd(SDIO_TypeDef *SDIOx, uint32_t EndAdd) +{ + SDIO_CmdInitTypeDef sdmmc_cmdinit; + uint32_t errorstate; + + /* Set Block Size for Card */ + sdmmc_cmdinit.Argument = (uint32_t)EndAdd; + sdmmc_cmdinit.CmdIndex = SDMMC_CMD_ERASE_GRP_END; + sdmmc_cmdinit.Response = SDIO_RESPONSE_SHORT; + sdmmc_cmdinit.WaitForInterrupt = SDIO_WAIT_NO; + sdmmc_cmdinit.CPSM = SDIO_CPSM_ENABLE; + (void)SDIO_SendCommand(SDIOx, &sdmmc_cmdinit); + + /* Check for error conditions */ + errorstate = SDMMC_GetCmdResp1(SDIOx, SDMMC_CMD_ERASE_GRP_END, SDIO_CMDTIMEOUT); + + return errorstate; +} + +/** + * @brief Send the Erase command and check the response + * @param SDIOx: Pointer to SDIO register base + * @retval DAL status + */ +uint32_t SDMMC_CmdErase(SDIO_TypeDef *SDIOx) +{ + SDIO_CmdInitTypeDef sdmmc_cmdinit; + uint32_t errorstate; + + /* Set Block Size for Card */ + sdmmc_cmdinit.Argument = 0U; + sdmmc_cmdinit.CmdIndex = SDMMC_CMD_ERASE; + sdmmc_cmdinit.Response = SDIO_RESPONSE_SHORT; + sdmmc_cmdinit.WaitForInterrupt = SDIO_WAIT_NO; + sdmmc_cmdinit.CPSM = SDIO_CPSM_ENABLE; + (void)SDIO_SendCommand(SDIOx, &sdmmc_cmdinit); + + /* Check for error conditions */ + errorstate = SDMMC_GetCmdResp1(SDIOx, SDMMC_CMD_ERASE, SDIO_MAXERASETIMEOUT); + + return errorstate; +} + +/** + * @brief Send the Stop Transfer command and check the response. + * @param SDIOx: Pointer to SDIO register base + * @retval DAL status + */ +uint32_t SDMMC_CmdStopTransfer(SDIO_TypeDef *SDIOx) +{ + SDIO_CmdInitTypeDef sdmmc_cmdinit; + uint32_t errorstate; + + /* Send CMD12 STOP_TRANSMISSION */ + sdmmc_cmdinit.Argument = 0U; + sdmmc_cmdinit.CmdIndex = SDMMC_CMD_STOP_TRANSMISSION; + sdmmc_cmdinit.Response = SDIO_RESPONSE_SHORT; + sdmmc_cmdinit.WaitForInterrupt = SDIO_WAIT_NO; + sdmmc_cmdinit.CPSM = SDIO_CPSM_ENABLE; + (void)SDIO_SendCommand(SDIOx, &sdmmc_cmdinit); + + /* Check for error conditions */ + errorstate = SDMMC_GetCmdResp1(SDIOx, SDMMC_CMD_STOP_TRANSMISSION, SDIO_STOPTRANSFERTIMEOUT); + + return errorstate; +} + +/** + * @brief Send the Select Deselect command and check the response. + * @param SDIOx: Pointer to SDIO register base + * @param addr: Address of the card to be selected + * @retval DAL status + */ +uint32_t SDMMC_CmdSelDesel(SDIO_TypeDef *SDIOx, uint64_t Addr) +{ + SDIO_CmdInitTypeDef sdmmc_cmdinit; + uint32_t errorstate; + + /* Send CMD7 SDMMC_SEL_DESEL_CARD */ + sdmmc_cmdinit.Argument = (uint32_t)Addr; + sdmmc_cmdinit.CmdIndex = SDMMC_CMD_SEL_DESEL_CARD; + sdmmc_cmdinit.Response = SDIO_RESPONSE_SHORT; + sdmmc_cmdinit.WaitForInterrupt = SDIO_WAIT_NO; + sdmmc_cmdinit.CPSM = SDIO_CPSM_ENABLE; + (void)SDIO_SendCommand(SDIOx, &sdmmc_cmdinit); + + /* Check for error conditions */ + errorstate = SDMMC_GetCmdResp1(SDIOx, SDMMC_CMD_SEL_DESEL_CARD, SDIO_CMDTIMEOUT); + + return errorstate; +} + +/** + * @brief Send the Go Idle State command and check the response. + * @param SDIOx: Pointer to SDIO register base + * @retval DAL status + */ +uint32_t SDMMC_CmdGoIdleState(SDIO_TypeDef *SDIOx) +{ + SDIO_CmdInitTypeDef sdmmc_cmdinit; + uint32_t errorstate; + + sdmmc_cmdinit.Argument = 0U; + sdmmc_cmdinit.CmdIndex = SDMMC_CMD_GO_IDLE_STATE; + sdmmc_cmdinit.Response = SDIO_RESPONSE_NO; + sdmmc_cmdinit.WaitForInterrupt = SDIO_WAIT_NO; + sdmmc_cmdinit.CPSM = SDIO_CPSM_ENABLE; + (void)SDIO_SendCommand(SDIOx, &sdmmc_cmdinit); + + /* Check for error conditions */ + errorstate = SDMMC_GetCmdError(SDIOx); + + return errorstate; +} + +/** + * @brief Send the Operating Condition command and check the response. + * @param SDIOx: Pointer to SDIO register base + * @retval DAL status + */ +uint32_t SDMMC_CmdOperCond(SDIO_TypeDef *SDIOx) +{ + SDIO_CmdInitTypeDef sdmmc_cmdinit; + uint32_t errorstate; + + /* Send CMD8 to verify SD card interface operating condition */ + /* Argument: - [31:12]: Reserved (shall be set to '0') + - [11:8]: Supply Voltage (VHS) 0x1 (Range: 2.7-3.6 V) + - [7:0]: Check Pattern (recommended 0xAA) */ + /* CMD Response: R7 */ + sdmmc_cmdinit.Argument = SDMMC_CHECK_PATTERN; + sdmmc_cmdinit.CmdIndex = SDMMC_CMD_HS_SEND_EXT_CSD; + sdmmc_cmdinit.Response = SDIO_RESPONSE_SHORT; + sdmmc_cmdinit.WaitForInterrupt = SDIO_WAIT_NO; + sdmmc_cmdinit.CPSM = SDIO_CPSM_ENABLE; + (void)SDIO_SendCommand(SDIOx, &sdmmc_cmdinit); + + /* Check for error conditions */ + errorstate = SDMMC_GetCmdResp7(SDIOx); + + return errorstate; +} + +/** + * @brief Send the Application command to verify that that the next command + * is an application specific com-mand rather than a standard command + * and check the response. + * @param SDIOx: Pointer to SDIO register base + * @param Argument: Command Argument + * @retval DAL status + */ +uint32_t SDMMC_CmdAppCommand(SDIO_TypeDef *SDIOx, uint32_t Argument) +{ + SDIO_CmdInitTypeDef sdmmc_cmdinit; + uint32_t errorstate; + + sdmmc_cmdinit.Argument = (uint32_t)Argument; + sdmmc_cmdinit.CmdIndex = SDMMC_CMD_APP_CMD; + sdmmc_cmdinit.Response = SDIO_RESPONSE_SHORT; + sdmmc_cmdinit.WaitForInterrupt = SDIO_WAIT_NO; + sdmmc_cmdinit.CPSM = SDIO_CPSM_ENABLE; + (void)SDIO_SendCommand(SDIOx, &sdmmc_cmdinit); + + /* Check for error conditions */ + /* If there is a DAL_ERROR, it is a MMC card, else + it is a SD card: SD card 2.0 (voltage range mismatch) + or SD card 1.x */ + errorstate = SDMMC_GetCmdResp1(SDIOx, SDMMC_CMD_APP_CMD, SDIO_CMDTIMEOUT); + + return errorstate; +} + +/** + * @brief Send the command asking the accessed card to send its operating + * condition register (OCR) + * @param SDIOx: Pointer to SDIO register base + * @param Argument: Command Argument + * @retval DAL status + */ +uint32_t SDMMC_CmdAppOperCommand(SDIO_TypeDef *SDIOx, uint32_t Argument) +{ + SDIO_CmdInitTypeDef sdmmc_cmdinit; + uint32_t errorstate; + + sdmmc_cmdinit.Argument = SDMMC_VOLTAGE_WINDOW_SD | Argument; + sdmmc_cmdinit.CmdIndex = SDMMC_CMD_SD_APP_OP_COND; + sdmmc_cmdinit.Response = SDIO_RESPONSE_SHORT; + sdmmc_cmdinit.WaitForInterrupt = SDIO_WAIT_NO; + sdmmc_cmdinit.CPSM = SDIO_CPSM_ENABLE; + (void)SDIO_SendCommand(SDIOx, &sdmmc_cmdinit); + + /* Check for error conditions */ + errorstate = SDMMC_GetCmdResp3(SDIOx); + + return errorstate; +} + +/** + * @brief Send the Bus Width command and check the response. + * @param SDIOx: Pointer to SDIO register base + * @param BusWidth: BusWidth + * @retval DAL status + */ +uint32_t SDMMC_CmdBusWidth(SDIO_TypeDef *SDIOx, uint32_t BusWidth) +{ + SDIO_CmdInitTypeDef sdmmc_cmdinit; + uint32_t errorstate; + + sdmmc_cmdinit.Argument = (uint32_t)BusWidth; + sdmmc_cmdinit.CmdIndex = SDMMC_CMD_APP_SD_SET_BUSWIDTH; + sdmmc_cmdinit.Response = SDIO_RESPONSE_SHORT; + sdmmc_cmdinit.WaitForInterrupt = SDIO_WAIT_NO; + sdmmc_cmdinit.CPSM = SDIO_CPSM_ENABLE; + (void)SDIO_SendCommand(SDIOx, &sdmmc_cmdinit); + + /* Check for error conditions */ + errorstate = SDMMC_GetCmdResp1(SDIOx, SDMMC_CMD_APP_SD_SET_BUSWIDTH, SDIO_CMDTIMEOUT); + + return errorstate; +} + +/** + * @brief Send the Send SCR command and check the response. + * @param SDIOx: Pointer to SDIO register base + * @retval DAL status + */ +uint32_t SDMMC_CmdSendSCR(SDIO_TypeDef *SDIOx) +{ + SDIO_CmdInitTypeDef sdmmc_cmdinit; + uint32_t errorstate; + + /* Send CMD51 SD_APP_SEND_SCR */ + sdmmc_cmdinit.Argument = 0U; + sdmmc_cmdinit.CmdIndex = SDMMC_CMD_SD_APP_SEND_SCR; + sdmmc_cmdinit.Response = SDIO_RESPONSE_SHORT; + sdmmc_cmdinit.WaitForInterrupt = SDIO_WAIT_NO; + sdmmc_cmdinit.CPSM = SDIO_CPSM_ENABLE; + (void)SDIO_SendCommand(SDIOx, &sdmmc_cmdinit); + + /* Check for error conditions */ + errorstate = SDMMC_GetCmdResp1(SDIOx, SDMMC_CMD_SD_APP_SEND_SCR, SDIO_CMDTIMEOUT); + + return errorstate; +} + +/** + * @brief Send the Send CID command and check the response. + * @param SDIOx: Pointer to SDIO register base + * @retval DAL status + */ +uint32_t SDMMC_CmdSendCID(SDIO_TypeDef *SDIOx) +{ + SDIO_CmdInitTypeDef sdmmc_cmdinit; + uint32_t errorstate; + + /* Send CMD2 ALL_SEND_CID */ + sdmmc_cmdinit.Argument = 0U; + sdmmc_cmdinit.CmdIndex = SDMMC_CMD_ALL_SEND_CID; + sdmmc_cmdinit.Response = SDIO_RESPONSE_LONG; + sdmmc_cmdinit.WaitForInterrupt = SDIO_WAIT_NO; + sdmmc_cmdinit.CPSM = SDIO_CPSM_ENABLE; + (void)SDIO_SendCommand(SDIOx, &sdmmc_cmdinit); + + /* Check for error conditions */ + errorstate = SDMMC_GetCmdResp2(SDIOx); + + return errorstate; +} + +/** + * @brief Send the Send CSD command and check the response. + * @param SDIOx: Pointer to SDIO register base + * @param Argument: Command Argument + * @retval DAL status + */ +uint32_t SDMMC_CmdSendCSD(SDIO_TypeDef *SDIOx, uint32_t Argument) +{ + SDIO_CmdInitTypeDef sdmmc_cmdinit; + uint32_t errorstate; + + /* Send CMD9 SEND_CSD */ + sdmmc_cmdinit.Argument = Argument; + sdmmc_cmdinit.CmdIndex = SDMMC_CMD_SEND_CSD; + sdmmc_cmdinit.Response = SDIO_RESPONSE_LONG; + sdmmc_cmdinit.WaitForInterrupt = SDIO_WAIT_NO; + sdmmc_cmdinit.CPSM = SDIO_CPSM_ENABLE; + (void)SDIO_SendCommand(SDIOx, &sdmmc_cmdinit); + + /* Check for error conditions */ + errorstate = SDMMC_GetCmdResp2(SDIOx); + + return errorstate; +} + +/** + * @brief Send the Send CSD command and check the response. + * @param SDIOx: Pointer to SDIO register base + * @param pRCA: Card RCA + * @retval DAL status + */ +uint32_t SDMMC_CmdSetRelAdd(SDIO_TypeDef *SDIOx, uint16_t *pRCA) +{ + SDIO_CmdInitTypeDef sdmmc_cmdinit; + uint32_t errorstate; + + /* Send CMD3 SD_CMD_SET_REL_ADDR */ + sdmmc_cmdinit.Argument = 0U; + sdmmc_cmdinit.CmdIndex = SDMMC_CMD_SET_REL_ADDR; + sdmmc_cmdinit.Response = SDIO_RESPONSE_SHORT; + sdmmc_cmdinit.WaitForInterrupt = SDIO_WAIT_NO; + sdmmc_cmdinit.CPSM = SDIO_CPSM_ENABLE; + (void)SDIO_SendCommand(SDIOx, &sdmmc_cmdinit); + + /* Check for error conditions */ + errorstate = SDMMC_GetCmdResp6(SDIOx, SDMMC_CMD_SET_REL_ADDR, pRCA); + + return errorstate; +} + +/** + * @brief Send the Set Relative Address command to MMC card (not SD card). + * @param SDIOx Pointer to SDIO register base + * @param RCA Card RCA + * @retval DAL status + */ +uint32_t SDMMC_CmdSetRelAddMmc(SDIO_TypeDef *SDIOx, uint16_t RCA) +{ + SDIO_CmdInitTypeDef sdmmc_cmdinit; + uint32_t errorstate; + + /* Send CMD3 SD_CMD_SET_REL_ADDR */ + sdmmc_cmdinit.Argument = ((uint32_t)RCA << 16U); + sdmmc_cmdinit.CmdIndex = SDMMC_CMD_SET_REL_ADDR; + sdmmc_cmdinit.Response = SDIO_RESPONSE_SHORT; + sdmmc_cmdinit.WaitForInterrupt = SDIO_WAIT_NO; + sdmmc_cmdinit.CPSM = SDIO_CPSM_ENABLE; + (void)SDIO_SendCommand(SDIOx, &sdmmc_cmdinit); + + /* Check for error conditions */ + errorstate = SDMMC_GetCmdResp1(SDIOx, SDMMC_CMD_SET_REL_ADDR, SDIO_CMDTIMEOUT); + + return errorstate; +} + +/** + * @brief Send the Status command and check the response. + * @param SDIOx: Pointer to SDIO register base + * @param Argument: Command Argument + * @retval DAL status + */ +uint32_t SDMMC_CmdSendStatus(SDIO_TypeDef *SDIOx, uint32_t Argument) +{ + SDIO_CmdInitTypeDef sdmmc_cmdinit; + uint32_t errorstate; + + sdmmc_cmdinit.Argument = Argument; + sdmmc_cmdinit.CmdIndex = SDMMC_CMD_SEND_STATUS; + sdmmc_cmdinit.Response = SDIO_RESPONSE_SHORT; + sdmmc_cmdinit.WaitForInterrupt = SDIO_WAIT_NO; + sdmmc_cmdinit.CPSM = SDIO_CPSM_ENABLE; + (void)SDIO_SendCommand(SDIOx, &sdmmc_cmdinit); + + /* Check for error conditions */ + errorstate = SDMMC_GetCmdResp1(SDIOx, SDMMC_CMD_SEND_STATUS, SDIO_CMDTIMEOUT); + + return errorstate; +} + +/** + * @brief Send the Status register command and check the response. + * @param SDIOx: Pointer to SDIO register base + * @retval DAL status + */ +uint32_t SDMMC_CmdStatusRegister(SDIO_TypeDef *SDIOx) +{ + SDIO_CmdInitTypeDef sdmmc_cmdinit; + uint32_t errorstate; + + sdmmc_cmdinit.Argument = 0U; + sdmmc_cmdinit.CmdIndex = SDMMC_CMD_SD_APP_STATUS; + sdmmc_cmdinit.Response = SDIO_RESPONSE_SHORT; + sdmmc_cmdinit.WaitForInterrupt = SDIO_WAIT_NO; + sdmmc_cmdinit.CPSM = SDIO_CPSM_ENABLE; + (void)SDIO_SendCommand(SDIOx, &sdmmc_cmdinit); + + /* Check for error conditions */ + errorstate = SDMMC_GetCmdResp1(SDIOx, SDMMC_CMD_SD_APP_STATUS, SDIO_CMDTIMEOUT); + + return errorstate; +} + +/** + * @brief Sends host capacity support information and activates the card's + * initialization process. Send SDMMC_CMD_SEND_OP_COND command + * @param SDIOx: Pointer to SDIO register base + * @parame Argument: Argument used for the command + * @retval DAL status + */ +uint32_t SDMMC_CmdOpCondition(SDIO_TypeDef *SDIOx, uint32_t Argument) +{ + SDIO_CmdInitTypeDef sdmmc_cmdinit; + uint32_t errorstate; + + sdmmc_cmdinit.Argument = Argument; + sdmmc_cmdinit.CmdIndex = SDMMC_CMD_SEND_OP_COND; + sdmmc_cmdinit.Response = SDIO_RESPONSE_SHORT; + sdmmc_cmdinit.WaitForInterrupt = SDIO_WAIT_NO; + sdmmc_cmdinit.CPSM = SDIO_CPSM_ENABLE; + (void)SDIO_SendCommand(SDIOx, &sdmmc_cmdinit); + + /* Check for error conditions */ + errorstate = SDMMC_GetCmdResp3(SDIOx); + + return errorstate; +} + +/** + * @brief Checks switchable function and switch card function. SDMMC_CMD_HS_SWITCH command + * @param SDIOx: Pointer to SDIO register base + * @parame Argument: Argument used for the command + * @retval DAL status + */ +uint32_t SDMMC_CmdSwitch(SDIO_TypeDef *SDIOx, uint32_t Argument) +{ + SDIO_CmdInitTypeDef sdmmc_cmdinit; + uint32_t errorstate; + + /* Send CMD6 to activate SDR50 Mode and Power Limit 1.44W */ + /* CMD Response: R1 */ + sdmmc_cmdinit.Argument = Argument; /* SDMMC_SDR25_SWITCH_PATTERN */ + sdmmc_cmdinit.CmdIndex = SDMMC_CMD_HS_SWITCH; + sdmmc_cmdinit.Response = SDIO_RESPONSE_SHORT; + sdmmc_cmdinit.WaitForInterrupt = SDIO_WAIT_NO; + sdmmc_cmdinit.CPSM = SDIO_CPSM_ENABLE; + (void)SDIO_SendCommand(SDIOx, &sdmmc_cmdinit); + + /* Check for error conditions */ + errorstate = SDMMC_GetCmdResp1(SDIOx, SDMMC_CMD_HS_SWITCH, SDIO_CMDTIMEOUT); + + return errorstate; +} + +/** + * @brief Send the Send EXT_CSD command and check the response. + * @param SDIOx Pointer to SDMMC register base + * @param Argument Command Argument + * @retval DAL status + */ +uint32_t SDMMC_CmdSendEXTCSD(SDIO_TypeDef *SDIOx, uint32_t Argument) +{ + SDIO_CmdInitTypeDef sdmmc_cmdinit; + uint32_t errorstate; + + /* Send CMD9 SEND_CSD */ + sdmmc_cmdinit.Argument = Argument; + sdmmc_cmdinit.CmdIndex = SDMMC_CMD_HS_SEND_EXT_CSD; + sdmmc_cmdinit.Response = SDIO_RESPONSE_SHORT; + sdmmc_cmdinit.WaitForInterrupt = SDIO_WAIT_NO; + sdmmc_cmdinit.CPSM = SDIO_CPSM_ENABLE; + (void)SDIO_SendCommand(SDIOx, &sdmmc_cmdinit); + + /* Check for error conditions */ + errorstate = SDMMC_GetCmdResp1(SDIOx, SDMMC_CMD_HS_SEND_EXT_CSD,SDIO_CMDTIMEOUT); + + return errorstate; +} + +/** + * @} + */ + +/** @defgroup DAL_SDMMC_DDL_Group5 Responses management functions + * @brief Responses functions + * +@verbatim + =============================================================================== + ##### Responses management functions ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to manage the needed responses. + +@endverbatim + * @{ + */ +/** + * @brief Checks for error conditions for R1 response. + * @param SDIOx Pointer to SDMMC register base + * @param SD_CMD: The sent command index + * @retval SD Card error state + */ +uint32_t SDMMC_GetCmdResp1(SDIO_TypeDef *SDIOx, uint8_t SD_CMD, uint32_t Timeout) +{ + uint32_t response_r1; + uint32_t sta_reg; + + /* 8 is the number of required instructions cycles for the below loop statement. + The Timeout is expressed in ms */ + uint32_t count = Timeout * (SystemCoreClock / 8U /1000U); + + do + { + if (count-- == 0U) + { + return SDMMC_ERROR_TIMEOUT; + } + sta_reg = SDIOx->STS; + }while(((sta_reg & (SDIO_FLAG_CCRCFAIL | SDIO_FLAG_CMDREND | SDIO_FLAG_CTIMEOUT)) == 0U) || + ((sta_reg & SDIO_FLAG_CMDACT) != 0U )); + + if(__SDIO_GET_FLAG(SDIOx, SDIO_FLAG_CTIMEOUT)) + { + __SDIO_CLEAR_FLAG(SDIOx, SDIO_FLAG_CTIMEOUT); + + return SDMMC_ERROR_CMD_RSP_TIMEOUT; + } + else if(__SDIO_GET_FLAG(SDIOx, SDIO_FLAG_CCRCFAIL)) + { + __SDIO_CLEAR_FLAG(SDIOx, SDIO_FLAG_CCRCFAIL); + + return SDMMC_ERROR_CMD_CRC_FAIL; + } + else + { + /* Nothing to do */ + } + + /* Clear all the static flags */ + __SDIO_CLEAR_FLAG(SDIOx, SDIO_STATIC_CMD_FLAGS); + + /* Check response received is of desired command */ + if(SDIO_GetCommandResponse(SDIOx) != SD_CMD) + { + return SDMMC_ERROR_CMD_CRC_FAIL; + } + + /* We have received response, retrieve it for analysis */ + response_r1 = SDIO_GetResponse(SDIOx, SDIO_RES1); + + if((response_r1 & SDMMC_OCR_ERRORBITS) == SDMMC_ALLZERO) + { + return SDMMC_ERROR_NONE; + } + else if((response_r1 & SDMMC_OCR_ADDR_OUT_OF_RANGE) == SDMMC_OCR_ADDR_OUT_OF_RANGE) + { + return SDMMC_ERROR_ADDR_OUT_OF_RANGE; + } + else if((response_r1 & SDMMC_OCR_ADDR_MISALIGNED) == SDMMC_OCR_ADDR_MISALIGNED) + { + return SDMMC_ERROR_ADDR_MISALIGNED; + } + else if((response_r1 & SDMMC_OCR_BLOCK_LEN_ERR) == SDMMC_OCR_BLOCK_LEN_ERR) + { + return SDMMC_ERROR_BLOCK_LEN_ERR; + } + else if((response_r1 & SDMMC_OCR_ERASE_SEQ_ERR) == SDMMC_OCR_ERASE_SEQ_ERR) + { + return SDMMC_ERROR_ERASE_SEQ_ERR; + } + else if((response_r1 & SDMMC_OCR_BAD_ERASE_PARAM) == SDMMC_OCR_BAD_ERASE_PARAM) + { + return SDMMC_ERROR_BAD_ERASE_PARAM; + } + else if((response_r1 & SDMMC_OCR_WRITE_PROT_VIOLATION) == SDMMC_OCR_WRITE_PROT_VIOLATION) + { + return SDMMC_ERROR_WRITE_PROT_VIOLATION; + } + else if((response_r1 & SDMMC_OCR_LOCK_UNLOCK_FAILED) == SDMMC_OCR_LOCK_UNLOCK_FAILED) + { + return SDMMC_ERROR_LOCK_UNLOCK_FAILED; + } + else if((response_r1 & SDMMC_OCR_COM_CRC_FAILED) == SDMMC_OCR_COM_CRC_FAILED) + { + return SDMMC_ERROR_COM_CRC_FAILED; + } + else if((response_r1 & SDMMC_OCR_ILLEGAL_CMD) == SDMMC_OCR_ILLEGAL_CMD) + { + return SDMMC_ERROR_ILLEGAL_CMD; + } + else if((response_r1 & SDMMC_OCR_CARD_ECC_FAILED) == SDMMC_OCR_CARD_ECC_FAILED) + { + return SDMMC_ERROR_CARD_ECC_FAILED; + } + else if((response_r1 & SDMMC_OCR_CC_ERROR) == SDMMC_OCR_CC_ERROR) + { + return SDMMC_ERROR_CC_ERR; + } + else if((response_r1 & SDMMC_OCR_STREAM_READ_UNDERRUN) == SDMMC_OCR_STREAM_READ_UNDERRUN) + { + return SDMMC_ERROR_STREAM_READ_UNDERRUN; + } + else if((response_r1 & SDMMC_OCR_STREAM_WRITE_OVERRUN) == SDMMC_OCR_STREAM_WRITE_OVERRUN) + { + return SDMMC_ERROR_STREAM_WRITE_OVERRUN; + } + else if((response_r1 & SDMMC_OCR_CID_CSD_OVERWRITE) == SDMMC_OCR_CID_CSD_OVERWRITE) + { + return SDMMC_ERROR_CID_CSD_OVERWRITE; + } + else if((response_r1 & SDMMC_OCR_WP_ERASE_SKIP) == SDMMC_OCR_WP_ERASE_SKIP) + { + return SDMMC_ERROR_WP_ERASE_SKIP; + } + else if((response_r1 & SDMMC_OCR_CARD_ECC_DISABLED) == SDMMC_OCR_CARD_ECC_DISABLED) + { + return SDMMC_ERROR_CARD_ECC_DISABLED; + } + else if((response_r1 & SDMMC_OCR_ERASE_RESET) == SDMMC_OCR_ERASE_RESET) + { + return SDMMC_ERROR_ERASE_RESET; + } + else if((response_r1 & SDMMC_OCR_AKE_SEQ_ERROR) == SDMMC_OCR_AKE_SEQ_ERROR) + { + return SDMMC_ERROR_AKE_SEQ_ERR; + } + else + { + return SDMMC_ERROR_GENERAL_UNKNOWN_ERR; + } +} + +/** + * @brief Checks for error conditions for R2 (CID or CSD) response. + * @param SDIOx Pointer to SDMMC register base + * @retval SD Card error state + */ +uint32_t SDMMC_GetCmdResp2(SDIO_TypeDef *SDIOx) +{ + uint32_t sta_reg; + /* 8 is the number of required instructions cycles for the below loop statement. + The SDIO_CMDTIMEOUT is expressed in ms */ + uint32_t count = SDIO_CMDTIMEOUT * (SystemCoreClock / 8U /1000U); + + do + { + if (count-- == 0U) + { + return SDMMC_ERROR_TIMEOUT; + } + sta_reg = SDIOx->STS; + }while(((sta_reg & (SDIO_FLAG_CCRCFAIL | SDIO_FLAG_CMDREND | SDIO_FLAG_CTIMEOUT)) == 0U) || + ((sta_reg & SDIO_FLAG_CMDACT) != 0U )); + + if (__SDIO_GET_FLAG(SDIOx, SDIO_FLAG_CTIMEOUT)) + { + __SDIO_CLEAR_FLAG(SDIOx, SDIO_FLAG_CTIMEOUT); + + return SDMMC_ERROR_CMD_RSP_TIMEOUT; + } + else if (__SDIO_GET_FLAG(SDIOx, SDIO_FLAG_CCRCFAIL)) + { + __SDIO_CLEAR_FLAG(SDIOx, SDIO_FLAG_CCRCFAIL); + + return SDMMC_ERROR_CMD_CRC_FAIL; + } + else + { + /* No error flag set */ + /* Clear all the static flags */ + __SDIO_CLEAR_FLAG(SDIOx, SDIO_STATIC_CMD_FLAGS); + } + + return SDMMC_ERROR_NONE; +} + +/** + * @brief Checks for error conditions for R3 (OCR) response. + * @param SDIOx Pointer to SDMMC register base + * @retval SD Card error state + */ +uint32_t SDMMC_GetCmdResp3(SDIO_TypeDef *SDIOx) +{ + uint32_t sta_reg; + /* 8 is the number of required instructions cycles for the below loop statement. + The SDIO_CMDTIMEOUT is expressed in ms */ + uint32_t count = SDIO_CMDTIMEOUT * (SystemCoreClock / 8U /1000U); + + do + { + if (count-- == 0U) + { + return SDMMC_ERROR_TIMEOUT; + } + sta_reg = SDIOx->STS; + }while(((sta_reg & (SDIO_FLAG_CCRCFAIL | SDIO_FLAG_CMDREND | SDIO_FLAG_CTIMEOUT)) == 0U) || + ((sta_reg & SDIO_FLAG_CMDACT) != 0U )); + + if(__SDIO_GET_FLAG(SDIOx, SDIO_FLAG_CTIMEOUT)) + { + __SDIO_CLEAR_FLAG(SDIOx, SDIO_FLAG_CTIMEOUT); + + return SDMMC_ERROR_CMD_RSP_TIMEOUT; + } + else + { + /* Clear all the static flags */ + __SDIO_CLEAR_FLAG(SDIOx, SDIO_STATIC_CMD_FLAGS); + } + + return SDMMC_ERROR_NONE; +} + +/** + * @brief Checks for error conditions for R6 (RCA) response. + * @param SDIOx Pointer to SDMMC register base + * @param SD_CMD: The sent command index + * @param pRCA: Pointer to the variable that will contain the SD card relative + * address RCA + * @retval SD Card error state + */ +uint32_t SDMMC_GetCmdResp6(SDIO_TypeDef *SDIOx, uint8_t SD_CMD, uint16_t *pRCA) +{ + uint32_t response_r1; + uint32_t sta_reg; + + /* 8 is the number of required instructions cycles for the below loop statement. + The SDIO_CMDTIMEOUT is expressed in ms */ + uint32_t count = SDIO_CMDTIMEOUT * (SystemCoreClock / 8U /1000U); + + do + { + if (count-- == 0U) + { + return SDMMC_ERROR_TIMEOUT; + } + sta_reg = SDIOx->STS; + }while(((sta_reg & (SDIO_FLAG_CCRCFAIL | SDIO_FLAG_CMDREND | SDIO_FLAG_CTIMEOUT)) == 0U) || + ((sta_reg & SDIO_FLAG_CMDACT) != 0U )); + + if(__SDIO_GET_FLAG(SDIOx, SDIO_FLAG_CTIMEOUT)) + { + __SDIO_CLEAR_FLAG(SDIOx, SDIO_FLAG_CTIMEOUT); + + return SDMMC_ERROR_CMD_RSP_TIMEOUT; + } + else if(__SDIO_GET_FLAG(SDIOx, SDIO_FLAG_CCRCFAIL)) + { + __SDIO_CLEAR_FLAG(SDIOx, SDIO_FLAG_CCRCFAIL); + + return SDMMC_ERROR_CMD_CRC_FAIL; + } + else + { + /* Nothing to do */ + } + + /* Check response received is of desired command */ + if(SDIO_GetCommandResponse(SDIOx) != SD_CMD) + { + return SDMMC_ERROR_CMD_CRC_FAIL; + } + + /* Clear all the static flags */ + __SDIO_CLEAR_FLAG(SDIOx, SDIO_STATIC_CMD_FLAGS); + + /* We have received response, retrieve it. */ + response_r1 = SDIO_GetResponse(SDIOx, SDIO_RES1); + + if((response_r1 & (SDMMC_R6_GENERAL_UNKNOWN_ERROR | SDMMC_R6_ILLEGAL_CMD | SDMMC_R6_COM_CRC_FAILED)) == SDMMC_ALLZERO) + { + *pRCA = (uint16_t) (response_r1 >> 16); + + return SDMMC_ERROR_NONE; + } + else if((response_r1 & SDMMC_R6_ILLEGAL_CMD) == SDMMC_R6_ILLEGAL_CMD) + { + return SDMMC_ERROR_ILLEGAL_CMD; + } + else if((response_r1 & SDMMC_R6_COM_CRC_FAILED) == SDMMC_R6_COM_CRC_FAILED) + { + return SDMMC_ERROR_COM_CRC_FAILED; + } + else + { + return SDMMC_ERROR_GENERAL_UNKNOWN_ERR; + } +} + +/** + * @brief Checks for error conditions for R7 response. + * @param SDIOx Pointer to SDMMC register base + * @retval SD Card error state + */ +uint32_t SDMMC_GetCmdResp7(SDIO_TypeDef *SDIOx) +{ + uint32_t sta_reg; + /* 8 is the number of required instructions cycles for the below loop statement. + The SDIO_CMDTIMEOUT is expressed in ms */ + uint32_t count = SDIO_CMDTIMEOUT * (SystemCoreClock / 8U /1000U); + + do + { + if (count-- == 0U) + { + return SDMMC_ERROR_TIMEOUT; + } + sta_reg = SDIOx->STS; + }while(((sta_reg & (SDIO_FLAG_CCRCFAIL | SDIO_FLAG_CMDREND | SDIO_FLAG_CTIMEOUT)) == 0U) || + ((sta_reg & SDIO_FLAG_CMDACT) != 0U )); + + if(__SDIO_GET_FLAG(SDIOx, SDIO_FLAG_CTIMEOUT)) + { + /* Card is SD V2.0 compliant */ + __SDIO_CLEAR_FLAG(SDIOx, SDIO_FLAG_CTIMEOUT); + + return SDMMC_ERROR_CMD_RSP_TIMEOUT; + } + else if(__SDIO_GET_FLAG(SDIOx, SDIO_FLAG_CCRCFAIL)) + { + /* Card is SD V2.0 compliant */ + __SDIO_CLEAR_FLAG(SDIOx, SDIO_FLAG_CCRCFAIL); + + return SDMMC_ERROR_CMD_CRC_FAIL; + } + else + { + /* Nothing to do */ + } + + if(__SDIO_GET_FLAG(SDIOx, SDIO_FLAG_CMDREND)) + { + /* Card is SD V2.0 compliant */ + __SDIO_CLEAR_FLAG(SDIOx, SDIO_FLAG_CMDREND); + } + + return SDMMC_ERROR_NONE; + +} + +/** + * @} + */ + +/* Private function ----------------------------------------------------------*/ +/** @addtogroup SD_Private_Functions + * @{ + */ + +/** + * @brief Checks for error conditions for CMD0. + * @param SDIOx Pointer to SDMMC register base + * @retval SD Card error state + */ +static uint32_t SDMMC_GetCmdError(SDIO_TypeDef *SDIOx) +{ + /* 8 is the number of required instructions cycles for the below loop statement. + The SDIO_CMDTIMEOUT is expressed in ms */ + uint32_t count = SDIO_CMDTIMEOUT * (SystemCoreClock / 8U /1000U); + + do + { + if (count-- == 0U) + { + return SDMMC_ERROR_TIMEOUT; + } + + }while(!__SDIO_GET_FLAG(SDIOx, SDIO_FLAG_CMDSENT)); + + /* Clear all the static flags */ + __SDIO_CLEAR_FLAG(SDIOx, SDIO_STATIC_CMD_FLAGS); + + return SDMMC_ERROR_NONE; +} + + +/** + * @} + */ + +#endif /* DAL_SD_MODULE_ENABLED || DAL_MMC_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + +#endif /* SDIO */ diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_ddl_smc.c b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_ddl_smc.c new file mode 100644 index 0000000000..67626b345d --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_ddl_smc.c @@ -0,0 +1,1087 @@ +/** + * + * @file apm32f4xx_ddl_smc.c + * @brief SMC Low Layer DDL module driver. + * + * This file provides firmware functions to manage the following + * functionalities of the Static Memory Controller (SMC) peripheral memories: + * + Initialization/de-initialization functions + * + Peripheral Control functions + * + Peripheral State functions + * + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + * + @verbatim + ============================================================================== + ##### SMC peripheral features ##### + ============================================================================== + [..] The Static memory controller (SMC) includes following memory controllers: + (+) The NOR/PSRAM memory controller + (+) The NAND/PC Card memory controller + + [..] The SMC functional block makes the interface with synchronous and asynchronous static + memories and 16-bit PC memory cards. Its main purposes are: + (+) to translate AHB transactions into the appropriate external device protocol + (+) to meet the access time requirements of the external memory devices + + [..] All external memories share the addresses, data and control signals with the controller. + Each external device is accessed by means of a unique Chip Select. The SMC performs + only one access at a time to an external device. + The main features of the SMC controller are the following: + (+) Interface with static-memory mapped devices including: + (++) Static random access memory (SRAM) + (++) Read-only memory (ROM) + (++) NOR Flash memory/OneNAND Flash memory + (++) PSRAM (4 memory banks) + (++) 16-bit PC Card compatible devices + (++) Two banks of NAND Flash memory with ECC hardware to check up to 8 Kbytes of + data + (+) Independent Chip Select control for each memory bank + (+) Independent configuration for each memory bank + + @endverbatim + * + */ + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ +#if defined(DAL_NOR_MODULE_ENABLED) || defined(DAL_SRAM_MODULE_ENABLED) || defined(DAL_NAND_MODULE_ENABLED) || defined(DAL_PCCARD_MODULE_ENABLED) + +/** @defgroup SMC_DDL SMC Low Layer + * @brief SMC driver modules + * @{ + */ + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ + +/** @defgroup SMC_DDL_Private_Constants SMC Low Layer Private Constants + * @{ + */ + +/* ----------------------- SMC registers bit mask --------------------------- */ + +#if defined(SMC_Bank1) +/* --- BCR Register ---*/ +/* BCR register clear mask */ + +/* --- BTR Register ---*/ +/* BTR register clear mask */ +#define BTR_CLEAR_MASK ((uint32_t)(SMC_CSTIM1_ADDRSETCFG | SMC_CSTIM1_ADDRHLDCFG |\ + SMC_CSTIM1_DATASETCFG | SMC_CSTIM1_BUSTURNCFG |\ + SMC_CSTIM1_CLKDIVCFG | SMC_CSTIM1_DATALATCFG |\ + SMC_CSTIM1_ASYNCACCCFG)) + +/* --- BWTR Register ---*/ +/* BWTR register clear mask */ +#define BWTR_CLEAR_MASK ((uint32_t)(SMC_WRTTIM1_ADDRSETCFG | SMC_WRTTIM1_ADDRHLDCFG |\ + SMC_WRTTIM1_DATASETCFG | SMC_WRTTIM1_BUSTURNCFG |\ + SMC_WRTTIM1_ASYNCACCCFG)) +#endif /* SMC_Bank1 */ +#if defined(SMC_Bank2_3) + +#if defined (SMC_PCR_PWAITEN) +/* --- PCR Register ---*/ +/* PCR register clear mask */ +#define PCR_CLEAR_MASK ((uint32_t)(SMC_PCR_PWAITEN | SMC_PCR_PBKEN | \ + SMC_PCR_PTYP | SMC_PCR_PWID | \ + SMC_PCR_ECCEN | SMC_PCR_TCLR | \ + SMC_PCR_TAR | SMC_PCR_ECCPS)) +/* --- PMEM Register ---*/ +/* PMEM register clear mask */ +#define PMEM_CLEAR_MASK ((uint32_t)(SMC_PMEM_MEMSET2 | SMC_PMEM_MEMWAIT2 |\ + SMC_PMEM_MEMHOLD2 | SMC_PMEM_MEMHIZ2)) + +/* --- PATT Register ---*/ +/* PATT register clear mask */ +#define PATT_CLEAR_MASK ((uint32_t)(SMC_PATT_ATTSET2 | SMC_PATT_ATTWAIT2 |\ + SMC_PATT_ATTHOLD2 | SMC_PATT_ATTHIZ2)) +#else +/* --- PCR Register ---*/ +/* PCR register clear mask */ +#define PCR_CLEAR_MASK ((uint32_t)(SMC_CTRL2_WAITFEN | SMC_CTRL2_MBKEN | \ + SMC_CTRL2_MTYPECFG | SMC_CTRL2_DBWIDCFG | \ + SMC_CTRL2_ECCEN | SMC_CTRL2_C2RDCFG | \ + SMC_CTRL2_A2RDCFG | SMC_CTRL2_ECCPSCFG)) +/* --- PMEM Register ---*/ +/* PMEM register clear mask */ +#define PMEM_CLEAR_MASK ((uint32_t)(SMC_CMSTIM2_SET2 | SMC_CMSTIM2_WAIT2 |\ + SMC_CMSTIM2_HLD2 | SMC_CMSTIM2_HIZ2)) + +/* --- PATT Register ---*/ +/* PATT register clear mask */ +#define PATT_CLEAR_MASK ((uint32_t)(SMC_AMSTIM2_SET2 | SMC_AMSTIM2_WAIT2 |\ + SMC_AMSTIM2_HLD2 | SMC_AMSTIM2_HIZ2)) + +#endif /* SMC_PCR_PWAITEN */ +#endif /* SMC_Bank2_3 */ +#if defined(SMC_Bank4) +/* --- PCR Register ---*/ +/* PCR register clear mask */ +#define PCR4_CLEAR_MASK ((uint32_t)(SMC_CTRL4_WAITFEN | SMC_CTRL4_MBKEN | \ + SMC_CTRL4_MTYPECFG | SMC_CTRL4_DBWIDCFG | \ + SMC_CTRL4_ECCEN | SMC_CTRL4_C2RDCFG | \ + SMC_CTRL4_A2RDCFG | SMC_CTRL4_ECCPSCFG)) +/* --- PMEM Register ---*/ +/* PMEM register clear mask */ +#define PMEM4_CLEAR_MASK ((uint32_t)(SMC_CMSTIM4_SET4 | SMC_CMSTIM4_WAIT4 |\ + SMC_CMSTIM4_HLD4 | SMC_CMSTIM4_HIZ4)) + +/* --- PATT Register ---*/ +/* PATT register clear mask */ +#define PATT4_CLEAR_MASK ((uint32_t)(SMC_AMSTIM4_SET4 | SMC_AMSTIM4_WAIT4 |\ + SMC_AMSTIM4_HLD4 | SMC_AMSTIM4_HIZ4)) + +/* --- PIO4 Register ---*/ +/* PIO4 register clear mask */ +#define PIO4_CLEAR_MASK ((uint32_t)(SMC_IOSTIM4_SET4 | SMC_IOSTIM4_WAIT4 | \ + SMC_IOSTIM4_HLD4 | SMC_IOSTIM4_HIZ4)) + +#endif /* SMC_Bank4 */ + +/** + * @} + */ + +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Exported functions --------------------------------------------------------*/ + +/** @defgroup SMC_DDL_Exported_Functions SMC Low Layer Exported Functions + * @{ + */ + +#if defined(SMC_Bank1) + +/** @defgroup SMC_DDL_Exported_Functions_NORSRAM SMC Low Layer NOR SRAM Exported Functions + * @brief NORSRAM Controller functions + * + @verbatim + ============================================================================== + ##### How to use NORSRAM device driver ##### + ============================================================================== + + [..] + This driver contains a set of APIs to interface with the SMC NORSRAM banks in order + to run the NORSRAM external devices. + + (+) SMC NORSRAM bank reset using the function SMC_NORSRAM_DeInit() + (+) SMC NORSRAM bank control configuration using the function SMC_NORSRAM_Init() + (+) SMC NORSRAM bank timing configuration using the function SMC_NORSRAM_Timing_Init() + (+) SMC NORSRAM bank extended timing configuration using the function + SMC_NORSRAM_Extended_Timing_Init() + (+) SMC NORSRAM bank enable/disable write operation using the functions + SMC_NORSRAM_WriteOperation_Enable()/SMC_NORSRAM_WriteOperation_Disable() + +@endverbatim + * @{ + */ + +/** @defgroup SMC_DDL_NORSRAM_Exported_Functions_Group1 Initialization and de-initialization functions + * @brief Initialization and Configuration functions + * + @verbatim + ============================================================================== + ##### Initialization and de_initialization functions ##### + ============================================================================== + [..] + This section provides functions allowing to: + (+) Initialize and configure the SMC NORSRAM interface + (+) De-initialize the SMC NORSRAM interface + (+) Configure the SMC clock and associated GPIOs + +@endverbatim + * @{ + */ + +/** + * @brief Initialize the SMC_NORSRAM device according to the specified + * control parameters in the SMC_NORSRAM_InitTypeDef + * @param Device Pointer to NORSRAM device instance + * @param Init Pointer to NORSRAM Initialization structure + * @retval DAL status + */ +DAL_StatusTypeDef SMC_NORSRAM_Init(SMC_NORSRAM_TypeDef *Device, + SMC_NORSRAM_InitTypeDef *Init) +{ + uint32_t flashaccess; + uint32_t btcr_reg; + uint32_t mask; + + /* Check the parameters */ + ASSERT_PARAM(IS_SMC_NORSRAM_DEVICE(Device)); + ASSERT_PARAM(IS_SMC_NORSRAM_BANK(Init->NSBank)); + ASSERT_PARAM(IS_SMC_MUX(Init->DataAddressMux)); + ASSERT_PARAM(IS_SMC_MEMORY(Init->MemoryType)); + ASSERT_PARAM(IS_SMC_NORSRAM_MEMORY_WIDTH(Init->MemoryDataWidth)); + ASSERT_PARAM(IS_SMC_BURSTMODE(Init->BurstAccessMode)); + ASSERT_PARAM(IS_SMC_WAIT_POLARITY(Init->WaitSignalPolarity)); +#if defined(SMC_CSCTRL1_WRAPBEN) + ASSERT_PARAM(IS_SMC_WRAP_MODE(Init->WrapMode)); +#endif /* SMC_CSCTRL1_WRAPBEN */ + ASSERT_PARAM(IS_SMC_WAIT_SIGNAL_ACTIVE(Init->WaitSignalActive)); + ASSERT_PARAM(IS_SMC_WRITE_OPERATION(Init->WriteOperation)); + ASSERT_PARAM(IS_SMC_WAITE_SIGNAL(Init->WaitSignal)); + ASSERT_PARAM(IS_SMC_EXTENDED_MODE(Init->ExtendedMode)); + ASSERT_PARAM(IS_SMC_ASYNWAIT(Init->AsynchronousWait)); + ASSERT_PARAM(IS_SMC_WRITE_BURST(Init->WriteBurst)); +#if defined(SMC_CSCTRL1_CCLKEN) + ASSERT_PARAM(IS_SMC_CONTINOUS_CLOCK(Init->ContinuousClock)); +#endif +#if defined(SMC_CSCTRL1_WFDIS) + ASSERT_PARAM(IS_SMC_WRITE_FIFO(Init->WriteFifo)); +#endif /* SMC_CSCTRL1_WFDIS */ + ASSERT_PARAM(IS_SMC_PAGESIZE(Init->PageSize)); + + /* Disable NORSRAM Device */ + __SMC_NORSRAM_DISABLE(Device, Init->NSBank); + + /* Set NORSRAM device control parameters */ + if (Init->MemoryType == SMC_MEMORY_TYPE_NOR) + { + flashaccess = SMC_NORSRAM_FLASH_ACCESS_ENABLE; + } + else + { + flashaccess = SMC_NORSRAM_FLASH_ACCESS_DISABLE; + } + + btcr_reg = (flashaccess | \ + Init->DataAddressMux | \ + Init->MemoryType | \ + Init->MemoryDataWidth | \ + Init->BurstAccessMode | \ + Init->WaitSignalPolarity | \ + Init->WaitSignalActive | \ + Init->WriteOperation | \ + Init->WaitSignal | \ + Init->ExtendedMode | \ + Init->AsynchronousWait | \ + Init->WriteBurst); + +#if defined(SMC_CSCTRL1_WRAPBEN) + btcr_reg |= Init->WrapMode; +#endif /* SMC_CSCTRL1_WRAPBEN */ +#if defined(SMC_CSCTRL1_CCLKEN) + btcr_reg |= Init->ContinuousClock; +#endif /* SMC_CSCTRL1_CCLKEN */ +#if defined(SMC_CSCTRL1_WFDIS) + btcr_reg |= Init->WriteFifo; +#endif /* SMC_CSCTRL1_WFDIS */ + btcr_reg |= Init->PageSize; + + mask = (SMC_CSCTRL1_MBKEN | + SMC_CSCTRL1_ADMUXEN | + SMC_CSCTRL1_MTYPECFG | + SMC_CSCTRL1_MDBWIDCFG | + SMC_CSCTRL1_NORFMACCEN | + SMC_CSCTRL1_BURSTEN | + SMC_CSCTRL1_WSPOLCFG | + SMC_CSCTRL1_WTIMCFG | + SMC_CSCTRL1_WREN | + SMC_CSCTRL1_WAITEN | + SMC_CSCTRL1_EXTMODEEN | + SMC_CSCTRL1_WSASYNCEN | + SMC_CSCTRL1_WRBURSTEN); + +#if defined(SMC_CSCTRL1_WRAPBEN) + mask |= SMC_CSCTRL1_WRAPBEN; +#endif /* SMC_CSCTRL1_WRAPBEN */ +#if defined(SMC_CSCTRL1_CCLKEN) + mask |= SMC_CSCTRL1_CCLKEN; +#endif +#if defined(SMC_CSCTRL1_WFDIS) + mask |= SMC_CSCTRL1_WFDIS; +#endif /* SMC_CSCTRL1_WFDIS */ + mask |= SMC_CSCTRL1_CRAMPSIZECFG; + + MODIFY_REG(Device->CSTR[Init->NSBank], mask, btcr_reg); + +#if defined(SMC_CSCTRL1_CCLKEN) + /* Configure synchronous mode when Continuous clock is enabled for bank2..4 */ + if ((Init->ContinuousClock == SMC_CONTINUOUS_CLOCK_SYNC_ASYNC) && (Init->NSBank != SMC_NORSRAM_BANK1)) + { + MODIFY_REG(Device->CSTR[SMC_NORSRAM_BANK1], SMC_CSCTRL1_CCLKEN, Init->ContinuousClock); + } +#endif +#if defined(SMC_CSCTRL1_WFDIS) + + if (Init->NSBank != SMC_NORSRAM_BANK1) + { + /* Configure Write FIFO mode when Write Fifo is enabled for bank2..4 */ + SET_BIT(Device->CSTR[SMC_NORSRAM_BANK1], (uint32_t)(Init->WriteFifo)); + } +#endif /* SMC_CSCTRL1_WFDIS */ + + return DAL_OK; +} + +/** + * @brief DeInitialize the SMC_NORSRAM peripheral + * @param Device Pointer to NORSRAM device instance + * @param ExDevice Pointer to NORSRAM extended mode device instance + * @param Bank NORSRAM bank number + * @retval DAL status + */ +DAL_StatusTypeDef SMC_NORSRAM_DeInit(SMC_NORSRAM_TypeDef *Device, + SMC_NORSRAM_EXTENDED_TypeDef *ExDevice, uint32_t Bank) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_SMC_NORSRAM_DEVICE(Device)); + ASSERT_PARAM(IS_SMC_NORSRAM_EXTENDED_DEVICE(ExDevice)); + ASSERT_PARAM(IS_SMC_NORSRAM_BANK(Bank)); + + /* Disable the SMC_NORSRAM device */ + __SMC_NORSRAM_DISABLE(Device, Bank); + + /* De-initialize the SMC_NORSRAM device */ + /* SMC_NORSRAM_BANK1 */ + if (Bank == SMC_NORSRAM_BANK1) + { + Device->CSTR[Bank] = 0x000030DBU; + } + /* SMC_NORSRAM_BANK2, SMC_NORSRAM_BANK3 or SMC_NORSRAM_BANK4 */ + else + { + Device->CSTR[Bank] = 0x000030D2U; + } + + Device->CSTR[Bank + 1U] = 0x0FFFFFFFU; + ExDevice->WRTTIM[Bank] = 0x0FFFFFFFU; + + return DAL_OK; +} + +/** + * @brief Initialize the SMC_NORSRAM Timing according to the specified + * parameters in the SMC_NORSRAM_TimingTypeDef + * @param Device Pointer to NORSRAM device instance + * @param Timing Pointer to NORSRAM Timing structure + * @param Bank NORSRAM bank number + * @retval DAL status + */ +DAL_StatusTypeDef SMC_NORSRAM_Timing_Init(SMC_NORSRAM_TypeDef *Device, + SMC_NORSRAM_TimingTypeDef *Timing, uint32_t Bank) +{ +#if defined(SMC_CSCTRL1_CCLKEN) + uint32_t tmpr; +#endif + + /* Check the parameters */ + ASSERT_PARAM(IS_SMC_NORSRAM_DEVICE(Device)); + ASSERT_PARAM(IS_SMC_ADDRESS_SETUP_TIME(Timing->AddressSetupTime)); + ASSERT_PARAM(IS_SMC_ADDRESS_HOLD_TIME(Timing->AddressHoldTime)); + ASSERT_PARAM(IS_SMC_DATASETUP_TIME(Timing->DataSetupTime)); + ASSERT_PARAM(IS_SMC_TURNAROUND_TIME(Timing->BusTurnAroundDuration)); + ASSERT_PARAM(IS_SMC_CLK_DIV(Timing->CLKDivision)); + ASSERT_PARAM(IS_SMC_DATA_LATENCY(Timing->DataLatency)); + ASSERT_PARAM(IS_SMC_ACCESS_MODE(Timing->AccessMode)); + ASSERT_PARAM(IS_SMC_NORSRAM_BANK(Bank)); + + /* Set SMC_NORSRAM device timing parameters */ + MODIFY_REG(Device->CSTR[Bank + 1U], BTR_CLEAR_MASK, (Timing->AddressSetupTime | + ((Timing->AddressHoldTime) << SMC_CSTIM1_ADDRHLDCFG_Pos) | + ((Timing->DataSetupTime) << SMC_CSTIM1_DATASETCFG_Pos) | + ((Timing->BusTurnAroundDuration) << SMC_CSTIM1_BUSTURNCFG_Pos) | + (((Timing->CLKDivision) - 1U) << SMC_CSTIM1_CLKDIVCFG_Pos) | + (((Timing->DataLatency) - 2U) << SMC_CSTIM1_DATALATCFG_Pos) | + (Timing->AccessMode))); + +#if defined(SMC_CSCTRL1_CCLKEN) + /* Configure Clock division value (in NORSRAM bank 1) when continuous clock is enabled */ + if (DAL_IS_BIT_SET(Device->CSTR[SMC_NORSRAM_BANK1], SMC_CSCTRL1_CCLKEN)) + { + tmpr = (uint32_t)(Device->CSTR[SMC_NORSRAM_BANK1 + 1U] & ~((0x0FU) << SMC_CSTIM1_CLKDIVCFG_Pos)); + tmpr |= (uint32_t)(((Timing->CLKDivision) - 1U) << SMC_CSTIM1_CLKDIVCFG_Pos); + MODIFY_REG(Device->CSTR[SMC_NORSRAM_BANK1 + 1U], SMC_CSTIM1_CLKDIVCFG, tmpr); + } + +#endif + return DAL_OK; +} + +/** + * @brief Initialize the SMC_NORSRAM Extended mode Timing according to the specified + * parameters in the SMC_NORSRAM_TimingTypeDef + * @param Device Pointer to NORSRAM device instance + * @param Timing Pointer to NORSRAM Timing structure + * @param Bank NORSRAM bank number + * @param ExtendedMode SMC Extended Mode + * This parameter can be one of the following values: + * @arg SMC_EXTENDED_MODE_DISABLE + * @arg SMC_EXTENDED_MODE_ENABLE + * @retval DAL status + */ +DAL_StatusTypeDef SMC_NORSRAM_Extended_Timing_Init(SMC_NORSRAM_EXTENDED_TypeDef *Device, + SMC_NORSRAM_TimingTypeDef *Timing, uint32_t Bank, + uint32_t ExtendedMode) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_SMC_EXTENDED_MODE(ExtendedMode)); + + /* Set NORSRAM device timing register for write configuration, if extended mode is used */ + if (ExtendedMode == SMC_EXTENDED_MODE_ENABLE) + { + /* Check the parameters */ + ASSERT_PARAM(IS_SMC_NORSRAM_EXTENDED_DEVICE(Device)); + ASSERT_PARAM(IS_SMC_ADDRESS_SETUP_TIME(Timing->AddressSetupTime)); + ASSERT_PARAM(IS_SMC_ADDRESS_HOLD_TIME(Timing->AddressHoldTime)); + ASSERT_PARAM(IS_SMC_DATASETUP_TIME(Timing->DataSetupTime)); + ASSERT_PARAM(IS_SMC_TURNAROUND_TIME(Timing->BusTurnAroundDuration)); + ASSERT_PARAM(IS_SMC_ACCESS_MODE(Timing->AccessMode)); + ASSERT_PARAM(IS_SMC_NORSRAM_BANK(Bank)); + + /* Set NORSRAM device timing register for write configuration, if extended mode is used */ + MODIFY_REG(Device->WRTTIM[Bank], BWTR_CLEAR_MASK, (Timing->AddressSetupTime | + ((Timing->AddressHoldTime) << SMC_WRTTIM1_ADDRHLDCFG_Pos) | + ((Timing->DataSetupTime) << SMC_WRTTIM1_DATASETCFG_Pos) | + Timing->AccessMode | + ((Timing->BusTurnAroundDuration) << SMC_WRTTIM1_BUSTURNCFG_Pos))); + } + else + { + Device->WRTTIM[Bank] = 0x0FFFFFFFU; + } + + return DAL_OK; +} +/** + * @} + */ + +/** @addtogroup SMC_DDL_NORSRAM_Private_Functions_Group2 + * @brief management functions + * +@verbatim + ============================================================================== + ##### SMC_NORSRAM Control functions ##### + ============================================================================== + [..] + This subsection provides a set of functions allowing to control dynamically + the SMC NORSRAM interface. + +@endverbatim + * @{ + */ + +/** + * @brief Enables dynamically SMC_NORSRAM write operation. + * @param Device Pointer to NORSRAM device instance + * @param Bank NORSRAM bank number + * @retval DAL status + */ +DAL_StatusTypeDef SMC_NORSRAM_WriteOperation_Enable(SMC_NORSRAM_TypeDef *Device, uint32_t Bank) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_SMC_NORSRAM_DEVICE(Device)); + ASSERT_PARAM(IS_SMC_NORSRAM_BANK(Bank)); + + /* Enable write operation */ + SET_BIT(Device->CSTR[Bank], SMC_WRITE_OPERATION_ENABLE); + + return DAL_OK; +} + +/** + * @brief Disables dynamically SMC_NORSRAM write operation. + * @param Device Pointer to NORSRAM device instance + * @param Bank NORSRAM bank number + * @retval DAL status + */ +DAL_StatusTypeDef SMC_NORSRAM_WriteOperation_Disable(SMC_NORSRAM_TypeDef *Device, uint32_t Bank) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_SMC_NORSRAM_DEVICE(Device)); + ASSERT_PARAM(IS_SMC_NORSRAM_BANK(Bank)); + + /* Disable write operation */ + CLEAR_BIT(Device->CSTR[Bank], SMC_WRITE_OPERATION_ENABLE); + + return DAL_OK; +} + +/** + * @} + */ + +/** + * @} + */ +#endif /* SMC_Bank1 */ + +#if defined(SMC_Bank2_3) + +/** @defgroup SMC_DDL_Exported_Functions_NAND SMC Low Layer NAND Exported Functions + * @brief NAND Controller functions + * + @verbatim + ============================================================================== + ##### How to use NAND device driver ##### + ============================================================================== + [..] + This driver contains a set of APIs to interface with the SMC NAND banks in order + to run the NAND external devices. + + (+) SMC NAND bank reset using the function SMC_NAND_DeInit() + (+) SMC NAND bank control configuration using the function SMC_NAND_Init() + (+) SMC NAND bank common space timing configuration using the function + SMC_NAND_CommonSpace_Timing_Init() + (+) SMC NAND bank attribute space timing configuration using the function + SMC_NAND_AttributeSpace_Timing_Init() + (+) SMC NAND bank enable/disable ECC correction feature using the functions + SMC_NAND_ECC_Enable()/SMC_NAND_ECC_Disable() + (+) SMC NAND bank get ECC correction code using the function SMC_NAND_GetECC() + +@endverbatim + * @{ + */ + +/** @defgroup SMC_DDL_NAND_Exported_Functions_Group1 Initialization and de-initialization functions + * @brief Initialization and Configuration functions + * +@verbatim + ============================================================================== + ##### Initialization and de_initialization functions ##### + ============================================================================== + [..] + This section provides functions allowing to: + (+) Initialize and configure the SMC NAND interface + (+) De-initialize the SMC NAND interface + (+) Configure the SMC clock and associated GPIOs + +@endverbatim + * @{ + */ + +/** + * @brief Initializes the SMC_NAND device according to the specified + * control parameters in the SMC_NAND_HandleTypeDef + * @param Device Pointer to NAND device instance + * @param Init Pointer to NAND Initialization structure + * @retval DAL status + */ +DAL_StatusTypeDef SMC_NAND_Init(SMC_NAND_TypeDef *Device, SMC_NAND_InitTypeDef *Init) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_SMC_NAND_DEVICE(Device)); + ASSERT_PARAM(IS_SMC_NAND_BANK(Init->NandBank)); + ASSERT_PARAM(IS_SMC_WAIT_FEATURE(Init->Waitfeature)); + ASSERT_PARAM(IS_SMC_NAND_MEMORY_WIDTH(Init->MemoryDataWidth)); + ASSERT_PARAM(IS_SMC_ECC_STATE(Init->EccComputation)); + ASSERT_PARAM(IS_SMC_ECCPAGE_SIZE(Init->ECCPageSize)); + ASSERT_PARAM(IS_SMC_TCLR_TIME(Init->TCLRSetupTime)); + ASSERT_PARAM(IS_SMC_TAR_TIME(Init->TARSetupTime)); + + /* Set NAND device control parameters */ + if (Init->NandBank == SMC_NAND_BANK2) + { + /* NAND bank 2 registers configuration */ + MODIFY_REG(Device->CTRL2, PCR_CLEAR_MASK, (Init->Waitfeature | + SMC_PCR_MEMORY_TYPE_NAND | + Init->MemoryDataWidth | + Init->EccComputation | + Init->ECCPageSize | + ((Init->TCLRSetupTime) << SMC_CTRL2_C2RDCFG_Pos) | + ((Init->TARSetupTime) << SMC_CTRL2_A2RDCFG_Pos))); + } + else + { + /* NAND bank 3 registers configuration */ + MODIFY_REG(Device->CTRL3, PCR_CLEAR_MASK, (Init->Waitfeature | + SMC_PCR_MEMORY_TYPE_NAND | + Init->MemoryDataWidth | + Init->EccComputation | + Init->ECCPageSize | + ((Init->TCLRSetupTime) << SMC_CTRL2_C2RDCFG_Pos) | + ((Init->TARSetupTime) << SMC_CTRL2_A2RDCFG_Pos))); + } + + return DAL_OK; +} + +/** + * @brief Initializes the SMC_NAND Common space Timing according to the specified + * parameters in the SMC_NAND_PCC_TimingTypeDef + * @param Device Pointer to NAND device instance + * @param Timing Pointer to NAND timing structure + * @param Bank NAND bank number + * @retval DAL status + */ +DAL_StatusTypeDef SMC_NAND_CommonSpace_Timing_Init(SMC_NAND_TypeDef *Device, + SMC_NAND_PCC_TimingTypeDef *Timing, uint32_t Bank) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_SMC_NAND_DEVICE(Device)); + ASSERT_PARAM(IS_SMC_SETUP_TIME(Timing->SetupTime)); + ASSERT_PARAM(IS_SMC_WAIT_TIME(Timing->WaitSetupTime)); + ASSERT_PARAM(IS_SMC_HOLD_TIME(Timing->HoldSetupTime)); + ASSERT_PARAM(IS_SMC_HIZ_TIME(Timing->HiZSetupTime)); + ASSERT_PARAM(IS_SMC_NAND_BANK(Bank)); + + /* Set SMC_NAND device timing parameters */ + if (Bank == SMC_NAND_BANK2) + { + /* NAND bank 2 registers configuration */ + MODIFY_REG(Device->CMSTIM2, PMEM_CLEAR_MASK, (Timing->SetupTime | + ((Timing->WaitSetupTime) << SMC_CMSTIM2_WAIT2_Pos) | + ((Timing->HoldSetupTime) << SMC_CMSTIM2_HLD2_Pos) | + ((Timing->HiZSetupTime) << SMC_CMSTIM2_HIZ2_Pos))); + } + else + { + /* NAND bank 3 registers configuration */ + MODIFY_REG(Device->CMSTIM3, PMEM_CLEAR_MASK, (Timing->SetupTime | + ((Timing->WaitSetupTime) << SMC_CMSTIM3_WAIT3_Pos) | + ((Timing->HoldSetupTime) << SMC_CMSTIM3_HLD3_Pos) | + ((Timing->HiZSetupTime) << SMC_CMSTIM3_HIZ3_Pos))); + } + + return DAL_OK; +} + +/** + * @brief Initializes the SMC_NAND Attribute space Timing according to the specified + * parameters in the SMC_NAND_PCC_TimingTypeDef + * @param Device Pointer to NAND device instance + * @param Timing Pointer to NAND timing structure + * @param Bank NAND bank number + * @retval DAL status + */ +DAL_StatusTypeDef SMC_NAND_AttributeSpace_Timing_Init(SMC_NAND_TypeDef *Device, + SMC_NAND_PCC_TimingTypeDef *Timing, uint32_t Bank) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_SMC_NAND_DEVICE(Device)); + ASSERT_PARAM(IS_SMC_SETUP_TIME(Timing->SetupTime)); + ASSERT_PARAM(IS_SMC_WAIT_TIME(Timing->WaitSetupTime)); + ASSERT_PARAM(IS_SMC_HOLD_TIME(Timing->HoldSetupTime)); + ASSERT_PARAM(IS_SMC_HIZ_TIME(Timing->HiZSetupTime)); + ASSERT_PARAM(IS_SMC_NAND_BANK(Bank)); + + /* Set SMC_NAND device timing parameters */ + if (Bank == SMC_NAND_BANK2) + { + /* NAND bank 2 registers configuration */ + MODIFY_REG(Device->AMSTIM2, PATT_CLEAR_MASK, (Timing->SetupTime | + ((Timing->WaitSetupTime) << SMC_AMSTIM2_WAIT2_Pos) | + ((Timing->HoldSetupTime) << SMC_AMSTIM2_HLD2_Pos) | + ((Timing->HiZSetupTime) << SMC_AMSTIM2_HIZ2_Pos))); + } + else + { + /* NAND bank 3 registers configuration */ + MODIFY_REG(Device->AMSTIM3, PATT_CLEAR_MASK, (Timing->SetupTime | + ((Timing->WaitSetupTime) << SMC_AMSTIM3_WAIT3_Pos) | + ((Timing->HoldSetupTime) << SMC_AMSTIM3_HLD3_Pos) | + ((Timing->HiZSetupTime) << SMC_AMSTIM3_HIZ3_Pos))); + } + + return DAL_OK; +} + +/** + * @brief DeInitializes the SMC_NAND device + * @param Device Pointer to NAND device instance + * @param Bank NAND bank number + * @retval DAL status + */ +DAL_StatusTypeDef SMC_NAND_DeInit(SMC_NAND_TypeDef *Device, uint32_t Bank) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_SMC_NAND_DEVICE(Device)); + ASSERT_PARAM(IS_SMC_NAND_BANK(Bank)); + + /* Disable the NAND Bank */ + __SMC_NAND_DISABLE(Device, Bank); + + /* De-initialize the NAND Bank */ + if (Bank == SMC_NAND_BANK2) + { + /* Set the SMC_NAND_BANK2 registers to their reset values */ + WRITE_REG(Device->CTRL2, 0x00000018U); + WRITE_REG(Device->STSINT2, 0x00000040U); + WRITE_REG(Device->CMSTIM2, 0xFCFCFCFCU); + WRITE_REG(Device->AMSTIM2, 0xFCFCFCFCU); + } + /* SMC_Bank3_NAND */ + else + { + /* Set the SMC_NAND_BANK3 registers to their reset values */ + WRITE_REG(Device->CTRL3, 0x00000018U); + WRITE_REG(Device->STSINT3, 0x00000040U); + WRITE_REG(Device->CMSTIM3, 0xFCFCFCFCU); + WRITE_REG(Device->AMSTIM3, 0xFCFCFCFCU); + } + + return DAL_OK; +} + +/** + * @} + */ + +/** @defgroup DAL_SMC_NAND_Group2 Peripheral Control functions + * @brief management functions + * +@verbatim + ============================================================================== + ##### SMC_NAND Control functions ##### + ============================================================================== + [..] + This subsection provides a set of functions allowing to control dynamically + the SMC NAND interface. + +@endverbatim + * @{ + */ + + +/** + * @brief Enables dynamically SMC_NAND ECC feature. + * @param Device Pointer to NAND device instance + * @param Bank NAND bank number + * @retval DAL status + */ +DAL_StatusTypeDef SMC_NAND_ECC_Enable(SMC_NAND_TypeDef *Device, uint32_t Bank) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_SMC_NAND_DEVICE(Device)); + ASSERT_PARAM(IS_SMC_NAND_BANK(Bank)); + + /* Enable ECC feature */ + if (Bank == SMC_NAND_BANK2) + { + SET_BIT(Device->CTRL2, SMC_CTRL2_ECCEN); + } + else + { + SET_BIT(Device->CTRL3, SMC_CTRL3_ECCEN); + } + + return DAL_OK; +} + + +/** + * @brief Disables dynamically SMC_NAND ECC feature. + * @param Device Pointer to NAND device instance + * @param Bank NAND bank number + * @retval DAL status + */ +DAL_StatusTypeDef SMC_NAND_ECC_Disable(SMC_NAND_TypeDef *Device, uint32_t Bank) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_SMC_NAND_DEVICE(Device)); + ASSERT_PARAM(IS_SMC_NAND_BANK(Bank)); + + /* Disable ECC feature */ + if (Bank == SMC_NAND_BANK2) + { + CLEAR_BIT(Device->CTRL2, SMC_CTRL2_ECCEN); + } + else + { + CLEAR_BIT(Device->CTRL3, SMC_CTRL3_ECCEN); + } + + return DAL_OK; +} + +/** + * @brief Disables dynamically SMC_NAND ECC feature. + * @param Device Pointer to NAND device instance + * @param ECCval Pointer to ECC value + * @param Bank NAND bank number + * @param Timeout Timeout wait value + * @retval DAL status + */ +DAL_StatusTypeDef SMC_NAND_GetECC(SMC_NAND_TypeDef *Device, uint32_t *ECCval, uint32_t Bank, + uint32_t Timeout) +{ + uint32_t tickstart; + + /* Check the parameters */ + ASSERT_PARAM(IS_SMC_NAND_DEVICE(Device)); + ASSERT_PARAM(IS_SMC_NAND_BANK(Bank)); + + /* Get tick */ + tickstart = DAL_GetTick(); + + /* Wait until FIFO is empty */ + while (__SMC_NAND_GET_FLAG(Device, Bank, SMC_FLAG_FEMPT) == RESET) + { + /* Check for the Timeout */ + if (Timeout != DAL_MAX_DELAY) + { + if (((DAL_GetTick() - tickstart) > Timeout) || (Timeout == 0U)) + { + return DAL_TIMEOUT; + } + } + } + + if (Bank == SMC_NAND_BANK2) + { + /* Get the ECCRS2 register value */ + *ECCval = (uint32_t)Device->ECCRS2; + } + else + { + /* Get the ECCRS3 register value */ + *ECCval = (uint32_t)Device->ECCRS3; + } + + return DAL_OK; +} + +/** + * @} + */ +#endif /* SMC_Bank2_3 */ + +#if defined(SMC_Bank4) + +/** @addtogroup SMC_DDL_PCCARD + * @brief PCCARD Controller functions + * + @verbatim + ============================================================================== + ##### How to use PCCARD device driver ##### + ============================================================================== + [..] + This driver contains a set of APIs to interface with the SMC PCCARD bank in order + to run the PCCARD/compact flash external devices. + + (+) SMC PCCARD bank reset using the function SMC_PCCARD_DeInit() + (+) SMC PCCARD bank control configuration using the function SMC_PCCARD_Init() + (+) SMC PCCARD bank common space timing configuration using the function + SMC_PCCARD_CommonSpace_Timing_Init() + (+) SMC PCCARD bank attribute space timing configuration using the function + SMC_PCCARD_AttributeSpace_Timing_Init() + (+) SMC PCCARD bank IO space timing configuration using the function + SMC_PCCARD_IOSpace_Timing_Init() +@endverbatim + * @{ + */ + +/** @addtogroup SMC_DDL_PCCARD_Private_Functions_Group1 + * @brief Initialization and Configuration functions + * +@verbatim + ============================================================================== + ##### Initialization and de_initialization functions ##### + ============================================================================== + [..] + This section provides functions allowing to: + (+) Initialize and configure the SMC PCCARD interface + (+) De-initialize the SMC PCCARD interface + (+) Configure the SMC clock and associated GPIOs + +@endverbatim + * @{ + */ + +/** + * @brief Initializes the SMC_PCCARD device according to the specified + * control parameters in the SMC_PCCARD_HandleTypeDef + * @param Device Pointer to PCCARD device instance + * @param Init Pointer to PCCARD Initialization structure + * @retval DAL status + */ +DAL_StatusTypeDef SMC_PCCARD_Init(SMC_PCCARD_TypeDef *Device, SMC_PCCARD_InitTypeDef *Init) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_SMC_PCCARD_DEVICE(Device)); +#if defined(SMC_Bank2_3) + ASSERT_PARAM(IS_SMC_WAIT_FEATURE(Init->Waitfeature)); + ASSERT_PARAM(IS_SMC_TCLR_TIME(Init->TCLRSetupTime)); + ASSERT_PARAM(IS_SMC_TAR_TIME(Init->TARSetupTime)); +#endif /* SMC_Bank2_3 */ + + /* Set SMC_PCCARD device control parameters */ + MODIFY_REG(Device->CTRL4, + (SMC_CTRL4_MTYPECFG | + SMC_CTRL4_WAITFEN | + SMC_CTRL4_DBWIDCFG | + SMC_CTRL4_C2RDCFG | + SMC_CTRL4_A2RDCFG), + (SMC_PCR_MEMORY_TYPE_PCCARD | + Init->Waitfeature | + SMC_NAND_PCC_MEM_BUS_WIDTH_16 | + (Init->TCLRSetupTime << SMC_CTRL4_C2RDCFG_Pos) | + (Init->TARSetupTime << SMC_CTRL4_A2RDCFG_Pos))); + + return DAL_OK; +} + +/** + * @brief Initializes the SMC_PCCARD Common space Timing according to the specified + * parameters in the SMC_NAND_PCC_TimingTypeDef + * @param Device Pointer to PCCARD device instance + * @param Timing Pointer to PCCARD timing structure + * @retval DAL status + */ +DAL_StatusTypeDef SMC_PCCARD_CommonSpace_Timing_Init(SMC_PCCARD_TypeDef *Device, + SMC_NAND_PCC_TimingTypeDef *Timing) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_SMC_PCCARD_DEVICE(Device)); +#if defined(SMC_Bank2_3) + ASSERT_PARAM(IS_SMC_SETUP_TIME(Timing->SetupTime)); + ASSERT_PARAM(IS_SMC_WAIT_TIME(Timing->WaitSetupTime)); + ASSERT_PARAM(IS_SMC_HOLD_TIME(Timing->HoldSetupTime)); + ASSERT_PARAM(IS_SMC_HIZ_TIME(Timing->HiZSetupTime)); +#endif /* SMC_Bank2_3 */ + + /* Set PCCARD timing parameters */ + MODIFY_REG(Device->CMSTIM4, PMEM4_CLEAR_MASK, + (Timing->SetupTime | + ((Timing->WaitSetupTime) << SMC_CMSTIM4_WAIT4_Pos) | + ((Timing->HoldSetupTime) << SMC_CMSTIM4_HLD4_Pos) | + ((Timing->HiZSetupTime) << SMC_CMSTIM4_HIZ4_Pos))); + + return DAL_OK; +} + +/** + * @brief Initializes the SMC_PCCARD Attribute space Timing according to the specified + * parameters in the SMC_NAND_PCC_TimingTypeDef + * @param Device Pointer to PCCARD device instance + * @param Timing Pointer to PCCARD timing structure + * @retval DAL status + */ +DAL_StatusTypeDef SMC_PCCARD_AttributeSpace_Timing_Init(SMC_PCCARD_TypeDef *Device, + SMC_NAND_PCC_TimingTypeDef *Timing) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_SMC_PCCARD_DEVICE(Device)); +#if defined(SMC_Bank2_3) + ASSERT_PARAM(IS_SMC_SETUP_TIME(Timing->SetupTime)); + ASSERT_PARAM(IS_SMC_WAIT_TIME(Timing->WaitSetupTime)); + ASSERT_PARAM(IS_SMC_HOLD_TIME(Timing->HoldSetupTime)); + ASSERT_PARAM(IS_SMC_HIZ_TIME(Timing->HiZSetupTime)); +#endif /* SMC_Bank2_3 */ + + /* Set PCCARD timing parameters */ + MODIFY_REG(Device->AMSTIM4, PATT4_CLEAR_MASK, + (Timing->SetupTime | + ((Timing->WaitSetupTime) << SMC_AMSTIM4_WAIT4_Pos) | + ((Timing->HoldSetupTime) << SMC_AMSTIM4_HLD4_Pos) | + ((Timing->HiZSetupTime) << SMC_AMSTIM4_HIZ4_Pos))); + + return DAL_OK; +} + +/** + * @brief Initializes the SMC_PCCARD IO space Timing according to the specified + * parameters in the SMC_NAND_PCC_TimingTypeDef + * @param Device Pointer to PCCARD device instance + * @param Timing Pointer to PCCARD timing structure + * @retval DAL status + */ +DAL_StatusTypeDef SMC_PCCARD_IOSpace_Timing_Init(SMC_PCCARD_TypeDef *Device, + SMC_NAND_PCC_TimingTypeDef *Timing) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_SMC_PCCARD_DEVICE(Device)); +#if defined(SMC_Bank2_3) + ASSERT_PARAM(IS_SMC_SETUP_TIME(Timing->SetupTime)); + ASSERT_PARAM(IS_SMC_WAIT_TIME(Timing->WaitSetupTime)); + ASSERT_PARAM(IS_SMC_HOLD_TIME(Timing->HoldSetupTime)); + ASSERT_PARAM(IS_SMC_HIZ_TIME(Timing->HiZSetupTime)); +#endif /* SMC_Bank2_3 */ + + /* Set SMC_PCCARD device timing parameters */ + MODIFY_REG(Device->IOSTIM4, PIO4_CLEAR_MASK, + (Timing->SetupTime | + (Timing->WaitSetupTime << SMC_IOSTIM4_WAIT4_Pos) | + (Timing->HoldSetupTime << SMC_IOSTIM4_HLD4_Pos) | + (Timing->HiZSetupTime << SMC_IOSTIM4_HIZ4_Pos))); + + return DAL_OK; +} + +/** + * @brief DeInitializes the SMC_PCCARD device + * @param Device Pointer to PCCARD device instance + * @retval DAL status + */ +DAL_StatusTypeDef SMC_PCCARD_DeInit(SMC_PCCARD_TypeDef *Device) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_SMC_PCCARD_DEVICE(Device)); + + /* Disable the SMC_PCCARD device */ + __SMC_PCCARD_DISABLE(Device); + + /* De-initialize the SMC_PCCARD device */ + Device->CTRL4 = 0x00000018U; + Device->STSINT4 = 0x00000040U; + Device->CMSTIM4 = 0xFCFCFCFCU; + Device->AMSTIM4 = 0xFCFCFCFCU; + Device->IOSTIM4 = 0xFCFCFCFCU; + + return DAL_OK; +} + +/** + * @} + */ +#endif /* SMC_Bank4 */ + + +/** + * @} + */ + +/** + * @} + */ + +#endif /* DAL_NOR_MODULE_ENABLED */ +/** + * @} + */ +/** + * @} + */ diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_ddl_spi.c b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_ddl_spi.c new file mode 100644 index 0000000000..7fd5462458 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_ddl_spi.c @@ -0,0 +1,649 @@ +/** + * + * @file apm32f4xx_ddl_spi.c + * @brief SPI DDL module driver. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + * + */ +#if defined(USE_FULL_DDL_DRIVER) + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_ddl_spi.h" +#include "apm32f4xx_ddl_bus.h" +#include "apm32f4xx_ddl_rcm.h" + +#ifdef USE_FULL_ASSERT +#include "apm32_assert.h" +#else +#define ASSERT_PARAM(_PARAM_) ((void)(_PARAM_)) +#endif /* USE_FULL_ASSERT */ + +/** @addtogroup APM32F4xx_DDL_Driver + * @{ + */ + +#if defined (SPI1) || defined (SPI2) || defined (SPI3) || defined (SPI4) || defined (SPI5) || defined(SPI6) + +/** @addtogroup SPI_DDL + * @{ + */ + +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ + +/* Private constants ---------------------------------------------------------*/ +/** @defgroup SPI_DDL_Private_Constants SPI Private Constants + * @{ + */ +/* SPI registers Masks */ +#define SPI_CTRL1_CLEAR_MASK (SPI_CTRL1_CPHA | SPI_CTRL1_CPOL | SPI_CTRL1_MSMCFG | \ + SPI_CTRL1_BRSEL | SPI_CTRL1_LSBSEL | SPI_CTRL1_ISSEL | \ + SPI_CTRL1_SSEN | SPI_CTRL1_RXOMEN | SPI_CTRL1_DFLSEL | \ + SPI_CTRL1_CRCNXT | SPI_CTRL1_CRCEN | SPI_CTRL1_BMOEN | \ + SPI_CTRL1_BMEN) +/** + * @} + */ + +/* Private macros ------------------------------------------------------------*/ +/** @defgroup SPI_DDL_Private_Macros SPI Private Macros + * @{ + */ +#define IS_DDL_SPI_TRANSFER_DIRECTION(__VALUE__) (((__VALUE__) == DDL_SPI_FULL_DUPLEX) \ + || ((__VALUE__) == DDL_SPI_SIMPLEX_RX) \ + || ((__VALUE__) == DDL_SPI_HALF_DUPLEX_RX) \ + || ((__VALUE__) == DDL_SPI_HALF_DUPLEX_TX)) + +#define IS_DDL_SPI_MODE(__VALUE__) (((__VALUE__) == DDL_SPI_MODE_MASTER) \ + || ((__VALUE__) == DDL_SPI_MODE_SLAVE)) + +#define IS_DDL_SPI_DATAWIDTH(__VALUE__) (((__VALUE__) == DDL_SPI_DATAWIDTH_8BIT) \ + || ((__VALUE__) == DDL_SPI_DATAWIDTH_16BIT)) + +#define IS_DDL_SPI_POLARITY(__VALUE__) (((__VALUE__) == DDL_SPI_POLARITY_LOW) \ + || ((__VALUE__) == DDL_SPI_POLARITY_HIGH)) + +#define IS_DDL_SPI_PHASE(__VALUE__) (((__VALUE__) == DDL_SPI_PHASE_1EDGE) \ + || ((__VALUE__) == DDL_SPI_PHASE_2EDGE)) + +#define IS_DDL_SPI_NSS(__VALUE__) (((__VALUE__) == DDL_SPI_NSS_SOFT) \ + || ((__VALUE__) == DDL_SPI_NSS_HARD_INPUT) \ + || ((__VALUE__) == DDL_SPI_NSS_HARD_OUTPUT)) + +#define IS_DDL_SPI_BAUDRATE(__VALUE__) (((__VALUE__) == DDL_SPI_BAUDRATEPRESCALER_DIV2) \ + || ((__VALUE__) == DDL_SPI_BAUDRATEPRESCALER_DIV4) \ + || ((__VALUE__) == DDL_SPI_BAUDRATEPRESCALER_DIV8) \ + || ((__VALUE__) == DDL_SPI_BAUDRATEPRESCALER_DIV16) \ + || ((__VALUE__) == DDL_SPI_BAUDRATEPRESCALER_DIV32) \ + || ((__VALUE__) == DDL_SPI_BAUDRATEPRESCALER_DIV64) \ + || ((__VALUE__) == DDL_SPI_BAUDRATEPRESCALER_DIV128) \ + || ((__VALUE__) == DDL_SPI_BAUDRATEPRESCALER_DIV256)) + +#define IS_DDL_SPI_BITORDER(__VALUE__) (((__VALUE__) == DDL_SPI_LSB_FIRST) \ + || ((__VALUE__) == DDL_SPI_MSB_FIRST)) + +#define IS_DDL_SPI_CRCCALCULATION(__VALUE__) (((__VALUE__) == DDL_SPI_CRCCALCULATION_ENABLE) \ + || ((__VALUE__) == DDL_SPI_CRCCALCULATION_DISABLE)) + +#define IS_DDL_SPI_CRC_POLYNOMIAL(__VALUE__) ((__VALUE__) >= 0x1U) + +/** + * @} + */ + +/* Private function prototypes -----------------------------------------------*/ + +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup SPI_DDL_Exported_Functions + * @{ + */ + +/** @addtogroup SPI_DDL_EF_Init + * @{ + */ + +/** + * @brief De-initialize the SPI registers to their default reset values. + * @param SPIx SPI Instance + * @retval An ErrorStatus enumeration value: + * - SUCCESS: SPI registers are de-initialized + * - ERROR: SPI registers are not de-initialized + */ +ErrorStatus DDL_SPI_DeInit(SPI_TypeDef *SPIx) +{ + ErrorStatus status = ERROR; + + /* Check the parameters */ + ASSERT_PARAM(IS_SPI_ALL_INSTANCE(SPIx)); + +#if defined(SPI1) + if (SPIx == SPI1) + { + /* Force reset of SPI clock */ + DDL_APB2_GRP1_ForceReset(DDL_APB2_GRP1_PERIPH_SPI1); + + /* Release reset of SPI clock */ + DDL_APB2_GRP1_ReleaseReset(DDL_APB2_GRP1_PERIPH_SPI1); + + status = SUCCESS; + } +#endif /* SPI1 */ +#if defined(SPI2) + if (SPIx == SPI2) + { + /* Force reset of SPI clock */ + DDL_APB1_GRP1_ForceReset(DDL_APB1_GRP1_PERIPH_SPI2); + + /* Release reset of SPI clock */ + DDL_APB1_GRP1_ReleaseReset(DDL_APB1_GRP1_PERIPH_SPI2); + + status = SUCCESS; + } +#endif /* SPI2 */ +#if defined(SPI3) + if (SPIx == SPI3) + { + /* Force reset of SPI clock */ + DDL_APB1_GRP1_ForceReset(DDL_APB1_GRP1_PERIPH_SPI3); + + /* Release reset of SPI clock */ + DDL_APB1_GRP1_ReleaseReset(DDL_APB1_GRP1_PERIPH_SPI3); + + status = SUCCESS; + } +#endif /* SPI3 */ +#if defined(SPI4) + if (SPIx == SPI4) + { + /* Force reset of SPI clock */ + DDL_APB2_GRP1_ForceReset(DDL_APB2_GRP1_PERIPH_SPI4); + + /* Release reset of SPI clock */ + DDL_APB2_GRP1_ReleaseReset(DDL_APB2_GRP1_PERIPH_SPI4); + + status = SUCCESS; + } +#endif /* SPI4 */ +#if defined(SPI5) + if (SPIx == SPI5) + { + /* Force reset of SPI clock */ + DDL_APB2_GRP1_ForceReset(DDL_APB2_GRP1_PERIPH_SPI5); + + /* Release reset of SPI clock */ + DDL_APB2_GRP1_ReleaseReset(DDL_APB2_GRP1_PERIPH_SPI5); + + status = SUCCESS; + } +#endif /* SPI5 */ +#if defined(SPI6) + if (SPIx == SPI6) + { + /* Force reset of SPI clock */ + DDL_APB2_GRP1_ForceReset(DDL_APB2_GRP1_PERIPH_SPI6); + + /* Release reset of SPI clock */ + DDL_APB2_GRP1_ReleaseReset(DDL_APB2_GRP1_PERIPH_SPI6); + + status = SUCCESS; + } +#endif /* SPI6 */ + + return status; +} + +/** + * @brief Initialize the SPI registers according to the specified parameters in SPI_InitStruct. + * @note As some bits in SPI configuration registers can only be written when the SPI is disabled (SPI_CTRL1_SPIEN bit =0), + * SPI peripheral should be in disabled state prior calling this function. Otherwise, ERROR result will be returned. + * @param SPIx SPI Instance + * @param SPI_InitStruct pointer to a @ref DDL_SPI_InitTypeDef structure + * @retval An ErrorStatus enumeration value. (Return always SUCCESS) + */ +ErrorStatus DDL_SPI_Init(SPI_TypeDef *SPIx, DDL_SPI_InitTypeDef *SPI_InitStruct) +{ + ErrorStatus status = ERROR; + + /* Check the SPI Instance SPIx*/ + ASSERT_PARAM(IS_SPI_ALL_INSTANCE(SPIx)); + + /* Check the SPI parameters from SPI_InitStruct*/ + ASSERT_PARAM(IS_DDL_SPI_TRANSFER_DIRECTION(SPI_InitStruct->TransferDirection)); + ASSERT_PARAM(IS_DDL_SPI_MODE(SPI_InitStruct->Mode)); + ASSERT_PARAM(IS_DDL_SPI_DATAWIDTH(SPI_InitStruct->DataWidth)); + ASSERT_PARAM(IS_DDL_SPI_POLARITY(SPI_InitStruct->ClockPolarity)); + ASSERT_PARAM(IS_DDL_SPI_PHASE(SPI_InitStruct->ClockPhase)); + ASSERT_PARAM(IS_DDL_SPI_NSS(SPI_InitStruct->NSS)); + ASSERT_PARAM(IS_DDL_SPI_BAUDRATE(SPI_InitStruct->BaudRate)); + ASSERT_PARAM(IS_DDL_SPI_BITORDER(SPI_InitStruct->BitOrder)); + ASSERT_PARAM(IS_DDL_SPI_CRCCALCULATION(SPI_InitStruct->CRCCalculation)); + + if (DDL_SPI_IsEnabled(SPIx) == 0x00000000U) + { + /*---------------------------- SPIx CTRL1 Configuration ------------------------ + * Configure SPIx CTRL1 with parameters: + * - TransferDirection: SPI_CTRL1_BMEN, SPI_CTRL1_BMOEN and SPI_CTRL1_RXOMEN bits + * - Master/Slave Mode: SPI_CTRL1_MSMCFG bit + * - DataWidth: SPI_CTRL1_DFLSEL bit + * - ClockPolarity: SPI_CTRL1_CPOL bit + * - ClockPhase: SPI_CTRL1_CPHA bit + * - NSS management: SPI_CTRL1_SSEN bit + * - BaudRate prescaler: SPI_CTRL1_BRSEL[2:0] bits + * - BitOrder: SPI_CTRL1_LSBSEL bit + * - CRCCalculation: SPI_CTRL1_CRCEN bit + */ + MODIFY_REG(SPIx->CTRL1, + SPI_CTRL1_CLEAR_MASK, + SPI_InitStruct->TransferDirection | SPI_InitStruct->Mode | SPI_InitStruct->DataWidth | + SPI_InitStruct->ClockPolarity | SPI_InitStruct->ClockPhase | + SPI_InitStruct->NSS | SPI_InitStruct->BaudRate | + SPI_InitStruct->BitOrder | SPI_InitStruct->CRCCalculation); + + /*---------------------------- SPIx CTRL2 Configuration ------------------------ + * Configure SPIx CTRL2 with parameters: + * - NSS management: SSOE bit + */ + MODIFY_REG(SPIx->CTRL2, SPI_CTRL2_SSOEN, (SPI_InitStruct->NSS >> 16U)); + + /*---------------------------- SPIx CRCPOLY Configuration ---------------------- + * Configure SPIx CRCPR with parameters: + * - CRCPoly: CRCPOLY[15:0] bits + */ + if (SPI_InitStruct->CRCCalculation == DDL_SPI_CRCCALCULATION_ENABLE) + { + ASSERT_PARAM(IS_DDL_SPI_CRC_POLYNOMIAL(SPI_InitStruct->CRCPoly)); + DDL_SPI_SetCRCPolynomial(SPIx, SPI_InitStruct->CRCPoly); + } + status = SUCCESS; + } + + /* Activate the SPI mode (Reset I2SMOD bit in I2SCFGR register) */ + CLEAR_BIT(SPIx->I2SCFG, SPI_I2SCFG_MODESEL); + return status; +} + +/** + * @brief Set each @ref DDL_SPI_InitTypeDef field to default value. + * @param SPI_InitStruct pointer to a @ref DDL_SPI_InitTypeDef structure + * whose fields will be set to default values. + * @retval None + */ +void DDL_SPI_StructInit(DDL_SPI_InitTypeDef *SPI_InitStruct) +{ + /* Set SPI_InitStruct fields to default values */ + SPI_InitStruct->TransferDirection = DDL_SPI_FULL_DUPLEX; + SPI_InitStruct->Mode = DDL_SPI_MODE_SLAVE; + SPI_InitStruct->DataWidth = DDL_SPI_DATAWIDTH_8BIT; + SPI_InitStruct->ClockPolarity = DDL_SPI_POLARITY_LOW; + SPI_InitStruct->ClockPhase = DDL_SPI_PHASE_1EDGE; + SPI_InitStruct->NSS = DDL_SPI_NSS_HARD_INPUT; + SPI_InitStruct->BaudRate = DDL_SPI_BAUDRATEPRESCALER_DIV2; + SPI_InitStruct->BitOrder = DDL_SPI_MSB_FIRST; + SPI_InitStruct->CRCCalculation = DDL_SPI_CRCCALCULATION_DISABLE; + SPI_InitStruct->CRCPoly = 7U; +} + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +/** @addtogroup I2S_DDL + * @{ + */ + +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/** @defgroup I2S_DDL_Private_Constants I2S Private Constants + * @{ + */ +/* I2S registers Masks */ +#define I2S_I2SCFG_CLEAR_MASK (SPI_I2SCFG_CHLEN | SPI_I2SCFG_DATALEN | \ + SPI_I2SCFG_CPOL | SPI_I2SCFG_I2SSSEL | \ + SPI_I2SCFG_I2SMOD | SPI_I2SCFG_MODESEL ) + +#define I2S_I2SPSC_CLEAR_MASK 0x0002U +/** + * @} + */ +/* Private macros ------------------------------------------------------------*/ +/** @defgroup I2S_DDL_Private_Macros I2S Private Macros + * @{ + */ + +#define IS_DDL_I2S_DATAFORMAT(__VALUE__) (((__VALUE__) == DDL_I2S_DATAFORMAT_16B) \ + || ((__VALUE__) == DDL_I2S_DATAFORMAT_16B_EXTENDED) \ + || ((__VALUE__) == DDL_I2S_DATAFORMAT_24B) \ + || ((__VALUE__) == DDL_I2S_DATAFORMAT_32B)) + +#define IS_DDL_I2S_CPOL(__VALUE__) (((__VALUE__) == DDL_I2S_POLARITY_LOW) \ + || ((__VALUE__) == DDL_I2S_POLARITY_HIGH)) + +#define IS_DDL_I2S_STANDARD(__VALUE__) (((__VALUE__) == DDL_I2S_STANDARD_PHILIPS) \ + || ((__VALUE__) == DDL_I2S_STANDARD_MSB) \ + || ((__VALUE__) == DDL_I2S_STANDARD_LSB) \ + || ((__VALUE__) == DDL_I2S_STANDARD_PCM_SHORT) \ + || ((__VALUE__) == DDL_I2S_STANDARD_PCM_LONG)) + +#define IS_DDL_I2S_MODE(__VALUE__) (((__VALUE__) == DDL_I2S_MODE_SLAVE_TX) \ + || ((__VALUE__) == DDL_I2S_MODE_SLAVE_RX) \ + || ((__VALUE__) == DDL_I2S_MODE_MASTER_TX) \ + || ((__VALUE__) == DDL_I2S_MODE_MASTER_RX)) + +#define IS_DDL_I2S_MCLK_OUTPUT(__VALUE__) (((__VALUE__) == DDL_I2S_MCLK_OUTPUT_ENABLE) \ + || ((__VALUE__) == DDL_I2S_MCLK_OUTPUT_DISABLE)) + +#define IS_DDL_I2S_AUDIO_FREQ(__VALUE__) ((((__VALUE__) >= DDL_I2S_AUDIOFREQ_8K) \ + && ((__VALUE__) <= DDL_I2S_AUDIOFREQ_192K)) \ + || ((__VALUE__) == DDL_I2S_AUDIOFREQ_DEFAULT)) + +#define IS_DDL_I2S_PRESCALER_LINEAR(__VALUE__) ((__VALUE__) >= 0x2U) + +#define IS_DDL_I2S_PRESCALER_PARITY(__VALUE__) (((__VALUE__) == DDL_I2S_PRESCALER_PARITY_EVEN) \ + || ((__VALUE__) == DDL_I2S_PRESCALER_PARITY_ODD)) +/** + * @} + */ + +/* Private function prototypes -----------------------------------------------*/ + +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup I2S_DDL_Exported_Functions + * @{ + */ + +/** @addtogroup I2S_DDL_EF_Init + * @{ + */ + +/** + * @brief De-initialize the SPI/I2S registers to their default reset values. + * @param SPIx SPI Instance + * @retval An ErrorStatus enumeration value: + * - SUCCESS: SPI registers are de-initialized + * - ERROR: SPI registers are not de-initialized + */ +ErrorStatus DDL_I2S_DeInit(SPI_TypeDef *SPIx) +{ + return DDL_SPI_DeInit(SPIx); +} + +/** + * @brief Initializes the SPI/I2S registers according to the specified parameters in I2S_InitStruct. + * @note As some bits in SPI configuration registers can only be written when the SPI is disabled (SPI_CTRL1_SPIEN bit =0), + * SPI peripheral should be in disabled state prior calling this function. Otherwise, ERROR result will be returned. + * @param SPIx SPI Instance + * @param I2S_InitStruct pointer to a @ref DDL_I2S_InitTypeDef structure + * @retval An ErrorStatus enumeration value: + * - SUCCESS: SPI registers are Initialized + * - ERROR: SPI registers are not Initialized + */ +ErrorStatus DDL_I2S_Init(SPI_TypeDef *SPIx, DDL_I2S_InitTypeDef *I2S_InitStruct) +{ + uint32_t i2sdiv = 2U; + uint32_t i2sodd = 0U; + uint32_t packetlength = 1U; + uint32_t tmp; + uint32_t sourceclock; + ErrorStatus status = ERROR; + + /* Check the I2S parameters */ + ASSERT_PARAM(IS_I2S_ALL_INSTANCE(SPIx)); + ASSERT_PARAM(IS_DDL_I2S_MODE(I2S_InitStruct->Mode)); + ASSERT_PARAM(IS_DDL_I2S_STANDARD(I2S_InitStruct->Standard)); + ASSERT_PARAM(IS_DDL_I2S_DATAFORMAT(I2S_InitStruct->DataFormat)); + ASSERT_PARAM(IS_DDL_I2S_MCLK_OUTPUT(I2S_InitStruct->MCLKOutput)); + ASSERT_PARAM(IS_DDL_I2S_AUDIO_FREQ(I2S_InitStruct->AudioFreq)); + ASSERT_PARAM(IS_DDL_I2S_CPOL(I2S_InitStruct->ClockPolarity)); + + if (DDL_I2S_IsEnabled(SPIx) == 0x00000000U) + { + /*---------------------------- SPIx I2SCFG Configuration -------------------- + * Configure SPIx I2SCFG with parameters: + * - Mode: SPI_I2SCFG_I2SMOD[1:0] bit + * - Standard: SPI_I2SCFG_I2SSSEL[1:0] and SPI_I2SCFG_PFSSEL bits + * - DataFormat: SPI_I2SCFG_CHLEN and SPI_I2SCFG_DATALEN bits + * - ClockPolarity: SPI_I2SCFG_CPOL bit + */ + + /* Write to SPIx I2SCFG */ + MODIFY_REG(SPIx->I2SCFG, + I2S_I2SCFG_CLEAR_MASK, + I2S_InitStruct->Mode | I2S_InitStruct->Standard | + I2S_InitStruct->DataFormat | I2S_InitStruct->ClockPolarity | + SPI_I2SCFG_MODESEL); + + /*---------------------------- SPIx I2SPSC Configuration ---------------------- + * Configure SPIx I2SPSC with parameters: + * - MCLKOutput: SPI_I2SPSC_MCOEN bit + * - AudioFreq: SPI_I2SPSC_I2SPSC[7:0] and SPI_I2SPSC_ODDPS bits + */ + + /* If the requested audio frequency is not the default, compute the prescaler (i2sodd, i2sdiv) + * else, default values are used: i2sodd = 0U, i2sdiv = 2U. + */ + if (I2S_InitStruct->AudioFreq != DDL_I2S_AUDIOFREQ_DEFAULT) + { + /* Check the frame length (For the Prescaler computing) + * Default value: DDL_I2S_DATAFORMAT_16B (packetlength = 1U). + */ + if (I2S_InitStruct->DataFormat != DDL_I2S_DATAFORMAT_16B) + { + /* Packet length is 32 bits */ + packetlength = 2U; + } + + /* If an external I2S clock has to be used, the specific define should be set + in the project configuration or in the apm32f4xx_ll_rcc.h file */ + /* Get the I2S source clock value */ + sourceclock = DDL_RCM_GetI2SClockFreq(DDL_RCM_I2S1_CLKSOURCE); + + /* Compute the Real divider depending on the MCLK output state with a floating point */ + if (I2S_InitStruct->MCLKOutput == DDL_I2S_MCLK_OUTPUT_ENABLE) + { + /* MCLK output is enabled */ + tmp = (((((sourceclock / 256U) * 10U) / I2S_InitStruct->AudioFreq)) + 5U); + } + else + { + /* MCLK output is disabled */ + tmp = (((((sourceclock / (32U * packetlength)) * 10U) / I2S_InitStruct->AudioFreq)) + 5U); + } + + /* Remove the floating point */ + tmp = tmp / 10U; + + /* Check the parity of the divider */ + i2sodd = (tmp & (uint16_t)0x0001U); + + /* Compute the i2sdiv prescaler */ + i2sdiv = ((tmp - i2sodd) / 2U); + + /* Get the Mask for the Odd bit (SPI_I2SPSC[8]) register */ + i2sodd = (i2sodd << 8U); + } + + /* Test if the divider is 1 or 0 or greater than 0xFF */ + if ((i2sdiv < 2U) || (i2sdiv > 0xFFU)) + { + /* Set the default values */ + i2sdiv = 2U; + i2sodd = 0U; + } + + /* Write to SPIx I2SPSC register the computed value */ + WRITE_REG(SPIx->I2SPSC, i2sdiv | i2sodd | I2S_InitStruct->MCLKOutput); + + status = SUCCESS; + } + return status; +} + +/** + * @brief Set each @ref DDL_I2S_InitTypeDef field to default value. + * @param I2S_InitStruct pointer to a @ref DDL_I2S_InitTypeDef structure + * whose fields will be set to default values. + * @retval None + */ +void DDL_I2S_StructInit(DDL_I2S_InitTypeDef *I2S_InitStruct) +{ + /*--------------- Reset I2S init structure parameters values -----------------*/ + I2S_InitStruct->Mode = DDL_I2S_MODE_SLAVE_TX; + I2S_InitStruct->Standard = DDL_I2S_STANDARD_PHILIPS; + I2S_InitStruct->DataFormat = DDL_I2S_DATAFORMAT_16B; + I2S_InitStruct->MCLKOutput = DDL_I2S_MCLK_OUTPUT_DISABLE; + I2S_InitStruct->AudioFreq = DDL_I2S_AUDIOFREQ_DEFAULT; + I2S_InitStruct->ClockPolarity = DDL_I2S_POLARITY_LOW; +} + +/** + * @brief Set linear and parity prescaler. + * @note To calculate value of PrescalerLinear(I2SDIV[7:0] bits) and PrescalerParity(ODD bit)\n + * Check Audio frequency table and formulas inside Reference Manual (SPI/I2S). + * @param SPIx SPI Instance + * @param PrescalerLinear value Min_Data=0x02 and Max_Data=0xFF. + * @param PrescalerParity This parameter can be one of the following values: + * @arg @ref DDL_I2S_PRESCALER_PARITY_EVEN + * @arg @ref DDL_I2S_PRESCALER_PARITY_ODD + * @retval None + */ +void DDL_I2S_ConfigPrescaler(SPI_TypeDef *SPIx, uint32_t PrescalerLinear, uint32_t PrescalerParity) +{ + /* Check the I2S parameters */ + ASSERT_PARAM(IS_I2S_ALL_INSTANCE(SPIx)); + ASSERT_PARAM(IS_DDL_I2S_PRESCALER_LINEAR(PrescalerLinear)); + ASSERT_PARAM(IS_DDL_I2S_PRESCALER_PARITY(PrescalerParity)); + + /* Write to SPIx I2SPSC */ + MODIFY_REG(SPIx->I2SPSC, SPI_I2SPSC_I2SPSC | SPI_I2SPSC_ODDPS, PrescalerLinear | (PrescalerParity << 8U)); +} + +#if defined (SPI_I2S_FULLDUPLEX_SUPPORT) +/** + * @brief Configures the full duplex mode for the I2Sx peripheral using its extension + * I2Sxext according to the specified parameters in the I2S_InitStruct. + * @note The structure pointed by I2S_InitStruct parameter should be the same + * used for the master I2S peripheral. In this case, if the master is + * configured as transmitter, the slave will be receiver and vice versa. + * Or you can force a different mode by modifying the field I2S_Mode to the + * value I2S_SlaveRx or I2S_SlaveTx independently of the master configuration. + * @param I2Sxext SPI Instance + * @param I2S_InitStruct pointer to a @ref DDL_I2S_InitTypeDef structure + * @retval An ErrorStatus enumeration value: + * - SUCCESS: I2Sxext registers are Initialized + * - ERROR: I2Sxext registers are not Initialized + */ +ErrorStatus DDL_I2S_InitFullDuplex(SPI_TypeDef *I2Sxext, DDL_I2S_InitTypeDef *I2S_InitStruct) +{ + uint32_t mode = 0U; + ErrorStatus status = ERROR; + + /* Check the I2S parameters */ + ASSERT_PARAM(IS_I2S_EXT_ALL_INSTANCE(I2Sxext)); + ASSERT_PARAM(IS_DDL_I2S_MODE(I2S_InitStruct->Mode)); + ASSERT_PARAM(IS_DDL_I2S_STANDARD(I2S_InitStruct->Standard)); + ASSERT_PARAM(IS_DDL_I2S_DATAFORMAT(I2S_InitStruct->DataFormat)); + ASSERT_PARAM(IS_DDL_I2S_CPOL(I2S_InitStruct->ClockPolarity)); + + if (DDL_I2S_IsEnabled(I2Sxext) == 0x00000000U) + { + /*---------------------------- SPIx I2SCFG Configuration -------------------- + * Configure SPIx I2SCFG with parameters: + * - Mode: SPI_I2SCFG_I2SMOD[1:0] bit + * - Standard: SPI_I2SCFG_I2SSSEL[1:0] and SPI_I2SCFG_PFSSEL bits + * - DataFormat: SPI_I2SCFG_CHLEN and SPI_I2SCFG_DATALEN bits + * - ClockPolarity: SPI_I2SCFG_CPOL bit + */ + + /* Reset I2SPSC registers */ + WRITE_REG(I2Sxext->I2SPSC, I2S_I2SPSC_CLEAR_MASK); + + /* Get the mode to be configured for the extended I2S */ + if ((I2S_InitStruct->Mode == DDL_I2S_MODE_MASTER_TX) || (I2S_InitStruct->Mode == DDL_I2S_MODE_SLAVE_TX)) + { + mode = DDL_I2S_MODE_SLAVE_RX; + } + else + { + if ((I2S_InitStruct->Mode == DDL_I2S_MODE_MASTER_RX) || (I2S_InitStruct->Mode == DDL_I2S_MODE_SLAVE_RX)) + { + mode = DDL_I2S_MODE_SLAVE_TX; + } + } + + /* Write to SPIx I2SCFG */ + MODIFY_REG(I2Sxext->I2SCFG, + I2S_I2SCFG_CLEAR_MASK, + I2S_InitStruct->Standard | + I2S_InitStruct->DataFormat | I2S_InitStruct->ClockPolarity | + SPI_I2SCFG_MODESEL | mode); + + status = SUCCESS; + } + return status; +} +#endif /* SPI_I2S_FULLDUPLEX_SUPPORT */ + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#endif /* defined (SPI1) || defined (SPI2) || defined (SPI3) || defined (SPI4) || defined (SPI5) || defined(SPI6) */ + +/** + * @} + */ + +#endif /* USE_FULL_DDL_DRIVER */ + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_ddl_tmr.c b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_ddl_tmr.c new file mode 100644 index 0000000000..1535902eb1 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_ddl_tmr.c @@ -0,0 +1,1214 @@ +/** + * + * @file apm32f4xx_ddl_tmr.c + * @brief TMR DDL module driver. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + * + */ +#if defined(USE_FULL_DDL_DRIVER) + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_ddl_tmr.h" +#include "apm32f4xx_ddl_bus.h" + +#ifdef USE_FULL_ASSERT +#include "apm32_assert.h" +#else +#define ASSERT_PARAM(_PARAM_) ((void)(_PARAM_)) +#endif /* USE_FULL_ASSERT */ + +/** @addtogroup APM32F4xx_DDL_Driver + * @{ + */ + +#if defined (TMR1) || defined (TMR2) || defined (TMR3) || defined (TMR4) || defined (TMR5) || defined (TMR6) || defined (TMR7) || defined (TMR8) || defined (TMR9) || defined (TMR10) || defined (TMR11) || defined (TMR12) || defined (TMR13) || defined (TMR14) + +/** @addtogroup TMR_DDL + * @{ + */ + +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/* Private macros ------------------------------------------------------------*/ +/** @addtogroup TMR_DDL_Private_Macros + * @{ + */ +#define IS_DDL_TMR_COUNTERMODE(__VALUE__) (((__VALUE__) == DDL_TMR_COUNTERMODE_UP) \ + || ((__VALUE__) == DDL_TMR_COUNTERMODE_DOWN) \ + || ((__VALUE__) == DDL_TMR_COUNTERMODE_CENTER_UP) \ + || ((__VALUE__) == DDL_TMR_COUNTERMODE_CENTER_DOWN) \ + || ((__VALUE__) == DDL_TMR_COUNTERMODE_CENTER_UP_DOWN)) + +#define IS_DDL_TMR_CLOCKDIVISION(__VALUE__) (((__VALUE__) == DDL_TMR_CLOCKDIVISION_DIV1) \ + || ((__VALUE__) == DDL_TMR_CLOCKDIVISION_DIV2) \ + || ((__VALUE__) == DDL_TMR_CLOCKDIVISION_DIV4)) + +#define IS_DDL_TMR_OCMODE(__VALUE__) (((__VALUE__) == DDL_TMR_OCMODE_FROZEN) \ + || ((__VALUE__) == DDL_TMR_OCMODE_ACTIVE) \ + || ((__VALUE__) == DDL_TMR_OCMODE_INACTIVE) \ + || ((__VALUE__) == DDL_TMR_OCMODE_TOGGLE) \ + || ((__VALUE__) == DDL_TMR_OCMODE_FORCED_INACTIVE) \ + || ((__VALUE__) == DDL_TMR_OCMODE_FORCED_ACTIVE) \ + || ((__VALUE__) == DDL_TMR_OCMODE_PWM1) \ + || ((__VALUE__) == DDL_TMR_OCMODE_PWM2)) + +#define IS_DDL_TMR_OCSTATE(__VALUE__) (((__VALUE__) == DDL_TMR_OCSTATE_DISABLE) \ + || ((__VALUE__) == DDL_TMR_OCSTATE_ENABLE)) + +#define IS_DDL_TMR_OCPOLARITY(__VALUE__) (((__VALUE__) == DDL_TMR_OCPOLARITY_HIGH) \ + || ((__VALUE__) == DDL_TMR_OCPOLARITY_LOW)) + +#define IS_DDL_TMR_OCIDLESTATE(__VALUE__) (((__VALUE__) == DDL_TMR_OCIDLESTATE_LOW) \ + || ((__VALUE__) == DDL_TMR_OCIDLESTATE_HIGH)) + +#define IS_DDL_TMR_ACTIVEINPUT(__VALUE__) (((__VALUE__) == DDL_TMR_ACTIVEINPUT_DIRECTTI) \ + || ((__VALUE__) == DDL_TMR_ACTIVEINPUT_INDIRECTTI) \ + || ((__VALUE__) == DDL_TMR_ACTIVEINPUT_TRC)) + +#define IS_DDL_TMR_ICPSC(__VALUE__) (((__VALUE__) == DDL_TMR_ICPSC_DIV1) \ + || ((__VALUE__) == DDL_TMR_ICPSC_DIV2) \ + || ((__VALUE__) == DDL_TMR_ICPSC_DIV4) \ + || ((__VALUE__) == DDL_TMR_ICPSC_DIV8)) + +#define IS_DDL_TMR_IC_FILTER(__VALUE__) (((__VALUE__) == DDL_TMR_IC_FILTER_FDIV1) \ + || ((__VALUE__) == DDL_TMR_IC_FILTER_FDIV1_N2) \ + || ((__VALUE__) == DDL_TMR_IC_FILTER_FDIV1_N4) \ + || ((__VALUE__) == DDL_TMR_IC_FILTER_FDIV1_N8) \ + || ((__VALUE__) == DDL_TMR_IC_FILTER_FDIV2_N6) \ + || ((__VALUE__) == DDL_TMR_IC_FILTER_FDIV2_N8) \ + || ((__VALUE__) == DDL_TMR_IC_FILTER_FDIV4_N6) \ + || ((__VALUE__) == DDL_TMR_IC_FILTER_FDIV4_N8) \ + || ((__VALUE__) == DDL_TMR_IC_FILTER_FDIV8_N6) \ + || ((__VALUE__) == DDL_TMR_IC_FILTER_FDIV8_N8) \ + || ((__VALUE__) == DDL_TMR_IC_FILTER_FDIV16_N5) \ + || ((__VALUE__) == DDL_TMR_IC_FILTER_FDIV16_N6) \ + || ((__VALUE__) == DDL_TMR_IC_FILTER_FDIV16_N8) \ + || ((__VALUE__) == DDL_TMR_IC_FILTER_FDIV32_N5) \ + || ((__VALUE__) == DDL_TMR_IC_FILTER_FDIV32_N6) \ + || ((__VALUE__) == DDL_TMR_IC_FILTER_FDIV32_N8)) + +#define IS_DDL_TMR_IC_POLARITY(__VALUE__) (((__VALUE__) == DDL_TMR_IC_POLARITY_RISING) \ + || ((__VALUE__) == DDL_TMR_IC_POLARITY_FALLING) \ + || ((__VALUE__) == DDL_TMR_IC_POLARITY_BOTHEDGE)) + +#define IS_DDL_TMR_ENCODERMODE(__VALUE__) (((__VALUE__) == DDL_TMR_ENCODERMODE_X2_TI1) \ + || ((__VALUE__) == DDL_TMR_ENCODERMODE_X2_TI2) \ + || ((__VALUE__) == DDL_TMR_ENCODERMODE_X4_TI12)) + +#define IS_DDL_TMR_IC_POLARITY_ENCODER(__VALUE__) (((__VALUE__) == DDL_TMR_IC_POLARITY_RISING) \ + || ((__VALUE__) == DDL_TMR_IC_POLARITY_FALLING)) + +#define IS_DDL_TMR_OSSR_STATE(__VALUE__) (((__VALUE__) == DDL_TMR_OSSR_DISABLE) \ + || ((__VALUE__) == DDL_TMR_OSSR_ENABLE)) + +#define IS_DDL_TMR_OSSI_STATE(__VALUE__) (((__VALUE__) == DDL_TMR_OSSI_DISABLE) \ + || ((__VALUE__) == DDL_TMR_OSSI_ENABLE)) + +#define IS_DDL_TMR_LOCK_LEVEL(__VALUE__) (((__VALUE__) == DDL_TMR_LOCKLEVEL_OFF) \ + || ((__VALUE__) == DDL_TMR_LOCKLEVEL_1) \ + || ((__VALUE__) == DDL_TMR_LOCKLEVEL_2) \ + || ((__VALUE__) == DDL_TMR_LOCKLEVEL_3)) + +#define IS_DDL_TMR_BREAK_STATE(__VALUE__) (((__VALUE__) == DDL_TMR_BREAK_DISABLE) \ + || ((__VALUE__) == DDL_TMR_BREAK_ENABLE)) + +#define IS_DDL_TMR_BREAK_POLARITY(__VALUE__) (((__VALUE__) == DDL_TMR_BREAK_POLARITY_LOW) \ + || ((__VALUE__) == DDL_TMR_BREAK_POLARITY_HIGH)) + +#define IS_DDL_TMR_AUTOMATIC_OUTPUT_STATE(__VALUE__) (((__VALUE__) == DDL_TMR_AUTOMATICOUTPUT_DISABLE) \ + || ((__VALUE__) == DDL_TMR_AUTOMATICOUTPUT_ENABLE)) +/** + * @} + */ + + +/* Private function prototypes -----------------------------------------------*/ +/** @defgroup TMR_DDL_Private_Functions TMR Private Functions + * @{ + */ +static ErrorStatus OC1Config(TMR_TypeDef *TMRx, DDL_TMR_OC_InitTypeDef *TMR_OCInitStruct); +static ErrorStatus OC2Config(TMR_TypeDef *TMRx, DDL_TMR_OC_InitTypeDef *TMR_OCInitStruct); +static ErrorStatus OC3Config(TMR_TypeDef *TMRx, DDL_TMR_OC_InitTypeDef *TMR_OCInitStruct); +static ErrorStatus OC4Config(TMR_TypeDef *TMRx, DDL_TMR_OC_InitTypeDef *TMR_OCInitStruct); +static ErrorStatus IC1Config(TMR_TypeDef *TMRx, DDL_TMR_IC_InitTypeDef *TMR_ICInitStruct); +static ErrorStatus IC2Config(TMR_TypeDef *TMRx, DDL_TMR_IC_InitTypeDef *TMR_ICInitStruct); +static ErrorStatus IC3Config(TMR_TypeDef *TMRx, DDL_TMR_IC_InitTypeDef *TMR_ICInitStruct); +static ErrorStatus IC4Config(TMR_TypeDef *TMRx, DDL_TMR_IC_InitTypeDef *TMR_ICInitStruct); +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup TMR_DDL_Exported_Functions + * @{ + */ + +/** @addtogroup TMR_DDL_EF_Init + * @{ + */ + +/** + * @brief Set TMRx registers to their reset values. + * @param TMRx Timer instance + * @retval An ErrorStatus enumeration value: + * - SUCCESS: TMRx registers are de-initialized + * - ERROR: invalid TMRx instance + */ +ErrorStatus DDL_TMR_DeInit(TMR_TypeDef *TMRx) +{ + ErrorStatus result = SUCCESS; + + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_INSTANCE(TMRx)); + + if (TMRx == TMR1) + { + DDL_APB2_GRP1_ForceReset(DDL_APB2_GRP1_PERIPH_TMR1); + DDL_APB2_GRP1_ReleaseReset(DDL_APB2_GRP1_PERIPH_TMR1); + } +#if defined(TMR2) + else if (TMRx == TMR2) + { + DDL_APB1_GRP1_ForceReset(DDL_APB1_GRP1_PERIPH_TMR2); + DDL_APB1_GRP1_ReleaseReset(DDL_APB1_GRP1_PERIPH_TMR2); + } +#endif /* TMR2 */ +#if defined(TMR3) + else if (TMRx == TMR3) + { + DDL_APB1_GRP1_ForceReset(DDL_APB1_GRP1_PERIPH_TMR3); + DDL_APB1_GRP1_ReleaseReset(DDL_APB1_GRP1_PERIPH_TMR3); + } +#endif /* TMR3 */ +#if defined(TMR4) + else if (TMRx == TMR4) + { + DDL_APB1_GRP1_ForceReset(DDL_APB1_GRP1_PERIPH_TMR4); + DDL_APB1_GRP1_ReleaseReset(DDL_APB1_GRP1_PERIPH_TMR4); + } +#endif /* TMR4 */ +#if defined(TMR5) + else if (TMRx == TMR5) + { + DDL_APB1_GRP1_ForceReset(DDL_APB1_GRP1_PERIPH_TMR5); + DDL_APB1_GRP1_ReleaseReset(DDL_APB1_GRP1_PERIPH_TMR5); + } +#endif /* TMR5 */ +#if defined(TMR6) + else if (TMRx == TMR6) + { + DDL_APB1_GRP1_ForceReset(DDL_APB1_GRP1_PERIPH_TMR6); + DDL_APB1_GRP1_ReleaseReset(DDL_APB1_GRP1_PERIPH_TMR6); + } +#endif /* TMR6 */ +#if defined (TMR7) + else if (TMRx == TMR7) + { + DDL_APB1_GRP1_ForceReset(DDL_APB1_GRP1_PERIPH_TMR7); + DDL_APB1_GRP1_ReleaseReset(DDL_APB1_GRP1_PERIPH_TMR7); + } +#endif /* TMR7 */ +#if defined(TMR8) + else if (TMRx == TMR8) + { + DDL_APB2_GRP1_ForceReset(DDL_APB2_GRP1_PERIPH_TMR8); + DDL_APB2_GRP1_ReleaseReset(DDL_APB2_GRP1_PERIPH_TMR8); + } +#endif /* TMR8 */ +#if defined(TMR9) + else if (TMRx == TMR9) + { + DDL_APB2_GRP1_ForceReset(DDL_APB2_GRP1_PERIPH_TMR9); + DDL_APB2_GRP1_ReleaseReset(DDL_APB2_GRP1_PERIPH_TMR9); + } +#endif /* TMR9 */ +#if defined(TMR10) + else if (TMRx == TMR10) + { + DDL_APB2_GRP1_ForceReset(DDL_APB2_GRP1_PERIPH_TMR10); + DDL_APB2_GRP1_ReleaseReset(DDL_APB2_GRP1_PERIPH_TMR10); + } +#endif /* TMR10 */ +#if defined(TMR11) + else if (TMRx == TMR11) + { + DDL_APB2_GRP1_ForceReset(DDL_APB2_GRP1_PERIPH_TMR11); + DDL_APB2_GRP1_ReleaseReset(DDL_APB2_GRP1_PERIPH_TMR11); + } +#endif /* TMR11 */ +#if defined(TMR12) + else if (TMRx == TMR12) + { + DDL_APB1_GRP1_ForceReset(DDL_APB1_GRP1_PERIPH_TMR12); + DDL_APB1_GRP1_ReleaseReset(DDL_APB1_GRP1_PERIPH_TMR12); + } +#endif /* TMR12 */ +#if defined(TMR13) + else if (TMRx == TMR13) + { + DDL_APB1_GRP1_ForceReset(DDL_APB1_GRP1_PERIPH_TMR13); + DDL_APB1_GRP1_ReleaseReset(DDL_APB1_GRP1_PERIPH_TMR13); + } +#endif /* TMR13 */ +#if defined(TMR14) + else if (TMRx == TMR14) + { + DDL_APB1_GRP1_ForceReset(DDL_APB1_GRP1_PERIPH_TMR14); + DDL_APB1_GRP1_ReleaseReset(DDL_APB1_GRP1_PERIPH_TMR14); + } +#endif /* TMR14 */ + else + { + result = ERROR; + } + + return result; +} + +/** + * @brief Set the fields of the time base unit configuration data structure + * to their default values. + * @param TMR_InitStruct pointer to a @ref DDL_TMR_InitTypeDef structure (time base unit configuration data structure) + * @retval None + */ +void DDL_TMR_StructInit(DDL_TMR_InitTypeDef *TMR_InitStruct) +{ + /* Set the default configuration */ + TMR_InitStruct->Prescaler = (uint16_t)0x0000; + TMR_InitStruct->CounterMode = DDL_TMR_COUNTERMODE_UP; + TMR_InitStruct->Autoreload = 0xFFFFFFFFU; + TMR_InitStruct->ClockDivision = DDL_TMR_CLOCKDIVISION_DIV1; + TMR_InitStruct->RepetitionCounter = 0x00000000U; +} + +/** + * @brief Configure the TMRx time base unit. + * @param TMRx Timer Instance + * @param TMR_InitStruct pointer to a @ref DDL_TMR_InitTypeDef structure + * (TMRx time base unit configuration data structure) + * @retval An ErrorStatus enumeration value: + * - SUCCESS: TMRx registers are de-initialized + * - ERROR: not applicable + */ +ErrorStatus DDL_TMR_Init(TMR_TypeDef *TMRx, DDL_TMR_InitTypeDef *TMR_InitStruct) +{ + uint32_t tmpcr1; + + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_INSTANCE(TMRx)); + ASSERT_PARAM(IS_DDL_TMR_COUNTERMODE(TMR_InitStruct->CounterMode)); + ASSERT_PARAM(IS_DDL_TMR_CLOCKDIVISION(TMR_InitStruct->ClockDivision)); + + tmpcr1 = DDL_TMR_ReadReg(TMRx, CTRL1); + + if (IS_TMR_COUNTER_MODE_SELECT_INSTANCE(TMRx)) + { + /* Select the Counter Mode */ + MODIFY_REG(tmpcr1, (TMR_CTRL1_CNTDIR | TMR_CTRL1_CAMSEL), TMR_InitStruct->CounterMode); + } + + if (IS_TMR_CLOCK_DIVISION_INSTANCE(TMRx)) + { + /* Set the clock division */ + MODIFY_REG(tmpcr1, TMR_CTRL1_CLKDIV, TMR_InitStruct->ClockDivision); + } + + /* Write to TMRx CTRL1 */ + DDL_TMR_WriteReg(TMRx, CTRL1, tmpcr1); + + /* Set the Autoreload value */ + DDL_TMR_SetAutoReload(TMRx, TMR_InitStruct->Autoreload); + + /* Set the Prescaler value */ + DDL_TMR_SetPrescaler(TMRx, TMR_InitStruct->Prescaler); + + if (IS_TMR_REPETITION_COUNTER_INSTANCE(TMRx)) + { + /* Set the Repetition Counter value */ + DDL_TMR_SetRepetitionCounter(TMRx, TMR_InitStruct->RepetitionCounter); + } + + /* Generate an update event to reload the Prescaler + and the repetition counter value (if applicable) immediately */ + DDL_TMR_GenerateEvent_UPDATE(TMRx); + + return SUCCESS; +} + +/** + * @brief Set the fields of the TMRx output channel configuration data + * structure to their default values. + * @param TMR_OC_InitStruct pointer to a @ref DDL_TMR_OC_InitTypeDef structure + * (the output channel configuration data structure) + * @retval None + */ +void DDL_TMR_OC_StructInit(DDL_TMR_OC_InitTypeDef *TMR_OC_InitStruct) +{ + /* Set the default configuration */ + TMR_OC_InitStruct->OCMode = DDL_TMR_OCMODE_FROZEN; + TMR_OC_InitStruct->OCState = DDL_TMR_OCSTATE_DISABLE; + TMR_OC_InitStruct->OCNState = DDL_TMR_OCSTATE_DISABLE; + TMR_OC_InitStruct->CompareValue = 0x00000000U; + TMR_OC_InitStruct->OCPolarity = DDL_TMR_OCPOLARITY_HIGH; + TMR_OC_InitStruct->OCNPolarity = DDL_TMR_OCPOLARITY_HIGH; + TMR_OC_InitStruct->OCIdleState = DDL_TMR_OCIDLESTATE_LOW; + TMR_OC_InitStruct->OCNIdleState = DDL_TMR_OCIDLESTATE_LOW; +} + +/** + * @brief Configure the TMRx output channel. + * @param TMRx Timer Instance + * @param Channel This parameter can be one of the following values: + * @arg @ref DDL_TMR_CHANNEL_CH1 + * @arg @ref DDL_TMR_CHANNEL_CH2 + * @arg @ref DDL_TMR_CHANNEL_CH3 + * @arg @ref DDL_TMR_CHANNEL_CH4 + * @param TMR_OC_InitStruct pointer to a @ref DDL_TMR_OC_InitTypeDef structure (TMRx output channel configuration + * data structure) + * @retval An ErrorStatus enumeration value: + * - SUCCESS: TMRx output channel is initialized + * - ERROR: TMRx output channel is not initialized + */ +ErrorStatus DDL_TMR_OC_Init(TMR_TypeDef *TMRx, uint32_t Channel, DDL_TMR_OC_InitTypeDef *TMR_OC_InitStruct) +{ + ErrorStatus result = ERROR; + + switch (Channel) + { + case DDL_TMR_CHANNEL_CH1: + result = OC1Config(TMRx, TMR_OC_InitStruct); + break; + case DDL_TMR_CHANNEL_CH2: + result = OC2Config(TMRx, TMR_OC_InitStruct); + break; + case DDL_TMR_CHANNEL_CH3: + result = OC3Config(TMRx, TMR_OC_InitStruct); + break; + case DDL_TMR_CHANNEL_CH4: + result = OC4Config(TMRx, TMR_OC_InitStruct); + break; + default: + break; + } + + return result; +} + +/** + * @brief Set the fields of the TMRx input channel configuration data + * structure to their default values. + * @param TMR_ICInitStruct pointer to a @ref DDL_TMR_IC_InitTypeDef structure (the input channel configuration + * data structure) + * @retval None + */ +void DDL_TMR_IC_StructInit(DDL_TMR_IC_InitTypeDef *TMR_ICInitStruct) +{ + /* Set the default configuration */ + TMR_ICInitStruct->ICPolarity = DDL_TMR_IC_POLARITY_RISING; + TMR_ICInitStruct->ICActiveInput = DDL_TMR_ACTIVEINPUT_DIRECTTI; + TMR_ICInitStruct->ICPrescaler = DDL_TMR_ICPSC_DIV1; + TMR_ICInitStruct->ICFilter = DDL_TMR_IC_FILTER_FDIV1; +} + +/** + * @brief Configure the TMRx input channel. + * @param TMRx Timer Instance + * @param Channel This parameter can be one of the following values: + * @arg @ref DDL_TMR_CHANNEL_CH1 + * @arg @ref DDL_TMR_CHANNEL_CH2 + * @arg @ref DDL_TMR_CHANNEL_CH3 + * @arg @ref DDL_TMR_CHANNEL_CH4 + * @param TMR_IC_InitStruct pointer to a @ref DDL_TMR_IC_InitTypeDef structure (TMRx input channel configuration data + * structure) + * @retval An ErrorStatus enumeration value: + * - SUCCESS: TMRx output channel is initialized + * - ERROR: TMRx output channel is not initialized + */ +ErrorStatus DDL_TMR_IC_Init(TMR_TypeDef *TMRx, uint32_t Channel, DDL_TMR_IC_InitTypeDef *TMR_IC_InitStruct) +{ + ErrorStatus result = ERROR; + + switch (Channel) + { + case DDL_TMR_CHANNEL_CH1: + result = IC1Config(TMRx, TMR_IC_InitStruct); + break; + case DDL_TMR_CHANNEL_CH2: + result = IC2Config(TMRx, TMR_IC_InitStruct); + break; + case DDL_TMR_CHANNEL_CH3: + result = IC3Config(TMRx, TMR_IC_InitStruct); + break; + case DDL_TMR_CHANNEL_CH4: + result = IC4Config(TMRx, TMR_IC_InitStruct); + break; + default: + break; + } + + return result; +} + +/** + * @brief Fills each TMR_EncoderInitStruct field with its default value + * @param TMR_EncoderInitStruct pointer to a @ref DDL_TMR_ENCODER_InitTypeDef structure (encoder interface + * configuration data structure) + * @retval None + */ +void DDL_TMR_ENCODER_StructInit(DDL_TMR_ENCODER_InitTypeDef *TMR_EncoderInitStruct) +{ + /* Set the default configuration */ + TMR_EncoderInitStruct->EncoderMode = DDL_TMR_ENCODERMODE_X2_TI1; + TMR_EncoderInitStruct->IC1Polarity = DDL_TMR_IC_POLARITY_RISING; + TMR_EncoderInitStruct->IC1ActiveInput = DDL_TMR_ACTIVEINPUT_DIRECTTI; + TMR_EncoderInitStruct->IC1Prescaler = DDL_TMR_ICPSC_DIV1; + TMR_EncoderInitStruct->IC1Filter = DDL_TMR_IC_FILTER_FDIV1; + TMR_EncoderInitStruct->IC2Polarity = DDL_TMR_IC_POLARITY_RISING; + TMR_EncoderInitStruct->IC2ActiveInput = DDL_TMR_ACTIVEINPUT_DIRECTTI; + TMR_EncoderInitStruct->IC2Prescaler = DDL_TMR_ICPSC_DIV1; + TMR_EncoderInitStruct->IC2Filter = DDL_TMR_IC_FILTER_FDIV1; +} + +/** + * @brief Configure the encoder interface of the timer instance. + * @param TMRx Timer Instance + * @param TMR_EncoderInitStruct pointer to a @ref DDL_TMR_ENCODER_InitTypeDef structure (TMRx encoder interface + * configuration data structure) + * @retval An ErrorStatus enumeration value: + * - SUCCESS: TMRx registers are initialized + * - ERROR: not applicable + */ +ErrorStatus DDL_TMR_ENCODER_Init(TMR_TypeDef *TMRx, DDL_TMR_ENCODER_InitTypeDef *TMR_EncoderInitStruct) +{ + uint32_t tmpccmr1; + uint32_t tmpccer; + + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_ENCODER_INTERFACE_INSTANCE(TMRx)); + ASSERT_PARAM(IS_DDL_TMR_ENCODERMODE(TMR_EncoderInitStruct->EncoderMode)); + ASSERT_PARAM(IS_DDL_TMR_IC_POLARITY_ENCODER(TMR_EncoderInitStruct->IC1Polarity)); + ASSERT_PARAM(IS_DDL_TMR_ACTIVEINPUT(TMR_EncoderInitStruct->IC1ActiveInput)); + ASSERT_PARAM(IS_DDL_TMR_ICPSC(TMR_EncoderInitStruct->IC1Prescaler)); + ASSERT_PARAM(IS_DDL_TMR_IC_FILTER(TMR_EncoderInitStruct->IC1Filter)); + ASSERT_PARAM(IS_DDL_TMR_IC_POLARITY_ENCODER(TMR_EncoderInitStruct->IC2Polarity)); + ASSERT_PARAM(IS_DDL_TMR_ACTIVEINPUT(TMR_EncoderInitStruct->IC2ActiveInput)); + ASSERT_PARAM(IS_DDL_TMR_ICPSC(TMR_EncoderInitStruct->IC2Prescaler)); + ASSERT_PARAM(IS_DDL_TMR_IC_FILTER(TMR_EncoderInitStruct->IC2Filter)); + + /* Disable the CC1 and CC2: Reset the CC1EN and CC2EN Bits */ + TMRx->CCEN &= (uint32_t)~(TMR_CCEN_CC1EN | TMR_CCEN_CC2EN); + + /* Get the TMRx CCM1 register value */ + tmpccmr1 = DDL_TMR_ReadReg(TMRx, CCM1); + + /* Get the TMRx CCEN register value */ + tmpccer = DDL_TMR_ReadReg(TMRx, CCEN); + + /* Configure TI1 */ + tmpccmr1 &= (uint32_t)~(TMR_CCM1_CC1SEL | TMR_CCM1_IC1F | TMR_CCM1_IC1PSC); + tmpccmr1 |= (uint32_t)(TMR_EncoderInitStruct->IC1ActiveInput >> 16U); + tmpccmr1 |= (uint32_t)(TMR_EncoderInitStruct->IC1Filter >> 16U); + tmpccmr1 |= (uint32_t)(TMR_EncoderInitStruct->IC1Prescaler >> 16U); + + /* Configure TI2 */ + tmpccmr1 &= (uint32_t)~(TMR_CCM1_CC2SEL | TMR_CCM1_IC2F | TMR_CCM1_IC2PSC); + tmpccmr1 |= (uint32_t)(TMR_EncoderInitStruct->IC2ActiveInput >> 8U); + tmpccmr1 |= (uint32_t)(TMR_EncoderInitStruct->IC2Filter >> 8U); + tmpccmr1 |= (uint32_t)(TMR_EncoderInitStruct->IC2Prescaler >> 8U); + + /* Set TI1 and TI2 polarity and enable TI1 and TI2 */ + tmpccer &= (uint32_t)~(TMR_CCEN_CC1POL | TMR_CCEN_CC1NPOL | TMR_CCEN_CC2POL | TMR_CCEN_CC2NPOL); + tmpccer |= (uint32_t)(TMR_EncoderInitStruct->IC1Polarity); + tmpccer |= (uint32_t)(TMR_EncoderInitStruct->IC2Polarity << 4U); + tmpccer |= (uint32_t)(TMR_CCEN_CC1EN | TMR_CCEN_CC2EN); + + /* Set encoder mode */ + DDL_TMR_SetEncoderMode(TMRx, TMR_EncoderInitStruct->EncoderMode); + + /* Write to TMRx CCM1 */ + DDL_TMR_WriteReg(TMRx, CCM1, tmpccmr1); + + /* Write to TMRx CCEN */ + DDL_TMR_WriteReg(TMRx, CCEN, tmpccer); + + return SUCCESS; +} + +/** + * @brief Set the fields of the TMRx Hall sensor interface configuration data + * structure to their default values. + * @param TMR_HallSensorInitStruct pointer to a @ref DDL_TMR_HALLSENSOR_InitTypeDef structure (HALL sensor interface + * configuration data structure) + * @retval None + */ +void DDL_TMR_HALLSENSOR_StructInit(DDL_TMR_HALLSENSOR_InitTypeDef *TMR_HallSensorInitStruct) +{ + /* Set the default configuration */ + TMR_HallSensorInitStruct->IC1Polarity = DDL_TMR_IC_POLARITY_RISING; + TMR_HallSensorInitStruct->IC1Prescaler = DDL_TMR_ICPSC_DIV1; + TMR_HallSensorInitStruct->IC1Filter = DDL_TMR_IC_FILTER_FDIV1; + TMR_HallSensorInitStruct->CommutationDelay = 0U; +} + +/** + * @brief Configure the Hall sensor interface of the timer instance. + * @note TMRx CH1, CH2 and CH3 inputs connected through a XOR + * to the TI1 input channel + * @note TMRx slave mode controller is configured in reset mode. + Selected internal trigger is TI1F_ED. + * @note Channel 1 is configured as input, IC1 is mapped on TRC. + * @note Captured value stored in TMRx_CCR1 correspond to the time elapsed + * between 2 changes on the inputs. It gives information about motor speed. + * @note Channel 2 is configured in output PWM 2 mode. + * @note Compare value stored in TMRx_CCR2 corresponds to the commutation delay. + * @note OC2REF is selected as trigger output on TRGO. + * @note DDL_TMR_IC_POLARITY_BOTHEDGE must not be used for TI1 when it is used + * when TMRx operates in Hall sensor interface mode. + * @param TMRx Timer Instance + * @param TMR_HallSensorInitStruct pointer to a @ref DDL_TMR_HALLSENSOR_InitTypeDef structure (TMRx DALL sensor + * interface configuration data structure) + * @retval An ErrorStatus enumeration value: + * - SUCCESS: TMRx registers are de-initialized + * - ERROR: not applicable + */ +ErrorStatus DDL_TMR_HALLSENSOR_Init(TMR_TypeDef *TMRx, DDL_TMR_HALLSENSOR_InitTypeDef *TMR_HallSensorInitStruct) +{ + uint32_t tmpcr2; + uint32_t tmpccmr1; + uint32_t tmpccer; + uint32_t tmpsmcr; + + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_HALL_SENSOR_INTERFACE_INSTANCE(TMRx)); + ASSERT_PARAM(IS_DDL_TMR_IC_POLARITY_ENCODER(TMR_HallSensorInitStruct->IC1Polarity)); + ASSERT_PARAM(IS_DDL_TMR_ICPSC(TMR_HallSensorInitStruct->IC1Prescaler)); + ASSERT_PARAM(IS_DDL_TMR_IC_FILTER(TMR_HallSensorInitStruct->IC1Filter)); + + /* Disable the CC1 and CC2: Reset the CC1E and CC2E Bits */ + TMRx->CCEN &= (uint32_t)~(TMR_CCEN_CC1EN | TMR_CCEN_CC2EN); + + /* Get the TMRx CTRL2 register value */ + tmpcr2 = DDL_TMR_ReadReg(TMRx, CTRL2); + + /* Get the TMRx CCM1 register value */ + tmpccmr1 = DDL_TMR_ReadReg(TMRx, CCM1); + + /* Get the TMRx CCEN register value */ + tmpccer = DDL_TMR_ReadReg(TMRx, CCEN); + + /* Get the TMRx SMCTRL register value */ + tmpsmcr = DDL_TMR_ReadReg(TMRx, SMCTRL); + + /* Connect TMRx_CH1, CH2 and CH3 pins to the TI1 input */ + tmpcr2 |= TMR_CTRL2_TI1SEL; + + /* OC2REF signal is used as trigger output (TRGO) */ + tmpcr2 |= DDL_TMR_TRGO_OC2REF; + + /* Configure the slave mode controller */ + tmpsmcr &= (uint32_t)~(TMR_SMCTRL_TRGSEL | TMR_SMCTRL_SMFSEL); + tmpsmcr |= DDL_TMR_TS_TI1F_ED; + tmpsmcr |= DDL_TMR_SLAVEMODE_RESET; + + /* Configure input channel 1 */ + tmpccmr1 &= (uint32_t)~(TMR_CCM1_CC1SEL | TMR_CCM1_IC1F | TMR_CCM1_IC1PSC); + tmpccmr1 |= (uint32_t)(DDL_TMR_ACTIVEINPUT_TRC >> 16U); + tmpccmr1 |= (uint32_t)(TMR_HallSensorInitStruct->IC1Filter >> 16U); + tmpccmr1 |= (uint32_t)(TMR_HallSensorInitStruct->IC1Prescaler >> 16U); + + /* Configure input channel 2 */ + tmpccmr1 &= (uint32_t)~(TMR_CCM1_OC2MOD | TMR_CCM1_OC2FEN | TMR_CCM1_OC2PEN | TMR_CCM1_OC2CEN); + tmpccmr1 |= (uint32_t)(DDL_TMR_OCMODE_PWM2 << 8U); + + /* Set Channel 1 polarity and enable Channel 1 and Channel2 */ + tmpccer &= (uint32_t)~(TMR_CCEN_CC1POL | TMR_CCEN_CC1NPOL | TMR_CCEN_CC2POL | TMR_CCEN_CC2NPOL); + tmpccer |= (uint32_t)(TMR_HallSensorInitStruct->IC1Polarity); + tmpccer |= (uint32_t)(TMR_CCEN_CC1EN | TMR_CCEN_CC2EN); + + /* Write to TMRx CTRL2 */ + DDL_TMR_WriteReg(TMRx, CTRL2, tmpcr2); + + /* Write to TMRx SMCTRL */ + DDL_TMR_WriteReg(TMRx, SMCTRL, tmpsmcr); + + /* Write to TMRx CCM1 */ + DDL_TMR_WriteReg(TMRx, CCM1, tmpccmr1); + + /* Write to TMRx CCEN */ + DDL_TMR_WriteReg(TMRx, CCEN, tmpccer); + + /* Write to TMRx CC2 */ + DDL_TMR_OC_SetCompareCH2(TMRx, TMR_HallSensorInitStruct->CommutationDelay); + + return SUCCESS; +} + +/** + * @brief Set the fields of the Break and Dead Time configuration data structure + * to their default values. + * @param TMR_BDTInitStruct pointer to a @ref DDL_TMR_BDT_InitTypeDef structure (Break and Dead Time configuration + * data structure) + * @retval None + */ +void DDL_TMR_BDT_StructInit(DDL_TMR_BDT_InitTypeDef *TMR_BDTInitStruct) +{ + /* Set the default configuration */ + TMR_BDTInitStruct->OSSRState = DDL_TMR_OSSR_DISABLE; + TMR_BDTInitStruct->OSSIState = DDL_TMR_OSSI_DISABLE; + TMR_BDTInitStruct->LockLevel = DDL_TMR_LOCKLEVEL_OFF; + TMR_BDTInitStruct->DeadTime = (uint8_t)0x00; + TMR_BDTInitStruct->BreakState = DDL_TMR_BREAK_DISABLE; + TMR_BDTInitStruct->BreakPolarity = DDL_TMR_BREAK_POLARITY_LOW; + TMR_BDTInitStruct->AutomaticOutput = DDL_TMR_AUTOMATICOUTPUT_DISABLE; +} + +/** + * @brief Configure the Break and Dead Time feature of the timer instance. + * @note As the bits AOE, BKP, BKE, OSSR, OSSI and DTG[7:0] can be write-locked + * depending on the LOCK configuration, it can be necessary to configure all of + * them during the first write access to the TMRx_BDTR register. + * @note Macro IS_TMR_BREAK_INSTANCE(TMRx) can be used to check whether or not + * a timer instance provides a break input. + * @param TMRx Timer Instance + * @param TMR_BDTInitStruct pointer to a @ref DDL_TMR_BDT_InitTypeDef structure (Break and Dead Time configuration + * data structure) + * @retval An ErrorStatus enumeration value: + * - SUCCESS: Break and Dead Time is initialized + * - ERROR: not applicable + */ +ErrorStatus DDL_TMR_BDT_Init(TMR_TypeDef *TMRx, DDL_TMR_BDT_InitTypeDef *TMR_BDTInitStruct) +{ + uint32_t tmpbdtr = 0; + + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_BREAK_INSTANCE(TMRx)); + ASSERT_PARAM(IS_DDL_TMR_OSSR_STATE(TMR_BDTInitStruct->OSSRState)); + ASSERT_PARAM(IS_DDL_TMR_OSSI_STATE(TMR_BDTInitStruct->OSSIState)); + ASSERT_PARAM(IS_DDL_TMR_LOCK_LEVEL(TMR_BDTInitStruct->LockLevel)); + ASSERT_PARAM(IS_DDL_TMR_BREAK_STATE(TMR_BDTInitStruct->BreakState)); + ASSERT_PARAM(IS_DDL_TMR_BREAK_POLARITY(TMR_BDTInitStruct->BreakPolarity)); + ASSERT_PARAM(IS_DDL_TMR_AUTOMATIC_OUTPUT_STATE(TMR_BDTInitStruct->AutomaticOutput)); + + /* Set the Lock level, the Break enable Bit and the Polarity, the OSSR State, + the OSSI State, the dead time value and the Automatic Output Enable Bit */ + + /* Set the BDT bits */ + MODIFY_REG(tmpbdtr, TMR_BDT_DTS, TMR_BDTInitStruct->DeadTime); + MODIFY_REG(tmpbdtr, TMR_BDT_LOCKCFG, TMR_BDTInitStruct->LockLevel); + MODIFY_REG(tmpbdtr, TMR_BDT_IMOS, TMR_BDTInitStruct->OSSIState); + MODIFY_REG(tmpbdtr, TMR_BDT_RMOS, TMR_BDTInitStruct->OSSRState); + MODIFY_REG(tmpbdtr, TMR_BDT_BRKEN, TMR_BDTInitStruct->BreakState); + MODIFY_REG(tmpbdtr, TMR_BDT_BRKPOL, TMR_BDTInitStruct->BreakPolarity); + MODIFY_REG(tmpbdtr, TMR_BDT_AOEN, TMR_BDTInitStruct->AutomaticOutput); + MODIFY_REG(tmpbdtr, TMR_BDT_MOEN, TMR_BDTInitStruct->AutomaticOutput); + + /* Set TMRx_BDT */ + DDL_TMR_WriteReg(TMRx, BDT, tmpbdtr); + + return SUCCESS; +} +/** + * @} + */ + +/** + * @} + */ + +/** @addtogroup TMR_DDL_Private_Functions TMR Private Functions + * @brief Private functions + * @{ + */ +/** + * @brief Configure the TMRx output channel 1. + * @param TMRx Timer Instance + * @param TMR_OCInitStruct pointer to the the TMRx output channel 1 configuration data structure + * @retval An ErrorStatus enumeration value: + * - SUCCESS: TMRx registers are de-initialized + * - ERROR: not applicable + */ +static ErrorStatus OC1Config(TMR_TypeDef *TMRx, DDL_TMR_OC_InitTypeDef *TMR_OCInitStruct) +{ + uint32_t tmpccmr1; + uint32_t tmpccer; + uint32_t tmpcr2; + + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_CC1_INSTANCE(TMRx)); + ASSERT_PARAM(IS_DDL_TMR_OCMODE(TMR_OCInitStruct->OCMode)); + ASSERT_PARAM(IS_DDL_TMR_OCSTATE(TMR_OCInitStruct->OCState)); + ASSERT_PARAM(IS_DDL_TMR_OCPOLARITY(TMR_OCInitStruct->OCPolarity)); + ASSERT_PARAM(IS_DDL_TMR_OCSTATE(TMR_OCInitStruct->OCNState)); + ASSERT_PARAM(IS_DDL_TMR_OCPOLARITY(TMR_OCInitStruct->OCNPolarity)); + + /* Disable the Channel 1: Reset the CC1E Bit */ + CLEAR_BIT(TMRx->CCEN, TMR_CCEN_CC1EN); + + /* Get the TMRx CCEN register value */ + tmpccer = DDL_TMR_ReadReg(TMRx, CCEN); + + /* Get the TMRx CTRL2 register value */ + tmpcr2 = DDL_TMR_ReadReg(TMRx, CTRL2); + + /* Get the TMRx CCM1 register value */ + tmpccmr1 = DDL_TMR_ReadReg(TMRx, CCM1); + + /* Reset Capture/Compare selection Bits */ + CLEAR_BIT(tmpccmr1, TMR_CCM1_CC1SEL); + + /* Set the Output Compare Mode */ + MODIFY_REG(tmpccmr1, TMR_CCM1_OC1MOD, TMR_OCInitStruct->OCMode); + + /* Set the Output Compare Polarity */ + MODIFY_REG(tmpccer, TMR_CCEN_CC1POL, TMR_OCInitStruct->OCPolarity); + + /* Set the Output State */ + MODIFY_REG(tmpccer, TMR_CCEN_CC1EN, TMR_OCInitStruct->OCState); + + if (IS_TMR_BREAK_INSTANCE(TMRx)) + { + ASSERT_PARAM(IS_DDL_TMR_OCIDLESTATE(TMR_OCInitStruct->OCNIdleState)); + ASSERT_PARAM(IS_DDL_TMR_OCIDLESTATE(TMR_OCInitStruct->OCIdleState)); + + /* Set the complementary output Polarity */ + MODIFY_REG(tmpccer, TMR_CCEN_CC1NPOL, TMR_OCInitStruct->OCNPolarity << 2U); + + /* Set the complementary output State */ + MODIFY_REG(tmpccer, TMR_CCEN_CC1NEN, TMR_OCInitStruct->OCNState << 2U); + + /* Set the Output Idle state */ + MODIFY_REG(tmpcr2, TMR_CTRL2_OC1OIS, TMR_OCInitStruct->OCIdleState); + + /* Set the complementary output Idle state */ + MODIFY_REG(tmpcr2, TMR_CTRL2_OC1NOIS, TMR_OCInitStruct->OCNIdleState << 1U); + } + + /* Write to TMRx CTRL2 */ + DDL_TMR_WriteReg(TMRx, CTRL2, tmpcr2); + + /* Write to TMRx CCM1 */ + DDL_TMR_WriteReg(TMRx, CCM1, tmpccmr1); + + /* Set the Capture Compare Register value */ + DDL_TMR_OC_SetCompareCH1(TMRx, TMR_OCInitStruct->CompareValue); + + /* Write to TMRx CCEN */ + DDL_TMR_WriteReg(TMRx, CCEN, tmpccer); + + return SUCCESS; +} + +/** + * @brief Configure the TMRx output channel 2. + * @param TMRx Timer Instance + * @param TMR_OCInitStruct pointer to the the TMRx output channel 2 configuration data structure + * @retval An ErrorStatus enumeration value: + * - SUCCESS: TMRx registers are de-initialized + * - ERROR: not applicable + */ +static ErrorStatus OC2Config(TMR_TypeDef *TMRx, DDL_TMR_OC_InitTypeDef *TMR_OCInitStruct) +{ + uint32_t tmpccmr1; + uint32_t tmpccer; + uint32_t tmpcr2; + + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_CC2_INSTANCE(TMRx)); + ASSERT_PARAM(IS_DDL_TMR_OCMODE(TMR_OCInitStruct->OCMode)); + ASSERT_PARAM(IS_DDL_TMR_OCSTATE(TMR_OCInitStruct->OCState)); + ASSERT_PARAM(IS_DDL_TMR_OCPOLARITY(TMR_OCInitStruct->OCPolarity)); + ASSERT_PARAM(IS_DDL_TMR_OCSTATE(TMR_OCInitStruct->OCNState)); + ASSERT_PARAM(IS_DDL_TMR_OCPOLARITY(TMR_OCInitStruct->OCNPolarity)); + + /* Disable the Channel 2: Reset the CC2E Bit */ + CLEAR_BIT(TMRx->CCEN, TMR_CCEN_CC2EN); + + /* Get the TMRx CCEN register value */ + tmpccer = DDL_TMR_ReadReg(TMRx, CCEN); + + /* Get the TMRx CTRL2 register value */ + tmpcr2 = DDL_TMR_ReadReg(TMRx, CTRL2); + + /* Get the TMRx CCM1 register value */ + tmpccmr1 = DDL_TMR_ReadReg(TMRx, CCM1); + + /* Reset Capture/Compare selection Bits */ + CLEAR_BIT(tmpccmr1, TMR_CCM1_CC2SEL); + + /* Select the Output Compare Mode */ + MODIFY_REG(tmpccmr1, TMR_CCM1_OC2MOD, TMR_OCInitStruct->OCMode << 8U); + + /* Set the Output Compare Polarity */ + MODIFY_REG(tmpccer, TMR_CCEN_CC2POL, TMR_OCInitStruct->OCPolarity << 4U); + + /* Set the Output State */ + MODIFY_REG(tmpccer, TMR_CCEN_CC2EN, TMR_OCInitStruct->OCState << 4U); + + if (IS_TMR_BREAK_INSTANCE(TMRx)) + { + ASSERT_PARAM(IS_DDL_TMR_OCIDLESTATE(TMR_OCInitStruct->OCNIdleState)); + ASSERT_PARAM(IS_DDL_TMR_OCIDLESTATE(TMR_OCInitStruct->OCIdleState)); + + /* Set the complementary output Polarity */ + MODIFY_REG(tmpccer, TMR_CCEN_CC2NPOL, TMR_OCInitStruct->OCNPolarity << 6U); + + /* Set the complementary output State */ + MODIFY_REG(tmpccer, TMR_CCEN_CC2NEN, TMR_OCInitStruct->OCNState << 6U); + + /* Set the Output Idle state */ + MODIFY_REG(tmpcr2, TMR_CTRL2_OC2OIS, TMR_OCInitStruct->OCIdleState << 2U); + + /* Set the complementary output Idle state */ + MODIFY_REG(tmpcr2, TMR_CTRL2_OC2NOIS, TMR_OCInitStruct->OCNIdleState << 3U); + } + + /* Write to TMRx CTRL2 */ + DDL_TMR_WriteReg(TMRx, CTRL2, tmpcr2); + + /* Write to TMRx CCM1 */ + DDL_TMR_WriteReg(TMRx, CCM1, tmpccmr1); + + /* Set the Capture Compare Register value */ + DDL_TMR_OC_SetCompareCH2(TMRx, TMR_OCInitStruct->CompareValue); + + /* Write to TMRx CCEN */ + DDL_TMR_WriteReg(TMRx, CCEN, tmpccer); + + return SUCCESS; +} + +/** + * @brief Configure the TMRx output channel 3. + * @param TMRx Timer Instance + * @param TMR_OCInitStruct pointer to the the TMRx output channel 3 configuration data structure + * @retval An ErrorStatus enumeration value: + * - SUCCESS: TMRx registers are de-initialized + * - ERROR: not applicable + */ +static ErrorStatus OC3Config(TMR_TypeDef *TMRx, DDL_TMR_OC_InitTypeDef *TMR_OCInitStruct) +{ + uint32_t tmpccmr2; + uint32_t tmpccer; + uint32_t tmpcr2; + + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_CC3_INSTANCE(TMRx)); + ASSERT_PARAM(IS_DDL_TMR_OCMODE(TMR_OCInitStruct->OCMode)); + ASSERT_PARAM(IS_DDL_TMR_OCSTATE(TMR_OCInitStruct->OCState)); + ASSERT_PARAM(IS_DDL_TMR_OCPOLARITY(TMR_OCInitStruct->OCPolarity)); + ASSERT_PARAM(IS_DDL_TMR_OCSTATE(TMR_OCInitStruct->OCNState)); + ASSERT_PARAM(IS_DDL_TMR_OCPOLARITY(TMR_OCInitStruct->OCNPolarity)); + + /* Disable the Channel 3: Reset the CC3E Bit */ + CLEAR_BIT(TMRx->CCEN, TMR_CCEN_CC3EN); + + /* Get the TMRx CCEN register value */ + tmpccer = DDL_TMR_ReadReg(TMRx, CCEN); + + /* Get the TMRx CTRL2 register value */ + tmpcr2 = DDL_TMR_ReadReg(TMRx, CTRL2); + + /* Get the TMRx CCM2 register value */ + tmpccmr2 = DDL_TMR_ReadReg(TMRx, CCM2); + + /* Reset Capture/Compare selection Bits */ + CLEAR_BIT(tmpccmr2, TMR_CCM2_CC3SEL); + + /* Select the Output Compare Mode */ + MODIFY_REG(tmpccmr2, TMR_CCM2_OC3MOD, TMR_OCInitStruct->OCMode); + + /* Set the Output Compare Polarity */ + MODIFY_REG(tmpccer, TMR_CCEN_CC3POL, TMR_OCInitStruct->OCPolarity << 8U); + + /* Set the Output State */ + MODIFY_REG(tmpccer, TMR_CCEN_CC3EN, TMR_OCInitStruct->OCState << 8U); + + if (IS_TMR_BREAK_INSTANCE(TMRx)) + { + ASSERT_PARAM(IS_DDL_TMR_OCIDLESTATE(TMR_OCInitStruct->OCNIdleState)); + ASSERT_PARAM(IS_DDL_TMR_OCIDLESTATE(TMR_OCInitStruct->OCIdleState)); + + /* Set the complementary output Polarity */ + MODIFY_REG(tmpccer, TMR_CCEN_CC3NPOL, TMR_OCInitStruct->OCNPolarity << 10U); + + /* Set the complementary output State */ + MODIFY_REG(tmpccer, TMR_CCEN_CC3NEN, TMR_OCInitStruct->OCNState << 10U); + + /* Set the Output Idle state */ + MODIFY_REG(tmpcr2, TMR_CTRL2_OC3OIS, TMR_OCInitStruct->OCIdleState << 4U); + + /* Set the complementary output Idle state */ + MODIFY_REG(tmpcr2, TMR_CTRL2_OC3NOIS, TMR_OCInitStruct->OCNIdleState << 5U); + } + + /* Write to TMRx CTRL2 */ + DDL_TMR_WriteReg(TMRx, CTRL2, tmpcr2); + + /* Write to TMRx CCM2 */ + DDL_TMR_WriteReg(TMRx, CCM2, tmpccmr2); + + /* Set the Capture Compare Register value */ + DDL_TMR_OC_SetCompareCH3(TMRx, TMR_OCInitStruct->CompareValue); + + /* Write to TMRx CCEN */ + DDL_TMR_WriteReg(TMRx, CCEN, tmpccer); + + return SUCCESS; +} + +/** + * @brief Configure the TMRx output channel 4. + * @param TMRx Timer Instance + * @param TMR_OCInitStruct pointer to the the TMRx output channel 4 configuration data structure + * @retval An ErrorStatus enumeration value: + * - SUCCESS: TMRx registers are de-initialized + * - ERROR: not applicable + */ +static ErrorStatus OC4Config(TMR_TypeDef *TMRx, DDL_TMR_OC_InitTypeDef *TMR_OCInitStruct) +{ + uint32_t tmpccmr2; + uint32_t tmpccer; + uint32_t tmpcr2; + + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_CC4_INSTANCE(TMRx)); + ASSERT_PARAM(IS_DDL_TMR_OCMODE(TMR_OCInitStruct->OCMode)); + ASSERT_PARAM(IS_DDL_TMR_OCSTATE(TMR_OCInitStruct->OCState)); + ASSERT_PARAM(IS_DDL_TMR_OCPOLARITY(TMR_OCInitStruct->OCPolarity)); + ASSERT_PARAM(IS_DDL_TMR_OCPOLARITY(TMR_OCInitStruct->OCNPolarity)); + ASSERT_PARAM(IS_DDL_TMR_OCSTATE(TMR_OCInitStruct->OCNState)); + + /* Disable the Channel 4: Reset the CC4E Bit */ + CLEAR_BIT(TMRx->CCEN, TMR_CCEN_CC4EN); + + /* Get the TMRx CCEN register value */ + tmpccer = DDL_TMR_ReadReg(TMRx, CCEN); + + /* Get the TMRx CTRL2 register value */ + tmpcr2 = DDL_TMR_ReadReg(TMRx, CTRL2); + + /* Get the TMRx CCM2 register value */ + tmpccmr2 = DDL_TMR_ReadReg(TMRx, CCM2); + + /* Reset Capture/Compare selection Bits */ + CLEAR_BIT(tmpccmr2, TMR_CCM2_CC4SEL); + + /* Select the Output Compare Mode */ + MODIFY_REG(tmpccmr2, TMR_CCM2_OC4MOD, TMR_OCInitStruct->OCMode << 8U); + + /* Set the Output Compare Polarity */ + MODIFY_REG(tmpccer, TMR_CCEN_CC4POL, TMR_OCInitStruct->OCPolarity << 12U); + + /* Set the Output State */ + MODIFY_REG(tmpccer, TMR_CCEN_CC4EN, TMR_OCInitStruct->OCState << 12U); + + if (IS_TMR_BREAK_INSTANCE(TMRx)) + { + ASSERT_PARAM(IS_DDL_TMR_OCIDLESTATE(TMR_OCInitStruct->OCNIdleState)); + ASSERT_PARAM(IS_DDL_TMR_OCIDLESTATE(TMR_OCInitStruct->OCIdleState)); + + /* Set the Output Idle state */ + MODIFY_REG(tmpcr2, TMR_CTRL2_OC4OIS, TMR_OCInitStruct->OCIdleState << 6U); + } + + /* Write to TMRx CTRL2 */ + DDL_TMR_WriteReg(TMRx, CTRL2, tmpcr2); + + /* Write to TMRx CCM2 */ + DDL_TMR_WriteReg(TMRx, CCM2, tmpccmr2); + + /* Set the Capture Compare Register value */ + DDL_TMR_OC_SetCompareCH4(TMRx, TMR_OCInitStruct->CompareValue); + + /* Write to TMRx CCEN */ + DDL_TMR_WriteReg(TMRx, CCEN , tmpccer); + + return SUCCESS; +} + + +/** + * @brief Configure the TMRx input channel 1. + * @param TMRx Timer Instance + * @param TMR_ICInitStruct pointer to the the TMRx input channel 1 configuration data structure + * @retval An ErrorStatus enumeration value: + * - SUCCESS: TMRx registers are de-initialized + * - ERROR: not applicable + */ +static ErrorStatus IC1Config(TMR_TypeDef *TMRx, DDL_TMR_IC_InitTypeDef *TMR_ICInitStruct) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_CC1_INSTANCE(TMRx)); + ASSERT_PARAM(IS_DDL_TMR_IC_POLARITY(TMR_ICInitStruct->ICPolarity)); + ASSERT_PARAM(IS_DDL_TMR_ACTIVEINPUT(TMR_ICInitStruct->ICActiveInput)); + ASSERT_PARAM(IS_DDL_TMR_ICPSC(TMR_ICInitStruct->ICPrescaler)); + ASSERT_PARAM(IS_DDL_TMR_IC_FILTER(TMR_ICInitStruct->ICFilter)); + + /* Disable the Channel 1: Reset the CC1E Bit */ + TMRx->CCEN &= (uint32_t)~TMR_CCEN_CC1EN; + + /* Select the Input and set the filter and the prescaler value */ + MODIFY_REG(TMRx->CCM1, + (TMR_CCM1_CC1SEL | TMR_CCM1_IC1F | TMR_CCM1_IC1PSC), + (TMR_ICInitStruct->ICActiveInput | TMR_ICInitStruct->ICFilter | TMR_ICInitStruct->ICPrescaler) >> 16U); + + /* Select the Polarity and set the CC1E Bit */ + MODIFY_REG(TMRx->CCEN, + (TMR_CCEN_CC1POL | TMR_CCEN_CC1NPOL), + (TMR_ICInitStruct->ICPolarity | TMR_CCEN_CC1EN)); + + return SUCCESS; +} + +/** + * @brief Configure the TMRx input channel 2. + * @param TMRx Timer Instance + * @param TMR_ICInitStruct pointer to the the TMRx input channel 2 configuration data structure + * @retval An ErrorStatus enumeration value: + * - SUCCESS: TMRx registers are de-initialized + * - ERROR: not applicable + */ +static ErrorStatus IC2Config(TMR_TypeDef *TMRx, DDL_TMR_IC_InitTypeDef *TMR_ICInitStruct) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_CC2_INSTANCE(TMRx)); + ASSERT_PARAM(IS_DDL_TMR_IC_POLARITY(TMR_ICInitStruct->ICPolarity)); + ASSERT_PARAM(IS_DDL_TMR_ACTIVEINPUT(TMR_ICInitStruct->ICActiveInput)); + ASSERT_PARAM(IS_DDL_TMR_ICPSC(TMR_ICInitStruct->ICPrescaler)); + ASSERT_PARAM(IS_DDL_TMR_IC_FILTER(TMR_ICInitStruct->ICFilter)); + + /* Disable the Channel 2: Reset the CC2E Bit */ + TMRx->CCEN &= (uint32_t)~TMR_CCEN_CC2EN; + + /* Select the Input and set the filter and the prescaler value */ + MODIFY_REG(TMRx->CCM1, + (TMR_CCM1_CC2SEL | TMR_CCM1_IC2F | TMR_CCM1_IC2PSC), + (TMR_ICInitStruct->ICActiveInput | TMR_ICInitStruct->ICFilter | TMR_ICInitStruct->ICPrescaler) >> 8U); + + /* Select the Polarity and set the CC2E Bit */ + MODIFY_REG(TMRx->CCEN, + (TMR_CCEN_CC2POL | TMR_CCEN_CC2NPOL), + ((TMR_ICInitStruct->ICPolarity << 4U) | TMR_CCEN_CC2EN)); + + return SUCCESS; +} + +/** + * @brief Configure the TMRx input channel 3. + * @param TMRx Timer Instance + * @param TMR_ICInitStruct pointer to the the TMRx input channel 3 configuration data structure + * @retval An ErrorStatus enumeration value: + * - SUCCESS: TMRx registers are de-initialized + * - ERROR: not applicable + */ +static ErrorStatus IC3Config(TMR_TypeDef *TMRx, DDL_TMR_IC_InitTypeDef *TMR_ICInitStruct) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_CC3_INSTANCE(TMRx)); + ASSERT_PARAM(IS_DDL_TMR_IC_POLARITY(TMR_ICInitStruct->ICPolarity)); + ASSERT_PARAM(IS_DDL_TMR_ACTIVEINPUT(TMR_ICInitStruct->ICActiveInput)); + ASSERT_PARAM(IS_DDL_TMR_ICPSC(TMR_ICInitStruct->ICPrescaler)); + ASSERT_PARAM(IS_DDL_TMR_IC_FILTER(TMR_ICInitStruct->ICFilter)); + + /* Disable the Channel 3: Reset the CC3E Bit */ + TMRx->CCEN &= (uint32_t)~TMR_CCEN_CC3EN; + + /* Select the Input and set the filter and the prescaler value */ + MODIFY_REG(TMRx->CCM2, + (TMR_CCM2_CC3SEL | TMR_CCM2_IC3F | TMR_CCM2_IC3PSC), + (TMR_ICInitStruct->ICActiveInput | TMR_ICInitStruct->ICFilter | TMR_ICInitStruct->ICPrescaler) >> 16U); + + /* Select the Polarity and set the CC3E Bit */ + MODIFY_REG(TMRx->CCEN, + (TMR_CCEN_CC3POL | TMR_CCEN_CC3NPOL), + ((TMR_ICInitStruct->ICPolarity << 8U) | TMR_CCEN_CC3EN)); + + return SUCCESS; +} + +/** + * @brief Configure the TMRx input channel 4. + * @param TMRx Timer Instance + * @param TMR_ICInitStruct pointer to the the TMRx input channel 4 configuration data structure + * @retval An ErrorStatus enumeration value: + * - SUCCESS: TMRx registers are de-initialized + * - ERROR: not applicable + */ +static ErrorStatus IC4Config(TMR_TypeDef *TMRx, DDL_TMR_IC_InitTypeDef *TMR_ICInitStruct) +{ + /* Check the parameters */ + ASSERT_PARAM(IS_TMR_CC4_INSTANCE(TMRx)); + ASSERT_PARAM(IS_DDL_TMR_IC_POLARITY(TMR_ICInitStruct->ICPolarity)); + ASSERT_PARAM(IS_DDL_TMR_ACTIVEINPUT(TMR_ICInitStruct->ICActiveInput)); + ASSERT_PARAM(IS_DDL_TMR_ICPSC(TMR_ICInitStruct->ICPrescaler)); + ASSERT_PARAM(IS_DDL_TMR_IC_FILTER(TMR_ICInitStruct->ICFilter)); + + /* Disable the Channel 4: Reset the CC4E Bit */ + TMRx->CCEN &= (uint32_t)~TMR_CCEN_CC4EN; + + /* Select the Input and set the filter and the prescaler value */ + MODIFY_REG(TMRx->CCM2, + (TMR_CCM2_CC4SEL | TMR_CCM2_IC4F | TMR_CCM2_IC4PSC), + (TMR_ICInitStruct->ICActiveInput | TMR_ICInitStruct->ICFilter | TMR_ICInitStruct->ICPrescaler) >> 8U); + + /* Select the Polarity and set the CC4E Bit */ + MODIFY_REG(TMRx->CCEN, + (TMR_CCEN_CC4POL | TMR_CCEN_CC4NPOL), + ((TMR_ICInitStruct->ICPolarity << 12U) | TMR_CCEN_CC4EN)); + + return SUCCESS; +} + + +/** + * @} + */ + +/** + * @} + */ + +#endif /* TMR1 || TMR2 || TMR3 || TMR4 || TMR5 || TMR6 || TMR7 || TMR8 || TMR9 || TMR10 || TMR11 || TMR12 || TMR13 || TMR14 */ + +/** + * @} + */ + +#endif /* USE_FULL_DDL_DRIVER */ + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_ddl_usart.c b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_ddl_usart.c new file mode 100644 index 0000000000..c7aa538272 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_ddl_usart.c @@ -0,0 +1,525 @@ +/** + * + * @file apm32f4xx_ddl_usart.c + * @brief USART DDL module driver. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + * + */ + +#if defined(USE_FULL_DDL_DRIVER) + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_ddl_usart.h" +#include "apm32f4xx_ddl_rcm.h" +#include "apm32f4xx_ddl_bus.h" +#ifdef USE_FULL_ASSERT +#include "apm32_assert.h" +#else +#define ASSERT_PARAM(_PARAM_) ((void)(_PARAM_)) +#endif + +/** @addtogroup APM32F4xx_DDL_Driver + * @{ + */ + +#if defined (USART1) || defined (USART2) || defined (USART3) || defined (USART6) || defined (UART4) || defined (UART5) || defined (UART7) || defined (UART8) || defined (UART9) || defined (UART10) + +/** @addtogroup USART_DDL + * @{ + */ + +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/** @addtogroup USART_DDL_Private_Constants + * @{ + */ + +/** + * @} + */ + + +/* Private macros ------------------------------------------------------------*/ +/** @addtogroup USART_DDL_Private_Macros + * @{ + */ + +/* __BAUDRATE__ The maximum Baud Rate is derived from the maximum clock available + * divided by the smallest oversampling used on the USART (i.e. 8) */ +#define IS_DDL_USART_BAUDRATE(__BAUDRATE__) ((__BAUDRATE__) <= 12500000U) + +/* __VALUE__ In case of oversampling by 16 and 8, BRR content must be greater than or equal to 16d. */ +#define IS_DDL_USART_BR_MIN(__VALUE__) ((__VALUE__) >= 16U) + +#define IS_DDL_USART_DIRECTION(__VALUE__) (((__VALUE__) == DDL_USART_DIRECTION_NONE) \ + || ((__VALUE__) == DDL_USART_DIRECTION_RX) \ + || ((__VALUE__) == DDL_USART_DIRECTION_TX) \ + || ((__VALUE__) == DDL_USART_DIRECTION_TX_RX)) + +#define IS_DDL_USART_PARITY(__VALUE__) (((__VALUE__) == DDL_USART_PARITY_NONE) \ + || ((__VALUE__) == DDL_USART_PARITY_EVEN) \ + || ((__VALUE__) == DDL_USART_PARITY_ODD)) + +#define IS_DDL_USART_DATAWIDTH(__VALUE__) (((__VALUE__) == DDL_USART_DATAWIDTH_8B) \ + || ((__VALUE__) == DDL_USART_DATAWIDTH_9B)) + +#define IS_DDL_USART_OVERSAMPLING(__VALUE__) (((__VALUE__) == DDL_USART_OVERSAMPLING_16) \ + || ((__VALUE__) == DDL_USART_OVERSAMPLING_8)) + +#define IS_DDL_USART_LASTBITCLKOUTPUT(__VALUE__) (((__VALUE__) == DDL_USART_LASTCLKPULSE_NO_OUTPUT) \ + || ((__VALUE__) == DDL_USART_LASTCLKPULSE_OUTPUT)) + +#define IS_DDL_USART_CLOCKPHASE(__VALUE__) (((__VALUE__) == DDL_USART_PHASE_1EDGE) \ + || ((__VALUE__) == DDL_USART_PHASE_2EDGE)) + +#define IS_DDL_USART_CLOCKPOLARITY(__VALUE__) (((__VALUE__) == DDL_USART_POLARITY_LOW) \ + || ((__VALUE__) == DDL_USART_POLARITY_HIGH)) + +#define IS_DDL_USART_CLOCKOUTPUT(__VALUE__) (((__VALUE__) == DDL_USART_CLOCK_DISABLE) \ + || ((__VALUE__) == DDL_USART_CLOCK_ENABLE)) + +#define IS_DDL_USART_STOPBITS(__VALUE__) (((__VALUE__) == DDL_USART_STOPBITS_0_5) \ + || ((__VALUE__) == DDL_USART_STOPBITS_1) \ + || ((__VALUE__) == DDL_USART_STOPBITS_1_5) \ + || ((__VALUE__) == DDL_USART_STOPBITS_2)) + +#define IS_DDL_USART_HWCONTROL(__VALUE__) (((__VALUE__) == DDL_USART_HWCONTROL_NONE) \ + || ((__VALUE__) == DDL_USART_HWCONTROL_RTS) \ + || ((__VALUE__) == DDL_USART_HWCONTROL_CTS) \ + || ((__VALUE__) == DDL_USART_HWCONTROL_RTS_CTS)) + +/** + * @} + */ + +/* Private function prototypes -----------------------------------------------*/ + +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup USART_DDL_Exported_Functions + * @{ + */ + +/** @addtogroup USART_DDL_EF_Init + * @{ + */ + +/** + * @brief De-initialize USART registers (Registers restored to their default values). + * @param USARTx USART Instance + * @retval An ErrorStatus enumeration value: + * - SUCCESS: USART registers are de-initialized + * - ERROR: USART registers are not de-initialized + */ +ErrorStatus DDL_USART_DeInit(USART_TypeDef *USARTx) +{ + ErrorStatus status = SUCCESS; + + /* Check the parameters */ + ASSERT_PARAM(IS_UART_INSTANCE(USARTx)); + + if (USARTx == USART1) + { + /* Force reset of USART clock */ + DDL_APB2_GRP1_ForceReset(DDL_APB2_GRP1_PERIPH_USART1); + + /* Release reset of USART clock */ + DDL_APB2_GRP1_ReleaseReset(DDL_APB2_GRP1_PERIPH_USART1); + } + else if (USARTx == USART2) + { + /* Force reset of USART clock */ + DDL_APB1_GRP1_ForceReset(DDL_APB1_GRP1_PERIPH_USART2); + + /* Release reset of USART clock */ + DDL_APB1_GRP1_ReleaseReset(DDL_APB1_GRP1_PERIPH_USART2); + } +#if defined(USART3) + else if (USARTx == USART3) + { + /* Force reset of USART clock */ + DDL_APB1_GRP1_ForceReset(DDL_APB1_GRP1_PERIPH_USART3); + + /* Release reset of USART clock */ + DDL_APB1_GRP1_ReleaseReset(DDL_APB1_GRP1_PERIPH_USART3); + } +#endif /* USART3 */ +#if defined(USART6) + else if (USARTx == USART6) + { + /* Force reset of USART clock */ + DDL_APB2_GRP1_ForceReset(DDL_APB2_GRP1_PERIPH_USART6); + + /* Release reset of USART clock */ + DDL_APB2_GRP1_ReleaseReset(DDL_APB2_GRP1_PERIPH_USART6); + } +#endif /* USART6 */ +#if defined(UART4) + else if (USARTx == UART4) + { + /* Force reset of UART clock */ + DDL_APB1_GRP1_ForceReset(DDL_APB1_GRP1_PERIPH_UART4); + + /* Release reset of UART clock */ + DDL_APB1_GRP1_ReleaseReset(DDL_APB1_GRP1_PERIPH_UART4); + } +#endif /* UART4 */ +#if defined(UART5) + else if (USARTx == UART5) + { + /* Force reset of UART clock */ + DDL_APB1_GRP1_ForceReset(DDL_APB1_GRP1_PERIPH_UART5); + + /* Release reset of UART clock */ + DDL_APB1_GRP1_ReleaseReset(DDL_APB1_GRP1_PERIPH_UART5); + } +#endif /* UART5 */ +#if defined(UART7) + else if (USARTx == UART7) + { + /* Force reset of UART clock */ + DDL_APB1_GRP1_ForceReset(DDL_APB1_GRP1_PERIPH_UART7); + + /* Release reset of UART clock */ + DDL_APB1_GRP1_ReleaseReset(DDL_APB1_GRP1_PERIPH_UART7); + } +#endif /* UART7 */ +#if defined(UART8) + else if (USARTx == UART8) + { + /* Force reset of UART clock */ + DDL_APB1_GRP1_ForceReset(DDL_APB1_GRP1_PERIPH_UART8); + + /* Release reset of UART clock */ + DDL_APB1_GRP1_ReleaseReset(DDL_APB1_GRP1_PERIPH_UART8); + } +#endif /* UART8 */ +#if defined(UART9) + else if (USARTx == UART9) + { + /* Force reset of UART clock */ + DDL_APB2_GRP1_ForceReset(DDL_APB2_GRP1_PERIPH_UART9); + + /* Release reset of UART clock */ + DDL_APB2_GRP1_ReleaseReset(DDL_APB2_GRP1_PERIPH_UART9); + } +#endif /* UART9 */ +#if defined(UART10) + else if (USARTx == UART10) + { + /* Force reset of UART clock */ + DDL_APB2_GRP1_ForceReset(DDL_APB2_GRP1_PERIPH_UART10); + + /* Release reset of UART clock */ + DDL_APB2_GRP1_ReleaseReset(DDL_APB2_GRP1_PERIPH_UART10); + } +#endif /* UART10 */ + else + { + status = ERROR; + } + + return (status); +} + +/** + * @brief Initialize USART registers according to the specified + * parameters in USART_InitStruct. + * @note As some bits in USART configuration registers can only be written when the USART is disabled (USART_CTRL1_UEN bit =0), + * USART IP should be in disabled state prior calling this function. Otherwise, ERROR result will be returned. + * @note Baud rate value stored in USART_InitStruct BaudRate field, should be valid (different from 0). + * @param USARTx USART Instance + * @param USART_InitStruct pointer to a DDL_USART_InitTypeDef structure + * that contains the configuration information for the specified USART peripheral. + * @retval An ErrorStatus enumeration value: + * - SUCCESS: USART registers are initialized according to USART_InitStruct content + * - ERROR: Problem occurred during USART Registers initialization + */ +ErrorStatus DDL_USART_Init(USART_TypeDef *USARTx, DDL_USART_InitTypeDef *USART_InitStruct) +{ + ErrorStatus status = ERROR; + uint32_t periphclk = DDL_RCM_PERIPH_FREQUENCY_NO; + DDL_RCM_ClocksTypeDef rcc_clocks; + + /* Check the parameters */ + ASSERT_PARAM(IS_UART_INSTANCE(USARTx)); + ASSERT_PARAM(IS_DDL_USART_BAUDRATE(USART_InitStruct->BaudRate)); + ASSERT_PARAM(IS_DDL_USART_DATAWIDTH(USART_InitStruct->DataWidth)); + ASSERT_PARAM(IS_DDL_USART_STOPBITS(USART_InitStruct->StopBits)); + ASSERT_PARAM(IS_DDL_USART_PARITY(USART_InitStruct->Parity)); + ASSERT_PARAM(IS_DDL_USART_DIRECTION(USART_InitStruct->TransferDirection)); + ASSERT_PARAM(IS_DDL_USART_HWCONTROL(USART_InitStruct->HardwareFlowControl)); + ASSERT_PARAM(IS_DDL_USART_OVERSAMPLING(USART_InitStruct->OverSampling)); + + /* USART needs to be in disabled state, in order to be able to configure some bits in + CTRLx registers */ + if (DDL_USART_IsEnabled(USARTx) == 0U) + { + /*---------------------------- USART CTRL1 Configuration ----------------------- + * Configure USARTx CTRL1 (USART Word Length, Parity, Mode and Oversampling bits) with parameters: + * - DataWidth: USART_CTRL1_DBLCFG bits according to USART_InitStruct->DataWidth value + * - Parity: USART_CTRL1_PCEN, USART_CTRL1_PCFG bits according to USART_InitStruct->Parity value + * - TransferDirection: USART_CTRL1_TXEN, USART_CTRL1_RXEN bits according to USART_InitStruct->TransferDirection value + * - Oversampling: USART_CTRL1_OSMCFG bit according to USART_InitStruct->OverSampling value. + */ + MODIFY_REG(USARTx->CTRL1, + (USART_CTRL1_DBLCFG | USART_CTRL1_PCEN | USART_CTRL1_PCFG | + USART_CTRL1_TXEN | USART_CTRL1_RXEN | USART_CTRL1_OSMCFG), + (USART_InitStruct->DataWidth | USART_InitStruct->Parity | + USART_InitStruct->TransferDirection | USART_InitStruct->OverSampling)); + + /*---------------------------- USART CTRL2 Configuration ----------------------- + * Configure USARTx CTRL2 (Stop bits) with parameters: + * - Stop Bits: USART_CTRL2_STOPCFG bits according to USART_InitStruct->StopBits value. + * - CLKEN, CPOL, CPHA and LBCL bits are to be configured using DDL_USART_ClockInit(). + */ + DDL_USART_SetStopBitsLength(USARTx, USART_InitStruct->StopBits); + + /*---------------------------- USART CTRL3 Configuration ----------------------- + * Configure USARTx CTRL3 (Hardware Flow Control) with parameters: + * - HardwareFlowControl: USART_CTRL3_RTSEN, USART_CTRL3_CTSEN bits according to USART_InitStruct->HardwareFlowControl value. + */ + DDL_USART_SetHWFlowCtrl(USARTx, USART_InitStruct->HardwareFlowControl); + + /*---------------------------- USART BRR Configuration ----------------------- + * Retrieve Clock frequency used for USART Peripheral + */ + DDL_RCM_GetSystemClocksFreq(&rcc_clocks); + if (USARTx == USART1) + { + periphclk = rcc_clocks.PCLK2_Frequency; + } + else if (USARTx == USART2) + { + periphclk = rcc_clocks.PCLK1_Frequency; + } +#if defined(USART3) + else if (USARTx == USART3) + { + periphclk = rcc_clocks.PCLK1_Frequency; + } +#endif /* USART3 */ +#if defined(USART6) + else if (USARTx == USART6) + { + periphclk = rcc_clocks.PCLK2_Frequency; + } +#endif /* USART6 */ +#if defined(UART4) + else if (USARTx == UART4) + { + periphclk = rcc_clocks.PCLK1_Frequency; + } +#endif /* UART4 */ +#if defined(UART5) + else if (USARTx == UART5) + { + periphclk = rcc_clocks.PCLK1_Frequency; + } +#endif /* UART5 */ +#if defined(UART7) + else if (USARTx == UART7) + { + periphclk = rcc_clocks.PCLK1_Frequency; + } +#endif /* UART7 */ +#if defined(UART8) + else if (USARTx == UART8) + { + periphclk = rcc_clocks.PCLK1_Frequency; + } +#endif /* UART8 */ +#if defined(UART9) + else if (USARTx == UART9) + { + periphclk = rcc_clocks.PCLK2_Frequency; + } +#endif /* UART9 */ +#if defined(UART10) + else if (USARTx == UART10) + { + periphclk = rcc_clocks.PCLK2_Frequency; + } +#endif /* UART10 */ + else + { + /* Nothing to do, as error code is already assigned to ERROR value */ + } + + /* Configure the USART Baud Rate : + - valid baud rate value (different from 0) is required + - Peripheral clock as returned by RCM service, should be valid (different from 0). + */ + if ((periphclk != DDL_RCM_PERIPH_FREQUENCY_NO) + && (USART_InitStruct->BaudRate != 0U)) + { + status = SUCCESS; + DDL_USART_SetBaudRate(USARTx, + periphclk, + USART_InitStruct->OverSampling, + USART_InitStruct->BaudRate); + + /* Check BR is greater than or equal to 16d */ + ASSERT_PARAM(IS_DDL_USART_BR_MIN(USARTx->BR)); + } + } + /* Endif (=> USART not in Disabled state => return ERROR) */ + + return (status); +} + +/** + * @brief Set each @ref DDL_USART_InitTypeDef field to default value. + * @param USART_InitStruct Pointer to a @ref DDL_USART_InitTypeDef structure + * whose fields will be set to default values. + * @retval None + */ + +void DDL_USART_StructInit(DDL_USART_InitTypeDef *USART_InitStruct) +{ + /* Set USART_InitStruct fields to default values */ + USART_InitStruct->BaudRate = 9600U; + USART_InitStruct->DataWidth = DDL_USART_DATAWIDTH_8B; + USART_InitStruct->StopBits = DDL_USART_STOPBITS_1; + USART_InitStruct->Parity = DDL_USART_PARITY_NONE ; + USART_InitStruct->TransferDirection = DDL_USART_DIRECTION_TX_RX; + USART_InitStruct->HardwareFlowControl = DDL_USART_HWCONTROL_NONE; + USART_InitStruct->OverSampling = DDL_USART_OVERSAMPLING_16; +} + +/** + * @brief Initialize USART Clock related settings according to the + * specified parameters in the USART_ClockInitStruct. + * @note As some bits in USART configuration registers can only be written when the USART is disabled (USART_CTRL1_UEN bit =0), + * USART IP should be in disabled state prior calling this function. Otherwise, ERROR result will be returned. + * @param USARTx USART Instance + * @param USART_ClockInitStruct Pointer to a @ref DDL_USART_ClockInitTypeDef structure + * that contains the Clock configuration information for the specified USART peripheral. + * @retval An ErrorStatus enumeration value: + * - SUCCESS: USART registers related to Clock settings are initialized according to USART_ClockInitStruct content + * - ERROR: Problem occurred during USART Registers initialization + */ +ErrorStatus DDL_USART_ClockInit(USART_TypeDef *USARTx, DDL_USART_ClockInitTypeDef *USART_ClockInitStruct) +{ + ErrorStatus status = SUCCESS; + + /* Check USART Instance and Clock signal output parameters */ + ASSERT_PARAM(IS_UART_INSTANCE(USARTx)); + ASSERT_PARAM(IS_DDL_USART_CLOCKOUTPUT(USART_ClockInitStruct->ClockOutput)); + + /* USART needs to be in disabled state, in order to be able to configure some bits in + CTRLx registers */ + if (DDL_USART_IsEnabled(USARTx) == 0U) + { + /*---------------------------- USART CTRL2 Configuration -----------------------*/ + /* If Clock signal has to be output */ + if (USART_ClockInitStruct->ClockOutput == DDL_USART_CLOCK_DISABLE) + { + /* Deactivate Clock signal delivery : + * - Disable Clock Output: USART_CTRL2_CLKEN cleared + */ + DDL_USART_DisableSCLKOutput(USARTx); + } + else + { + /* Ensure USART instance is USART capable */ + ASSERT_PARAM(IS_USART_INSTANCE(USARTx)); + + /* Check clock related parameters */ + ASSERT_PARAM(IS_DDL_USART_CLOCKPOLARITY(USART_ClockInitStruct->ClockPolarity)); + ASSERT_PARAM(IS_DDL_USART_CLOCKPHASE(USART_ClockInitStruct->ClockPhase)); + ASSERT_PARAM(IS_DDL_USART_LASTBITCLKOUTPUT(USART_ClockInitStruct->LastBitClockPulse)); + + /*---------------------------- USART CTRL2 Configuration ----------------------- + * Configure USARTx CTRL2 (Clock signal related bits) with parameters: + * - Enable Clock Output: USART_CTRL2_CLKEN set + * - Clock Polarity: USART_CTRL2_CPOL bit according to USART_ClockInitStruct->ClockPolarity value + * - Clock Phase: USART_CTRL2_CPHA bit according to USART_ClockInitStruct->ClockPhase value + * - Last Bit Clock Pulse Output: USART_CTRL2_LBCPOEN bit according to USART_ClockInitStruct->LastBitClockPulse value. + */ + MODIFY_REG(USARTx->CTRL2, + USART_CTRL2_CLKEN | USART_CTRL2_CPHA | USART_CTRL2_CPOL | USART_CTRL2_LBCPOEN, + USART_CTRL2_CLKEN | USART_ClockInitStruct->ClockPolarity | + USART_ClockInitStruct->ClockPhase | USART_ClockInitStruct->LastBitClockPulse); + } + } + /* Else (USART not in Disabled state => return ERROR */ + else + { + status = ERROR; + } + + return (status); +} + +/** + * @brief Set each field of a @ref DDL_USART_ClockInitTypeDef type structure to default value. + * @param USART_ClockInitStruct Pointer to a @ref DDL_USART_ClockInitTypeDef structure + * whose fields will be set to default values. + * @retval None + */ +void DDL_USART_ClockStructInit(DDL_USART_ClockInitTypeDef *USART_ClockInitStruct) +{ + /* Set DDL_USART_ClockInitStruct fields with default values */ + USART_ClockInitStruct->ClockOutput = DDL_USART_CLOCK_DISABLE; + USART_ClockInitStruct->ClockPolarity = DDL_USART_POLARITY_LOW; /* Not relevant when ClockOutput = DDL_USART_CLOCK_DISABLE */ + USART_ClockInitStruct->ClockPhase = DDL_USART_PHASE_1EDGE; /* Not relevant when ClockOutput = DDL_USART_CLOCK_DISABLE */ + USART_ClockInitStruct->LastBitClockPulse = DDL_USART_LASTCLKPULSE_NO_OUTPUT; /* Not relevant when ClockOutput = DDL_USART_CLOCK_DISABLE */ +} + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#endif /* USART1 || USART2 || USART3 || USART6 || UART4 || UART5 || UART7 || UART8 || UART9 || UART10 */ + +/** + * @} + */ + +#endif /* USE_FULL_DDL_DRIVER */ + + diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_ddl_usb.c b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_ddl_usb.c new file mode 100644 index 0000000000..f91e7c7889 --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_ddl_usb.c @@ -0,0 +1,2304 @@ +/** + * + * @file apm32f4xx_ddl_usb.c + * @brief USB Low Layer DDL module driver. + * + * This file provides firmware functions to manage the following + * functionalities of the USB Peripheral Controller: + * + Initialization/de-initialization functions + * + I/O operation functions + * + Peripheral Control functions + * + Peripheral State functions + * + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2016 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + * + @verbatim + ============================================================================== + ##### How to use this driver ##### + ============================================================================== + [..] + (#) Fill parameters of Init structure in USB_OTG_CfgTypeDef structure. + + (#) Call USB_CoreInit() API to initialize the USB Core peripheral. + + (#) The upper DAL HCD/PCD driver will call the right routines for its internal processes. + + @endverbatim + + * + */ + +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_dal.h" + +/** @addtogroup APM32F4xx_DAL_Driver + * @{ + */ + +#if defined (DAL_PCD_MODULE_ENABLED) || defined (DAL_HCD_MODULE_ENABLED) +#if defined (USB_OTG_FS) || defined (USB_OTG_HS) +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ +#if defined (USB_OTG_FS) || defined (USB_OTG_HS) +static DAL_StatusTypeDef USB_CoreReset(USB_OTG_GlobalTypeDef *USBx); + +/* Exported functions --------------------------------------------------------*/ +/** @defgroup USB_DDL_Exported_Functions USB Low Layer Exported Functions + * @{ + */ + +/** @defgroup USB_DDL_Exported_Functions_Group1 Initialization/de-initialization functions + * @brief Initialization and Configuration functions + * +@verbatim + =============================================================================== + ##### Initialization/de-initialization functions ##### + =============================================================================== + +@endverbatim + * @{ + */ + +/** + * @brief Initializes the USB Core + * @param USBx USB Instance + * @param cfg pointer to a USB_OTG_CfgTypeDef structure that contains + * the configuration information for the specified USBx peripheral. + * @retval DAL status + */ +DAL_StatusTypeDef USB_CoreInit(USB_OTG_GlobalTypeDef *USBx, USB_OTG_CfgTypeDef cfg) +{ + DAL_StatusTypeDef ret; + if (cfg.phy_itface == USB_OTG_ULPI_PHY) + { + USBx->GGCCFG &= ~(USB_OTG_GGCCFG_PWEN); + + /* Init The ULPI Interface */ + USBx->GUSBCFG &= ~(USB_OTG_GUSBCFG_DPSEL | USB_OTG_GUSBCFG_ULPISEL | USB_OTG_GUSBCFG_FSSTSEL); + + /* Select vbus source */ + USBx->GUSBCFG &= ~(USB_OTG_GUSBCFG_ULPIEVDSEL | USB_OTG_GUSBCFG_ULPIEVC); + if (cfg.use_external_vbus == 1U) + { + USBx->GUSBCFG |= USB_OTG_GUSBCFG_ULPIEVDSEL; + } + + /* Reset after a PHY select */ + ret = USB_CoreReset(USBx); + } + else /* Embedded Phy */ + { +#if defined(APM32F405xx) || defined(APM32F407xx) || defined(APM32F417xx) + /* USBD_HS_SPEED || USBH_HS_SPEED */ + if (cfg.speed == USBD_HS_SPEED) + { + /* Switch HS2 */ + USB_OTG_HS2->USB_SWITCH |= USB_OTG_HS2_USB_SWITCH; + USB_OTG_HS2->POWERON_CORE |= USB_OTG_HS2_POWERON_CORE; + USB_OTG_HS2->OTG_SUSPENDM |= USB_OTG_HS2_OTG_SUSPENDM; + USB_OTG_HS2->SW_RREF_I2C = 0x05U; + + /* Select HS ULPI PHY, no effect on HS2 */ + USBx->GUSBCFG &= ~(USB_OTG_GUSBCFG_FSSTSEL); + + /* Reset after a PHY select */ + ret = USB_CoreReset(USBx); + + if (cfg.battery_charging_enable == 0U) + { + /* Activate the USB Transceiver */ + USBx->GGCCFG |= USB_OTG_GGCCFG_PWEN; + } + else + { + /* Deactivate the USB Transceiver */ + USBx->GGCCFG &= ~(USB_OTG_GGCCFG_PWEN); + } + } + else + { + /* Select FS Embedded PHY */ + USBx->GUSBCFG |= USB_OTG_GUSBCFG_FSSTSEL; + + /* Reset after a PHY select */ + ret = USB_CoreReset(USBx); + + if (cfg.battery_charging_enable == 0U) + { + /* Activate the USB Transceiver */ + USBx->GGCCFG |= USB_OTG_GGCCFG_PWEN; + } + else + { + /* Deactivate the USB Transceiver */ + USBx->GGCCFG &= ~(USB_OTG_GGCCFG_PWEN); + } + } +#else + /* Select FS Embedded PHY */ + USBx->GUSBCFG |= USB_OTG_GUSBCFG_FSSTSEL; + + /* Reset after a PHY select */ + ret = USB_CoreReset(USBx); + + if (cfg.battery_charging_enable == 0U) + { + /* Activate the USB Transceiver */ + USBx->GGCCFG |= USB_OTG_GGCCFG_PWEN; + } + else + { + /* Deactivate the USB Transceiver */ + USBx->GGCCFG &= ~(USB_OTG_GGCCFG_PWEN); + } +#endif /* APM32F405xx || APM32F407xx || APM32F417xx */ + } + + if (cfg.dma_enable == 1U) + { + USBx->GAHBCFG |= USB_OTG_GAHBCFG_BLT_2; + USBx->GAHBCFG |= USB_OTG_GAHBCFG_DMAEN; + } + + return ret; +} + + +/** + * @brief Set the USB turnaround time + * @param USBx USB Instance + * @param hclk: AHB clock frequency + * @retval USB turnaround time In PHY Clocks number + */ +DAL_StatusTypeDef USB_SetTurnaroundTime(USB_OTG_GlobalTypeDef *USBx, + uint32_t hclk, uint8_t speed) +{ + uint32_t UsbTrd; + + /* The USBTRD is configured according to the tables below, depending on AHB frequency + used by application. In the low AHB frequency range it is used to stretch enough the USB response + time to IN tokens, the USB turnaround time, so to compensate for the longer AHB read access + latency to the Data FIFO */ + if (speed == USBD_FS_SPEED) + { + if ((hclk >= 14200000U) && (hclk < 15000000U)) + { + /* hclk Clock Range between 14.2-15 MHz */ + UsbTrd = 0xFU; + } + else if ((hclk >= 15000000U) && (hclk < 16000000U)) + { + /* hclk Clock Range between 15-16 MHz */ + UsbTrd = 0xEU; + } + else if ((hclk >= 16000000U) && (hclk < 17200000U)) + { + /* hclk Clock Range between 16-17.2 MHz */ + UsbTrd = 0xDU; + } + else if ((hclk >= 17200000U) && (hclk < 18500000U)) + { + /* hclk Clock Range between 17.2-18.5 MHz */ + UsbTrd = 0xCU; + } + else if ((hclk >= 18500000U) && (hclk < 20000000U)) + { + /* hclk Clock Range between 18.5-20 MHz */ + UsbTrd = 0xBU; + } + else if ((hclk >= 20000000U) && (hclk < 21800000U)) + { + /* hclk Clock Range between 20-21.8 MHz */ + UsbTrd = 0xAU; + } + else if ((hclk >= 21800000U) && (hclk < 24000000U)) + { + /* hclk Clock Range between 21.8-24 MHz */ + UsbTrd = 0x9U; + } + else if ((hclk >= 24000000U) && (hclk < 27700000U)) + { + /* hclk Clock Range between 24-27.7 MHz */ + UsbTrd = 0x8U; + } + else if ((hclk >= 27700000U) && (hclk < 32000000U)) + { + /* hclk Clock Range between 27.7-32 MHz */ + UsbTrd = 0x7U; + } + else /* if(hclk >= 32000000) */ + { + /* hclk Clock Range between 32-200 MHz */ + UsbTrd = 0x6U; + } + } + else if (speed == USBD_HS_SPEED) + { + UsbTrd = USBD_HS_TRDT_VALUE; + } + else + { + UsbTrd = USBD_DEFAULT_TRDT_VALUE; + } + + USBx->GUSBCFG &= ~USB_OTG_GUSBCFG_TRTIM; + USBx->GUSBCFG |= (uint32_t)((UsbTrd << 10) & USB_OTG_GUSBCFG_TRTIM); + + return DAL_OK; +} + +/** + * @brief USB_EnableGlobalInt + * Enables the controller's Global Int in the AHB Config reg + * @param USBx Selected device + * @retval DAL status + */ +DAL_StatusTypeDef USB_EnableGlobalInt(USB_OTG_GlobalTypeDef *USBx) +{ + USBx->GAHBCFG |= USB_OTG_GAHBCFG_GINTMASK; + return DAL_OK; +} + +/** + * @brief USB_DisableGlobalInt + * Disable the controller's Global Int in the AHB Config reg + * @param USBx Selected device + * @retval DAL status + */ +DAL_StatusTypeDef USB_DisableGlobalInt(USB_OTG_GlobalTypeDef *USBx) +{ + USBx->GAHBCFG &= ~USB_OTG_GAHBCFG_GINTMASK; + return DAL_OK; +} + +/** + * @brief USB_SetCurrentMode Set functional mode + * @param USBx Selected device + * @param mode current core mode + * This parameter can be one of these values: + * @arg USB_DEVICE_MODE Peripheral mode + * @arg USB_HOST_MODE Host mode + * @retval DAL status + */ +DAL_StatusTypeDef USB_SetCurrentMode(USB_OTG_GlobalTypeDef *USBx, USB_OTG_ModeTypeDef mode) +{ + uint32_t ms = 0U; + + USBx->GUSBCFG &= ~(USB_OTG_GUSBCFG_FHMODE | USB_OTG_GUSBCFG_FDMODE); + + if (mode == USB_HOST_MODE) + { + USBx->GUSBCFG |= USB_OTG_GUSBCFG_FHMODE; + + do + { + DAL_Delay(1U); + ms++; + } while ((USB_GetMode(USBx) != (uint32_t)USB_HOST_MODE) && (ms < 50U)); + } + else if (mode == USB_DEVICE_MODE) + { + USBx->GUSBCFG |= USB_OTG_GUSBCFG_FDMODE; + + do + { + DAL_Delay(1U); + ms++; + } while ((USB_GetMode(USBx) != (uint32_t)USB_DEVICE_MODE) && (ms < 50U)); + } + else + { + return DAL_ERROR; + } + + if (ms == 50U) + { + return DAL_ERROR; + } + + return DAL_OK; +} + +/** + * @brief USB_DevInit Initializes the USB_OTG controller registers + * for device mode + * @param USBx Selected device + * @param cfg pointer to a USB_OTG_CfgTypeDef structure that contains + * the configuration information for the specified USBx peripheral. + * @retval DAL status + */ +DAL_StatusTypeDef USB_DevInit(USB_OTG_GlobalTypeDef *USBx, USB_OTG_CfgTypeDef cfg) +{ + DAL_StatusTypeDef ret = DAL_OK; + uint32_t USBx_BASE = (uint32_t)USBx; + uint32_t i; + + for (i = 0U; i < 15U; i++) + { + USBx->DTXFIFO[i] = 0U; + } + + /* VBUS Sensing setup */ + if (cfg.vbus_sensing_enable == 0U) + { + /* + * Disable HW VBUS sensing. VBUS is internally considered to be always + * at VBUS-Valid level (5V). + */ + USBx_DEVICE->DCTRL |= USB_OTG_DCTRL_SDCNNT; + USBx->GGCCFG |= USB_OTG_GGCCFG_VBSDIS; + USBx->GGCCFG &= ~USB_OTG_GGCCFG_BDVBSEN; + USBx->GGCCFG &= ~USB_OTG_GGCCFG_ADVBSEN; + } + else + { + /* Enable HW VBUS sensing */ + USBx->GGCCFG &= ~USB_OTG_GGCCFG_VBSDIS; + USBx->GGCCFG |= USB_OTG_GGCCFG_BDVBSEN; + } + + /* Restart the Phy Clock */ + USBx_PCGCCTL = 0U; + + /* Device mode configuration */ + USBx_DEVICE->DCFG |= DCFG_FRAME_INTERVAL_80; + + if (cfg.phy_itface == USB_OTG_ULPI_PHY) + { + if (cfg.speed == USBD_HS_SPEED) + { + /* Set Core speed to High speed mode */ + (void)USB_SetDevSpeed(USBx, USB_OTG_SPEED_HIGH); + } + else + { + /* Set Core speed to Full speed mode */ + (void)USB_SetDevSpeed(USBx, USB_OTG_SPEED_HIGH_IN_FULL); + } + } + else + { +#if defined(APM32F405xx) || defined(APM32F407xx) || defined(APM32F417xx) + if (cfg.speed == USBD_HS_SPEED) + { + /* Set Core speed to High speed mode */ + (void)USB_SetDevSpeed(USBx, USB_OTG_SPEED_HIGH); + } + else if (cfg.speed == USBD_HSINFS_SPEED) + { + /* Set Core speed to Full speed mode */ + (void)USB_SetDevSpeed(USBx, USB_OTG_SPEED_FULL); + } + else + { + /* Set Core speed to Full speed mode */ + (void)USB_SetDevSpeed(USBx, USB_OTG_SPEED_FULL); + } +#else + /* Set Core speed to Full speed mode */ + (void)USB_SetDevSpeed(USBx, USB_OTG_SPEED_FULL); +#endif /* APM32F405xx || APM32F407xx || APM32F417xx */ + } + + /* Flush the FIFOs */ + if (USB_FlushTxFifo(USBx, 0x10U) != DAL_OK) /* all Tx FIFOs */ + { + ret = DAL_ERROR; + } + + if (USB_FlushRxFifo(USBx) != DAL_OK) + { + ret = DAL_ERROR; + } + + /* Clear all pending Device Interrupts */ + USBx_DEVICE->DINIMASK = 0U; + USBx_DEVICE->DOUTIMASK = 0U; + USBx_DEVICE->DAEPIMASK = 0U; + + for (i = 0U; i < cfg.dev_endpoints; i++) + { + if ((USBx_INEP(i)->DIEPCTRL & USB_OTG_DIEPCTRL_EPEN) == USB_OTG_DIEPCTRL_EPEN) + { + if (i == 0U) + { + USBx_INEP(i)->DIEPCTRL = USB_OTG_DIEPCTRL_NAKSET; + } + else + { + USBx_INEP(i)->DIEPCTRL = USB_OTG_DIEPCTRL_EPDIS | USB_OTG_DIEPCTRL_NAKSET; + } + } + else + { + USBx_INEP(i)->DIEPCTRL = 0U; + } + + USBx_INEP(i)->DIEPTRS = 0U; + USBx_INEP(i)->DIEPINT = 0xFB7FU; + } + + for (i = 0U; i < cfg.dev_endpoints; i++) + { + if ((USBx_OUTEP(i)->DOEPCTRL & USB_OTG_DOEPCTRL_EPEN) == USB_OTG_DOEPCTRL_EPEN) + { + if (i == 0U) + { + USBx_OUTEP(i)->DOEPCTRL = USB_OTG_DOEPCTRL_NAKSET; + } + else + { + USBx_OUTEP(i)->DOEPCTRL = USB_OTG_DOEPCTRL_EPDIS | USB_OTG_DOEPCTRL_NAKSET; + } + } + else + { + USBx_OUTEP(i)->DOEPCTRL = 0U; + } + + USBx_OUTEP(i)->DOEPTRS = 0U; + USBx_OUTEP(i)->DOEPINT = 0xFB7FU; + } + + USBx_DEVICE->DINIMASK &= ~(USB_OTG_DINIMASK_FUDRM); + + /* Disable all interrupts. */ + USBx->GINTMASK = 0U; + + /* Clear any pending interrupts */ + USBx->GCINT = 0xBFFFFFFFU; + + /* Enable the common interrupts */ + if (cfg.dma_enable == 0U) + { + USBx->GINTMASK |= USB_OTG_GINTMASK_RXFNONEM; + } + + /* Enable interrupts matching to the Device mode ONLY */ + USBx->GINTMASK |= USB_OTG_GINTMASK_USBSUSM | USB_OTG_GINTMASK_USBRSTM | + USB_OTG_GINTMASK_ENUMDM | USB_OTG_GINTMASK_INEPM | + USB_OTG_GINTMASK_OUTEPM | USB_OTG_GINTMASK_IIINTXM | + USB_OTG_GINTMASK_IP_OUTTXM | USB_OTG_GINTMASK_RWAKEM; + + if (cfg.Sof_enable != 0U) + { + USBx->GINTMASK |= USB_OTG_GINTMASK_SOFM; + } + + if (cfg.vbus_sensing_enable == 1U) + { + USBx->GINTMASK |= (USB_OTG_GINTMASK_SREQM | USB_OTG_GINTMASK_OTGM); + } + + return ret; +} + +/** + * @brief USB_FlushTxFifo Flush a Tx FIFO + * @param USBx Selected device + * @param num FIFO number + * This parameter can be a value from 1 to 15 + 15 means Flush all Tx FIFOs + * @retval DAL status + */ +DAL_StatusTypeDef USB_FlushTxFifo(USB_OTG_GlobalTypeDef *USBx, uint32_t num) +{ + __IO uint32_t count = 0U; + + /* Wait for AHB master IDLE state. */ + do + { + count++; + + if (count > 200000U) + { + return DAL_TIMEOUT; + } + } while ((USBx->GRSTCTRL & USB_OTG_GRSTCTRL_AHBMIDL) == 0U); + + /* Flush TX Fifo */ + count = 0U; + USBx->GRSTCTRL = (USB_OTG_GRSTCTRL_TXFFLU | (num << 6)); + + do + { + count++; + + if (count > 200000U) + { + return DAL_TIMEOUT; + } + } while ((USBx->GRSTCTRL & USB_OTG_GRSTCTRL_TXFFLU) == USB_OTG_GRSTCTRL_TXFFLU); + + return DAL_OK; +} + +/** + * @brief USB_FlushRxFifo Flush Rx FIFO + * @param USBx Selected device + * @retval DAL status + */ +DAL_StatusTypeDef USB_FlushRxFifo(USB_OTG_GlobalTypeDef *USBx) +{ + __IO uint32_t count = 0U; + + /* Wait for AHB master IDLE state. */ + do + { + count++; + + if (count > 200000U) + { + return DAL_TIMEOUT; + } + } while ((USBx->GRSTCTRL & USB_OTG_GRSTCTRL_AHBMIDL) == 0U); + + /* Flush RX Fifo */ + count = 0U; + USBx->GRSTCTRL = USB_OTG_GRSTCTRL_RXFFLU; + + do + { + count++; + + if (count > 200000U) + { + return DAL_TIMEOUT; + } + } while ((USBx->GRSTCTRL & USB_OTG_GRSTCTRL_RXFFLU) == USB_OTG_GRSTCTRL_RXFFLU); + + return DAL_OK; +} + +/** + * @brief USB_SetDevSpeed Initializes the DevSpd field of DCFG register + * depending the PHY type and the enumeration speed of the device. + * @param USBx Selected device + * @param speed device speed + * This parameter can be one of these values: + * @arg USB_OTG_SPEED_HIGH: High speed mode + * @arg USB_OTG_SPEED_HIGH_IN_FULL: High speed core in Full Speed mode + * @arg USB_OTG_SPEED_FULL: Full speed mode + * @retval Hal status + */ +DAL_StatusTypeDef USB_SetDevSpeed(USB_OTG_GlobalTypeDef *USBx, uint8_t speed) +{ + uint32_t USBx_BASE = (uint32_t)USBx; + + USBx_DEVICE->DCFG |= speed; + return DAL_OK; +} + +/** + * @brief USB_GetDevSpeed Return the Dev Speed + * @param USBx Selected device + * @retval speed device speed + * This parameter can be one of these values: + * @arg USBD_HS_SPEED: High speed mode + * @arg USBD_FS_SPEED: Full speed mode + */ +uint8_t USB_GetDevSpeed(USB_OTG_GlobalTypeDef *USBx) +{ + uint32_t USBx_BASE = (uint32_t)USBx; + uint8_t speed; + uint32_t DevEnumSpeed = USBx_DEVICE->DSTS & USB_OTG_DSTS_ENUMSPD; + + if (DevEnumSpeed == DSTS_ENUMSPD_HS_PHY_30MHZ_OR_60MHZ) + { + speed = USBD_HS_SPEED; + } + else if ((DevEnumSpeed == DSTS_ENUMSPD_FS_PHY_30MHZ_OR_60MHZ) || + (DevEnumSpeed == DSTS_ENUMSPD_FS_PHY_48MHZ)) + { + speed = USBD_FS_SPEED; + } + else + { + speed = 0xFU; + } + + return speed; +} + +/** + * @brief Activate and configure an endpoint + * @param USBx Selected device + * @param ep pointer to endpoint structure + * @retval DAL status + */ +DAL_StatusTypeDef USB_ActivateEndpoint(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTypeDef *ep) +{ + uint32_t USBx_BASE = (uint32_t)USBx; + uint32_t epnum = (uint32_t)ep->num; + + if (ep->is_in == 1U) + { + USBx_DEVICE->DAEPIMASK |= USB_OTG_DAEPIMASK_AINM & (uint32_t)(1UL << (ep->num & EP_ADDR_MSK)); + + if ((USBx_INEP(epnum)->DIEPCTRL & USB_OTG_DIEPCTRL_USBAEP) == 0U) + { + USBx_INEP(epnum)->DIEPCTRL |= (ep->maxpacket & USB_OTG_DIEPCTRL_MAXPS) | + ((uint32_t)ep->type << 18) | (epnum << 22) | + USB_OTG_DIEPCTRL_DPIDSET | + USB_OTG_DIEPCTRL_USBAEP; + } + } + else + { + USBx_DEVICE->DAEPIMASK |= USB_OTG_DAEPIMASK_AOUTM & ((uint32_t)(1UL << (ep->num & EP_ADDR_MSK)) << 16); + + if (((USBx_OUTEP(epnum)->DOEPCTRL) & USB_OTG_DOEPCTRL_USBAEP) == 0U) + { + USBx_OUTEP(epnum)->DOEPCTRL |= (ep->maxpacket & USB_OTG_DOEPCTRL_MAXPS) | + ((uint32_t)ep->type << 18) | + USB_OTG_DIEPCTRL_DPIDSET | + USB_OTG_DOEPCTRL_USBAEP; + } + } + return DAL_OK; +} + +/** + * @brief Activate and configure a dedicated endpoint + * @param USBx Selected device + * @param ep pointer to endpoint structure + * @retval DAL status + */ +DAL_StatusTypeDef USB_ActivateDedicatedEndpoint(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTypeDef *ep) +{ + uint32_t USBx_BASE = (uint32_t)USBx; + uint32_t epnum = (uint32_t)ep->num; + + /* Read DEPCTLn register */ + if (ep->is_in == 1U) + { + if (((USBx_INEP(epnum)->DIEPCTRL) & USB_OTG_DIEPCTRL_USBAEP) == 0U) + { + USBx_INEP(epnum)->DIEPCTRL |= (ep->maxpacket & USB_OTG_DIEPCTRL_MAXPS) | + ((uint32_t)ep->type << 18) | (epnum << 22) | + USB_OTG_DIEPCTRL_DPIDSET | + USB_OTG_DIEPCTRL_USBAEP; + } + + USBx_DEVICE->DEPIMASK |= USB_OTG_DAEPIMASK_AINM & (uint32_t)(1UL << (ep->num & EP_ADDR_MSK)); + } + else + { + if (((USBx_OUTEP(epnum)->DOEPCTRL) & USB_OTG_DOEPCTRL_USBAEP) == 0U) + { + USBx_OUTEP(epnum)->DOEPCTRL |= (ep->maxpacket & USB_OTG_DOEPCTRL_MAXPS) | + ((uint32_t)ep->type << 18) | (epnum << 22) | + USB_OTG_DOEPCTRL_USBAEP; + } + + USBx_DEVICE->DEPIMASK |= USB_OTG_DAEPIMASK_AOUTM & ((uint32_t)(1UL << (ep->num & EP_ADDR_MSK)) << 16); + } + + return DAL_OK; +} + +/** + * @brief De-activate and de-initialize an endpoint + * @param USBx Selected device + * @param ep pointer to endpoint structure + * @retval DAL status + */ +DAL_StatusTypeDef USB_DeactivateEndpoint(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTypeDef *ep) +{ + uint32_t USBx_BASE = (uint32_t)USBx; + uint32_t epnum = (uint32_t)ep->num; + + /* Read DEPCTLn register */ + if (ep->is_in == 1U) + { + if ((USBx_INEP(epnum)->DIEPCTRL & USB_OTG_DIEPCTRL_EPEN) == USB_OTG_DIEPCTRL_EPEN) + { + USBx_INEP(epnum)->DIEPCTRL |= USB_OTG_DIEPCTRL_NAKSET; + USBx_INEP(epnum)->DIEPCTRL |= USB_OTG_DIEPCTRL_EPDIS; + } + + USBx_DEVICE->DEPIMASK &= ~(USB_OTG_DAEPIMASK_AINM & (uint32_t)(1UL << (ep->num & EP_ADDR_MSK))); + USBx_DEVICE->DAEPIMASK &= ~(USB_OTG_DAEPIMASK_AINM & (uint32_t)(1UL << (ep->num & EP_ADDR_MSK))); + USBx_INEP(epnum)->DIEPCTRL &= ~(USB_OTG_DIEPCTRL_USBAEP | + USB_OTG_DIEPCTRL_MAXPS | + USB_OTG_DIEPCTRL_TXFNUM | + USB_OTG_DIEPCTRL_DPIDSET | + USB_OTG_DIEPCTRL_EPTYPE); + } + else + { + if ((USBx_OUTEP(epnum)->DOEPCTRL & USB_OTG_DOEPCTRL_EPEN) == USB_OTG_DOEPCTRL_EPEN) + { + USBx_OUTEP(epnum)->DOEPCTRL |= USB_OTG_DOEPCTRL_NAKSET; + USBx_OUTEP(epnum)->DOEPCTRL |= USB_OTG_DOEPCTRL_EPDIS; + } + + USBx_DEVICE->DEPIMASK &= ~(USB_OTG_DAEPIMASK_AOUTM & ((uint32_t)(1UL << (ep->num & EP_ADDR_MSK)) << 16)); + USBx_DEVICE->DAEPIMASK &= ~(USB_OTG_DAEPIMASK_AOUTM & ((uint32_t)(1UL << (ep->num & EP_ADDR_MSK)) << 16)); + USBx_OUTEP(epnum)->DOEPCTRL &= ~(USB_OTG_DOEPCTRL_USBAEP | + USB_OTG_DOEPCTRL_MAXPS | + USB_OTG_DOEPCTRL_DPIDSET | + USB_OTG_DOEPCTRL_EPTYPE); + } + + return DAL_OK; +} + +/** + * @brief De-activate and de-initialize a dedicated endpoint + * @param USBx Selected device + * @param ep pointer to endpoint structure + * @retval DAL status + */ +DAL_StatusTypeDef USB_DeactivateDedicatedEndpoint(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTypeDef *ep) +{ + uint32_t USBx_BASE = (uint32_t)USBx; + uint32_t epnum = (uint32_t)ep->num; + + /* Read DEPCTLn register */ + if (ep->is_in == 1U) + { + if ((USBx_INEP(epnum)->DIEPCTRL & USB_OTG_DIEPCTRL_EPEN) == USB_OTG_DIEPCTRL_EPEN) + { + USBx_INEP(epnum)->DIEPCTRL |= USB_OTG_DIEPCTRL_NAKSET; + USBx_INEP(epnum)->DIEPCTRL |= USB_OTG_DIEPCTRL_EPDIS; + } + + USBx_INEP(epnum)->DIEPCTRL &= ~ USB_OTG_DIEPCTRL_USBAEP; + USBx_DEVICE->DAEPIMASK &= ~(USB_OTG_DAEPIMASK_AINM & (uint32_t)(1UL << (ep->num & EP_ADDR_MSK))); + } + else + { + if ((USBx_OUTEP(epnum)->DOEPCTRL & USB_OTG_DOEPCTRL_EPEN) == USB_OTG_DOEPCTRL_EPEN) + { + USBx_OUTEP(epnum)->DOEPCTRL |= USB_OTG_DOEPCTRL_NAKSET; + USBx_OUTEP(epnum)->DOEPCTRL |= USB_OTG_DOEPCTRL_EPDIS; + } + + USBx_OUTEP(epnum)->DOEPCTRL &= ~USB_OTG_DOEPCTRL_USBAEP; + USBx_DEVICE->DAEPIMASK &= ~(USB_OTG_DAEPIMASK_AOUTM & ((uint32_t)(1UL << (ep->num & EP_ADDR_MSK)) << 16)); + } + + return DAL_OK; +} + +/** + * @brief USB_EPStartXfer : setup and starts a transfer over an EP + * @param USBx Selected device + * @param ep pointer to endpoint structure + * @param dma USB dma enabled or disabled + * This parameter can be one of these values: + * 0 : DMA feature not used + * 1 : DMA feature used + * @retval DAL status + */ +DAL_StatusTypeDef USB_EPStartXfer(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTypeDef *ep, uint8_t dma) +{ + uint32_t USBx_BASE = (uint32_t)USBx; + uint32_t epnum = (uint32_t)ep->num; + uint16_t pktcnt; + + /* IN endpoint */ + if (ep->is_in == 1U) + { + /* Zero Length Packet? */ + if (ep->xfer_len == 0U) + { + USBx_INEP(epnum)->DIEPTRS &= ~(USB_OTG_DIEPTRS_EPPCNT); + USBx_INEP(epnum)->DIEPTRS |= (USB_OTG_DIEPTRS_EPPCNT & (1U << 19)); + USBx_INEP(epnum)->DIEPTRS &= ~(USB_OTG_DIEPTRS_EPTRS); + } + else + { + /* Program the transfer size and packet count + * as follows: xfersize = N * maxpacket + + * short_packet pktcnt = N + (short_packet + * exist ? 1 : 0) + */ + USBx_INEP(epnum)->DIEPTRS &= ~(USB_OTG_DIEPTRS_EPTRS); + USBx_INEP(epnum)->DIEPTRS &= ~(USB_OTG_DIEPTRS_EPPCNT); + USBx_INEP(epnum)->DIEPTRS |= (USB_OTG_DIEPTRS_EPPCNT & + (((ep->xfer_len + ep->maxpacket - 1U) / ep->maxpacket) << 19)); + + USBx_INEP(epnum)->DIEPTRS |= (USB_OTG_DIEPTRS_EPTRS & ep->xfer_len); + + if (ep->type == EP_TYPE_ISOC) + { + USBx_INEP(epnum)->DIEPTRS &= ~(USB_OTG_DIEPTRS_TXDSEL); + USBx_INEP(epnum)->DIEPTRS |= (USB_OTG_DIEPTRS_TXDSEL & (1U << 29)); + } + } + + if (dma == 1U) + { + if ((uint32_t)ep->dma_addr != 0U) + { + USBx_INEP(epnum)->DIEPDMA = (uint32_t)(ep->dma_addr); + } + + if (ep->type == EP_TYPE_ISOC) + { + if ((USBx_DEVICE->DSTS & (1U << 8)) == 0U) + { + USBx_INEP(epnum)->DIEPCTRL |= USB_OTG_DIEPCTRL_OFSET; + } + else + { + USBx_INEP(epnum)->DIEPCTRL |= USB_OTG_DIEPCTRL_DPIDSET; + } + } + + /* EP enable, IN data in FIFO */ + USBx_INEP(epnum)->DIEPCTRL |= (USB_OTG_DIEPCTRL_NAKCLR | USB_OTG_DIEPCTRL_EPEN); + } + else + { + /* EP enable, IN data in FIFO */ + USBx_INEP(epnum)->DIEPCTRL |= (USB_OTG_DIEPCTRL_NAKCLR | USB_OTG_DIEPCTRL_EPEN); + + if (ep->type != EP_TYPE_ISOC) + { + /* Enable the Tx FIFO Empty Interrupt for this EP */ + if (ep->xfer_len > 0U) + { + USBx_DEVICE->DIEIMASK |= 1UL << (ep->num & EP_ADDR_MSK); + } + } + else + { + if ((USBx_DEVICE->DSTS & (1U << 8)) == 0U) + { + USBx_INEP(epnum)->DIEPCTRL |= USB_OTG_DIEPCTRL_OFSET; + } + else + { + USBx_INEP(epnum)->DIEPCTRL |= USB_OTG_DIEPCTRL_DPIDSET; + } + + (void)USB_WritePacket(USBx, ep->xfer_buff, ep->num, (uint16_t)ep->xfer_len, dma); + } + } + } + else /* OUT endpoint */ + { + /* Program the transfer size and packet count as follows: + * pktcnt = N + * xfersize = N * maxpacket + */ + USBx_OUTEP(epnum)->DOEPTRS &= ~(USB_OTG_DOEPTRS_EPTRS); + USBx_OUTEP(epnum)->DOEPTRS &= ~(USB_OTG_DOEPTRS_EPPCNT); + + if (ep->xfer_len == 0U) + { + USBx_OUTEP(epnum)->DOEPTRS |= (USB_OTG_DOEPTRS_EPTRS & ep->maxpacket); + USBx_OUTEP(epnum)->DOEPTRS |= (USB_OTG_DOEPTRS_EPPCNT & (1U << 19)); + } + else + { + pktcnt = (uint16_t)((ep->xfer_len + ep->maxpacket - 1U) / ep->maxpacket); + ep->xfer_size = ep->maxpacket * pktcnt; + + USBx_OUTEP(epnum)->DOEPTRS |= USB_OTG_DOEPTRS_EPPCNT & ((uint32_t)pktcnt << 19); + USBx_OUTEP(epnum)->DOEPTRS |= USB_OTG_DOEPTRS_EPTRS & ep->xfer_size; + } + + if (dma == 1U) + { + if ((uint32_t)ep->xfer_buff != 0U) + { + USBx_OUTEP(epnum)->DOEPDMA = (uint32_t)(ep->xfer_buff); + } + } + + if (ep->type == EP_TYPE_ISOC) + { + if ((USBx_DEVICE->DSTS & (1U << 8)) == 0U) + { + USBx_OUTEP(epnum)->DOEPCTRL |= USB_OTG_DOEPCTRL_OFSET; + } + else + { + USBx_OUTEP(epnum)->DOEPCTRL |= USB_OTG_DOEPCTRL_DPIDSET; + } + } + /* EP enable */ + USBx_OUTEP(epnum)->DOEPCTRL |= (USB_OTG_DOEPCTRL_NAKCLR | USB_OTG_DOEPCTRL_EPEN); + } + + return DAL_OK; +} + +/** + * @brief USB_EP0StartXfer : setup and starts a transfer over the EP 0 + * @param USBx Selected device + * @param ep pointer to endpoint structure + * @param dma USB dma enabled or disabled + * This parameter can be one of these values: + * 0 : DMA feature not used + * 1 : DMA feature used + * @retval DAL status + */ +DAL_StatusTypeDef USB_EP0StartXfer(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTypeDef *ep, uint8_t dma) +{ + uint32_t USBx_BASE = (uint32_t)USBx; + uint32_t epnum = (uint32_t)ep->num; + + /* IN endpoint */ + if (ep->is_in == 1U) + { + /* Zero Length Packet? */ + if (ep->xfer_len == 0U) + { + USBx_INEP(epnum)->DIEPTRS &= ~(USB_OTG_DIEPTRS_EPPCNT); + USBx_INEP(epnum)->DIEPTRS |= (USB_OTG_DIEPTRS_EPPCNT & (1U << 19)); + USBx_INEP(epnum)->DIEPTRS &= ~(USB_OTG_DIEPTRS_EPTRS); + } + else + { + /* Program the transfer size and packet count + * as follows: xfersize = N * maxpacket + + * short_packet pktcnt = N + (short_packet + * exist ? 1 : 0) + */ + USBx_INEP(epnum)->DIEPTRS &= ~(USB_OTG_DIEPTRS_EPTRS); + USBx_INEP(epnum)->DIEPTRS &= ~(USB_OTG_DIEPTRS_EPPCNT); + + if (ep->xfer_len > ep->maxpacket) + { + ep->xfer_len = ep->maxpacket; + } + USBx_INEP(epnum)->DIEPTRS |= (USB_OTG_DIEPTRS_EPPCNT & (1U << 19)); + USBx_INEP(epnum)->DIEPTRS |= (USB_OTG_DIEPTRS_EPTRS & ep->xfer_len); + } + + if (dma == 1U) + { + if ((uint32_t)ep->dma_addr != 0U) + { + USBx_INEP(epnum)->DIEPDMA = (uint32_t)(ep->dma_addr); + } + + /* EP enable, IN data in FIFO */ + USBx_INEP(epnum)->DIEPCTRL |= (USB_OTG_DIEPCTRL_NAKCLR | USB_OTG_DIEPCTRL_EPEN); + } + else + { + /* EP enable, IN data in FIFO */ + USBx_INEP(epnum)->DIEPCTRL |= (USB_OTG_DIEPCTRL_NAKCLR | USB_OTG_DIEPCTRL_EPEN); + + /* Enable the Tx FIFO Empty Interrupt for this EP */ + if (ep->xfer_len > 0U) + { + USBx_DEVICE->DIEIMASK |= 1UL << (ep->num & EP_ADDR_MSK); + } + } + } + else /* OUT endpoint */ + { + /* Program the transfer size and packet count as follows: + * pktcnt = N + * xfersize = N * maxpacket + */ + USBx_OUTEP(epnum)->DOEPTRS &= ~(USB_OTG_DOEPTRS_EPTRS); + USBx_OUTEP(epnum)->DOEPTRS &= ~(USB_OTG_DOEPTRS_EPPCNT); + + if (ep->xfer_len > 0U) + { + ep->xfer_len = ep->maxpacket; + } + + /* Store transfer size, for EP0 this is equal to endpoint max packet size */ + ep->xfer_size = ep->maxpacket; + + USBx_OUTEP(epnum)->DOEPTRS |= (USB_OTG_DOEPTRS_EPPCNT & (1U << 19)); + USBx_OUTEP(epnum)->DOEPTRS |= (USB_OTG_DOEPTRS_EPTRS & ep->xfer_size); + + if (dma == 1U) + { + if ((uint32_t)ep->xfer_buff != 0U) + { + USBx_OUTEP(epnum)->DOEPDMA = (uint32_t)(ep->xfer_buff); + } + } + + /* EP enable */ + USBx_OUTEP(epnum)->DOEPCTRL |= (USB_OTG_DOEPCTRL_NAKCLR | USB_OTG_DOEPCTRL_EPEN); + } + + return DAL_OK; +} + + +/** + * @brief USB_EPStoptXfer Stop transfer on an EP + * @param USBx usb device instance + * @param ep pointer to endpoint structure + * @retval DAL status + */ +DAL_StatusTypeDef USB_EPStopXfer(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTypeDef *ep) +{ + __IO uint32_t count = 0U; + DAL_StatusTypeDef ret = DAL_OK; + uint32_t USBx_BASE = (uint32_t)USBx; + + /* IN endpoint */ + if (ep->is_in == 1U) + { + /* EP enable, IN data in FIFO */ + if (((USBx_INEP(ep->num)->DIEPCTRL) & USB_OTG_DIEPCTRL_EPEN) == USB_OTG_DIEPCTRL_EPEN) + { + USBx_INEP(ep->num)->DIEPCTRL |= (USB_OTG_DIEPCTRL_NAKSET); + USBx_INEP(ep->num)->DIEPCTRL |= (USB_OTG_DIEPCTRL_EPDIS); + + do + { + count++; + + if (count > 10000U) + { + ret = DAL_ERROR; + break; + } + } while (((USBx_INEP(ep->num)->DIEPCTRL) & USB_OTG_DIEPCTRL_EPEN) == USB_OTG_DIEPCTRL_EPEN); + } + } + else /* OUT endpoint */ + { + if (((USBx_OUTEP(ep->num)->DOEPCTRL) & USB_OTG_DOEPCTRL_EPEN) == USB_OTG_DOEPCTRL_EPEN) + { + USBx_OUTEP(ep->num)->DOEPCTRL |= (USB_OTG_DOEPCTRL_NAKSET); + USBx_OUTEP(ep->num)->DOEPCTRL |= (USB_OTG_DOEPCTRL_EPDIS); + + do + { + count++; + + if (count > 10000U) + { + ret = DAL_ERROR; + break; + } + } while (((USBx_OUTEP(ep->num)->DOEPCTRL) & USB_OTG_DOEPCTRL_EPEN) == USB_OTG_DOEPCTRL_EPEN); + } + } + + return ret; +} + + +/** + * @brief USB_WritePacket : Writes a packet into the Tx FIFO associated + * with the EP/channel + * @param USBx Selected device + * @param src pointer to source buffer + * @param ch_ep_num endpoint or host channel number + * @param len Number of bytes to write + * @param dma USB dma enabled or disabled + * This parameter can be one of these values: + * 0 : DMA feature not used + * 1 : DMA feature used + * @retval DAL status + */ +DAL_StatusTypeDef USB_WritePacket(USB_OTG_GlobalTypeDef *USBx, uint8_t *src, + uint8_t ch_ep_num, uint16_t len, uint8_t dma) +{ + uint32_t USBx_BASE = (uint32_t)USBx; + uint8_t *pSrc = src; + uint32_t count32b; + uint32_t i; + + if (dma == 0U) + { + count32b = ((uint32_t)len + 3U) / 4U; + for (i = 0U; i < count32b; i++) + { + USBx_DFIFO((uint32_t)ch_ep_num) = __UNALIGNED_UINT32_READ(pSrc); + pSrc++; + pSrc++; + pSrc++; + pSrc++; + } + } + + return DAL_OK; +} + +/** + * @brief USB_ReadPacket : read a packet from the RX FIFO + * @param USBx Selected device + * @param dest source pointer + * @param len Number of bytes to read + * @retval pointer to destination buffer + */ +void *USB_ReadPacket(USB_OTG_GlobalTypeDef *USBx, uint8_t *dest, uint16_t len) +{ + uint32_t USBx_BASE = (uint32_t)USBx; + uint8_t *pDest = dest; + uint32_t pData; + uint32_t i; + uint32_t count32b = (uint32_t)len >> 2U; + uint16_t remaining_bytes = len % 4U; + + for (i = 0U; i < count32b; i++) + { + __UNALIGNED_UINT32_WRITE(pDest, USBx_DFIFO(0U)); + pDest++; + pDest++; + pDest++; + pDest++; + } + + /* When Number of data is not word aligned, read the remaining byte */ + if (remaining_bytes != 0U) + { + i = 0U; + __UNALIGNED_UINT32_WRITE(&pData, USBx_DFIFO(0U)); + + do + { + *(uint8_t *)pDest = (uint8_t)(pData >> (8U * (uint8_t)(i))); + i++; + pDest++; + remaining_bytes--; + } while (remaining_bytes != 0U); + } + + return ((void *)pDest); +} + +/** + * @brief USB_EPSetStall : set a stall condition over an EP + * @param USBx Selected device + * @param ep pointer to endpoint structure + * @retval DAL status + */ +DAL_StatusTypeDef USB_EPSetStall(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTypeDef *ep) +{ + uint32_t USBx_BASE = (uint32_t)USBx; + uint32_t epnum = (uint32_t)ep->num; + + if (ep->is_in == 1U) + { + if (((USBx_INEP(epnum)->DIEPCTRL & USB_OTG_DIEPCTRL_EPEN) == 0U) && (epnum != 0U)) + { + USBx_INEP(epnum)->DIEPCTRL &= ~(USB_OTG_DIEPCTRL_EPDIS); + } + USBx_INEP(epnum)->DIEPCTRL |= USB_OTG_DIEPCTRL_STALLH; + } + else + { + if (((USBx_OUTEP(epnum)->DOEPCTRL & USB_OTG_DOEPCTRL_EPEN) == 0U) && (epnum != 0U)) + { + USBx_OUTEP(epnum)->DOEPCTRL &= ~(USB_OTG_DOEPCTRL_EPDIS); + } + USBx_OUTEP(epnum)->DOEPCTRL |= USB_OTG_DOEPCTRL_STALLH; + } + + return DAL_OK; +} + +/** + * @brief USB_EPClearStall : Clear a stall condition over an EP + * @param USBx Selected device + * @param ep pointer to endpoint structure + * @retval DAL status + */ +DAL_StatusTypeDef USB_EPClearStall(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTypeDef *ep) +{ + uint32_t USBx_BASE = (uint32_t)USBx; + uint32_t epnum = (uint32_t)ep->num; + + if (ep->is_in == 1U) + { + USBx_INEP(epnum)->DIEPCTRL &= ~USB_OTG_DIEPCTRL_STALLH; + if ((ep->type == EP_TYPE_INTR) || (ep->type == EP_TYPE_BULK)) + { + USBx_INEP(epnum)->DIEPCTRL |= USB_OTG_DIEPCTRL_DPIDSET; /* DATA0 */ + } + } + else + { + USBx_OUTEP(epnum)->DOEPCTRL &= ~USB_OTG_DOEPCTRL_STALLH; + if ((ep->type == EP_TYPE_INTR) || (ep->type == EP_TYPE_BULK)) + { + USBx_OUTEP(epnum)->DOEPCTRL |= USB_OTG_DOEPCTRL_DPIDSET; /* DATA0 */ + } + } + return DAL_OK; +} + +/** + * @brief USB_StopDevice : Stop the usb device mode + * @param USBx Selected device + * @retval DAL status + */ +DAL_StatusTypeDef USB_StopDevice(USB_OTG_GlobalTypeDef *USBx) +{ + DAL_StatusTypeDef ret; + uint32_t USBx_BASE = (uint32_t)USBx; + uint32_t i; + + /* Clear Pending interrupt */ + for (i = 0U; i < 15U; i++) + { + USBx_INEP(i)->DIEPINT = 0xFB7FU; + USBx_OUTEP(i)->DOEPINT = 0xFB7FU; + } + + /* Clear interrupt masks */ + USBx_DEVICE->DINIMASK = 0U; + USBx_DEVICE->DOUTIMASK = 0U; + USBx_DEVICE->DAEPIMASK = 0U; + + /* Flush the FIFO */ + ret = USB_FlushRxFifo(USBx); + if (ret != DAL_OK) + { + return ret; + } + + ret = USB_FlushTxFifo(USBx, 0x10U); + if (ret != DAL_OK) + { + return ret; + } + + return ret; +} + +/** + * @brief USB_SetDevAddress : Stop the usb device mode + * @param USBx Selected device + * @param address new device address to be assigned + * This parameter can be a value from 0 to 255 + * @retval DAL status + */ +DAL_StatusTypeDef USB_SetDevAddress(USB_OTG_GlobalTypeDef *USBx, uint8_t address) +{ + uint32_t USBx_BASE = (uint32_t)USBx; + + USBx_DEVICE->DCFG &= ~(USB_OTG_DCFG_DADDR); + USBx_DEVICE->DCFG |= ((uint32_t)address << 4) & USB_OTG_DCFG_DADDR; + + return DAL_OK; +} + +/** + * @brief USB_DevConnect : Connect the USB device by enabling Rpu + * @param USBx Selected device + * @retval DAL status + */ +DAL_StatusTypeDef USB_DevConnect(USB_OTG_GlobalTypeDef *USBx) +{ + uint32_t USBx_BASE = (uint32_t)USBx; + + /* In case phy is stopped, ensure to ungate and restore the phy CLK */ + USBx_PCGCCTL &= ~(USB_OTG_PCGCCTL_STOPCLK | USB_OTG_PCGCCTL_GATECLK); + + USBx_DEVICE->DCTRL &= ~USB_OTG_DCTRL_SDCNNT; + + return DAL_OK; +} + +/** + * @brief USB_DevDisconnect : Disconnect the USB device by disabling Rpu + * @param USBx Selected device + * @retval DAL status + */ +DAL_StatusTypeDef USB_DevDisconnect(USB_OTG_GlobalTypeDef *USBx) +{ + uint32_t USBx_BASE = (uint32_t)USBx; + + /* In case phy is stopped, ensure to ungate and restore the phy CLK */ + USBx_PCGCCTL &= ~(USB_OTG_PCGCCTL_STOPCLK | USB_OTG_PCGCCTL_GATECLK); + + USBx_DEVICE->DCTRL |= USB_OTG_DCTRL_SDCNNT; + + return DAL_OK; +} + +/** + * @brief USB_ReadInterrupts: return the global USB interrupt status + * @param USBx Selected device + * @retval DAL status + */ +uint32_t USB_ReadInterrupts(USB_OTG_GlobalTypeDef *USBx) +{ + uint32_t tmpreg; + + tmpreg = USBx->GCINT; + tmpreg &= USBx->GINTMASK; + + return tmpreg; +} + +/** + * @brief USB_ReadDevAllOutEpInterrupt: return the USB device OUT endpoints interrupt status + * @param USBx Selected device + * @retval DAL status + */ +uint32_t USB_ReadDevAllOutEpInterrupt(USB_OTG_GlobalTypeDef *USBx) +{ + uint32_t USBx_BASE = (uint32_t)USBx; + uint32_t tmpreg; + + tmpreg = USBx_DEVICE->DAEPINT; + tmpreg &= USBx_DEVICE->DAEPIMASK; + + return ((tmpreg & 0xffff0000U) >> 16); +} + +/** + * @brief USB_ReadDevAllInEpInterrupt: return the USB device IN endpoints interrupt status + * @param USBx Selected device + * @retval DAL status + */ +uint32_t USB_ReadDevAllInEpInterrupt(USB_OTG_GlobalTypeDef *USBx) +{ + uint32_t USBx_BASE = (uint32_t)USBx; + uint32_t tmpreg; + + tmpreg = USBx_DEVICE->DAEPINT; + tmpreg &= USBx_DEVICE->DAEPIMASK; + + return ((tmpreg & 0xFFFFU)); +} + +/** + * @brief Returns Device OUT EP Interrupt register + * @param USBx Selected device + * @param epnum endpoint number + * This parameter can be a value from 0 to 15 + * @retval Device OUT EP Interrupt register + */ +uint32_t USB_ReadDevOutEPInterrupt(USB_OTG_GlobalTypeDef *USBx, uint8_t epnum) +{ + uint32_t USBx_BASE = (uint32_t)USBx; + uint32_t tmpreg; + + tmpreg = USBx_OUTEP((uint32_t)epnum)->DOEPINT; + tmpreg &= USBx_DEVICE->DOUTIMASK; + + return tmpreg; +} + +/** + * @brief Returns Device IN EP Interrupt register + * @param USBx Selected device + * @param epnum endpoint number + * This parameter can be a value from 0 to 15 + * @retval Device IN EP Interrupt register + */ +uint32_t USB_ReadDevInEPInterrupt(USB_OTG_GlobalTypeDef *USBx, uint8_t epnum) +{ + uint32_t USBx_BASE = (uint32_t)USBx; + uint32_t tmpreg; + uint32_t msk; + uint32_t emp; + + msk = USBx_DEVICE->DINIMASK; + emp = USBx_DEVICE->DIEIMASK; + msk |= ((emp >> (epnum & EP_ADDR_MSK)) & 0x1U) << 7; + tmpreg = USBx_INEP((uint32_t)epnum)->DIEPINT & msk; + + return tmpreg; +} + +/** + * @brief USB_ClearInterrupts: clear a USB interrupt + * @param USBx Selected device + * @param interrupt flag + * @retval None + */ +void USB_ClearInterrupts(USB_OTG_GlobalTypeDef *USBx, uint32_t interrupt) +{ + USBx->GCINT |= interrupt; +} + +/** + * @brief Returns USB core mode + * @param USBx Selected device + * @retval return core mode : Host or Device + * This parameter can be one of these values: + * 0 : Host + * 1 : Device + */ +uint32_t USB_GetMode(USB_OTG_GlobalTypeDef *USBx) +{ + return ((USBx->GCINT) & 0x1U); +} + +/** + * @brief Activate EP0 for Setup transactions + * @param USBx Selected device + * @retval DAL status + */ +DAL_StatusTypeDef USB_ActivateSetup(USB_OTG_GlobalTypeDef *USBx) +{ + uint32_t USBx_BASE = (uint32_t)USBx; + + /* Set the MPS of the IN EP0 to 64 bytes */ + USBx_INEP(0U)->DIEPCTRL &= ~USB_OTG_DIEPCTRL_MAXPS; + + USBx_DEVICE->DCTRL |= USB_OTG_DCTRL_GINAKCLR; + + return DAL_OK; +} + +/** + * @brief Prepare the EP0 to start the first control setup + * @param USBx Selected device + * @param dma USB dma enabled or disabled + * This parameter can be one of these values: + * 0 : DMA feature not used + * 1 : DMA feature used + * @param psetup pointer to setup packet + * @retval DAL status + */ +DAL_StatusTypeDef USB_EP0_OutStart(USB_OTG_GlobalTypeDef *USBx, uint8_t dma, uint8_t *psetup) +{ + uint32_t USBx_BASE = (uint32_t)USBx; + uint32_t gSNPSiD = *(__IO uint32_t *)(&USBx->GCID + 0x1U); + + if (gSNPSiD > USB_OTG_CORE_ID_300A) + { + if ((USBx_OUTEP(0U)->DOEPCTRL & USB_OTG_DOEPCTRL_EPEN) == USB_OTG_DOEPCTRL_EPEN) + { + return DAL_OK; + } + } + + USBx_OUTEP(0U)->DOEPTRS = 0U; + USBx_OUTEP(0U)->DOEPTRS |= (USB_OTG_DOEPTRS_EPPCNT & (1U << 19)); + USBx_OUTEP(0U)->DOEPTRS |= (3U * 8U); + USBx_OUTEP(0U)->DOEPTRS |= USB_OTG_DOEPTRS_SPCNT; + + if (dma == 1U) + { + USBx_OUTEP(0U)->DOEPDMA = (uint32_t)psetup; + /* EP enable */ + USBx_OUTEP(0U)->DOEPCTRL |= USB_OTG_DOEPCTRL_EPEN | USB_OTG_DOEPCTRL_USBAEP; + } + + return DAL_OK; +} + +/** + * @brief Reset the USB Core (needed after USB clock settings change) + * @param USBx Selected device + * @retval DAL status + */ +static DAL_StatusTypeDef USB_CoreReset(USB_OTG_GlobalTypeDef *USBx) +{ + __IO uint32_t count = 0U; + + /* Wait for AHB master IDLE state. */ + do + { + count++; + + if (count > 200000U) + { + return DAL_TIMEOUT; + } + } while ((USBx->GRSTCTRL & USB_OTG_GRSTCTRL_AHBMIDL) == 0U); + + /* Core Soft Reset */ + count = 0U; + USBx->GRSTCTRL |= USB_OTG_GRSTCTRL_CSRST; + + do + { + count++; + + if (count > 200000U) + { + return DAL_TIMEOUT; + } + } while ((USBx->GRSTCTRL & USB_OTG_GRSTCTRL_CSRST) == USB_OTG_GRSTCTRL_CSRST); + + return DAL_OK; +} + +/** + * @brief USB_HostInit : Initializes the USB OTG controller registers + * for Host mode + * @param USBx Selected device + * @param cfg pointer to a USB_OTG_CfgTypeDef structure that contains + * the configuration information for the specified USBx peripheral. + * @retval DAL status + */ +DAL_StatusTypeDef USB_HostInit(USB_OTG_GlobalTypeDef *USBx, USB_OTG_CfgTypeDef cfg) +{ + DAL_StatusTypeDef ret = DAL_OK; + uint32_t USBx_BASE = (uint32_t)USBx; + uint32_t i; + + /* Restart the Phy Clock */ + USBx_PCGCCTL = 0U; + + /* + * Disable HW VBUS sensing. VBUS is internally considered to be always + * at VBUS-Valid level (5V). + */ + USBx->GGCCFG |= USB_OTG_GGCCFG_VBSDIS; + USBx->GGCCFG &= ~USB_OTG_GGCCFG_BDVBSEN; + USBx->GGCCFG &= ~USB_OTG_GGCCFG_ADVBSEN; + + if ((USBx->GCID & (0x1U << 8)) != 0U) + { + if (cfg.speed == USBH_FSLS_SPEED) + { + /* Force Device Enumeration to FS/LS mode only */ + USBx_HOST->HCFG |= USB_OTG_HCFG_FSSPT; + } + else + { + /* Set default Max speed support */ + USBx_HOST->HCFG &= ~(USB_OTG_HCFG_FSSPT); + } + } + else + { + /* Set default Max speed support */ + USBx_HOST->HCFG &= ~(USB_OTG_HCFG_FSSPT); + } + + /* Make sure the FIFOs are flushed. */ + if (USB_FlushTxFifo(USBx, 0x10U) != DAL_OK) /* all Tx FIFOs */ + { + ret = DAL_ERROR; + } + + if (USB_FlushRxFifo(USBx) != DAL_OK) + { + ret = DAL_ERROR; + } + + /* Clear all pending HC Interrupts */ + for (i = 0U; i < cfg.Host_channels; i++) + { + USBx_HC(i)->HCHINT = 0xFFFFFFFFU; + USBx_HC(i)->HCHIMASK = 0U; + } + + /* Disable all interrupts. */ + USBx->GINTMASK = 0U; + + /* Clear any pending interrupts */ + USBx->GCINT = 0xFFFFFFFFU; + +#if 0 + if ((USBx->GCID & (0x1U << 8)) != 0U) + { + /* set Rx FIFO size */ + USBx->GRXFIFO = 0x200U; + USBx->GTXFCFG = (uint32_t)(((0x100U << 16) & USB_OTG_NPTXFDEP) | 0x200U); + USBx->GHPTXFSIZE = (uint32_t)(((0xE0U << 16) & USB_OTG_GHPTXFSIZE_HPDTXFDEP) | 0x300U); + } + else + { + /* set Rx FIFO size */ + USBx->GRXFIFO = 0x80U; + USBx->GTXFCFG = (uint32_t)(((0x60U << 16) & USB_OTG_NPTXFDEP) | 0x80U); + USBx->GHPTXFSIZE = (uint32_t)(((0x40U << 16)& USB_OTG_GHPTXFSIZE_HPDTXFDEP) | 0xE0U); + } +#endif + + /* USBD_HS_SPEED || USBH_HS_SPEED */ + if (cfg.speed == USBD_HS_SPEED) + { + /* set Rx FIFO size */ + USBx->GRXFIFO = 0x200U; + USBx->GTXFCFG = (uint32_t)(((0x100U << 16) & USB_OTG_NPTXFDEP) | 0x200U); + USBx->GHPTXFSIZE = (uint32_t)(((0xE0U << 16) & USB_OTG_GHPTXFSIZE_HPDTXFDEP) | 0x300U); + } + else + { + /* set Rx FIFO size */ + USBx->GRXFIFO = 0x80U; + USBx->GTXFCFG = (uint32_t)(((0x60U << 16) & USB_OTG_NPTXFDEP) | 0x80U); + USBx->GHPTXFSIZE = (uint32_t)(((0x40U << 16)& USB_OTG_GHPTXFSIZE_HPDTXFDEP) | 0xE0U); + } + + /* Enable the common interrupts */ + if (cfg.dma_enable == 0U) + { + USBx->GINTMASK |= USB_OTG_GINTMASK_RXFNONEM; + } + + /* Enable interrupts matching to the Host mode ONLY */ + USBx->GINTMASK |= (USB_OTG_GINTMASK_HPORTM | USB_OTG_GINTMASK_HCHM | \ + USB_OTG_GINTMASK_SOFM | USB_OTG_GCINT_DEDIS | \ + USB_OTG_GINTMASK_IP_OUTTXM | USB_OTG_GINTMASK_RWAKEM); + + return ret; +} + +/** + * @brief USB_InitFSLSPClkSel : Initializes the FSLSPClkSel field of the + * HCFG register on the PHY type and set the right frame interval + * @param USBx Selected device + * @param freq clock frequency + * This parameter can be one of these values: + * HCFG_48_MHZ : Full Speed 48 MHz Clock + * HCFG_6_MHZ : Low Speed 6 MHz Clock + * @retval DAL status + */ +DAL_StatusTypeDef USB_InitFSLSPClkSel(USB_OTG_GlobalTypeDef *USBx, uint8_t freq) +{ + uint32_t USBx_BASE = (uint32_t)USBx; + + USBx_HOST->HCFG &= ~(USB_OTG_HCFG_PHYCLKSEL); + USBx_HOST->HCFG |= (uint32_t)freq & USB_OTG_HCFG_PHYCLKSEL; + + if (freq == HCFG_48_MHZ) + { + USBx_HOST->HFIVL = 48000U; + } + else if (freq == HCFG_6_MHZ) + { + USBx_HOST->HFIVL = 6000U; + } + else + { + /* ... */ + } + + return DAL_OK; +} + +/** + * @brief USB_OTG_ResetPort : Reset Host Port + * @param USBx Selected device + * @retval DAL status + * @note (1)The application must wait at least 10 ms + * before clearing the reset bit. + */ +DAL_StatusTypeDef USB_ResetPort(USB_OTG_GlobalTypeDef *USBx) +{ + uint32_t USBx_BASE = (uint32_t)USBx; + + __IO uint32_t hprt0 = 0U; + + hprt0 = USBx_HPRT0; + + hprt0 &= ~(USB_OTG_HPORTCSTS_PEN | USB_OTG_HPORTCSTS_PCINTFLG | + USB_OTG_HPORTCSTS_PENCHG | USB_OTG_HPORTCSTS_POVCCHG); + + USBx_HPRT0 = (USB_OTG_HPORTCSTS_PRST | hprt0); + DAL_Delay(100U); /* See Note #1 */ + USBx_HPRT0 = ((~USB_OTG_HPORTCSTS_PRST) & hprt0); + DAL_Delay(10U); + + return DAL_OK; +} + +/** + * @brief USB_DriveVbus : activate or de-activate vbus + * @param state VBUS state + * This parameter can be one of these values: + * 0 : Deactivate VBUS + * 1 : Activate VBUS + * @retval DAL status + */ +DAL_StatusTypeDef USB_DriveVbus(USB_OTG_GlobalTypeDef *USBx, uint8_t state) +{ + uint32_t USBx_BASE = (uint32_t)USBx; + __IO uint32_t hprt0 = 0U; + + hprt0 = USBx_HPRT0; + + hprt0 &= ~(USB_OTG_HPORTCSTS_PEN | USB_OTG_HPORTCSTS_PCINTFLG | + USB_OTG_HPORTCSTS_PENCHG | USB_OTG_HPORTCSTS_POVCCHG); + + if (((hprt0 & USB_OTG_HPORTCSTS_PP) == 0U) && (state == 1U)) + { + USBx_HPRT0 = (USB_OTG_HPORTCSTS_PP | hprt0); + } + if (((hprt0 & USB_OTG_HPORTCSTS_PP) == USB_OTG_HPORTCSTS_PP) && (state == 0U)) + { + USBx_HPRT0 = ((~USB_OTG_HPORTCSTS_PP) & hprt0); + } + return DAL_OK; +} + +/** + * @brief Return Host Core speed + * @param USBx Selected device + * @retval speed : Host speed + * This parameter can be one of these values: + * @arg HCD_SPEED_HIGH: High speed mode + * @arg HCD_SPEED_FULL: Full speed mode + * @arg HCD_SPEED_LOW: Low speed mode + */ +uint32_t USB_GetHostSpeed(USB_OTG_GlobalTypeDef *USBx) +{ + uint32_t USBx_BASE = (uint32_t)USBx; + __IO uint32_t hprt0 = 0U; + + hprt0 = USBx_HPRT0; + return ((hprt0 & USB_OTG_HPORTCSTS_PSPDSEL) >> 17); +} + +/** + * @brief Return Host Current Frame number + * @param USBx Selected device + * @retval current frame number + */ +uint32_t USB_GetCurrentFrame(USB_OTG_GlobalTypeDef *USBx) +{ + uint32_t USBx_BASE = (uint32_t)USBx; + + return (USBx_HOST->HFIFM & USB_OTG_HFIFM_FNUM); +} + +/** + * @brief Initialize a host channel + * @param USBx Selected device + * @param ch_num Channel number + * This parameter can be a value from 1 to 15 + * @param epnum Endpoint number + * This parameter can be a value from 1 to 15 + * @param dev_address Current device address + * This parameter can be a value from 0 to 255 + * @param speed Current device speed + * This parameter can be one of these values: + * @arg USB_OTG_SPEED_HIGH: High speed mode + * @arg USB_OTG_SPEED_FULL: Full speed mode + * @arg USB_OTG_SPEED_LOW: Low speed mode + * @param ep_type Endpoint Type + * This parameter can be one of these values: + * @arg EP_TYPE_CTRL: Control type + * @arg EP_TYPE_ISOC: Isochronous type + * @arg EP_TYPE_BULK: Bulk type + * @arg EP_TYPE_INTR: Interrupt type + * @param mps Max Packet Size + * This parameter can be a value from 0 to 32K + * @retval DAL state + */ +DAL_StatusTypeDef USB_HC_Init(USB_OTG_GlobalTypeDef *USBx, uint8_t ch_num, + uint8_t epnum, uint8_t dev_address, uint8_t speed, + uint8_t ep_type, uint16_t mps) +{ + DAL_StatusTypeDef ret = DAL_OK; + uint32_t USBx_BASE = (uint32_t)USBx; + uint32_t HCcharEpDir; + uint32_t HCcharLowSpeed; + uint32_t HostCoreSpeed; + + /* Clear old interrupt conditions for this host channel. */ + USBx_HC((uint32_t)ch_num)->HCHINT = 0xFFFFFFFFU; + + /* Enable channel interrupts required for this transfer. */ + switch (ep_type) + { + case EP_TYPE_CTRL: + case EP_TYPE_BULK: + USBx_HC((uint32_t)ch_num)->HCHIMASK = USB_OTG_HCHIMASK_TSFCMPNM | + USB_OTG_HCHIMASK_RXSTALLM | + USB_OTG_HCHIMASK_TERRM | + USB_OTG_HCHIMASK_DTOGM | + USB_OTG_HCHIMASK_AHBERRM | + USB_OTG_HCHIMASK_RXNAKM; + + if ((epnum & 0x80U) == 0x80U) + { + USBx_HC((uint32_t)ch_num)->HCHIMASK |= USB_OTG_HCHIMASK_BABBLEM; + } + else + { + if ((USBx->GCID & (0x1U << 8)) != 0U) + { + USBx_HC((uint32_t)ch_num)->HCHIMASK |= USB_OTG_HCHIMASK_RXNYETM | + USB_OTG_HCHIMASK_RXTXACKM; + } + } + break; + + case EP_TYPE_INTR: + USBx_HC((uint32_t)ch_num)->HCHIMASK = USB_OTG_HCHIMASK_TSFCMPNM | + USB_OTG_HCHIMASK_RXSTALLM | + USB_OTG_HCHIMASK_TERRM | + USB_OTG_HCHIMASK_DTOGM | + USB_OTG_HCHIMASK_RXNAKM | + USB_OTG_HCHIMASK_AHBERRM | + USB_OTG_HCHIMASK_FOVRM; + + if ((epnum & 0x80U) == 0x80U) + { + USBx_HC((uint32_t)ch_num)->HCHIMASK |= USB_OTG_HCHIMASK_BABBLEM; + } + + break; + + case EP_TYPE_ISOC: + USBx_HC((uint32_t)ch_num)->HCHIMASK = USB_OTG_HCHIMASK_TSFCMPNM | + USB_OTG_HCHIMASK_RXTXACKM | + USB_OTG_HCHIMASK_AHBERRM | + USB_OTG_HCHIMASK_FOVRM; + + if ((epnum & 0x80U) == 0x80U) + { + USBx_HC((uint32_t)ch_num)->HCHIMASK |= (USB_OTG_HCHIMASK_TERRM | USB_OTG_HCHIMASK_BABBLEM); + } + break; + + default: + ret = DAL_ERROR; + break; + } + + /* Enable host channel Halt interrupt */ + USBx_HC((uint32_t)ch_num)->HCHIMASK |= USB_OTG_HCHIMASK_TSFCMPANM; + + /* Enable the top level host channel interrupt. */ + USBx_HOST->HACHIMASK |= 1UL << (ch_num & 0xFU); + + /* Make sure host channel interrupts are enabled. */ + USBx->GINTMASK |= USB_OTG_GINTMASK_HCHM; + + /* Program the HCCHAR register */ + if ((epnum & 0x80U) == 0x80U) + { + HCcharEpDir = (0x1U << 15) & USB_OTG_HCH_EDPDRT; + } + else + { + HCcharEpDir = 0U; + } + + HostCoreSpeed = USB_GetHostSpeed(USBx); + + /* LS device plugged to HUB */ + if ((speed == HPRT0_PRTSPD_LOW_SPEED) && (HostCoreSpeed != HPRT0_PRTSPD_LOW_SPEED)) + { + HCcharLowSpeed = (0x1U << 17) & USB_OTG_HCH_LSDV; + } + else + { + HCcharLowSpeed = 0U; + } + + USBx_HC((uint32_t)ch_num)->HCH = (((uint32_t)dev_address << 22) & USB_OTG_HCH_DVADDR) | + ((((uint32_t)epnum & 0x7FU) << 11) & USB_OTG_HCH_EDPNUM) | + (((uint32_t)ep_type << 18) & USB_OTG_HCH_EDPTYP) | + ((uint32_t)mps & USB_OTG_HCH_MAXPSIZE) | HCcharEpDir | HCcharLowSpeed; + + if ((ep_type == EP_TYPE_INTR) || (ep_type == EP_TYPE_ISOC)) + { + USBx_HC((uint32_t)ch_num)->HCH |= USB_OTG_HCH_ODDF; + } + + return ret; +} + +/** + * @brief Start a transfer over a host channel + * @param USBx Selected device + * @param hc pointer to host channel structure + * @param dma USB dma enabled or disabled + * This parameter can be one of these values: + * 0 : DMA feature not used + * 1 : DMA feature used + * @retval DAL state + */ +DAL_StatusTypeDef USB_HC_StartXfer(USB_OTG_GlobalTypeDef *USBx, USB_OTG_HCTypeDef *hc, uint8_t dma) +{ + uint32_t USBx_BASE = (uint32_t)USBx; + uint32_t ch_num = (uint32_t)hc->ch_num; + __IO uint32_t tmpreg; + uint8_t is_oddframe; + uint16_t len_words; + uint16_t num_packets; + uint16_t max_hc_pkt_count = 256U; + + if (((USBx->GCID & (0x1U << 8)) != 0U) && (hc->speed == USBH_HS_SPEED)) + { + /* in DMA mode host Core automatically issues ping in case of NYET/NAK */ + if ((dma == 1U) && ((hc->ep_type == EP_TYPE_CTRL) || (hc->ep_type == EP_TYPE_BULK))) + { + USBx_HC((uint32_t)ch_num)->HCHIMASK &= ~(USB_OTG_HCHIMASK_RXNYETM | + USB_OTG_HCHIMASK_RXTXACKM | + USB_OTG_HCHIMASK_RXNAKM); + } + + if ((dma == 0U) && (hc->do_ping == 1U)) + { + (void)USB_DoPing(USBx, hc->ch_num); + return DAL_OK; + } + + } + + /* Compute the expected number of packets associated to the transfer */ + if (hc->xfer_len > 0U) + { + num_packets = (uint16_t)((hc->xfer_len + hc->max_packet - 1U) / hc->max_packet); + + if (num_packets > max_hc_pkt_count) + { + num_packets = max_hc_pkt_count; + hc->XferSize = (uint32_t)num_packets * hc->max_packet; + } + } + else + { + num_packets = 1U; + } + + /* + * For IN channel HCTSIZ.XferSize is expected to be an integer multiple of + * max_packet size. + */ + if (hc->ep_is_in != 0U) + { + hc->XferSize = (uint32_t)num_packets * hc->max_packet; + } + else + { + hc->XferSize = hc->xfer_len; + } + + /* Initialize the HCTSIZn register */ + USBx_HC(ch_num)->HCHTSIZE = (hc->XferSize & USB_OTG_HCHTSIZE_TSFSIZE) | + (((uint32_t)num_packets << 19) & USB_OTG_HCHTSIZE_PCKTCNT) | + (((uint32_t)hc->data_pid << 29) & USB_OTG_HCHTSIZE_DATAPID); + + if (dma != 0U) + { + /* xfer_buff MUST be 32-bits aligned */ + USBx_HC(ch_num)->HCHDMA = (uint32_t)hc->xfer_buff; + } + + is_oddframe = (((uint32_t)USBx_HOST->HFIFM & 0x01U) != 0U) ? 0U : 1U; + USBx_HC(ch_num)->HCH &= ~USB_OTG_HCH_ODDF; + USBx_HC(ch_num)->HCH |= (uint32_t)is_oddframe << 29; + + /* Set host channel enable */ + tmpreg = USBx_HC(ch_num)->HCH; + tmpreg &= ~USB_OTG_HCH_CHINT; + + /* make sure to set the correct ep direction */ + if (hc->ep_is_in != 0U) + { + tmpreg |= USB_OTG_HCH_EDPDRT; + } + else + { + tmpreg &= ~USB_OTG_HCH_EDPDRT; + } + tmpreg |= USB_OTG_HCH_CHEN; + USBx_HC(ch_num)->HCH = tmpreg; + + if (dma != 0U) /* dma mode */ + { + return DAL_OK; + } + + if ((hc->ep_is_in == 0U) && (hc->xfer_len > 0U)) + { + switch (hc->ep_type) + { + /* Non periodic transfer */ + case EP_TYPE_CTRL: + case EP_TYPE_BULK: + + len_words = (uint16_t)((hc->xfer_len + 3U) / 4U); + + /* check if there is enough space in FIFO space */ + if (len_words > (USBx->GNPTXFQSTS & 0xFFFFU)) + { + /* need to process data in nptxfempty interrupt */ + USBx->GINTMASK |= USB_OTG_GINTMASK_NPTXFEMM; + } + break; + + /* Periodic transfer */ + case EP_TYPE_INTR: + case EP_TYPE_ISOC: + len_words = (uint16_t)((hc->xfer_len + 3U) / 4U); + /* check if there is enough space in FIFO space */ + if (len_words > (USBx_HOST->HPTXSTS & 0xFFFFU)) /* split the transfer */ + { + /* need to process data in ptxfempty interrupt */ + USBx->GINTMASK |= USB_OTG_GINTMASK_PTXFEM; + } + break; + + default: + break; + } + + /* Write packet into the Tx FIFO. */ + (void)USB_WritePacket(USBx, hc->xfer_buff, hc->ch_num, (uint16_t)hc->xfer_len, 0); + } + + return DAL_OK; +} + +/** + * @brief Read all host channel interrupts status + * @param USBx Selected device + * @retval DAL state + */ +uint32_t USB_HC_ReadInterrupt(USB_OTG_GlobalTypeDef *USBx) +{ + uint32_t USBx_BASE = (uint32_t)USBx; + + return ((USBx_HOST->HACHINT) & 0xFFFFU); +} + +/** + * @brief Halt a host channel + * @param USBx Selected device + * @param hc_num Host Channel number + * This parameter can be a value from 1 to 15 + * @retval DAL state + */ +DAL_StatusTypeDef USB_HC_Halt(USB_OTG_GlobalTypeDef *USBx, uint8_t hc_num) +{ + uint32_t USBx_BASE = (uint32_t)USBx; + uint32_t hcnum = (uint32_t)hc_num; + __IO uint32_t count = 0U; + uint32_t HcEpType = (USBx_HC(hcnum)->HCH & USB_OTG_HCH_EDPTYP) >> 18; + uint32_t ChannelEna = (USBx_HC(hcnum)->HCH & USB_OTG_HCH_CHEN) >> 31; + + if (((USBx->GAHBCFG & USB_OTG_GAHBCFG_DMAEN) == USB_OTG_GAHBCFG_DMAEN) && + (ChannelEna == 0U)) + { + return DAL_OK; + } + + /* Check for space in the request queue to issue the halt. */ + if ((HcEpType == HCCHAR_CTRL) || (HcEpType == HCCHAR_BULK)) + { + USBx_HC(hcnum)->HCH |= USB_OTG_HCH_CHINT; + + if ((USBx->GAHBCFG & USB_OTG_GAHBCFG_DMAEN) == 0U) + { + if ((USBx->GNPTXFQSTS & (0xFFU << 16)) == 0U) + { + USBx_HC(hcnum)->HCH &= ~USB_OTG_HCH_CHEN; + USBx_HC(hcnum)->HCH |= USB_OTG_HCH_CHEN; + do + { + count++; + + if (count > 1000U) + { + break; + } + } while ((USBx_HC(hcnum)->HCH & USB_OTG_HCH_CHEN) == USB_OTG_HCH_CHEN); + } + else + { + USBx_HC(hcnum)->HCH |= USB_OTG_HCH_CHEN; + } + } + } + else + { + USBx_HC(hcnum)->HCH |= USB_OTG_HCH_CHINT; + + if ((USBx_HOST->HPTXSTS & (0xFFU << 16)) == 0U) + { + USBx_HC(hcnum)->HCH &= ~USB_OTG_HCH_CHEN; + USBx_HC(hcnum)->HCH |= USB_OTG_HCH_CHEN; + do + { + count++; + + if (count > 1000U) + { + break; + } + } while ((USBx_HC(hcnum)->HCH & USB_OTG_HCH_CHEN) == USB_OTG_HCH_CHEN); + } + else + { + USBx_HC(hcnum)->HCH |= USB_OTG_HCH_CHEN; + } + } + + return DAL_OK; +} + +/** + * @brief Initiate Do Ping protocol + * @param USBx Selected device + * @param hc_num Host Channel number + * This parameter can be a value from 1 to 15 + * @retval DAL state + */ +DAL_StatusTypeDef USB_DoPing(USB_OTG_GlobalTypeDef *USBx, uint8_t ch_num) +{ + uint32_t USBx_BASE = (uint32_t)USBx; + uint32_t chnum = (uint32_t)ch_num; + uint32_t num_packets = 1U; + uint32_t tmpreg; + + USBx_HC(chnum)->HCHTSIZE = ((num_packets << 19) & USB_OTG_HCHTSIZE_PCKTCNT) | + USB_OTG_HCHTSIZE_DO_PING; + + /* Set host channel enable */ + tmpreg = USBx_HC(chnum)->HCH; + tmpreg &= ~USB_OTG_HCH_CHINT; + tmpreg |= USB_OTG_HCH_CHEN; + USBx_HC(chnum)->HCH = tmpreg; + + return DAL_OK; +} + +/** + * @brief Stop Host Core + * @param USBx Selected device + * @retval DAL state + */ +DAL_StatusTypeDef USB_StopHost(USB_OTG_GlobalTypeDef *USBx) +{ + DAL_StatusTypeDef ret = DAL_OK; + uint32_t USBx_BASE = (uint32_t)USBx; + __IO uint32_t count = 0U; + uint32_t value; + uint32_t i; + + (void)USB_DisableGlobalInt(USBx); + + /* Flush USB FIFO */ + if (USB_FlushTxFifo(USBx, 0x10U) != DAL_OK) /* all Tx FIFOs */ + { + ret = DAL_ERROR; + } + + if (USB_FlushRxFifo(USBx) != DAL_OK) + { + ret = DAL_ERROR; + } + + /* Flush out any leftover queued requests. */ + for (i = 0U; i <= 15U; i++) + { + value = USBx_HC(i)->HCH; + value |= USB_OTG_HCH_CHINT; + value &= ~USB_OTG_HCH_CHEN; + value &= ~USB_OTG_HCH_EDPDRT; + USBx_HC(i)->HCH = value; + } + + /* Halt all channels to put them into a known state. */ + for (i = 0U; i <= 15U; i++) + { + value = USBx_HC(i)->HCH; + value |= USB_OTG_HCH_CHINT; + value |= USB_OTG_HCH_CHEN; + value &= ~USB_OTG_HCH_EDPDRT; + USBx_HC(i)->HCH = value; + + do + { + count++; + + if (count > 1000U) + { + break; + } + } while ((USBx_HC(i)->HCH & USB_OTG_HCH_CHEN) == USB_OTG_HCH_CHEN); + } + + /* Clear any pending Host interrupts */ + USBx_HOST->HACHINT = 0xFFFFFFFFU; + USBx->GCINT = 0xFFFFFFFFU; + + (void)USB_EnableGlobalInt(USBx); + + return ret; +} + +/** + * @brief USB_ActivateRemoteWakeup active remote wakeup signalling + * @param USBx Selected device + * @retval DAL status + */ +DAL_StatusTypeDef USB_ActivateRemoteWakeup(USB_OTG_GlobalTypeDef *USBx) +{ + uint32_t USBx_BASE = (uint32_t)USBx; + + if ((USBx_DEVICE->DSTS & USB_OTG_DSTS_SUSSTS) == USB_OTG_DSTS_SUSSTS) + { + /* active Remote wakeup signalling */ + USBx_DEVICE->DCTRL |= USB_OTG_DCTRL_RWKUPS; + } + + return DAL_OK; +} + +/** + * @brief USB_DeActivateRemoteWakeup de-active remote wakeup signalling + * @param USBx Selected device + * @retval DAL status + */ +DAL_StatusTypeDef USB_DeActivateRemoteWakeup(USB_OTG_GlobalTypeDef *USBx) +{ + uint32_t USBx_BASE = (uint32_t)USBx; + + /* active Remote wakeup signalling */ + USBx_DEVICE->DCTRL &= ~(USB_OTG_DCTRL_RWKUPS); + + return DAL_OK; +} +#endif /* defined (USB_OTG_FS) || defined (USB_OTG_HS) */ + + +/** + * @} + */ + +/** + * @} + */ +#endif /* defined (USB_OTG_FS) || defined (USB_OTG_HS) */ +#endif /* defined (DAL_PCD_MODULE_ENABLED) || defined (DAL_HCD_MODULE_ENABLED) */ + +/** + * @} + */ diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_ddl_utils.c b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_ddl_utils.c new file mode 100644 index 0000000000..24d35df70e --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_ddl_utils.c @@ -0,0 +1,766 @@ +/** + * + * @file apm32f4xx_ddl_utils.c + * @brief UTILS DDL module driver. + * + * @attention + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2017 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + * + */ +/* Includes ------------------------------------------------------------------*/ +#include "apm32f4xx_ddl_utils.h" +#include "apm32f4xx_ddl_rcm.h" +#include "apm32f4xx_ddl_system.h" +#include "apm32f4xx_ddl_pmu.h" +#ifdef USE_FULL_ASSERT +#include "apm32_assert.h" +#else +#define ASSERT_PARAM(_PARAM_) ((void)(_PARAM_)) +#endif /* USE_FULL_ASSERT */ + +/** @addtogroup APM32F4xx_DDL_Driver + * @{ + */ + +/** @addtogroup UTILS_DDL + * @{ + */ + +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/** @addtogroup UTILS_DDL_Private_Constants + * @{ + */ +#if defined(RCM_MAX_FREQUENCY_SCALE1) +#define UTILS_MAX_FREQUENCY_SCALE1 RCM_MAX_FREQUENCY /*!< Maximum frequency for system clock at power scale1, in Hz */ +#endif /*RCM_MAX_FREQUENCY_SCALE1 */ +#define UTILS_MAX_FREQUENCY_SCALE2 RCM_MAX_FREQUENCY_SCALE2 /*!< Maximum frequency for system clock at power scale2, in Hz */ +#if defined(RCM_MAX_FREQUENCY_SCALE3) +#define UTILS_MAX_FREQUENCY_SCALE3 RCM_MAX_FREQUENCY_SCALE3 /*!< Maximum frequency for system clock at power scale3, in Hz */ +#endif /* MAX_FREQUENCY_SCALE3 */ + +/* Defines used for PLL range */ +#define UTILS_PLLVCO_INPUT_MIN RCM_PLLVCO_INPUT_MIN /*!< Frequency min for PLLVCO input, in Hz */ +#define UTILS_PLLVCO_INPUT_MAX RCM_PLLVCO_INPUT_MAX /*!< Frequency max for PLLVCO input, in Hz */ +#define UTILS_PLLVCO_OUTPUT_MIN RCM_PLLVCO_OUTPUT_MIN /*!< Frequency min for PLLVCO output, in Hz */ +#define UTILS_PLLVCO_OUTPUT_MAX RCM_PLLVCO_OUTPUT_MAX /*!< Frequency max for PLLVCO output, in Hz */ + +/* Defines used for HSE range */ +#define UTILS_HSE_FREQUENCY_MIN 4000000U /*!< Frequency min for HSE frequency, in Hz */ +#define UTILS_HSE_FREQUENCY_MAX 26000000U /*!< Frequency max for HSE frequency, in Hz */ + +/* Defines used for FLASH latency according to HCLK Frequency */ +#if defined(FLASH_SCALE1_LATENCY1_FREQ) +#define UTILS_SCALE1_LATENCY1_FREQ FLASH_SCALE1_LATENCY1_FREQ /*!< HCLK frequency to set FLASH latency 1 in power scale 1 */ +#endif +#if defined(FLASH_SCALE1_LATENCY2_FREQ) +#define UTILS_SCALE1_LATENCY2_FREQ FLASH_SCALE1_LATENCY2_FREQ /*!< HCLK frequency to set FLASH latency 2 in power scale 1 */ +#endif +#if defined(FLASH_SCALE1_LATENCY3_FREQ) +#define UTILS_SCALE1_LATENCY3_FREQ FLASH_SCALE1_LATENCY3_FREQ /*!< HCLK frequency to set FLASH latency 3 in power scale 1 */ +#endif +#if defined(FLASH_SCALE1_LATENCY4_FREQ) +#define UTILS_SCALE1_LATENCY4_FREQ FLASH_SCALE1_LATENCY4_FREQ /*!< HCLK frequency to set FLASH latency 4 in power scale 1 */ +#endif +#if defined(FLASH_SCALE1_LATENCY5_FREQ) +#define UTILS_SCALE1_LATENCY5_FREQ FLASH_SCALE1_LATENCY5_FREQ /*!< HCLK frequency to set FLASH latency 5 in power scale 1 */ +#endif +#define UTILS_SCALE2_LATENCY1_FREQ FLASH_SCALE2_LATENCY1_FREQ /*!< HCLK frequency to set FLASH latency 1 in power scale 2 */ +#define UTILS_SCALE2_LATENCY2_FREQ FLASH_SCALE2_LATENCY2_FREQ /*!< HCLK frequency to set FLASH latency 2 in power scale 2 */ +#if defined(FLASH_SCALE2_LATENCY3_FREQ) +#define UTILS_SCALE2_LATENCY3_FREQ FLASH_SCALE2_LATENCY3_FREQ /*!< HCLK frequency to set FLASH latency 2 in power scale 2 */ +#endif +#if defined(FLASH_SCALE2_LATENCY4_FREQ) +#define UTILS_SCALE2_LATENCY4_FREQ FLASH_SCALE2_LATENCY4_FREQ /*!< HCLK frequency to set FLASH latency 4 in power scale 2 */ +#endif +#if defined(FLASH_SCALE2_LATENCY5_FREQ) +#define UTILS_SCALE2_LATENCY5_FREQ FLASH_SCALE2_LATENCY5_FREQ /*!< HCLK frequency to set FLASH latency 5 in power scale 2 */ +#endif +#if defined(FLASH_SCALE3_LATENCY1_FREQ) +#define UTILS_SCALE3_LATENCY1_FREQ FLASH_SCALE3_LATENCY1_FREQ /*!< HCLK frequency to set FLASH latency 1 in power scale 3 */ +#endif +#if defined(FLASH_SCALE3_LATENCY2_FREQ) +#define UTILS_SCALE3_LATENCY2_FREQ FLASH_SCALE3_LATENCY2_FREQ /*!< HCLK frequency to set FLASH latency 2 in power scale 3 */ +#endif +#if defined(FLASH_SCALE3_LATENCY3_FREQ) +#define UTILS_SCALE3_LATENCY3_FREQ FLASH_SCALE3_LATENCY3_FREQ /*!< HCLK frequency to set FLASH latency 3 in power scale 3 */ +#endif +#if defined(FLASH_SCALE3_LATENCY4_FREQ) +#define UTILS_SCALE3_LATENCY4_FREQ FLASH_SCALE3_LATENCY4_FREQ /*!< HCLK frequency to set FLASH latency 4 in power scale 3 */ +#endif +#if defined(FLASH_SCALE3_LATENCY5_FREQ) +#define UTILS_SCALE3_LATENCY5_FREQ FLASH_SCALE3_LATENCY5_FREQ /*!< HCLK frequency to set FLASH latency 5 in power scale 3 */ +#endif +/** + * @} + */ + +/* Private macros ------------------------------------------------------------*/ +/** @addtogroup UTILS_DDL_Private_Macros + * @{ + */ +#define IS_DDL_UTILS_SYSCLK_DIV(__VALUE__) (((__VALUE__) == DDL_RCM_SYSCLK_DIV_1) \ + || ((__VALUE__) == DDL_RCM_SYSCLK_DIV_2) \ + || ((__VALUE__) == DDL_RCM_SYSCLK_DIV_4) \ + || ((__VALUE__) == DDL_RCM_SYSCLK_DIV_8) \ + || ((__VALUE__) == DDL_RCM_SYSCLK_DIV_16) \ + || ((__VALUE__) == DDL_RCM_SYSCLK_DIV_64) \ + || ((__VALUE__) == DDL_RCM_SYSCLK_DIV_128) \ + || ((__VALUE__) == DDL_RCM_SYSCLK_DIV_256) \ + || ((__VALUE__) == DDL_RCM_SYSCLK_DIV_512)) + +#define IS_DDL_UTILS_APB1_DIV(__VALUE__) (((__VALUE__) == DDL_RCM_APB1_DIV_1) \ + || ((__VALUE__) == DDL_RCM_APB1_DIV_2) \ + || ((__VALUE__) == DDL_RCM_APB1_DIV_4) \ + || ((__VALUE__) == DDL_RCM_APB1_DIV_8) \ + || ((__VALUE__) == DDL_RCM_APB1_DIV_16)) + +#define IS_DDL_UTILS_APB2_DIV(__VALUE__) (((__VALUE__) == DDL_RCM_APB2_DIV_1) \ + || ((__VALUE__) == DDL_RCM_APB2_DIV_2) \ + || ((__VALUE__) == DDL_RCM_APB2_DIV_4) \ + || ((__VALUE__) == DDL_RCM_APB2_DIV_8) \ + || ((__VALUE__) == DDL_RCM_APB2_DIV_16)) + +#define IS_DDL_UTILS_PLLB_VALUE(__VALUE__) (((__VALUE__) == DDL_RCM_PLLB_DIV_2) \ + || ((__VALUE__) == DDL_RCM_PLLB_DIV_3) \ + || ((__VALUE__) == DDL_RCM_PLLB_DIV_4) \ + || ((__VALUE__) == DDL_RCM_PLLB_DIV_5) \ + || ((__VALUE__) == DDL_RCM_PLLB_DIV_6) \ + || ((__VALUE__) == DDL_RCM_PLLB_DIV_7) \ + || ((__VALUE__) == DDL_RCM_PLLB_DIV_8) \ + || ((__VALUE__) == DDL_RCM_PLLB_DIV_9) \ + || ((__VALUE__) == DDL_RCM_PLLB_DIV_10) \ + || ((__VALUE__) == DDL_RCM_PLLB_DIV_11) \ + || ((__VALUE__) == DDL_RCM_PLLB_DIV_12) \ + || ((__VALUE__) == DDL_RCM_PLLB_DIV_13) \ + || ((__VALUE__) == DDL_RCM_PLLB_DIV_14) \ + || ((__VALUE__) == DDL_RCM_PLLB_DIV_15) \ + || ((__VALUE__) == DDL_RCM_PLLB_DIV_16) \ + || ((__VALUE__) == DDL_RCM_PLLB_DIV_17) \ + || ((__VALUE__) == DDL_RCM_PLLB_DIV_18) \ + || ((__VALUE__) == DDL_RCM_PLLB_DIV_19) \ + || ((__VALUE__) == DDL_RCM_PLLB_DIV_20) \ + || ((__VALUE__) == DDL_RCM_PLLB_DIV_21) \ + || ((__VALUE__) == DDL_RCM_PLLB_DIV_22) \ + || ((__VALUE__) == DDL_RCM_PLLB_DIV_23) \ + || ((__VALUE__) == DDL_RCM_PLLB_DIV_24) \ + || ((__VALUE__) == DDL_RCM_PLLB_DIV_25) \ + || ((__VALUE__) == DDL_RCM_PLLB_DIV_26) \ + || ((__VALUE__) == DDL_RCM_PLLB_DIV_27) \ + || ((__VALUE__) == DDL_RCM_PLLB_DIV_28) \ + || ((__VALUE__) == DDL_RCM_PLLB_DIV_29) \ + || ((__VALUE__) == DDL_RCM_PLLB_DIV_30) \ + || ((__VALUE__) == DDL_RCM_PLLB_DIV_31) \ + || ((__VALUE__) == DDL_RCM_PLLB_DIV_32) \ + || ((__VALUE__) == DDL_RCM_PLLB_DIV_33) \ + || ((__VALUE__) == DDL_RCM_PLLB_DIV_34) \ + || ((__VALUE__) == DDL_RCM_PLLB_DIV_35) \ + || ((__VALUE__) == DDL_RCM_PLLB_DIV_36) \ + || ((__VALUE__) == DDL_RCM_PLLB_DIV_37) \ + || ((__VALUE__) == DDL_RCM_PLLB_DIV_38) \ + || ((__VALUE__) == DDL_RCM_PLLB_DIV_39) \ + || ((__VALUE__) == DDL_RCM_PLLB_DIV_40) \ + || ((__VALUE__) == DDL_RCM_PLLB_DIV_41) \ + || ((__VALUE__) == DDL_RCM_PLLB_DIV_42) \ + || ((__VALUE__) == DDL_RCM_PLLB_DIV_43) \ + || ((__VALUE__) == DDL_RCM_PLLB_DIV_44) \ + || ((__VALUE__) == DDL_RCM_PLLB_DIV_45) \ + || ((__VALUE__) == DDL_RCM_PLLB_DIV_46) \ + || ((__VALUE__) == DDL_RCM_PLLB_DIV_47) \ + || ((__VALUE__) == DDL_RCM_PLLB_DIV_48) \ + || ((__VALUE__) == DDL_RCM_PLLB_DIV_49) \ + || ((__VALUE__) == DDL_RCM_PLLB_DIV_50) \ + || ((__VALUE__) == DDL_RCM_PLLB_DIV_51) \ + || ((__VALUE__) == DDL_RCM_PLLB_DIV_52) \ + || ((__VALUE__) == DDL_RCM_PLLB_DIV_53) \ + || ((__VALUE__) == DDL_RCM_PLLB_DIV_54) \ + || ((__VALUE__) == DDL_RCM_PLLB_DIV_55) \ + || ((__VALUE__) == DDL_RCM_PLLB_DIV_56) \ + || ((__VALUE__) == DDL_RCM_PLLB_DIV_57) \ + || ((__VALUE__) == DDL_RCM_PLLB_DIV_58) \ + || ((__VALUE__) == DDL_RCM_PLLB_DIV_59) \ + || ((__VALUE__) == DDL_RCM_PLLB_DIV_60) \ + || ((__VALUE__) == DDL_RCM_PLLB_DIV_61) \ + || ((__VALUE__) == DDL_RCM_PLLB_DIV_62) \ + || ((__VALUE__) == DDL_RCM_PLLB_DIV_63)) + +#define IS_DDL_UTILS_PLL1A_VALUE(__VALUE__) ((RCM_PLL1A_MIN_VALUE <= (__VALUE__)) && ((__VALUE__) <= RCM_PLL1A_MAX_VALUE)) + +#define IS_DDL_UTILS_PLL1C_VALUE(__VALUE__) (((__VALUE__) == DDL_RCM_PLL1C_DIV_2) \ + || ((__VALUE__) == DDL_RCM_PLL1C_DIV_4) \ + || ((__VALUE__) == DDL_RCM_PLL1C_DIV_6) \ + || ((__VALUE__) == DDL_RCM_PLL1C_DIV_8)) + +#define IS_DDL_UTILS_PLLVCO_INPUT(__VALUE__) ((UTILS_PLLVCO_INPUT_MIN <= (__VALUE__)) && ((__VALUE__) <= UTILS_PLLVCO_INPUT_MAX)) + +#define IS_DDL_UTILS_PLLVCO_OUTPUT(__VALUE__) ((UTILS_PLLVCO_OUTPUT_MIN <= (__VALUE__)) && ((__VALUE__) <= UTILS_PLLVCO_OUTPUT_MAX)) + +#if !defined(RCM_MAX_FREQUENCY_SCALE1) +#define IS_DDL_UTILS_PLL_FREQUENCY(__VALUE__) ((DDL_PMU_GetRegulVoltageScaling() == DDL_PMU_REGU_VOLTAGE_SCALE2) ? ((__VALUE__) <= UTILS_MAX_FREQUENCY_SCALE2) : \ + ((__VALUE__) <= UTILS_MAX_FREQUENCY_SCALE3)) + +#elif defined(RCM_MAX_FREQUENCY_SCALE3) +#define IS_DDL_UTILS_PLL_FREQUENCY(__VALUE__) ((DDL_PMU_GetRegulVoltageScaling() == DDL_PMU_REGU_VOLTAGE_SCALE1) ? ((__VALUE__) <= UTILS_MAX_FREQUENCY_SCALE1) : \ + (DDL_PMU_GetRegulVoltageScaling() == DDL_PMU_REGU_VOLTAGE_SCALE2) ? ((__VALUE__) <= UTILS_MAX_FREQUENCY_SCALE2) : \ + ((__VALUE__) <= UTILS_MAX_FREQUENCY_SCALE3)) + +#else +#define IS_DDL_UTILS_PLL_FREQUENCY(__VALUE__) ((DDL_PMU_GetRegulVoltageScaling() == DDL_PMU_REGU_VOLTAGE_SCALE1) ? ((__VALUE__) <= UTILS_MAX_FREQUENCY_SCALE1) : \ + ((__VALUE__) <= UTILS_MAX_FREQUENCY_SCALE2)) + +#endif /* RCM_MAX_FREQUENCY_SCALE1*/ +#define IS_DDL_UTILS_HSE_BYPASS(__STATE__) (((__STATE__) == DDL_UTILS_HSEBYPASS_ON) \ + || ((__STATE__) == DDL_UTILS_HSEBYPASS_OFF)) + +#define IS_DDL_UTILS_HSE_FREQUENCY(__FREQUENCY__) (((__FREQUENCY__) >= UTILS_HSE_FREQUENCY_MIN) && ((__FREQUENCY__) <= UTILS_HSE_FREQUENCY_MAX)) +/** + * @} + */ +/* Private function prototypes -----------------------------------------------*/ +/** @defgroup UTILS_DDL_Private_Functions UTILS Private functions + * @{ + */ +static uint32_t UTILS_GetPLLOutputFrequency(uint32_t PLL_InputFrequency, + DDL_UTILS_PLLInitTypeDef *UTILS_PLLInitStruct); +static ErrorStatus UTILS_EnablePLLAndSwitchSystem(uint32_t SYSCLK_Frequency, DDL_UTILS_ClkInitTypeDef *UTILS_ClkInitStruct); +static ErrorStatus UTILS_PLL_IsBusy(void); +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup UTILS_DDL_Exported_Functions + * @{ + */ + +/** @addtogroup UTILS_DDL_EF_DELAY + * @{ + */ + +/** + * @brief This function configures the Cortex-M SysTick source to have 1ms time base. + * @note When a RTOS is used, it is recommended to avoid changing the Systick + * configuration by calling this function, for a delay use rather osDelay RTOS service. + * @param HCLKFrequency HCLK frequency in Hz + * @note HCLK frequency can be calculated thanks to RCM helper macro or function @ref DDL_RCM_GetSystemClocksFreq + * @retval None + */ +void DDL_Init1msTick(uint32_t HCLKFrequency) +{ + /* Use frequency provided in argument */ + DDL_InitTick(HCLKFrequency, 1000U); +} + +/** + * @brief This function provides accurate delay (in milliseconds) based + * on SysTick counter flag + * @note When a RTOS is used, it is recommended to avoid using blocking delay + * and use rather osDelay service. + * @note To respect 1ms timebase, user should call @ref DDL_Init1msTick function which + * will configure Systick to 1ms + * @param Delay specifies the delay time length, in milliseconds. + * @retval None + */ +void DDL_mDelay(uint32_t Delay) +{ + __IO uint32_t tmp = SysTick->CTRL; /* Clear the COUNTFLAG first */ + /* Add this code to indicate that local variable is not used */ + ((void)tmp); + + /* Add a period to guaranty minimum wait */ + if(Delay < DDL_MAX_DELAY) + { + Delay++; + } + + while (Delay) + { + if((SysTick->CTRL & SysTick_CTRL_COUNTFLAG_Msk) != 0U) + { + Delay--; + } + } +} + +/** + * @} + */ + +/** @addtogroup UTILS_EF_SYSTEM + * @brief System Configuration functions + * + @verbatim + =============================================================================== + ##### System Configuration functions ##### + =============================================================================== + [..] + System, AHB and APB buses clocks configuration + + (+) The maximum frequency of the SYSCLK, HCLK, PCLK1 and PCLK2 is 180000000 Hz. + @endverbatim + @internal + Depending on the device voltage range, the maximum frequency should be + adapted accordingly to the Refenece manual. + @endinternal + * @{ + */ + +/** + * @brief This function sets directly SystemCoreClock CMSIS variable. + * @note Variable can be calculated also through SystemCoreClockUpdate function. + * @param HCLKFrequency HCLK frequency in Hz (can be calculated thanks to RCM helper macro) + * @retval None + */ +void DDL_SetSystemCoreClock(uint32_t HCLKFrequency) +{ + /* HCLK clock frequency */ + SystemCoreClock = HCLKFrequency; +} + +/** + * @brief Update number of Flash wait states in line with new frequency and current + voltage range. + * @note This Function support ONLY devices with supply voltage (voltage range) between 2.7V and 3.6V + * @param HCLK_Frequency HCLK frequency + * @retval An ErrorStatus enumeration value: + * - SUCCESS: Latency has been modified + * - ERROR: Latency cannot be modified + */ +ErrorStatus DDL_SetFlashLatency(uint32_t HCLK_Frequency) +{ + uint32_t timeout; + uint32_t getlatency; + uint32_t latency = DDL_FLASH_LATENCY_0; /* default value 0WS */ + ErrorStatus status = SUCCESS; + + + /* Frequency cannot be equal to 0 */ + if(HCLK_Frequency == 0U) + { + status = ERROR; + } + else + { + if(DDL_PMU_GetRegulVoltageScaling() == DDL_PMU_REGU_VOLTAGE_SCALE1) + { +#if defined (UTILS_SCALE1_LATENCY5_FREQ) + if((HCLK_Frequency > UTILS_SCALE1_LATENCY5_FREQ)&&(latency == DDL_FLASH_LATENCY_0)) + { + latency = DDL_FLASH_LATENCY_5; + } +#endif /*UTILS_SCALE1_LATENCY5_FREQ */ +#if defined (UTILS_SCALE1_LATENCY4_FREQ) + if((HCLK_Frequency > UTILS_SCALE1_LATENCY4_FREQ)&&(latency == DDL_FLASH_LATENCY_0)) + { + latency = DDL_FLASH_LATENCY_4; + } +#endif /* UTILS_SCALE1_LATENCY4_FREQ */ +#if defined (UTILS_SCALE1_LATENCY3_FREQ) + if((HCLK_Frequency > UTILS_SCALE1_LATENCY3_FREQ)&&(latency == DDL_FLASH_LATENCY_0)) + { + latency = DDL_FLASH_LATENCY_3; + } +#endif /* UTILS_SCALE1_LATENCY3_FREQ */ +#if defined (UTILS_SCALE1_LATENCY2_FREQ) + if((HCLK_Frequency > UTILS_SCALE1_LATENCY2_FREQ)&&(latency == DDL_FLASH_LATENCY_0)) + { + latency = DDL_FLASH_LATENCY_2; + } + else + { + if((HCLK_Frequency > UTILS_SCALE1_LATENCY1_FREQ)&&(latency == DDL_FLASH_LATENCY_0)) + { + latency = DDL_FLASH_LATENCY_1; + } + } +#endif /* UTILS_SCALE1_LATENCY2_FREQ */ + } + if(DDL_PMU_GetRegulVoltageScaling() == DDL_PMU_REGU_VOLTAGE_SCALE2) + { +#if defined (UTILS_SCALE2_LATENCY5_FREQ) + if((HCLK_Frequency > UTILS_SCALE2_LATENCY5_FREQ)&&(latency == DDL_FLASH_LATENCY_0)) + { + latency = DDL_FLASH_LATENCY_5; + } +#endif /*UTILS_SCALE1_LATENCY5_FREQ */ +#if defined (UTILS_SCALE2_LATENCY4_FREQ) + if((HCLK_Frequency > UTILS_SCALE2_LATENCY4_FREQ)&&(latency == DDL_FLASH_LATENCY_0)) + { + latency = DDL_FLASH_LATENCY_4; + } +#endif /*UTILS_SCALE1_LATENCY4_FREQ */ +#if defined (UTILS_SCALE2_LATENCY3_FREQ) + if((HCLK_Frequency > UTILS_SCALE2_LATENCY3_FREQ)&&(latency == DDL_FLASH_LATENCY_0)) + { + latency = DDL_FLASH_LATENCY_3; + } +#endif /*UTILS_SCALE1_LATENCY3_FREQ */ + if((HCLK_Frequency > UTILS_SCALE2_LATENCY2_FREQ)&&(latency == DDL_FLASH_LATENCY_0)) + { + latency = DDL_FLASH_LATENCY_2; + } + else + { + if((HCLK_Frequency > UTILS_SCALE2_LATENCY1_FREQ)&&(latency == DDL_FLASH_LATENCY_0)) + { + latency = DDL_FLASH_LATENCY_1; + } + } + } +#if defined (DDL_PMU_REGU_VOLTAGE_SCALE3) + if(DDL_PMU_GetRegulVoltageScaling() == DDL_PMU_REGU_VOLTAGE_SCALE3) + { +#if defined (UTILS_SCALE3_LATENCY3_FREQ) + if((HCLK_Frequency > UTILS_SCALE3_LATENCY3_FREQ)&&(latency == DDL_FLASH_LATENCY_0)) + { + latency = DDL_FLASH_LATENCY_3; + } +#endif /*UTILS_SCALE1_LATENCY3_FREQ */ +#if defined (UTILS_SCALE3_LATENCY2_FREQ) + if((HCLK_Frequency > UTILS_SCALE3_LATENCY2_FREQ)&&(latency == DDL_FLASH_LATENCY_0)) + { + latency = DDL_FLASH_LATENCY_2; + } + else + { + if((HCLK_Frequency > UTILS_SCALE3_LATENCY1_FREQ)&&(latency == DDL_FLASH_LATENCY_0)) + { + latency = DDL_FLASH_LATENCY_1; + } + } + } +#endif /*UTILS_SCALE1_LATENCY2_FREQ */ +#endif /* DDL_PMU_REGU_VOLTAGE_SCALE3 */ + + DDL_FLASH_SetLatency(latency); + /* Check that the new number of wait states is taken into account to access the Flash + memory by reading the FLASH_ACCTRL register */ + timeout = 2; + do + { + /* Wait for Flash latency to be updated */ + getlatency = DDL_FLASH_GetLatency(); + timeout--; + } while ((getlatency != latency) && (timeout > 0)); + + if(getlatency != latency) + { + status = ERROR; + } + else + { + status = SUCCESS; + } + } + return status; +} + +/** + * @brief This function configures system clock at maximum frequency with HSI as clock source of the PLL + * @note The application need to ensure that PLL is disabled. + * @note Function is based on the following formula: + * - PLL output frequency = (((HSI frequency / PLLB) * PLL1A) / PLL1C) + * - PLLB: ensure that the VCO input frequency ranges from @ref RCM_PLLVCO_INPUT_MIN to @ref RCM_PLLVCO_INPUT_MAX (PLLVCO_input = HSI frequency / PLLB) + * - PLL1A: ensure that the VCO output frequency is between @ref RCM_PLLVCO_OUTPUT_MIN and @ref RCM_PLLVCO_OUTPUT_MAX (PLLVCO_output = PLLVCO_input * PLL1A) + * - PLL1C: ensure that max frequency at 180000000 Hz is reach (PLLVCO_output / PLL1C) + * @param UTILS_PLLInitStruct pointer to a @ref DDL_UTILS_PLLInitTypeDef structure that contains + * the configuration information for the PLL. + * @param UTILS_ClkInitStruct pointer to a @ref DDL_UTILS_ClkInitTypeDef structure that contains + * the configuration information for the BUS prescalers. + * @retval An ErrorStatus enumeration value: + * - SUCCESS: Max frequency configuration done + * - ERROR: Max frequency configuration not done + */ +ErrorStatus DDL_PLL_ConfigSystemClock_HSI(DDL_UTILS_PLLInitTypeDef *UTILS_PLLInitStruct, + DDL_UTILS_ClkInitTypeDef *UTILS_ClkInitStruct) +{ + ErrorStatus status = SUCCESS; + uint32_t pllfreq = 0U; + + /* Check if one of the PLL is enabled */ + if(UTILS_PLL_IsBusy() == SUCCESS) + { + /* Calculate the new PLL output frequency */ + pllfreq = UTILS_GetPLLOutputFrequency(HSI_VALUE, UTILS_PLLInitStruct); + + /* Enable HSI if not enabled */ + if(DDL_RCM_HSI_IsReady() != 1U) + { + DDL_RCM_HSI_Enable(); + while (DDL_RCM_HSI_IsReady() != 1U) + { + /* Wait for HSI ready */ + } + } + + /* Configure PLL */ + DDL_RCM_PLL_ConfigDomain_SYS(DDL_RCM_PLLSOURCE_HSI, UTILS_PLLInitStruct->PLLB, UTILS_PLLInitStruct->PLL1A, + UTILS_PLLInitStruct->PLL1C); + + /* Enable PLL and switch system clock to PLL */ + status = UTILS_EnablePLLAndSwitchSystem(pllfreq, UTILS_ClkInitStruct); + } + else + { + /* Current PLL configuration cannot be modified */ + status = ERROR; + } + + return status; +} + +/** + * @brief This function configures system clock with HSE as clock source of the PLL + * @note The application need to ensure that PLL is disabled. + * - PLL output frequency = (((HSI frequency / PLLB) * PLL1A) / PLL1C) + * - PLLB: ensure that the VCO input frequency ranges from @ref RCM_PLLVCO_INPUT_MIN to @ref RCM_PLLVCO_INPUT_MAX (PLLVCO_input = HSI frequency / PLLB) + * - PLL1A: ensure that the VCO output frequency is between @ref RCM_PLLVCO_OUTPUT_MIN and @ref RCM_PLLVCO_OUTPUT_MAX (PLLVCO_output = PLLVCO_input * PLL1A) + * - PLL1C: ensure that max frequency at 180000000 Hz is reach (PLLVCO_output / PLL1C) + * @param HSEFrequency Value between Min_Data = 4000000 and Max_Data = 26000000 + * @param HSEBypass This parameter can be one of the following values: + * @arg @ref DDL_UTILS_HSEBYPASS_ON + * @arg @ref DDL_UTILS_HSEBYPASS_OFF + * @param UTILS_PLLInitStruct pointer to a @ref DDL_UTILS_PLLInitTypeDef structure that contains + * the configuration information for the PLL. + * @param UTILS_ClkInitStruct pointer to a @ref DDL_UTILS_ClkInitTypeDef structure that contains + * the configuration information for the BUS prescalers. + * @retval An ErrorStatus enumeration value: + * - SUCCESS: Max frequency configuration done + * - ERROR: Max frequency configuration not done + */ +ErrorStatus DDL_PLL_ConfigSystemClock_HSE(uint32_t HSEFrequency, uint32_t HSEBypass, + DDL_UTILS_PLLInitTypeDef *UTILS_PLLInitStruct, DDL_UTILS_ClkInitTypeDef *UTILS_ClkInitStruct) +{ + ErrorStatus status = SUCCESS; + uint32_t pllfreq = 0U; + + /* Check the parameters */ + ASSERT_PARAM(IS_DDL_UTILS_HSE_FREQUENCY(HSEFrequency)); + ASSERT_PARAM(IS_DDL_UTILS_HSE_BYPASS(HSEBypass)); + + /* Check if one of the PLL is enabled */ + if(UTILS_PLL_IsBusy() == SUCCESS) + { + /* Calculate the new PLL output frequency */ + pllfreq = UTILS_GetPLLOutputFrequency(HSEFrequency, UTILS_PLLInitStruct); + + /* Enable HSE if not enabled */ + if(DDL_RCM_HSE_IsReady() != 1U) + { + /* Check if need to enable HSE bypass feature or not */ + if(HSEBypass == DDL_UTILS_HSEBYPASS_ON) + { + DDL_RCM_HSE_EnableBypass(); + } + else + { + DDL_RCM_HSE_DisableBypass(); + } + + /* Enable HSE */ + DDL_RCM_HSE_Enable(); + while (DDL_RCM_HSE_IsReady() != 1U) + { + /* Wait for HSE ready */ + } + } + + /* Configure PLL */ + DDL_RCM_PLL_ConfigDomain_SYS(DDL_RCM_PLLSOURCE_HSE, UTILS_PLLInitStruct->PLLB, UTILS_PLLInitStruct->PLL1A, + UTILS_PLLInitStruct->PLL1C); + + /* Enable PLL and switch system clock to PLL */ + status = UTILS_EnablePLLAndSwitchSystem(pllfreq, UTILS_ClkInitStruct); + } + else + { + /* Current PLL configuration cannot be modified */ + status = ERROR; + } + + return status; +} + +/** + * @} + */ + +/** + * @} + */ + +/** @addtogroup UTILS_DDL_Private_Functions + * @{ + */ +/** + * @brief Function to check that PLL can be modified + * @param PLL_InputFrequency PLL input frequency (in Hz) + * @param UTILS_PLLInitStruct pointer to a @ref DDL_UTILS_PLLInitTypeDef structure that contains + * the configuration information for the PLL. + * @retval PLL output frequency (in Hz) + */ +static uint32_t UTILS_GetPLLOutputFrequency(uint32_t PLL_InputFrequency, DDL_UTILS_PLLInitTypeDef *UTILS_PLLInitStruct) +{ + uint32_t pllfreq = 0U; + + /* Check the parameters */ + ASSERT_PARAM(IS_DDL_UTILS_PLLB_VALUE(UTILS_PLLInitStruct->PLLB)); + ASSERT_PARAM(IS_DDL_UTILS_PLL1A_VALUE(UTILS_PLLInitStruct->PLL1A)); + ASSERT_PARAM(IS_DDL_UTILS_PLL1C_VALUE(UTILS_PLLInitStruct->PLL1C)); + + /* Check different PLL parameters according to RM */ + /* - PLLB: ensure that the VCO input frequency ranges from @ref UTILS_PLLVCO_INPUT_MIN to @ref UTILS_PLLVCO_INPUT_MAX MHz. */ + pllfreq = PLL_InputFrequency / (UTILS_PLLInitStruct->PLLB & (RCM_PLL1CFG_PLLB >> RCM_PLL1CFG_PLLB_Pos)); + ASSERT_PARAM(IS_DDL_UTILS_PLLVCO_INPUT(pllfreq)); + + /* - PLL1A: ensure that the VCO output frequency is between @ref UTILS_PLLVCO_OUTPUT_MIN and @ref UTILS_PLLVCO_OUTPUT_MAX .*/ + pllfreq = pllfreq * (UTILS_PLLInitStruct->PLL1A & (RCM_PLL1CFG_PLL1A >> RCM_PLL1CFG_PLL1A_Pos)); + ASSERT_PARAM(IS_DDL_UTILS_PLLVCO_OUTPUT(pllfreq)); + + /* - PLL1C: ensure that max frequency at @ref RCM_MAX_FREQUENCY Hz is reached */ + pllfreq = pllfreq / (((UTILS_PLLInitStruct->PLL1C >> RCM_PLL1CFG_PLL1C_Pos) + 1) * 2); + ASSERT_PARAM(IS_DDL_UTILS_PLL_FREQUENCY(pllfreq)); + + return pllfreq; +} + +/** + * @brief Function to check that PLL can be modified + * @retval An ErrorStatus enumeration value: + * - SUCCESS: PLL modification can be done + * - ERROR: PLL is busy + */ +static ErrorStatus UTILS_PLL_IsBusy(void) +{ + ErrorStatus status = SUCCESS; + + /* Check if PLL is busy*/ + if(DDL_RCM_PLL_IsReady() != 0U) + { + /* PLL configuration cannot be modified */ + status = ERROR; + } + +#if defined(RCM_PLLI2S_SUPPORT) + /* Check if PLLI2S is busy*/ + if(DDL_RCM_PLLI2S_IsReady() != 0U) + { + /* PLLI2S configuration cannot be modified */ + status = ERROR; + } +#endif /*RCM_PLLI2S_SUPPORT*/ + return status; +} + +/** + * @brief Function to enable PLL and switch system clock to PLL + * @param SYSCLK_Frequency SYSCLK frequency + * @param UTILS_ClkInitStruct pointer to a @ref DDL_UTILS_ClkInitTypeDef structure that contains + * the configuration information for the BUS prescalers. + * @retval An ErrorStatus enumeration value: + * - SUCCESS: No problem to switch system to PLL + * - ERROR: Problem to switch system to PLL + */ +static ErrorStatus UTILS_EnablePLLAndSwitchSystem(uint32_t SYSCLK_Frequency, DDL_UTILS_ClkInitTypeDef *UTILS_ClkInitStruct) +{ + ErrorStatus status = SUCCESS; + uint32_t hclk_frequency = 0U; + + ASSERT_PARAM(IS_DDL_UTILS_SYSCLK_DIV(UTILS_ClkInitStruct->AHBCLKDivider)); + ASSERT_PARAM(IS_DDL_UTILS_APB1_DIV(UTILS_ClkInitStruct->APB1CLKDivider)); + ASSERT_PARAM(IS_DDL_UTILS_APB2_DIV(UTILS_ClkInitStruct->APB2CLKDivider)); + + /* Calculate HCLK frequency */ + hclk_frequency = __DDL_RCM_CALC_HCLK_FREQ(SYSCLK_Frequency, UTILS_ClkInitStruct->AHBCLKDivider); + + /* Increasing the number of wait states because of higher CPU frequency */ + if(SystemCoreClock < hclk_frequency) + { + /* Set FLASH latency to highest latency */ + status = DDL_SetFlashLatency(hclk_frequency); + } + + /* Update system clock configuration */ + if(status == SUCCESS) + { + /* Enable PLL */ + DDL_RCM_PLL_Enable(); + while (DDL_RCM_PLL_IsReady() != 1U) + { + /* Wait for PLL ready */ + } + + /* Sysclk activation on the main PLL */ + DDL_RCM_SetAHBPrescaler(UTILS_ClkInitStruct->AHBCLKDivider); + DDL_RCM_SetSysClkSource(DDL_RCM_SYS_CLKSOURCE_PLL); + while (DDL_RCM_GetSysClkSource() != DDL_RCM_SYS_CLKSOURCE_STATUS_PLL) + { + /* Wait for system clock switch to PLL */ + } + + /* Set APB1 & APB2 prescaler*/ + DDL_RCM_SetAPB1Prescaler(UTILS_ClkInitStruct->APB1CLKDivider); + DDL_RCM_SetAPB2Prescaler(UTILS_ClkInitStruct->APB2CLKDivider); + } + + /* Decreasing the number of wait states because of lower CPU frequency */ + if(SystemCoreClock > hclk_frequency) + { + /* Set FLASH latency to lowest latency */ + status = DDL_SetFlashLatency(hclk_frequency); + } + + /* Update SystemCoreClock variable */ + if(status == SUCCESS) + { + DDL_SetSystemCoreClock(hclk_frequency); + } + + return status; +} + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ diff --git a/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_device_cfg_template.c b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_device_cfg_template.c new file mode 100644 index 0000000000..951e42befc --- /dev/null +++ b/lib/main/APM32F4/Libraries/APM32F4xx_DAL_Driver/Source/apm32f4xx_device_cfg_template.c @@ -0,0 +1,188 @@ +/** + * @file apm32f4xx_device_cfg.c + * + * @brief This file provides all configuration support for device + * + * @version V1.0.0 + * + * @date 2023-07-31 + * + * @attention + * + * Copyright (C) 2023 Geehy Semiconductor + * + * You may not use this file except in compliance with the + * GEEHY COPYRIGHT NOTICE (GEEHY SOFTWARE PACKAGE LICENSE). + * + * The program is only for reference, which is distributed in the hope + * that it will be useful and instructional for customers to develop + * their software. Unless required by applicable law or agreed to in + * writing, the program is distributed on an "AS IS" BASIS, WITHOUT + * ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied. + * See the GEEHY SOFTWARE PACKAGE LICENSE for the governing permissions + * and limitations under the License. + */ + +/* Includes */ +#include "apm32f4xx_device_cfg.h" + +/** @addtogroup Config + @{ + */ + +/** @addtogroup Device_Config + @{ + */ + +/** @defgroup Device_Config_Functions + @{ +*/ + +/** + * @brief Device configuration + * + * @param None + * + * @retval None + */ +void DAL_DeviceConfig(void) +{ + /* Configure DAL library */ + DAL_Init(); + + /* Configure system clock */ + DAL_SysClkConfig(); + + /* Configure peripheral clock */ + DAL_RCM_PeripheralClkConfig(); + + /* Configure GPIO */ + DAL_GPIO_Config(); + + /* Configure DMA */ + DAL_DMA_Config(); + + /* Configure peripheral */ + + /* Configure NVIC */ + DAL_NVIC_Config(); +} + +/** + * @brief Device reset + * + * @param None + * + * @retval None + */ +void DAL_DeviceReset(void) +{ + /* Reset DAL library */ + DAL_DeInit(); + + /* Reset Peripheral */ + + /* Reset service */ +} + +/** + * @brief System clock configuration + * + * @param None + * + * @retval None + */ +void DAL_SysClkConfig(void) +{ + +} + +/** + * @brief Peripheral Clock configuration + * + * @param None + * + * @retval None + */ +void DAL_RCM_PeripheralClkConfig(void) +{ + /* Configure the Peripheral Clock */ +} + +/** + * @brief GPIO configuration + * + * @param None + * + * @retval None + */ +void DAL_GPIO_Config(void) +{ + /* Configure GPIO */ +} + +/** + * @brief DMA configuration + * + * @param None + * + * @retval None + */ +void DAL_DMA_Config(void) +{ + /* Configure DMA */ +} + +/** + * @brief NVIC configuration + * + * @param None + * + * @retval None + */ +void DAL_NVIC_Config(void) +{ + /* Configure NVIC */ +} + +/** + * @brief Error handler + * + * @param None + * + * @retval None + */ +void DAL_ErrorHandler(void) +{ + /* When the function is needed, this function + could be implemented in the user file + */ + while(1) + { + } +} + +/** + * @brief Assert failed handler + * + * @param file :Pointer to the source file name + * + * @param line :Error line source number + * + * @retval None + */ +void AssertFailedHandler(uint8_t *file, uint32_t line) +{ + /* When the function is needed, this function + could be implemented in the user file + */ + UNUSED(file); + UNUSED(line); + while(1) + { + } +} + +/**@} end of group Device_Config_Functions */ +/**@} end of group Device_Config */ +/**@} end of group Config */ diff --git a/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Include/apm32f405xx.h b/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Include/apm32f405xx.h new file mode 100644 index 0000000000..3a0ecbe674 --- /dev/null +++ b/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Include/apm32f405xx.h @@ -0,0 +1,14362 @@ +/** + * + * @file apm32f405xx.h + * + * @brief CMSIS APM32F405xx Device Peripheral Access Layer Header File. + * + * @version V1.0.0 + * + * @date 2023-07-31 + * + * @attention + * + * Licensed under the Apache License, Version 2.0 (the License); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * The original code has been modified by Geehy Semiconductor. + * + * Copyright (c) 2017 STMicroelectronics. + * Copyright (C) 2023 Geehy Semiconductor. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + */ + +/** @addtogroup CMSIS_Device + * @{ + */ + +/** @addtogroup apm32f405xx + * @{ + */ + +#ifndef __APM32F405xx_H +#define __APM32F405xx_H + +#ifdef __cplusplus + extern "C" { +#endif /* __cplusplus */ + +/** @addtogroup Configuration_section_for_CMSIS + * @{ + */ + +/** + * @brief Configuration of the Cortex-M4 Processor and Core Peripherals + */ +#define __CM4_REV 0x0001U /*!< Core revision r0p1 */ +#define __MPU_PRESENT 1U /*!< APM32F4XX provides an MPU */ +#define __NVIC_PRIO_BITS 4U /*!< APM32F4XX uses 4 Bits for the Priority Levels */ +#define __Vendor_SysTickConfig 0U /*!< Set to 1 if different SysTick Config is used */ +#define __FPU_PRESENT 1U /*!< FPU present */ + +/** + * @} + */ + +/** @addtogroup Peripheral_interrupt_number_definition + * @{ + */ + +/** + * @brief APM32F4XX Interrupt Number Definition, according to the selected device + * in @ref Library_configuration_section + */ +typedef enum +{ +/****** Cortex-M4 Processor Exceptions Numbers ****************************************************************/ + NonMaskableInt_IRQn = -14, /*!< 2 Non Maskable Interrupt */ + MemoryManagement_IRQn = -12, /*!< 4 Cortex-M4 Memory Management Interrupt */ + BusFault_IRQn = -11, /*!< 5 Cortex-M4 Bus Fault Interrupt */ + UsageFault_IRQn = -10, /*!< 6 Cortex-M4 Usage Fault Interrupt */ + SVCall_IRQn = -5, /*!< 11 Cortex-M4 SV Call Interrupt */ + DebugMonitor_IRQn = -4, /*!< 12 Cortex-M4 Debug Monitor Interrupt */ + PendSV_IRQn = -2, /*!< 14 Cortex-M4 Pend SV Interrupt */ + SysTick_IRQn = -1, /*!< 15 Cortex-M4 System Tick Interrupt */ +/****** APM32 specific Interrupt Numbers **********************************************************************/ + WWDT_IRQn = 0, /*!< Window WatchDog Interrupt */ + PVD_IRQn = 1, /*!< PVD through EINT Line detection Interrupt */ + TAMP_STAMP_IRQn = 2, /*!< Tamper and TimeStamp interrupts through the EINT line */ + RTC_WKUP_IRQn = 3, /*!< RTC Wakeup interrupt through the EINT line */ + FLASH_IRQn = 4, /*!< FLASH global Interrupt */ + RCM_IRQn = 5, /*!< RCM global Interrupt */ + EINT0_IRQn = 6, /*!< EINT Line0 Interrupt */ + EINT1_IRQn = 7, /*!< EINT Line1 Interrupt */ + EINT2_IRQn = 8, /*!< EINT Line2 Interrupt */ + EINT3_IRQn = 9, /*!< EINT Line3 Interrupt */ + EINT4_IRQn = 10, /*!< EINT Line4 Interrupt */ + DMA1_Stream0_IRQn = 11, /*!< DMA1 Stream 0 global Interrupt */ + DMA1_Stream1_IRQn = 12, /*!< DMA1 Stream 1 global Interrupt */ + DMA1_Stream2_IRQn = 13, /*!< DMA1 Stream 2 global Interrupt */ + DMA1_Stream3_IRQn = 14, /*!< DMA1 Stream 3 global Interrupt */ + DMA1_Stream4_IRQn = 15, /*!< DMA1 Stream 4 global Interrupt */ + DMA1_Stream5_IRQn = 16, /*!< DMA1 Stream 5 global Interrupt */ + DMA1_Stream6_IRQn = 17, /*!< DMA1 Stream 6 global Interrupt */ + ADC_IRQn = 18, /*!< ADC1, ADC2 and ADC3 global Interrupts */ + CAN1_TX_IRQn = 19, /*!< CAN1 TX Interrupt */ + CAN1_RX0_IRQn = 20, /*!< CAN1 RX0 Interrupt */ + CAN1_RX1_IRQn = 21, /*!< CAN1 RX1 Interrupt */ + CAN1_SCE_IRQn = 22, /*!< CAN1 SCE Interrupt */ + EINT9_5_IRQn = 23, /*!< External Line[9:5] Interrupts */ + TMR1_BRK_TMR9_IRQn = 24, /*!< TMR1 Break interrupt and TMR9 global interrupt */ + TMR1_UP_TMR10_IRQn = 25, /*!< TMR1 Update Interrupt and TMR10 global interrupt */ + TMR1_TRG_COM_TMR11_IRQn = 26, /*!< TMR1 Trigger and Commutation Interrupt and TMR11 global interrupt */ + TMR1_CC_IRQn = 27, /*!< TMR1 Capture Compare Interrupt */ + TMR2_IRQn = 28, /*!< TMR2 global Interrupt */ + TMR3_IRQn = 29, /*!< TMR3 global Interrupt */ + TMR4_IRQn = 30, /*!< TMR4 global Interrupt */ + I2C1_EV_IRQn = 31, /*!< I2C1 Event Interrupt */ + I2C1_ER_IRQn = 32, /*!< I2C1 Error Interrupt */ + I2C2_EV_IRQn = 33, /*!< I2C2 Event Interrupt */ + I2C2_ER_IRQn = 34, /*!< I2C2 Error Interrupt */ + SPI1_IRQn = 35, /*!< SPI1 global Interrupt */ + SPI2_IRQn = 36, /*!< SPI2 global Interrupt */ + USART1_IRQn = 37, /*!< USART1 global Interrupt */ + USART2_IRQn = 38, /*!< USART2 global Interrupt */ + USART3_IRQn = 39, /*!< USART3 global Interrupt */ + EINT15_10_IRQn = 40, /*!< External Line[15:10] Interrupts */ + RTC_Alarm_IRQn = 41, /*!< RTC Alarm (A and B) through EINT Line Interrupt */ + OTG_FS_WKUP_IRQn = 42, /*!< USB OTG FS Wakeup through EINT line interrupt */ + TMR8_BRK_TMR12_IRQn = 43, /*!< TMR8 Break Interrupt and TMR12 global interrupt */ + TMR8_UP_TMR13_IRQn = 44, /*!< TMR8 Update Interrupt and TMR13 global interrupt */ + TMR8_TRG_COM_TMR14_IRQn = 45, /*!< TMR8 Trigger and Commutation Interrupt and TMR14 global interrupt */ + TMR8_CC_IRQn = 46, /*!< TMR8 Capture Compare global interrupt */ + DMA1_Stream7_IRQn = 47, /*!< DMA1 Stream7 Interrupt */ + SMC_IRQn = 48, /*!< SMC global Interrupt */ + SDIO_IRQn = 49, /*!< SDIO global Interrupt */ + TMR5_IRQn = 50, /*!< TMR5 global Interrupt */ + SPI3_IRQn = 51, /*!< SPI3 global Interrupt */ + UART4_IRQn = 52, /*!< UART4 global Interrupt */ + UART5_IRQn = 53, /*!< UART5 global Interrupt */ + TMR6_DAC_IRQn = 54, /*!< TMR6 global and DAC1&2 underrun error interrupts */ + TMR7_IRQn = 55, /*!< TMR7 global interrupt */ + DMA2_Stream0_IRQn = 56, /*!< DMA2 Stream 0 global Interrupt */ + DMA2_Stream1_IRQn = 57, /*!< DMA2 Stream 1 global Interrupt */ + DMA2_Stream2_IRQn = 58, /*!< DMA2 Stream 2 global Interrupt */ + DMA2_Stream3_IRQn = 59, /*!< DMA2 Stream 3 global Interrupt */ + DMA2_Stream4_IRQn = 60, /*!< DMA2 Stream 4 global Interrupt */ + CAN2_TX_IRQn = 63, /*!< CAN2 TX Interrupt */ + CAN2_RX0_IRQn = 64, /*!< CAN2 RX0 Interrupt */ + CAN2_RX1_IRQn = 65, /*!< CAN2 RX1 Interrupt */ + CAN2_SCE_IRQn = 66, /*!< CAN2 SCE Interrupt */ + OTG_FS_IRQn = 67, /*!< USB OTG FS global Interrupt */ + DMA2_Stream5_IRQn = 68, /*!< DMA2 Stream 5 global interrupt */ + DMA2_Stream6_IRQn = 69, /*!< DMA2 Stream 6 global interrupt */ + DMA2_Stream7_IRQn = 70, /*!< DMA2 Stream 7 global interrupt */ + USART6_IRQn = 71, /*!< USART6 global interrupt */ + I2C3_EV_IRQn = 72, /*!< I2C3 event interrupt */ + I2C3_ER_IRQn = 73, /*!< I2C3 error interrupt */ + OTG_HS_EP1_OUT_IRQn = 74, /*!< USB OTG HS End Point 1 Out global interrupt */ + OTG_HS_EP1_IN_IRQn = 75, /*!< USB OTG HS End Point 1 In global interrupt */ + OTG_HS_WKUP_IRQn = 76, /*!< USB OTG HS Wakeup through EINT interrupt */ + OTG_HS_IRQn = 77, /*!< USB OTG HS global interrupt */ + RNG_IRQn = 80, /*!< RNG global Interrupt */ + FPU_IRQn = 81, /*!< FPU global interrupt */ + SM3_IRQn = 82, /*!< SM3 global interrupt */ + SM4_IRQn = 83, /*!< SM4 global interrupt */ + BN_IRQn = 84 /*!< BN global interrupt */ +} IRQn_Type; +/* Legacy define */ +#define HASH_RNG_IRQn RNG_IRQn + +/** + * @} + */ + +#include "core_cm4.h" /* Cortex-M4 processor and core peripherals */ +#include "system_apm32f4xx.h" +#include + +/** @addtogroup Peripheral_registers_structures + * @{ + */ + +/** + * @brief Analog to Digital Converter + */ + +typedef struct +{ + __IO uint32_t STS; /*!< ADC status register, Address offset: 0x00 */ + __IO uint32_t CTRL1; /*!< ADC control register 1, Address offset: 0x04 */ + __IO uint32_t CTRL2; /*!< ADC control register 2, Address offset: 0x08 */ + __IO uint32_t SMPTIM1; /*!< ADC sample time register 1, Address offset: 0x0C */ + __IO uint32_t SMPTIM2; /*!< ADC sample time register 2, Address offset: 0x10 */ + __IO uint32_t INJDOF1; /*!< ADC injected channel data offset register 1, Address offset: 0x14 */ + __IO uint32_t INJDOF2; /*!< ADC injected channel data offset register 2, Address offset: 0x18 */ + __IO uint32_t INJDOF3; /*!< ADC injected channel data offset register 3, Address offset: 0x1C */ + __IO uint32_t INJDOF4; /*!< ADC injected channel data offset register 4, Address offset: 0x20 */ + __IO uint32_t AWDHT; /*!< ADC watchdog higher threshold register, Address offset: 0x24 */ + __IO uint32_t AWDLT; /*!< ADC watchdog lower threshold register, Address offset: 0x28 */ + __IO uint32_t REGSEQ1; /*!< ADC regular sequence register 1, Address offset: 0x2C */ + __IO uint32_t REGSEQ2; /*!< ADC regular sequence register 2, Address offset: 0x30 */ + __IO uint32_t REGSEQ3; /*!< ADC regular sequence register 3, Address offset: 0x34 */ + __IO uint32_t INJSEQ; /*!< ADC injected sequence register, Address offset: 0x38 */ + __IO uint32_t INJDATA1; /*!< ADC injected data register 1, Address offset: 0x3C */ + __IO uint32_t INJDATA2; /*!< ADC injected data register 2, Address offset: 0x40 */ + __IO uint32_t INJDATA3; /*!< ADC injected data register 3, Address offset: 0x44 */ + __IO uint32_t INJDATA4; /*!< ADC injected data register 4, Address offset: 0x48 */ + __IO uint32_t REGDATA; /*!< ADC regular data register, Address offset: 0x4C */ +} ADC_TypeDef; + +typedef struct +{ + __IO uint32_t CSTS; /*!< ADC Common status register, Address offset: ADC1 base address + 0x300 */ + __IO uint32_t CCTRL; /*!< ADC common control register, Address offset: ADC1 base address + 0x304 */ + __IO uint32_t CDATA; /*!< ADC common regular data register for dual + AND triple modes, Address offset: ADC1 base address + 0x308 */ +} ADC_Common_TypeDef; + + +/** + * @brief Controller Area Network TxMailBox + */ + +typedef struct +{ + __IO uint32_t TXMID; /*!< CAN TX mailbox identifier register */ + __IO uint32_t TXDLEN; /*!< CAN mailbox data length control and time stamp register */ + __IO uint32_t TXMDL; /*!< CAN mailbox data low register */ + __IO uint32_t TXMDH; /*!< CAN mailbox data high register */ +} CAN_TxMailBox_TypeDef; + +/** + * @brief Controller Area Network FIFOMailBox + */ + +typedef struct +{ + __IO uint32_t RXMID; /*!< CAN receive FIFO mailbox identifier register */ + __IO uint32_t RXDLEN; /*!< CAN receive FIFO mailbox data length control and time stamp register */ + __IO uint32_t RXMDL; /*!< CAN receive FIFO mailbox data low register */ + __IO uint32_t RXMDH; /*!< CAN receive FIFO mailbox data high register */ +} CAN_FIFOMailBox_TypeDef; + +/** + * @brief Controller Area Network FilterRegister + */ + +typedef struct +{ + __IO uint32_t FBANK1; /*!< CAN Filter bank register 1 */ + __IO uint32_t FBANK2; /*!< CAN Filter bank register 1 */ +} CAN_FilterRegister_TypeDef; + +/** + * @brief Controller Area Network + */ + +typedef struct +{ + __IO uint32_t MCTRL; /*!< CAN master control register, Address offset: 0x00 */ + __IO uint32_t MSTS; /*!< CAN master status register, Address offset: 0x04 */ + __IO uint32_t TXSTS; /*!< CAN transmit status register, Address offset: 0x08 */ + __IO uint32_t RXF0; /*!< CAN receive FIFO 0 register, Address offset: 0x0C */ + __IO uint32_t RXF1; /*!< CAN receive FIFO 1 register, Address offset: 0x10 */ + __IO uint32_t INTEN; /*!< CAN interrupt enable register, Address offset: 0x14 */ + __IO uint32_t ERRSTS; /*!< CAN error status register, Address offset: 0x18 */ + __IO uint32_t BITTIM; /*!< CAN bit timing register, Address offset: 0x1C */ + uint32_t RESERVED0[88]; /*!< Reserved, 0x020 - 0x17F */ + CAN_TxMailBox_TypeDef sTxMailBox[3]; /*!< CAN Tx MailBox, Address offset: 0x180 - 0x1AC */ + CAN_FIFOMailBox_TypeDef sFIFOMailBox[2]; /*!< CAN FIFO MailBox, Address offset: 0x1B0 - 0x1CC */ + uint32_t RESERVED1[12]; /*!< Reserved, 0x1D0 - 0x1FF */ + __IO uint32_t FCTRL; /*!< CAN filter master register, Address offset: 0x200 */ + __IO uint32_t FMCFG; /*!< CAN filter mode register, Address offset: 0x204 */ + uint32_t RESERVED2; /*!< Reserved, 0x208 */ + __IO uint32_t FSCFG; /*!< CAN filter scale register, Address offset: 0x20C */ + uint32_t RESERVED3; /*!< Reserved, 0x210 */ + __IO uint32_t FFASS; /*!< CAN filter FIFO assignment register, Address offset: 0x214 */ + uint32_t RESERVED4; /*!< Reserved, 0x218 */ + __IO uint32_t FACT; /*!< CAN filter activation register, Address offset: 0x21C */ + uint32_t RESERVED5[8]; /*!< Reserved, 0x220-0x23F */ + CAN_FilterRegister_TypeDef sFilterRegister[28]; /*!< CAN Filter Register, Address offset: 0x240-0x31C */ +} CAN_TypeDef; + +/** + * @brief CRC calculation unit + */ + +typedef struct +{ + __IO uint32_t DATA; /*!< CRC Data register, Address offset: 0x00 */ + __IO uint8_t INDATA; /*!< CRC Independent data register, Address offset: 0x04 */ + uint8_t RESERVED0; /*!< Reserved, 0x05 */ + uint16_t RESERVED1; /*!< Reserved, 0x06 */ + __IO uint32_t CTRL; /*!< CRC Control register, Address offset: 0x08 */ +} CRC_TypeDef; + +/** + * @brief Digital to Analog Converter + */ + +typedef struct +{ + __IO uint32_t CTRL; /*!< DAC control register, Address offset: 0x00 */ + __IO uint32_t SWTRG; /*!< DAC software trigger register, Address offset: 0x04 */ + __IO uint32_t DH12R1; /*!< DAC channel1 12-bit right-aligned data holding register, Address offset: 0x08 */ + __IO uint32_t DH12L1; /*!< DAC channel1 12-bit left aligned data holding register, Address offset: 0x0C */ + __IO uint32_t DH8R1; /*!< DAC channel1 8-bit right aligned data holding register, Address offset: 0x10 */ + __IO uint32_t DH12R2; /*!< DAC channel2 12-bit right aligned data holding register, Address offset: 0x14 */ + __IO uint32_t DH12L2; /*!< DAC channel2 12-bit left aligned data holding register, Address offset: 0x18 */ + __IO uint32_t DH8R2; /*!< DAC channel2 8-bit right-aligned data holding register, Address offset: 0x1C */ + __IO uint32_t DH12RDUAL; /*!< Dual DAC 12-bit right-aligned data holding register, Address offset: 0x20 */ + __IO uint32_t DH12LDUAL; /*!< DUAL DAC 12-bit left aligned data holding register, Address offset: 0x24 */ + __IO uint32_t DH8RDUAL; /*!< DUAL DAC 8-bit right aligned data holding register, Address offset: 0x28 */ + __IO uint32_t DATAOCH1; /*!< DAC channel1 data output register, Address offset: 0x2C */ + __IO uint32_t DATAOCH2; /*!< DAC channel2 data output register, Address offset: 0x30 */ + __IO uint32_t STS; /*!< DAC status register, Address offset: 0x34 */ +} DAC_TypeDef; + +/** + * @brief Debug MCU + */ + +typedef struct +{ + __IO uint32_t IDCODE; /*!< MCU device ID code, Address offset: 0x00 */ + __IO uint32_t CFG; /*!< Debug MCU configuration register, Address offset: 0x04 */ + __IO uint32_t APB1F; /*!< Debug MCU APB1 freeze register, Address offset: 0x08 */ + __IO uint32_t APB2F; /*!< Debug MCU APB2 freeze register, Address offset: 0x0C */ +} DBGMCU_TypeDef; + + +/** + * @brief DMA Controller + */ + +typedef struct +{ + __IO uint32_t SCFG; /*!< DMA stream x configuration register */ + __IO uint32_t NDATA; /*!< DMA stream x number of data register */ + __IO uint32_t PADDR; /*!< DMA stream x peripheral address register */ + __IO uint32_t M0ADDR; /*!< DMA stream x memory 0 address register */ + __IO uint32_t M1ADDR; /*!< DMA stream x memory 1 address register */ + __IO uint32_t FCTRL; /*!< DMA stream x FIFO control register */ +} DMA_Stream_TypeDef; + +typedef struct +{ + __IO uint32_t LINTSTS; /*!< DMA low interrupt status register, Address offset: 0x00 */ + __IO uint32_t HINTSTS; /*!< DMA high interrupt status register, Address offset: 0x04 */ + __IO uint32_t LIFCLR; /*!< DMA low interrupt flag clear register, Address offset: 0x08 */ + __IO uint32_t HIFCLR; /*!< DMA high interrupt flag clear register, Address offset: 0x0C */ +} DMA_TypeDef; + +/** + * @brief External Interrupt/Event Controller + */ + +typedef struct +{ + __IO uint32_t IMASK; /*!< EINT Interrupt mask register, Address offset: 0x00 */ + __IO uint32_t EMASK; /*!< EINT Event mask register, Address offset: 0x04 */ + __IO uint32_t RTEN; /*!< EINT Rising trigger selection register, Address offset: 0x08 */ + __IO uint32_t FTEN; /*!< EINT Falling trigger selection register, Address offset: 0x0C */ + __IO uint32_t SWINTE; /*!< EINT Software interrupt event register, Address offset: 0x10 */ + __IO uint32_t IPEND; /*!< EINT Pending register, Address offset: 0x14 */ +} EINT_TypeDef; + +/** + * @brief FLASH Registers + */ + +typedef struct +{ + __IO uint32_t ACCTRL; /*!< FLASH access control register, Address offset: 0x00 */ + __IO uint32_t KEY; /*!< FLASH key register, Address offset: 0x04 */ + __IO uint32_t OPTKEY; /*!< FLASH option key register, Address offset: 0x08 */ + __IO uint32_t STS; /*!< FLASH status register, Address offset: 0x0C */ + __IO uint32_t CTRL; /*!< FLASH control register, Address offset: 0x10 */ + __IO uint32_t OPTCTRL; /*!< FLASH option control register , Address offset: 0x14 */ + __IO uint32_t OPTCTRL1; /*!< FLASH option control register 1, Address offset: 0x18 */ +} FLASH_TypeDef; + +/** + * @brief Flexible Static Memory Controller + */ + +typedef struct +{ + __IO uint32_t CSTR[8]; /*!< NOR/PSRAM chip-select control register(CSCTRL) and chip-select timing register(CSTIM), Address offset: 0x00-1C */ +} SMC_Bank1_TypeDef; + +/** + * @brief Flexible Static Memory Controller Bank1E + */ + +typedef struct +{ + __IO uint32_t WRTTIM[7]; /*!< NOR/PSRAM write timing registers, Address offset: 0x104-0x11C */ +} SMC_Bank1E_TypeDef; + +/** + * @brief Flexible Static Memory Controller Bank2 + */ + +typedef struct +{ + __IO uint32_t CTRL2; /*!< NAND Flash control register 2, Address offset: 0x60 */ + __IO uint32_t STSINT2; /*!< NAND Flash FIFO status and interrupt register 2, Address offset: 0x64 */ + __IO uint32_t CMSTIM2; /*!< NAND Flash Common memory space timing register 2, Address offset: 0x68 */ + __IO uint32_t AMSTIM2; /*!< NAND Flash Attribute memory space timing register 2, Address offset: 0x6C */ + uint32_t RESERVED0; /*!< Reserved, 0x70 */ + __IO uint32_t ECCRS2; /*!< NAND Flash ECC result registers 2, Address offset: 0x74 */ + uint32_t RESERVED1; /*!< Reserved, 0x78 */ + uint32_t RESERVED2; /*!< Reserved, 0x7C */ + __IO uint32_t CTRL3; /*!< NAND Flash control register 3, Address offset: 0x80 */ + __IO uint32_t STSINT3; /*!< NAND Flash FIFO status and interrupt register 3, Address offset: 0x84 */ + __IO uint32_t CMSTIM3; /*!< NAND Flash Common memory space timing register 3, Address offset: 0x88 */ + __IO uint32_t AMSTIM3; /*!< NAND Flash Attribute memory space timing register 3, Address offset: 0x8C */ + uint32_t RESERVED3; /*!< Reserved, 0x90 */ + __IO uint32_t ECCRS3; /*!< NAND Flash ECC result registers 3, Address offset: 0x94 */ +} SMC_Bank2_3_TypeDef; + +/** + * @brief Flexible Static Memory Controller Bank4 + */ + +typedef struct +{ + __IO uint32_t CTRL4; /*!< PC Card control register 4, Address offset: 0xA0 */ + __IO uint32_t STSINT4; /*!< PC Card FIFO status and interrupt register 4, Address offset: 0xA4 */ + __IO uint32_t CMSTIM4; /*!< PC Card Common memory space timing register 4, Address offset: 0xA8 */ + __IO uint32_t AMSTIM4; /*!< PC Card Attribute memory space timing register 4, Address offset: 0xAC */ + __IO uint32_t IOSTIM4; /*!< PC Card I/O space timing register 4, Address offset: 0xB0 */ +} SMC_Bank4_TypeDef; + +/** + * @brief General Purpose I/O + */ + +typedef struct +{ + __IO uint32_t MODE; /*!< GPIO port mode register, Address offset: 0x00 */ + __IO uint32_t OMODE; /*!< GPIO port output type register, Address offset: 0x04 */ + __IO uint32_t OSSEL; /*!< GPIO port output speed register, Address offset: 0x08 */ + __IO uint32_t PUPD; /*!< GPIO port pull-up/pull-down register, Address offset: 0x0C */ + __IO uint32_t IDATA; /*!< GPIO port input data register, Address offset: 0x10 */ + __IO uint32_t ODATA; /*!< GPIO port output data register, Address offset: 0x14 */ + __IO uint32_t BSC; /*!< GPIO port bit set/reset register, Address offset: 0x18 */ + __IO uint32_t LOCK; /*!< GPIO port configuration lock register, Address offset: 0x1C */ + __IO uint32_t ALF[2]; /*!< GPIO alternate function registers, Address offset: 0x20-0x24 */ +} GPIO_TypeDef; + +/** + * @brief System configuration controller + */ + +typedef struct +{ + __IO uint32_t MMSEL; /*!< SYSCFG memory remap register, Address offset: 0x00 */ + __IO uint32_t PMCFG; /*!< SYSCFG peripheral mode configuration register, Address offset: 0x04 */ + __IO uint32_t EINTCFG[4]; /*!< SYSCFG external interrupt configuration registers, Address offset: 0x08-0x14 */ + uint32_t RESERVED[2]; /*!< Reserved, 0x18-0x1C */ + __IO uint32_t CCCTRL; /*!< SYSCFG Compensation cell control register, Address offset: 0x20 */ +} SYSCFG_TypeDef; + +/** + * @brief Inter-integrated Circuit Interface + */ + +typedef struct +{ + __IO uint32_t CTRL1; /*!< I2C Control register 1, Address offset: 0x00 */ + __IO uint32_t CTRL2; /*!< I2C Control register 2, Address offset: 0x04 */ + __IO uint32_t SADDR1; /*!< I2C Own address register 1, Address offset: 0x08 */ + __IO uint32_t SADDR2; /*!< I2C Own address register 2, Address offset: 0x0C */ + __IO uint32_t DATA; /*!< I2C Data register, Address offset: 0x10 */ + __IO uint32_t STS1; /*!< I2C Status register 1, Address offset: 0x14 */ + __IO uint32_t STS2; /*!< I2C Status register 2, Address offset: 0x18 */ + __IO uint32_t CLKCTRL; /*!< I2C Clock control register, Address offset: 0x1C */ + __IO uint32_t RISETMAX; /*!< I2C RISETMAX register, Address offset: 0x20 */ +} I2C_TypeDef; + +/** + * @brief Independent WATCHDOG + */ + +typedef struct +{ + __IO uint32_t KEY; /*!< IWDT Key register, Address offset: 0x00 */ + __IO uint32_t PSC; /*!< IWDT Prescaler register, Address offset: 0x04 */ + __IO uint32_t CNTRLD; /*!< IWDT Reload register, Address offset: 0x08 */ + __IO uint32_t STS; /*!< IWDT Status register, Address offset: 0x0C */ +} IWDT_TypeDef; + + +/** + * @brief Power Control + */ + +typedef struct +{ + __IO uint32_t CTRL; /*!< PMU power control register, Address offset: 0x00 */ + __IO uint32_t CSTS; /*!< PMU power control/status register, Address offset: 0x04 */ +} PMU_TypeDef; + +/** + * @brief Reset and Clock Control + */ + +typedef struct +{ + __IO uint32_t CTRL; /*!< RCM clock control register, Address offset: 0x00 */ + __IO uint32_t PLL1CFG; /*!< RCM PLL configuration register, Address offset: 0x04 */ + __IO uint32_t CFG; /*!< RCM clock configuration register, Address offset: 0x08 */ + __IO uint32_t INT; /*!< RCM clock interrupt register, Address offset: 0x0C */ + __IO uint32_t AHB1RST; /*!< RCM AHB1 peripheral reset register, Address offset: 0x10 */ + __IO uint32_t AHB2RST; /*!< RCM AHB2 peripheral reset register, Address offset: 0x14 */ + __IO uint32_t AHB3RST; /*!< RCM AHB3 peripheral reset register, Address offset: 0x18 */ + uint32_t RESERVED0; /*!< Reserved, 0x1C */ + __IO uint32_t APB1RST; /*!< RCM APB1 peripheral reset register, Address offset: 0x20 */ + __IO uint32_t APB2RST; /*!< RCM APB2 peripheral reset register, Address offset: 0x24 */ + uint32_t RESERVED1[2]; /*!< Reserved, 0x28-0x2C */ + __IO uint32_t AHB1CLKEN; /*!< RCM AHB1 peripheral clock register, Address offset: 0x30 */ + __IO uint32_t AHB2CLKEN; /*!< RCM AHB2 peripheral clock register, Address offset: 0x34 */ + __IO uint32_t AHB3CLKEN; /*!< RCM AHB3 peripheral clock register, Address offset: 0x38 */ + uint32_t RESERVED2; /*!< Reserved, 0x3C */ + __IO uint32_t APB1CLKEN; /*!< RCM APB1 peripheral clock enable register, Address offset: 0x40 */ + __IO uint32_t APB2CLKEN; /*!< RCM APB2 peripheral clock enable register, Address offset: 0x44 */ + uint32_t RESERVED3[2]; /*!< Reserved, 0x48-0x4C */ + __IO uint32_t LPAHB1CLKEN; /*!< RCM AHB1 peripheral clock enable in low power mode register, Address offset: 0x50 */ + __IO uint32_t LPAHB2CLKEN; /*!< RCM AHB2 peripheral clock enable in low power mode register, Address offset: 0x54 */ + __IO uint32_t LPAHB3CLKEN; /*!< RCM AHB3 peripheral clock enable in low power mode register, Address offset: 0x58 */ + uint32_t RESERVED4; /*!< Reserved, 0x5C */ + __IO uint32_t LPAPB1CLKEN; /*!< RCM APB1 peripheral clock enable in low power mode register, Address offset: 0x60 */ + __IO uint32_t LPAPB2CLKEN; /*!< RCM APB2 peripheral clock enable in low power mode register, Address offset: 0x64 */ + uint32_t RESERVED5[2]; /*!< Reserved, 0x68-0x6C */ + __IO uint32_t BDCTRL; /*!< RCM Backup domain control register, Address offset: 0x70 */ + __IO uint32_t CSTS; /*!< RCM clock control & status register, Address offset: 0x74 */ + uint32_t RESERVED6[2]; /*!< Reserved, 0x78-0x7C */ + __IO uint32_t SSCCFG; /*!< RCM spread spectrum clock generation register, Address offset: 0x80 */ + __IO uint32_t PLL2CFG; /*!< RCM PLLI2S configuration register, Address offset: 0x84 */ +} RCM_TypeDef; + +/** + * @brief Real-Time Clock + */ + +typedef struct +{ + __IO uint32_t TIME; /*!< RTC time register, Address offset: 0x00 */ + __IO uint32_t DATE; /*!< RTC date register, Address offset: 0x04 */ + __IO uint32_t CTRL; /*!< RTC control register, Address offset: 0x08 */ + __IO uint32_t STS; /*!< RTC initialization and status register, Address offset: 0x0C */ + __IO uint32_t PSC; /*!< RTC prescaler register, Address offset: 0x10 */ + __IO uint32_t AUTORLD; /*!< RTC wakeup timer register, Address offset: 0x14 */ + __IO uint32_t DCAL; /*!< RTC calibration register, Address offset: 0x18 */ + __IO uint32_t ALRMA; /*!< RTC alarm A register, Address offset: 0x1C */ + __IO uint32_t ALRMB; /*!< RTC alarm B register, Address offset: 0x20 */ + __IO uint32_t WRPROT; /*!< RTC write protection register, Address offset: 0x24 */ + __IO uint32_t SUBSEC; /*!< RTC sub second register, Address offset: 0x28 */ + __IO uint32_t SHIFT; /*!< RTC shift control register, Address offset: 0x2C */ + __IO uint32_t TSTIME; /*!< RTC time stamp time register, Address offset: 0x30 */ + __IO uint32_t TSDATE; /*!< RTC time stamp date register, Address offset: 0x34 */ + __IO uint32_t TSSUBSEC; /*!< RTC time-stamp sub second register, Address offset: 0x38 */ + __IO uint32_t CAL; /*!< RTC calibration register, Address offset: 0x3C */ + __IO uint32_t TACFG; /*!< RTC tamper and alternate function configuration register, Address offset: 0x40 */ + __IO uint32_t ALRMASS; /*!< RTC alarm A sub second register, Address offset: 0x44 */ + __IO uint32_t ALRMBSS; /*!< RTC alarm B sub second register, Address offset: 0x48 */ + uint32_t RESERVED7; /*!< Reserved, 0x4C */ + __IO uint32_t BAKP0; /*!< RTC backup register 1, Address offset: 0x50 */ + __IO uint32_t BAKP1; /*!< RTC backup register 1, Address offset: 0x54 */ + __IO uint32_t BAKP2; /*!< RTC backup register 2, Address offset: 0x58 */ + __IO uint32_t BAKP3; /*!< RTC backup register 3, Address offset: 0x5C */ + __IO uint32_t BAKP4; /*!< RTC backup register 4, Address offset: 0x60 */ + __IO uint32_t BAKP5; /*!< RTC backup register 5, Address offset: 0x64 */ + __IO uint32_t BAKP6; /*!< RTC backup register 6, Address offset: 0x68 */ + __IO uint32_t BAKP7; /*!< RTC backup register 7, Address offset: 0x6C */ + __IO uint32_t BAKP8; /*!< RTC backup register 8, Address offset: 0x70 */ + __IO uint32_t BAKP9; /*!< RTC backup register 9, Address offset: 0x74 */ + __IO uint32_t BAKP10; /*!< RTC backup register 10, Address offset: 0x78 */ + __IO uint32_t BAKP11; /*!< RTC backup register 11, Address offset: 0x7C */ + __IO uint32_t BAKP12; /*!< RTC backup register 12, Address offset: 0x80 */ + __IO uint32_t BAKP13; /*!< RTC backup register 13, Address offset: 0x84 */ + __IO uint32_t BAKP14; /*!< RTC backup register 14, Address offset: 0x88 */ + __IO uint32_t BAKP15; /*!< RTC backup register 15, Address offset: 0x8C */ + __IO uint32_t BAKP16; /*!< RTC backup register 16, Address offset: 0x90 */ + __IO uint32_t BAKP17; /*!< RTC backup register 17, Address offset: 0x94 */ + __IO uint32_t BAKP18; /*!< RTC backup register 18, Address offset: 0x98 */ + __IO uint32_t BAKP19; /*!< RTC backup register 19, Address offset: 0x9C */ +} RTC_TypeDef; + +/** + * @brief SD host Interface + */ + +typedef struct +{ + __IO uint32_t PWRCTRL; /*!< SDIO power control register, Address offset: 0x00 */ + __IO uint32_t CLKCTRL; /*!< SDI clock control register, Address offset: 0x04 */ + __IO uint32_t ARG; /*!< SDIO argument register, Address offset: 0x08 */ + __IO uint32_t CMD; /*!< SDIO command register, Address offset: 0x0C */ + __IO const uint32_t CMDRES; /*!< SDIO command response register, Address offset: 0x10 */ + __IO const uint32_t RES1; /*!< SDIO response 1 register, Address offset: 0x14 */ + __IO const uint32_t RES2; /*!< SDIO response 2 register, Address offset: 0x18 */ + __IO const uint32_t RES3; /*!< SDIO response 3 register, Address offset: 0x1C */ + __IO const uint32_t RES4; /*!< SDIO response 4 register, Address offset: 0x20 */ + __IO uint32_t DATATIME; /*!< SDIO data timer register, Address offset: 0x24 */ + __IO uint32_t DATALEN; /*!< SDIO data length register, Address offset: 0x28 */ + __IO uint32_t DCTRL; /*!< SDIO data control register, Address offset: 0x2C */ + __IO const uint32_t DCNT; /*!< SDIO data counter register, Address offset: 0x30 */ + __IO const uint32_t STS; /*!< SDIO status register, Address offset: 0x34 */ + __IO uint32_t ICF; /*!< SDIO interrupt clear register, Address offset: 0x38 */ + __IO uint32_t MASK; /*!< SDIO mask register, Address offset: 0x3C */ + uint32_t RESERVED0[2]; /*!< Reserved, 0x40-0x44 */ + __IO const uint32_t FIFOCNT; /*!< SDIO FIFO counter register, Address offset: 0x48 */ + uint32_t RESERVED1[13]; /*!< Reserved, 0x4C-0x7C */ + __IO uint32_t FIFODATA; /*!< SDIO data FIFO register, Address offset: 0x80 */ +} SDIO_TypeDef; + +/** + * @brief Serial Peripheral Interface + */ + +typedef struct +{ + __IO uint32_t CTRL1; /*!< SPI control register 1 (not used in I2S mode), Address offset: 0x00 */ + __IO uint32_t CTRL2; /*!< SPI control register 2, Address offset: 0x04 */ + __IO uint32_t STS; /*!< SPI status register, Address offset: 0x08 */ + __IO uint32_t DATA; /*!< SPI data register, Address offset: 0x0C */ + __IO uint32_t CRCPOLY; /*!< SPI CRC polynomial register (not used in I2S mode), Address offset: 0x10 */ + __IO uint32_t RXCRC; /*!< SPI RX CRC register (not used in I2S mode), Address offset: 0x14 */ + __IO uint32_t TXCRC; /*!< SPI TX CRC register (not used in I2S mode), Address offset: 0x18 */ + __IO uint32_t I2SCFG; /*!< SPI_I2S configuration register, Address offset: 0x1C */ + __IO uint32_t I2SPSC; /*!< SPI_I2S prescaler register, Address offset: 0x20 */ +} SPI_TypeDef; + + +/** + * @brief TMR + */ + +typedef struct +{ + __IO uint32_t CTRL1; /*!< TMR control register 1, Address offset: 0x00 */ + __IO uint32_t CTRL2; /*!< TMR control register 2, Address offset: 0x04 */ + __IO uint32_t SMCTRL; /*!< TMR slave mode control register, Address offset: 0x08 */ + __IO uint32_t DIEN; /*!< TMR DMA/interrupt enable register, Address offset: 0x0C */ + __IO uint32_t STS; /*!< TMR status register, Address offset: 0x10 */ + __IO uint32_t CEG; /*!< TMR event generation register, Address offset: 0x14 */ + __IO uint32_t CCM1; /*!< TMR capture/compare mode register 1, Address offset: 0x18 */ + __IO uint32_t CCM2; /*!< TMR capture/compare mode register 2, Address offset: 0x1C */ + __IO uint32_t CCEN; /*!< TMR capture/compare enable register, Address offset: 0x20 */ + __IO uint32_t CNT; /*!< TMR counter register, Address offset: 0x24 */ + __IO uint32_t PSC; /*!< TMR prescaler, Address offset: 0x28 */ + __IO uint32_t AUTORLD; /*!< TMR auto-reload register, Address offset: 0x2C */ + __IO uint32_t REPCNT; /*!< TMR repetition counter register, Address offset: 0x30 */ + __IO uint32_t CC1; /*!< TMR capture/compare register 1, Address offset: 0x34 */ + __IO uint32_t CC2; /*!< TMR capture/compare register 2, Address offset: 0x38 */ + __IO uint32_t CC3; /*!< TMR capture/compare register 3, Address offset: 0x3C */ + __IO uint32_t CC4; /*!< TMR capture/compare register 4, Address offset: 0x40 */ + __IO uint32_t BDT; /*!< TMR break and dead-time register, Address offset: 0x44 */ + __IO uint32_t DCTRL; /*!< TMR DMA control register, Address offset: 0x48 */ + __IO uint32_t DMAR; /*!< TMR DMA address for full transfer, Address offset: 0x4C */ + __IO uint32_t OR; /*!< TMR option register, Address offset: 0x50 */ +} TMR_TypeDef; + +/** + * @brief Universal Synchronous Asynchronous Receiver Transmitter + */ + +typedef struct +{ + __IO uint32_t STS; /*!< USART Status register, Address offset: 0x00 */ + __IO uint32_t DATA; /*!< USART Data register, Address offset: 0x04 */ + __IO uint32_t BR; /*!< USART Baud rate register, Address offset: 0x08 */ + __IO uint32_t CTRL1; /*!< USART Control register 1, Address offset: 0x0C */ + __IO uint32_t CTRL2; /*!< USART Control register 2, Address offset: 0x10 */ + __IO uint32_t CTRL3; /*!< USART Control register 3, Address offset: 0x14 */ + __IO uint32_t GTPSC; /*!< USART Guard time and prescaler register, Address offset: 0x18 */ +} USART_TypeDef; + +/** + * @brief Window WATCHDOG + */ + +typedef struct +{ + __IO uint32_t CTRL; /*!< WWDT Control register, Address offset: 0x00 */ + __IO uint32_t CFR; /*!< WWDT Configuration register, Address offset: 0x04 */ + __IO uint32_t STS; /*!< WWDT Status register, Address offset: 0x08 */ +} WWDT_TypeDef; + +/** + * @brief RNG + */ + +typedef struct +{ + __IO uint32_t CTRL; /*!< RNG control register, Address offset: 0x00 */ + __IO uint32_t STS; /*!< RNG status register, Address offset: 0x04 */ + __IO uint32_t DATA; /*!< RNG data register, Address offset: 0x08 */ +} RNG_TypeDef; + +/** + * @brief USB_OTG_Core_Registers + */ +typedef struct +{ + __IO uint32_t GCTRLSTS; /*!< USB_OTG Control and Status Register 000h */ + __IO uint32_t GINT; /*!< USB_OTG Interrupt Register 004h */ + __IO uint32_t GAHBCFG; /*!< Core AHB Configuration Register 008h */ + __IO uint32_t GUSBCFG; /*!< Core USB Configuration Register 00Ch */ + __IO uint32_t GRSTCTRL; /*!< Core Reset Register 010h */ + __IO uint32_t GCINT; /*!< Core Interrupt Register 014h */ + __IO uint32_t GINTMASK; /*!< Core Interrupt Mask Register 018h */ + __IO uint32_t GRXSTS; /*!< Receive Sts Q Read Register 01Ch */ + __IO uint32_t GRXSTSP; /*!< Receive Sts Q Read & POP Register 020h */ + __IO uint32_t GRXFIFO; /*!< Receive FIFO Size Register 024h */ + __IO uint32_t GTXFCFG; /*!< EP0 / Non Periodic Tx FIFO Size Register 028h */ + __IO uint32_t GNPTXFQSTS; /*!< Non Periodic Tx FIFO/Queue Sts reg 02Ch */ + uint32_t Reserved30[2]; /*!< Reserved 030h */ + __IO uint32_t GGCCFG; /*!< General Purpose IO Register 038h */ + __IO uint32_t GCID; /*!< User ID Register 03Ch */ + uint32_t Reserved40[48]; /*!< Reserved 0x40-0xFF */ + __IO uint32_t GHPTXFSIZE; /*!< Host Periodic Tx FIFO Size Reg 100h */ + __IO uint32_t DTXFIFO[0x0F]; /*!< dev Periodic Transmit FIFO */ +} USB_OTG_GlobalTypeDef; + +/** + * @brief USB_OTG_device_Registers + */ +typedef struct +{ + __IO uint32_t DCFG; /*!< dev Configuration Register 800h */ + __IO uint32_t DCTRL; /*!< dev Control Register 804h */ + __IO uint32_t DSTS; /*!< dev Status Register (RO) 808h */ + uint32_t Reserved0C; /*!< Reserved 80Ch */ + __IO uint32_t DINIMASK; /*!< dev IN Endpoint Mask 810h */ + __IO uint32_t DOUTIMASK; /*!< dev OUT Endpoint Mask 814h */ + __IO uint32_t DAEPINT; /*!< dev All Endpoints Itr Reg 818h */ + __IO uint32_t DAEPIMASK; /*!< dev All Endpoints Itr Mask 81Ch */ + uint32_t Reserved20; /*!< Reserved 820h */ + uint32_t Reserved9; /*!< Reserved 824h */ + __IO uint32_t DVBUSDTIM; /*!< dev VBUS discharge Register 828h */ + __IO uint32_t DVBUSPTIM; /*!< dev VBUS Pulse Register 82Ch */ + __IO uint32_t DTHCTRL; /*!< dev threshold 830h */ + __IO uint32_t DIEIMASK; /*!< dev empty msk 834h */ + __IO uint32_t DEPINT; /*!< dedicated EP interrupt 838h */ + __IO uint32_t DEPIMASK; /*!< dedicated EP msk 83Ch */ + uint32_t Reserved40; /*!< dedicated EP mask 840h */ + __IO uint32_t DIN1IMASK; /*!< dedicated EP mask 844h */ + uint32_t Reserved44[15]; /*!< Reserved 844-87Ch */ + __IO uint32_t DOUT1MASK; /*!< dedicated EP msk 884h */ +} USB_OTG_DeviceTypeDef; + +/** + * @brief USB_OTG_IN_Endpoint-Specific_Register + */ +typedef struct +{ + __IO uint32_t DIEPCTRL; /*!< dev IN Endpoint Control Reg 900h + (ep_num * 20h) + 00h */ + uint32_t Reserved04; /*!< Reserved 900h + (ep_num * 20h) + 04h */ + __IO uint32_t DIEPINT; /*!< dev IN Endpoint Itr Reg 900h + (ep_num * 20h) + 08h */ + uint32_t Reserved0C; /*!< Reserved 900h + (ep_num * 20h) + 0Ch */ + __IO uint32_t DIEPTRS; /*!< IN Endpoint Txfer Size 900h + (ep_num * 20h) + 10h */ + __IO uint32_t DIEPDMA; /*!< IN Endpoint DMA Address Reg 900h + (ep_num * 20h) + 14h */ + __IO uint32_t DITXFSTS; /*!< IN Endpoint Tx FIFO Status Reg 900h + (ep_num * 20h) + 18h */ + uint32_t Reserved18; /*!< Reserved 900h+(ep_num*20h)+1Ch-900h+ (ep_num * 20h) + 1Ch */ +} USB_OTG_INEndpointTypeDef; + +/** + * @brief USB_OTG_OUT_Endpoint-Specific_Registers + */ +typedef struct +{ + __IO uint32_t DOEPCTRL; /*!< dev OUT Endpoint Control Reg B00h + (ep_num * 20h) + 00h */ + uint32_t Reserved04; /*!< Reserved B00h + (ep_num * 20h) + 04h */ + __IO uint32_t DOEPINT; /*!< dev OUT Endpoint Itr Reg B00h + (ep_num * 20h) + 08h */ + uint32_t Reserved0C; /*!< Reserved B00h + (ep_num * 20h) + 0Ch */ + __IO uint32_t DOEPTRS; /*!< dev OUT Endpoint Txfer Size B00h + (ep_num * 20h) + 10h */ + __IO uint32_t DOEPDMA; /*!< dev OUT Endpoint DMA Address B00h + (ep_num * 20h) + 14h */ + uint32_t Reserved18[2]; /*!< Reserved B00h + (ep_num * 20h) + 18h - B00h + (ep_num * 20h) + 1Ch */ +} USB_OTG_OUTEndpointTypeDef; + +/** + * @brief USB_OTG_Host_Mode_Register_Structures + */ +typedef struct +{ + __IO uint32_t HCFG; /*!< Host Configuration Register 400h */ + __IO uint32_t HFIVL; /*!< Host Frame Interval Register 404h */ + __IO uint32_t HFIFM; /*!< Host Frame Nbr/Frame Remaining 408h */ + uint32_t Reserved40C; /*!< Reserved 40Ch */ + __IO uint32_t HPTXSTS; /*!< Host Periodic Tx FIFO/ Queue Status 410h */ + __IO uint32_t HACHINT; /*!< Host All Channels Interrupt Register 414h */ + __IO uint32_t HACHIMASK; /*!< Host All Channels Interrupt Mask 418h */ +} USB_OTG_HostTypeDef; + +/** + * @brief USB_OTG_Host_Channel_Specific_Registers + */ +typedef struct +{ + __IO uint32_t HCH; /*!< Host Channel Characteristics Register 500h */ + __IO uint32_t HCHSCTRL; /*!< Host Channel Split Control Register 504h */ + __IO uint32_t HCHINT; /*!< Host Channel Interrupt Register 508h */ + __IO uint32_t HCHIMASK; /*!< Host Channel Interrupt Mask Register 50Ch */ + __IO uint32_t HCHTSIZE; /*!< Host Channel Transfer Size Register 510h */ + __IO uint32_t HCHDMA; /*!< Host Channel DMA Address Register 514h */ + uint32_t Reserved[2]; /*!< Reserved */ +} USB_OTG_HostChannelTypeDef; + +/** + * @brief USB_OTG_HS2_Specific_Registers + */ +typedef struct +{ + __IO uint32_t USB_SWITCH; /*!< USB Switch Register 200h */ + __IO uint32_t POWERON_CORE; /*!< Power On Core Register 204h */ + __IO uint32_t USB_PLL_EN; /*!< USB PLL Enable Register 208h */ + __IO uint32_t SHORT_5V_ENABLE; /*!< VBUS Short 5V Enable 20Ch */ + __IO uint32_t OTG_SUSPENDM; /*!< OTG VBUS Suspend 210h */ + __IO uint32_t TXBITSTUFFENABLE; /*!< TX Bit Stuff Enable 214h */ + __IO uint32_t PLLICP_SEL_I2C; /*!< PLL Charge Current Setting 218h */ + __IO uint32_t HSZR_CNTL_I2C; /*!< The DP/DM to the Ground Impedance Setting 21Ch */ + __IO uint32_t SQVTH_CNTL_I2C; /*!< The SQ Reference Voltage Setting 220h*/ + __IO uint32_t SW_RREF_I2C; /*!< The DP/DM Output Swing Setting When HS Mode 224h */ + __IO uint32_t SW_BUF_I2C; /*!< The TX Driver Setting 228h */ + __IO uint32_t TX2RX_T_CFG_I2C; /*!< Debug Control Signal 22Ch */ + __IO uint32_t TEST_ANA_FAST_I2C; /*!< Debug Control Signal 230h */ + __IO uint32_t CLK_MODE_I2C; /*!< Debug control signal 234h */ + __IO uint32_t USB_DBNCE_FLTR_BYPASS; /*!< Bypass debounce filters for avalid, bvalid, vbusvalid, + sessend, iddig signals when enabled 238h */ + __IO uint32_t USB_SS_SCALEDOWN_MODE; /*!< Used only in simulation 23Ch */ +} USB_OTG_HS2TypeDef; + +/** + * @} + */ + +/** @addtogroup Peripheral_memory_map + * @{ + */ +#define FLASH_BASE 0x08000000UL /*!< FLASH(up to 1 MB) base address in the alias region */ +#define CCMDATARAM_BASE 0x10000000UL /*!< CCM(core coupled memory) data RAM(64 KB) base address in the alias region */ +#define SRAM1_BASE 0x20000000UL /*!< SRAM1(112 KB) base address in the alias region */ +#define SRAM2_BASE 0x2001C000UL /*!< SRAM2(16 KB) base address in the alias region */ +#define PERIPH_BASE 0x40000000UL /*!< Peripheral base address in the alias region */ +#define BKPSRAM_BASE 0x40024000UL /*!< Backup SRAM(4 KB) base address in the alias region */ +#define SMC_R_BASE 0xA0000000UL /*!< SMC registers base address */ +#define SRAM1_BB_BASE 0x22000000UL /*!< SRAM1(112 KB) base address in the bit-band region */ +#define SRAM2_BB_BASE 0x22380000UL /*!< SRAM2(16 KB) base address in the bit-band region */ +#define PERIPH_BB_BASE 0x42000000UL /*!< Peripheral base address in the bit-band region */ +#define BKPSRAM_BB_BASE 0x42480000UL /*!< Backup SRAM(4 KB) base address in the bit-band region */ +#define FLASH_END 0x080FFFFFUL /*!< FLASH end address */ +#define FLASH_OTP_BASE 0x1FFF7800UL /*!< Base address of : (up to 528 Bytes) embedded FLASH OTP Area */ +#define FLASH_OTP_END 0x1FFF7A0FUL /*!< End address of : (up to 528 Bytes) embedded FLASH OTP Area */ +#define CCMDATARAM_END 0x1000FFFFUL /*!< CCM data RAM end address */ + +/* Legacy defines */ +#define SRAM_BASE SRAM1_BASE +#define SRAM_BB_BASE SRAM1_BB_BASE + +/*!< Peripheral memory map */ +#define APB1PERIPH_BASE PERIPH_BASE +#define APB2PERIPH_BASE (PERIPH_BASE + 0x00010000UL) +#define AHB1PERIPH_BASE (PERIPH_BASE + 0x00020000UL) +#define AHB2PERIPH_BASE (PERIPH_BASE + 0x10000000UL) + +/*!< APB1 peripherals */ +#define TMR2_BASE (APB1PERIPH_BASE + 0x0000UL) +#define TMR3_BASE (APB1PERIPH_BASE + 0x0400UL) +#define TMR4_BASE (APB1PERIPH_BASE + 0x0800UL) +#define TMR5_BASE (APB1PERIPH_BASE + 0x0C00UL) +#define TMR6_BASE (APB1PERIPH_BASE + 0x1000UL) +#define TMR7_BASE (APB1PERIPH_BASE + 0x1400UL) +#define TMR12_BASE (APB1PERIPH_BASE + 0x1800UL) +#define TMR13_BASE (APB1PERIPH_BASE + 0x1C00UL) +#define TMR14_BASE (APB1PERIPH_BASE + 0x2000UL) +#define RTC_BASE (APB1PERIPH_BASE + 0x2800UL) +#define WWDT_BASE (APB1PERIPH_BASE + 0x2C00UL) +#define IWDT_BASE (APB1PERIPH_BASE + 0x3000UL) +#define I2S2ext_BASE (APB1PERIPH_BASE + 0x3400UL) +#define SPI2_BASE (APB1PERIPH_BASE + 0x3800UL) +#define SPI3_BASE (APB1PERIPH_BASE + 0x3C00UL) +#define I2S3ext_BASE (APB1PERIPH_BASE + 0x4000UL) +#define USART2_BASE (APB1PERIPH_BASE + 0x4400UL) +#define USART3_BASE (APB1PERIPH_BASE + 0x4800UL) +#define UART4_BASE (APB1PERIPH_BASE + 0x4C00UL) +#define UART5_BASE (APB1PERIPH_BASE + 0x5000UL) +#define I2C1_BASE (APB1PERIPH_BASE + 0x5400UL) +#define I2C2_BASE (APB1PERIPH_BASE + 0x5800UL) +#define I2C3_BASE (APB1PERIPH_BASE + 0x5C00UL) +#define CAN1_BASE (APB1PERIPH_BASE + 0x6400UL) +#define CAN2_BASE (APB1PERIPH_BASE + 0x6800UL) +#define PMU_BASE (APB1PERIPH_BASE + 0x7000UL) +#define DAC_BASE (APB1PERIPH_BASE + 0x7400UL) + +/*!< APB2 peripherals */ +#define TMR1_BASE (APB2PERIPH_BASE + 0x0000UL) +#define TMR8_BASE (APB2PERIPH_BASE + 0x0400UL) +#define USART1_BASE (APB2PERIPH_BASE + 0x1000UL) +#define USART6_BASE (APB2PERIPH_BASE + 0x1400UL) +#define ADC1_BASE (APB2PERIPH_BASE + 0x2000UL) +#define ADC2_BASE (APB2PERIPH_BASE + 0x2100UL) +#define ADC3_BASE (APB2PERIPH_BASE + 0x2200UL) +#define ADC123_COMMON_BASE (APB2PERIPH_BASE + 0x2300UL) +/* Legacy define */ +#define ADC_BASE ADC123_COMMON_BASE +#define SDIO_BASE (APB2PERIPH_BASE + 0x2C00UL) +#define SPI1_BASE (APB2PERIPH_BASE + 0x3000UL) +#define SYSCFG_BASE (APB2PERIPH_BASE + 0x3800UL) +#define EINT_BASE (APB2PERIPH_BASE + 0x3C00UL) +#define TMR9_BASE (APB2PERIPH_BASE + 0x4000UL) +#define TMR10_BASE (APB2PERIPH_BASE + 0x4400UL) +#define TMR11_BASE (APB2PERIPH_BASE + 0x4800UL) + +/*!< AHB1 peripherals */ +#define GPIOA_BASE (AHB1PERIPH_BASE + 0x0000UL) +#define GPIOB_BASE (AHB1PERIPH_BASE + 0x0400UL) +#define GPIOC_BASE (AHB1PERIPH_BASE + 0x0800UL) +#define GPIOD_BASE (AHB1PERIPH_BASE + 0x0C00UL) +#define GPIOE_BASE (AHB1PERIPH_BASE + 0x1000UL) +#define GPIOF_BASE (AHB1PERIPH_BASE + 0x1400UL) +#define GPIOG_BASE (AHB1PERIPH_BASE + 0x1800UL) +#define GPIOH_BASE (AHB1PERIPH_BASE + 0x1C00UL) +#define GPIOI_BASE (AHB1PERIPH_BASE + 0x2000UL) +#define CRC_BASE (AHB1PERIPH_BASE + 0x3000UL) +#define RCM_BASE (AHB1PERIPH_BASE + 0x3800UL) +#define FLASH_R_BASE (AHB1PERIPH_BASE + 0x3C00UL) +#define DMA1_BASE (AHB1PERIPH_BASE + 0x6000UL) +#define DMA1_Stream0_BASE (DMA1_BASE + 0x010UL) +#define DMA1_Stream1_BASE (DMA1_BASE + 0x028UL) +#define DMA1_Stream2_BASE (DMA1_BASE + 0x040UL) +#define DMA1_Stream3_BASE (DMA1_BASE + 0x058UL) +#define DMA1_Stream4_BASE (DMA1_BASE + 0x070UL) +#define DMA1_Stream5_BASE (DMA1_BASE + 0x088UL) +#define DMA1_Stream6_BASE (DMA1_BASE + 0x0A0UL) +#define DMA1_Stream7_BASE (DMA1_BASE + 0x0B8UL) +#define DMA2_BASE (AHB1PERIPH_BASE + 0x6400UL) +#define DMA2_Stream0_BASE (DMA2_BASE + 0x010UL) +#define DMA2_Stream1_BASE (DMA2_BASE + 0x028UL) +#define DMA2_Stream2_BASE (DMA2_BASE + 0x040UL) +#define DMA2_Stream3_BASE (DMA2_BASE + 0x058UL) +#define DMA2_Stream4_BASE (DMA2_BASE + 0x070UL) +#define DMA2_Stream5_BASE (DMA2_BASE + 0x088UL) +#define DMA2_Stream6_BASE (DMA2_BASE + 0x0A0UL) +#define DMA2_Stream7_BASE (DMA2_BASE + 0x0B8UL) + +/*!< AHB2 peripherals */ +#define RNG_BASE (AHB2PERIPH_BASE + 0x60800UL) + +/*!< SMC Bankx registers base address */ +#define SMC_Bank1_R_BASE (SMC_R_BASE + 0x0000UL) +#define SMC_Bank1E_R_BASE (SMC_R_BASE + 0x0104UL) +#define SMC_Bank2_3_R_BASE (SMC_R_BASE + 0x0060UL) +#define SMC_Bank4_R_BASE (SMC_R_BASE + 0x00A0UL) + + +/*!< Debug MCU registers base address */ +#define DBGMCU_BASE 0xE0042000UL +/*!< USB registers base address */ +#define USB_OTG_HS2_PERIPH_BASE 0x40040200UL +#define USB_OTG_HS_PERIPH_BASE 0x40040000UL +#define USB_OTG_FS_PERIPH_BASE 0x50000000UL + +#define USB_OTG_GLOBAL_BASE 0x000UL +#define USB_OTG_DEVICE_BASE 0x800UL +#define USB_OTG_IN_ENDPOINT_BASE 0x900UL +#define USB_OTG_OUT_ENDPOINT_BASE 0xB00UL +#define USB_OTG_EP_REG_SIZE 0x20UL +#define USB_OTG_HOST_BASE 0x400UL +#define USB_OTG_HOST_PORT_BASE 0x440UL +#define USB_OTG_HOST_CHANNEL_BASE 0x500UL +#define USB_OTG_HOST_CHANNEL_SIZE 0x20UL +#define USB_OTG_PCGCCTL_BASE 0xE00UL +#define USB_OTG_FIFO_BASE 0x1000UL +#define USB_OTG_FIFO_SIZE 0x1000UL + +#define UID_BASE 0x1FFF7A10UL /*!< Unique device ID register base address */ +#define FLASHSIZE_BASE 0x1FFF7A22UL /*!< FLASH Size register base address */ +#define PACKAGE_BASE 0x1FFF7BF0UL /*!< Package size register base address */ +/** + * @} + */ + +/** @addtogroup Peripheral_declaration + * @{ + */ +#define TMR2 ((TMR_TypeDef *) TMR2_BASE) +#define TMR3 ((TMR_TypeDef *) TMR3_BASE) +#define TMR4 ((TMR_TypeDef *) TMR4_BASE) +#define TMR5 ((TMR_TypeDef *) TMR5_BASE) +#define TMR6 ((TMR_TypeDef *) TMR6_BASE) +#define TMR7 ((TMR_TypeDef *) TMR7_BASE) +#define TMR12 ((TMR_TypeDef *) TMR12_BASE) +#define TMR13 ((TMR_TypeDef *) TMR13_BASE) +#define TMR14 ((TMR_TypeDef *) TMR14_BASE) +#define RTC ((RTC_TypeDef *) RTC_BASE) +#define WWDT ((WWDT_TypeDef *) WWDT_BASE) +#define IWDT ((IWDT_TypeDef *) IWDT_BASE) +#define I2S2ext ((SPI_TypeDef *) I2S2ext_BASE) +#define SPI2 ((SPI_TypeDef *) SPI2_BASE) +#define SPI3 ((SPI_TypeDef *) SPI3_BASE) +#define I2S3ext ((SPI_TypeDef *) I2S3ext_BASE) +#define USART2 ((USART_TypeDef *) USART2_BASE) +#define USART3 ((USART_TypeDef *) USART3_BASE) +#define UART4 ((USART_TypeDef *) UART4_BASE) +#define UART5 ((USART_TypeDef *) UART5_BASE) +#define I2C1 ((I2C_TypeDef *) I2C1_BASE) +#define I2C2 ((I2C_TypeDef *) I2C2_BASE) +#define I2C3 ((I2C_TypeDef *) I2C3_BASE) +#define CAN1 ((CAN_TypeDef *) CAN1_BASE) +#define CAN2 ((CAN_TypeDef *) CAN2_BASE) +#define PMU ((PMU_TypeDef *) PMU_BASE) +#define DAC1 ((DAC_TypeDef *) DAC_BASE) +#define DAC ((DAC_TypeDef *) DAC_BASE) /* Kept for legacy purpose */ +#define TMR1 ((TMR_TypeDef *) TMR1_BASE) +#define TMR8 ((TMR_TypeDef *) TMR8_BASE) +#define USART1 ((USART_TypeDef *) USART1_BASE) +#define USART6 ((USART_TypeDef *) USART6_BASE) +#define ADC1 ((ADC_TypeDef *) ADC1_BASE) +#define ADC2 ((ADC_TypeDef *) ADC2_BASE) +#define ADC3 ((ADC_TypeDef *) ADC3_BASE) +#define ADC123_COMMON ((ADC_Common_TypeDef *) ADC123_COMMON_BASE) +/* Legacy define */ +#define ADC ADC123_COMMON +#define SDIO ((SDIO_TypeDef *) SDIO_BASE) +#define SPI1 ((SPI_TypeDef *) SPI1_BASE) +#define SYSCFG ((SYSCFG_TypeDef *) SYSCFG_BASE) +#define EINT ((EINT_TypeDef *) EINT_BASE) +#define TMR9 ((TMR_TypeDef *) TMR9_BASE) +#define TMR10 ((TMR_TypeDef *) TMR10_BASE) +#define TMR11 ((TMR_TypeDef *) TMR11_BASE) +#define GPIOA ((GPIO_TypeDef *) GPIOA_BASE) +#define GPIOB ((GPIO_TypeDef *) GPIOB_BASE) +#define GPIOC ((GPIO_TypeDef *) GPIOC_BASE) +#define GPIOD ((GPIO_TypeDef *) GPIOD_BASE) +#define GPIOE ((GPIO_TypeDef *) GPIOE_BASE) +#define GPIOF ((GPIO_TypeDef *) GPIOF_BASE) +#define GPIOG ((GPIO_TypeDef *) GPIOG_BASE) +#define GPIOH ((GPIO_TypeDef *) GPIOH_BASE) +#define GPIOI ((GPIO_TypeDef *) GPIOI_BASE) +#define CRC ((CRC_TypeDef *) CRC_BASE) +#define RCM ((RCM_TypeDef *) RCM_BASE) +#define FLASH ((FLASH_TypeDef *) FLASH_R_BASE) +#define DMA1 ((DMA_TypeDef *) DMA1_BASE) +#define DMA1_Stream0 ((DMA_Stream_TypeDef *) DMA1_Stream0_BASE) +#define DMA1_Stream1 ((DMA_Stream_TypeDef *) DMA1_Stream1_BASE) +#define DMA1_Stream2 ((DMA_Stream_TypeDef *) DMA1_Stream2_BASE) +#define DMA1_Stream3 ((DMA_Stream_TypeDef *) DMA1_Stream3_BASE) +#define DMA1_Stream4 ((DMA_Stream_TypeDef *) DMA1_Stream4_BASE) +#define DMA1_Stream5 ((DMA_Stream_TypeDef *) DMA1_Stream5_BASE) +#define DMA1_Stream6 ((DMA_Stream_TypeDef *) DMA1_Stream6_BASE) +#define DMA1_Stream7 ((DMA_Stream_TypeDef *) DMA1_Stream7_BASE) +#define DMA2 ((DMA_TypeDef *) DMA2_BASE) +#define DMA2_Stream0 ((DMA_Stream_TypeDef *) DMA2_Stream0_BASE) +#define DMA2_Stream1 ((DMA_Stream_TypeDef *) DMA2_Stream1_BASE) +#define DMA2_Stream2 ((DMA_Stream_TypeDef *) DMA2_Stream2_BASE) +#define DMA2_Stream3 ((DMA_Stream_TypeDef *) DMA2_Stream3_BASE) +#define DMA2_Stream4 ((DMA_Stream_TypeDef *) DMA2_Stream4_BASE) +#define DMA2_Stream5 ((DMA_Stream_TypeDef *) DMA2_Stream5_BASE) +#define DMA2_Stream6 ((DMA_Stream_TypeDef *) DMA2_Stream6_BASE) +#define DMA2_Stream7 ((DMA_Stream_TypeDef *) DMA2_Stream7_BASE) +#define RNG ((RNG_TypeDef *) RNG_BASE) +#define SMC_Bank1 ((SMC_Bank1_TypeDef *) SMC_Bank1_R_BASE) +#define SMC_Bank1E ((SMC_Bank1E_TypeDef *) SMC_Bank1E_R_BASE) +#define SMC_Bank2_3 ((SMC_Bank2_3_TypeDef *) SMC_Bank2_3_R_BASE) +#define SMC_Bank4 ((SMC_Bank4_TypeDef *) SMC_Bank4_R_BASE) +#define DBGMCU ((DBGMCU_TypeDef *) DBGMCU_BASE) +#define USB_OTG_FS ((USB_OTG_GlobalTypeDef *) USB_OTG_FS_PERIPH_BASE) +#define USB_OTG_HS ((USB_OTG_GlobalTypeDef *) USB_OTG_HS_PERIPH_BASE) +#define USB_OTG_HS2 ((USB_OTG_HS2TypeDef *) USB_OTG_HS2_PERIPH_BASE) + +/** + * @} + */ + +/** @addtogroup Exported_constants + * @{ + */ + +/** @addtogroup Hardware_Constant_Definition + * @{ + */ +#define LSI_STARTUP_TIME 40U /*!< LSI Maximum startup time in us */ +/** + * @} + */ + + /** @addtogroup Peripheral_Registers_Bits_Definition + * @{ + */ + +/******************************************************************************/ +/* Peripheral Registers_Bits_Definition */ +/******************************************************************************/ + +/******************************************************************************/ +/* */ +/* Analog to Digital Converter */ +/* */ +/******************************************************************************/ +/* + * @brief Specific device feature definitions (not present on all devices in the APM32F4 serie) + */ +#define ADC_MULTIMODE_SUPPORT /*! + +/** @addtogroup Peripheral_registers_structures + * @{ + */ + +/** + * @brief Analog to Digital Converter + */ + +typedef struct +{ + __IO uint32_t STS; /*!< ADC status register, Address offset: 0x00 */ + __IO uint32_t CTRL1; /*!< ADC control register 1, Address offset: 0x04 */ + __IO uint32_t CTRL2; /*!< ADC control register 2, Address offset: 0x08 */ + __IO uint32_t SMPTIM1; /*!< ADC sample time register 1, Address offset: 0x0C */ + __IO uint32_t SMPTIM2; /*!< ADC sample time register 2, Address offset: 0x10 */ + __IO uint32_t INJDOF1; /*!< ADC injected channel data offset register 1, Address offset: 0x14 */ + __IO uint32_t INJDOF2; /*!< ADC injected channel data offset register 2, Address offset: 0x18 */ + __IO uint32_t INJDOF3; /*!< ADC injected channel data offset register 3, Address offset: 0x1C */ + __IO uint32_t INJDOF4; /*!< ADC injected channel data offset register 4, Address offset: 0x20 */ + __IO uint32_t AWDHT; /*!< ADC watchdog higher threshold register, Address offset: 0x24 */ + __IO uint32_t AWDLT; /*!< ADC watchdog lower threshold register, Address offset: 0x28 */ + __IO uint32_t REGSEQ1; /*!< ADC regular sequence register 1, Address offset: 0x2C */ + __IO uint32_t REGSEQ2; /*!< ADC regular sequence register 2, Address offset: 0x30 */ + __IO uint32_t REGSEQ3; /*!< ADC regular sequence register 3, Address offset: 0x34 */ + __IO uint32_t INJSEQ; /*!< ADC injected sequence register, Address offset: 0x38 */ + __IO uint32_t INJDATA1; /*!< ADC injected data register 1, Address offset: 0x3C */ + __IO uint32_t INJDATA2; /*!< ADC injected data register 2, Address offset: 0x40 */ + __IO uint32_t INJDATA3; /*!< ADC injected data register 3, Address offset: 0x44 */ + __IO uint32_t INJDATA4; /*!< ADC injected data register 4, Address offset: 0x48 */ + __IO uint32_t REGDATA; /*!< ADC regular data register, Address offset: 0x4C */ +} ADC_TypeDef; + +typedef struct +{ + __IO uint32_t CSTS; /*!< ADC Common status register, Address offset: ADC1 base address + 0x300 */ + __IO uint32_t CCTRL; /*!< ADC common control register, Address offset: ADC1 base address + 0x304 */ + __IO uint32_t CDATA; /*!< ADC common regular data register for dual + AND triple modes, Address offset: ADC1 base address + 0x308 */ +} ADC_Common_TypeDef; + + +/** + * @brief Controller Area Network TxMailBox + */ + +typedef struct +{ + __IO uint32_t TXMID; /*!< CAN TX mailbox identifier register */ + __IO uint32_t TXDLEN; /*!< CAN mailbox data length control and time stamp register */ + __IO uint32_t TXMDL; /*!< CAN mailbox data low register */ + __IO uint32_t TXMDH; /*!< CAN mailbox data high register */ +} CAN_TxMailBox_TypeDef; + +/** + * @brief Controller Area Network FIFOMailBox + */ + +typedef struct +{ + __IO uint32_t RXMID; /*!< CAN receive FIFO mailbox identifier register */ + __IO uint32_t RXDLEN; /*!< CAN receive FIFO mailbox data length control and time stamp register */ + __IO uint32_t RXMDL; /*!< CAN receive FIFO mailbox data low register */ + __IO uint32_t RXMDH; /*!< CAN receive FIFO mailbox data high register */ +} CAN_FIFOMailBox_TypeDef; + +/** + * @brief Controller Area Network FilterRegister + */ + +typedef struct +{ + __IO uint32_t FBANK1; /*!< CAN Filter bank register 1 */ + __IO uint32_t FBANK2; /*!< CAN Filter bank register 1 */ +} CAN_FilterRegister_TypeDef; + +/** + * @brief Controller Area Network + */ + +typedef struct +{ + __IO uint32_t MCTRL; /*!< CAN master control register, Address offset: 0x00 */ + __IO uint32_t MSTS; /*!< CAN master status register, Address offset: 0x04 */ + __IO uint32_t TXSTS; /*!< CAN transmit status register, Address offset: 0x08 */ + __IO uint32_t RXF0; /*!< CAN receive FIFO 0 register, Address offset: 0x0C */ + __IO uint32_t RXF1; /*!< CAN receive FIFO 1 register, Address offset: 0x10 */ + __IO uint32_t INTEN; /*!< CAN interrupt enable register, Address offset: 0x14 */ + __IO uint32_t ERRSTS; /*!< CAN error status register, Address offset: 0x18 */ + __IO uint32_t BITTIM; /*!< CAN bit timing register, Address offset: 0x1C */ + uint32_t RESERVED0[88]; /*!< Reserved, 0x020 - 0x17F */ + CAN_TxMailBox_TypeDef sTxMailBox[3]; /*!< CAN Tx MailBox, Address offset: 0x180 - 0x1AC */ + CAN_FIFOMailBox_TypeDef sFIFOMailBox[2]; /*!< CAN FIFO MailBox, Address offset: 0x1B0 - 0x1CC */ + uint32_t RESERVED1[12]; /*!< Reserved, 0x1D0 - 0x1FF */ + __IO uint32_t FCTRL; /*!< CAN filter master register, Address offset: 0x200 */ + __IO uint32_t FMCFG; /*!< CAN filter mode register, Address offset: 0x204 */ + uint32_t RESERVED2; /*!< Reserved, 0x208 */ + __IO uint32_t FSCFG; /*!< CAN filter scale register, Address offset: 0x20C */ + uint32_t RESERVED3; /*!< Reserved, 0x210 */ + __IO uint32_t FFASS; /*!< CAN filter FIFO assignment register, Address offset: 0x214 */ + uint32_t RESERVED4; /*!< Reserved, 0x218 */ + __IO uint32_t FACT; /*!< CAN filter activation register, Address offset: 0x21C */ + uint32_t RESERVED5[8]; /*!< Reserved, 0x220-0x23F */ + CAN_FilterRegister_TypeDef sFilterRegister[28]; /*!< CAN Filter Register, Address offset: 0x240-0x31C */ +} CAN_TypeDef; + +/** + * @brief CRC calculation unit + */ + +typedef struct +{ + __IO uint32_t DATA; /*!< CRC Data register, Address offset: 0x00 */ + __IO uint8_t INDATA; /*!< CRC Independent data register, Address offset: 0x04 */ + uint8_t RESERVED0; /*!< Reserved, 0x05 */ + uint16_t RESERVED1; /*!< Reserved, 0x06 */ + __IO uint32_t CTRL; /*!< CRC Control register, Address offset: 0x08 */ +} CRC_TypeDef; + +/** + * @brief Digital to Analog Converter + */ + +typedef struct +{ + __IO uint32_t CTRL; /*!< DAC control register, Address offset: 0x00 */ + __IO uint32_t SWTRG; /*!< DAC software trigger register, Address offset: 0x04 */ + __IO uint32_t DH12R1; /*!< DAC channel1 12-bit right-aligned data holding register, Address offset: 0x08 */ + __IO uint32_t DH12L1; /*!< DAC channel1 12-bit left aligned data holding register, Address offset: 0x0C */ + __IO uint32_t DH8R1; /*!< DAC channel1 8-bit right aligned data holding register, Address offset: 0x10 */ + __IO uint32_t DH12R2; /*!< DAC channel2 12-bit right aligned data holding register, Address offset: 0x14 */ + __IO uint32_t DH12L2; /*!< DAC channel2 12-bit left aligned data holding register, Address offset: 0x18 */ + __IO uint32_t DH8R2; /*!< DAC channel2 8-bit right-aligned data holding register, Address offset: 0x1C */ + __IO uint32_t DH12RDUAL; /*!< Dual DAC 12-bit right-aligned data holding register, Address offset: 0x20 */ + __IO uint32_t DH12LDUAL; /*!< DUAL DAC 12-bit left aligned data holding register, Address offset: 0x24 */ + __IO uint32_t DH8RDUAL; /*!< DUAL DAC 8-bit right aligned data holding register, Address offset: 0x28 */ + __IO uint32_t DATAOCH1; /*!< DAC channel1 data output register, Address offset: 0x2C */ + __IO uint32_t DATAOCH2; /*!< DAC channel2 data output register, Address offset: 0x30 */ + __IO uint32_t STS; /*!< DAC status register, Address offset: 0x34 */ +} DAC_TypeDef; + +/** + * @brief Debug MCU + */ + +typedef struct +{ + __IO uint32_t IDCODE; /*!< MCU device ID code, Address offset: 0x00 */ + __IO uint32_t CFG; /*!< Debug MCU configuration register, Address offset: 0x04 */ + __IO uint32_t APB1F; /*!< Debug MCU APB1 freeze register, Address offset: 0x08 */ + __IO uint32_t APB2F; /*!< Debug MCU APB2 freeze register, Address offset: 0x0C */ +} DBGMCU_TypeDef; + +/** + * @brief DCI + */ + +typedef struct +{ + __IO uint32_t CTRL; /*!< DCI control register 1, Address offset: 0x00 */ + __IO uint32_t STS; /*!< DCI status register, Address offset: 0x04 */ + __IO uint32_t RINTSTS; /*!< DCI raw interrupt status register, Address offset: 0x08 */ + __IO uint32_t INTEN; /*!< DCI interrupt enable register, Address offset: 0x0C */ + __IO uint32_t MINTSTS; /*!< DCI masked interrupt status register, Address offset: 0x10 */ + __IO uint32_t INTCLR; /*!< DCI interrupt clear register, Address offset: 0x14 */ + __IO uint32_t ESYNCC; /*!< DCI embedded synchronization code register, Address offset: 0x18 */ + __IO uint32_t ESYNCUM; /*!< DCI embedded synchronization unmask register, Address offset: 0x1C */ + __IO uint32_t CROPWSTAT; /*!< DCI crop window start, Address offset: 0x20 */ + __IO uint32_t CROPWSIZE; /*!< DCI crop window size, Address offset: 0x24 */ + __IO uint32_t DATA; /*!< DCI data register, Address offset: 0x28 */ +} DCI_TypeDef; + +/** + * @brief DMA Controller + */ + +typedef struct +{ + __IO uint32_t SCFG; /*!< DMA stream x configuration register */ + __IO uint32_t NDATA; /*!< DMA stream x number of data register */ + __IO uint32_t PADDR; /*!< DMA stream x peripheral address register */ + __IO uint32_t M0ADDR; /*!< DMA stream x memory 0 address register */ + __IO uint32_t M1ADDR; /*!< DMA stream x memory 1 address register */ + __IO uint32_t FCTRL; /*!< DMA stream x FIFO control register */ +} DMA_Stream_TypeDef; + +typedef struct +{ + __IO uint32_t LINTSTS; /*!< DMA low interrupt status register, Address offset: 0x00 */ + __IO uint32_t HINTSTS; /*!< DMA high interrupt status register, Address offset: 0x04 */ + __IO uint32_t LIFCLR; /*!< DMA low interrupt flag clear register, Address offset: 0x08 */ + __IO uint32_t HIFCLR; /*!< DMA high interrupt flag clear register, Address offset: 0x0C */ +} DMA_TypeDef; + +/** + * @brief Ethernet MAC + */ + +typedef struct +{ + __IO uint32_t MACCFG; + __IO uint32_t MACFRAF; + __IO uint32_t MACHTH; + __IO uint32_t MACHTL; + __IO uint32_t MACADDR; + __IO uint32_t MACDATA; + __IO uint32_t MACFCTRL; + __IO uint32_t MACVLANT; /* 8 */ + uint32_t RESERVED0[2]; + __IO uint32_t MACREMWKUPFFL; /* 11 */ + __IO uint32_t MACPMTCTRLSTS; + uint32_t RESERVED1; + __IO uint32_t MACDBG; + __IO uint32_t MACISTS; /* 15 */ + __IO uint32_t MACIMASK; + __IO uint32_t MACADDR0H; + __IO uint32_t MACADDR0L; + __IO uint32_t MACADDR1H; + __IO uint32_t MACADDR1L; + __IO uint32_t MACADDR2H; + __IO uint32_t MACADDR2L; + __IO uint32_t MACADDR3H; + __IO uint32_t MACADDR3L; /* 24 */ + uint32_t RESERVED2[40]; + __IO uint32_t MMCCTRL; /* 65 */ + __IO uint32_t MMCRXINT; + __IO uint32_t MMCTXINT; + __IO uint32_t MMCRXINTMASK; + __IO uint32_t MMCTXINTMASK; /* 69 */ + uint32_t RESERVED3[14]; + __IO uint32_t MMCTXGFSCCNT; /* 84 */ + __IO uint32_t MMCTXGFMCCNT; + uint32_t RESERVED4[5]; + __IO uint32_t MMCTXGFCNT; + uint32_t RESERVED5[10]; + __IO uint32_t MMCRXFCECNT; + __IO uint32_t MMCRXFAECNT; + uint32_t RESERVED6[10]; + __IO uint32_t MMCRXGUNCNT; + uint32_t RESERVED7[334]; + __IO uint32_t PTPTSCTRL; + __IO uint32_t PTPSUBSECI; + __IO uint32_t PTPTSH; + __IO uint32_t PTPTSL; + __IO uint32_t PTPTSHUD; + __IO uint32_t PTPTSLUD; + __IO uint32_t PTPTSA; + __IO uint32_t PTPTTSH; + __IO uint32_t PTPTTSL; + __IO uint32_t RESERVED8; + __IO uint32_t PTPTSSTS; + uint32_t RESERVED9[565]; + __IO uint32_t DMABMOD; + __IO uint32_t DMATXPD; + __IO uint32_t DMARXPD; + __IO uint32_t DMARXDLADDR; + __IO uint32_t DMATXDLADDR; + __IO uint32_t DMASTS; + __IO uint32_t DMAOPMOD; + __IO uint32_t DMAINTEN; + __IO uint32_t DMAMFABOCNT; + __IO uint32_t DMARXFLGWDT; + uint32_t RESERVED10[8]; + __IO uint32_t DMAHTXD; + __IO uint32_t DMAHRXD; + __IO uint32_t DMAHTXBADDR; + __IO uint32_t DMAHRXBADDR; +} ETH_TypeDef; + +/** + * @brief External Interrupt/Event Controller + */ + +typedef struct +{ + __IO uint32_t IMASK; /*!< EINT Interrupt mask register, Address offset: 0x00 */ + __IO uint32_t EMASK; /*!< EINT Event mask register, Address offset: 0x04 */ + __IO uint32_t RTEN; /*!< EINT Rising trigger selection register, Address offset: 0x08 */ + __IO uint32_t FTEN; /*!< EINT Falling trigger selection register, Address offset: 0x0C */ + __IO uint32_t SWINTE; /*!< EINT Software interrupt event register, Address offset: 0x10 */ + __IO uint32_t IPEND; /*!< EINT Pending register, Address offset: 0x14 */ +} EINT_TypeDef; + +/** + * @brief FLASH Registers + */ + +typedef struct +{ + __IO uint32_t ACCTRL; /*!< FLASH access control register, Address offset: 0x00 */ + __IO uint32_t KEY; /*!< FLASH key register, Address offset: 0x04 */ + __IO uint32_t OPTKEY; /*!< FLASH option key register, Address offset: 0x08 */ + __IO uint32_t STS; /*!< FLASH status register, Address offset: 0x0C */ + __IO uint32_t CTRL; /*!< FLASH control register, Address offset: 0x10 */ + __IO uint32_t OPTCTRL; /*!< FLASH option control register , Address offset: 0x14 */ + __IO uint32_t OPTCTRL1; /*!< FLASH option control register 1, Address offset: 0x18 */ +} FLASH_TypeDef; + +/** + * @brief Dynamic memory controler (DMC) + */ +typedef struct +{ + __IO uint32_t CFG; /*!< Configuraion register, Address offset: 0x00 */ + __IO uint32_t TIM0; /*!< Timing register 0, Address offset: 0x04 */ + __IO uint32_t TIM1; /*!< Timing register 1, Address offset: 0x08 */ + __IO uint32_t CTRL1; /*!< Control register 1, Address offset: 0x0C */ + __IO uint32_t REF; /*!< refresh register, Address offset: 0x10 */ + uint32_t RESERVED[251]; + __IO uint32_t SW; /*!< switch register, Address offset: 0x400 */ + __IO uint32_t CTRL2; /*!< Control register 2, Address offset: 0x404 */ +} DMC_TypeDef; + +/** + * @brief Flexible Static Memory Controller + */ + +typedef struct +{ + __IO uint32_t CSTR[8]; /*!< NOR/PSRAM chip-select control register(CSCTRL) and chip-select timing register(CSTIM), Address offset: 0x00-1C */ +} SMC_Bank1_TypeDef; + +/** + * @brief Flexible Static Memory Controller Bank1E + */ + +typedef struct +{ + __IO uint32_t WRTTIM[7]; /*!< NOR/PSRAM write timing registers, Address offset: 0x104-0x11C */ +} SMC_Bank1E_TypeDef; + +/** + * @brief Flexible Static Memory Controller Bank2 + */ + +typedef struct +{ + __IO uint32_t CTRL2; /*!< NAND Flash control register 2, Address offset: 0x60 */ + __IO uint32_t STSINT2; /*!< NAND Flash FIFO status and interrupt register 2, Address offset: 0x64 */ + __IO uint32_t CMSTIM2; /*!< NAND Flash Common memory space timing register 2, Address offset: 0x68 */ + __IO uint32_t AMSTIM2; /*!< NAND Flash Attribute memory space timing register 2, Address offset: 0x6C */ + uint32_t RESERVED0; /*!< Reserved, 0x70 */ + __IO uint32_t ECCRS2; /*!< NAND Flash ECC result registers 2, Address offset: 0x74 */ + uint32_t RESERVED1; /*!< Reserved, 0x78 */ + uint32_t RESERVED2; /*!< Reserved, 0x7C */ + __IO uint32_t CTRL3; /*!< NAND Flash control register 3, Address offset: 0x80 */ + __IO uint32_t STSINT3; /*!< NAND Flash FIFO status and interrupt register 3, Address offset: 0x84 */ + __IO uint32_t CMSTIM3; /*!< NAND Flash Common memory space timing register 3, Address offset: 0x88 */ + __IO uint32_t AMSTIM3; /*!< NAND Flash Attribute memory space timing register 3, Address offset: 0x8C */ + uint32_t RESERVED3; /*!< Reserved, 0x90 */ + __IO uint32_t ECCRS3; /*!< NAND Flash ECC result registers 3, Address offset: 0x94 */ +} SMC_Bank2_3_TypeDef; + +/** + * @brief Flexible Static Memory Controller Bank4 + */ + +typedef struct +{ + __IO uint32_t CTRL4; /*!< PC Card control register 4, Address offset: 0xA0 */ + __IO uint32_t STSINT4; /*!< PC Card FIFO status and interrupt register 4, Address offset: 0xA4 */ + __IO uint32_t CMSTIM4; /*!< PC Card Common memory space timing register 4, Address offset: 0xA8 */ + __IO uint32_t AMSTIM4; /*!< PC Card Attribute memory space timing register 4, Address offset: 0xAC */ + __IO uint32_t IOSTIM4; /*!< PC Card I/O space timing register 4, Address offset: 0xB0 */ +} SMC_Bank4_TypeDef; + +/** + * @brief General Purpose I/O + */ + +typedef struct +{ + __IO uint32_t MODE; /*!< GPIO port mode register, Address offset: 0x00 */ + __IO uint32_t OMODE; /*!< GPIO port output type register, Address offset: 0x04 */ + __IO uint32_t OSSEL; /*!< GPIO port output speed register, Address offset: 0x08 */ + __IO uint32_t PUPD; /*!< GPIO port pull-up/pull-down register, Address offset: 0x0C */ + __IO uint32_t IDATA; /*!< GPIO port input data register, Address offset: 0x10 */ + __IO uint32_t ODATA; /*!< GPIO port output data register, Address offset: 0x14 */ + __IO uint32_t BSC; /*!< GPIO port bit set/reset register, Address offset: 0x18 */ + __IO uint32_t LOCK; /*!< GPIO port configuration lock register, Address offset: 0x1C */ + __IO uint32_t ALF[2]; /*!< GPIO alternate function registers, Address offset: 0x20-0x24 */ +} GPIO_TypeDef; + +/** + * @brief System configuration controller + */ + +typedef struct +{ + __IO uint32_t MMSEL; /*!< SYSCFG memory remap register, Address offset: 0x00 */ + __IO uint32_t PMCFG; /*!< SYSCFG peripheral mode configuration register, Address offset: 0x04 */ + __IO uint32_t EINTCFG[4]; /*!< SYSCFG external interrupt configuration registers, Address offset: 0x08-0x14 */ + uint32_t RESERVED[2]; /*!< Reserved, 0x18-0x1C */ + __IO uint32_t CCCTRL; /*!< SYSCFG Compensation cell control register, Address offset: 0x20 */ +} SYSCFG_TypeDef; + +/** + * @brief Inter-integrated Circuit Interface + */ + +typedef struct +{ + __IO uint32_t CTRL1; /*!< I2C Control register 1, Address offset: 0x00 */ + __IO uint32_t CTRL2; /*!< I2C Control register 2, Address offset: 0x04 */ + __IO uint32_t SADDR1; /*!< I2C Own address register 1, Address offset: 0x08 */ + __IO uint32_t SADDR2; /*!< I2C Own address register 2, Address offset: 0x0C */ + __IO uint32_t DATA; /*!< I2C Data register, Address offset: 0x10 */ + __IO uint32_t STS1; /*!< I2C Status register 1, Address offset: 0x14 */ + __IO uint32_t STS2; /*!< I2C Status register 2, Address offset: 0x18 */ + __IO uint32_t CLKCTRL; /*!< I2C Clock control register, Address offset: 0x1C */ + __IO uint32_t RISETMAX; /*!< I2C RISETMAX register, Address offset: 0x20 */ +} I2C_TypeDef; + +/** + * @brief Independent WATCHDOG + */ + +typedef struct +{ + __IO uint32_t KEY; /*!< IWDT Key register, Address offset: 0x00 */ + __IO uint32_t PSC; /*!< IWDT Prescaler register, Address offset: 0x04 */ + __IO uint32_t CNTRLD; /*!< IWDT Reload register, Address offset: 0x08 */ + __IO uint32_t STS; /*!< IWDT Status register, Address offset: 0x0C */ +} IWDT_TypeDef; + + +/** + * @brief Power Control + */ + +typedef struct +{ + __IO uint32_t CTRL; /*!< PMU power control register, Address offset: 0x00 */ + __IO uint32_t CSTS; /*!< PMU power control/status register, Address offset: 0x04 */ +} PMU_TypeDef; + +/** + * @brief Reset and Clock Control + */ + +typedef struct +{ + __IO uint32_t CTRL; /*!< RCM clock control register, Address offset: 0x00 */ + __IO uint32_t PLL1CFG; /*!< RCM PLL configuration register, Address offset: 0x04 */ + __IO uint32_t CFG; /*!< RCM clock configuration register, Address offset: 0x08 */ + __IO uint32_t INT; /*!< RCM clock interrupt register, Address offset: 0x0C */ + __IO uint32_t AHB1RST; /*!< RCM AHB1 peripheral reset register, Address offset: 0x10 */ + __IO uint32_t AHB2RST; /*!< RCM AHB2 peripheral reset register, Address offset: 0x14 */ + __IO uint32_t AHB3RST; /*!< RCM AHB3 peripheral reset register, Address offset: 0x18 */ + uint32_t RESERVED0; /*!< Reserved, 0x1C */ + __IO uint32_t APB1RST; /*!< RCM APB1 peripheral reset register, Address offset: 0x20 */ + __IO uint32_t APB2RST; /*!< RCM APB2 peripheral reset register, Address offset: 0x24 */ + uint32_t RESERVED1[2]; /*!< Reserved, 0x28-0x2C */ + __IO uint32_t AHB1CLKEN; /*!< RCM AHB1 peripheral clock register, Address offset: 0x30 */ + __IO uint32_t AHB2CLKEN; /*!< RCM AHB2 peripheral clock register, Address offset: 0x34 */ + __IO uint32_t AHB3CLKEN; /*!< RCM AHB3 peripheral clock register, Address offset: 0x38 */ + uint32_t RESERVED2; /*!< Reserved, 0x3C */ + __IO uint32_t APB1CLKEN; /*!< RCM APB1 peripheral clock enable register, Address offset: 0x40 */ + __IO uint32_t APB2CLKEN; /*!< RCM APB2 peripheral clock enable register, Address offset: 0x44 */ + uint32_t RESERVED3[2]; /*!< Reserved, 0x48-0x4C */ + __IO uint32_t LPAHB1CLKEN; /*!< RCM AHB1 peripheral clock enable in low power mode register, Address offset: 0x50 */ + __IO uint32_t LPAHB2CLKEN; /*!< RCM AHB2 peripheral clock enable in low power mode register, Address offset: 0x54 */ + __IO uint32_t LPAHB3CLKEN; /*!< RCM AHB3 peripheral clock enable in low power mode register, Address offset: 0x58 */ + uint32_t RESERVED4; /*!< Reserved, 0x5C */ + __IO uint32_t LPAPB1CLKEN; /*!< RCM APB1 peripheral clock enable in low power mode register, Address offset: 0x60 */ + __IO uint32_t LPAPB2CLKEN; /*!< RCM APB2 peripheral clock enable in low power mode register, Address offset: 0x64 */ + uint32_t RESERVED5[2]; /*!< Reserved, 0x68-0x6C */ + __IO uint32_t BDCTRL; /*!< RCM Backup domain control register, Address offset: 0x70 */ + __IO uint32_t CSTS; /*!< RCM clock control & status register, Address offset: 0x74 */ + uint32_t RESERVED6[2]; /*!< Reserved, 0x78-0x7C */ + __IO uint32_t SSCCFG; /*!< RCM spread spectrum clock generation register, Address offset: 0x80 */ + __IO uint32_t PLL2CFG; /*!< RCM PLLI2S configuration register, Address offset: 0x84 */ +} RCM_TypeDef; + +/** + * @brief Real-Time Clock + */ + +typedef struct +{ + __IO uint32_t TIME; /*!< RTC time register, Address offset: 0x00 */ + __IO uint32_t DATE; /*!< RTC date register, Address offset: 0x04 */ + __IO uint32_t CTRL; /*!< RTC control register, Address offset: 0x08 */ + __IO uint32_t STS; /*!< RTC initialization and status register, Address offset: 0x0C */ + __IO uint32_t PSC; /*!< RTC prescaler register, Address offset: 0x10 */ + __IO uint32_t AUTORLD; /*!< RTC wakeup timer register, Address offset: 0x14 */ + __IO uint32_t DCAL; /*!< RTC calibration register, Address offset: 0x18 */ + __IO uint32_t ALRMA; /*!< RTC alarm A register, Address offset: 0x1C */ + __IO uint32_t ALRMB; /*!< RTC alarm B register, Address offset: 0x20 */ + __IO uint32_t WRPROT; /*!< RTC write protection register, Address offset: 0x24 */ + __IO uint32_t SUBSEC; /*!< RTC sub second register, Address offset: 0x28 */ + __IO uint32_t SHIFT; /*!< RTC shift control register, Address offset: 0x2C */ + __IO uint32_t TSTIME; /*!< RTC time stamp time register, Address offset: 0x30 */ + __IO uint32_t TSDATE; /*!< RTC time stamp date register, Address offset: 0x34 */ + __IO uint32_t TSSUBSEC; /*!< RTC time-stamp sub second register, Address offset: 0x38 */ + __IO uint32_t CAL; /*!< RTC calibration register, Address offset: 0x3C */ + __IO uint32_t TACFG; /*!< RTC tamper and alternate function configuration register, Address offset: 0x40 */ + __IO uint32_t ALRMASS; /*!< RTC alarm A sub second register, Address offset: 0x44 */ + __IO uint32_t ALRMBSS; /*!< RTC alarm B sub second register, Address offset: 0x48 */ + uint32_t RESERVED7; /*!< Reserved, 0x4C */ + __IO uint32_t BAKP0; /*!< RTC backup register 1, Address offset: 0x50 */ + __IO uint32_t BAKP1; /*!< RTC backup register 1, Address offset: 0x54 */ + __IO uint32_t BAKP2; /*!< RTC backup register 2, Address offset: 0x58 */ + __IO uint32_t BAKP3; /*!< RTC backup register 3, Address offset: 0x5C */ + __IO uint32_t BAKP4; /*!< RTC backup register 4, Address offset: 0x60 */ + __IO uint32_t BAKP5; /*!< RTC backup register 5, Address offset: 0x64 */ + __IO uint32_t BAKP6; /*!< RTC backup register 6, Address offset: 0x68 */ + __IO uint32_t BAKP7; /*!< RTC backup register 7, Address offset: 0x6C */ + __IO uint32_t BAKP8; /*!< RTC backup register 8, Address offset: 0x70 */ + __IO uint32_t BAKP9; /*!< RTC backup register 9, Address offset: 0x74 */ + __IO uint32_t BAKP10; /*!< RTC backup register 10, Address offset: 0x78 */ + __IO uint32_t BAKP11; /*!< RTC backup register 11, Address offset: 0x7C */ + __IO uint32_t BAKP12; /*!< RTC backup register 12, Address offset: 0x80 */ + __IO uint32_t BAKP13; /*!< RTC backup register 13, Address offset: 0x84 */ + __IO uint32_t BAKP14; /*!< RTC backup register 14, Address offset: 0x88 */ + __IO uint32_t BAKP15; /*!< RTC backup register 15, Address offset: 0x8C */ + __IO uint32_t BAKP16; /*!< RTC backup register 16, Address offset: 0x90 */ + __IO uint32_t BAKP17; /*!< RTC backup register 17, Address offset: 0x94 */ + __IO uint32_t BAKP18; /*!< RTC backup register 18, Address offset: 0x98 */ + __IO uint32_t BAKP19; /*!< RTC backup register 19, Address offset: 0x9C */ +} RTC_TypeDef; + +/** + * @brief SD host Interface + */ + +typedef struct +{ + __IO uint32_t PWRCTRL; /*!< SDIO power control register, Address offset: 0x00 */ + __IO uint32_t CLKCTRL; /*!< SDI clock control register, Address offset: 0x04 */ + __IO uint32_t ARG; /*!< SDIO argument register, Address offset: 0x08 */ + __IO uint32_t CMD; /*!< SDIO command register, Address offset: 0x0C */ + __IO const uint32_t CMDRES; /*!< SDIO command response register, Address offset: 0x10 */ + __IO const uint32_t RES1; /*!< SDIO response 1 register, Address offset: 0x14 */ + __IO const uint32_t RES2; /*!< SDIO response 2 register, Address offset: 0x18 */ + __IO const uint32_t RES3; /*!< SDIO response 3 register, Address offset: 0x1C */ + __IO const uint32_t RES4; /*!< SDIO response 4 register, Address offset: 0x20 */ + __IO uint32_t DATATIME; /*!< SDIO data timer register, Address offset: 0x24 */ + __IO uint32_t DATALEN; /*!< SDIO data length register, Address offset: 0x28 */ + __IO uint32_t DCTRL; /*!< SDIO data control register, Address offset: 0x2C */ + __IO const uint32_t DCNT; /*!< SDIO data counter register, Address offset: 0x30 */ + __IO const uint32_t STS; /*!< SDIO status register, Address offset: 0x34 */ + __IO uint32_t ICF; /*!< SDIO interrupt clear register, Address offset: 0x38 */ + __IO uint32_t MASK; /*!< SDIO mask register, Address offset: 0x3C */ + uint32_t RESERVED0[2]; /*!< Reserved, 0x40-0x44 */ + __IO const uint32_t FIFOCNT; /*!< SDIO FIFO counter register, Address offset: 0x48 */ + uint32_t RESERVED1[13]; /*!< Reserved, 0x4C-0x7C */ + __IO uint32_t FIFODATA; /*!< SDIO data FIFO register, Address offset: 0x80 */ +} SDIO_TypeDef; + +/** + * @brief Serial Peripheral Interface + */ + +typedef struct +{ + __IO uint32_t CTRL1; /*!< SPI control register 1 (not used in I2S mode), Address offset: 0x00 */ + __IO uint32_t CTRL2; /*!< SPI control register 2, Address offset: 0x04 */ + __IO uint32_t STS; /*!< SPI status register, Address offset: 0x08 */ + __IO uint32_t DATA; /*!< SPI data register, Address offset: 0x0C */ + __IO uint32_t CRCPOLY; /*!< SPI CRC polynomial register (not used in I2S mode), Address offset: 0x10 */ + __IO uint32_t RXCRC; /*!< SPI RX CRC register (not used in I2S mode), Address offset: 0x14 */ + __IO uint32_t TXCRC; /*!< SPI TX CRC register (not used in I2S mode), Address offset: 0x18 */ + __IO uint32_t I2SCFG; /*!< SPI_I2S configuration register, Address offset: 0x1C */ + __IO uint32_t I2SPSC; /*!< SPI_I2S prescaler register, Address offset: 0x20 */ +} SPI_TypeDef; + + +/** + * @brief TMR + */ + +typedef struct +{ + __IO uint32_t CTRL1; /*!< TMR control register 1, Address offset: 0x00 */ + __IO uint32_t CTRL2; /*!< TMR control register 2, Address offset: 0x04 */ + __IO uint32_t SMCTRL; /*!< TMR slave mode control register, Address offset: 0x08 */ + __IO uint32_t DIEN; /*!< TMR DMA/interrupt enable register, Address offset: 0x0C */ + __IO uint32_t STS; /*!< TMR status register, Address offset: 0x10 */ + __IO uint32_t CEG; /*!< TMR event generation register, Address offset: 0x14 */ + __IO uint32_t CCM1; /*!< TMR capture/compare mode register 1, Address offset: 0x18 */ + __IO uint32_t CCM2; /*!< TMR capture/compare mode register 2, Address offset: 0x1C */ + __IO uint32_t CCEN; /*!< TMR capture/compare enable register, Address offset: 0x20 */ + __IO uint32_t CNT; /*!< TMR counter register, Address offset: 0x24 */ + __IO uint32_t PSC; /*!< TMR prescaler, Address offset: 0x28 */ + __IO uint32_t AUTORLD; /*!< TMR auto-reload register, Address offset: 0x2C */ + __IO uint32_t REPCNT; /*!< TMR repetition counter register, Address offset: 0x30 */ + __IO uint32_t CC1; /*!< TMR capture/compare register 1, Address offset: 0x34 */ + __IO uint32_t CC2; /*!< TMR capture/compare register 2, Address offset: 0x38 */ + __IO uint32_t CC3; /*!< TMR capture/compare register 3, Address offset: 0x3C */ + __IO uint32_t CC4; /*!< TMR capture/compare register 4, Address offset: 0x40 */ + __IO uint32_t BDT; /*!< TMR break and dead-time register, Address offset: 0x44 */ + __IO uint32_t DCTRL; /*!< TMR DMA control register, Address offset: 0x48 */ + __IO uint32_t DMAR; /*!< TMR DMA address for full transfer, Address offset: 0x4C */ + __IO uint32_t OR; /*!< TMR option register, Address offset: 0x50 */ +} TMR_TypeDef; + +/** + * @brief Universal Synchronous Asynchronous Receiver Transmitter + */ + +typedef struct +{ + __IO uint32_t STS; /*!< USART Status register, Address offset: 0x00 */ + __IO uint32_t DATA; /*!< USART Data register, Address offset: 0x04 */ + __IO uint32_t BR; /*!< USART Baud rate register, Address offset: 0x08 */ + __IO uint32_t CTRL1; /*!< USART Control register 1, Address offset: 0x0C */ + __IO uint32_t CTRL2; /*!< USART Control register 2, Address offset: 0x10 */ + __IO uint32_t CTRL3; /*!< USART Control register 3, Address offset: 0x14 */ + __IO uint32_t GTPSC; /*!< USART Guard time and prescaler register, Address offset: 0x18 */ +} USART_TypeDef; + +/** + * @brief Window WATCHDOG + */ + +typedef struct +{ + __IO uint32_t CTRL; /*!< WWDT Control register, Address offset: 0x00 */ + __IO uint32_t CFR; /*!< WWDT Configuration register, Address offset: 0x04 */ + __IO uint32_t STS; /*!< WWDT Status register, Address offset: 0x08 */ +} WWDT_TypeDef; + +/** + * @brief RNG + */ + +typedef struct +{ + __IO uint32_t CTRL; /*!< RNG control register, Address offset: 0x00 */ + __IO uint32_t STS; /*!< RNG status register, Address offset: 0x04 */ + __IO uint32_t DATA; /*!< RNG data register, Address offset: 0x08 */ +} RNG_TypeDef; + +/** + * @brief USB_OTG_Core_Registers + */ +typedef struct +{ + __IO uint32_t GCTRLSTS; /*!< USB_OTG Control and Status Register 000h */ + __IO uint32_t GINT; /*!< USB_OTG Interrupt Register 004h */ + __IO uint32_t GAHBCFG; /*!< Core AHB Configuration Register 008h */ + __IO uint32_t GUSBCFG; /*!< Core USB Configuration Register 00Ch */ + __IO uint32_t GRSTCTRL; /*!< Core Reset Register 010h */ + __IO uint32_t GCINT; /*!< Core Interrupt Register 014h */ + __IO uint32_t GINTMASK; /*!< Core Interrupt Mask Register 018h */ + __IO uint32_t GRXSTS; /*!< Receive Sts Q Read Register 01Ch */ + __IO uint32_t GRXSTSP; /*!< Receive Sts Q Read & POP Register 020h */ + __IO uint32_t GRXFIFO; /*!< Receive FIFO Size Register 024h */ + __IO uint32_t GTXFCFG; /*!< EP0 / Non Periodic Tx FIFO Size Register 028h */ + __IO uint32_t GNPTXFQSTS; /*!< Non Periodic Tx FIFO/Queue Sts reg 02Ch */ + uint32_t Reserved30[2]; /*!< Reserved 030h */ + __IO uint32_t GGCCFG; /*!< General Purpose IO Register 038h */ + __IO uint32_t GCID; /*!< User ID Register 03Ch */ + uint32_t Reserved40[48]; /*!< Reserved 0x40-0xFF */ + __IO uint32_t GHPTXFSIZE; /*!< Host Periodic Tx FIFO Size Reg 100h */ + __IO uint32_t DTXFIFO[0x0F]; /*!< dev Periodic Transmit FIFO */ +} USB_OTG_GlobalTypeDef; + +/** + * @brief USB_OTG_device_Registers + */ +typedef struct +{ + __IO uint32_t DCFG; /*!< dev Configuration Register 800h */ + __IO uint32_t DCTRL; /*!< dev Control Register 804h */ + __IO uint32_t DSTS; /*!< dev Status Register (RO) 808h */ + uint32_t Reserved0C; /*!< Reserved 80Ch */ + __IO uint32_t DINIMASK; /*!< dev IN Endpoint Mask 810h */ + __IO uint32_t DOUTIMASK; /*!< dev OUT Endpoint Mask 814h */ + __IO uint32_t DAEPINT; /*!< dev All Endpoints Itr Reg 818h */ + __IO uint32_t DAEPIMASK; /*!< dev All Endpoints Itr Mask 81Ch */ + uint32_t Reserved20; /*!< Reserved 820h */ + uint32_t Reserved9; /*!< Reserved 824h */ + __IO uint32_t DVBUSDTIM; /*!< dev VBUS discharge Register 828h */ + __IO uint32_t DVBUSPTIM; /*!< dev VBUS Pulse Register 82Ch */ + __IO uint32_t DTHCTRL; /*!< dev threshold 830h */ + __IO uint32_t DIEIMASK; /*!< dev empty msk 834h */ + __IO uint32_t DEPINT; /*!< dedicated EP interrupt 838h */ + __IO uint32_t DEPIMASK; /*!< dedicated EP msk 83Ch */ + uint32_t Reserved40; /*!< dedicated EP mask 840h */ + __IO uint32_t DIN1IMASK; /*!< dedicated EP mask 844h */ + uint32_t Reserved44[15]; /*!< Reserved 844-87Ch */ + __IO uint32_t DOUT1MASK; /*!< dedicated EP msk 884h */ +} USB_OTG_DeviceTypeDef; + +/** + * @brief USB_OTG_IN_Endpoint-Specific_Register + */ +typedef struct +{ + __IO uint32_t DIEPCTRL; /*!< dev IN Endpoint Control Reg 900h + (ep_num * 20h) + 00h */ + uint32_t Reserved04; /*!< Reserved 900h + (ep_num * 20h) + 04h */ + __IO uint32_t DIEPINT; /*!< dev IN Endpoint Itr Reg 900h + (ep_num * 20h) + 08h */ + uint32_t Reserved0C; /*!< Reserved 900h + (ep_num * 20h) + 0Ch */ + __IO uint32_t DIEPTRS; /*!< IN Endpoint Txfer Size 900h + (ep_num * 20h) + 10h */ + __IO uint32_t DIEPDMA; /*!< IN Endpoint DMA Address Reg 900h + (ep_num * 20h) + 14h */ + __IO uint32_t DITXFSTS; /*!< IN Endpoint Tx FIFO Status Reg 900h + (ep_num * 20h) + 18h */ + uint32_t Reserved18; /*!< Reserved 900h+(ep_num*20h)+1Ch-900h+ (ep_num * 20h) + 1Ch */ +} USB_OTG_INEndpointTypeDef; + +/** + * @brief USB_OTG_OUT_Endpoint-Specific_Registers + */ +typedef struct +{ + __IO uint32_t DOEPCTRL; /*!< dev OUT Endpoint Control Reg B00h + (ep_num * 20h) + 00h */ + uint32_t Reserved04; /*!< Reserved B00h + (ep_num * 20h) + 04h */ + __IO uint32_t DOEPINT; /*!< dev OUT Endpoint Itr Reg B00h + (ep_num * 20h) + 08h */ + uint32_t Reserved0C; /*!< Reserved B00h + (ep_num * 20h) + 0Ch */ + __IO uint32_t DOEPTRS; /*!< dev OUT Endpoint Txfer Size B00h + (ep_num * 20h) + 10h */ + __IO uint32_t DOEPDMA; /*!< dev OUT Endpoint DMA Address B00h + (ep_num * 20h) + 14h */ + uint32_t Reserved18[2]; /*!< Reserved B00h + (ep_num * 20h) + 18h - B00h + (ep_num * 20h) + 1Ch */ +} USB_OTG_OUTEndpointTypeDef; + +/** + * @brief USB_OTG_Host_Mode_Register_Structures + */ +typedef struct +{ + __IO uint32_t HCFG; /*!< Host Configuration Register 400h */ + __IO uint32_t HFIVL; /*!< Host Frame Interval Register 404h */ + __IO uint32_t HFIFM; /*!< Host Frame Nbr/Frame Remaining 408h */ + uint32_t Reserved40C; /*!< Reserved 40Ch */ + __IO uint32_t HPTXSTS; /*!< Host Periodic Tx FIFO/ Queue Status 410h */ + __IO uint32_t HACHINT; /*!< Host All Channels Interrupt Register 414h */ + __IO uint32_t HACHIMASK; /*!< Host All Channels Interrupt Mask 418h */ +} USB_OTG_HostTypeDef; + +/** + * @brief USB_OTG_Host_Channel_Specific_Registers + */ +typedef struct +{ + __IO uint32_t HCH; /*!< Host Channel Characteristics Register 500h */ + __IO uint32_t HCHSCTRL; /*!< Host Channel Split Control Register 504h */ + __IO uint32_t HCHINT; /*!< Host Channel Interrupt Register 508h */ + __IO uint32_t HCHIMASK; /*!< Host Channel Interrupt Mask Register 50Ch */ + __IO uint32_t HCHTSIZE; /*!< Host Channel Transfer Size Register 510h */ + __IO uint32_t HCHDMA; /*!< Host Channel DMA Address Register 514h */ + uint32_t Reserved[2]; /*!< Reserved */ +} USB_OTG_HostChannelTypeDef; + +/** + * @brief USB_OTG_HS2_Specific_Registers + */ +typedef struct +{ + __IO uint32_t USB_SWITCH; /*!< USB Switch Register 200h */ + __IO uint32_t POWERON_CORE; /*!< Power On Core Register 204h */ + __IO uint32_t USB_PLL_EN; /*!< USB PLL Enable Register 208h */ + __IO uint32_t SHORT_5V_ENABLE; /*!< VBUS Short 5V Enable 20Ch */ + __IO uint32_t OTG_SUSPENDM; /*!< OTG VBUS Suspend 210h */ + __IO uint32_t TXBITSTUFFENABLE; /*!< TX Bit Stuff Enable 214h */ + __IO uint32_t PLLICP_SEL_I2C; /*!< PLL Charge Current Setting 218h */ + __IO uint32_t HSZR_CNTL_I2C; /*!< The DP/DM to the Ground Impedance Setting 21Ch */ + __IO uint32_t SQVTH_CNTL_I2C; /*!< The SQ Reference Voltage Setting 220h*/ + __IO uint32_t SW_RREF_I2C; /*!< The DP/DM Output Swing Setting When HS Mode 224h */ + __IO uint32_t SW_BUF_I2C; /*!< The TX Driver Setting 228h */ + __IO uint32_t TX2RX_T_CFG_I2C; /*!< Debug Control Signal 22Ch */ + __IO uint32_t TEST_ANA_FAST_I2C; /*!< Debug Control Signal 230h */ + __IO uint32_t CLK_MODE_I2C; /*!< Debug control signal 234h */ + __IO uint32_t USB_DBNCE_FLTR_BYPASS; /*!< Bypass debounce filters for avalid, bvalid, vbusvalid, + sessend, iddig signals when enabled 238h */ + __IO uint32_t USB_SS_SCALEDOWN_MODE; /*!< Used only in simulation 23Ch */ +} USB_OTG_HS2TypeDef; + +/** + * @} + */ + +/** @addtogroup Peripheral_memory_map + * @{ + */ +#define FLASH_BASE 0x08000000UL /*!< FLASH(up to 1 MB) base address in the alias region */ +#define CCMDATARAM_BASE 0x10000000UL /*!< CCM(core coupled memory) data RAM(64 KB) base address in the alias region */ +#define SRAM1_BASE 0x20000000UL /*!< SRAM1(112 KB) base address in the alias region */ +#define SRAM2_BASE 0x2001C000UL /*!< SRAM2(16 KB) base address in the alias region */ +#define PERIPH_BASE 0x40000000UL /*!< Peripheral base address in the alias region */ +#define BKPSRAM_BASE 0x40024000UL /*!< Backup SRAM(4 KB) base address in the alias region */ +#define SMC_R_BASE 0xA0000000UL /*!< SMC registers base address */ +#define SRAM1_BB_BASE 0x22000000UL /*!< SRAM1(112 KB) base address in the bit-band region */ +#define SRAM2_BB_BASE 0x22380000UL /*!< SRAM2(16 KB) base address in the bit-band region */ +#define PERIPH_BB_BASE 0x42000000UL /*!< Peripheral base address in the bit-band region */ +#define BKPSRAM_BB_BASE 0x42480000UL /*!< Backup SRAM(4 KB) base address in the bit-band region */ +#define FLASH_END 0x080FFFFFUL /*!< FLASH end address */ +#define FLASH_OTP_BASE 0x1FFF7800UL /*!< Base address of : (up to 528 Bytes) embedded FLASH OTP Area */ +#define FLASH_OTP_END 0x1FFF7A0FUL /*!< End address of : (up to 528 Bytes) embedded FLASH OTP Area */ +#define CCMDATARAM_END 0x1000FFFFUL /*!< CCM data RAM end address */ + +/* Legacy defines */ +#define SRAM_BASE SRAM1_BASE +#define SRAM_BB_BASE SRAM1_BB_BASE + +/*!< Peripheral memory map */ +#define APB1PERIPH_BASE PERIPH_BASE +#define APB2PERIPH_BASE (PERIPH_BASE + 0x00010000UL) +#define AHB1PERIPH_BASE (PERIPH_BASE + 0x00020000UL) +#define AHB2PERIPH_BASE (PERIPH_BASE + 0x10000000UL) + +/*!< APB1 peripherals */ +#define TMR2_BASE (APB1PERIPH_BASE + 0x0000UL) +#define TMR3_BASE (APB1PERIPH_BASE + 0x0400UL) +#define TMR4_BASE (APB1PERIPH_BASE + 0x0800UL) +#define TMR5_BASE (APB1PERIPH_BASE + 0x0C00UL) +#define TMR6_BASE (APB1PERIPH_BASE + 0x1000UL) +#define TMR7_BASE (APB1PERIPH_BASE + 0x1400UL) +#define TMR12_BASE (APB1PERIPH_BASE + 0x1800UL) +#define TMR13_BASE (APB1PERIPH_BASE + 0x1C00UL) +#define TMR14_BASE (APB1PERIPH_BASE + 0x2000UL) +#define RTC_BASE (APB1PERIPH_BASE + 0x2800UL) +#define WWDT_BASE (APB1PERIPH_BASE + 0x2C00UL) +#define IWDT_BASE (APB1PERIPH_BASE + 0x3000UL) +#define I2S2ext_BASE (APB1PERIPH_BASE + 0x3400UL) +#define SPI2_BASE (APB1PERIPH_BASE + 0x3800UL) +#define SPI3_BASE (APB1PERIPH_BASE + 0x3C00UL) +#define I2S3ext_BASE (APB1PERIPH_BASE + 0x4000UL) +#define USART2_BASE (APB1PERIPH_BASE + 0x4400UL) +#define USART3_BASE (APB1PERIPH_BASE + 0x4800UL) +#define UART4_BASE (APB1PERIPH_BASE + 0x4C00UL) +#define UART5_BASE (APB1PERIPH_BASE + 0x5000UL) +#define I2C1_BASE (APB1PERIPH_BASE + 0x5400UL) +#define I2C2_BASE (APB1PERIPH_BASE + 0x5800UL) +#define I2C3_BASE (APB1PERIPH_BASE + 0x5C00UL) +#define CAN1_BASE (APB1PERIPH_BASE + 0x6400UL) +#define CAN2_BASE (APB1PERIPH_BASE + 0x6800UL) +#define PMU_BASE (APB1PERIPH_BASE + 0x7000UL) +#define DAC_BASE (APB1PERIPH_BASE + 0x7400UL) + +/*!< APB2 peripherals */ +#define TMR1_BASE (APB2PERIPH_BASE + 0x0000UL) +#define TMR8_BASE (APB2PERIPH_BASE + 0x0400UL) +#define USART1_BASE (APB2PERIPH_BASE + 0x1000UL) +#define USART6_BASE (APB2PERIPH_BASE + 0x1400UL) +#define ADC1_BASE (APB2PERIPH_BASE + 0x2000UL) +#define ADC2_BASE (APB2PERIPH_BASE + 0x2100UL) +#define ADC3_BASE (APB2PERIPH_BASE + 0x2200UL) +#define ADC123_COMMON_BASE (APB2PERIPH_BASE + 0x2300UL) +/* Legacy define */ +#define ADC_BASE ADC123_COMMON_BASE +#define SDIO_BASE (APB2PERIPH_BASE + 0x2C00UL) +#define SPI1_BASE (APB2PERIPH_BASE + 0x3000UL) +#define SYSCFG_BASE (APB2PERIPH_BASE + 0x3800UL) +#define EINT_BASE (APB2PERIPH_BASE + 0x3C00UL) +#define TMR9_BASE (APB2PERIPH_BASE + 0x4000UL) +#define TMR10_BASE (APB2PERIPH_BASE + 0x4400UL) +#define TMR11_BASE (APB2PERIPH_BASE + 0x4800UL) + +/*!< AHB1 peripherals */ +#define GPIOA_BASE (AHB1PERIPH_BASE + 0x0000UL) +#define GPIOB_BASE (AHB1PERIPH_BASE + 0x0400UL) +#define GPIOC_BASE (AHB1PERIPH_BASE + 0x0800UL) +#define GPIOD_BASE (AHB1PERIPH_BASE + 0x0C00UL) +#define GPIOE_BASE (AHB1PERIPH_BASE + 0x1000UL) +#define GPIOF_BASE (AHB1PERIPH_BASE + 0x1400UL) +#define GPIOG_BASE (AHB1PERIPH_BASE + 0x1800UL) +#define GPIOH_BASE (AHB1PERIPH_BASE + 0x1C00UL) +#define GPIOI_BASE (AHB1PERIPH_BASE + 0x2000UL) +#define CRC_BASE (AHB1PERIPH_BASE + 0x3000UL) +#define RCM_BASE (AHB1PERIPH_BASE + 0x3800UL) +#define FLASH_R_BASE (AHB1PERIPH_BASE + 0x3C00UL) +#define DMA1_BASE (AHB1PERIPH_BASE + 0x6000UL) +#define DMA1_Stream0_BASE (DMA1_BASE + 0x010UL) +#define DMA1_Stream1_BASE (DMA1_BASE + 0x028UL) +#define DMA1_Stream2_BASE (DMA1_BASE + 0x040UL) +#define DMA1_Stream3_BASE (DMA1_BASE + 0x058UL) +#define DMA1_Stream4_BASE (DMA1_BASE + 0x070UL) +#define DMA1_Stream5_BASE (DMA1_BASE + 0x088UL) +#define DMA1_Stream6_BASE (DMA1_BASE + 0x0A0UL) +#define DMA1_Stream7_BASE (DMA1_BASE + 0x0B8UL) +#define DMA2_BASE (AHB1PERIPH_BASE + 0x6400UL) +#define DMA2_Stream0_BASE (DMA2_BASE + 0x010UL) +#define DMA2_Stream1_BASE (DMA2_BASE + 0x028UL) +#define DMA2_Stream2_BASE (DMA2_BASE + 0x040UL) +#define DMA2_Stream3_BASE (DMA2_BASE + 0x058UL) +#define DMA2_Stream4_BASE (DMA2_BASE + 0x070UL) +#define DMA2_Stream5_BASE (DMA2_BASE + 0x088UL) +#define DMA2_Stream6_BASE (DMA2_BASE + 0x0A0UL) +#define DMA2_Stream7_BASE (DMA2_BASE + 0x0B8UL) +#define ETH_BASE (AHB1PERIPH_BASE + 0x8000UL) +#define ETH_MAC_BASE (ETH_BASE) +#define ETH_MMC_BASE (ETH_BASE + 0x0100UL) +#define ETH_PTP_BASE (ETH_BASE + 0x0700UL) +#define ETH_DMA_BASE (ETH_BASE + 0x1000UL) + +/*!< AHB2 peripherals */ +#define DCI_BASE (AHB2PERIPH_BASE + 0x50000UL) +#define RNG_BASE (AHB2PERIPH_BASE + 0x60800UL) + +/*!< SMC Bankx registers base address */ +#define SMC_Bank1_R_BASE (SMC_R_BASE + 0x0000UL) +#define SMC_Bank1E_R_BASE (SMC_R_BASE + 0x0104UL) +#define SMC_Bank2_3_R_BASE (SMC_R_BASE + 0x0060UL) +#define SMC_Bank4_R_BASE (SMC_R_BASE + 0x00A0UL) + +/*!< DMC registers base address */ +#define DMC_BASE ((uint32_t)0xA0000000UL) + +/*!< Debug MCU registers base address */ +#define DBGMCU_BASE 0xE0042000UL +/*!< USB registers base address */ +#define USB_OTG_HS2_PERIPH_BASE 0x40040200UL +#define USB_OTG_HS_PERIPH_BASE 0x40040000UL +#define USB_OTG_FS_PERIPH_BASE 0x50000000UL + +#define USB_OTG_GLOBAL_BASE 0x000UL +#define USB_OTG_DEVICE_BASE 0x800UL +#define USB_OTG_IN_ENDPOINT_BASE 0x900UL +#define USB_OTG_OUT_ENDPOINT_BASE 0xB00UL +#define USB_OTG_EP_REG_SIZE 0x20UL +#define USB_OTG_HOST_BASE 0x400UL +#define USB_OTG_HOST_PORT_BASE 0x440UL +#define USB_OTG_HOST_CHANNEL_BASE 0x500UL +#define USB_OTG_HOST_CHANNEL_SIZE 0x20UL +#define USB_OTG_PCGCCTL_BASE 0xE00UL +#define USB_OTG_FIFO_BASE 0x1000UL +#define USB_OTG_FIFO_SIZE 0x1000UL + +#define UID_BASE 0x1FFF7A10UL /*!< Unique device ID register base address */ +#define FLASHSIZE_BASE 0x1FFF7A22UL /*!< FLASH Size register base address */ +#define PACKAGE_BASE 0x1FFF7BF0UL /*!< Package size register base address */ +/** + * @} + */ + +/** @addtogroup Peripheral_declaration + * @{ + */ +#define TMR2 ((TMR_TypeDef *) TMR2_BASE) +#define TMR3 ((TMR_TypeDef *) TMR3_BASE) +#define TMR4 ((TMR_TypeDef *) TMR4_BASE) +#define TMR5 ((TMR_TypeDef *) TMR5_BASE) +#define TMR6 ((TMR_TypeDef *) TMR6_BASE) +#define TMR7 ((TMR_TypeDef *) TMR7_BASE) +#define TMR12 ((TMR_TypeDef *) TMR12_BASE) +#define TMR13 ((TMR_TypeDef *) TMR13_BASE) +#define TMR14 ((TMR_TypeDef *) TMR14_BASE) +#define RTC ((RTC_TypeDef *) RTC_BASE) +#define WWDT ((WWDT_TypeDef *) WWDT_BASE) +#define IWDT ((IWDT_TypeDef *) IWDT_BASE) +#define I2S2ext ((SPI_TypeDef *) I2S2ext_BASE) +#define SPI2 ((SPI_TypeDef *) SPI2_BASE) +#define SPI3 ((SPI_TypeDef *) SPI3_BASE) +#define I2S3ext ((SPI_TypeDef *) I2S3ext_BASE) +#define USART2 ((USART_TypeDef *) USART2_BASE) +#define USART3 ((USART_TypeDef *) USART3_BASE) +#define UART4 ((USART_TypeDef *) UART4_BASE) +#define UART5 ((USART_TypeDef *) UART5_BASE) +#define I2C1 ((I2C_TypeDef *) I2C1_BASE) +#define I2C2 ((I2C_TypeDef *) I2C2_BASE) +#define I2C3 ((I2C_TypeDef *) I2C3_BASE) +#define CAN1 ((CAN_TypeDef *) CAN1_BASE) +#define CAN2 ((CAN_TypeDef *) CAN2_BASE) +#define PMU ((PMU_TypeDef *) PMU_BASE) +#define DAC1 ((DAC_TypeDef *) DAC_BASE) +#define DAC ((DAC_TypeDef *) DAC_BASE) /* Kept for legacy purpose */ +#define TMR1 ((TMR_TypeDef *) TMR1_BASE) +#define TMR8 ((TMR_TypeDef *) TMR8_BASE) +#define USART1 ((USART_TypeDef *) USART1_BASE) +#define USART6 ((USART_TypeDef *) USART6_BASE) +#define ADC1 ((ADC_TypeDef *) ADC1_BASE) +#define ADC2 ((ADC_TypeDef *) ADC2_BASE) +#define ADC3 ((ADC_TypeDef *) ADC3_BASE) +#define ADC123_COMMON ((ADC_Common_TypeDef *) ADC123_COMMON_BASE) +/* Legacy define */ +#define ADC ADC123_COMMON +#define SDIO ((SDIO_TypeDef *) SDIO_BASE) +#define SPI1 ((SPI_TypeDef *) SPI1_BASE) +#define SYSCFG ((SYSCFG_TypeDef *) SYSCFG_BASE) +#define EINT ((EINT_TypeDef *) EINT_BASE) +#define TMR9 ((TMR_TypeDef *) TMR9_BASE) +#define TMR10 ((TMR_TypeDef *) TMR10_BASE) +#define TMR11 ((TMR_TypeDef *) TMR11_BASE) +#define GPIOA ((GPIO_TypeDef *) GPIOA_BASE) +#define GPIOB ((GPIO_TypeDef *) GPIOB_BASE) +#define GPIOC ((GPIO_TypeDef *) GPIOC_BASE) +#define GPIOD ((GPIO_TypeDef *) GPIOD_BASE) +#define GPIOE ((GPIO_TypeDef *) GPIOE_BASE) +#define GPIOF ((GPIO_TypeDef *) GPIOF_BASE) +#define GPIOG ((GPIO_TypeDef *) GPIOG_BASE) +#define GPIOH ((GPIO_TypeDef *) GPIOH_BASE) +#define GPIOI ((GPIO_TypeDef *) GPIOI_BASE) +#define CRC ((CRC_TypeDef *) CRC_BASE) +#define RCM ((RCM_TypeDef *) RCM_BASE) +#define FLASH ((FLASH_TypeDef *) FLASH_R_BASE) +#define DMA1 ((DMA_TypeDef *) DMA1_BASE) +#define DMA1_Stream0 ((DMA_Stream_TypeDef *) DMA1_Stream0_BASE) +#define DMA1_Stream1 ((DMA_Stream_TypeDef *) DMA1_Stream1_BASE) +#define DMA1_Stream2 ((DMA_Stream_TypeDef *) DMA1_Stream2_BASE) +#define DMA1_Stream3 ((DMA_Stream_TypeDef *) DMA1_Stream3_BASE) +#define DMA1_Stream4 ((DMA_Stream_TypeDef *) DMA1_Stream4_BASE) +#define DMA1_Stream5 ((DMA_Stream_TypeDef *) DMA1_Stream5_BASE) +#define DMA1_Stream6 ((DMA_Stream_TypeDef *) DMA1_Stream6_BASE) +#define DMA1_Stream7 ((DMA_Stream_TypeDef *) DMA1_Stream7_BASE) +#define DMA2 ((DMA_TypeDef *) DMA2_BASE) +#define DMA2_Stream0 ((DMA_Stream_TypeDef *) DMA2_Stream0_BASE) +#define DMA2_Stream1 ((DMA_Stream_TypeDef *) DMA2_Stream1_BASE) +#define DMA2_Stream2 ((DMA_Stream_TypeDef *) DMA2_Stream2_BASE) +#define DMA2_Stream3 ((DMA_Stream_TypeDef *) DMA2_Stream3_BASE) +#define DMA2_Stream4 ((DMA_Stream_TypeDef *) DMA2_Stream4_BASE) +#define DMA2_Stream5 ((DMA_Stream_TypeDef *) DMA2_Stream5_BASE) +#define DMA2_Stream6 ((DMA_Stream_TypeDef *) DMA2_Stream6_BASE) +#define DMA2_Stream7 ((DMA_Stream_TypeDef *) DMA2_Stream7_BASE) +#define ETH ((ETH_TypeDef *) ETH_BASE) +#define DCI ((DCI_TypeDef *) DCI_BASE) +#define RNG ((RNG_TypeDef *) RNG_BASE) +#define SMC_Bank1 ((SMC_Bank1_TypeDef *) SMC_Bank1_R_BASE) +#define SMC_Bank1E ((SMC_Bank1E_TypeDef *) SMC_Bank1E_R_BASE) +#define SMC_Bank2_3 ((SMC_Bank2_3_TypeDef *) SMC_Bank2_3_R_BASE) +#define SMC_Bank4 ((SMC_Bank4_TypeDef *) SMC_Bank4_R_BASE) +#define DBGMCU ((DBGMCU_TypeDef *) DBGMCU_BASE) +#define USB_OTG_FS ((USB_OTG_GlobalTypeDef *) USB_OTG_FS_PERIPH_BASE) +#define USB_OTG_HS ((USB_OTG_GlobalTypeDef *) USB_OTG_HS_PERIPH_BASE) +#define USB_OTG_HS2 ((USB_OTG_HS2TypeDef *) USB_OTG_HS2_PERIPH_BASE) +#define DMC ((DMC_TypeDef *) DMC_BASE) + +/** + * @} + */ + +/** @addtogroup Exported_constants + * @{ + */ + +/** @addtogroup Hardware_Constant_Definition + * @{ + */ +#define LSI_STARTUP_TIME 40U /*!< LSI Maximum startup time in us */ +/** + * @} + */ + + /** @addtogroup Peripheral_Registers_Bits_Definition + * @{ + */ + +/******************************************************************************/ +/* Peripheral Registers_Bits_Definition */ +/******************************************************************************/ + +/******************************************************************************/ +/* */ +/* Analog to Digital Converter */ +/* */ +/******************************************************************************/ +/* + * @brief Specific device feature definitions (not present on all devices in the APM32F4 serie) + */ +#define ADC_MULTIMODE_SUPPORT /*! + +/** @addtogroup Peripheral_registers_structures + * @{ + */ + +/** + * @brief Analog to Digital Converter + */ + +typedef struct +{ + __IO uint32_t STS; /*!< ADC status register, Address offset: 0x00 */ + __IO uint32_t CTRL1; /*!< ADC control register 1, Address offset: 0x04 */ + __IO uint32_t CTRL2; /*!< ADC control register 2, Address offset: 0x08 */ + __IO uint32_t SMPTIM1; /*!< ADC sample time register 1, Address offset: 0x0C */ + __IO uint32_t SMPTIM2; /*!< ADC sample time register 2, Address offset: 0x10 */ + __IO uint32_t INJDOF1; /*!< ADC injected channel data offset register 1, Address offset: 0x14 */ + __IO uint32_t INJDOF2; /*!< ADC injected channel data offset register 2, Address offset: 0x18 */ + __IO uint32_t INJDOF3; /*!< ADC injected channel data offset register 3, Address offset: 0x1C */ + __IO uint32_t INJDOF4; /*!< ADC injected channel data offset register 4, Address offset: 0x20 */ + __IO uint32_t AWDHT; /*!< ADC watchdog higher threshold register, Address offset: 0x24 */ + __IO uint32_t AWDLT; /*!< ADC watchdog lower threshold register, Address offset: 0x28 */ + __IO uint32_t REGSEQ1; /*!< ADC regular sequence register 1, Address offset: 0x2C */ + __IO uint32_t REGSEQ2; /*!< ADC regular sequence register 2, Address offset: 0x30 */ + __IO uint32_t REGSEQ3; /*!< ADC regular sequence register 3, Address offset: 0x34 */ + __IO uint32_t INJSEQ; /*!< ADC injected sequence register, Address offset: 0x38 */ + __IO uint32_t INJDATA1; /*!< ADC injected data register 1, Address offset: 0x3C */ + __IO uint32_t INJDATA2; /*!< ADC injected data register 2, Address offset: 0x40 */ + __IO uint32_t INJDATA3; /*!< ADC injected data register 3, Address offset: 0x44 */ + __IO uint32_t INJDATA4; /*!< ADC injected data register 4, Address offset: 0x48 */ + __IO uint32_t REGDATA; /*!< ADC regular data register, Address offset: 0x4C */ +} ADC_TypeDef; + +typedef struct +{ + __IO uint32_t RESERVED1; /*!< Reserved, 0x300 */ + __IO uint32_t CCTRL; /*!< ADC common control register, Address offset: ADC1 base address + 0x304 */ +} ADC_Common_TypeDef; + + +/** + * @brief Controller Area Network TxMailBox + */ + +typedef struct +{ + __IO uint32_t TXMID; /*!< CAN TX mailbox identifier register */ + __IO uint32_t TXDLEN; /*!< CAN mailbox data length control and time stamp register */ + __IO uint32_t TXMDL; /*!< CAN mailbox data low register */ + __IO uint32_t TXMDH; /*!< CAN mailbox data high register */ +} CAN_TxMailBox_TypeDef; + +/** + * @brief Controller Area Network FIFOMailBox + */ + +typedef struct +{ + __IO uint32_t RXMID; /*!< CAN receive FIFO mailbox identifier register */ + __IO uint32_t RXDLEN; /*!< CAN receive FIFO mailbox data length control and time stamp register */ + __IO uint32_t RXMDL; /*!< CAN receive FIFO mailbox data low register */ + __IO uint32_t RXMDH; /*!< CAN receive FIFO mailbox data high register */ +} CAN_FIFOMailBox_TypeDef; + +/** + * @brief Controller Area Network FilterRegister + */ + +typedef struct +{ + __IO uint32_t FBANK1; /*!< CAN Filter bank register 1 */ + __IO uint32_t FBANK2; /*!< CAN Filter bank register 1 */ +} CAN_FilterRegister_TypeDef; + +/** + * @brief Controller Area Network + */ + +typedef struct +{ + __IO uint32_t MCTRL; /*!< CAN master control register, Address offset: 0x00 */ + __IO uint32_t MSTS; /*!< CAN master status register, Address offset: 0x04 */ + __IO uint32_t TXSTS; /*!< CAN transmit status register, Address offset: 0x08 */ + __IO uint32_t RXF0; /*!< CAN receive FIFO 0 register, Address offset: 0x0C */ + __IO uint32_t RXF1; /*!< CAN receive FIFO 1 register, Address offset: 0x10 */ + __IO uint32_t INTEN; /*!< CAN interrupt enable register, Address offset: 0x14 */ + __IO uint32_t ERRSTS; /*!< CAN error status register, Address offset: 0x18 */ + __IO uint32_t BITTIM; /*!< CAN bit timing register, Address offset: 0x1C */ + uint32_t RESERVED0[88]; /*!< Reserved, 0x020 - 0x17F */ + CAN_TxMailBox_TypeDef sTxMailBox[3]; /*!< CAN Tx MailBox, Address offset: 0x180 - 0x1AC */ + CAN_FIFOMailBox_TypeDef sFIFOMailBox[2]; /*!< CAN FIFO MailBox, Address offset: 0x1B0 - 0x1CC */ + uint32_t RESERVED1[12]; /*!< Reserved, 0x1D0 - 0x1FF */ + __IO uint32_t FCTRL; /*!< CAN filter master register, Address offset: 0x200 */ + __IO uint32_t FMCFG; /*!< CAN filter mode register, Address offset: 0x204 */ + uint32_t RESERVED2; /*!< Reserved, 0x208 */ + __IO uint32_t FSCFG; /*!< CAN filter scale register, Address offset: 0x20C */ + uint32_t RESERVED3; /*!< Reserved, 0x210 */ + __IO uint32_t FFASS; /*!< CAN filter FIFO assignment register, Address offset: 0x214 */ + uint32_t RESERVED4; /*!< Reserved, 0x218 */ + __IO uint32_t FACT; /*!< CAN filter activation register, Address offset: 0x21C */ + uint32_t RESERVED5[8]; /*!< Reserved, 0x220-0x23F */ + CAN_FilterRegister_TypeDef sFilterRegister[28]; /*!< CAN Filter Register, Address offset: 0x240-0x31C */ +} CAN_TypeDef; + +/** + * @brief CRC calculation unit + */ + +typedef struct +{ + __IO uint32_t DATA; /*!< CRC Data register, Address offset: 0x00 */ + __IO uint8_t INDATA; /*!< CRC Independent data register, Address offset: 0x04 */ + uint8_t RESERVED0; /*!< Reserved, 0x05 */ + uint16_t RESERVED1; /*!< Reserved, 0x06 */ + __IO uint32_t CTRL; /*!< CRC Control register, Address offset: 0x08 */ +} CRC_TypeDef; + +/** + * @brief Debug MCU + */ + +typedef struct +{ + __IO uint32_t IDCODE; /*!< MCU device ID code, Address offset: 0x00 */ + __IO uint32_t CFG; /*!< Debug MCU configuration register, Address offset: 0x04 */ + __IO uint32_t APB1F; /*!< Debug MCU APB1 freeze register, Address offset: 0x08 */ + __IO uint32_t APB2F; /*!< Debug MCU APB2 freeze register, Address offset: 0x0C */ +} DBGMCU_TypeDef; + +/** + * @brief DMA Controller + */ + +typedef struct +{ + __IO uint32_t SCFG; /*!< DMA stream x configuration register */ + __IO uint32_t NDATA; /*!< DMA stream x number of data register */ + __IO uint32_t PADDR; /*!< DMA stream x peripheral address register */ + __IO uint32_t M0ADDR; /*!< DMA stream x memory 0 address register */ + __IO uint32_t M1ADDR; /*!< DMA stream x memory 1 address register */ + __IO uint32_t FCTRL; /*!< DMA stream x FIFO control register */ +} DMA_Stream_TypeDef; + +typedef struct +{ + __IO uint32_t LINTSTS; /*!< DMA low interrupt status register, Address offset: 0x00 */ + __IO uint32_t HINTSTS; /*!< DMA high interrupt status register, Address offset: 0x04 */ + __IO uint32_t LIFCLR; /*!< DMA low interrupt flag clear register, Address offset: 0x08 */ + __IO uint32_t HIFCLR; /*!< DMA high interrupt flag clear register, Address offset: 0x0C */ +} DMA_TypeDef; + +/** + * @brief External Interrupt/Event Controller + */ + +typedef struct +{ + __IO uint32_t IMASK; /*!< EINT Interrupt mask register, Address offset: 0x00 */ + __IO uint32_t EMASK; /*!< EINT Event mask register, Address offset: 0x04 */ + __IO uint32_t RTEN; /*!< EINT Rising trigger selection register, Address offset: 0x08 */ + __IO uint32_t FTEN; /*!< EINT Falling trigger selection register, Address offset: 0x0C */ + __IO uint32_t SWINTE; /*!< EINT Software interrupt event register, Address offset: 0x10 */ + __IO uint32_t IPEND; /*!< EINT Pending register, Address offset: 0x14 */ +} EINT_TypeDef; + +/** + * @brief FLASH Registers + */ + +typedef struct +{ + __IO uint32_t ACCTRL; /*!< FLASH access control register, Address offset: 0x00 */ + __IO uint32_t KEY; /*!< FLASH key register, Address offset: 0x04 */ + __IO uint32_t OPTKEY; /*!< FLASH option key register, Address offset: 0x08 */ + __IO uint32_t STS; /*!< FLASH status register, Address offset: 0x0C */ + __IO uint32_t CTRL; /*!< FLASH control register, Address offset: 0x10 */ + __IO uint32_t OPTCTRL; /*!< FLASH option control register , Address offset: 0x14 */ + __IO uint32_t OPTCTRL1; /*!< FLASH option control register 1, Address offset: 0x18 */ +} FLASH_TypeDef; + +/** + * @brief Flexible Static Memory Controller + */ + +typedef struct +{ + __IO uint32_t CSTR[8]; /*!< NOR/PSRAM chip-select control register(CSCTRL) and chip-select timing register(CSTIM), Address offset: 0x00-1C */ +} SMC_Bank1_TypeDef; + +/** + * @brief Flexible Static Memory Controller Bank1E + */ + +typedef struct +{ + __IO uint32_t WRTTIM[7]; /*!< NOR/PSRAM write timing registers, Address offset: 0x104-0x11C */ +} SMC_Bank1E_TypeDef; + +/** + * @brief Flexible Static Memory Controller Bank2 + */ + +typedef struct +{ + __IO uint32_t CTRL2; /*!< NAND Flash control register 2, Address offset: 0x60 */ + __IO uint32_t STSINT2; /*!< NAND Flash FIFO status and interrupt register 2, Address offset: 0x64 */ + __IO uint32_t CMSTIM2; /*!< NAND Flash Common memory space timing register 2, Address offset: 0x68 */ + __IO uint32_t AMSTIM2; /*!< NAND Flash Attribute memory space timing register 2, Address offset: 0x6C */ + uint32_t RESERVED0; /*!< Reserved, 0x70 */ + __IO uint32_t ECCRS2; /*!< NAND Flash ECC result registers 2, Address offset: 0x74 */ + uint32_t RESERVED1; /*!< Reserved, 0x78 */ + uint32_t RESERVED2; /*!< Reserved, 0x7C */ + __IO uint32_t CTRL3; /*!< NAND Flash control register 3, Address offset: 0x80 */ + __IO uint32_t STSINT3; /*!< NAND Flash FIFO status and interrupt register 3, Address offset: 0x84 */ + __IO uint32_t CMSTIM3; /*!< NAND Flash Common memory space timing register 3, Address offset: 0x88 */ + __IO uint32_t AMSTIM3; /*!< NAND Flash Attribute memory space timing register 3, Address offset: 0x8C */ + uint32_t RESERVED3; /*!< Reserved, 0x90 */ + __IO uint32_t ECCRS3; /*!< NAND Flash ECC result registers 3, Address offset: 0x94 */ +} SMC_Bank2_3_TypeDef; + +/** + * @brief Flexible Static Memory Controller Bank4 + */ + +typedef struct +{ + __IO uint32_t CTRL4; /*!< PC Card control register 4, Address offset: 0xA0 */ + __IO uint32_t STSINT4; /*!< PC Card FIFO status and interrupt register 4, Address offset: 0xA4 */ + __IO uint32_t CMSTIM4; /*!< PC Card Common memory space timing register 4, Address offset: 0xA8 */ + __IO uint32_t AMSTIM4; /*!< PC Card Attribute memory space timing register 4, Address offset: 0xAC */ + __IO uint32_t IOSTIM4; /*!< PC Card I/O space timing register 4, Address offset: 0xB0 */ +} SMC_Bank4_TypeDef; + +/** + * @brief General Purpose I/O + */ + +typedef struct +{ + __IO uint32_t MODE; /*!< GPIO port mode register, Address offset: 0x00 */ + __IO uint32_t OMODE; /*!< GPIO port output type register, Address offset: 0x04 */ + __IO uint32_t OSSEL; /*!< GPIO port output speed register, Address offset: 0x08 */ + __IO uint32_t PUPD; /*!< GPIO port pull-up/pull-down register, Address offset: 0x0C */ + __IO uint32_t IDATA; /*!< GPIO port input data register, Address offset: 0x10 */ + __IO uint32_t ODATA; /*!< GPIO port output data register, Address offset: 0x14 */ + __IO uint32_t BSC; /*!< GPIO port bit set/reset register, Address offset: 0x18 */ + __IO uint32_t LOCK; /*!< GPIO port configuration lock register, Address offset: 0x1C */ + __IO uint32_t ALF[2]; /*!< GPIO alternate function registers, Address offset: 0x20-0x24 */ +} GPIO_TypeDef; + +/** + * @brief System configuration controller + */ + +typedef struct +{ + __IO uint32_t MMSEL; /*!< SYSCFG memory remap register, Address offset: 0x00 */ + __IO uint32_t PMCFG; /*!< SYSCFG peripheral mode configuration register, Address offset: 0x04 */ + __IO uint32_t EINTCFG[4]; /*!< SYSCFG external interrupt configuration registers, Address offset: 0x08-0x14 */ + uint32_t RESERVED[2]; /*!< Reserved, 0x18-0x1C */ + __IO uint32_t CCCTRL; /*!< SYSCFG Compensation cell control register, Address offset: 0x20 */ +} SYSCFG_TypeDef; + +/** + * @brief Inter-integrated Circuit Interface + */ + +typedef struct +{ + __IO uint32_t CTRL1; /*!< I2C Control register 1, Address offset: 0x00 */ + __IO uint32_t CTRL2; /*!< I2C Control register 2, Address offset: 0x04 */ + __IO uint32_t SADDR1; /*!< I2C Own address register 1, Address offset: 0x08 */ + __IO uint32_t SADDR2; /*!< I2C Own address register 2, Address offset: 0x0C */ + __IO uint32_t DATA; /*!< I2C Data register, Address offset: 0x10 */ + __IO uint32_t STS1; /*!< I2C Status register 1, Address offset: 0x14 */ + __IO uint32_t STS2; /*!< I2C Status register 2, Address offset: 0x18 */ + __IO uint32_t CLKCTRL; /*!< I2C Clock control register, Address offset: 0x1C */ + __IO uint32_t RISETMAX; /*!< I2C RISETMAX register, Address offset: 0x20 */ + __IO uint32_t FILTER; /*!< I2C Filter register, Address offset: 0x24 */ +} I2C_TypeDef; + +/** + * @brief Independent WATCHDOG + */ + +typedef struct +{ + __IO uint32_t KEY; /*!< IWDT Key register, Address offset: 0x00 */ + __IO uint32_t PSC; /*!< IWDT Prescaler register, Address offset: 0x04 */ + __IO uint32_t CNTRLD; /*!< IWDT Reload register, Address offset: 0x08 */ + __IO uint32_t STS; /*!< IWDT Status register, Address offset: 0x0C */ +} IWDT_TypeDef; + + +/** + * @brief Power Control + */ + +typedef struct +{ + __IO uint32_t CTRL; /*!< PMU power control register, Address offset: 0x00 */ + __IO uint32_t CSTS; /*!< PMU power control/status register, Address offset: 0x04 */ +} PMU_TypeDef; + +/** + * @brief Reset and Clock Control + */ + +typedef struct +{ + __IO uint32_t CTRL; /*!< RCM clock control register, Address offset: 0x00 */ + __IO uint32_t PLL1CFG; /*!< RCM PLL configuration register, Address offset: 0x04 */ + __IO uint32_t CFG; /*!< RCM clock configuration register, Address offset: 0x08 */ + __IO uint32_t INT; /*!< RCM clock interrupt register, Address offset: 0x0C */ + __IO uint32_t AHB1RST; /*!< RCM AHB1 peripheral reset register, Address offset: 0x10 */ + __IO uint32_t AHB2RST; /*!< RCM AHB2 peripheral reset register, Address offset: 0x14 */ + __IO uint32_t AHB3RST; /*!< RCM AHB3 peripheral reset register, Address offset: 0x18 */ + uint32_t RESERVED0; /*!< Reserved, 0x1C */ + __IO uint32_t APB1RST; /*!< RCM APB1 peripheral reset register, Address offset: 0x20 */ + __IO uint32_t APB2RST; /*!< RCM APB2 peripheral reset register, Address offset: 0x24 */ + uint32_t RESERVED1[2]; /*!< Reserved, 0x28-0x2C */ + __IO uint32_t AHB1CLKEN; /*!< RCM AHB1 peripheral clock register, Address offset: 0x30 */ + __IO uint32_t AHB2CLKEN; /*!< RCM AHB2 peripheral clock register, Address offset: 0x34 */ + __IO uint32_t AHB3CLKEN; /*!< RCM AHB3 peripheral clock register, Address offset: 0x38 */ + uint32_t RESERVED2; /*!< Reserved, 0x3C */ + __IO uint32_t APB1CLKEN; /*!< RCM APB1 peripheral clock enable register, Address offset: 0x40 */ + __IO uint32_t APB2CLKEN; /*!< RCM APB2 peripheral clock enable register, Address offset: 0x44 */ + uint32_t RESERVED3[2]; /*!< Reserved, 0x48-0x4C */ + __IO uint32_t LPAHB1CLKEN; /*!< RCM AHB1 peripheral clock enable in low power mode register, Address offset: 0x50 */ + __IO uint32_t LPAHB2CLKEN; /*!< RCM AHB2 peripheral clock enable in low power mode register, Address offset: 0x54 */ + __IO uint32_t LPAHB3CLKEN; /*!< RCM AHB3 peripheral clock enable in low power mode register, Address offset: 0x58 */ + uint32_t RESERVED4; /*!< Reserved, 0x5C */ + __IO uint32_t LPAPB1CLKEN; /*!< RCM APB1 peripheral clock enable in low power mode register, Address offset: 0x60 */ + __IO uint32_t LPAPB2CLKEN; /*!< RCM APB2 peripheral clock enable in low power mode register, Address offset: 0x64 */ + uint32_t RESERVED5[2]; /*!< Reserved, 0x68-0x6C */ + __IO uint32_t BDCTRL; /*!< RCM Backup domain control register, Address offset: 0x70 */ + __IO uint32_t CSTS; /*!< RCM clock control & status register, Address offset: 0x74 */ + uint32_t RESERVED6[2]; /*!< Reserved, 0x78-0x7C */ + __IO uint32_t SSCCFG; /*!< RCM spread spectrum clock generation register, Address offset: 0x80 */ + __IO uint32_t PLL2CFG; /*!< RCM PLLI2S configuration register, Address offset: 0x84 */ + uint32_t RESERVED7; /*!< Reserved, 0x88 */ + __IO uint32_t CFGSEL; /*!< RCM clock configuration select register, Address offset: 0x8C */ +} RCM_TypeDef; + +/** + * @brief Real-Time Clock + */ + +typedef struct +{ + __IO uint32_t TIME; /*!< RTC time register, Address offset: 0x00 */ + __IO uint32_t DATE; /*!< RTC date register, Address offset: 0x04 */ + __IO uint32_t CTRL; /*!< RTC control register, Address offset: 0x08 */ + __IO uint32_t STS; /*!< RTC initialization and status register, Address offset: 0x0C */ + __IO uint32_t PSC; /*!< RTC prescaler register, Address offset: 0x10 */ + __IO uint32_t AUTORLD; /*!< RTC wakeup timer register, Address offset: 0x14 */ + __IO uint32_t DCAL; /*!< RTC calibration register, Address offset: 0x18 */ + __IO uint32_t ALRMA; /*!< RTC alarm A register, Address offset: 0x1C */ + __IO uint32_t ALRMB; /*!< RTC alarm B register, Address offset: 0x20 */ + __IO uint32_t WRPROT; /*!< RTC write protection register, Address offset: 0x24 */ + __IO uint32_t SUBSEC; /*!< RTC sub second register, Address offset: 0x28 */ + __IO uint32_t SHIFT; /*!< RTC shift control register, Address offset: 0x2C */ + __IO uint32_t TSTIME; /*!< RTC time stamp time register, Address offset: 0x30 */ + __IO uint32_t TSDATE; /*!< RTC time stamp date register, Address offset: 0x34 */ + __IO uint32_t TSSUBSEC; /*!< RTC time-stamp sub second register, Address offset: 0x38 */ + __IO uint32_t CAL; /*!< RTC calibration register, Address offset: 0x3C */ + __IO uint32_t TACFG; /*!< RTC tamper and alternate function configuration register, Address offset: 0x40 */ + __IO uint32_t ALRMASS; /*!< RTC alarm A sub second register, Address offset: 0x44 */ + __IO uint32_t ALRMBSS; /*!< RTC alarm B sub second register, Address offset: 0x48 */ + uint32_t RESERVED7; /*!< Reserved, 0x4C */ + __IO uint32_t BAKP0; /*!< RTC backup register 1, Address offset: 0x50 */ + __IO uint32_t BAKP1; /*!< RTC backup register 1, Address offset: 0x54 */ + __IO uint32_t BAKP2; /*!< RTC backup register 2, Address offset: 0x58 */ + __IO uint32_t BAKP3; /*!< RTC backup register 3, Address offset: 0x5C */ + __IO uint32_t BAKP4; /*!< RTC backup register 4, Address offset: 0x60 */ + __IO uint32_t BAKP5; /*!< RTC backup register 5, Address offset: 0x64 */ + __IO uint32_t BAKP6; /*!< RTC backup register 6, Address offset: 0x68 */ + __IO uint32_t BAKP7; /*!< RTC backup register 7, Address offset: 0x6C */ + __IO uint32_t BAKP8; /*!< RTC backup register 8, Address offset: 0x70 */ + __IO uint32_t BAKP9; /*!< RTC backup register 9, Address offset: 0x74 */ + __IO uint32_t BAKP10; /*!< RTC backup register 10, Address offset: 0x78 */ + __IO uint32_t BAKP11; /*!< RTC backup register 11, Address offset: 0x7C */ + __IO uint32_t BAKP12; /*!< RTC backup register 12, Address offset: 0x80 */ + __IO uint32_t BAKP13; /*!< RTC backup register 13, Address offset: 0x84 */ + __IO uint32_t BAKP14; /*!< RTC backup register 14, Address offset: 0x88 */ + __IO uint32_t BAKP15; /*!< RTC backup register 15, Address offset: 0x8C */ + __IO uint32_t BAKP16; /*!< RTC backup register 16, Address offset: 0x90 */ + __IO uint32_t BAKP17; /*!< RTC backup register 17, Address offset: 0x94 */ + __IO uint32_t BAKP18; /*!< RTC backup register 18, Address offset: 0x98 */ + __IO uint32_t BAKP19; /*!< RTC backup register 19, Address offset: 0x9C */ +} RTC_TypeDef; + +/** + * @brief SD host Interface + */ + +typedef struct +{ + __IO uint32_t PWRCTRL; /*!< SDIO power control register, Address offset: 0x00 */ + __IO uint32_t CLKCTRL; /*!< SDI clock control register, Address offset: 0x04 */ + __IO uint32_t ARG; /*!< SDIO argument register, Address offset: 0x08 */ + __IO uint32_t CMD; /*!< SDIO command register, Address offset: 0x0C */ + __IO const uint32_t CMDRES; /*!< SDIO command response register, Address offset: 0x10 */ + __IO const uint32_t RES1; /*!< SDIO response 1 register, Address offset: 0x14 */ + __IO const uint32_t RES2; /*!< SDIO response 2 register, Address offset: 0x18 */ + __IO const uint32_t RES3; /*!< SDIO response 3 register, Address offset: 0x1C */ + __IO const uint32_t RES4; /*!< SDIO response 4 register, Address offset: 0x20 */ + __IO uint32_t DATATIME; /*!< SDIO data timer register, Address offset: 0x24 */ + __IO uint32_t DATALEN; /*!< SDIO data length register, Address offset: 0x28 */ + __IO uint32_t DCTRL; /*!< SDIO data control register, Address offset: 0x2C */ + __IO const uint32_t DCNT; /*!< SDIO data counter register, Address offset: 0x30 */ + __IO const uint32_t STS; /*!< SDIO status register, Address offset: 0x34 */ + __IO uint32_t ICF; /*!< SDIO interrupt clear register, Address offset: 0x38 */ + __IO uint32_t MASK; /*!< SDIO mask register, Address offset: 0x3C */ + uint32_t RESERVED0[2]; /*!< Reserved, 0x40-0x44 */ + __IO const uint32_t FIFOCNT; /*!< SDIO FIFO counter register, Address offset: 0x48 */ + uint32_t RESERVED1[13]; /*!< Reserved, 0x4C-0x7C */ + __IO uint32_t FIFODATA; /*!< SDIO data FIFO register, Address offset: 0x80 */ +} SDIO_TypeDef; + +/** + * @brief Serial Peripheral Interface + */ + +typedef struct +{ + __IO uint32_t CTRL1; /*!< SPI control register 1 (not used in I2S mode), Address offset: 0x00 */ + __IO uint32_t CTRL2; /*!< SPI control register 2, Address offset: 0x04 */ + __IO uint32_t STS; /*!< SPI status register, Address offset: 0x08 */ + __IO uint32_t DATA; /*!< SPI data register, Address offset: 0x0C */ + __IO uint32_t CRCPOLY; /*!< SPI CRC polynomial register (not used in I2S mode), Address offset: 0x10 */ + __IO uint32_t RXCRC; /*!< SPI RX CRC register (not used in I2S mode), Address offset: 0x14 */ + __IO uint32_t TXCRC; /*!< SPI TX CRC register (not used in I2S mode), Address offset: 0x18 */ + __IO uint32_t I2SCFG; /*!< SPI_I2S configuration register, Address offset: 0x1C */ + __IO uint32_t I2SPSC; /*!< SPI_I2S prescaler register, Address offset: 0x20 */ +} SPI_TypeDef; + + +/** + * @brief TMR + */ + +typedef struct +{ + __IO uint32_t CTRL1; /*!< TMR control register 1, Address offset: 0x00 */ + __IO uint32_t CTRL2; /*!< TMR control register 2, Address offset: 0x04 */ + __IO uint32_t SMCTRL; /*!< TMR slave mode control register, Address offset: 0x08 */ + __IO uint32_t DIEN; /*!< TMR DMA/interrupt enable register, Address offset: 0x0C */ + __IO uint32_t STS; /*!< TMR status register, Address offset: 0x10 */ + __IO uint32_t CEG; /*!< TMR event generation register, Address offset: 0x14 */ + __IO uint32_t CCM1; /*!< TMR capture/compare mode register 1, Address offset: 0x18 */ + __IO uint32_t CCM2; /*!< TMR capture/compare mode register 2, Address offset: 0x1C */ + __IO uint32_t CCEN; /*!< TMR capture/compare enable register, Address offset: 0x20 */ + __IO uint32_t CNT; /*!< TMR counter register, Address offset: 0x24 */ + __IO uint32_t PSC; /*!< TMR prescaler, Address offset: 0x28 */ + __IO uint32_t AUTORLD; /*!< TMR auto-reload register, Address offset: 0x2C */ + __IO uint32_t REPCNT; /*!< TMR repetition counter register, Address offset: 0x30 */ + __IO uint32_t CC1; /*!< TMR capture/compare register 1, Address offset: 0x34 */ + __IO uint32_t CC2; /*!< TMR capture/compare register 2, Address offset: 0x38 */ + __IO uint32_t CC3; /*!< TMR capture/compare register 3, Address offset: 0x3C */ + __IO uint32_t CC4; /*!< TMR capture/compare register 4, Address offset: 0x40 */ + __IO uint32_t BDT; /*!< TMR break and dead-time register, Address offset: 0x44 */ + __IO uint32_t DCTRL; /*!< TMR DMA control register, Address offset: 0x48 */ + __IO uint32_t DMAR; /*!< TMR DMA address for full transfer, Address offset: 0x4C */ + __IO uint32_t OR; /*!< TMR option register, Address offset: 0x50 */ +} TMR_TypeDef; + +/** + * @brief Universal Synchronous Asynchronous Receiver Transmitter + */ + +typedef struct +{ + __IO uint32_t STS; /*!< USART Status register, Address offset: 0x00 */ + __IO uint32_t DATA; /*!< USART Data register, Address offset: 0x04 */ + __IO uint32_t BR; /*!< USART Baud rate register, Address offset: 0x08 */ + __IO uint32_t CTRL1; /*!< USART Control register 1, Address offset: 0x0C */ + __IO uint32_t CTRL2; /*!< USART Control register 2, Address offset: 0x10 */ + __IO uint32_t CTRL3; /*!< USART Control register 3, Address offset: 0x14 */ + __IO uint32_t GTPSC; /*!< USART Guard time and prescaler register, Address offset: 0x18 */ +} USART_TypeDef; + +/** + * @brief Window WATCHDOG + */ + +typedef struct +{ + __IO uint32_t CTRL; /*!< WWDT Control register, Address offset: 0x00 */ + __IO uint32_t CFR; /*!< WWDT Configuration register, Address offset: 0x04 */ + __IO uint32_t STS; /*!< WWDT Status register, Address offset: 0x08 */ +} WWDT_TypeDef; + +/** + * @brief RNG + */ + +typedef struct +{ + __IO uint32_t CTRL; /*!< RNG control register, Address offset: 0x00 */ + __IO uint32_t STS; /*!< RNG status register, Address offset: 0x04 */ + __IO uint32_t DATA; /*!< RNG data register, Address offset: 0x08 */ +} RNG_TypeDef; + +/** + * @brief Quick Serial peripheral interface + */ + +typedef struct +{ + __IO uint32_t CTRL1; /*!< QSPI control register 1, Address offset: 0x00 */ + __IO uint32_t CTRL2; /*!< QSPI control register 2, Address offset: 0x04 */ + __IO uint32_t SSIEN; /*!< QSPI enable register, Address offset: 0x08 */ + __IO uint32_t RESERVED0; /*!< Reserved, Address offset: 0x0C */ + __IO uint32_t SLAEN; /*!< QSPI slave enable register, Address offset: 0x10 */ + __IO uint32_t BR; /*!< QSPI baud rate register, Address offset: 0x14 */ + __IO uint32_t TFTL; /*!< QSPI transmit FIFO threshold level register, Address offset: 0x18 */ + __IO uint32_t RFTL; /*!< QSPI receive FIFO threshold level register, Address offset: 0x1C */ + __IO uint32_t TFL; /*!< QSPI transmit FIFO level register, Address offset: 0x20 */ + __IO uint32_t RFL; /*!< QSPI receive FIFO level register, Address offset: 0x24 */ + __IO uint32_t STS; /*!< QSPI status register, Address offset: 0x28 */ + __IO uint32_t INTEN; /*!< QSPI interrupt enable register, Address offset: 0x2C */ + __IO uint32_t ISTS; /*!< QSPI interrupt status register, Address offset: 0x30 */ + __IO uint32_t RIS; /*!< QSPI raw interrupt status register, Address offset: 0x34 */ + __IO uint32_t TFOIC; /*!< QSPI transmit FIFO overflow interrupt clear register, Address offset: 0x38 */ + __IO uint32_t RFOIC; /*!< QSPI receive FIFO overflow interrupt clear register, Address offset: 0x3C */ + __IO uint32_t RFUIC; /*!< QSPI receive FIFO underflow interrupt clear register, Address offset: 0x40 */ + __IO uint32_t MIC; /*!< QSPI master interrupt clear register, Address offset: 0x44 */ + __IO uint32_t ICF; /*!< QSPI interrupt clear flag register, Address offset: 0x48 */ + __IO uint32_t DMACTRL; /*!< QSPI DMA control register, Address offset: 0x4C */ + __IO uint32_t DMATDL; /*!< QSPI DMA transmit data level register, Address offset: 0x50 */ + __IO uint32_t DMARDL; /*!< QSPI DMA receive data level register, Address offset: 0x54 */ + __IO uint32_t RESERVED1[2]; /*!< Reserved, Address offset: 0x58-0x5C */ + __IO uint32_t DATA; /*!< QSPI data register, Address offset: 0x60 */ + __IO uint32_t RESERVED2[35]; /*!< Reserved, Address offset: 0x64-0xEC */ + __IO uint32_t RSD; /*!< QSPI receive sample delay register, Address offset: 0xF0 */ + __IO uint32_t CTRL3; /*!< QSPI control register 3, Address offset: 0xF4 */ + __IO uint32_t RESERVED3[66]; /*!< Reserved, Address offset: 0xF8-0x1FC */ + __IO uint32_t IOSW; /*!< QSPI IO switch register, Address offset: 0x200 */ +} QSPI_TypeDef; + +/** + * @brief Comparator + */ + +typedef struct +{ + __IO uint32_t CSTS; /*!< COMP control and status register, Address offset: 0x00 */ +} COMP_TypeDef; + +typedef struct +{ + __IO uint32_t CSTS; /*!< COMP control and status register, used for bits common to several COMP instances, Address offset: 0x00 */ +} COMP_Common_TypeDef; + +/** + * @brief USB_OTG_Core_Registers + */ +typedef struct +{ + __IO uint32_t GCTRLSTS; /*!< USB_OTG Control and Status Register 000h */ + __IO uint32_t GINT; /*!< USB_OTG Interrupt Register 004h */ + __IO uint32_t GAHBCFG; /*!< Core AHB Configuration Register 008h */ + __IO uint32_t GUSBCFG; /*!< Core USB Configuration Register 00Ch */ + __IO uint32_t GRSTCTRL; /*!< Core Reset Register 010h */ + __IO uint32_t GCINT; /*!< Core Interrupt Register 014h */ + __IO uint32_t GINTMASK; /*!< Core Interrupt Mask Register 018h */ + __IO uint32_t GRXSTS; /*!< Receive Sts Q Read Register 01Ch */ + __IO uint32_t GRXSTSP; /*!< Receive Sts Q Read & POP Register 020h */ + __IO uint32_t GRXFIFO; /*!< Receive FIFO Size Register 024h */ + __IO uint32_t GTXFCFG; /*!< EP0 / Non Periodic Tx FIFO Size Register 028h */ + __IO uint32_t GNPTXFQSTS; /*!< Non Periodic Tx FIFO/Queue Sts reg 02Ch */ + uint32_t Reserved30[2]; /*!< Reserved 030h */ + __IO uint32_t GGCCFG; /*!< General Purpose IO Register 038h */ + __IO uint32_t GCID; /*!< User ID Register 03Ch */ + uint32_t Reserved40[48]; /*!< Reserved 0x40-0xFF */ + __IO uint32_t GHPTXFSIZE; /*!< Host Periodic Tx FIFO Size Reg 100h */ + __IO uint32_t DTXFIFO[0x0F]; /*!< dev Periodic Transmit FIFO */ +} USB_OTG_GlobalTypeDef; + +/** + * @brief USB_OTG_device_Registers + */ +typedef struct +{ + __IO uint32_t DCFG; /*!< dev Configuration Register 800h */ + __IO uint32_t DCTRL; /*!< dev Control Register 804h */ + __IO uint32_t DSTS; /*!< dev Status Register (RO) 808h */ + uint32_t Reserved0C; /*!< Reserved 80Ch */ + __IO uint32_t DINIMASK; /*!< dev IN Endpoint Mask 810h */ + __IO uint32_t DOUTIMASK; /*!< dev OUT Endpoint Mask 814h */ + __IO uint32_t DAEPINT; /*!< dev All Endpoints Itr Reg 818h */ + __IO uint32_t DAEPIMASK; /*!< dev All Endpoints Itr Mask 81Ch */ + uint32_t Reserved20; /*!< Reserved 820h */ + uint32_t Reserved9; /*!< Reserved 824h */ + __IO uint32_t DVBUSDTIM; /*!< dev VBUS discharge Register 828h */ + __IO uint32_t DVBUSPTIM; /*!< dev VBUS Pulse Register 82Ch */ + __IO uint32_t DTHCTRL; /*!< dev threshold 830h */ + __IO uint32_t DIEIMASK; /*!< dev empty msk 834h */ + __IO uint32_t DEPINT; /*!< dedicated EP interrupt 838h */ + __IO uint32_t DEPIMASK; /*!< dedicated EP msk 83Ch */ + uint32_t Reserved40; /*!< dedicated EP mask 840h */ + __IO uint32_t DIN1IMASK; /*!< dedicated EP mask 844h */ + uint32_t Reserved44[15]; /*!< Reserved 844-87Ch */ + __IO uint32_t DOUT1MASK; /*!< dedicated EP msk 884h */ +} USB_OTG_DeviceTypeDef; + +/** + * @brief USB_OTG_IN_Endpoint-Specific_Register + */ +typedef struct +{ + __IO uint32_t DIEPCTRL; /*!< dev IN Endpoint Control Reg 900h + (ep_num * 20h) + 00h */ + uint32_t Reserved04; /*!< Reserved 900h + (ep_num * 20h) + 04h */ + __IO uint32_t DIEPINT; /*!< dev IN Endpoint Itr Reg 900h + (ep_num * 20h) + 08h */ + uint32_t Reserved0C; /*!< Reserved 900h + (ep_num * 20h) + 0Ch */ + __IO uint32_t DIEPTRS; /*!< IN Endpoint Txfer Size 900h + (ep_num * 20h) + 10h */ + __IO uint32_t DIEPDMA; /*!< IN Endpoint DMA Address Reg 900h + (ep_num * 20h) + 14h */ + __IO uint32_t DITXFSTS; /*!< IN Endpoint Tx FIFO Status Reg 900h + (ep_num * 20h) + 18h */ + uint32_t Reserved18; /*!< Reserved 900h+(ep_num*20h)+1Ch-900h+ (ep_num * 20h) + 1Ch */ +} USB_OTG_INEndpointTypeDef; + +/** + * @brief USB_OTG_OUT_Endpoint-Specific_Registers + */ +typedef struct +{ + __IO uint32_t DOEPCTRL; /*!< dev OUT Endpoint Control Reg B00h + (ep_num * 20h) + 00h */ + uint32_t Reserved04; /*!< Reserved B00h + (ep_num * 20h) + 04h */ + __IO uint32_t DOEPINT; /*!< dev OUT Endpoint Itr Reg B00h + (ep_num * 20h) + 08h */ + uint32_t Reserved0C; /*!< Reserved B00h + (ep_num * 20h) + 0Ch */ + __IO uint32_t DOEPTRS; /*!< dev OUT Endpoint Txfer Size B00h + (ep_num * 20h) + 10h */ + __IO uint32_t DOEPDMA; /*!< dev OUT Endpoint DMA Address B00h + (ep_num * 20h) + 14h */ + uint32_t Reserved18[2]; /*!< Reserved B00h + (ep_num * 20h) + 18h - B00h + (ep_num * 20h) + 1Ch */ +} USB_OTG_OUTEndpointTypeDef; + +/** + * @brief USB_OTG_Host_Mode_Register_Structures + */ +typedef struct +{ + __IO uint32_t HCFG; /*!< Host Configuration Register 400h */ + __IO uint32_t HFIVL; /*!< Host Frame Interval Register 404h */ + __IO uint32_t HFIFM; /*!< Host Frame Nbr/Frame Remaining 408h */ + uint32_t Reserved40C; /*!< Reserved 40Ch */ + __IO uint32_t HPTXSTS; /*!< Host Periodic Tx FIFO/ Queue Status 410h */ + __IO uint32_t HACHINT; /*!< Host All Channels Interrupt Register 414h */ + __IO uint32_t HACHIMASK; /*!< Host All Channels Interrupt Mask 418h */ +} USB_OTG_HostTypeDef; + +/** + * @brief USB_OTG_Host_Channel_Specific_Registers + */ +typedef struct +{ + __IO uint32_t HCH; /*!< Host Channel Characteristics Register 500h */ + __IO uint32_t HCHSCTRL; /*!< Host Channel Split Control Register 504h */ + __IO uint32_t HCHINT; /*!< Host Channel Interrupt Register 508h */ + __IO uint32_t HCHIMASK; /*!< Host Channel Interrupt Mask Register 50Ch */ + __IO uint32_t HCHTSIZE; /*!< Host Channel Transfer Size Register 510h */ + __IO uint32_t HCHDMA; /*!< Host Channel DMA Address Register 514h */ + uint32_t Reserved[2]; /*!< Reserved */ +} USB_OTG_HostChannelTypeDef; + +/** + * @} + */ + +/** @addtogroup Peripheral_memory_map + * @{ + */ +#define FLASH_BASE 0x08000000UL /*!< FLASH(up to 1 MB) base address in the alias region */ +#define CCMDATARAM_BASE 0x10000000UL /*!< CCM(core coupled memory) data RAM(64 KB) base address in the alias region */ +#define SRAM1_BASE 0x20000000UL /*!< SRAM1(112 KB) base address in the alias region */ +#define SRAM2_BASE 0x2001C000UL /*!< SRAM2(16 KB) base address in the alias region */ +#define PERIPH_BASE 0x40000000UL /*!< Peripheral base address in the alias region */ +#define BKPSRAM_BASE 0x40024000UL /*!< Backup SRAM(4 KB) base address in the alias region */ +#define SMC_R_BASE 0xA0000000UL /*!< SMC registers base address */ +#define SRAM1_BB_BASE 0x22000000UL /*!< SRAM1(112 KB) base address in the bit-band region */ +#define SRAM2_BB_BASE 0x22380000UL /*!< SRAM2(16 KB) base address in the bit-band region */ +#define PERIPH_BB_BASE 0x42000000UL /*!< Peripheral base address in the bit-band region */ +#define BKPSRAM_BB_BASE 0x42480000UL /*!< Backup SRAM(4 KB) base address in the bit-band region */ +#define FLASH_END 0x080FFFFFUL /*!< FLASH end address */ +#define FLASH_OTP_BASE 0x1FFF7800UL /*!< Base address of : (up to 528 Bytes) embedded FLASH OTP Area */ +#define FLASH_OTP_END 0x1FFF7A0FUL /*!< End address of : (up to 528 Bytes) embedded FLASH OTP Area */ +#define CCMDATARAM_END 0x1000FFFFUL /*!< CCM data RAM end address */ + +/* Legacy defines */ +#define SRAM_BASE SRAM1_BASE +#define SRAM_BB_BASE SRAM1_BB_BASE + +/*!< Peripheral memory map */ +#define APB1PERIPH_BASE PERIPH_BASE +#define APB2PERIPH_BASE (PERIPH_BASE + 0x00010000UL) +#define AHB1PERIPH_BASE (PERIPH_BASE + 0x00020000UL) +#define AHB2PERIPH_BASE (PERIPH_BASE + 0x10000000UL) + +/*!< APB1 peripherals */ +#define TMR2_BASE (APB1PERIPH_BASE + 0x0000UL) +#define TMR3_BASE (APB1PERIPH_BASE + 0x0400UL) +#define TMR4_BASE (APB1PERIPH_BASE + 0x0800UL) +#define TMR5_BASE (APB1PERIPH_BASE + 0x0C00UL) +#define TMR12_BASE (APB1PERIPH_BASE + 0x1800UL) +#define TMR13_BASE (APB1PERIPH_BASE + 0x1C00UL) +#define TMR14_BASE (APB1PERIPH_BASE + 0x2000UL) +#define RTC_BASE (APB1PERIPH_BASE + 0x2800UL) +#define WWDT_BASE (APB1PERIPH_BASE + 0x2C00UL) +#define IWDT_BASE (APB1PERIPH_BASE + 0x3000UL) +#define I2S2ext_BASE (APB1PERIPH_BASE + 0x3400UL) +#define SPI2_BASE (APB1PERIPH_BASE + 0x3800UL) +#define SPI3_BASE (APB1PERIPH_BASE + 0x3C00UL) +#define I2S3ext_BASE (APB1PERIPH_BASE + 0x4000UL) +#define USART2_BASE (APB1PERIPH_BASE + 0x4400UL) +#define USART3_BASE (APB1PERIPH_BASE + 0x4800UL) +#define UART4_BASE (APB1PERIPH_BASE + 0x4C00UL) +#define UART5_BASE (APB1PERIPH_BASE + 0x5000UL) +#define I2C1_BASE (APB1PERIPH_BASE + 0x5400UL) +#define I2C2_BASE (APB1PERIPH_BASE + 0x5800UL) +#define I2C3_BASE (APB1PERIPH_BASE + 0x5C00UL) +#define CAN1_BASE (APB1PERIPH_BASE + 0x6400UL) +#define CAN2_BASE (APB1PERIPH_BASE + 0x6800UL) +#define PMU_BASE (APB1PERIPH_BASE + 0x7000UL) + +/*!< APB2 peripherals */ +#define TMR1_BASE (APB2PERIPH_BASE + 0x0000UL) +#define TMR8_BASE (APB2PERIPH_BASE + 0x0400UL) +#define USART1_BASE (APB2PERIPH_BASE + 0x1000UL) +#define USART6_BASE (APB2PERIPH_BASE + 0x1400UL) +#define ADC1_BASE (APB2PERIPH_BASE + 0x2000UL) +#define ADC2_BASE (APB2PERIPH_BASE + 0x2400UL) +#define ADC1_COMMON_BASE (APB2PERIPH_BASE + 0x2300UL) +#define ADC2_COMMON_BASE (APB2PERIPH_BASE + 0x2700UL) +/* Legacy define */ +#define SDIO_BASE (APB2PERIPH_BASE + 0x2C00UL) +#define SPI1_BASE (APB2PERIPH_BASE + 0x3000UL) +#define SPI4_BASE (APB2PERIPH_BASE + 0x3400UL) +#define SYSCFG_BASE (APB2PERIPH_BASE + 0x3800UL) +#define COMP1_BASE (APB2PERIPH_BASE + 0x3818UL) +#define COMP2_BASE (APB2PERIPH_BASE + 0x381CUL) +#define EINT_BASE (APB2PERIPH_BASE + 0x3C00UL) +#define TMR9_BASE (APB2PERIPH_BASE + 0x4000UL) +#define TMR10_BASE (APB2PERIPH_BASE + 0x4400UL) +#define TMR11_BASE (APB2PERIPH_BASE + 0x4800UL) +#define SPI5_BASE (APB2PERIPH_BASE + 0x5000UL) + +/*!< AHB1 peripherals */ +#define GPIOA_BASE (AHB1PERIPH_BASE + 0x0000UL) +#define GPIOB_BASE (AHB1PERIPH_BASE + 0x0400UL) +#define GPIOC_BASE (AHB1PERIPH_BASE + 0x0800UL) +#define GPIOD_BASE (AHB1PERIPH_BASE + 0x0C00UL) +#define GPIOE_BASE (AHB1PERIPH_BASE + 0x1000UL) +#define GPIOH_BASE (AHB1PERIPH_BASE + 0x1C00UL) +#define CRC_BASE (AHB1PERIPH_BASE + 0x3000UL) +#define RCM_BASE (AHB1PERIPH_BASE + 0x3800UL) +#define FLASH_R_BASE (AHB1PERIPH_BASE + 0x3C00UL) +#define DMA1_BASE (AHB1PERIPH_BASE + 0x6000UL) +#define DMA1_Stream0_BASE (DMA1_BASE + 0x010UL) +#define DMA1_Stream1_BASE (DMA1_BASE + 0x028UL) +#define DMA1_Stream2_BASE (DMA1_BASE + 0x040UL) +#define DMA1_Stream3_BASE (DMA1_BASE + 0x058UL) +#define DMA1_Stream4_BASE (DMA1_BASE + 0x070UL) +#define DMA1_Stream5_BASE (DMA1_BASE + 0x088UL) +#define DMA1_Stream6_BASE (DMA1_BASE + 0x0A0UL) +#define DMA1_Stream7_BASE (DMA1_BASE + 0x0B8UL) +#define DMA2_BASE (AHB1PERIPH_BASE + 0x6400UL) +#define DMA2_Stream0_BASE (DMA2_BASE + 0x010UL) +#define DMA2_Stream1_BASE (DMA2_BASE + 0x028UL) +#define DMA2_Stream2_BASE (DMA2_BASE + 0x040UL) +#define DMA2_Stream3_BASE (DMA2_BASE + 0x058UL) +#define DMA2_Stream4_BASE (DMA2_BASE + 0x070UL) +#define DMA2_Stream5_BASE (DMA2_BASE + 0x088UL) +#define DMA2_Stream6_BASE (DMA2_BASE + 0x0A0UL) +#define DMA2_Stream7_BASE (DMA2_BASE + 0x0B8UL) + +/*!< AHB2 peripherals */ +#define RNG_BASE (AHB2PERIPH_BASE + 0x60800UL) + +/*!< SMC Bankx registers base address */ +#define SMC_Bank1_R_BASE (SMC_R_BASE + 0x0000UL) +#define SMC_Bank1E_R_BASE (SMC_R_BASE + 0x0104UL) +#define SMC_Bank2_3_R_BASE (SMC_R_BASE + 0x0060UL) +#define SMC_Bank4_R_BASE (SMC_R_BASE + 0x00A0UL) + +/*!< QuadSPI registers base address */ +#define QSPI_BASE 0xA0001000UL + +/*!< Debug MCU registers base address */ +#define DBGMCU_BASE 0xE0042000UL +/*!< USB registers base address */ +#define USB_OTG_FS_PERIPH_BASE 0x50000000UL + +#define USB_OTG_GLOBAL_BASE 0x000UL +#define USB_OTG_DEVICE_BASE 0x800UL +#define USB_OTG_IN_ENDPOINT_BASE 0x900UL +#define USB_OTG_OUT_ENDPOINT_BASE 0xB00UL +#define USB_OTG_EP_REG_SIZE 0x20UL +#define USB_OTG_HOST_BASE 0x400UL +#define USB_OTG_HOST_PORT_BASE 0x440UL +#define USB_OTG_HOST_CHANNEL_BASE 0x500UL +#define USB_OTG_HOST_CHANNEL_SIZE 0x20UL +#define USB_OTG_PCGCCTL_BASE 0xE00UL +#define USB_OTG_FIFO_BASE 0x1000UL +#define USB_OTG_FIFO_SIZE 0x1000UL + +#define UID_BASE 0x1FFF7A10UL /*!< Unique device ID register base address */ +#define FLASHSIZE_BASE 0x1FFF7A22UL /*!< FLASH Size register base address */ +#define PACKAGE_BASE 0x1FFF7BF0UL /*!< Package size register base address */ +/** + * @} + */ + +/** @addtogroup Peripheral_declaration + * @{ + */ +#define TMR2 ((TMR_TypeDef *) TMR2_BASE) +#define TMR3 ((TMR_TypeDef *) TMR3_BASE) +#define TMR4 ((TMR_TypeDef *) TMR4_BASE) +#define TMR5 ((TMR_TypeDef *) TMR5_BASE) +#define TMR12 ((TMR_TypeDef *) TMR12_BASE) +#define TMR13 ((TMR_TypeDef *) TMR13_BASE) +#define TMR14 ((TMR_TypeDef *) TMR14_BASE) +#define RTC ((RTC_TypeDef *) RTC_BASE) +#define WWDT ((WWDT_TypeDef *) WWDT_BASE) +#define IWDT ((IWDT_TypeDef *) IWDT_BASE) +#define I2S2ext ((SPI_TypeDef *) I2S2ext_BASE) +#define SPI2 ((SPI_TypeDef *) SPI2_BASE) +#define SPI3 ((SPI_TypeDef *) SPI3_BASE) +#define I2S3ext ((SPI_TypeDef *) I2S3ext_BASE) +#define USART2 ((USART_TypeDef *) USART2_BASE) +#define USART3 ((USART_TypeDef *) USART3_BASE) +#define UART4 ((USART_TypeDef *) UART4_BASE) +#define UART5 ((USART_TypeDef *) UART5_BASE) +#define I2C1 ((I2C_TypeDef *) I2C1_BASE) +#define I2C2 ((I2C_TypeDef *) I2C2_BASE) +#define I2C3 ((I2C_TypeDef *) I2C3_BASE) +#define CAN1 ((CAN_TypeDef *) CAN1_BASE) +#define CAN2 ((CAN_TypeDef *) CAN2_BASE) +#define PMU ((PMU_TypeDef *) PMU_BASE) +#define TMR1 ((TMR_TypeDef *) TMR1_BASE) +#define TMR8 ((TMR_TypeDef *) TMR8_BASE) +#define USART1 ((USART_TypeDef *) USART1_BASE) +#define USART6 ((USART_TypeDef *) USART6_BASE) +#define ADC1 ((ADC_TypeDef *) ADC1_BASE) +#define ADC2 ((ADC_TypeDef *) ADC2_BASE) +#define ADC1_COMMON ((ADC_Common_TypeDef *) ADC1_COMMON_BASE) +#define ADC2_COMMON ((ADC_Common_TypeDef *) ADC2_COMMON_BASE) +/* Legacy define */ +#define ADC1_C ADC1_COMMON +#define ADC2_C ADC2_COMMON +#define SDIO ((SDIO_TypeDef *) SDIO_BASE) +#define SPI1 ((SPI_TypeDef *) SPI1_BASE) +#define SPI4 ((SPI_TypeDef *) SPI4_BASE) +#define SYSCFG ((SYSCFG_TypeDef *) SYSCFG_BASE) +#define COMP1 ((COMP_TypeDef *) COMP1_BASE) +#define COMP2 ((COMP_TypeDef *) COMP2_BASE) +#define COMP12_COMMON ((COMP_Common_TypeDef *) COMP1_BASE) +#define EINT ((EINT_TypeDef *) EINT_BASE) +#define TMR9 ((TMR_TypeDef *) TMR9_BASE) +#define TMR10 ((TMR_TypeDef *) TMR10_BASE) +#define TMR11 ((TMR_TypeDef *) TMR11_BASE) +#define SPI5 ((SPI_TypeDef *) SPI5_BASE) +#define GPIOA ((GPIO_TypeDef *) GPIOA_BASE) +#define GPIOB ((GPIO_TypeDef *) GPIOB_BASE) +#define GPIOC ((GPIO_TypeDef *) GPIOC_BASE) +#define GPIOD ((GPIO_TypeDef *) GPIOD_BASE) +#define GPIOE ((GPIO_TypeDef *) GPIOE_BASE) +#define GPIOH ((GPIO_TypeDef *) GPIOH_BASE) +#define CRC ((CRC_TypeDef *) CRC_BASE) +#define RCM ((RCM_TypeDef *) RCM_BASE) +#define FLASH ((FLASH_TypeDef *) FLASH_R_BASE) +#define DMA1 ((DMA_TypeDef *) DMA1_BASE) +#define DMA1_Stream0 ((DMA_Stream_TypeDef *) DMA1_Stream0_BASE) +#define DMA1_Stream1 ((DMA_Stream_TypeDef *) DMA1_Stream1_BASE) +#define DMA1_Stream2 ((DMA_Stream_TypeDef *) DMA1_Stream2_BASE) +#define DMA1_Stream3 ((DMA_Stream_TypeDef *) DMA1_Stream3_BASE) +#define DMA1_Stream4 ((DMA_Stream_TypeDef *) DMA1_Stream4_BASE) +#define DMA1_Stream5 ((DMA_Stream_TypeDef *) DMA1_Stream5_BASE) +#define DMA1_Stream6 ((DMA_Stream_TypeDef *) DMA1_Stream6_BASE) +#define DMA1_Stream7 ((DMA_Stream_TypeDef *) DMA1_Stream7_BASE) +#define DMA2 ((DMA_TypeDef *) DMA2_BASE) +#define DMA2_Stream0 ((DMA_Stream_TypeDef *) DMA2_Stream0_BASE) +#define DMA2_Stream1 ((DMA_Stream_TypeDef *) DMA2_Stream1_BASE) +#define DMA2_Stream2 ((DMA_Stream_TypeDef *) DMA2_Stream2_BASE) +#define DMA2_Stream3 ((DMA_Stream_TypeDef *) DMA2_Stream3_BASE) +#define DMA2_Stream4 ((DMA_Stream_TypeDef *) DMA2_Stream4_BASE) +#define DMA2_Stream5 ((DMA_Stream_TypeDef *) DMA2_Stream5_BASE) +#define DMA2_Stream6 ((DMA_Stream_TypeDef *) DMA2_Stream6_BASE) +#define DMA2_Stream7 ((DMA_Stream_TypeDef *) DMA2_Stream7_BASE) +#define RNG ((RNG_TypeDef *) RNG_BASE) +#define QSPI ((QSPI_TypeDef *) QSPI_BASE) +#define SMC_Bank1 ((SMC_Bank1_TypeDef *) SMC_Bank1_R_BASE) +#define SMC_Bank1E ((SMC_Bank1E_TypeDef *) SMC_Bank1E_R_BASE) +#define SMC_Bank2_3 ((SMC_Bank2_3_TypeDef *) SMC_Bank2_3_R_BASE) +#define SMC_Bank4 ((SMC_Bank4_TypeDef *) SMC_Bank4_R_BASE) +#define DBGMCU ((DBGMCU_TypeDef *) DBGMCU_BASE) +#define USB_OTG_FS ((USB_OTG_GlobalTypeDef *) USB_OTG_FS_PERIPH_BASE) + +/** + * @} + */ + +/** @addtogroup Exported_constants + * @{ + */ + +/** @addtogroup Hardware_Constant_Definition + * @{ + */ +#define LSI_STARTUP_TIME 40U /*!< LSI Maximum startup time in us */ +/** + * @} + */ + + /** @addtogroup Peripheral_Registers_Bits_Definition + * @{ + */ + +/******************************************************************************/ +/* Peripheral Registers_Bits_Definition */ +/******************************************************************************/ + +/******************************************************************************/ +/* */ +/* Analog to Digital Converter */ +/* */ +/******************************************************************************/ +/* + * @brief Specific device feature definitions (not present on all devices in the APM32F4 serie) + */ + +/******************** Bit definition for ADC_STS register ********************/ +#define ADC_STS_AWDFLG_Pos (0U) +#define ADC_STS_AWDFLG_Msk (0x1UL << ADC_STS_AWDFLG_Pos) /*!< 0x00000001 */ +#define ADC_STS_AWDFLG ADC_STS_AWDFLG_Msk /*! + +/** @addtogroup Peripheral_registers_structures + * @{ + */ + +/** + * @brief Analog to Digital Converter + */ + +typedef struct +{ + __IO uint32_t STS; /*!< ADC status register, Address offset: 0x00 */ + __IO uint32_t CTRL1; /*!< ADC control register 1, Address offset: 0x04 */ + __IO uint32_t CTRL2; /*!< ADC control register 2, Address offset: 0x08 */ + __IO uint32_t SMPTIM1; /*!< ADC sample time register 1, Address offset: 0x0C */ + __IO uint32_t SMPTIM2; /*!< ADC sample time register 2, Address offset: 0x10 */ + __IO uint32_t INJDOF1; /*!< ADC injected channel data offset register 1, Address offset: 0x14 */ + __IO uint32_t INJDOF2; /*!< ADC injected channel data offset register 2, Address offset: 0x18 */ + __IO uint32_t INJDOF3; /*!< ADC injected channel data offset register 3, Address offset: 0x1C */ + __IO uint32_t INJDOF4; /*!< ADC injected channel data offset register 4, Address offset: 0x20 */ + __IO uint32_t AWDHT; /*!< ADC watchdog higher threshold register, Address offset: 0x24 */ + __IO uint32_t AWDLT; /*!< ADC watchdog lower threshold register, Address offset: 0x28 */ + __IO uint32_t REGSEQ1; /*!< ADC regular sequence register 1, Address offset: 0x2C */ + __IO uint32_t REGSEQ2; /*!< ADC regular sequence register 2, Address offset: 0x30 */ + __IO uint32_t REGSEQ3; /*!< ADC regular sequence register 3, Address offset: 0x34 */ + __IO uint32_t INJSEQ; /*!< ADC injected sequence register, Address offset: 0x38 */ + __IO uint32_t INJDATA1; /*!< ADC injected data register 1, Address offset: 0x3C */ + __IO uint32_t INJDATA2; /*!< ADC injected data register 2, Address offset: 0x40 */ + __IO uint32_t INJDATA3; /*!< ADC injected data register 3, Address offset: 0x44 */ + __IO uint32_t INJDATA4; /*!< ADC injected data register 4, Address offset: 0x48 */ + __IO uint32_t REGDATA; /*!< ADC regular data register, Address offset: 0x4C */ +} ADC_TypeDef; + +typedef struct +{ + __IO uint32_t CSTS; /*!< ADC Common status register, Address offset: ADC1 base address + 0x300 */ + __IO uint32_t CCTRL; /*!< ADC common control register, Address offset: ADC1 base address + 0x304 */ + __IO uint32_t CDATA; /*!< ADC common regular data register for dual + AND triple modes, Address offset: ADC1 base address + 0x308 */ +} ADC_Common_TypeDef; + + +/** + * @brief Controller Area Network TxMailBox + */ + +typedef struct +{ + __IO uint32_t TXMID; /*!< CAN TX mailbox identifier register */ + __IO uint32_t TXDLEN; /*!< CAN mailbox data length control and time stamp register */ + __IO uint32_t TXMDL; /*!< CAN mailbox data low register */ + __IO uint32_t TXMDH; /*!< CAN mailbox data high register */ +} CAN_TxMailBox_TypeDef; + +/** + * @brief Controller Area Network FIFOMailBox + */ + +typedef struct +{ + __IO uint32_t RXMID; /*!< CAN receive FIFO mailbox identifier register */ + __IO uint32_t RXDLEN; /*!< CAN receive FIFO mailbox data length control and time stamp register */ + __IO uint32_t RXMDL; /*!< CAN receive FIFO mailbox data low register */ + __IO uint32_t RXMDH; /*!< CAN receive FIFO mailbox data high register */ +} CAN_FIFOMailBox_TypeDef; + +/** + * @brief Controller Area Network FilterRegister + */ + +typedef struct +{ + __IO uint32_t FBANK1; /*!< CAN Filter bank register 1 */ + __IO uint32_t FBANK2; /*!< CAN Filter bank register 1 */ +} CAN_FilterRegister_TypeDef; + +/** + * @brief Controller Area Network + */ + +typedef struct +{ + __IO uint32_t MCTRL; /*!< CAN master control register, Address offset: 0x00 */ + __IO uint32_t MSTS; /*!< CAN master status register, Address offset: 0x04 */ + __IO uint32_t TXSTS; /*!< CAN transmit status register, Address offset: 0x08 */ + __IO uint32_t RXF0; /*!< CAN receive FIFO 0 register, Address offset: 0x0C */ + __IO uint32_t RXF1; /*!< CAN receive FIFO 1 register, Address offset: 0x10 */ + __IO uint32_t INTEN; /*!< CAN interrupt enable register, Address offset: 0x14 */ + __IO uint32_t ERRSTS; /*!< CAN error status register, Address offset: 0x18 */ + __IO uint32_t BITTIM; /*!< CAN bit timing register, Address offset: 0x1C */ + uint32_t RESERVED0[88]; /*!< Reserved, 0x020 - 0x17F */ + CAN_TxMailBox_TypeDef sTxMailBox[3]; /*!< CAN Tx MailBox, Address offset: 0x180 - 0x1AC */ + CAN_FIFOMailBox_TypeDef sFIFOMailBox[2]; /*!< CAN FIFO MailBox, Address offset: 0x1B0 - 0x1CC */ + uint32_t RESERVED1[12]; /*!< Reserved, 0x1D0 - 0x1FF */ + __IO uint32_t FCTRL; /*!< CAN filter master register, Address offset: 0x200 */ + __IO uint32_t FMCFG; /*!< CAN filter mode register, Address offset: 0x204 */ + uint32_t RESERVED2; /*!< Reserved, 0x208 */ + __IO uint32_t FSCFG; /*!< CAN filter scale register, Address offset: 0x20C */ + uint32_t RESERVED3; /*!< Reserved, 0x210 */ + __IO uint32_t FFASS; /*!< CAN filter FIFO assignment register, Address offset: 0x214 */ + uint32_t RESERVED4; /*!< Reserved, 0x218 */ + __IO uint32_t FACT; /*!< CAN filter activation register, Address offset: 0x21C */ + uint32_t RESERVED5[8]; /*!< Reserved, 0x220-0x23F */ + CAN_FilterRegister_TypeDef sFilterRegister[28]; /*!< CAN Filter Register, Address offset: 0x240-0x31C */ +} CAN_TypeDef; + +/** + * @brief CRC calculation unit + */ + +typedef struct +{ + __IO uint32_t DATA; /*!< CRC Data register, Address offset: 0x00 */ + __IO uint8_t INDATA; /*!< CRC Independent data register, Address offset: 0x04 */ + uint8_t RESERVED0; /*!< Reserved, 0x05 */ + uint16_t RESERVED1; /*!< Reserved, 0x06 */ + __IO uint32_t CTRL; /*!< CRC Control register, Address offset: 0x08 */ +} CRC_TypeDef; + +/** + * @brief Digital to Analog Converter + */ + +typedef struct +{ + __IO uint32_t CTRL; /*!< DAC control register, Address offset: 0x00 */ + __IO uint32_t SWTRG; /*!< DAC software trigger register, Address offset: 0x04 */ + __IO uint32_t DH12R1; /*!< DAC channel1 12-bit right-aligned data holding register, Address offset: 0x08 */ + __IO uint32_t DH12L1; /*!< DAC channel1 12-bit left aligned data holding register, Address offset: 0x0C */ + __IO uint32_t DH8R1; /*!< DAC channel1 8-bit right aligned data holding register, Address offset: 0x10 */ + __IO uint32_t DH12R2; /*!< DAC channel2 12-bit right aligned data holding register, Address offset: 0x14 */ + __IO uint32_t DH12L2; /*!< DAC channel2 12-bit left aligned data holding register, Address offset: 0x18 */ + __IO uint32_t DH8R2; /*!< DAC channel2 8-bit right-aligned data holding register, Address offset: 0x1C */ + __IO uint32_t DH12RDUAL; /*!< Dual DAC 12-bit right-aligned data holding register, Address offset: 0x20 */ + __IO uint32_t DH12LDUAL; /*!< DUAL DAC 12-bit left aligned data holding register, Address offset: 0x24 */ + __IO uint32_t DH8RDUAL; /*!< DUAL DAC 8-bit right aligned data holding register, Address offset: 0x28 */ + __IO uint32_t DATAOCH1; /*!< DAC channel1 data output register, Address offset: 0x2C */ + __IO uint32_t DATAOCH2; /*!< DAC channel2 data output register, Address offset: 0x30 */ + __IO uint32_t STS; /*!< DAC status register, Address offset: 0x34 */ +} DAC_TypeDef; + +/** + * @brief Debug MCU + */ + +typedef struct +{ + __IO uint32_t IDCODE; /*!< MCU device ID code, Address offset: 0x00 */ + __IO uint32_t CFG; /*!< Debug MCU configuration register, Address offset: 0x04 */ + __IO uint32_t APB1F; /*!< Debug MCU APB1 freeze register, Address offset: 0x08 */ + __IO uint32_t APB2F; /*!< Debug MCU APB2 freeze register, Address offset: 0x0C */ +} DBGMCU_TypeDef; + +/** + * @brief DCI + */ + +typedef struct +{ + __IO uint32_t CTRL; /*!< DCI control register 1, Address offset: 0x00 */ + __IO uint32_t STS; /*!< DCI status register, Address offset: 0x04 */ + __IO uint32_t RINTSTS; /*!< DCI raw interrupt status register, Address offset: 0x08 */ + __IO uint32_t INTEN; /*!< DCI interrupt enable register, Address offset: 0x0C */ + __IO uint32_t MINTSTS; /*!< DCI masked interrupt status register, Address offset: 0x10 */ + __IO uint32_t INTCLR; /*!< DCI interrupt clear register, Address offset: 0x14 */ + __IO uint32_t ESYNCC; /*!< DCI embedded synchronization code register, Address offset: 0x18 */ + __IO uint32_t ESYNCUM; /*!< DCI embedded synchronization unmask register, Address offset: 0x1C */ + __IO uint32_t CROPWSTAT; /*!< DCI crop window start, Address offset: 0x20 */ + __IO uint32_t CROPWSIZE; /*!< DCI crop window size, Address offset: 0x24 */ + __IO uint32_t DATA; /*!< DCI data register, Address offset: 0x28 */ +} DCI_TypeDef; + +/** + * @brief DMA Controller + */ + +typedef struct +{ + __IO uint32_t SCFG; /*!< DMA stream x configuration register */ + __IO uint32_t NDATA; /*!< DMA stream x number of data register */ + __IO uint32_t PADDR; /*!< DMA stream x peripheral address register */ + __IO uint32_t M0ADDR; /*!< DMA stream x memory 0 address register */ + __IO uint32_t M1ADDR; /*!< DMA stream x memory 1 address register */ + __IO uint32_t FCTRL; /*!< DMA stream x FIFO control register */ +} DMA_Stream_TypeDef; + +typedef struct +{ + __IO uint32_t LINTSTS; /*!< DMA low interrupt status register, Address offset: 0x00 */ + __IO uint32_t HINTSTS; /*!< DMA high interrupt status register, Address offset: 0x04 */ + __IO uint32_t LIFCLR; /*!< DMA low interrupt flag clear register, Address offset: 0x08 */ + __IO uint32_t HIFCLR; /*!< DMA high interrupt flag clear register, Address offset: 0x0C */ +} DMA_TypeDef; + +/** + * @brief Ethernet MAC + */ + +typedef struct +{ + __IO uint32_t MACCFG; + __IO uint32_t MACFRAF; + __IO uint32_t MACHTH; + __IO uint32_t MACHTL; + __IO uint32_t MACADDR; + __IO uint32_t MACDATA; + __IO uint32_t MACFCTRL; + __IO uint32_t MACVLANT; /* 8 */ + uint32_t RESERVED0[2]; + __IO uint32_t MACREMWKUPFFL; /* 11 */ + __IO uint32_t MACPMTCTRLSTS; + uint32_t RESERVED1; + __IO uint32_t MACDBG; + __IO uint32_t MACISTS; /* 15 */ + __IO uint32_t MACIMASK; + __IO uint32_t MACADDR0H; + __IO uint32_t MACADDR0L; + __IO uint32_t MACADDR1H; + __IO uint32_t MACADDR1L; + __IO uint32_t MACADDR2H; + __IO uint32_t MACADDR2L; + __IO uint32_t MACADDR3H; + __IO uint32_t MACADDR3L; /* 24 */ + uint32_t RESERVED2[40]; + __IO uint32_t MMCCTRL; /* 65 */ + __IO uint32_t MMCRXINT; + __IO uint32_t MMCTXINT; + __IO uint32_t MMCRXINTMASK; + __IO uint32_t MMCTXINTMASK; /* 69 */ + uint32_t RESERVED3[14]; + __IO uint32_t MMCTXGFSCCNT; /* 84 */ + __IO uint32_t MMCTXGFMCCNT; + uint32_t RESERVED4[5]; + __IO uint32_t MMCTXGFCNT; + uint32_t RESERVED5[10]; + __IO uint32_t MMCRXFCECNT; + __IO uint32_t MMCRXFAECNT; + uint32_t RESERVED6[10]; + __IO uint32_t MMCRXGUNCNT; + uint32_t RESERVED7[334]; + __IO uint32_t PTPTSCTRL; + __IO uint32_t PTPSUBSECI; + __IO uint32_t PTPTSH; + __IO uint32_t PTPTSL; + __IO uint32_t PTPTSHUD; + __IO uint32_t PTPTSLUD; + __IO uint32_t PTPTSA; + __IO uint32_t PTPTTSH; + __IO uint32_t PTPTTSL; + __IO uint32_t RESERVED8; + __IO uint32_t PTPTSSTS; + uint32_t RESERVED9[565]; + __IO uint32_t DMABMOD; + __IO uint32_t DMATXPD; + __IO uint32_t DMARXPD; + __IO uint32_t DMARXDLADDR; + __IO uint32_t DMATXDLADDR; + __IO uint32_t DMASTS; + __IO uint32_t DMAOPMOD; + __IO uint32_t DMAINTEN; + __IO uint32_t DMAMFABOCNT; + __IO uint32_t DMARXFLGWDT; + uint32_t RESERVED10[8]; + __IO uint32_t DMAHTXD; + __IO uint32_t DMAHRXD; + __IO uint32_t DMAHTXBADDR; + __IO uint32_t DMAHRXBADDR; +} ETH_TypeDef; + +/** + * @brief External Interrupt/Event Controller + */ + +typedef struct +{ + __IO uint32_t IMASK; /*!< EINT Interrupt mask register, Address offset: 0x00 */ + __IO uint32_t EMASK; /*!< EINT Event mask register, Address offset: 0x04 */ + __IO uint32_t RTEN; /*!< EINT Rising trigger selection register, Address offset: 0x08 */ + __IO uint32_t FTEN; /*!< EINT Falling trigger selection register, Address offset: 0x0C */ + __IO uint32_t SWINTE; /*!< EINT Software interrupt event register, Address offset: 0x10 */ + __IO uint32_t IPEND; /*!< EINT Pending register, Address offset: 0x14 */ +} EINT_TypeDef; + +/** + * @brief FLASH Registers + */ + +typedef struct +{ + __IO uint32_t ACCTRL; /*!< FLASH access control register, Address offset: 0x00 */ + __IO uint32_t KEY; /*!< FLASH key register, Address offset: 0x04 */ + __IO uint32_t OPTKEY; /*!< FLASH option key register, Address offset: 0x08 */ + __IO uint32_t STS; /*!< FLASH status register, Address offset: 0x0C */ + __IO uint32_t CTRL; /*!< FLASH control register, Address offset: 0x10 */ + __IO uint32_t OPTCTRL; /*!< FLASH option control register , Address offset: 0x14 */ + __IO uint32_t OPTCTRL1; /*!< FLASH option control register 1, Address offset: 0x18 */ +} FLASH_TypeDef; + +/** + * @brief Dynamic memory controler (DMC) + */ +typedef struct +{ + __IO uint32_t CFG; /*!< Configuraion register, Address offset: 0x00 */ + __IO uint32_t TIM0; /*!< Timing register 0, Address offset: 0x04 */ + __IO uint32_t TIM1; /*!< Timing register 1, Address offset: 0x08 */ + __IO uint32_t CTRL1; /*!< Control register 1, Address offset: 0x0C */ + __IO uint32_t REF; /*!< refresh register, Address offset: 0x10 */ + uint32_t RESERVED[251]; + __IO uint32_t SW; /*!< switch register, Address offset: 0x400 */ + __IO uint32_t CTRL2; /*!< Control register 2, Address offset: 0x404 */ +} DMC_TypeDef; + +/** + * @brief Flexible Static Memory Controller + */ + +typedef struct +{ + __IO uint32_t CSTR[8]; /*!< NOR/PSRAM chip-select control register(CSCTRL) and chip-select timing register(CSTIM), Address offset: 0x00-1C */ +} SMC_Bank1_TypeDef; + +/** + * @brief Flexible Static Memory Controller Bank1E + */ + +typedef struct +{ + __IO uint32_t WRTTIM[7]; /*!< NOR/PSRAM write timing registers, Address offset: 0x104-0x11C */ +} SMC_Bank1E_TypeDef; + +/** + * @brief Flexible Static Memory Controller Bank2 + */ + +typedef struct +{ + __IO uint32_t CTRL2; /*!< NAND Flash control register 2, Address offset: 0x60 */ + __IO uint32_t STSINT2; /*!< NAND Flash FIFO status and interrupt register 2, Address offset: 0x64 */ + __IO uint32_t CMSTIM2; /*!< NAND Flash Common memory space timing register 2, Address offset: 0x68 */ + __IO uint32_t AMSTIM2; /*!< NAND Flash Attribute memory space timing register 2, Address offset: 0x6C */ + uint32_t RESERVED0; /*!< Reserved, 0x70 */ + __IO uint32_t ECCRS2; /*!< NAND Flash ECC result registers 2, Address offset: 0x74 */ + uint32_t RESERVED1; /*!< Reserved, 0x78 */ + uint32_t RESERVED2; /*!< Reserved, 0x7C */ + __IO uint32_t CTRL3; /*!< NAND Flash control register 3, Address offset: 0x80 */ + __IO uint32_t STSINT3; /*!< NAND Flash FIFO status and interrupt register 3, Address offset: 0x84 */ + __IO uint32_t CMSTIM3; /*!< NAND Flash Common memory space timing register 3, Address offset: 0x88 */ + __IO uint32_t AMSTIM3; /*!< NAND Flash Attribute memory space timing register 3, Address offset: 0x8C */ + uint32_t RESERVED3; /*!< Reserved, 0x90 */ + __IO uint32_t ECCRS3; /*!< NAND Flash ECC result registers 3, Address offset: 0x94 */ +} SMC_Bank2_3_TypeDef; + +/** + * @brief Flexible Static Memory Controller Bank4 + */ + +typedef struct +{ + __IO uint32_t CTRL4; /*!< PC Card control register 4, Address offset: 0xA0 */ + __IO uint32_t STSINT4; /*!< PC Card FIFO status and interrupt register 4, Address offset: 0xA4 */ + __IO uint32_t CMSTIM4; /*!< PC Card Common memory space timing register 4, Address offset: 0xA8 */ + __IO uint32_t AMSTIM4; /*!< PC Card Attribute memory space timing register 4, Address offset: 0xAC */ + __IO uint32_t IOSTIM4; /*!< PC Card I/O space timing register 4, Address offset: 0xB0 */ +} SMC_Bank4_TypeDef; + +/** + * @brief General Purpose I/O + */ + +typedef struct +{ + __IO uint32_t MODE; /*!< GPIO port mode register, Address offset: 0x00 */ + __IO uint32_t OMODE; /*!< GPIO port output type register, Address offset: 0x04 */ + __IO uint32_t OSSEL; /*!< GPIO port output speed register, Address offset: 0x08 */ + __IO uint32_t PUPD; /*!< GPIO port pull-up/pull-down register, Address offset: 0x0C */ + __IO uint32_t IDATA; /*!< GPIO port input data register, Address offset: 0x10 */ + __IO uint32_t ODATA; /*!< GPIO port output data register, Address offset: 0x14 */ + __IO uint32_t BSC; /*!< GPIO port bit set/reset register, Address offset: 0x18 */ + __IO uint32_t LOCK; /*!< GPIO port configuration lock register, Address offset: 0x1C */ + __IO uint32_t ALF[2]; /*!< GPIO alternate function registers, Address offset: 0x20-0x24 */ +} GPIO_TypeDef; + +/** + * @brief System configuration controller + */ + +typedef struct +{ + __IO uint32_t MMSEL; /*!< SYSCFG memory remap register, Address offset: 0x00 */ + __IO uint32_t PMCFG; /*!< SYSCFG peripheral mode configuration register, Address offset: 0x04 */ + __IO uint32_t EINTCFG[4]; /*!< SYSCFG external interrupt configuration registers, Address offset: 0x08-0x14 */ + uint32_t RESERVED[2]; /*!< Reserved, 0x18-0x1C */ + __IO uint32_t CCCTRL; /*!< SYSCFG Compensation cell control register, Address offset: 0x20 */ +} SYSCFG_TypeDef; + +/** + * @brief Inter-integrated Circuit Interface + */ + +typedef struct +{ + __IO uint32_t CTRL1; /*!< I2C Control register 1, Address offset: 0x00 */ + __IO uint32_t CTRL2; /*!< I2C Control register 2, Address offset: 0x04 */ + __IO uint32_t SADDR1; /*!< I2C Own address register 1, Address offset: 0x08 */ + __IO uint32_t SADDR2; /*!< I2C Own address register 2, Address offset: 0x0C */ + __IO uint32_t DATA; /*!< I2C Data register, Address offset: 0x10 */ + __IO uint32_t STS1; /*!< I2C Status register 1, Address offset: 0x14 */ + __IO uint32_t STS2; /*!< I2C Status register 2, Address offset: 0x18 */ + __IO uint32_t CLKCTRL; /*!< I2C Clock control register, Address offset: 0x1C */ + __IO uint32_t RISETMAX; /*!< I2C RISETMAX register, Address offset: 0x20 */ +} I2C_TypeDef; + +/** + * @brief Independent WATCHDOG + */ + +typedef struct +{ + __IO uint32_t KEY; /*!< IWDT Key register, Address offset: 0x00 */ + __IO uint32_t PSC; /*!< IWDT Prescaler register, Address offset: 0x04 */ + __IO uint32_t CNTRLD; /*!< IWDT Reload register, Address offset: 0x08 */ + __IO uint32_t STS; /*!< IWDT Status register, Address offset: 0x0C */ +} IWDT_TypeDef; + + +/** + * @brief Power Control + */ + +typedef struct +{ + __IO uint32_t CTRL; /*!< PMU power control register, Address offset: 0x00 */ + __IO uint32_t CSTS; /*!< PMU power control/status register, Address offset: 0x04 */ +} PMU_TypeDef; + +/** + * @brief Reset and Clock Control + */ + +typedef struct +{ + __IO uint32_t CTRL; /*!< RCM clock control register, Address offset: 0x00 */ + __IO uint32_t PLL1CFG; /*!< RCM PLL configuration register, Address offset: 0x04 */ + __IO uint32_t CFG; /*!< RCM clock configuration register, Address offset: 0x08 */ + __IO uint32_t INT; /*!< RCM clock interrupt register, Address offset: 0x0C */ + __IO uint32_t AHB1RST; /*!< RCM AHB1 peripheral reset register, Address offset: 0x10 */ + __IO uint32_t AHB2RST; /*!< RCM AHB2 peripheral reset register, Address offset: 0x14 */ + __IO uint32_t AHB3RST; /*!< RCM AHB3 peripheral reset register, Address offset: 0x18 */ + uint32_t RESERVED0; /*!< Reserved, 0x1C */ + __IO uint32_t APB1RST; /*!< RCM APB1 peripheral reset register, Address offset: 0x20 */ + __IO uint32_t APB2RST; /*!< RCM APB2 peripheral reset register, Address offset: 0x24 */ + uint32_t RESERVED1[2]; /*!< Reserved, 0x28-0x2C */ + __IO uint32_t AHB1CLKEN; /*!< RCM AHB1 peripheral clock register, Address offset: 0x30 */ + __IO uint32_t AHB2CLKEN; /*!< RCM AHB2 peripheral clock register, Address offset: 0x34 */ + __IO uint32_t AHB3CLKEN; /*!< RCM AHB3 peripheral clock register, Address offset: 0x38 */ + uint32_t RESERVED2; /*!< Reserved, 0x3C */ + __IO uint32_t APB1CLKEN; /*!< RCM APB1 peripheral clock enable register, Address offset: 0x40 */ + __IO uint32_t APB2CLKEN; /*!< RCM APB2 peripheral clock enable register, Address offset: 0x44 */ + uint32_t RESERVED3[2]; /*!< Reserved, 0x48-0x4C */ + __IO uint32_t LPAHB1CLKEN; /*!< RCM AHB1 peripheral clock enable in low power mode register, Address offset: 0x50 */ + __IO uint32_t LPAHB2CLKEN; /*!< RCM AHB2 peripheral clock enable in low power mode register, Address offset: 0x54 */ + __IO uint32_t LPAHB3CLKEN; /*!< RCM AHB3 peripheral clock enable in low power mode register, Address offset: 0x58 */ + uint32_t RESERVED4; /*!< Reserved, 0x5C */ + __IO uint32_t LPAPB1CLKEN; /*!< RCM APB1 peripheral clock enable in low power mode register, Address offset: 0x60 */ + __IO uint32_t LPAPB2CLKEN; /*!< RCM APB2 peripheral clock enable in low power mode register, Address offset: 0x64 */ + uint32_t RESERVED5[2]; /*!< Reserved, 0x68-0x6C */ + __IO uint32_t BDCTRL; /*!< RCM Backup domain control register, Address offset: 0x70 */ + __IO uint32_t CSTS; /*!< RCM clock control & status register, Address offset: 0x74 */ + uint32_t RESERVED6[2]; /*!< Reserved, 0x78-0x7C */ + __IO uint32_t SSCCFG; /*!< RCM spread spectrum clock generation register, Address offset: 0x80 */ + __IO uint32_t PLL2CFG; /*!< RCM PLLI2S configuration register, Address offset: 0x84 */ +} RCM_TypeDef; + +/** + * @brief Real-Time Clock + */ + +typedef struct +{ + __IO uint32_t TIME; /*!< RTC time register, Address offset: 0x00 */ + __IO uint32_t DATE; /*!< RTC date register, Address offset: 0x04 */ + __IO uint32_t CTRL; /*!< RTC control register, Address offset: 0x08 */ + __IO uint32_t STS; /*!< RTC initialization and status register, Address offset: 0x0C */ + __IO uint32_t PSC; /*!< RTC prescaler register, Address offset: 0x10 */ + __IO uint32_t AUTORLD; /*!< RTC wakeup timer register, Address offset: 0x14 */ + __IO uint32_t DCAL; /*!< RTC calibration register, Address offset: 0x18 */ + __IO uint32_t ALRMA; /*!< RTC alarm A register, Address offset: 0x1C */ + __IO uint32_t ALRMB; /*!< RTC alarm B register, Address offset: 0x20 */ + __IO uint32_t WRPROT; /*!< RTC write protection register, Address offset: 0x24 */ + __IO uint32_t SUBSEC; /*!< RTC sub second register, Address offset: 0x28 */ + __IO uint32_t SHIFT; /*!< RTC shift control register, Address offset: 0x2C */ + __IO uint32_t TSTIME; /*!< RTC time stamp time register, Address offset: 0x30 */ + __IO uint32_t TSDATE; /*!< RTC time stamp date register, Address offset: 0x34 */ + __IO uint32_t TSSUBSEC; /*!< RTC time-stamp sub second register, Address offset: 0x38 */ + __IO uint32_t CAL; /*!< RTC calibration register, Address offset: 0x3C */ + __IO uint32_t TACFG; /*!< RTC tamper and alternate function configuration register, Address offset: 0x40 */ + __IO uint32_t ALRMASS; /*!< RTC alarm A sub second register, Address offset: 0x44 */ + __IO uint32_t ALRMBSS; /*!< RTC alarm B sub second register, Address offset: 0x48 */ + uint32_t RESERVED7; /*!< Reserved, 0x4C */ + __IO uint32_t BAKP0; /*!< RTC backup register 1, Address offset: 0x50 */ + __IO uint32_t BAKP1; /*!< RTC backup register 1, Address offset: 0x54 */ + __IO uint32_t BAKP2; /*!< RTC backup register 2, Address offset: 0x58 */ + __IO uint32_t BAKP3; /*!< RTC backup register 3, Address offset: 0x5C */ + __IO uint32_t BAKP4; /*!< RTC backup register 4, Address offset: 0x60 */ + __IO uint32_t BAKP5; /*!< RTC backup register 5, Address offset: 0x64 */ + __IO uint32_t BAKP6; /*!< RTC backup register 6, Address offset: 0x68 */ + __IO uint32_t BAKP7; /*!< RTC backup register 7, Address offset: 0x6C */ + __IO uint32_t BAKP8; /*!< RTC backup register 8, Address offset: 0x70 */ + __IO uint32_t BAKP9; /*!< RTC backup register 9, Address offset: 0x74 */ + __IO uint32_t BAKP10; /*!< RTC backup register 10, Address offset: 0x78 */ + __IO uint32_t BAKP11; /*!< RTC backup register 11, Address offset: 0x7C */ + __IO uint32_t BAKP12; /*!< RTC backup register 12, Address offset: 0x80 */ + __IO uint32_t BAKP13; /*!< RTC backup register 13, Address offset: 0x84 */ + __IO uint32_t BAKP14; /*!< RTC backup register 14, Address offset: 0x88 */ + __IO uint32_t BAKP15; /*!< RTC backup register 15, Address offset: 0x8C */ + __IO uint32_t BAKP16; /*!< RTC backup register 16, Address offset: 0x90 */ + __IO uint32_t BAKP17; /*!< RTC backup register 17, Address offset: 0x94 */ + __IO uint32_t BAKP18; /*!< RTC backup register 18, Address offset: 0x98 */ + __IO uint32_t BAKP19; /*!< RTC backup register 19, Address offset: 0x9C */ +} RTC_TypeDef; + +/** + * @brief SD host Interface + */ + +typedef struct +{ + __IO uint32_t PWRCTRL; /*!< SDIO power control register, Address offset: 0x00 */ + __IO uint32_t CLKCTRL; /*!< SDI clock control register, Address offset: 0x04 */ + __IO uint32_t ARG; /*!< SDIO argument register, Address offset: 0x08 */ + __IO uint32_t CMD; /*!< SDIO command register, Address offset: 0x0C */ + __IO const uint32_t CMDRES; /*!< SDIO command response register, Address offset: 0x10 */ + __IO const uint32_t RES1; /*!< SDIO response 1 register, Address offset: 0x14 */ + __IO const uint32_t RES2; /*!< SDIO response 2 register, Address offset: 0x18 */ + __IO const uint32_t RES3; /*!< SDIO response 3 register, Address offset: 0x1C */ + __IO const uint32_t RES4; /*!< SDIO response 4 register, Address offset: 0x20 */ + __IO uint32_t DATATIME; /*!< SDIO data timer register, Address offset: 0x24 */ + __IO uint32_t DATALEN; /*!< SDIO data length register, Address offset: 0x28 */ + __IO uint32_t DCTRL; /*!< SDIO data control register, Address offset: 0x2C */ + __IO const uint32_t DCNT; /*!< SDIO data counter register, Address offset: 0x30 */ + __IO const uint32_t STS; /*!< SDIO status register, Address offset: 0x34 */ + __IO uint32_t ICF; /*!< SDIO interrupt clear register, Address offset: 0x38 */ + __IO uint32_t MASK; /*!< SDIO mask register, Address offset: 0x3C */ + uint32_t RESERVED0[2]; /*!< Reserved, 0x40-0x44 */ + __IO const uint32_t FIFOCNT; /*!< SDIO FIFO counter register, Address offset: 0x48 */ + uint32_t RESERVED1[13]; /*!< Reserved, 0x4C-0x7C */ + __IO uint32_t FIFODATA; /*!< SDIO data FIFO register, Address offset: 0x80 */ +} SDIO_TypeDef; + +/** + * @brief Serial Peripheral Interface + */ + +typedef struct +{ + __IO uint32_t CTRL1; /*!< SPI control register 1 (not used in I2S mode), Address offset: 0x00 */ + __IO uint32_t CTRL2; /*!< SPI control register 2, Address offset: 0x04 */ + __IO uint32_t STS; /*!< SPI status register, Address offset: 0x08 */ + __IO uint32_t DATA; /*!< SPI data register, Address offset: 0x0C */ + __IO uint32_t CRCPOLY; /*!< SPI CRC polynomial register (not used in I2S mode), Address offset: 0x10 */ + __IO uint32_t RXCRC; /*!< SPI RX CRC register (not used in I2S mode), Address offset: 0x14 */ + __IO uint32_t TXCRC; /*!< SPI TX CRC register (not used in I2S mode), Address offset: 0x18 */ + __IO uint32_t I2SCFG; /*!< SPI_I2S configuration register, Address offset: 0x1C */ + __IO uint32_t I2SPSC; /*!< SPI_I2S prescaler register, Address offset: 0x20 */ +} SPI_TypeDef; + + +/** + * @brief TMR + */ + +typedef struct +{ + __IO uint32_t CTRL1; /*!< TMR control register 1, Address offset: 0x00 */ + __IO uint32_t CTRL2; /*!< TMR control register 2, Address offset: 0x04 */ + __IO uint32_t SMCTRL; /*!< TMR slave mode control register, Address offset: 0x08 */ + __IO uint32_t DIEN; /*!< TMR DMA/interrupt enable register, Address offset: 0x0C */ + __IO uint32_t STS; /*!< TMR status register, Address offset: 0x10 */ + __IO uint32_t CEG; /*!< TMR event generation register, Address offset: 0x14 */ + __IO uint32_t CCM1; /*!< TMR capture/compare mode register 1, Address offset: 0x18 */ + __IO uint32_t CCM2; /*!< TMR capture/compare mode register 2, Address offset: 0x1C */ + __IO uint32_t CCEN; /*!< TMR capture/compare enable register, Address offset: 0x20 */ + __IO uint32_t CNT; /*!< TMR counter register, Address offset: 0x24 */ + __IO uint32_t PSC; /*!< TMR prescaler, Address offset: 0x28 */ + __IO uint32_t AUTORLD; /*!< TMR auto-reload register, Address offset: 0x2C */ + __IO uint32_t REPCNT; /*!< TMR repetition counter register, Address offset: 0x30 */ + __IO uint32_t CC1; /*!< TMR capture/compare register 1, Address offset: 0x34 */ + __IO uint32_t CC2; /*!< TMR capture/compare register 2, Address offset: 0x38 */ + __IO uint32_t CC3; /*!< TMR capture/compare register 3, Address offset: 0x3C */ + __IO uint32_t CC4; /*!< TMR capture/compare register 4, Address offset: 0x40 */ + __IO uint32_t BDT; /*!< TMR break and dead-time register, Address offset: 0x44 */ + __IO uint32_t DCTRL; /*!< TMR DMA control register, Address offset: 0x48 */ + __IO uint32_t DMAR; /*!< TMR DMA address for full transfer, Address offset: 0x4C */ + __IO uint32_t OR; /*!< TMR option register, Address offset: 0x50 */ +} TMR_TypeDef; + +/** + * @brief Universal Synchronous Asynchronous Receiver Transmitter + */ + +typedef struct +{ + __IO uint32_t STS; /*!< USART Status register, Address offset: 0x00 */ + __IO uint32_t DATA; /*!< USART Data register, Address offset: 0x04 */ + __IO uint32_t BR; /*!< USART Baud rate register, Address offset: 0x08 */ + __IO uint32_t CTRL1; /*!< USART Control register 1, Address offset: 0x0C */ + __IO uint32_t CTRL2; /*!< USART Control register 2, Address offset: 0x10 */ + __IO uint32_t CTRL3; /*!< USART Control register 3, Address offset: 0x14 */ + __IO uint32_t GTPSC; /*!< USART Guard time and prescaler register, Address offset: 0x18 */ +} USART_TypeDef; + +/** + * @brief Window WATCHDOG + */ + +typedef struct +{ + __IO uint32_t CTRL; /*!< WWDT Control register, Address offset: 0x00 */ + __IO uint32_t CFR; /*!< WWDT Configuration register, Address offset: 0x04 */ + __IO uint32_t STS; /*!< WWDT Status register, Address offset: 0x08 */ +} WWDT_TypeDef; + +/** + * @brief Crypto Processor + */ + +typedef struct +{ + __IO uint32_t CTRL; /*!< CRYP control register, Address offset: 0x00 */ + __IO uint32_t STS; /*!< CRYP status register, Address offset: 0x04 */ + __IO uint32_t DATAIN; /*!< CRYP data input register, Address offset: 0x08 */ + __IO uint32_t DATAOUT; /*!< CRYP data output register, Address offset: 0x0C */ + __IO uint32_t DMACTRL; /*!< CRYP DMA control register, Address offset: 0x10 */ + __IO uint32_t INTMASK; /*!< CRYP interrupt mask set/clear register, Address offset: 0x14 */ + __IO uint32_t INTSTS; /*!< CRYP raw interrupt status register, Address offset: 0x18 */ + __IO uint32_t MINTSTS; /*!< CRYP masked interrupt status register, Address offset: 0x1C */ + __IO uint32_t K0L; /*!< CRYP key left register 0, Address offset: 0x20 */ + __IO uint32_t K0R; /*!< CRYP key right register 0, Address offset: 0x24 */ + __IO uint32_t K1L; /*!< CRYP key left register 1, Address offset: 0x28 */ + __IO uint32_t K1R; /*!< CRYP key right register 1, Address offset: 0x2C */ + __IO uint32_t K2L; /*!< CRYP key left register 2, Address offset: 0x30 */ + __IO uint32_t K2R; /*!< CRYP key right register 2, Address offset: 0x34 */ + __IO uint32_t K3L; /*!< CRYP key left register 3, Address offset: 0x38 */ + __IO uint32_t K3R; /*!< CRYP key right register 3, Address offset: 0x3C */ + __IO uint32_t IV0L; /*!< CRYP initialization vector left-word register 0, Address offset: 0x40 */ + __IO uint32_t IV0R; /*!< CRYP initialization vector right-word register 0, Address offset: 0x44 */ + __IO uint32_t IV1L; /*!< CRYP initialization vector left-word register 1, Address offset: 0x48 */ + __IO uint32_t IV1R; /*!< CRYP initialization vector right-word register 1, Address offset: 0x4C */ + __IO uint32_t CSGCMCCM0R; /*!< CRYP GCM/GMAC or CCM/CMAC context swap register 0, Address offset: 0x50 */ + __IO uint32_t CSGCMCCM1R; /*!< CRYP GCM/GMAC or CCM/CMAC context swap register 1, Address offset: 0x54 */ + __IO uint32_t CSGCMCCM2R; /*!< CRYP GCM/GMAC or CCM/CMAC context swap register 2, Address offset: 0x58 */ + __IO uint32_t CSGCMCCM3R; /*!< CRYP GCM/GMAC or CCM/CMAC context swap register 3, Address offset: 0x5C */ + __IO uint32_t CSGCMCCM4R; /*!< CRYP GCM/GMAC or CCM/CMAC context swap register 4, Address offset: 0x60 */ + __IO uint32_t CSGCMCCM5R; /*!< CRYP GCM/GMAC or CCM/CMAC context swap register 5, Address offset: 0x64 */ + __IO uint32_t CSGCMCCM6R; /*!< CRYP GCM/GMAC or CCM/CMAC context swap register 6, Address offset: 0x68 */ + __IO uint32_t CSGCMCCM7R; /*!< CRYP GCM/GMAC or CCM/CMAC context swap register 7, Address offset: 0x6C */ + __IO uint32_t CSGCM0R; /*!< CRYP GCM/GMAC context swap register 0, Address offset: 0x70 */ + __IO uint32_t CSGCM1R; /*!< CRYP GCM/GMAC context swap register 1, Address offset: 0x74 */ + __IO uint32_t CSGCM2R; /*!< CRYP GCM/GMAC context swap register 2, Address offset: 0x78 */ + __IO uint32_t CSGCM3R; /*!< CRYP GCM/GMAC context swap register 3, Address offset: 0x7C */ + __IO uint32_t CSGCM4R; /*!< CRYP GCM/GMAC context swap register 4, Address offset: 0x80 */ + __IO uint32_t CSGCM5R; /*!< CRYP GCM/GMAC context swap register 5, Address offset: 0x84 */ + __IO uint32_t CSGCM6R; /*!< CRYP GCM/GMAC context swap register 6, Address offset: 0x88 */ + __IO uint32_t CSGCM7R; /*!< CRYP GCM/GMAC context swap register 7, Address offset: 0x8C */ +} CRYP_TypeDef; + +/** + * @brief HASH + */ + +typedef struct +{ + __IO uint32_t CTRL; /*!< HASH control register, Address offset: 0x00 */ + __IO uint32_t INDATA; /*!< HASH data input register, Address offset: 0x04 */ + __IO uint32_t START; /*!< HASH start register, Address offset: 0x08 */ + __IO uint32_t DIG[5]; /*!< HASH digest registers, Address offset: 0x0C-0x1C */ + __IO uint32_t INT; /*!< HASH interrupt enable register, Address offset: 0x20 */ + __IO uint32_t STS; /*!< HASH status register, Address offset: 0x24 */ + uint32_t RESERVED[52]; /*!< Reserved, 0x28-0xF4 */ + __IO uint32_t CTSWAP[54]; /*!< HASH context swap registers, Address offset: 0x0F8-0x1CC */ +} HASH_TypeDef; + +/** + * @brief HASH_DIGEST + */ + +typedef struct +{ + __IO uint32_t HR[5]; /*!< HASH digest registers, Address offset: 0x310-0x32C */ +} HASH_DIGEST_TypeDef; + +/** + * @brief RNG + */ + +typedef struct +{ + __IO uint32_t CTRL; /*!< RNG control register, Address offset: 0x00 */ + __IO uint32_t STS; /*!< RNG status register, Address offset: 0x04 */ + __IO uint32_t DATA; /*!< RNG data register, Address offset: 0x08 */ +} RNG_TypeDef; + +/** + * @brief USB_OTG_Core_Registers + */ +typedef struct +{ + __IO uint32_t GCTRLSTS; /*!< USB_OTG Control and Status Register 000h */ + __IO uint32_t GINT; /*!< USB_OTG Interrupt Register 004h */ + __IO uint32_t GAHBCFG; /*!< Core AHB Configuration Register 008h */ + __IO uint32_t GUSBCFG; /*!< Core USB Configuration Register 00Ch */ + __IO uint32_t GRSTCTRL; /*!< Core Reset Register 010h */ + __IO uint32_t GCINT; /*!< Core Interrupt Register 014h */ + __IO uint32_t GINTMASK; /*!< Core Interrupt Mask Register 018h */ + __IO uint32_t GRXSTS; /*!< Receive Sts Q Read Register 01Ch */ + __IO uint32_t GRXSTSP; /*!< Receive Sts Q Read & POP Register 020h */ + __IO uint32_t GRXFIFO; /*!< Receive FIFO Size Register 024h */ + __IO uint32_t GTXFCFG; /*!< EP0 / Non Periodic Tx FIFO Size Register 028h */ + __IO uint32_t GNPTXFQSTS; /*!< Non Periodic Tx FIFO/Queue Sts reg 02Ch */ + uint32_t Reserved30[2]; /*!< Reserved 030h */ + __IO uint32_t GGCCFG; /*!< General Purpose IO Register 038h */ + __IO uint32_t GCID; /*!< User ID Register 03Ch */ + uint32_t Reserved40[48]; /*!< Reserved 0x40-0xFF */ + __IO uint32_t GHPTXFSIZE; /*!< Host Periodic Tx FIFO Size Reg 100h */ + __IO uint32_t DTXFIFO[0x0F]; /*!< dev Periodic Transmit FIFO */ +} USB_OTG_GlobalTypeDef; + +/** + * @brief USB_OTG_device_Registers + */ +typedef struct +{ + __IO uint32_t DCFG; /*!< dev Configuration Register 800h */ + __IO uint32_t DCTRL; /*!< dev Control Register 804h */ + __IO uint32_t DSTS; /*!< dev Status Register (RO) 808h */ + uint32_t Reserved0C; /*!< Reserved 80Ch */ + __IO uint32_t DINIMASK; /*!< dev IN Endpoint Mask 810h */ + __IO uint32_t DOUTIMASK; /*!< dev OUT Endpoint Mask 814h */ + __IO uint32_t DAEPINT; /*!< dev All Endpoints Itr Reg 818h */ + __IO uint32_t DAEPIMASK; /*!< dev All Endpoints Itr Mask 81Ch */ + uint32_t Reserved20; /*!< Reserved 820h */ + uint32_t Reserved9; /*!< Reserved 824h */ + __IO uint32_t DVBUSDTIM; /*!< dev VBUS discharge Register 828h */ + __IO uint32_t DVBUSPTIM; /*!< dev VBUS Pulse Register 82Ch */ + __IO uint32_t DTHCTRL; /*!< dev threshold 830h */ + __IO uint32_t DIEIMASK; /*!< dev empty msk 834h */ + __IO uint32_t DEPINT; /*!< dedicated EP interrupt 838h */ + __IO uint32_t DEPIMASK; /*!< dedicated EP msk 83Ch */ + uint32_t Reserved40; /*!< dedicated EP mask 840h */ + __IO uint32_t DIN1IMASK; /*!< dedicated EP mask 844h */ + uint32_t Reserved44[15]; /*!< Reserved 844-87Ch */ + __IO uint32_t DOUT1MASK; /*!< dedicated EP msk 884h */ +} USB_OTG_DeviceTypeDef; + +/** + * @brief USB_OTG_IN_Endpoint-Specific_Register + */ +typedef struct +{ + __IO uint32_t DIEPCTRL; /*!< dev IN Endpoint Control Reg 900h + (ep_num * 20h) + 00h */ + uint32_t Reserved04; /*!< Reserved 900h + (ep_num * 20h) + 04h */ + __IO uint32_t DIEPINT; /*!< dev IN Endpoint Itr Reg 900h + (ep_num * 20h) + 08h */ + uint32_t Reserved0C; /*!< Reserved 900h + (ep_num * 20h) + 0Ch */ + __IO uint32_t DIEPTRS; /*!< IN Endpoint Txfer Size 900h + (ep_num * 20h) + 10h */ + __IO uint32_t DIEPDMA; /*!< IN Endpoint DMA Address Reg 900h + (ep_num * 20h) + 14h */ + __IO uint32_t DITXFSTS; /*!< IN Endpoint Tx FIFO Status Reg 900h + (ep_num * 20h) + 18h */ + uint32_t Reserved18; /*!< Reserved 900h+(ep_num*20h)+1Ch-900h+ (ep_num * 20h) + 1Ch */ +} USB_OTG_INEndpointTypeDef; + +/** + * @brief USB_OTG_OUT_Endpoint-Specific_Registers + */ +typedef struct +{ + __IO uint32_t DOEPCTRL; /*!< dev OUT Endpoint Control Reg B00h + (ep_num * 20h) + 00h */ + uint32_t Reserved04; /*!< Reserved B00h + (ep_num * 20h) + 04h */ + __IO uint32_t DOEPINT; /*!< dev OUT Endpoint Itr Reg B00h + (ep_num * 20h) + 08h */ + uint32_t Reserved0C; /*!< Reserved B00h + (ep_num * 20h) + 0Ch */ + __IO uint32_t DOEPTRS; /*!< dev OUT Endpoint Txfer Size B00h + (ep_num * 20h) + 10h */ + __IO uint32_t DOEPDMA; /*!< dev OUT Endpoint DMA Address B00h + (ep_num * 20h) + 14h */ + uint32_t Reserved18[2]; /*!< Reserved B00h + (ep_num * 20h) + 18h - B00h + (ep_num * 20h) + 1Ch */ +} USB_OTG_OUTEndpointTypeDef; + +/** + * @brief USB_OTG_Host_Mode_Register_Structures + */ +typedef struct +{ + __IO uint32_t HCFG; /*!< Host Configuration Register 400h */ + __IO uint32_t HFIVL; /*!< Host Frame Interval Register 404h */ + __IO uint32_t HFIFM; /*!< Host Frame Nbr/Frame Remaining 408h */ + uint32_t Reserved40C; /*!< Reserved 40Ch */ + __IO uint32_t HPTXSTS; /*!< Host Periodic Tx FIFO/ Queue Status 410h */ + __IO uint32_t HACHINT; /*!< Host All Channels Interrupt Register 414h */ + __IO uint32_t HACHIMASK; /*!< Host All Channels Interrupt Mask 418h */ +} USB_OTG_HostTypeDef; + +/** + * @brief USB_OTG_Host_Channel_Specific_Registers + */ +typedef struct +{ + __IO uint32_t HCH; /*!< Host Channel Characteristics Register 500h */ + __IO uint32_t HCHSCTRL; /*!< Host Channel Split Control Register 504h */ + __IO uint32_t HCHINT; /*!< Host Channel Interrupt Register 508h */ + __IO uint32_t HCHIMASK; /*!< Host Channel Interrupt Mask Register 50Ch */ + __IO uint32_t HCHTSIZE; /*!< Host Channel Transfer Size Register 510h */ + __IO uint32_t HCHDMA; /*!< Host Channel DMA Address Register 514h */ + uint32_t Reserved[2]; /*!< Reserved */ +} USB_OTG_HostChannelTypeDef; + +/** + * @brief USB_OTG_HS2_Specific_Registers + */ +typedef struct +{ + __IO uint32_t USB_SWITCH; /*!< USB Switch Register 200h */ + __IO uint32_t POWERON_CORE; /*!< Power On Core Register 204h */ + __IO uint32_t USB_PLL_EN; /*!< USB PLL Enable Register 208h */ + __IO uint32_t SHORT_5V_ENABLE; /*!< VBUS Short 5V Enable 20Ch */ + __IO uint32_t OTG_SUSPENDM; /*!< OTG VBUS Suspend 210h */ + __IO uint32_t TXBITSTUFFENABLE; /*!< TX Bit Stuff Enable 214h */ + __IO uint32_t PLLICP_SEL_I2C; /*!< PLL Charge Current Setting 218h */ + __IO uint32_t HSZR_CNTL_I2C; /*!< The DP/DM to the Ground Impedance Setting 21Ch */ + __IO uint32_t SQVTH_CNTL_I2C; /*!< The SQ Reference Voltage Setting 220h*/ + __IO uint32_t SW_RREF_I2C; /*!< The DP/DM Output Swing Setting When HS Mode 224h */ + __IO uint32_t SW_BUF_I2C; /*!< The TX Driver Setting 228h */ + __IO uint32_t TX2RX_T_CFG_I2C; /*!< Debug Control Signal 22Ch */ + __IO uint32_t TEST_ANA_FAST_I2C; /*!< Debug Control Signal 230h */ + __IO uint32_t CLK_MODE_I2C; /*!< Debug control signal 234h */ + __IO uint32_t USB_DBNCE_FLTR_BYPASS; /*!< Bypass debounce filters for avalid, bvalid, vbusvalid, + sessend, iddig signals when enabled 238h */ + __IO uint32_t USB_SS_SCALEDOWN_MODE; /*!< Used only in simulation 23Ch */ +} USB_OTG_HS2TypeDef; + +/** + * @} + */ + +/** @addtogroup Peripheral_memory_map + * @{ + */ +#define FLASH_BASE 0x08000000UL /*!< FLASH(up to 1 MB) base address in the alias region */ +#define CCMDATARAM_BASE 0x10000000UL /*!< CCM(core coupled memory) data RAM(64 KB) base address in the alias region */ +#define SRAM1_BASE 0x20000000UL /*!< SRAM1(112 KB) base address in the alias region */ +#define SRAM2_BASE 0x2001C000UL /*!< SRAM2(16 KB) base address in the alias region */ +#define PERIPH_BASE 0x40000000UL /*!< Peripheral base address in the alias region */ +#define BKPSRAM_BASE 0x40024000UL /*!< Backup SRAM(4 KB) base address in the alias region */ +#define SMC_R_BASE 0xA0000000UL /*!< SMC registers base address */ +#define SRAM1_BB_BASE 0x22000000UL /*!< SRAM1(112 KB) base address in the bit-band region */ +#define SRAM2_BB_BASE 0x22380000UL /*!< SRAM2(16 KB) base address in the bit-band region */ +#define PERIPH_BB_BASE 0x42000000UL /*!< Peripheral base address in the bit-band region */ +#define BKPSRAM_BB_BASE 0x42480000UL /*!< Backup SRAM(4 KB) base address in the bit-band region */ +#define FLASH_END 0x080FFFFFUL /*!< FLASH end address */ +#define FLASH_OTP_BASE 0x1FFF7800UL /*!< Base address of : (up to 528 Bytes) embedded FLASH OTP Area */ +#define FLASH_OTP_END 0x1FFF7A0FUL /*!< End address of : (up to 528 Bytes) embedded FLASH OTP Area */ +#define CCMDATARAM_END 0x1000FFFFUL /*!< CCM data RAM end address */ + +/* Legacy defines */ +#define SRAM_BASE SRAM1_BASE +#define SRAM_BB_BASE SRAM1_BB_BASE + +/*!< Peripheral memory map */ +#define APB1PERIPH_BASE PERIPH_BASE +#define APB2PERIPH_BASE (PERIPH_BASE + 0x00010000UL) +#define AHB1PERIPH_BASE (PERIPH_BASE + 0x00020000UL) +#define AHB2PERIPH_BASE (PERIPH_BASE + 0x10000000UL) + +/*!< APB1 peripherals */ +#define TMR2_BASE (APB1PERIPH_BASE + 0x0000UL) +#define TMR3_BASE (APB1PERIPH_BASE + 0x0400UL) +#define TMR4_BASE (APB1PERIPH_BASE + 0x0800UL) +#define TMR5_BASE (APB1PERIPH_BASE + 0x0C00UL) +#define TMR6_BASE (APB1PERIPH_BASE + 0x1000UL) +#define TMR7_BASE (APB1PERIPH_BASE + 0x1400UL) +#define TMR12_BASE (APB1PERIPH_BASE + 0x1800UL) +#define TMR13_BASE (APB1PERIPH_BASE + 0x1C00UL) +#define TMR14_BASE (APB1PERIPH_BASE + 0x2000UL) +#define RTC_BASE (APB1PERIPH_BASE + 0x2800UL) +#define WWDT_BASE (APB1PERIPH_BASE + 0x2C00UL) +#define IWDT_BASE (APB1PERIPH_BASE + 0x3000UL) +#define I2S2ext_BASE (APB1PERIPH_BASE + 0x3400UL) +#define SPI2_BASE (APB1PERIPH_BASE + 0x3800UL) +#define SPI3_BASE (APB1PERIPH_BASE + 0x3C00UL) +#define I2S3ext_BASE (APB1PERIPH_BASE + 0x4000UL) +#define USART2_BASE (APB1PERIPH_BASE + 0x4400UL) +#define USART3_BASE (APB1PERIPH_BASE + 0x4800UL) +#define UART4_BASE (APB1PERIPH_BASE + 0x4C00UL) +#define UART5_BASE (APB1PERIPH_BASE + 0x5000UL) +#define I2C1_BASE (APB1PERIPH_BASE + 0x5400UL) +#define I2C2_BASE (APB1PERIPH_BASE + 0x5800UL) +#define I2C3_BASE (APB1PERIPH_BASE + 0x5C00UL) +#define CAN1_BASE (APB1PERIPH_BASE + 0x6400UL) +#define CAN2_BASE (APB1PERIPH_BASE + 0x6800UL) +#define PMU_BASE (APB1PERIPH_BASE + 0x7000UL) +#define DAC_BASE (APB1PERIPH_BASE + 0x7400UL) + +/*!< APB2 peripherals */ +#define TMR1_BASE (APB2PERIPH_BASE + 0x0000UL) +#define TMR8_BASE (APB2PERIPH_BASE + 0x0400UL) +#define USART1_BASE (APB2PERIPH_BASE + 0x1000UL) +#define USART6_BASE (APB2PERIPH_BASE + 0x1400UL) +#define ADC1_BASE (APB2PERIPH_BASE + 0x2000UL) +#define ADC2_BASE (APB2PERIPH_BASE + 0x2100UL) +#define ADC3_BASE (APB2PERIPH_BASE + 0x2200UL) +#define ADC123_COMMON_BASE (APB2PERIPH_BASE + 0x2300UL) +/* Legacy define */ +#define ADC_BASE ADC123_COMMON_BASE +#define SDIO_BASE (APB2PERIPH_BASE + 0x2C00UL) +#define SPI1_BASE (APB2PERIPH_BASE + 0x3000UL) +#define SYSCFG_BASE (APB2PERIPH_BASE + 0x3800UL) +#define EINT_BASE (APB2PERIPH_BASE + 0x3C00UL) +#define TMR9_BASE (APB2PERIPH_BASE + 0x4000UL) +#define TMR10_BASE (APB2PERIPH_BASE + 0x4400UL) +#define TMR11_BASE (APB2PERIPH_BASE + 0x4800UL) + +/*!< AHB1 peripherals */ +#define GPIOA_BASE (AHB1PERIPH_BASE + 0x0000UL) +#define GPIOB_BASE (AHB1PERIPH_BASE + 0x0400UL) +#define GPIOC_BASE (AHB1PERIPH_BASE + 0x0800UL) +#define GPIOD_BASE (AHB1PERIPH_BASE + 0x0C00UL) +#define GPIOE_BASE (AHB1PERIPH_BASE + 0x1000UL) +#define GPIOF_BASE (AHB1PERIPH_BASE + 0x1400UL) +#define GPIOG_BASE (AHB1PERIPH_BASE + 0x1800UL) +#define GPIOH_BASE (AHB1PERIPH_BASE + 0x1C00UL) +#define GPIOI_BASE (AHB1PERIPH_BASE + 0x2000UL) +#define CRC_BASE (AHB1PERIPH_BASE + 0x3000UL) +#define RCM_BASE (AHB1PERIPH_BASE + 0x3800UL) +#define FLASH_R_BASE (AHB1PERIPH_BASE + 0x3C00UL) +#define DMA1_BASE (AHB1PERIPH_BASE + 0x6000UL) +#define DMA1_Stream0_BASE (DMA1_BASE + 0x010UL) +#define DMA1_Stream1_BASE (DMA1_BASE + 0x028UL) +#define DMA1_Stream2_BASE (DMA1_BASE + 0x040UL) +#define DMA1_Stream3_BASE (DMA1_BASE + 0x058UL) +#define DMA1_Stream4_BASE (DMA1_BASE + 0x070UL) +#define DMA1_Stream5_BASE (DMA1_BASE + 0x088UL) +#define DMA1_Stream6_BASE (DMA1_BASE + 0x0A0UL) +#define DMA1_Stream7_BASE (DMA1_BASE + 0x0B8UL) +#define DMA2_BASE (AHB1PERIPH_BASE + 0x6400UL) +#define DMA2_Stream0_BASE (DMA2_BASE + 0x010UL) +#define DMA2_Stream1_BASE (DMA2_BASE + 0x028UL) +#define DMA2_Stream2_BASE (DMA2_BASE + 0x040UL) +#define DMA2_Stream3_BASE (DMA2_BASE + 0x058UL) +#define DMA2_Stream4_BASE (DMA2_BASE + 0x070UL) +#define DMA2_Stream5_BASE (DMA2_BASE + 0x088UL) +#define DMA2_Stream6_BASE (DMA2_BASE + 0x0A0UL) +#define DMA2_Stream7_BASE (DMA2_BASE + 0x0B8UL) +#define ETH_BASE (AHB1PERIPH_BASE + 0x8000UL) +#define ETH_MAC_BASE (ETH_BASE) +#define ETH_MMC_BASE (ETH_BASE + 0x0100UL) +#define ETH_PTP_BASE (ETH_BASE + 0x0700UL) +#define ETH_DMA_BASE (ETH_BASE + 0x1000UL) + +/*!< AHB2 peripherals */ +#define DCI_BASE (AHB2PERIPH_BASE + 0x50000UL) +#define CRYP_BASE (AHB2PERIPH_BASE + 0x60000UL) +#define HASH_BASE (AHB2PERIPH_BASE + 0x60400UL) +#define HASH_DIGEST_BASE (AHB2PERIPH_BASE + 0x60710UL) +#define RNG_BASE (AHB2PERIPH_BASE + 0x60800UL) + +/*!< SMC Bankx registers base address */ +#define SMC_Bank1_R_BASE (SMC_R_BASE + 0x0000UL) +#define SMC_Bank1E_R_BASE (SMC_R_BASE + 0x0104UL) +#define SMC_Bank2_3_R_BASE (SMC_R_BASE + 0x0060UL) +#define SMC_Bank4_R_BASE (SMC_R_BASE + 0x00A0UL) + +/*!< DMC registers base address */ +#define DMC_BASE ((uint32_t)0xA0000000UL) + +/*!< Debug MCU registers base address */ +#define DBGMCU_BASE 0xE0042000UL +/*!< USB registers base address */ +#define USB_OTG_HS2_PERIPH_BASE 0x40040200UL +#define USB_OTG_HS_PERIPH_BASE 0x40040000UL +#define USB_OTG_FS_PERIPH_BASE 0x50000000UL + +#define USB_OTG_GLOBAL_BASE 0x000UL +#define USB_OTG_DEVICE_BASE 0x800UL +#define USB_OTG_IN_ENDPOINT_BASE 0x900UL +#define USB_OTG_OUT_ENDPOINT_BASE 0xB00UL +#define USB_OTG_EP_REG_SIZE 0x20UL +#define USB_OTG_HOST_BASE 0x400UL +#define USB_OTG_HOST_PORT_BASE 0x440UL +#define USB_OTG_HOST_CHANNEL_BASE 0x500UL +#define USB_OTG_HOST_CHANNEL_SIZE 0x20UL +#define USB_OTG_PCGCCTL_BASE 0xE00UL +#define USB_OTG_FIFO_BASE 0x1000UL +#define USB_OTG_FIFO_SIZE 0x1000UL + +#define UID_BASE 0x1FFF7A10UL /*!< Unique device ID register base address */ +#define FLASHSIZE_BASE 0x1FFF7A22UL /*!< FLASH Size register base address */ +#define PACKAGE_BASE 0x1FFF7BF0UL /*!< Package size register base address */ +/** + * @} + */ + +/** @addtogroup Peripheral_declaration + * @{ + */ +#define TMR2 ((TMR_TypeDef *) TMR2_BASE) +#define TMR3 ((TMR_TypeDef *) TMR3_BASE) +#define TMR4 ((TMR_TypeDef *) TMR4_BASE) +#define TMR5 ((TMR_TypeDef *) TMR5_BASE) +#define TMR6 ((TMR_TypeDef *) TMR6_BASE) +#define TMR7 ((TMR_TypeDef *) TMR7_BASE) +#define TMR12 ((TMR_TypeDef *) TMR12_BASE) +#define TMR13 ((TMR_TypeDef *) TMR13_BASE) +#define TMR14 ((TMR_TypeDef *) TMR14_BASE) +#define RTC ((RTC_TypeDef *) RTC_BASE) +#define WWDT ((WWDT_TypeDef *) WWDT_BASE) +#define IWDT ((IWDT_TypeDef *) IWDT_BASE) +#define I2S2ext ((SPI_TypeDef *) I2S2ext_BASE) +#define SPI2 ((SPI_TypeDef *) SPI2_BASE) +#define SPI3 ((SPI_TypeDef *) SPI3_BASE) +#define I2S3ext ((SPI_TypeDef *) I2S3ext_BASE) +#define USART2 ((USART_TypeDef *) USART2_BASE) +#define USART3 ((USART_TypeDef *) USART3_BASE) +#define UART4 ((USART_TypeDef *) UART4_BASE) +#define UART5 ((USART_TypeDef *) UART5_BASE) +#define I2C1 ((I2C_TypeDef *) I2C1_BASE) +#define I2C2 ((I2C_TypeDef *) I2C2_BASE) +#define I2C3 ((I2C_TypeDef *) I2C3_BASE) +#define CAN1 ((CAN_TypeDef *) CAN1_BASE) +#define CAN2 ((CAN_TypeDef *) CAN2_BASE) +#define PMU ((PMU_TypeDef *) PMU_BASE) +#define DAC1 ((DAC_TypeDef *) DAC_BASE) +#define DAC ((DAC_TypeDef *) DAC_BASE) /* Kept for legacy purpose */ +#define TMR1 ((TMR_TypeDef *) TMR1_BASE) +#define TMR8 ((TMR_TypeDef *) TMR8_BASE) +#define USART1 ((USART_TypeDef *) USART1_BASE) +#define USART6 ((USART_TypeDef *) USART6_BASE) +#define ADC1 ((ADC_TypeDef *) ADC1_BASE) +#define ADC2 ((ADC_TypeDef *) ADC2_BASE) +#define ADC3 ((ADC_TypeDef *) ADC3_BASE) +#define ADC123_COMMON ((ADC_Common_TypeDef *) ADC123_COMMON_BASE) +/* Legacy define */ +#define ADC ADC123_COMMON +#define SDIO ((SDIO_TypeDef *) SDIO_BASE) +#define SPI1 ((SPI_TypeDef *) SPI1_BASE) +#define SYSCFG ((SYSCFG_TypeDef *) SYSCFG_BASE) +#define EINT ((EINT_TypeDef *) EINT_BASE) +#define TMR9 ((TMR_TypeDef *) TMR9_BASE) +#define TMR10 ((TMR_TypeDef *) TMR10_BASE) +#define TMR11 ((TMR_TypeDef *) TMR11_BASE) +#define GPIOA ((GPIO_TypeDef *) GPIOA_BASE) +#define GPIOB ((GPIO_TypeDef *) GPIOB_BASE) +#define GPIOC ((GPIO_TypeDef *) GPIOC_BASE) +#define GPIOD ((GPIO_TypeDef *) GPIOD_BASE) +#define GPIOE ((GPIO_TypeDef *) GPIOE_BASE) +#define GPIOF ((GPIO_TypeDef *) GPIOF_BASE) +#define GPIOG ((GPIO_TypeDef *) GPIOG_BASE) +#define GPIOH ((GPIO_TypeDef *) GPIOH_BASE) +#define GPIOI ((GPIO_TypeDef *) GPIOI_BASE) +#define CRC ((CRC_TypeDef *) CRC_BASE) +#define RCM ((RCM_TypeDef *) RCM_BASE) +#define FLASH ((FLASH_TypeDef *) FLASH_R_BASE) +#define DMA1 ((DMA_TypeDef *) DMA1_BASE) +#define DMA1_Stream0 ((DMA_Stream_TypeDef *) DMA1_Stream0_BASE) +#define DMA1_Stream1 ((DMA_Stream_TypeDef *) DMA1_Stream1_BASE) +#define DMA1_Stream2 ((DMA_Stream_TypeDef *) DMA1_Stream2_BASE) +#define DMA1_Stream3 ((DMA_Stream_TypeDef *) DMA1_Stream3_BASE) +#define DMA1_Stream4 ((DMA_Stream_TypeDef *) DMA1_Stream4_BASE) +#define DMA1_Stream5 ((DMA_Stream_TypeDef *) DMA1_Stream5_BASE) +#define DMA1_Stream6 ((DMA_Stream_TypeDef *) DMA1_Stream6_BASE) +#define DMA1_Stream7 ((DMA_Stream_TypeDef *) DMA1_Stream7_BASE) +#define DMA2 ((DMA_TypeDef *) DMA2_BASE) +#define DMA2_Stream0 ((DMA_Stream_TypeDef *) DMA2_Stream0_BASE) +#define DMA2_Stream1 ((DMA_Stream_TypeDef *) DMA2_Stream1_BASE) +#define DMA2_Stream2 ((DMA_Stream_TypeDef *) DMA2_Stream2_BASE) +#define DMA2_Stream3 ((DMA_Stream_TypeDef *) DMA2_Stream3_BASE) +#define DMA2_Stream4 ((DMA_Stream_TypeDef *) DMA2_Stream4_BASE) +#define DMA2_Stream5 ((DMA_Stream_TypeDef *) DMA2_Stream5_BASE) +#define DMA2_Stream6 ((DMA_Stream_TypeDef *) DMA2_Stream6_BASE) +#define DMA2_Stream7 ((DMA_Stream_TypeDef *) DMA2_Stream7_BASE) +#define ETH ((ETH_TypeDef *) ETH_BASE) +#define DCI ((DCI_TypeDef *) DCI_BASE) +#define CRYP ((CRYP_TypeDef *) CRYP_BASE) +#define HASH ((HASH_TypeDef *) HASH_BASE) +#define HASH_DIGEST ((HASH_DIGEST_TypeDef *) HASH_DIGEST_BASE) +#define RNG ((RNG_TypeDef *) RNG_BASE) +#define SMC_Bank1 ((SMC_Bank1_TypeDef *) SMC_Bank1_R_BASE) +#define SMC_Bank1E ((SMC_Bank1E_TypeDef *) SMC_Bank1E_R_BASE) +#define SMC_Bank2_3 ((SMC_Bank2_3_TypeDef *) SMC_Bank2_3_R_BASE) +#define SMC_Bank4 ((SMC_Bank4_TypeDef *) SMC_Bank4_R_BASE) +#define DBGMCU ((DBGMCU_TypeDef *) DBGMCU_BASE) +#define USB_OTG_FS ((USB_OTG_GlobalTypeDef *) USB_OTG_FS_PERIPH_BASE) +#define USB_OTG_HS ((USB_OTG_GlobalTypeDef *) USB_OTG_HS_PERIPH_BASE) +#define USB_OTG_HS2 ((USB_OTG_HS2TypeDef *) USB_OTG_HS2_PERIPH_BASE) +#define DMC ((DMC_TypeDef *) DMC_BASE) + +/** + * @} + */ + +/** @addtogroup Exported_constants + * @{ + */ + +/** @addtogroup Hardware_Constant_Definition + * @{ + */ +#define LSI_STARTUP_TIME 40U /*!< LSI Maximum startup time in us */ +/** + * @} + */ + + /** @addtogroup Peripheral_Registers_Bits_Definition + * @{ + */ + +/******************************************************************************/ +/* Peripheral Registers_Bits_Definition */ +/******************************************************************************/ + +/******************************************************************************/ +/* */ +/* Analog to Digital Converter */ +/* */ +/******************************************************************************/ +/* + * @brief Specific device feature definitions (not present on all devices in the APM32F4 serie) + */ +#define ADC_MULTIMODE_SUPPORT /*! + +/** @addtogroup Peripheral_registers_structures + * @{ + */ + +/** + * @brief Analog to Digital Converter + */ + +typedef struct +{ + __IO uint32_t STS; /*!< ADC status register, Address offset: 0x00 */ + __IO uint32_t CTRL1; /*!< ADC control register 1, Address offset: 0x04 */ + __IO uint32_t CTRL2; /*!< ADC control register 2, Address offset: 0x08 */ + __IO uint32_t SMPTIM1; /*!< ADC sample time register 1, Address offset: 0x0C */ + __IO uint32_t SMPTIM2; /*!< ADC sample time register 2, Address offset: 0x10 */ + __IO uint32_t INJDOF1; /*!< ADC injected channel data offset register 1, Address offset: 0x14 */ + __IO uint32_t INJDOF2; /*!< ADC injected channel data offset register 2, Address offset: 0x18 */ + __IO uint32_t INJDOF3; /*!< ADC injected channel data offset register 3, Address offset: 0x1C */ + __IO uint32_t INJDOF4; /*!< ADC injected channel data offset register 4, Address offset: 0x20 */ + __IO uint32_t AWDHT; /*!< ADC watchdog higher threshold register, Address offset: 0x24 */ + __IO uint32_t AWDLT; /*!< ADC watchdog lower threshold register, Address offset: 0x28 */ + __IO uint32_t REGSEQ1; /*!< ADC regular sequence register 1, Address offset: 0x2C */ + __IO uint32_t REGSEQ2; /*!< ADC regular sequence register 2, Address offset: 0x30 */ + __IO uint32_t REGSEQ3; /*!< ADC regular sequence register 3, Address offset: 0x34 */ + __IO uint32_t INJSEQ; /*!< ADC injected sequence register, Address offset: 0x38 */ + __IO uint32_t INJDATA1; /*!< ADC injected data register 1, Address offset: 0x3C */ + __IO uint32_t INJDATA2; /*!< ADC injected data register 2, Address offset: 0x40 */ + __IO uint32_t INJDATA3; /*!< ADC injected data register 3, Address offset: 0x44 */ + __IO uint32_t INJDATA4; /*!< ADC injected data register 4, Address offset: 0x48 */ + __IO uint32_t REGDATA; /*!< ADC regular data register, Address offset: 0x4C */ +} ADC_TypeDef; + +typedef struct +{ + __IO uint32_t CSTS; /*!< ADC Common status register, Address offset: ADC1 base address + 0x300 */ + __IO uint32_t CCTRL; /*!< ADC common control register, Address offset: ADC1 base address + 0x304 */ + __IO uint32_t CDATA; /*!< ADC common regular data register for dual + AND triple modes, Address offset: ADC1 base address + 0x308 */ +} ADC_Common_TypeDef; + + +/** + * @brief Controller Area Network TxMailBox + */ + +typedef struct +{ + __IO uint32_t TXMID; /*!< CAN TX mailbox identifier register */ + __IO uint32_t TXDLEN; /*!< CAN mailbox data length control and time stamp register */ + __IO uint32_t TXMDL; /*!< CAN mailbox data low register */ + __IO uint32_t TXMDH; /*!< CAN mailbox data high register */ +} CAN_TxMailBox_TypeDef; + +/** + * @brief Controller Area Network FIFOMailBox + */ + +typedef struct +{ + __IO uint32_t RXMID; /*!< CAN receive FIFO mailbox identifier register */ + __IO uint32_t RXDLEN; /*!< CAN receive FIFO mailbox data length control and time stamp register */ + __IO uint32_t RXMDL; /*!< CAN receive FIFO mailbox data low register */ + __IO uint32_t RXMDH; /*!< CAN receive FIFO mailbox data high register */ +} CAN_FIFOMailBox_TypeDef; + +/** + * @brief Controller Area Network FilterRegister + */ + +typedef struct +{ + __IO uint32_t FBANK1; /*!< CAN Filter bank register 1 */ + __IO uint32_t FBANK2; /*!< CAN Filter bank register 1 */ +} CAN_FilterRegister_TypeDef; + +/** + * @brief Controller Area Network + */ + +typedef struct +{ + __IO uint32_t MCTRL; /*!< CAN master control register, Address offset: 0x00 */ + __IO uint32_t MSTS; /*!< CAN master status register, Address offset: 0x04 */ + __IO uint32_t TXSTS; /*!< CAN transmit status register, Address offset: 0x08 */ + __IO uint32_t RXF0; /*!< CAN receive FIFO 0 register, Address offset: 0x0C */ + __IO uint32_t RXF1; /*!< CAN receive FIFO 1 register, Address offset: 0x10 */ + __IO uint32_t INTEN; /*!< CAN interrupt enable register, Address offset: 0x14 */ + __IO uint32_t ERRSTS; /*!< CAN error status register, Address offset: 0x18 */ + __IO uint32_t BITTIM; /*!< CAN bit timing register, Address offset: 0x1C */ + uint32_t RESERVED0[88]; /*!< Reserved, 0x020 - 0x17F */ + CAN_TxMailBox_TypeDef sTxMailBox[3]; /*!< CAN Tx MailBox, Address offset: 0x180 - 0x1AC */ + CAN_FIFOMailBox_TypeDef sFIFOMailBox[2]; /*!< CAN FIFO MailBox, Address offset: 0x1B0 - 0x1CC */ + uint32_t RESERVED1[12]; /*!< Reserved, 0x1D0 - 0x1FF */ + __IO uint32_t FCTRL; /*!< CAN filter master register, Address offset: 0x200 */ + __IO uint32_t FMCFG; /*!< CAN filter mode register, Address offset: 0x204 */ + uint32_t RESERVED2; /*!< Reserved, 0x208 */ + __IO uint32_t FSCFG; /*!< CAN filter scale register, Address offset: 0x20C */ + uint32_t RESERVED3; /*!< Reserved, 0x210 */ + __IO uint32_t FFASS; /*!< CAN filter FIFO assignment register, Address offset: 0x214 */ + uint32_t RESERVED4; /*!< Reserved, 0x218 */ + __IO uint32_t FACT; /*!< CAN filter activation register, Address offset: 0x21C */ + uint32_t RESERVED5[8]; /*!< Reserved, 0x220-0x23F */ + CAN_FilterRegister_TypeDef sFilterRegister[28]; /*!< CAN Filter Register, Address offset: 0x240-0x31C */ +} CAN_TypeDef; + +/** + * @brief CRC calculation unit + */ + +typedef struct +{ + __IO uint32_t DATA; /*!< CRC Data register, Address offset: 0x00 */ + __IO uint8_t INDATA; /*!< CRC Independent data register, Address offset: 0x04 */ + uint8_t RESERVED0; /*!< Reserved, 0x05 */ + uint16_t RESERVED1; /*!< Reserved, 0x06 */ + __IO uint32_t CTRL; /*!< CRC Control register, Address offset: 0x08 */ +} CRC_TypeDef; + +/** + * @brief Digital to Analog Converter + */ + +typedef struct +{ + __IO uint32_t CTRL; /*!< DAC control register, Address offset: 0x00 */ + __IO uint32_t SWTRG; /*!< DAC software trigger register, Address offset: 0x04 */ + __IO uint32_t DH12R1; /*!< DAC channel1 12-bit right-aligned data holding register, Address offset: 0x08 */ + __IO uint32_t DH12L1; /*!< DAC channel1 12-bit left aligned data holding register, Address offset: 0x0C */ + __IO uint32_t DH8R1; /*!< DAC channel1 8-bit right aligned data holding register, Address offset: 0x10 */ + __IO uint32_t DH12R2; /*!< DAC channel2 12-bit right aligned data holding register, Address offset: 0x14 */ + __IO uint32_t DH12L2; /*!< DAC channel2 12-bit left aligned data holding register, Address offset: 0x18 */ + __IO uint32_t DH8R2; /*!< DAC channel2 8-bit right-aligned data holding register, Address offset: 0x1C */ + __IO uint32_t DH12RDUAL; /*!< Dual DAC 12-bit right-aligned data holding register, Address offset: 0x20 */ + __IO uint32_t DH12LDUAL; /*!< DUAL DAC 12-bit left aligned data holding register, Address offset: 0x24 */ + __IO uint32_t DH8RDUAL; /*!< DUAL DAC 8-bit right aligned data holding register, Address offset: 0x28 */ + __IO uint32_t DATAOCH1; /*!< DAC channel1 data output register, Address offset: 0x2C */ + __IO uint32_t DATAOCH2; /*!< DAC channel2 data output register, Address offset: 0x30 */ + __IO uint32_t STS; /*!< DAC status register, Address offset: 0x34 */ +} DAC_TypeDef; + +/** + * @brief Debug MCU + */ + +typedef struct +{ + __IO uint32_t IDCODE; /*!< MCU device ID code, Address offset: 0x00 */ + __IO uint32_t CFG; /*!< Debug MCU configuration register, Address offset: 0x04 */ + __IO uint32_t APB1F; /*!< Debug MCU APB1 freeze register, Address offset: 0x08 */ + __IO uint32_t APB2F; /*!< Debug MCU APB2 freeze register, Address offset: 0x0C */ +} DBGMCU_TypeDef; + +/** + * @brief DMA Controller + */ + +typedef struct +{ + __IO uint32_t SCFG; /*!< DMA stream x configuration register */ + __IO uint32_t NDATA; /*!< DMA stream x number of data register */ + __IO uint32_t PADDR; /*!< DMA stream x peripheral address register */ + __IO uint32_t M0ADDR; /*!< DMA stream x memory 0 address register */ + __IO uint32_t M1ADDR; /*!< DMA stream x memory 1 address register */ + __IO uint32_t FCTRL; /*!< DMA stream x FIFO control register */ +} DMA_Stream_TypeDef; + +typedef struct +{ + __IO uint32_t LINTSTS; /*!< DMA low interrupt status register, Address offset: 0x00 */ + __IO uint32_t HINTSTS; /*!< DMA high interrupt status register, Address offset: 0x04 */ + __IO uint32_t LIFCLR; /*!< DMA low interrupt flag clear register, Address offset: 0x08 */ + __IO uint32_t HIFCLR; /*!< DMA high interrupt flag clear register, Address offset: 0x0C */ +} DMA_TypeDef; + +/** + * @brief External Interrupt/Event Controller + */ + +typedef struct +{ + __IO uint32_t IMASK; /*!< EINT Interrupt mask register, Address offset: 0x00 */ + __IO uint32_t EMASK; /*!< EINT Event mask register, Address offset: 0x04 */ + __IO uint32_t RTEN; /*!< EINT Rising trigger selection register, Address offset: 0x08 */ + __IO uint32_t FTEN; /*!< EINT Falling trigger selection register, Address offset: 0x0C */ + __IO uint32_t SWINTE; /*!< EINT Software interrupt event register, Address offset: 0x10 */ + __IO uint32_t IPEND; /*!< EINT Pending register, Address offset: 0x14 */ +} EINT_TypeDef; + +/** + * @brief FLASH Registers + */ + +typedef struct +{ + __IO uint32_t ACCTRL; /*!< FLASH access control register, Address offset: 0x00 */ + __IO uint32_t KEY; /*!< FLASH key register, Address offset: 0x04 */ + __IO uint32_t OPTKEY; /*!< FLASH option key register, Address offset: 0x08 */ + __IO uint32_t STS; /*!< FLASH status register, Address offset: 0x0C */ + __IO uint32_t CTRL; /*!< FLASH control register, Address offset: 0x10 */ + __IO uint32_t OPTCTRL; /*!< FLASH option control register , Address offset: 0x14 */ + __IO uint32_t OPTCTRL1; /*!< FLASH option control register 1, Address offset: 0x18 */ +} FLASH_TypeDef; + +/** + * @brief Flexible Static Memory Controller + */ + +typedef struct +{ + __IO uint32_t CSTR[8]; /*!< NOR/PSRAM chip-select control register(CSCTRL) and chip-select timing register(CSTIM), Address offset: 0x00-1C */ +} SMC_Bank1_TypeDef; + +/** + * @brief Flexible Static Memory Controller Bank1E + */ + +typedef struct +{ + __IO uint32_t WRTTIM[7]; /*!< NOR/PSRAM write timing registers, Address offset: 0x104-0x11C */ +} SMC_Bank1E_TypeDef; + +/** + * @brief Flexible Static Memory Controller Bank2 + */ + +typedef struct +{ + __IO uint32_t CTRL2; /*!< NAND Flash control register 2, Address offset: 0x60 */ + __IO uint32_t STSINT2; /*!< NAND Flash FIFO status and interrupt register 2, Address offset: 0x64 */ + __IO uint32_t CMSTIM2; /*!< NAND Flash Common memory space timing register 2, Address offset: 0x68 */ + __IO uint32_t AMSTIM2; /*!< NAND Flash Attribute memory space timing register 2, Address offset: 0x6C */ + uint32_t RESERVED0; /*!< Reserved, 0x70 */ + __IO uint32_t ECCRS2; /*!< NAND Flash ECC result registers 2, Address offset: 0x74 */ + uint32_t RESERVED1; /*!< Reserved, 0x78 */ + uint32_t RESERVED2; /*!< Reserved, 0x7C */ + __IO uint32_t CTRL3; /*!< NAND Flash control register 3, Address offset: 0x80 */ + __IO uint32_t STSINT3; /*!< NAND Flash FIFO status and interrupt register 3, Address offset: 0x84 */ + __IO uint32_t CMSTIM3; /*!< NAND Flash Common memory space timing register 3, Address offset: 0x88 */ + __IO uint32_t AMSTIM3; /*!< NAND Flash Attribute memory space timing register 3, Address offset: 0x8C */ + uint32_t RESERVED3; /*!< Reserved, 0x90 */ + __IO uint32_t ECCRS3; /*!< NAND Flash ECC result registers 3, Address offset: 0x94 */ +} SMC_Bank2_3_TypeDef; + +/** + * @brief Flexible Static Memory Controller Bank4 + */ + +typedef struct +{ + __IO uint32_t CTRL4; /*!< PC Card control register 4, Address offset: 0xA0 */ + __IO uint32_t STSINT4; /*!< PC Card FIFO status and interrupt register 4, Address offset: 0xA4 */ + __IO uint32_t CMSTIM4; /*!< PC Card Common memory space timing register 4, Address offset: 0xA8 */ + __IO uint32_t AMSTIM4; /*!< PC Card Attribute memory space timing register 4, Address offset: 0xAC */ + __IO uint32_t IOSTIM4; /*!< PC Card I/O space timing register 4, Address offset: 0xB0 */ +} SMC_Bank4_TypeDef; + +/** + * @brief General Purpose I/O + */ + +typedef struct +{ + __IO uint32_t MODE; /*!< GPIO port mode register, Address offset: 0x00 */ + __IO uint32_t OMODE; /*!< GPIO port output type register, Address offset: 0x04 */ + __IO uint32_t OSSEL; /*!< GPIO port output speed register, Address offset: 0x08 */ + __IO uint32_t PUPD; /*!< GPIO port pull-up/pull-down register, Address offset: 0x0C */ + __IO uint32_t IDATA; /*!< GPIO port input data register, Address offset: 0x10 */ + __IO uint32_t ODATA; /*!< GPIO port output data register, Address offset: 0x14 */ + __IO uint32_t BSC; /*!< GPIO port bit set/reset register, Address offset: 0x18 */ + __IO uint32_t LOCK; /*!< GPIO port configuration lock register, Address offset: 0x1C */ + __IO uint32_t ALF[2]; /*!< GPIO alternate function registers, Address offset: 0x20-0x24 */ +} GPIO_TypeDef; + +/** + * @brief System configuration controller + */ + +typedef struct +{ + __IO uint32_t MMSEL; /*!< SYSCFG memory remap register, Address offset: 0x00 */ + __IO uint32_t PMCFG; /*!< SYSCFG peripheral mode configuration register, Address offset: 0x04 */ + __IO uint32_t EINTCFG[4]; /*!< SYSCFG external interrupt configuration registers, Address offset: 0x08-0x14 */ + uint32_t RESERVED[2]; /*!< Reserved, 0x18-0x1C */ + __IO uint32_t CCCTRL; /*!< SYSCFG Compensation cell control register, Address offset: 0x20 */ +} SYSCFG_TypeDef; + +/** + * @brief Inter-integrated Circuit Interface + */ + +typedef struct +{ + __IO uint32_t CTRL1; /*!< I2C Control register 1, Address offset: 0x00 */ + __IO uint32_t CTRL2; /*!< I2C Control register 2, Address offset: 0x04 */ + __IO uint32_t SADDR1; /*!< I2C Own address register 1, Address offset: 0x08 */ + __IO uint32_t SADDR2; /*!< I2C Own address register 2, Address offset: 0x0C */ + __IO uint32_t DATA; /*!< I2C Data register, Address offset: 0x10 */ + __IO uint32_t STS1; /*!< I2C Status register 1, Address offset: 0x14 */ + __IO uint32_t STS2; /*!< I2C Status register 2, Address offset: 0x18 */ + __IO uint32_t CLKCTRL; /*!< I2C Clock control register, Address offset: 0x1C */ + __IO uint32_t RISETMAX; /*!< I2C RISETMAX register, Address offset: 0x20 */ +} I2C_TypeDef; + +/** + * @brief Independent WATCHDOG + */ + +typedef struct +{ + __IO uint32_t KEY; /*!< IWDT Key register, Address offset: 0x00 */ + __IO uint32_t PSC; /*!< IWDT Prescaler register, Address offset: 0x04 */ + __IO uint32_t CNTRLD; /*!< IWDT Reload register, Address offset: 0x08 */ + __IO uint32_t STS; /*!< IWDT Status register, Address offset: 0x0C */ +} IWDT_TypeDef; + + +/** + * @brief Power Control + */ + +typedef struct +{ + __IO uint32_t CTRL; /*!< PMU power control register, Address offset: 0x00 */ + __IO uint32_t CSTS; /*!< PMU power control/status register, Address offset: 0x04 */ +} PMU_TypeDef; + +/** + * @brief Reset and Clock Control + */ + +typedef struct +{ + __IO uint32_t CTRL; /*!< RCM clock control register, Address offset: 0x00 */ + __IO uint32_t PLL1CFG; /*!< RCM PLL configuration register, Address offset: 0x04 */ + __IO uint32_t CFG; /*!< RCM clock configuration register, Address offset: 0x08 */ + __IO uint32_t INT; /*!< RCM clock interrupt register, Address offset: 0x0C */ + __IO uint32_t AHB1RST; /*!< RCM AHB1 peripheral reset register, Address offset: 0x10 */ + __IO uint32_t AHB2RST; /*!< RCM AHB2 peripheral reset register, Address offset: 0x14 */ + __IO uint32_t AHB3RST; /*!< RCM AHB3 peripheral reset register, Address offset: 0x18 */ + uint32_t RESERVED0; /*!< Reserved, 0x1C */ + __IO uint32_t APB1RST; /*!< RCM APB1 peripheral reset register, Address offset: 0x20 */ + __IO uint32_t APB2RST; /*!< RCM APB2 peripheral reset register, Address offset: 0x24 */ + uint32_t RESERVED1[2]; /*!< Reserved, 0x28-0x2C */ + __IO uint32_t AHB1CLKEN; /*!< RCM AHB1 peripheral clock register, Address offset: 0x30 */ + __IO uint32_t AHB2CLKEN; /*!< RCM AHB2 peripheral clock register, Address offset: 0x34 */ + __IO uint32_t AHB3CLKEN; /*!< RCM AHB3 peripheral clock register, Address offset: 0x38 */ + uint32_t RESERVED2; /*!< Reserved, 0x3C */ + __IO uint32_t APB1CLKEN; /*!< RCM APB1 peripheral clock enable register, Address offset: 0x40 */ + __IO uint32_t APB2CLKEN; /*!< RCM APB2 peripheral clock enable register, Address offset: 0x44 */ + uint32_t RESERVED3[2]; /*!< Reserved, 0x48-0x4C */ + __IO uint32_t LPAHB1CLKEN; /*!< RCM AHB1 peripheral clock enable in low power mode register, Address offset: 0x50 */ + __IO uint32_t LPAHB2CLKEN; /*!< RCM AHB2 peripheral clock enable in low power mode register, Address offset: 0x54 */ + __IO uint32_t LPAHB3CLKEN; /*!< RCM AHB3 peripheral clock enable in low power mode register, Address offset: 0x58 */ + uint32_t RESERVED4; /*!< Reserved, 0x5C */ + __IO uint32_t LPAPB1CLKEN; /*!< RCM APB1 peripheral clock enable in low power mode register, Address offset: 0x60 */ + __IO uint32_t LPAPB2CLKEN; /*!< RCM APB2 peripheral clock enable in low power mode register, Address offset: 0x64 */ + uint32_t RESERVED5[2]; /*!< Reserved, 0x68-0x6C */ + __IO uint32_t BDCTRL; /*!< RCM Backup domain control register, Address offset: 0x70 */ + __IO uint32_t CSTS; /*!< RCM clock control & status register, Address offset: 0x74 */ + uint32_t RESERVED6[2]; /*!< Reserved, 0x78-0x7C */ + __IO uint32_t SSCCFG; /*!< RCM spread spectrum clock generation register, Address offset: 0x80 */ + __IO uint32_t PLL2CFG; /*!< RCM PLLI2S configuration register, Address offset: 0x84 */ +} RCM_TypeDef; + +/** + * @brief Real-Time Clock + */ + +typedef struct +{ + __IO uint32_t TIME; /*!< RTC time register, Address offset: 0x00 */ + __IO uint32_t DATE; /*!< RTC date register, Address offset: 0x04 */ + __IO uint32_t CTRL; /*!< RTC control register, Address offset: 0x08 */ + __IO uint32_t STS; /*!< RTC initialization and status register, Address offset: 0x0C */ + __IO uint32_t PSC; /*!< RTC prescaler register, Address offset: 0x10 */ + __IO uint32_t AUTORLD; /*!< RTC wakeup timer register, Address offset: 0x14 */ + __IO uint32_t DCAL; /*!< RTC calibration register, Address offset: 0x18 */ + __IO uint32_t ALRMA; /*!< RTC alarm A register, Address offset: 0x1C */ + __IO uint32_t ALRMB; /*!< RTC alarm B register, Address offset: 0x20 */ + __IO uint32_t WRPROT; /*!< RTC write protection register, Address offset: 0x24 */ + __IO uint32_t SUBSEC; /*!< RTC sub second register, Address offset: 0x28 */ + __IO uint32_t SHIFT; /*!< RTC shift control register, Address offset: 0x2C */ + __IO uint32_t TSTIME; /*!< RTC time stamp time register, Address offset: 0x30 */ + __IO uint32_t TSDATE; /*!< RTC time stamp date register, Address offset: 0x34 */ + __IO uint32_t TSSUBSEC; /*!< RTC time-stamp sub second register, Address offset: 0x38 */ + __IO uint32_t CAL; /*!< RTC calibration register, Address offset: 0x3C */ + __IO uint32_t TACFG; /*!< RTC tamper and alternate function configuration register, Address offset: 0x40 */ + __IO uint32_t ALRMASS; /*!< RTC alarm A sub second register, Address offset: 0x44 */ + __IO uint32_t ALRMBSS; /*!< RTC alarm B sub second register, Address offset: 0x48 */ + uint32_t RESERVED7; /*!< Reserved, 0x4C */ + __IO uint32_t BAKP0; /*!< RTC backup register 1, Address offset: 0x50 */ + __IO uint32_t BAKP1; /*!< RTC backup register 1, Address offset: 0x54 */ + __IO uint32_t BAKP2; /*!< RTC backup register 2, Address offset: 0x58 */ + __IO uint32_t BAKP3; /*!< RTC backup register 3, Address offset: 0x5C */ + __IO uint32_t BAKP4; /*!< RTC backup register 4, Address offset: 0x60 */ + __IO uint32_t BAKP5; /*!< RTC backup register 5, Address offset: 0x64 */ + __IO uint32_t BAKP6; /*!< RTC backup register 6, Address offset: 0x68 */ + __IO uint32_t BAKP7; /*!< RTC backup register 7, Address offset: 0x6C */ + __IO uint32_t BAKP8; /*!< RTC backup register 8, Address offset: 0x70 */ + __IO uint32_t BAKP9; /*!< RTC backup register 9, Address offset: 0x74 */ + __IO uint32_t BAKP10; /*!< RTC backup register 10, Address offset: 0x78 */ + __IO uint32_t BAKP11; /*!< RTC backup register 11, Address offset: 0x7C */ + __IO uint32_t BAKP12; /*!< RTC backup register 12, Address offset: 0x80 */ + __IO uint32_t BAKP13; /*!< RTC backup register 13, Address offset: 0x84 */ + __IO uint32_t BAKP14; /*!< RTC backup register 14, Address offset: 0x88 */ + __IO uint32_t BAKP15; /*!< RTC backup register 15, Address offset: 0x8C */ + __IO uint32_t BAKP16; /*!< RTC backup register 16, Address offset: 0x90 */ + __IO uint32_t BAKP17; /*!< RTC backup register 17, Address offset: 0x94 */ + __IO uint32_t BAKP18; /*!< RTC backup register 18, Address offset: 0x98 */ + __IO uint32_t BAKP19; /*!< RTC backup register 19, Address offset: 0x9C */ +} RTC_TypeDef; + +/** + * @brief SD host Interface + */ + +typedef struct +{ + __IO uint32_t PWRCTRL; /*!< SDIO power control register, Address offset: 0x00 */ + __IO uint32_t CLKCTRL; /*!< SDI clock control register, Address offset: 0x04 */ + __IO uint32_t ARG; /*!< SDIO argument register, Address offset: 0x08 */ + __IO uint32_t CMD; /*!< SDIO command register, Address offset: 0x0C */ + __IO const uint32_t CMDRES; /*!< SDIO command response register, Address offset: 0x10 */ + __IO const uint32_t RES1; /*!< SDIO response 1 register, Address offset: 0x14 */ + __IO const uint32_t RES2; /*!< SDIO response 2 register, Address offset: 0x18 */ + __IO const uint32_t RES3; /*!< SDIO response 3 register, Address offset: 0x1C */ + __IO const uint32_t RES4; /*!< SDIO response 4 register, Address offset: 0x20 */ + __IO uint32_t DATATIME; /*!< SDIO data timer register, Address offset: 0x24 */ + __IO uint32_t DATALEN; /*!< SDIO data length register, Address offset: 0x28 */ + __IO uint32_t DCTRL; /*!< SDIO data control register, Address offset: 0x2C */ + __IO const uint32_t DCNT; /*!< SDIO data counter register, Address offset: 0x30 */ + __IO const uint32_t STS; /*!< SDIO status register, Address offset: 0x34 */ + __IO uint32_t ICF; /*!< SDIO interrupt clear register, Address offset: 0x38 */ + __IO uint32_t MASK; /*!< SDIO mask register, Address offset: 0x3C */ + uint32_t RESERVED0[2]; /*!< Reserved, 0x40-0x44 */ + __IO const uint32_t FIFOCNT; /*!< SDIO FIFO counter register, Address offset: 0x48 */ + uint32_t RESERVED1[13]; /*!< Reserved, 0x4C-0x7C */ + __IO uint32_t FIFODATA; /*!< SDIO data FIFO register, Address offset: 0x80 */ +} SDIO_TypeDef; + +/** + * @brief Serial Peripheral Interface + */ + +typedef struct +{ + __IO uint32_t CTRL1; /*!< SPI control register 1 (not used in I2S mode), Address offset: 0x00 */ + __IO uint32_t CTRL2; /*!< SPI control register 2, Address offset: 0x04 */ + __IO uint32_t STS; /*!< SPI status register, Address offset: 0x08 */ + __IO uint32_t DATA; /*!< SPI data register, Address offset: 0x0C */ + __IO uint32_t CRCPOLY; /*!< SPI CRC polynomial register (not used in I2S mode), Address offset: 0x10 */ + __IO uint32_t RXCRC; /*!< SPI RX CRC register (not used in I2S mode), Address offset: 0x14 */ + __IO uint32_t TXCRC; /*!< SPI TX CRC register (not used in I2S mode), Address offset: 0x18 */ + __IO uint32_t I2SCFG; /*!< SPI_I2S configuration register, Address offset: 0x1C */ + __IO uint32_t I2SPSC; /*!< SPI_I2S prescaler register, Address offset: 0x20 */ +} SPI_TypeDef; + + +/** + * @brief TMR + */ + +typedef struct +{ + __IO uint32_t CTRL1; /*!< TMR control register 1, Address offset: 0x00 */ + __IO uint32_t CTRL2; /*!< TMR control register 2, Address offset: 0x04 */ + __IO uint32_t SMCTRL; /*!< TMR slave mode control register, Address offset: 0x08 */ + __IO uint32_t DIEN; /*!< TMR DMA/interrupt enable register, Address offset: 0x0C */ + __IO uint32_t STS; /*!< TMR status register, Address offset: 0x10 */ + __IO uint32_t CEG; /*!< TMR event generation register, Address offset: 0x14 */ + __IO uint32_t CCM1; /*!< TMR capture/compare mode register 1, Address offset: 0x18 */ + __IO uint32_t CCM2; /*!< TMR capture/compare mode register 2, Address offset: 0x1C */ + __IO uint32_t CCEN; /*!< TMR capture/compare enable register, Address offset: 0x20 */ + __IO uint32_t CNT; /*!< TMR counter register, Address offset: 0x24 */ + __IO uint32_t PSC; /*!< TMR prescaler, Address offset: 0x28 */ + __IO uint32_t AUTORLD; /*!< TMR auto-reload register, Address offset: 0x2C */ + __IO uint32_t REPCNT; /*!< TMR repetition counter register, Address offset: 0x30 */ + __IO uint32_t CC1; /*!< TMR capture/compare register 1, Address offset: 0x34 */ + __IO uint32_t CC2; /*!< TMR capture/compare register 2, Address offset: 0x38 */ + __IO uint32_t CC3; /*!< TMR capture/compare register 3, Address offset: 0x3C */ + __IO uint32_t CC4; /*!< TMR capture/compare register 4, Address offset: 0x40 */ + __IO uint32_t BDT; /*!< TMR break and dead-time register, Address offset: 0x44 */ + __IO uint32_t DCTRL; /*!< TMR DMA control register, Address offset: 0x48 */ + __IO uint32_t DMAR; /*!< TMR DMA address for full transfer, Address offset: 0x4C */ + __IO uint32_t OR; /*!< TMR option register, Address offset: 0x50 */ +} TMR_TypeDef; + +/** + * @brief Universal Synchronous Asynchronous Receiver Transmitter + */ + +typedef struct +{ + __IO uint32_t STS; /*!< USART Status register, Address offset: 0x00 */ + __IO uint32_t DATA; /*!< USART Data register, Address offset: 0x04 */ + __IO uint32_t BR; /*!< USART Baud rate register, Address offset: 0x08 */ + __IO uint32_t CTRL1; /*!< USART Control register 1, Address offset: 0x0C */ + __IO uint32_t CTRL2; /*!< USART Control register 2, Address offset: 0x10 */ + __IO uint32_t CTRL3; /*!< USART Control register 3, Address offset: 0x14 */ + __IO uint32_t GTPSC; /*!< USART Guard time and prescaler register, Address offset: 0x18 */ +} USART_TypeDef; + +/** + * @brief Window WATCHDOG + */ + +typedef struct +{ + __IO uint32_t CTRL; /*!< WWDT Control register, Address offset: 0x00 */ + __IO uint32_t CFR; /*!< WWDT Configuration register, Address offset: 0x04 */ + __IO uint32_t STS; /*!< WWDT Status register, Address offset: 0x08 */ +} WWDT_TypeDef; + +/** + * @brief RNG + */ + +typedef struct +{ + __IO uint32_t CTRL; /*!< RNG control register, Address offset: 0x00 */ + __IO uint32_t STS; /*!< RNG status register, Address offset: 0x04 */ + __IO uint32_t DATA; /*!< RNG data register, Address offset: 0x08 */ +} RNG_TypeDef; + +/** + * @brief USB_OTG_Core_Registers + */ +typedef struct +{ + __IO uint32_t GCTRLSTS; /*!< USB_OTG Control and Status Register 000h */ + __IO uint32_t GINT; /*!< USB_OTG Interrupt Register 004h */ + __IO uint32_t GAHBCFG; /*!< Core AHB Configuration Register 008h */ + __IO uint32_t GUSBCFG; /*!< Core USB Configuration Register 00Ch */ + __IO uint32_t GRSTCTRL; /*!< Core Reset Register 010h */ + __IO uint32_t GCINT; /*!< Core Interrupt Register 014h */ + __IO uint32_t GINTMASK; /*!< Core Interrupt Mask Register 018h */ + __IO uint32_t GRXSTS; /*!< Receive Sts Q Read Register 01Ch */ + __IO uint32_t GRXSTSP; /*!< Receive Sts Q Read & POP Register 020h */ + __IO uint32_t GRXFIFO; /*!< Receive FIFO Size Register 024h */ + __IO uint32_t GTXFCFG; /*!< EP0 / Non Periodic Tx FIFO Size Register 028h */ + __IO uint32_t GNPTXFQSTS; /*!< Non Periodic Tx FIFO/Queue Sts reg 02Ch */ + uint32_t Reserved30[2]; /*!< Reserved 030h */ + __IO uint32_t GGCCFG; /*!< General Purpose IO Register 038h */ + __IO uint32_t GCID; /*!< User ID Register 03Ch */ + uint32_t Reserved40[48]; /*!< Reserved 0x40-0xFF */ + __IO uint32_t GHPTXFSIZE; /*!< Host Periodic Tx FIFO Size Reg 100h */ + __IO uint32_t DTXFIFO[0x0F]; /*!< dev Periodic Transmit FIFO */ +} USB_OTG_GlobalTypeDef; + +/** + * @brief USB_OTG_device_Registers + */ +typedef struct +{ + __IO uint32_t DCFG; /*!< dev Configuration Register 800h */ + __IO uint32_t DCTRL; /*!< dev Control Register 804h */ + __IO uint32_t DSTS; /*!< dev Status Register (RO) 808h */ + uint32_t Reserved0C; /*!< Reserved 80Ch */ + __IO uint32_t DINIMASK; /*!< dev IN Endpoint Mask 810h */ + __IO uint32_t DOUTIMASK; /*!< dev OUT Endpoint Mask 814h */ + __IO uint32_t DAEPINT; /*!< dev All Endpoints Itr Reg 818h */ + __IO uint32_t DAEPIMASK; /*!< dev All Endpoints Itr Mask 81Ch */ + uint32_t Reserved20; /*!< Reserved 820h */ + uint32_t Reserved9; /*!< Reserved 824h */ + __IO uint32_t DVBUSDTIM; /*!< dev VBUS discharge Register 828h */ + __IO uint32_t DVBUSPTIM; /*!< dev VBUS Pulse Register 82Ch */ + __IO uint32_t DTHCTRL; /*!< dev threshold 830h */ + __IO uint32_t DIEIMASK; /*!< dev empty msk 834h */ + __IO uint32_t DEPINT; /*!< dedicated EP interrupt 838h */ + __IO uint32_t DEPIMASK; /*!< dedicated EP msk 83Ch */ + uint32_t Reserved40; /*!< dedicated EP mask 840h */ + __IO uint32_t DIN1IMASK; /*!< dedicated EP mask 844h */ + uint32_t Reserved44[15]; /*!< Reserved 844-87Ch */ + __IO uint32_t DOUT1MASK; /*!< dedicated EP msk 884h */ +} USB_OTG_DeviceTypeDef; + +/** + * @brief USB_OTG_IN_Endpoint-Specific_Register + */ +typedef struct +{ + __IO uint32_t DIEPCTRL; /*!< dev IN Endpoint Control Reg 900h + (ep_num * 20h) + 00h */ + uint32_t Reserved04; /*!< Reserved 900h + (ep_num * 20h) + 04h */ + __IO uint32_t DIEPINT; /*!< dev IN Endpoint Itr Reg 900h + (ep_num * 20h) + 08h */ + uint32_t Reserved0C; /*!< Reserved 900h + (ep_num * 20h) + 0Ch */ + __IO uint32_t DIEPTRS; /*!< IN Endpoint Txfer Size 900h + (ep_num * 20h) + 10h */ + __IO uint32_t DIEPDMA; /*!< IN Endpoint DMA Address Reg 900h + (ep_num * 20h) + 14h */ + __IO uint32_t DITXFSTS; /*!< IN Endpoint Tx FIFO Status Reg 900h + (ep_num * 20h) + 18h */ + uint32_t Reserved18; /*!< Reserved 900h+(ep_num*20h)+1Ch-900h+ (ep_num * 20h) + 1Ch */ +} USB_OTG_INEndpointTypeDef; + +/** + * @brief USB_OTG_OUT_Endpoint-Specific_Registers + */ +typedef struct +{ + __IO uint32_t DOEPCTRL; /*!< dev OUT Endpoint Control Reg B00h + (ep_num * 20h) + 00h */ + uint32_t Reserved04; /*!< Reserved B00h + (ep_num * 20h) + 04h */ + __IO uint32_t DOEPINT; /*!< dev OUT Endpoint Itr Reg B00h + (ep_num * 20h) + 08h */ + uint32_t Reserved0C; /*!< Reserved B00h + (ep_num * 20h) + 0Ch */ + __IO uint32_t DOEPTRS; /*!< dev OUT Endpoint Txfer Size B00h + (ep_num * 20h) + 10h */ + __IO uint32_t DOEPDMA; /*!< dev OUT Endpoint DMA Address B00h + (ep_num * 20h) + 14h */ + uint32_t Reserved18[2]; /*!< Reserved B00h + (ep_num * 20h) + 18h - B00h + (ep_num * 20h) + 1Ch */ +} USB_OTG_OUTEndpointTypeDef; + +/** + * @brief USB_OTG_Host_Mode_Register_Structures + */ +typedef struct +{ + __IO uint32_t HCFG; /*!< Host Configuration Register 400h */ + __IO uint32_t HFIVL; /*!< Host Frame Interval Register 404h */ + __IO uint32_t HFIFM; /*!< Host Frame Nbr/Frame Remaining 408h */ + uint32_t Reserved40C; /*!< Reserved 40Ch */ + __IO uint32_t HPTXSTS; /*!< Host Periodic Tx FIFO/ Queue Status 410h */ + __IO uint32_t HACHINT; /*!< Host All Channels Interrupt Register 414h */ + __IO uint32_t HACHIMASK; /*!< Host All Channels Interrupt Mask 418h */ +} USB_OTG_HostTypeDef; + +/** + * @brief USB_OTG_Host_Channel_Specific_Registers + */ +typedef struct +{ + __IO uint32_t HCH; /*!< Host Channel Characteristics Register 500h */ + __IO uint32_t HCHSCTRL; /*!< Host Channel Split Control Register 504h */ + __IO uint32_t HCHINT; /*!< Host Channel Interrupt Register 508h */ + __IO uint32_t HCHIMASK; /*!< Host Channel Interrupt Mask Register 50Ch */ + __IO uint32_t HCHTSIZE; /*!< Host Channel Transfer Size Register 510h */ + __IO uint32_t HCHDMA; /*!< Host Channel DMA Address Register 514h */ + uint32_t Reserved[2]; /*!< Reserved */ +} USB_OTG_HostChannelTypeDef; + +/** + * @} + */ + +/** @addtogroup Peripheral_memory_map + * @{ + */ +#define FLASH_BASE 0x08000000UL /*!< FLASH(up to 1 MB) base address in the alias region */ +#define CCMDATARAM_BASE 0x10000000UL /*!< CCM(core coupled memory) data RAM(64 KB) base address in the alias region */ +#define SRAM1_BASE 0x20000000UL /*!< SRAM1(112 KB) base address in the alias region */ +#define SRAM2_BASE 0x2001C000UL /*!< SRAM2(16 KB) base address in the alias region */ +#define PERIPH_BASE 0x40000000UL /*!< Peripheral base address in the alias region */ +#define BKPSRAM_BASE 0x40024000UL /*!< Backup SRAM(4 KB) base address in the alias region */ +#define SMC_R_BASE 0xA0000000UL /*!< SMC registers base address */ +#define SRAM1_BB_BASE 0x22000000UL /*!< SRAM1(112 KB) base address in the bit-band region */ +#define SRAM2_BB_BASE 0x22380000UL /*!< SRAM2(16 KB) base address in the bit-band region */ +#define PERIPH_BB_BASE 0x42000000UL /*!< Peripheral base address in the bit-band region */ +#define BKPSRAM_BB_BASE 0x42480000UL /*!< Backup SRAM(4 KB) base address in the bit-band region */ +#define FLASH_END 0x080FFFFFUL /*!< FLASH end address */ +#define FLASH_OTP_BASE 0x1FFF7800UL /*!< Base address of : (up to 528 Bytes) embedded FLASH OTP Area */ +#define FLASH_OTP_END 0x1FFF7A0FUL /*!< End address of : (up to 528 Bytes) embedded FLASH OTP Area */ +#define CCMDATARAM_END 0x1000FFFFUL /*!< CCM data RAM end address */ + +/* Legacy defines */ +#define SRAM_BASE SRAM1_BASE +#define SRAM_BB_BASE SRAM1_BB_BASE + +/*!< Peripheral memory map */ +#define APB1PERIPH_BASE PERIPH_BASE +#define APB2PERIPH_BASE (PERIPH_BASE + 0x00010000UL) +#define AHB1PERIPH_BASE (PERIPH_BASE + 0x00020000UL) +#define AHB2PERIPH_BASE (PERIPH_BASE + 0x10000000UL) + +/*!< APB1 peripherals */ +#define TMR2_BASE (APB1PERIPH_BASE + 0x0000UL) +#define TMR3_BASE (APB1PERIPH_BASE + 0x0400UL) +#define TMR4_BASE (APB1PERIPH_BASE + 0x0800UL) +#define TMR5_BASE (APB1PERIPH_BASE + 0x0C00UL) +#define TMR6_BASE (APB1PERIPH_BASE + 0x1000UL) +#define TMR7_BASE (APB1PERIPH_BASE + 0x1400UL) +#define TMR12_BASE (APB1PERIPH_BASE + 0x1800UL) +#define TMR13_BASE (APB1PERIPH_BASE + 0x1C00UL) +#define TMR14_BASE (APB1PERIPH_BASE + 0x2000UL) +#define RTC_BASE (APB1PERIPH_BASE + 0x2800UL) +#define WWDT_BASE (APB1PERIPH_BASE + 0x2C00UL) +#define IWDT_BASE (APB1PERIPH_BASE + 0x3000UL) +#define I2S2ext_BASE (APB1PERIPH_BASE + 0x3400UL) +#define SPI2_BASE (APB1PERIPH_BASE + 0x3800UL) +#define SPI3_BASE (APB1PERIPH_BASE + 0x3C00UL) +#define I2S3ext_BASE (APB1PERIPH_BASE + 0x4000UL) +#define USART2_BASE (APB1PERIPH_BASE + 0x4400UL) +#define USART3_BASE (APB1PERIPH_BASE + 0x4800UL) +#define UART4_BASE (APB1PERIPH_BASE + 0x4C00UL) +#define UART5_BASE (APB1PERIPH_BASE + 0x5000UL) +#define I2C1_BASE (APB1PERIPH_BASE + 0x5400UL) +#define I2C2_BASE (APB1PERIPH_BASE + 0x5800UL) +#define I2C3_BASE (APB1PERIPH_BASE + 0x5C00UL) +#define CAN1_BASE (APB1PERIPH_BASE + 0x6400UL) +#define CAN2_BASE (APB1PERIPH_BASE + 0x6800UL) +#define PMU_BASE (APB1PERIPH_BASE + 0x7000UL) +#define DAC_BASE (APB1PERIPH_BASE + 0x7400UL) + +/*!< APB2 peripherals */ +#define TMR1_BASE (APB2PERIPH_BASE + 0x0000UL) +#define TMR8_BASE (APB2PERIPH_BASE + 0x0400UL) +#define USART1_BASE (APB2PERIPH_BASE + 0x1000UL) +#define USART6_BASE (APB2PERIPH_BASE + 0x1400UL) +#define ADC1_BASE (APB2PERIPH_BASE + 0x2000UL) +#define ADC2_BASE (APB2PERIPH_BASE + 0x2100UL) +#define ADC3_BASE (APB2PERIPH_BASE + 0x2200UL) +#define ADC123_COMMON_BASE (APB2PERIPH_BASE + 0x2300UL) +/* Legacy define */ +#define ADC_BASE ADC123_COMMON_BASE +#define SDIO_BASE (APB2PERIPH_BASE + 0x2C00UL) +#define SPI1_BASE (APB2PERIPH_BASE + 0x3000UL) +#define SYSCFG_BASE (APB2PERIPH_BASE + 0x3800UL) +#define EINT_BASE (APB2PERIPH_BASE + 0x3C00UL) +#define TMR9_BASE (APB2PERIPH_BASE + 0x4000UL) +#define TMR10_BASE (APB2PERIPH_BASE + 0x4400UL) +#define TMR11_BASE (APB2PERIPH_BASE + 0x4800UL) + +/*!< AHB1 peripherals */ +#define GPIOA_BASE (AHB1PERIPH_BASE + 0x0000UL) +#define GPIOB_BASE (AHB1PERIPH_BASE + 0x0400UL) +#define GPIOC_BASE (AHB1PERIPH_BASE + 0x0800UL) +#define GPIOD_BASE (AHB1PERIPH_BASE + 0x0C00UL) +#define GPIOE_BASE (AHB1PERIPH_BASE + 0x1000UL) +#define GPIOF_BASE (AHB1PERIPH_BASE + 0x1400UL) +#define GPIOG_BASE (AHB1PERIPH_BASE + 0x1800UL) +#define GPIOH_BASE (AHB1PERIPH_BASE + 0x1C00UL) +#define GPIOI_BASE (AHB1PERIPH_BASE + 0x2000UL) +#define CRC_BASE (AHB1PERIPH_BASE + 0x3000UL) +#define RCM_BASE (AHB1PERIPH_BASE + 0x3800UL) +#define FLASH_R_BASE (AHB1PERIPH_BASE + 0x3C00UL) +#define DMA1_BASE (AHB1PERIPH_BASE + 0x6000UL) +#define DMA1_Stream0_BASE (DMA1_BASE + 0x010UL) +#define DMA1_Stream1_BASE (DMA1_BASE + 0x028UL) +#define DMA1_Stream2_BASE (DMA1_BASE + 0x040UL) +#define DMA1_Stream3_BASE (DMA1_BASE + 0x058UL) +#define DMA1_Stream4_BASE (DMA1_BASE + 0x070UL) +#define DMA1_Stream5_BASE (DMA1_BASE + 0x088UL) +#define DMA1_Stream6_BASE (DMA1_BASE + 0x0A0UL) +#define DMA1_Stream7_BASE (DMA1_BASE + 0x0B8UL) +#define DMA2_BASE (AHB1PERIPH_BASE + 0x6400UL) +#define DMA2_Stream0_BASE (DMA2_BASE + 0x010UL) +#define DMA2_Stream1_BASE (DMA2_BASE + 0x028UL) +#define DMA2_Stream2_BASE (DMA2_BASE + 0x040UL) +#define DMA2_Stream3_BASE (DMA2_BASE + 0x058UL) +#define DMA2_Stream4_BASE (DMA2_BASE + 0x070UL) +#define DMA2_Stream5_BASE (DMA2_BASE + 0x088UL) +#define DMA2_Stream6_BASE (DMA2_BASE + 0x0A0UL) +#define DMA2_Stream7_BASE (DMA2_BASE + 0x0B8UL) + +/*!< AHB2 peripherals */ +#define RNG_BASE (AHB2PERIPH_BASE + 0x60800UL) + +/*!< SMC Bankx registers base address */ +#define SMC_Bank1_R_BASE (SMC_R_BASE + 0x0000UL) +#define SMC_Bank1E_R_BASE (SMC_R_BASE + 0x0104UL) +#define SMC_Bank2_3_R_BASE (SMC_R_BASE + 0x0060UL) +#define SMC_Bank4_R_BASE (SMC_R_BASE + 0x00A0UL) + +/*!< Debug MCU registers base address */ +#define DBGMCU_BASE 0xE0042000UL +/*!< USB registers base address */ +#define USB_OTG_HS_PERIPH_BASE 0x40040000UL +#define USB_OTG_FS_PERIPH_BASE 0x50000000UL + +#define USB_OTG_GLOBAL_BASE 0x000UL +#define USB_OTG_DEVICE_BASE 0x800UL +#define USB_OTG_IN_ENDPOINT_BASE 0x900UL +#define USB_OTG_OUT_ENDPOINT_BASE 0xB00UL +#define USB_OTG_EP_REG_SIZE 0x20UL +#define USB_OTG_HOST_BASE 0x400UL +#define USB_OTG_HOST_PORT_BASE 0x440UL +#define USB_OTG_HOST_CHANNEL_BASE 0x500UL +#define USB_OTG_HOST_CHANNEL_SIZE 0x20UL +#define USB_OTG_PCGCCTL_BASE 0xE00UL +#define USB_OTG_FIFO_BASE 0x1000UL +#define USB_OTG_FIFO_SIZE 0x1000UL + +#define UID_BASE 0x1FFF7A10UL /*!< Unique device ID register base address */ +#define FLASHSIZE_BASE 0x1FFF7A22UL /*!< FLASH Size register base address */ +#define PACKAGE_BASE 0x1FFF7BF0UL /*!< Package size register base address */ +/** + * @} + */ + +/** @addtogroup Peripheral_declaration + * @{ + */ +#define TMR2 ((TMR_TypeDef *) TMR2_BASE) +#define TMR3 ((TMR_TypeDef *) TMR3_BASE) +#define TMR4 ((TMR_TypeDef *) TMR4_BASE) +#define TMR5 ((TMR_TypeDef *) TMR5_BASE) +#define TMR6 ((TMR_TypeDef *) TMR6_BASE) +#define TMR7 ((TMR_TypeDef *) TMR7_BASE) +#define TMR12 ((TMR_TypeDef *) TMR12_BASE) +#define TMR13 ((TMR_TypeDef *) TMR13_BASE) +#define TMR14 ((TMR_TypeDef *) TMR14_BASE) +#define RTC ((RTC_TypeDef *) RTC_BASE) +#define WWDT ((WWDT_TypeDef *) WWDT_BASE) +#define IWDT ((IWDT_TypeDef *) IWDT_BASE) +#define I2S2ext ((SPI_TypeDef *) I2S2ext_BASE) +#define SPI2 ((SPI_TypeDef *) SPI2_BASE) +#define SPI3 ((SPI_TypeDef *) SPI3_BASE) +#define I2S3ext ((SPI_TypeDef *) I2S3ext_BASE) +#define USART2 ((USART_TypeDef *) USART2_BASE) +#define USART3 ((USART_TypeDef *) USART3_BASE) +#define UART4 ((USART_TypeDef *) UART4_BASE) +#define UART5 ((USART_TypeDef *) UART5_BASE) +#define I2C1 ((I2C_TypeDef *) I2C1_BASE) +#define I2C2 ((I2C_TypeDef *) I2C2_BASE) +#define I2C3 ((I2C_TypeDef *) I2C3_BASE) +#define CAN1 ((CAN_TypeDef *) CAN1_BASE) +#define CAN2 ((CAN_TypeDef *) CAN2_BASE) +#define PMU ((PMU_TypeDef *) PMU_BASE) +#define DAC1 ((DAC_TypeDef *) DAC_BASE) +#define DAC ((DAC_TypeDef *) DAC_BASE) /* Kept for legacy purpose */ +#define TMR1 ((TMR_TypeDef *) TMR1_BASE) +#define TMR8 ((TMR_TypeDef *) TMR8_BASE) +#define USART1 ((USART_TypeDef *) USART1_BASE) +#define USART6 ((USART_TypeDef *) USART6_BASE) +#define ADC1 ((ADC_TypeDef *) ADC1_BASE) +#define ADC2 ((ADC_TypeDef *) ADC2_BASE) +#define ADC3 ((ADC_TypeDef *) ADC3_BASE) +#define ADC123_COMMON ((ADC_Common_TypeDef *) ADC123_COMMON_BASE) +/* Legacy define */ +#define ADC ADC123_COMMON +#define SDIO ((SDIO_TypeDef *) SDIO_BASE) +#define SPI1 ((SPI_TypeDef *) SPI1_BASE) +#define SYSCFG ((SYSCFG_TypeDef *) SYSCFG_BASE) +#define EINT ((EINT_TypeDef *) EINT_BASE) +#define TMR9 ((TMR_TypeDef *) TMR9_BASE) +#define TMR10 ((TMR_TypeDef *) TMR10_BASE) +#define TMR11 ((TMR_TypeDef *) TMR11_BASE) +#define GPIOA ((GPIO_TypeDef *) GPIOA_BASE) +#define GPIOB ((GPIO_TypeDef *) GPIOB_BASE) +#define GPIOC ((GPIO_TypeDef *) GPIOC_BASE) +#define GPIOD ((GPIO_TypeDef *) GPIOD_BASE) +#define GPIOE ((GPIO_TypeDef *) GPIOE_BASE) +#define GPIOF ((GPIO_TypeDef *) GPIOF_BASE) +#define GPIOG ((GPIO_TypeDef *) GPIOG_BASE) +#define GPIOH ((GPIO_TypeDef *) GPIOH_BASE) +#define GPIOI ((GPIO_TypeDef *) GPIOI_BASE) +#define CRC ((CRC_TypeDef *) CRC_BASE) +#define RCM ((RCM_TypeDef *) RCM_BASE) +#define FLASH ((FLASH_TypeDef *) FLASH_R_BASE) +#define DMA1 ((DMA_TypeDef *) DMA1_BASE) +#define DMA1_Stream0 ((DMA_Stream_TypeDef *) DMA1_Stream0_BASE) +#define DMA1_Stream1 ((DMA_Stream_TypeDef *) DMA1_Stream1_BASE) +#define DMA1_Stream2 ((DMA_Stream_TypeDef *) DMA1_Stream2_BASE) +#define DMA1_Stream3 ((DMA_Stream_TypeDef *) DMA1_Stream3_BASE) +#define DMA1_Stream4 ((DMA_Stream_TypeDef *) DMA1_Stream4_BASE) +#define DMA1_Stream5 ((DMA_Stream_TypeDef *) DMA1_Stream5_BASE) +#define DMA1_Stream6 ((DMA_Stream_TypeDef *) DMA1_Stream6_BASE) +#define DMA1_Stream7 ((DMA_Stream_TypeDef *) DMA1_Stream7_BASE) +#define DMA2 ((DMA_TypeDef *) DMA2_BASE) +#define DMA2_Stream0 ((DMA_Stream_TypeDef *) DMA2_Stream0_BASE) +#define DMA2_Stream1 ((DMA_Stream_TypeDef *) DMA2_Stream1_BASE) +#define DMA2_Stream2 ((DMA_Stream_TypeDef *) DMA2_Stream2_BASE) +#define DMA2_Stream3 ((DMA_Stream_TypeDef *) DMA2_Stream3_BASE) +#define DMA2_Stream4 ((DMA_Stream_TypeDef *) DMA2_Stream4_BASE) +#define DMA2_Stream5 ((DMA_Stream_TypeDef *) DMA2_Stream5_BASE) +#define DMA2_Stream6 ((DMA_Stream_TypeDef *) DMA2_Stream6_BASE) +#define DMA2_Stream7 ((DMA_Stream_TypeDef *) DMA2_Stream7_BASE) +#define RNG ((RNG_TypeDef *) RNG_BASE) +#define SMC_Bank1 ((SMC_Bank1_TypeDef *) SMC_Bank1_R_BASE) +#define SMC_Bank1E ((SMC_Bank1E_TypeDef *) SMC_Bank1E_R_BASE) +#define SMC_Bank2_3 ((SMC_Bank2_3_TypeDef *) SMC_Bank2_3_R_BASE) +#define SMC_Bank4 ((SMC_Bank4_TypeDef *) SMC_Bank4_R_BASE) +#define DBGMCU ((DBGMCU_TypeDef *) DBGMCU_BASE) +#define USB_OTG_FS ((USB_OTG_GlobalTypeDef *) USB_OTG_FS_PERIPH_BASE) +#define USB_OTG_HS ((USB_OTG_GlobalTypeDef *) USB_OTG_HS_PERIPH_BASE) + +/** + * @} + */ + +/** @addtogroup Exported_constants + * @{ + */ + +/** @addtogroup Hardware_Constant_Definition + * @{ + */ +#define LSI_STARTUP_TIME 40U /*!< LSI Maximum startup time in us */ +/** + * @} + */ + + /** @addtogroup Peripheral_Registers_Bits_Definition + * @{ + */ + +/******************************************************************************/ +/* Peripheral Registers_Bits_Definition */ +/******************************************************************************/ + +/******************************************************************************/ +/* */ +/* Analog to Digital Converter */ +/* */ +/******************************************************************************/ +/* + * @brief Specific device feature definitions (not present on all devices in the APM32F4 serie) + */ +#define ADC_MULTIMODE_SUPPORT /*!>> +; Stack Configuration +; Stack Size (in Bytes) <0x0-0xFFFFFFFF:8> +; + +Stack_Size EQU 0x00000400 + + AREA STACK, NOINIT, READWRITE, ALIGN=3 +Stack_Mem SPACE Stack_Size +__initial_sp + +; Heap Configuration +; Heap Size (in Bytes) <0x0-0xFFFFFFFF:8> +; + +Heap_Size EQU 0x00000200 + + AREA HEAP, NOINIT, READWRITE, ALIGN=3 +__heap_base +Heap_Mem SPACE Heap_Size +__heap_limit + + PRESERVE8 + THUMB + +; Vector Table Mapped to Address 0 at Reset + AREA RESET, DATA, READONLY + EXPORT __Vectors + EXPORT __Vectors_End + EXPORT __Vectors_Size + +__Vectors DCD __initial_sp ; Top of Stack + DCD Reset_Handler ; Reset Handler + DCD NMI_Handler ; NMI Handler + DCD HardFault_Handler ; Hard Fault Handler + DCD MemManage_Handler ; MPU Fault Handler + DCD BusFault_Handler ; Bus Fault Handler + DCD UsageFault_Handler ; Usage Fault Handler + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD SVC_Handler ; SVCall Handler + DCD DebugMon_Handler ; Debug Monitor Handler + DCD 0 ; Reserved + DCD PendSV_Handler ; PendSV Handler + DCD SysTick_Handler ; SysTick Handler + + ; External Interrupts + DCD WWDT_IRQHandler ; Window WatchDog + DCD PVD_IRQHandler ; PVD through EINT Line detection + DCD TAMP_STAMP_IRQHandler ; Tamper and TimeStamps through the EINT line + DCD RTC_WKUP_IRQHandler ; RTC Wakeup through the EINT line + DCD FLASH_IRQHandler ; FLASH + DCD RCM_IRQHandler ; RCM + DCD EINT0_IRQHandler ; EINT Line0 + DCD EINT1_IRQHandler ; EINT Line1 + DCD EINT2_IRQHandler ; EINT Line2 + DCD EINT3_IRQHandler ; EINT Line3 + DCD EINT4_IRQHandler ; EINT Line4 + DCD DMA1_STR0_IRQHandler ; DMA1 Stream 0 + DCD DMA1_STR1_IRQHandler ; DMA1 Stream 1 + DCD DMA1_STR2_IRQHandler ; DMA1 Stream 2 + DCD DMA1_STR3_IRQHandler ; DMA1 Stream 3 + DCD DMA1_STR4_IRQHandler ; DMA1 Stream 4 + DCD DMA1_STR5_IRQHandler ; DMA1 Stream 5 + DCD DMA1_STR6_IRQHandler ; DMA1 Stream 6 + DCD ADC_IRQHandler ; ADC1, ADC2 and ADC3s + DCD CAN1_TX_IRQHandler ; CAN1 TX + DCD CAN1_RX0_IRQHandler ; CAN1 RX0 + DCD CAN1_RX1_IRQHandler ; CAN1 RX1 + DCD CAN1_SCE_IRQHandler ; CAN1 SCE + DCD EINT9_5_IRQHandler ; External Line[9:5]s + DCD TMR1_BRK_TMR9_IRQHandler ; TMR1 Break and TMR9 + DCD TMR1_UP_TMR10_IRQHandler ; TMR1 Update and TMR10 + DCD TMR1_TRG_COM_TMR11_IRQHandler ; TMR1 Trigger and Commutation and TMR11 + DCD TMR1_CC_IRQHandler ; TMR1 Capture Compare + DCD TMR2_IRQHandler ; TMR2 + DCD TMR3_IRQHandler ; TMR3 + DCD TMR4_IRQHandler ; TMR4 + DCD I2C1_EV_IRQHandler ; I2C1 Event + DCD I2C1_ER_IRQHandler ; I2C1 Error + DCD I2C2_EV_IRQHandler ; I2C2 Event + DCD I2C2_ER_IRQHandler ; I2C2 Error + DCD SPI1_IRQHandler ; SPI1 + DCD SPI2_IRQHandler ; SPI2 + DCD USART1_IRQHandler ; USART1 + DCD USART2_IRQHandler ; USART2 + DCD USART3_IRQHandler ; USART3 + DCD EINT15_10_IRQHandler ; External Line[15:10]s + DCD RTC_Alarm_IRQHandler ; RTC Alarm (A and B) through EINT Line + DCD OTG_FS_WKUP_IRQHandler ; OTG_FS Wakeup through EINT line + DCD TMR8_BRK_TMR12_IRQHandler ; TMR8 Break and TMR12 + DCD TMR8_UP_TMR13_IRQHandler ; TMR8 Update and TMR13 + DCD TMR8_TRG_COM_TMR14_IRQHandler ; TMR8 Trigger and Commutation and TMR14 + DCD TMR8_CC_IRQHandler ; TMR8 Capture Compare + DCD DMA1_STR7_IRQHandler ; DMA1 Stream 7 + DCD EMMC_IRQHandler ; EMMC + DCD SDIO_IRQHandler ; SDIO + DCD TMR5_IRQHandler ; TMR5 + DCD SPI3_IRQHandler ; SPI3 + DCD UART4_IRQHandler ; UART4 + DCD UART5_IRQHandler ; UART5 + DCD TMR6_DAC_IRQHandler ; TMR6 and DAC1&2 underrun errors + DCD TMR7_IRQHandler ; TMR7 + DCD DMA2_STR0_IRQHandler ; DMA2 Stream 0 + DCD DMA2_STR1_IRQHandler ; DMA2 Stream 1 + DCD DMA2_STR2_IRQHandler ; DMA2 Stream 2 + DCD DMA2_STR3_IRQHandler ; DMA2 Stream 3 + DCD DMA2_STR4_IRQHandler ; DMA2 Stream 4 + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD CAN2_TX_IRQHandler ; CAN2 TX + DCD CAN2_RX0_IRQHandler ; CAN2 RX0 + DCD CAN2_RX1_IRQHandler ; CAN2 RX1 + DCD CAN2_SCE_IRQHandler ; CAN2 SCE + DCD OTG_FS_IRQHandler ; OTG_FS + DCD DMA2_STR5_IRQHandler ; DMA2 Stream 5 + DCD DMA2_STR6_IRQHandler ; DMA2 Stream 6 + DCD DMA2_STR7_IRQHandler ; DMA2 Stream 7 + DCD USART6_IRQHandler ; USART6 + DCD I2C3_EV_IRQHandler ; I2C3 event + DCD I2C3_ER_IRQHandler ; I2C3 error + DCD OTG_HS1_EP1_OUT_IRQHandler ; OTG_HS1 End Point 1 Out + DCD OTG_HS1_EP1_IN_IRQHandler ; OTG_HS1 End Point 1 In + DCD OTG_HS1_WKUP_IRQHandler ; OTG_HS1 Wakeup through EINT + DCD OTG_HS1_IRQHandler ; OTG_HS1 + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD HASH_RNG_IRQHandler ; Hash and Rng + DCD FPU_IRQHandler ; FPU + DCD SM3_IRQHandler ; SM3 + DCD SM4_IRQHandler ; SM4 + DCD BN_IRQHandler ; BN +__Vectors_End + +__Vectors_Size EQU __Vectors_End - __Vectors + + AREA |.text|, CODE, READONLY + +; Reset handler +Reset_Handler PROC + EXPORT Reset_Handler [WEAK] + IMPORT SystemInit + IMPORT __main + LDR R0, =SystemInit + BLX R0 + LDR R0, =__main + BX R0 + ENDP + +; Dummy Exception Handlers (infinite loops which can be modified) + +NMI_Handler PROC + EXPORT NMI_Handler [WEAK] + B . + ENDP +HardFault_Handler\ + PROC + EXPORT HardFault_Handler [WEAK] + B . + ENDP +MemManage_Handler\ + PROC + EXPORT MemManage_Handler [WEAK] + B . + ENDP +BusFault_Handler\ + PROC + EXPORT BusFault_Handler [WEAK] + B . + ENDP +UsageFault_Handler\ + PROC + EXPORT UsageFault_Handler [WEAK] + B . + ENDP +SVC_Handler PROC + EXPORT SVC_Handler [WEAK] + B . + ENDP +DebugMon_Handler\ + PROC + EXPORT DebugMon_Handler [WEAK] + B . + ENDP +PendSV_Handler PROC + EXPORT PendSV_Handler [WEAK] + B . + ENDP +SysTick_Handler PROC + EXPORT SysTick_Handler [WEAK] + B . + ENDP + +Default_Handler PROC + + EXPORT WWDT_IRQHandler [WEAK] + EXPORT PVD_IRQHandler [WEAK] + EXPORT TAMP_STAMP_IRQHandler [WEAK] + EXPORT RTC_WKUP_IRQHandler [WEAK] + EXPORT FLASH_IRQHandler [WEAK] + EXPORT RCM_IRQHandler [WEAK] + EXPORT EINT0_IRQHandler [WEAK] + EXPORT EINT1_IRQHandler [WEAK] + EXPORT EINT2_IRQHandler [WEAK] + EXPORT EINT3_IRQHandler [WEAK] + EXPORT EINT4_IRQHandler [WEAK] + EXPORT DMA1_STR0_IRQHandler [WEAK] + EXPORT DMA1_STR1_IRQHandler [WEAK] + EXPORT DMA1_STR2_IRQHandler [WEAK] + EXPORT DMA1_STR3_IRQHandler [WEAK] + EXPORT DMA1_STR4_IRQHandler [WEAK] + EXPORT DMA1_STR5_IRQHandler [WEAK] + EXPORT DMA1_STR6_IRQHandler [WEAK] + EXPORT ADC_IRQHandler [WEAK] + EXPORT CAN1_TX_IRQHandler [WEAK] + EXPORT CAN1_RX0_IRQHandler [WEAK] + EXPORT CAN1_RX1_IRQHandler [WEAK] + EXPORT CAN1_SCE_IRQHandler [WEAK] + EXPORT EINT9_5_IRQHandler [WEAK] + EXPORT TMR1_BRK_TMR9_IRQHandler [WEAK] + EXPORT TMR1_UP_TMR10_IRQHandler [WEAK] + EXPORT TMR1_TRG_COM_TMR11_IRQHandler [WEAK] + EXPORT TMR1_CC_IRQHandler [WEAK] + EXPORT TMR2_IRQHandler [WEAK] + EXPORT TMR3_IRQHandler [WEAK] + EXPORT TMR4_IRQHandler [WEAK] + EXPORT I2C1_EV_IRQHandler [WEAK] + EXPORT I2C1_ER_IRQHandler [WEAK] + EXPORT I2C2_EV_IRQHandler [WEAK] + EXPORT I2C2_ER_IRQHandler [WEAK] + EXPORT SPI1_IRQHandler [WEAK] + EXPORT SPI2_IRQHandler [WEAK] + EXPORT USART1_IRQHandler [WEAK] + EXPORT USART2_IRQHandler [WEAK] + EXPORT USART3_IRQHandler [WEAK] + EXPORT EINT15_10_IRQHandler [WEAK] + EXPORT RTC_Alarm_IRQHandler [WEAK] + EXPORT OTG_FS_WKUP_IRQHandler [WEAK] + EXPORT TMR8_BRK_TMR12_IRQHandler [WEAK] + EXPORT TMR8_UP_TMR13_IRQHandler [WEAK] + EXPORT TMR8_TRG_COM_TMR14_IRQHandler [WEAK] + EXPORT TMR8_CC_IRQHandler [WEAK] + EXPORT DMA1_STR7_IRQHandler [WEAK] + EXPORT EMMC_IRQHandler [WEAK] + EXPORT SDIO_IRQHandler [WEAK] + EXPORT TMR5_IRQHandler [WEAK] + EXPORT SPI3_IRQHandler [WEAK] + EXPORT UART4_IRQHandler [WEAK] + EXPORT UART5_IRQHandler [WEAK] + EXPORT TMR6_DAC_IRQHandler [WEAK] + EXPORT TMR7_IRQHandler [WEAK] + EXPORT DMA2_STR0_IRQHandler [WEAK] + EXPORT DMA2_STR1_IRQHandler [WEAK] + EXPORT DMA2_STR2_IRQHandler [WEAK] + EXPORT DMA2_STR3_IRQHandler [WEAK] + EXPORT DMA2_STR4_IRQHandler [WEAK] + EXPORT CAN2_TX_IRQHandler [WEAK] + EXPORT CAN2_RX0_IRQHandler [WEAK] + EXPORT CAN2_RX1_IRQHandler [WEAK] + EXPORT CAN2_SCE_IRQHandler [WEAK] + EXPORT OTG_FS_IRQHandler [WEAK] + EXPORT DMA2_STR5_IRQHandler [WEAK] + EXPORT DMA2_STR6_IRQHandler [WEAK] + EXPORT DMA2_STR7_IRQHandler [WEAK] + EXPORT USART6_IRQHandler [WEAK] + EXPORT I2C3_EV_IRQHandler [WEAK] + EXPORT I2C3_ER_IRQHandler [WEAK] + EXPORT OTG_HS1_EP1_OUT_IRQHandler [WEAK] + EXPORT OTG_HS1_EP1_IN_IRQHandler [WEAK] + EXPORT OTG_HS1_WKUP_IRQHandler [WEAK] + EXPORT OTG_HS1_IRQHandler [WEAK] + EXPORT HASH_RNG_IRQHandler [WEAK] + EXPORT FPU_IRQHandler [WEAK] + EXPORT SM3_IRQHandler [WEAK] + EXPORT SM4_IRQHandler [WEAK] + EXPORT BN_IRQHandler [WEAK] + +WWDT_IRQHandler +PVD_IRQHandler +TAMP_STAMP_IRQHandler +RTC_WKUP_IRQHandler +FLASH_IRQHandler +RCM_IRQHandler +EINT0_IRQHandler +EINT1_IRQHandler +EINT2_IRQHandler +EINT3_IRQHandler +EINT4_IRQHandler +DMA1_STR0_IRQHandler +DMA1_STR1_IRQHandler +DMA1_STR2_IRQHandler +DMA1_STR3_IRQHandler +DMA1_STR4_IRQHandler +DMA1_STR5_IRQHandler +DMA1_STR6_IRQHandler +ADC_IRQHandler +CAN1_TX_IRQHandler +CAN1_RX0_IRQHandler +CAN1_RX1_IRQHandler +CAN1_SCE_IRQHandler +EINT9_5_IRQHandler +TMR1_BRK_TMR9_IRQHandler +TMR1_UP_TMR10_IRQHandler +TMR1_TRG_COM_TMR11_IRQHandler +TMR1_CC_IRQHandler +TMR2_IRQHandler +TMR3_IRQHandler +TMR4_IRQHandler +I2C1_EV_IRQHandler +I2C1_ER_IRQHandler +I2C2_EV_IRQHandler +I2C2_ER_IRQHandler +SPI1_IRQHandler +SPI2_IRQHandler +USART1_IRQHandler +USART2_IRQHandler +USART3_IRQHandler +EINT15_10_IRQHandler +RTC_Alarm_IRQHandler +OTG_FS_WKUP_IRQHandler +TMR8_BRK_TMR12_IRQHandler +TMR8_UP_TMR13_IRQHandler +TMR8_TRG_COM_TMR14_IRQHandler +TMR8_CC_IRQHandler +DMA1_STR7_IRQHandler +EMMC_IRQHandler +SDIO_IRQHandler +TMR5_IRQHandler +SPI3_IRQHandler +UART4_IRQHandler +UART5_IRQHandler +TMR6_DAC_IRQHandler +TMR7_IRQHandler +DMA2_STR0_IRQHandler +DMA2_STR1_IRQHandler +DMA2_STR2_IRQHandler +DMA2_STR3_IRQHandler +DMA2_STR4_IRQHandler +CAN2_TX_IRQHandler +CAN2_RX0_IRQHandler +CAN2_RX1_IRQHandler +CAN2_SCE_IRQHandler +OTG_FS_IRQHandler +DMA2_STR5_IRQHandler +DMA2_STR6_IRQHandler +DMA2_STR7_IRQHandler +USART6_IRQHandler +I2C3_EV_IRQHandler +I2C3_ER_IRQHandler +OTG_HS1_EP1_OUT_IRQHandler +OTG_HS1_EP1_IN_IRQHandler +OTG_HS1_WKUP_IRQHandler +OTG_HS1_IRQHandler +HASH_RNG_IRQHandler +FPU_IRQHandler +SM3_IRQHandler +SM4_IRQHandler +BN_IRQHandler + + B . + + ENDP + + ALIGN + +;******************************************************************************* +; User Stack and Heap initialization +;******************************************************************************* + IF :DEF:__MICROLIB + + EXPORT __initial_sp + EXPORT __heap_base + EXPORT __heap_limit + + ELSE + + IMPORT __use_two_region_memory + EXPORT __user_initial_stackheap + +__user_initial_stackheap + + LDR R0, = Heap_Mem + LDR R1, =(Stack_Mem + Stack_Size) + LDR R2, = (Heap_Mem + Heap_Size) + LDR R3, = Stack_Mem + BX LR + + ALIGN + + ENDIF + + END + +;************************ (C) COPYRIGHT Geehy Semiconductor Co.,Ltd *****END OF FILE***** diff --git a/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/arm/startup_apm32f407xx.s b/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/arm/startup_apm32f407xx.s new file mode 100644 index 0000000000..eb194510a6 --- /dev/null +++ b/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/arm/startup_apm32f407xx.s @@ -0,0 +1,427 @@ +;/** +; * @file startup_apm32f407xx.s +; * +; * @brief CMSIS Cortex-M4 based Core Device Startup File for Device startup_apm32f407xx +; * +; * @version V1.0.0 +; * +; * @date 2023-07-31 +; * +; * @attention +; * +; * Copyright (C) 2023 Geehy Semiconductor +; * +; * You may not use this file except in compliance with the +; * GEEHY COPYRIGHT NOTICE (GEEHY SOFTWARE PACKAGE LICENSE). +; * +; * The program is only for reference, which is distributed in the hope +; * that it will be useful and instructional for customers to develop +; * their software. Unless required by applicable law or agreed to in +; * writing, the program is distributed on an "AS IS" BASIS, WITHOUT +; * ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied. +; * See the GEEHY SOFTWARE PACKAGE LICENSE for the governing permissions +; * and limitations under the License. +; */ + +; <<< Use Configuration Wizard in Context Menu >>> +; Stack Configuration +; Stack Size (in Bytes) <0x0-0xFFFFFFFF:8> +; + +Stack_Size EQU 0x00000400 + + AREA STACK, NOINIT, READWRITE, ALIGN=3 +Stack_Mem SPACE Stack_Size +__initial_sp + +; Heap Configuration +; Heap Size (in Bytes) <0x0-0xFFFFFFFF:8> +; + +Heap_Size EQU 0x00000200 + + AREA HEAP, NOINIT, READWRITE, ALIGN=3 +__heap_base +Heap_Mem SPACE Heap_Size +__heap_limit + + PRESERVE8 + THUMB + +; Vector Table Mapped to Address 0 at Reset + AREA RESET, DATA, READONLY + EXPORT __Vectors + EXPORT __Vectors_End + EXPORT __Vectors_Size + +__Vectors DCD __initial_sp ; Top of Stack + DCD Reset_Handler ; Reset Handler + DCD NMI_Handler ; NMI Handler + DCD HardFault_Handler ; Hard Fault Handler + DCD MemManage_Handler ; MPU Fault Handler + DCD BusFault_Handler ; Bus Fault Handler + DCD UsageFault_Handler ; Usage Fault Handler + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD SVC_Handler ; SVCall Handler + DCD DebugMon_Handler ; Debug Monitor Handler + DCD 0 ; Reserved + DCD PendSV_Handler ; PendSV Handler + DCD SysTick_Handler ; SysTick Handler + + ; External Interrupts + DCD WWDT_IRQHandler ; Window WatchDog + DCD PVD_IRQHandler ; PVD through EINT Line detection + DCD TAMP_STAMP_IRQHandler ; Tamper and TimeStamps through the EINT line + DCD RTC_WKUP_IRQHandler ; RTC Wakeup through the EINT line + DCD FLASH_IRQHandler ; FLASH + DCD RCM_IRQHandler ; RCM + DCD EINT0_IRQHandler ; EINT Line0 + DCD EINT1_IRQHandler ; EINT Line1 + DCD EINT2_IRQHandler ; EINT Line2 + DCD EINT3_IRQHandler ; EINT Line3 + DCD EINT4_IRQHandler ; EINT Line4 + DCD DMA1_STR0_IRQHandler ; DMA1 Stream 0 + DCD DMA1_STR1_IRQHandler ; DMA1 Stream 1 + DCD DMA1_STR2_IRQHandler ; DMA1 Stream 2 + DCD DMA1_STR3_IRQHandler ; DMA1 Stream 3 + DCD DMA1_STR4_IRQHandler ; DMA1 Stream 4 + DCD DMA1_STR5_IRQHandler ; DMA1 Stream 5 + DCD DMA1_STR6_IRQHandler ; DMA1 Stream 6 + DCD ADC_IRQHandler ; ADC1, ADC2 and ADC3s + DCD CAN1_TX_IRQHandler ; CAN1 TX + DCD CAN1_RX0_IRQHandler ; CAN1 RX0 + DCD CAN1_RX1_IRQHandler ; CAN1 RX1 + DCD CAN1_SCE_IRQHandler ; CAN1 SCE + DCD EINT9_5_IRQHandler ; External Line[9:5]s + DCD TMR1_BRK_TMR9_IRQHandler ; TMR1 Break and TMR9 + DCD TMR1_UP_TMR10_IRQHandler ; TMR1 Update and TMR10 + DCD TMR1_TRG_COM_TMR11_IRQHandler ; TMR1 Trigger and Commutation and TMR11 + DCD TMR1_CC_IRQHandler ; TMR1 Capture Compare + DCD TMR2_IRQHandler ; TMR2 + DCD TMR3_IRQHandler ; TMR3 + DCD TMR4_IRQHandler ; TMR4 + DCD I2C1_EV_IRQHandler ; I2C1 Event + DCD I2C1_ER_IRQHandler ; I2C1 Error + DCD I2C2_EV_IRQHandler ; I2C2 Event + DCD I2C2_ER_IRQHandler ; I2C2 Error + DCD SPI1_IRQHandler ; SPI1 + DCD SPI2_IRQHandler ; SPI2 + DCD USART1_IRQHandler ; USART1 + DCD USART2_IRQHandler ; USART2 + DCD USART3_IRQHandler ; USART3 + DCD EINT15_10_IRQHandler ; External Line[15:10]s + DCD RTC_Alarm_IRQHandler ; RTC Alarm (A and B) through EINT Line + DCD OTG_FS_WKUP_IRQHandler ; OTG_FS Wakeup through EINT line + DCD TMR8_BRK_TMR12_IRQHandler ; TMR8 Break and TMR12 + DCD TMR8_UP_TMR13_IRQHandler ; TMR8 Update and TMR13 + DCD TMR8_TRG_COM_TMR14_IRQHandler ; TMR8 Trigger and Commutation and TMR14 + DCD TMR8_CC_IRQHandler ; TMR8 Capture Compare + DCD DMA1_STR7_IRQHandler ; DMA1 Stream 7 + DCD EMMC_IRQHandler ; EMMC + DCD SDIO_IRQHandler ; SDIO + DCD TMR5_IRQHandler ; TMR5 + DCD SPI3_IRQHandler ; SPI3 + DCD UART4_IRQHandler ; UART4 + DCD UART5_IRQHandler ; UART5 + DCD TMR6_DAC_IRQHandler ; TMR6 and DAC1&2 underrun errors + DCD TMR7_IRQHandler ; TMR7 + DCD DMA2_STR0_IRQHandler ; DMA2 Stream 0 + DCD DMA2_STR1_IRQHandler ; DMA2 Stream 1 + DCD DMA2_STR2_IRQHandler ; DMA2 Stream 2 + DCD DMA2_STR3_IRQHandler ; DMA2 Stream 3 + DCD DMA2_STR4_IRQHandler ; DMA2 Stream 4 + DCD ETH_IRQHandler ; Ethernet + DCD ETH_WKUP_IRQHandler ; Ethernet Wakeup through EINT line + DCD CAN2_TX_IRQHandler ; CAN2 TX + DCD CAN2_RX0_IRQHandler ; CAN2 RX0 + DCD CAN2_RX1_IRQHandler ; CAN2 RX1 + DCD CAN2_SCE_IRQHandler ; CAN2 SCE + DCD OTG_FS_IRQHandler ; OTG_FS + DCD DMA2_STR5_IRQHandler ; DMA2 Stream 5 + DCD DMA2_STR6_IRQHandler ; DMA2 Stream 6 + DCD DMA2_STR7_IRQHandler ; DMA2 Stream 7 + DCD USART6_IRQHandler ; USART6 + DCD I2C3_EV_IRQHandler ; I2C3 event + DCD I2C3_ER_IRQHandler ; I2C3 error + DCD OTG_HS1_EP1_OUT_IRQHandler ; OTG_HS1 End Point 1 Out + DCD OTG_HS1_EP1_IN_IRQHandler ; OTG_HS1 End Point 1 In + DCD OTG_HS1_WKUP_IRQHandler ; OTG_HS1 Wakeup through EINT + DCD OTG_HS1_IRQHandler ; OTG_HS1 + DCD DCI_IRQHandler ; DCI + DCD 0 ; Reserved + DCD HASH_RNG_IRQHandler ; Hash and Rng + DCD FPU_IRQHandler ; FPU + DCD SM3_IRQHandler ; SM3 + DCD SM4_IRQHandler ; SM4 + DCD BN_IRQHandler ; BN +__Vectors_End + +__Vectors_Size EQU __Vectors_End - __Vectors + + AREA |.text|, CODE, READONLY + +; Reset handler +Reset_Handler PROC + EXPORT Reset_Handler [WEAK] + IMPORT SystemInit + IMPORT __main + LDR R0, =SystemInit + BLX R0 + LDR R0, =__main + BX R0 + ENDP + +; Dummy Exception Handlers (infinite loops which can be modified) + +NMI_Handler PROC + EXPORT NMI_Handler [WEAK] + B . + ENDP +HardFault_Handler\ + PROC + EXPORT HardFault_Handler [WEAK] + B . + ENDP +MemManage_Handler\ + PROC + EXPORT MemManage_Handler [WEAK] + B . + ENDP +BusFault_Handler\ + PROC + EXPORT BusFault_Handler [WEAK] + B . + ENDP +UsageFault_Handler\ + PROC + EXPORT UsageFault_Handler [WEAK] + B . + ENDP +SVC_Handler PROC + EXPORT SVC_Handler [WEAK] + B . + ENDP +DebugMon_Handler\ + PROC + EXPORT DebugMon_Handler [WEAK] + B . + ENDP +PendSV_Handler PROC + EXPORT PendSV_Handler [WEAK] + B . + ENDP +SysTick_Handler PROC + EXPORT SysTick_Handler [WEAK] + B . + ENDP + +Default_Handler PROC + + EXPORT WWDT_IRQHandler [WEAK] + EXPORT PVD_IRQHandler [WEAK] + EXPORT TAMP_STAMP_IRQHandler [WEAK] + EXPORT RTC_WKUP_IRQHandler [WEAK] + EXPORT FLASH_IRQHandler [WEAK] + EXPORT RCM_IRQHandler [WEAK] + EXPORT EINT0_IRQHandler [WEAK] + EXPORT EINT1_IRQHandler [WEAK] + EXPORT EINT2_IRQHandler [WEAK] + EXPORT EINT3_IRQHandler [WEAK] + EXPORT EINT4_IRQHandler [WEAK] + EXPORT DMA1_STR0_IRQHandler [WEAK] + EXPORT DMA1_STR1_IRQHandler [WEAK] + EXPORT DMA1_STR2_IRQHandler [WEAK] + EXPORT DMA1_STR3_IRQHandler [WEAK] + EXPORT DMA1_STR4_IRQHandler [WEAK] + EXPORT DMA1_STR5_IRQHandler [WEAK] + EXPORT DMA1_STR6_IRQHandler [WEAK] + EXPORT ADC_IRQHandler [WEAK] + EXPORT CAN1_TX_IRQHandler [WEAK] + EXPORT CAN1_RX0_IRQHandler [WEAK] + EXPORT CAN1_RX1_IRQHandler [WEAK] + EXPORT CAN1_SCE_IRQHandler [WEAK] + EXPORT EINT9_5_IRQHandler [WEAK] + EXPORT TMR1_BRK_TMR9_IRQHandler [WEAK] + EXPORT TMR1_UP_TMR10_IRQHandler [WEAK] + EXPORT TMR1_TRG_COM_TMR11_IRQHandler [WEAK] + EXPORT TMR1_CC_IRQHandler [WEAK] + EXPORT TMR2_IRQHandler [WEAK] + EXPORT TMR3_IRQHandler [WEAK] + EXPORT TMR4_IRQHandler [WEAK] + EXPORT I2C1_EV_IRQHandler [WEAK] + EXPORT I2C1_ER_IRQHandler [WEAK] + EXPORT I2C2_EV_IRQHandler [WEAK] + EXPORT I2C2_ER_IRQHandler [WEAK] + EXPORT SPI1_IRQHandler [WEAK] + EXPORT SPI2_IRQHandler [WEAK] + EXPORT USART1_IRQHandler [WEAK] + EXPORT USART2_IRQHandler [WEAK] + EXPORT USART3_IRQHandler [WEAK] + EXPORT EINT15_10_IRQHandler [WEAK] + EXPORT RTC_Alarm_IRQHandler [WEAK] + EXPORT OTG_FS_WKUP_IRQHandler [WEAK] + EXPORT TMR8_BRK_TMR12_IRQHandler [WEAK] + EXPORT TMR8_UP_TMR13_IRQHandler [WEAK] + EXPORT TMR8_TRG_COM_TMR14_IRQHandler [WEAK] + EXPORT TMR8_CC_IRQHandler [WEAK] + EXPORT DMA1_STR7_IRQHandler [WEAK] + EXPORT EMMC_IRQHandler [WEAK] + EXPORT SDIO_IRQHandler [WEAK] + EXPORT TMR5_IRQHandler [WEAK] + EXPORT SPI3_IRQHandler [WEAK] + EXPORT UART4_IRQHandler [WEAK] + EXPORT UART5_IRQHandler [WEAK] + EXPORT TMR6_DAC_IRQHandler [WEAK] + EXPORT TMR7_IRQHandler [WEAK] + EXPORT DMA2_STR0_IRQHandler [WEAK] + EXPORT DMA2_STR1_IRQHandler [WEAK] + EXPORT DMA2_STR2_IRQHandler [WEAK] + EXPORT DMA2_STR3_IRQHandler [WEAK] + EXPORT DMA2_STR4_IRQHandler [WEAK] + EXPORT ETH_IRQHandler [WEAK] + EXPORT ETH_WKUP_IRQHandler [WEAK] + EXPORT CAN2_TX_IRQHandler [WEAK] + EXPORT CAN2_RX0_IRQHandler [WEAK] + EXPORT CAN2_RX1_IRQHandler [WEAK] + EXPORT CAN2_SCE_IRQHandler [WEAK] + EXPORT OTG_FS_IRQHandler [WEAK] + EXPORT DMA2_STR5_IRQHandler [WEAK] + EXPORT DMA2_STR6_IRQHandler [WEAK] + EXPORT DMA2_STR7_IRQHandler [WEAK] + EXPORT USART6_IRQHandler [WEAK] + EXPORT I2C3_EV_IRQHandler [WEAK] + EXPORT I2C3_ER_IRQHandler [WEAK] + EXPORT OTG_HS1_EP1_OUT_IRQHandler [WEAK] + EXPORT OTG_HS1_EP1_IN_IRQHandler [WEAK] + EXPORT OTG_HS1_WKUP_IRQHandler [WEAK] + EXPORT OTG_HS1_IRQHandler [WEAK] + EXPORT DCI_IRQHandler [WEAK] + EXPORT HASH_RNG_IRQHandler [WEAK] + EXPORT FPU_IRQHandler [WEAK] + EXPORT SM3_IRQHandler [WEAK] + EXPORT SM4_IRQHandler [WEAK] + EXPORT BN_IRQHandler [WEAK] + +WWDT_IRQHandler +PVD_IRQHandler +TAMP_STAMP_IRQHandler +RTC_WKUP_IRQHandler +FLASH_IRQHandler +RCM_IRQHandler +EINT0_IRQHandler +EINT1_IRQHandler +EINT2_IRQHandler +EINT3_IRQHandler +EINT4_IRQHandler +DMA1_STR0_IRQHandler +DMA1_STR1_IRQHandler +DMA1_STR2_IRQHandler +DMA1_STR3_IRQHandler +DMA1_STR4_IRQHandler +DMA1_STR5_IRQHandler +DMA1_STR6_IRQHandler +ADC_IRQHandler +CAN1_TX_IRQHandler +CAN1_RX0_IRQHandler +CAN1_RX1_IRQHandler +CAN1_SCE_IRQHandler +EINT9_5_IRQHandler +TMR1_BRK_TMR9_IRQHandler +TMR1_UP_TMR10_IRQHandler +TMR1_TRG_COM_TMR11_IRQHandler +TMR1_CC_IRQHandler +TMR2_IRQHandler +TMR3_IRQHandler +TMR4_IRQHandler +I2C1_EV_IRQHandler +I2C1_ER_IRQHandler +I2C2_EV_IRQHandler +I2C2_ER_IRQHandler +SPI1_IRQHandler +SPI2_IRQHandler +USART1_IRQHandler +USART2_IRQHandler +USART3_IRQHandler +EINT15_10_IRQHandler +RTC_Alarm_IRQHandler +OTG_FS_WKUP_IRQHandler +TMR8_BRK_TMR12_IRQHandler +TMR8_UP_TMR13_IRQHandler +TMR8_TRG_COM_TMR14_IRQHandler +TMR8_CC_IRQHandler +DMA1_STR7_IRQHandler +EMMC_IRQHandler +SDIO_IRQHandler +TMR5_IRQHandler +SPI3_IRQHandler +UART4_IRQHandler +UART5_IRQHandler +TMR6_DAC_IRQHandler +TMR7_IRQHandler +DMA2_STR0_IRQHandler +DMA2_STR1_IRQHandler +DMA2_STR2_IRQHandler +DMA2_STR3_IRQHandler +DMA2_STR4_IRQHandler +ETH_IRQHandler +ETH_WKUP_IRQHandler +CAN2_TX_IRQHandler +CAN2_RX0_IRQHandler +CAN2_RX1_IRQHandler +CAN2_SCE_IRQHandler +OTG_FS_IRQHandler +DMA2_STR5_IRQHandler +DMA2_STR6_IRQHandler +DMA2_STR7_IRQHandler +USART6_IRQHandler +I2C3_EV_IRQHandler +I2C3_ER_IRQHandler +OTG_HS1_EP1_OUT_IRQHandler +OTG_HS1_EP1_IN_IRQHandler +OTG_HS1_WKUP_IRQHandler +OTG_HS1_IRQHandler +DCI_IRQHandler +HASH_RNG_IRQHandler +FPU_IRQHandler +SM3_IRQHandler +SM4_IRQHandler +BN_IRQHandler + + B . + + ENDP + + ALIGN + +;******************************************************************************* +; User Stack and Heap initialization +;******************************************************************************* + IF :DEF:__MICROLIB + + EXPORT __initial_sp + EXPORT __heap_base + EXPORT __heap_limit + + ELSE + + IMPORT __use_two_region_memory + EXPORT __user_initial_stackheap + +__user_initial_stackheap + + LDR R0, = Heap_Mem + LDR R1, =(Stack_Mem + Stack_Size) + LDR R2, = (Heap_Mem + Heap_Size) + LDR R3, = Stack_Mem + BX LR + + ALIGN + + ENDIF + + END + +;************************ (C) COPYRIGHT Geehy Semiconductor Co.,Ltd *****END OF FILE***** diff --git a/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/arm/startup_apm32f411xx.s b/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/arm/startup_apm32f411xx.s new file mode 100644 index 0000000000..f8663bae4d --- /dev/null +++ b/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/arm/startup_apm32f411xx.s @@ -0,0 +1,410 @@ +;/** +; * @file startup_apm32f411xx.s +; * +; * @brief CMSIS Cortex-M4 based Core Device Startup File for Device startup_apm32f411xx +; * +; * @version V1.0.0 +; * +; * @date 2023-12-01 +; * +; * @attention +; * +; * Copyright (C) 2023 Geehy Semiconductor +; * +; * You may not use this file except in compliance with the +; * GEEHY COPYRIGHT NOTICE (GEEHY SOFTWARE PACKAGE LICENSE). +; * +; * The program is only for reference, which is distributed in the hope +; * that it will be useful and instructional for customers to develop +; * their software. Unless required by applicable law or agreed to in +; * writing, the program is distributed on an "AS IS" BASIS, WITHOUT +; * ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied. +; * See the GEEHY SOFTWARE PACKAGE LICENSE for the governing permissions +; * and limitations under the License. +; */ + +; <<< Use Configuration Wizard in Context Menu >>> +; Stack Configuration +; Stack Size (in Bytes) <0x0-0xFFFFFFFF:8> +; + +Stack_Size EQU 0x00000400 + + AREA STACK, NOINIT, READWRITE, ALIGN=3 +Stack_Mem SPACE Stack_Size +__initial_sp + +; Heap Configuration +; Heap Size (in Bytes) <0x0-0xFFFFFFFF:8> +; + +Heap_Size EQU 0x00000200 + + AREA HEAP, NOINIT, READWRITE, ALIGN=3 +__heap_base +Heap_Mem SPACE Heap_Size +__heap_limit + + PRESERVE8 + THUMB + +; Vector Table Mapped to Address 0 at Reset + AREA RESET, DATA, READONLY + EXPORT __Vectors + EXPORT __Vectors_End + EXPORT __Vectors_Size + +__Vectors DCD __initial_sp ; Top of Stack + DCD Reset_Handler ; Reset Handler + DCD NMI_Handler ; NMI Handler + DCD HardFault_Handler ; Hard Fault Handler + DCD MemManage_Handler ; MPU Fault Handler + DCD BusFault_Handler ; Bus Fault Handler + DCD UsageFault_Handler ; Usage Fault Handler + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD SVC_Handler ; SVCall Handler + DCD DebugMon_Handler ; Debug Monitor Handler + DCD 0 ; Reserved + DCD PendSV_Handler ; PendSV Handler + DCD SysTick_Handler ; SysTick Handler + + ; External Interrupts + DCD WWDT_IRQHandler ; Window WatchDog + DCD PVD_IRQHandler ; PVD through EINT Line detection + DCD TAMP_STAMP_IRQHandler ; Tamper and TimeStamps through the EINT line + DCD RTC_WKUP_IRQHandler ; RTC Wakeup through the EINT line + DCD FLASH_IRQHandler ; FLASH + DCD RCM_IRQHandler ; RCM + DCD EINT0_IRQHandler ; EINT Line0 + DCD EINT1_IRQHandler ; EINT Line1 + DCD EINT2_IRQHandler ; EINT Line2 + DCD EINT3_IRQHandler ; EINT Line3 + DCD EINT4_IRQHandler ; EINT Line4 + DCD DMA1_STR0_IRQHandler ; DMA1 Stream 0 + DCD DMA1_STR1_IRQHandler ; DMA1 Stream 1 + DCD DMA1_STR2_IRQHandler ; DMA1 Stream 2 + DCD DMA1_STR3_IRQHandler ; DMA1 Stream 3 + DCD DMA1_STR4_IRQHandler ; DMA1 Stream 4 + DCD DMA1_STR5_IRQHandler ; DMA1 Stream 5 + DCD DMA1_STR6_IRQHandler ; DMA1 Stream 6 + DCD ADC_IRQHandler ; ADC1 and ADC2 + DCD CAN1_TX_IRQHandler ; CAN1 TX + DCD CAN1_RX0_IRQHandler ; CAN1 RX0 + DCD CAN1_RX1_IRQHandler ; CAN1 RX1 + DCD CAN1_SCE_IRQHandler ; CAN1 SCE + DCD EINT9_5_IRQHandler ; External Line[9:5]s + DCD TMR1_BRK_TMR9_IRQHandler ; TMR1 Break and TMR9 + DCD TMR1_UP_TMR10_IRQHandler ; TMR1 Update and TMR10 + DCD TMR1_TRG_COM_TMR11_IRQHandler ; TMR1 Trigger and Commutation and TMR11 + DCD TMR1_CC_IRQHandler ; TMR1 Capture Compare + DCD TMR2_IRQHandler ; TMR2 + DCD TMR3_IRQHandler ; TMR3 + DCD TMR4_IRQHandler ; TMR4 + DCD I2C1_EV_IRQHandler ; I2C1 Event + DCD I2C1_ER_IRQHandler ; I2C1 Error + DCD I2C2_EV_IRQHandler ; I2C2 Event + DCD I2C2_ER_IRQHandler ; I2C2 Error + DCD SPI1_IRQHandler ; SPI1 + DCD SPI2_IRQHandler ; SPI2 + DCD USART1_IRQHandler ; USART1 + DCD USART2_IRQHandler ; USART2 + DCD USART3_IRQHandler ; USART3 + DCD EINT15_10_IRQHandler ; External Line[15:10]s + DCD RTC_Alarm_IRQHandler ; RTC Alarm (A and B) through EINT Line + DCD OTG_FS_WKUP_IRQHandler ; OTG_FS Wakeup through EINT line + DCD TMR8_BRK_TMR12_IRQHandler ; TMR8 Break and TMR12 + DCD TMR8_UP_TMR13_IRQHandler ; TMR8 Update and TMR13 + DCD TMR8_TRG_COM_TMR14_IRQHandler ; TMR8 Trigger and Commutation and TMR14 + DCD TMR8_CC_IRQHandler ; TMR8 Capture Compare + DCD DMA1_STR7_IRQHandler ; DMA1 Stream 7 + DCD SMC_IRQHandler ; SMC + DCD SDIO_IRQHandler ; SDIO + DCD TMR5_IRQHandler ; TMR5 + DCD SPI3_IRQHandler ; SPI3 + DCD UART4_IRQHandler ; UART4 + DCD UART5_IRQHandler ; UART5 + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD DMA2_STR0_IRQHandler ; DMA2 Stream 0 + DCD DMA2_STR1_IRQHandler ; DMA2 Stream 1 + DCD DMA2_STR2_IRQHandler ; DMA2 Stream 2 + DCD DMA2_STR3_IRQHandler ; DMA2 Stream 3 + DCD DMA2_STR4_IRQHandler ; DMA2 Stream 4 + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD CAN2_TX_IRQHandler ; CAN2 TX + DCD CAN2_RX0_IRQHandler ; CAN2 RX0 + DCD CAN2_RX1_IRQHandler ; CAN2 RX1 + DCD CAN2_SCE_IRQHandler ; CAN2 SCE + DCD OTG_FS_IRQHandler ; OTG_FS + DCD DMA2_STR5_IRQHandler ; DMA2 Stream 5 + DCD DMA2_STR6_IRQHandler ; DMA2 Stream 6 + DCD DMA2_STR7_IRQHandler ; DMA2 Stream 7 + DCD USART6_IRQHandler ; USART6 + DCD I2C3_EV_IRQHandler ; I2C3 event + DCD I2C3_ER_IRQHandler ; I2C3 error + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD RNG_IRQHandler ; RNG + DCD FPU_IRQHandler ; FPU + DCD 0 ; Reserved + DCD QSPI_IRQHandler ; QSPI + DCD SPI4_IRQHandler ; SPI4 + DCD SPI5_IRQHandler ; SPI5 +__Vectors_End + +__Vectors_Size EQU __Vectors_End - __Vectors + + AREA |.text|, CODE, READONLY + +; Reset handler +Reset_Handler PROC + EXPORT Reset_Handler [WEAK] + IMPORT SystemInit + IMPORT __main + LDR R0, =SystemInit + BLX R0 + LDR R0, =__main + BX R0 + ENDP + +; Dummy Exception Handlers (infinite loops which can be modified) + +NMI_Handler PROC + EXPORT NMI_Handler [WEAK] + B . + ENDP +HardFault_Handler\ + PROC + EXPORT HardFault_Handler [WEAK] + B . + ENDP +MemManage_Handler\ + PROC + EXPORT MemManage_Handler [WEAK] + B . + ENDP +BusFault_Handler\ + PROC + EXPORT BusFault_Handler [WEAK] + B . + ENDP +UsageFault_Handler\ + PROC + EXPORT UsageFault_Handler [WEAK] + B . + ENDP +SVC_Handler PROC + EXPORT SVC_Handler [WEAK] + B . + ENDP +DebugMon_Handler\ + PROC + EXPORT DebugMon_Handler [WEAK] + B . + ENDP +PendSV_Handler PROC + EXPORT PendSV_Handler [WEAK] + B . + ENDP +SysTick_Handler PROC + EXPORT SysTick_Handler [WEAK] + B . + ENDP + +Default_Handler PROC + + EXPORT WWDT_IRQHandler [WEAK] + EXPORT PVD_IRQHandler [WEAK] + EXPORT TAMP_STAMP_IRQHandler [WEAK] + EXPORT RTC_WKUP_IRQHandler [WEAK] + EXPORT FLASH_IRQHandler [WEAK] + EXPORT RCM_IRQHandler [WEAK] + EXPORT EINT0_IRQHandler [WEAK] + EXPORT EINT1_IRQHandler [WEAK] + EXPORT EINT2_IRQHandler [WEAK] + EXPORT EINT3_IRQHandler [WEAK] + EXPORT EINT4_IRQHandler [WEAK] + EXPORT DMA1_STR0_IRQHandler [WEAK] + EXPORT DMA1_STR1_IRQHandler [WEAK] + EXPORT DMA1_STR2_IRQHandler [WEAK] + EXPORT DMA1_STR3_IRQHandler [WEAK] + EXPORT DMA1_STR4_IRQHandler [WEAK] + EXPORT DMA1_STR5_IRQHandler [WEAK] + EXPORT DMA1_STR6_IRQHandler [WEAK] + EXPORT ADC_IRQHandler [WEAK] + EXPORT CAN1_TX_IRQHandler [WEAK] + EXPORT CAN1_RX0_IRQHandler [WEAK] + EXPORT CAN1_RX1_IRQHandler [WEAK] + EXPORT CAN1_SCE_IRQHandler [WEAK] + EXPORT EINT9_5_IRQHandler [WEAK] + EXPORT TMR1_BRK_TMR9_IRQHandler [WEAK] + EXPORT TMR1_UP_TMR10_IRQHandler [WEAK] + EXPORT TMR1_TRG_COM_TMR11_IRQHandler [WEAK] + EXPORT TMR1_CC_IRQHandler [WEAK] + EXPORT TMR2_IRQHandler [WEAK] + EXPORT TMR3_IRQHandler [WEAK] + EXPORT TMR4_IRQHandler [WEAK] + EXPORT I2C1_EV_IRQHandler [WEAK] + EXPORT I2C1_ER_IRQHandler [WEAK] + EXPORT I2C2_EV_IRQHandler [WEAK] + EXPORT I2C2_ER_IRQHandler [WEAK] + EXPORT SPI1_IRQHandler [WEAK] + EXPORT SPI2_IRQHandler [WEAK] + EXPORT USART1_IRQHandler [WEAK] + EXPORT USART2_IRQHandler [WEAK] + EXPORT USART3_IRQHandler [WEAK] + EXPORT EINT15_10_IRQHandler [WEAK] + EXPORT RTC_Alarm_IRQHandler [WEAK] + EXPORT OTG_FS_WKUP_IRQHandler [WEAK] + EXPORT TMR8_BRK_TMR12_IRQHandler [WEAK] + EXPORT TMR8_UP_TMR13_IRQHandler [WEAK] + EXPORT TMR8_TRG_COM_TMR14_IRQHandler [WEAK] + EXPORT TMR8_CC_IRQHandler [WEAK] + EXPORT DMA1_STR7_IRQHandler [WEAK] + EXPORT SMC_IRQHandler [WEAK] + EXPORT SDIO_IRQHandler [WEAK] + EXPORT TMR5_IRQHandler [WEAK] + EXPORT SPI3_IRQHandler [WEAK] + EXPORT UART4_IRQHandler [WEAK] + EXPORT UART5_IRQHandler [WEAK] + EXPORT DMA2_STR0_IRQHandler [WEAK] + EXPORT DMA2_STR1_IRQHandler [WEAK] + EXPORT DMA2_STR2_IRQHandler [WEAK] + EXPORT DMA2_STR3_IRQHandler [WEAK] + EXPORT DMA2_STR4_IRQHandler [WEAK] + EXPORT CAN2_TX_IRQHandler [WEAK] + EXPORT CAN2_RX0_IRQHandler [WEAK] + EXPORT CAN2_RX1_IRQHandler [WEAK] + EXPORT CAN2_SCE_IRQHandler [WEAK] + EXPORT OTG_FS_IRQHandler [WEAK] + EXPORT DMA2_STR5_IRQHandler [WEAK] + EXPORT DMA2_STR6_IRQHandler [WEAK] + EXPORT DMA2_STR7_IRQHandler [WEAK] + EXPORT USART6_IRQHandler [WEAK] + EXPORT I2C3_EV_IRQHandler [WEAK] + EXPORT I2C3_ER_IRQHandler [WEAK] + EXPORT RNG_IRQHandler [WEAK] + EXPORT FPU_IRQHandler [WEAK] + EXPORT QSPI_IRQHandler [WEAK] + EXPORT SPI4_IRQHandler [WEAK] + EXPORT SPI5_IRQHandler [WEAK] + +WWDT_IRQHandler +PVD_IRQHandler +TAMP_STAMP_IRQHandler +RTC_WKUP_IRQHandler +FLASH_IRQHandler +RCM_IRQHandler +EINT0_IRQHandler +EINT1_IRQHandler +EINT2_IRQHandler +EINT3_IRQHandler +EINT4_IRQHandler +DMA1_STR0_IRQHandler +DMA1_STR1_IRQHandler +DMA1_STR2_IRQHandler +DMA1_STR3_IRQHandler +DMA1_STR4_IRQHandler +DMA1_STR5_IRQHandler +DMA1_STR6_IRQHandler +ADC_IRQHandler +CAN1_TX_IRQHandler +CAN1_RX0_IRQHandler +CAN1_RX1_IRQHandler +CAN1_SCE_IRQHandler +EINT9_5_IRQHandler +TMR1_BRK_TMR9_IRQHandler +TMR1_UP_TMR10_IRQHandler +TMR1_TRG_COM_TMR11_IRQHandler +TMR1_CC_IRQHandler +TMR2_IRQHandler +TMR3_IRQHandler +TMR4_IRQHandler +I2C1_EV_IRQHandler +I2C1_ER_IRQHandler +I2C2_EV_IRQHandler +I2C2_ER_IRQHandler +SPI1_IRQHandler +SPI2_IRQHandler +USART1_IRQHandler +USART2_IRQHandler +USART3_IRQHandler +EINT15_10_IRQHandler +RTC_Alarm_IRQHandler +OTG_FS_WKUP_IRQHandler +TMR8_BRK_TMR12_IRQHandler +TMR8_UP_TMR13_IRQHandler +TMR8_TRG_COM_TMR14_IRQHandler +TMR8_CC_IRQHandler +DMA1_STR7_IRQHandler +SMC_IRQHandler +SDIO_IRQHandler +TMR5_IRQHandler +SPI3_IRQHandler +UART4_IRQHandler +UART5_IRQHandler +DMA2_STR0_IRQHandler +DMA2_STR1_IRQHandler +DMA2_STR2_IRQHandler +DMA2_STR3_IRQHandler +DMA2_STR4_IRQHandler +CAN2_TX_IRQHandler +CAN2_RX0_IRQHandler +CAN2_RX1_IRQHandler +CAN2_SCE_IRQHandler +OTG_FS_IRQHandler +DMA2_STR5_IRQHandler +DMA2_STR6_IRQHandler +DMA2_STR7_IRQHandler +USART6_IRQHandler +I2C3_EV_IRQHandler +I2C3_ER_IRQHandler +RNG_IRQHandler +FPU_IRQHandler +QSPI_IRQHandler +SPI4_IRQHandler +SPI5_IRQHandler + + B . + + ENDP + + ALIGN + +;******************************************************************************* +; User Stack and Heap initialization +;******************************************************************************* + IF :DEF:__MICROLIB + + EXPORT __initial_sp + EXPORT __heap_base + EXPORT __heap_limit + + ELSE + + IMPORT __use_two_region_memory + EXPORT __user_initial_stackheap + +__user_initial_stackheap + + LDR R0, = Heap_Mem + LDR R1, =(Stack_Mem + Stack_Size) + LDR R2, = (Heap_Mem + Heap_Size) + LDR R3, = Stack_Mem + BX LR + + ALIGN + + ENDIF + + END + +;************************ (C) COPYRIGHT Geehy Semiconductor Co.,Ltd *****END OF FILE***** diff --git a/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/arm/startup_apm32f417xx.s b/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/arm/startup_apm32f417xx.s new file mode 100644 index 0000000000..18b920ee0e --- /dev/null +++ b/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/arm/startup_apm32f417xx.s @@ -0,0 +1,428 @@ +;/** +; * @file startup_apm32f417xx.s +; * +; * @brief CMSIS Cortex-M4 based Core Device Startup File for Device startup_apm32f417xx +; * +; * @version V1.0.0 +; * +; * @date 2023-07-31 +; * +; * @attention +; * +; * Copyright (C) 2023 Geehy Semiconductor +; * +; * You may not use this file except in compliance with the +; * GEEHY COPYRIGHT NOTICE (GEEHY SOFTWARE PACKAGE LICENSE). +; * +; * The program is only for reference, which is distributed in the hope +; * that it will be useful and instructional for customers to develop +; * their software. Unless required by applicable law or agreed to in +; * writing, the program is distributed on an "AS IS" BASIS, WITHOUT +; * ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied. +; * See the GEEHY SOFTWARE PACKAGE LICENSE for the governing permissions +; * and limitations under the License. +; */ + +; <<< Use Configuration Wizard in Context Menu >>> +; Stack Configuration +; Stack Size (in Bytes) <0x0-0xFFFFFFFF:8> +; + +Stack_Size EQU 0x00000400 + + AREA STACK, NOINIT, READWRITE, ALIGN=3 +Stack_Mem SPACE Stack_Size +__initial_sp + +; Heap Configuration +; Heap Size (in Bytes) <0x0-0xFFFFFFFF:8> +; + +Heap_Size EQU 0x00000200 + + AREA HEAP, NOINIT, READWRITE, ALIGN=3 +__heap_base +Heap_Mem SPACE Heap_Size +__heap_limit + + PRESERVE8 + THUMB + +; Vector Table Mapped to Address 0 at Reset + AREA RESET, DATA, READONLY + EXPORT __Vectors + EXPORT __Vectors_End + EXPORT __Vectors_Size + +__Vectors DCD __initial_sp ; Top of Stack + DCD Reset_Handler ; Reset Handler + DCD NMI_Handler ; NMI Handler + DCD HardFault_Handler ; Hard Fault Handler + DCD MemManage_Handler ; MPU Fault Handler + DCD BusFault_Handler ; Bus Fault Handler + DCD UsageFault_Handler ; Usage Fault Handler + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD SVC_Handler ; SVCall Handler + DCD DebugMon_Handler ; Debug Monitor Handler + DCD 0 ; Reserved + DCD PendSV_Handler ; PendSV Handler + DCD SysTick_Handler ; SysTick Handler + + ; External Interrupts + DCD WWDT_IRQHandler ; Window WatchDog + DCD PVD_IRQHandler ; PVD through EINT Line detection + DCD TAMP_STAMP_IRQHandler ; Tamper and TimeStamps through the EINT line + DCD RTC_WKUP_IRQHandler ; RTC Wakeup through the EINT line + DCD FLASH_IRQHandler ; FLASH + DCD RCM_IRQHandler ; RCM + DCD EINT0_IRQHandler ; EINT Line0 + DCD EINT1_IRQHandler ; EINT Line1 + DCD EINT2_IRQHandler ; EINT Line2 + DCD EINT3_IRQHandler ; EINT Line3 + DCD EINT4_IRQHandler ; EINT Line4 + DCD DMA1_STR0_IRQHandler ; DMA1 Stream 0 + DCD DMA1_STR1_IRQHandler ; DMA1 Stream 1 + DCD DMA1_STR2_IRQHandler ; DMA1 Stream 2 + DCD DMA1_STR3_IRQHandler ; DMA1 Stream 3 + DCD DMA1_STR4_IRQHandler ; DMA1 Stream 4 + DCD DMA1_STR5_IRQHandler ; DMA1 Stream 5 + DCD DMA1_STR6_IRQHandler ; DMA1 Stream 6 + DCD ADC_IRQHandler ; ADC1, ADC2 and ADC3s + DCD CAN1_TX_IRQHandler ; CAN1 TX + DCD CAN1_RX0_IRQHandler ; CAN1 RX0 + DCD CAN1_RX1_IRQHandler ; CAN1 RX1 + DCD CAN1_SCE_IRQHandler ; CAN1 SCE + DCD EINT9_5_IRQHandler ; External Line[9:5]s + DCD TMR1_BRK_TMR9_IRQHandler ; TMR1 Break and TMR9 + DCD TMR1_UP_TMR10_IRQHandler ; TMR1 Update and TMR10 + DCD TMR1_TRG_COM_TMR11_IRQHandler ; TMR1 Trigger and Commutation and TMR11 + DCD TMR1_CC_IRQHandler ; TMR1 Capture Compare + DCD TMR2_IRQHandler ; TMR2 + DCD TMR3_IRQHandler ; TMR3 + DCD TMR4_IRQHandler ; TMR4 + DCD I2C1_EV_IRQHandler ; I2C1 Event + DCD I2C1_ER_IRQHandler ; I2C1 Error + DCD I2C2_EV_IRQHandler ; I2C2 Event + DCD I2C2_ER_IRQHandler ; I2C2 Error + DCD SPI1_IRQHandler ; SPI1 + DCD SPI2_IRQHandler ; SPI2 + DCD USART1_IRQHandler ; USART1 + DCD USART2_IRQHandler ; USART2 + DCD USART3_IRQHandler ; USART3 + DCD EINT15_10_IRQHandler ; External Line[15:10]s + DCD RTC_Alarm_IRQHandler ; RTC Alarm (A and B) through EINT Line + DCD OTG_FS_WKUP_IRQHandler ; OTG_FS Wakeup through EINT line + DCD TMR8_BRK_TMR12_IRQHandler ; TMR8 Break and TMR12 + DCD TMR8_UP_TMR13_IRQHandler ; TMR8 Update and TMR13 + DCD TMR8_TRG_COM_TMR14_IRQHandler ; TMR8 Trigger and Commutation and TMR14 + DCD TMR8_CC_IRQHandler ; TMR8 Capture Compare + DCD DMA1_STR7_IRQHandler ; DMA1 Stream 7 + DCD EMMC_IRQHandler ; EMMC + DCD SDIO_IRQHandler ; SDIO + DCD TMR5_IRQHandler ; TMR5 + DCD SPI3_IRQHandler ; SPI3 + DCD UART4_IRQHandler ; UART4 + DCD UART5_IRQHandler ; UART5 + DCD TMR6_DAC_IRQHandler ; TMR6 and DAC1&2 underrun errors + DCD TMR7_IRQHandler ; TMR7 + DCD DMA2_STR0_IRQHandler ; DMA2 Stream 0 + DCD DMA2_STR1_IRQHandler ; DMA2 Stream 1 + DCD DMA2_STR2_IRQHandler ; DMA2 Stream 2 + DCD DMA2_STR3_IRQHandler ; DMA2 Stream 3 + DCD DMA2_STR4_IRQHandler ; DMA2 Stream 4 + DCD ETH_IRQHandler ; Ethernet + DCD ETH_WKUP_IRQHandler ; Ethernet Wakeup through EINT line + DCD CAN2_TX_IRQHandler ; CAN2 TX + DCD CAN2_RX0_IRQHandler ; CAN2 RX0 + DCD CAN2_RX1_IRQHandler ; CAN2 RX1 + DCD CAN2_SCE_IRQHandler ; CAN2 SCE + DCD OTG_FS_IRQHandler ; OTG_FS + DCD DMA2_STR5_IRQHandler ; DMA2 Stream 5 + DCD DMA2_STR6_IRQHandler ; DMA2 Stream 6 + DCD DMA2_STR7_IRQHandler ; DMA2 Stream 7 + DCD USART6_IRQHandler ; USART6 + DCD I2C3_EV_IRQHandler ; I2C3 event + DCD I2C3_ER_IRQHandler ; I2C3 error + DCD OTG_HS1_EP1_OUT_IRQHandler ; OTG_HS1 End Point 1 Out + DCD OTG_HS1_EP1_IN_IRQHandler ; OTG_HS1 End Point 1 In + DCD OTG_HS1_WKUP_IRQHandler ; OTG_HS1 Wakeup through EINT + DCD OTG_HS1_IRQHandler ; OTG_HS1 + DCD DCI_IRQHandler ; DCI + DCD CRYP_IRQHandler ; CRYP crypto + DCD HASH_RNG_IRQHandler ; Hash and Rng + DCD FPU_IRQHandler ; FPU + DCD SM3_IRQHandler ; SM3 + DCD SM4_IRQHandler ; SM4 + DCD BN_IRQHandler ; BN +__Vectors_End + +__Vectors_Size EQU __Vectors_End - __Vectors + + AREA |.text|, CODE, READONLY + +; Reset handler +Reset_Handler PROC + EXPORT Reset_Handler [WEAK] + IMPORT SystemInit + IMPORT __main + LDR R0, =SystemInit + BLX R0 + LDR R0, =__main + BX R0 + ENDP + +; Dummy Exception Handlers (infinite loops which can be modified) + +NMI_Handler PROC + EXPORT NMI_Handler [WEAK] + B . + ENDP +HardFault_Handler\ + PROC + EXPORT HardFault_Handler [WEAK] + B . + ENDP +MemManage_Handler\ + PROC + EXPORT MemManage_Handler [WEAK] + B . + ENDP +BusFault_Handler\ + PROC + EXPORT BusFault_Handler [WEAK] + B . + ENDP +UsageFault_Handler\ + PROC + EXPORT UsageFault_Handler [WEAK] + B . + ENDP +SVC_Handler PROC + EXPORT SVC_Handler [WEAK] + B . + ENDP +DebugMon_Handler\ + PROC + EXPORT DebugMon_Handler [WEAK] + B . + ENDP +PendSV_Handler PROC + EXPORT PendSV_Handler [WEAK] + B . + ENDP +SysTick_Handler PROC + EXPORT SysTick_Handler [WEAK] + B . + ENDP + +Default_Handler PROC + + EXPORT WWDT_IRQHandler [WEAK] + EXPORT PVD_IRQHandler [WEAK] + EXPORT TAMP_STAMP_IRQHandler [WEAK] + EXPORT RTC_WKUP_IRQHandler [WEAK] + EXPORT FLASH_IRQHandler [WEAK] + EXPORT RCM_IRQHandler [WEAK] + EXPORT EINT0_IRQHandler [WEAK] + EXPORT EINT1_IRQHandler [WEAK] + EXPORT EINT2_IRQHandler [WEAK] + EXPORT EINT3_IRQHandler [WEAK] + EXPORT EINT4_IRQHandler [WEAK] + EXPORT DMA1_STR0_IRQHandler [WEAK] + EXPORT DMA1_STR1_IRQHandler [WEAK] + EXPORT DMA1_STR2_IRQHandler [WEAK] + EXPORT DMA1_STR3_IRQHandler [WEAK] + EXPORT DMA1_STR4_IRQHandler [WEAK] + EXPORT DMA1_STR5_IRQHandler [WEAK] + EXPORT DMA1_STR6_IRQHandler [WEAK] + EXPORT ADC_IRQHandler [WEAK] + EXPORT CAN1_TX_IRQHandler [WEAK] + EXPORT CAN1_RX0_IRQHandler [WEAK] + EXPORT CAN1_RX1_IRQHandler [WEAK] + EXPORT CAN1_SCE_IRQHandler [WEAK] + EXPORT EINT9_5_IRQHandler [WEAK] + EXPORT TMR1_BRK_TMR9_IRQHandler [WEAK] + EXPORT TMR1_UP_TMR10_IRQHandler [WEAK] + EXPORT TMR1_TRG_COM_TMR11_IRQHandler [WEAK] + EXPORT TMR1_CC_IRQHandler [WEAK] + EXPORT TMR2_IRQHandler [WEAK] + EXPORT TMR3_IRQHandler [WEAK] + EXPORT TMR4_IRQHandler [WEAK] + EXPORT I2C1_EV_IRQHandler [WEAK] + EXPORT I2C1_ER_IRQHandler [WEAK] + EXPORT I2C2_EV_IRQHandler [WEAK] + EXPORT I2C2_ER_IRQHandler [WEAK] + EXPORT SPI1_IRQHandler [WEAK] + EXPORT SPI2_IRQHandler [WEAK] + EXPORT USART1_IRQHandler [WEAK] + EXPORT USART2_IRQHandler [WEAK] + EXPORT USART3_IRQHandler [WEAK] + EXPORT EINT15_10_IRQHandler [WEAK] + EXPORT RTC_Alarm_IRQHandler [WEAK] + EXPORT OTG_FS_WKUP_IRQHandler [WEAK] + EXPORT TMR8_BRK_TMR12_IRQHandler [WEAK] + EXPORT TMR8_UP_TMR13_IRQHandler [WEAK] + EXPORT TMR8_TRG_COM_TMR14_IRQHandler [WEAK] + EXPORT TMR8_CC_IRQHandler [WEAK] + EXPORT DMA1_STR7_IRQHandler [WEAK] + EXPORT EMMC_IRQHandler [WEAK] + EXPORT SDIO_IRQHandler [WEAK] + EXPORT TMR5_IRQHandler [WEAK] + EXPORT SPI3_IRQHandler [WEAK] + EXPORT UART4_IRQHandler [WEAK] + EXPORT UART5_IRQHandler [WEAK] + EXPORT TMR6_DAC_IRQHandler [WEAK] + EXPORT TMR7_IRQHandler [WEAK] + EXPORT DMA2_STR0_IRQHandler [WEAK] + EXPORT DMA2_STR1_IRQHandler [WEAK] + EXPORT DMA2_STR2_IRQHandler [WEAK] + EXPORT DMA2_STR3_IRQHandler [WEAK] + EXPORT DMA2_STR4_IRQHandler [WEAK] + EXPORT ETH_IRQHandler [WEAK] + EXPORT ETH_WKUP_IRQHandler [WEAK] + EXPORT CAN2_TX_IRQHandler [WEAK] + EXPORT CAN2_RX0_IRQHandler [WEAK] + EXPORT CAN2_RX1_IRQHandler [WEAK] + EXPORT CAN2_SCE_IRQHandler [WEAK] + EXPORT OTG_FS_IRQHandler [WEAK] + EXPORT DMA2_STR5_IRQHandler [WEAK] + EXPORT DMA2_STR6_IRQHandler [WEAK] + EXPORT DMA2_STR7_IRQHandler [WEAK] + EXPORT USART6_IRQHandler [WEAK] + EXPORT I2C3_EV_IRQHandler [WEAK] + EXPORT I2C3_ER_IRQHandler [WEAK] + EXPORT OTG_HS1_EP1_OUT_IRQHandler [WEAK] + EXPORT OTG_HS1_EP1_IN_IRQHandler [WEAK] + EXPORT OTG_HS1_WKUP_IRQHandler [WEAK] + EXPORT OTG_HS1_IRQHandler [WEAK] + EXPORT DCI_IRQHandler [WEAK] + EXPORT CRYP_IRQHandler [WEAK] + EXPORT HASH_RNG_IRQHandler [WEAK] + EXPORT FPU_IRQHandler [WEAK] + EXPORT SM3_IRQHandler [WEAK] + EXPORT SM4_IRQHandler [WEAK] + EXPORT BN_IRQHandler [WEAK] +WWDT_IRQHandler +PVD_IRQHandler +TAMP_STAMP_IRQHandler +RTC_WKUP_IRQHandler +FLASH_IRQHandler +RCM_IRQHandler +EINT0_IRQHandler +EINT1_IRQHandler +EINT2_IRQHandler +EINT3_IRQHandler +EINT4_IRQHandler +DMA1_STR0_IRQHandler +DMA1_STR1_IRQHandler +DMA1_STR2_IRQHandler +DMA1_STR3_IRQHandler +DMA1_STR4_IRQHandler +DMA1_STR5_IRQHandler +DMA1_STR6_IRQHandler +ADC_IRQHandler +CAN1_TX_IRQHandler +CAN1_RX0_IRQHandler +CAN1_RX1_IRQHandler +CAN1_SCE_IRQHandler +EINT9_5_IRQHandler +TMR1_BRK_TMR9_IRQHandler +TMR1_UP_TMR10_IRQHandler +TMR1_TRG_COM_TMR11_IRQHandler +TMR1_CC_IRQHandler +TMR2_IRQHandler +TMR3_IRQHandler +TMR4_IRQHandler +I2C1_EV_IRQHandler +I2C1_ER_IRQHandler +I2C2_EV_IRQHandler +I2C2_ER_IRQHandler +SPI1_IRQHandler +SPI2_IRQHandler +USART1_IRQHandler +USART2_IRQHandler +USART3_IRQHandler +EINT15_10_IRQHandler +RTC_Alarm_IRQHandler +OTG_FS_WKUP_IRQHandler +TMR8_BRK_TMR12_IRQHandler +TMR8_UP_TMR13_IRQHandler +TMR8_TRG_COM_TMR14_IRQHandler +TMR8_CC_IRQHandler +DMA1_STR7_IRQHandler +EMMC_IRQHandler +SDIO_IRQHandler +TMR5_IRQHandler +SPI3_IRQHandler +UART4_IRQHandler +UART5_IRQHandler +TMR6_DAC_IRQHandler +TMR7_IRQHandler +DMA2_STR0_IRQHandler +DMA2_STR1_IRQHandler +DMA2_STR2_IRQHandler +DMA2_STR3_IRQHandler +DMA2_STR4_IRQHandler +ETH_IRQHandler +ETH_WKUP_IRQHandler +CAN2_TX_IRQHandler +CAN2_RX0_IRQHandler +CAN2_RX1_IRQHandler +CAN2_SCE_IRQHandler +OTG_FS_IRQHandler +DMA2_STR5_IRQHandler +DMA2_STR6_IRQHandler +DMA2_STR7_IRQHandler +USART6_IRQHandler +I2C3_EV_IRQHandler +I2C3_ER_IRQHandler +OTG_HS1_EP1_OUT_IRQHandler +OTG_HS1_EP1_IN_IRQHandler +OTG_HS1_WKUP_IRQHandler +OTG_HS1_IRQHandler +DCI_IRQHandler +CRYP_IRQHandler +HASH_RNG_IRQHandler +FPU_IRQHandler +SM3_IRQHandler +SM4_IRQHandler +BN_IRQHandler + + B . + + ENDP + + ALIGN + +;******************************************************************************* +; User Stack and Heap initialization +;******************************************************************************* + IF :DEF:__MICROLIB + + EXPORT __initial_sp + EXPORT __heap_base + EXPORT __heap_limit + + ELSE + + IMPORT __use_two_region_memory + EXPORT __user_initial_stackheap + +__user_initial_stackheap + + LDR R0, = Heap_Mem + LDR R1, =(Stack_Mem + Stack_Size) + LDR R2, = (Heap_Mem + Heap_Size) + LDR R3, = Stack_Mem + BX LR + + ALIGN + + ENDIF + + END + +;************************ (C) COPYRIGHT Geehy Semiconductor Co.,Ltd *****END OF FILE***** diff --git a/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/arm/startup_apm32f465xx.s b/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/arm/startup_apm32f465xx.s new file mode 100644 index 0000000000..365f4cf9f1 --- /dev/null +++ b/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/arm/startup_apm32f465xx.s @@ -0,0 +1,421 @@ +;/** +; * @file startup_apm32f465xx.s +; * +; * @brief CMSIS Cortex-M4 based Core Device Startup File for Device startup_apm32f465xx +; * +; * @version V1.0.0 +; * +; * @date 2023-12-01 +; * +; * @attention +; * +; * Copyright (C) 2023 Geehy Semiconductor +; * +; * You may not use this file except in compliance with the +; * GEEHY COPYRIGHT NOTICE (GEEHY SOFTWARE PACKAGE LICENSE). +; * +; * The program is only for reference, which is distributed in the hope +; * that it will be useful and instructional for customers to develop +; * their software. Unless required by applicable law or agreed to in +; * writing, the program is distributed on an "AS IS" BASIS, WITHOUT +; * ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied. +; * See the GEEHY SOFTWARE PACKAGE LICENSE for the governing permissions +; * and limitations under the License. +; */ + +; <<< Use Configuration Wizard in Context Menu >>> +; Stack Configuration +; Stack Size (in Bytes) <0x0-0xFFFFFFFF:8> +; + +Stack_Size EQU 0x00000400 + + AREA STACK, NOINIT, READWRITE, ALIGN=3 +Stack_Mem SPACE Stack_Size +__initial_sp + +; Heap Configuration +; Heap Size (in Bytes) <0x0-0xFFFFFFFF:8> +; + +Heap_Size EQU 0x00000200 + + AREA HEAP, NOINIT, READWRITE, ALIGN=3 +__heap_base +Heap_Mem SPACE Heap_Size +__heap_limit + + PRESERVE8 + THUMB + +; Vector Table Mapped to Address 0 at Reset + AREA RESET, DATA, READONLY + EXPORT __Vectors + EXPORT __Vectors_End + EXPORT __Vectors_Size + +__Vectors DCD __initial_sp ; Top of Stack + DCD Reset_Handler ; Reset Handler + DCD NMI_Handler ; NMI Handler + DCD HardFault_Handler ; Hard Fault Handler + DCD MemManage_Handler ; MPU Fault Handler + DCD BusFault_Handler ; Bus Fault Handler + DCD UsageFault_Handler ; Usage Fault Handler + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD SVC_Handler ; SVCall Handler + DCD DebugMon_Handler ; Debug Monitor Handler + DCD 0 ; Reserved + DCD PendSV_Handler ; PendSV Handler + DCD SysTick_Handler ; SysTick Handler + + ; External Interrupts + DCD WWDT_IRQHandler ; Window WatchDog + DCD PVD_IRQHandler ; PVD through EINT Line detection + DCD TAMP_STAMP_IRQHandler ; Tamper and TimeStamps through the EINT line + DCD RTC_WKUP_IRQHandler ; RTC Wakeup through the EINT line + DCD FLASH_IRQHandler ; FLASH + DCD RCM_IRQHandler ; RCM + DCD EINT0_IRQHandler ; EINT Line0 + DCD EINT1_IRQHandler ; EINT Line1 + DCD EINT2_IRQHandler ; EINT Line2 + DCD EINT3_IRQHandler ; EINT Line3 + DCD EINT4_IRQHandler ; EINT Line4 + DCD DMA1_STR0_IRQHandler ; DMA1 Stream 0 + DCD DMA1_STR1_IRQHandler ; DMA1 Stream 1 + DCD DMA1_STR2_IRQHandler ; DMA1 Stream 2 + DCD DMA1_STR3_IRQHandler ; DMA1 Stream 3 + DCD DMA1_STR4_IRQHandler ; DMA1 Stream 4 + DCD DMA1_STR5_IRQHandler ; DMA1 Stream 5 + DCD DMA1_STR6_IRQHandler ; DMA1 Stream 6 + DCD ADC_IRQHandler ; ADC1, ADC2 and ADC3s + DCD CAN1_TX_IRQHandler ; CAN1 TX + DCD CAN1_RX0_IRQHandler ; CAN1 RX0 + DCD CAN1_RX1_IRQHandler ; CAN1 RX1 + DCD CAN1_SCE_IRQHandler ; CAN1 SCE + DCD EINT9_5_IRQHandler ; External Line[9:5]s + DCD TMR1_BRK_TMR9_IRQHandler ; TMR1 Break and TMR9 + DCD TMR1_UP_TMR10_IRQHandler ; TMR1 Update and TMR10 + DCD TMR1_TRG_COM_TMR11_IRQHandler ; TMR1 Trigger and Commutation and TMR11 + DCD TMR1_CC_IRQHandler ; TMR1 Capture Compare + DCD TMR2_IRQHandler ; TMR2 + DCD TMR3_IRQHandler ; TMR3 + DCD TMR4_IRQHandler ; TMR4 + DCD I2C1_EV_IRQHandler ; I2C1 Event + DCD I2C1_ER_IRQHandler ; I2C1 Error + DCD I2C2_EV_IRQHandler ; I2C2 Event + DCD I2C2_ER_IRQHandler ; I2C2 Error + DCD SPI1_IRQHandler ; SPI1 + DCD SPI2_IRQHandler ; SPI2 + DCD USART1_IRQHandler ; USART1 + DCD USART2_IRQHandler ; USART2 + DCD USART3_IRQHandler ; USART3 + DCD EINT15_10_IRQHandler ; External Line[15:10]s + DCD RTC_Alarm_IRQHandler ; RTC Alarm (A and B) through EINT Line + DCD OTG_FS_WKUP_IRQHandler ; OTG_FS Wakeup through EINT line + DCD TMR8_BRK_TMR12_IRQHandler ; TMR8 Break and TMR12 + DCD TMR8_UP_TMR13_IRQHandler ; TMR8 Update and TMR13 + DCD TMR8_TRG_COM_TMR14_IRQHandler ; TMR8 Trigger and Commutation and TMR14 + DCD TMR8_CC_IRQHandler ; TMR8 Capture Compare + DCD DMA1_STR7_IRQHandler ; DMA1 Stream 7 + DCD SMC_IRQHandler ; SMC + DCD SDIO_IRQHandler ; SDIO + DCD TMR5_IRQHandler ; TMR5 + DCD SPI3_IRQHandler ; SPI3 + DCD UART4_IRQHandler ; UART4 + DCD UART5_IRQHandler ; UART5 + DCD TMR6_DAC_IRQHandler ; TMR6 and DAC1&2 underrun errors + DCD TMR7_IRQHandler ; TMR7 + DCD DMA2_STR0_IRQHandler ; DMA2 Stream 0 + DCD DMA2_STR1_IRQHandler ; DMA2 Stream 1 + DCD DMA2_STR2_IRQHandler ; DMA2 Stream 2 + DCD DMA2_STR3_IRQHandler ; DMA2 Stream 3 + DCD DMA2_STR4_IRQHandler ; DMA2 Stream 4 + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD CAN2_TX_IRQHandler ; CAN2 TX + DCD CAN2_RX0_IRQHandler ; CAN2 RX0 + DCD CAN2_RX1_IRQHandler ; CAN2 RX1 + DCD CAN2_SCE_IRQHandler ; CAN2 SCE + DCD OTG_FS_IRQHandler ; OTG_FS + DCD DMA2_STR5_IRQHandler ; DMA2 Stream 5 + DCD DMA2_STR6_IRQHandler ; DMA2 Stream 6 + DCD DMA2_STR7_IRQHandler ; DMA2 Stream 7 + DCD USART6_IRQHandler ; USART6 + DCD I2C3_EV_IRQHandler ; I2C3 event + DCD I2C3_ER_IRQHandler ; I2C3 error + DCD OTG_HS1_EP1_OUT_IRQHandler ; OTG_HS1 End Point 1 Out + DCD OTG_HS1_EP1_IN_IRQHandler ; OTG_HS1 End Point 1 In + DCD OTG_HS1_WKUP_IRQHandler ; OTG_HS1 Wakeup through EINT + DCD OTG_HS1_IRQHandler ; OTG_HS1 + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD RNG_IRQHandler ; RNG + DCD FPU_IRQHandler ; FPU + DCD SM3_IRQHandler ; SM3 + DCD SM4_IRQHandler ; SM4 + DCD BN_IRQHandler ; BN +__Vectors_End + +__Vectors_Size EQU __Vectors_End - __Vectors + + AREA |.text|, CODE, READONLY + +; Reset handler +Reset_Handler PROC + EXPORT Reset_Handler [WEAK] + IMPORT SystemInit + IMPORT __main + LDR R0, =SystemInit + BLX R0 + LDR R0, =__main + BX R0 + ENDP + +; Dummy Exception Handlers (infinite loops which can be modified) + +NMI_Handler PROC + EXPORT NMI_Handler [WEAK] + B . + ENDP +HardFault_Handler\ + PROC + EXPORT HardFault_Handler [WEAK] + B . + ENDP +MemManage_Handler\ + PROC + EXPORT MemManage_Handler [WEAK] + B . + ENDP +BusFault_Handler\ + PROC + EXPORT BusFault_Handler [WEAK] + B . + ENDP +UsageFault_Handler\ + PROC + EXPORT UsageFault_Handler [WEAK] + B . + ENDP +SVC_Handler PROC + EXPORT SVC_Handler [WEAK] + B . + ENDP +DebugMon_Handler\ + PROC + EXPORT DebugMon_Handler [WEAK] + B . + ENDP +PendSV_Handler PROC + EXPORT PendSV_Handler [WEAK] + B . + ENDP +SysTick_Handler PROC + EXPORT SysTick_Handler [WEAK] + B . + ENDP + +Default_Handler PROC + + EXPORT WWDT_IRQHandler [WEAK] + EXPORT PVD_IRQHandler [WEAK] + EXPORT TAMP_STAMP_IRQHandler [WEAK] + EXPORT RTC_WKUP_IRQHandler [WEAK] + EXPORT FLASH_IRQHandler [WEAK] + EXPORT RCM_IRQHandler [WEAK] + EXPORT EINT0_IRQHandler [WEAK] + EXPORT EINT1_IRQHandler [WEAK] + EXPORT EINT2_IRQHandler [WEAK] + EXPORT EINT3_IRQHandler [WEAK] + EXPORT EINT4_IRQHandler [WEAK] + EXPORT DMA1_STR0_IRQHandler [WEAK] + EXPORT DMA1_STR1_IRQHandler [WEAK] + EXPORT DMA1_STR2_IRQHandler [WEAK] + EXPORT DMA1_STR3_IRQHandler [WEAK] + EXPORT DMA1_STR4_IRQHandler [WEAK] + EXPORT DMA1_STR5_IRQHandler [WEAK] + EXPORT DMA1_STR6_IRQHandler [WEAK] + EXPORT ADC_IRQHandler [WEAK] + EXPORT CAN1_TX_IRQHandler [WEAK] + EXPORT CAN1_RX0_IRQHandler [WEAK] + EXPORT CAN1_RX1_IRQHandler [WEAK] + EXPORT CAN1_SCE_IRQHandler [WEAK] + EXPORT EINT9_5_IRQHandler [WEAK] + EXPORT TMR1_BRK_TMR9_IRQHandler [WEAK] + EXPORT TMR1_UP_TMR10_IRQHandler [WEAK] + EXPORT TMR1_TRG_COM_TMR11_IRQHandler [WEAK] + EXPORT TMR1_CC_IRQHandler [WEAK] + EXPORT TMR2_IRQHandler [WEAK] + EXPORT TMR3_IRQHandler [WEAK] + EXPORT TMR4_IRQHandler [WEAK] + EXPORT I2C1_EV_IRQHandler [WEAK] + EXPORT I2C1_ER_IRQHandler [WEAK] + EXPORT I2C2_EV_IRQHandler [WEAK] + EXPORT I2C2_ER_IRQHandler [WEAK] + EXPORT SPI1_IRQHandler [WEAK] + EXPORT SPI2_IRQHandler [WEAK] + EXPORT USART1_IRQHandler [WEAK] + EXPORT USART2_IRQHandler [WEAK] + EXPORT USART3_IRQHandler [WEAK] + EXPORT EINT15_10_IRQHandler [WEAK] + EXPORT RTC_Alarm_IRQHandler [WEAK] + EXPORT OTG_FS_WKUP_IRQHandler [WEAK] + EXPORT TMR8_BRK_TMR12_IRQHandler [WEAK] + EXPORT TMR8_UP_TMR13_IRQHandler [WEAK] + EXPORT TMR8_TRG_COM_TMR14_IRQHandler [WEAK] + EXPORT TMR8_CC_IRQHandler [WEAK] + EXPORT DMA1_STR7_IRQHandler [WEAK] + EXPORT SMC_IRQHandler [WEAK] + EXPORT SDIO_IRQHandler [WEAK] + EXPORT TMR5_IRQHandler [WEAK] + EXPORT SPI3_IRQHandler [WEAK] + EXPORT UART4_IRQHandler [WEAK] + EXPORT UART5_IRQHandler [WEAK] + EXPORT TMR6_DAC_IRQHandler [WEAK] + EXPORT TMR7_IRQHandler [WEAK] + EXPORT DMA2_STR0_IRQHandler [WEAK] + EXPORT DMA2_STR1_IRQHandler [WEAK] + EXPORT DMA2_STR2_IRQHandler [WEAK] + EXPORT DMA2_STR3_IRQHandler [WEAK] + EXPORT DMA2_STR4_IRQHandler [WEAK] + EXPORT CAN2_TX_IRQHandler [WEAK] + EXPORT CAN2_RX0_IRQHandler [WEAK] + EXPORT CAN2_RX1_IRQHandler [WEAK] + EXPORT CAN2_SCE_IRQHandler [WEAK] + EXPORT OTG_FS_IRQHandler [WEAK] + EXPORT DMA2_STR5_IRQHandler [WEAK] + EXPORT DMA2_STR6_IRQHandler [WEAK] + EXPORT DMA2_STR7_IRQHandler [WEAK] + EXPORT USART6_IRQHandler [WEAK] + EXPORT I2C3_EV_IRQHandler [WEAK] + EXPORT I2C3_ER_IRQHandler [WEAK] + EXPORT OTG_HS1_EP1_OUT_IRQHandler [WEAK] + EXPORT OTG_HS1_EP1_IN_IRQHandler [WEAK] + EXPORT OTG_HS1_WKUP_IRQHandler [WEAK] + EXPORT OTG_HS1_IRQHandler [WEAK] + EXPORT RNG_IRQHandler [WEAK] + EXPORT FPU_IRQHandler [WEAK] + EXPORT SM3_IRQHandler [WEAK] + EXPORT SM4_IRQHandler [WEAK] + EXPORT BN_IRQHandler [WEAK] + +WWDT_IRQHandler +PVD_IRQHandler +TAMP_STAMP_IRQHandler +RTC_WKUP_IRQHandler +FLASH_IRQHandler +RCM_IRQHandler +EINT0_IRQHandler +EINT1_IRQHandler +EINT2_IRQHandler +EINT3_IRQHandler +EINT4_IRQHandler +DMA1_STR0_IRQHandler +DMA1_STR1_IRQHandler +DMA1_STR2_IRQHandler +DMA1_STR3_IRQHandler +DMA1_STR4_IRQHandler +DMA1_STR5_IRQHandler +DMA1_STR6_IRQHandler +ADC_IRQHandler +CAN1_TX_IRQHandler +CAN1_RX0_IRQHandler +CAN1_RX1_IRQHandler +CAN1_SCE_IRQHandler +EINT9_5_IRQHandler +TMR1_BRK_TMR9_IRQHandler +TMR1_UP_TMR10_IRQHandler +TMR1_TRG_COM_TMR11_IRQHandler +TMR1_CC_IRQHandler +TMR2_IRQHandler +TMR3_IRQHandler +TMR4_IRQHandler +I2C1_EV_IRQHandler +I2C1_ER_IRQHandler +I2C2_EV_IRQHandler +I2C2_ER_IRQHandler +SPI1_IRQHandler +SPI2_IRQHandler +USART1_IRQHandler +USART2_IRQHandler +USART3_IRQHandler +EINT15_10_IRQHandler +RTC_Alarm_IRQHandler +OTG_FS_WKUP_IRQHandler +TMR8_BRK_TMR12_IRQHandler +TMR8_UP_TMR13_IRQHandler +TMR8_TRG_COM_TMR14_IRQHandler +TMR8_CC_IRQHandler +DMA1_STR7_IRQHandler +SMC_IRQHandler +SDIO_IRQHandler +TMR5_IRQHandler +SPI3_IRQHandler +UART4_IRQHandler +UART5_IRQHandler +TMR6_DAC_IRQHandler +TMR7_IRQHandler +DMA2_STR0_IRQHandler +DMA2_STR1_IRQHandler +DMA2_STR2_IRQHandler +DMA2_STR3_IRQHandler +DMA2_STR4_IRQHandler +CAN2_TX_IRQHandler +CAN2_RX0_IRQHandler +CAN2_RX1_IRQHandler +CAN2_SCE_IRQHandler +OTG_FS_IRQHandler +DMA2_STR5_IRQHandler +DMA2_STR6_IRQHandler +DMA2_STR7_IRQHandler +USART6_IRQHandler +I2C3_EV_IRQHandler +I2C3_ER_IRQHandler +OTG_HS1_EP1_OUT_IRQHandler +OTG_HS1_EP1_IN_IRQHandler +OTG_HS1_WKUP_IRQHandler +OTG_HS1_IRQHandler +RNG_IRQHandler +FPU_IRQHandler +SM3_IRQHandler +SM4_IRQHandler +BN_IRQHandler + + B . + + ENDP + + ALIGN + +;******************************************************************************* +; User Stack and Heap initialization +;******************************************************************************* + IF :DEF:__MICROLIB + + EXPORT __initial_sp + EXPORT __heap_base + EXPORT __heap_limit + + ELSE + + IMPORT __use_two_region_memory + EXPORT __user_initial_stackheap + +__user_initial_stackheap + + LDR R0, = Heap_Mem + LDR R1, =(Stack_Mem + Stack_Size) + LDR R2, = (Heap_Mem + Heap_Size) + LDR R3, = Stack_Mem + BX LR + + ALIGN + + ENDIF + + END + +;************************ (C) COPYRIGHT Geehy Semiconductor Co.,Ltd *****END OF FILE***** diff --git a/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/gcc/apm32f405xe_flash.ld b/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/gcc/apm32f405xe_flash.ld new file mode 100644 index 0000000000..06892010dd --- /dev/null +++ b/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/gcc/apm32f405xe_flash.ld @@ -0,0 +1,183 @@ +/** + * @file apm32f405xe_flash.ld + * + * @brief Linker script for APM32F4xxxE series + * 512Kbytes FLASH, 128KByte RAM, 64KByte CCMRAM + * + * @version V1.0.0 + * + * @date 2023-07-31 + * + * @attention + * + * Copyright (C) 2023 Geehy Semiconductor + * + * You may not use this file except in compliance with the + * GEEHY COPYRIGHT NOTICE (GEEHY SOFTWARE PACKAGE LICENSE). + * + * The program is only for reference, which is distributed in the hope + * that it will be useful and instructional for customers to develop + * their software. Unless required by applicable law or agreed to in + * writing, the program is distributed on an "AS IS" BASIS, WITHOUT + * ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied. + * See the GEEHY SOFTWARE PACKAGE LICENSE for the governing permissions + * and limitations under the License. + */ + +/* Entry Point */ +ENTRY(Reset_Handler) + +/* Flash Configuration*/ +/* Flash Base Address */ +_rom_base = 0x8000000; +/*Flash Size (in Bytes) */ +_rom_size = 0x0080000; + +/* Embedded RAM Configuration */ +/* RAM Base Address */ +_ram_base = 0x20000000; +/* RAM Size (in Bytes) */ +_ram_size = 0x00020000; + +/* CCMRAM Base Address */ +_ccmram_base = 0x10000000; +/* CCMRAM Size (in Bytes) */ +_ccmram_size = 0x00010000; + +/* Stack / Heap Configuration */ +_end_stack = 0x20020000; +/* Heap Size (in Bytes) */ +_heap_size = 0x200; +/* Stack Size (in Bytes) */ +_stack_size = 0x400; + +MEMORY +{ +FLASH (rx) : ORIGIN = _rom_base, LENGTH = _rom_size +RAM (xrw) : ORIGIN = _ram_base, LENGTH = _ram_size +CCMRAM (xrw) : ORIGIN = _ccmram_base, LENGTH = _ccmram_size +} + +SECTIONS +{ + .apm32_isr_vector : + { + . = ALIGN(4); + KEEP(*(.apm32_isr_vector)) + . = ALIGN(4); + } >FLASH + + .text : + { + . = ALIGN(4); + *(.text) + *(.text*) + *(.glue_7) + *(.glue_7t) + *(.eh_frame) + + KEEP (*(.init)) + KEEP (*(.fini)) + + . = ALIGN(4); + _etext = .; + } >FLASH + + .rodata : + { + . = ALIGN(4); + *(.rodata) + *(.rodata*) + . = ALIGN(4); + } >FLASH + + .ARM.extab : { *(.ARM.extab* .gnu.linkonce.armextab.*) } >FLASH + .ARM : { + __exidx_start = .; + *(.ARM.exidx*) + __exidx_end = .; + } >FLASH + + .preinit_array : + { + PROVIDE_HIDDEN (__preinit_array_start = .); + KEEP (*(.preinit_array*)) + PROVIDE_HIDDEN (__preinit_array_end = .); + } >FLASH + .init_array : + { + PROVIDE_HIDDEN (__init_array_start = .); + KEEP (*(SORT(.init_array.*))) + KEEP (*(.init_array*)) + PROVIDE_HIDDEN (__init_array_end = .); + } >FLASH + .fini_array : + { + PROVIDE_HIDDEN (__fini_array_start = .); + KEEP (*(SORT(.fini_array.*))) + KEEP (*(.fini_array*)) + PROVIDE_HIDDEN (__fini_array_end = .); + } >FLASH + + _start_address_init_data = LOADADDR(.data); + + .data : + { + . = ALIGN(4); + _start_address_data = .; + *(.data) + *(.data*) + + . = ALIGN(4); + _end_address_data = .; + } >RAM AT> FLASH + + _siccmram = LOADADDR(.ccmram); + + .ccmram : + { + . = ALIGN(4); + _sccmram = .; + *(.ccmram) + *(.ccmram*) + + . = ALIGN(4); + _eccmram = .; + } >CCMRAM AT> FLASH + + . = ALIGN(4); + .bss : + { + + _start_address_bss = .; + __bss_start__ = _start_address_bss; + *(.bss) + *(.bss*) + *(COMMON) + + . = ALIGN(4); + _end_address_bss = .; + __bss_end__ = _end_address_bss; + } >RAM + + ._user_heap_stack : + { + . = ALIGN(8); + PROVIDE ( end = . ); + PROVIDE ( _end = . ); + . = . + _heap_size; + . = . + _stack_size; + . = ALIGN(8); + } >RAM + + /DISCARD/ : + { + libc.a ( * ) + libm.a ( * ) + libgcc.a ( * ) + } + + .ARM.attributes 0 : { *(.ARM.attributes) } +} + + diff --git a/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/gcc/apm32f405xg_flash.ld b/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/gcc/apm32f405xg_flash.ld new file mode 100644 index 0000000000..83229d7cc6 --- /dev/null +++ b/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/gcc/apm32f405xg_flash.ld @@ -0,0 +1,183 @@ +/** + * @file apm32f405xg_flash.ld + * + * @brief Linker script for APM32F4xxxG series + * 1024Kbytes FLASH, 128KByte RAM, 64KByte CCMRAM + * + * @version V1.0.0 + * + * @date 2023-07-31 + * + * @attention + * + * Copyright (C) 2023 Geehy Semiconductor + * + * You may not use this file except in compliance with the + * GEEHY COPYRIGHT NOTICE (GEEHY SOFTWARE PACKAGE LICENSE). + * + * The program is only for reference, which is distributed in the hope + * that it will be useful and instructional for customers to develop + * their software. Unless required by applicable law or agreed to in + * writing, the program is distributed on an "AS IS" BASIS, WITHOUT + * ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied. + * See the GEEHY SOFTWARE PACKAGE LICENSE for the governing permissions + * and limitations under the License. + */ + +/* Entry Point */ +ENTRY(Reset_Handler) + +/* Flash Configuration*/ +/* Flash Base Address */ +_rom_base = 0x8000000; +/*Flash Size (in Bytes) */ +_rom_size = 0x0100000; + +/* Embedded RAM Configuration */ +/* RAM Base Address */ +_ram_base = 0x20000000; +/* RAM Size (in Bytes) */ +_ram_size = 0x00020000; + +/* CCMRAM Base Address */ +_ccmram_base = 0x10000000; +/* CCMRAM Size (in Bytes) */ +_ccmram_size = 0x00010000; + +/* Stack / Heap Configuration */ +_end_stack = 0x20020000; +/* Heap Size (in Bytes) */ +_heap_size = 0x200; +/* Stack Size (in Bytes) */ +_stack_size = 0x400; + +MEMORY +{ +FLASH (rx) : ORIGIN = _rom_base, LENGTH = _rom_size +RAM (xrw) : ORIGIN = _ram_base, LENGTH = _ram_size +CCMRAM (xrw) : ORIGIN = _ccmram_base, LENGTH = _ccmram_size +} + +SECTIONS +{ + .apm32_isr_vector : + { + . = ALIGN(4); + KEEP(*(.apm32_isr_vector)) + . = ALIGN(4); + } >FLASH + + .text : + { + . = ALIGN(4); + *(.text) + *(.text*) + *(.glue_7) + *(.glue_7t) + *(.eh_frame) + + KEEP (*(.init)) + KEEP (*(.fini)) + + . = ALIGN(4); + _etext = .; + } >FLASH + + .rodata : + { + . = ALIGN(4); + *(.rodata) + *(.rodata*) + . = ALIGN(4); + } >FLASH + + .ARM.extab : { *(.ARM.extab* .gnu.linkonce.armextab.*) } >FLASH + .ARM : { + __exidx_start = .; + *(.ARM.exidx*) + __exidx_end = .; + } >FLASH + + .preinit_array : + { + PROVIDE_HIDDEN (__preinit_array_start = .); + KEEP (*(.preinit_array*)) + PROVIDE_HIDDEN (__preinit_array_end = .); + } >FLASH + .init_array : + { + PROVIDE_HIDDEN (__init_array_start = .); + KEEP (*(SORT(.init_array.*))) + KEEP (*(.init_array*)) + PROVIDE_HIDDEN (__init_array_end = .); + } >FLASH + .fini_array : + { + PROVIDE_HIDDEN (__fini_array_start = .); + KEEP (*(SORT(.fini_array.*))) + KEEP (*(.fini_array*)) + PROVIDE_HIDDEN (__fini_array_end = .); + } >FLASH + + _start_address_init_data = LOADADDR(.data); + + .data : + { + . = ALIGN(4); + _start_address_data = .; + *(.data) + *(.data*) + + . = ALIGN(4); + _end_address_data = .; + } >RAM AT> FLASH + + _siccmram = LOADADDR(.ccmram); + + .ccmram : + { + . = ALIGN(4); + _sccmram = .; + *(.ccmram) + *(.ccmram*) + + . = ALIGN(4); + _eccmram = .; + } >CCMRAM AT> FLASH + + . = ALIGN(4); + .bss : + { + + _start_address_bss = .; + __bss_start__ = _start_address_bss; + *(.bss) + *(.bss*) + *(COMMON) + + . = ALIGN(4); + _end_address_bss = .; + __bss_end__ = _end_address_bss; + } >RAM + + ._user_heap_stack : + { + . = ALIGN(8); + PROVIDE ( end = . ); + PROVIDE ( _end = . ); + . = . + _heap_size; + . = . + _stack_size; + . = ALIGN(8); + } >RAM + + /DISCARD/ : + { + libc.a ( * ) + libm.a ( * ) + libgcc.a ( * ) + } + + .ARM.attributes 0 : { *(.ARM.attributes) } +} + + diff --git a/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/gcc/apm32f407xe_flash.ld b/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/gcc/apm32f407xe_flash.ld new file mode 100644 index 0000000000..d8e3053840 --- /dev/null +++ b/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/gcc/apm32f407xe_flash.ld @@ -0,0 +1,183 @@ +/** + * @file apm32f407xe_flash.ld + * + * @brief Linker script for APM32F4xxxE series + * 512Kbytes FLASH, 128KByte RAM, 64KByte CCMRAM + * + * @version V1.0.0 + * + * @date 2023-07-31 + * + * @attention + * + * Copyright (C) 2023 Geehy Semiconductor + * + * You may not use this file except in compliance with the + * GEEHY COPYRIGHT NOTICE (GEEHY SOFTWARE PACKAGE LICENSE). + * + * The program is only for reference, which is distributed in the hope + * that it will be useful and instructional for customers to develop + * their software. Unless required by applicable law or agreed to in + * writing, the program is distributed on an "AS IS" BASIS, WITHOUT + * ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied. + * See the GEEHY SOFTWARE PACKAGE LICENSE for the governing permissions + * and limitations under the License. + */ + +/* Entry Point */ +ENTRY(Reset_Handler) + +/* Flash Configuration*/ +/* Flash Base Address */ +_rom_base = 0x8000000; +/*Flash Size (in Bytes) */ +_rom_size = 0x0080000; + +/* Embedded RAM Configuration */ +/* RAM Base Address */ +_ram_base = 0x20000000; +/* RAM Size (in Bytes) */ +_ram_size = 0x00020000; + +/* CCMRAM Base Address */ +_ccmram_base = 0x10000000; +/* CCMRAM Size (in Bytes) */ +_ccmram_size = 0x00010000; + +/* Stack / Heap Configuration */ +_end_stack = 0x20020000; +/* Heap Size (in Bytes) */ +_heap_size = 0x200; +/* Stack Size (in Bytes) */ +_stack_size = 0x400; + +MEMORY +{ +FLASH (rx) : ORIGIN = _rom_base, LENGTH = _rom_size +RAM (xrw) : ORIGIN = _ram_base, LENGTH = _ram_size +CCMRAM (xrw) : ORIGIN = _ccmram_base, LENGTH = _ccmram_size +} + +SECTIONS +{ + .apm32_isr_vector : + { + . = ALIGN(4); + KEEP(*(.apm32_isr_vector)) + . = ALIGN(4); + } >FLASH + + .text : + { + . = ALIGN(4); + *(.text) + *(.text*) + *(.glue_7) + *(.glue_7t) + *(.eh_frame) + + KEEP (*(.init)) + KEEP (*(.fini)) + + . = ALIGN(4); + _etext = .; + } >FLASH + + .rodata : + { + . = ALIGN(4); + *(.rodata) + *(.rodata*) + . = ALIGN(4); + } >FLASH + + .ARM.extab : { *(.ARM.extab* .gnu.linkonce.armextab.*) } >FLASH + .ARM : { + __exidx_start = .; + *(.ARM.exidx*) + __exidx_end = .; + } >FLASH + + .preinit_array : + { + PROVIDE_HIDDEN (__preinit_array_start = .); + KEEP (*(.preinit_array*)) + PROVIDE_HIDDEN (__preinit_array_end = .); + } >FLASH + .init_array : + { + PROVIDE_HIDDEN (__init_array_start = .); + KEEP (*(SORT(.init_array.*))) + KEEP (*(.init_array*)) + PROVIDE_HIDDEN (__init_array_end = .); + } >FLASH + .fini_array : + { + PROVIDE_HIDDEN (__fini_array_start = .); + KEEP (*(SORT(.fini_array.*))) + KEEP (*(.fini_array*)) + PROVIDE_HIDDEN (__fini_array_end = .); + } >FLASH + + _start_address_init_data = LOADADDR(.data); + + .data : + { + . = ALIGN(4); + _start_address_data = .; + *(.data) + *(.data*) + + . = ALIGN(4); + _end_address_data = .; + } >RAM AT> FLASH + + _siccmram = LOADADDR(.ccmram); + + .ccmram : + { + . = ALIGN(4); + _sccmram = .; + *(.ccmram) + *(.ccmram*) + + . = ALIGN(4); + _eccmram = .; + } >CCMRAM AT> FLASH + + . = ALIGN(4); + .bss : + { + + _start_address_bss = .; + __bss_start__ = _start_address_bss; + *(.bss) + *(.bss*) + *(COMMON) + + . = ALIGN(4); + _end_address_bss = .; + __bss_end__ = _end_address_bss; + } >RAM + + ._user_heap_stack : + { + . = ALIGN(8); + PROVIDE ( end = . ); + PROVIDE ( _end = . ); + . = . + _heap_size; + . = . + _stack_size; + . = ALIGN(8); + } >RAM + + /DISCARD/ : + { + libc.a ( * ) + libm.a ( * ) + libgcc.a ( * ) + } + + .ARM.attributes 0 : { *(.ARM.attributes) } +} + + diff --git a/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/gcc/apm32f407xg_flash.ld b/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/gcc/apm32f407xg_flash.ld new file mode 100644 index 0000000000..f268897da4 --- /dev/null +++ b/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/gcc/apm32f407xg_flash.ld @@ -0,0 +1,183 @@ +/** + * @file apm32f407xg_flash.ld + * + * @brief Linker script for APM32F4xxxG series + * 1024Kbytes FLASH, 128KByte RAM, 64KByte CCMRAM + * + * @version V1.0.0 + * + * @date 2023-07-31 + * + * @attention + * + * Copyright (C) 2023 Geehy Semiconductor + * + * You may not use this file except in compliance with the + * GEEHY COPYRIGHT NOTICE (GEEHY SOFTWARE PACKAGE LICENSE). + * + * The program is only for reference, which is distributed in the hope + * that it will be useful and instructional for customers to develop + * their software. Unless required by applicable law or agreed to in + * writing, the program is distributed on an "AS IS" BASIS, WITHOUT + * ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied. + * See the GEEHY SOFTWARE PACKAGE LICENSE for the governing permissions + * and limitations under the License. + */ + +/* Entry Point */ +ENTRY(Reset_Handler) + +/* Flash Configuration*/ +/* Flash Base Address */ +_rom_base = 0x8000000; +/*Flash Size (in Bytes) */ +_rom_size = 0x0100000; + +/* Embedded RAM Configuration */ +/* RAM Base Address */ +_ram_base = 0x20000000; +/* RAM Size (in Bytes) */ +_ram_size = 0x00020000; + +/* CCMRAM Base Address */ +_ccmram_base = 0x10000000; +/* CCMRAM Size (in Bytes) */ +_ccmram_size = 0x00010000; + +/* Stack / Heap Configuration */ +_end_stack = 0x20020000; +/* Heap Size (in Bytes) */ +_heap_size = 0x200; +/* Stack Size (in Bytes) */ +_stack_size = 0x400; + +MEMORY +{ +FLASH (rx) : ORIGIN = _rom_base, LENGTH = _rom_size +RAM (xrw) : ORIGIN = _ram_base, LENGTH = _ram_size +CCMRAM (xrw) : ORIGIN = _ccmram_base, LENGTH = _ccmram_size +} + +SECTIONS +{ + .apm32_isr_vector : + { + . = ALIGN(4); + KEEP(*(.apm32_isr_vector)) + . = ALIGN(4); + } >FLASH + + .text : + { + . = ALIGN(4); + *(.text) + *(.text*) + *(.glue_7) + *(.glue_7t) + *(.eh_frame) + + KEEP (*(.init)) + KEEP (*(.fini)) + + . = ALIGN(4); + _etext = .; + } >FLASH + + .rodata : + { + . = ALIGN(4); + *(.rodata) + *(.rodata*) + . = ALIGN(4); + } >FLASH + + .ARM.extab : { *(.ARM.extab* .gnu.linkonce.armextab.*) } >FLASH + .ARM : { + __exidx_start = .; + *(.ARM.exidx*) + __exidx_end = .; + } >FLASH + + .preinit_array : + { + PROVIDE_HIDDEN (__preinit_array_start = .); + KEEP (*(.preinit_array*)) + PROVIDE_HIDDEN (__preinit_array_end = .); + } >FLASH + .init_array : + { + PROVIDE_HIDDEN (__init_array_start = .); + KEEP (*(SORT(.init_array.*))) + KEEP (*(.init_array*)) + PROVIDE_HIDDEN (__init_array_end = .); + } >FLASH + .fini_array : + { + PROVIDE_HIDDEN (__fini_array_start = .); + KEEP (*(SORT(.fini_array.*))) + KEEP (*(.fini_array*)) + PROVIDE_HIDDEN (__fini_array_end = .); + } >FLASH + + _start_address_init_data = LOADADDR(.data); + + .data : + { + . = ALIGN(4); + _start_address_data = .; + *(.data) + *(.data*) + + . = ALIGN(4); + _end_address_data = .; + } >RAM AT> FLASH + + _siccmram = LOADADDR(.ccmram); + + .ccmram : + { + . = ALIGN(4); + _sccmram = .; + *(.ccmram) + *(.ccmram*) + + . = ALIGN(4); + _eccmram = .; + } >CCMRAM AT> FLASH + + . = ALIGN(4); + .bss : + { + + _start_address_bss = .; + __bss_start__ = _start_address_bss; + *(.bss) + *(.bss*) + *(COMMON) + + . = ALIGN(4); + _end_address_bss = .; + __bss_end__ = _end_address_bss; + } >RAM + + ._user_heap_stack : + { + . = ALIGN(8); + PROVIDE ( end = . ); + PROVIDE ( _end = . ); + . = . + _heap_size; + . = . + _stack_size; + . = ALIGN(8); + } >RAM + + /DISCARD/ : + { + libc.a ( * ) + libm.a ( * ) + libgcc.a ( * ) + } + + .ARM.attributes 0 : { *(.ARM.attributes) } +} + + diff --git a/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/gcc/apm32f411xc_flash.ld b/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/gcc/apm32f411xc_flash.ld new file mode 100644 index 0000000000..89590783cb --- /dev/null +++ b/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/gcc/apm32f411xc_flash.ld @@ -0,0 +1,164 @@ +/*! + * @file apm32f411xc_flash.ld + * + * @brief Linker script for APM32F411xC series + * 256Kbytes FLASH, 128KByte RAM + * + * @version V1.0.0 + * + * @date 2023-12-01 + * + * @attention + * + * Copyright (C) 2023 Geehy Semiconductor + * + * You may not use this file except in compliance with the + * GEEHY COPYRIGHT NOTICE (GEEHY SOFTWARE PACKAGE LICENSE). + * + * The program is only for reference, which is distributed in the hope + * that it will be useful and instructional for customers to develop + * their software. Unless required by applicable law or agreed to in + * writing, the program is distributed on an "AS IS" BASIS, WITHOUT + * ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied. + * See the GEEHY SOFTWARE PACKAGE LICENSE for the governing permissions + * and limitations under the License. + */ + +/* Entry Point */ +ENTRY(Reset_Handler) + +/* Flash Configuration*/ +/* Flash Base Address */ +_rom_base = 0x8000000; +/*Flash Size (in Bytes) */ +_rom_size = 0x0040000; + +/* Embedded RAM Configuration */ +/* RAM Base Address */ +_ram_base = 0x20000000; +/* RAM Size (in Bytes) */ +_ram_size = 0x00020000; + +/* Stack / Heap Configuration */ +_end_stack = 0x20020000; +/* Heap Size (in Bytes) */ +_heap_size = 0x200; +/* Stack Size (in Bytes) */ +_stack_size = 0x400; + +MEMORY +{ +FLASH (rx) : ORIGIN = _rom_base, LENGTH = _rom_size +RAM (xrw) : ORIGIN = _ram_base, LENGTH = _ram_size +} + +SECTIONS +{ + .apm32_isr_vector : + { + . = ALIGN(4); + KEEP(*(.apm32_isr_vector)) + . = ALIGN(4); + } >FLASH + + .text : + { + . = ALIGN(4); + *(.text) + *(.text*) + *(.glue_7) + *(.glue_7t) + *(.eh_frame) + + KEEP (*(.init)) + KEEP (*(.fini)) + + . = ALIGN(4); + _etext = .; + } >FLASH + + .rodata : + { + . = ALIGN(4); + *(.rodata) + *(.rodata*) + . = ALIGN(4); + } >FLASH + + .ARM.extab : { *(.ARM.extab* .gnu.linkonce.armextab.*) } >FLASH + .ARM : { + __exidx_start = .; + *(.ARM.exidx*) + __exidx_end = .; + } >FLASH + + .preinit_array : + { + PROVIDE_HIDDEN (__preinit_array_start = .); + KEEP (*(.preinit_array*)) + PROVIDE_HIDDEN (__preinit_array_end = .); + } >FLASH + .init_array : + { + PROVIDE_HIDDEN (__init_array_start = .); + KEEP (*(SORT(.init_array.*))) + KEEP (*(.init_array*)) + PROVIDE_HIDDEN (__init_array_end = .); + } >FLASH + .fini_array : + { + PROVIDE_HIDDEN (__fini_array_start = .); + KEEP (*(SORT(.fini_array.*))) + KEEP (*(.fini_array*)) + PROVIDE_HIDDEN (__fini_array_end = .); + } >FLASH + + _start_address_init_data = LOADADDR(.data); + + .data : + { + . = ALIGN(4); + _start_address_data = .; + *(.data) + *(.data*) + + . = ALIGN(4); + _end_address_data = .; + } >RAM AT> FLASH + + . = ALIGN(4); + .bss : + { + + _start_address_bss = .; + __bss_start__ = _start_address_bss; + *(.bss) + *(.bss*) + *(COMMON) + + . = ALIGN(4); + _end_address_bss = .; + __bss_end__ = _end_address_bss; + } >RAM + + ._user_heap_stack : + { + . = ALIGN(8); + PROVIDE ( end = . ); + PROVIDE ( _end = . ); + . = . + _heap_size; + . = . + _stack_size; + . = ALIGN(8); + } >RAM + + /DISCARD/ : + { + libc.a ( * ) + libm.a ( * ) + libgcc.a ( * ) + } + + .ARM.attributes 0 : { *(.ARM.attributes) } +} + + diff --git a/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/gcc/apm32f411xe_flash.ld b/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/gcc/apm32f411xe_flash.ld new file mode 100644 index 0000000000..e4cfdc6b65 --- /dev/null +++ b/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/gcc/apm32f411xe_flash.ld @@ -0,0 +1,164 @@ +/*! + * @file apm32f411xe_flash.ld + * + * @brief Linker script for APM32F411xE series + * 256Kbytes FLASH, 128KByte RAM + * + * @version V1.0.0 + * + * @date 2023-12-01 + * + * @attention + * + * Copyright (C) 2023 Geehy Semiconductor + * + * You may not use this file except in compliance with the + * GEEHY COPYRIGHT NOTICE (GEEHY SOFTWARE PACKAGE LICENSE). + * + * The program is only for reference, which is distributed in the hope + * that it will be useful and instructional for customers to develop + * their software. Unless required by applicable law or agreed to in + * writing, the program is distributed on an "AS IS" BASIS, WITHOUT + * ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied. + * See the GEEHY SOFTWARE PACKAGE LICENSE for the governing permissions + * and limitations under the License. + */ + +/* Entry Point */ +ENTRY(Reset_Handler) + +/* Flash Configuration*/ +/* Flash Base Address */ +_rom_base = 0x8000000; +/*Flash Size (in Bytes) */ +_rom_size = 0x0080000; + +/* Embedded RAM Configuration */ +/* RAM Base Address */ +_ram_base = 0x20000000; +/* RAM Size (in Bytes) */ +_ram_size = 0x00020000; + +/* Stack / Heap Configuration */ +_end_stack = 0x20020000; +/* Heap Size (in Bytes) */ +_heap_size = 0x200; +/* Stack Size (in Bytes) */ +_stack_size = 0x400; + +MEMORY +{ +FLASH (rx) : ORIGIN = _rom_base, LENGTH = _rom_size +RAM (xrw) : ORIGIN = _ram_base, LENGTH = _ram_size +} + +SECTIONS +{ + .apm32_isr_vector : + { + . = ALIGN(4); + KEEP(*(.apm32_isr_vector)) + . = ALIGN(4); + } >FLASH + + .text : + { + . = ALIGN(4); + *(.text) + *(.text*) + *(.glue_7) + *(.glue_7t) + *(.eh_frame) + + KEEP (*(.init)) + KEEP (*(.fini)) + + . = ALIGN(4); + _etext = .; + } >FLASH + + .rodata : + { + . = ALIGN(4); + *(.rodata) + *(.rodata*) + . = ALIGN(4); + } >FLASH + + .ARM.extab : { *(.ARM.extab* .gnu.linkonce.armextab.*) } >FLASH + .ARM : { + __exidx_start = .; + *(.ARM.exidx*) + __exidx_end = .; + } >FLASH + + .preinit_array : + { + PROVIDE_HIDDEN (__preinit_array_start = .); + KEEP (*(.preinit_array*)) + PROVIDE_HIDDEN (__preinit_array_end = .); + } >FLASH + .init_array : + { + PROVIDE_HIDDEN (__init_array_start = .); + KEEP (*(SORT(.init_array.*))) + KEEP (*(.init_array*)) + PROVIDE_HIDDEN (__init_array_end = .); + } >FLASH + .fini_array : + { + PROVIDE_HIDDEN (__fini_array_start = .); + KEEP (*(SORT(.fini_array.*))) + KEEP (*(.fini_array*)) + PROVIDE_HIDDEN (__fini_array_end = .); + } >FLASH + + _start_address_init_data = LOADADDR(.data); + + .data : + { + . = ALIGN(4); + _start_address_data = .; + *(.data) + *(.data*) + + . = ALIGN(4); + _end_address_data = .; + } >RAM AT> FLASH + + . = ALIGN(4); + .bss : + { + + _start_address_bss = .; + __bss_start__ = _start_address_bss; + *(.bss) + *(.bss*) + *(COMMON) + + . = ALIGN(4); + _end_address_bss = .; + __bss_end__ = _end_address_bss; + } >RAM + + ._user_heap_stack : + { + . = ALIGN(8); + PROVIDE ( end = . ); + PROVIDE ( _end = . ); + . = . + _heap_size; + . = . + _stack_size; + . = ALIGN(8); + } >RAM + + /DISCARD/ : + { + libc.a ( * ) + libm.a ( * ) + libgcc.a ( * ) + } + + .ARM.attributes 0 : { *(.ARM.attributes) } +} + + diff --git a/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/gcc/apm32f417xe_flash.ld b/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/gcc/apm32f417xe_flash.ld new file mode 100644 index 0000000000..30e355b87b --- /dev/null +++ b/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/gcc/apm32f417xe_flash.ld @@ -0,0 +1,183 @@ +/** + * @file apm32f417xe_flash.ld + * + * @brief Linker script for APM32F4xxxE series + * 512Kbytes FLASH, 128KByte RAM, 64KByte CCMRAM + * + * @version V1.0.0 + * + * @date 2023-07-31 + * + * @attention + * + * Copyright (C) 2023 Geehy Semiconductor + * + * You may not use this file except in compliance with the + * GEEHY COPYRIGHT NOTICE (GEEHY SOFTWARE PACKAGE LICENSE). + * + * The program is only for reference, which is distributed in the hope + * that it will be useful and instructional for customers to develop + * their software. Unless required by applicable law or agreed to in + * writing, the program is distributed on an "AS IS" BASIS, WITHOUT + * ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied. + * See the GEEHY SOFTWARE PACKAGE LICENSE for the governing permissions + * and limitations under the License. + */ + +/* Entry Point */ +ENTRY(Reset_Handler) + +/* Flash Configuration*/ +/* Flash Base Address */ +_rom_base = 0x8000000; +/*Flash Size (in Bytes) */ +_rom_size = 0x0080000; + +/* Embedded RAM Configuration */ +/* RAM Base Address */ +_ram_base = 0x20000000; +/* RAM Size (in Bytes) */ +_ram_size = 0x00020000; + +/* CCMRAM Base Address */ +_ccmram_base = 0x10000000; +/* CCMRAM Size (in Bytes) */ +_ccmram_size = 0x00010000; + +/* Stack / Heap Configuration */ +_end_stack = 0x20020000; +/* Heap Size (in Bytes) */ +_heap_size = 0x200; +/* Stack Size (in Bytes) */ +_stack_size = 0x400; + +MEMORY +{ +FLASH (rx) : ORIGIN = _rom_base, LENGTH = _rom_size +RAM (xrw) : ORIGIN = _ram_base, LENGTH = _ram_size +CCMRAM (xrw) : ORIGIN = _ccmram_base, LENGTH = _ccmram_size +} + +SECTIONS +{ + .apm32_isr_vector : + { + . = ALIGN(4); + KEEP(*(.apm32_isr_vector)) + . = ALIGN(4); + } >FLASH + + .text : + { + . = ALIGN(4); + *(.text) + *(.text*) + *(.glue_7) + *(.glue_7t) + *(.eh_frame) + + KEEP (*(.init)) + KEEP (*(.fini)) + + . = ALIGN(4); + _etext = .; + } >FLASH + + .rodata : + { + . = ALIGN(4); + *(.rodata) + *(.rodata*) + . = ALIGN(4); + } >FLASH + + .ARM.extab : { *(.ARM.extab* .gnu.linkonce.armextab.*) } >FLASH + .ARM : { + __exidx_start = .; + *(.ARM.exidx*) + __exidx_end = .; + } >FLASH + + .preinit_array : + { + PROVIDE_HIDDEN (__preinit_array_start = .); + KEEP (*(.preinit_array*)) + PROVIDE_HIDDEN (__preinit_array_end = .); + } >FLASH + .init_array : + { + PROVIDE_HIDDEN (__init_array_start = .); + KEEP (*(SORT(.init_array.*))) + KEEP (*(.init_array*)) + PROVIDE_HIDDEN (__init_array_end = .); + } >FLASH + .fini_array : + { + PROVIDE_HIDDEN (__fini_array_start = .); + KEEP (*(SORT(.fini_array.*))) + KEEP (*(.fini_array*)) + PROVIDE_HIDDEN (__fini_array_end = .); + } >FLASH + + _start_address_init_data = LOADADDR(.data); + + .data : + { + . = ALIGN(4); + _start_address_data = .; + *(.data) + *(.data*) + + . = ALIGN(4); + _end_address_data = .; + } >RAM AT> FLASH + + _siccmram = LOADADDR(.ccmram); + + .ccmram : + { + . = ALIGN(4); + _sccmram = .; + *(.ccmram) + *(.ccmram*) + + . = ALIGN(4); + _eccmram = .; + } >CCMRAM AT> FLASH + + . = ALIGN(4); + .bss : + { + + _start_address_bss = .; + __bss_start__ = _start_address_bss; + *(.bss) + *(.bss*) + *(COMMON) + + . = ALIGN(4); + _end_address_bss = .; + __bss_end__ = _end_address_bss; + } >RAM + + ._user_heap_stack : + { + . = ALIGN(8); + PROVIDE ( end = . ); + PROVIDE ( _end = . ); + . = . + _heap_size; + . = . + _stack_size; + . = ALIGN(8); + } >RAM + + /DISCARD/ : + { + libc.a ( * ) + libm.a ( * ) + libgcc.a ( * ) + } + + .ARM.attributes 0 : { *(.ARM.attributes) } +} + + diff --git a/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/gcc/apm32f417xg_flash.ld b/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/gcc/apm32f417xg_flash.ld new file mode 100644 index 0000000000..68b38e3953 --- /dev/null +++ b/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/gcc/apm32f417xg_flash.ld @@ -0,0 +1,183 @@ +/** + * @file apm32f417xg_flash.ld + * + * @brief Linker script for APM32F4xxxG series + * 1024Kbytes FLASH, 128KByte RAM, 64KByte CCMRAM + * + * @version V1.0.0 + * + * @date 2023-07-31 + * + * @attention + * + * Copyright (C) 2023 Geehy Semiconductor + * + * You may not use this file except in compliance with the + * GEEHY COPYRIGHT NOTICE (GEEHY SOFTWARE PACKAGE LICENSE). + * + * The program is only for reference, which is distributed in the hope + * that it will be useful and instructional for customers to develop + * their software. Unless required by applicable law or agreed to in + * writing, the program is distributed on an "AS IS" BASIS, WITHOUT + * ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied. + * See the GEEHY SOFTWARE PACKAGE LICENSE for the governing permissions + * and limitations under the License. + */ + +/* Entry Point */ +ENTRY(Reset_Handler) + +/* Flash Configuration*/ +/* Flash Base Address */ +_rom_base = 0x8000000; +/*Flash Size (in Bytes) */ +_rom_size = 0x0100000; + +/* Embedded RAM Configuration */ +/* RAM Base Address */ +_ram_base = 0x20000000; +/* RAM Size (in Bytes) */ +_ram_size = 0x00020000; + +/* CCMRAM Base Address */ +_ccmram_base = 0x10000000; +/* CCMRAM Size (in Bytes) */ +_ccmram_size = 0x00010000; + +/* Stack / Heap Configuration */ +_end_stack = 0x20020000; +/* Heap Size (in Bytes) */ +_heap_size = 0x200; +/* Stack Size (in Bytes) */ +_stack_size = 0x400; + +MEMORY +{ +FLASH (rx) : ORIGIN = _rom_base, LENGTH = _rom_size +RAM (xrw) : ORIGIN = _ram_base, LENGTH = _ram_size +CCMRAM (xrw) : ORIGIN = _ccmram_base, LENGTH = _ccmram_size +} + +SECTIONS +{ + .apm32_isr_vector : + { + . = ALIGN(4); + KEEP(*(.apm32_isr_vector)) + . = ALIGN(4); + } >FLASH + + .text : + { + . = ALIGN(4); + *(.text) + *(.text*) + *(.glue_7) + *(.glue_7t) + *(.eh_frame) + + KEEP (*(.init)) + KEEP (*(.fini)) + + . = ALIGN(4); + _etext = .; + } >FLASH + + .rodata : + { + . = ALIGN(4); + *(.rodata) + *(.rodata*) + . = ALIGN(4); + } >FLASH + + .ARM.extab : { *(.ARM.extab* .gnu.linkonce.armextab.*) } >FLASH + .ARM : { + __exidx_start = .; + *(.ARM.exidx*) + __exidx_end = .; + } >FLASH + + .preinit_array : + { + PROVIDE_HIDDEN (__preinit_array_start = .); + KEEP (*(.preinit_array*)) + PROVIDE_HIDDEN (__preinit_array_end = .); + } >FLASH + .init_array : + { + PROVIDE_HIDDEN (__init_array_start = .); + KEEP (*(SORT(.init_array.*))) + KEEP (*(.init_array*)) + PROVIDE_HIDDEN (__init_array_end = .); + } >FLASH + .fini_array : + { + PROVIDE_HIDDEN (__fini_array_start = .); + KEEP (*(SORT(.fini_array.*))) + KEEP (*(.fini_array*)) + PROVIDE_HIDDEN (__fini_array_end = .); + } >FLASH + + _start_address_init_data = LOADADDR(.data); + + .data : + { + . = ALIGN(4); + _start_address_data = .; + *(.data) + *(.data*) + + . = ALIGN(4); + _end_address_data = .; + } >RAM AT> FLASH + + _siccmram = LOADADDR(.ccmram); + + .ccmram : + { + . = ALIGN(4); + _sccmram = .; + *(.ccmram) + *(.ccmram*) + + . = ALIGN(4); + _eccmram = .; + } >CCMRAM AT> FLASH + + . = ALIGN(4); + .bss : + { + + _start_address_bss = .; + __bss_start__ = _start_address_bss; + *(.bss) + *(.bss*) + *(COMMON) + + . = ALIGN(4); + _end_address_bss = .; + __bss_end__ = _end_address_bss; + } >RAM + + ._user_heap_stack : + { + . = ALIGN(8); + PROVIDE ( end = . ); + PROVIDE ( _end = . ); + . = . + _heap_size; + . = . + _stack_size; + . = ALIGN(8); + } >RAM + + /DISCARD/ : + { + libc.a ( * ) + libm.a ( * ) + libgcc.a ( * ) + } + + .ARM.attributes 0 : { *(.ARM.attributes) } +} + + diff --git a/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/gcc/apm32f465xe_flash.ld b/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/gcc/apm32f465xe_flash.ld new file mode 100644 index 0000000000..f705073906 --- /dev/null +++ b/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/gcc/apm32f465xe_flash.ld @@ -0,0 +1,183 @@ +/** + * @file apm32f465xe_flash.ld + * + * @brief Linker script for APM32F465xE series + * 512Kbytes FLASH, 128KByte RAM, 64KByte CCMRAM + * + * @version V1.0.0 + * + * @date 2023-12-01 + * + * @attention + * + * Copyright (C) 2023 Geehy Semiconductor + * + * You may not use this file except in compliance with the + * GEEHY COPYRIGHT NOTICE (GEEHY SOFTWARE PACKAGE LICENSE). + * + * The program is only for reference, which is distributed in the hope + * that it will be useful and instructional for customers to develop + * their software. Unless required by applicable law or agreed to in + * writing, the program is distributed on an "AS IS" BASIS, WITHOUT + * ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied. + * See the GEEHY SOFTWARE PACKAGE LICENSE for the governing permissions + * and limitations under the License. + */ + +/* Entry Point */ +ENTRY(Reset_Handler) + +/* Flash Configuration*/ +/* Flash Base Address */ +_rom_base = 0x8000000; +/*Flash Size (in Bytes) */ +_rom_size = 0x0080000; + +/* Embedded RAM Configuration */ +/* RAM Base Address */ +_ram_base = 0x20000000; +/* RAM Size (in Bytes) */ +_ram_size = 0x00020000; + +/* CCMRAM Base Address */ +_ccmram_base = 0x10000000; +/* CCMRAM Size (in Bytes) */ +_ccmram_size = 0x00010000; + +/* Stack / Heap Configuration */ +_end_stack = 0x20020000; +/* Heap Size (in Bytes) */ +_heap_size = 0x200; +/* Stack Size (in Bytes) */ +_stack_size = 0x400; + +MEMORY +{ +FLASH (rx) : ORIGIN = _rom_base, LENGTH = _rom_size +RAM (xrw) : ORIGIN = _ram_base, LENGTH = _ram_size +CCMRAM (xrw) : ORIGIN = _ccmram_base, LENGTH = _ccmram_size +} + +SECTIONS +{ + .apm32_isr_vector : + { + . = ALIGN(4); + KEEP(*(.apm32_isr_vector)) + . = ALIGN(4); + } >FLASH + + .text : + { + . = ALIGN(4); + *(.text) + *(.text*) + *(.glue_7) + *(.glue_7t) + *(.eh_frame) + + KEEP (*(.init)) + KEEP (*(.fini)) + + . = ALIGN(4); + _etext = .; + } >FLASH + + .rodata : + { + . = ALIGN(4); + *(.rodata) + *(.rodata*) + . = ALIGN(4); + } >FLASH + + .ARM.extab : { *(.ARM.extab* .gnu.linkonce.armextab.*) } >FLASH + .ARM : { + __exidx_start = .; + *(.ARM.exidx*) + __exidx_end = .; + } >FLASH + + .preinit_array : + { + PROVIDE_HIDDEN (__preinit_array_start = .); + KEEP (*(.preinit_array*)) + PROVIDE_HIDDEN (__preinit_array_end = .); + } >FLASH + .init_array : + { + PROVIDE_HIDDEN (__init_array_start = .); + KEEP (*(SORT(.init_array.*))) + KEEP (*(.init_array*)) + PROVIDE_HIDDEN (__init_array_end = .); + } >FLASH + .fini_array : + { + PROVIDE_HIDDEN (__fini_array_start = .); + KEEP (*(SORT(.fini_array.*))) + KEEP (*(.fini_array*)) + PROVIDE_HIDDEN (__fini_array_end = .); + } >FLASH + + _start_address_init_data = LOADADDR(.data); + + .data : + { + . = ALIGN(4); + _start_address_data = .; + *(.data) + *(.data*) + + . = ALIGN(4); + _end_address_data = .; + } >RAM AT> FLASH + + _siccmram = LOADADDR(.ccmram); + + .ccmram : + { + . = ALIGN(4); + _sccmram = .; + *(.ccmram) + *(.ccmram*) + + . = ALIGN(4); + _eccmram = .; + } >CCMRAM AT> FLASH + + . = ALIGN(4); + .bss : + { + + _start_address_bss = .; + __bss_start__ = _start_address_bss; + *(.bss) + *(.bss*) + *(COMMON) + + . = ALIGN(4); + _end_address_bss = .; + __bss_end__ = _end_address_bss; + } >RAM + + ._user_heap_stack : + { + . = ALIGN(8); + PROVIDE ( end = . ); + PROVIDE ( _end = . ); + . = . + _heap_size; + . = . + _stack_size; + . = ALIGN(8); + } >RAM + + /DISCARD/ : + { + libc.a ( * ) + libm.a ( * ) + libgcc.a ( * ) + } + + .ARM.attributes 0 : { *(.ARM.attributes) } +} + + diff --git a/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/gcc/startup_apm32f405xx.S b/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/gcc/startup_apm32f405xx.S new file mode 100644 index 0000000000..d2f1e5b1a1 --- /dev/null +++ b/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/gcc/startup_apm32f405xx.S @@ -0,0 +1,485 @@ +/** + * @file startup_apm32f405xx.S + * + * @brief APM32F405xx Devices vector table for GCC based toolchains. + * This module performs: + * - Set the initial SP + * - Set the initial PC == Reset_Handler, + * - Set the vector table entries with the exceptions ISR address + * - Branches to main in the C library (which eventually + * calls main()). + * After Reset the Cortex-M4 processor is in Thread mode, + * priority is Privileged, and the Stack is set to Main. + * + * @version V1.0.0 + * + * @date 2023-07-31 + * + * @attention + * + * Copyright (C) 2023 Geehy Semiconductor + * + * You may not use this file except in compliance with the + * GEEHY COPYRIGHT NOTICE (GEEHY SOFTWARE PACKAGE LICENSE). + * + * The program is only for reference, which is distributed in the hope + * that it will be useful and instructional for customers to develop + * their software. Unless required by applicable law or agreed to in + * writing, the program is distributed on an "AS IS" BASIS, WITHOUT + * ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied. + * See the GEEHY SOFTWARE PACKAGE LICENSE for the governing permissions + * and limitations under the License. + */ + + .syntax unified + .cpu cortex-m4 + .fpu softvfp + .thumb + +.global g_apm32_Vectors +.global Default_Handler + +/* start address for the initialization values of the .data section. +defined in linker script */ +.word _start_address_init_data +/* start address for the .data section. defined in linker script */ +.word _start_address_data +/* end address for the .data section. defined in linker script */ +.word _end_address_data +/* start address for the .bss section. defined in linker script */ +.word _start_address_bss +/* end address for the .bss section. defined in linker script */ +.word _end_address_bss +/* stack used for SystemInit_ExtMemCtl; always internal RAM used */ + + .section .text.Reset_Handler + .weak Reset_Handler + .type Reset_Handler, %function +// Reset handler routine +Reset_Handler: + ldr sp, =_end_stack + +/* Copy the data segment initializers from flash to SRAM */ + ldr r0, =_start_address_data + ldr r1, =_end_address_data + ldr r2, =_start_address_init_data + movs r3, #0 + b L_loop0_0 + +L_loop0: + ldr r4, [r2, r3] + str r4, [r0, r3] + adds r3, r3, #4 + +L_loop0_0: + adds r4, r0, r3 + cmp r4, r1 + bcc L_loop0 + + ldr r2, =_start_address_bss + ldr r4, =_end_address_bss + movs r3, #0 + b L_loop1 + +L_loop2: + str r3, [r2] + adds r2, r2, #4 + +L_loop1: + cmp r2, r4 + bcc L_loop2 + + bl SystemInit + bl __libc_init_array + bl main + bx lr +.size Reset_Handler, .-Reset_Handler + +// This is the code that gets called when the processor receives an unexpected interrupt. + .section .text.Default_Handler,"ax",%progbits +Default_Handler: +Infinite_Loop: + b Infinite_Loop + .size Default_Handler, .-Default_Handler +// The minimal vector table for a Cortex M4. + .section .apm32_isr_vector,"a",%progbits + .type g_apm32_Vectors, %object + .size g_apm32_Vectors, .-g_apm32_Vectors + +// Vector Table Mapped to Address 0 at Reset +g_apm32_Vectors: + .word _end_stack // Top of Stack + .word Reset_Handler // Reset Handler + .word NMI_Handler // NMI Handler + .word HardFault_Handler // Hard Fault Handler + .word MemManage_Handler // MPU Fault Handler + .word BusFault_Handler // Bus Fault Handler + .word UsageFault_Handler // Usage Fault Handler + .word 0 // Reserved + .word 0 // Reserved + .word 0 // Reserved + .word 0 // Reserved + .word SVC_Handler // SVCall Handler + .word DebugMon_Handler // Debug Monitor Handler + .word 0 // Reserved + .word PendSV_Handler // PendSV Handler + .word SysTick_Handler // SysTick Handler + + /* External Interrupts */ + .word WWDT_IRQHandler // Window WatchDog + .word PVD_IRQHandler // PVD through EINT Line detection + .word TAMP_STAMP_IRQHandler // Tamper and TimeStamps through the EINT line + .word RTC_WKUP_IRQHandler // RTC Wakeup through the EINT line + .word FLASH_IRQHandler // FLASH + .word RCM_IRQHandler // RCM + .word EINT0_IRQHandler // EINT Line0 + .word EINT1_IRQHandler // EINT Line1 + .word EINT2_IRQHandler // EINT Line2 + .word EINT3_IRQHandler // EINT Line3 + .word EINT4_IRQHandler // EINT Line4 + .word DMA1_STR0_IRQHandler // DMA1 Stream 0 + .word DMA1_STR1_IRQHandler // DMA1 Stream 1 + .word DMA1_STR2_IRQHandler // DMA1 Stream 2 + .word DMA1_STR3_IRQHandler // DMA1 Stream 3 + .word DMA1_STR4_IRQHandler // DMA1 Stream 4 + .word DMA1_STR5_IRQHandler // DMA1 Stream 5 + .word DMA1_STR6_IRQHandler // DMA1 Stream 6 + .word ADC_IRQHandler // ADC1, ADC2 and ADC3s + .word CAN1_TX_IRQHandler // CAN1 TX + .word CAN1_RX0_IRQHandler // CAN1 RX0 + .word CAN1_RX1_IRQHandler // CAN1 RX1 + .word CAN1_SCE_IRQHandler // CAN1 SCE + .word EINT9_5_IRQHandler // External Line[9:5]s + .word TMR1_BRK_TMR9_IRQHandler // TMR1 Break and TMR9 + .word TMR1_UP_TMR10_IRQHandler // TMR1 Update and TMR10 + .word TMR1_TRG_COM_TMR11_IRQHandler // TMR1 Trigger and Commutation and TMR11 + .word TMR1_CC_IRQHandler // TMR1 Capture Compare + .word TMR2_IRQHandler // TMR2 + .word TMR3_IRQHandler // TMR3 + .word TMR4_IRQHandler // TMR4 + .word I2C1_EV_IRQHandler // I2C1 Event + .word I2C1_ER_IRQHandler // I2C1 Error + .word I2C2_EV_IRQHandler // I2C2 Event + .word I2C2_ER_IRQHandler // I2C2 Error + .word SPI1_IRQHandler // SPI1 + .word SPI2_IRQHandler // SPI2 + .word USART1_IRQHandler // USART1 + .word USART2_IRQHandler // USART2 + .word USART3_IRQHandler // USART3 + .word EINT15_10_IRQHandler // External Line[15:10]s + .word RTC_Alarm_IRQHandler // RTC Alarm (A and B) through EINT Line + .word OTG_FS_WKUP_IRQHandler // USB OTG FS Wakeup through EINT line + .word TMR8_BRK_TMR12_IRQHandler // TMR8 Break and TMR12 + .word TMR8_UP_TMR13_IRQHandler // TMR8 Update and TMR13 + .word TMR8_TRG_COM_TMR14_IRQHandler // TMR8 Trigger and Commutation and TMR14 + .word TMR8_CC_IRQHandler // TMR8 Capture Compare + .word DMA1_STR7_IRQHandler // DMA1 Stream7 + .word EMMC_IRQHandler // EMMC + .word SDIO_IRQHandler // SDIO + .word TMR5_IRQHandler // TMR5 + .word SPI3_IRQHandler // SPI3 + .word UART4_IRQHandler // UART4 + .word UART5_IRQHandler // UART5 + .word TMR6_DAC_IRQHandler // TMR6 and DAC1&2 underrun errors + .word TMR7_IRQHandler // TMR7 + .word DMA2_STR0_IRQHandler // DMA2 Stream 0 + .word DMA2_STR1_IRQHandler // DMA2 Stream 1 + .word DMA2_STR2_IRQHandler // DMA2 Stream 2 + .word DMA2_STR3_IRQHandler // DMA2 Stream 3 + .word DMA2_STR4_IRQHandler // DMA2 Stream 4 + .word 0 // Reserved + .word 0 // Reserved + .word CAN2_TX_IRQHandler // CAN2 TX + .word CAN2_RX0_IRQHandler // CAN2 RX0 + .word CAN2_RX1_IRQHandler // CAN2 RX1 + .word CAN2_SCE_IRQHandler // CAN2 SCE + .word OTG_FS_IRQHandler // USB OTG FS + .word DMA2_STR5_IRQHandler // DMA2 Stream 5 + .word DMA2_STR6_IRQHandler // DMA2 Stream 6 + .word DMA2_STR7_IRQHandler // DMA2 Stream 7 + .word USART6_IRQHandler // USART6 + .word I2C3_EV_IRQHandler // I2C3 event + .word I2C3_ER_IRQHandler // I2C3 error + .word OTG_HS1_EP1_OUT_IRQHandler // USB OTG HS End Point 1 Out + .word OTG_HS1_EP1_IN_IRQHandler // USB OTG HS End Point 1 In + .word OTG_HS1_WKUP_IRQHandler // USB OTG HS Wakeup through EINT + .word OTG_HS1_IRQHandler // USB OTG HS + .word 0 // Reserved + .word 0 // Reserved + .word HASH_RNG_IRQHandler // Hash and Rng + .word FPU_IRQHandler // FPU + .word SM3_IRQHandler // SM3 + .word SM4_IRQHandler // SM4 + .word BN_IRQHandler // BN + +// Default exception/interrupt handler + + .weak NMI_Handler + .thumb_set NMI_Handler,Default_Handler + + .weak HardFault_Handler + .thumb_set HardFault_Handler,Default_Handler + + .weak MemManage_Handler + .thumb_set MemManage_Handler,Default_Handler + + .weak BusFault_Handler + .thumb_set BusFault_Handler,Default_Handler + + .weak UsageFault_Handler + .thumb_set UsageFault_Handler,Default_Handler + + .weak SVC_Handler + .thumb_set SVC_Handler,Default_Handler + + .weak DebugMon_Handler + .thumb_set DebugMon_Handler,Default_Handler + + .weak PendSV_Handler + .thumb_set PendSV_Handler,Default_Handler + + .weak SysTick_Handler + .thumb_set SysTick_Handler,Default_Handler + + .weak WWDT_IRQHandler + .thumb_set WWDT_IRQHandler,Default_Handler + + .weak PVD_IRQHandler + .thumb_set PVD_IRQHandler,Default_Handler + + .weak TAMP_STAMP_IRQHandler + .thumb_set TAMP_STAMP_IRQHandler,Default_Handler + + .weak RTC_WKUP_IRQHandler + .thumb_set RTC_WKUP_IRQHandler,Default_Handler + + .weak FLASH_IRQHandler + .thumb_set FLASH_IRQHandler,Default_Handler + + .weak RCM_IRQHandler + .thumb_set RCM_IRQHandler,Default_Handler + + .weak EINT0_IRQHandler + .thumb_set EINT0_IRQHandler,Default_Handler + + .weak EINT1_IRQHandler + .thumb_set EINT1_IRQHandler,Default_Handler + + .weak EINT2_IRQHandler + .thumb_set EINT2_IRQHandler,Default_Handler + + .weak EINT3_IRQHandler + .thumb_set EINT3_IRQHandler,Default_Handler + + .weak EINT4_IRQHandler + .thumb_set EINT4_IRQHandler,Default_Handler + + .weak DMA1_STR0_IRQHandler + .thumb_set DMA1_STR0_IRQHandler,Default_Handler + + .weak DMA1_STR1_IRQHandler + .thumb_set DMA1_STR1_IRQHandler,Default_Handler + + .weak DMA1_STR2_IRQHandler + .thumb_set DMA1_STR2_IRQHandler,Default_Handler + + .weak DMA1_STR3_IRQHandler + .thumb_set DMA1_STR3_IRQHandler,Default_Handler + + .weak DMA1_STR4_IRQHandler + .thumb_set DMA1_STR4_IRQHandler,Default_Handler + + .weak DMA1_STR5_IRQHandler + .thumb_set DMA1_STR5_IRQHandler,Default_Handler + + .weak DMA1_STR6_IRQHandler + .thumb_set DMA1_STR6_IRQHandler,Default_Handler + + .weak ADC_IRQHandler + .thumb_set ADC_IRQHandler,Default_Handler + + .weak CAN1_TX_IRQHandler + .thumb_set CAN1_TX_IRQHandler,Default_Handler + + .weak CAN1_RX0_IRQHandler + .thumb_set CAN1_RX0_IRQHandler,Default_Handler + + .weak CAN1_RX1_IRQHandler + .thumb_set CAN1_RX1_IRQHandler,Default_Handler + + .weak CAN1_SCE_IRQHandler + .thumb_set CAN1_SCE_IRQHandler,Default_Handler + + .weak EINT9_5_IRQHandler + .thumb_set EINT9_5_IRQHandler,Default_Handler + + .weak TMR1_BRK_TMR9_IRQHandler + .thumb_set TMR1_BRK_TMR9_IRQHandler,Default_Handler + + .weak TMR1_UP_TMR10_IRQHandler + .thumb_set TMR1_UP_TMR10_IRQHandler,Default_Handler + + .weak TMR1_TRG_COM_TMR11_IRQHandler + .thumb_set TMR1_TRG_COM_TMR11_IRQHandler,Default_Handler + + .weak TMR1_CC_IRQHandler + .thumb_set TMR1_CC_IRQHandler,Default_Handler + + .weak TMR2_IRQHandler + .thumb_set TMR2_IRQHandler,Default_Handler + + .weak TMR3_IRQHandler + .thumb_set TMR3_IRQHandler,Default_Handler + + .weak TMR4_IRQHandler + .thumb_set TMR4_IRQHandler,Default_Handler + + .weak I2C1_EV_IRQHandler + .thumb_set I2C1_EV_IRQHandler,Default_Handler + + .weak I2C1_ER_IRQHandler + .thumb_set I2C1_ER_IRQHandler,Default_Handler + + .weak I2C2_EV_IRQHandler + .thumb_set I2C2_EV_IRQHandler,Default_Handler + + .weak I2C2_ER_IRQHandler + .thumb_set I2C2_ER_IRQHandler,Default_Handler + + .weak SPI1_IRQHandler + .thumb_set SPI1_IRQHandler,Default_Handler + + .weak SPI2_IRQHandler + .thumb_set SPI2_IRQHandler,Default_Handler + + .weak USART1_IRQHandler + .thumb_set USART1_IRQHandler,Default_Handler + + .weak USART2_IRQHandler + .thumb_set USART2_IRQHandler,Default_Handler + + .weak USART3_IRQHandler + .thumb_set USART3_IRQHandler,Default_Handler + + .weak EINT15_10_IRQHandler + .thumb_set EINT15_10_IRQHandler,Default_Handler + + .weak RTC_Alarm_IRQHandler + .thumb_set RTC_Alarm_IRQHandler,Default_Handler + + .weak OTG_FS_WKUP_IRQHandler + .thumb_set OTG_FS_WKUP_IRQHandler,Default_Handler + + .weak TMR8_BRK_TMR12_IRQHandler + .thumb_set TMR8_BRK_TMR12_IRQHandler,Default_Handler + + .weak TMR8_UP_TMR13_IRQHandler + .thumb_set TMR8_UP_TMR13_IRQHandler,Default_Handler + + .weak TMR8_TRG_COM_TMR14_IRQHandler + .thumb_set TMR8_TRG_COM_TMR14_IRQHandler,Default_Handler + + .weak TMR8_CC_IRQHandler + .thumb_set TMR8_CC_IRQHandler,Default_Handler + + .weak DMA1_STR7_IRQHandler + .thumb_set DMA1_STR7_IRQHandler,Default_Handler + + .weak EMMC_IRQHandler + .thumb_set EMMC_IRQHandler,Default_Handler + + .weak SDIO_IRQHandler + .thumb_set SDIO_IRQHandler,Default_Handler + + .weak TMR5_IRQHandler + .thumb_set TMR5_IRQHandler,Default_Handler + + .weak SPI3_IRQHandler + .thumb_set SPI3_IRQHandler,Default_Handler + + .weak UART4_IRQHandler + .thumb_set UART4_IRQHandler,Default_Handler + + .weak UART5_IRQHandler + .thumb_set UART5_IRQHandler,Default_Handler + + .weak TMR6_DAC_IRQHandler + .thumb_set TMR6_DAC_IRQHandler,Default_Handler + + .weak TMR7_IRQHandler + .thumb_set TMR7_IRQHandler,Default_Handler + + .weak DMA2_STR0_IRQHandler + .thumb_set DMA2_STR0_IRQHandler,Default_Handler + + .weak DMA2_STR1_IRQHandler + .thumb_set DMA2_STR1_IRQHandler,Default_Handler + + .weak DMA2_STR2_IRQHandler + .thumb_set DMA2_STR2_IRQHandler,Default_Handler + + .weak DMA2_STR3_IRQHandler + .thumb_set DMA2_STR3_IRQHandler,Default_Handler + + .weak DMA2_STR4_IRQHandler + .thumb_set DMA2_STR4_IRQHandler,Default_Handler + + .weak CAN2_TX_IRQHandler + .thumb_set CAN2_TX_IRQHandler,Default_Handler + + .weak CAN2_RX0_IRQHandler + .thumb_set CAN2_RX0_IRQHandler,Default_Handler + + .weak CAN2_RX1_IRQHandler + .thumb_set CAN2_RX1_IRQHandler,Default_Handler + + .weak CAN2_SCE_IRQHandler + .thumb_set CAN2_SCE_IRQHandler,Default_Handler + + .weak OTG_FS_IRQHandler + .thumb_set OTG_FS_IRQHandler,Default_Handler + + .weak DMA2_STR5_IRQHandler + .thumb_set DMA2_STR5_IRQHandler,Default_Handler + + .weak DMA2_STR6_IRQHandler + .thumb_set DMA2_STR6_IRQHandler,Default_Handler + + .weak DMA2_STR7_IRQHandler + .thumb_set DMA2_STR7_IRQHandler,Default_Handler + + .weak USART6_IRQHandler + .thumb_set USART6_IRQHandler,Default_Handler + + .weak I2C3_EV_IRQHandler + .thumb_set I2C3_EV_IRQHandler,Default_Handler + + .weak I2C3_ER_IRQHandler + .thumb_set I2C3_ER_IRQHandler,Default_Handler + + .weak OTG_HS1_EP1_OUT_IRQHandler + .thumb_set OTG_HS1_EP1_OUT_IRQHandler,Default_Handler + + .weak OTG_HS1_EP1_IN_IRQHandler + .thumb_set OTG_HS1_EP1_IN_IRQHandler,Default_Handler + + .weak OTG_HS1_WKUP_IRQHandler + .thumb_set OTG_HS1_WKUP_IRQHandler,Default_Handler + + .weak OTG_HS1_IRQHandler + .thumb_set OTG_HS1_IRQHandler,Default_Handler + + .weak HASH_RNG_IRQHandler + .thumb_set HASH_RNG_IRQHandler,Default_Handler + + .weak FPU_IRQHandler + .thumb_set FPU_IRQHandler,Default_Handler + + .weak SM3_IRQHandler + .thumb_set SM3_IRQHandler,Default_Handler + + .weak SM4_IRQHandler + .thumb_set SM4_IRQHandler,Default_Handler + + .weak BN_IRQHandler + .thumb_set BN_IRQHandler,Default_Handler diff --git a/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/gcc/startup_apm32f407xx.S b/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/gcc/startup_apm32f407xx.S new file mode 100644 index 0000000000..cc59f0d0dc --- /dev/null +++ b/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/gcc/startup_apm32f407xx.S @@ -0,0 +1,494 @@ +/** + * @file startup_apm32f407xx.S + * + * @brief APM32F407xx Devices vector table for GCC based toolchains. + * This module performs: + * - Set the initial SP + * - Set the initial PC == Reset_Handler, + * - Set the vector table entries with the exceptions ISR address + * - Branches to main in the C library (which eventually + * calls main()). + * After Reset the Cortex-M4 processor is in Thread mode, + * priority is Privileged, and the Stack is set to Main. + * + * @version V1.0.0 + * + * @date 2023-07-31 + * + * @attention + * + * Copyright (C) 2023 Geehy Semiconductor + * + * You may not use this file except in compliance with the + * GEEHY COPYRIGHT NOTICE (GEEHY SOFTWARE PACKAGE LICENSE). + * + * The program is only for reference, which is distributed in the hope + * that it will be useful and instructional for customers to develop + * their software. Unless required by applicable law or agreed to in + * writing, the program is distributed on an "AS IS" BASIS, WITHOUT + * ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied. + * See the GEEHY SOFTWARE PACKAGE LICENSE for the governing permissions + * and limitations under the License. + */ + + .syntax unified + .cpu cortex-m4 + .fpu softvfp + .thumb + +.global g_apm32_Vectors +.global Default_Handler + +/* start address for the initialization values of the .data section. +defined in linker script */ +.word _start_address_init_data +/* start address for the .data section. defined in linker script */ +.word _start_address_data +/* end address for the .data section. defined in linker script */ +.word _end_address_data +/* start address for the .bss section. defined in linker script */ +.word _start_address_bss +/* end address for the .bss section. defined in linker script */ +.word _end_address_bss +/* stack used for SystemInit_ExtMemCtl; always internal RAM used */ + + .section .text.Reset_Handler + .weak Reset_Handler + .type Reset_Handler, %function +// Reset handler routine +Reset_Handler: + ldr sp, =_end_stack + +/* Copy the data segment initializers from flash to SRAM */ + ldr r0, =_start_address_data + ldr r1, =_end_address_data + ldr r2, =_start_address_init_data + movs r3, #0 + b L_loop0_0 + +L_loop0: + ldr r4, [r2, r3] + str r4, [r0, r3] + adds r3, r3, #4 + +L_loop0_0: + adds r4, r0, r3 + cmp r4, r1 + bcc L_loop0 + + ldr r2, =_start_address_bss + ldr r4, =_end_address_bss + movs r3, #0 + b L_loop1 + +L_loop2: + str r3, [r2] + adds r2, r2, #4 + +L_loop1: + cmp r2, r4 + bcc L_loop2 + + bl SystemInit + bl __libc_init_array + bl main + bx lr +.size Reset_Handler, .-Reset_Handler + +// This is the code that gets called when the processor receives an unexpected interrupt. + .section .text.Default_Handler,"ax",%progbits +Default_Handler: +Infinite_Loop: + b Infinite_Loop + .size Default_Handler, .-Default_Handler +// The minimal vector table for a Cortex M4. + .section .apm32_isr_vector,"a",%progbits + .type g_apm32_Vectors, %object + .size g_apm32_Vectors, .-g_apm32_Vectors + +// Vector Table Mapped to Address 0 at Reset +g_apm32_Vectors: + .word _end_stack // Top of Stack + .word Reset_Handler // Reset Handler + .word NMI_Handler // NMI Handler + .word HardFault_Handler // Hard Fault Handler + .word MemManage_Handler // MPU Fault Handler + .word BusFault_Handler // Bus Fault Handler + .word UsageFault_Handler // Usage Fault Handler + .word 0 // Reserved + .word 0 // Reserved + .word 0 // Reserved + .word 0 // Reserved + .word SVC_Handler // SVCall Handler + .word DebugMon_Handler // Debug Monitor Handler + .word 0 // Reserved + .word PendSV_Handler // PendSV Handler + .word SysTick_Handler // SysTick Handler + + /* External Interrupts */ + .word WWDT_IRQHandler // Window WatchDog + .word PVD_IRQHandler // PVD through EINT Line detection + .word TAMP_STAMP_IRQHandler // Tamper and TimeStamps through the EINT line + .word RTC_WKUP_IRQHandler // RTC Wakeup through the EINT line + .word FLASH_IRQHandler // FLASH + .word RCM_IRQHandler // RCM + .word EINT0_IRQHandler // EINT Line0 + .word EINT1_IRQHandler // EINT Line1 + .word EINT2_IRQHandler // EINT Line2 + .word EINT3_IRQHandler // EINT Line3 + .word EINT4_IRQHandler // EINT Line4 + .word DMA1_STR0_IRQHandler // DMA1 Stream 0 + .word DMA1_STR1_IRQHandler // DMA1 Stream 1 + .word DMA1_STR2_IRQHandler // DMA1 Stream 2 + .word DMA1_STR3_IRQHandler // DMA1 Stream 3 + .word DMA1_STR4_IRQHandler // DMA1 Stream 4 + .word DMA1_STR5_IRQHandler // DMA1 Stream 5 + .word DMA1_STR6_IRQHandler // DMA1 Stream 6 + .word ADC_IRQHandler // ADC1, ADC2 and ADC3s + .word CAN1_TX_IRQHandler // CAN1 TX + .word CAN1_RX0_IRQHandler // CAN1 RX0 + .word CAN1_RX1_IRQHandler // CAN1 RX1 + .word CAN1_SCE_IRQHandler // CAN1 SCE + .word EINT9_5_IRQHandler // External Line[9:5]s + .word TMR1_BRK_TMR9_IRQHandler // TMR1 Break and TMR9 + .word TMR1_UP_TMR10_IRQHandler // TMR1 Update and TMR10 + .word TMR1_TRG_COM_TMR11_IRQHandler // TMR1 Trigger and Commutation and TMR11 + .word TMR1_CC_IRQHandler // TMR1 Capture Compare + .word TMR2_IRQHandler // TMR2 + .word TMR3_IRQHandler // TMR3 + .word TMR4_IRQHandler // TMR4 + .word I2C1_EV_IRQHandler // I2C1 Event + .word I2C1_ER_IRQHandler // I2C1 Error + .word I2C2_EV_IRQHandler // I2C2 Event + .word I2C2_ER_IRQHandler // I2C2 Error + .word SPI1_IRQHandler // SPI1 + .word SPI2_IRQHandler // SPI2 + .word USART1_IRQHandler // USART1 + .word USART2_IRQHandler // USART2 + .word USART3_IRQHandler // USART3 + .word EINT15_10_IRQHandler // External Line[15:10]s + .word RTC_Alarm_IRQHandler // RTC Alarm (A and B) through EINT Line + .word OTG_FS_WKUP_IRQHandler // USB OTG FS Wakeup through EINT line + .word TMR8_BRK_TMR12_IRQHandler // TMR8 Break and TMR12 + .word TMR8_UP_TMR13_IRQHandler // TMR8 Update and TMR13 + .word TMR8_TRG_COM_TMR14_IRQHandler // TMR8 Trigger and Commutation and TMR14 + .word TMR8_CC_IRQHandler // TMR8 Capture Compare + .word DMA1_STR7_IRQHandler // DMA1 Stream7 + .word EMMC_IRQHandler // EMMC + .word SDIO_IRQHandler // SDIO + .word TMR5_IRQHandler // TMR5 + .word SPI3_IRQHandler // SPI3 + .word UART4_IRQHandler // UART4 + .word UART5_IRQHandler // UART5 + .word TMR6_DAC_IRQHandler // TMR6 and DAC1&2 underrun errors + .word TMR7_IRQHandler // TMR7 + .word DMA2_STR0_IRQHandler // DMA2 Stream 0 + .word DMA2_STR1_IRQHandler // DMA2 Stream 1 + .word DMA2_STR2_IRQHandler // DMA2 Stream 2 + .word DMA2_STR3_IRQHandler // DMA2 Stream 3 + .word DMA2_STR4_IRQHandler // DMA2 Stream 4 + .word ETH_IRQHandler // Ethernet + .word ETH_WKUP_IRQHandler // Ethernet Wakeup through EINT line + .word CAN2_TX_IRQHandler // CAN2 TX + .word CAN2_RX0_IRQHandler // CAN2 RX0 + .word CAN2_RX1_IRQHandler // CAN2 RX1 + .word CAN2_SCE_IRQHandler // CAN2 SCE + .word OTG_FS_IRQHandler // USB OTG FS + .word DMA2_STR5_IRQHandler // DMA2 Stream 5 + .word DMA2_STR6_IRQHandler // DMA2 Stream 6 + .word DMA2_STR7_IRQHandler // DMA2 Stream 7 + .word USART6_IRQHandler // USART6 + .word I2C3_EV_IRQHandler // I2C3 event + .word I2C3_ER_IRQHandler // I2C3 error + .word OTG_HS1_EP1_OUT_IRQHandler // USB OTG HS End Point 1 Out + .word OTG_HS1_EP1_IN_IRQHandler // USB OTG HS End Point 1 In + .word OTG_HS1_WKUP_IRQHandler // USB OTG HS Wakeup through EINT + .word OTG_HS1_IRQHandler // USB OTG HS + .word DCI_IRQHandler // DCI + .word 0 // Reserved + .word HASH_RNG_IRQHandler // Hash and Rng + .word FPU_IRQHandler // FPU + .word SM3_IRQHandler // SM3 + .word SM4_IRQHandler // SM4 + .word BN_IRQHandler // BN + +// Default exception/interrupt handler + + .weak NMI_Handler + .thumb_set NMI_Handler,Default_Handler + + .weak HardFault_Handler + .thumb_set HardFault_Handler,Default_Handler + + .weak MemManage_Handler + .thumb_set MemManage_Handler,Default_Handler + + .weak BusFault_Handler + .thumb_set BusFault_Handler,Default_Handler + + .weak UsageFault_Handler + .thumb_set UsageFault_Handler,Default_Handler + + .weak SVC_Handler + .thumb_set SVC_Handler,Default_Handler + + .weak DebugMon_Handler + .thumb_set DebugMon_Handler,Default_Handler + + .weak PendSV_Handler + .thumb_set PendSV_Handler,Default_Handler + + .weak SysTick_Handler + .thumb_set SysTick_Handler,Default_Handler + + .weak WWDT_IRQHandler + .thumb_set WWDT_IRQHandler,Default_Handler + + .weak PVD_IRQHandler + .thumb_set PVD_IRQHandler,Default_Handler + + .weak TAMP_STAMP_IRQHandler + .thumb_set TAMP_STAMP_IRQHandler,Default_Handler + + .weak RTC_WKUP_IRQHandler + .thumb_set RTC_WKUP_IRQHandler,Default_Handler + + .weak FLASH_IRQHandler + .thumb_set FLASH_IRQHandler,Default_Handler + + .weak RCM_IRQHandler + .thumb_set RCM_IRQHandler,Default_Handler + + .weak EINT0_IRQHandler + .thumb_set EINT0_IRQHandler,Default_Handler + + .weak EINT1_IRQHandler + .thumb_set EINT1_IRQHandler,Default_Handler + + .weak EINT2_IRQHandler + .thumb_set EINT2_IRQHandler,Default_Handler + + .weak EINT3_IRQHandler + .thumb_set EINT3_IRQHandler,Default_Handler + + .weak EINT4_IRQHandler + .thumb_set EINT4_IRQHandler,Default_Handler + + .weak DMA1_STR0_IRQHandler + .thumb_set DMA1_STR0_IRQHandler,Default_Handler + + .weak DMA1_STR1_IRQHandler + .thumb_set DMA1_STR1_IRQHandler,Default_Handler + + .weak DMA1_STR2_IRQHandler + .thumb_set DMA1_STR2_IRQHandler,Default_Handler + + .weak DMA1_STR3_IRQHandler + .thumb_set DMA1_STR3_IRQHandler,Default_Handler + + .weak DMA1_STR4_IRQHandler + .thumb_set DMA1_STR4_IRQHandler,Default_Handler + + .weak DMA1_STR5_IRQHandler + .thumb_set DMA1_STR5_IRQHandler,Default_Handler + + .weak DMA1_STR6_IRQHandler + .thumb_set DMA1_STR6_IRQHandler,Default_Handler + + .weak ADC_IRQHandler + .thumb_set ADC_IRQHandler,Default_Handler + + .weak CAN1_TX_IRQHandler + .thumb_set CAN1_TX_IRQHandler,Default_Handler + + .weak CAN1_RX0_IRQHandler + .thumb_set CAN1_RX0_IRQHandler,Default_Handler + + .weak CAN1_RX1_IRQHandler + .thumb_set CAN1_RX1_IRQHandler,Default_Handler + + .weak CAN1_SCE_IRQHandler + .thumb_set CAN1_SCE_IRQHandler,Default_Handler + + .weak EINT9_5_IRQHandler + .thumb_set EINT9_5_IRQHandler,Default_Handler + + .weak TMR1_BRK_TMR9_IRQHandler + .thumb_set TMR1_BRK_TMR9_IRQHandler,Default_Handler + + .weak TMR1_UP_TMR10_IRQHandler + .thumb_set TMR1_UP_TMR10_IRQHandler,Default_Handler + + .weak TMR1_TRG_COM_TMR11_IRQHandler + .thumb_set TMR1_TRG_COM_TMR11_IRQHandler,Default_Handler + + .weak TMR1_CC_IRQHandler + .thumb_set TMR1_CC_IRQHandler,Default_Handler + + .weak TMR2_IRQHandler + .thumb_set TMR2_IRQHandler,Default_Handler + + .weak TMR3_IRQHandler + .thumb_set TMR3_IRQHandler,Default_Handler + + .weak TMR4_IRQHandler + .thumb_set TMR4_IRQHandler,Default_Handler + + .weak I2C1_EV_IRQHandler + .thumb_set I2C1_EV_IRQHandler,Default_Handler + + .weak I2C1_ER_IRQHandler + .thumb_set I2C1_ER_IRQHandler,Default_Handler + + .weak I2C2_EV_IRQHandler + .thumb_set I2C2_EV_IRQHandler,Default_Handler + + .weak I2C2_ER_IRQHandler + .thumb_set I2C2_ER_IRQHandler,Default_Handler + + .weak SPI1_IRQHandler + .thumb_set SPI1_IRQHandler,Default_Handler + + .weak SPI2_IRQHandler + .thumb_set SPI2_IRQHandler,Default_Handler + + .weak USART1_IRQHandler + .thumb_set USART1_IRQHandler,Default_Handler + + .weak USART2_IRQHandler + .thumb_set USART2_IRQHandler,Default_Handler + + .weak USART3_IRQHandler + .thumb_set USART3_IRQHandler,Default_Handler + + .weak EINT15_10_IRQHandler + .thumb_set EINT15_10_IRQHandler,Default_Handler + + .weak RTC_Alarm_IRQHandler + .thumb_set RTC_Alarm_IRQHandler,Default_Handler + + .weak OTG_FS_WKUP_IRQHandler + .thumb_set OTG_FS_WKUP_IRQHandler,Default_Handler + + .weak TMR8_BRK_TMR12_IRQHandler + .thumb_set TMR8_BRK_TMR12_IRQHandler,Default_Handler + + .weak TMR8_UP_TMR13_IRQHandler + .thumb_set TMR8_UP_TMR13_IRQHandler,Default_Handler + + .weak TMR8_TRG_COM_TMR14_IRQHandler + .thumb_set TMR8_TRG_COM_TMR14_IRQHandler,Default_Handler + + .weak TMR8_CC_IRQHandler + .thumb_set TMR8_CC_IRQHandler,Default_Handler + + .weak DMA1_STR7_IRQHandler + .thumb_set DMA1_STR7_IRQHandler,Default_Handler + + .weak EMMC_IRQHandler + .thumb_set EMMC_IRQHandler,Default_Handler + + .weak SDIO_IRQHandler + .thumb_set SDIO_IRQHandler,Default_Handler + + .weak TMR5_IRQHandler + .thumb_set TMR5_IRQHandler,Default_Handler + + .weak SPI3_IRQHandler + .thumb_set SPI3_IRQHandler,Default_Handler + + .weak UART4_IRQHandler + .thumb_set UART4_IRQHandler,Default_Handler + + .weak UART5_IRQHandler + .thumb_set UART5_IRQHandler,Default_Handler + + .weak TMR6_DAC_IRQHandler + .thumb_set TMR6_DAC_IRQHandler,Default_Handler + + .weak TMR7_IRQHandler + .thumb_set TMR7_IRQHandler,Default_Handler + + .weak DMA2_STR0_IRQHandler + .thumb_set DMA2_STR0_IRQHandler,Default_Handler + + .weak DMA2_STR1_IRQHandler + .thumb_set DMA2_STR1_IRQHandler,Default_Handler + + .weak DMA2_STR2_IRQHandler + .thumb_set DMA2_STR2_IRQHandler,Default_Handler + + .weak DMA2_STR3_IRQHandler + .thumb_set DMA2_STR3_IRQHandler,Default_Handler + + .weak DMA2_STR4_IRQHandler + .thumb_set DMA2_STR4_IRQHandler,Default_Handler + + .weak ETH_IRQHandler + .thumb_set ETH_IRQHandler,Default_Handler + + .weak ETH_WKUP_IRQHandler + .thumb_set ETH_WKUP_IRQHandler,Default_Handler + + .weak CAN2_TX_IRQHandler + .thumb_set CAN2_TX_IRQHandler,Default_Handler + + .weak CAN2_RX0_IRQHandler + .thumb_set CAN2_RX0_IRQHandler,Default_Handler + + .weak CAN2_RX1_IRQHandler + .thumb_set CAN2_RX1_IRQHandler,Default_Handler + + .weak CAN2_SCE_IRQHandler + .thumb_set CAN2_SCE_IRQHandler,Default_Handler + + .weak OTG_FS_IRQHandler + .thumb_set OTG_FS_IRQHandler,Default_Handler + + .weak DMA2_STR5_IRQHandler + .thumb_set DMA2_STR5_IRQHandler,Default_Handler + + .weak DMA2_STR6_IRQHandler + .thumb_set DMA2_STR6_IRQHandler,Default_Handler + + .weak DMA2_STR7_IRQHandler + .thumb_set DMA2_STR7_IRQHandler,Default_Handler + + .weak USART6_IRQHandler + .thumb_set USART6_IRQHandler,Default_Handler + + .weak I2C3_EV_IRQHandler + .thumb_set I2C3_EV_IRQHandler,Default_Handler + + .weak I2C3_ER_IRQHandler + .thumb_set I2C3_ER_IRQHandler,Default_Handler + + .weak OTG_HS1_EP1_OUT_IRQHandler + .thumb_set OTG_HS1_EP1_OUT_IRQHandler,Default_Handler + + .weak OTG_HS1_EP1_IN_IRQHandler + .thumb_set OTG_HS1_EP1_IN_IRQHandler,Default_Handler + + .weak OTG_HS1_WKUP_IRQHandler + .thumb_set OTG_HS1_WKUP_IRQHandler,Default_Handler + + .weak OTG_HS1_IRQHandler + .thumb_set OTG_HS1_IRQHandler,Default_Handler + + .weak DCI_IRQHandler + .thumb_set DCI_IRQHandler,Default_Handler + + .weak HASH_RNG_IRQHandler + .thumb_set HASH_RNG_IRQHandler,Default_Handler + + .weak FPU_IRQHandler + .thumb_set FPU_IRQHandler,Default_Handler + + .weak SM3_IRQHandler + .thumb_set SM3_IRQHandler,Default_Handler + + .weak SM4_IRQHandler + .thumb_set SM4_IRQHandler,Default_Handler + + .weak BN_IRQHandler + .thumb_set BN_IRQHandler,Default_Handler diff --git a/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/gcc/startup_apm32f411xx.S b/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/gcc/startup_apm32f411xx.S new file mode 100644 index 0000000000..9b4e0ad577 --- /dev/null +++ b/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/gcc/startup_apm32f411xx.S @@ -0,0 +1,468 @@ +/** + * @file startup_apm32f411xx.S + * + * @brief APM32F411xx Devices vector table for GCC based toolchains. + * This module performs: + * - Set the initial SP + * - Set the initial PC == Reset_Handler, + * - Set the vector table entries with the exceptions ISR address + * - Branches to main in the C library (which eventually + * calls main()). + * After Reset the Cortex-M4 processor is in Thread mode, + * priority is Privileged, and the Stack is set to Main. + * + * @version V1.0.0 + * + * @date 2023-12-01 + * + * @attention + * + * Copyright (C) 2023 Geehy Semiconductor + * + * You may not use this file except in compliance with the + * GEEHY COPYRIGHT NOTICE (GEEHY SOFTWARE PACKAGE LICENSE). + * + * The program is only for reference, which is distributed in the hope + * that it will be useful and instructional for customers to develop + * their software. Unless required by applicable law or agreed to in + * writing, the program is distributed on an "AS IS" BASIS, WITHOUT + * ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied. + * See the GEEHY SOFTWARE PACKAGE LICENSE for the governing permissions + * and limitations under the License. + */ + + .syntax unified + .cpu cortex-m4 + .fpu softvfp + .thumb + +.global g_apm32_Vectors +.global Default_Handler + +/* start address for the initialization values of the .data section. +defined in linker script */ +.word _start_address_init_data +/* start address for the .data section. defined in linker script */ +.word _start_address_data +/* end address for the .data section. defined in linker script */ +.word _end_address_data +/* start address for the .bss section. defined in linker script */ +.word _start_address_bss +/* end address for the .bss section. defined in linker script */ +.word _end_address_bss +/* stack used for SystemInit_ExtMemCtl; always internal RAM used */ + + .section .text.Reset_Handler + .weak Reset_Handler + .type Reset_Handler, %function +// Reset handler routine +Reset_Handler: + ldr sp, =_end_stack + +/* Copy the data segment initializers from flash to SRAM */ + ldr r0, =_start_address_data + ldr r1, =_end_address_data + ldr r2, =_start_address_init_data + movs r3, #0 + b L_loop0_0 + +L_loop0: + ldr r4, [r2, r3] + str r4, [r0, r3] + adds r3, r3, #4 + +L_loop0_0: + adds r4, r0, r3 + cmp r4, r1 + bcc L_loop0 + + ldr r2, =_start_address_bss + ldr r4, =_end_address_bss + movs r3, #0 + b L_loop1 + +L_loop2: + str r3, [r2] + adds r2, r2, #4 + +L_loop1: + cmp r2, r4 + bcc L_loop2 + + bl SystemInit + bl __libc_init_array + bl main + bx lr +.size Reset_Handler, .-Reset_Handler + +// This is the code that gets called when the processor receives an unexpected interrupt. + .section .text.Default_Handler,"ax",%progbits +Default_Handler: +Infinite_Loop: + b Infinite_Loop + .size Default_Handler, .-Default_Handler +// The minimal vector table for a Cortex M4. + .section .apm32_isr_vector,"a",%progbits + .type g_apm32_Vectors, %object + .size g_apm32_Vectors, .-g_apm32_Vectors + +// Vector Table Mapped to Address 0 at Reset +g_apm32_Vectors: + .word _end_stack // Top of Stack + .word Reset_Handler // Reset Handler + .word NMI_Handler // NMI Handler + .word HardFault_Handler // Hard Fault Handler + .word MemManage_Handler // MPU Fault Handler + .word BusFault_Handler // Bus Fault Handler + .word UsageFault_Handler // Usage Fault Handler + .word 0 // Reserved + .word 0 // Reserved + .word 0 // Reserved + .word 0 // Reserved + .word SVC_Handler // SVCall Handler + .word DebugMon_Handler // Debug Monitor Handler + .word 0 // Reserved + .word PendSV_Handler // PendSV Handler + .word SysTick_Handler // SysTick Handler + + /* External Interrupts */ + .word WWDT_IRQHandler // Window WatchDog + .word PVD_IRQHandler // PVD through EINT Line detection + .word TAMP_STAMP_IRQHandler // Tamper and TimeStamps through the EINT line + .word RTC_WKUP_IRQHandler // RTC Wakeup through the EINT line + .word FLASH_IRQHandler // FLASH + .word RCM_IRQHandler // RCM + .word EINT0_IRQHandler // EINT Line0 + .word EINT1_IRQHandler // EINT Line1 + .word EINT2_IRQHandler // EINT Line2 + .word EINT3_IRQHandler // EINT Line3 + .word EINT4_IRQHandler // EINT Line4 + .word DMA1_STR0_IRQHandler // DMA1 Stream 0 + .word DMA1_STR1_IRQHandler // DMA1 Stream 1 + .word DMA1_STR2_IRQHandler // DMA1 Stream 2 + .word DMA1_STR3_IRQHandler // DMA1 Stream 3 + .word DMA1_STR4_IRQHandler // DMA1 Stream 4 + .word DMA1_STR5_IRQHandler // DMA1 Stream 5 + .word DMA1_STR6_IRQHandler // DMA1 Stream 6 + .word ADC_IRQHandler // ADC1, ADC2 + .word CAN1_TX_IRQHandler // CAN1 TX + .word CAN1_RX0_IRQHandler // CAN1 RX0 + .word CAN1_RX1_IRQHandler // CAN1 RX1 + .word CAN1_SCE_IRQHandler // CAN1 SCE + .word EINT9_5_IRQHandler // External Line[9:5]s + .word TMR1_BRK_TMR9_IRQHandler // TMR1 Break and TMR9 + .word TMR1_UP_TMR10_IRQHandler // TMR1 Update and TMR10 + .word TMR1_TRG_COM_TMR11_IRQHandler // TMR1 Trigger and Commutation and TMR11 + .word TMR1_CC_IRQHandler // TMR1 Capture Compare + .word TMR2_IRQHandler // TMR2 + .word TMR3_IRQHandler // TMR3 + .word TMR4_IRQHandler // TMR4 + .word I2C1_EV_IRQHandler // I2C1 Event + .word I2C1_ER_IRQHandler // I2C1 Error + .word I2C2_EV_IRQHandler // I2C2 Event + .word I2C2_ER_IRQHandler // I2C2 Error + .word SPI1_IRQHandler // SPI1 + .word SPI2_IRQHandler // SPI2 + .word USART1_IRQHandler // USART1 + .word USART2_IRQHandler // USART2 + .word USART3_IRQHandler // USART3 + .word EINT15_10_IRQHandler // External Line[15:10]s + .word RTC_Alarm_IRQHandler // RTC Alarm (A and B) through EINT Line + .word OTG_FS_WKUP_IRQHandler // USB OTG FS Wakeup through EINT line + .word TMR8_BRK_TMR12_IRQHandler // TMR8 Break and TMR12 + .word TMR8_UP_TMR13_IRQHandler // TMR8 Update and TMR13 + .word TMR8_TRG_COM_TMR14_IRQHandler // TMR8 Trigger and Commutation and TMR14 + .word TMR8_CC_IRQHandler // TMR8 Capture Compare + .word DMA1_STR7_IRQHandler // DMA1 Stream7 + .word SMC_IRQHandler // SMC + .word SDIO_IRQHandler // SDIO + .word TMR5_IRQHandler // TMR5 + .word SPI3_IRQHandler // SPI3 + .word UART4_IRQHandler // UART4 + .word UART5_IRQHandler // UART5 + .word 0 // Reserved + .word 0 // Reserved + .word DMA2_STR0_IRQHandler // DMA2 Stream 0 + .word DMA2_STR1_IRQHandler // DMA2 Stream 1 + .word DMA2_STR2_IRQHandler // DMA2 Stream 2 + .word DMA2_STR3_IRQHandler // DMA2 Stream 3 + .word DMA2_STR4_IRQHandler // DMA2 Stream 4 + .word 0 // Reserved + .word 0 // Reserved + .word CAN2_TX_IRQHandler // CAN2 TX + .word CAN2_RX0_IRQHandler // CAN2 RX0 + .word CAN2_RX1_IRQHandler // CAN2 RX1 + .word CAN2_SCE_IRQHandler // CAN2 SCE + .word OTG_FS_IRQHandler // USB OTG FS + .word DMA2_STR5_IRQHandler // DMA2 Stream 5 + .word DMA2_STR6_IRQHandler // DMA2 Stream 6 + .word DMA2_STR7_IRQHandler // DMA2 Stream 7 + .word USART6_IRQHandler // USART6 + .word I2C3_EV_IRQHandler // I2C3 event + .word I2C3_ER_IRQHandler // I2C3 error + .word 0 // Reserved + .word 0 // Reserved + .word 0 // Reserved + .word 0 // Reserved + .word 0 // Reserved + .word 0 // Reserved + .word RNG_IRQHandler // RNG + .word FPU_IRQHandler // FPU + .word 0 // Reserved + .word QSPI_IRQHandler // QSPI + .word SPI4_IRQHandler // SPI4 + .word SPI5_IRQHandler // SPI5 + +// Default exception/interrupt handler + + .weak NMI_Handler + .thumb_set NMI_Handler,Default_Handler + + .weak HardFault_Handler + .thumb_set HardFault_Handler,Default_Handler + + .weak MemManage_Handler + .thumb_set MemManage_Handler,Default_Handler + + .weak BusFault_Handler + .thumb_set BusFault_Handler,Default_Handler + + .weak UsageFault_Handler + .thumb_set UsageFault_Handler,Default_Handler + + .weak SVC_Handler + .thumb_set SVC_Handler,Default_Handler + + .weak DebugMon_Handler + .thumb_set DebugMon_Handler,Default_Handler + + .weak PendSV_Handler + .thumb_set PendSV_Handler,Default_Handler + + .weak SysTick_Handler + .thumb_set SysTick_Handler,Default_Handler + + .weak WWDT_IRQHandler + .thumb_set WWDT_IRQHandler,Default_Handler + + .weak PVD_IRQHandler + .thumb_set PVD_IRQHandler,Default_Handler + + .weak TAMP_STAMP_IRQHandler + .thumb_set TAMP_STAMP_IRQHandler,Default_Handler + + .weak RTC_WKUP_IRQHandler + .thumb_set RTC_WKUP_IRQHandler,Default_Handler + + .weak FLASH_IRQHandler + .thumb_set FLASH_IRQHandler,Default_Handler + + .weak RCM_IRQHandler + .thumb_set RCM_IRQHandler,Default_Handler + + .weak EINT0_IRQHandler + .thumb_set EINT0_IRQHandler,Default_Handler + + .weak EINT1_IRQHandler + .thumb_set EINT1_IRQHandler,Default_Handler + + .weak EINT2_IRQHandler + .thumb_set EINT2_IRQHandler,Default_Handler + + .weak EINT3_IRQHandler + .thumb_set EINT3_IRQHandler,Default_Handler + + .weak EINT4_IRQHandler + .thumb_set EINT4_IRQHandler,Default_Handler + + .weak DMA1_STR0_IRQHandler + .thumb_set DMA1_STR0_IRQHandler,Default_Handler + + .weak DMA1_STR1_IRQHandler + .thumb_set DMA1_STR1_IRQHandler,Default_Handler + + .weak DMA1_STR2_IRQHandler + .thumb_set DMA1_STR2_IRQHandler,Default_Handler + + .weak DMA1_STR3_IRQHandler + .thumb_set DMA1_STR3_IRQHandler,Default_Handler + + .weak DMA1_STR4_IRQHandler + .thumb_set DMA1_STR4_IRQHandler,Default_Handler + + .weak DMA1_STR5_IRQHandler + .thumb_set DMA1_STR5_IRQHandler,Default_Handler + + .weak DMA1_STR6_IRQHandler + .thumb_set DMA1_STR6_IRQHandler,Default_Handler + + .weak ADC_IRQHandler + .thumb_set ADC_IRQHandler,Default_Handler + + .weak CAN1_TX_IRQHandler + .thumb_set CAN1_TX_IRQHandler,Default_Handler + + .weak CAN1_RX0_IRQHandler + .thumb_set CAN1_RX0_IRQHandler,Default_Handler + + .weak CAN1_RX1_IRQHandler + .thumb_set CAN1_RX1_IRQHandler,Default_Handler + + .weak CAN1_SCE_IRQHandler + .thumb_set CAN1_SCE_IRQHandler,Default_Handler + + .weak EINT9_5_IRQHandler + .thumb_set EINT9_5_IRQHandler,Default_Handler + + .weak TMR1_BRK_TMR9_IRQHandler + .thumb_set TMR1_BRK_TMR9_IRQHandler,Default_Handler + + .weak TMR1_UP_TMR10_IRQHandler + .thumb_set TMR1_UP_TMR10_IRQHandler,Default_Handler + + .weak TMR1_TRG_COM_TMR11_IRQHandler + .thumb_set TMR1_TRG_COM_TMR11_IRQHandler,Default_Handler + + .weak TMR1_CC_IRQHandler + .thumb_set TMR1_CC_IRQHandler,Default_Handler + + .weak TMR2_IRQHandler + .thumb_set TMR2_IRQHandler,Default_Handler + + .weak TMR3_IRQHandler + .thumb_set TMR3_IRQHandler,Default_Handler + + .weak TMR4_IRQHandler + .thumb_set TMR4_IRQHandler,Default_Handler + + .weak I2C1_EV_IRQHandler + .thumb_set I2C1_EV_IRQHandler,Default_Handler + + .weak I2C1_ER_IRQHandler + .thumb_set I2C1_ER_IRQHandler,Default_Handler + + .weak I2C2_EV_IRQHandler + .thumb_set I2C2_EV_IRQHandler,Default_Handler + + .weak I2C2_ER_IRQHandler + .thumb_set I2C2_ER_IRQHandler,Default_Handler + + .weak SPI1_IRQHandler + .thumb_set SPI1_IRQHandler,Default_Handler + + .weak SPI2_IRQHandler + .thumb_set SPI2_IRQHandler,Default_Handler + + .weak USART1_IRQHandler + .thumb_set USART1_IRQHandler,Default_Handler + + .weak USART2_IRQHandler + .thumb_set USART2_IRQHandler,Default_Handler + + .weak USART3_IRQHandler + .thumb_set USART3_IRQHandler,Default_Handler + + .weak EINT15_10_IRQHandler + .thumb_set EINT15_10_IRQHandler,Default_Handler + + .weak RTC_Alarm_IRQHandler + .thumb_set RTC_Alarm_IRQHandler,Default_Handler + + .weak OTG_FS_WKUP_IRQHandler + .thumb_set OTG_FS_WKUP_IRQHandler,Default_Handler + + .weak TMR8_BRK_TMR12_IRQHandler + .thumb_set TMR8_BRK_TMR12_IRQHandler,Default_Handler + + .weak TMR8_UP_TMR13_IRQHandler + .thumb_set TMR8_UP_TMR13_IRQHandler,Default_Handler + + .weak TMR8_TRG_COM_TMR14_IRQHandler + .thumb_set TMR8_TRG_COM_TMR14_IRQHandler,Default_Handler + + .weak TMR8_CC_IRQHandler + .thumb_set TMR8_CC_IRQHandler,Default_Handler + + .weak DMA1_STR7_IRQHandler + .thumb_set DMA1_STR7_IRQHandler,Default_Handler + + .weak SMC_IRQHandler + .thumb_set SMC_IRQHandler,Default_Handler + + .weak SDIO_IRQHandler + .thumb_set SDIO_IRQHandler,Default_Handler + + .weak TMR5_IRQHandler + .thumb_set TMR5_IRQHandler,Default_Handler + + .weak SPI3_IRQHandler + .thumb_set SPI3_IRQHandler,Default_Handler + + .weak UART4_IRQHandler + .thumb_set UART4_IRQHandler,Default_Handler + + .weak UART5_IRQHandler + .thumb_set UART5_IRQHandler,Default_Handler + + .weak DMA2_STR0_IRQHandler + .thumb_set DMA2_STR0_IRQHandler,Default_Handler + + .weak DMA2_STR1_IRQHandler + .thumb_set DMA2_STR1_IRQHandler,Default_Handler + + .weak DMA2_STR2_IRQHandler + .thumb_set DMA2_STR2_IRQHandler,Default_Handler + + .weak DMA2_STR3_IRQHandler + .thumb_set DMA2_STR3_IRQHandler,Default_Handler + + .weak DMA2_STR4_IRQHandler + .thumb_set DMA2_STR4_IRQHandler,Default_Handler + + .weak CAN2_TX_IRQHandler + .thumb_set CAN2_TX_IRQHandler,Default_Handler + + .weak CAN2_RX0_IRQHandler + .thumb_set CAN2_RX0_IRQHandler,Default_Handler + + .weak CAN2_RX1_IRQHandler + .thumb_set CAN2_RX1_IRQHandler,Default_Handler + + .weak CAN2_SCE_IRQHandler + .thumb_set CAN2_SCE_IRQHandler,Default_Handler + + .weak OTG_FS_IRQHandler + .thumb_set OTG_FS_IRQHandler,Default_Handler + + .weak DMA2_STR5_IRQHandler + .thumb_set DMA2_STR5_IRQHandler,Default_Handler + + .weak DMA2_STR6_IRQHandler + .thumb_set DMA2_STR6_IRQHandler,Default_Handler + + .weak DMA2_STR7_IRQHandler + .thumb_set DMA2_STR7_IRQHandler,Default_Handler + + .weak USART6_IRQHandler + .thumb_set USART6_IRQHandler,Default_Handler + + .weak I2C3_EV_IRQHandler + .thumb_set I2C3_EV_IRQHandler,Default_Handler + + .weak I2C3_ER_IRQHandler + .thumb_set I2C3_ER_IRQHandler,Default_Handler + + .weak RNG_IRQHandler + .thumb_set RNG_IRQHandler,Default_Handler + + .weak FPU_IRQHandler + .thumb_set FPU_IRQHandler,Default_Handler + + .weak QSPI_IRQHandler + .thumb_set QSPI_IRQHandler,Default_Handler + + .weak SPI4_IRQHandler + .thumb_set SPI4_IRQHandler,Default_Handler + + .weak SPI5_IRQHandler + .thumb_set SPI5_IRQHandler,Default_Handler diff --git a/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/gcc/startup_apm32f417xx.S b/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/gcc/startup_apm32f417xx.S new file mode 100644 index 0000000000..4052952fdc --- /dev/null +++ b/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/gcc/startup_apm32f417xx.S @@ -0,0 +1,497 @@ +/** + * @file startup_apm32f417xx.S + * + * @brief APM32F417xx Devices vector table for GCC based toolchains. + * This module performs: + * - Set the initial SP + * - Set the initial PC == Reset_Handler, + * - Set the vector table entries with the exceptions ISR address + * - Branches to main in the C library (which eventually + * calls main()). + * After Reset the Cortex-M4 processor is in Thread mode, + * priority is Privileged, and the Stack is set to Main. + * + * @version V1.0.0 + * + * @date 2023-07-31 + * + * @attention + * + * Copyright (C) 2023 Geehy Semiconductor + * + * You may not use this file except in compliance with the + * GEEHY COPYRIGHT NOTICE (GEEHY SOFTWARE PACKAGE LICENSE). + * + * The program is only for reference, which is distributed in the hope + * that it will be useful and instructional for customers to develop + * their software. Unless required by applicable law or agreed to in + * writing, the program is distributed on an "AS IS" BASIS, WITHOUT + * ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied. + * See the GEEHY SOFTWARE PACKAGE LICENSE for the governing permissions + * and limitations under the License. + */ + + .syntax unified + .cpu cortex-m4 + .fpu softvfp + .thumb + +.global g_apm32_Vectors +.global Default_Handler + +/* start address for the initialization values of the .data section. +defined in linker script */ +.word _start_address_init_data +/* start address for the .data section. defined in linker script */ +.word _start_address_data +/* end address for the .data section. defined in linker script */ +.word _end_address_data +/* start address for the .bss section. defined in linker script */ +.word _start_address_bss +/* end address for the .bss section. defined in linker script */ +.word _end_address_bss +/* stack used for SystemInit_ExtMemCtl; always internal RAM used */ + + .section .text.Reset_Handler + .weak Reset_Handler + .type Reset_Handler, %function +// Reset handler routine +Reset_Handler: + ldr sp, =_end_stack + +/* Copy the data segment initializers from flash to SRAM */ + ldr r0, =_start_address_data + ldr r1, =_end_address_data + ldr r2, =_start_address_init_data + movs r3, #0 + b L_loop0_0 + +L_loop0: + ldr r4, [r2, r3] + str r4, [r0, r3] + adds r3, r3, #4 + +L_loop0_0: + adds r4, r0, r3 + cmp r4, r1 + bcc L_loop0 + + ldr r2, =_start_address_bss + ldr r4, =_end_address_bss + movs r3, #0 + b L_loop1 + +L_loop2: + str r3, [r2] + adds r2, r2, #4 + +L_loop1: + cmp r2, r4 + bcc L_loop2 + + bl SystemInit + bl __libc_init_array + bl main + bx lr +.size Reset_Handler, .-Reset_Handler + +// This is the code that gets called when the processor receives an unexpected interrupt. + .section .text.Default_Handler,"ax",%progbits +Default_Handler: +Infinite_Loop: + b Infinite_Loop + .size Default_Handler, .-Default_Handler +// The minimal vector table for a Cortex M4. + .section .apm32_isr_vector,"a",%progbits + .type g_apm32_Vectors, %object + .size g_apm32_Vectors, .-g_apm32_Vectors + +// Vector Table Mapped to Address 0 at Reset +g_apm32_Vectors: + .word _end_stack // Top of Stack + .word Reset_Handler // Reset Handler + .word NMI_Handler // NMI Handler + .word HardFault_Handler // Hard Fault Handler + .word MemManage_Handler // MPU Fault Handler + .word BusFault_Handler // Bus Fault Handler + .word UsageFault_Handler // Usage Fault Handler + .word 0 // Reserved + .word 0 // Reserved + .word 0 // Reserved + .word 0 // Reserved + .word SVC_Handler // SVCall Handler + .word DebugMon_Handler // Debug Monitor Handler + .word 0 // Reserved + .word PendSV_Handler // PendSV Handler + .word SysTick_Handler // SysTick Handler + + /* External Interrupts */ + .word WWDT_IRQHandler // Window WatchDog + .word PVD_IRQHandler // PVD through EINT Line detection + .word TAMP_STAMP_IRQHandler // Tamper and TimeStamps through the EINT line + .word RTC_WKUP_IRQHandler // RTC Wakeup through the EINT line + .word FLASH_IRQHandler // FLASH + .word RCM_IRQHandler // RCM + .word EINT0_IRQHandler // EINT Line0 + .word EINT1_IRQHandler // EINT Line1 + .word EINT2_IRQHandler // EINT Line2 + .word EINT3_IRQHandler // EINT Line3 + .word EINT4_IRQHandler // EINT Line4 + .word DMA1_STR0_IRQHandler // DMA1 Stream 0 + .word DMA1_STR1_IRQHandler // DMA1 Stream 1 + .word DMA1_STR2_IRQHandler // DMA1 Stream 2 + .word DMA1_STR3_IRQHandler // DMA1 Stream 3 + .word DMA1_STR4_IRQHandler // DMA1 Stream 4 + .word DMA1_STR5_IRQHandler // DMA1 Stream 5 + .word DMA1_STR6_IRQHandler // DMA1 Stream 6 + .word ADC_IRQHandler // ADC1, ADC2 and ADC3s + .word CAN1_TX_IRQHandler // CAN1 TX + .word CAN1_RX0_IRQHandler // CAN1 RX0 + .word CAN1_RX1_IRQHandler // CAN1 RX1 + .word CAN1_SCE_IRQHandler // CAN1 SCE + .word EINT9_5_IRQHandler // External Line[9:5]s + .word TMR1_BRK_TMR9_IRQHandler // TMR1 Break and TMR9 + .word TMR1_UP_TMR10_IRQHandler // TMR1 Update and TMR10 + .word TMR1_TRG_COM_TMR11_IRQHandler // TMR1 Trigger and Commutation and TMR11 + .word TMR1_CC_IRQHandler // TMR1 Capture Compare + .word TMR2_IRQHandler // TMR2 + .word TMR3_IRQHandler // TMR3 + .word TMR4_IRQHandler // TMR4 + .word I2C1_EV_IRQHandler // I2C1 Event + .word I2C1_ER_IRQHandler // I2C1 Error + .word I2C2_EV_IRQHandler // I2C2 Event + .word I2C2_ER_IRQHandler // I2C2 Error + .word SPI1_IRQHandler // SPI1 + .word SPI2_IRQHandler // SPI2 + .word USART1_IRQHandler // USART1 + .word USART2_IRQHandler // USART2 + .word USART3_IRQHandler // USART3 + .word EINT15_10_IRQHandler // External Line[15:10]s + .word RTC_Alarm_IRQHandler // RTC Alarm (A and B) through EINT Line + .word OTG_FS_WKUP_IRQHandler // USB OTG FS Wakeup through EINT line + .word TMR8_BRK_TMR12_IRQHandler // TMR8 Break and TMR12 + .word TMR8_UP_TMR13_IRQHandler // TMR8 Update and TMR13 + .word TMR8_TRG_COM_TMR14_IRQHandler // TMR8 Trigger and Commutation and TMR14 + .word TMR8_CC_IRQHandler // TMR8 Capture Compare + .word DMA1_STR7_IRQHandler // DMA1 Stream7 + .word EMMC_IRQHandler // EMMC + .word SDIO_IRQHandler // SDIO + .word TMR5_IRQHandler // TMR5 + .word SPI3_IRQHandler // SPI3 + .word UART4_IRQHandler // UART4 + .word UART5_IRQHandler // UART5 + .word TMR6_DAC_IRQHandler // TMR6 and DAC1&2 underrun errors + .word TMR7_IRQHandler // TMR7 + .word DMA2_STR0_IRQHandler // DMA2 Stream 0 + .word DMA2_STR1_IRQHandler // DMA2 Stream 1 + .word DMA2_STR2_IRQHandler // DMA2 Stream 2 + .word DMA2_STR3_IRQHandler // DMA2 Stream 3 + .word DMA2_STR4_IRQHandler // DMA2 Stream 4 + .word ETH_IRQHandler // Ethernet + .word ETH_WKUP_IRQHandler // Ethernet Wakeup through EINT line + .word CAN2_TX_IRQHandler // CAN2 TX + .word CAN2_RX0_IRQHandler // CAN2 RX0 + .word CAN2_RX1_IRQHandler // CAN2 RX1 + .word CAN2_SCE_IRQHandler // CAN2 SCE + .word OTG_FS_IRQHandler // USB OTG FS + .word DMA2_STR5_IRQHandler // DMA2 Stream 5 + .word DMA2_STR6_IRQHandler // DMA2 Stream 6 + .word DMA2_STR7_IRQHandler // DMA2 Stream 7 + .word USART6_IRQHandler // USART6 + .word I2C3_EV_IRQHandler // I2C3 event + .word I2C3_ER_IRQHandler // I2C3 error + .word OTG_HS1_EP1_OUT_IRQHandler // USB OTG HS End Point 1 Out + .word OTG_HS1_EP1_IN_IRQHandler // USB OTG HS End Point 1 In + .word OTG_HS1_WKUP_IRQHandler // USB OTG HS Wakeup through EINT + .word OTG_HS1_IRQHandler // USB OTG HS + .word DCI_IRQHandler // DCI + .word CRYP_IRQHandler // CRYP crypto + .word HASH_RNG_IRQHandler // Hash and Rng + .word FPU_IRQHandler // FPU + .word SM3_IRQHandler // SM3 + .word SM4_IRQHandler // SM4 + .word BN_IRQHandler // BN + +// Default exception/interrupt handler + + .weak NMI_Handler + .thumb_set NMI_Handler,Default_Handler + + .weak HardFault_Handler + .thumb_set HardFault_Handler,Default_Handler + + .weak MemManage_Handler + .thumb_set MemManage_Handler,Default_Handler + + .weak BusFault_Handler + .thumb_set BusFault_Handler,Default_Handler + + .weak UsageFault_Handler + .thumb_set UsageFault_Handler,Default_Handler + + .weak SVC_Handler + .thumb_set SVC_Handler,Default_Handler + + .weak DebugMon_Handler + .thumb_set DebugMon_Handler,Default_Handler + + .weak PendSV_Handler + .thumb_set PendSV_Handler,Default_Handler + + .weak SysTick_Handler + .thumb_set SysTick_Handler,Default_Handler + + .weak WWDT_IRQHandler + .thumb_set WWDT_IRQHandler,Default_Handler + + .weak PVD_IRQHandler + .thumb_set PVD_IRQHandler,Default_Handler + + .weak TAMP_STAMP_IRQHandler + .thumb_set TAMP_STAMP_IRQHandler,Default_Handler + + .weak RTC_WKUP_IRQHandler + .thumb_set RTC_WKUP_IRQHandler,Default_Handler + + .weak FLASH_IRQHandler + .thumb_set FLASH_IRQHandler,Default_Handler + + .weak RCM_IRQHandler + .thumb_set RCM_IRQHandler,Default_Handler + + .weak EINT0_IRQHandler + .thumb_set EINT0_IRQHandler,Default_Handler + + .weak EINT1_IRQHandler + .thumb_set EINT1_IRQHandler,Default_Handler + + .weak EINT2_IRQHandler + .thumb_set EINT2_IRQHandler,Default_Handler + + .weak EINT3_IRQHandler + .thumb_set EINT3_IRQHandler,Default_Handler + + .weak EINT4_IRQHandler + .thumb_set EINT4_IRQHandler,Default_Handler + + .weak DMA1_STR0_IRQHandler + .thumb_set DMA1_STR0_IRQHandler,Default_Handler + + .weak DMA1_STR1_IRQHandler + .thumb_set DMA1_STR1_IRQHandler,Default_Handler + + .weak DMA1_STR2_IRQHandler + .thumb_set DMA1_STR2_IRQHandler,Default_Handler + + .weak DMA1_STR3_IRQHandler + .thumb_set DMA1_STR3_IRQHandler,Default_Handler + + .weak DMA1_STR4_IRQHandler + .thumb_set DMA1_STR4_IRQHandler,Default_Handler + + .weak DMA1_STR5_IRQHandler + .thumb_set DMA1_STR5_IRQHandler,Default_Handler + + .weak DMA1_STR6_IRQHandler + .thumb_set DMA1_STR6_IRQHandler,Default_Handler + + .weak ADC_IRQHandler + .thumb_set ADC_IRQHandler,Default_Handler + + .weak CAN1_TX_IRQHandler + .thumb_set CAN1_TX_IRQHandler,Default_Handler + + .weak CAN1_RX0_IRQHandler + .thumb_set CAN1_RX0_IRQHandler,Default_Handler + + .weak CAN1_RX1_IRQHandler + .thumb_set CAN1_RX1_IRQHandler,Default_Handler + + .weak CAN1_SCE_IRQHandler + .thumb_set CAN1_SCE_IRQHandler,Default_Handler + + .weak EINT9_5_IRQHandler + .thumb_set EINT9_5_IRQHandler,Default_Handler + + .weak TMR1_BRK_TMR9_IRQHandler + .thumb_set TMR1_BRK_TMR9_IRQHandler,Default_Handler + + .weak TMR1_UP_TMR10_IRQHandler + .thumb_set TMR1_UP_TMR10_IRQHandler,Default_Handler + + .weak TMR1_TRG_COM_TMR11_IRQHandler + .thumb_set TMR1_TRG_COM_TMR11_IRQHandler,Default_Handler + + .weak TMR1_CC_IRQHandler + .thumb_set TMR1_CC_IRQHandler,Default_Handler + + .weak TMR2_IRQHandler + .thumb_set TMR2_IRQHandler,Default_Handler + + .weak TMR3_IRQHandler + .thumb_set TMR3_IRQHandler,Default_Handler + + .weak TMR4_IRQHandler + .thumb_set TMR4_IRQHandler,Default_Handler + + .weak I2C1_EV_IRQHandler + .thumb_set I2C1_EV_IRQHandler,Default_Handler + + .weak I2C1_ER_IRQHandler + .thumb_set I2C1_ER_IRQHandler,Default_Handler + + .weak I2C2_EV_IRQHandler + .thumb_set I2C2_EV_IRQHandler,Default_Handler + + .weak I2C2_ER_IRQHandler + .thumb_set I2C2_ER_IRQHandler,Default_Handler + + .weak SPI1_IRQHandler + .thumb_set SPI1_IRQHandler,Default_Handler + + .weak SPI2_IRQHandler + .thumb_set SPI2_IRQHandler,Default_Handler + + .weak USART1_IRQHandler + .thumb_set USART1_IRQHandler,Default_Handler + + .weak USART2_IRQHandler + .thumb_set USART2_IRQHandler,Default_Handler + + .weak USART3_IRQHandler + .thumb_set USART3_IRQHandler,Default_Handler + + .weak EINT15_10_IRQHandler + .thumb_set EINT15_10_IRQHandler,Default_Handler + + .weak RTC_Alarm_IRQHandler + .thumb_set RTC_Alarm_IRQHandler,Default_Handler + + .weak OTG_FS_WKUP_IRQHandler + .thumb_set OTG_FS_WKUP_IRQHandler,Default_Handler + + .weak TMR8_BRK_TMR12_IRQHandler + .thumb_set TMR8_BRK_TMR12_IRQHandler,Default_Handler + + .weak TMR8_UP_TMR13_IRQHandler + .thumb_set TMR8_UP_TMR13_IRQHandler,Default_Handler + + .weak TMR8_TRG_COM_TMR14_IRQHandler + .thumb_set TMR8_TRG_COM_TMR14_IRQHandler,Default_Handler + + .weak TMR8_CC_IRQHandler + .thumb_set TMR8_CC_IRQHandler,Default_Handler + + .weak DMA1_STR7_IRQHandler + .thumb_set DMA1_STR7_IRQHandler,Default_Handler + + .weak EMMC_IRQHandler + .thumb_set EMMC_IRQHandler,Default_Handler + + .weak SDIO_IRQHandler + .thumb_set SDIO_IRQHandler,Default_Handler + + .weak TMR5_IRQHandler + .thumb_set TMR5_IRQHandler,Default_Handler + + .weak SPI3_IRQHandler + .thumb_set SPI3_IRQHandler,Default_Handler + + .weak UART4_IRQHandler + .thumb_set UART4_IRQHandler,Default_Handler + + .weak UART5_IRQHandler + .thumb_set UART5_IRQHandler,Default_Handler + + .weak TMR6_DAC_IRQHandler + .thumb_set TMR6_DAC_IRQHandler,Default_Handler + + .weak TMR7_IRQHandler + .thumb_set TMR7_IRQHandler,Default_Handler + + .weak DMA2_STR0_IRQHandler + .thumb_set DMA2_STR0_IRQHandler,Default_Handler + + .weak DMA2_STR1_IRQHandler + .thumb_set DMA2_STR1_IRQHandler,Default_Handler + + .weak DMA2_STR2_IRQHandler + .thumb_set DMA2_STR2_IRQHandler,Default_Handler + + .weak DMA2_STR3_IRQHandler + .thumb_set DMA2_STR3_IRQHandler,Default_Handler + + .weak DMA2_STR4_IRQHandler + .thumb_set DMA2_STR4_IRQHandler,Default_Handler + + .weak ETH_IRQHandler + .thumb_set ETH_IRQHandler,Default_Handler + + .weak ETH_WKUP_IRQHandler + .thumb_set ETH_WKUP_IRQHandler,Default_Handler + + .weak CAN2_TX_IRQHandler + .thumb_set CAN2_TX_IRQHandler,Default_Handler + + .weak CAN2_RX0_IRQHandler + .thumb_set CAN2_RX0_IRQHandler,Default_Handler + + .weak CAN2_RX1_IRQHandler + .thumb_set CAN2_RX1_IRQHandler,Default_Handler + + .weak CAN2_SCE_IRQHandler + .thumb_set CAN2_SCE_IRQHandler,Default_Handler + + .weak OTG_FS_IRQHandler + .thumb_set OTG_FS_IRQHandler,Default_Handler + + .weak DMA2_STR5_IRQHandler + .thumb_set DMA2_STR5_IRQHandler,Default_Handler + + .weak DMA2_STR6_IRQHandler + .thumb_set DMA2_STR6_IRQHandler,Default_Handler + + .weak DMA2_STR7_IRQHandler + .thumb_set DMA2_STR7_IRQHandler,Default_Handler + + .weak USART6_IRQHandler + .thumb_set USART6_IRQHandler,Default_Handler + + .weak I2C3_EV_IRQHandler + .thumb_set I2C3_EV_IRQHandler,Default_Handler + + .weak I2C3_ER_IRQHandler + .thumb_set I2C3_ER_IRQHandler,Default_Handler + + .weak OTG_HS1_EP1_OUT_IRQHandler + .thumb_set OTG_HS1_EP1_OUT_IRQHandler,Default_Handler + + .weak OTG_HS1_EP1_IN_IRQHandler + .thumb_set OTG_HS1_EP1_IN_IRQHandler,Default_Handler + + .weak OTG_HS1_WKUP_IRQHandler + .thumb_set OTG_HS1_WKUP_IRQHandler,Default_Handler + + .weak OTG_HS1_IRQHandler + .thumb_set OTG_HS1_IRQHandler,Default_Handler + + .weak DCI_IRQHandler + .thumb_set DCI_IRQHandler,Default_Handler + + .weak CRYP_IRQHandler + .thumb_set CRYP_IRQHandler,Default_Handler + + .weak HASH_RNG_IRQHandler + .thumb_set HASH_RNG_IRQHandler,Default_Handler + + .weak FPU_IRQHandler + .thumb_set FPU_IRQHandler,Default_Handler + + .weak SM3_IRQHandler + .thumb_set SM3_IRQHandler,Default_Handler + + .weak SM4_IRQHandler + .thumb_set SM4_IRQHandler,Default_Handler + + .weak BN_IRQHandler + .thumb_set BN_IRQHandler,Default_Handler diff --git a/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/gcc/startup_apm32f465xx.S b/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/gcc/startup_apm32f465xx.S new file mode 100644 index 0000000000..68c5636540 --- /dev/null +++ b/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/gcc/startup_apm32f465xx.S @@ -0,0 +1,485 @@ +/** + * @file startup_apm32f465xx.S + * + * @brief APM32F465xx Devices vector table for GCC based toolchains. + * This module performs: + * - Set the initial SP + * - Set the initial PC == Reset_Handler, + * - Set the vector table entries with the exceptions ISR address + * - Branches to main in the C library (which eventually + * calls main()). + * After Reset the Cortex-M4 processor is in Thread mode, + * priority is Privileged, and the Stack is set to Main. + * + * @version V1.0.0 + * + * @date 2023-12-01 + * + * @attention + * + * Copyright (C) 2023 Geehy Semiconductor + * + * You may not use this file except in compliance with the + * GEEHY COPYRIGHT NOTICE (GEEHY SOFTWARE PACKAGE LICENSE). + * + * The program is only for reference, which is distributed in the hope + * that it will be useful and instructional for customers to develop + * their software. Unless required by applicable law or agreed to in + * writing, the program is distributed on an "AS IS" BASIS, WITHOUT + * ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied. + * See the GEEHY SOFTWARE PACKAGE LICENSE for the governing permissions + * and limitations under the License. + */ + + .syntax unified + .cpu cortex-m4 + .fpu softvfp + .thumb + +.global g_apm32_Vectors +.global Default_Handler + +/* start address for the initialization values of the .data section. +defined in linker script */ +.word _start_address_init_data +/* start address for the .data section. defined in linker script */ +.word _start_address_data +/* end address for the .data section. defined in linker script */ +.word _end_address_data +/* start address for the .bss section. defined in linker script */ +.word _start_address_bss +/* end address for the .bss section. defined in linker script */ +.word _end_address_bss +/* stack used for SystemInit_ExtMemCtl; always internal RAM used */ + + .section .text.Reset_Handler + .weak Reset_Handler + .type Reset_Handler, %function +// Reset handler routine +Reset_Handler: + ldr sp, =_end_stack + +/* Copy the data segment initializers from flash to SRAM */ + ldr r0, =_start_address_data + ldr r1, =_end_address_data + ldr r2, =_start_address_init_data + movs r3, #0 + b L_loop0_0 + +L_loop0: + ldr r4, [r2, r3] + str r4, [r0, r3] + adds r3, r3, #4 + +L_loop0_0: + adds r4, r0, r3 + cmp r4, r1 + bcc L_loop0 + + ldr r2, =_start_address_bss + ldr r4, =_end_address_bss + movs r3, #0 + b L_loop1 + +L_loop2: + str r3, [r2] + adds r2, r2, #4 + +L_loop1: + cmp r2, r4 + bcc L_loop2 + + bl SystemInit + bl __libc_init_array + bl main + bx lr +.size Reset_Handler, .-Reset_Handler + +// This is the code that gets called when the processor receives an unexpected interrupt. + .section .text.Default_Handler,"ax",%progbits +Default_Handler: +Infinite_Loop: + b Infinite_Loop + .size Default_Handler, .-Default_Handler +// The minimal vector table for a Cortex M4. + .section .apm32_isr_vector,"a",%progbits + .type g_apm32_Vectors, %object + .size g_apm32_Vectors, .-g_apm32_Vectors + +// Vector Table Mapped to Address 0 at Reset +g_apm32_Vectors: + .word _end_stack // Top of Stack + .word Reset_Handler // Reset Handler + .word NMI_Handler // NMI Handler + .word HardFault_Handler // Hard Fault Handler + .word MemManage_Handler // MPU Fault Handler + .word BusFault_Handler // Bus Fault Handler + .word UsageFault_Handler // Usage Fault Handler + .word 0 // Reserved + .word 0 // Reserved + .word 0 // Reserved + .word 0 // Reserved + .word SVC_Handler // SVCall Handler + .word DebugMon_Handler // Debug Monitor Handler + .word 0 // Reserved + .word PendSV_Handler // PendSV Handler + .word SysTick_Handler // SysTick Handler + + /* External Interrupts */ + .word WWDT_IRQHandler // Window WatchDog + .word PVD_IRQHandler // PVD through EINT Line detection + .word TAMP_STAMP_IRQHandler // Tamper and TimeStamps through the EINT line + .word RTC_WKUP_IRQHandler // RTC Wakeup through the EINT line + .word FLASH_IRQHandler // FLASH + .word RCM_IRQHandler // RCM + .word EINT0_IRQHandler // EINT Line0 + .word EINT1_IRQHandler // EINT Line1 + .word EINT2_IRQHandler // EINT Line2 + .word EINT3_IRQHandler // EINT Line3 + .word EINT4_IRQHandler // EINT Line4 + .word DMA1_STR0_IRQHandler // DMA1 Stream 0 + .word DMA1_STR1_IRQHandler // DMA1 Stream 1 + .word DMA1_STR2_IRQHandler // DMA1 Stream 2 + .word DMA1_STR3_IRQHandler // DMA1 Stream 3 + .word DMA1_STR4_IRQHandler // DMA1 Stream 4 + .word DMA1_STR5_IRQHandler // DMA1 Stream 5 + .word DMA1_STR6_IRQHandler // DMA1 Stream 6 + .word ADC_IRQHandler // ADC1, ADC2 and ADC3s + .word CAN1_TX_IRQHandler // CAN1 TX + .word CAN1_RX0_IRQHandler // CAN1 RX0 + .word CAN1_RX1_IRQHandler // CAN1 RX1 + .word CAN1_SCE_IRQHandler // CAN1 SCE + .word EINT9_5_IRQHandler // External Line[9:5]s + .word TMR1_BRK_TMR9_IRQHandler // TMR1 Break and TMR9 + .word TMR1_UP_TMR10_IRQHandler // TMR1 Update and TMR10 + .word TMR1_TRG_COM_TMR11_IRQHandler // TMR1 Trigger and Commutation and TMR11 + .word TMR1_CC_IRQHandler // TMR1 Capture Compare + .word TMR2_IRQHandler // TMR2 + .word TMR3_IRQHandler // TMR3 + .word TMR4_IRQHandler // TMR4 + .word I2C1_EV_IRQHandler // I2C1 Event + .word I2C1_ER_IRQHandler // I2C1 Error + .word I2C2_EV_IRQHandler // I2C2 Event + .word I2C2_ER_IRQHandler // I2C2 Error + .word SPI1_IRQHandler // SPI1 + .word SPI2_IRQHandler // SPI2 + .word USART1_IRQHandler // USART1 + .word USART2_IRQHandler // USART2 + .word USART3_IRQHandler // USART3 + .word EINT15_10_IRQHandler // External Line[15:10]s + .word RTC_Alarm_IRQHandler // RTC Alarm (A and B) through EINT Line + .word OTG_FS_WKUP_IRQHandler // USB OTG FS Wakeup through EINT line + .word TMR8_BRK_TMR12_IRQHandler // TMR8 Break and TMR12 + .word TMR8_UP_TMR13_IRQHandler // TMR8 Update and TMR13 + .word TMR8_TRG_COM_TMR14_IRQHandler // TMR8 Trigger and Commutation and TMR14 + .word TMR8_CC_IRQHandler // TMR8 Capture Compare + .word DMA1_STR7_IRQHandler // DMA1 Stream7 + .word SMC_IRQHandler // SMC + .word SDIO_IRQHandler // SDIO + .word TMR5_IRQHandler // TMR5 + .word SPI3_IRQHandler // SPI3 + .word UART4_IRQHandler // UART4 + .word UART5_IRQHandler // UART5 + .word TMR6_DAC_IRQHandler // TMR6 and DAC1&2 underrun errors + .word TMR7_IRQHandler // TMR7 + .word DMA2_STR0_IRQHandler // DMA2 Stream 0 + .word DMA2_STR1_IRQHandler // DMA2 Stream 1 + .word DMA2_STR2_IRQHandler // DMA2 Stream 2 + .word DMA2_STR3_IRQHandler // DMA2 Stream 3 + .word DMA2_STR4_IRQHandler // DMA2 Stream 4 + .word 0 // Reserved + .word 0 // Reserved + .word CAN2_TX_IRQHandler // CAN2 TX + .word CAN2_RX0_IRQHandler // CAN2 RX0 + .word CAN2_RX1_IRQHandler // CAN2 RX1 + .word CAN2_SCE_IRQHandler // CAN2 SCE + .word OTG_FS_IRQHandler // USB OTG FS + .word DMA2_STR5_IRQHandler // DMA2 Stream 5 + .word DMA2_STR6_IRQHandler // DMA2 Stream 6 + .word DMA2_STR7_IRQHandler // DMA2 Stream 7 + .word USART6_IRQHandler // USART6 + .word I2C3_EV_IRQHandler // I2C3 event + .word I2C3_ER_IRQHandler // I2C3 error + .word OTG_HS1_EP1_OUT_IRQHandler // USB OTG HS End Point 1 Out + .word OTG_HS1_EP1_IN_IRQHandler // USB OTG HS End Point 1 In + .word OTG_HS1_WKUP_IRQHandler // USB OTG HS Wakeup through EINT + .word OTG_HS1_IRQHandler // USB OTG HS + .word 0 // Reserved + .word 0 // Reserved + .word RNG_IRQHandler // RNG + .word FPU_IRQHandler // FPU + .word SM3_IRQHandler // SM3 + .word SM4_IRQHandler // SM4 + .word BN_IRQHandler // BN + +// Default exception/interrupt handler + + .weak NMI_Handler + .thumb_set NMI_Handler,Default_Handler + + .weak HardFault_Handler + .thumb_set HardFault_Handler,Default_Handler + + .weak MemManage_Handler + .thumb_set MemManage_Handler,Default_Handler + + .weak BusFault_Handler + .thumb_set BusFault_Handler,Default_Handler + + .weak UsageFault_Handler + .thumb_set UsageFault_Handler,Default_Handler + + .weak SVC_Handler + .thumb_set SVC_Handler,Default_Handler + + .weak DebugMon_Handler + .thumb_set DebugMon_Handler,Default_Handler + + .weak PendSV_Handler + .thumb_set PendSV_Handler,Default_Handler + + .weak SysTick_Handler + .thumb_set SysTick_Handler,Default_Handler + + .weak WWDT_IRQHandler + .thumb_set WWDT_IRQHandler,Default_Handler + + .weak PVD_IRQHandler + .thumb_set PVD_IRQHandler,Default_Handler + + .weak TAMP_STAMP_IRQHandler + .thumb_set TAMP_STAMP_IRQHandler,Default_Handler + + .weak RTC_WKUP_IRQHandler + .thumb_set RTC_WKUP_IRQHandler,Default_Handler + + .weak FLASH_IRQHandler + .thumb_set FLASH_IRQHandler,Default_Handler + + .weak RCM_IRQHandler + .thumb_set RCM_IRQHandler,Default_Handler + + .weak EINT0_IRQHandler + .thumb_set EINT0_IRQHandler,Default_Handler + + .weak EINT1_IRQHandler + .thumb_set EINT1_IRQHandler,Default_Handler + + .weak EINT2_IRQHandler + .thumb_set EINT2_IRQHandler,Default_Handler + + .weak EINT3_IRQHandler + .thumb_set EINT3_IRQHandler,Default_Handler + + .weak EINT4_IRQHandler + .thumb_set EINT4_IRQHandler,Default_Handler + + .weak DMA1_STR0_IRQHandler + .thumb_set DMA1_STR0_IRQHandler,Default_Handler + + .weak DMA1_STR1_IRQHandler + .thumb_set DMA1_STR1_IRQHandler,Default_Handler + + .weak DMA1_STR2_IRQHandler + .thumb_set DMA1_STR2_IRQHandler,Default_Handler + + .weak DMA1_STR3_IRQHandler + .thumb_set DMA1_STR3_IRQHandler,Default_Handler + + .weak DMA1_STR4_IRQHandler + .thumb_set DMA1_STR4_IRQHandler,Default_Handler + + .weak DMA1_STR5_IRQHandler + .thumb_set DMA1_STR5_IRQHandler,Default_Handler + + .weak DMA1_STR6_IRQHandler + .thumb_set DMA1_STR6_IRQHandler,Default_Handler + + .weak ADC_IRQHandler + .thumb_set ADC_IRQHandler,Default_Handler + + .weak CAN1_TX_IRQHandler + .thumb_set CAN1_TX_IRQHandler,Default_Handler + + .weak CAN1_RX0_IRQHandler + .thumb_set CAN1_RX0_IRQHandler,Default_Handler + + .weak CAN1_RX1_IRQHandler + .thumb_set CAN1_RX1_IRQHandler,Default_Handler + + .weak CAN1_SCE_IRQHandler + .thumb_set CAN1_SCE_IRQHandler,Default_Handler + + .weak EINT9_5_IRQHandler + .thumb_set EINT9_5_IRQHandler,Default_Handler + + .weak TMR1_BRK_TMR9_IRQHandler + .thumb_set TMR1_BRK_TMR9_IRQHandler,Default_Handler + + .weak TMR1_UP_TMR10_IRQHandler + .thumb_set TMR1_UP_TMR10_IRQHandler,Default_Handler + + .weak TMR1_TRG_COM_TMR11_IRQHandler + .thumb_set TMR1_TRG_COM_TMR11_IRQHandler,Default_Handler + + .weak TMR1_CC_IRQHandler + .thumb_set TMR1_CC_IRQHandler,Default_Handler + + .weak TMR2_IRQHandler + .thumb_set TMR2_IRQHandler,Default_Handler + + .weak TMR3_IRQHandler + .thumb_set TMR3_IRQHandler,Default_Handler + + .weak TMR4_IRQHandler + .thumb_set TMR4_IRQHandler,Default_Handler + + .weak I2C1_EV_IRQHandler + .thumb_set I2C1_EV_IRQHandler,Default_Handler + + .weak I2C1_ER_IRQHandler + .thumb_set I2C1_ER_IRQHandler,Default_Handler + + .weak I2C2_EV_IRQHandler + .thumb_set I2C2_EV_IRQHandler,Default_Handler + + .weak I2C2_ER_IRQHandler + .thumb_set I2C2_ER_IRQHandler,Default_Handler + + .weak SPI1_IRQHandler + .thumb_set SPI1_IRQHandler,Default_Handler + + .weak SPI2_IRQHandler + .thumb_set SPI2_IRQHandler,Default_Handler + + .weak USART1_IRQHandler + .thumb_set USART1_IRQHandler,Default_Handler + + .weak USART2_IRQHandler + .thumb_set USART2_IRQHandler,Default_Handler + + .weak USART3_IRQHandler + .thumb_set USART3_IRQHandler,Default_Handler + + .weak EINT15_10_IRQHandler + .thumb_set EINT15_10_IRQHandler,Default_Handler + + .weak RTC_Alarm_IRQHandler + .thumb_set RTC_Alarm_IRQHandler,Default_Handler + + .weak OTG_FS_WKUP_IRQHandler + .thumb_set OTG_FS_WKUP_IRQHandler,Default_Handler + + .weak TMR8_BRK_TMR12_IRQHandler + .thumb_set TMR8_BRK_TMR12_IRQHandler,Default_Handler + + .weak TMR8_UP_TMR13_IRQHandler + .thumb_set TMR8_UP_TMR13_IRQHandler,Default_Handler + + .weak TMR8_TRG_COM_TMR14_IRQHandler + .thumb_set TMR8_TRG_COM_TMR14_IRQHandler,Default_Handler + + .weak TMR8_CC_IRQHandler + .thumb_set TMR8_CC_IRQHandler,Default_Handler + + .weak DMA1_STR7_IRQHandler + .thumb_set DMA1_STR7_IRQHandler,Default_Handler + + .weak SMC_IRQHandler + .thumb_set SMC_IRQHandler,Default_Handler + + .weak SDIO_IRQHandler + .thumb_set SDIO_IRQHandler,Default_Handler + + .weak TMR5_IRQHandler + .thumb_set TMR5_IRQHandler,Default_Handler + + .weak SPI3_IRQHandler + .thumb_set SPI3_IRQHandler,Default_Handler + + .weak UART4_IRQHandler + .thumb_set UART4_IRQHandler,Default_Handler + + .weak UART5_IRQHandler + .thumb_set UART5_IRQHandler,Default_Handler + + .weak TMR6_DAC_IRQHandler + .thumb_set TMR6_DAC_IRQHandler,Default_Handler + + .weak TMR7_IRQHandler + .thumb_set TMR7_IRQHandler,Default_Handler + + .weak DMA2_STR0_IRQHandler + .thumb_set DMA2_STR0_IRQHandler,Default_Handler + + .weak DMA2_STR1_IRQHandler + .thumb_set DMA2_STR1_IRQHandler,Default_Handler + + .weak DMA2_STR2_IRQHandler + .thumb_set DMA2_STR2_IRQHandler,Default_Handler + + .weak DMA2_STR3_IRQHandler + .thumb_set DMA2_STR3_IRQHandler,Default_Handler + + .weak DMA2_STR4_IRQHandler + .thumb_set DMA2_STR4_IRQHandler,Default_Handler + + .weak CAN2_TX_IRQHandler + .thumb_set CAN2_TX_IRQHandler,Default_Handler + + .weak CAN2_RX0_IRQHandler + .thumb_set CAN2_RX0_IRQHandler,Default_Handler + + .weak CAN2_RX1_IRQHandler + .thumb_set CAN2_RX1_IRQHandler,Default_Handler + + .weak CAN2_SCE_IRQHandler + .thumb_set CAN2_SCE_IRQHandler,Default_Handler + + .weak OTG_FS_IRQHandler + .thumb_set OTG_FS_IRQHandler,Default_Handler + + .weak DMA2_STR5_IRQHandler + .thumb_set DMA2_STR5_IRQHandler,Default_Handler + + .weak DMA2_STR6_IRQHandler + .thumb_set DMA2_STR6_IRQHandler,Default_Handler + + .weak DMA2_STR7_IRQHandler + .thumb_set DMA2_STR7_IRQHandler,Default_Handler + + .weak USART6_IRQHandler + .thumb_set USART6_IRQHandler,Default_Handler + + .weak I2C3_EV_IRQHandler + .thumb_set I2C3_EV_IRQHandler,Default_Handler + + .weak I2C3_ER_IRQHandler + .thumb_set I2C3_ER_IRQHandler,Default_Handler + + .weak OTG_HS1_EP1_OUT_IRQHandler + .thumb_set OTG_HS1_EP1_OUT_IRQHandler,Default_Handler + + .weak OTG_HS1_EP1_IN_IRQHandler + .thumb_set OTG_HS1_EP1_IN_IRQHandler,Default_Handler + + .weak OTG_HS1_WKUP_IRQHandler + .thumb_set OTG_HS1_WKUP_IRQHandler,Default_Handler + + .weak OTG_HS1_IRQHandler + .thumb_set OTG_HS1_IRQHandler,Default_Handler + + .weak RNG_IRQHandler + .thumb_set RNG_IRQHandler,Default_Handler + + .weak FPU_IRQHandler + .thumb_set FPU_IRQHandler,Default_Handler + + .weak SM3_IRQHandler + .thumb_set SM3_IRQHandler,Default_Handler + + .weak SM4_IRQHandler + .thumb_set SM4_IRQHandler,Default_Handler + + .weak BN_IRQHandler + .thumb_set BN_IRQHandler,Default_Handler diff --git a/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/iar/apm32f405xG.icf b/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/iar/apm32f405xG.icf new file mode 100644 index 0000000000..eca26d5fd2 --- /dev/null +++ b/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/iar/apm32f405xG.icf @@ -0,0 +1,172 @@ +/*###ICF### Section handled by ICF editor, don't touch! ****/ +/*-Editor annotation file-*/ +/* IcfEditorFile="$TOOLKIT_DIR$\config\ide\IcfEditor\cortex_v1_4.xml" */ +/*-Specials-*/ +define symbol __ICFEDIT_intvec_start__ = 0x08000000; +/*-Memory Regions-*/ +define symbol __ICFEDIT_region_IROM1_start__ = 0x08000000; +define symbol __ICFEDIT_region_IROM1_end__ = 0x080FFFFF; +define symbol __ICFEDIT_region_IROM2_start__ = 0x0; +define symbol __ICFEDIT_region_IROM2_end__ = 0x0; +define symbol __ICFEDIT_region_EROM1_start__ = 0x0; +define symbol __ICFEDIT_region_EROM1_end__ = 0x0; +define symbol __ICFEDIT_region_EROM2_start__ = 0x0; +define symbol __ICFEDIT_region_EROM2_end__ = 0x0; +define symbol __ICFEDIT_region_EROM3_start__ = 0x0; +define symbol __ICFEDIT_region_EROM3_end__ = 0x0; +define symbol __ICFEDIT_region_IRAM1_start__ = 0x20000000; +define symbol __ICFEDIT_region_IRAM1_end__ = 0x2001FFFF; +define symbol __ICFEDIT_region_IRAM2_start__ = 0x10000000; +define symbol __ICFEDIT_region_IRAM2_end__ = 0x1000FFFF; +define symbol __ICFEDIT_region_ERAM1_start__ = 0x0; +define symbol __ICFEDIT_region_ERAM1_end__ = 0x0; +define symbol __ICFEDIT_region_ERAM2_start__ = 0x0; +define symbol __ICFEDIT_region_ERAM2_end__ = 0x0; +define symbol __ICFEDIT_region_ERAM3_start__ = 0x0; +define symbol __ICFEDIT_region_ERAM3_end__ = 0x0; +/*-Sizes-*/ +define symbol __ICFEDIT_size_cstack__ = 0x400; +define symbol __ICFEDIT_size_proc_stack__ = 0x0; +define symbol __ICFEDIT_size_heap__ = 0x800; +/**** End of ICF editor section. ###ICF###*/ + +define memory mem with size = 4G; +define symbol use_IROM1 = (__ICFEDIT_region_IROM1_start__ != 0x0 || __ICFEDIT_region_IROM1_end__ != 0x0); +define symbol use_IROM2 = (__ICFEDIT_region_IROM2_start__ != 0x0 || __ICFEDIT_region_IROM2_end__ != 0x0); +define symbol use_EROM1 = (__ICFEDIT_region_EROM1_start__ != 0x0 || __ICFEDIT_region_EROM1_end__ != 0x0); +define symbol use_EROM2 = (__ICFEDIT_region_EROM2_start__ != 0x0 || __ICFEDIT_region_EROM2_end__ != 0x0); +define symbol use_EROM3 = (__ICFEDIT_region_EROM3_start__ != 0x0 || __ICFEDIT_region_EROM3_end__ != 0x0); +define symbol use_IRAM1 = (__ICFEDIT_region_IRAM1_start__ != 0x0 || __ICFEDIT_region_IRAM1_end__ != 0x0); +define symbol use_IRAM2 = (__ICFEDIT_region_IRAM2_start__ != 0x0 || __ICFEDIT_region_IRAM2_end__ != 0x0); +define symbol use_ERAM1 = (__ICFEDIT_region_ERAM1_start__ != 0x0 || __ICFEDIT_region_ERAM1_end__ != 0x0); +define symbol use_ERAM2 = (__ICFEDIT_region_ERAM2_start__ != 0x0 || __ICFEDIT_region_ERAM2_end__ != 0x0); +define symbol use_ERAM3 = (__ICFEDIT_region_ERAM3_start__ != 0x0 || __ICFEDIT_region_ERAM3_end__ != 0x0); + +if (use_IROM1) +{ + define region IROM1_region = mem:[from __ICFEDIT_region_IROM1_start__ to __ICFEDIT_region_IROM1_end__]; +} +else +{ + define region IROM1_region = []; +} + +if (use_IROM2) +{ + define region IROM2_region = mem:[from __ICFEDIT_region_IROM2_start__ to __ICFEDIT_region_IROM2_end__]; +} +else +{ + define region IROM2_region = []; +} +define region IROM_region = IROM1_region | IROM2_region; + +if (use_EROM1) +{ + define region EROM1_region = mem:[from __ICFEDIT_region_EROM1_start__ to __ICFEDIT_region_EROM1_end__]; +} +else +{ + define region EROM1_region = []; +} +if (use_EROM2) +{ + define region EROM2_region = mem:[from __ICFEDIT_region_EROM2_start__ to __ICFEDIT_region_EROM2_end__]; +} +else +{ + define region EROM2_region = []; +} +if (use_EROM3) +{ + define region EROM3_region = mem:[from __ICFEDIT_region_EROM3_start__ to __ICFEDIT_region_EROM3_end__]; +} +else +{ + define region EROM3_region = []; +} +define region EROM_region = EROM1_region | EROM2_region | EROM3_region; + +if (use_IRAM1) +{ + define region IRAM1_region = mem:[from __ICFEDIT_region_IRAM1_start__ to __ICFEDIT_region_IRAM1_end__]; +} +else +{ + define region IRAM1_region = []; +} +if (use_IRAM2) +{ + define region IRAM2_region = mem:[from __ICFEDIT_region_IRAM2_start__ to __ICFEDIT_region_IRAM2_end__]; +} +else +{ + define region IRAM2_region = []; +} + +define region IRAM_region = IRAM1_region; + +define region TCMRAM_region = IRAM2_region; + +if (use_ERAM1) +{ + define region ERAM1_region = mem:[from __ICFEDIT_region_ERAM1_start__ to __ICFEDIT_region_ERAM1_end__]; +} +else +{ + define region ERAM1_region = []; +} +if (use_ERAM2) +{ + define region ERAM2_region = mem:[from __ICFEDIT_region_ERAM2_start__ to __ICFEDIT_region_ERAM2_end__]; +} +else +{ + define region ERAM2_region = []; +} +if (use_ERAM3) +{ + define region ERAM3_region = mem:[from __ICFEDIT_region_ERAM3_start__ to __ICFEDIT_region_ERAM3_end__]; +} +else +{ + define region ERAM3_region = []; +} +define region ERAM_region = ERAM1_region | ERAM2_region | ERAM3_region; + +initialize by copy { readwrite }; +if (isdefinedsymbol(__USE_DLIB_PERTHREAD)) +{ + // Required in a multi-threaded application + initialize by copy with packing = none { section __DLIB_PERTHREAD }; +} + +place at address mem:__ICFEDIT_intvec_start__ { readonly section .intvec }; + +if (!isempty(IROM_region)) +{ + place in IROM_region { readonly }; +} + +if (!isempty(EROM_region)) +{ + place in EROM_region { readonly section application_specific_ro }; +} + +if (!isempty(IRAM_region)) +{ + define block CSTACK with alignment = 8, size = __ICFEDIT_size_cstack__ { }; + define block PROC_STACK with alignment = 8, size = __ICFEDIT_size_proc_stack__ { }; + define block HEAP with alignment = 8, size = __ICFEDIT_size_heap__ { }; + place in IRAM_region { readwrite, block CSTACK, block PROC_STACK, block HEAP }; +} + +if (!isempty(TCMRAM_region)) +{ + place in TCMRAM_region { section .textrw }; +} + +if (!isempty(ERAM_region)) +{ + place in ERAM_region { readwrite section application_specific_rw }; +} diff --git a/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/iar/apm32f407xE.icf b/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/iar/apm32f407xE.icf new file mode 100644 index 0000000000..7ac762c50f --- /dev/null +++ b/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/iar/apm32f407xE.icf @@ -0,0 +1,172 @@ +/*###ICF### Section handled by ICF editor, don't touch! ****/ +/*-Editor annotation file-*/ +/* IcfEditorFile="$TOOLKIT_DIR$\config\ide\IcfEditor\cortex_v1_4.xml" */ +/*-Specials-*/ +define symbol __ICFEDIT_intvec_start__ = 0x08000000; +/*-Memory Regions-*/ +define symbol __ICFEDIT_region_IROM1_start__ = 0x08000000; +define symbol __ICFEDIT_region_IROM1_end__ = 0x0807FFFF; +define symbol __ICFEDIT_region_IROM2_start__ = 0x0; +define symbol __ICFEDIT_region_IROM2_end__ = 0x0; +define symbol __ICFEDIT_region_EROM1_start__ = 0x0; +define symbol __ICFEDIT_region_EROM1_end__ = 0x0; +define symbol __ICFEDIT_region_EROM2_start__ = 0x0; +define symbol __ICFEDIT_region_EROM2_end__ = 0x0; +define symbol __ICFEDIT_region_EROM3_start__ = 0x0; +define symbol __ICFEDIT_region_EROM3_end__ = 0x0; +define symbol __ICFEDIT_region_IRAM1_start__ = 0x20000000; +define symbol __ICFEDIT_region_IRAM1_end__ = 0x2001FFFF; +define symbol __ICFEDIT_region_IRAM2_start__ = 0x10000000; +define symbol __ICFEDIT_region_IRAM2_end__ = 0x1000FFFF; +define symbol __ICFEDIT_region_ERAM1_start__ = 0x0; +define symbol __ICFEDIT_region_ERAM1_end__ = 0x0; +define symbol __ICFEDIT_region_ERAM2_start__ = 0x0; +define symbol __ICFEDIT_region_ERAM2_end__ = 0x0; +define symbol __ICFEDIT_region_ERAM3_start__ = 0x0; +define symbol __ICFEDIT_region_ERAM3_end__ = 0x0; +/*-Sizes-*/ +define symbol __ICFEDIT_size_cstack__ = 0x400; +define symbol __ICFEDIT_size_proc_stack__ = 0x0; +define symbol __ICFEDIT_size_heap__ = 0x800; +/**** End of ICF editor section. ###ICF###*/ + +define memory mem with size = 4G; +define symbol use_IROM1 = (__ICFEDIT_region_IROM1_start__ != 0x0 || __ICFEDIT_region_IROM1_end__ != 0x0); +define symbol use_IROM2 = (__ICFEDIT_region_IROM2_start__ != 0x0 || __ICFEDIT_region_IROM2_end__ != 0x0); +define symbol use_EROM1 = (__ICFEDIT_region_EROM1_start__ != 0x0 || __ICFEDIT_region_EROM1_end__ != 0x0); +define symbol use_EROM2 = (__ICFEDIT_region_EROM2_start__ != 0x0 || __ICFEDIT_region_EROM2_end__ != 0x0); +define symbol use_EROM3 = (__ICFEDIT_region_EROM3_start__ != 0x0 || __ICFEDIT_region_EROM3_end__ != 0x0); +define symbol use_IRAM1 = (__ICFEDIT_region_IRAM1_start__ != 0x0 || __ICFEDIT_region_IRAM1_end__ != 0x0); +define symbol use_IRAM2 = (__ICFEDIT_region_IRAM2_start__ != 0x0 || __ICFEDIT_region_IRAM2_end__ != 0x0); +define symbol use_ERAM1 = (__ICFEDIT_region_ERAM1_start__ != 0x0 || __ICFEDIT_region_ERAM1_end__ != 0x0); +define symbol use_ERAM2 = (__ICFEDIT_region_ERAM2_start__ != 0x0 || __ICFEDIT_region_ERAM2_end__ != 0x0); +define symbol use_ERAM3 = (__ICFEDIT_region_ERAM3_start__ != 0x0 || __ICFEDIT_region_ERAM3_end__ != 0x0); + +if (use_IROM1) +{ + define region IROM1_region = mem:[from __ICFEDIT_region_IROM1_start__ to __ICFEDIT_region_IROM1_end__]; +} +else +{ + define region IROM1_region = []; +} + +if (use_IROM2) +{ + define region IROM2_region = mem:[from __ICFEDIT_region_IROM2_start__ to __ICFEDIT_region_IROM2_end__]; +} +else +{ + define region IROM2_region = []; +} +define region IROM_region = IROM1_region | IROM2_region; + +if (use_EROM1) +{ + define region EROM1_region = mem:[from __ICFEDIT_region_EROM1_start__ to __ICFEDIT_region_EROM1_end__]; +} +else +{ + define region EROM1_region = []; +} +if (use_EROM2) +{ + define region EROM2_region = mem:[from __ICFEDIT_region_EROM2_start__ to __ICFEDIT_region_EROM2_end__]; +} +else +{ + define region EROM2_region = []; +} +if (use_EROM3) +{ + define region EROM3_region = mem:[from __ICFEDIT_region_EROM3_start__ to __ICFEDIT_region_EROM3_end__]; +} +else +{ + define region EROM3_region = []; +} +define region EROM_region = EROM1_region | EROM2_region | EROM3_region; + +if (use_IRAM1) +{ + define region IRAM1_region = mem:[from __ICFEDIT_region_IRAM1_start__ to __ICFEDIT_region_IRAM1_end__]; +} +else +{ + define region IRAM1_region = []; +} +if (use_IRAM2) +{ + define region IRAM2_region = mem:[from __ICFEDIT_region_IRAM2_start__ to __ICFEDIT_region_IRAM2_end__]; +} +else +{ + define region IRAM2_region = []; +} + +define region IRAM_region = IRAM1_region; + +define region TCMRAM_region = IRAM2_region; + +if (use_ERAM1) +{ + define region ERAM1_region = mem:[from __ICFEDIT_region_ERAM1_start__ to __ICFEDIT_region_ERAM1_end__]; +} +else +{ + define region ERAM1_region = []; +} +if (use_ERAM2) +{ + define region ERAM2_region = mem:[from __ICFEDIT_region_ERAM2_start__ to __ICFEDIT_region_ERAM2_end__]; +} +else +{ + define region ERAM2_region = []; +} +if (use_ERAM3) +{ + define region ERAM3_region = mem:[from __ICFEDIT_region_ERAM3_start__ to __ICFEDIT_region_ERAM3_end__]; +} +else +{ + define region ERAM3_region = []; +} +define region ERAM_region = ERAM1_region | ERAM2_region | ERAM3_region; + +initialize by copy { readwrite }; +if (isdefinedsymbol(__USE_DLIB_PERTHREAD)) +{ + // Required in a multi-threaded application + initialize by copy with packing = none { section __DLIB_PERTHREAD }; +} + +place at address mem:__ICFEDIT_intvec_start__ { readonly section .intvec }; + +if (!isempty(IROM_region)) +{ + place in IROM_region { readonly }; +} + +if (!isempty(EROM_region)) +{ + place in EROM_region { readonly section application_specific_ro }; +} + +if (!isempty(IRAM_region)) +{ + define block CSTACK with alignment = 8, size = __ICFEDIT_size_cstack__ { }; + define block PROC_STACK with alignment = 8, size = __ICFEDIT_size_proc_stack__ { }; + define block HEAP with alignment = 8, size = __ICFEDIT_size_heap__ { }; + place in IRAM_region { readwrite, block CSTACK, block PROC_STACK, block HEAP }; +} + +if (!isempty(TCMRAM_region)) +{ + place in TCMRAM_region { section .textrw }; +} + +if (!isempty(ERAM_region)) +{ + place in ERAM_region { readwrite section application_specific_rw }; +} diff --git a/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/iar/apm32f407xG.icf b/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/iar/apm32f407xG.icf new file mode 100644 index 0000000000..eca26d5fd2 --- /dev/null +++ b/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/iar/apm32f407xG.icf @@ -0,0 +1,172 @@ +/*###ICF### Section handled by ICF editor, don't touch! ****/ +/*-Editor annotation file-*/ +/* IcfEditorFile="$TOOLKIT_DIR$\config\ide\IcfEditor\cortex_v1_4.xml" */ +/*-Specials-*/ +define symbol __ICFEDIT_intvec_start__ = 0x08000000; +/*-Memory Regions-*/ +define symbol __ICFEDIT_region_IROM1_start__ = 0x08000000; +define symbol __ICFEDIT_region_IROM1_end__ = 0x080FFFFF; +define symbol __ICFEDIT_region_IROM2_start__ = 0x0; +define symbol __ICFEDIT_region_IROM2_end__ = 0x0; +define symbol __ICFEDIT_region_EROM1_start__ = 0x0; +define symbol __ICFEDIT_region_EROM1_end__ = 0x0; +define symbol __ICFEDIT_region_EROM2_start__ = 0x0; +define symbol __ICFEDIT_region_EROM2_end__ = 0x0; +define symbol __ICFEDIT_region_EROM3_start__ = 0x0; +define symbol __ICFEDIT_region_EROM3_end__ = 0x0; +define symbol __ICFEDIT_region_IRAM1_start__ = 0x20000000; +define symbol __ICFEDIT_region_IRAM1_end__ = 0x2001FFFF; +define symbol __ICFEDIT_region_IRAM2_start__ = 0x10000000; +define symbol __ICFEDIT_region_IRAM2_end__ = 0x1000FFFF; +define symbol __ICFEDIT_region_ERAM1_start__ = 0x0; +define symbol __ICFEDIT_region_ERAM1_end__ = 0x0; +define symbol __ICFEDIT_region_ERAM2_start__ = 0x0; +define symbol __ICFEDIT_region_ERAM2_end__ = 0x0; +define symbol __ICFEDIT_region_ERAM3_start__ = 0x0; +define symbol __ICFEDIT_region_ERAM3_end__ = 0x0; +/*-Sizes-*/ +define symbol __ICFEDIT_size_cstack__ = 0x400; +define symbol __ICFEDIT_size_proc_stack__ = 0x0; +define symbol __ICFEDIT_size_heap__ = 0x800; +/**** End of ICF editor section. ###ICF###*/ + +define memory mem with size = 4G; +define symbol use_IROM1 = (__ICFEDIT_region_IROM1_start__ != 0x0 || __ICFEDIT_region_IROM1_end__ != 0x0); +define symbol use_IROM2 = (__ICFEDIT_region_IROM2_start__ != 0x0 || __ICFEDIT_region_IROM2_end__ != 0x0); +define symbol use_EROM1 = (__ICFEDIT_region_EROM1_start__ != 0x0 || __ICFEDIT_region_EROM1_end__ != 0x0); +define symbol use_EROM2 = (__ICFEDIT_region_EROM2_start__ != 0x0 || __ICFEDIT_region_EROM2_end__ != 0x0); +define symbol use_EROM3 = (__ICFEDIT_region_EROM3_start__ != 0x0 || __ICFEDIT_region_EROM3_end__ != 0x0); +define symbol use_IRAM1 = (__ICFEDIT_region_IRAM1_start__ != 0x0 || __ICFEDIT_region_IRAM1_end__ != 0x0); +define symbol use_IRAM2 = (__ICFEDIT_region_IRAM2_start__ != 0x0 || __ICFEDIT_region_IRAM2_end__ != 0x0); +define symbol use_ERAM1 = (__ICFEDIT_region_ERAM1_start__ != 0x0 || __ICFEDIT_region_ERAM1_end__ != 0x0); +define symbol use_ERAM2 = (__ICFEDIT_region_ERAM2_start__ != 0x0 || __ICFEDIT_region_ERAM2_end__ != 0x0); +define symbol use_ERAM3 = (__ICFEDIT_region_ERAM3_start__ != 0x0 || __ICFEDIT_region_ERAM3_end__ != 0x0); + +if (use_IROM1) +{ + define region IROM1_region = mem:[from __ICFEDIT_region_IROM1_start__ to __ICFEDIT_region_IROM1_end__]; +} +else +{ + define region IROM1_region = []; +} + +if (use_IROM2) +{ + define region IROM2_region = mem:[from __ICFEDIT_region_IROM2_start__ to __ICFEDIT_region_IROM2_end__]; +} +else +{ + define region IROM2_region = []; +} +define region IROM_region = IROM1_region | IROM2_region; + +if (use_EROM1) +{ + define region EROM1_region = mem:[from __ICFEDIT_region_EROM1_start__ to __ICFEDIT_region_EROM1_end__]; +} +else +{ + define region EROM1_region = []; +} +if (use_EROM2) +{ + define region EROM2_region = mem:[from __ICFEDIT_region_EROM2_start__ to __ICFEDIT_region_EROM2_end__]; +} +else +{ + define region EROM2_region = []; +} +if (use_EROM3) +{ + define region EROM3_region = mem:[from __ICFEDIT_region_EROM3_start__ to __ICFEDIT_region_EROM3_end__]; +} +else +{ + define region EROM3_region = []; +} +define region EROM_region = EROM1_region | EROM2_region | EROM3_region; + +if (use_IRAM1) +{ + define region IRAM1_region = mem:[from __ICFEDIT_region_IRAM1_start__ to __ICFEDIT_region_IRAM1_end__]; +} +else +{ + define region IRAM1_region = []; +} +if (use_IRAM2) +{ + define region IRAM2_region = mem:[from __ICFEDIT_region_IRAM2_start__ to __ICFEDIT_region_IRAM2_end__]; +} +else +{ + define region IRAM2_region = []; +} + +define region IRAM_region = IRAM1_region; + +define region TCMRAM_region = IRAM2_region; + +if (use_ERAM1) +{ + define region ERAM1_region = mem:[from __ICFEDIT_region_ERAM1_start__ to __ICFEDIT_region_ERAM1_end__]; +} +else +{ + define region ERAM1_region = []; +} +if (use_ERAM2) +{ + define region ERAM2_region = mem:[from __ICFEDIT_region_ERAM2_start__ to __ICFEDIT_region_ERAM2_end__]; +} +else +{ + define region ERAM2_region = []; +} +if (use_ERAM3) +{ + define region ERAM3_region = mem:[from __ICFEDIT_region_ERAM3_start__ to __ICFEDIT_region_ERAM3_end__]; +} +else +{ + define region ERAM3_region = []; +} +define region ERAM_region = ERAM1_region | ERAM2_region | ERAM3_region; + +initialize by copy { readwrite }; +if (isdefinedsymbol(__USE_DLIB_PERTHREAD)) +{ + // Required in a multi-threaded application + initialize by copy with packing = none { section __DLIB_PERTHREAD }; +} + +place at address mem:__ICFEDIT_intvec_start__ { readonly section .intvec }; + +if (!isempty(IROM_region)) +{ + place in IROM_region { readonly }; +} + +if (!isempty(EROM_region)) +{ + place in EROM_region { readonly section application_specific_ro }; +} + +if (!isempty(IRAM_region)) +{ + define block CSTACK with alignment = 8, size = __ICFEDIT_size_cstack__ { }; + define block PROC_STACK with alignment = 8, size = __ICFEDIT_size_proc_stack__ { }; + define block HEAP with alignment = 8, size = __ICFEDIT_size_heap__ { }; + place in IRAM_region { readwrite, block CSTACK, block PROC_STACK, block HEAP }; +} + +if (!isempty(TCMRAM_region)) +{ + place in TCMRAM_region { section .textrw }; +} + +if (!isempty(ERAM_region)) +{ + place in ERAM_region { readwrite section application_specific_rw }; +} diff --git a/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/iar/apm32f411xC.icf b/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/iar/apm32f411xC.icf new file mode 100644 index 0000000000..c5fecc9e66 --- /dev/null +++ b/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/iar/apm32f411xC.icf @@ -0,0 +1,172 @@ +/*###ICF### Section handled by ICF editor, don't touch! ****/ +/*-Editor annotation file-*/ +/* IcfEditorFile="$TOOLKIT_DIR$\config\ide\IcfEditor\cortex_v1_4.xml" */ +/*-Specials-*/ +define symbol __ICFEDIT_intvec_start__ = 0x08000000; +/*-Memory Regions-*/ +define symbol __ICFEDIT_region_IROM1_start__ = 0x08000000; +define symbol __ICFEDIT_region_IROM1_end__ = 0x0803FFFF; +define symbol __ICFEDIT_region_IROM2_start__ = 0x0; +define symbol __ICFEDIT_region_IROM2_end__ = 0x0; +define symbol __ICFEDIT_region_EROM1_start__ = 0x0; +define symbol __ICFEDIT_region_EROM1_end__ = 0x0; +define symbol __ICFEDIT_region_EROM2_start__ = 0x0; +define symbol __ICFEDIT_region_EROM2_end__ = 0x0; +define symbol __ICFEDIT_region_EROM3_start__ = 0x0; +define symbol __ICFEDIT_region_EROM3_end__ = 0x0; +define symbol __ICFEDIT_region_IRAM1_start__ = 0x20000000; +define symbol __ICFEDIT_region_IRAM1_end__ = 0x2001FFFF; +define symbol __ICFEDIT_region_IRAM2_start__ = 0x0; +define symbol __ICFEDIT_region_IRAM2_end__ = 0x0; +define symbol __ICFEDIT_region_ERAM1_start__ = 0x0; +define symbol __ICFEDIT_region_ERAM1_end__ = 0x0; +define symbol __ICFEDIT_region_ERAM2_start__ = 0x0; +define symbol __ICFEDIT_region_ERAM2_end__ = 0x0; +define symbol __ICFEDIT_region_ERAM3_start__ = 0x0; +define symbol __ICFEDIT_region_ERAM3_end__ = 0x0; +/*-Sizes-*/ +define symbol __ICFEDIT_size_cstack__ = 0x400; +define symbol __ICFEDIT_size_proc_stack__ = 0x0; +define symbol __ICFEDIT_size_heap__ = 0x800; +/**** End of ICF editor section. ###ICF###*/ + +define memory mem with size = 4G; +define symbol use_IROM1 = (__ICFEDIT_region_IROM1_start__ != 0x0 || __ICFEDIT_region_IROM1_end__ != 0x0); +define symbol use_IROM2 = (__ICFEDIT_region_IROM2_start__ != 0x0 || __ICFEDIT_region_IROM2_end__ != 0x0); +define symbol use_EROM1 = (__ICFEDIT_region_EROM1_start__ != 0x0 || __ICFEDIT_region_EROM1_end__ != 0x0); +define symbol use_EROM2 = (__ICFEDIT_region_EROM2_start__ != 0x0 || __ICFEDIT_region_EROM2_end__ != 0x0); +define symbol use_EROM3 = (__ICFEDIT_region_EROM3_start__ != 0x0 || __ICFEDIT_region_EROM3_end__ != 0x0); +define symbol use_IRAM1 = (__ICFEDIT_region_IRAM1_start__ != 0x0 || __ICFEDIT_region_IRAM1_end__ != 0x0); +define symbol use_IRAM2 = (__ICFEDIT_region_IRAM2_start__ != 0x0 || __ICFEDIT_region_IRAM2_end__ != 0x0); +define symbol use_ERAM1 = (__ICFEDIT_region_ERAM1_start__ != 0x0 || __ICFEDIT_region_ERAM1_end__ != 0x0); +define symbol use_ERAM2 = (__ICFEDIT_region_ERAM2_start__ != 0x0 || __ICFEDIT_region_ERAM2_end__ != 0x0); +define symbol use_ERAM3 = (__ICFEDIT_region_ERAM3_start__ != 0x0 || __ICFEDIT_region_ERAM3_end__ != 0x0); + +if (use_IROM1) +{ + define region IROM1_region = mem:[from __ICFEDIT_region_IROM1_start__ to __ICFEDIT_region_IROM1_end__]; +} +else +{ + define region IROM1_region = []; +} + +if (use_IROM2) +{ + define region IROM2_region = mem:[from __ICFEDIT_region_IROM2_start__ to __ICFEDIT_region_IROM2_end__]; +} +else +{ + define region IROM2_region = []; +} +define region IROM_region = IROM1_region | IROM2_region; + +if (use_EROM1) +{ + define region EROM1_region = mem:[from __ICFEDIT_region_EROM1_start__ to __ICFEDIT_region_EROM1_end__]; +} +else +{ + define region EROM1_region = []; +} +if (use_EROM2) +{ + define region EROM2_region = mem:[from __ICFEDIT_region_EROM2_start__ to __ICFEDIT_region_EROM2_end__]; +} +else +{ + define region EROM2_region = []; +} +if (use_EROM3) +{ + define region EROM3_region = mem:[from __ICFEDIT_region_EROM3_start__ to __ICFEDIT_region_EROM3_end__]; +} +else +{ + define region EROM3_region = []; +} +define region EROM_region = EROM1_region | EROM2_region | EROM3_region; + +if (use_IRAM1) +{ + define region IRAM1_region = mem:[from __ICFEDIT_region_IRAM1_start__ to __ICFEDIT_region_IRAM1_end__]; +} +else +{ + define region IRAM1_region = []; +} +if (use_IRAM2) +{ + define region IRAM2_region = mem:[from __ICFEDIT_region_IRAM2_start__ to __ICFEDIT_region_IRAM2_end__]; +} +else +{ + define region IRAM2_region = []; +} + +define region IRAM_region = IRAM1_region; + +define region TCMRAM_region = IRAM2_region; + +if (use_ERAM1) +{ + define region ERAM1_region = mem:[from __ICFEDIT_region_ERAM1_start__ to __ICFEDIT_region_ERAM1_end__]; +} +else +{ + define region ERAM1_region = []; +} +if (use_ERAM2) +{ + define region ERAM2_region = mem:[from __ICFEDIT_region_ERAM2_start__ to __ICFEDIT_region_ERAM2_end__]; +} +else +{ + define region ERAM2_region = []; +} +if (use_ERAM3) +{ + define region ERAM3_region = mem:[from __ICFEDIT_region_ERAM3_start__ to __ICFEDIT_region_ERAM3_end__]; +} +else +{ + define region ERAM3_region = []; +} +define region ERAM_region = ERAM1_region | ERAM2_region | ERAM3_region; + +initialize by copy { readwrite }; +if (isdefinedsymbol(__USE_DLIB_PERTHREAD)) +{ + // Required in a multi-threaded application + initialize by copy with packing = none { section __DLIB_PERTHREAD }; +} + +place at address mem:__ICFEDIT_intvec_start__ { readonly section .intvec }; + +if (!isempty(IROM_region)) +{ + place in IROM_region { readonly }; +} + +if (!isempty(EROM_region)) +{ + place in EROM_region { readonly section application_specific_ro }; +} + +if (!isempty(IRAM_region)) +{ + define block CSTACK with alignment = 8, size = __ICFEDIT_size_cstack__ { }; + define block PROC_STACK with alignment = 8, size = __ICFEDIT_size_proc_stack__ { }; + define block HEAP with alignment = 8, size = __ICFEDIT_size_heap__ { }; + place in IRAM_region { readwrite, block CSTACK, block PROC_STACK, block HEAP }; +} + +if (!isempty(TCMRAM_region)) +{ + place in TCMRAM_region { section .textrw }; +} + +if (!isempty(ERAM_region)) +{ + place in ERAM_region { readwrite section application_specific_rw }; +} diff --git a/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/iar/apm32f411xE.icf b/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/iar/apm32f411xE.icf new file mode 100644 index 0000000000..ee3a607319 --- /dev/null +++ b/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/iar/apm32f411xE.icf @@ -0,0 +1,172 @@ +/*###ICF### Section handled by ICF editor, don't touch! ****/ +/*-Editor annotation file-*/ +/* IcfEditorFile="$TOOLKIT_DIR$\config\ide\IcfEditor\cortex_v1_4.xml" */ +/*-Specials-*/ +define symbol __ICFEDIT_intvec_start__ = 0x08000000; +/*-Memory Regions-*/ +define symbol __ICFEDIT_region_IROM1_start__ = 0x08000000; +define symbol __ICFEDIT_region_IROM1_end__ = 0x0807FFFF; +define symbol __ICFEDIT_region_IROM2_start__ = 0x0; +define symbol __ICFEDIT_region_IROM2_end__ = 0x0; +define symbol __ICFEDIT_region_EROM1_start__ = 0x0; +define symbol __ICFEDIT_region_EROM1_end__ = 0x0; +define symbol __ICFEDIT_region_EROM2_start__ = 0x0; +define symbol __ICFEDIT_region_EROM2_end__ = 0x0; +define symbol __ICFEDIT_region_EROM3_start__ = 0x0; +define symbol __ICFEDIT_region_EROM3_end__ = 0x0; +define symbol __ICFEDIT_region_IRAM1_start__ = 0x20000000; +define symbol __ICFEDIT_region_IRAM1_end__ = 0x2001FFFF; +define symbol __ICFEDIT_region_IRAM2_start__ = 0x0; +define symbol __ICFEDIT_region_IRAM2_end__ = 0x0; +define symbol __ICFEDIT_region_ERAM1_start__ = 0x0; +define symbol __ICFEDIT_region_ERAM1_end__ = 0x0; +define symbol __ICFEDIT_region_ERAM2_start__ = 0x0; +define symbol __ICFEDIT_region_ERAM2_end__ = 0x0; +define symbol __ICFEDIT_region_ERAM3_start__ = 0x0; +define symbol __ICFEDIT_region_ERAM3_end__ = 0x0; +/*-Sizes-*/ +define symbol __ICFEDIT_size_cstack__ = 0x400; +define symbol __ICFEDIT_size_proc_stack__ = 0x0; +define symbol __ICFEDIT_size_heap__ = 0x800; +/**** End of ICF editor section. ###ICF###*/ + +define memory mem with size = 4G; +define symbol use_IROM1 = (__ICFEDIT_region_IROM1_start__ != 0x0 || __ICFEDIT_region_IROM1_end__ != 0x0); +define symbol use_IROM2 = (__ICFEDIT_region_IROM2_start__ != 0x0 || __ICFEDIT_region_IROM2_end__ != 0x0); +define symbol use_EROM1 = (__ICFEDIT_region_EROM1_start__ != 0x0 || __ICFEDIT_region_EROM1_end__ != 0x0); +define symbol use_EROM2 = (__ICFEDIT_region_EROM2_start__ != 0x0 || __ICFEDIT_region_EROM2_end__ != 0x0); +define symbol use_EROM3 = (__ICFEDIT_region_EROM3_start__ != 0x0 || __ICFEDIT_region_EROM3_end__ != 0x0); +define symbol use_IRAM1 = (__ICFEDIT_region_IRAM1_start__ != 0x0 || __ICFEDIT_region_IRAM1_end__ != 0x0); +define symbol use_IRAM2 = (__ICFEDIT_region_IRAM2_start__ != 0x0 || __ICFEDIT_region_IRAM2_end__ != 0x0); +define symbol use_ERAM1 = (__ICFEDIT_region_ERAM1_start__ != 0x0 || __ICFEDIT_region_ERAM1_end__ != 0x0); +define symbol use_ERAM2 = (__ICFEDIT_region_ERAM2_start__ != 0x0 || __ICFEDIT_region_ERAM2_end__ != 0x0); +define symbol use_ERAM3 = (__ICFEDIT_region_ERAM3_start__ != 0x0 || __ICFEDIT_region_ERAM3_end__ != 0x0); + +if (use_IROM1) +{ + define region IROM1_region = mem:[from __ICFEDIT_region_IROM1_start__ to __ICFEDIT_region_IROM1_end__]; +} +else +{ + define region IROM1_region = []; +} + +if (use_IROM2) +{ + define region IROM2_region = mem:[from __ICFEDIT_region_IROM2_start__ to __ICFEDIT_region_IROM2_end__]; +} +else +{ + define region IROM2_region = []; +} +define region IROM_region = IROM1_region | IROM2_region; + +if (use_EROM1) +{ + define region EROM1_region = mem:[from __ICFEDIT_region_EROM1_start__ to __ICFEDIT_region_EROM1_end__]; +} +else +{ + define region EROM1_region = []; +} +if (use_EROM2) +{ + define region EROM2_region = mem:[from __ICFEDIT_region_EROM2_start__ to __ICFEDIT_region_EROM2_end__]; +} +else +{ + define region EROM2_region = []; +} +if (use_EROM3) +{ + define region EROM3_region = mem:[from __ICFEDIT_region_EROM3_start__ to __ICFEDIT_region_EROM3_end__]; +} +else +{ + define region EROM3_region = []; +} +define region EROM_region = EROM1_region | EROM2_region | EROM3_region; + +if (use_IRAM1) +{ + define region IRAM1_region = mem:[from __ICFEDIT_region_IRAM1_start__ to __ICFEDIT_region_IRAM1_end__]; +} +else +{ + define region IRAM1_region = []; +} +if (use_IRAM2) +{ + define region IRAM2_region = mem:[from __ICFEDIT_region_IRAM2_start__ to __ICFEDIT_region_IRAM2_end__]; +} +else +{ + define region IRAM2_region = []; +} + +define region IRAM_region = IRAM1_region; + +define region TCMRAM_region = IRAM2_region; + +if (use_ERAM1) +{ + define region ERAM1_region = mem:[from __ICFEDIT_region_ERAM1_start__ to __ICFEDIT_region_ERAM1_end__]; +} +else +{ + define region ERAM1_region = []; +} +if (use_ERAM2) +{ + define region ERAM2_region = mem:[from __ICFEDIT_region_ERAM2_start__ to __ICFEDIT_region_ERAM2_end__]; +} +else +{ + define region ERAM2_region = []; +} +if (use_ERAM3) +{ + define region ERAM3_region = mem:[from __ICFEDIT_region_ERAM3_start__ to __ICFEDIT_region_ERAM3_end__]; +} +else +{ + define region ERAM3_region = []; +} +define region ERAM_region = ERAM1_region | ERAM2_region | ERAM3_region; + +initialize by copy { readwrite }; +if (isdefinedsymbol(__USE_DLIB_PERTHREAD)) +{ + // Required in a multi-threaded application + initialize by copy with packing = none { section __DLIB_PERTHREAD }; +} + +place at address mem:__ICFEDIT_intvec_start__ { readonly section .intvec }; + +if (!isempty(IROM_region)) +{ + place in IROM_region { readonly }; +} + +if (!isempty(EROM_region)) +{ + place in EROM_region { readonly section application_specific_ro }; +} + +if (!isempty(IRAM_region)) +{ + define block CSTACK with alignment = 8, size = __ICFEDIT_size_cstack__ { }; + define block PROC_STACK with alignment = 8, size = __ICFEDIT_size_proc_stack__ { }; + define block HEAP with alignment = 8, size = __ICFEDIT_size_heap__ { }; + place in IRAM_region { readwrite, block CSTACK, block PROC_STACK, block HEAP }; +} + +if (!isempty(TCMRAM_region)) +{ + place in TCMRAM_region { section .textrw }; +} + +if (!isempty(ERAM_region)) +{ + place in ERAM_region { readwrite section application_specific_rw }; +} diff --git a/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/iar/apm32f417xE.icf b/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/iar/apm32f417xE.icf new file mode 100644 index 0000000000..7ac762c50f --- /dev/null +++ b/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/iar/apm32f417xE.icf @@ -0,0 +1,172 @@ +/*###ICF### Section handled by ICF editor, don't touch! ****/ +/*-Editor annotation file-*/ +/* IcfEditorFile="$TOOLKIT_DIR$\config\ide\IcfEditor\cortex_v1_4.xml" */ +/*-Specials-*/ +define symbol __ICFEDIT_intvec_start__ = 0x08000000; +/*-Memory Regions-*/ +define symbol __ICFEDIT_region_IROM1_start__ = 0x08000000; +define symbol __ICFEDIT_region_IROM1_end__ = 0x0807FFFF; +define symbol __ICFEDIT_region_IROM2_start__ = 0x0; +define symbol __ICFEDIT_region_IROM2_end__ = 0x0; +define symbol __ICFEDIT_region_EROM1_start__ = 0x0; +define symbol __ICFEDIT_region_EROM1_end__ = 0x0; +define symbol __ICFEDIT_region_EROM2_start__ = 0x0; +define symbol __ICFEDIT_region_EROM2_end__ = 0x0; +define symbol __ICFEDIT_region_EROM3_start__ = 0x0; +define symbol __ICFEDIT_region_EROM3_end__ = 0x0; +define symbol __ICFEDIT_region_IRAM1_start__ = 0x20000000; +define symbol __ICFEDIT_region_IRAM1_end__ = 0x2001FFFF; +define symbol __ICFEDIT_region_IRAM2_start__ = 0x10000000; +define symbol __ICFEDIT_region_IRAM2_end__ = 0x1000FFFF; +define symbol __ICFEDIT_region_ERAM1_start__ = 0x0; +define symbol __ICFEDIT_region_ERAM1_end__ = 0x0; +define symbol __ICFEDIT_region_ERAM2_start__ = 0x0; +define symbol __ICFEDIT_region_ERAM2_end__ = 0x0; +define symbol __ICFEDIT_region_ERAM3_start__ = 0x0; +define symbol __ICFEDIT_region_ERAM3_end__ = 0x0; +/*-Sizes-*/ +define symbol __ICFEDIT_size_cstack__ = 0x400; +define symbol __ICFEDIT_size_proc_stack__ = 0x0; +define symbol __ICFEDIT_size_heap__ = 0x800; +/**** End of ICF editor section. ###ICF###*/ + +define memory mem with size = 4G; +define symbol use_IROM1 = (__ICFEDIT_region_IROM1_start__ != 0x0 || __ICFEDIT_region_IROM1_end__ != 0x0); +define symbol use_IROM2 = (__ICFEDIT_region_IROM2_start__ != 0x0 || __ICFEDIT_region_IROM2_end__ != 0x0); +define symbol use_EROM1 = (__ICFEDIT_region_EROM1_start__ != 0x0 || __ICFEDIT_region_EROM1_end__ != 0x0); +define symbol use_EROM2 = (__ICFEDIT_region_EROM2_start__ != 0x0 || __ICFEDIT_region_EROM2_end__ != 0x0); +define symbol use_EROM3 = (__ICFEDIT_region_EROM3_start__ != 0x0 || __ICFEDIT_region_EROM3_end__ != 0x0); +define symbol use_IRAM1 = (__ICFEDIT_region_IRAM1_start__ != 0x0 || __ICFEDIT_region_IRAM1_end__ != 0x0); +define symbol use_IRAM2 = (__ICFEDIT_region_IRAM2_start__ != 0x0 || __ICFEDIT_region_IRAM2_end__ != 0x0); +define symbol use_ERAM1 = (__ICFEDIT_region_ERAM1_start__ != 0x0 || __ICFEDIT_region_ERAM1_end__ != 0x0); +define symbol use_ERAM2 = (__ICFEDIT_region_ERAM2_start__ != 0x0 || __ICFEDIT_region_ERAM2_end__ != 0x0); +define symbol use_ERAM3 = (__ICFEDIT_region_ERAM3_start__ != 0x0 || __ICFEDIT_region_ERAM3_end__ != 0x0); + +if (use_IROM1) +{ + define region IROM1_region = mem:[from __ICFEDIT_region_IROM1_start__ to __ICFEDIT_region_IROM1_end__]; +} +else +{ + define region IROM1_region = []; +} + +if (use_IROM2) +{ + define region IROM2_region = mem:[from __ICFEDIT_region_IROM2_start__ to __ICFEDIT_region_IROM2_end__]; +} +else +{ + define region IROM2_region = []; +} +define region IROM_region = IROM1_region | IROM2_region; + +if (use_EROM1) +{ + define region EROM1_region = mem:[from __ICFEDIT_region_EROM1_start__ to __ICFEDIT_region_EROM1_end__]; +} +else +{ + define region EROM1_region = []; +} +if (use_EROM2) +{ + define region EROM2_region = mem:[from __ICFEDIT_region_EROM2_start__ to __ICFEDIT_region_EROM2_end__]; +} +else +{ + define region EROM2_region = []; +} +if (use_EROM3) +{ + define region EROM3_region = mem:[from __ICFEDIT_region_EROM3_start__ to __ICFEDIT_region_EROM3_end__]; +} +else +{ + define region EROM3_region = []; +} +define region EROM_region = EROM1_region | EROM2_region | EROM3_region; + +if (use_IRAM1) +{ + define region IRAM1_region = mem:[from __ICFEDIT_region_IRAM1_start__ to __ICFEDIT_region_IRAM1_end__]; +} +else +{ + define region IRAM1_region = []; +} +if (use_IRAM2) +{ + define region IRAM2_region = mem:[from __ICFEDIT_region_IRAM2_start__ to __ICFEDIT_region_IRAM2_end__]; +} +else +{ + define region IRAM2_region = []; +} + +define region IRAM_region = IRAM1_region; + +define region TCMRAM_region = IRAM2_region; + +if (use_ERAM1) +{ + define region ERAM1_region = mem:[from __ICFEDIT_region_ERAM1_start__ to __ICFEDIT_region_ERAM1_end__]; +} +else +{ + define region ERAM1_region = []; +} +if (use_ERAM2) +{ + define region ERAM2_region = mem:[from __ICFEDIT_region_ERAM2_start__ to __ICFEDIT_region_ERAM2_end__]; +} +else +{ + define region ERAM2_region = []; +} +if (use_ERAM3) +{ + define region ERAM3_region = mem:[from __ICFEDIT_region_ERAM3_start__ to __ICFEDIT_region_ERAM3_end__]; +} +else +{ + define region ERAM3_region = []; +} +define region ERAM_region = ERAM1_region | ERAM2_region | ERAM3_region; + +initialize by copy { readwrite }; +if (isdefinedsymbol(__USE_DLIB_PERTHREAD)) +{ + // Required in a multi-threaded application + initialize by copy with packing = none { section __DLIB_PERTHREAD }; +} + +place at address mem:__ICFEDIT_intvec_start__ { readonly section .intvec }; + +if (!isempty(IROM_region)) +{ + place in IROM_region { readonly }; +} + +if (!isempty(EROM_region)) +{ + place in EROM_region { readonly section application_specific_ro }; +} + +if (!isempty(IRAM_region)) +{ + define block CSTACK with alignment = 8, size = __ICFEDIT_size_cstack__ { }; + define block PROC_STACK with alignment = 8, size = __ICFEDIT_size_proc_stack__ { }; + define block HEAP with alignment = 8, size = __ICFEDIT_size_heap__ { }; + place in IRAM_region { readwrite, block CSTACK, block PROC_STACK, block HEAP }; +} + +if (!isempty(TCMRAM_region)) +{ + place in TCMRAM_region { section .textrw }; +} + +if (!isempty(ERAM_region)) +{ + place in ERAM_region { readwrite section application_specific_rw }; +} diff --git a/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/iar/apm32f417xG.icf b/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/iar/apm32f417xG.icf new file mode 100644 index 0000000000..eca26d5fd2 --- /dev/null +++ b/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/iar/apm32f417xG.icf @@ -0,0 +1,172 @@ +/*###ICF### Section handled by ICF editor, don't touch! ****/ +/*-Editor annotation file-*/ +/* IcfEditorFile="$TOOLKIT_DIR$\config\ide\IcfEditor\cortex_v1_4.xml" */ +/*-Specials-*/ +define symbol __ICFEDIT_intvec_start__ = 0x08000000; +/*-Memory Regions-*/ +define symbol __ICFEDIT_region_IROM1_start__ = 0x08000000; +define symbol __ICFEDIT_region_IROM1_end__ = 0x080FFFFF; +define symbol __ICFEDIT_region_IROM2_start__ = 0x0; +define symbol __ICFEDIT_region_IROM2_end__ = 0x0; +define symbol __ICFEDIT_region_EROM1_start__ = 0x0; +define symbol __ICFEDIT_region_EROM1_end__ = 0x0; +define symbol __ICFEDIT_region_EROM2_start__ = 0x0; +define symbol __ICFEDIT_region_EROM2_end__ = 0x0; +define symbol __ICFEDIT_region_EROM3_start__ = 0x0; +define symbol __ICFEDIT_region_EROM3_end__ = 0x0; +define symbol __ICFEDIT_region_IRAM1_start__ = 0x20000000; +define symbol __ICFEDIT_region_IRAM1_end__ = 0x2001FFFF; +define symbol __ICFEDIT_region_IRAM2_start__ = 0x10000000; +define symbol __ICFEDIT_region_IRAM2_end__ = 0x1000FFFF; +define symbol __ICFEDIT_region_ERAM1_start__ = 0x0; +define symbol __ICFEDIT_region_ERAM1_end__ = 0x0; +define symbol __ICFEDIT_region_ERAM2_start__ = 0x0; +define symbol __ICFEDIT_region_ERAM2_end__ = 0x0; +define symbol __ICFEDIT_region_ERAM3_start__ = 0x0; +define symbol __ICFEDIT_region_ERAM3_end__ = 0x0; +/*-Sizes-*/ +define symbol __ICFEDIT_size_cstack__ = 0x400; +define symbol __ICFEDIT_size_proc_stack__ = 0x0; +define symbol __ICFEDIT_size_heap__ = 0x800; +/**** End of ICF editor section. ###ICF###*/ + +define memory mem with size = 4G; +define symbol use_IROM1 = (__ICFEDIT_region_IROM1_start__ != 0x0 || __ICFEDIT_region_IROM1_end__ != 0x0); +define symbol use_IROM2 = (__ICFEDIT_region_IROM2_start__ != 0x0 || __ICFEDIT_region_IROM2_end__ != 0x0); +define symbol use_EROM1 = (__ICFEDIT_region_EROM1_start__ != 0x0 || __ICFEDIT_region_EROM1_end__ != 0x0); +define symbol use_EROM2 = (__ICFEDIT_region_EROM2_start__ != 0x0 || __ICFEDIT_region_EROM2_end__ != 0x0); +define symbol use_EROM3 = (__ICFEDIT_region_EROM3_start__ != 0x0 || __ICFEDIT_region_EROM3_end__ != 0x0); +define symbol use_IRAM1 = (__ICFEDIT_region_IRAM1_start__ != 0x0 || __ICFEDIT_region_IRAM1_end__ != 0x0); +define symbol use_IRAM2 = (__ICFEDIT_region_IRAM2_start__ != 0x0 || __ICFEDIT_region_IRAM2_end__ != 0x0); +define symbol use_ERAM1 = (__ICFEDIT_region_ERAM1_start__ != 0x0 || __ICFEDIT_region_ERAM1_end__ != 0x0); +define symbol use_ERAM2 = (__ICFEDIT_region_ERAM2_start__ != 0x0 || __ICFEDIT_region_ERAM2_end__ != 0x0); +define symbol use_ERAM3 = (__ICFEDIT_region_ERAM3_start__ != 0x0 || __ICFEDIT_region_ERAM3_end__ != 0x0); + +if (use_IROM1) +{ + define region IROM1_region = mem:[from __ICFEDIT_region_IROM1_start__ to __ICFEDIT_region_IROM1_end__]; +} +else +{ + define region IROM1_region = []; +} + +if (use_IROM2) +{ + define region IROM2_region = mem:[from __ICFEDIT_region_IROM2_start__ to __ICFEDIT_region_IROM2_end__]; +} +else +{ + define region IROM2_region = []; +} +define region IROM_region = IROM1_region | IROM2_region; + +if (use_EROM1) +{ + define region EROM1_region = mem:[from __ICFEDIT_region_EROM1_start__ to __ICFEDIT_region_EROM1_end__]; +} +else +{ + define region EROM1_region = []; +} +if (use_EROM2) +{ + define region EROM2_region = mem:[from __ICFEDIT_region_EROM2_start__ to __ICFEDIT_region_EROM2_end__]; +} +else +{ + define region EROM2_region = []; +} +if (use_EROM3) +{ + define region EROM3_region = mem:[from __ICFEDIT_region_EROM3_start__ to __ICFEDIT_region_EROM3_end__]; +} +else +{ + define region EROM3_region = []; +} +define region EROM_region = EROM1_region | EROM2_region | EROM3_region; + +if (use_IRAM1) +{ + define region IRAM1_region = mem:[from __ICFEDIT_region_IRAM1_start__ to __ICFEDIT_region_IRAM1_end__]; +} +else +{ + define region IRAM1_region = []; +} +if (use_IRAM2) +{ + define region IRAM2_region = mem:[from __ICFEDIT_region_IRAM2_start__ to __ICFEDIT_region_IRAM2_end__]; +} +else +{ + define region IRAM2_region = []; +} + +define region IRAM_region = IRAM1_region; + +define region TCMRAM_region = IRAM2_region; + +if (use_ERAM1) +{ + define region ERAM1_region = mem:[from __ICFEDIT_region_ERAM1_start__ to __ICFEDIT_region_ERAM1_end__]; +} +else +{ + define region ERAM1_region = []; +} +if (use_ERAM2) +{ + define region ERAM2_region = mem:[from __ICFEDIT_region_ERAM2_start__ to __ICFEDIT_region_ERAM2_end__]; +} +else +{ + define region ERAM2_region = []; +} +if (use_ERAM3) +{ + define region ERAM3_region = mem:[from __ICFEDIT_region_ERAM3_start__ to __ICFEDIT_region_ERAM3_end__]; +} +else +{ + define region ERAM3_region = []; +} +define region ERAM_region = ERAM1_region | ERAM2_region | ERAM3_region; + +initialize by copy { readwrite }; +if (isdefinedsymbol(__USE_DLIB_PERTHREAD)) +{ + // Required in a multi-threaded application + initialize by copy with packing = none { section __DLIB_PERTHREAD }; +} + +place at address mem:__ICFEDIT_intvec_start__ { readonly section .intvec }; + +if (!isempty(IROM_region)) +{ + place in IROM_region { readonly }; +} + +if (!isempty(EROM_region)) +{ + place in EROM_region { readonly section application_specific_ro }; +} + +if (!isempty(IRAM_region)) +{ + define block CSTACK with alignment = 8, size = __ICFEDIT_size_cstack__ { }; + define block PROC_STACK with alignment = 8, size = __ICFEDIT_size_proc_stack__ { }; + define block HEAP with alignment = 8, size = __ICFEDIT_size_heap__ { }; + place in IRAM_region { readwrite, block CSTACK, block PROC_STACK, block HEAP }; +} + +if (!isempty(TCMRAM_region)) +{ + place in TCMRAM_region { section .textrw }; +} + +if (!isempty(ERAM_region)) +{ + place in ERAM_region { readwrite section application_specific_rw }; +} diff --git a/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/iar/apm32f465xE.icf b/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/iar/apm32f465xE.icf new file mode 100644 index 0000000000..41b500e19d --- /dev/null +++ b/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/iar/apm32f465xE.icf @@ -0,0 +1,172 @@ +/*###ICF### Section handled by ICF editor, don't touch! ****/ +/*-Editor annotation file-*/ +/* IcfEditorFile="$TOOLKIT_DIR$\config\ide\IcfEditor\cortex_v1_4.xml" */ +/*-Specials-*/ +define symbol __ICFEDIT_intvec_start__ = 0x08000000; +/*-Memory Regions-*/ +define symbol __ICFEDIT_region_IROM1_start__ = 0x08000000; +define symbol __ICFEDIT_region_IROM1_end__ = 0x080FFFFF; +define symbol __ICFEDIT_region_IROM2_start__ = 0x0; +define symbol __ICFEDIT_region_IROM2_end__ = 0x0; +define symbol __ICFEDIT_region_EROM1_start__ = 0x0; +define symbol __ICFEDIT_region_EROM1_end__ = 0x0; +define symbol __ICFEDIT_region_EROM2_start__ = 0x0; +define symbol __ICFEDIT_region_EROM2_end__ = 0x0; +define symbol __ICFEDIT_region_EROM3_start__ = 0x0; +define symbol __ICFEDIT_region_EROM3_end__ = 0x0; +define symbol __ICFEDIT_region_IRAM1_start__ = 0x10000000; +define symbol __ICFEDIT_region_IRAM1_end__ = 0x1000FFFF; +define symbol __ICFEDIT_region_IRAM2_start__ = 0x20000000; +define symbol __ICFEDIT_region_IRAM2_end__ = 0x2001FFFF; +define symbol __ICFEDIT_region_ERAM1_start__ = 0x0; +define symbol __ICFEDIT_region_ERAM1_end__ = 0x0; +define symbol __ICFEDIT_region_ERAM2_start__ = 0x0; +define symbol __ICFEDIT_region_ERAM2_end__ = 0x0; +define symbol __ICFEDIT_region_ERAM3_start__ = 0x0; +define symbol __ICFEDIT_region_ERAM3_end__ = 0x0; +/*-Sizes-*/ +define symbol __ICFEDIT_size_cstack__ = 0x400; +define symbol __ICFEDIT_size_proc_stack__ = 0x0; +define symbol __ICFEDIT_size_heap__ = 0x800; +/**** End of ICF editor section. ###ICF###*/ + +define memory mem with size = 4G; +define symbol use_IROM1 = (__ICFEDIT_region_IROM1_start__ != 0x0 || __ICFEDIT_region_IROM1_end__ != 0x0); +define symbol use_IROM2 = (__ICFEDIT_region_IROM2_start__ != 0x0 || __ICFEDIT_region_IROM2_end__ != 0x0); +define symbol use_EROM1 = (__ICFEDIT_region_EROM1_start__ != 0x0 || __ICFEDIT_region_EROM1_end__ != 0x0); +define symbol use_EROM2 = (__ICFEDIT_region_EROM2_start__ != 0x0 || __ICFEDIT_region_EROM2_end__ != 0x0); +define symbol use_EROM3 = (__ICFEDIT_region_EROM3_start__ != 0x0 || __ICFEDIT_region_EROM3_end__ != 0x0); +define symbol use_IRAM1 = (__ICFEDIT_region_IRAM1_start__ != 0x0 || __ICFEDIT_region_IRAM1_end__ != 0x0); +define symbol use_IRAM2 = (__ICFEDIT_region_IRAM2_start__ != 0x0 || __ICFEDIT_region_IRAM2_end__ != 0x0); +define symbol use_ERAM1 = (__ICFEDIT_region_ERAM1_start__ != 0x0 || __ICFEDIT_region_ERAM1_end__ != 0x0); +define symbol use_ERAM2 = (__ICFEDIT_region_ERAM2_start__ != 0x0 || __ICFEDIT_region_ERAM2_end__ != 0x0); +define symbol use_ERAM3 = (__ICFEDIT_region_ERAM3_start__ != 0x0 || __ICFEDIT_region_ERAM3_end__ != 0x0); + +if (use_IROM1) +{ + define region IROM1_region = mem:[from __ICFEDIT_region_IROM1_start__ to __ICFEDIT_region_IROM1_end__]; +} +else +{ + define region IROM1_region = []; +} + +if (use_IROM2) +{ + define region IROM2_region = mem:[from __ICFEDIT_region_IROM2_start__ to __ICFEDIT_region_IROM2_end__]; +} +else +{ + define region IROM2_region = []; +} +define region IROM_region = IROM1_region | IROM2_region; + +if (use_EROM1) +{ + define region EROM1_region = mem:[from __ICFEDIT_region_EROM1_start__ to __ICFEDIT_region_EROM1_end__]; +} +else +{ + define region EROM1_region = []; +} +if (use_EROM2) +{ + define region EROM2_region = mem:[from __ICFEDIT_region_EROM2_start__ to __ICFEDIT_region_EROM2_end__]; +} +else +{ + define region EROM2_region = []; +} +if (use_EROM3) +{ + define region EROM3_region = mem:[from __ICFEDIT_region_EROM3_start__ to __ICFEDIT_region_EROM3_end__]; +} +else +{ + define region EROM3_region = []; +} +define region EROM_region = EROM1_region | EROM2_region | EROM3_region; + +if (use_IRAM1) +{ + define region IRAM1_region = mem:[from __ICFEDIT_region_IRAM1_start__ to __ICFEDIT_region_IRAM1_end__]; +} +else +{ + define region IRAM1_region = []; +} +if (use_IRAM2) +{ + define region IRAM2_region = mem:[from __ICFEDIT_region_IRAM2_start__ to __ICFEDIT_region_IRAM2_end__]; +} +else +{ + define region IRAM2_region = []; +} + +define region IRAM_region = IRAM1_region; + +define region TCMRAM_region = IRAM2_region; + +if (use_ERAM1) +{ + define region ERAM1_region = mem:[from __ICFEDIT_region_ERAM1_start__ to __ICFEDIT_region_ERAM1_end__]; +} +else +{ + define region ERAM1_region = []; +} +if (use_ERAM2) +{ + define region ERAM2_region = mem:[from __ICFEDIT_region_ERAM2_start__ to __ICFEDIT_region_ERAM2_end__]; +} +else +{ + define region ERAM2_region = []; +} +if (use_ERAM3) +{ + define region ERAM3_region = mem:[from __ICFEDIT_region_ERAM3_start__ to __ICFEDIT_region_ERAM3_end__]; +} +else +{ + define region ERAM3_region = []; +} +define region ERAM_region = ERAM1_region | ERAM2_region | ERAM3_region; + +initialize by copy { readwrite }; +if (isdefinedsymbol(__USE_DLIB_PERTHREAD)) +{ + // Required in a multi-threaded application + initialize by copy with packing = none { section __DLIB_PERTHREAD }; +} + +place at address mem:__ICFEDIT_intvec_start__ { readonly section .intvec }; + +if (!isempty(IROM_region)) +{ + place in IROM_region { readonly }; +} + +if (!isempty(EROM_region)) +{ + place in EROM_region { readonly section application_specific_ro }; +} + +if (!isempty(IRAM_region)) +{ + define block CSTACK with alignment = 8, size = __ICFEDIT_size_cstack__ { }; + define block PROC_STACK with alignment = 8, size = __ICFEDIT_size_proc_stack__ { }; + define block HEAP with alignment = 8, size = __ICFEDIT_size_heap__ { }; + place in IRAM_region { readwrite, block CSTACK, block PROC_STACK, block HEAP }; +} + +if (!isempty(TCMRAM_region)) +{ + place in TCMRAM_region { section .textrw }; +} + +if (!isempty(ERAM_region)) +{ + place in ERAM_region { readwrite section application_specific_rw }; +} diff --git a/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/iar/startup_apm32f405xx.s b/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/iar/startup_apm32f405xx.s new file mode 100644 index 0000000000..58ab69c4f4 --- /dev/null +++ b/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/iar/startup_apm32f405xx.s @@ -0,0 +1,608 @@ +;/** +; * @file startup_apm32f405xx.s +; * +; * @brief CMSIS Cortex-M4 based Core Device Startup File for Device startup_apm32f405xx +; * +; * @version V1.0.0 +; * +; * @date 2023-07-31 +; * +; * @attention +; * +; * Copyright (C) 2023 Geehy Semiconductor +; * +; * You may not use this file except in compliance with the +; * GEEHY COPYRIGHT NOTICE (GEEHY SOFTWARE PACKAGE LICENSE). +; * +; * The program is only for reference, which is distributed in the hope +; * that it will be useful and instructional for customers to develop +; * their software. Unless required by applicable law or agreed to in +; * writing, the program is distributed on an "AS IS" BASIS, WITHOUT +; * ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied. +; * See the GEEHY SOFTWARE PACKAGE LICENSE for the governing permissions +; * and limitations under the License. +; */ + + MODULE ?cstartup + + ;; Forward declaration of sections. + SECTION CSTACK:DATA:NOROOT(3) + + SECTION .intvec:CODE:NOROOT(2) + + EXTERN __iar_program_start + EXTERN SystemInit + PUBLIC __vector_table + + DATA +__vector_table + DCD sfe(CSTACK) + DCD Reset_Handler ; Reset Handler + + DCD NMI_Handler ; NMI Handler + DCD HardFault_Handler ; Hard Fault Handler + DCD MemManage_Handler ; MPU Fault Handler + DCD BusFault_Handler ; Bus Fault Handler + DCD UsageFault_Handler ; Usage Fault Handler + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD SVC_Handler ; SVCall Handler + DCD DebugMon_Handler ; Debug Monitor Handler + DCD 0 ; Reserved + DCD PendSV_Handler ; PendSV Handler + DCD SysTick_Handler ; SysTick Handler + + ; External Interrupts + DCD WWDT_IRQHandler ; Window WatchDog + DCD PVD_IRQHandler ; PVD through EINT Line detection + DCD TAMP_STAMP_IRQHandler ; Tamper and TimeStamps through the EINT line + DCD RTC_WKUP_IRQHandler ; RTC Wakeup through the EINT line + DCD FLASH_IRQHandler ; FLASH + DCD RCM_IRQHandler ; RCM + DCD EINT0_IRQHandler ; EINT Line0 + DCD EINT1_IRQHandler ; EINT Line1 + DCD EINT2_IRQHandler ; EINT Line2 + DCD EINT3_IRQHandler ; EINT Line3 + DCD EINT4_IRQHandler ; EINT Line4 + DCD DMA1_STR0_IRQHandler ; DMA1 Stream 0 + DCD DMA1_STR1_IRQHandler ; DMA1 Stream 1 + DCD DMA1_STR2_IRQHandler ; DMA1 Stream 2 + DCD DMA1_STR3_IRQHandler ; DMA1 Stream 3 + DCD DMA1_STR4_IRQHandler ; DMA1 Stream 4 + DCD DMA1_STR5_IRQHandler ; DMA1 Stream 5 + DCD DMA1_STR6_IRQHandler ; DMA1 Stream 6 + DCD ADC_IRQHandler ; ADC1, ADC2 and ADC3s + DCD CAN1_TX_IRQHandler ; CAN1 TX + DCD CAN1_RX0_IRQHandler ; CAN1 RX0 + DCD CAN1_RX1_IRQHandler ; CAN1 RX1 + DCD CAN1_SCE_IRQHandler ; CAN1 SCE + DCD EINT9_5_IRQHandler ; External Line[9:5]s + DCD TMR1_BRK_TMR9_IRQHandler ; TMR1 Break and TMR9 + DCD TMR1_UP_TMR10_IRQHandler ; TMR1 Update and TMR10 + DCD TMR1_TRG_COM_TMR11_IRQHandler ; TMR1 Trigger and Commutation and TMR11 + DCD TMR1_CC_IRQHandler ; TMR1 Capture Compare + DCD TMR2_IRQHandler ; TMR2 + DCD TMR3_IRQHandler ; TMR3 + DCD TMR4_IRQHandler ; TMR4 + DCD I2C1_EV_IRQHandler ; I2C1 Event + DCD I2C1_ER_IRQHandler ; I2C1 Error + DCD I2C2_EV_IRQHandler ; I2C2 Event + DCD I2C2_ER_IRQHandler ; I2C2 Error + DCD SPI1_IRQHandler ; SPI1 + DCD SPI2_IRQHandler ; SPI2 + DCD USART1_IRQHandler ; USART1 + DCD USART2_IRQHandler ; USART2 + DCD USART3_IRQHandler ; USART3 + DCD EINT15_10_IRQHandler ; External Line[15:10]s + DCD RTC_Alarm_IRQHandler ; RTC Alarm (A and B) through EINT Line + DCD OTG_FS_WKUP_IRQHandler ; OTG_FS Wakeup through EINT line + DCD TMR8_BRK_TMR12_IRQHandler ; TMR8 Break and TMR12 + DCD TMR8_UP_TMR13_IRQHandler ; TMR8 Update and TMR13 + DCD TMR8_TRG_COM_TMR14_IRQHandler ; TMR8 Trigger and Commutation and TMR14 + DCD TMR8_CC_IRQHandler ; TMR8 Capture Compare + DCD DMA1_STR7_IRQHandler ; DMA1 Stream 7 + DCD EMMC_IRQHandler ; EMMC + DCD SDIO_IRQHandler ; SDIO + DCD TMR5_IRQHandler ; TMR5 + DCD SPI3_IRQHandler ; SPI3 + DCD UART4_IRQHandler ; UART4 + DCD UART5_IRQHandler ; UART5 + DCD TMR6_DAC_IRQHandler ; TMR6 and DAC1&2 underrun errors + DCD TMR7_IRQHandler ; TMR7 + DCD DMA2_STR0_IRQHandler ; DMA2 Stream 0 + DCD DMA2_STR1_IRQHandler ; DMA2 Stream 1 + DCD DMA2_STR2_IRQHandler ; DMA2 Stream 2 + DCD DMA2_STR3_IRQHandler ; DMA2 Stream 3 + DCD DMA2_STR4_IRQHandler ; DMA2 Stream 4 + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD CAN2_TX_IRQHandler ; CAN2 TX + DCD CAN2_RX0_IRQHandler ; CAN2 RX0 + DCD CAN2_RX1_IRQHandler ; CAN2 RX1 + DCD CAN2_SCE_IRQHandler ; CAN2 SCE + DCD OTG_FS_IRQHandler ; OTG_FS + DCD DMA2_STR5_IRQHandler ; DMA2 Stream 5 + DCD DMA2_STR6_IRQHandler ; DMA2 Stream 6 + DCD DMA2_STR7_IRQHandler ; DMA2 Stream 7 + DCD USART6_IRQHandler ; USART6 + DCD I2C3_EV_IRQHandler ; I2C3 event + DCD I2C3_ER_IRQHandler ; I2C3 error + DCD OTG_HS1_EP1_OUT_IRQHandler ; OTG_HS1 End Point 1 Out + DCD OTG_HS1_EP1_IN_IRQHandler ; OTG_HS1 End Point 1 In + DCD OTG_HS1_WKUP_IRQHandler ; OTG_HS1 Wakeup through EINT + DCD OTG_HS1_IRQHandler ; OTG_HS1 + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD HASH_RNG_IRQHandler ; Hash and Rng + DCD FPU_IRQHandler ; FPU + DCD SM3_IRQHandler ; SM3 + DCD SM4_IRQHandler ; SM4 + DCD BN_IRQHandler ; BN + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; +;; Default interrupt handlers. +;; + THUMB + PUBWEAK Reset_Handler + SECTION .text:CODE:REORDER:NOROOT(2) +Reset_Handler + + LDR R0, =SystemInit + BLX R0 + LDR R0, =__iar_program_start + BX R0 + + PUBWEAK NMI_Handler + SECTION .text:CODE:REORDER:NOROOT(1) +NMI_Handler + B NMI_Handler + + PUBWEAK HardFault_Handler + SECTION .text:CODE:REORDER:NOROOT(1) +HardFault_Handler + B HardFault_Handler + + PUBWEAK MemManage_Handler + SECTION .text:CODE:REORDER:NOROOT(1) +MemManage_Handler + B MemManage_Handler + + PUBWEAK BusFault_Handler + SECTION .text:CODE:REORDER:NOROOT(1) +BusFault_Handler + B BusFault_Handler + + PUBWEAK UsageFault_Handler + SECTION .text:CODE:REORDER:NOROOT(1) +UsageFault_Handler + B UsageFault_Handler + + PUBWEAK SVC_Handler + SECTION .text:CODE:REORDER:NOROOT(1) +SVC_Handler + B SVC_Handler + + PUBWEAK DebugMon_Handler + SECTION .text:CODE:REORDER:NOROOT(1) +DebugMon_Handler + B DebugMon_Handler + + PUBWEAK PendSV_Handler + SECTION .text:CODE:REORDER:NOROOT(1) +PendSV_Handler + B PendSV_Handler + + PUBWEAK SysTick_Handler + SECTION .text:CODE:REORDER:NOROOT(1) +SysTick_Handler + B SysTick_Handler + + PUBWEAK WWDT_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +WWDT_IRQHandler + B WWDT_IRQHandler + + PUBWEAK PVD_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +PVD_IRQHandler + B PVD_IRQHandler + + PUBWEAK TAMP_STAMP_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +TAMP_STAMP_IRQHandler + B TAMP_STAMP_IRQHandler + + PUBWEAK RTC_WKUP_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +RTC_WKUP_IRQHandler + B RTC_WKUP_IRQHandler + + PUBWEAK FLASH_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +FLASH_IRQHandler + B FLASH_IRQHandler + + PUBWEAK RCM_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +RCM_IRQHandler + B RCM_IRQHandler + + PUBWEAK EINT0_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +EINT0_IRQHandler + B EINT0_IRQHandler + + PUBWEAK EINT1_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +EINT1_IRQHandler + B EINT1_IRQHandler + + PUBWEAK EINT2_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +EINT2_IRQHandler + B EINT2_IRQHandler + + PUBWEAK EINT3_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +EINT3_IRQHandler + B EINT3_IRQHandler + + PUBWEAK EINT4_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +EINT4_IRQHandler + B EINT4_IRQHandler + + PUBWEAK DMA1_STR0_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +DMA1_STR0_IRQHandler + B DMA1_STR0_IRQHandler + + PUBWEAK DMA1_STR1_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +DMA1_STR1_IRQHandler + B DMA1_STR1_IRQHandler + + PUBWEAK DMA1_STR2_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +DMA1_STR2_IRQHandler + B DMA1_STR2_IRQHandler + + PUBWEAK DMA1_STR3_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +DMA1_STR3_IRQHandler + B DMA1_STR3_IRQHandler + + PUBWEAK DMA1_STR4_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +DMA1_STR4_IRQHandler + B DMA1_STR4_IRQHandler + + PUBWEAK DMA1_STR5_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +DMA1_STR5_IRQHandler + B DMA1_STR5_IRQHandler + + PUBWEAK DMA1_STR6_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +DMA1_STR6_IRQHandler + B DMA1_STR6_IRQHandler + + PUBWEAK ADC_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +ADC_IRQHandler + B ADC_IRQHandler + + PUBWEAK CAN1_TX_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +CAN1_TX_IRQHandler + B CAN1_TX_IRQHandler + + PUBWEAK CAN1_RX0_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +CAN1_RX0_IRQHandler + B CAN1_RX0_IRQHandler + + PUBWEAK CAN1_RX1_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +CAN1_RX1_IRQHandler + B CAN1_RX1_IRQHandler + + PUBWEAK CAN1_SCE_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +CAN1_SCE_IRQHandler + B CAN1_SCE_IRQHandler + + PUBWEAK EINT9_5_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +EINT9_5_IRQHandler + B EINT9_5_IRQHandler + + PUBWEAK TMR1_BRK_TMR9_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +TMR1_BRK_TMR9_IRQHandler + B TMR1_BRK_TMR9_IRQHandler + + PUBWEAK TMR1_UP_TMR10_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +TMR1_UP_TMR10_IRQHandler + B TMR1_UP_TMR10_IRQHandler + + PUBWEAK TMR1_TRG_COM_TMR11_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +TMR1_TRG_COM_TMR11_IRQHandler + B TMR1_TRG_COM_TMR11_IRQHandler + + PUBWEAK TMR1_CC_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +TMR1_CC_IRQHandler + B TMR1_CC_IRQHandler + + PUBWEAK TMR2_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +TMR2_IRQHandler + B TMR2_IRQHandler + + PUBWEAK TMR3_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +TMR3_IRQHandler + B TMR3_IRQHandler + + PUBWEAK TMR4_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +TMR4_IRQHandler + B TMR4_IRQHandler + + PUBWEAK I2C1_EV_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +I2C1_EV_IRQHandler + B I2C1_EV_IRQHandler + + PUBWEAK I2C1_ER_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +I2C1_ER_IRQHandler + B I2C1_ER_IRQHandler + + PUBWEAK I2C2_EV_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +I2C2_EV_IRQHandler + B I2C2_EV_IRQHandler + + PUBWEAK I2C2_ER_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +I2C2_ER_IRQHandler + B I2C2_ER_IRQHandler + + PUBWEAK SPI1_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +SPI1_IRQHandler + B SPI1_IRQHandler + + PUBWEAK SPI2_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +SPI2_IRQHandler + B SPI2_IRQHandler + + PUBWEAK USART1_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +USART1_IRQHandler + B USART1_IRQHandler + + PUBWEAK USART2_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +USART2_IRQHandler + B USART2_IRQHandler + + PUBWEAK USART3_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +USART3_IRQHandler + B USART3_IRQHandler + + PUBWEAK EINT15_10_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +EINT15_10_IRQHandler + B EINT15_10_IRQHandler + + PUBWEAK RTC_Alarm_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +RTC_Alarm_IRQHandler + B RTC_Alarm_IRQHandler + + PUBWEAK OTG_FS_WKUP_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +OTG_FS_WKUP_IRQHandler + B OTG_FS_WKUP_IRQHandler + + PUBWEAK TMR8_BRK_TMR12_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +TMR8_BRK_TMR12_IRQHandler + B TMR8_BRK_TMR12_IRQHandler + + PUBWEAK TMR8_UP_TMR13_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +TMR8_UP_TMR13_IRQHandler + B TMR8_UP_TMR13_IRQHandler + + PUBWEAK TMR8_TRG_COM_TMR14_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +TMR8_TRG_COM_TMR14_IRQHandler + B TMR8_TRG_COM_TMR14_IRQHandler + + PUBWEAK TMR8_CC_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +TMR8_CC_IRQHandler + B TMR8_CC_IRQHandler + + PUBWEAK DMA1_STR7_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +DMA1_STR7_IRQHandler + B DMA1_STR7_IRQHandler + + PUBWEAK EMMC_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +EMMC_IRQHandler + B EMMC_IRQHandler + + PUBWEAK SDIO_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +SDIO_IRQHandler + B SDIO_IRQHandler + + PUBWEAK TMR5_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +TMR5_IRQHandler + B TMR5_IRQHandler + + PUBWEAK SPI3_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +SPI3_IRQHandler + B SPI3_IRQHandler + + PUBWEAK UART4_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +UART4_IRQHandler + B UART4_IRQHandler + + PUBWEAK UART5_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +UART5_IRQHandler + B UART5_IRQHandler + + PUBWEAK TMR6_DAC_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +TMR6_DAC_IRQHandler + B TMR6_DAC_IRQHandler + + PUBWEAK TMR7_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +TMR7_IRQHandler + B TMR7_IRQHandler + + PUBWEAK DMA2_STR0_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +DMA2_STR0_IRQHandler + B DMA2_STR0_IRQHandler + + PUBWEAK DMA2_STR1_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +DMA2_STR1_IRQHandler + B DMA2_STR1_IRQHandler + + PUBWEAK DMA2_STR2_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +DMA2_STR2_IRQHandler + B DMA2_STR2_IRQHandler + + PUBWEAK DMA2_STR3_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +DMA2_STR3_IRQHandler + B DMA2_STR3_IRQHandler + + PUBWEAK DMA2_STR4_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +DMA2_STR4_IRQHandler + B DMA2_STR4_IRQHandler + + PUBWEAK CAN2_TX_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +CAN2_TX_IRQHandler + B CAN2_TX_IRQHandler + + PUBWEAK CAN2_RX0_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +CAN2_RX0_IRQHandler + B CAN2_RX0_IRQHandler + + PUBWEAK CAN2_RX1_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +CAN2_RX1_IRQHandler + B CAN2_RX1_IRQHandler + + PUBWEAK CAN2_SCE_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +CAN2_SCE_IRQHandler + B CAN2_SCE_IRQHandler + + PUBWEAK OTG_FS_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +OTG_FS_IRQHandler + B OTG_FS_IRQHandler + + PUBWEAK DMA2_STR5_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +DMA2_STR5_IRQHandler + B DMA2_STR5_IRQHandler + + PUBWEAK DMA2_STR6_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +DMA2_STR6_IRQHandler + B DMA2_STR6_IRQHandler + + PUBWEAK DMA2_STR7_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +DMA2_STR7_IRQHandler + B DMA2_STR7_IRQHandler + + PUBWEAK USART6_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +USART6_IRQHandler + B USART6_IRQHandler + + PUBWEAK I2C3_EV_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +I2C3_EV_IRQHandler + B I2C3_EV_IRQHandler + + PUBWEAK I2C3_ER_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +I2C3_ER_IRQHandler + B I2C3_ER_IRQHandler + + PUBWEAK OTG_HS1_EP1_OUT_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +OTG_HS1_EP1_OUT_IRQHandler + B OTG_HS1_EP1_OUT_IRQHandler + + PUBWEAK OTG_HS1_EP1_IN_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +OTG_HS1_EP1_IN_IRQHandler + B OTG_HS1_EP1_IN_IRQHandler + + PUBWEAK OTG_HS1_WKUP_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +OTG_HS1_WKUP_IRQHandler + B OTG_HS1_WKUP_IRQHandler + + PUBWEAK OTG_HS1_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +OTG_HS1_IRQHandler + B OTG_HS1_IRQHandler + + PUBWEAK HASH_RNG_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +HASH_RNG_IRQHandler + B HASH_RNG_IRQHandler + + PUBWEAK FPU_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +FPU_IRQHandler + B FPU_IRQHandler + + PUBWEAK SM3_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +SM3_IRQHandler + B SM3_IRQHandler + + PUBWEAK SM4_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +SM4_IRQHandler + B SM4_IRQHandler + + PUBWEAK BN_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +BN_IRQHandler + B BN_IRQHandler + + END diff --git a/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/iar/startup_apm32f407xx.s b/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/iar/startup_apm32f407xx.s new file mode 100644 index 0000000000..a032e91184 --- /dev/null +++ b/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/iar/startup_apm32f407xx.s @@ -0,0 +1,623 @@ +;/** +; * @file startup_apm32f407xx.s +; * +; * @brief CMSIS Cortex-M4 based Core Device Startup File for Device startup_apm32f407xx +; * +; * @version V1.0.0 +; * +; * @date 2023-07-31 +; * +; * @attention +; * +; * Copyright (C) 2023 Geehy Semiconductor +; * +; * You may not use this file except in compliance with the +; * GEEHY COPYRIGHT NOTICE (GEEHY SOFTWARE PACKAGE LICENSE). +; * +; * The program is only for reference, which is distributed in the hope +; * that it will be useful and instructional for customers to develop +; * their software. Unless required by applicable law or agreed to in +; * writing, the program is distributed on an "AS IS" BASIS, WITHOUT +; * ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied. +; * See the GEEHY SOFTWARE PACKAGE LICENSE for the governing permissions +; * and limitations under the License. +; */ + + MODULE ?cstartup + + ;; Forward declaration of sections. + SECTION CSTACK:DATA:NOROOT(3) + + SECTION .intvec:CODE:NOROOT(2) + + EXTERN __iar_program_start + EXTERN SystemInit + PUBLIC __vector_table + + DATA +__vector_table + DCD sfe(CSTACK) + DCD Reset_Handler ; Reset Handler + + DCD NMI_Handler ; NMI Handler + DCD HardFault_Handler ; Hard Fault Handler + DCD MemManage_Handler ; MPU Fault Handler + DCD BusFault_Handler ; Bus Fault Handler + DCD UsageFault_Handler ; Usage Fault Handler + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD SVC_Handler ; SVCall Handler + DCD DebugMon_Handler ; Debug Monitor Handler + DCD 0 ; Reserved + DCD PendSV_Handler ; PendSV Handler + DCD SysTick_Handler ; SysTick Handler + + ; External Interrupts + DCD WWDT_IRQHandler ; Window WatchDog + DCD PVD_IRQHandler ; PVD through EINT Line detection + DCD TAMP_STAMP_IRQHandler ; Tamper and TimeStamps through the EINT line + DCD RTC_WKUP_IRQHandler ; RTC Wakeup through the EINT line + DCD FLASH_IRQHandler ; FLASH + DCD RCM_IRQHandler ; RCM + DCD EINT0_IRQHandler ; EINT Line0 + DCD EINT1_IRQHandler ; EINT Line1 + DCD EINT2_IRQHandler ; EINT Line2 + DCD EINT3_IRQHandler ; EINT Line3 + DCD EINT4_IRQHandler ; EINT Line4 + DCD DMA1_STR0_IRQHandler ; DMA1 Stream 0 + DCD DMA1_STR1_IRQHandler ; DMA1 Stream 1 + DCD DMA1_STR2_IRQHandler ; DMA1 Stream 2 + DCD DMA1_STR3_IRQHandler ; DMA1 Stream 3 + DCD DMA1_STR4_IRQHandler ; DMA1 Stream 4 + DCD DMA1_STR5_IRQHandler ; DMA1 Stream 5 + DCD DMA1_STR6_IRQHandler ; DMA1 Stream 6 + DCD ADC_IRQHandler ; ADC1, ADC2 and ADC3s + DCD CAN1_TX_IRQHandler ; CAN1 TX + DCD CAN1_RX0_IRQHandler ; CAN1 RX0 + DCD CAN1_RX1_IRQHandler ; CAN1 RX1 + DCD CAN1_SCE_IRQHandler ; CAN1 SCE + DCD EINT9_5_IRQHandler ; External Line[9:5]s + DCD TMR1_BRK_TMR9_IRQHandler ; TMR1 Break and TMR9 + DCD TMR1_UP_TMR10_IRQHandler ; TMR1 Update and TMR10 + DCD TMR1_TRG_COM_TMR11_IRQHandler ; TMR1 Trigger and Commutation and TMR11 + DCD TMR1_CC_IRQHandler ; TMR1 Capture Compare + DCD TMR2_IRQHandler ; TMR2 + DCD TMR3_IRQHandler ; TMR3 + DCD TMR4_IRQHandler ; TMR4 + DCD I2C1_EV_IRQHandler ; I2C1 Event + DCD I2C1_ER_IRQHandler ; I2C1 Error + DCD I2C2_EV_IRQHandler ; I2C2 Event + DCD I2C2_ER_IRQHandler ; I2C2 Error + DCD SPI1_IRQHandler ; SPI1 + DCD SPI2_IRQHandler ; SPI2 + DCD USART1_IRQHandler ; USART1 + DCD USART2_IRQHandler ; USART2 + DCD USART3_IRQHandler ; USART3 + DCD EINT15_10_IRQHandler ; External Line[15:10]s + DCD RTC_Alarm_IRQHandler ; RTC Alarm (A and B) through EINT Line + DCD OTG_FS_WKUP_IRQHandler ; OTG_FS Wakeup through EINT line + DCD TMR8_BRK_TMR12_IRQHandler ; TMR8 Break and TMR12 + DCD TMR8_UP_TMR13_IRQHandler ; TMR8 Update and TMR13 + DCD TMR8_TRG_COM_TMR14_IRQHandler ; TMR8 Trigger and Commutation and TMR14 + DCD TMR8_CC_IRQHandler ; TMR8 Capture Compare + DCD DMA1_STR7_IRQHandler ; DMA1 Stream 7 + DCD EMMC_IRQHandler ; EMMC + DCD SDIO_IRQHandler ; SDIO + DCD TMR5_IRQHandler ; TMR5 + DCD SPI3_IRQHandler ; SPI3 + DCD UART4_IRQHandler ; UART4 + DCD UART5_IRQHandler ; UART5 + DCD TMR6_DAC_IRQHandler ; TMR6 and DAC1&2 underrun errors + DCD TMR7_IRQHandler ; TMR7 + DCD DMA2_STR0_IRQHandler ; DMA2 Stream 0 + DCD DMA2_STR1_IRQHandler ; DMA2 Stream 1 + DCD DMA2_STR2_IRQHandler ; DMA2 Stream 2 + DCD DMA2_STR3_IRQHandler ; DMA2 Stream 3 + DCD DMA2_STR4_IRQHandler ; DMA2 Stream 4 + DCD ETH_IRQHandler ; Ethernet + DCD ETH_WKUP_IRQHandler ; Ethernet Wakeup through EINT line + DCD CAN2_TX_IRQHandler ; CAN2 TX + DCD CAN2_RX0_IRQHandler ; CAN2 RX0 + DCD CAN2_RX1_IRQHandler ; CAN2 RX1 + DCD CAN2_SCE_IRQHandler ; CAN2 SCE + DCD OTG_FS_IRQHandler ; OTG_FS + DCD DMA2_STR5_IRQHandler ; DMA2 Stream 5 + DCD DMA2_STR6_IRQHandler ; DMA2 Stream 6 + DCD DMA2_STR7_IRQHandler ; DMA2 Stream 7 + DCD USART6_IRQHandler ; USART6 + DCD I2C3_EV_IRQHandler ; I2C3 event + DCD I2C3_ER_IRQHandler ; I2C3 error + DCD OTG_HS1_EP1_OUT_IRQHandler ; OTG_HS1 End Point 1 Out + DCD OTG_HS1_EP1_IN_IRQHandler ; OTG_HS1 End Point 1 In + DCD OTG_HS1_WKUP_IRQHandler ; OTG_HS1 Wakeup through EINT + DCD OTG_HS1_IRQHandler ; OTG_HS1 + DCD DCI_IRQHandler ; DCI + DCD 0 ; Reserved + DCD HASH_RNG_IRQHandler ; Hash and Rng + DCD FPU_IRQHandler ; FPU + DCD SM3_IRQHandler ; SM3 + DCD SM4_IRQHandler ; SM4 + DCD BN_IRQHandler ; BN + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; +;; Default interrupt handlers. +;; + THUMB + PUBWEAK Reset_Handler + SECTION .text:CODE:REORDER:NOROOT(2) +Reset_Handler + + LDR R0, =SystemInit + BLX R0 + LDR R0, =__iar_program_start + BX R0 + + PUBWEAK NMI_Handler + SECTION .text:CODE:REORDER:NOROOT(1) +NMI_Handler + B NMI_Handler + + PUBWEAK HardFault_Handler + SECTION .text:CODE:REORDER:NOROOT(1) +HardFault_Handler + B HardFault_Handler + + PUBWEAK MemManage_Handler + SECTION .text:CODE:REORDER:NOROOT(1) +MemManage_Handler + B MemManage_Handler + + PUBWEAK BusFault_Handler + SECTION .text:CODE:REORDER:NOROOT(1) +BusFault_Handler + B BusFault_Handler + + PUBWEAK UsageFault_Handler + SECTION .text:CODE:REORDER:NOROOT(1) +UsageFault_Handler + B UsageFault_Handler + + PUBWEAK SVC_Handler + SECTION .text:CODE:REORDER:NOROOT(1) +SVC_Handler + B SVC_Handler + + PUBWEAK DebugMon_Handler + SECTION .text:CODE:REORDER:NOROOT(1) +DebugMon_Handler + B DebugMon_Handler + + PUBWEAK PendSV_Handler + SECTION .text:CODE:REORDER:NOROOT(1) +PendSV_Handler + B PendSV_Handler + + PUBWEAK SysTick_Handler + SECTION .text:CODE:REORDER:NOROOT(1) +SysTick_Handler + B SysTick_Handler + + PUBWEAK WWDT_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +WWDT_IRQHandler + B WWDT_IRQHandler + + PUBWEAK PVD_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +PVD_IRQHandler + B PVD_IRQHandler + + PUBWEAK TAMP_STAMP_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +TAMP_STAMP_IRQHandler + B TAMP_STAMP_IRQHandler + + PUBWEAK RTC_WKUP_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +RTC_WKUP_IRQHandler + B RTC_WKUP_IRQHandler + + PUBWEAK FLASH_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +FLASH_IRQHandler + B FLASH_IRQHandler + + PUBWEAK RCM_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +RCM_IRQHandler + B RCM_IRQHandler + + PUBWEAK EINT0_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +EINT0_IRQHandler + B EINT0_IRQHandler + + PUBWEAK EINT1_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +EINT1_IRQHandler + B EINT1_IRQHandler + + PUBWEAK EINT2_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +EINT2_IRQHandler + B EINT2_IRQHandler + + PUBWEAK EINT3_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +EINT3_IRQHandler + B EINT3_IRQHandler + + PUBWEAK EINT4_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +EINT4_IRQHandler + B EINT4_IRQHandler + + PUBWEAK DMA1_STR0_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +DMA1_STR0_IRQHandler + B DMA1_STR0_IRQHandler + + PUBWEAK DMA1_STR1_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +DMA1_STR1_IRQHandler + B DMA1_STR1_IRQHandler + + PUBWEAK DMA1_STR2_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +DMA1_STR2_IRQHandler + B DMA1_STR2_IRQHandler + + PUBWEAK DMA1_STR3_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +DMA1_STR3_IRQHandler + B DMA1_STR3_IRQHandler + + PUBWEAK DMA1_STR4_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +DMA1_STR4_IRQHandler + B DMA1_STR4_IRQHandler + + PUBWEAK DMA1_STR5_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +DMA1_STR5_IRQHandler + B DMA1_STR5_IRQHandler + + PUBWEAK DMA1_STR6_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +DMA1_STR6_IRQHandler + B DMA1_STR6_IRQHandler + + PUBWEAK ADC_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +ADC_IRQHandler + B ADC_IRQHandler + + PUBWEAK CAN1_TX_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +CAN1_TX_IRQHandler + B CAN1_TX_IRQHandler + + PUBWEAK CAN1_RX0_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +CAN1_RX0_IRQHandler + B CAN1_RX0_IRQHandler + + PUBWEAK CAN1_RX1_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +CAN1_RX1_IRQHandler + B CAN1_RX1_IRQHandler + + PUBWEAK CAN1_SCE_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +CAN1_SCE_IRQHandler + B CAN1_SCE_IRQHandler + + PUBWEAK EINT9_5_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +EINT9_5_IRQHandler + B EINT9_5_IRQHandler + + PUBWEAK TMR1_BRK_TMR9_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +TMR1_BRK_TMR9_IRQHandler + B TMR1_BRK_TMR9_IRQHandler + + PUBWEAK TMR1_UP_TMR10_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +TMR1_UP_TMR10_IRQHandler + B TMR1_UP_TMR10_IRQHandler + + PUBWEAK TMR1_TRG_COM_TMR11_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +TMR1_TRG_COM_TMR11_IRQHandler + B TMR1_TRG_COM_TMR11_IRQHandler + + PUBWEAK TMR1_CC_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +TMR1_CC_IRQHandler + B TMR1_CC_IRQHandler + + PUBWEAK TMR2_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +TMR2_IRQHandler + B TMR2_IRQHandler + + PUBWEAK TMR3_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +TMR3_IRQHandler + B TMR3_IRQHandler + + PUBWEAK TMR4_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +TMR4_IRQHandler + B TMR4_IRQHandler + + PUBWEAK I2C1_EV_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +I2C1_EV_IRQHandler + B I2C1_EV_IRQHandler + + PUBWEAK I2C1_ER_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +I2C1_ER_IRQHandler + B I2C1_ER_IRQHandler + + PUBWEAK I2C2_EV_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +I2C2_EV_IRQHandler + B I2C2_EV_IRQHandler + + PUBWEAK I2C2_ER_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +I2C2_ER_IRQHandler + B I2C2_ER_IRQHandler + + PUBWEAK SPI1_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +SPI1_IRQHandler + B SPI1_IRQHandler + + PUBWEAK SPI2_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +SPI2_IRQHandler + B SPI2_IRQHandler + + PUBWEAK USART1_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +USART1_IRQHandler + B USART1_IRQHandler + + PUBWEAK USART2_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +USART2_IRQHandler + B USART2_IRQHandler + + PUBWEAK USART3_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +USART3_IRQHandler + B USART3_IRQHandler + + PUBWEAK EINT15_10_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +EINT15_10_IRQHandler + B EINT15_10_IRQHandler + + PUBWEAK RTC_Alarm_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +RTC_Alarm_IRQHandler + B RTC_Alarm_IRQHandler + + PUBWEAK OTG_FS_WKUP_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +OTG_FS_WKUP_IRQHandler + B OTG_FS_WKUP_IRQHandler + + PUBWEAK TMR8_BRK_TMR12_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +TMR8_BRK_TMR12_IRQHandler + B TMR8_BRK_TMR12_IRQHandler + + PUBWEAK TMR8_UP_TMR13_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +TMR8_UP_TMR13_IRQHandler + B TMR8_UP_TMR13_IRQHandler + + PUBWEAK TMR8_TRG_COM_TMR14_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +TMR8_TRG_COM_TMR14_IRQHandler + B TMR8_TRG_COM_TMR14_IRQHandler + + PUBWEAK TMR8_CC_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +TMR8_CC_IRQHandler + B TMR8_CC_IRQHandler + + PUBWEAK DMA1_STR7_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +DMA1_STR7_IRQHandler + B DMA1_STR7_IRQHandler + + PUBWEAK EMMC_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +EMMC_IRQHandler + B EMMC_IRQHandler + + PUBWEAK SDIO_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +SDIO_IRQHandler + B SDIO_IRQHandler + + PUBWEAK TMR5_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +TMR5_IRQHandler + B TMR5_IRQHandler + + PUBWEAK SPI3_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +SPI3_IRQHandler + B SPI3_IRQHandler + + PUBWEAK UART4_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +UART4_IRQHandler + B UART4_IRQHandler + + PUBWEAK UART5_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +UART5_IRQHandler + B UART5_IRQHandler + + PUBWEAK TMR6_DAC_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +TMR6_DAC_IRQHandler + B TMR6_DAC_IRQHandler + + PUBWEAK TMR7_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +TMR7_IRQHandler + B TMR7_IRQHandler + + PUBWEAK DMA2_STR0_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +DMA2_STR0_IRQHandler + B DMA2_STR0_IRQHandler + + PUBWEAK DMA2_STR1_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +DMA2_STR1_IRQHandler + B DMA2_STR1_IRQHandler + + PUBWEAK DMA2_STR2_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +DMA2_STR2_IRQHandler + B DMA2_STR2_IRQHandler + + PUBWEAK DMA2_STR3_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +DMA2_STR3_IRQHandler + B DMA2_STR3_IRQHandler + + PUBWEAK DMA2_STR4_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +DMA2_STR4_IRQHandler + B DMA2_STR4_IRQHandler + + PUBWEAK ETH_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +ETH_IRQHandler + B ETH_IRQHandler + + PUBWEAK ETH_WKUP_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +ETH_WKUP_IRQHandler + B ETH_WKUP_IRQHandler + + PUBWEAK CAN2_TX_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +CAN2_TX_IRQHandler + B CAN2_TX_IRQHandler + + PUBWEAK CAN2_RX0_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +CAN2_RX0_IRQHandler + B CAN2_RX0_IRQHandler + + PUBWEAK CAN2_RX1_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +CAN2_RX1_IRQHandler + B CAN2_RX1_IRQHandler + + PUBWEAK CAN2_SCE_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +CAN2_SCE_IRQHandler + B CAN2_SCE_IRQHandler + + PUBWEAK OTG_FS_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +OTG_FS_IRQHandler + B OTG_FS_IRQHandler + + PUBWEAK DMA2_STR5_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +DMA2_STR5_IRQHandler + B DMA2_STR5_IRQHandler + + PUBWEAK DMA2_STR6_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +DMA2_STR6_IRQHandler + B DMA2_STR6_IRQHandler + + PUBWEAK DMA2_STR7_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +DMA2_STR7_IRQHandler + B DMA2_STR7_IRQHandler + + PUBWEAK USART6_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +USART6_IRQHandler + B USART6_IRQHandler + + PUBWEAK I2C3_EV_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +I2C3_EV_IRQHandler + B I2C3_EV_IRQHandler + + PUBWEAK I2C3_ER_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +I2C3_ER_IRQHandler + B I2C3_ER_IRQHandler + + PUBWEAK OTG_HS1_EP1_OUT_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +OTG_HS1_EP1_OUT_IRQHandler + B OTG_HS1_EP1_OUT_IRQHandler + + PUBWEAK OTG_HS1_EP1_IN_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +OTG_HS1_EP1_IN_IRQHandler + B OTG_HS1_EP1_IN_IRQHandler + + PUBWEAK OTG_HS1_WKUP_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +OTG_HS1_WKUP_IRQHandler + B OTG_HS1_WKUP_IRQHandler + + PUBWEAK OTG_HS1_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +OTG_HS1_IRQHandler + B OTG_HS1_IRQHandler + + PUBWEAK DCI_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +DCI_IRQHandler + B DCI_IRQHandler + + PUBWEAK HASH_RNG_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +HASH_RNG_IRQHandler + B HASH_RNG_IRQHandler + + PUBWEAK FPU_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +FPU_IRQHandler + B FPU_IRQHandler + + PUBWEAK SM3_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +SM3_IRQHandler + B SM3_IRQHandler + + PUBWEAK SM4_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +SM4_IRQHandler + B SM4_IRQHandler + + PUBWEAK BN_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +BN_IRQHandler + B BN_IRQHandler + + END diff --git a/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/iar/startup_apm32f411xx.s b/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/iar/startup_apm32f411xx.s new file mode 100644 index 0000000000..adc6332e97 --- /dev/null +++ b/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/iar/startup_apm32f411xx.s @@ -0,0 +1,579 @@ +;/** +; * @file startup_apm32f411xx.s +; * +; * @brief CMSIS Cortex-M4 based Core Device Startup File for Device startup_apm32f411xx +; * +; * @version V1.0.0 +; * +; * @date 2023-12-01 +; * +; * @attention +; * +; * Copyright (C) 2023 Geehy Semiconductor +; * +; * You may not use this file except in compliance with the +; * GEEHY COPYRIGHT NOTICE (GEEHY SOFTWARE PACKAGE LICENSE). +; * +; * The program is only for reference, which is distributed in the hope +; * that it will be useful and instructional for customers to develop +; * their software. Unless required by applicable law or agreed to in +; * writing, the program is distributed on an "AS IS" BASIS, WITHOUT +; * ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied. +; * See the GEEHY SOFTWARE PACKAGE LICENSE for the governing permissions +; * and limitations under the License. +; */ + + MODULE ?cstartup + + ;; Forward declaration of sections. + SECTION CSTACK:DATA:NOROOT(3) + + SECTION .intvec:CODE:NOROOT(2) + + EXTERN __iar_program_start + EXTERN SystemInit + PUBLIC __vector_table + + DATA +__vector_table + DCD sfe(CSTACK) + DCD Reset_Handler ; Reset Handler + + DCD NMI_Handler ; NMI Handler + DCD HardFault_Handler ; Hard Fault Handler + DCD MemManage_Handler ; MPU Fault Handler + DCD BusFault_Handler ; Bus Fault Handler + DCD UsageFault_Handler ; Usage Fault Handler + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD SVC_Handler ; SVCall Handler + DCD DebugMon_Handler ; Debug Monitor Handler + DCD 0 ; Reserved + DCD PendSV_Handler ; PendSV Handler + DCD SysTick_Handler ; SysTick Handler + + ; External Interrupts + DCD WWDT_IRQHandler ; Window WatchDog + DCD PVD_IRQHandler ; PVD through EINT Line detection + DCD TAMP_STAMP_IRQHandler ; Tamper and TimeStamps through the EINT line + DCD RTC_WKUP_IRQHandler ; RTC Wakeup through the EINT line + DCD FLASH_IRQHandler ; FLASH + DCD RCM_IRQHandler ; RCM + DCD EINT0_IRQHandler ; EINT Line0 + DCD EINT1_IRQHandler ; EINT Line1 + DCD EINT2_IRQHandler ; EINT Line2 + DCD EINT3_IRQHandler ; EINT Line3 + DCD EINT4_IRQHandler ; EINT Line4 + DCD DMA1_STR0_IRQHandler ; DMA1 Stream 0 + DCD DMA1_STR1_IRQHandler ; DMA1 Stream 1 + DCD DMA1_STR2_IRQHandler ; DMA1 Stream 2 + DCD DMA1_STR3_IRQHandler ; DMA1 Stream 3 + DCD DMA1_STR4_IRQHandler ; DMA1 Stream 4 + DCD DMA1_STR5_IRQHandler ; DMA1 Stream 5 + DCD DMA1_STR6_IRQHandler ; DMA1 Stream 6 + DCD ADC_IRQHandler ; ADC1, ADC2 + DCD CAN1_TX_IRQHandler ; CAN1 TX + DCD CAN1_RX0_IRQHandler ; CAN1 RX0 + DCD CAN1_RX1_IRQHandler ; CAN1 RX1 + DCD CAN1_SCE_IRQHandler ; CAN1 SCE + DCD EINT9_5_IRQHandler ; External Line[9:5]s + DCD TMR1_BRK_TMR9_IRQHandler ; TMR1 Break and TMR9 + DCD TMR1_UP_TMR10_IRQHandler ; TMR1 Update and TMR10 + DCD TMR1_TRG_COM_TMR11_IRQHandler ; TMR1 Trigger and Commutation and TMR11 + DCD TMR1_CC_IRQHandler ; TMR1 Capture Compare + DCD TMR2_IRQHandler ; TMR2 + DCD TMR3_IRQHandler ; TMR3 + DCD TMR4_IRQHandler ; TMR4 + DCD I2C1_EV_IRQHandler ; I2C1 Event + DCD I2C1_ER_IRQHandler ; I2C1 Error + DCD I2C2_EV_IRQHandler ; I2C2 Event + DCD I2C2_ER_IRQHandler ; I2C2 Error + DCD SPI1_IRQHandler ; SPI1 + DCD SPI2_IRQHandler ; SPI2 + DCD USART1_IRQHandler ; USART1 + DCD USART2_IRQHandler ; USART2 + DCD USART3_IRQHandler ; USART3 + DCD EINT15_10_IRQHandler ; External Line[15:10]s + DCD RTC_Alarm_IRQHandler ; RTC Alarm (A and B) through EINT Line + DCD OTG_FS_WKUP_IRQHandler ; OTG_FS Wakeup through EINT line + DCD TMR8_BRK_TMR12_IRQHandler ; TMR8 Break and TMR12 + DCD TMR8_UP_TMR13_IRQHandler ; TMR8 Update and TMR13 + DCD TMR8_TRG_COM_TMR14_IRQHandler ; TMR8 Trigger and Commutation and TMR14 + DCD TMR8_CC_IRQHandler ; TMR8 Capture Compare + DCD DMA1_STR7_IRQHandler ; DMA1 Stream 7 + DCD SMC_IRQHandler ; SMC + DCD SDIO_IRQHandler ; SDIO + DCD TMR5_IRQHandler ; TMR5 + DCD SPI3_IRQHandler ; SPI3 + DCD UART4_IRQHandler ; UART4 + DCD UART5_IRQHandler ; UART5 + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD DMA2_STR0_IRQHandler ; DMA2 Stream 0 + DCD DMA2_STR1_IRQHandler ; DMA2 Stream 1 + DCD DMA2_STR2_IRQHandler ; DMA2 Stream 2 + DCD DMA2_STR3_IRQHandler ; DMA2 Stream 3 + DCD DMA2_STR4_IRQHandler ; DMA2 Stream 4 + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD CAN2_TX_IRQHandler ; CAN2 TX + DCD CAN2_RX0_IRQHandler ; CAN2 RX0 + DCD CAN2_RX1_IRQHandler ; CAN2 RX1 + DCD CAN2_SCE_IRQHandler ; CAN2 SCE + DCD OTG_FS_IRQHandler ; OTG_FS + DCD DMA2_STR5_IRQHandler ; DMA2 Stream 5 + DCD DMA2_STR6_IRQHandler ; DMA2 Stream 6 + DCD DMA2_STR7_IRQHandler ; DMA2 Stream 7 + DCD USART6_IRQHandler ; USART6 + DCD I2C3_EV_IRQHandler ; I2C3 event + DCD I2C3_ER_IRQHandler ; I2C3 error + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD RNG_IRQHandler ; RNG + DCD FPU_IRQHandler ; FPU + DCD 0 ; Reserved + DCD QSPI_IRQHandler ; QSPI + DCD SPI4_IRQHandler ; SPI4 + DCD SPI5_IRQHandler ; SPI5 + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; +;; Default interrupt handlers. +;; + THUMB + PUBWEAK Reset_Handler + SECTION .text:CODE:REORDER:NOROOT(2) +Reset_Handler + + LDR R0, =SystemInit + BLX R0 + LDR R0, =__iar_program_start + BX R0 + + PUBWEAK NMI_Handler + SECTION .text:CODE:REORDER:NOROOT(1) +NMI_Handler + B NMI_Handler + + PUBWEAK HardFault_Handler + SECTION .text:CODE:REORDER:NOROOT(1) +HardFault_Handler + B HardFault_Handler + + PUBWEAK MemManage_Handler + SECTION .text:CODE:REORDER:NOROOT(1) +MemManage_Handler + B MemManage_Handler + + PUBWEAK BusFault_Handler + SECTION .text:CODE:REORDER:NOROOT(1) +BusFault_Handler + B BusFault_Handler + + PUBWEAK UsageFault_Handler + SECTION .text:CODE:REORDER:NOROOT(1) +UsageFault_Handler + B UsageFault_Handler + + PUBWEAK SVC_Handler + SECTION .text:CODE:REORDER:NOROOT(1) +SVC_Handler + B SVC_Handler + + PUBWEAK DebugMon_Handler + SECTION .text:CODE:REORDER:NOROOT(1) +DebugMon_Handler + B DebugMon_Handler + + PUBWEAK PendSV_Handler + SECTION .text:CODE:REORDER:NOROOT(1) +PendSV_Handler + B PendSV_Handler + + PUBWEAK SysTick_Handler + SECTION .text:CODE:REORDER:NOROOT(1) +SysTick_Handler + B SysTick_Handler + + PUBWEAK WWDT_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +WWDT_IRQHandler + B WWDT_IRQHandler + + PUBWEAK PVD_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +PVD_IRQHandler + B PVD_IRQHandler + + PUBWEAK TAMP_STAMP_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +TAMP_STAMP_IRQHandler + B TAMP_STAMP_IRQHandler + + PUBWEAK RTC_WKUP_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +RTC_WKUP_IRQHandler + B RTC_WKUP_IRQHandler + + PUBWEAK FLASH_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +FLASH_IRQHandler + B FLASH_IRQHandler + + PUBWEAK RCM_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +RCM_IRQHandler + B RCM_IRQHandler + + PUBWEAK EINT0_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +EINT0_IRQHandler + B EINT0_IRQHandler + + PUBWEAK EINT1_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +EINT1_IRQHandler + B EINT1_IRQHandler + + PUBWEAK EINT2_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +EINT2_IRQHandler + B EINT2_IRQHandler + + PUBWEAK EINT3_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +EINT3_IRQHandler + B EINT3_IRQHandler + + PUBWEAK EINT4_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +EINT4_IRQHandler + B EINT4_IRQHandler + + PUBWEAK DMA1_STR0_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +DMA1_STR0_IRQHandler + B DMA1_STR0_IRQHandler + + PUBWEAK DMA1_STR1_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +DMA1_STR1_IRQHandler + B DMA1_STR1_IRQHandler + + PUBWEAK DMA1_STR2_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +DMA1_STR2_IRQHandler + B DMA1_STR2_IRQHandler + + PUBWEAK DMA1_STR3_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +DMA1_STR3_IRQHandler + B DMA1_STR3_IRQHandler + + PUBWEAK DMA1_STR4_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +DMA1_STR4_IRQHandler + B DMA1_STR4_IRQHandler + + PUBWEAK DMA1_STR5_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +DMA1_STR5_IRQHandler + B DMA1_STR5_IRQHandler + + PUBWEAK DMA1_STR6_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +DMA1_STR6_IRQHandler + B DMA1_STR6_IRQHandler + + PUBWEAK ADC_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +ADC_IRQHandler + B ADC_IRQHandler + + PUBWEAK CAN1_TX_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +CAN1_TX_IRQHandler + B CAN1_TX_IRQHandler + + PUBWEAK CAN1_RX0_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +CAN1_RX0_IRQHandler + B CAN1_RX0_IRQHandler + + PUBWEAK CAN1_RX1_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +CAN1_RX1_IRQHandler + B CAN1_RX1_IRQHandler + + PUBWEAK CAN1_SCE_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +CAN1_SCE_IRQHandler + B CAN1_SCE_IRQHandler + + PUBWEAK EINT9_5_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +EINT9_5_IRQHandler + B EINT9_5_IRQHandler + + PUBWEAK TMR1_BRK_TMR9_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +TMR1_BRK_TMR9_IRQHandler + B TMR1_BRK_TMR9_IRQHandler + + PUBWEAK TMR1_UP_TMR10_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +TMR1_UP_TMR10_IRQHandler + B TMR1_UP_TMR10_IRQHandler + + PUBWEAK TMR1_TRG_COM_TMR11_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +TMR1_TRG_COM_TMR11_IRQHandler + B TMR1_TRG_COM_TMR11_IRQHandler + + PUBWEAK TMR1_CC_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +TMR1_CC_IRQHandler + B TMR1_CC_IRQHandler + + PUBWEAK TMR2_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +TMR2_IRQHandler + B TMR2_IRQHandler + + PUBWEAK TMR3_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +TMR3_IRQHandler + B TMR3_IRQHandler + + PUBWEAK TMR4_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +TMR4_IRQHandler + B TMR4_IRQHandler + + PUBWEAK I2C1_EV_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +I2C1_EV_IRQHandler + B I2C1_EV_IRQHandler + + PUBWEAK I2C1_ER_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +I2C1_ER_IRQHandler + B I2C1_ER_IRQHandler + + PUBWEAK I2C2_EV_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +I2C2_EV_IRQHandler + B I2C2_EV_IRQHandler + + PUBWEAK I2C2_ER_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +I2C2_ER_IRQHandler + B I2C2_ER_IRQHandler + + PUBWEAK SPI1_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +SPI1_IRQHandler + B SPI1_IRQHandler + + PUBWEAK SPI2_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +SPI2_IRQHandler + B SPI2_IRQHandler + + PUBWEAK USART1_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +USART1_IRQHandler + B USART1_IRQHandler + + PUBWEAK USART2_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +USART2_IRQHandler + B USART2_IRQHandler + + PUBWEAK USART3_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +USART3_IRQHandler + B USART3_IRQHandler + + PUBWEAK EINT15_10_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +EINT15_10_IRQHandler + B EINT15_10_IRQHandler + + PUBWEAK RTC_Alarm_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +RTC_Alarm_IRQHandler + B RTC_Alarm_IRQHandler + + PUBWEAK OTG_FS_WKUP_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +OTG_FS_WKUP_IRQHandler + B OTG_FS_WKUP_IRQHandler + + PUBWEAK TMR8_BRK_TMR12_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +TMR8_BRK_TMR12_IRQHandler + B TMR8_BRK_TMR12_IRQHandler + + PUBWEAK TMR8_UP_TMR13_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +TMR8_UP_TMR13_IRQHandler + B TMR8_UP_TMR13_IRQHandler + + PUBWEAK TMR8_TRG_COM_TMR14_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +TMR8_TRG_COM_TMR14_IRQHandler + B TMR8_TRG_COM_TMR14_IRQHandler + + PUBWEAK TMR8_CC_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +TMR8_CC_IRQHandler + B TMR8_CC_IRQHandler + + PUBWEAK DMA1_STR7_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +DMA1_STR7_IRQHandler + B DMA1_STR7_IRQHandler + + PUBWEAK SMC_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +SMC_IRQHandler + B SMC_IRQHandler + + PUBWEAK SDIO_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +SDIO_IRQHandler + B SDIO_IRQHandler + + PUBWEAK TMR5_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +TMR5_IRQHandler + B TMR5_IRQHandler + + PUBWEAK SPI3_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +SPI3_IRQHandler + B SPI3_IRQHandler + + PUBWEAK UART4_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +UART4_IRQHandler + B UART4_IRQHandler + + PUBWEAK UART5_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +UART5_IRQHandler + B UART5_IRQHandler + + PUBWEAK DMA2_STR0_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +DMA2_STR0_IRQHandler + B DMA2_STR0_IRQHandler + + PUBWEAK DMA2_STR1_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +DMA2_STR1_IRQHandler + B DMA2_STR1_IRQHandler + + PUBWEAK DMA2_STR2_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +DMA2_STR2_IRQHandler + B DMA2_STR2_IRQHandler + + PUBWEAK DMA2_STR3_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +DMA2_STR3_IRQHandler + B DMA2_STR3_IRQHandler + + PUBWEAK DMA2_STR4_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +DMA2_STR4_IRQHandler + B DMA2_STR4_IRQHandler + + PUBWEAK CAN2_TX_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +CAN2_TX_IRQHandler + B CAN2_TX_IRQHandler + + PUBWEAK CAN2_RX0_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +CAN2_RX0_IRQHandler + B CAN2_RX0_IRQHandler + + PUBWEAK CAN2_RX1_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +CAN2_RX1_IRQHandler + B CAN2_RX1_IRQHandler + + PUBWEAK CAN2_SCE_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +CAN2_SCE_IRQHandler + B CAN2_SCE_IRQHandler + + PUBWEAK OTG_FS_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +OTG_FS_IRQHandler + B OTG_FS_IRQHandler + + PUBWEAK DMA2_STR5_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +DMA2_STR5_IRQHandler + B DMA2_STR5_IRQHandler + + PUBWEAK DMA2_STR6_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +DMA2_STR6_IRQHandler + B DMA2_STR6_IRQHandler + + PUBWEAK DMA2_STR7_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +DMA2_STR7_IRQHandler + B DMA2_STR7_IRQHandler + + PUBWEAK USART6_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +USART6_IRQHandler + B USART6_IRQHandler + + PUBWEAK I2C3_EV_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +I2C3_EV_IRQHandler + B I2C3_EV_IRQHandler + + PUBWEAK I2C3_ER_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +I2C3_ER_IRQHandler + B I2C3_ER_IRQHandler + + PUBWEAK RNG_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +RNG_IRQHandler + B RNG_IRQHandler + + PUBWEAK FPU_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +FPU_IRQHandler + B FPU_IRQHandler + + PUBWEAK QSPI_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +QSPI_IRQHandler + B QSPI_IRQHandler + + PUBWEAK SPI4_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +SPI4_IRQHandler + B SPI4_IRQHandler + + PUBWEAK SPI5_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +SPI5_IRQHandler + B SPI5_IRQHandler + + END diff --git a/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/iar/startup_apm32f417xx.s b/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/iar/startup_apm32f417xx.s new file mode 100644 index 0000000000..9a37211583 --- /dev/null +++ b/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/iar/startup_apm32f417xx.s @@ -0,0 +1,628 @@ +;/** +; * @file startup_apm32f417xx.s +; * +; * @brief CMSIS Cortex-M4 based Core Device Startup File for Device startup_apm32f417xx +; * +; * @version V1.0.0 +; * +; * @date 2023-07-31 +; * +; * @attention +; * +; * Copyright (C) 2023 Geehy Semiconductor +; * +; * You may not use this file except in compliance with the +; * GEEHY COPYRIGHT NOTICE (GEEHY SOFTWARE PACKAGE LICENSE). +; * +; * The program is only for reference, which is distributed in the hope +; * that it will be useful and instructional for customers to develop +; * their software. Unless required by applicable law or agreed to in +; * writing, the program is distributed on an "AS IS" BASIS, WITHOUT +; * ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied. +; * See the GEEHY SOFTWARE PACKAGE LICENSE for the governing permissions +; * and limitations under the License. +; */ + + MODULE ?cstartup + + ;; Forward declaration of sections. + SECTION CSTACK:DATA:NOROOT(3) + + SECTION .intvec:CODE:NOROOT(2) + + EXTERN __iar_program_start + EXTERN SystemInit + PUBLIC __vector_table + + DATA +__vector_table + DCD sfe(CSTACK) + DCD Reset_Handler ; Reset Handler + + DCD NMI_Handler ; NMI Handler + DCD HardFault_Handler ; Hard Fault Handler + DCD MemManage_Handler ; MPU Fault Handler + DCD BusFault_Handler ; Bus Fault Handler + DCD UsageFault_Handler ; Usage Fault Handler + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD SVC_Handler ; SVCall Handler + DCD DebugMon_Handler ; Debug Monitor Handler + DCD 0 ; Reserved + DCD PendSV_Handler ; PendSV Handler + DCD SysTick_Handler ; SysTick Handler + + ; External Interrupts + DCD WWDT_IRQHandler ; Window WatchDog + DCD PVD_IRQHandler ; PVD through EINT Line detection + DCD TAMP_STAMP_IRQHandler ; Tamper and TimeStamps through the EINT line + DCD RTC_WKUP_IRQHandler ; RTC Wakeup through the EINT line + DCD FLASH_IRQHandler ; FLASH + DCD RCM_IRQHandler ; RCM + DCD EINT0_IRQHandler ; EINT Line0 + DCD EINT1_IRQHandler ; EINT Line1 + DCD EINT2_IRQHandler ; EINT Line2 + DCD EINT3_IRQHandler ; EINT Line3 + DCD EINT4_IRQHandler ; EINT Line4 + DCD DMA1_STR0_IRQHandler ; DMA1 Stream 0 + DCD DMA1_STR1_IRQHandler ; DMA1 Stream 1 + DCD DMA1_STR2_IRQHandler ; DMA1 Stream 2 + DCD DMA1_STR3_IRQHandler ; DMA1 Stream 3 + DCD DMA1_STR4_IRQHandler ; DMA1 Stream 4 + DCD DMA1_STR5_IRQHandler ; DMA1 Stream 5 + DCD DMA1_STR6_IRQHandler ; DMA1 Stream 6 + DCD ADC_IRQHandler ; ADC1, ADC2 and ADC3s + DCD CAN1_TX_IRQHandler ; CAN1 TX + DCD CAN1_RX0_IRQHandler ; CAN1 RX0 + DCD CAN1_RX1_IRQHandler ; CAN1 RX1 + DCD CAN1_SCE_IRQHandler ; CAN1 SCE + DCD EINT9_5_IRQHandler ; External Line[9:5]s + DCD TMR1_BRK_TMR9_IRQHandler ; TMR1 Break and TMR9 + DCD TMR1_UP_TMR10_IRQHandler ; TMR1 Update and TMR10 + DCD TMR1_TRG_COM_TMR11_IRQHandler ; TMR1 Trigger and Commutation and TMR11 + DCD TMR1_CC_IRQHandler ; TMR1 Capture Compare + DCD TMR2_IRQHandler ; TMR2 + DCD TMR3_IRQHandler ; TMR3 + DCD TMR4_IRQHandler ; TMR4 + DCD I2C1_EV_IRQHandler ; I2C1 Event + DCD I2C1_ER_IRQHandler ; I2C1 Error + DCD I2C2_EV_IRQHandler ; I2C2 Event + DCD I2C2_ER_IRQHandler ; I2C2 Error + DCD SPI1_IRQHandler ; SPI1 + DCD SPI2_IRQHandler ; SPI2 + DCD USART1_IRQHandler ; USART1 + DCD USART2_IRQHandler ; USART2 + DCD USART3_IRQHandler ; USART3 + DCD EINT15_10_IRQHandler ; External Line[15:10]s + DCD RTC_Alarm_IRQHandler ; RTC Alarm (A and B) through EINT Line + DCD OTG_FS_WKUP_IRQHandler ; OTG_FS Wakeup through EINT line + DCD TMR8_BRK_TMR12_IRQHandler ; TMR8 Break and TMR12 + DCD TMR8_UP_TMR13_IRQHandler ; TMR8 Update and TMR13 + DCD TMR8_TRG_COM_TMR14_IRQHandler ; TMR8 Trigger and Commutation and TMR14 + DCD TMR8_CC_IRQHandler ; TMR8 Capture Compare + DCD DMA1_STR7_IRQHandler ; DMA1 Stream 7 + DCD EMMC_IRQHandler ; EMMC + DCD SDIO_IRQHandler ; SDIO + DCD TMR5_IRQHandler ; TMR5 + DCD SPI3_IRQHandler ; SPI3 + DCD UART4_IRQHandler ; UART4 + DCD UART5_IRQHandler ; UART5 + DCD TMR6_DAC_IRQHandler ; TMR6 and DAC1&2 underrun errors + DCD TMR7_IRQHandler ; TMR7 + DCD DMA2_STR0_IRQHandler ; DMA2 Stream 0 + DCD DMA2_STR1_IRQHandler ; DMA2 Stream 1 + DCD DMA2_STR2_IRQHandler ; DMA2 Stream 2 + DCD DMA2_STR3_IRQHandler ; DMA2 Stream 3 + DCD DMA2_STR4_IRQHandler ; DMA2 Stream 4 + DCD ETH_IRQHandler ; Ethernet + DCD ETH_WKUP_IRQHandler ; Ethernet Wakeup through EINT line + DCD CAN2_TX_IRQHandler ; CAN2 TX + DCD CAN2_RX0_IRQHandler ; CAN2 RX0 + DCD CAN2_RX1_IRQHandler ; CAN2 RX1 + DCD CAN2_SCE_IRQHandler ; CAN2 SCE + DCD OTG_FS_IRQHandler ; OTG_FS + DCD DMA2_STR5_IRQHandler ; DMA2 Stream 5 + DCD DMA2_STR6_IRQHandler ; DMA2 Stream 6 + DCD DMA2_STR7_IRQHandler ; DMA2 Stream 7 + DCD USART6_IRQHandler ; USART6 + DCD I2C3_EV_IRQHandler ; I2C3 event + DCD I2C3_ER_IRQHandler ; I2C3 error + DCD OTG_HS1_EP1_OUT_IRQHandler ; OTG_HS1 End Point 1 Out + DCD OTG_HS1_EP1_IN_IRQHandler ; OTG_HS1 End Point 1 In + DCD OTG_HS1_WKUP_IRQHandler ; OTG_HS1 Wakeup through EINT + DCD OTG_HS1_IRQHandler ; OTG_HS1 + DCD DCI_IRQHandler ; DCI + DCD CRYP_IRQHandler ; CRYP crypto + DCD HASH_RNG_IRQHandler ; Hash and Rng + DCD FPU_IRQHandler ; FPU + DCD SM3_IRQHandler ; SM3 + DCD SM4_IRQHandler ; SM4 + DCD BN_IRQHandler ; BN + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; +;; Default interrupt handlers. +;; + THUMB + PUBWEAK Reset_Handler + SECTION .text:CODE:REORDER:NOROOT(2) +Reset_Handler + + LDR R0, =SystemInit + BLX R0 + LDR R0, =__iar_program_start + BX R0 + + PUBWEAK NMI_Handler + SECTION .text:CODE:REORDER:NOROOT(1) +NMI_Handler + B NMI_Handler + + PUBWEAK HardFault_Handler + SECTION .text:CODE:REORDER:NOROOT(1) +HardFault_Handler + B HardFault_Handler + + PUBWEAK MemManage_Handler + SECTION .text:CODE:REORDER:NOROOT(1) +MemManage_Handler + B MemManage_Handler + + PUBWEAK BusFault_Handler + SECTION .text:CODE:REORDER:NOROOT(1) +BusFault_Handler + B BusFault_Handler + + PUBWEAK UsageFault_Handler + SECTION .text:CODE:REORDER:NOROOT(1) +UsageFault_Handler + B UsageFault_Handler + + PUBWEAK SVC_Handler + SECTION .text:CODE:REORDER:NOROOT(1) +SVC_Handler + B SVC_Handler + + PUBWEAK DebugMon_Handler + SECTION .text:CODE:REORDER:NOROOT(1) +DebugMon_Handler + B DebugMon_Handler + + PUBWEAK PendSV_Handler + SECTION .text:CODE:REORDER:NOROOT(1) +PendSV_Handler + B PendSV_Handler + + PUBWEAK SysTick_Handler + SECTION .text:CODE:REORDER:NOROOT(1) +SysTick_Handler + B SysTick_Handler + + PUBWEAK WWDT_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +WWDT_IRQHandler + B WWDT_IRQHandler + + PUBWEAK PVD_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +PVD_IRQHandler + B PVD_IRQHandler + + PUBWEAK TAMP_STAMP_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +TAMP_STAMP_IRQHandler + B TAMP_STAMP_IRQHandler + + PUBWEAK RTC_WKUP_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +RTC_WKUP_IRQHandler + B RTC_WKUP_IRQHandler + + PUBWEAK FLASH_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +FLASH_IRQHandler + B FLASH_IRQHandler + + PUBWEAK RCM_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +RCM_IRQHandler + B RCM_IRQHandler + + PUBWEAK EINT0_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +EINT0_IRQHandler + B EINT0_IRQHandler + + PUBWEAK EINT1_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +EINT1_IRQHandler + B EINT1_IRQHandler + + PUBWEAK EINT2_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +EINT2_IRQHandler + B EINT2_IRQHandler + + PUBWEAK EINT3_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +EINT3_IRQHandler + B EINT3_IRQHandler + + PUBWEAK EINT4_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +EINT4_IRQHandler + B EINT4_IRQHandler + + PUBWEAK DMA1_STR0_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +DMA1_STR0_IRQHandler + B DMA1_STR0_IRQHandler + + PUBWEAK DMA1_STR1_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +DMA1_STR1_IRQHandler + B DMA1_STR1_IRQHandler + + PUBWEAK DMA1_STR2_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +DMA1_STR2_IRQHandler + B DMA1_STR2_IRQHandler + + PUBWEAK DMA1_STR3_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +DMA1_STR3_IRQHandler + B DMA1_STR3_IRQHandler + + PUBWEAK DMA1_STR4_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +DMA1_STR4_IRQHandler + B DMA1_STR4_IRQHandler + + PUBWEAK DMA1_STR5_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +DMA1_STR5_IRQHandler + B DMA1_STR5_IRQHandler + + PUBWEAK DMA1_STR6_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +DMA1_STR6_IRQHandler + B DMA1_STR6_IRQHandler + + PUBWEAK ADC_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +ADC_IRQHandler + B ADC_IRQHandler + + PUBWEAK CAN1_TX_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +CAN1_TX_IRQHandler + B CAN1_TX_IRQHandler + + PUBWEAK CAN1_RX0_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +CAN1_RX0_IRQHandler + B CAN1_RX0_IRQHandler + + PUBWEAK CAN1_RX1_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +CAN1_RX1_IRQHandler + B CAN1_RX1_IRQHandler + + PUBWEAK CAN1_SCE_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +CAN1_SCE_IRQHandler + B CAN1_SCE_IRQHandler + + PUBWEAK EINT9_5_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +EINT9_5_IRQHandler + B EINT9_5_IRQHandler + + PUBWEAK TMR1_BRK_TMR9_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +TMR1_BRK_TMR9_IRQHandler + B TMR1_BRK_TMR9_IRQHandler + + PUBWEAK TMR1_UP_TMR10_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +TMR1_UP_TMR10_IRQHandler + B TMR1_UP_TMR10_IRQHandler + + PUBWEAK TMR1_TRG_COM_TMR11_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +TMR1_TRG_COM_TMR11_IRQHandler + B TMR1_TRG_COM_TMR11_IRQHandler + + PUBWEAK TMR1_CC_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +TMR1_CC_IRQHandler + B TMR1_CC_IRQHandler + + PUBWEAK TMR2_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +TMR2_IRQHandler + B TMR2_IRQHandler + + PUBWEAK TMR3_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +TMR3_IRQHandler + B TMR3_IRQHandler + + PUBWEAK TMR4_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +TMR4_IRQHandler + B TMR4_IRQHandler + + PUBWEAK I2C1_EV_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +I2C1_EV_IRQHandler + B I2C1_EV_IRQHandler + + PUBWEAK I2C1_ER_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +I2C1_ER_IRQHandler + B I2C1_ER_IRQHandler + + PUBWEAK I2C2_EV_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +I2C2_EV_IRQHandler + B I2C2_EV_IRQHandler + + PUBWEAK I2C2_ER_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +I2C2_ER_IRQHandler + B I2C2_ER_IRQHandler + + PUBWEAK SPI1_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +SPI1_IRQHandler + B SPI1_IRQHandler + + PUBWEAK SPI2_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +SPI2_IRQHandler + B SPI2_IRQHandler + + PUBWEAK USART1_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +USART1_IRQHandler + B USART1_IRQHandler + + PUBWEAK USART2_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +USART2_IRQHandler + B USART2_IRQHandler + + PUBWEAK USART3_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +USART3_IRQHandler + B USART3_IRQHandler + + PUBWEAK EINT15_10_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +EINT15_10_IRQHandler + B EINT15_10_IRQHandler + + PUBWEAK RTC_Alarm_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +RTC_Alarm_IRQHandler + B RTC_Alarm_IRQHandler + + PUBWEAK OTG_FS_WKUP_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +OTG_FS_WKUP_IRQHandler + B OTG_FS_WKUP_IRQHandler + + PUBWEAK TMR8_BRK_TMR12_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +TMR8_BRK_TMR12_IRQHandler + B TMR8_BRK_TMR12_IRQHandler + + PUBWEAK TMR8_UP_TMR13_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +TMR8_UP_TMR13_IRQHandler + B TMR8_UP_TMR13_IRQHandler + + PUBWEAK TMR8_TRG_COM_TMR14_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +TMR8_TRG_COM_TMR14_IRQHandler + B TMR8_TRG_COM_TMR14_IRQHandler + + PUBWEAK TMR8_CC_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +TMR8_CC_IRQHandler + B TMR8_CC_IRQHandler + + PUBWEAK DMA1_STR7_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +DMA1_STR7_IRQHandler + B DMA1_STR7_IRQHandler + + PUBWEAK EMMC_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +EMMC_IRQHandler + B EMMC_IRQHandler + + PUBWEAK SDIO_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +SDIO_IRQHandler + B SDIO_IRQHandler + + PUBWEAK TMR5_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +TMR5_IRQHandler + B TMR5_IRQHandler + + PUBWEAK SPI3_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +SPI3_IRQHandler + B SPI3_IRQHandler + + PUBWEAK UART4_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +UART4_IRQHandler + B UART4_IRQHandler + + PUBWEAK UART5_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +UART5_IRQHandler + B UART5_IRQHandler + + PUBWEAK TMR6_DAC_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +TMR6_DAC_IRQHandler + B TMR6_DAC_IRQHandler + + PUBWEAK TMR7_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +TMR7_IRQHandler + B TMR7_IRQHandler + + PUBWEAK DMA2_STR0_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +DMA2_STR0_IRQHandler + B DMA2_STR0_IRQHandler + + PUBWEAK DMA2_STR1_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +DMA2_STR1_IRQHandler + B DMA2_STR1_IRQHandler + + PUBWEAK DMA2_STR2_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +DMA2_STR2_IRQHandler + B DMA2_STR2_IRQHandler + + PUBWEAK DMA2_STR3_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +DMA2_STR3_IRQHandler + B DMA2_STR3_IRQHandler + + PUBWEAK DMA2_STR4_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +DMA2_STR4_IRQHandler + B DMA2_STR4_IRQHandler + + PUBWEAK ETH_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +ETH_IRQHandler + B ETH_IRQHandler + + PUBWEAK ETH_WKUP_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +ETH_WKUP_IRQHandler + B ETH_WKUP_IRQHandler + + PUBWEAK CAN2_TX_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +CAN2_TX_IRQHandler + B CAN2_TX_IRQHandler + + PUBWEAK CAN2_RX0_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +CAN2_RX0_IRQHandler + B CAN2_RX0_IRQHandler + + PUBWEAK CAN2_RX1_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +CAN2_RX1_IRQHandler + B CAN2_RX1_IRQHandler + + PUBWEAK CAN2_SCE_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +CAN2_SCE_IRQHandler + B CAN2_SCE_IRQHandler + + PUBWEAK OTG_FS_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +OTG_FS_IRQHandler + B OTG_FS_IRQHandler + + PUBWEAK DMA2_STR5_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +DMA2_STR5_IRQHandler + B DMA2_STR5_IRQHandler + + PUBWEAK DMA2_STR6_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +DMA2_STR6_IRQHandler + B DMA2_STR6_IRQHandler + + PUBWEAK DMA2_STR7_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +DMA2_STR7_IRQHandler + B DMA2_STR7_IRQHandler + + PUBWEAK USART6_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +USART6_IRQHandler + B USART6_IRQHandler + + PUBWEAK I2C3_EV_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +I2C3_EV_IRQHandler + B I2C3_EV_IRQHandler + + PUBWEAK I2C3_ER_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +I2C3_ER_IRQHandler + B I2C3_ER_IRQHandler + + PUBWEAK OTG_HS1_EP1_OUT_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +OTG_HS1_EP1_OUT_IRQHandler + B OTG_HS1_EP1_OUT_IRQHandler + + PUBWEAK OTG_HS1_EP1_IN_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +OTG_HS1_EP1_IN_IRQHandler + B OTG_HS1_EP1_IN_IRQHandler + + PUBWEAK OTG_HS1_WKUP_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +OTG_HS1_WKUP_IRQHandler + B OTG_HS1_WKUP_IRQHandler + + PUBWEAK OTG_HS1_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +OTG_HS1_IRQHandler + B OTG_HS1_IRQHandler + + PUBWEAK DCI_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +DCI_IRQHandler + B DCI_IRQHandler + + PUBWEAK CRYP_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +CRYP_IRQHandler + B CRYP_IRQHandler + + PUBWEAK HASH_RNG_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +HASH_RNG_IRQHandler + B HASH_RNG_IRQHandler + + PUBWEAK FPU_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +FPU_IRQHandler + B FPU_IRQHandler + + PUBWEAK SM3_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +SM3_IRQHandler + B SM3_IRQHandler + + PUBWEAK SM4_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +SM4_IRQHandler + B SM4_IRQHandler + + PUBWEAK BN_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +BN_IRQHandler + B BN_IRQHandler + + END diff --git a/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/iar/startup_apm32f465xx.s b/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/iar/startup_apm32f465xx.s new file mode 100644 index 0000000000..5e64935483 --- /dev/null +++ b/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/iar/startup_apm32f465xx.s @@ -0,0 +1,608 @@ +;/** +; * @file startup_apm32f465xx.s +; * +; * @brief CMSIS Cortex-M4 based Core Device Startup File for Device startup_apm32f465xx +; * +; * @version V1.0.0 +; * +; * @date 2023-12-01 +; * +; * @attention +; * +; * Copyright (C) 2023 Geehy Semiconductor +; * +; * You may not use this file except in compliance with the +; * GEEHY COPYRIGHT NOTICE (GEEHY SOFTWARE PACKAGE LICENSE). +; * +; * The program is only for reference, which is distributed in the hope +; * that it will be useful and instructional for customers to develop +; * their software. Unless required by applicable law or agreed to in +; * writing, the program is distributed on an "AS IS" BASIS, WITHOUT +; * ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied. +; * See the GEEHY SOFTWARE PACKAGE LICENSE for the governing permissions +; * and limitations under the License. +; */ + + MODULE ?cstartup + + ;; Forward declaration of sections. + SECTION CSTACK:DATA:NOROOT(3) + + SECTION .intvec:CODE:NOROOT(2) + + EXTERN __iar_program_start + EXTERN SystemInit + PUBLIC __vector_table + + DATA +__vector_table + DCD sfe(CSTACK) + DCD Reset_Handler ; Reset Handler + + DCD NMI_Handler ; NMI Handler + DCD HardFault_Handler ; Hard Fault Handler + DCD MemManage_Handler ; MPU Fault Handler + DCD BusFault_Handler ; Bus Fault Handler + DCD UsageFault_Handler ; Usage Fault Handler + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD SVC_Handler ; SVCall Handler + DCD DebugMon_Handler ; Debug Monitor Handler + DCD 0 ; Reserved + DCD PendSV_Handler ; PendSV Handler + DCD SysTick_Handler ; SysTick Handler + + ; External Interrupts + DCD WWDT_IRQHandler ; Window WatchDog + DCD PVD_IRQHandler ; PVD through EINT Line detection + DCD TAMP_STAMP_IRQHandler ; Tamper and TimeStamps through the EINT line + DCD RTC_WKUP_IRQHandler ; RTC Wakeup through the EINT line + DCD FLASH_IRQHandler ; FLASH + DCD RCM_IRQHandler ; RCM + DCD EINT0_IRQHandler ; EINT Line0 + DCD EINT1_IRQHandler ; EINT Line1 + DCD EINT2_IRQHandler ; EINT Line2 + DCD EINT3_IRQHandler ; EINT Line3 + DCD EINT4_IRQHandler ; EINT Line4 + DCD DMA1_STR0_IRQHandler ; DMA1 Stream 0 + DCD DMA1_STR1_IRQHandler ; DMA1 Stream 1 + DCD DMA1_STR2_IRQHandler ; DMA1 Stream 2 + DCD DMA1_STR3_IRQHandler ; DMA1 Stream 3 + DCD DMA1_STR4_IRQHandler ; DMA1 Stream 4 + DCD DMA1_STR5_IRQHandler ; DMA1 Stream 5 + DCD DMA1_STR6_IRQHandler ; DMA1 Stream 6 + DCD ADC_IRQHandler ; ADC1, ADC2 and ADC3s + DCD CAN1_TX_IRQHandler ; CAN1 TX + DCD CAN1_RX0_IRQHandler ; CAN1 RX0 + DCD CAN1_RX1_IRQHandler ; CAN1 RX1 + DCD CAN1_SCE_IRQHandler ; CAN1 SCE + DCD EINT9_5_IRQHandler ; External Line[9:5]s + DCD TMR1_BRK_TMR9_IRQHandler ; TMR1 Break and TMR9 + DCD TMR1_UP_TMR10_IRQHandler ; TMR1 Update and TMR10 + DCD TMR1_TRG_COM_TMR11_IRQHandler ; TMR1 Trigger and Commutation and TMR11 + DCD TMR1_CC_IRQHandler ; TMR1 Capture Compare + DCD TMR2_IRQHandler ; TMR2 + DCD TMR3_IRQHandler ; TMR3 + DCD TMR4_IRQHandler ; TMR4 + DCD I2C1_EV_IRQHandler ; I2C1 Event + DCD I2C1_ER_IRQHandler ; I2C1 Error + DCD I2C2_EV_IRQHandler ; I2C2 Event + DCD I2C2_ER_IRQHandler ; I2C2 Error + DCD SPI1_IRQHandler ; SPI1 + DCD SPI2_IRQHandler ; SPI2 + DCD USART1_IRQHandler ; USART1 + DCD USART2_IRQHandler ; USART2 + DCD USART3_IRQHandler ; USART3 + DCD EINT15_10_IRQHandler ; External Line[15:10]s + DCD RTC_Alarm_IRQHandler ; RTC Alarm (A and B) through EINT Line + DCD OTG_FS_WKUP_IRQHandler ; OTG_FS Wakeup through EINT line + DCD TMR8_BRK_TMR12_IRQHandler ; TMR8 Break and TMR12 + DCD TMR8_UP_TMR13_IRQHandler ; TMR8 Update and TMR13 + DCD TMR8_TRG_COM_TMR14_IRQHandler ; TMR8 Trigger and Commutation and TMR14 + DCD TMR8_CC_IRQHandler ; TMR8 Capture Compare + DCD DMA1_STR7_IRQHandler ; DMA1 Stream 7 + DCD SMC_IRQHandler ; SMC + DCD SDIO_IRQHandler ; SDIO + DCD TMR5_IRQHandler ; TMR5 + DCD SPI3_IRQHandler ; SPI3 + DCD UART4_IRQHandler ; UART4 + DCD UART5_IRQHandler ; UART5 + DCD TMR6_DAC_IRQHandler ; TMR6 and DAC1&2 underrun errors + DCD TMR7_IRQHandler ; TMR7 + DCD DMA2_STR0_IRQHandler ; DMA2 Stream 0 + DCD DMA2_STR1_IRQHandler ; DMA2 Stream 1 + DCD DMA2_STR2_IRQHandler ; DMA2 Stream 2 + DCD DMA2_STR3_IRQHandler ; DMA2 Stream 3 + DCD DMA2_STR4_IRQHandler ; DMA2 Stream 4 + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD CAN2_TX_IRQHandler ; CAN2 TX + DCD CAN2_RX0_IRQHandler ; CAN2 RX0 + DCD CAN2_RX1_IRQHandler ; CAN2 RX1 + DCD CAN2_SCE_IRQHandler ; CAN2 SCE + DCD OTG_FS_IRQHandler ; OTG_FS + DCD DMA2_STR5_IRQHandler ; DMA2 Stream 5 + DCD DMA2_STR6_IRQHandler ; DMA2 Stream 6 + DCD DMA2_STR7_IRQHandler ; DMA2 Stream 7 + DCD USART6_IRQHandler ; USART6 + DCD I2C3_EV_IRQHandler ; I2C3 event + DCD I2C3_ER_IRQHandler ; I2C3 error + DCD OTG_HS1_EP1_OUT_IRQHandler ; OTG_HS1 End Point 1 Out + DCD OTG_HS1_EP1_IN_IRQHandler ; OTG_HS1 End Point 1 In + DCD OTG_HS1_WKUP_IRQHandler ; OTG_HS1 Wakeup through EINT + DCD OTG_HS1_IRQHandler ; OTG_HS1 + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD RNG_IRQHandler ; RNG + DCD FPU_IRQHandler ; FPU + DCD SM3_IRQHandler ; SM3 + DCD SM4_IRQHandler ; SM4 + DCD BN_IRQHandler ; BN + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; +;; Default interrupt handlers. +;; + THUMB + PUBWEAK Reset_Handler + SECTION .text:CODE:REORDER:NOROOT(2) +Reset_Handler + + LDR R0, =SystemInit + BLX R0 + LDR R0, =__iar_program_start + BX R0 + + PUBWEAK NMI_Handler + SECTION .text:CODE:REORDER:NOROOT(1) +NMI_Handler + B NMI_Handler + + PUBWEAK HardFault_Handler + SECTION .text:CODE:REORDER:NOROOT(1) +HardFault_Handler + B HardFault_Handler + + PUBWEAK MemManage_Handler + SECTION .text:CODE:REORDER:NOROOT(1) +MemManage_Handler + B MemManage_Handler + + PUBWEAK BusFault_Handler + SECTION .text:CODE:REORDER:NOROOT(1) +BusFault_Handler + B BusFault_Handler + + PUBWEAK UsageFault_Handler + SECTION .text:CODE:REORDER:NOROOT(1) +UsageFault_Handler + B UsageFault_Handler + + PUBWEAK SVC_Handler + SECTION .text:CODE:REORDER:NOROOT(1) +SVC_Handler + B SVC_Handler + + PUBWEAK DebugMon_Handler + SECTION .text:CODE:REORDER:NOROOT(1) +DebugMon_Handler + B DebugMon_Handler + + PUBWEAK PendSV_Handler + SECTION .text:CODE:REORDER:NOROOT(1) +PendSV_Handler + B PendSV_Handler + + PUBWEAK SysTick_Handler + SECTION .text:CODE:REORDER:NOROOT(1) +SysTick_Handler + B SysTick_Handler + + PUBWEAK WWDT_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +WWDT_IRQHandler + B WWDT_IRQHandler + + PUBWEAK PVD_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +PVD_IRQHandler + B PVD_IRQHandler + + PUBWEAK TAMP_STAMP_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +TAMP_STAMP_IRQHandler + B TAMP_STAMP_IRQHandler + + PUBWEAK RTC_WKUP_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +RTC_WKUP_IRQHandler + B RTC_WKUP_IRQHandler + + PUBWEAK FLASH_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +FLASH_IRQHandler + B FLASH_IRQHandler + + PUBWEAK RCM_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +RCM_IRQHandler + B RCM_IRQHandler + + PUBWEAK EINT0_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +EINT0_IRQHandler + B EINT0_IRQHandler + + PUBWEAK EINT1_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +EINT1_IRQHandler + B EINT1_IRQHandler + + PUBWEAK EINT2_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +EINT2_IRQHandler + B EINT2_IRQHandler + + PUBWEAK EINT3_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +EINT3_IRQHandler + B EINT3_IRQHandler + + PUBWEAK EINT4_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +EINT4_IRQHandler + B EINT4_IRQHandler + + PUBWEAK DMA1_STR0_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +DMA1_STR0_IRQHandler + B DMA1_STR0_IRQHandler + + PUBWEAK DMA1_STR1_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +DMA1_STR1_IRQHandler + B DMA1_STR1_IRQHandler + + PUBWEAK DMA1_STR2_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +DMA1_STR2_IRQHandler + B DMA1_STR2_IRQHandler + + PUBWEAK DMA1_STR3_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +DMA1_STR3_IRQHandler + B DMA1_STR3_IRQHandler + + PUBWEAK DMA1_STR4_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +DMA1_STR4_IRQHandler + B DMA1_STR4_IRQHandler + + PUBWEAK DMA1_STR5_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +DMA1_STR5_IRQHandler + B DMA1_STR5_IRQHandler + + PUBWEAK DMA1_STR6_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +DMA1_STR6_IRQHandler + B DMA1_STR6_IRQHandler + + PUBWEAK ADC_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +ADC_IRQHandler + B ADC_IRQHandler + + PUBWEAK CAN1_TX_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +CAN1_TX_IRQHandler + B CAN1_TX_IRQHandler + + PUBWEAK CAN1_RX0_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +CAN1_RX0_IRQHandler + B CAN1_RX0_IRQHandler + + PUBWEAK CAN1_RX1_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +CAN1_RX1_IRQHandler + B CAN1_RX1_IRQHandler + + PUBWEAK CAN1_SCE_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +CAN1_SCE_IRQHandler + B CAN1_SCE_IRQHandler + + PUBWEAK EINT9_5_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +EINT9_5_IRQHandler + B EINT9_5_IRQHandler + + PUBWEAK TMR1_BRK_TMR9_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +TMR1_BRK_TMR9_IRQHandler + B TMR1_BRK_TMR9_IRQHandler + + PUBWEAK TMR1_UP_TMR10_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +TMR1_UP_TMR10_IRQHandler + B TMR1_UP_TMR10_IRQHandler + + PUBWEAK TMR1_TRG_COM_TMR11_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +TMR1_TRG_COM_TMR11_IRQHandler + B TMR1_TRG_COM_TMR11_IRQHandler + + PUBWEAK TMR1_CC_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +TMR1_CC_IRQHandler + B TMR1_CC_IRQHandler + + PUBWEAK TMR2_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +TMR2_IRQHandler + B TMR2_IRQHandler + + PUBWEAK TMR3_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +TMR3_IRQHandler + B TMR3_IRQHandler + + PUBWEAK TMR4_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +TMR4_IRQHandler + B TMR4_IRQHandler + + PUBWEAK I2C1_EV_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +I2C1_EV_IRQHandler + B I2C1_EV_IRQHandler + + PUBWEAK I2C1_ER_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +I2C1_ER_IRQHandler + B I2C1_ER_IRQHandler + + PUBWEAK I2C2_EV_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +I2C2_EV_IRQHandler + B I2C2_EV_IRQHandler + + PUBWEAK I2C2_ER_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +I2C2_ER_IRQHandler + B I2C2_ER_IRQHandler + + PUBWEAK SPI1_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +SPI1_IRQHandler + B SPI1_IRQHandler + + PUBWEAK SPI2_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +SPI2_IRQHandler + B SPI2_IRQHandler + + PUBWEAK USART1_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +USART1_IRQHandler + B USART1_IRQHandler + + PUBWEAK USART2_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +USART2_IRQHandler + B USART2_IRQHandler + + PUBWEAK USART3_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +USART3_IRQHandler + B USART3_IRQHandler + + PUBWEAK EINT15_10_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +EINT15_10_IRQHandler + B EINT15_10_IRQHandler + + PUBWEAK RTC_Alarm_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +RTC_Alarm_IRQHandler + B RTC_Alarm_IRQHandler + + PUBWEAK OTG_FS_WKUP_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +OTG_FS_WKUP_IRQHandler + B OTG_FS_WKUP_IRQHandler + + PUBWEAK TMR8_BRK_TMR12_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +TMR8_BRK_TMR12_IRQHandler + B TMR8_BRK_TMR12_IRQHandler + + PUBWEAK TMR8_UP_TMR13_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +TMR8_UP_TMR13_IRQHandler + B TMR8_UP_TMR13_IRQHandler + + PUBWEAK TMR8_TRG_COM_TMR14_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +TMR8_TRG_COM_TMR14_IRQHandler + B TMR8_TRG_COM_TMR14_IRQHandler + + PUBWEAK TMR8_CC_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +TMR8_CC_IRQHandler + B TMR8_CC_IRQHandler + + PUBWEAK DMA1_STR7_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +DMA1_STR7_IRQHandler + B DMA1_STR7_IRQHandler + + PUBWEAK SMC_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +SMC_IRQHandler + B SMC_IRQHandler + + PUBWEAK SDIO_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +SDIO_IRQHandler + B SDIO_IRQHandler + + PUBWEAK TMR5_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +TMR5_IRQHandler + B TMR5_IRQHandler + + PUBWEAK SPI3_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +SPI3_IRQHandler + B SPI3_IRQHandler + + PUBWEAK UART4_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +UART4_IRQHandler + B UART4_IRQHandler + + PUBWEAK UART5_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +UART5_IRQHandler + B UART5_IRQHandler + + PUBWEAK TMR6_DAC_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +TMR6_DAC_IRQHandler + B TMR6_DAC_IRQHandler + + PUBWEAK TMR7_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +TMR7_IRQHandler + B TMR7_IRQHandler + + PUBWEAK DMA2_STR0_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +DMA2_STR0_IRQHandler + B DMA2_STR0_IRQHandler + + PUBWEAK DMA2_STR1_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +DMA2_STR1_IRQHandler + B DMA2_STR1_IRQHandler + + PUBWEAK DMA2_STR2_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +DMA2_STR2_IRQHandler + B DMA2_STR2_IRQHandler + + PUBWEAK DMA2_STR3_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +DMA2_STR3_IRQHandler + B DMA2_STR3_IRQHandler + + PUBWEAK DMA2_STR4_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +DMA2_STR4_IRQHandler + B DMA2_STR4_IRQHandler + + PUBWEAK CAN2_TX_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +CAN2_TX_IRQHandler + B CAN2_TX_IRQHandler + + PUBWEAK CAN2_RX0_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +CAN2_RX0_IRQHandler + B CAN2_RX0_IRQHandler + + PUBWEAK CAN2_RX1_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +CAN2_RX1_IRQHandler + B CAN2_RX1_IRQHandler + + PUBWEAK CAN2_SCE_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +CAN2_SCE_IRQHandler + B CAN2_SCE_IRQHandler + + PUBWEAK OTG_FS_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +OTG_FS_IRQHandler + B OTG_FS_IRQHandler + + PUBWEAK DMA2_STR5_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +DMA2_STR5_IRQHandler + B DMA2_STR5_IRQHandler + + PUBWEAK DMA2_STR6_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +DMA2_STR6_IRQHandler + B DMA2_STR6_IRQHandler + + PUBWEAK DMA2_STR7_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +DMA2_STR7_IRQHandler + B DMA2_STR7_IRQHandler + + PUBWEAK USART6_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +USART6_IRQHandler + B USART6_IRQHandler + + PUBWEAK I2C3_EV_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +I2C3_EV_IRQHandler + B I2C3_EV_IRQHandler + + PUBWEAK I2C3_ER_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +I2C3_ER_IRQHandler + B I2C3_ER_IRQHandler + + PUBWEAK OTG_HS1_EP1_OUT_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +OTG_HS1_EP1_OUT_IRQHandler + B OTG_HS1_EP1_OUT_IRQHandler + + PUBWEAK OTG_HS1_EP1_IN_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +OTG_HS1_EP1_IN_IRQHandler + B OTG_HS1_EP1_IN_IRQHandler + + PUBWEAK OTG_HS1_WKUP_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +OTG_HS1_WKUP_IRQHandler + B OTG_HS1_WKUP_IRQHandler + + PUBWEAK OTG_HS1_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +OTG_HS1_IRQHandler + B OTG_HS1_IRQHandler + + PUBWEAK RNG_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +RNG_IRQHandler + B RNG_IRQHandler + + PUBWEAK FPU_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +FPU_IRQHandler + B FPU_IRQHandler + + PUBWEAK SM3_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +SM3_IRQHandler + B SM3_IRQHandler + + PUBWEAK SM4_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +SM4_IRQHandler + B SM4_IRQHandler + + PUBWEAK BN_IRQHandler + SECTION .text:CODE:REORDER:NOROOT(1) +BN_IRQHandler + B BN_IRQHandler + + END diff --git a/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/system_apm32f4xx.c b/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/system_apm32f4xx.c new file mode 100644 index 0000000000..f939fde55e --- /dev/null +++ b/lib/main/APM32F4/Libraries/Device/Geehy/APM32F4xx/Source/system_apm32f4xx.c @@ -0,0 +1,229 @@ +/** + * + * @file system_apm32f4xx.c + * + * @brief CMSIS Cortex-M4 Device Peripheral Access Layer System Source File. + * + * @version V1.0.0 + * + * @date 2023-07-31 + * + * @attention + * + * Copyright (C) 2023 Geehy Semiconductor + * + * You may not use this file except in compliance with the + * GEEHY COPYRIGHT NOTICE (GEEHY SOFTWARE PACKAGE LICENSE). + * + * The program is only for reference, which is distributed in the hope + * that it will be useful and instructional for customers to develop + * their software. Unless required by applicable law or agreed to in + * writing, the program is distributed on an "AS IS" BASIS, WITHOUT + * ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied. + * See the GEEHY SOFTWARE PACKAGE LICENSE for the governing permissions + * and limitations under the License. + */ + +/** @addtogroup CMSIS + * @{ + */ + +/** @addtogroup apm32f4xx_system + * @{ + */ + +/** @addtogroup APM32F4xx_System_Private_Includes + * @{ + */ + +#include "apm32f4xx.h" + +/* Value of the external oscillator in Hz */ +#if !defined (HSE_VALUE) + #define HSE_VALUE ((uint32_t)8000000U) +#endif /* HSE_VALUE */ + +/* Value of the internal oscillator in Hz */ +#if !defined (HSI_VALUE) + #define HSI_VALUE ((uint32_t)16000000U) +#endif /* HSI_VALUE */ + +/** + * @} + */ + +/** @addtogroup APM32F4xx_System_Private_TypesDefinitions + * @{ + */ + +/** + * @} + */ + +/** @addtogroup APM32F4xx_System_Private_Defines + * @{ + */ +/* Uncomment the following line if you need to relocate your vector table in internal SRAM */ +/* #define VECT_TAB_SRAM */ + +/* Vector table base offset field. This value must be a multiple of 0x200 */ +#define VECT_TAB_OFFSET 0x00 + +/** + * @} + */ + +/** @addtogroup APM32F4xx_System_Private_Macros + * @{ + */ + +/** + * @} + */ + +/** @addtogroup APM32F4xx_System_Private_Variables + * @{ + */ +uint32_t SystemCoreClock = 16000000; +const uint8_t AHBPrescTable[16] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 6, 7, 8, 9}; +const uint8_t APBPrescTable[8] = {0, 0, 0, 0, 1, 2, 3, 4}; +/** + * @} + */ + +/** @addtogroup APM32F4xx_System_Private_FunctionPrototypes + * @{ + */ + +/** + * @} + */ + +/** @addtogroup APM32F4xx_System_Private_Functions + * @{ + */ + +/** + * @brief Setup the microcontroller system + * + * @param None + * + * @retval None + */ +void SystemInit(void) +{ + uint8_t i; + + /* Disable global interrupt */ + __disable_irq(); + + SysTick->CTRL = 0U; + SysTick->LOAD = 0U; + SysTick->VAL = 0U; + + for (i = 0U; i < 8U; i++) + { + NVIC->ICER[i] = 0xFFFFFFFFU; + NVIC->ICPR[i] = 0xFFFFFFFFU; + } + + /* FPU settings */ +#if (__FPU_PRESENT == 1U) && (__FPU_USED == 1U) + SCB->CPACR |= ((3UL << 10U * 2U)|(3UL << 11U * 2U)); /* set CP10 and CP11 Full Access */ +#endif + /* Reset the RCM clock configuration to the default reset state */ + /* Set HSIEN bit */ + RCM->CTRL |= (uint32_t)0x00000001; + + /* Reset CFG register */ + RCM->CFG = 0x00000000; + + /* Reset HSEEN, CSSEN and PLL1EN bits */ + RCM->CTRL &= (uint32_t)0xFEF6FFFF; + + /* Reset PLL1CFG register */ + RCM->PLL1CFG = 0x24003010; + + /* Reset HSEBCFG bit */ + RCM->CTRL &= (uint32_t)0xFFFBFFFF; + + /* Disable all interrupts */ + RCM->INT = 0x00000000; + + /* Configure the Vector Table location add offset address */ +#ifdef VECT_TAB_SRAM + SCB->VTOR = SRAM_BASE | VECT_TAB_OFFSET; /* Vector Table Relocation in Internal SRAM */ +#else + SCB->VTOR = FLASH_BASE | VECT_TAB_OFFSET; /* Vector Table Relocation in Internal FLASH */ +#endif + + /* Enable global interrupt */ + __enable_irq(); +} + +/** + * @brief Update SystemCoreClock variable according to clock register values + * The SystemCoreClock variable contains the core clock (HCLK) + * + * @param None + * @retval None + */ +void SystemCoreClockUpdate(void) +{ + uint32_t sysClock = 0, pllvco = 0, pllc, pllClock, pllb; + + /* Get SYSCLK source */ + sysClock = RCM->CFG & RCM_CFG_SCLKSWSTS; + + switch (sysClock) + { + case 0x00: /* HSI used as system clock source */ + SystemCoreClock = HSI_VALUE; + break; + + case 0x04: /* HSE used as system clock source */ + SystemCoreClock = HSE_VALUE; + break; + + case 0x08: /* PLL used as system clock source */ + pllClock = (RCM->PLL1CFG & RCM_PLL1CFG_PLL1CLKS) >> 22; + pllb = RCM->PLL1CFG & RCM_PLL1CFG_PLLB; + + if (pllClock != 0) + { + /* HSE used as PLL clock source */ + pllvco = (HSE_VALUE / pllb) * ((RCM->PLL1CFG & RCM_PLL1CFG_PLL1A) >> 6); + } + else + { + /* HSI used as PLL clock source */ + pllvco = (HSI_VALUE / pllb) * ((RCM->PLL1CFG & RCM_PLL1CFG_PLL1A) >> 6); + } + + pllc = (((RCM->PLL1CFG & RCM_PLL1CFG_PLL1C) >> 16) + 1 ) * 2; + SystemCoreClock = pllvco / pllc; + break; + + default: + SystemCoreClock = HSI_VALUE; + break; + } + + /* Compute HCLK frequency --------------------------------------------------*/ + /* Get HCLK prescaler */ + sysClock = AHBPrescTable[((RCM->CFG & RCM_CFG_AHBPSC) >> 4)]; + /* HCLK frequency */ + SystemCoreClock >>= sysClock; +} + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ diff --git a/lib/main/APM32F4/Middlewares/APM32_USB_Library/Device/Class/CDC/Inc/usbd_cdc.h b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Device/Class/CDC/Inc/usbd_cdc.h new file mode 100644 index 0000000000..8c6f973897 --- /dev/null +++ b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Device/Class/CDC/Inc/usbd_cdc.h @@ -0,0 +1,173 @@ +/*! + * @file usbd_cdc.h + * + * @brief usb device cdc class handler header file + * + * @version V1.0.0 + * + * @date 2023-01-16 + * + * @attention + * + * Copyright (C) 2023 Geehy Semiconductor + * + * You may not use this file except in compliance with the + * GEEHY COPYRIGHT NOTICE (GEEHY SOFTWARE PACKAGE LICENSE). + * + * The program is only for reference, which is distributed in the hope + * that it will be useful and instructional for customers to develop + * their software. Unless required by applicable law or agreed to in + * writing, the program is distributed on an "AS IS" BASIS, WITHOUT + * ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied. + * See the GEEHY SOFTWARE PACKAGE LICENSE for the governing permissions + * and limitations under the License. + */ + +/* Define to prevent recursive inclusion */ +#ifndef _USBD_CDC_H_ +#define _USBD_CDC_H_ + +/* Includes */ +#include "usbd_core.h" + +/** @addtogroup APM32_USB_Library + @{ + */ + +/** @addtogroup USBD_CDC_Class + @{ + */ + +/** @defgroup USBD_CDC_Macros Macros + @{ +*/ + +#define USBD_CDC_FS_MP_SIZE 0x40 +#define USBD_CDC_HS_MP_SIZE 0x200 +#define USBD_CDC_CMD_MP_SIZE 0x08 +#define USBD_CDC_DATA_MP_SIZE 0x07 + +#define USBD_CDC_CMD_EP_ADDR 0x82 +#define USBD_CDC_DATA_IN_EP_ADDR 0x81 +#define USBD_CDC_DATA_OUT_EP_ADDR 0x01 + +#define USBD_CDC_FS_INTERVAL 16 +#define USBD_CDC_HS_INTERVAL 16 + +/**@} end of group USBD_CDC_Macros*/ + +/** @defgroup USBD_CDC_Enumerates Enumerates + @{ + */ + +/** + * @brief USB device CDC xfer status + */ +typedef enum +{ + USBD_CDC_XFER_IDLE, + USBD_CDC_XFER_BUSY, +} USBD_CDC_XFER_STA_T; + +/** + * @brief USB device CDC control status + */ +typedef enum +{ + USBD_CDC_SEND_ENCAPSULATED_COMMAND = 0x00, + USBD_CDC_GET_ENCAPSULATED_RESPONSE = 0x01, + USBD_CDC_SET_COMM_FEATURE = 0x02, + USBD_CDC_GET_COMM_FEATURE = 0x03, + USBD_CDC_CLEAR_COMM_FEATURE = 0x04, + USBD_CDC_SET_LINE_CODING = 0x20, + USBD_CDC_GET_LINE_CODING = 0x21, + USBD_CDC_SET_CONTROL_LINE_STATE = 0x22, + USBD_CDC_SEND_BREAK = 0x23, +} USBD_CDC_CTRL_STA_T; + +/**@} end of group USBD_CDC_Enumerates*/ + +/** @defgroup USBD_CDC_Structures Structures + @{ + */ + +/** + * @brief USB device CDC Line Coding Structure + */ +typedef struct +{ + uint32_t baudRate; + uint8_t format; + uint8_t parityType; + uint8_t WordLen; +} USBD_CDC_LINE_CODING_T; + +/** + * @brief USB device CDC interface handler + */ +typedef struct +{ + const char* itfName; + USBD_STA_T (*ItfInit)(void); + USBD_STA_T (*ItfDeInit)(void); + USBD_STA_T (*ItfCtrl)(uint8_t command, uint8_t *buffer, uint16_t length); + USBD_STA_T (*ItfSend)(uint8_t *buffer, uint16_t length); + USBD_STA_T (*ItfSendEnd)(uint8_t epNum, uint8_t *buffer, uint32_t *length); + USBD_STA_T (*ItfReceive)(uint8_t *buffer, uint32_t *length); + USBD_STA_T (*ItfSOF)(void); +} USBD_CDC_INTERFACE_T; + +/** + * @brief USB device CDC data handler + */ +typedef struct +{ + __IO uint8_t state; + uint8_t *buffer; + uint32_t length; +} USBD_CDC_DATA_XFER_T; + +/** + * @brief USB device CDC command handler + */ +typedef struct +{ + uint8_t opcode; + uint8_t length; +} USBD_CDC_CMD_XFER_T; + +/** + * @brief CDC information management + */ +typedef struct +{ + uint8_t itf; + uint8_t epInAddr; + uint8_t epOutAddr; + uint8_t epCmdAddr; + USBD_CDC_DATA_XFER_T cdcTx; + USBD_CDC_DATA_XFER_T cdcRx; + uint32_t data[USBD_CDC_HS_MP_SIZE / 4]; + USBD_CDC_CMD_XFER_T cdcCmd; +} USBD_CDC_INFO_T; + +extern USBD_CLASS_T USBD_CDC_CLASS; + +/**@} end of group USBD_CDC_Structures*/ + +/** @defgroup USBD_CDC_Functions Functions + @{ + */ + +USBD_STA_T USBD_CDC_TxPacket(USBD_INFO_T* usbInfo); +USBD_STA_T USBD_CDC_RxPacket(USBD_INFO_T* usbInfo); +uint8_t USBD_CDC_ReadInterval(USBD_INFO_T* usbInfo); +USBD_STA_T USBD_CDC_ConfigTxBuffer(USBD_INFO_T* usbInfo, uint8_t *buffer, uint32_t length); +USBD_STA_T USBD_CDC_ConfigRxBuffer(USBD_INFO_T* usbInfo, uint8_t *buffer); +USBD_STA_T USBD_CDC_RegisterItf(USBD_INFO_T* usbInfo, USBD_CDC_INTERFACE_T* itf); + +/**@} end of group USBD_CDC_Functions */ +/**@} end of group USBD_CDC_Class */ +/**@} end of group APM32_USB_Library */ + +#endif diff --git a/lib/main/APM32F4/Middlewares/APM32_USB_Library/Device/Class/CDC/Src/usbd_cdc.c b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Device/Class/CDC/Src/usbd_cdc.c new file mode 100644 index 0000000000..7d04fef93a --- /dev/null +++ b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Device/Class/CDC/Src/usbd_cdc.c @@ -0,0 +1,663 @@ +/*! + * @file usbd_cdc.c + * + * @brief usb device cdc class handler + * + * @version V1.0.0 + * + * @date 2023-01-16 + * + * @attention + * + * Copyright (C) 2023 Geehy Semiconductor + * + * You may not use this file except in compliance with the + * GEEHY COPYRIGHT NOTICE (GEEHY SOFTWARE PACKAGE LICENSE). + * + * The program is only for reference, which is distributed in the hope + * that it will be useful and instructional for customers to develop + * their software. Unless required by applicable law or agreed to in + * writing, the program is distributed on an "AS IS" BASIS, WITHOUT + * ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied. + * See the GEEHY SOFTWARE PACKAGE LICENSE for the governing permissions + * and limitations under the License. + */ + +/* Includes */ +#include "usbd_cdc.h" +#include "usbd_stdReq.h" +#include "usbd_dataXfer.h" +//#include +#include +#include + +/** @addtogroup APM32_USB_Library + @{ + */ + +/** @addtogroup USBD_CDC_Class + @{ + */ + +/** @defgroup USBD_CDC_Functions Functions + @{ + */ + +static USBD_STA_T USBD_CDC_ClassInitHandler(USBD_INFO_T* usbInfo, uint8_t cfgIndex); +static USBD_STA_T USBD_CDC_ClassDeInitHandler(USBD_INFO_T* usbInfo, uint8_t cfgIndex); +static USBD_STA_T USBD_CDC_SOFHandler(USBD_INFO_T* usbInfo); +static USBD_STA_T USBD_CDC_SetupHandler(USBD_INFO_T* usbInfo, USBD_REQ_SETUP_T* req); +static USBD_STA_T USBD_CDC_RxEP0Handler(USBD_INFO_T* usbInfo); +static USBD_STA_T USBD_CDC_DataInHandler(USBD_INFO_T* usbInfo, uint8_t epNum); +static USBD_STA_T USBD_CDC_DataOutHandler(USBD_INFO_T* usbInfo, uint8_t epNum); + +/**@} end of group USBD_CDC_Functions */ + +/** @defgroup USBD_CDC_Structures Structures + @{ + */ + +/* CDC class handler */ +USBD_CLASS_T USBD_CDC_CLASS = +{ + /* Class handler */ + "Class CDC", + NULL, + USBD_CDC_ClassInitHandler, + USBD_CDC_ClassDeInitHandler, + USBD_CDC_SOFHandler, + + /* Control endpoint */ + USBD_CDC_SetupHandler, + NULL, + USBD_CDC_RxEP0Handler, + /* Specific endpoint */ + USBD_CDC_DataInHandler, + USBD_CDC_DataOutHandler, + NULL, + NULL, +}; + +/**@} end of group USBD_CDC_Structures*/ + +/** @defgroup USBD_CDC_Functions Functions + @{ + */ + +/*! + * @brief USB device CDC configuration handler + * + * @param usbInfo: usb device information + * + * @param cfgIndex: configuration index + * + * @retval USB device operation status + */ +static USBD_STA_T USBD_CDC_ClassInitHandler(USBD_INFO_T* usbInfo, uint8_t cfgIndex) +{ + USBD_STA_T usbStatus = USBD_OK; + + USBD_CDC_INFO_T* usbDevCDC; + + UNUSED(cfgIndex); + + /* Link class data */ + usbInfo->devClass[usbInfo->classID]->classData = (USBD_CDC_INFO_T*)malloc(sizeof(USBD_CDC_INFO_T)); + usbDevCDC = (USBD_CDC_INFO_T*)usbInfo->devClass[usbInfo->classID]->classData; + memset(usbDevCDC, 0, sizeof(USBD_CDC_INFO_T)); + + USBD_USR_Debug("USBD_CDC_INFO_T size %d\r\n", sizeof(USBD_CDC_INFO_T)); + + if (usbDevCDC == NULL) + { + USBD_USR_LOG("usbDevCDC is NULL"); + return USBD_FAIL; + } + + usbDevCDC->epCmdAddr = USBD_CDC_CMD_EP_ADDR; + usbDevCDC->epInAddr = USBD_CDC_DATA_IN_EP_ADDR; + usbDevCDC->epOutAddr = USBD_CDC_DATA_OUT_EP_ADDR; + + /* Open Command endpoint */ + USBD_EP_OpenCallback(usbInfo, usbDevCDC->epCmdAddr, EP_TYPE_INTERRUPT, USBD_CDC_CMD_MP_SIZE); + usbInfo->devEpIn[usbDevCDC->epCmdAddr & 0x0F].useStatus = ENABLE; + + /* Open Data endpoint */ + switch (usbInfo->devSpeed) + { + case USBD_SPEED_FS: + USBD_EP_OpenCallback(usbInfo, usbDevCDC->epOutAddr, EP_TYPE_BULK, USBD_CDC_FS_MP_SIZE); + usbInfo->devEpOut[usbDevCDC->epOutAddr & 0x0F].useStatus = ENABLE; + + USBD_EP_OpenCallback(usbInfo, usbDevCDC->epInAddr, EP_TYPE_BULK, USBD_CDC_FS_MP_SIZE); + usbInfo->devEpIn[usbDevCDC->epInAddr & 0x0F].useStatus = ENABLE; + + usbInfo->devEpIn[usbDevCDC->epCmdAddr & 0x0F].interval = USBD_CDC_FS_INTERVAL; + break; + + default: + USBD_EP_OpenCallback(usbInfo, usbDevCDC->epOutAddr, EP_TYPE_BULK, USBD_CDC_HS_MP_SIZE); + usbInfo->devEpOut[usbDevCDC->epOutAddr & 0x0F].useStatus = ENABLE; + + USBD_EP_OpenCallback(usbInfo, usbDevCDC->epInAddr, EP_TYPE_BULK, USBD_CDC_HS_MP_SIZE); + usbInfo->devEpIn[usbDevCDC->epInAddr & 0x0F].useStatus = ENABLE; + + usbInfo->devEpIn[usbDevCDC->epCmdAddr & 0x0F].interval = USBD_CDC_HS_INTERVAL; + break; + } + + /* Interface Init */ + usbDevCDC->cdcTx.buffer = NULL; + usbDevCDC->cdcRx.buffer = NULL; + + usbDevCDC->cdcTx.state = USBD_CDC_XFER_IDLE; + usbDevCDC->cdcRx.state = USBD_CDC_XFER_IDLE; + + ((USBD_CDC_INTERFACE_T *)usbInfo->devClassUserData[usbInfo->classID])->ItfInit(); + + if(usbDevCDC->cdcRx.buffer == NULL) + { + USBD_USR_LOG("cdcRx buffer is NULL"); + return USBD_FAIL; + } + + switch (usbInfo->devSpeed) + { + case USBD_SPEED_FS: + USBD_EP_ReceiveCallback(usbInfo, usbDevCDC->epOutAddr, \ + usbDevCDC->cdcRx.buffer, \ + USBD_CDC_FS_MP_SIZE); + break; + + default: + USBD_EP_ReceiveCallback(usbInfo, usbDevCDC->epOutAddr, \ + usbDevCDC->cdcRx.buffer, \ + USBD_CDC_HS_MP_SIZE); + break; + } + + return usbStatus; +} + +/*! + * @brief USB device CDC reset handler + * + * @param usbInfo: usb device information + * + * @param cfgIndex: configuration index + * + * @retval USB device operation status + */ +static USBD_STA_T USBD_CDC_ClassDeInitHandler(USBD_INFO_T* usbInfo, uint8_t cfgIndex) +{ + USBD_STA_T usbStatus = USBD_OK; + USBD_CDC_INFO_T* usbDevCDC = (USBD_CDC_INFO_T*)usbInfo->devClass[usbInfo->classID]->classData; + + UNUSED(cfgIndex); + + /* Close CDC EP */ + USBD_EP_CloseCallback(usbInfo, usbDevCDC->epOutAddr); + usbInfo->devEpOut[usbDevCDC->epOutAddr & 0x0F].useStatus = DISABLE; + + USBD_EP_CloseCallback(usbInfo, usbDevCDC->epInAddr); + usbInfo->devEpIn[usbDevCDC->epInAddr & 0x0F].useStatus = DISABLE; + + USBD_EP_CloseCallback(usbInfo, usbDevCDC->epCmdAddr); + usbInfo->devEpIn[usbDevCDC->epCmdAddr & 0x0F].useStatus = DISABLE; + usbInfo->devEpIn[usbDevCDC->epCmdAddr & 0x0F].interval = 0; + + if (usbInfo->devClass[usbInfo->classID]->classData != NULL) + { + if(((USBD_CDC_INTERFACE_T *)usbInfo->devClassUserData[usbInfo->classID])->ItfDeInit != NULL) + { + ((USBD_CDC_INTERFACE_T *)usbInfo->devClassUserData[usbInfo->classID])->ItfDeInit(); + } + + free(usbInfo->devClass[usbInfo->classID]->classData); + usbInfo->devClass[usbInfo->classID]->classData = 0; + } + + return usbStatus; +} + +/*! + * @brief USB device CDC SOF handler + * + * @param usbInfo: usb device information + * + * @retval USB device operation status + */ +static USBD_STA_T USBD_CDC_SOFHandler(USBD_INFO_T* usbInfo) +{ + USBD_STA_T usbStatus = USBD_BUSY; + + if(((USBD_CDC_INTERFACE_T *)usbInfo->devClassUserData[usbInfo->classID])->ItfSOF != NULL) + { + ((USBD_CDC_INTERFACE_T *)usbInfo->devClassUserData[usbInfo->classID])->ItfSOF(); + } + + return usbStatus; +} + +/*! + * @brief USB CDC device receive CTRL status + * + * @param usbInfo : usb handler information + * + * @param buffer : data buffer + * + * @param length : length of data + * + * @retval usb device status + */ +USBD_STA_T USBD_CDC_CtrlReceiveData(USBD_INFO_T* usbInfo, uint8_t *buffer, uint32_t length) +{ + USBD_STA_T usbStatus = USBD_OK; + + usbInfo->devEp0State = USBD_DEV_EP0_DATA_OUT; + usbInfo->devEpOut[USBD_EP_0].length = length; + usbInfo->devEpOut[USBD_EP_0].remainLen = length; + + USBD_EP_ReceiveCallback(usbInfo, USBD_EP_0, buffer, length); + + return usbStatus; +} + +/*! + * @brief USB device CDC SETUP handler + * + * @param usbInfo: usb device information + * + * @param req: setup request + * + * @retval USB device operation status + */ +static USBD_STA_T USBD_CDC_SetupHandler(USBD_INFO_T* usbInfo, USBD_REQ_SETUP_T* req) +{ + USBD_STA_T usbStatus = USBD_OK; + USBD_CDC_INFO_T* usbDevCDC = (USBD_CDC_INFO_T*)usbInfo->devClass[usbInfo->classID]->classData; + + uint8_t request; + uint8_t reqType; + uint16_t wLength = req->DATA_FIELD.wLength[0] | req->DATA_FIELD.wLength[1] << 8; + uint16_t status = 0x0000; + uint16_t length; + + if (usbDevCDC == NULL) + { + return USBD_FAIL; + } + + request = req->DATA_FIELD.bRequest; + reqType = req->DATA_FIELD.bmRequest.REQ_TYPE_B.type; + + switch (reqType) + { + case USBD_REQ_TYPE_STANDARD: + switch (request) + { + case USBD_STD_GET_STATUS: + if (usbInfo->devState == USBD_DEV_CONFIGURE) + { + USBD_CtrlSendData(usbInfo, (uint8_t*)&status, 2); + } + else + { + USBD_REQ_CtrlError(usbInfo, req); + usbStatus = USBD_FAIL; + } + break; + + case USBD_STD_GET_INTERFACE: + if (usbInfo->devState == USBD_DEV_CONFIGURE) + { + usbDevCDC->itf = 0; + USBD_CtrlSendData(usbInfo, (uint8_t*)&usbDevCDC->itf, 1); + } + else + { + USBD_REQ_CtrlError(usbInfo, req); + usbStatus = USBD_FAIL; + } + break; + + case USBD_STD_SET_INTERFACE: + if (usbInfo->devState == USBD_DEV_CONFIGURE) + { + + } + else + { + USBD_REQ_CtrlError(usbInfo, req); + usbStatus = USBD_FAIL; + } + break; + + case USBD_STD_CLEAR_FEATURE: + break; + + default: + USBD_REQ_CtrlError(usbInfo, req); + usbStatus = USBD_FAIL; + break; + } + break; + + case USBD_REQ_TYPE_CLASS: + if(wLength) + { + if((usbInfo->reqSetup.DATA_FIELD.bmRequest.REQ_TYPE & 0x80) != 0) + { + ((USBD_CDC_INTERFACE_T *)usbInfo->devClassUserData[usbInfo->classID])->ItfCtrl(request, \ + (uint8_t *)usbDevCDC->data, + wLength); + + length = USBD_CDC_DATA_MP_SIZE < wLength ? USBD_CDC_DATA_MP_SIZE : wLength; + USBD_CtrlSendData(usbInfo, (uint8_t *)usbDevCDC->data, length); + } + else + { + usbDevCDC->cdcCmd.opcode = request; + usbDevCDC->cdcCmd.length = wLength < USBD_EP0_PACKET_MAX_SIZE ? \ + wLength : USBD_EP0_PACKET_MAX_SIZE; + + USBD_CDC_CtrlReceiveData(usbInfo, (uint8_t *)usbDevCDC->data, usbDevCDC->cdcCmd.length); + } + } + else + { + ((USBD_CDC_INTERFACE_T *)usbInfo->devClassUserData[usbInfo->classID])->ItfCtrl(request, \ + (uint8_t *)req, \ + 0); + } + break; + + case USBD_REQ_TYPE_VENDOR: + USBD_REQ_CtrlError(usbInfo, req); + usbStatus = USBD_FAIL; + break; + + default: + usbStatus = USBD_FAIL; + USBD_REQ_CtrlError(usbInfo, req); + break; + } + + return usbStatus; +} + +/*! + * @brief USB device CDC EP0 receive handler + * + * @param usbInfo: usb device information + * + * @retval USB device operation status + */ +static USBD_STA_T USBD_CDC_RxEP0Handler(USBD_INFO_T* usbInfo) +{ + USBD_STA_T usbStatus = USBD_OK; + USBD_CDC_INFO_T* usbDevCDC = (USBD_CDC_INFO_T*)usbInfo->devClass[usbInfo->classID]->classData; + + if (usbDevCDC == NULL) + { + return USBD_FAIL; + } + + if((usbInfo->devClassUserData[usbInfo->classID] != NULL) && (usbDevCDC->cdcCmd.opcode != 0xFF)) + { + ((USBD_CDC_INTERFACE_T *)usbInfo->devClassUserData[usbInfo->classID])->ItfCtrl(usbDevCDC->cdcCmd.opcode, \ + (uint8_t *)usbDevCDC->data, \ + (uint16_t)usbDevCDC->cdcCmd.length); + + usbDevCDC->cdcCmd.opcode = 0xFF; + } + + return usbStatus; +} + +/*! + * @brief USB device CDC IN data handler + * + * @param usbInfo: usb device information + * + * @param epNum: endpoint number + * + * @retval USB device operation status + */ +static USBD_STA_T USBD_CDC_DataInHandler(USBD_INFO_T* usbInfo, uint8_t epNum) +{ + USBD_STA_T usbStatus = USBD_OK; + USBD_CDC_INFO_T* usbDevCDC = (USBD_CDC_INFO_T*)usbInfo->devClass[usbInfo->classID]->classData; + +#if defined(USE_DAL_DRIVER) + PCD_HandleTypeDef* usbdh = (PCD_HandleTypeDef *)usbInfo->dataPoint; +#else + USBD_HANDLE_T* usbdh = (USBD_HANDLE_T *)usbInfo->dataPoint; +#endif /* USE_DAL_DRIVER */ + if (usbdh == NULL) + { + return USBD_FAIL; + } + + if (usbDevCDC == NULL) + { + return USBD_FAIL; + } + +#if defined(USE_DAL_DRIVER) + if((usbInfo->devEpIn[epNum & 0x0F].length > 0) && \ + (usbInfo->devEpIn[epNum & 0x0F].length % usbdh->IN_ep[epNum & 0x0F].maxpacket) == 0) +#else + if((usbInfo->devEpIn[epNum & 0x0F].length > 0) && \ + (usbInfo->devEpIn[epNum & 0x0F].length % usbdh->epIN[epNum & 0x0F].mps) == 0) +#endif /* USE_DAL_DRIVER */ + { + usbInfo->devEpIn[epNum & 0x0F].length = 0; + + USBD_EP_TransferCallback(usbInfo, epNum, NULL, 0); + } + else + { + usbDevCDC->cdcTx.state = USBD_CDC_XFER_IDLE; + + if(((USBD_CDC_INTERFACE_T *)usbInfo->devClassUserData[usbInfo->classID])->ItfSendEnd != NULL) + { + ((USBD_CDC_INTERFACE_T *)usbInfo->devClassUserData[usbInfo->classID])->ItfSendEnd(epNum, \ + usbDevCDC->cdcTx.buffer, \ + &usbDevCDC->cdcTx.length); + } + } + + return usbStatus; +} + +/*! + * @brief USB device CDC OUT data handler + * + * @param usbInfo: usb device information + * + * @param epNum: endpoint number + * + * @retval USB device operation status + */ +static USBD_STA_T USBD_CDC_DataOutHandler(USBD_INFO_T* usbInfo, uint8_t epNum) +{ + USBD_STA_T usbStatus = USBD_OK; + USBD_CDC_INFO_T* usbDevCDC = (USBD_CDC_INFO_T*)usbInfo->devClass[usbInfo->classID]->classData; + + if (usbDevCDC == NULL) + { + return USBD_FAIL; + } + + usbDevCDC->cdcRx.length = USBD_EP_ReadRxDataLenCallback(usbInfo, epNum); + + ((USBD_CDC_INTERFACE_T *)usbInfo->devClassUserData[usbInfo->classID])->ItfReceive(usbDevCDC->cdcRx.buffer, \ + &usbDevCDC->cdcRx.length); + + return usbStatus; +} + +/*! + * @brief USB device CDC configure TX buffer handler + * + * @param usbInfo: usb device information + * + * @param buffer: tx buffer + * + * @param length: tx buffer length + * + * @retval USB device operation status + */ +USBD_STA_T USBD_CDC_ConfigTxBuffer(USBD_INFO_T* usbInfo, uint8_t *buffer, uint32_t length) +{ + USBD_STA_T usbStatus = USBD_OK; + USBD_CDC_INFO_T* usbDevCDC = (USBD_CDC_INFO_T*)usbInfo->devClass[usbInfo->classID]->classData; + + if (usbDevCDC == NULL) + { + return USBD_FAIL; + } + + usbDevCDC->cdcTx.buffer = buffer; + usbDevCDC->cdcTx.length = length; + + return usbStatus; +} + +/*! + * @brief USB device CDC configure RX buffer handler + * + * @param usbInfo: usb device information + * + * @param buffer: tx buffer + * + * @retval USB device operation status + */ +USBD_STA_T USBD_CDC_ConfigRxBuffer(USBD_INFO_T* usbInfo, uint8_t *buffer) +{ + USBD_STA_T usbStatus = USBD_OK; + USBD_CDC_INFO_T* usbDevCDC = (USBD_CDC_INFO_T*)usbInfo->devClass[usbInfo->classID]->classData; + + if (usbDevCDC == NULL) + { + return USBD_FAIL; + } + + usbDevCDC->cdcRx.buffer = buffer; + + return usbStatus; +} + +/*! + * @brief USB device CDC register interface handler + * + * @param usbInfo: usb device information + * + * @param itf: interface handler + * + * @retval USB device operation status + */ +USBD_STA_T USBD_CDC_RegisterItf(USBD_INFO_T* usbInfo, USBD_CDC_INTERFACE_T* itf) +{ + USBD_STA_T usbStatus = USBD_FAIL; + + if (itf != NULL) + { + usbInfo->devClassUserData[usbInfo->classID] = itf; + usbStatus = USBD_OK; + } + + return usbStatus; +} + +/*! + * @brief USB device CDC transmit packet handler + * + * @param usbInfo: usb device information + * + * @retval USB device operation status + */ +USBD_STA_T USBD_CDC_TxPacket(USBD_INFO_T* usbInfo) +{ + USBD_STA_T usbStatus = USBD_BUSY; + USBD_CDC_INFO_T* usbDevCDC = (USBD_CDC_INFO_T*)usbInfo->devClass[usbInfo->classID]->classData; + + if (usbDevCDC == NULL) + { + return USBD_FAIL; + } + + if(usbDevCDC->cdcTx.state == USBD_CDC_XFER_IDLE) + { + usbDevCDC->cdcTx.state = USBD_CDC_XFER_BUSY; + + usbInfo->devEpIn[usbDevCDC->epInAddr & 0x0F].length = usbDevCDC->cdcTx.length; + + USBD_EP_TransferCallback(usbInfo, usbDevCDC->epInAddr, usbDevCDC->cdcTx.buffer, usbDevCDC->cdcTx.length); + + usbStatus = USBD_OK; + } + + return usbStatus; +} + +/*! + * @brief USB device CDC receive packet handler + * + * @param usbInfo: usb device information + * + * @retval USB device operation status + */ +USBD_STA_T USBD_CDC_RxPacket(USBD_INFO_T* usbInfo) +{ + USBD_STA_T usbStatus = USBD_BUSY; + USBD_CDC_INFO_T* usbDevCDC = (USBD_CDC_INFO_T*)usbInfo->devClass[usbInfo->classID]->classData; + + if (usbDevCDC == NULL) + { + return USBD_FAIL; + } + + if(usbInfo->devSpeed == USBD_SPEED_HS) + { + USBD_EP_ReceiveCallback(usbInfo, usbDevCDC->epOutAddr, \ + usbDevCDC->cdcRx.buffer, \ + USBD_CDC_HS_MP_SIZE); + } + else + { + USBD_EP_ReceiveCallback(usbInfo, usbDevCDC->epOutAddr, \ + usbDevCDC->cdcRx.buffer, \ + USBD_CDC_FS_MP_SIZE); + } + + return usbStatus; +} + +/*! + * @brief USB device CDC read interval + * + * @param usbInfo: usb device information + * + * @retval usb interval + */ +uint8_t USBD_CDC_ReadInterval(USBD_INFO_T* usbInfo) +{ + uint8_t interval; + + if (usbInfo->devSpeed == USBD_SPEED_FS) + { + interval = USBD_CDC_FS_INTERVAL; + } + else + { + interval = USBD_CDC_HS_INTERVAL; + } + + return interval; +} + +/**@} end of group USBD_CDC_Functions */ +/**@} end of group USBD_CDC_Class */ +/**@} end of group APM32_USB_Library */ diff --git a/lib/main/APM32F4/Middlewares/APM32_USB_Library/Device/Class/Composite/usbd_composite_template.c b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Device/Class/Composite/usbd_composite_template.c new file mode 100644 index 0000000000..f21f0495d3 --- /dev/null +++ b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Device/Class/Composite/usbd_composite_template.c @@ -0,0 +1,228 @@ +/*! + * @file usbd_composite_template.c + * + * @brief usb device composite class handler + * + * @version V1.0.0 + * + * @date 2023-11-13 + * + * @attention + * + * Copyright (C) 2023 Geehy Semiconductor + * + * You may not use this file except in compliance with the + * GEEHY COPYRIGHT NOTICE (GEEHY SOFTWARE PACKAGE LICENSE). + * + * The program is only for reference, which is distributed in the hope + * that it will be useful and instructional for customers to develop + * their software. Unless required by applicable law or agreed to in + * writing, the program is distributed on an "AS IS" BASIS, WITHOUT + * ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied. + * See the GEEHY SOFTWARE PACKAGE LICENSE for the governing permissions + * and limitations under the License. + */ + +/* Includes */ +#include "usbd_composite.h" +#include "usbd_stdReq.h" +#include "usbd_dataXfer.h" +#include +#include +#include + +/** @addtogroup Examples + @{ + */ + +/** @addtogroup OTGD_Composite + @{ + */ + +/** @defgroup OTGD_Composite_Functions Functions + @{ + */ +static USBD_STA_T USBD_Composite_ClassInitHandler(USBD_INFO_T* usbInfo, uint8_t cfgIndex); +static USBD_STA_T USBD_Composite_ClassDeInitHandler(USBD_INFO_T* usbInfo, uint8_t cfgIndex); +static USBD_STA_T USBD_Composite_SOFHandler(USBD_INFO_T* usbInfo); +static USBD_STA_T USBD_Composite_SetupHandler(USBD_INFO_T* usbInfo, USBD_REQ_SETUP_T* req); +static USBD_STA_T USBD_Composite_RxEP0Handler(USBD_INFO_T* usbInfo); +static USBD_STA_T USBD_Composite_DataInHandler(USBD_INFO_T* usbInfo, uint8_t epNum); +static USBD_STA_T USBD_Composite_DataOutHandler(USBD_INFO_T* usbInfo, uint8_t epNum); +/**@} end of group OTGD_Composite_Functions */ + +/** @defgroup OTGD_Composite_Structures Structures + @{ + */ + +/* Composite class handler */ +USBD_CLASS_T USBD_COMPOSITE_CLASS = +{ + /* Class handler */ + "Class Composite", + NULL, + USBD_Composite_ClassInitHandler, + USBD_Composite_ClassDeInitHandler, + USBD_Composite_SOFHandler, + + /* Control endpoint */ + USBD_Composite_SetupHandler, + NULL, + USBD_Composite_RxEP0Handler, + /* Specific endpoint */ + USBD_Composite_DataInHandler, + USBD_Composite_DataOutHandler, + NULL, + NULL, +}; + +/**@} end of group OTGD_Composite_Structures*/ + +/** @defgroup OTGD_Composite_Functions Functions + @{ + */ + +/*! + * @brief USB device composite init + * + * @param usbInfo: usb device information + * + * @param itf1: class interface 1 + * + * @param itf2: class interface 2 + * + * @retval USB device operation status + */ +USBD_STA_T USBD_Composite_Init(USBD_INFO_T* usbInfo, void* itf1, void* itf2) +{ + USBD_STA_T usbStatus = USBD_OK; + + return usbStatus; +} + +/*! + * @brief USB device composite de-init + * + * @param usbInfo: usb device information + * + * @retval USB device operation status + */ +USBD_STA_T USBD_Composite_Deinit(USBD_INFO_T* usbInfo) +{ + USBD_STA_T usbStatus = USBD_OK; + + return usbStatus; +} + +/*! + * @brief USB device composite configuration handler + * + * @param usbInfo: usb device information + * + * @param cfgIndex: configuration index + * + * @retval USB device operation status + */ +static USBD_STA_T USBD_Composite_ClassInitHandler(USBD_INFO_T* usbInfo, uint8_t cfgIndex) +{ + USBD_STA_T usbStatus = USBD_OK; + + return usbStatus; +} + +/*! + * @brief USB device composite reset handler + * + * @param usbInfo: usb device information + * + * @param cfgIndex: configuration index + * + * @retval USB device operation status + */ +static USBD_STA_T USBD_Composite_ClassDeInitHandler(USBD_INFO_T* usbInfo, uint8_t cfgIndex) +{ + USBD_STA_T usbStatus = USBD_OK; + + return usbStatus; +} + +/*! + * @brief USB device composite SOF handler + * + * @param usbInfo: usb device information + * + * @retval USB device operation status + */ +static USBD_STA_T USBD_Composite_SOFHandler(USBD_INFO_T* usbInfo) +{ + USBD_STA_T usbStatus = USBD_BUSY; + + return usbStatus; +} + +/*! + * @brief USB device composite SETUP handler + * + * @param usbInfo: usb device information + * + * @param req: setup request + * + * @retval USB device operation status + */ +static USBD_STA_T USBD_Composite_SetupHandler(USBD_INFO_T* usbInfo, USBD_REQ_SETUP_T* req) +{ + USBD_STA_T usbStatus = USBD_OK; + + return usbStatus; +} + +/*! + * @brief USB device composite EP0 receive handler + * + * @param usbInfo: usb device information + * + * @retval USB device operation status + */ +static USBD_STA_T USBD_Composite_RxEP0Handler(USBD_INFO_T* usbInfo) +{ + USBD_STA_T usbStatus = USBD_OK; + + return usbStatus; +} + + +/*! + * @brief USB device composite IN data handler + * + * @param usbInfo: usb device information + * + * @param epNum: endpoint number + * + * @retval USB device operation status + */ +static USBD_STA_T USBD_Composite_DataInHandler(USBD_INFO_T* usbInfo, uint8_t epNum) +{ + USBD_STA_T usbStatus = USBD_OK; + + return usbStatus; +} + +/*! + * @brief USB device composite OUT data handler + * + * @param usbInfo: usb device information + * + * @param epNum: endpoint number + * + * @retval USB device operation status + */ +static USBD_STA_T USBD_Composite_DataOutHandler(USBD_INFO_T* usbInfo, uint8_t epNum) +{ + USBD_STA_T usbStatus = USBD_OK; + + return usbStatus; +} + +/**@} end of group OTGD_Composite_Functions */ +/**@} end of group OTGD_Composite */ +/**@} end of group Examples */ diff --git a/lib/main/APM32F4/Middlewares/APM32_USB_Library/Device/Class/Composite/usbd_composite_template.h b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Device/Class/Composite/usbd_composite_template.h new file mode 100644 index 0000000000..35fa94d9a3 --- /dev/null +++ b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Device/Class/Composite/usbd_composite_template.h @@ -0,0 +1,70 @@ +/*! + * @file usbd_composite_template.h + * + * @brief usb device composite class handler header file + * + * @version V1.0.0 + * + * @date 2023-11-13 + * + * @attention + * + * Copyright (C) 2023 Geehy Semiconductor + * + * You may not use this file except in compliance with the + * GEEHY COPYRIGHT NOTICE (GEEHY SOFTWARE PACKAGE LICENSE). + * + * The program is only for reference, which is distributed in the hope + * that it will be useful and instructional for customers to develop + * their software. Unless required by applicable law or agreed to in + * writing, the program is distributed on an "AS IS" BASIS, WITHOUT + * ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied. + * See the GEEHY SOFTWARE PACKAGE LICENSE for the governing permissions + * and limitations under the License. + */ + +/* Define to prevent recursive inclusion */ +#ifndef _USBD_COMPOSITE_H_ +#define _USBD_COMPOSITE_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +/* Includes */ +#include "usbd_core.h" + +/** @addtogroup Examples + @{ + */ + +/** @addtogroup OTGD_Composite + @{ + */ + +/** @defgroup OTGD_Composite_Macros Macros + @{ +*/ + +/**@} end of group OTGD_Composite_Macros*/ + +/** @defgroup OTGD_Composite_Structures Structures + @{ + */ +extern USBD_CLASS_T USBD_COMPOSITE_CLASS; +/**@} end of group OTGD_Composite_Structures*/ + +/** @defgroup OTGD_Composite_Functions Functions + @{ + */ +USBD_STA_T USBD_Composite_Init(USBD_INFO_T* usbInfo, void* itf1, void* itf2); +USBD_STA_T USBD_Composite_Deinit(USBD_INFO_T* usbInfo); +/**@} end of group OTGD_Composite_Functions */ +/**@} end of group OTGD_Composite */ +/**@} end of group Examples */ + +#ifdef __cplusplus +} +#endif + +#endif /* _USBD_COMPOSITE_H_ */ diff --git a/lib/main/APM32F4/Middlewares/APM32_USB_Library/Device/Class/CustomHID/Inc/usbd_customhid.h b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Device/Class/CustomHID/Inc/usbd_customhid.h new file mode 100644 index 0000000000..6e24baaad3 --- /dev/null +++ b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Device/Class/CustomHID/Inc/usbd_customhid.h @@ -0,0 +1,374 @@ +/*! + * @file usbd_hid.h + * + * @brief usb device hid class handler header file + * + * @version V1.0.0 + * + * @date 2023-01-16 + * + * @attention + * + * Copyright (C) 2023 Geehy Semiconductor + * + * You may not use this file except in compliance with the + * GEEHY COPYRIGHT NOTICE (GEEHY SOFTWARE PACKAGE LICENSE). + * + * The program is only for reference, which is distributed in the hope + * that it will be useful and instructional for customers to develop + * their software. Unless required by applicable law or agreed to in + * writing, the program is distributed on an "AS IS" BASIS, WITHOUT + * ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied. + * See the GEEHY SOFTWARE PACKAGE LICENSE for the governing permissions + * and limitations under the License. + */ + +/* Define to prevent recursive inclusion */ +#ifndef _USBD_CUSTOM_HID_H_ +#define _USBD_CUSTOM_HID_H_ + +/* Includes */ +#include "usbd_core.h" + +/** @addtogroup APM32_USB_Library + @{ + */ + +/** @addtogroup USBD_CUSTOM_HID_Class + @{ + */ + +/** @defgroup USBD_CUSTOM_HID_Macros Macros + @{ +*/ + +#define USBD_CUSTOM_HID_REPORT_DESC_SIZE 63 +#define USBD_CUSTOM_HID_DESC_SIZE 9 +#define USBD_CUSTOM_HID_FS_INTERVAL 10 +#define USBD_CUSTOM_HID_HS_INTERVAL 7 +#define USBD_CUSTOM_HID_IN_EP_ADDR 0x81 +#define USBD_CUSTOM_HID_IN_EP_SIZE 0x04 + +#define USBD_CUSTOM_HID_OUT_EP_ADDR 0x01 +#define USBD_CUSTOM_HID_OUT_EP_SIZE 0x04 + +#define USBD_CUSTOM_HID_FS_MP_SIZE 0x40 + +#define USBD_CLASS_SET_IDLE 0x0A +#define USBD_CLASS_GET_IDLE 0x02 + +#define USBD_CLASS_SET_REPORT 0x09 +#define USBD_CLASS_GET_REPORT 0x01 + +#define USBD_CLASS_SET_PROTOCOL 0x0B +#define USBD_CLASS_GET_PROTOCOL 0x03 + +/**@} end of group USBD_CUSTOM_HID_Macros*/ + +/** @defgroup USBD_CUSTOM_HID_Enumerates Enumerates + @{ + */ + +/** + * @brief HID state type + */ +typedef enum +{ + USBD_CUSTOM_HID_IDLE, + USBD_CUSTOM_HID_BUSY, +} USBD_CUSTOM_HID_STATE_T; + +/** + * @brief HID keyboard value + */ +typedef enum +{ + KEYBOARD_NONE, + KEYBOARD_ERROR_ROLL_OVER, + KEYBOARD_POST_FAIL, + KEYBOARD_ERROR_UNDEFINED, + KEYBOARD_A, + KEYBOARD_B, + KEYBOARD_C, + KEYBOARD_D, + KEYBOARD_E, + KEYBOARD_F, + KEYBOARD_G, + KEYBOARD_H, + KEYBOARD_I, + KEYBOARD_J, + KEYBOARD_K, + KEYBOARD_L, + KEYBOARD_M, + KEYBOARD_N, + KEYBOARD_O, + KEYBOARD_P, + KEYBOARD_Q, + KEYBOARD_R, + KEYBOARD_S, + KEYBOARD_T, + KEYBOARD_U, + KEYBOARD_V, + KEYBOARD_W, + KEYBOARD_X, + KEYBOARD_Y, + KEYBOARD_Z, + KEYBOARD_1_EXCLAMATION, + KEYBOARD_2_AT, + KEYBOARD_3_NUMBER_SIGN, + KEYBOARD_4_DOLLAR, + KEYBOARD_5_PERCENT, + KEYBOARD_6_CARET, + KEYBOARD_7_AMPERSAND, + KEYBOARD_8_ASTERISK, + KEYBOARD_9_OPARENTHESIS, + KEYBOARD_10_CPARENTHESIS, + KEYBOARD_ENTER, + KEYBOARD_ESCAPE, + KEYBOARD_BACKSPACE, + KEYBOARD_TAB, + KEYBOARD_SPACEBAR, + KEYBOARD_MINUS_UNDERSCORE, + KEYBOARD_EQUAL_PLUS, + KEYBOARD_OBRACKET_AND_OBRACE, + KEYBOARD_CBRACKET_AND_CBRACE, + KEYBOARD_BACKSLASH_VERTICAL_BAR, + KEYBOARD_NONUS_NUMBER_SIGN_TILDE, + KEYBOARD_SEMICOLON_COLON, + KEYBOARD_SINGLE_AND_DOUBLE_QUOTE, + KEYBOARD_GRAVE_ACCENT_AND_TILDE, + KEYBOARD_COMMA_AND_LESS, + KEYBOARD_DOT_GREATER, + KEYBOARD_SLASH_QUESTION, + KEYBOARD_CAPS_LOCK, + KEYBOARD_F1, + KEYBOARD_F2, + KEYBOARD_F3, + KEYBOARD_F4, + KEYBOARD_F5, + KEYBOARD_F6, + KEYBOARD_F7, + KEYBOARD_F8, + KEYBOARD_F9, + KEYBOARD_F10, + KEYBOARD_F11, + KEYBOARD_F12, + KEYBOARD_PRINTSCREEN, + KEYBOARD_SCROLL_LOCK, + KEYBOARD_PAUSE, + KEYBOARD_INSERT, + KEYBOARD_HOME, + KEYBOARD_PAGEUP, + KEYBOARD_DELETE, + KEYBOARD_END1, + KEYBOARD_PAGEDOWN, + KEYBOARD_RIGHTARROW, + KEYBOARD_LEFTARROW, + KEYBOARD_DOWNARROW, + KEYBOARD_UPARROW, + KEYBOARD_KEYBOARDPAD_NUM_LOCK_AND_CLEAR, + KEYBOARD_KEYBOARDPAD_SLASH, + KEYBOARD_KEYBOARDPAD_ASTERIKS, + KEYBOARD_KEYBOARDPAD_MINUS, + KEYBOARD_KEYBOARDPAD_PLUS, + KEYBOARD_KEYBOARDPAD_ENTER, + KEYBOARD_KEYBOARDPAD_1_END, + KEYBOARD_KEYBOARDPAD_2_DOWN_ARROW, + KEYBOARD_KEYBOARDPAD_3_PAGEDN, + KEYBOARD_KEYBOARDPAD_4_LEFT_ARROW, + KEYBOARD_KEYBOARDPAD_5, + KEYBOARD_KEYBOARDPAD_6_RIGHT_ARROW, + KEYBOARD_KEYBOARDPAD_7_HOME, + KEYBOARD_KEYBOARDPAD_8_UP_ARROW, + KEYBOARD_KEYBOARDPAD_9_PAGEUP, + KEYBOARD_KEYBOARDPAD_0_INSERT, + KEYBOARD_KEYBOARDPAD_DECIMAL_SEPARATOR_DELETE, + KEYBOARD_NONUS_BACK_SLASH_VERTICAL_BAR, + KEYBOARD_APPLICATION, + KEYBOARD_POWER, + KEYBOARD_KEYBOARDPAD_EQUAL, + KEYBOARD_F13, + KEYBOARD_F14, + KEYBOARD_F15, + KEYBOARD_F16, + KEYBOARD_F17, + KEYBOARD_F18, + KEYBOARD_F19, + KEYBOARD_F20, + KEYBOARD_F21, + KEYBOARD_F22, + KEYBOARD_F23, + KEYBOARD_F24, + KEYBOARD_EXECUTE, + KEYBOARD_HELP, + KEYBOARD_MENU, + KEYBOARD_SELECT, + KEYBOARD_STOP, + KEYBOARD_AGAIN, + KEYBOARD_UNDO, + KEYBOARD_CUT, + KEYBOARD_COPY, + KEYBOARD_PASTE, + KEYBOARD_FIND, + KEYBOARD_MUTE, + KEYBOARD_VOLUME_UP, + KEYBOARD_VOLUME_DOWN, + KEYBOARD_LOCKING_CAPS_LOCK, + KEYBOARD_LOCKING_NUM_LOCK, + KEYBOARD_LOCKING_SCROLL_LOCK, + KEYBOARD_KEYBOARDPAD_COMMA, + KEYBOARD_KEYBOARDPAD_EQUAL_SIGN, + KEYBOARD_INTERNATIONAL1, + KEYBOARD_INTERNATIONAL2, + KEYBOARD_INTERNATIONAL3, + KEYBOARD_INTERNATIONAL4, + KEYBOARD_INTERNATIONAL5, + KEYBOARD_INTERNATIONAL6, + KEYBOARD_INTERNATIONAL7, + KEYBOARD_INTERNATIONAL8, + KEYBOARD_INTERNATIONAL9, + KEYBOARD_LANG1, + KEYBOARD_LANG2, + KEYBOARD_LANG3, + KEYBOARD_LANG4, + KEYBOARD_LANG5, + KEYBOARD_LANG6, + KEYBOARD_LANG7, + KEYBOARD_LANG8, + KEYBOARD_LANG9, + KEYBOARD_ALTERNATE_ERASE, + KEYBOARD_SYSREQ, + KEYBOARD_CANCEL, + KEYBOARD_CLEAR, + KEYBOARD_PRIOR, + KEYBOARD_RETURN, + KEYBOARD_SEPARATOR, + KEYBOARD_OUT, + KEYBOARD_OPER, + KEYBOARD_CLEAR_AGAIN, + KEYBOARD_CRSEL, + KEYBOARD_EXSEL, + KEYBOARD_RESERVED1, + KEYBOARD_RESERVED2, + KEYBOARD_RESERVED3, + KEYBOARD_RESERVED4, + KEYBOARD_RESERVED5, + KEYBOARD_RESERVED6, + KEYBOARD_RESERVED7, + KEYBOARD_RESERVED8, + KEYBOARD_RESERVED9, + KEYBOARD_RESERVED10, + KEYBOARD_RESERVED11, + KEYBOARD_KEYBOARDPAD_00, + KEYBOARD_KEYBOARDPAD_000, + KEYBOARD_THOUSANDS_SEPARATOR, + KEYBOARD_DECIMAL_SEPARATOR, + KEYBOARD_CURRENCY_UNIT, + KEYBOARD_CURRENCY_SUB_UNIT, + KEYBOARD_KEYBOARDPAD_OPARENTHESIS, + KEYBOARD_KEYBOARDPAD_CPARENTHESIS, + KEYBOARD_KEYBOARDPAD_OBRACE, + KEYBOARD_KEYBOARDPAD_CBRACE, + KEYBOARD_KEYBOARDPAD_TAB, + KEYBOARD_KEYBOARDPAD_BACKSPACE, + KEYBOARD_KEYBOARDPAD_A, + KEYBOARD_KEYBOARDPAD_B, + KEYBOARD_KEYBOARDPAD_C, + KEYBOARD_KEYBOARDPAD_D, + KEYBOARD_KEYBOARDPAD_E, + KEYBOARD_KEYBOARDPAD_F, + KEYBOARD_KEYBOARDPAD_XOR, + KEYBOARD_KEYBOARDPAD_CARET, + KEYBOARD_KEYBOARDPAD_PERCENT, + KEYBOARD_KEYBOARDPAD_LESS, + KEYBOARD_KEYBOARDPAD_GREATER, + KEYBOARD_KEYBOARDPAD_AMPERSAND, + KEYBOARD_KEYBOARDPAD_LOGICAL_AND, + KEYBOARD_KEYBOARDPAD_VERTICAL_BAR, + KEYBOARD_KEYBOARDPAD_LOGIACL_OR, + KEYBOARD_KEYBOARDPAD_COLON, + KEYBOARD_KEYBOARDPAD_NUMBER_SIGN, + KEYBOARD_KEYBOARDPAD_SPACE, + KEYBOARD_KEYBOARDPAD_AT, + KEYBOARD_KEYBOARDPAD_EXCLAMATION_MARK, + KEYBOARD_KEYBOARDPAD_MEMORY_STORE, + KEYBOARD_KEYBOARDPAD_MEMORY_RECALL, + KEYBOARD_KEYBOARDPAD_MEMORY_CLEAR, + KEYBOARD_KEYBOARDPAD_MEMORY_ADD, + KEYBOARD_KEYBOARDPAD_MEMORY_SUBTRACT, + KEYBOARD_KEYBOARDPAD_MEMORY_MULTIPLY, + KEYBOARD_KEYBOARDPAD_MEMORY_DIVIDE, + KEYBOARD_KEYBOARDPAD_PLUSMINUS, + KEYBOARD_KEYBOARDPAD_CLEAR, + KEYBOARD_KEYBOARDPAD_CLEAR_ENTRY, + KEYBOARD_KEYBOARDPAD_BINARY, + KEYBOARD_KEYBOARDPAD_OCTAL, + KEYBOARD_KEYBOARDPAD_DECIMAL, + KEYBOARD_KEYBOARDPAD_HEXADECIMAL, + KEYBOARD_RESERVED12, + KEYBOARD_RESERVED13, + KEYBOARD_LEFTCONTROL, + KEYBOARD_LEFTSHIFT, + KEYBOARD_LEFTALT, + KEYBOARD_LEFT_GUI, + KEYBOARD_RIGHTCONTROL, + KEYBOARD_RIGHTSHIFT, + KEYBOARD_RIGHTALT, + KEYBOARD_RIGHT_GUI, +} USBH_HID_KEYBOARD_VALUE_T; + +/**@} end of group USBD_CUSTOM_HID_Enumerates*/ + +/** @defgroup USBD_CUSTOM_HID_Structures Structures + @{ + */ + +/** + * @brief USB device Custom HID interface handler + */ +typedef struct +{ + const char* itfName; + uint8_t *report; + USBD_STA_T (*ItfInit)(void); + USBD_STA_T (*ItfDeInit)(void); + USBD_STA_T (*ItfSend)(uint8_t *buffer, uint8_t length); + USBD_STA_T (*ItfReceive)(uint8_t *buffer, uint8_t *length); +} USBD_CUSTOM_HID_INTERFACE_T; + +/** + * @brief CUSTOM HID information management + */ +typedef struct +{ + uint8_t state; + uint8_t epInAddr; + + uint8_t epOutAddr; + uint8_t reportSize; + uint8_t report[USBD_CUSTOM_HID_OUT_EP_SIZE]; + uint8_t getReport; + + uint8_t altSettingStatus; + uint8_t idleStatus; + uint8_t protocol; +} USBD_CUSTOM_HID_INFO_T; + +extern USBD_CLASS_T USBD_CUSTOM_HID_CLASS; + +/**@} end of group USBD_CUSTOM_HID_Structures*/ + +/** @defgroup USBD_CUSTOM_HID_Functions Functions + @{ + */ + +uint8_t USBD_CUSTOM_HID_ReadInterval(USBD_INFO_T* usbInfo); +USBD_STA_T USBD_CUSTOM_HID_TxReport(USBD_INFO_T* usbInfo, uint8_t* report, uint16_t length); +USBD_STA_T USBD_CUSTOM_HID_RxPacket(USBD_INFO_T* usbInfo); +USBD_STA_T USBD_CUSTOM_HID_RegisterItf(USBD_INFO_T* usbInfo, USBD_CUSTOM_HID_INTERFACE_T* itf); + +/**@} end of group USBD_CUSTOM_HID_Functions */ +/**@} end of group USBD_CUSTOM_HID_Class */ +/**@} end of group APM32_USB_Library */ + +#endif diff --git a/lib/main/APM32F4/Middlewares/APM32_USB_Library/Device/Class/CustomHID/Src/usbd_customhid.c b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Device/Class/CustomHID/Src/usbd_customhid.c new file mode 100644 index 0000000000..b78b6cc81a --- /dev/null +++ b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Device/Class/CustomHID/Src/usbd_customhid.c @@ -0,0 +1,644 @@ +/*! + * @file usbd_customhid.c + * + * @brief usb device custom hid class handler + * + * @version V1.0.0 + * + * @date 2023-01-16 + * + * @attention + * + * Copyright (C) 2023 Geehy Semiconductor + * + * You may not use this file except in compliance with the + * GEEHY COPYRIGHT NOTICE (GEEHY SOFTWARE PACKAGE LICENSE). + * + * The program is only for reference, which is distributed in the hope + * that it will be useful and instructional for customers to develop + * their software. Unless required by applicable law or agreed to in + * writing, the program is distributed on an "AS IS" BASIS, WITHOUT + * ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied. + * See the GEEHY SOFTWARE PACKAGE LICENSE for the governing permissions + * and limitations under the License. + */ + +/* Includes */ +#include "usbd_customhid.h" +#include "usbd_stdReq.h" +#include "usbd_dataXfer.h" +#include +#include +#include + +/** @addtogroup APM32_USB_Library + @{ + */ + +/** @addtogroup USBD_CUSTOM_HID_Class + @{ + */ + +/** @defgroup USBD_CUSTOM_HID_Functions Functions + @{ + */ + +static USBD_STA_T USBD_CUSTOM_HID_ClassInitHandler(USBD_INFO_T* usbInfo, uint8_t cfgIndex); +static USBD_STA_T USBD_CUSTOM_HID_ClassDeInitHandler(USBD_INFO_T* usbInfo, uint8_t cfgIndex); +static USBD_STA_T USBD_CUSTOM_HID_SOFHandler(USBD_INFO_T* usbInfo); +static USBD_STA_T USBD_CUSTOM_HID_SetupHandler(USBD_INFO_T* usbInfo, USBD_REQ_SETUP_T* req); +static USBD_STA_T USBD_CUSTOM_HID_RxEP0Handler(USBD_INFO_T* usbInfo); +static USBD_STA_T USBD_CUSTOM_HID_DataInHandler(USBD_INFO_T* usbInfo, uint8_t epNum); +static USBD_STA_T USBD_CUSTOM_HID_DataOutHandler(USBD_INFO_T* usbInfo, uint8_t epNum); + +static USBD_DESC_INFO_T USBD_CUSTOM_HID_ReportDescHandler(USBD_INFO_T* usbInfo); +static USBD_DESC_INFO_T USBD_CUSTOM_HID_DescHandler(uint8_t usbSpeed); + +/**@} end of group USBD_CUSTOM_HID_Functions */ + +/** @defgroup USBD_CUSTOM_HID_Structures Structures + @{ + */ + +/* CUSTOM HID class handler */ +USBD_CLASS_T USBD_CUSTOM_HID_CLASS = +{ + /* Class handler */ + "Class custom HID", + NULL, + USBD_CUSTOM_HID_ClassInitHandler, + USBD_CUSTOM_HID_ClassDeInitHandler, + USBD_CUSTOM_HID_SOFHandler, + + /* Control endpoint */ + USBD_CUSTOM_HID_SetupHandler, + NULL, + USBD_CUSTOM_HID_RxEP0Handler, + /* Specific endpoint */ + USBD_CUSTOM_HID_DataInHandler, + USBD_CUSTOM_HID_DataOutHandler, + NULL, + NULL, +}; + +/**@} end of group USBD_CUSTOM_HID_Structures*/ + +/** @defgroup USBD_CUSTOM_HID_Variables Variables + @{ + */ + +/** + * @brief HID descriptor + */ +uint8_t USBD_HIDDesc[USBD_CUSTOM_HID_DESC_SIZE] = +{ + /* bLength */ + 0x09, + /* bDescriptorType: HID */ + USBD_DESC_HID, + /* bcdHID */ + 0x11, 0x01, + /* bCountryCode */ + 0x00, + /* bNumDescriptors */ + 0x01, + /* bDescriptorType */ + USBD_DESC_HID_REPORT, + /* wItemLength */ + USBD_CUSTOM_HID_REPORT_DESC_SIZE & 0xFF, USBD_CUSTOM_HID_REPORT_DESC_SIZE >> 8, +}; + +/**@} end of group USBD_CUSTOM_HID_Variables*/ + +/** @defgroup USBD_CUSTOM_HID_Functions Functions + @{ + */ + +/*! + * @brief USB device CUSTOM HID configuration handler + * + * @param usbInfo: usb device information + * + * @param cfgIndex: configuration index + * + * @retval USB device operation status + */ +static USBD_STA_T USBD_CUSTOM_HID_ClassInitHandler(USBD_INFO_T* usbInfo, uint8_t cfgIndex) +{ + USBD_STA_T usbStatus = USBD_OK; + + USBD_CUSTOM_HID_INFO_T* usbDevHID; + + /* Link class data */ + usbInfo->devClass[usbInfo->classID]->classData = (USBD_CUSTOM_HID_INFO_T*)malloc(sizeof(USBD_CUSTOM_HID_INFO_T)); + usbDevHID = (USBD_CUSTOM_HID_INFO_T*)usbInfo->devClass[usbInfo->classID]->classData; + memset(usbDevHID, 0, sizeof(USBD_CUSTOM_HID_INFO_T)); + + USBD_USR_Debug("USBD_CUSTOM_HID_INFO_T size %d\r\n", sizeof(USBD_CUSTOM_HID_INFO_T)); + + if (usbDevHID == NULL) + { + USBD_USR_LOG("usbDevHID is NULL"); + return USBD_FAIL; + } + + usbDevHID->epInAddr = USBD_CUSTOM_HID_IN_EP_ADDR; + usbDevHID->epOutAddr = USBD_CUSTOM_HID_OUT_EP_ADDR; + + if (usbInfo->devSpeed == USBD_SPEED_FS) + { + usbInfo->devEpIn[usbDevHID->epInAddr & 0x0F].interval = USBD_CUSTOM_HID_FS_INTERVAL; + usbInfo->devEpOut[usbDevHID->epOutAddr & 0x0F].interval = USBD_CUSTOM_HID_FS_INTERVAL; + } + else + { + usbInfo->devEpIn[usbDevHID->epInAddr & 0x0F].interval = USBD_CUSTOM_HID_HS_INTERVAL; + usbInfo->devEpOut[usbDevHID->epOutAddr & 0x0F].interval = USBD_CUSTOM_HID_HS_INTERVAL; + } + + /* Open endpoint */ + USBD_EP_OpenCallback(usbInfo, usbDevHID->epInAddr, EP_TYPE_INTERRUPT, USBD_CUSTOM_HID_IN_EP_SIZE); + usbInfo->devEpIn[usbDevHID->epInAddr & 0x0F].useStatus = ENABLE; + + USBD_EP_OpenCallback(usbInfo, usbDevHID->epOutAddr, EP_TYPE_INTERRUPT, USBD_CUSTOM_HID_OUT_EP_SIZE); + usbInfo->devEpOut[usbDevHID->epOutAddr & 0x0F].useStatus = ENABLE; + + ((USBD_CUSTOM_HID_INTERFACE_T *)usbInfo->devClassUserData[usbInfo->classID])->ItfInit(); + + USBD_EP_ReceiveCallback(usbInfo, usbDevHID->epOutAddr, \ + usbDevHID->report, \ + USBD_CUSTOM_HID_OUT_EP_SIZE); + + usbDevHID->state = USBD_CUSTOM_HID_IDLE; + + return usbStatus; +} + +/*! + * @brief USB device CUSTOM HID reset handler + * + * @param usbInfo: usb device information + * + * @param cfgIndex: configuration index + * + * @retval USB device operation status + */ +static USBD_STA_T USBD_CUSTOM_HID_ClassDeInitHandler(USBD_INFO_T* usbInfo, uint8_t cfgIndex) +{ + USBD_STA_T usbStatus = USBD_OK; + USBD_CUSTOM_HID_INFO_T* usbDevHID = (USBD_CUSTOM_HID_INFO_T*)usbInfo->devClass[usbInfo->classID]->classData; + + /* Close HID EP */ + USBD_EP_CloseCallback(usbInfo, usbDevHID->epInAddr); + usbInfo->devEpIn[usbDevHID->epInAddr & 0x0F].interval = 0; + usbInfo->devEpIn[usbDevHID->epInAddr & 0x0F].useStatus = DISABLE; + + USBD_EP_CloseCallback(usbInfo, usbDevHID->epOutAddr); + usbInfo->devEpOut[usbDevHID->epOutAddr & 0x0F].useStatus = DISABLE; + + if (usbInfo->devClass[usbInfo->classID]->classData != NULL) + { + if(((USBD_CUSTOM_HID_INTERFACE_T *)usbInfo->devClassUserData[usbInfo->classID])->ItfDeInit != NULL) + { + ((USBD_CUSTOM_HID_INTERFACE_T *)usbInfo->devClassUserData[usbInfo->classID])->ItfDeInit(); + } + free(usbInfo->devClass[usbInfo->classID]->classData); + usbInfo->devClass[usbInfo->classID]->classData = 0; + } + + return usbStatus; +} + +/*! + * @brief USB device CUSTOM HID SOF handler + * + * @param usbInfo: usb device information + * + * @retval USB device operation status + */ +static USBD_STA_T USBD_CUSTOM_HID_SOFHandler(USBD_INFO_T* usbInfo) +{ + USBD_STA_T usbStatus = USBD_BUSY; + + return usbStatus; +} + +/*! + * @brief USB CUSTOM HID device receive CTRL status + * + * @param usbInfo : usb handler information + * + * @param buffer : data buffer + * + * @param length : length of data + * + * @retval usb device status + */ +USBD_STA_T USBD_CUSTOM_HID_CtrlReceiveData(USBD_INFO_T* usbInfo, uint8_t *buffer, uint32_t length) +{ + USBD_STA_T usbStatus = USBD_OK; + + usbInfo->devEp0State = USBD_DEV_EP0_DATA_OUT; + usbInfo->devEpOut[USBD_EP_0].length = length; + usbInfo->devEpOut[USBD_EP_0].remainLen = length; + + USBD_EP_ReceiveCallback(usbInfo, USBD_EP_0, buffer, length); + + return usbStatus; +} + +/*! + * @brief USB device CUSTOM HID SETUP handler + * + * @param usbInfo: usb device information + * + * @param req: setup request + * + * @retval USB device operation status + */ +static USBD_STA_T USBD_CUSTOM_HID_SetupHandler(USBD_INFO_T* usbInfo, USBD_REQ_SETUP_T* req) +{ + USBD_STA_T usbStatus = USBD_OK; + USBD_CUSTOM_HID_INFO_T* usbDevHID = (USBD_CUSTOM_HID_INFO_T*)usbInfo->devClass[usbInfo->classID]->classData; + + USBD_DESC_INFO_T descInfo; + uint8_t request; + uint8_t reqType; + uint16_t wValue = req->DATA_FIELD.wValue[0] | req->DATA_FIELD.wValue[1] << 8; + uint16_t wLength = req->DATA_FIELD.wLength[0] | req->DATA_FIELD.wLength[1] << 8; + uint16_t status = 0x0000; + + if (usbDevHID == NULL) + { + USBD_USR_LOG("usbDevHID is NULL"); + return USBD_FAIL; + } + + request = req->DATA_FIELD.bRequest; + reqType = usbInfo->reqSetup.DATA_FIELD.bmRequest.REQ_TYPE_B.type; + + switch (reqType) + { + case USBD_REQ_TYPE_STANDARD: + switch (request) + { + /* HID descriptor */ + case USBD_STD_GET_DESCRIPTOR: + switch (req->DATA_FIELD.wValue[1]) + { + case USBD_DESC_HID_REPORT: + descInfo = USBD_CUSTOM_HID_ReportDescHandler(usbInfo); + + descInfo.size = descInfo.size < wLength ? descInfo.size : wLength; + break; + + case USBD_DESC_HID: + descInfo = USBD_CUSTOM_HID_DescHandler(usbInfo->devSpeed); + + descInfo.size = descInfo.size < wLength ? descInfo.size : wLength; + break; + + default: + USBD_REQ_CtrlError(usbInfo, req); + usbStatus = USBD_FAIL; + break; + } + + if (descInfo.desc != NULL) + { + USBD_CtrlSendData(usbInfo, descInfo.desc, descInfo.size); + } + + break; + + case USBD_STD_GET_STATUS: + if (usbInfo->devState == USBD_DEV_CONFIGURE) + { + USBD_CtrlSendData(usbInfo, (uint8_t*)&status, 2); + } + else + { + USBD_REQ_CtrlError(usbInfo, req); + usbStatus = USBD_FAIL; + } + break; + + case USBD_STD_GET_INTERFACE: + if (usbInfo->devState == USBD_DEV_CONFIGURE) + { + USBD_CtrlSendData(usbInfo, (uint8_t*)&usbDevHID->altSettingStatus, 1); + } + else + { + USBD_REQ_CtrlError(usbInfo, req); + usbStatus = USBD_FAIL; + } + break; + + case USBD_STD_SET_INTERFACE: + if (usbInfo->devState == USBD_DEV_CONFIGURE) + { + usbDevHID->altSettingStatus = wValue; + } + else + { + USBD_REQ_CtrlError(usbInfo, req); + usbStatus = USBD_FAIL; + } + break; + + case USBD_STD_CLEAR_FEATURE: + break; + + default: + USBD_REQ_CtrlError(usbInfo, req); + usbStatus = USBD_FAIL; + break; + } + break; + + case USBD_REQ_TYPE_CLASS: + switch (request) + { + case USBD_CLASS_SET_IDLE: + usbDevHID->idleStatus = req->DATA_FIELD.wValue[1]; + break; + + case USBD_CLASS_GET_IDLE: + USBD_CtrlSendData(usbInfo, (uint8_t*)&usbDevHID->idleStatus, 1); + break; + + case USBD_CLASS_SET_PROTOCOL: + usbDevHID->protocol = req->DATA_FIELD.wValue[0]; + break; + + case USBD_CLASS_GET_PROTOCOL: + USBD_CtrlSendData(usbInfo, (uint8_t*)&usbDevHID->protocol, 1); + break; + case USBD_CLASS_SET_REPORT: + if (wLength < USBD_CUSTOM_HID_OUT_EP_SIZE) + { + USBD_CUSTOM_HID_CtrlReceiveData(usbInfo, usbDevHID->report, wLength); + usbDevHID->reportSize = wLength; + } + else + { + USBD_CUSTOM_HID_CtrlReceiveData(usbInfo, usbDevHID->report, USBD_CUSTOM_HID_OUT_EP_SIZE); + usbDevHID->reportSize = USBD_CUSTOM_HID_OUT_EP_SIZE; + } + + usbDevHID->getReport = 1; + break; + default: + USBD_REQ_CtrlError(usbInfo, req); + usbStatus = USBD_FAIL; + break; + } + break; + + case USBD_REQ_TYPE_VENDOR: + USBD_REQ_CtrlError(usbInfo, req); + usbStatus = USBD_FAIL; + break; + + default: + usbStatus = USBD_FAIL; + USBD_REQ_CtrlError(usbInfo, req); + break; + } + + return usbStatus; +} + +/*! + * @brief USB device CUSTOM HID EP0 receive handler + * + * @param usbInfo: usb device information + * + * @retval USB device operation status + */ +static USBD_STA_T USBD_CUSTOM_HID_RxEP0Handler(USBD_INFO_T* usbInfo) +{ + USBD_STA_T usbStatus = USBD_OK; + USBD_CUSTOM_HID_INFO_T* usbDevHID = (USBD_CUSTOM_HID_INFO_T*)usbInfo->devClass[usbInfo->classID]->classData; + + if (usbDevHID == NULL) + { + return USBD_FAIL; + } + + if((usbInfo->devClassUserData[usbInfo->classID] != NULL) && (usbDevHID->getReport == 1)) + { + ((USBD_CUSTOM_HID_INTERFACE_T *)usbInfo->devClassUserData[usbInfo->classID])->ItfReceive(usbDevHID->report, \ + &usbDevHID->reportSize); + usbDevHID->getReport = 0; + } + + return usbStatus; +} + +/*! + * @brief USB device CUSTOM HID IN data handler + * + * @param usbInfo: usb device information + * + * @param epNum: endpoint number + * + * @retval USB device operation status + */ +static USBD_STA_T USBD_CUSTOM_HID_DataInHandler(USBD_INFO_T* usbInfo, uint8_t epNum) +{ + USBD_STA_T usbStatus = USBD_OK; + USBD_CUSTOM_HID_INFO_T* usbDevHID = (USBD_CUSTOM_HID_INFO_T*)usbInfo->devClass[usbInfo->classID]->classData; + + if (usbDevHID == NULL) + { + return USBD_FAIL; + } + + usbDevHID->state = USBD_CUSTOM_HID_IDLE; + + return usbStatus; +} + +/*! + * @brief USB device CUSTOM HID OUT data handler + * + * @param usbInfo: usb device information + * + * @param epNum: endpoint number + * + * @retval USB device operation status + */ +static USBD_STA_T USBD_CUSTOM_HID_DataOutHandler(USBD_INFO_T* usbInfo, uint8_t epNum) +{ + USBD_STA_T usbStatus = USBD_OK; + USBD_CUSTOM_HID_INFO_T* usbDevHID = (USBD_CUSTOM_HID_INFO_T*)usbInfo->devClass[usbInfo->classID]->classData; + + if (usbDevHID == NULL) + { + return USBD_FAIL; + } + + usbDevHID->reportSize = USBD_EP_ReadRxDataLenCallback(usbInfo, epNum); + + ((USBD_CUSTOM_HID_INTERFACE_T *)usbInfo->devClassUserData[usbInfo->classID])->ItfReceive(usbDevHID->report, \ + &usbDevHID->reportSize); + + + return usbStatus; +} + +/*! + * @brief USB device CUSTOM HID report descriptor + * + * @param usbSpeed : usb speed + * + * @retval usb descriptor information + */ +static USBD_DESC_INFO_T USBD_CUSTOM_HID_ReportDescHandler(USBD_INFO_T* usbInfo) +{ + USBD_DESC_INFO_T descInfo; + + descInfo.desc = (uint8_t*)(((USBD_CUSTOM_HID_INTERFACE_T*)usbInfo->devClassUserData[usbInfo->classID])->report); + descInfo.size = USBD_CUSTOM_HID_REPORT_DESC_SIZE; + + return descInfo; +} + +/*! + * @brief USB device CUSTOM HID descriptor + * + * @param usbSpeed : usb speed + * + * @retval usb descriptor information + */ +static USBD_DESC_INFO_T USBD_CUSTOM_HID_DescHandler(uint8_t usbSpeed) +{ + USBD_DESC_INFO_T descInfo; + + descInfo.desc = USBD_HIDDesc; + descInfo.size = sizeof(USBD_HIDDesc); + + return descInfo; +} + +/*! + * @brief USB device CUSTOM HID send report descriptor + * + * @param usbInfo: usb device information + * + * @param report: report buffer + * + * @param length: report data length + * + * @retval usb descriptor information + */ +USBD_STA_T USBD_CUSTOM_HID_TxReport(USBD_INFO_T* usbInfo, uint8_t* report, uint16_t length) +{ + USBD_STA_T usbStatus = USBD_OK; + USBD_CUSTOM_HID_INFO_T* usbDevHID = (USBD_CUSTOM_HID_INFO_T*)usbInfo->devClass[usbInfo->classID]->classData; + + if (usbDevHID == NULL) + { + return USBD_FAIL; + } + + switch (usbInfo->devState) + { + case USBD_DEV_CONFIGURE: + if (usbDevHID->state == USBD_CUSTOM_HID_IDLE) + { + usbDevHID->state = USBD_CUSTOM_HID_BUSY; + USBD_EP_TransferCallback(usbInfo, usbDevHID->epInAddr, report, length); + } + break; + + default: + break; + } + + return usbStatus; +} + +/*! + * @brief USB device CUSTOM HID receive packet handler + * + * @param usbInfo: usb device information + * + * @retval USB device operation status + */ +USBD_STA_T USBD_CUSTOM_HID_RxPacket(USBD_INFO_T* usbInfo) +{ + USBD_STA_T usbStatus = USBD_BUSY; + USBD_CUSTOM_HID_INFO_T* usbDevHID = (USBD_CUSTOM_HID_INFO_T*)usbInfo->devClass[usbInfo->classID]->classData; + + if (usbDevHID == NULL) + { + return USBD_FAIL; + } + + if(usbInfo->devSpeed == USBD_SPEED_HS) + { + USBD_EP_ReceiveCallback(usbInfo, usbDevHID->epOutAddr, \ + usbDevHID->report, \ + USBD_CUSTOM_HID_OUT_EP_SIZE); + } + else + { + USBD_EP_ReceiveCallback(usbInfo, usbDevHID->epOutAddr, \ + usbDevHID->report, \ + USBD_CUSTOM_HID_OUT_EP_SIZE); + } + + return usbStatus; +} + +/*! + * @brief USB device CUSTOM HID read interval + * + * @param usbInfo: usb device information + * + * @retval usb interval + */ +uint8_t USBD_CUSTOM_HID_ReadInterval(USBD_INFO_T* usbInfo) +{ + uint8_t interval; + + if (usbInfo->devSpeed == USBD_SPEED_FS) + { + interval = USBD_CUSTOM_HID_FS_INTERVAL; + } + else + { + interval = ((1 << (USBD_CUSTOM_HID_FS_INTERVAL - 1)) / 8); + } + + return interval; +} + +/*! + * @brief USB device CUSTOM HID register interface handler + * + * @param usbInfo: usb device information + * + * @param itf: interface handler + * + * @retval USB device operation status + */ +USBD_STA_T USBD_CUSTOM_HID_RegisterItf(USBD_INFO_T* usbInfo, USBD_CUSTOM_HID_INTERFACE_T* itf) +{ + USBD_STA_T usbStatus = USBD_FAIL; + + if (itf != NULL) + { + usbInfo->devClassUserData[usbInfo->classID] = itf; + usbStatus = USBD_OK; + } + + return usbStatus; +} + +/**@} end of group USBD_CUSTOM_HID_Functions */ +/**@} end of group USBD_CUSTOM_HID_Class */ +/**@} end of group APM32_USB_Library */ diff --git a/lib/main/APM32F4/Middlewares/APM32_USB_Library/Device/Class/HID/Inc/usbd_hid.h b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Device/Class/HID/Inc/usbd_hid.h new file mode 100644 index 0000000000..d0aca581eb --- /dev/null +++ b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Device/Class/HID/Inc/usbd_hid.h @@ -0,0 +1,350 @@ +/*! + * @file usbd_hid.h + * + * @brief usb device hid class handler header file + * + * @version V1.0.0 + * + * @date 2023-01-16 + * + * @attention + * + * Copyright (C) 2023 Geehy Semiconductor + * + * You may not use this file except in compliance with the + * GEEHY COPYRIGHT NOTICE (GEEHY SOFTWARE PACKAGE LICENSE). + * + * The program is only for reference, which is distributed in the hope + * that it will be useful and instructional for customers to develop + * their software. Unless required by applicable law or agreed to in + * writing, the program is distributed on an "AS IS" BASIS, WITHOUT + * ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied. + * See the GEEHY SOFTWARE PACKAGE LICENSE for the governing permissions + * and limitations under the License. + */ + +/* Define to prevent recursive inclusion */ +#ifndef _USBD_HID_H_ +#define _USBD_HID_H_ + +/* Includes */ +#include "usbd_core.h" + +/** @addtogroup APM32_USB_Library + @{ + */ + +/** @addtogroup USBD_HID_Class + @{ + */ + +/** @defgroup USBD_HID_Macros Macros + @{ +*/ + +#define USBD_HID_MOUSE_REPORT_DESC_SIZE 74 +#define USBD_HID_KEYBOARD_REPORT_DESC_SIZE 63 +#define USBD_HID_DESC_SIZE 9 +#define USBD_HID_FS_INTERVAL 10 +#define USBD_HID_HS_INTERVAL 7 +#define USBD_HID_IN_EP_ADDR 0x81 +#define USBD_HID_IN_EP_SIZE 0x04 +#define USBD_HID_FS_MP_SIZE 0x40 + +#define USBD_CLASS_SET_IDLE 0x0A +#define USBD_CLASS_GET_IDLE 0x02 + +#define USBD_CLASS_SET_REPORT 0x09 +#define USBD_CLASS_GET_REPORT 0x01 + +#define USBD_CLASS_SET_PROTOCOL 0x0B +#define USBD_CLASS_GET_PROTOCOL 0x03 + +/**@} end of group USBD_HID_Macros*/ + +/** @defgroup USBD_HID_Enumerates Enumerates + @{ + */ + +/** + * @brief HID state type + */ +typedef enum +{ + USBD_HID_IDLE, + USBD_HID_BUSY, +} USBD_HID_STATE_T; + +/** + * @brief HID keyboard value + */ +typedef enum +{ + KEYBOARD_NONE, + KEYBOARD_ERROR_ROLL_OVER, + KEYBOARD_POST_FAIL, + KEYBOARD_ERROR_UNDEFINED, + KEYBOARD_A, + KEYBOARD_B, + KEYBOARD_C, + KEYBOARD_D, + KEYBOARD_E, + KEYBOARD_F, + KEYBOARD_G, + KEYBOARD_H, + KEYBOARD_I, + KEYBOARD_J, + KEYBOARD_K, + KEYBOARD_L, + KEYBOARD_M, + KEYBOARD_N, + KEYBOARD_O, + KEYBOARD_P, + KEYBOARD_Q, + KEYBOARD_R, + KEYBOARD_S, + KEYBOARD_T, + KEYBOARD_U, + KEYBOARD_V, + KEYBOARD_W, + KEYBOARD_X, + KEYBOARD_Y, + KEYBOARD_Z, + KEYBOARD_1_EXCLAMATION, + KEYBOARD_2_AT, + KEYBOARD_3_NUMBER_SIGN, + KEYBOARD_4_DOLLAR, + KEYBOARD_5_PERCENT, + KEYBOARD_6_CARET, + KEYBOARD_7_AMPERSAND, + KEYBOARD_8_ASTERISK, + KEYBOARD_9_OPARENTHESIS, + KEYBOARD_10_CPARENTHESIS, + KEYBOARD_ENTER, + KEYBOARD_ESCAPE, + KEYBOARD_BACKSPACE, + KEYBOARD_TAB, + KEYBOARD_SPACEBAR, + KEYBOARD_MINUS_UNDERSCORE, + KEYBOARD_EQUAL_PLUS, + KEYBOARD_OBRACKET_AND_OBRACE, + KEYBOARD_CBRACKET_AND_CBRACE, + KEYBOARD_BACKSLASH_VERTICAL_BAR, + KEYBOARD_NONUS_NUMBER_SIGN_TILDE, + KEYBOARD_SEMICOLON_COLON, + KEYBOARD_SINGLE_AND_DOUBLE_QUOTE, + KEYBOARD_GRAVE_ACCENT_AND_TILDE, + KEYBOARD_COMMA_AND_LESS, + KEYBOARD_DOT_GREATER, + KEYBOARD_SLASH_QUESTION, + KEYBOARD_CAPS_LOCK, + KEYBOARD_F1, + KEYBOARD_F2, + KEYBOARD_F3, + KEYBOARD_F4, + KEYBOARD_F5, + KEYBOARD_F6, + KEYBOARD_F7, + KEYBOARD_F8, + KEYBOARD_F9, + KEYBOARD_F10, + KEYBOARD_F11, + KEYBOARD_F12, + KEYBOARD_PRINTSCREEN, + KEYBOARD_SCROLL_LOCK, + KEYBOARD_PAUSE, + KEYBOARD_INSERT, + KEYBOARD_HOME, + KEYBOARD_PAGEUP, + KEYBOARD_DELETE, + KEYBOARD_END1, + KEYBOARD_PAGEDOWN, + KEYBOARD_RIGHTARROW, + KEYBOARD_LEFTARROW, + KEYBOARD_DOWNARROW, + KEYBOARD_UPARROW, + KEYBOARD_KEYBOARDPAD_NUM_LOCK_AND_CLEAR, + KEYBOARD_KEYBOARDPAD_SLASH, + KEYBOARD_KEYBOARDPAD_ASTERIKS, + KEYBOARD_KEYBOARDPAD_MINUS, + KEYBOARD_KEYBOARDPAD_PLUS, + KEYBOARD_KEYBOARDPAD_ENTER, + KEYBOARD_KEYBOARDPAD_1_END, + KEYBOARD_KEYBOARDPAD_2_DOWN_ARROW, + KEYBOARD_KEYBOARDPAD_3_PAGEDN, + KEYBOARD_KEYBOARDPAD_4_LEFT_ARROW, + KEYBOARD_KEYBOARDPAD_5, + KEYBOARD_KEYBOARDPAD_6_RIGHT_ARROW, + KEYBOARD_KEYBOARDPAD_7_HOME, + KEYBOARD_KEYBOARDPAD_8_UP_ARROW, + KEYBOARD_KEYBOARDPAD_9_PAGEUP, + KEYBOARD_KEYBOARDPAD_0_INSERT, + KEYBOARD_KEYBOARDPAD_DECIMAL_SEPARATOR_DELETE, + KEYBOARD_NONUS_BACK_SLASH_VERTICAL_BAR, + KEYBOARD_APPLICATION, + KEYBOARD_POWER, + KEYBOARD_KEYBOARDPAD_EQUAL, + KEYBOARD_F13, + KEYBOARD_F14, + KEYBOARD_F15, + KEYBOARD_F16, + KEYBOARD_F17, + KEYBOARD_F18, + KEYBOARD_F19, + KEYBOARD_F20, + KEYBOARD_F21, + KEYBOARD_F22, + KEYBOARD_F23, + KEYBOARD_F24, + KEYBOARD_EXECUTE, + KEYBOARD_HELP, + KEYBOARD_MENU, + KEYBOARD_SELECT, + KEYBOARD_STOP, + KEYBOARD_AGAIN, + KEYBOARD_UNDO, + KEYBOARD_CUT, + KEYBOARD_COPY, + KEYBOARD_PASTE, + KEYBOARD_FIND, + KEYBOARD_MUTE, + KEYBOARD_VOLUME_UP, + KEYBOARD_VOLUME_DOWN, + KEYBOARD_LOCKING_CAPS_LOCK, + KEYBOARD_LOCKING_NUM_LOCK, + KEYBOARD_LOCKING_SCROLL_LOCK, + KEYBOARD_KEYBOARDPAD_COMMA, + KEYBOARD_KEYBOARDPAD_EQUAL_SIGN, + KEYBOARD_INTERNATIONAL1, + KEYBOARD_INTERNATIONAL2, + KEYBOARD_INTERNATIONAL3, + KEYBOARD_INTERNATIONAL4, + KEYBOARD_INTERNATIONAL5, + KEYBOARD_INTERNATIONAL6, + KEYBOARD_INTERNATIONAL7, + KEYBOARD_INTERNATIONAL8, + KEYBOARD_INTERNATIONAL9, + KEYBOARD_LANG1, + KEYBOARD_LANG2, + KEYBOARD_LANG3, + KEYBOARD_LANG4, + KEYBOARD_LANG5, + KEYBOARD_LANG6, + KEYBOARD_LANG7, + KEYBOARD_LANG8, + KEYBOARD_LANG9, + KEYBOARD_ALTERNATE_ERASE, + KEYBOARD_SYSREQ, + KEYBOARD_CANCEL, + KEYBOARD_CLEAR, + KEYBOARD_PRIOR, + KEYBOARD_RETURN, + KEYBOARD_SEPARATOR, + KEYBOARD_OUT, + KEYBOARD_OPER, + KEYBOARD_CLEAR_AGAIN, + KEYBOARD_CRSEL, + KEYBOARD_EXSEL, + KEYBOARD_RESERVED1, + KEYBOARD_RESERVED2, + KEYBOARD_RESERVED3, + KEYBOARD_RESERVED4, + KEYBOARD_RESERVED5, + KEYBOARD_RESERVED6, + KEYBOARD_RESERVED7, + KEYBOARD_RESERVED8, + KEYBOARD_RESERVED9, + KEYBOARD_RESERVED10, + KEYBOARD_RESERVED11, + KEYBOARD_KEYBOARDPAD_00, + KEYBOARD_KEYBOARDPAD_000, + KEYBOARD_THOUSANDS_SEPARATOR, + KEYBOARD_DECIMAL_SEPARATOR, + KEYBOARD_CURRENCY_UNIT, + KEYBOARD_CURRENCY_SUB_UNIT, + KEYBOARD_KEYBOARDPAD_OPARENTHESIS, + KEYBOARD_KEYBOARDPAD_CPARENTHESIS, + KEYBOARD_KEYBOARDPAD_OBRACE, + KEYBOARD_KEYBOARDPAD_CBRACE, + KEYBOARD_KEYBOARDPAD_TAB, + KEYBOARD_KEYBOARDPAD_BACKSPACE, + KEYBOARD_KEYBOARDPAD_A, + KEYBOARD_KEYBOARDPAD_B, + KEYBOARD_KEYBOARDPAD_C, + KEYBOARD_KEYBOARDPAD_D, + KEYBOARD_KEYBOARDPAD_E, + KEYBOARD_KEYBOARDPAD_F, + KEYBOARD_KEYBOARDPAD_XOR, + KEYBOARD_KEYBOARDPAD_CARET, + KEYBOARD_KEYBOARDPAD_PERCENT, + KEYBOARD_KEYBOARDPAD_LESS, + KEYBOARD_KEYBOARDPAD_GREATER, + KEYBOARD_KEYBOARDPAD_AMPERSAND, + KEYBOARD_KEYBOARDPAD_LOGICAL_AND, + KEYBOARD_KEYBOARDPAD_VERTICAL_BAR, + KEYBOARD_KEYBOARDPAD_LOGIACL_OR, + KEYBOARD_KEYBOARDPAD_COLON, + KEYBOARD_KEYBOARDPAD_NUMBER_SIGN, + KEYBOARD_KEYBOARDPAD_SPACE, + KEYBOARD_KEYBOARDPAD_AT, + KEYBOARD_KEYBOARDPAD_EXCLAMATION_MARK, + KEYBOARD_KEYBOARDPAD_MEMORY_STORE, + KEYBOARD_KEYBOARDPAD_MEMORY_RECALL, + KEYBOARD_KEYBOARDPAD_MEMORY_CLEAR, + KEYBOARD_KEYBOARDPAD_MEMORY_ADD, + KEYBOARD_KEYBOARDPAD_MEMORY_SUBTRACT, + KEYBOARD_KEYBOARDPAD_MEMORY_MULTIPLY, + KEYBOARD_KEYBOARDPAD_MEMORY_DIVIDE, + KEYBOARD_KEYBOARDPAD_PLUSMINUS, + KEYBOARD_KEYBOARDPAD_CLEAR, + KEYBOARD_KEYBOARDPAD_CLEAR_ENTRY, + KEYBOARD_KEYBOARDPAD_BINARY, + KEYBOARD_KEYBOARDPAD_OCTAL, + KEYBOARD_KEYBOARDPAD_DECIMAL, + KEYBOARD_KEYBOARDPAD_HEXADECIMAL, + KEYBOARD_RESERVED12, + KEYBOARD_RESERVED13, + KEYBOARD_LEFTCONTROL, + KEYBOARD_LEFTSHIFT, + KEYBOARD_LEFTALT, + KEYBOARD_LEFT_GUI, + KEYBOARD_RIGHTCONTROL, + KEYBOARD_RIGHTSHIFT, + KEYBOARD_RIGHTALT, + KEYBOARD_RIGHT_GUI, +} USBH_HID_KEYBOARD_VALUE_T; + +/**@} end of group USBD_HID_Enumerates*/ + +/** @defgroup USBD_HID_Structures Structures + @{ + */ + +/** + * @brief HID information management + */ +typedef struct +{ + uint8_t state; + uint8_t epInAddr; + uint8_t altSettingStatus; + uint8_t idleStatus; + uint8_t protocol; +} USBD_HID_INFO_T; + +extern USBD_CLASS_T USBD_HID_CLASS; + +/**@} end of group USBD_HID_Structures*/ + +/** @defgroup USBD_HID_Functions Functions + @{ + */ + +uint8_t USBD_HID_ReadInterval(USBD_INFO_T* usbInfo); +USBD_STA_T USBD_HID_TxReport(USBD_INFO_T* usbInfo, uint8_t* report, uint16_t length); + +/**@} end of group USBD_HID_Functions */ +/**@} end of group USBD_HID_Class */ +/**@} end of group APM32_USB_Library */ + +#endif diff --git a/lib/main/APM32F4/Middlewares/APM32_USB_Library/Device/Class/HID/Src/usbd_hid.c b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Device/Class/HID/Src/usbd_hid.c new file mode 100644 index 0000000000..e657281cda --- /dev/null +++ b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Device/Class/HID/Src/usbd_hid.c @@ -0,0 +1,523 @@ +/*! + * @file usbd_hid.c + * + * @brief usb device hid class handler + * + * @version V1.0.0 + * + * @date 2023-01-16 + * + * @attention + * + * Copyright (C) 2023 Geehy Semiconductor + * + * You may not use this file except in compliance with the + * GEEHY COPYRIGHT NOTICE (GEEHY SOFTWARE PACKAGE LICENSE). + * + * The program is only for reference, which is distributed in the hope + * that it will be useful and instructional for customers to develop + * their software. Unless required by applicable law or agreed to in + * writing, the program is distributed on an "AS IS" BASIS, WITHOUT + * ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied. + * See the GEEHY SOFTWARE PACKAGE LICENSE for the governing permissions + * and limitations under the License. + */ + +/* Includes */ +#include "usbd_hid.h" +#include "usbd_stdReq.h" +#include "usbd_dataXfer.h" +#include +#include +#include + +/** @addtogroup APM32_USB_Library + @{ + */ + +/** @addtogroup USBD_HID_Class + @{ + */ + +/** @defgroup USBD_HID_Functions Functions + @{ + */ + +static USBD_STA_T USBD_HID_ClassInitHandler(USBD_INFO_T* usbInfo, uint8_t cfgIndex); +static USBD_STA_T USBD_HID_ClassDeInitHandler(USBD_INFO_T* usbInfo, uint8_t cfgIndex); +static USBD_STA_T USBD_HID_SOFHandler(USBD_INFO_T* usbInfo); +static USBD_STA_T USBD_HID_SetupHandler(USBD_INFO_T* usbInfo, USBD_REQ_SETUP_T* req); +static USBD_STA_T USBD_HID_DataInHandler(USBD_INFO_T* usbInfo, uint8_t epNum); + +static USBD_DESC_INFO_T USBD_HID_ReportDescHandler(uint8_t usbSpeed); +static USBD_DESC_INFO_T USBD_HID_DescHandler(uint8_t usbSpeed); + +/**@} end of group USBD_HID_Functions */ + +/** @defgroup USBD_HID_Structures Structures + @{ + */ + +/* HID class handler */ +USBD_CLASS_T USBD_HID_CLASS = +{ + /* Class handler */ + "Class HID", + NULL, + USBD_HID_ClassInitHandler, + USBD_HID_ClassDeInitHandler, + USBD_HID_SOFHandler, + + /* Control endpoint */ + USBD_HID_SetupHandler, + NULL, + NULL, + /* Specific endpoint */ + USBD_HID_DataInHandler, + NULL, + NULL, + NULL, +}; + +/**@} end of group USBD_HID_Structures*/ + +/** @defgroup USBD_HID_Variables Variables + @{ + */ + +/** + * @brief HID descriptor + */ +uint8_t USBD_HIDDesc[USBD_HID_DESC_SIZE] = +{ + /* bLength */ + 0x09, + /* bDescriptorType: HID */ + USBD_DESC_HID, + /* bcdHID */ + 0x11, 0x01, + /* bCountryCode */ + 0x00, + /* bNumDescriptors */ + 0x01, + /* bDescriptorType */ + USBD_DESC_HID_REPORT, + /* wItemLength */ + USBD_HID_MOUSE_REPORT_DESC_SIZE & 0xFF, USBD_HID_MOUSE_REPORT_DESC_SIZE >> 8, +}; + +/** + * @brief HID mouse report descriptor + */ +uint8_t USBD_HIDReportDesc[USBD_HID_MOUSE_REPORT_DESC_SIZE] = +{ + 0x05, 0x01, /* Usage Page (Generic Desktop Ctrls) */ + 0x09, 0x02, /* Usage (Mouse) */ + 0xA1, 0x01, /* Collection (Application) */ + + 0x09, 0x01, /* Usage (Pointer) */ + 0xA1, 0x00, /* Collection (Physical) */ + 0x05, 0x09, /* Usage Page (Button) */ + 0x19, 0x01, /* Usage Minimum (0x01) */ + 0x29, 0x03, /* Usage Maximum (0x03) */ + 0x15, 0x00, /* Logical Minimum (0) */ + 0x25, 0x01, /* Logical Maximum (1) */ + 0x95, 0x03, /* Report Count (3) */ + 0x75, 0x01, /* Report Size (1) */ + 0x81, 0x02, /* Input (Data,Var,Abs) */ + 0x95, 0x01, /* Report Count (1) */ + 0x75, 0x05, /* Report Size (5) */ + 0x81, 0x01, /* Input (Const,Array,Abs) */ + 0x05, 0x01, /* Usage Page (Generic Desktop Ctrls) */ + 0x09, 0x30, /* Usage (X) */ + 0x09, 0x31, /* Usage (Y) */ + 0x09, 0x38, /* Usage (Wheel) */ + 0x15, 0x81, /* Logical Minimum (-127) */ + 0x25, 0x7F, /* Logical Maximum (127) */ + 0x75, 0x08, /* Report Size (8) */ + 0x95, 0x03, /* Report Count (3) */ + 0x81, 0x06, /* Input (Data,Var,Rel) */ + 0xC0, /* End Collection */ + + 0x09, 0x3C, /* Usage (Motion Wakeup) */ + 0x05, 0xFF, /* Usage Page (Reserved 0xFF) */ + 0x09, 0x01, /* Usage (0x01) */ + 0x15, 0x00, /* Logical Minimum (0) */ + 0x25, 0x01, /* Logical Maximum (1) */ + 0x75, 0x01, /* Report Size (1) */ + 0x95, 0x02, /* Report Count (2) */ + 0xB1, 0x22, /* Feature (Data,Var,Abs,NoWrp) */ + 0x75, 0x06, /* Report Size (6) */ + 0x95, 0x01, /* Report Count (1) */ + 0xB1, 0x01, /* Feature (Const,Array,Abs,NoWrp) */ + 0xC0 /* End Collection */ +}; + +/**@} end of group USBD_HID_Variables*/ + +/** @defgroup USBD_HID_Functions Functions + @{ + */ + +/*! + * @brief USB device HID configuration handler + * + * @param usbInfo: usb device information + * + * @param cfgIndex: configuration index + * + * @retval USB device operation status + */ +static USBD_STA_T USBD_HID_ClassInitHandler(USBD_INFO_T* usbInfo, uint8_t cfgIndex) +{ + USBD_STA_T usbStatus = USBD_OK; + + USBD_HID_INFO_T* usbDevHID; + + /* Link class data */ + usbInfo->devClass[usbInfo->classID]->classData = (USBD_HID_INFO_T*)malloc(sizeof(USBD_HID_INFO_T)); + usbDevHID = (USBD_HID_INFO_T*)usbInfo->devClass[usbInfo->classID]->classData; + memset(usbDevHID, 0, sizeof(USBD_HID_INFO_T)); + + USBD_USR_Debug("USBD_HID_INFO_T size %d\r\n", sizeof(USBD_HID_INFO_T)); + + if (usbDevHID == NULL) + { + USBD_USR_LOG("usbDevHID is NULL"); + return USBD_FAIL; + } + + usbDevHID->epInAddr = USBD_HID_IN_EP_ADDR; + + if (usbInfo->devSpeed == USBD_SPEED_FS) + { + usbInfo->devEpIn[usbDevHID->epInAddr & 0x0F].interval = USBD_HID_FS_INTERVAL; + } + else + { + usbInfo->devEpIn[usbDevHID->epInAddr & 0x0F].interval = USBD_HID_HS_INTERVAL; + } + + /* Open endpoint */ + USBD_EP_OpenCallback(usbInfo, usbDevHID->epInAddr, EP_TYPE_INTERRUPT, USBD_HID_IN_EP_SIZE); + usbInfo->devEpIn[usbDevHID->epInAddr & 0x0F].useStatus = ENABLE; + + usbDevHID->state = USBD_HID_IDLE; + + return usbStatus; +} + +/*! + * @brief USB device HID reset handler + * + * @param usbInfo: usb device information + * + * @param cfgIndex: configuration index + * + * @retval USB device operation status + */ +static USBD_STA_T USBD_HID_ClassDeInitHandler(USBD_INFO_T* usbInfo, uint8_t cfgIndex) +{ + USBD_STA_T usbStatus = USBD_OK; + USBD_HID_INFO_T* usbDevHID = (USBD_HID_INFO_T*)usbInfo->devClass[usbInfo->classID]->classData; + + /* Close HID EP */ + USBD_EP_CloseCallback(usbInfo, usbDevHID->epInAddr); + usbInfo->devEpIn[usbDevHID->epInAddr & 0x0F].interval = 0; + usbInfo->devEpIn[usbDevHID->epInAddr & 0x0F].useStatus = DISABLE; + + if (usbInfo->devClass[usbInfo->classID]->classData != NULL) + { + free(usbInfo->devClass[usbInfo->classID]->classData); + usbInfo->devClass[usbInfo->classID]->classData = 0; + } + + return usbStatus; +} + +/*! + * @brief USB device HID SOF handler + * + * @param usbInfo: usb device information + * + * @retval USB device operation status + */ +static USBD_STA_T USBD_HID_SOFHandler(USBD_INFO_T* usbInfo) +{ + USBD_STA_T usbStatus = USBD_BUSY; + + return usbStatus; +} + +/*! + * @brief USB device HID SETUP handler + * + * @param usbInfo: usb device information + * + * @param req: setup request + * + * @retval USB device operation status + */ +static USBD_STA_T USBD_HID_SetupHandler(USBD_INFO_T* usbInfo, USBD_REQ_SETUP_T* req) +{ + USBD_STA_T usbStatus = USBD_OK; + USBD_HID_INFO_T* usbDevHID = (USBD_HID_INFO_T*)usbInfo->devClass[usbInfo->classID]->classData; + + USBD_DESC_INFO_T descInfo; + uint8_t request; + uint8_t reqType; + uint16_t wValue = req->DATA_FIELD.wValue[0] | req->DATA_FIELD.wValue[1] << 8; + uint16_t wLength = req->DATA_FIELD.wLength[0] | req->DATA_FIELD.wLength[1] << 8; + uint16_t status = 0x0000; + + if (usbDevHID == NULL) + { + USBD_USR_LOG("usbDevHID is NULL"); + return USBD_FAIL; + } + + request = req->DATA_FIELD.bRequest; + reqType = usbInfo->reqSetup.DATA_FIELD.bmRequest.REQ_TYPE_B.type; + + switch (reqType) + { + case USBD_REQ_TYPE_STANDARD: + switch (request) + { + /* HID descriptor */ + case USBD_STD_GET_DESCRIPTOR: + switch (req->DATA_FIELD.wValue[1]) + { + case USBD_DESC_HID_REPORT: + descInfo = USBD_HID_ReportDescHandler(usbInfo->devSpeed); + + descInfo.size = descInfo.size < wLength ? descInfo.size : wLength; + break; + + case USBD_DESC_HID: + descInfo = USBD_HID_DescHandler(usbInfo->devSpeed); + + descInfo.size = descInfo.size < wLength ? descInfo.size : wLength; + break; + + default: + USBD_REQ_CtrlError(usbInfo, req); + usbStatus = USBD_FAIL; + break; + } + + if (descInfo.desc != NULL) + { + USBD_CtrlSendData(usbInfo, descInfo.desc, descInfo.size); + } + + break; + + case USBD_STD_GET_STATUS: + if (usbInfo->devState == USBD_DEV_CONFIGURE) + { + USBD_CtrlSendData(usbInfo, (uint8_t*)&status, 2); + } + else + { + USBD_REQ_CtrlError(usbInfo, req); + usbStatus = USBD_FAIL; + } + break; + + case USBD_STD_GET_INTERFACE: + if (usbInfo->devState == USBD_DEV_CONFIGURE) + { + USBD_CtrlSendData(usbInfo, (uint8_t*)&usbDevHID->altSettingStatus, 1); + } + else + { + USBD_REQ_CtrlError(usbInfo, req); + usbStatus = USBD_FAIL; + } + break; + + case USBD_STD_SET_INTERFACE: + if (usbInfo->devState == USBD_DEV_CONFIGURE) + { + usbDevHID->altSettingStatus = wValue; + } + else + { + USBD_REQ_CtrlError(usbInfo, req); + usbStatus = USBD_FAIL; + } + break; + + case USBD_STD_CLEAR_FEATURE: + break; + + default: + USBD_REQ_CtrlError(usbInfo, req); + usbStatus = USBD_FAIL; + break; + } + break; + + case USBD_REQ_TYPE_CLASS: + switch (request) + { + case USBD_CLASS_SET_IDLE: + usbDevHID->idleStatus = req->DATA_FIELD.wValue[1]; + break; + + case USBD_CLASS_GET_IDLE: + USBD_CtrlSendData(usbInfo, (uint8_t*)&usbDevHID->idleStatus, 1); + break; + + case USBD_CLASS_SET_PROTOCOL: + usbDevHID->protocol = req->DATA_FIELD.wValue[0]; + break; + + case USBD_CLASS_GET_PROTOCOL: + USBD_CtrlSendData(usbInfo, (uint8_t*)&usbDevHID->protocol, 1); + break; + + default: + USBD_REQ_CtrlError(usbInfo, req); + usbStatus = USBD_FAIL; + break; + } + break; + + case USBD_REQ_TYPE_VENDOR: + USBD_REQ_CtrlError(usbInfo, req); + usbStatus = USBD_FAIL; + break; + + default: + usbStatus = USBD_FAIL; + USBD_REQ_CtrlError(usbInfo, req); + break; + } + + return usbStatus; +} + +/*! + * @brief USB device HID IN data handler + * + * @param usbInfo: usb device information + * + * @param epNum: endpoint number + * + * @retval USB device operation status + */ +static USBD_STA_T USBD_HID_DataInHandler(USBD_INFO_T* usbInfo, uint8_t epNum) +{ + USBD_STA_T usbStatus = USBD_OK; + USBD_HID_INFO_T* usbDevHID = (USBD_HID_INFO_T*)usbInfo->devClass[usbInfo->classID]->classData; + + if (usbDevHID == NULL) + { + return USBD_FAIL; + } + + usbDevHID->state = USBD_HID_IDLE; + + return usbStatus; +} + +/*! + * @brief USB device HID report descriptor + * + * @param usbSpeed : usb speed + * + * @retval usb descriptor information + */ +static USBD_DESC_INFO_T USBD_HID_ReportDescHandler(uint8_t usbSpeed) +{ + USBD_DESC_INFO_T descInfo; + + descInfo.desc = USBD_HIDReportDesc; + descInfo.size = sizeof(USBD_HIDReportDesc); + + return descInfo; +} + +/*! + * @brief USB device HID descriptor + * + * @param usbSpeed : usb speed + * + * @retval usb descriptor information + */ +static USBD_DESC_INFO_T USBD_HID_DescHandler(uint8_t usbSpeed) +{ + USBD_DESC_INFO_T descInfo; + + descInfo.desc = USBD_HIDDesc; + descInfo.size = sizeof(USBD_HIDDesc); + + return descInfo; +} + +/*! + * @brief USB device HID send report descriptor + * + * @param usbInfo: usb device information + * + * @param report: report buffer + * + * @param length: report data length + * + * @retval usb descriptor information + */ +USBD_STA_T USBD_HID_TxReport(USBD_INFO_T* usbInfo, uint8_t* report, uint16_t length) +{ + USBD_STA_T usbStatus = USBD_OK; + USBD_HID_INFO_T* usbDevHID = (USBD_HID_INFO_T*)usbInfo->devClass[usbInfo->classID]->classData; + + if (usbDevHID == NULL) + { + return USBD_FAIL; + } + + switch (usbInfo->devState) + { + case USBD_DEV_CONFIGURE: + if (usbDevHID->state == USBD_HID_IDLE) + { + usbDevHID->state = USBD_HID_BUSY; + USBD_EP_TransferCallback(usbInfo, usbDevHID->epInAddr, report, length); + } + break; + + default: + break; + } + + return usbStatus; +} + +/*! + * @brief USB device HID read interval + * + * @param usbInfo: usb device information + * + * @retval usb interval + */ +uint8_t USBD_HID_ReadInterval(USBD_INFO_T* usbInfo) +{ + uint8_t interval; + + if (usbInfo->devSpeed == USBD_SPEED_FS) + { + interval = USBD_HID_FS_INTERVAL; + } + else + { + interval = ((1 << (USBD_HID_HS_INTERVAL - 1)) / 8); + } + + return interval; +} + +/**@} end of group USBD_HID_Functions */ +/**@} end of group USBD_HID_Class */ +/**@} end of group APM32_USB_Library */ diff --git a/lib/main/APM32F4/Middlewares/APM32_USB_Library/Device/Class/HID/Src/usbd_hid_keyboard.c b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Device/Class/HID/Src/usbd_hid_keyboard.c new file mode 100644 index 0000000000..eb449208e0 --- /dev/null +++ b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Device/Class/HID/Src/usbd_hid_keyboard.c @@ -0,0 +1,515 @@ +/*! + * @file usbd_hid_keyboard.c + * + * @brief usb device hid class handler + * + * @version V1.0.0 + * + * @date 2023-03-23 + * + * @attention + * + * Copyright (C) 2023 Geehy Semiconductor + * + * You may not use this file except in compliance with the + * GEEHY COPYRIGHT NOTICE (GEEHY SOFTWARE PACKAGE LICENSE). + * + * The program is only for reference, which is distributed in the hope + * that it will be useful and instructional for customers to develop + * their software. Unless required by applicable law or agreed to in + * writing, the program is distributed on an "AS IS" BASIS, WITHOUT + * ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied. + * See the GEEHY SOFTWARE PACKAGE LICENSE for the governing permissions + * and limitations under the License. + */ + +/* Includes */ +#include "usbd_hid.h" +#include "usbd_stdReq.h" +#include "usbd_dataXfer.h" +#include +#include +#include + +/** @addtogroup APM32_USB_Library + @{ + */ + +/** @addtogroup USBD_HID_Class + @{ + */ + +/** @defgroup USBD_HID_Keyboard_Functions Functions + @{ + */ + +static USBD_STA_T USBD_HID_ClassInitHandler(USBD_INFO_T* usbInfo, uint8_t cfgIndex); +static USBD_STA_T USBD_HID_ClassDeInitHandler(USBD_INFO_T* usbInfo, uint8_t cfgIndex); +static USBD_STA_T USBD_HID_SOFHandler(USBD_INFO_T* usbInfo); +static USBD_STA_T USBD_HID_SetupHandler(USBD_INFO_T* usbInfo, USBD_REQ_SETUP_T* req); +static USBD_STA_T USBD_HID_DataInHandler(USBD_INFO_T* usbInfo, uint8_t epNum); + +static USBD_DESC_INFO_T USBD_HID_ReportDescHandler(uint8_t usbSpeed); +static USBD_DESC_INFO_T USBD_HID_DescHandler(uint8_t usbSpeed); + +/**@} end of group USBD_HID_Keyboard_Functions */ + +/** @defgroup USBD_HID_Keyboard_Structures Structures + @{ + */ + +/* HID class handler */ +USBD_CLASS_T USBD_HID_CLASS = +{ + /* Class handler */ + "Class HID", + NULL, + USBD_HID_ClassInitHandler, + USBD_HID_ClassDeInitHandler, + USBD_HID_SOFHandler, + + /* Control endpoint */ + USBD_HID_SetupHandler, + NULL, + NULL, + /* Specific endpoint */ + USBD_HID_DataInHandler, + NULL, + NULL, + NULL, +}; + +/**@} end of group USBD_HID_Keyboard_Structures*/ + +/** @defgroup USBD_HID_Keyboard_Variables Variables + @{ + */ + +/** + * @brief HID descriptor + */ +uint8_t USBD_HIDDesc[USBD_HID_DESC_SIZE] = +{ + /* bLength */ + 0x09, + /* bDescriptorType: HID */ + USBD_DESC_HID, + /* bcdHID */ + 0x11, 0x01, + /* bCountryCode */ + 0x00, + /* bNumDescriptors */ + 0x01, + /* bDescriptorType */ + USBD_DESC_HID_REPORT, + /* wItemLength */ + USBD_HID_KEYBOARD_REPORT_DESC_SIZE & 0xFF, USBD_HID_KEYBOARD_REPORT_DESC_SIZE >> 8, +}; + +/** + * @brief HID keyboard report descriptor + */ +uint8_t USBD_HIDReportDesc[USBD_HID_KEYBOARD_REPORT_DESC_SIZE] = +{ + 0x05, 0x01, /* Usage Page (Generic Desktop Ctrls) */ + 0x09, 0x06, /* Usage (Keyboard) */ + 0xA1, 0x01, /* Collection (Application) */ + 0x05, 0x07, /* Usage Page (Keyboard) */ + 0x19, 0xE0, /* Usage Mininum (Keyboard LeftControl) */ + 0x29, 0xE7, /* Usage Maxinum (Keyboard Right GUI) */ + 0x15, 0x00, /* Logical Mininum (0) */ + 0x25, 0x01, /* Logical Maxinum (1) */ + 0x75, 0x01, /* Report Size (1) */ + 0x95, 0x08, /* Report Count (8) */ + 0x81, 0x02, /* Input (Data,Var,Abs) */ + 0x95, 0x01, /* Report Count (1) */ + 0x75, 0x08, /* Report Size (8) */ + 0x81, 0x03, /* Input (Cnst,Var,Abs) */ + 0x95, 0x05, /* Report Count (5) */ + 0x75, 0x01, /* Report Size (1) */ + 0x05, 0x08, /* Usage Page (LEDs) */ + 0x19, 0x01, /* Usage Mininum (Num Lock) */ + 0x29, 0x05, /* Usage Maxinum (Kana) */ + 0x91, 0x02, /* Output (Data,Var,Abs) */ + 0x95, 0x01, /* Report Count (1) */ + 0x75, 0x03, /* Report Size (3) */ + 0x91, 0x03, /* Output (Cnst,Var,Abs) */ + 0x95, 0x06, /* Report Count (6) */ + 0x75, 0x08, /* Report Size (8) */ + 0x15, 0x00, /* Logical Mininum (0) */ + 0x25, 0x65, /* Logical Maxinum (101) */ + 0x05, 0x07, /* Usage Page (Keyboard) */ + 0x19, 0x00, /* Usage Mininum (Reserved (no event indicated)) */ + 0x29, 0x65, /* Usage Maxinum (Keyboard Application) */ + 0x81, 0x00, /* Input (Data,Ary,Abs) */ + 0xC0 /* End Collection */ +}; + +/**@} end of group USBD_HID_Keyboard_Variables*/ + +/** @defgroup USBD_HID_Keyboard_Functions Functions + @{ + */ + +/*! + * @brief USB device HID configuration handler + * + * @param usbInfo: usb device information + * + * @param cfgIndex: configuration index + * + * @retval USB device operation status + */ +static USBD_STA_T USBD_HID_ClassInitHandler(USBD_INFO_T* usbInfo, uint8_t cfgIndex) +{ + USBD_STA_T usbStatus = USBD_OK; + + USBD_HID_INFO_T* usbDevHID; + + /* Link class data */ + usbInfo->devClass[usbInfo->classID]->classData = (USBD_HID_INFO_T*)malloc(sizeof(USBD_HID_INFO_T)); + usbDevHID = (USBD_HID_INFO_T*)usbInfo->devClass[usbInfo->classID]->classData; + memset(usbDevHID, 0, sizeof(USBD_HID_INFO_T)); + + USBD_USR_Debug("USBD_HID_INFO_T size %d\r\n", sizeof(USBD_HID_INFO_T)); + + if (usbDevHID == NULL) + { + USBD_USR_LOG("usbDevHID is NULL"); + return USBD_FAIL; + } + + usbDevHID->epInAddr = USBD_HID_IN_EP_ADDR; + + if (usbInfo->devSpeed == USBD_SPEED_FS) + { + usbInfo->devEpIn[usbDevHID->epInAddr & 0x0F].interval = USBD_HID_FS_INTERVAL; + } + else + { + usbInfo->devEpIn[usbDevHID->epInAddr & 0x0F].interval = USBD_HID_HS_INTERVAL; + } + + /* Open endpoint */ + USBD_EP_OpenCallback(usbInfo, usbDevHID->epInAddr, EP_TYPE_INTERRUPT, USBD_HID_IN_EP_SIZE); + usbInfo->devEpIn[usbDevHID->epInAddr & 0x0F].useStatus = ENABLE; + + usbDevHID->state = USBD_HID_IDLE; + + return usbStatus; +} + +/*! + * @brief USB device HID reset handler + * + * @param usbInfo: usb device information + * + * @param cfgIndex: configuration index + * + * @retval USB device operation status + */ +static USBD_STA_T USBD_HID_ClassDeInitHandler(USBD_INFO_T* usbInfo, uint8_t cfgIndex) +{ + USBD_STA_T usbStatus = USBD_OK; + USBD_HID_INFO_T* usbDevHID = (USBD_HID_INFO_T*)usbInfo->devClass[usbInfo->classID]->classData; + + /* Close HID EP */ + USBD_EP_CloseCallback(usbInfo, usbDevHID->epInAddr); + usbInfo->devEpIn[usbDevHID->epInAddr & 0x0F].interval = 0; + usbInfo->devEpIn[usbDevHID->epInAddr & 0x0F].useStatus = DISABLE; + + if (usbInfo->devClass[usbInfo->classID]->classData != NULL) + { + free(usbInfo->devClass[usbInfo->classID]->classData); + usbInfo->devClass[usbInfo->classID]->classData = 0; + } + + return usbStatus; +} + +/*! + * @brief USB device HID SOF handler + * + * @param usbInfo: usb device information + * + * @retval USB device operation status + */ +static USBD_STA_T USBD_HID_SOFHandler(USBD_INFO_T* usbInfo) +{ + USBD_STA_T usbStatus = USBD_BUSY; + + return usbStatus; +} + +/*! + * @brief USB device HID SETUP handler + * + * @param usbInfo: usb device information + * + * @param req: setup request + * + * @retval USB device operation status + */ +static USBD_STA_T USBD_HID_SetupHandler(USBD_INFO_T* usbInfo, USBD_REQ_SETUP_T* req) +{ + USBD_STA_T usbStatus = USBD_OK; + USBD_HID_INFO_T* usbDevHID = (USBD_HID_INFO_T*)usbInfo->devClass[usbInfo->classID]->classData; + + USBD_DESC_INFO_T descInfo; + uint8_t request; + uint8_t reqType; + uint16_t wValue = req->DATA_FIELD.wValue[0] | req->DATA_FIELD.wValue[1] << 8; + uint16_t wLength = req->DATA_FIELD.wLength[0] | req->DATA_FIELD.wLength[1] << 8; + uint16_t status = 0x0000; + + if (usbDevHID == NULL) + { + USBD_USR_LOG("usbDevHID is NULL"); + return USBD_FAIL; + } + + request = req->DATA_FIELD.bRequest; + reqType = usbInfo->reqSetup.DATA_FIELD.bmRequest.REQ_TYPE_B.type; + + switch (reqType) + { + case USBD_REQ_TYPE_STANDARD: + switch (request) + { + /* HID descriptor */ + case USBD_STD_GET_DESCRIPTOR: + switch (req->DATA_FIELD.wValue[1]) + { + case USBD_DESC_HID_REPORT: + descInfo = USBD_HID_ReportDescHandler(usbInfo->devSpeed); + + descInfo.size = descInfo.size < wLength ? descInfo.size : wLength; + break; + + case USBD_DESC_HID: + descInfo = USBD_HID_DescHandler(usbInfo->devSpeed); + + descInfo.size = descInfo.size < wLength ? descInfo.size : wLength; + break; + + default: + USBD_REQ_CtrlError(usbInfo, req); + usbStatus = USBD_FAIL; + break; + } + + if (descInfo.desc != NULL) + { + USBD_CtrlSendData(usbInfo, descInfo.desc, descInfo.size); + } + + break; + + case USBD_STD_GET_STATUS: + if (usbInfo->devState == USBD_DEV_CONFIGURE) + { + USBD_CtrlSendData(usbInfo, (uint8_t*)&status, 2); + } + else + { + USBD_REQ_CtrlError(usbInfo, req); + usbStatus = USBD_FAIL; + } + break; + + case USBD_STD_GET_INTERFACE: + if (usbInfo->devState == USBD_DEV_CONFIGURE) + { + USBD_CtrlSendData(usbInfo, (uint8_t*)&usbDevHID->altSettingStatus, 1); + } + else + { + USBD_REQ_CtrlError(usbInfo, req); + usbStatus = USBD_FAIL; + } + break; + + case USBD_STD_SET_INTERFACE: + if (usbInfo->devState == USBD_DEV_CONFIGURE) + { + usbDevHID->altSettingStatus = wValue; + } + else + { + USBD_REQ_CtrlError(usbInfo, req); + usbStatus = USBD_FAIL; + } + break; + + case USBD_STD_CLEAR_FEATURE: + break; + + default: + USBD_REQ_CtrlError(usbInfo, req); + usbStatus = USBD_FAIL; + break; + } + break; + + case USBD_REQ_TYPE_CLASS: + switch (request) + { + case USBD_CLASS_SET_IDLE: + usbDevHID->idleStatus = req->DATA_FIELD.wValue[1]; + break; + + case USBD_CLASS_GET_IDLE: + USBD_CtrlSendData(usbInfo, (uint8_t*)&usbDevHID->idleStatus, 1); + break; + + case USBD_CLASS_SET_PROTOCOL: + usbDevHID->protocol = req->DATA_FIELD.wValue[0]; + break; + + case USBD_CLASS_GET_PROTOCOL: + USBD_CtrlSendData(usbInfo, (uint8_t*)&usbDevHID->protocol, 1); + break; + + default: + USBD_REQ_CtrlError(usbInfo, req); + usbStatus = USBD_FAIL; + break; + } + break; + + case USBD_REQ_TYPE_VENDOR: + USBD_REQ_CtrlError(usbInfo, req); + usbStatus = USBD_FAIL; + break; + + default: + usbStatus = USBD_FAIL; + USBD_REQ_CtrlError(usbInfo, req); + break; + } + + return usbStatus; +} + +/*! + * @brief USB device HID IN data handler + * + * @param usbInfo: usb device information + * + * @param epNum: endpoint number + * + * @retval USB device operation status + */ +static USBD_STA_T USBD_HID_DataInHandler(USBD_INFO_T* usbInfo, uint8_t epNum) +{ + USBD_STA_T usbStatus = USBD_OK; + USBD_HID_INFO_T* usbDevHID = (USBD_HID_INFO_T*)usbInfo->devClass[usbInfo->classID]->classData; + + if (usbDevHID == NULL) + { + return USBD_FAIL; + } + + usbDevHID->state = USBD_HID_IDLE; + + return usbStatus; +} + +/*! + * @brief USB device HID report descriptor + * + * @param usbSpeed : usb speed + * + * @retval usb descriptor information + */ +static USBD_DESC_INFO_T USBD_HID_ReportDescHandler(uint8_t usbSpeed) +{ + USBD_DESC_INFO_T descInfo; + + descInfo.desc = USBD_HIDReportDesc; + descInfo.size = sizeof(USBD_HIDReportDesc); + + return descInfo; +} + +/*! + * @brief USB device HID descriptor + * + * @param usbSpeed : usb speed + * + * @retval usb descriptor information + */ +static USBD_DESC_INFO_T USBD_HID_DescHandler(uint8_t usbSpeed) +{ + USBD_DESC_INFO_T descInfo; + + descInfo.desc = USBD_HIDDesc; + descInfo.size = sizeof(USBD_HIDDesc); + + return descInfo; +} + +/*! + * @brief USB device HID send report descriptor + * + * @param usbInfo: usb device information + * + * @param report: report buffer + * + * @param length: report data length + * + * @retval usb descriptor information + */ +USBD_STA_T USBD_HID_TxReport(USBD_INFO_T* usbInfo, uint8_t* report, uint16_t length) +{ + USBD_STA_T usbStatus = USBD_OK; + USBD_HID_INFO_T* usbDevHID = (USBD_HID_INFO_T*)usbInfo->devClass[usbInfo->classID]->classData; + + if (usbDevHID == NULL) + { + return USBD_FAIL; + } + + switch (usbInfo->devState) + { + case USBD_DEV_CONFIGURE: + if (usbDevHID->state == USBD_HID_IDLE) + { + usbDevHID->state = USBD_HID_BUSY; + USBD_EP_TransferCallback(usbInfo, usbDevHID->epInAddr, report, length); + } + break; + + default: + break; + } + + return usbStatus; +} + +/*! + * @brief USB device HID read interval + * + * @param usbInfo: usb device information + * + * @retval usb interval + */ +uint8_t USBD_HID_ReadInterval(USBD_INFO_T* usbInfo) +{ + uint8_t interval; + + if (usbInfo->devSpeed == USBD_SPEED_FS) + { + interval = USBD_HID_FS_INTERVAL; + } + else + { + interval = ((1 << (USBD_HID_HS_INTERVAL - 1)) / 8); + } + + return interval; +} + +/**@} end of group USBD_HID_Keyboard_Functions */ +/**@} end of group USBD_HID_Class */ +/**@} end of group APM32_USB_Library */ diff --git a/lib/main/APM32F4/Middlewares/APM32_USB_Library/Device/Class/MSC/Inc/usbd_msc.h b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Device/Class/MSC/Inc/usbd_msc.h new file mode 100644 index 0000000000..bbc60d74a5 --- /dev/null +++ b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Device/Class/MSC/Inc/usbd_msc.h @@ -0,0 +1,122 @@ +/*! + * @file usbd_msc.h + * + * @brief usb device msc class handler header file + * + * @version V1.0.0 + * + * @date 2023-01-16 + * + * @attention + * + * Copyright (C) 2023 Geehy Semiconductor + * + * You may not use this file except in compliance with the + * GEEHY COPYRIGHT NOTICE (GEEHY SOFTWARE PACKAGE LICENSE). + * + * The program is only for reference, which is distributed in the hope + * that it will be useful and instructional for customers to develop + * their software. Unless required by applicable law or agreed to in + * writing, the program is distributed on an "AS IS" BASIS, WITHOUT + * ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied. + * See the GEEHY SOFTWARE PACKAGE LICENSE for the governing permissions + * and limitations under the License. + */ + +/* Define to prevent recursive inclusion */ +#ifndef _USBD_MSC_H_ +#define _USBD_MSC_H_ + +/* Includes */ +#include "usbd_core.h" +#include "usbd_msc_scsi.h" +#include "usbd_msc_bot.h" + +/** @addtogroup APM32_USB_Library + @{ + */ + +/** @addtogroup USBD_MSC_Class + @{ + */ + +/** @defgroup USBD_MSC_Macros Macros + @{ +*/ + +#define USBD_MSC_OUT_EP_ADDR 0x01 +#define USBD_MSC_IN_EP_ADDR 0x81 + +#define USBD_MSC_FS_MP_SIZE 0x40 +#define USBD_MSC_HS_MP_SIZE 0x200 + +#define USBD_CLASS_GET_MAX_LUN 0xFE +#define USBD_CLASS_BOT_RESET 0xFF + + +/**@} end of group USBD_MSC_Macros*/ + +/** @defgroup USBD_MSC_Structures Structures + @{ + */ + +/** + * @brief USB device storage handler + */ +typedef struct +{ + const char* memoryName; + uint8_t* inquiryData; + uint8_t (*MemoryReadMaxLun)(void); + USBD_STA_T (*MemoryInit)(uint8_t lun); + USBD_STA_T (*MemoryReadCapacity)(uint8_t lun, uint32_t* blockNum, uint16_t* blockSize); + USBD_STA_T (*MemoryCheckReady)(uint8_t lun); + USBD_STA_T (*MemoryCheckWPR)(uint8_t lun); + USBD_STA_T (*MemoryReadData)(uint8_t lun, uint8_t* buffer, uint32_t blockAddr, uint16_t blockLength); + USBD_STA_T (*MemoryWriteData)(uint8_t lun, uint8_t* buffer, uint32_t blockAddr, uint16_t blockLength); +} USBD_MSC_MEMORY_T; + +typedef struct +{ + int8_t (* Init)(uint8_t lun); + int8_t (* GetCapacity)(uint8_t lun, uint32_t *block_num, uint16_t *block_size); + int8_t (* IsReady)(uint8_t lun); + int8_t (* IsWriteProtected)(uint8_t lun); + int8_t (* Read)(uint8_t lun, uint8_t *buf, uint32_t blk_addr, uint16_t blk_len); + int8_t (* Write)(uint8_t lun, uint8_t *buf, uint32_t blk_addr, uint16_t blk_len); + int8_t (* GetMaxLun)(void); + int8_t *pInquiry; + +} USBD_StorageTypeDef; + +/** + * @brief MSC information management + */ +typedef struct +{ + uint8_t epInAddr; + uint8_t epOutAddr; + + uint8_t maxLun; + uint8_t itf; + + USBD_MSC_BOT_T* mscBot; + USBD_BOT_INFO_T usbDevBOT; + USBD_SCSI_INFO_T usbDevSCSI; +} USBD_MSC_INFO_T; + +extern USBD_CLASS_T USBD_MSC_CLASS; + +/**@} end of group USBD_MSC_Structures*/ + +/** @defgroup USBD_MSC_Functions Functions + @{ + */ + +USBD_STA_T USBD_MSC_RegisterMemory(USBD_INFO_T* usbInfo, USBD_MSC_MEMORY_T* memory); + +/**@} end of group USBD_MSC_Functions */ +/**@} end of group USBD_MSC_Class */ +/**@} end of group APM32_USB_Library */ + +#endif diff --git a/lib/main/APM32F4/Middlewares/APM32_USB_Library/Device/Class/MSC/Inc/usbd_msc_bot.h b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Device/Class/MSC/Inc/usbd_msc_bot.h new file mode 100644 index 0000000000..27afe60a22 --- /dev/null +++ b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Device/Class/MSC/Inc/usbd_msc_bot.h @@ -0,0 +1,218 @@ +/*! + * @file usbd_msc_bot.h + * + * @brief usb device msc bot handler header file + * + * @version V1.0.0 + * + * @date 2023-01-16 + * + * @attention + * + * Copyright (C) 2023 Geehy Semiconductor + * + * You may not use this file except in compliance with the + * GEEHY COPYRIGHT NOTICE (GEEHY SOFTWARE PACKAGE LICENSE). + * + * The program is only for reference, which is distributed in the hope + * that it will be useful and instructional for customers to develop + * their software. Unless required by applicable law or agreed to in + * writing, the program is distributed on an "AS IS" BASIS, WITHOUT + * ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied. + * See the GEEHY SOFTWARE PACKAGE LICENSE for the governing permissions + * and limitations under the License. + */ + +/* Define to prevent recursive inclusion */ +#ifndef _USBD_MSC_BOT_H_ +#define _USBD_MSC_BOT_H_ + +/* Includes */ +#include "usbd_core.h" + +/** @addtogroup APM32_USB_Library + @{ + */ + +/** @addtogroup USBD_MSC_Class + @{ + */ + +/** @defgroup USBD_MSC_Macros Macros + @{ +*/ + +/* CBW parameter */ +#define USBD_MSC_BOT_CBW_SIGNATURE (uint32_t)(0x43425355) +#define USBD_MSC_BOT_CBW_TAG (uint32_t)(0x20304050) +#define USBD_MSC_BOT_CBW_LEN 31 +#define USBD_BOT_CBW_CB_LEN 16 +#define USBD_LEN_CBW 10 + +/* CSW parameter */ +#define USBD_MSC_BOT_CSW_SIGNATURE (uint32_t)(0x53425355) +#define USBD_MSC_BOT_CSW_LEN 13 +#define USBD_LEN_CSW_MAX 63 + +#ifndef USBD_SUP_MSC_MEDIA_PACKET +#define USBD_SUP_MSC_MEDIA_PACKET 512U +#endif /* USBD_SUP_MSC_MEDIA_PACKET */ + +/**@} end of group USBD_MSC_Macros*/ + +/** @defgroup USBD_MSC_Enumerates Enumerates + @{ + */ + +/** + * @brief SCSI transmission state of BOT + */ +typedef enum +{ + USBD_BOT_IDLE, + USBD_BOT_DATAOUT, + USBD_BOT_DATAIN, + USBD_BOT_DATAIN_LAST, + USBD_BOT_DATA_SEND, + USBD_BOT_NO_DATA, +} USBD_BOT_STATE_T; + +/** + * @brief SCSI transmission status of BOT + */ +typedef enum +{ + USBD_BOT_NORMAL, + USBD_BOT_RECOVERY, + USBD_BOT_ERR, +} USBD_BOT_STATUS_T; + +/** + * @brief CSW status of BOT + */ +typedef enum +{ + USBD_BOT_CSW_OK, + USBD_BOT_CSW_FAIL, + USBD_BOT_CSW_ERROR, +} USBD_BOT_CSW_STA_T; + +/**@} end of group USBD_MSC_Enumerates*/ + +/** @defgroup USBD_MSC_Structures Structures + @{ + */ + +/** + * @brief USB device SCSI handler + */ +typedef struct +{ + USBD_STA_T(*MemoryInit)(uint8_t lun); + USBD_STA_T(*MemoryReadCapacity)(uint8_t lun, uint32_t* blockNum, uint16_t* blockSize); + USBD_STA_T(*MemoryCheckReady)(uint8_t lun); + USBD_STA_T(*MemoryCheckWPR)(uint8_t lun); + USBD_STA_T(*MemoryReadData)(uint8_t lun, uint8_t* buffer, uint32_t blockAddr, uint16_t blockLength); + USBD_STA_T(*MemoryWriteData)(uint8_t lun, uint8_t* buffer, uint32_t blockAddr, uint16_t blockLength); +} USBD_MSC_SCSI_T; + +/** + * @brief CBW flag + */ +typedef union +{ + uint8_t CBW_Flag; + + struct + { + uint8_t reserved : 7; + uint8_t dir : 1; + } CBW_FLAG_B; + +} USBD_BOT_CBW_FLAG_T; + +/** + * @brief Command Block Wrapper + */ +typedef union +{ + struct + { + uint32_t dSignature; + uint32_t dTag; + uint32_t dDataXferLen; + USBD_BOT_CBW_FLAG_T bmFlags; + uint8_t bLUN; + uint8_t bCBLen; + uint8_t CB[16]; + } DATA_FIELD; + + uint8_t buffer[31]; +} USBD_BOT_CBW_T; + +/** + * @brief Command Status Wrapper + */ +typedef union +{ + struct + { + uint32_t dSignature; + uint32_t dTag; + uint32_t dDataResidue; + uint8_t bStatus; + } DATA_FIELD; + + uint8_t buffer[13]; +} USBD_BOT_CSW_T; + +/** + * @brief USB device BOT handler + */ +typedef struct +{ + USBD_STA_T(*Init)(USBD_INFO_T* usbInfo); + USBD_STA_T(*DeInit)(USBD_INFO_T* usbInfo); +} USBD_MSC_BOT_T; + +/** + * @brief BOT transmission parameter + */ +typedef struct +{ + USBD_BOT_CBW_T CBW; + USBD_BOT_CSW_T CSW; + USBD_BOT_CSW_STA_T cswStatus; + uint8_t cbwStatus; +} USBD_BOT_CMDPACK_T; + +/** + * @brief MSC BOT information + */ +typedef struct +{ + uint8_t state; + uint8_t status; + USBD_BOT_CMDPACK_T cmdPack; + uint32_t dataLen; + uint8_t data[USBD_SUP_MSC_MEDIA_PACKET]; +} USBD_BOT_INFO_T; + +/**@} end of group USBD_MSC_Structures*/ + +/** @defgroup USBD_MSC_Functions Functions + @{ + */ + +USBD_STA_T USBD_MSC_BOT_Init(USBD_INFO_T* usbInfo); +USBD_STA_T USBD_MSC_BOT_DeInit(USBD_INFO_T* usbInfo); +USBD_STA_T USBD_MSC_BOT_Reset(USBD_INFO_T* usbInfo); +USBD_STA_T USBD_MSC_BOT_CBW_Decode(USBD_INFO_T* usbInfo); +USBD_STA_T USBD_MSC_BOT_ClearFeature(USBD_INFO_T* usbInfo, uint8_t epNum); +USBD_STA_T USBD_MSC_BOT_SendCSW(USBD_INFO_T* usbInfo, USBD_BOT_CSW_STA_T status); + +/**@} end of group USBD_MSC_Functions */ +/**@} end of group USBD_MSC_Class */ +/**@} end of group APM32_USB_Library */ + +#endif diff --git a/lib/main/APM32F4/Middlewares/APM32_USB_Library/Device/Class/MSC/Inc/usbd_msc_scsi.h b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Device/Class/MSC/Inc/usbd_msc_scsi.h new file mode 100644 index 0000000000..7918500e5f --- /dev/null +++ b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Device/Class/MSC/Inc/usbd_msc_scsi.h @@ -0,0 +1,190 @@ +/*! + * @file usbd_msc_scsi.h + * + * @brief usb device msc scsi handler header file + * + * @version V1.0.0 + * + * @date 2023-01-16 + * + * @attention + * + * Copyright (C) 2023 Geehy Semiconductor + * + * You may not use this file except in compliance with the + * GEEHY COPYRIGHT NOTICE (GEEHY SOFTWARE PACKAGE LICENSE). + * + * The program is only for reference, which is distributed in the hope + * that it will be useful and instructional for customers to develop + * their software. Unless required by applicable law or agreed to in + * writing, the program is distributed on an "AS IS" BASIS, WITHOUT + * ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied. + * See the GEEHY SOFTWARE PACKAGE LICENSE for the governing permissions + * and limitations under the License. + */ + +/* Define to prevent recursive inclusion */ +#ifndef _USBD_MSC_SCSI_H_ +#define _USBD_MSC_SCSI_H_ + +/* Includes */ +#include "usbd_core.h" + +/** @addtogroup APM32_USB_Library + @{ + */ + +/** @addtogroup USBD_MSC_Class + @{ + */ + +/** @defgroup USBD_MSC_Macros Macros + @{ +*/ + +/* Length define of command */ +#define USBD_LEN_STD_INQUIRY 36 +#define USBD_LEN_STD_MODE_SENSE6 23 +#define USBD_LEN_STD_MODE_SENSE10 27 +#define USBD_LEN_STD_REQ_SENSE 18 +#define USBD_SCSI_SENSE_LIST_NUMBER 4 +#define USBD_LEN_INQUIRY_PAGE00 6 +#define USBD_LEN_INQUIRY_PAGE80 8 + + +#define STANDARD_INQUIRY_DATA_LEN USBD_LEN_STD_INQUIRY + +/* SCSI Commands */ +#define USBD_SCSI_CMD_FORMAT_UNIT ((uint8_t)0x04) +#define USBD_SCSI_CMD_INQUIRY ((uint8_t)0x12) +#define USBD_SCSI_CMD_SEND_DIAGNOSTIC ((uint8_t)0x1D) +#define USBD_SCSI_CMD_ALLOW_MEDIUM_REMOVAL ((uint8_t)0x1E) + +#define USBD_SCSI_CMD_MODE_SELECT_6 ((uint8_t)0x15) +#define USBD_SCSI_CMD_MODE_SELECT_10 ((uint8_t)0x55) +#define USBD_SCSI_CMD_MODE_SENSE_6 ((uint8_t)0x1A) +#define USBD_SCSI_CMD_MODE_SENSE_10 ((uint8_t)0x5A) + +#define USBD_SCSI_CMD_READ_FORMAT_CAPACITIES ((uint8_t)0x23) +#define USBD_SCSI_CMD_READ_CAPACITY ((uint8_t)0x25) +#define USBD_SCSI_CMD_READ_CAPACITY_16 ((uint8_t)0x9E) + +#define USBD_SCSI_CMD_REQUEST_SENSE ((uint8_t)0x03) +#define USBD_SCSI_CMD_START_STOP_UNIT ((uint8_t)0x1B) +#define USBD_SCSI_CMD_TEST_UNIT_READY ((uint8_t)0x00) + +#define USBD_SCSI_CMD_WRITE6 ((uint8_t)0x0A) +#define USBD_SCSI_CMD_WRITE10 ((uint8_t)0x2A) +#define USBD_SCSI_CMD_WRITE12 ((uint8_t)0xAA) +#define USBD_SCSI_CMD_WRITE16 ((uint8_t)0x8A) + +#define USBD_SCSI_CMD_VERIFY_10 ((uint8_t)0x2F) +#define USBD_SCSI_CMD_VERIFY_12 ((uint8_t)0xAF) +#define USBD_SCSI_CMD_VERIFY_16 ((uint8_t)0x8F) + +#define USBD_SCSI_CMD_READ_6 ((uint8_t)0x08) +#define USBD_SCSI_CMD_READ_10 ((uint8_t)0x28) +#define USBD_SCSI_CMD_READ_12 ((uint8_t)0xA8) +#define USBD_SCSI_CMD_READ_16 ((uint8_t)0x88) + +/**@} end of group USBD_MSC_Macros*/ + +/** @defgroup USBD_MSC_Enumerates Enumerates + @{ + */ + +/** + * @brief MSC SCSI medium status + */ +typedef enum +{ + USBD_SCSI_MEDIUM_UNLOCK, + USBD_SCSI_MEDIUM_LOCK, + USBD_SCSI_MEDIUM_EJECT, +} USBD_MEDIUM_STA_T; + +/** + * @brief SCSI sense key type + */ +typedef enum +{ + USBD_SCSI_SENSE_KEY_NO_SENSE = 0x00, + USBD_SCSI_SENSE_KEY_RECOVERED_ERROR, + USBD_SCSI_SENSE_KEY_NOT_READY, + USBD_SCSI_SENSE_KEY_MEDIUM_ERROR, + USBD_SCSI_SENSE_KEY_HARDWARE_ERROR, + USBD_SCSI_SENSE_KEY_ILLEGAL_REQUEST, + USBD_SCSI_SENSE_KEY_UNIT_ATTENTION, + USBD_SCSI_SENSE_KEY_DATA_PROTECT, + USBD_SCSI_SENSE_KEY_BLANK_CHECK, + USBD_SCSI_SENSE_KEY_VENDOR_SPECIFIC, + USBD_SCSI_SENSE_KEY_COPY_ABORTED, + USBD_SCSI_SENSE_KEY_ABORTED_COMMAND, + USBD_SCSI_SENSE_KEY_VOLUME_OVERFLOW = 0x0D, + USBD_SCSI_SENSE_KEY_MISCOMPARE = 0x0E, +} USBD_SCSI_SENSE_KEY_T; + +/** + * @brief SCSI sense ASC type + */ +typedef enum +{ + USBD_SCSI_ASC_WRITE_FAULT = 0x03, + USBD_SCSI_ASC_UNRECOVERED_READ_ERROR = 0x11, + USBD_SCSI_ASC_PARAMETER_LIST_LENGTH_ERROR = 0x1A, + USBD_SCSI_ASC_INVALID_CDB = 0x20, + USBD_SCSI_ASC_ADDRESS_OUT_OF_RANGE = 0x21, + USBD_SCSI_ASC_INVALID_FIELED_IN_COMMAND = 0x24, + USBD_SCSI_ASC_INVALID_FIELD_IN_PARAMETER_LIST = 0x26, + USBD_SCSI_ASC_WRITE_PROTECTED = 0x27, + USBD_SCSI_ASC_MEDIUM_HAVE_CHANGED = 0x28, + USBD_SCSI_ASC_MEDIUM_NOT_PRESENT = 0x3A, +} USBD_SCSI_SENSE_ASC_T; + +/**@} end of group USBD_MSC_Enumerates*/ + +/** @defgroup USBD_MSC_Structures Structures + @{ + */ + +/** + * @brief MSC SCSI sense data type + */ +typedef struct +{ + uint8_t Key; + uint8_t ASC; + uint8_t ASCQ; +} USBD_SCSI_SENSE_T; + +/** + * @brief MSC SCSI information + */ +typedef struct +{ + uint8_t senseHead; + uint8_t senseEnd; + uint8_t mediumState; + + uint16_t blockSize; + uint32_t blockNum; + + uint32_t blockAddr; + uint32_t blockLen; + USBD_SCSI_SENSE_T sense[USBD_SCSI_SENSE_LIST_NUMBER]; +} USBD_SCSI_INFO_T; + +/**@} end of group USBD_MSC_Structures*/ + +/** @defgroup USBD_MSC_Functions Functions + @{ + */ + +USBD_STA_T USBD_SCSI_Handle(USBD_INFO_T* usbInfo, uint8_t lun, uint8_t* command); +USBD_STA_T USBD_SCSI_CodeSense(USBD_INFO_T* usbInfo, uint8_t lun, uint8_t key, uint8_t asc, uint8_t ascq); + +/**@} end of group USBD_MSC_Functions */ +/**@} end of group USBD_MSC_Class */ +/**@} end of group APM32_USB_Library */ + +#endif diff --git a/lib/main/APM32F4/Middlewares/APM32_USB_Library/Device/Class/MSC/Src/usbd_msc.c b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Device/Class/MSC/Src/usbd_msc.c new file mode 100644 index 0000000000..6ac27c04e7 --- /dev/null +++ b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Device/Class/MSC/Src/usbd_msc.c @@ -0,0 +1,457 @@ +/*! + * @file usbd_msc.c + * + * @brief usb device msc class handler + * + * @version V1.0.0 + * + * @date 2023-01-16 + * + * @attention + * + * Copyright (C) 2023 Geehy Semiconductor + * + * You may not use this file except in compliance with the + * GEEHY COPYRIGHT NOTICE (GEEHY SOFTWARE PACKAGE LICENSE). + * + * The program is only for reference, which is distributed in the hope + * that it will be useful and instructional for customers to develop + * their software. Unless required by applicable law or agreed to in + * writing, the program is distributed on an "AS IS" BASIS, WITHOUT + * ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied. + * See the GEEHY SOFTWARE PACKAGE LICENSE for the governing permissions + * and limitations under the License. + */ + +/* Includes */ +#include "usbd_msc.h" +#include "usbd_msc_bot.h" +#include "usbd_stdReq.h" +#include "usbd_dataXfer.h" +//#include +#include +#include + +/** @addtogroup APM32_USB_Library + @{ + */ + +/** @addtogroup USBD_MSC_Class + @{ + */ + +/** @defgroup USBD_MSC_Functions Functions + @{ + */ + +static USBD_STA_T USBD_MSC_ClassInitHandler(USBD_INFO_T* usbInfo, uint8_t cfgIndex); +static USBD_STA_T USBD_MSC_ClassDeInitHandler(USBD_INFO_T* usbInfo, uint8_t cfgIndex); +static USBD_STA_T USBD_MSC_SOFHandler(USBD_INFO_T* usbInfo); +static USBD_STA_T USBD_MSC_SetupHandler(USBD_INFO_T* usbInfo, USBD_REQ_SETUP_T* req); +static USBD_STA_T USBD_MSC_DataInHandler(USBD_INFO_T* usbInfo, uint8_t epNum); +static USBD_STA_T USBD_MSC_DataOutHandler(USBD_INFO_T* usbInfo, uint8_t epNum); + +/**@} end of group USBD_MSC_Functions */ + +/** @defgroup USBD_MSC_Structures Structures + @{ + */ + +/* MSC class handler */ +USBD_CLASS_T USBD_MSC_CLASS = +{ + /* Class handler */ + "Class MSC", + NULL, + USBD_MSC_ClassInitHandler, + USBD_MSC_ClassDeInitHandler, + USBD_MSC_SOFHandler, + + /* Control endpoint */ + USBD_MSC_SetupHandler, + NULL, + NULL, + /* Specific endpoint */ + USBD_MSC_DataInHandler, + USBD_MSC_DataOutHandler, + NULL, + NULL, +}; + +/**@} end of group USBD_MSC_Structures*/ + +/** @defgroup USBD_MSC_Functions Functions + @{ + */ + +/*! + * @brief USB device MSC configuration handler + * + * @param usbInfo: usb device information + * + * @param cfgIndex: configuration index + * + * @retval USB device operation status + */ +static USBD_STA_T USBD_MSC_ClassInitHandler(USBD_INFO_T* usbInfo, uint8_t cfgIndex) +{ + USBD_STA_T usbStatus = USBD_OK; + + USBD_MSC_INFO_T* usbDevMSC; + + UNUSED(cfgIndex); + + /* Link class data */ + usbInfo->devClass[usbInfo->classID]->classData = (USBD_MSC_INFO_T*)malloc(sizeof(USBD_MSC_INFO_T)); + usbDevMSC = (USBD_MSC_INFO_T*)usbInfo->devClass[usbInfo->classID]->classData; + memset(usbDevMSC, 0, sizeof(USBD_MSC_INFO_T)); + + USBD_USR_Debug("USBD_MSC_INFO_T size %d\r\n", sizeof(USBD_MSC_INFO_T)); + + if (usbDevMSC == NULL) + { + USBD_USR_LOG("usbDevMSC is NULL"); + return USBD_FAIL; + } + + usbDevMSC->epInAddr = USBD_MSC_IN_EP_ADDR; + usbDevMSC->epOutAddr = USBD_MSC_OUT_EP_ADDR; + + /* Open endpoint */ + switch (usbInfo->devSpeed) + { + case USBD_SPEED_FS: + USBD_EP_OpenCallback(usbInfo, usbDevMSC->epOutAddr, EP_TYPE_BULK, USBD_MSC_FS_MP_SIZE); + usbInfo->devEpOut[usbDevMSC->epOutAddr & 0x0F].useStatus = ENABLE; + + USBD_EP_OpenCallback(usbInfo, usbDevMSC->epInAddr, EP_TYPE_BULK, USBD_MSC_FS_MP_SIZE); + usbInfo->devEpIn[usbDevMSC->epInAddr & 0x0F].useStatus = ENABLE; + break; + + default: + USBD_EP_OpenCallback(usbInfo, usbDevMSC->epOutAddr, EP_TYPE_BULK, USBD_MSC_HS_MP_SIZE); + usbInfo->devEpOut[usbDevMSC->epOutAddr & 0x0F].useStatus = ENABLE; + + USBD_EP_OpenCallback(usbInfo, usbDevMSC->epInAddr, EP_TYPE_BULK, USBD_MSC_HS_MP_SIZE); + usbInfo->devEpIn[usbDevMSC->epInAddr & 0x0F].useStatus = ENABLE; + break; + } + + USBD_MSC_BOT_Init(usbInfo); + + return usbStatus; +} + +/*! + * @brief USB device MSC reset handler + * + * @param usbInfo: usb device information + * + * @param cfgIndex: configuration index + * + * @retval USB device operation status + */ +static USBD_STA_T USBD_MSC_ClassDeInitHandler(USBD_INFO_T* usbInfo, uint8_t cfgIndex) +{ + USBD_STA_T usbStatus = USBD_OK; + USBD_MSC_INFO_T* usbDevMSC = (USBD_MSC_INFO_T*)usbInfo->devClass[usbInfo->classID]->classData; + + UNUSED(cfgIndex); + + /* Close MSC EP */ + USBD_EP_CloseCallback(usbInfo, usbDevMSC->epOutAddr); + usbInfo->devEpOut[usbDevMSC->epOutAddr & 0x0F].useStatus = DISABLE; + + USBD_EP_CloseCallback(usbInfo, usbDevMSC->epInAddr); + usbInfo->devEpIn[usbDevMSC->epInAddr & 0x0F].useStatus = DISABLE; + + if (usbInfo->devClassUserData[usbInfo->classID] != NULL) + { + USBD_MSC_BOT_DeInit(usbInfo); + } + + if (usbInfo->devClass[usbInfo->classID]->classData != NULL) + { + free(usbInfo->devClass[usbInfo->classID]->classData); + usbInfo->devClass[usbInfo->classID]->classData = 0; + } + + return usbStatus; +} + +/*! + * @brief USB device MSC SOF handler + * + * @param usbInfo: usb device information + * + * @retval USB device operation status + */ +static USBD_STA_T USBD_MSC_SOFHandler(USBD_INFO_T* usbInfo) +{ + USBD_STA_T usbStatus = USBD_BUSY; + + UNUSED(usbInfo); + + return usbStatus; +} + +/*! + * @brief USB device MSC SETUP handler + * + * @param usbInfo: usb device information + * + * @param req: setup request + * + * @retval USB device operation status + */ +static USBD_STA_T USBD_MSC_SetupHandler(USBD_INFO_T* usbInfo, USBD_REQ_SETUP_T* req) +{ + USBD_STA_T usbStatus = USBD_OK; + + USBD_MSC_INFO_T* usbDevMSC = (USBD_MSC_INFO_T*)usbInfo->devClass[usbInfo->classID]->classData; + + uint8_t request; + uint8_t reqType; + uint16_t wIndex = req->DATA_FIELD.wIndex[0] | req->DATA_FIELD.wIndex[1] << 8; + uint16_t wValue = req->DATA_FIELD.wValue[0] | req->DATA_FIELD.wValue[1] << 8; + uint16_t wLength = req->DATA_FIELD.wLength[0] | req->DATA_FIELD.wLength[1] << 8; + uint16_t status = 0x0000; + + if (usbDevMSC == NULL) + { + return USBD_FAIL; + } + + request = req->DATA_FIELD.bRequest; + reqType = req->DATA_FIELD.bmRequest.REQ_TYPE_B.type; + + switch (reqType) + { + case USBD_REQ_TYPE_STANDARD: + switch (request) + { + case USBD_STD_GET_STATUS: + if (usbInfo->devState == USBD_DEV_CONFIGURE) + { + USBD_CtrlSendData(usbInfo, (uint8_t*)&status, 2); + } + else + { + USBD_REQ_CtrlError(usbInfo, req); + usbStatus = USBD_FAIL; + } + break; + + case USBD_STD_GET_INTERFACE: + if (usbInfo->devState == USBD_DEV_CONFIGURE) + { + USBD_CtrlSendData(usbInfo, (uint8_t*)&usbDevMSC->itf, 1); + } + else + { + USBD_REQ_CtrlError(usbInfo, req); + usbStatus = USBD_FAIL; + } + break; + + case USBD_STD_SET_INTERFACE: + if (usbInfo->devState == USBD_DEV_CONFIGURE) + { + usbDevMSC->itf = wValue; + } + else + { + USBD_REQ_CtrlError(usbInfo, req); + usbStatus = USBD_FAIL; + } + break; + + case USBD_STD_CLEAR_FEATURE: + if (usbInfo->devState == USBD_DEV_CONFIGURE) + { + if (wValue == USBD_FEATURE_SELECTOR_ENDPOINT_HALT) + { + USBD_EP_FlushCallback(usbInfo, wIndex); + + /* BOT error */ + USBD_MSC_BOT_ClearFeature(usbInfo, wIndex); + } + } + break; + + default: + USBD_REQ_CtrlError(usbInfo, req); + usbStatus = USBD_FAIL; + break; + } + break; + + case USBD_REQ_TYPE_CLASS: + switch (request) + { + case USBD_CLASS_GET_MAX_LUN: + if ((req->DATA_FIELD.bmRequest.REQ_TYPE_B.dir == EP_DIR_IN) && \ + (wValue == 0) && (wLength == 1)) + { + usbDevMSC->maxLun = \ + ((USBD_MSC_MEMORY_T*)usbInfo->devClassUserData[usbInfo->classID])->MemoryReadMaxLun(); + + USBD_CtrlSendData(usbInfo, (uint8_t*)&usbDevMSC->maxLun, 1); + } + else + { + USBD_REQ_CtrlError(usbInfo, req); + usbStatus = USBD_FAIL; + } + break; + + case USBD_CLASS_BOT_RESET: + if ((req->DATA_FIELD.bmRequest.REQ_TYPE_B.dir == EP_DIR_OUT) && \ + (wValue == 0) && (wLength == 0)) + { + USBD_MSC_BOT_Reset(usbInfo); + } + else + { + USBD_REQ_CtrlError(usbInfo, req); + usbStatus = USBD_FAIL; + } + break; + + default: + USBD_REQ_CtrlError(usbInfo, req); + usbStatus = USBD_FAIL; + break; + } + break; + + case USBD_REQ_TYPE_VENDOR: + USBD_REQ_CtrlError(usbInfo, req); + usbStatus = USBD_FAIL; + break; + + default: + usbStatus = USBD_FAIL; + USBD_REQ_CtrlError(usbInfo, req); + break; + } + + return usbStatus; +} + +/*! + * @brief USB device MSC IN data handler + * + * @param usbInfo: usb device information + * + * @param epNum: endpoint number + * + * @retval USB device operation status + */ +static USBD_STA_T USBD_MSC_DataInHandler(USBD_INFO_T* usbInfo, uint8_t epNum) +{ + USBD_STA_T usbStatus = USBD_OK; + uint8_t reqStatus = USBD_BUSY; + USBD_MSC_INFO_T* usbDevMSC = (USBD_MSC_INFO_T*)usbInfo->devClass[usbInfo->classID]->classData; + + UNUSED(epNum); + + if (usbDevMSC == NULL) + { + return USBD_FAIL; + } + + switch (usbDevMSC->usbDevBOT.state) + { + case USBD_BOT_DATAIN: + reqStatus = USBD_SCSI_Handle(usbInfo, usbDevMSC->usbDevBOT.cmdPack.CBW.DATA_FIELD.bLUN, \ + &usbDevMSC->usbDevBOT.cmdPack.CBW.DATA_FIELD.CB[0]); + + if (reqStatus == USBD_FAIL) + { + USBD_MSC_BOT_SendCSW(usbInfo, USBD_BOT_CSW_FAIL); + } + break; + + case USBD_BOT_DATAIN_LAST: + case USBD_BOT_DATA_SEND: + USBD_MSC_BOT_SendCSW(usbInfo, USBD_BOT_CSW_OK); + break; + + default: + break; + } + + return usbStatus; +} + +/*! + * @brief USB device MSC OUT data handler + * + * @param usbInfo: usb device information + * + * @param epNum: endpoint number + * + * @retval USB device operation status + */ +static USBD_STA_T USBD_MSC_DataOutHandler(USBD_INFO_T* usbInfo, uint8_t epNum) +{ + USBD_STA_T usbStatus = USBD_OK; + uint8_t reqStatus = USBD_BUSY; + USBD_MSC_INFO_T* usbDevMSC = (USBD_MSC_INFO_T*)usbInfo->devClass[usbInfo->classID]->classData; + + UNUSED(epNum); + + if (usbDevMSC == NULL) + { + return USBD_FAIL; + } + + /* Handler BOT state */ + switch (usbDevMSC->usbDevBOT.state) + { + case USBD_BOT_IDLE: + USBD_MSC_BOT_CBW_Decode(usbInfo); + break; + + case USBD_BOT_DATAOUT: + reqStatus = USBD_SCSI_Handle(usbInfo, usbDevMSC->usbDevBOT.cmdPack.CBW.DATA_FIELD.bLUN, \ + &usbDevMSC->usbDevBOT.cmdPack.CBW.DATA_FIELD.CB[0]); + if (reqStatus == USBD_FAIL) + { + USBD_MSC_BOT_SendCSW(usbInfo, USBD_BOT_CSW_FAIL); + } + break; + + default: + break; + } + + return usbStatus; +} + +/*! + * @brief USB device MSC register memory handler + * + * @param usbInfo: usb device information + * + * @param memory: memory handler + * + * @retval USB device operation status + */ +USBD_STA_T USBD_MSC_RegisterMemory(USBD_INFO_T* usbInfo, USBD_MSC_MEMORY_T* memory) +{ + USBD_STA_T usbStatus = USBD_FAIL; + + if (memory != NULL) + { + usbInfo->devClassUserData[usbInfo->classID] = memory; + usbStatus = USBD_OK; + } + + return usbStatus; +} + +/**@} end of group USBD_MSC_Functions */ +/**@} end of group USBD_MSC_Class */ +/**@} end of group APM32_USB_Library */ diff --git a/lib/main/APM32F4/Middlewares/APM32_USB_Library/Device/Class/MSC/Src/usbd_msc_bot.c b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Device/Class/MSC/Src/usbd_msc_bot.c new file mode 100644 index 0000000000..30bc402866 --- /dev/null +++ b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Device/Class/MSC/Src/usbd_msc_bot.c @@ -0,0 +1,367 @@ +/*! + * @file usbd_msc_bot.c + * + * @brief usb device msc bot handler + * + * @version V1.0.0 + * + * @date 2023-01-16 + * + * @attention + * + * Copyright (C) 2023 Geehy Semiconductor + * + * You may not use this file except in compliance with the + * GEEHY COPYRIGHT NOTICE (GEEHY SOFTWARE PACKAGE LICENSE). + * + * The program is only for reference, which is distributed in the hope + * that it will be useful and instructional for customers to develop + * their software. Unless required by applicable law or agreed to in + * writing, the program is distributed on an "AS IS" BASIS, WITHOUT + * ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied. + * See the GEEHY SOFTWARE PACKAGE LICENSE for the governing permissions + * and limitations under the License. + */ + +/* Includes */ +#include "usbd_msc_bot.h" +#include "usbd_msc.h" +#include "usbd_dataXfer.h" + +/** @addtogroup APM32_USB_Library + @{ + */ + +/** @addtogroup USBD_MSC_Class + @{ + */ + +/** @defgroup USBD_MSC_Functions Functions + @{ + */ + +/*! + * @brief Init BOT of USB device MSC + * + * @param usbInfo : usb handler information + * + * @retval USB device operation status + */ +USBD_STA_T USBD_MSC_BOT_Init(USBD_INFO_T* usbInfo) +{ + USBD_STA_T usbStatus = USBD_OK; + + USBD_MSC_INFO_T* usbDevMSC = (USBD_MSC_INFO_T*)usbInfo->devClass[usbInfo->classID]->classData; + + if (usbDevMSC == NULL) + { + return USBD_FAIL; + } + + usbDevMSC->usbDevSCSI.senseHead = 0; + usbDevMSC->usbDevSCSI.senseEnd = 0; + usbDevMSC->usbDevSCSI.mediumState = USBD_SCSI_MEDIUM_UNLOCK; + + /* Init USB device memory managment */ + ((USBD_MSC_MEMORY_T*)usbInfo->devClassUserData[usbInfo->classID])->MemoryInit(0); + + usbDevMSC->usbDevBOT.state = USBD_BOT_IDLE; + usbDevMSC->usbDevBOT.status = USBD_BOT_NORMAL; + + USBD_EP_FlushCallback(usbInfo, usbDevMSC->epInAddr); + USBD_EP_FlushCallback(usbInfo, usbDevMSC->epOutAddr); + + USBD_EP_ReceiveCallback(usbInfo, usbDevMSC->epOutAddr, \ + (uint8_t*)&usbDevMSC->usbDevBOT.cmdPack.CBW, + USBD_MSC_BOT_CBW_LEN); + return usbStatus; +} + +/*! + * @brief De-init BOT of USB device MSC + * + * @param usbInfo : usb handler information + * + * @retval USB device operation status + */ +USBD_STA_T USBD_MSC_BOT_DeInit(USBD_INFO_T* usbInfo) +{ + USBD_STA_T usbStatus = USBD_OK; + + USBD_MSC_INFO_T* usbDevMSC = (USBD_MSC_INFO_T*)usbInfo->devClass[usbInfo->classID]->classData; + + if (usbDevMSC == NULL) + { + return USBD_FAIL; + } + + usbDevMSC->usbDevBOT.state = USBD_BOT_IDLE; + + return usbStatus; +} + +/*! + * @brief Reset BOT of USB device MSC + * + * @param usbInfo : usb handler information + * + * @retval USB device operation status + */ +USBD_STA_T USBD_MSC_BOT_Reset(USBD_INFO_T* usbInfo) +{ + USBD_STA_T usbStatus = USBD_OK; + USBD_MSC_INFO_T* usbDevMSC = (USBD_MSC_INFO_T*)usbInfo->devClass[usbInfo->classID]->classData; + + if (usbDevMSC == NULL) + { + return USBD_FAIL; + } + + usbDevMSC->usbDevBOT.state = USBD_BOT_IDLE; + usbDevMSC->usbDevBOT.status = USBD_BOT_RECOVERY; + + USBD_EP_ClearStallCallback(usbInfo, usbDevMSC->epInAddr); + USBD_EP_ClearStallCallback(usbInfo, usbDevMSC->epOutAddr); + + USBD_EP_ReceiveCallback(usbInfo, usbDevMSC->epOutAddr, \ + (uint8_t*)&usbDevMSC->usbDevBOT.cmdPack.CBW, \ + USBD_MSC_BOT_CBW_LEN); + + return usbStatus; +} + +/*! + * @brief Abort BOT of USB device MSC + * + * @param usbInfo : usb handler information + * + * @retval USB device operation status + */ +USBD_STA_T USBD_MSC_BOT_Abort(USBD_INFO_T* usbInfo) +{ + USBD_STA_T usbStatus = USBD_OK; + USBD_MSC_INFO_T* usbDevMSC = (USBD_MSC_INFO_T*)usbInfo->devClass[usbInfo->classID]->classData; + + if (usbDevMSC == NULL) + { + return USBD_FAIL; + } + + if ((usbDevMSC->usbDevBOT.cmdPack.CBW.DATA_FIELD.bmFlags.CBW_Flag == 0) && \ + (usbDevMSC->usbDevBOT.cmdPack.CBW.DATA_FIELD.dDataXferLen != 0) && \ + (usbDevMSC->usbDevBOT.status == USBD_BOT_NORMAL)) + { + USBD_EP_StallCallback(usbInfo, usbDevMSC->epOutAddr); + } + + USBD_EP_StallCallback(usbInfo, usbDevMSC->epInAddr); + + if (usbDevMSC->usbDevBOT.status == USBD_BOT_ERR) + { + USBD_EP_StallCallback(usbInfo, usbDevMSC->epInAddr); + USBD_EP_StallCallback(usbInfo, usbDevMSC->epOutAddr); + } + + return usbStatus; +} + +/*! + * @brief Send CSW packet + * + * @param usbInfo : usb handler information + * + * @param status : CSW status + * + * @retval USB device operation status + */ +USBD_STA_T USBD_MSC_BOT_SendCSW(USBD_INFO_T* usbInfo, USBD_BOT_CSW_STA_T status) +{ + USBD_STA_T usbStatus = USBD_OK; + USBD_MSC_INFO_T* usbDevMSC = (USBD_MSC_INFO_T*)usbInfo->devClass[usbInfo->classID]->classData; + + if (usbDevMSC == NULL) + { + return USBD_FAIL; + } + + usbDevMSC->usbDevBOT.cmdPack.CSW.DATA_FIELD.dSignature = USBD_MSC_BOT_CSW_SIGNATURE; + usbDevMSC->usbDevBOT.cmdPack.CSW.DATA_FIELD.bStatus = status; + + usbDevMSC->usbDevBOT.state = USBD_BOT_IDLE; + + USBD_EP_TransferCallback(usbInfo, usbDevMSC->epInAddr, \ + (uint8_t*)&usbDevMSC->usbDevBOT.cmdPack.CSW, \ + USBD_MSC_BOT_CSW_LEN); + + USBD_EP_ReceiveCallback(usbInfo, usbDevMSC->epOutAddr, \ + (uint8_t*)&usbDevMSC->usbDevBOT.cmdPack.CBW, \ + USBD_MSC_BOT_CBW_LEN); + + return usbStatus; +} + +/*! + * @brief Send BOT data + * + * @param usbInfo : usb handler information + * + * @param buffer : data buffer + * + * @param length : data length + * + * @retval USB device operation status + */ +USBD_STA_T USBD_MSC_BOT_SendData(USBD_INFO_T* usbInfo, uint8_t* buffer, uint32_t length) +{ + USBD_STA_T usbStatus = USBD_OK; + + USBD_MSC_INFO_T* usbDevMSC = (USBD_MSC_INFO_T*)usbInfo->devClass[usbInfo->classID]->classData; + + uint32_t lengthTemp; + + if (usbDevMSC == NULL) + { + return USBD_FAIL; + } + + lengthTemp = length; + + if (usbDevMSC->usbDevBOT.cmdPack.CBW.DATA_FIELD.dDataXferLen < length) + { + lengthTemp = usbDevMSC->usbDevBOT.cmdPack.CBW.DATA_FIELD.dDataXferLen; + } + + usbDevMSC->usbDevBOT.cmdPack.CSW.DATA_FIELD.dDataResidue -= length; + usbDevMSC->usbDevBOT.cmdPack.CSW.DATA_FIELD.bStatus = USBD_BOT_CSW_OK; + usbDevMSC->usbDevBOT.state = USBD_BOT_DATA_SEND; + + USBD_EP_TransferCallback(usbInfo, usbDevMSC->epInAddr, buffer, lengthTemp); + + return usbStatus; +} + +/*! + * @brief Decode CBW packet + * + * @param usbInfo : usb handler information + * + * @retval USB device operation status + */ +USBD_STA_T USBD_MSC_BOT_CBW_Decode(USBD_INFO_T* usbInfo) +{ + USBD_STA_T usbStatus = USBD_OK; + uint8_t reqStatus = USBD_BUSY; + USBD_MSC_INFO_T* usbDevMSC = (USBD_MSC_INFO_T*)usbInfo->devClass[usbInfo->classID]->classData; + uint32_t lastRevDataLen; + + if (usbDevMSC == NULL) + { + return USBD_FAIL; + } + + usbDevMSC->usbDevBOT.cmdPack.CSW.DATA_FIELD.dTag = \ + usbDevMSC->usbDevBOT.cmdPack.CBW.DATA_FIELD.dTag; + + usbDevMSC->usbDevBOT.cmdPack.CSW.DATA_FIELD.dDataResidue = \ + usbDevMSC->usbDevBOT.cmdPack.CBW.DATA_FIELD.dDataXferLen; + + lastRevDataLen = USBD_EP_ReadRxDataLenCallback(usbInfo, usbDevMSC->epOutAddr); + + if ((lastRevDataLen != USBD_MSC_BOT_CBW_LEN) || \ + (usbDevMSC->usbDevBOT.cmdPack.CBW.DATA_FIELD.dSignature != USBD_MSC_BOT_CBW_SIGNATURE) || \ + (usbDevMSC->usbDevBOT.cmdPack.CBW.DATA_FIELD.bLUN > 1) || \ + (usbDevMSC->usbDevBOT.cmdPack.CBW.DATA_FIELD.bCBLen < 1) || \ + (usbDevMSC->usbDevBOT.cmdPack.CBW.DATA_FIELD.bCBLen > 16)) + { + USBD_SCSI_CodeSense(usbInfo, usbDevMSC->usbDevBOT.cmdPack.CBW.DATA_FIELD.bLUN, \ + USBD_SCSI_SENSE_KEY_ILLEGAL_REQUEST, USBD_SCSI_ASC_INVALID_CDB, 0); + + usbDevMSC->usbDevBOT.status = USBD_BOT_ERR; + USBD_MSC_BOT_Abort(usbInfo); + } + else + { + reqStatus = USBD_SCSI_Handle(usbInfo, usbDevMSC->usbDevBOT.cmdPack.CBW.DATA_FIELD.bLUN, \ + &usbDevMSC->usbDevBOT.cmdPack.CBW.DATA_FIELD.CB[0]); + if (reqStatus == USBD_FAIL) + { + if (usbDevMSC->usbDevBOT.state == USBD_BOT_NO_DATA) + { + USBD_MSC_BOT_SendCSW(usbInfo, USBD_BOT_CSW_FAIL); + } + else + { + USBD_MSC_BOT_Abort(usbInfo); + } + } + else if ((usbDevMSC->usbDevBOT.state != USBD_BOT_DATAIN) && \ + (usbDevMSC->usbDevBOT.state != USBD_BOT_DATAOUT) && \ + (usbDevMSC->usbDevBOT.state != USBD_BOT_DATAIN_LAST)) + { + if (usbDevMSC->usbDevBOT.dataLen == 0) + { + USBD_MSC_BOT_SendCSW(usbInfo, USBD_BOT_CSW_OK); + } + else if (usbDevMSC->usbDevBOT.dataLen > 0) + { + USBD_MSC_BOT_SendData(usbInfo, usbDevMSC->usbDevBOT.data, usbDevMSC->usbDevBOT.dataLen); + } + else + { + USBD_MSC_BOT_Abort(usbInfo); + } + } + else + { + return USBD_OK; + } + } + + return usbStatus; +} + +/*! + * @brief Clear feature BOT of USB device MSC + * + * @param usbInfo : usb handler information + * + * @param epNum : endpoint number + * + * @retval USB device operation status + */ +USBD_STA_T USBD_MSC_BOT_ClearFeature(USBD_INFO_T* usbInfo, uint8_t epNum) +{ + USBD_STA_T usbStatus = USBD_OK; + USBD_MSC_INFO_T* usbDevMSC = (USBD_MSC_INFO_T*)usbInfo->devClass[usbInfo->classID]->classData; + + if (usbDevMSC == NULL) + { + return USBD_FAIL; + } + + switch (usbDevMSC->usbDevBOT.status) + { + /* CBW signature error */ + case USBD_BOT_ERR: + USBD_EP_StallCallback(usbInfo, usbDevMSC->epInAddr); + USBD_EP_StallCallback(usbInfo, usbDevMSC->epOutAddr); + break; + + case USBD_BOT_NORMAL: + if ((epNum & 0x80) == 0x80) + { + usbDevMSC->usbDevBOT.cmdPack.cswStatus = USBD_BOT_CSW_FAIL; + USBD_MSC_BOT_SendCSW(usbInfo, usbDevMSC->usbDevBOT.cmdPack.cswStatus); + } + break; + + default: + break; + } + + return usbStatus; +} + +/**@} end of group USBD_MSC_Functions */ +/**@} end of group USBD_MSC_Class */ +/**@} end of group APM32_USB_Library */ diff --git a/lib/main/APM32F4/Middlewares/APM32_USB_Library/Device/Class/MSC/Src/usbd_msc_scsi.c b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Device/Class/MSC/Src/usbd_msc_scsi.c new file mode 100644 index 0000000000..c6fa523d0e --- /dev/null +++ b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Device/Class/MSC/Src/usbd_msc_scsi.c @@ -0,0 +1,1455 @@ +/*! + * @file usbd_msc_scsi.c + * + * @brief usb device msc scsi handler + * + * @version V1.0.0 + * + * @date 2023-01-16 + * + * @attention + * + * Copyright (C) 2023 Geehy Semiconductor + * + * You may not use this file except in compliance with the + * GEEHY COPYRIGHT NOTICE (GEEHY SOFTWARE PACKAGE LICENSE). + * + * The program is only for reference, which is distributed in the hope + * that it will be useful and instructional for customers to develop + * their software. Unless required by applicable law or agreed to in + * writing, the program is distributed on an "AS IS" BASIS, WITHOUT + * ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied. + * See the GEEHY SOFTWARE PACKAGE LICENSE for the governing permissions + * and limitations under the License. + */ + +/* Includes */ +#include "usbd_msc_scsi.h" +#include "usbd_msc.h" +#include "usbd_msc_bot.h" +#include "usbd_dataXfer.h" +//#include +#include +#include + +/** @addtogroup APM32_USB_Library + @{ + */ + +/** @addtogroup USBD_MSC_Class + @{ + */ + +/** @defgroup USBD_MSC_Variables Variables + @{ + */ + +/* USB mass storage page 00 inquiry data */ +uint8_t page00InquiryData[USBD_LEN_INQUIRY_PAGE00] = +{ + 0x00, + 0x00, + 0x00, + (USBD_LEN_INQUIRY_PAGE00 - 4U), + 0x00, + 0x80 +}; + +/* USB mass storage page 80 inquiry data */ +uint8_t page80InquiryData[USBD_LEN_INQUIRY_PAGE80] = +{ + 0x00, + 0x80, + 0x00, + USBD_LEN_INQUIRY_PAGE80, + 0x20, + 0x20, + 0x20, + 0x20 +}; + +/* USB mass storage sense 6 data */ +uint8_t modeSense6data[USBD_LEN_STD_MODE_SENSE6] = +{ + 0x22, + 0x00, + 0x00, + 0x00, + 0x08, + 0x12, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00 +}; + +/* USB Mass storage sense 10 Data */ +uint8_t modeSense10data[USBD_LEN_STD_MODE_SENSE10] = +{ + 0x00, + 0x26, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x08, + 0x12, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00 +}; + +/**@} end of group USBD_MSC_Variables*/ + +/** @defgroup USBD_MSC_Functions Functions + @{ + */ + +/*! + * @brief Put the sense code to array + * + * @param usbInfo : usb handler information + * + * @param lun : LUN + * + * @param key: sense Key + * + * @param asc: Additional Sense Code + * + * @param ascq: Additional Sense Code Qualifier + * + * @retval USB device operation status + */ +USBD_STA_T USBD_SCSI_CodeSense(USBD_INFO_T* usbInfo, uint8_t lun, uint8_t key, uint8_t asc, uint8_t ascq) +{ + USBD_STA_T usbStatus = USBD_OK; + USBD_MSC_INFO_T* usbDevMSC = (USBD_MSC_INFO_T*)usbInfo->devClass[usbInfo->classID]->classData; + + UNUSED(lun); + + if (usbDevMSC == NULL) + { + return USBD_FAIL; + } + + usbDevMSC->usbDevSCSI.sense[usbDevMSC->usbDevSCSI.senseEnd].Key = key; + usbDevMSC->usbDevSCSI.sense[usbDevMSC->usbDevSCSI.senseEnd].ASC = asc; + usbDevMSC->usbDevSCSI.sense[usbDevMSC->usbDevSCSI.senseEnd].ASCQ = ascq; + usbDevMSC->usbDevSCSI.senseEnd++; + + if (usbDevMSC->usbDevSCSI.senseEnd == USBD_SCSI_SENSE_LIST_NUMBER) + { + usbDevMSC->usbDevSCSI.senseEnd = 0; + } + + return usbStatus; +} + +/*! + * @brief USB device SCSI configure BOT data + * + * @param usbInfo : usb handler information + * + * @param buffer : data buffer + * + * @param length: data length + * + * @retval USB device operation status + */ +USBD_STA_T USBD_SCSI_ConfigBotData(USBD_INFO_T* usbInfo, uint8_t* buffer, uint16_t length) +{ + USBD_STA_T usbStatus = USBD_BUSY; + + USBD_MSC_INFO_T* usbDevMSC = (USBD_MSC_INFO_T*)usbInfo->devClass[usbInfo->classID]->classData; + uint16_t i; + + if (usbDevMSC == NULL) + { + return USBD_OK; + } + + usbDevMSC->usbDevBOT.dataLen = length; + + for (i = 0; i < length; i++) + { + usbDevMSC->usbDevBOT.data[i] = buffer[i]; + } + + return usbStatus; +} + +/*! + * @brief USB device SCSI read capacity 16 command handler + * + * @param usbInfo : usb handler information + * + * @param lun : LUN + * + * @param command: SCSI command + * + * @retval USB device operation status + */ +USBD_STA_T USBD_SCSI_ReadCapacity16(USBD_INFO_T* usbInfo, uint8_t lun, uint8_t* command) +{ + USBD_STA_T usbStatus = USBD_OK; + uint8_t reqStatus = USBD_BUSY; + USBD_MSC_INFO_T* usbDevMSC = (USBD_MSC_INFO_T*)usbInfo->devClass[usbInfo->classID]->classData; + + if (usbDevMSC == NULL) + { + return USBD_FAIL; + } + + reqStatus = ((USBD_MSC_MEMORY_T*)usbInfo->devClassUserData[usbInfo->classID])->MemoryReadCapacity(lun, \ + &usbDevMSC->usbDevSCSI.blockNum, &usbDevMSC->usbDevSCSI.blockSize); + + if ((reqStatus != USBD_OK) || (usbDevMSC->usbDevSCSI.mediumState == USBD_SCSI_MEDIUM_EJECT)) + { + USBD_SCSI_CodeSense(usbInfo, lun, \ + USBD_SCSI_SENSE_KEY_NOT_READY, \ + USBD_SCSI_ASC_MEDIUM_NOT_PRESENT, \ + 0); + + return USBD_FAIL; + } + + usbDevMSC->usbDevBOT.dataLen = (uint32_t)((command[10] << 24) | \ + (command[11] << 16) | \ + (command[12] << 8) | \ + (command[13])); + + memset(usbDevMSC->usbDevBOT.data, 0, usbDevMSC->usbDevBOT.dataLen); + + usbDevMSC->usbDevBOT.data[4] = (uint8_t)((usbDevMSC->usbDevSCSI.blockNum - 1) >> 24); + usbDevMSC->usbDevBOT.data[5] = (uint8_t)((usbDevMSC->usbDevSCSI.blockNum - 1) >> 16); + usbDevMSC->usbDevBOT.data[6] = (uint8_t)((usbDevMSC->usbDevSCSI.blockNum - 1) >> 8); + usbDevMSC->usbDevBOT.data[7] = (uint8_t)((usbDevMSC->usbDevSCSI.blockNum - 1)); + + usbDevMSC->usbDevBOT.data[8] = (uint8_t)((usbDevMSC->usbDevSCSI.blockSize) >> 24); + usbDevMSC->usbDevBOT.data[9] = (uint8_t)(usbDevMSC->usbDevSCSI.blockSize >> 16); + usbDevMSC->usbDevBOT.data[10] = (uint8_t)(usbDevMSC->usbDevSCSI.blockSize >> 8); + usbDevMSC->usbDevBOT.data[11] = (uint8_t)(usbDevMSC->usbDevSCSI.blockSize); + + return usbStatus; +} + +/*! + * @brief USB device SCSI read capacity command handler + * + * @param usbInfo : usb handler information + * + * @param lun : LUN + * + * @param command: SCSI command + * + * @retval USB device operation status + */ +USBD_STA_T USBD_SCSI_ReadCapacity(USBD_INFO_T* usbInfo, uint8_t lun, uint8_t* command) +{ + USBD_STA_T usbStatus = USBD_OK; + uint8_t reqStatus = USBD_BUSY; + USBD_MSC_INFO_T* usbDevMSC = (USBD_MSC_INFO_T*)usbInfo->devClass[usbInfo->classID]->classData; + + UNUSED(command); + + if (usbDevMSC == NULL) + { + return USBD_FAIL; + } + + reqStatus = ((USBD_MSC_MEMORY_T*)usbInfo->devClassUserData[usbInfo->classID])->MemoryReadCapacity(lun, \ + &usbDevMSC->usbDevSCSI.blockNum, &usbDevMSC->usbDevSCSI.blockSize); + + if ((reqStatus != USBD_OK) || (usbDevMSC->usbDevSCSI.mediumState == USBD_SCSI_MEDIUM_EJECT)) + { + USBD_SCSI_CodeSense(usbInfo, lun, \ + USBD_SCSI_SENSE_KEY_NOT_READY, \ + USBD_SCSI_ASC_MEDIUM_NOT_PRESENT, \ + 0); + + return USBD_FAIL; + } + + memset(usbDevMSC->usbDevBOT.data, 0, 8); + + usbDevMSC->usbDevBOT.data[0] = (uint8_t)((usbDevMSC->usbDevSCSI.blockNum - 1) >> 24); + usbDevMSC->usbDevBOT.data[1] = (uint8_t)((usbDevMSC->usbDevSCSI.blockNum - 1) >> 16); + usbDevMSC->usbDevBOT.data[2] = (uint8_t)((usbDevMSC->usbDevSCSI.blockNum - 1) >> 8); + usbDevMSC->usbDevBOT.data[3] = (uint8_t)((usbDevMSC->usbDevSCSI.blockNum - 1)); + + usbDevMSC->usbDevBOT.data[4] = (uint8_t)((usbDevMSC->usbDevSCSI.blockSize) >> 24); + usbDevMSC->usbDevBOT.data[5] = (uint8_t)(usbDevMSC->usbDevSCSI.blockSize >> 16); + usbDevMSC->usbDevBOT.data[6] = (uint8_t)(usbDevMSC->usbDevSCSI.blockSize >> 8); + usbDevMSC->usbDevBOT.data[7] = (uint8_t)(usbDevMSC->usbDevSCSI.blockSize); + + usbDevMSC->usbDevBOT.dataLen = 8; + + return usbStatus; +} + +/*! + * @brief USB device SCSI read format capacity command handler + * + * @param usbInfo : usb handler information + * + * @param lun : LUN + * + * @param command: SCSI command + * + * @retval USB device operation status + */ +USBD_STA_T USBD_SCSI_ReadFormatCapacity(USBD_INFO_T* usbInfo, uint8_t lun, uint8_t* command) +{ + USBD_STA_T usbStatus = USBD_OK; + uint8_t reqStatus = USBD_BUSY; + USBD_MSC_INFO_T* usbDevMSC = (USBD_MSC_INFO_T*)usbInfo->devClass[usbInfo->classID]->classData; + uint16_t blockSize; + uint32_t blockNum; + + UNUSED(command); + + if (usbDevMSC == NULL) + { + return USBD_FAIL; + } + + reqStatus = ((USBD_MSC_MEMORY_T*)usbInfo->devClassUserData[usbInfo->classID])->MemoryReadCapacity(lun, &blockNum, &blockSize); + + if ((reqStatus != USBD_OK) || (usbDevMSC->usbDevSCSI.mediumState == USBD_SCSI_MEDIUM_EJECT)) + { + USBD_SCSI_CodeSense(usbInfo, lun, \ + USBD_SCSI_SENSE_KEY_NOT_READY, \ + USBD_SCSI_ASC_MEDIUM_NOT_PRESENT, \ + 0); + + return USBD_FAIL; + } + + memset(usbDevMSC->usbDevBOT.data, 0, 12); + + blockNum -= 1; + + usbDevMSC->usbDevBOT.data[3] = 0x08; + usbDevMSC->usbDevBOT.data[4] = (uint8_t)(blockNum >> 24); + usbDevMSC->usbDevBOT.data[5] = (uint8_t)(blockNum >> 16); + usbDevMSC->usbDevBOT.data[6] = (uint8_t)(blockNum >> 8); + usbDevMSC->usbDevBOT.data[7] = (uint8_t)(blockNum); + + usbDevMSC->usbDevBOT.data[8] = 0x02; + usbDevMSC->usbDevBOT.data[9] = (uint8_t)(blockSize >> 16); + usbDevMSC->usbDevBOT.data[10] = (uint8_t)(blockSize >> 8); + usbDevMSC->usbDevBOT.data[11] = (uint8_t)(blockSize); + + usbDevMSC->usbDevBOT.dataLen = 12; + + return usbStatus; +} + +/*! + * @brief USB device SCSI inquiry command handler + * + * @param usbInfo : usb handler information + * + * @param lun : LUN + * + * @param command: SCSI command + * + * @retval USB device operation status + */ +USBD_STA_T USBD_SCSI_Inquiry(USBD_INFO_T* usbInfo, uint8_t lun, uint8_t* command) +{ + USBD_STA_T usbStatus = USBD_OK; + USBD_MSC_INFO_T* usbDevMSC = (USBD_MSC_INFO_T*)usbInfo->devClass[usbInfo->classID]->classData; + uint8_t epvd = command[1] & 0x01; + uint8_t addLen = command[4]; + uint8_t* buffer; + uint16_t bufferLen; + + if (usbDevMSC == NULL) + { + return USBD_FAIL; + } + + if (usbDevMSC->usbDevBOT.cmdPack.CBW.DATA_FIELD.dDataXferLen == 0) + { + USBD_SCSI_CodeSense(usbInfo, usbDevMSC->usbDevBOT.cmdPack.CBW.DATA_FIELD.bLUN, \ + USBD_SCSI_SENSE_KEY_ILLEGAL_REQUEST, \ + USBD_SCSI_ASC_INVALID_CDB, 0); + return USBD_FAIL; + } + + /* EPVD is set */ + if (epvd != 0) + { + if (command[2] == 0) + { + USBD_SCSI_ConfigBotData(usbInfo, page00InquiryData, USBD_LEN_INQUIRY_PAGE00); + } + else if (command[2] == 0x80) + { + USBD_SCSI_ConfigBotData(usbInfo, page80InquiryData, USBD_LEN_INQUIRY_PAGE80); + } + else + { + USBD_SCSI_CodeSense(usbInfo, usbDevMSC->usbDevBOT.cmdPack.CBW.DATA_FIELD.bLUN, \ + USBD_SCSI_SENSE_KEY_ILLEGAL_REQUEST, \ + USBD_SCSI_ASC_INVALID_FIELED_IN_COMMAND, 0); + return USBD_FAIL; + } + } + else + { + buffer = (uint8_t*) & ((USBD_MSC_MEMORY_T*)usbInfo->devClassUserData[usbInfo->classID])->inquiryData[lun * USBD_LEN_STD_INQUIRY]; + bufferLen = buffer[4] + 5; + + if (addLen <= bufferLen) + { + bufferLen = addLen; + } + + USBD_SCSI_ConfigBotData(usbInfo, buffer, bufferLen); + } + + return usbStatus; +} + +/*! + * @brief USB device SCSI allow medium removable command handler + * + * @param usbInfo : usb handler information + * + * @param lun : LUN + * + * @param command: SCSI command + * + * @retval USB device operation status + */ +USBD_STA_T USBD_SCSI_AllowMediumRemoval(USBD_INFO_T* usbInfo, uint8_t lun, uint8_t* command) +{ + USBD_STA_T usbStatus = USBD_OK; + USBD_MSC_INFO_T* usbDevMSC = (USBD_MSC_INFO_T*)usbInfo->devClass[usbInfo->classID]->classData; + + UNUSED(lun); + + if (usbDevMSC == NULL) + { + return USBD_FAIL; + } + + if (command[4]) + { + usbDevMSC->usbDevSCSI.mediumState = USBD_SCSI_MEDIUM_LOCK; + } + else + { + usbDevMSC->usbDevSCSI.mediumState = USBD_SCSI_MEDIUM_UNLOCK; + } + + usbDevMSC->usbDevBOT.dataLen = 0; + + return usbStatus; +} + +/*! + * @brief USB device SCSI mode sense 6 command handler + * + * @param usbInfo : usb handler information + * + * @param lun : LUN + * + * @param command: SCSI command + * + * @retval USB device operation status + */ +USBD_STA_T USBD_SCSI_ModeSense6(USBD_INFO_T* usbInfo, uint8_t lun, uint8_t* command) +{ + USBD_STA_T usbStatus = USBD_OK; + USBD_MSC_INFO_T* usbDevMSC = (USBD_MSC_INFO_T*)usbInfo->devClass[usbInfo->classID]->classData; + uint16_t length; + + UNUSED(lun); + + if (usbDevMSC == NULL) + { + return USBD_FAIL; + } + + length = USBD_LEN_STD_MODE_SENSE6; + + if (length >= command[4]) + { + length = command[4]; + } + + USBD_SCSI_ConfigBotData(usbInfo, modeSense6data, length); + + return usbStatus; +} + +/*! + * @brief USB device SCSI mode sense 10 command handler + * + * @param usbInfo : usb handler information + * + * @param lun : LUN + * + * @param command: SCSI command + * + * @retval USB device operation status + */ +USBD_STA_T USBD_SCSI_ModeSense10(USBD_INFO_T* usbInfo, uint8_t lun, uint8_t* command) +{ + USBD_STA_T usbStatus = USBD_OK; + USBD_MSC_INFO_T* usbDevMSC = (USBD_MSC_INFO_T*)usbInfo->devClass[usbInfo->classID]->classData; + uint16_t length; + + UNUSED(lun); + + if (usbDevMSC == NULL) + { + return USBD_FAIL; + } + + length = USBD_LEN_STD_MODE_SENSE10; + + if (length >= command[8]) + { + length = command[8]; + } + + USBD_SCSI_ConfigBotData(usbInfo, modeSense10data, length); + + return usbStatus; +} + +/*! + * @brief USB device SCSI request sense command handler + * + * @param usbInfo : usb handler information + * + * @param lun : LUN + * + * @param command: SCSI command + * + * @retval USB device operation status + */ +USBD_STA_T USBD_SCSI_RequestSense(USBD_INFO_T* usbInfo, uint8_t lun, uint8_t* command) +{ + USBD_STA_T usbStatus = USBD_OK; + USBD_MSC_INFO_T* usbDevMSC = (USBD_MSC_INFO_T*)usbInfo->devClass[usbInfo->classID]->classData; + + if (usbDevMSC == NULL) + { + return USBD_FAIL; + } + + if (usbDevMSC->usbDevBOT.cmdPack.CBW.DATA_FIELD.dDataXferLen == 0) + { + USBD_SCSI_CodeSense(usbInfo, usbDevMSC->usbDevBOT.cmdPack.CBW.DATA_FIELD.bLUN, \ + USBD_SCSI_SENSE_KEY_ILLEGAL_REQUEST, \ + USBD_SCSI_ASC_INVALID_CDB, \ + 0); + + return USBD_FAIL; + } + + memset(usbDevMSC->usbDevBOT.data, 0, USBD_LEN_STD_REQ_SENSE); + + usbDevMSC->usbDevBOT.data[0] = 0x70; + usbDevMSC->usbDevBOT.data[7] = USBD_LEN_STD_REQ_SENSE - 6; + + UNUSED(lun); + + if ((usbDevMSC->usbDevSCSI.senseHead != usbDevMSC->usbDevSCSI.senseEnd)) + { + usbDevMSC->usbDevBOT.data[2] = usbDevMSC->usbDevSCSI.sense[usbDevMSC->usbDevSCSI.senseHead].Key; + usbDevMSC->usbDevBOT.data[12] = usbDevMSC->usbDevSCSI.sense[usbDevMSC->usbDevSCSI.senseHead].ASC; + usbDevMSC->usbDevBOT.data[13] = usbDevMSC->usbDevSCSI.sense[usbDevMSC->usbDevSCSI.senseHead].ASCQ; + + if (++usbDevMSC->usbDevSCSI.senseHead == USBD_SCSI_SENSE_LIST_NUMBER) + { + usbDevMSC->usbDevSCSI.senseHead = 0; + } + } + + usbDevMSC->usbDevBOT.dataLen = (command[4] <= USBD_LEN_STD_REQ_SENSE) ? \ + command[4] : USBD_LEN_STD_REQ_SENSE; + + return usbStatus; +} + +/*! + * @brief USB device SCSI start or stop unit command handler + * + * @param usbInfo : usb handler information + * + * @param lun : LUN + * + * @param command: SCSI command + * + * @retval USB device operation status + */ +USBD_STA_T USBD_SCSI_StartStopUnit(USBD_INFO_T* usbInfo, uint8_t lun, uint8_t* command) +{ + USBD_STA_T usbStatus = USBD_OK; + USBD_MSC_INFO_T* usbDevMSC = (USBD_MSC_INFO_T*)usbInfo->devClass[usbInfo->classID]->classData; + + UNUSED(lun); + + uint8_t temp = command[4] & 0x03; + + if (usbDevMSC == NULL) + { + return USBD_FAIL; + } + + if ((usbDevMSC->usbDevSCSI.mediumState == USBD_SCSI_MEDIUM_LOCK) && \ + (temp == 0x02)) + { + USBD_SCSI_CodeSense(usbInfo, usbDevMSC->usbDevBOT.cmdPack.CBW.DATA_FIELD.bLUN, \ + USBD_SCSI_SENSE_KEY_ILLEGAL_REQUEST, \ + USBD_SCSI_ASC_INVALID_FIELED_IN_COMMAND, \ + 0); + + return USBD_FAIL; + } + + switch (temp) + { + /* START=1 */ + case 0x01: + usbDevMSC->usbDevSCSI.mediumState = USBD_SCSI_MEDIUM_UNLOCK; + break; + + /* START=0 and LOEJ Load Eject=1 */ + case 0x02: + usbDevMSC->usbDevSCSI.mediumState = USBD_SCSI_MEDIUM_EJECT; + break; + + /* START=1 and LOEJ Load Eject=1 */ + case 0x03: + usbDevMSC->usbDevSCSI.mediumState = USBD_SCSI_MEDIUM_UNLOCK; + break; + + default: + break; + } + + usbDevMSC->usbDevBOT.dataLen = 0; + + return usbStatus; +} + +/*! + * @brief USB device SCSI test unit ready command handler + * + * @param usbInfo : usb handler information + * + * @param lun : LUN + * + * @param command: SCSI command + * + * @retval USB device operation status + */ +USBD_STA_T USBD_SCSI_TestUnitReady(USBD_INFO_T* usbInfo, uint8_t lun, uint8_t* command) +{ + USBD_STA_T usbStatus = USBD_OK; + uint8_t reqStatus = USBD_BUSY; + USBD_MSC_INFO_T* usbDevMSC = (USBD_MSC_INFO_T*)usbInfo->devClass[usbInfo->classID]->classData; + + UNUSED(command); + + if (usbDevMSC == NULL) + { + return USBD_FAIL; + } + + if (usbDevMSC->usbDevBOT.cmdPack.CBW.DATA_FIELD.dDataXferLen != 0) + { + USBD_SCSI_CodeSense(usbInfo, usbDevMSC->usbDevBOT.cmdPack.CBW.DATA_FIELD.bLUN, \ + USBD_SCSI_SENSE_KEY_ILLEGAL_REQUEST, \ + USBD_SCSI_ASC_INVALID_CDB, \ + 0); + + return USBD_FAIL; + } + + if (usbDevMSC->usbDevSCSI.mediumState == USBD_SCSI_MEDIUM_EJECT) + { + USBD_SCSI_CodeSense(usbInfo, usbDevMSC->usbDevBOT.cmdPack.CBW.DATA_FIELD.bLUN, \ + USBD_SCSI_SENSE_KEY_NOT_READY, \ + USBD_SCSI_ASC_MEDIUM_NOT_PRESENT, \ + 0); + + usbDevMSC->usbDevBOT.state = USBD_BOT_NO_DATA; + + return USBD_FAIL; + } + + reqStatus = ((USBD_MSC_MEMORY_T*)usbInfo->devClassUserData[usbInfo->classID])->MemoryCheckReady(lun); + + if (reqStatus != USBD_OK) + { + USBD_SCSI_CodeSense(usbInfo, usbDevMSC->usbDevBOT.cmdPack.CBW.DATA_FIELD.bLUN, \ + USBD_SCSI_SENSE_KEY_NOT_READY, \ + USBD_SCSI_ASC_MEDIUM_NOT_PRESENT, \ + 0); + + usbDevMSC->usbDevBOT.state = USBD_BOT_NO_DATA; + + return USBD_FAIL; + } + + usbDevMSC->usbDevBOT.dataLen = 0; + + return usbStatus; +} + +/*! + * @brief USB device SCSI write data handler + * + * @param usbInfo : usb handler information + * + * @param lun : LUN + * + * @retval USB device operation status + */ +USBD_STA_T USBD_SCSI_TxData(USBD_INFO_T* usbInfo, uint8_t lun) +{ + USBD_STA_T usbStatus = USBD_OK; + uint8_t reqStatus = USBD_BUSY; + USBD_MSC_INFO_T* usbDevMSC = (USBD_MSC_INFO_T*)usbInfo->devClass[usbInfo->classID]->classData; + uint32_t length; + uint32_t blockSize = usbDevMSC->usbDevSCSI.blockSize; + uint32_t blockLen = usbDevMSC->usbDevSCSI.blockLen; + uint32_t blockAddr = usbDevMSC->usbDevSCSI.blockAddr; + + if (usbDevMSC == NULL) + { + return USBD_FAIL; + } + + length = (blockLen * blockSize) < USBD_SUP_MSC_MEDIA_PACKET ? \ + (blockLen * blockSize) : USBD_SUP_MSC_MEDIA_PACKET; + + reqStatus = ((USBD_MSC_MEMORY_T*)usbInfo->devClassUserData[usbInfo->classID])->MemoryWriteData(lun, \ + usbDevMSC->usbDevBOT.data, \ + blockAddr, \ + (length / blockSize)); + + if (reqStatus != USBD_OK) + { + USBD_SCSI_CodeSense(usbInfo, usbDevMSC->usbDevBOT.cmdPack.CBW.DATA_FIELD.bLUN, \ + USBD_SCSI_SENSE_KEY_HARDWARE_ERROR, \ + USBD_SCSI_ASC_WRITE_FAULT, \ + 0); + + return USBD_FAIL; + } + + usbDevMSC->usbDevSCSI.blockAddr += (length / blockSize); + usbDevMSC->usbDevSCSI.blockLen -= (length / blockSize); + + usbDevMSC->usbDevBOT.cmdPack.CSW.DATA_FIELD.dDataResidue -= length; + + if (usbDevMSC->usbDevSCSI.blockLen) + { + length = (usbDevMSC->usbDevSCSI.blockLen * usbDevMSC->usbDevSCSI.blockSize) < USBD_SUP_MSC_MEDIA_PACKET ? \ + (usbDevMSC->usbDevSCSI.blockLen * usbDevMSC->usbDevSCSI.blockSize) : USBD_SUP_MSC_MEDIA_PACKET; + + USBD_EP_ReceiveCallback(usbInfo, usbDevMSC->epOutAddr, \ + usbDevMSC->usbDevBOT.data, \ + length); + } + else + { + USBD_MSC_BOT_SendCSW(usbInfo, USBD_BOT_CSW_OK); + } + + return usbStatus; +} + +/*! + * @brief USB device SCSI read data handler + * + * @param usbInfo : usb handler information + * + * @param lun : LUN + * + * @retval USB device operation status + */ +USBD_STA_T USBD_SCSI_RxData(USBD_INFO_T* usbInfo, uint8_t lun) +{ + USBD_STA_T usbStatus = USBD_OK; + uint8_t reqStatus = USBD_BUSY; + USBD_MSC_INFO_T* usbDevMSC = (USBD_MSC_INFO_T*)usbInfo->devClass[usbInfo->classID]->classData; + uint32_t length; + + if (usbDevMSC == NULL) + { + return USBD_FAIL; + } + + length = (usbDevMSC->usbDevSCSI.blockLen * usbDevMSC->usbDevSCSI.blockSize) < USBD_SUP_MSC_MEDIA_PACKET ? \ + (usbDevMSC->usbDevSCSI.blockLen * usbDevMSC->usbDevSCSI.blockSize) : USBD_SUP_MSC_MEDIA_PACKET; + + reqStatus = ((USBD_MSC_MEMORY_T*)usbInfo->devClassUserData[usbInfo->classID])->MemoryReadData(lun, \ + usbDevMSC->usbDevBOT.data, \ + usbDevMSC->usbDevSCSI.blockAddr, \ + (length / usbDevMSC->usbDevSCSI.blockSize)); + + if (reqStatus != USBD_OK) + { + USBD_SCSI_CodeSense(usbInfo, usbDevMSC->usbDevBOT.cmdPack.CBW.DATA_FIELD.bLUN, \ + USBD_SCSI_SENSE_KEY_HARDWARE_ERROR, \ + USBD_SCSI_ASC_UNRECOVERED_READ_ERROR, \ + 0); + + return USBD_FAIL; + } + + USBD_EP_TransferCallback(usbInfo, usbDevMSC->epInAddr, \ + usbDevMSC->usbDevBOT.data, \ + length); + + usbDevMSC->usbDevSCSI.blockAddr += (length / usbDevMSC->usbDevSCSI.blockSize); + usbDevMSC->usbDevSCSI.blockLen -= (length / usbDevMSC->usbDevSCSI.blockSize); + + usbDevMSC->usbDevBOT.cmdPack.CSW.DATA_FIELD.dDataResidue -= length; + + if (usbDevMSC->usbDevSCSI.blockLen == 0) + { + usbDevMSC->usbDevBOT.state = USBD_BOT_DATAIN_LAST; + } + + return usbStatus; +} + +/*! + * @brief USB device SCSI write 10 command handler + * + * @param usbInfo : usb handler information + * + * @param lun : LUN + * + * @param command: SCSI command + * + * @retval USB device operation status + */ +USBD_STA_T USBD_SCSI_Write10(USBD_INFO_T* usbInfo, uint8_t lun, uint8_t* command) +{ + USBD_STA_T usbStatus = USBD_OK; + uint8_t reqStatus = USBD_BUSY; + USBD_MSC_INFO_T* usbDevMSC = (USBD_MSC_INFO_T*)usbInfo->devClass[usbInfo->classID]->classData; + + uint32_t length; + + if (usbDevMSC == NULL) + { + return USBD_FAIL; + } + + switch (usbDevMSC->usbDevBOT.state) + { + case USBD_BOT_IDLE: + if (usbDevMSC->usbDevBOT.cmdPack.CBW.DATA_FIELD.dDataXferLen == 0) + { + USBD_SCSI_CodeSense(usbInfo, usbDevMSC->usbDevBOT.cmdPack.CBW.DATA_FIELD.bLUN, \ + USBD_SCSI_SENSE_KEY_ILLEGAL_REQUEST, \ + USBD_SCSI_ASC_INVALID_CDB, \ + 0); + + return USBD_FAIL; + } + + if ((usbDevMSC->usbDevBOT.cmdPack.CBW.DATA_FIELD.bmFlags.CBW_Flag & 0x80) == 0x80) + { + USBD_SCSI_CodeSense(usbInfo, usbDevMSC->usbDevBOT.cmdPack.CBW.DATA_FIELD.bLUN, \ + USBD_SCSI_SENSE_KEY_ILLEGAL_REQUEST, \ + USBD_SCSI_ASC_INVALID_CDB, \ + 0); + + return USBD_FAIL; + } + + reqStatus = ((USBD_MSC_MEMORY_T*)usbInfo->devClassUserData[usbInfo->classID])->MemoryCheckReady(lun); + + if (reqStatus != USBD_OK) + { + USBD_SCSI_CodeSense(usbInfo, usbDevMSC->usbDevBOT.cmdPack.CBW.DATA_FIELD.bLUN, \ + USBD_SCSI_SENSE_KEY_NOT_READY, \ + USBD_SCSI_ASC_MEDIUM_NOT_PRESENT, \ + 0); + + return USBD_FAIL; + } + + reqStatus = ((USBD_MSC_MEMORY_T*)usbInfo->devClassUserData[usbInfo->classID])->MemoryCheckWPR(lun); + + if (reqStatus != USBD_OK) + { + USBD_SCSI_CodeSense(usbInfo, usbDevMSC->usbDevBOT.cmdPack.CBW.DATA_FIELD.bLUN, \ + USBD_SCSI_SENSE_KEY_NOT_READY, \ + USBD_SCSI_ASC_WRITE_PROTECTED, \ + 0); + + return USBD_FAIL; + } + + /* Store write block information */ + usbDevMSC->usbDevSCSI.blockAddr = (uint32_t)((command[2] << 24) | \ + (command[3] << 16) | \ + (command[4] << 8) | \ + (command[5])); + + usbDevMSC->usbDevSCSI.blockLen = (uint32_t)((command[7] << 8) | \ + (command[8])); + + /* check if LBA address is in the right range */ + if ((usbDevMSC->usbDevSCSI.blockAddr + usbDevMSC->usbDevSCSI.blockLen) > \ + usbDevMSC->usbDevSCSI.blockNum) + { + USBD_SCSI_CodeSense(usbInfo, usbDevMSC->usbDevBOT.cmdPack.CBW.DATA_FIELD.bLUN, \ + USBD_SCSI_SENSE_KEY_ILLEGAL_REQUEST, \ + USBD_SCSI_ASC_ADDRESS_OUT_OF_RANGE, \ + 0); + + return USBD_FAIL; + } + + length = usbDevMSC->usbDevSCSI.blockLen * usbDevMSC->usbDevSCSI.blockSize; + + if (usbDevMSC->usbDevBOT.cmdPack.CBW.DATA_FIELD.dDataXferLen != length) + { + USBD_SCSI_CodeSense(usbInfo, usbDevMSC->usbDevBOT.cmdPack.CBW.DATA_FIELD.bLUN, \ + USBD_SCSI_SENSE_KEY_ILLEGAL_REQUEST, \ + USBD_SCSI_ASC_INVALID_CDB, \ + 0); + + return USBD_FAIL; + } + + + length = length < USBD_SUP_MSC_MEDIA_PACKET ? \ + length : USBD_SUP_MSC_MEDIA_PACKET; + + usbDevMSC->usbDevBOT.state = USBD_BOT_DATAOUT; + + USBD_EP_ReceiveCallback(usbInfo, usbDevMSC->epOutAddr, \ + usbDevMSC->usbDevBOT.data, \ + length); + + break; + + default: + USBD_SCSI_TxData(usbInfo, lun); + break; + } + + return usbStatus; +} + +/*! + * @brief USB device SCSI write 12 command handler + * + * @param usbInfo : usb handler information + * + * @param lun : LUN + * + * @param command: SCSI command + * + * @retval USB device operation status + */ +USBD_STA_T USBD_SCSI_Write12(USBD_INFO_T* usbInfo, uint8_t lun, uint8_t* command) +{ + USBD_STA_T usbStatus = USBD_OK; + uint8_t reqStatus = USBD_BUSY; + USBD_MSC_INFO_T* usbDevMSC = (USBD_MSC_INFO_T*)usbInfo->devClass[usbInfo->classID]->classData; + + uint32_t length; + + if (usbDevMSC == NULL) + { + return USBD_FAIL; + } + + switch (usbDevMSC->usbDevBOT.state) + { + case USBD_BOT_IDLE: + if (usbDevMSC->usbDevBOT.cmdPack.CBW.DATA_FIELD.dDataXferLen == 0) + { + USBD_SCSI_CodeSense(usbInfo, usbDevMSC->usbDevBOT.cmdPack.CBW.DATA_FIELD.bLUN, \ + USBD_SCSI_SENSE_KEY_ILLEGAL_REQUEST, \ + USBD_SCSI_ASC_INVALID_CDB, \ + 0); + + return USBD_FAIL; + } + + if ((usbDevMSC->usbDevBOT.cmdPack.CBW.DATA_FIELD.bmFlags.CBW_Flag & 0x80) == 0x80) + { + USBD_SCSI_CodeSense(usbInfo, usbDevMSC->usbDevBOT.cmdPack.CBW.DATA_FIELD.bLUN, \ + USBD_SCSI_SENSE_KEY_ILLEGAL_REQUEST, \ + USBD_SCSI_ASC_INVALID_CDB, \ + 0); + + return USBD_FAIL; + } + + reqStatus = ((USBD_MSC_MEMORY_T*)usbInfo->devClassUserData[usbInfo->classID])->MemoryCheckReady(lun); + + if (reqStatus != USBD_OK) + { + USBD_SCSI_CodeSense(usbInfo, usbDevMSC->usbDevBOT.cmdPack.CBW.DATA_FIELD.bLUN, \ + USBD_SCSI_SENSE_KEY_NOT_READY, \ + USBD_SCSI_ASC_MEDIUM_NOT_PRESENT, \ + 0); + + usbDevMSC->usbDevBOT.state = USBD_BOT_NO_DATA; + + return USBD_FAIL; + } + + reqStatus = ((USBD_MSC_MEMORY_T*)usbInfo->devClassUserData[usbInfo->classID])->MemoryCheckWPR(lun); + + if (reqStatus != USBD_OK) + { + USBD_SCSI_CodeSense(usbInfo, usbDevMSC->usbDevBOT.cmdPack.CBW.DATA_FIELD.bLUN, \ + USBD_SCSI_SENSE_KEY_NOT_READY, \ + USBD_SCSI_ASC_WRITE_PROTECTED, \ + 0); + + usbDevMSC->usbDevBOT.state = USBD_BOT_NO_DATA; + + return USBD_FAIL; + } + + /* Store write block information */ + usbDevMSC->usbDevSCSI.blockAddr = (uint32_t)((command[2] << 24) | \ + (command[3] << 16) | \ + (command[4] << 8) | \ + (command[5])); + + usbDevMSC->usbDevSCSI.blockLen = (uint32_t)((command[6] << 24) | \ + (command[7] << 16) | \ + (command[8] << 8) | \ + (command[9])); + + /* check if LBA address is in the right range */ + if ((usbDevMSC->usbDevSCSI.blockAddr + usbDevMSC->usbDevSCSI.blockLen) > \ + usbDevMSC->usbDevSCSI.blockNum) + { + USBD_SCSI_CodeSense(usbInfo, usbDevMSC->usbDevBOT.cmdPack.CBW.DATA_FIELD.bLUN, \ + USBD_SCSI_SENSE_KEY_ILLEGAL_REQUEST, \ + USBD_SCSI_ASC_ADDRESS_OUT_OF_RANGE, \ + 0); + + return USBD_FAIL; + } + + length = usbDevMSC->usbDevSCSI.blockLen * usbDevMSC->usbDevSCSI.blockSize; + + if (usbDevMSC->usbDevBOT.cmdPack.CBW.DATA_FIELD.dDataXferLen != length) + { + USBD_SCSI_CodeSense(usbInfo, usbDevMSC->usbDevBOT.cmdPack.CBW.DATA_FIELD.bLUN, \ + USBD_SCSI_SENSE_KEY_ILLEGAL_REQUEST, \ + USBD_SCSI_ASC_INVALID_CDB, \ + 0); + + return USBD_FAIL; + } + + length = length < USBD_SUP_MSC_MEDIA_PACKET ? \ + length : USBD_SUP_MSC_MEDIA_PACKET; + + usbDevMSC->usbDevBOT.state = USBD_BOT_DATAOUT; + + USBD_EP_ReceiveCallback(usbInfo, usbDevMSC->epOutAddr, \ + usbDevMSC->usbDevBOT.data, \ + length); + + break; + + default: + USBD_SCSI_TxData(usbInfo, lun); + break; + } + + return usbStatus; +} + +/*! + * @brief USB device SCSI verify 10 command handler + * + * @param usbInfo : usb handler information + * + * @param lun : LUN + * + * @param command: SCSI command + * + * @retval USB device operation status + */ +USBD_STA_T USBD_SCSI_Verify10(USBD_INFO_T* usbInfo, uint8_t lun, uint8_t* command) +{ + USBD_STA_T usbStatus = USBD_OK; + + USBD_MSC_INFO_T* usbDevMSC = (USBD_MSC_INFO_T*)usbInfo->devClass[usbInfo->classID]->classData; + + UNUSED(lun); + + if (usbDevMSC == NULL) + { + return USBD_FAIL; + } + + if ((command[1] & 0x02) == 0x02) + { + USBD_SCSI_CodeSense(usbInfo, usbDevMSC->usbDevBOT.cmdPack.CBW.DATA_FIELD.bLUN, \ + USBD_SCSI_SENSE_KEY_ILLEGAL_REQUEST, \ + USBD_SCSI_ASC_INVALID_FIELED_IN_COMMAND, \ + 0); + + return USBD_FAIL; + } + + /* check if LBA address is in the right range */ + if ((usbDevMSC->usbDevSCSI.blockAddr + usbDevMSC->usbDevSCSI.blockLen) > \ + usbDevMSC->usbDevSCSI.blockNum) + { + USBD_SCSI_CodeSense(usbInfo, usbDevMSC->usbDevBOT.cmdPack.CBW.DATA_FIELD.bLUN, \ + USBD_SCSI_SENSE_KEY_ILLEGAL_REQUEST, \ + USBD_SCSI_ASC_ADDRESS_OUT_OF_RANGE, \ + 0); + + return USBD_FAIL; + } + + usbDevMSC->usbDevBOT.dataLen = 0; + + return usbStatus; +} + +/*! + * @brief USB device SCSI read 10 command handler + * + * @param usbInfo : usb handler information + * + * @param lun : LUN + * + * @param command: SCSI command + * + * @retval USB device operation status + */ +USBD_STA_T USBD_SCSI_Read10(USBD_INFO_T* usbInfo, uint8_t lun, uint8_t* command) +{ + USBD_STA_T usbStatus = USBD_OK; + uint8_t reqStatus = USBD_BUSY; + USBD_MSC_INFO_T* usbDevMSC = (USBD_MSC_INFO_T*)usbInfo->devClass[usbInfo->classID]->classData; + + if (usbDevMSC == NULL) + { + return USBD_FAIL; + } + + if (usbDevMSC->usbDevBOT.state == USBD_BOT_IDLE) + { + if ((usbDevMSC->usbDevBOT.cmdPack.CBW.DATA_FIELD.bmFlags.CBW_Flag & 0x80) != 0x80) + { + USBD_SCSI_CodeSense(usbInfo, usbDevMSC->usbDevBOT.cmdPack.CBW.DATA_FIELD.bLUN, \ + USBD_SCSI_SENSE_KEY_ILLEGAL_REQUEST, \ + USBD_SCSI_ASC_INVALID_CDB, \ + 0); + + return USBD_FAIL; + } + + if (usbDevMSC->usbDevSCSI.mediumState == USBD_SCSI_MEDIUM_EJECT) + { + USBD_SCSI_CodeSense(usbInfo, usbDevMSC->usbDevBOT.cmdPack.CBW.DATA_FIELD.bLUN, \ + USBD_SCSI_SENSE_KEY_NOT_READY, \ + USBD_SCSI_ASC_MEDIUM_NOT_PRESENT, \ + 0); + + return USBD_FAIL; + } + + reqStatus = ((USBD_MSC_MEMORY_T*)usbInfo->devClassUserData[usbInfo->classID])->MemoryCheckReady(lun); + + if (reqStatus != USBD_OK) + { + USBD_SCSI_CodeSense(usbInfo, usbDevMSC->usbDevBOT.cmdPack.CBW.DATA_FIELD.bLUN, \ + USBD_SCSI_SENSE_KEY_NOT_READY, \ + USBD_SCSI_ASC_MEDIUM_NOT_PRESENT, \ + 0); + + return USBD_FAIL; + } + + /* Store write block information */ + usbDevMSC->usbDevSCSI.blockAddr = (uint32_t)((command[2] << 24) | \ + (command[3] << 16) | \ + (command[4] << 8) | \ + (command[5])); + + usbDevMSC->usbDevSCSI.blockLen = (uint32_t)((command[7] << 8) | \ + (command[8])); + + /* check if LBA address is in the right range */ + if ((usbDevMSC->usbDevSCSI.blockAddr + usbDevMSC->usbDevSCSI.blockLen) > \ + usbDevMSC->usbDevSCSI.blockNum) + { + USBD_SCSI_CodeSense(usbInfo, usbDevMSC->usbDevBOT.cmdPack.CBW.DATA_FIELD.bLUN, \ + USBD_SCSI_SENSE_KEY_ILLEGAL_REQUEST, \ + USBD_SCSI_ASC_ADDRESS_OUT_OF_RANGE, \ + 0); + + return USBD_FAIL; + } + + if (usbDevMSC->usbDevBOT.cmdPack.CBW.DATA_FIELD.dDataXferLen != \ + (usbDevMSC->usbDevSCSI.blockLen * usbDevMSC->usbDevSCSI.blockSize)) + { + USBD_SCSI_CodeSense(usbInfo, usbDevMSC->usbDevBOT.cmdPack.CBW.DATA_FIELD.bLUN, \ + USBD_SCSI_SENSE_KEY_ILLEGAL_REQUEST, \ + USBD_SCSI_ASC_INVALID_CDB, \ + 0); + + return USBD_FAIL; + } + + usbDevMSC->usbDevBOT.state = USBD_BOT_DATAIN; + } + + usbDevMSC->usbDevBOT.dataLen = USBD_SUP_MSC_MEDIA_PACKET; + + usbStatus = USBD_SCSI_RxData(usbInfo, lun); + + return usbStatus; +} + +/*! + * @brief USB device SCSI read 12 command handler + * + * @param usbInfo : usb handler information + * + * @param lun : LUN + * + * @param command: SCSI command + * + * @retval USB device operation status + */ +USBD_STA_T USBD_SCSI_Read12(USBD_INFO_T* usbInfo, uint8_t lun, uint8_t* command) +{ + USBD_STA_T usbStatus = USBD_OK; + uint8_t reqStatus = USBD_BUSY; + USBD_MSC_INFO_T* usbDevMSC = (USBD_MSC_INFO_T*)usbInfo->devClass[usbInfo->classID]->classData; + + if (usbDevMSC == NULL) + { + return USBD_FAIL; + } + + if (usbDevMSC->usbDevBOT.state == USBD_BOT_IDLE) + { + if ((usbDevMSC->usbDevBOT.cmdPack.CBW.DATA_FIELD.bmFlags.CBW_Flag & 0x80) != 0x80) + { + USBD_SCSI_CodeSense(usbInfo, usbDevMSC->usbDevBOT.cmdPack.CBW.DATA_FIELD.bLUN, \ + USBD_SCSI_SENSE_KEY_ILLEGAL_REQUEST, \ + USBD_SCSI_ASC_INVALID_CDB, \ + 0); + + return USBD_FAIL; + } + + if (usbDevMSC->usbDevSCSI.mediumState == USBD_SCSI_MEDIUM_EJECT) + { + USBD_SCSI_CodeSense(usbInfo, usbDevMSC->usbDevBOT.cmdPack.CBW.DATA_FIELD.bLUN, \ + USBD_SCSI_SENSE_KEY_NOT_READY, \ + USBD_SCSI_ASC_MEDIUM_NOT_PRESENT, \ + 0); + + return USBD_FAIL; + } + + reqStatus = ((USBD_MSC_MEMORY_T*)usbInfo->devClassUserData[usbInfo->classID])->MemoryCheckReady(lun); + + if (reqStatus != USBD_OK) + { + USBD_SCSI_CodeSense(usbInfo, usbDevMSC->usbDevBOT.cmdPack.CBW.DATA_FIELD.bLUN, \ + USBD_SCSI_SENSE_KEY_NOT_READY, \ + USBD_SCSI_ASC_MEDIUM_NOT_PRESENT, \ + 0); + + return USBD_FAIL; + } + + /* Store write block information */ + usbDevMSC->usbDevSCSI.blockAddr = (uint32_t)((command[2] << 24) | \ + (command[3] << 16) | \ + (command[4] << 8) | \ + (command[5])); + + usbDevMSC->usbDevSCSI.blockLen = (uint32_t)((command[6] << 24) | \ + (command[7] << 16) | \ + (command[8] << 8) | \ + (command[9])); + + /* check if LBA address is in the right range */ + if ((usbDevMSC->usbDevSCSI.blockAddr + usbDevMSC->usbDevSCSI.blockLen) > \ + usbDevMSC->usbDevSCSI.blockNum) + { + USBD_SCSI_CodeSense(usbInfo, usbDevMSC->usbDevBOT.cmdPack.CBW.DATA_FIELD.bLUN, \ + USBD_SCSI_SENSE_KEY_ILLEGAL_REQUEST, \ + USBD_SCSI_ASC_ADDRESS_OUT_OF_RANGE, \ + 0); + + return USBD_FAIL; + } + + if (usbDevMSC->usbDevBOT.cmdPack.CBW.DATA_FIELD.dDataXferLen != \ + (usbDevMSC->usbDevSCSI.blockLen * usbDevMSC->usbDevSCSI.blockSize)) + { + USBD_SCSI_CodeSense(usbInfo, usbDevMSC->usbDevBOT.cmdPack.CBW.DATA_FIELD.bLUN, \ + USBD_SCSI_SENSE_KEY_ILLEGAL_REQUEST, \ + USBD_SCSI_ASC_INVALID_CDB, \ + 0); + + return USBD_FAIL; + } + + usbDevMSC->usbDevBOT.state = USBD_BOT_DATAIN; + } + + usbDevMSC->usbDevBOT.dataLen = USBD_SUP_MSC_MEDIA_PACKET; + + usbStatus = USBD_SCSI_RxData(usbInfo, lun); + + return usbStatus; +} + +/*! + * @brief USB device SCSI handler + * + * @param usbInfo : usb handler information + * + * @param lun : LUN + * + * @param command: SCSI command + * + * @retval USB device operation status + */ +USBD_STA_T USBD_SCSI_Handle(USBD_INFO_T* usbInfo, uint8_t lun, uint8_t* command) +{ + USBD_STA_T usbStatus = USBD_FAIL; + USBD_MSC_INFO_T* usbDevMSC = (USBD_MSC_INFO_T*)usbInfo->devClass[usbInfo->classID]->classData; + + if (usbDevMSC == NULL) + { + return usbStatus; + } + + switch (command[0]) + { + case USBD_SCSI_CMD_INQUIRY: + usbStatus = USBD_SCSI_Inquiry(usbInfo, lun, command); + break; + + case USBD_SCSI_CMD_ALLOW_MEDIUM_REMOVAL: + usbStatus = USBD_SCSI_AllowMediumRemoval(usbInfo, lun, command); + break; + + case USBD_SCSI_CMD_MODE_SENSE_6: + usbStatus = USBD_SCSI_ModeSense6(usbInfo, lun, command); + break; + + case USBD_SCSI_CMD_MODE_SENSE_10: + usbStatus = USBD_SCSI_ModeSense10(usbInfo, lun, command); + break; + + case USBD_SCSI_CMD_READ_FORMAT_CAPACITIES: + usbStatus = USBD_SCSI_ReadFormatCapacity(usbInfo, lun, command); + break; + + case USBD_SCSI_CMD_READ_CAPACITY: + usbStatus = USBD_SCSI_ReadCapacity(usbInfo, lun, command); + break; + + case USBD_SCSI_CMD_READ_CAPACITY_16: + usbStatus = USBD_SCSI_ReadCapacity16(usbInfo, lun, command); + break; + + case USBD_SCSI_CMD_REQUEST_SENSE: + usbStatus = USBD_SCSI_RequestSense(usbInfo, lun, command); + break; + + case USBD_SCSI_CMD_START_STOP_UNIT: + usbStatus = USBD_SCSI_StartStopUnit(usbInfo, lun, command); + break; + + case USBD_SCSI_CMD_TEST_UNIT_READY: + usbStatus = USBD_SCSI_TestUnitReady(usbInfo, lun, command); + break; + + case USBD_SCSI_CMD_WRITE10: + usbStatus = USBD_SCSI_Write10(usbInfo, lun, command); + break; + + case USBD_SCSI_CMD_WRITE12: + usbStatus = USBD_SCSI_Write12(usbInfo, lun, command); + break; + + case USBD_SCSI_CMD_VERIFY_10: + usbStatus = USBD_SCSI_Verify10(usbInfo, lun, command); + break; + + case USBD_SCSI_CMD_READ_10: + usbStatus = USBD_SCSI_Read10(usbInfo, lun, command); + break; + + case USBD_SCSI_CMD_READ_12: + usbStatus = USBD_SCSI_Read12(usbInfo, lun, command); + break; + + default: + USBD_SCSI_CodeSense(usbInfo, lun, USBD_SCSI_SENSE_KEY_ILLEGAL_REQUEST, \ + USBD_SCSI_ASC_INVALID_CDB, 0); + usbDevMSC->usbDevBOT.status = USBD_BOT_ERR; + usbStatus = USBD_FAIL; + break; + } + + return usbStatus; +} + +/**@} end of group USBD_MSC_Functions */ +/**@} end of group USBD_MSC_Class */ +/**@} end of group APM32_USB_Library */ diff --git a/lib/main/APM32F4/Middlewares/APM32_USB_Library/Device/Class/WINUSB/Inc/usbd_winusb.h b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Device/Class/WINUSB/Inc/usbd_winusb.h new file mode 100644 index 0000000000..299df44564 --- /dev/null +++ b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Device/Class/WINUSB/Inc/usbd_winusb.h @@ -0,0 +1,146 @@ +/*! + * @file usbd_winusb.h + * + * @brief usb device winUSB class handler header file + * + * @version V1.0.0 + * + * @date 2023-01-16 + * + * @attention + * + * Copyright (C) 2023 Geehy Semiconductor + * + * You may not use this file except in compliance with the + * GEEHY COPYRIGHT NOTICE (GEEHY SOFTWARE PACKAGE LICENSE). + * + * The program is only for reference, which is distributed in the hope + * that it will be useful and instructional for customers to develop + * their software. Unless required by applicable law or agreed to in + * writing, the program is distributed on an "AS IS" BASIS, WITHOUT + * ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied. + * See the GEEHY SOFTWARE PACKAGE LICENSE for the governing permissions + * and limitations under the License. + */ + +/* Define to prevent recursive inclusion */ +#ifndef _USBD_WINUSB_H_ +#define _USBD_WINUSB_H_ + +/* Includes */ +#include "usbd_core.h" + +/** @addtogroup APM32_USB_Library + @{ + */ + +/** @addtogroup USBD_WINUSB_Class + @{ + */ + +/** @defgroup USBD_WINUSB_Macros Macros + @{ +*/ + +#define USBD_WINUSB_OS_FEATURE_DESC_SIZE 0x28 +#define USBD_WINUSB_OS_PROPERTY_DESC_SIZE 0x8E + +#define USBD_WINUSB_FS_MP_SIZE 0x40 +#define USBD_WINUSB_HS_MP_SIZE 0x200 +#define USBD_WINUSB_CMD_MP_SIZE 0x08 +#define USBD_WINUSB_DATA_MP_SIZE 0x07 + +#define USBD_WINUSB_CMD_EP_ADDR 0x82 +#define USBD_WINUSB_DATA_IN_EP_ADDR 0x81 +#define USBD_WINUSB_DATA_OUT_EP_ADDR 0x01 + +#define USBD_WINUSB_FS_INTERVAL 16 +#define USBD_WINUSB_HS_INTERVAL 16 + +/**@} end of group USBD_WINUSB_Macros*/ + +/** @defgroup USBD_WINUSB_Enumerates Enumerates + @{ + */ + +/** + * @brief USB device WINUSB xfer status + */ +typedef enum +{ + USBD_WINUSB_XFER_IDLE, + USBD_WINUSB_XFER_BUSY, +} USBD_WINUSB_XFER_STA_T; + +/**@} end of group USBD_WINUSB_Enumerates*/ + +/** @defgroup USBD_WINUSB_Structures Structures + @{ + */ + +/** + * @brief USB device WINUSB interface handler + */ +typedef struct +{ + const char* itfName; + USBD_STA_T (*ItfInit)(void); + USBD_STA_T (*ItfDeInit)(void); + USBD_STA_T (*ItfCtrl)(uint8_t command, uint8_t *buffer, uint16_t length); + USBD_STA_T (*ItfSend)(uint8_t *buffer, uint16_t length); + USBD_STA_T (*ItfSendEnd)(uint8_t epNum, uint8_t *buffer, uint32_t *length); + USBD_STA_T (*ItfReceive)(uint8_t *buffer, uint32_t *length); +} USBD_WINUSB_INTERFACE_T; + +/** + * @brief USB device WINUSB data handler + */ +typedef struct +{ + __IO uint8_t state; + uint8_t *buffer; + uint32_t length; +} USBD_WINUSB_DATA_XFER_T; + +/** + * @brief USB device WINUSB command handler + */ +typedef struct +{ + uint8_t opcode; + uint8_t length; +} USBD_WINUSB_CMD_XFER_T; + +/** + * @brief WINUSB information management + */ +typedef struct +{ + uint8_t itf; + uint8_t epInAddr; + uint8_t epOutAddr; + USBD_WINUSB_DATA_XFER_T winusbTx; + USBD_WINUSB_DATA_XFER_T winusbRx; + uint32_t data[USBD_WINUSB_HS_MP_SIZE / 4]; +} USBD_WINUSB_INFO_T; + +extern USBD_CLASS_T USBD_WINUSB_CLASS; + +/**@} end of group USBD_WINUSB_Structures*/ + +/** @defgroup USBD_WINUSB_Functions Functions + @{ + */ + +USBD_STA_T USBD_WINUSB_TxPacket(USBD_INFO_T* usbInfo); +USBD_STA_T USBD_WINUSB_RxPacket(USBD_INFO_T* usbInfo); +uint8_t USBD_WINUSB_ReadInterval(USBD_INFO_T* usbInfo); +USBD_STA_T USBD_WINUSB_ConfigTxBuffer(USBD_INFO_T* usbInfo, uint8_t *buffer, uint32_t length); +USBD_STA_T USBD_WINUSB_ConfigRxBuffer(USBD_INFO_T* usbInfo, uint8_t *buffer); +USBD_STA_T USBD_WINUSB_RegisterItf(USBD_INFO_T* usbInfo, USBD_WINUSB_INTERFACE_T* itf); + +/**@} end of group USBD_WINUSB_Functions */ +/**@} end of group USBD_WINUSB_Class */ +/**@} end of group APM32_USB_Library */ + +#endif diff --git a/lib/main/APM32F4/Middlewares/APM32_USB_Library/Device/Class/WINUSB/Src/usbd_winusb.c b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Device/Class/WINUSB/Src/usbd_winusb.c new file mode 100644 index 0000000000..1672365919 --- /dev/null +++ b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Device/Class/WINUSB/Src/usbd_winusb.c @@ -0,0 +1,769 @@ +/*! + * @file usbd_winusb.c + * + * @brief usb device winUSB class handler + * + * @version V1.0.0 + * + * @date 2023-01-16 + * + * @attention + * + * Copyright (C) 2023 Geehy Semiconductor + * + * You may not use this file except in compliance with the + * GEEHY COPYRIGHT NOTICE (GEEHY SOFTWARE PACKAGE LICENSE). + * + * The program is only for reference, which is distributed in the hope + * that it will be useful and instructional for customers to develop + * their software. Unless required by applicable law or agreed to in + * writing, the program is distributed on an "AS IS" BASIS, WITHOUT + * ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied. + * See the GEEHY SOFTWARE PACKAGE LICENSE for the governing permissions + * and limitations under the License. + */ + +/* Includes */ +#include "usbd_winusb.h" +#include "usbd_stdReq.h" +#include "usbd_dataXfer.h" +#include +#include +#include + +/** @addtogroup APM32_USB_Library + @{ + */ + +/** @addtogroup USBD_WINUSB_Class + @{ + */ + +/** @defgroup USBD_WINUSB_Functions Functions + @{ + */ + +static USBD_STA_T USBD_WINUSB_ClassInitHandler(USBD_INFO_T* usbInfo, uint8_t cfgIndex); +static USBD_STA_T USBD_WINUSB_ClassDeInitHandler(USBD_INFO_T* usbInfo, uint8_t cfgIndex); +static USBD_STA_T USBD_WINUSB_SOFHandler(USBD_INFO_T* usbInfo); +static USBD_STA_T USBD_WINUSB_SetupHandler(USBD_INFO_T* usbInfo, USBD_REQ_SETUP_T* req); +static USBD_STA_T USBD_WINUSB_DataInHandler(USBD_INFO_T* usbInfo, uint8_t epNum); +static USBD_STA_T USBD_WINUSB_DataOutHandler(USBD_INFO_T* usbInfo, uint8_t epNum); + +/**@} end of group USBD_WINUSB_Functions */ + +/** @defgroup USBD_WINUSB_Structures Structures + @{ + */ + +/* WINUSB class handler */ +USBD_CLASS_T USBD_WINUSB_CLASS = +{ + /* Class handler */ + "Class WINUSB", + NULL, + USBD_WINUSB_ClassInitHandler, + USBD_WINUSB_ClassDeInitHandler, + USBD_WINUSB_SOFHandler, + + /* Control endpoint */ + USBD_WINUSB_SetupHandler, + NULL, + NULL, + /* Specific endpoint */ + USBD_WINUSB_DataInHandler, + USBD_WINUSB_DataOutHandler, + NULL, + NULL, +}; + +/**@} end of group USBD_WINUSB_Structures*/ + +/** @defgroup USBD_WINUSB_Variables Variables + @{ + */ + +/** + * @brief WinUSB OS feature descriptor + */ +uint8_t USBD_WinUsbOsFeatureDesc[USBD_WINUSB_OS_FEATURE_DESC_SIZE] = +{ + /* dwLength */ + 0x28, 0x00, 0x00, 0x00, + /* bcdVersion */ + 0x00, 0x01, + /* wIndex extended compat ID descritor */ + 0x04, 0x00, + /* bCount */ + 0x01, + /* Reserved */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + /* WCID Function */ + /* bFirstInterfaceNumber */ + 0x00, + /* bReserved */ + 0x00, + /* CID */ + 'W', 'I', 'N', 'U', 'S', 'B', 0x00, 0x00, + /* Sub CID */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + /* Reserved */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +}; + +/* L"DeviceInterfaceGUID" : wIndex = 0x0005 */ +/* L"{12345678-1234-1234-1234-123456789ABC}" */ +uint8_t USBD_WinUsbOsPropertyDesc[USBD_WINUSB_OS_PROPERTY_DESC_SIZE] = +{ + /* dwTotalSize = Header + All sections */ + 0x8E, 0x00, 0x00, 0x00, + /* bcdVersion */ + 0x00, 0x01, + /* wIndex */ + 0x05, 0x00, + /* bCount */ + 0x01, 0x00, + + /* dwSize - this section */ + 0x84, 0x00, 0x00, 0x00, + + /* dwPropertyDataType */ + 0x01, 0x00, 0x00, 0x00, + + /* wPropertyNameLength */ + 0x28, 0x00, + + /* WCHAR L"DeviceInterfaceGUID" */ + 'D', 0x00, 'e', 0x00, + 'v', 0x00, 'i', 0x00, + 'c', 0x00, 'e', 0x00, + 'I', 0x00, 'n', 0x00, + 't', 0x00, 'e', 0x00, + 'r', 0x00, 'f', 0x00, + 'a', 0x00, 'c', 0x00, + 'e', 0x00, 'G', 0x00, + 'U', 0x00, 'I', 0x00, + 'D', 0x00, 0x00, 0x00, + + /* dwPropertyDataLength : 78 Bytes = 0x0000004E */ + 0x4E, 0x00, 0x00, 0x00, + + /* WCHAR : L"{12345678-1234-1234-1234-123456789ABC}" */ + '{', 0x00, '1', 0x00, + '2', 0x00, '3', 0x00, + '4', 0x00, '5', 0x00, + '6', 0x00, '7', 0x00, + '8', 0x00, '-', 0x00, + '1', 0x00, '2', 0x00, + '3', 0x00, '4', 0x00, + '-', 0x00, '1', 0x00, + '2', 0x00, '3', 0x00, + '4', 0x00, '-', 0x00, + '1', 0x00, '2', 0x00, + '3', 0x00, '4', 0x00, + '-', 0x00, '1', 0x00, + '2', 0x00, '3', 0x00, + '4', 0x00, '5', 0x00, + '6', 0x00, '7', 0x00, + '8', 0x00, '9', 0x00, + 'A', 0x00, 'B', 0x00, + 'C', 0x00, '}', 0x00, + 0x00, 0x00 +}; + +/**@} end of group USBD_WINUSB_Variables*/ + +/** @defgroup USBD_WINUSB_Functions Functions + @{ + */ + +/*! + * @brief USB device WINUSB feature descriptor + * + * @param usbSpeed : usb speed + * + * @retval usb descriptor information + */ +static USBD_DESC_INFO_T USBD_WinUsbFeatureDescHandler(uint8_t usbSpeed) +{ + USBD_DESC_INFO_T descInfo; + + descInfo.desc = USBD_WinUsbOsFeatureDesc; + descInfo.size = sizeof(USBD_WinUsbOsFeatureDesc); + + return descInfo; +} + +/*! + * @brief USB device WINUSB property descriptor + * + * @param usbSpeed : usb speed + * + * @retval usb descriptor information + */ +static USBD_DESC_INFO_T USBD_WinUsbPropertyDescHandler(uint8_t usbSpeed) +{ + USBD_DESC_INFO_T descInfo; + + descInfo.desc = USBD_WinUsbOsPropertyDesc; + descInfo.size = sizeof(USBD_WinUsbOsPropertyDesc); + + return descInfo; +} + +/*! + * @brief USB device WINUSB configuration handler + * + * @param usbInfo: usb device information + * + * @param cfgIndex: configuration index + * + * @retval USB device operation status + */ +static USBD_STA_T USBD_WINUSB_ClassInitHandler(USBD_INFO_T* usbInfo, uint8_t cfgIndex) +{ + USBD_STA_T usbStatus = USBD_OK; + + USBD_WINUSB_INFO_T* usbDevWINUSB; + + /* Link class data */ + usbInfo->devClass[usbInfo->classID]->classData = (USBD_WINUSB_INFO_T*)malloc(sizeof(USBD_WINUSB_INFO_T)); + usbDevWINUSB = (USBD_WINUSB_INFO_T*)usbInfo->devClass[usbInfo->classID]->classData; + memset(usbDevWINUSB, 0, sizeof(USBD_WINUSB_INFO_T)); + + USBD_USR_Debug("USBD_WINUSB_INFO_T size %d\r\n", sizeof(USBD_WINUSB_INFO_T)); + + if (usbDevWINUSB == NULL) + { + USBD_USR_LOG("usbDevWINUSB is NULL"); + return USBD_FAIL; + } + + usbDevWINUSB->epInAddr = USBD_WINUSB_DATA_IN_EP_ADDR; + usbDevWINUSB->epOutAddr = USBD_WINUSB_DATA_OUT_EP_ADDR; + + /* Open Data endpoint */ + switch (usbInfo->devSpeed) + { + case USBD_SPEED_FS: + USBD_EP_OpenCallback(usbInfo, usbDevWINUSB->epOutAddr, EP_TYPE_BULK, USBD_WINUSB_FS_MP_SIZE); + usbInfo->devEpOut[usbDevWINUSB->epOutAddr & 0x0F].useStatus = ENABLE; + + USBD_EP_OpenCallback(usbInfo, usbDevWINUSB->epInAddr, EP_TYPE_BULK, USBD_WINUSB_FS_MP_SIZE); + usbInfo->devEpIn[usbDevWINUSB->epInAddr & 0x0F].useStatus = ENABLE; + break; + + default: + USBD_EP_OpenCallback(usbInfo, usbDevWINUSB->epOutAddr, EP_TYPE_BULK, USBD_WINUSB_HS_MP_SIZE); + usbInfo->devEpOut[usbDevWINUSB->epOutAddr & 0x0F].useStatus = ENABLE; + + USBD_EP_OpenCallback(usbInfo, usbDevWINUSB->epInAddr, EP_TYPE_BULK, USBD_WINUSB_HS_MP_SIZE); + usbInfo->devEpIn[usbDevWINUSB->epInAddr & 0x0F].useStatus = ENABLE; + break; + } + + /* Interface Init */ + usbDevWINUSB->winusbTx.buffer = NULL; + usbDevWINUSB->winusbRx.buffer = NULL; + + usbDevWINUSB->winusbTx.state = USBD_WINUSB_XFER_IDLE; + usbDevWINUSB->winusbRx.state = USBD_WINUSB_XFER_IDLE; + + ((USBD_WINUSB_INTERFACE_T *)usbInfo->devClassUserData[usbInfo->classID])->ItfInit(); + + if(usbDevWINUSB->winusbRx.buffer == NULL) + { + USBD_USR_LOG("winusbRx buffer is NULL"); + return USBD_FAIL; + } + + switch (usbInfo->devSpeed) + { + case USBD_SPEED_FS: + USBD_EP_ReceiveCallback(usbInfo, usbDevWINUSB->epOutAddr, \ + usbDevWINUSB->winusbRx.buffer, \ + USBD_WINUSB_FS_MP_SIZE); + break; + + default: + USBD_EP_ReceiveCallback(usbInfo, usbDevWINUSB->epOutAddr, \ + usbDevWINUSB->winusbRx.buffer, \ + USBD_WINUSB_HS_MP_SIZE); + break; + } + + return usbStatus; +} + +/*! + * @brief USB device WINUSB reset handler + * + * @param usbInfo: usb device information + * + * @param cfgIndex: configuration index + * + * @retval USB device operation status + */ +static USBD_STA_T USBD_WINUSB_ClassDeInitHandler(USBD_INFO_T* usbInfo, uint8_t cfgIndex) +{ + USBD_STA_T usbStatus = USBD_OK; + USBD_WINUSB_INFO_T* usbDevWINUSB = (USBD_WINUSB_INFO_T*)usbInfo->devClass[usbInfo->classID]->classData; + + /* Close WINUSB EP */ + USBD_EP_CloseCallback(usbInfo, usbDevWINUSB->epOutAddr); + usbInfo->devEpOut[usbDevWINUSB->epOutAddr & 0x0F].useStatus = DISABLE; + + USBD_EP_CloseCallback(usbInfo, usbDevWINUSB->epInAddr); + usbInfo->devEpIn[usbDevWINUSB->epInAddr & 0x0F].useStatus = DISABLE; + + if (usbInfo->devClass[usbInfo->classID]->classData != NULL) + { + if(((USBD_WINUSB_INTERFACE_T *)usbInfo->devClassUserData[usbInfo->classID])->ItfDeInit != NULL) + { + ((USBD_WINUSB_INTERFACE_T *)usbInfo->devClassUserData[usbInfo->classID])->ItfDeInit(); + } + + free(usbInfo->devClass[usbInfo->classID]->classData); + usbInfo->devClass[usbInfo->classID]->classData = 0; + } + + return usbStatus; +} + +/*! + * @brief USB device WINUSB SOF handler + * + * @param usbInfo: usb device information + * + * @retval USB device operation status + */ +static USBD_STA_T USBD_WINUSB_SOFHandler(USBD_INFO_T* usbInfo) +{ + USBD_STA_T usbStatus = USBD_BUSY; + + return usbStatus; +} + +/*! + * @brief USB WINUSB device receive CTRL status + * + * @param usbInfo : usb handler information + * + * @param buffer : data buffer + * + * @param length : length of data + * + * @retval usb device status + */ +USBD_STA_T USBD_WINUSB_CtrlReceiveData(USBD_INFO_T* usbInfo, uint8_t *buffer, uint32_t length) +{ + USBD_STA_T usbStatus = USBD_OK; + + usbInfo->devEp0State = USBD_DEV_EP0_DATA_OUT; + usbInfo->devEpOut[USBD_EP_0].length = length; + usbInfo->devEpOut[USBD_EP_0].remainLen = length; + + USBD_EP_ReceiveCallback(usbInfo, USBD_EP_0, buffer, length); + + return usbStatus; +} + +/*! + * @brief USB device WINUSB SETUP handler + * + * @param usbInfo: usb device information + * + * @param req: setup request + * + * @retval USB device operation status + */ +static USBD_STA_T USBD_WINUSB_SetupHandler(USBD_INFO_T* usbInfo, USBD_REQ_SETUP_T* req) +{ + USBD_STA_T usbStatus = USBD_OK; + USBD_WINUSB_INFO_T* usbDevWINUSB = (USBD_WINUSB_INFO_T*)usbInfo->devClass[usbInfo->classID]->classData; + + uint8_t request; + uint8_t reqType; + uint16_t wLength = req->DATA_FIELD.wLength[0] | req->DATA_FIELD.wLength[1] << 8; + uint16_t wIndex = req->DATA_FIELD.wIndex[0] | req->DATA_FIELD.wIndex[1] << 8; + uint16_t status = 0x0000; + uint16_t length; + + USBD_DESC_INFO_T descInfo; + + request = req->DATA_FIELD.bRequest; + reqType = usbInfo->reqSetup.DATA_FIELD.bmRequest.REQ_TYPE_B.type; + + if(request != USBD_VEN_REQ_MS_CODE) + { + if (usbDevWINUSB == NULL) + { + return USBD_FAIL; + } + } + + switch (reqType) + { + case USBD_REQ_TYPE_STANDARD: + switch (request) + { + case USBD_STD_GET_STATUS: + if (usbInfo->devState == USBD_DEV_CONFIGURE) + { + USBD_CtrlSendData(usbInfo, (uint8_t*)&status, 2); + } + else + { + USBD_REQ_CtrlError(usbInfo, req); + usbStatus = USBD_FAIL; + } + break; + + case USBD_STD_GET_INTERFACE: + if (usbInfo->devState == USBD_DEV_CONFIGURE) + { + usbDevWINUSB->itf = 0; + USBD_CtrlSendData(usbInfo, (uint8_t*)&usbDevWINUSB->itf, 1); + } + else + { + USBD_REQ_CtrlError(usbInfo, req); + usbStatus = USBD_FAIL; + } + break; + + case USBD_STD_SET_INTERFACE: + if (usbInfo->devState == USBD_DEV_CONFIGURE) + { + + } + else + { + USBD_REQ_CtrlError(usbInfo, req); + usbStatus = USBD_FAIL; + } + break; + + case USBD_STD_CLEAR_FEATURE: + break; + + default: + USBD_REQ_CtrlError(usbInfo, req); + usbStatus = USBD_FAIL; + break; + } + break; + + case USBD_REQ_TYPE_CLASS: + if(wLength) + { + if((usbInfo->reqSetup.DATA_FIELD.bmRequest.REQ_TYPE & 0x80) == 0x80) + { + ((USBD_WINUSB_INTERFACE_T *)usbInfo->devClassUserData[usbInfo->classID])->ItfCtrl(request, \ + (uint8_t *)usbDevWINUSB->data, + wLength); + + length = USBD_WINUSB_DATA_MP_SIZE < wLength ? USBD_WINUSB_DATA_MP_SIZE : wLength; + USBD_CtrlSendData(usbInfo, (uint8_t *)usbDevWINUSB->data, length); + } + } + else + { + ((USBD_WINUSB_INTERFACE_T *)usbInfo->devClassUserData[usbInfo->classID])->ItfCtrl(request, \ + (uint8_t *)req, \ + 0); + } + break; + + case USBD_REQ_TYPE_VENDOR: + switch (request) + { + case USBD_VEN_REQ_MS_CODE: + switch(wIndex) + { + case USBD_WINUSB_DESC_FEATURE: + descInfo = USBD_WinUsbFeatureDescHandler(usbInfo->devSpeed); + + descInfo.size = descInfo.size < wLength ? descInfo.size : wLength; + break; + + case USBD_WINUSB_DESC_PROPERTY: + descInfo = USBD_WinUsbPropertyDescHandler(usbInfo->devSpeed); + + descInfo.size = descInfo.size < wLength ? descInfo.size : wLength; + break; + + default: + USBD_REQ_CtrlError(usbInfo, req); + usbStatus = USBD_FAIL; + break; + } + + if (descInfo.desc != NULL) + { + USBD_CtrlSendData(usbInfo, descInfo.desc, descInfo.size); + } + break; + + default: + USBD_REQ_CtrlError(usbInfo, req); + usbStatus = USBD_FAIL; + break; + } + break; + + default: + usbStatus = USBD_FAIL; + USBD_REQ_CtrlError(usbInfo, req); + break; + } + + return usbStatus; +} + +/*! + * @brief USB device WINUSB IN data handler + * + * @param usbInfo: usb device information + * + * @param epNum: endpoint number + * + * @retval USB device operation status + */ +static USBD_STA_T USBD_WINUSB_DataInHandler(USBD_INFO_T* usbInfo, uint8_t epNum) +{ + USBD_STA_T usbStatus = USBD_OK; + USBD_WINUSB_INFO_T* usbDevWINUSB = (USBD_WINUSB_INFO_T*)usbInfo->devClass[usbInfo->classID]->classData; + +#if defined(USE_DAL_DRIVER) + PCD_HandleTypeDef* usbdh = (PCD_HandleTypeDef *)usbInfo->dataPoint; +#else + USBD_HANDLE_T* usbdh = (USBD_HANDLE_T *)usbInfo->dataPoint; +#endif /* USE_DAL_DRIVER */ + if (usbdh == NULL) + { + return USBD_FAIL; + } + + if (usbDevWINUSB == NULL) + { + return USBD_FAIL; + } + +#if defined(USE_DAL_DRIVER) + if((usbInfo->devEpIn[epNum & 0x0F].length > 0) && \ + (usbInfo->devEpIn[epNum & 0x0F].length % usbdh->IN_ep[epNum & 0x0F].maxpacket) == 0) +#else + if((usbInfo->devEpIn[epNum & 0x0F].length > 0) && \ + (usbInfo->devEpIn[epNum & 0x0F].length % usbdh->epIN[epNum & 0x0F].mps) == 0) +#endif /* USE_DAL_DRIVER */ + { + usbInfo->devEpIn[epNum & 0x0F].length = 0; + + USBD_EP_TransferCallback(usbInfo, epNum, NULL, 0); + } + else + { + usbDevWINUSB->winusbTx.state = USBD_WINUSB_XFER_IDLE; + + if(((USBD_WINUSB_INTERFACE_T *)usbInfo->devClassUserData[usbInfo->classID])->ItfSendEnd != NULL) + { + ((USBD_WINUSB_INTERFACE_T *)usbInfo->devClassUserData[usbInfo->classID])->ItfSendEnd(epNum, \ + usbDevWINUSB->winusbTx.buffer, \ + &usbDevWINUSB->winusbTx.length); + } + } + + return usbStatus; +} + +/*! + * @brief USB device WINUSB OUT data handler + * + * @param usbInfo: usb device information + * + * @param epNum: endpoint number + * + * @retval USB device operation status + */ +static USBD_STA_T USBD_WINUSB_DataOutHandler(USBD_INFO_T* usbInfo, uint8_t epNum) +{ + USBD_STA_T usbStatus = USBD_OK; + USBD_WINUSB_INFO_T* usbDevWINUSB = (USBD_WINUSB_INFO_T*)usbInfo->devClass[usbInfo->classID]->classData; + + if (usbDevWINUSB == NULL) + { + return USBD_FAIL; + } + + usbDevWINUSB->winusbRx.length = USBD_EP_ReadRxDataLenCallback(usbInfo, epNum); + + ((USBD_WINUSB_INTERFACE_T *)usbInfo->devClassUserData[usbInfo->classID])->ItfReceive(usbDevWINUSB->winusbRx.buffer, \ + &usbDevWINUSB->winusbRx.length); + + return usbStatus; +} + +/*! + * @brief USB device WINUSB configure TX buffer handler + * + * @param usbInfo: usb device information + * + * @param buffer: tx buffer + * + * @param length: tx buffer length + * + * @retval USB device operation status + */ +USBD_STA_T USBD_WINUSB_ConfigTxBuffer(USBD_INFO_T* usbInfo, uint8_t *buffer, uint32_t length) +{ + USBD_STA_T usbStatus = USBD_OK; + USBD_WINUSB_INFO_T* usbDevWINUSB = (USBD_WINUSB_INFO_T*)usbInfo->devClass[usbInfo->classID]->classData; + + if (usbDevWINUSB == NULL) + { + return USBD_FAIL; + } + + usbDevWINUSB->winusbTx.buffer = buffer; + usbDevWINUSB->winusbTx.length = length; + + return usbStatus; +} + +/*! + * @brief USB device WINUSB configure RX buffer handler + * + * @param usbInfo: usb device information + * + * @param buffer: tx buffer + * + * @retval USB device operation status + */ +USBD_STA_T USBD_WINUSB_ConfigRxBuffer(USBD_INFO_T* usbInfo, uint8_t *buffer) +{ + USBD_STA_T usbStatus = USBD_OK; + USBD_WINUSB_INFO_T* usbDevWINUSB = (USBD_WINUSB_INFO_T*)usbInfo->devClass[usbInfo->classID]->classData; + + if (usbDevWINUSB == NULL) + { + return USBD_FAIL; + } + + usbDevWINUSB->winusbRx.buffer = buffer; + + return usbStatus; +} + +/*! + * @brief USB device WINUSB register interface handler + * + * @param usbInfo: usb device information + * + * @param itf: interface handler + * + * @retval USB device operation status + */ +USBD_STA_T USBD_WINUSB_RegisterItf(USBD_INFO_T* usbInfo, USBD_WINUSB_INTERFACE_T* itf) +{ + USBD_STA_T usbStatus = USBD_FAIL; + + if (itf != NULL) + { + usbInfo->devClassUserData[usbInfo->classID] = itf; + usbStatus = USBD_OK; + } + + return usbStatus; +} + +/*! + * @brief USB device WINUSB transmit packet handler + * + * @param usbInfo: usb device information + * + * @retval USB device operation status + */ +USBD_STA_T USBD_WINUSB_TxPacket(USBD_INFO_T* usbInfo) +{ + USBD_STA_T usbStatus = USBD_BUSY; + USBD_WINUSB_INFO_T* usbDevWINUSB = (USBD_WINUSB_INFO_T*)usbInfo->devClass[usbInfo->classID]->classData; + + if (usbDevWINUSB == NULL) + { + return USBD_FAIL; + } + + if(usbDevWINUSB->winusbTx.state == USBD_WINUSB_XFER_IDLE) + { + usbDevWINUSB->winusbTx.state = USBD_WINUSB_XFER_BUSY; + + usbInfo->devEpIn[usbDevWINUSB->epInAddr & 0x0F].length = usbDevWINUSB->winusbTx.length; + + USBD_EP_TransferCallback(usbInfo, usbDevWINUSB->epInAddr, usbDevWINUSB->winusbTx.buffer, usbDevWINUSB->winusbTx.length); + + usbStatus = USBD_OK; + } + + return usbStatus; +} + +/*! + * @brief USB device WINUSB receive packet handler + * + * @param usbInfo: usb device information + * + * @retval USB device operation status + */ +USBD_STA_T USBD_WINUSB_RxPacket(USBD_INFO_T* usbInfo) +{ + USBD_STA_T usbStatus = USBD_BUSY; + USBD_WINUSB_INFO_T* usbDevWINUSB = (USBD_WINUSB_INFO_T*)usbInfo->devClass[usbInfo->classID]->classData; + + if (usbDevWINUSB == NULL) + { + return USBD_FAIL; + } + + if(usbInfo->devSpeed == USBD_SPEED_HS) + { + USBD_EP_ReceiveCallback(usbInfo, usbDevWINUSB->epOutAddr, \ + usbDevWINUSB->winusbRx.buffer, \ + USBD_WINUSB_HS_MP_SIZE); + } + else + { + USBD_EP_ReceiveCallback(usbInfo, usbDevWINUSB->epOutAddr, \ + usbDevWINUSB->winusbRx.buffer, \ + USBD_WINUSB_FS_MP_SIZE); + } + + return usbStatus; +} + +/*! + * @brief USB device WINUSB read interval + * + * @param usbInfo: usb device information + * + * @retval usb interval + */ +uint8_t USBD_WINUSB_ReadInterval(USBD_INFO_T* usbInfo) +{ + uint8_t interval; + + if (usbInfo->devSpeed == USBD_SPEED_FS) + { + interval = USBD_WINUSB_FS_INTERVAL; + } + else + { + interval = USBD_WINUSB_HS_INTERVAL; + } + + return interval; +} + +/**@} end of group USBD_WINUSB_Functions */ +/**@} end of group USBD_WINUSB_Class */ +/**@} end of group APM32_USB_Library */ diff --git a/lib/main/APM32F4/Middlewares/APM32_USB_Library/Device/Core/Inc/usbd_config.h b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Device/Core/Inc/usbd_config.h new file mode 100644 index 0000000000..5c4e34312f --- /dev/null +++ b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Device/Core/Inc/usbd_config.h @@ -0,0 +1,389 @@ +/*! + * @file usbd_config.h + * + * @brief usb device config header file + * + * @version V1.0.1 + * + * @date 2023-03-27 + * + * @attention + * + * Copyright (C) 2023 Geehy Semiconductor + * + * You may not use this file except in compliance with the + * GEEHY COPYRIGHT NOTICE (GEEHY SOFTWARE PACKAGE LICENSE). + * + * The program is only for reference, which is distributed in the hope + * that it will be useful and instructional for customers to develop + * their software. Unless required by applicable law or agreed to in + * writing, the program is distributed on an "AS IS" BASIS, WITHOUT + * ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied. + * See the GEEHY SOFTWARE PACKAGE LICENSE for the governing permissions + * and limitations under the License. + */ + +/* Define to prevent recursive inclusion */ +#ifndef _USBD_CONFIG_H_ +#define _USBD_CONFIG_H_ + +/* Includes */ +#include "usbd_board.h" +//#include + +/** @addtogroup APM32_USB_Library + @{ + */ + +/** @addtogroup USBD_Core + @{ + */ + +/** @defgroup USBD_Core_Macros Macros + @{ +*/ + +/*!< [31:16] APM32 USB Device Library main version V1.1.3*/ +#define __APM32_USB_DEVICE_VERSION_MAIN (0x01) /*!< [31:24] main version */ +#define __APM32_USB_DEVICE_VERSION_SUB1 (0x01) /*!< [23:16] sub1 version */ +#define __APM32_USB_DEVICE_VERSION_SUB2 (0x03) /*!< [15:8] sub2 version */ +#define __APM32_USB_DEVICE_VERSION_RC (0x00) /*!< [7:0] release candidate */ +#define __APM32_USB_DEVICE_VERSION ((__APM32_USB_DEVICE_VERSION_MAIN << 24)\ + |(__APM32_USB_DEVICE_VERSION_SUB1 << 16)\ + |(__APM32_USB_DEVICE_VERSION_SUB2 << 8 )\ + |(__APM32_USB_DEVICE_VERSION_RC)) + +#define USBD_DEVICE_DEFAULT_ADDRESS 0 +#define USBD_EP0_PACKET_MAX_SIZE 64 + +/**@} end of group USBD_Core_Macros*/ + +/** @defgroup USBD_Core_Enumerates Enumerates + @{ + */ + +/** + * @brief USB device operation status + */ +typedef enum +{ + USBD_OK, + USBD_BUSY, + USBD_FAIL, +} USBD_STA_T; + +/** + * @brief USB device speed type + */ +typedef enum +{ + USBD_SPEED_FS, + USBD_SPEED_HS, +} USBD_SPEED_T; + +/** + * @brief USB device speed + */ +typedef enum +{ + USBD_DEVICE_SPEED_HS, + USBD_DEVICE_SPEED_FS, + USBD_DEVICE_SPEED_LS +} USBD_DEVICE_SPEED_T; + +/** + * @brief USB device state + */ +typedef enum +{ + USBD_DEV_IDLE, + USBD_DEV_DEFAULT, + USBD_DEV_ADDRESS, + USBD_DEV_CONFIGURE, + USBD_DEV_SUSPEND, +} USBD_DEV_STA_T; + +/** + * @brief USB device EP0 state + */ +typedef enum +{ + USBD_DEV_EP0_IDLE, + USBD_DEV_EP0_SETUP, + USBD_DEV_EP0_DATA_IN, + USBD_DEV_EP0_DATA_OUT, + USBD_DEV_EP0_STATUS_IN, + USBD_DEV_EP0_STATUS_OUT, + USBD_DEV_EP0_STALL, +} USBD_DEV_EP0_STA_T; + +/** + * @brief USB device request type + */ +typedef enum +{ + USBD_REQ_TYPE_STANDARD = 0, + USBD_REQ_TYPE_CLASS, + USBD_REQ_TYPE_VENDOR, + USBD_REQ_TYPE_RESERVED +} USBD_DEV_REQ_TYPE_T; + +/** + * @brief USB device feature request type + */ +typedef enum +{ + USBD_FEATURE_SELECTOR_ENDPOINT_HALT, + USBD_FEATURE_REMOTE_WAKEUP, + USBD_FEATURE_TEST_MODE, +} USBD_REQ_FEATURE_T; + +/** + * @brief USB device status configuration type + */ +typedef enum +{ + USBD_CFG_NONE, + USBD_CFG_SELF_POWER, + USBD_CFG_REMOTE_WAKEUP, +} USBD_REQ_CFG_T; + +/** + * @brief USB standard device standard requests type + */ +typedef enum +{ + USBD_STD_GET_STATUS = 0, + USBD_STD_CLEAR_FEATURE = 1, + USBD_STD_RESERVED1 = 2, + USBD_STD_SET_FEATURE = 3, + USBD_STD_RESERVED2 = 4, + USBD_STD_SET_ADDRESS = 5, + USBD_STD_GET_DESCRIPTOR = 6, + USBD_STD_SET_DESCRIPTOR = 7, + USBD_STD_GET_CONFIGURATION = 8, + USBD_STD_SET_CONFIGURATION = 9, + USBD_STD_GET_INTERFACE = 10, + USBD_STD_SET_INTERFACE = 11, + USBD_STD_SYNCH_FRAME = 12, + USBD_STD_CNT, /* devDesc = usbDevDesc; + } + + /* Register class function */ + if (usbDevClass == NULL) + { + usbStatus = USBD_FAIL; + return usbStatus; + } + else + { + usbInfo->devClass[usbInfo->classNum++] = usbDevClass; + } + + /* Register user application */ + usbInfo->userCallback = userCallbackFunc; + + usbInfo->devState = USBD_DEV_DEFAULT; + /* Set USB device speed */ + usbInfo->devSpeed = usbDevSpeed; + + /* Init USB hardware */ + USBD_HardwareInit(usbInfo); + + return usbStatus; +} + +/*! + * @brief USB device core de-init + * + * @param usbInfo : usb handler information + * + * @retval usb device status + */ +USBD_STA_T USBD_DeInit(USBD_INFO_T* usbInfo) +{ + USBD_STA_T usbStatus = USBD_OK; + + usbInfo->devState = USBD_DEV_DEFAULT; + usbInfo->classNum = 0; + + if(usbInfo->devClass[0] != NULL) + { + usbInfo->devClass[0]->ClassDeInitHandler(usbInfo, usbInfo->devCfg); + } + + if(usbInfo->dataPoint != NULL) + { + USBD_StopCallback(usbInfo); + + USBD_StopDeviceCallback(usbInfo); + } + + usbInfo->userCallback = NULL; + usbInfo->devDesc = NULL; + + /* Reset USB hardware */ + USBD_HardwareReset(usbInfo); + + return usbStatus; +} + +/*! + * @brief USB device set speed + * + * @param usbInfo : usb handler information + * + * @param speed : device speed + * + * @retval usb device status + */ +USBD_STA_T USBD_SetSpeed(USBD_INFO_T* usbInfo, USBD_DEVICE_SPEED_T speed) +{ + USBD_STA_T usbStatus = USBD_OK; + + if (speed == USBD_DEVICE_SPEED_FS) + { + usbInfo->devSpeed = USBD_SPEED_FS; + } + else + { + usbInfo->devSpeed = USBD_SPEED_HS; + } + + return usbStatus; +} + +/*! + * @brief USB device test mode handle + * + * @param usbInfo : usb handler information + * + * @retval usb device status + */ +USBD_STA_T USBD_TestModeHandler(USBD_INFO_T* usbInfo) +{ + USBD_STA_T usbStatus = USBD_OK; + + UNUSED(usbInfo); + + return usbStatus; +} + +/*! + * @brief USB device SETUP stage + * + * @param usbInfo : usb handler information + * + * @param setup : setup data + * + * @retval usb device status + */ +USBD_STA_T USBD_SetupStage(USBD_INFO_T* usbInfo, uint8_t* setup) +{ + USBD_STA_T usbStatus = USBD_OK; + + USBD_EP_INFO_T* ep; + + uint8_t recipient; + uint8_t reqType; + uint8_t request; + uint8_t classIndex; + uint8_t epAddr; + uint16_t reqWvalue; + uint16_t reqWLength; + + USBH_SetupReqParse(setup, &usbInfo->reqSetup); + + recipient = usbInfo->reqSetup.DATA_FIELD.bmRequest.REQ_TYPE_B.recipient; + reqType = usbInfo->reqSetup.DATA_FIELD.bmRequest.REQ_TYPE_B.type; + request = usbInfo->reqSetup.DATA_FIELD.bRequest; + reqWvalue = usbInfo->reqSetup.DATA_FIELD.wValue[0] | \ + usbInfo->reqSetup.DATA_FIELD.wValue[1] << 8; + reqWLength = usbInfo->reqSetup.DATA_FIELD.wLength[0] | \ + usbInfo->reqSetup.DATA_FIELD.wLength[1] << 8; + + usbInfo->devEp0State = USBD_DEV_EP0_SETUP; + + usbInfo->devEp0DataLen = usbInfo->reqSetup.DATA_FIELD.wLength[0] | \ + usbInfo->reqSetup.DATA_FIELD.wLength[1] << 8; + + switch (recipient) + { + case USBD_RECIPIENT_DEVICE: + switch (reqType) + { + case USBD_REQ_TYPE_STANDARD: + if (request >= USBD_STD_CNT) + { + USBD_REQ_CtrlError(usbInfo, &usbInfo->reqSetup); + } + else + { + /* Standard device request */ + if (USBD_StdDevReqHandler[request] != NULL) + { + USBD_StdDevReqHandler[request](usbInfo, &usbInfo->reqSetup); + } + } + break; + + case USBD_REQ_TYPE_CLASS: + case USBD_REQ_TYPE_VENDOR: + usbInfo->devClass[usbInfo->classID]->ClassSetup(usbInfo, &usbInfo->reqSetup); + break; + + default: + USBD_REQ_CtrlError(usbInfo, &usbInfo->reqSetup); + break; + } + break; + + case USBD_RECIPIENT_INTERFACE: + switch (reqType) + { + case USBD_REQ_TYPE_STANDARD: + case USBD_REQ_TYPE_CLASS: + case USBD_REQ_TYPE_VENDOR: + switch (usbInfo->devState) + { + case USBD_DEV_DEFAULT: + case USBD_DEV_ADDRESS: + case USBD_DEV_CONFIGURE: + if(request == USBD_VEN_REQ_MS_CODE) + { + usbInfo->devClass[usbInfo->classID]->ClassSetup(usbInfo, &usbInfo->reqSetup); + } + else + { + if (usbInfo->reqSetup.DATA_FIELD.wIndex[0] <= USBD_SUP_INTERFACE_MAX_NUM) + { + /* Add multi class support */ + classIndex = 0; + if ((classIndex != 0xFF) && (classIndex < USBD_SUP_CLASS_MAX_NUM)) + { + usbInfo->classID = classIndex; + + if (usbInfo->devClass[classIndex]->ClassSetup != NULL) + { + usbStatus = usbInfo->devClass[classIndex]->ClassSetup(usbInfo, &usbInfo->reqSetup); + } + else + { + usbStatus = USBD_FAIL; + } + } + else + { + usbStatus = USBD_FAIL; + } + + if ((usbStatus == USBD_OK) && (reqWLength == 0)) + { + USBD_CtrlSendStatus(usbInfo); + } + } + else + { + USBD_REQ_CtrlError(usbInfo, &usbInfo->reqSetup); + } + } + break; + + default: + USBD_REQ_CtrlError(usbInfo, &usbInfo->reqSetup); + break; + } + break; + + default: + USBD_REQ_CtrlError(usbInfo, &usbInfo->reqSetup); + break; + } + break; + + case USBD_RECIPIENT_ENDPOINT: + epAddr = usbInfo->reqSetup.DATA_FIELD.wIndex[0]; + + switch (reqType) + { + case USBD_REQ_TYPE_STANDARD: + switch (request) + { + case USBD_STD_GET_STATUS: + switch (usbInfo->devState) + { + case USBD_DEV_ADDRESS: + if ((epAddr != 0x00) && (epAddr != 0x80)) + { + USBD_REQ_CtrlError(usbInfo, &usbInfo->reqSetup); + break; + } + + if ((epAddr & 0x80) == 0x80) + { + ep = &usbInfo->devEpIn[epAddr & 0x7F]; + + } + else + { + ep = &usbInfo->devEpOut[epAddr & 0x7F]; + } + + ep->status = 0x0000; + + USBD_CtrlSendData(usbInfo, \ + (uint8_t*)&ep->status, \ + 2); + break; + + case USBD_DEV_CONFIGURE: + if ((epAddr & 0x80) == 0x80) + { + if (usbInfo->devEpIn[epAddr & 0x0F].useStatus == DISABLE) + { + USBD_REQ_CtrlError(usbInfo, &usbInfo->reqSetup); + break; + } + } + else + { + if (usbInfo->devEpOut[epAddr & 0x0F].useStatus == DISABLE) + { + USBD_REQ_CtrlError(usbInfo, &usbInfo->reqSetup); + break; + } + } + + if ((epAddr & 0x80) == 0x80) + { + ep = &usbInfo->devEpIn[epAddr & 0x7F]; + + } + else + { + ep = &usbInfo->devEpOut[epAddr & 0x7F]; + } + + if ((epAddr == 0x00) || epAddr == 0x80) + { + ep->status = 0x0000; + } + else if (USBD_EP_ReadStallStatusCallback(usbInfo, epAddr)) + { + ep->status = 0x0001; + } + else + { + ep->status = 0x0000; + } + + USBD_CtrlSendData(usbInfo, \ + (uint8_t*)&ep->status, \ + 2); + break; + + default: + USBD_REQ_CtrlError(usbInfo, &usbInfo->reqSetup); + break; + } + break; + + case USBD_STD_CLEAR_FEATURE: + switch (usbInfo->devState) + { + case USBD_DEV_ADDRESS: + if ((epAddr != 0x00) && (epAddr != 0x80)) + { + USBD_EP_StallCallback(usbInfo, epAddr); + USBD_EP_StallCallback(usbInfo, 0x80); + } + else + { + USBD_REQ_CtrlError(usbInfo, &usbInfo->reqSetup); + } + break; + + case USBD_DEV_CONFIGURE: + if (reqWvalue == USBD_FEATURE_SELECTOR_ENDPOINT_HALT) + { + if ((epAddr & 0x7F) != 0x00) + { + USBD_EP_ClearStallCallback(usbInfo, epAddr); + } + + USBD_CtrlSendStatus(usbInfo); + + /* Add multi class support */ + classIndex = 0; + if ((classIndex != 0xFF) && (classIndex < USBD_SUP_CLASS_MAX_NUM)) + { + usbInfo->classID = classIndex; + + if (usbInfo->devClass[classIndex]->ClassSetup != NULL) + { + usbStatus = usbInfo->devClass[classIndex]->ClassSetup(usbInfo, &usbInfo->reqSetup); + } + } + } + break; + + default: + USBD_REQ_CtrlError(usbInfo, &usbInfo->reqSetup); + break; + } + break; + + case USBD_STD_SET_FEATURE: + switch (usbInfo->devState) + { + case USBD_DEV_ADDRESS: + if ((epAddr != 0x00) && (epAddr != 0x80)) + { + USBD_EP_StallCallback(usbInfo, epAddr); + USBD_EP_StallCallback(usbInfo, 0x80); + } + else + { + USBD_REQ_CtrlError(usbInfo, &usbInfo->reqSetup); + } + break; + + case USBD_DEV_CONFIGURE: + if (reqWvalue == USBD_FEATURE_SELECTOR_ENDPOINT_HALT) + { + if ((epAddr != 0x00) && (epAddr != 0x80) && \ + (reqWLength == 0x00)) + { + USBD_EP_StallCallback(usbInfo, epAddr); + } + } + + USBD_CtrlSendStatus(usbInfo); + break; + + default: + USBD_REQ_CtrlError(usbInfo, &usbInfo->reqSetup); + break; + } + break; + + default: + USBD_REQ_CtrlError(usbInfo, &usbInfo->reqSetup); + break; + } + break; + + case USBD_REQ_TYPE_CLASS: + case USBD_REQ_TYPE_VENDOR: + /* Add multi class support */ + classIndex = 0; + if ((classIndex != 0xFF) && (classIndex < USBD_SUP_CLASS_MAX_NUM)) + { + usbInfo->classID = classIndex; + + if (usbInfo->devClass[classIndex]->ClassSetup != NULL) + { + usbStatus = usbInfo->devClass[classIndex]->ClassSetup(usbInfo, &usbInfo->reqSetup); + } + } + break; + + default: + USBD_REQ_CtrlError(usbInfo, &usbInfo->reqSetup); + break; + } + break; + + default: + usbStatus = USBD_EP_StallCallback(usbInfo, usbInfo->reqSetup.DATA_FIELD.bmRequest.REQ_TYPE_B.dir); + break; + } + + return usbStatus; +} + +/*! + * @brief USB device data OUT stage + * + * @param usbInfo : usb handler information + * + * @param epNum : endpoint number + * + * @param buffer : data buffer + * + * @retval usb device status + */ +USBD_STA_T USBD_DataOutStage(USBD_INFO_T* usbInfo, uint8_t epNum, uint8_t* buffer) +{ + USBD_STA_T usbStatus = USBD_OK; + uint32_t ctrlLenTemp; + uint8_t classIndex; + + if (epNum != 0) + { + /* Add multi class support */ + classIndex = 0; + + if ((classIndex != 0xFF) && (classIndex < USBD_SUP_CLASS_MAX_NUM)) + { + if (usbInfo->devState == USBD_DEV_CONFIGURE) + { + if (usbInfo->devClass[classIndex]->ClassDataOut != NULL) + { + usbInfo->classNum = classIndex; + usbStatus = usbInfo->devClass[classIndex]->ClassDataOut(usbInfo, epNum); + + if (usbStatus != USBD_OK) + { + return usbStatus; + } + } + } + } + } + /* EP0 */ + else + { + switch (usbInfo->devEp0State) + { + case USBD_DEV_EP0_DATA_OUT: + if (usbInfo->devEpOut[USBD_EP_0].remainLen > usbInfo->devEpOut[USBD_EP_0].mp) + { + usbInfo->devEpOut[USBD_EP_0].remainLen -= usbInfo->devEpOut[USBD_EP_0].mp; + + ctrlLenTemp = usbInfo->devEpOut[USBD_EP_0].remainLen < usbInfo->devEpOut[USBD_EP_0].mp ? \ + usbInfo->devEpOut[USBD_EP_0].remainLen : usbInfo->devEpOut[USBD_EP_0].mp; + + USBD_CtrlReceiveData(usbInfo, buffer, ctrlLenTemp); + } + else + { + switch (usbInfo->reqSetup.DATA_FIELD.bmRequest.REQ_TYPE_B.recipient) + { + case USBD_RECIPIENT_DEVICE: + classIndex = 0; + break; + + case USBD_RECIPIENT_INTERFACE: + /* Add multi class support */ + classIndex = 0; + break; + + case USBD_RECIPIENT_ENDPOINT: + /* Add multi class support */ + classIndex = 0; + break; + + default: + classIndex = 0; + break; + } + + if (classIndex < USBD_SUP_CLASS_MAX_NUM) + { + if (usbInfo->devState == USBD_DEV_CONFIGURE) + { + if (usbInfo->devClass[classIndex]->ClassRxEP0 != NULL) + { + usbInfo->classNum = classIndex; + usbInfo->devClass[classIndex]->ClassRxEP0(usbInfo); + } + } + } + + USBD_CtrlSendStatus(usbInfo); + } + break; + + default: + + break; + } + } + + return usbStatus; +} + +/*! + * @brief USB device data IN stage + * + * @param usbInfo : usb handler information + * + * @param epNum : endpoint number + * + * @param buffer : data buffer + * + * @retval usb device status + */ +USBD_STA_T USBD_DataInStage(USBD_INFO_T* usbInfo, uint8_t epNum, uint8_t* buffer) +{ + USBD_STA_T usbStatus = USBD_OK; + uint8_t classIndex; + USBD_EP_INFO_T* ep; + + if (epNum) + { + /* Add multi class support */ + classIndex = 0; + if ((classIndex != 0xFF) && (classIndex < USBD_SUP_CLASS_MAX_NUM)) + { + if (usbInfo->devState == USBD_DEV_CONFIGURE) + { + if (usbInfo->devClass[classIndex]->ClassDataIn != NULL) + { + usbInfo->classID = classIndex; + + usbStatus = usbInfo->devClass[classIndex]->ClassDataIn(usbInfo, epNum); + + if (usbStatus != USBD_OK) + { + return usbStatus; + } + } + } + } + } + else + { + ep = &usbInfo->devEpIn[USBD_EP_0]; + + if (usbInfo->devEp0State == USBD_DEV_EP0_DATA_IN) + { + if (ep->remainLen > ep->mp) + { + ep->remainLen -= ep->mp; + + USBD_CtrlSendNextData(usbInfo, buffer, ep->remainLen); + + USBD_EP_ReceiveCallback(usbInfo, USBD_EP_0, NULL, 0); + } + else + { + /* last packet is MPS multiple data, so need to send ZLP packet */ + if ((ep->mp == ep->remainLen) && \ + (ep->length >= ep->mp) && \ + (ep->length < usbInfo->devEp0DataLen)) + { + USBD_CtrlSendNextData(usbInfo, NULL, 0); + + usbInfo->devEp0DataLen = 0; + + USBD_EP_ReceiveCallback(usbInfo, USBD_EP_0, NULL, 0); + } + else + { + classIndex = 0; + + if (usbInfo->devState == USBD_DEV_CONFIGURE) + { + if (usbInfo->devClass[USBD_EP_0]->ClassTxEP0 != NULL) + { + usbInfo->classID = classIndex; + usbInfo->devClass[USBD_EP_0]->ClassTxEP0(usbInfo); + } + } + USBD_EP_StallCallback(usbInfo, 0x80); + USBD_CtrlReceiveStatus(usbInfo); + } + } + } + else + { + + } + + if (usbInfo->devTestModeStatus == ENABLE) + { + USBD_TestModeHandler(usbInfo); + usbInfo->devTestModeStatus = DISABLE; + } + } + + return usbStatus; +} + +/*! + * @brief USB device resume + * + * @param usbInfo : usb handler information + * + * @retval usb device status + */ +USBD_STA_T USBD_Resume(USBD_INFO_T* usbInfo) +{ + USBD_STA_T usbStatus = USBD_OK; + + usbInfo->userCallback(usbInfo, USBD_USER_RESUME); + + if (usbInfo->devState == USBD_DEV_SUSPEND) + { + usbInfo->devState = usbInfo->preDevState; + } + + return usbStatus; +} + +/*! + * @brief USB device suspend + * + * @param usbInfo : usb handler information + * + * @retval usb device status + */ +USBD_STA_T USBD_Suspend(USBD_INFO_T* usbInfo) +{ + USBD_STA_T usbStatus = USBD_OK; + + usbInfo->userCallback(usbInfo, USBD_USER_SUSPEND); + + usbInfo->preDevState = usbInfo->devState; + usbInfo->devState = USBD_DEV_SUSPEND; + + return usbStatus; +} + +/*! + * @brief USB device reset + * + * @param usbInfo : usb handler information + * + * @retval usb device status + */ +USBD_STA_T USBD_Reset(USBD_INFO_T* usbInfo) +{ + USBD_STA_T usbStatus = USBD_OK; + + usbInfo->devCfg = 0; + usbInfo->devTestModeStatus = 0; + usbInfo->devRemoteWakeUpStatus = 0; + usbInfo->devState = USBD_DEV_DEFAULT; + usbInfo->devEp0State = USBD_DEV_EP0_IDLE; + + if ((usbInfo->devClass[0] != NULL) && \ + (usbInfo->devClass[0]->ClassDeInitHandler != NULL)) + { + usbStatus = usbInfo->devClass[0]->ClassDeInitHandler(usbInfo, \ + usbInfo->devCfg); + if (usbStatus != USBD_OK) + { + usbStatus = USBD_FAIL; + } + } + + /* Open EP0 OUT */ + USBD_EP_OpenCallback(usbInfo, 0x00, EP_TYPE_CONTROL, USBD_EP0_PACKET_MAX_SIZE); + usbInfo->devEpOut[0x00 & 0x0F].useStatus = ENABLE; + usbInfo->devEpOut[0].mp = USBD_EP0_PACKET_MAX_SIZE; + + /* Open EP0 IN */ + USBD_EP_OpenCallback(usbInfo, 0x80, EP_TYPE_CONTROL, USBD_EP0_PACKET_MAX_SIZE); + usbInfo->devEpIn[0x80 & 0x0F].useStatus = ENABLE; + usbInfo->devEpIn[0].mp = USBD_EP0_PACKET_MAX_SIZE; + + usbInfo->userCallback(usbInfo, USBD_USER_RESET); + + return usbStatus; +} + +/*! + * @brief USB device SOF handler + * + * @param usbInfo : usb handler information + * + * @retval usb device status + */ +USBD_STA_T USBD_HandleSOF(USBD_INFO_T* usbInfo) +{ + USBD_STA_T usbStatus = USBD_OK; + + if (usbInfo->devState == USBD_DEV_CONFIGURE) + { + if ((usbInfo->devClass[0] != NULL) && \ + usbInfo->devClass[0]->ClassSofHandler != NULL) + { + usbInfo->devClass[0]->ClassSofHandler(usbInfo); + } + } + + return usbStatus; +} + +/*! + * @brief USB device ISO IN in complete handler + * + * @param usbInfo : usb handler information + * + * @param epNum : endpoint number + * + * @retval usb device status + */ +USBD_STA_T USBD_IsoInInComplete(USBD_INFO_T* usbInfo, uint8_t epNum) +{ + USBD_STA_T usbStatus = USBD_OK; + + if (usbInfo->devClass[usbInfo->classID] == NULL) + { + return USBD_FAIL; + } + + if (usbInfo->devState == USBD_DEV_CONFIGURE) + { + if (usbInfo->devClass[usbInfo->classID]->ClassIsoInIncomplete != NULL) + { + usbInfo->devClass[usbInfo->classID]->ClassIsoInIncomplete(usbInfo, epNum); + } + } + + return usbStatus; +} + +/*! + * @brief USB device ISO OUT in complete handler + * + * @param usbInfo : usb handler information + * + * @param epNum : endpoint number + * + * @retval usb device status + */ +USBD_STA_T USBD_IsoOutInComplete(USBD_INFO_T* usbInfo, uint8_t epNum) +{ + USBD_STA_T usbStatus = USBD_OK; + + if (usbInfo->devClass[usbInfo->classID] == NULL) + { + return USBD_FAIL; + } + + if (usbInfo->devState == USBD_DEV_CONFIGURE) + { + if (usbInfo->devClass[usbInfo->classID]->ClassIsoOutIncomplete != NULL) + { + usbInfo->devClass[usbInfo->classID]->ClassIsoOutIncomplete(usbInfo, epNum); + } + } + + return usbStatus; +} + +/*! + * @brief USB device connect handler + * + * @param usbInfo : usb handler information + * + * @retval usb device status + */ +USBD_STA_T USBD_Connect(USBD_INFO_T* usbInfo) +{ + USBD_STA_T usbStatus = USBD_OK; + + usbInfo->userCallback(usbInfo, USBD_USER_CONNECT); + + return usbStatus; +} + +/*! + * @brief USB device disconnect handler + * + * @param usbInfo : usb handler information + * + * @retval usb device status + */ +USBD_STA_T USBD_Disconnect(USBD_INFO_T* usbInfo) +{ + USBD_STA_T usbStatus = USBD_OK; + uint8_t reqStatus = USBD_BUSY; + + usbInfo->devState = USBD_DEV_DEFAULT; + + if (usbInfo->devClass[0] != NULL) + { + reqStatus = usbInfo->devClass[0]->ClassDeInitHandler(usbInfo, usbInfo->devCfg); + + switch (reqStatus) + { + case USBD_OK: + break; + + default: + usbStatus = USBD_FAIL; + break; + } + } + + usbInfo->userCallback(usbInfo, USBD_USER_DISCONNECT); + + return usbStatus; +} + +/*! + * @brief USB device open EP callback + * + * @param usbInfo : usb handler information + * + * @param epAddr: endpoint address + * + * @param epType: endpoint type + * + * @param epMps: endpoint maxinum of packet size + * + * @retval None + */ +__weak void USBD_EP_OpenCallback(USBD_INFO_T* usbInfo, uint8_t epAddr, \ + uint8_t epType, uint16_t epMps) +{ + /* callback interface */ + UNUSED(usbInfo); + UNUSED(epAddr); + UNUSED(epType); + UNUSED(epMps); +} + +/*! + * @brief USB device close EP callback + * + * @param usbInfo : usb handler information + * + * @param epAddr: endpoint address + * + * @retval None + */ +__weak void USBD_EP_CloseCallback(USBD_INFO_T* usbInfo, uint8_t epAddr) +{ + /* callback interface */ + UNUSED(usbInfo); + UNUSED(epAddr); +} + +/*! + * @brief USB device set EP to stall status callback + * + * @param usbInfo : usb handler information + * + * @param epAddr: endpoint address + * + * @retval None + */ +__weak USBD_STA_T USBD_EP_StallCallback(USBD_INFO_T* usbInfo, uint8_t epAddr) +{ + USBD_STA_T usbStatus = USBD_OK; + + /* callback interface */ + UNUSED(usbInfo); + UNUSED(epAddr); + + return usbStatus; +} + +/*! + * @brief USB device read EP last receive data size callback + * + * @param usbInfo : usb handler information + * + * @param epAddr: endpoint address + * + * @retval size of last receive data + */ +__weak uint32_t USBD_EP_ReadRxDataLenCallback(USBD_INFO_T* usbInfo, uint8_t epAddr) +{ + /* callback interface */ + UNUSED(usbInfo); + UNUSED(epAddr); + + return 0; +} + +/*! + * @brief USB device clear EP stall status callback + * + * @param usbInfo : usb handler information + * + * @param epAddr: endpoint address + * + * @retval None + */ +__weak USBD_STA_T USBD_EP_ClearStallCallback(USBD_INFO_T* usbInfo, uint8_t epAddr) +{ + USBD_STA_T usbStatus = USBD_OK; + + /* callback interface */ + UNUSED(usbInfo); + UNUSED(epAddr); + + return usbStatus; +} + +/*! + * @brief USB device read EP stall status callback + * + * @param usbInfo : usb handler information + * + * @param epAddr: endpoint address + * + * @retval Stall status + */ +__weak uint8_t USBD_EP_ReadStallStatusCallback(USBD_INFO_T* usbInfo, uint8_t epAddr) +{ + /* callback interface */ + UNUSED(usbInfo); + UNUSED(epAddr); + + return 0; +} + +/*! + * @brief USB device EP receive handler callback + * + * @param usbInfo : usb handler information + * + * @param epAddr : endpoint address + * + * @param buffer : data buffer + * + * @param length : length of data + * + * @retval usb device status + */ +__weak USBD_STA_T USBD_EP_ReceiveCallback(USBD_INFO_T* usbInfo, uint8_t epAddr, \ + uint8_t* buffer, uint32_t length) +{ + USBD_STA_T usbStatus = USBD_OK; + + /* Callback Interface */ + UNUSED(usbInfo); + UNUSED(epAddr); + UNUSED(buffer); + UNUSED(length); + + return usbStatus; +} + +/*! + * @brief USB device EP transfer handler callback + * + * @param usbInfo : usb handler information + * + * @param epAddr : endpoint address + * + * @param buffer : data buffer + * + * @param length : length of data + * + * @retval usb device status + */ +__weak USBD_STA_T USBD_EP_TransferCallback(USBD_INFO_T* usbInfo, uint8_t epAddr, \ + uint8_t* buffer, uint32_t length) +{ + USBD_STA_T usbStatus = USBD_OK; + + /* Callback Interface */ + UNUSED(usbInfo); + UNUSED(epAddr); + UNUSED(buffer); + UNUSED(length); + + return usbStatus; +} + +/*! + * @brief USB device flush EP handler callback + * + * @param usbInfo : usb handler information + * + * @param epAddr : endpoint address + * + * @retval usb device status + */ +__weak USBD_STA_T USBD_EP_FlushCallback(USBD_INFO_T* usbInfo, uint8_t epAddr) +{ + USBD_STA_T usbStatus = USBD_OK; + + /* Callback Interface */ + UNUSED(usbInfo); + UNUSED(epAddr); + + return usbStatus; +} + +/*! + * @brief USB device set device address handler callback + * + * @param usbInfo : usb handler information + * + * @param address : address + * + * @retval usb device status + */ +__weak USBD_STA_T USBD_SetDevAddressCallback(USBD_INFO_T* usbInfo, uint8_t address) +{ + USBD_STA_T usbStatus = USBD_OK; + + /* Callback Interface */ + UNUSED(usbInfo); + UNUSED(address); + + return usbStatus; +} + +/*! + * @brief USB device start handler callback + * + * @param usbInfo : usb handler information + * + * @retval None + */ +__weak void USBD_StartCallback(USBD_INFO_T* usbInfo) +{ + /* Callback Interface */ + UNUSED(usbInfo); +} + +/*! + * @brief USB device stop handler callback + * + * @param usbInfo : usb handler information + * + * @retval None + */ +__weak void USBD_StopCallback(USBD_INFO_T* usbInfo) +{ + /* Callback Interface */ + UNUSED(usbInfo); +} + +/*! + * @brief USB device stop device mode handler callback + * + * @param usbInfo : usb handler information + * + * @retval None + */ +__weak void USBD_StopDeviceCallback(USBD_INFO_T* usbInfo) +{ + /* Callback Interface */ + UNUSED(usbInfo); +} + +/**@} end of group USBD_Core_Functions */ +/**@} end of group USBD_Core */ +/**@} end of group APM32_USB_Library */ diff --git a/lib/main/APM32F4/Middlewares/APM32_USB_Library/Device/Core/Src/usbd_dataXfer.c b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Device/Core/Src/usbd_dataXfer.c new file mode 100644 index 0000000000..e8ebf2fca8 --- /dev/null +++ b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Device/Core/Src/usbd_dataXfer.c @@ -0,0 +1,173 @@ +/*! + * @file usbd_dataXfer.c + * + * @brief USB device input and output hander function + * + * @version V1.0.0 + * + * @date 2023-01-16 + * + * @attention + * + * Copyright (C) 2023 Geehy Semiconductor + * + * You may not use this file except in compliance with the + * GEEHY COPYRIGHT NOTICE (GEEHY SOFTWARE PACKAGE LICENSE). + * + * The program is only for reference, which is distributed in the hope + * that it will be useful and instructional for customers to develop + * their software. Unless required by applicable law or agreed to in + * writing, the program is distributed on an "AS IS" BASIS, WITHOUT + * ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied. + * See the GEEHY SOFTWARE PACKAGE LICENSE for the governing permissions + * and limitations under the License. + */ + +/* Includes */ +#include "usbd_dataXfer.h" + +/** @addtogroup APM32_USB_Library + @{ + */ + +/** @addtogroup USBD_Core + @{ + */ + +/** @defgroup USBD_Core_Functions Functions + @{ + */ + +/*! + * @brief Parse setup request + * + * @param buffer : parse buffer + * + * @param req : setup request data + * + * @retval usb device status + */ +USBD_STA_T USBH_SetupReqParse(uint8_t* buffer, USBD_REQ_SETUP_T* req) +{ + USBD_STA_T usbStatus = USBD_OK; + + /* bmRequestType */ + req->REQ_DATA[0] = *(uint8_t*)(buffer + 0); + + req->DATA_FIELD.bRequest = *(uint8_t*)(buffer + 1); + + req->DATA_FIELD.wValue[0] = *(uint8_t*)(buffer + 2); + req->DATA_FIELD.wValue[1] = *(uint8_t*)(buffer + 3); + + req->DATA_FIELD.wIndex[0] = *(uint8_t*)(buffer + 4); + req->DATA_FIELD.wIndex[1] = *(uint8_t*)(buffer + 5); + + req->DATA_FIELD.wLength[0] = *(uint8_t*)(buffer + 6); + req->DATA_FIELD.wLength[1] = *(uint8_t*)(buffer + 7); + + return usbStatus; +} + +/*! + * @brief USB device continue receive CTRL data + * + * @param usbInfo : usb handler information + * + * @param buffer : data buffer + * + * @param length : length of data + * + * @retval usb device status + */ +USBD_STA_T USBD_CtrlReceiveData(USBD_INFO_T* usbInfo, uint8_t* buffer, uint32_t length) +{ + USBD_STA_T usbStatus = USBD_OK; + + USBD_EP_ReceiveCallback(usbInfo, USBD_EP_0, buffer, length); + + return usbStatus; +} + +/*! + * @brief USB device send CTRL status + * + * @param usbInfo : usb handler information + * + * @retval usb device status + */ +USBD_STA_T USBD_CtrlSendStatus(USBD_INFO_T* usbInfo) +{ + USBD_STA_T usbStatus = USBD_OK; + + usbInfo->devEp0State = USBD_DEV_EP0_STATUS_IN; + + USBD_EP_TransferCallback(usbInfo, USBD_EP_0, NULL, 0); + + return usbStatus; +} + +/*! + * @brief USB device receive CTRL status + * + * @param usbInfo : usb handler information + * + * @retval usb device status + */ +USBD_STA_T USBD_CtrlReceiveStatus(USBD_INFO_T* usbInfo) +{ + USBD_STA_T usbStatus = USBD_OK; + + usbInfo->devEp0State = USBD_DEV_EP0_STATUS_OUT; + + USBD_EP_ReceiveCallback(usbInfo, USBD_EP_0, NULL, 0); + + return usbStatus; +} + +/*! + * @brief USB device send CTRL data + * + * @param usbInfo : usb handler information + * + * @param buffer : data buffer + * + * @param length : length of data + * + * @retval usb device status + */ +USBD_STA_T USBD_CtrlSendData(USBD_INFO_T* usbInfo, uint8_t* buffer, uint32_t length) +{ + USBD_STA_T usbStatus = USBD_OK; + + usbInfo->devEp0State = USBD_DEV_EP0_DATA_IN; + usbInfo->devEpIn[USBD_EP_0].length = length; + usbInfo->devEpIn[USBD_EP_0].remainLen = length; + + USBD_EP_TransferCallback(usbInfo, USBD_EP_0, buffer, length); + + return usbStatus; +} + +/*! + * @brief USB device send next CTRL data + * + * @param usbInfo : usb handler information + * + * @param buffer : data buffer + * + * @param length : length of data + * + * @retval usb device status + */ +USBD_STA_T USBD_CtrlSendNextData(USBD_INFO_T* usbInfo, uint8_t* buffer, uint32_t length) +{ + USBD_STA_T usbStatus = USBD_OK; + + USBD_EP_TransferCallback(usbInfo, USBD_EP_0, buffer, length); + + return usbStatus; +} + +/**@} end of group USBD_Core_Functions */ +/**@} end of group USBD_Core */ +/**@} end of group APM32_USB_Library */ diff --git a/lib/main/APM32F4/Middlewares/APM32_USB_Library/Device/Core/Src/usbd_stdReq.c b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Device/Core/Src/usbd_stdReq.c new file mode 100644 index 0000000000..4b31733d7d --- /dev/null +++ b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Device/Core/Src/usbd_stdReq.c @@ -0,0 +1,697 @@ +/*! + * @file usbd_stdReq.c + * + * @brief USB standard request process + * + * @version V1.0.0 + * + * @date 2023-01-16 + * + * @attention + * + * Copyright (C) 2023 Geehy Semiconductor + * + * You may not use this file except in compliance with the + * GEEHY COPYRIGHT NOTICE (GEEHY SOFTWARE PACKAGE LICENSE). + * + * The program is only for reference, which is distributed in the hope + * that it will be useful and instructional for customers to develop + * their software. Unless required by applicable law or agreed to in + * writing, the program is distributed on an "AS IS" BASIS, WITHOUT + * ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied. + * See the GEEHY SOFTWARE PACKAGE LICENSE for the governing permissions + * and limitations under the License. + */ + +/* Includes */ +#include "usbd_stdReq.h" +#include "usbd_dataXfer.h" + +/** @addtogroup APM32_USB_Library + @{ + */ + +/** @addtogroup USBD_Core + @{ + */ + +/** @defgroup USBD_Core_Functions Functions + @{ + */ + +static USBD_STA_T USBD_REQ_GetStatus(USBD_INFO_T* usbInfo, USBD_REQ_SETUP_T* req); +static USBD_STA_T USBD_REQ_ClearFeature(USBD_INFO_T* usbInfo, USBD_REQ_SETUP_T* req); +static USBD_STA_T USBD_REQ_SetFeature(USBD_INFO_T* usbInfo, USBD_REQ_SETUP_T* req); +static USBD_STA_T USBD_REQ_SetAddress(USBD_INFO_T* usbInfo, USBD_REQ_SETUP_T* req); +static USBD_STA_T USBD_REQ_GetDesc(USBD_INFO_T* usbInfo, USBD_REQ_SETUP_T* req); +static USBD_STA_T USBD_REQ_SetDesc(USBD_INFO_T* usbInfo, USBD_REQ_SETUP_T* req); +static USBD_STA_T USBD_REQ_GetCfg(USBD_INFO_T* usbInfo, USBD_REQ_SETUP_T* req); +static USBD_STA_T USBD_REQ_SetCfg(USBD_INFO_T* usbInfo, USBD_REQ_SETUP_T* req); +static USBD_STA_T USBD_REQ_GetItf(USBD_INFO_T* usbInfo, USBD_REQ_SETUP_T* req); +static USBD_STA_T USBD_REQ_SetItf(USBD_INFO_T* usbInfo, USBD_REQ_SETUP_T* req); +static USBD_STA_T USBD_REQ_SyncFrame(USBD_INFO_T* usbInfo, USBD_REQ_SETUP_T* req); + +/**@} end of group USBD_Core_Functions */ + +/** @defgroup USBD_Core_Structures Structures + @{ + */ + +/* Standard device request function match with USBD_STD_REQ_TYPE_T */ +USBD_StdDevReqCallback_T USBD_StdDevReqHandler[] = +{ + USBD_REQ_GetStatus, + USBD_REQ_ClearFeature, + NULL, + USBD_REQ_SetFeature, + NULL, + USBD_REQ_SetAddress, + USBD_REQ_GetDesc, + USBD_REQ_SetDesc, + USBD_REQ_GetCfg, + USBD_REQ_SetCfg, + USBD_REQ_GetItf, + USBD_REQ_SetItf, + USBD_REQ_SyncFrame, +}; + +/**@} end of group USBD_Core_Structures*/ + +/** @defgroup USBD_Core_Functions Functions + @{ + */ + +/*! + * @brief USB device get status request + * + * @param usbInfo : usb handler information + * + * @param setup : setup data + * + * @retval usb device status + */ +static USBD_STA_T USBD_REQ_GetStatus(USBD_INFO_T* usbInfo, USBD_REQ_SETUP_T* req) +{ + USBD_STA_T usbStatus = USBD_OK; + + uint16_t wLength = req->DATA_FIELD.wLength[0] | req->DATA_FIELD.wLength[1] << 8; + + switch (usbInfo->devState) + { + case USBD_DEV_DEFAULT: + case USBD_DEV_ADDRESS: + case USBD_DEV_CONFIGURE: + if (wLength != 0x02) + { + USBD_REQ_CtrlError(usbInfo, req); + break; + } +#if USBD_SUP_SELF_PWR + usbInfo->devCfgStatus = USBD_CFG_SELF_POWER; +#else + usbInfo->devCfgStatus = USBD_CFG_NONE; +#endif + + if (usbInfo->devRemoteWakeUpStatus == ENABLE) + { + usbInfo->devCfgStatus |= USBD_CFG_REMOTE_WAKEUP; + } + + USBD_CtrlSendData(usbInfo, (uint8_t*)&usbInfo->devCfgStatus, 2); + + break; + + default: + USBD_REQ_CtrlError(usbInfo, req); + break; + } + + return usbStatus; +} + +/*! + * @brief USB device clear feature request + * + * @param usbInfo : usb handler information + * + * @param setup : setup data + * + * @retval usb device status + */ +static USBD_STA_T USBD_REQ_ClearFeature(USBD_INFO_T* usbInfo, USBD_REQ_SETUP_T* req) +{ + USBD_STA_T usbStatus = USBD_OK; + + uint16_t wValue = req->DATA_FIELD.wValue[0] | req->DATA_FIELD.wValue[1] << 8; + + switch (usbInfo->devState) + { + case USBD_DEV_DEFAULT: + case USBD_DEV_ADDRESS: + case USBD_DEV_CONFIGURE: + if (wValue == USBD_FEATURE_REMOTE_WAKEUP) + { + usbInfo->devRemoteWakeUpStatus = DISABLE; + USBD_CtrlSendStatus(usbInfo); + } + break; + + default: + USBD_REQ_CtrlError(usbInfo, req); + break; + } + + return usbStatus; +} + +/*! + * @brief USB device set feature request + * + * @param usbInfo : usb handler information + * + * @param setup : setup data + * + * @retval usb device status + */ +static USBD_STA_T USBD_REQ_SetFeature(USBD_INFO_T* usbInfo, USBD_REQ_SETUP_T* req) +{ + USBD_STA_T usbStatus = USBD_OK; + + uint16_t wValue = req->DATA_FIELD.wValue[0] | req->DATA_FIELD.wValue[1] << 8; + + switch (wValue) + { + case USBD_FEATURE_REMOTE_WAKEUP: + usbInfo->devRemoteWakeUpStatus = ENABLE; + USBD_CtrlSendStatus(usbInfo); + break; + + case USBD_FEATURE_TEST_MODE: + usbInfo->devTestModeStatus = req->DATA_FIELD.wIndex[1]; + USBD_CtrlSendStatus(usbInfo); + break; + + default: + USBD_REQ_CtrlError(usbInfo, req); + break; + } + + return usbStatus; +} + +/*! + * @brief USB device set address request + * + * @param usbInfo : usb handler information + * + * @param setup : setup data + * + * @retval usb device status + */ +static USBD_STA_T USBD_REQ_SetAddress(USBD_INFO_T* usbInfo, USBD_REQ_SETUP_T* req) +{ + USBD_STA_T usbStatus = USBD_OK; + + uint16_t wIndex = req->DATA_FIELD.wIndex[0] | req->DATA_FIELD.wIndex[1] << 8; + uint16_t wLength = req->DATA_FIELD.wLength[0] | req->DATA_FIELD.wLength[1] << 8; + uint16_t wValue = req->DATA_FIELD.wValue[0] | req->DATA_FIELD.wValue[1] << 8; + uint8_t devAddr = wValue & 0x7F; + + if ((wIndex == 0) && (wLength == 0) && (wValue < 0x80)) + { + switch (usbInfo->devState) + { + case USBD_DEV_CONFIGURE: + USBD_REQ_CtrlError(usbInfo, req); + break; + + default: + usbInfo->devAddr = devAddr; + USBD_SetDevAddressCallback(usbInfo, devAddr); + + USBD_CtrlSendStatus(usbInfo); + + if (devAddr) + { + usbInfo->devState = USBD_DEV_ADDRESS; + } + else + { + usbInfo->devState = USBD_DEV_DEFAULT; + } + break; + } + } + else + { + USBD_REQ_CtrlError(usbInfo, req); + } + + return usbStatus; +} + +/*! + * @brief USB device get descriptor request + * + * @param usbInfo : usb handler information + * + * @param setup : setup data + * + * @retval usb device status + */ +static USBD_STA_T USBD_REQ_GetDesc(USBD_INFO_T* usbInfo, USBD_REQ_SETUP_T* req) +{ + USBD_STA_T usbStatus = USBD_OK; + USBD_DESC_INFO_T descInfo; + uint8_t reqError = 0; + uint16_t wLength = req->DATA_FIELD.wLength[0] | req->DATA_FIELD.wLength[1] << 8; + + switch (req->DATA_FIELD.wValue[1]) + { +#if USBD_SUP_LPM + case USBD_DESC_BOS: + if (usbInfo->devDesc->bosDescHandler != NULL) + { + descInfo = usbInfo->devDesc->bosDescHandler(usbInfo->devSpeed); + } + else + { + USBD_REQ_CtrlError(usbInfo, req); + reqError++; + } + break; +#endif + + case USBD_DESC_DEVICE: + descInfo = usbInfo->devDesc->deviceDescHandler(usbInfo->devSpeed); + break; + + case USBD_DESC_CONFIGURATION: + descInfo = usbInfo->devDesc->configDescHandler(usbInfo->devSpeed); + break; + + case USBD_DESC_STRING: + switch (req->DATA_FIELD.wValue[0]) + { + case USBD_DESC_STR_LANGID: + if (usbInfo->devDesc->langIdStrDescHandler != NULL) + { + descInfo = usbInfo->devDesc->langIdStrDescHandler(usbInfo->devSpeed); + } + else + { + USBD_REQ_CtrlError(usbInfo, req); + reqError++; + } + break; + + case USBD_DESC_STR_MFC: + if (usbInfo->devDesc->manufacturerStrDescHandler != NULL) + { + descInfo = usbInfo->devDesc->manufacturerStrDescHandler(usbInfo->devSpeed); + } + else + { + USBD_REQ_CtrlError(usbInfo, req); + reqError++; + } + break; + + case USBD_DESC_STR_PRODUCT: + if (usbInfo->devDesc->productStrDescHandler != NULL) + { + descInfo = usbInfo->devDesc->productStrDescHandler(usbInfo->devSpeed); + } + else + { + USBD_REQ_CtrlError(usbInfo, req); + reqError++; + } + break; + + case USBD_DESC_STR_SERIAL: + if (usbInfo->devDesc->serialStrDescHandler != NULL) + { + descInfo = usbInfo->devDesc->serialStrDescHandler(usbInfo->devSpeed); + } + else + { + USBD_REQ_CtrlError(usbInfo, req); + reqError++; + } + break; + + case USBD_DESC_STR_CONFIG: + if (usbInfo->devDesc->configStrDescHandler != NULL) + { + descInfo = usbInfo->devDesc->configStrDescHandler(usbInfo->devSpeed); + } + else + { + USBD_REQ_CtrlError(usbInfo, req); + reqError++; + } + break; + + case USBD_DESC_STR_INTERFACE: + if (usbInfo->devDesc->interfaceStrDescHandler != NULL) + { + descInfo = usbInfo->devDesc->interfaceStrDescHandler(usbInfo->devSpeed); + } + else + { + USBD_REQ_CtrlError(usbInfo, req); + reqError++; + } + break; + + case USBD_DESC_STR_WINUSB_OS: + if (usbInfo->devDesc->winUsbOsStrDescHandler != NULL) + { + descInfo = usbInfo->devDesc->winUsbOsStrDescHandler(usbInfo->devSpeed); + } + else + { + USBD_REQ_CtrlError(usbInfo, req); + reqError++; + } + break; + + default: + USBD_REQ_CtrlError(usbInfo, req); + reqError++; + break; + } + break; + + case USBD_DESC_DEVICE_QUALIFIER: + if (usbInfo->devSpeed == USBD_SPEED_FS) + { + USBD_REQ_CtrlError(usbInfo, req); + reqError++; + } + else + { + descInfo = usbInfo->devDesc->devQualifierDescHandler(usbInfo->devSpeed); + } + break; + + case USBD_DESC_OTHER_SPEED: + if (usbInfo->devSpeed == USBD_SPEED_FS) + { + USBD_REQ_CtrlError(usbInfo, req); + reqError++; + } + else + { + descInfo = usbInfo->devDesc->otherSpeedConfigDescHandler(usbInfo->devSpeed); + } + break; + + default: + USBD_REQ_CtrlError(usbInfo, req); + reqError++; + break; + } + + if (reqError) + { + usbStatus = USBD_FAIL; + return usbStatus; + } + + if (wLength) + { + if (descInfo.size) + { + if (descInfo.size > wLength) + { + descInfo.size = wLength; + } + + USBD_CtrlSendData(usbInfo, descInfo.desc, descInfo.size); + } + else + { + USBD_REQ_CtrlError(usbInfo, req); + } + } + else + { + USBD_CtrlSendStatus(usbInfo); + } + + return usbStatus; +} + +/*! + * @brief USB device set descriptor request + * + * @param usbInfo : usb handler information + * + * @param req : setup data + * + * @retval usb device status + */ +static USBD_STA_T USBD_REQ_SetDesc(USBD_INFO_T* usbInfo, USBD_REQ_SETUP_T* req) +{ + USBD_STA_T usbStatus = USBD_OK; + + UNUSED(usbInfo); + UNUSED(req); + + return usbStatus; +} + +/*! + * @brief USB device get configuration request + * + * @param usbInfo : usb handler information + * + * @param setup : setup data + * + * @retval usb device status + */ +static USBD_STA_T USBD_REQ_GetCfg(USBD_INFO_T* usbInfo, USBD_REQ_SETUP_T* req) +{ + USBD_STA_T usbStatus = USBD_OK; + uint16_t wLength = req->DATA_FIELD.wLength[0] | req->DATA_FIELD.wLength[1] << 8; + + if (wLength == 1) + { + switch (usbInfo->devState) + { + case USBD_DEV_DEFAULT: + case USBD_DEV_ADDRESS: + usbInfo->devCfgDefault = 0; + USBD_CtrlSendData(usbInfo, (uint8_t*)&usbInfo->devCfgDefault, 1); + break; + + case USBD_DEV_CONFIGURE: + USBD_CtrlSendData(usbInfo, (uint8_t*)&usbInfo->devCfg, 1); + break; + + default: + USBD_REQ_CtrlError(usbInfo, req); + break; + } + } + else + { + USBD_REQ_CtrlError(usbInfo, req); + } + + return usbStatus; +} + +/*! + * @brief USB device set configuration request + * + * @param usbInfo : usb handler information + * + * @param setup : setup data + * + * @retval usb device status + */ +static USBD_STA_T USBD_REQ_SetCfg(USBD_INFO_T* usbInfo, USBD_REQ_SETUP_T* req) +{ + USBD_STA_T usbStatus = USBD_OK; + static uint8_t cfgIndex; + + cfgIndex = req->DATA_FIELD.wValue[0]; + + if (cfgIndex > USBD_SUP_CONFIGURATION_MAX_NUM) + { + USBD_REQ_CtrlError(usbInfo, req); + + return USBD_FAIL; + } + + switch (usbInfo->devState) + { + case USBD_DEV_ADDRESS: + if (cfgIndex == 0) + { + USBD_CtrlSendStatus(usbInfo); + } + else + { + usbInfo->devCfg = cfgIndex; + + /* Set class configuration */ + if (usbInfo->devClass[0] != NULL) + { + usbStatus = usbInfo->devClass[0]->ClassInitHandler(usbInfo, cfgIndex); + } + + if (usbStatus == USBD_OK) + { + USBD_CtrlSendStatus(usbInfo); + usbInfo->devState = USBD_DEV_CONFIGURE; + } + else + { + USBD_REQ_CtrlError(usbInfo, req); + usbInfo->devState = USBD_DEV_ADDRESS; + } + } + break; + + case USBD_DEV_CONFIGURE: + if (cfgIndex == 0) + { + usbInfo->devState = USBD_DEV_ADDRESS; + usbInfo->devCfg = cfgIndex; + + /* Clear class configuration */ + usbInfo->devClass[0]->ClassDeInitHandler(usbInfo, cfgIndex); + + USBD_CtrlSendStatus(usbInfo); + } + else if (cfgIndex != usbInfo->devCfg) + { + /* Clear old class configuration */ + usbInfo->devClass[0]->ClassDeInitHandler(usbInfo, usbInfo->devCfg); + + usbInfo->devCfg = cfgIndex; + + /* Set class configuration */ + if (usbInfo->devClass[0] != NULL) + { + usbStatus = usbInfo->devClass[0]->ClassInitHandler(usbInfo, cfgIndex); + } + + if (usbStatus == USBD_OK) + { + USBD_CtrlSendStatus(usbInfo); + } + else + { + USBD_REQ_CtrlError(usbInfo, req); + /* Clear old class configuration */ + usbInfo->devClass[0]->ClassDeInitHandler(usbInfo, usbInfo->devCfg); + usbInfo->devState = USBD_DEV_ADDRESS; + } + } + else + { + USBD_CtrlSendStatus(usbInfo); + } + break; + + default: + USBD_REQ_CtrlError(usbInfo, req); + + /* Clear class configuration */ + if (usbInfo->devClass[0]->ClassDeInitHandler(usbInfo, cfgIndex) != USBD_OK) + { + usbStatus = USBD_FAIL; + } + + break; + } + + return usbStatus; +} + +/*! + * @brief USB device get interface request + * + * @param usbInfo : usb handler information + * + * @param setup : setup data + * + * @retval usb device status + */ +static USBD_STA_T USBD_REQ_GetItf(USBD_INFO_T* usbInfo, USBD_REQ_SETUP_T* req) +{ + USBD_STA_T usbStatus = USBD_OK; + + UNUSED(usbInfo); + UNUSED(req); + + return usbStatus; +} + +/*! + * @brief USB device set interface request + * + * @param usbInfo : usb handler information + * + * @param setup : setup data + * + * @retval usb device status + */ +static USBD_STA_T USBD_REQ_SetItf(USBD_INFO_T* usbInfo, USBD_REQ_SETUP_T* req) +{ + USBD_STA_T usbStatus = USBD_OK; + + UNUSED(usbInfo); + UNUSED(req); + + return usbStatus; +} + +/*! + * @brief USB device sync frame request + * + * @param usbInfo : usb handler information + * + * @param setup : setup data + * + * @retval usb device status + */ +static USBD_STA_T USBD_REQ_SyncFrame(USBD_INFO_T* usbInfo, USBD_REQ_SETUP_T* req) +{ + USBD_STA_T usbStatus = USBD_OK; + + UNUSED(usbInfo); + UNUSED(req); + + return usbStatus; +} + +/*! + * @brief USB device control request error + * + * @param usbInfo : usb handler information + * + * @param setup : setup data + * + * @retval usb device status + */ +USBD_STA_T USBD_REQ_CtrlError(USBD_INFO_T* usbInfo, USBD_REQ_SETUP_T* req) +{ + USBD_STA_T usbStatus = USBD_OK; + + UNUSED(req); + + USBD_EP_StallCallback(usbInfo, 0x80); + USBD_EP_StallCallback(usbInfo, 0x00); + + return usbStatus; +} + +/**@} end of group USBD_Core_Functions */ +/**@} end of group USBD_Core */ +/**@} end of group APM32_USB_Library */ diff --git a/lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Class/CDC/Inc/usbh_cdc.h b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Class/CDC/Inc/usbh_cdc.h new file mode 100644 index 0000000000..15d58da3b9 --- /dev/null +++ b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Class/CDC/Inc/usbh_cdc.h @@ -0,0 +1,200 @@ +/*! + * @file usbh_cdc.h + * + * @brief USB CDC core function head file + * + * @version V1.0.0 + * + * @date 2023-01-16 + * + * @attention + * + * Copyright (C) 2023 Geehy Semiconductor + * + * You may not use this file except in compliance with the + * GEEHY COPYRIGHT NOTICE (GEEHY SOFTWARE PACKAGE LICENSE). + * + * The program is only for reference, which is distributed in the hope + * that it will be useful and instructional for customers to develop + * their software. Unless required by applicable law or agreed to in + * writing, the program is distributed on an "AS IS" BASIS, WITHOUT + * ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied. + * See the GEEHY SOFTWARE PACKAGE LICENSE for the governing permissions + * and limitations under the License. + */ + +/* Define to prevent recursive inclusion */ +#ifndef _USBH_CDC_H_ +#define _USBH_CDC_H_ + +/* Includes */ +#include "usbh_core.h" + +/** @addtogroup APM32_USB_Library + @{ + */ + +/** @addtogroup USBH_CDC_Class + @{ + */ + +/** @defgroup USBH_CDC_Macros Macros + @{ +*/ + +#define USBH_CDC_ACM_CODE 0x02 +#define USBH_CDC_AT_COMMAND_CODE 0x01 +#define USBH_CDC_LINE_CODING_NUM 0x07 + +/**@} end of group USBH_CDC_Macros*/ + +/** @defgroup USBH_CDC_Enumerates Enumerates + @{ + */ + +/** + * @brief USB CDC state table + */ +typedef enum +{ + USBH_CDC_INIT = 0, + USBH_CDC_IDLE = 1, + USBH_CDC_SET_LINE_CODING_STATE, + USBH_CDC_GET_LINE_CODING_STATE, + USBH_CDC_SET_CONTROL_LINE_STATE, + USBH_CDC_TRANSFER_DATA_STATE, + USBH_CDC_ERROR_STATE, +} USBH_CDC_STATE_T; + +/** + * @brief USB CDC data state table + */ +typedef enum +{ + USBH_CDC_DATA_IDLE = 0, + USBH_CDC_DATA_SEND, + USBH_CDC_DATA_SEND_WAIT, + USBH_CDC_DATA_RECEIVE, + USBH_CDC_DATA_RECEIVE_WAIT, + USBH_CDC_DATA_ERROR, +} USBH_CDC_DATA_STATE_T; + +/** + * @brief USB CDC device class requests type + */ +typedef enum +{ + USBH_CDC_REQ_SEND_ENCAPSULATED_COMMAND = 0, + USBH_CDC_REQ_SET_LINE_CODING = 0x20, + USBH_CDC_REQ_GET_LINE_CODING, + USBH_CDC_REQ_SET_CONTROL_LINE_STATE, +} USBH_CDC_REQ_TYPE_T; + +/**@} end of group USBH_CDC_Enumerates*/ + +/** @defgroup USBH_CDC_Structures Structures + @{ + */ + +/* Host CDC class state handler function */ +typedef USBH_STA_T(*USBH_CDCStateHandler_T)(USBH_INFO_T* usbInfo); +typedef USBH_STA_T(*USBH_CDCDataHandler_T)(USBH_INFO_T* usbInfo); + +/** + * @brief CDC line coding structure + */ +typedef union +{ + uint8_t data[USBH_CDC_LINE_CODING_NUM]; + + struct + { + uint32_t dwDTERate; + uint8_t bCharFormat; + uint8_t bParityType; + uint8_t bDataBits; + } DATA_B; +} USBH_CDC_LINE_CODING_T; + +/** + * @brief CDC control line state structure + */ +typedef union +{ + uint8_t bitmap; + + struct + { + uint8_t DTR : 1; + uint8_t RTS : 1; + uint8_t RESERVED : 6; + } DATA_B; + +} USBH_CDC_CONTROL_LINE_STATE_T; + +/** + * @brief CDC communication data + */ +typedef struct +{ + uint8_t notifyChNum; + uint8_t notifyEpAddr; + uint16_t notifyEpsize; + uint8_t notifyBuffer[8]; +} USBH_CDC_COMMUNICATION_T; + +/** + * @brief CDC transfer data + */ +typedef struct +{ + uint32_t txdLength; + uint32_t rxdLength; + uint8_t* txBuffer; + uint8_t* rxBuffer; + uint8_t inChNum; + uint8_t outChNum; + uint8_t inEpAddr; + uint8_t outEpAddr; + uint16_t inEpsize; + uint16_t outEpsize; + uint8_t dataBuffer[8]; +} USBH_CDC_XFER_T; + +/** + * @brief CDC information management + */ +typedef struct +{ + USBH_CDC_STATE_T state; + USBH_CDC_DATA_STATE_T dataXferState; + USBH_CDC_XFER_T dataXfer; + USBH_CDC_LINE_CODING_T userLineCoding; + USBH_CDC_LINE_CODING_T* lineCoding; + USBH_CDC_CONTROL_LINE_STATE_T* controlLine; + USBH_CDC_COMMUNICATION_T comm; + uint32_t timer; +} USBH_CDC_INFO_T; + +extern USBH_CLASS_T USBH_CDC_CLASS; + +/**@} end of group USBH_CDC_Structures*/ + +/** @defgroup USBH_CDC_Functions Functions + @{ + */ + +USBH_CDC_DATA_STATE_T USBH_CDC_ReadDataStatus(USBH_INFO_T* usbInfo); +uint16_t USBH_CDC_ReadRevDataSize(USBH_INFO_T* usbInfo); +USBH_STA_T USBH_CDC_SendData(USBH_INFO_T* usbInfo, uint8_t* buffer, uint32_t length); +USBH_STA_T USBH_CDC_ReceiveData(USBH_INFO_T* usbInfo, uint8_t* buffer, uint32_t length); + +void USBH_CDC_LineCodingIsChangeCallback(USBH_INFO_T* usbInfo); +void USBH_CDC_XferEndCallback(USBH_INFO_T* usbInfo); +void USBH_CDC_RevEndCallback(USBH_INFO_T* usbInfo); + +/**@} end of group USBH_CDC_Functions */ +/**@} end of group USBH_CDC_Class */ +/**@} end of group APM32_USB_Library */ + +#endif diff --git a/lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Class/CDC/Src/usbh_cdc.c b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Class/CDC/Src/usbh_cdc.c new file mode 100644 index 0000000000..7ae2bb48fb --- /dev/null +++ b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Class/CDC/Src/usbh_cdc.c @@ -0,0 +1,1108 @@ +/*! + * @file usbh_cdc.h + * + * @brief USB CDC core function + * + * @version V1.0.0 + * + * @date 2023-01-16 + * + * @attention + * + * Copyright (C) 2023 Geehy Semiconductor + * + * You may not use this file except in compliance with the + * GEEHY COPYRIGHT NOTICE (GEEHY SOFTWARE PACKAGE LICENSE). + * + * The program is only for reference, which is distributed in the hope + * that it will be useful and instructional for customers to develop + * their software. Unless required by applicable law or agreed to in + * writing, the program is distributed on an "AS IS" BASIS, WITHOUT + * ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied. + * See the GEEHY SOFTWARE PACKAGE LICENSE for the governing permissions + * and limitations under the License. + */ + +/* Includes */ +#include "usbh_cdc.h" +#include "usbh_stdReq.h" +#include "usbh_dataXfer.h" +#include +#include +#include + +/** @addtogroup APM32_USB_Library + @{ + */ + +/** @addtogroup USBH_CDC_Class + @{ + */ + +/** @defgroup USBH_CDC_Functions Functions + @{ + */ + +static USBH_STA_T USBH_CDC_ClassInitHandler(USBH_INFO_T* usbInfo); +static USBH_STA_T USBH_CDC_ClassDeInitHandler(USBH_INFO_T* usbInfo); +static USBH_STA_T USBH_CDC_ClassReqHandler(USBH_INFO_T* usbInfo); +static USBH_STA_T USBH_CDC_SOFHandler(USBH_INFO_T* usbInfo); +static USBH_STA_T USBH_CDC_CoreHandler(USBH_INFO_T* usbInfo); + +static USBH_STA_T USBH_CDC_InitHandler(USBH_INFO_T* usbInfo); +static USBH_STA_T USBH_CDC_IdleHandler(USBH_INFO_T* usbInfo); +static USBH_STA_T USBH_CDC_SetLineCodingHandler(USBH_INFO_T* usbInfo); +static USBH_STA_T USBH_CDC_GetLineCodingHandler(USBH_INFO_T* usbInfo); +static USBH_STA_T USBH_CDC_SetControlLineHandler(USBH_INFO_T* usbInfo); +static USBH_STA_T USBH_CDC_TransferDataHandler(USBH_INFO_T* usbInfo); +static USBH_STA_T USBH_CDC_ErrorHandler(USBH_INFO_T* usbInfo); + +static USBH_STA_T USBH_CDC_DataIdleHandler(USBH_INFO_T* usbInfo); +static USBH_STA_T USBH_CDC_DataSendHandler(USBH_INFO_T* usbInfo); +static USBH_STA_T USBH_CDC_DataSendWaitHandler(USBH_INFO_T* usbInfo); +static USBH_STA_T USBH_CDC_DataRevHandler(USBH_INFO_T* usbInfo); +static USBH_STA_T USBH_CDC_DataRevWaitHandler(USBH_INFO_T* usbInfo); +static USBH_STA_T USBH_CDC_DataErrorHandler(USBH_INFO_T* usbInfo); + +/**@} end of group USBH_CDC_Functions */ + +/** @defgroup USBH_CDC_Structures Structures + @{ + */ + +/* CDC class handler */ +USBH_CLASS_T USBH_CDC_CLASS = +{ + "Class CDC", + USBH_CLASS_CDCC, + NULL, + USBH_CDC_ClassInitHandler, + USBH_CDC_ClassDeInitHandler, + USBH_CDC_ClassReqHandler, + USBH_CDC_CoreHandler, + USBH_CDC_SOFHandler, +}; + +/* USB host CDC state handler function */ +USBH_CDCStateHandler_T USBH_CDC_Handler[] = +{ + USBH_CDC_InitHandler, + USBH_CDC_IdleHandler, + USBH_CDC_SetLineCodingHandler, + USBH_CDC_GetLineCodingHandler, + USBH_CDC_SetControlLineHandler, + USBH_CDC_TransferDataHandler, + USBH_CDC_ErrorHandler, +}; + +/* USB host CDC data state handler function */ +USBH_CDCDataHandler_T USBH_CDC_DATA_Handler[] = +{ + USBH_CDC_DataIdleHandler, + USBH_CDC_DataSendHandler, + USBH_CDC_DataSendWaitHandler, + USBH_CDC_DataRevHandler, + USBH_CDC_DataRevWaitHandler, + USBH_CDC_DataErrorHandler, +}; + +/**@} end of group USBH_CDC_Structures*/ + +/** @defgroup USBH_CDC_Functions Functions + @{ + */ + +/*! + * @brief USB host get CDC line coding request + * + * @param usbInfo : usb handler information + * + * @param reqType : Select request type. + * + * @param lineCoding : line coding structure + * + * @retval usb host status + */ +static USBH_STA_T USBH_CDC_REQ_GetLineCoding(USBH_INFO_T* usbInfo, uint8_t reqType, \ + USBH_CDC_LINE_CODING_T* lineCoding) +{ + USBH_STA_T usbStatus = USBH_OK; + + switch (usbInfo->xferState) + { + case USBH_XFER_START: + usbInfo->ctrl.reqData.DATA_FIELD.bmRequestType.REQ_TYPE_B.dir = ((reqType & 0x80) >> 7); + usbInfo->ctrl.reqData.DATA_FIELD.bmRequestType.REQ_TYPE_B.type = ((reqType & 0x60) >> 5); + usbInfo->ctrl.reqData.DATA_FIELD.bmRequestType.REQ_TYPE_B.recipient = (reqType & 0x1F); + + usbInfo->ctrl.reqData.DATA_FIELD.bRequest = USBH_CDC_REQ_GET_LINE_CODING; + + usbInfo->ctrl.reqData.DATA_FIELD.wValue[0] = 0; + usbInfo->ctrl.reqData.DATA_FIELD.wValue[1] = 0; + + usbInfo->ctrl.reqData.DATA_FIELD.wIndex[0] = 0; + usbInfo->ctrl.reqData.DATA_FIELD.wIndex[1] = 0; + + usbInfo->ctrl.reqData.DATA_FIELD.wLength[0] = USBH_CDC_LINE_CODING_NUM & 0xFF; + usbInfo->ctrl.reqData.DATA_FIELD.wLength[1] = USBH_CDC_LINE_CODING_NUM >> 8; + break; + + default: + break; + } + + usbStatus = USBH_REQ_CtrlXferHandler(usbInfo, lineCoding->data, USBH_CDC_LINE_CODING_NUM); + + return usbStatus; +} + +/*! + * @brief USB host set CDC line coding request + * + * @param usbInfo : usb handler information + * + * @param reqType : Select request type. + * + * @param lineCoding : line coding structure + * + * @retval usb host status + */ +static USBH_STA_T USBH_CDC_REQ_SetLineCoding(USBH_INFO_T* usbInfo, uint8_t reqType, \ + USBH_CDC_LINE_CODING_T* lineCoding) +{ + USBH_STA_T usbStatus = USBH_OK; + + switch (usbInfo->xferState) + { + case USBH_XFER_START: + usbInfo->ctrl.reqData.DATA_FIELD.bmRequestType.REQ_TYPE_B.dir = ((reqType & 0x80) >> 7); + usbInfo->ctrl.reqData.DATA_FIELD.bmRequestType.REQ_TYPE_B.type = ((reqType & 0x60) >> 5); + usbInfo->ctrl.reqData.DATA_FIELD.bmRequestType.REQ_TYPE_B.recipient = (reqType & 0x1F); + + usbInfo->ctrl.reqData.DATA_FIELD.bRequest = USBH_CDC_REQ_SET_LINE_CODING; + + usbInfo->ctrl.reqData.DATA_FIELD.wValue[0] = 0; + usbInfo->ctrl.reqData.DATA_FIELD.wValue[1] = 0; + + usbInfo->ctrl.reqData.DATA_FIELD.wIndex[0] = 0; + usbInfo->ctrl.reqData.DATA_FIELD.wIndex[1] = 0; + + usbInfo->ctrl.reqData.DATA_FIELD.wLength[0] = USBH_CDC_LINE_CODING_NUM & 0xFF; + usbInfo->ctrl.reqData.DATA_FIELD.wLength[1] = USBH_CDC_LINE_CODING_NUM >> 8; + break; + + default: + break; + } + + usbStatus = USBH_REQ_CtrlXferHandler(usbInfo, lineCoding->data, USBH_CDC_LINE_CODING_NUM); + + return usbStatus; +} + +/*! + * @brief USB host set CDC line coding request + * + * @param usbInfo : usb handler information + * + * @param reqType : Select request type. + * + * @param controlLine : control line status + * + * @retval usb host status + */ +static USBH_STA_T USBH_CDC_REQ_SetControlLineState(USBH_INFO_T* usbInfo, uint8_t reqType, \ + USBH_CDC_CONTROL_LINE_STATE_T* controlLine) +{ + USBH_STA_T usbStatus = USBH_OK; + + switch (usbInfo->xferState) + { + case USBH_XFER_START: + usbInfo->ctrl.reqData.DATA_FIELD.bmRequestType.REQ_TYPE_B.dir = ((reqType & 0x80) >> 7); + usbInfo->ctrl.reqData.DATA_FIELD.bmRequestType.REQ_TYPE_B.type = ((reqType & 0x60) >> 5); + usbInfo->ctrl.reqData.DATA_FIELD.bmRequestType.REQ_TYPE_B.recipient = (reqType & 0x1F); + + usbInfo->ctrl.reqData.DATA_FIELD.bRequest = USBH_CDC_REQ_SET_CONTROL_LINE_STATE; + + usbInfo->ctrl.reqData.DATA_FIELD.wValue[0] = controlLine->bitmap; + usbInfo->ctrl.reqData.DATA_FIELD.wValue[1] = 0; + + usbInfo->ctrl.reqData.DATA_FIELD.wIndex[0] = 0; + usbInfo->ctrl.reqData.DATA_FIELD.wIndex[1] = 0; + + usbInfo->ctrl.reqData.DATA_FIELD.wLength[0] = 0; + usbInfo->ctrl.reqData.DATA_FIELD.wLength[1] = 0; + break; + + default: + break; + } + + usbStatus = USBH_REQ_CtrlXferHandler(usbInfo, NULL, 0); + + return usbStatus; +} + +/*! + * @brief USB host get CDC line coding + * + * @param usbInfo : usb handler information + * + * @param lineCoding : line coding structure + * + * @retval usb host status + */ +static USBH_STA_T USBH_CDC_GetLineCoding(USBH_INFO_T* usbInfo, USBH_CDC_LINE_CODING_T* lineCoding) +{ + USBH_STA_T usbStatus = USBH_OK; + + usbStatus = USBH_CDC_REQ_GetLineCoding(usbInfo, ((USBH_REQ_DIR_IN << 7) | \ + (USBH_REQ_TYPE_CLASS << 5) | \ + (USBH_RECIPIENT_INTERFACE)), + lineCoding); + + return usbStatus; +} + +/*! + * @brief USB host set CDC line coding + * + * @param usbInfo : usb handler information + * + * @param lineCoding : line coding structure + * + * @retval usb host status + */ +static USBH_STA_T USBH_CDC_SetLineCoding(USBH_INFO_T* usbInfo, USBH_CDC_LINE_CODING_T* lineCoding) +{ + USBH_STA_T usbStatus = USBH_OK; + + usbStatus = USBH_CDC_REQ_SetLineCoding(usbInfo, ((USBH_REQ_DIR_OUT << 7) | \ + (USBH_REQ_TYPE_CLASS << 5) | \ + (USBH_RECIPIENT_INTERFACE)), + lineCoding); + + return usbStatus; +} + +/*! + * @brief USB host set CDC control line state + * + * @param usbInfo : usb handler information + * + * @param controlLine : control line status + * + * @retval usb host status + */ +static USBH_STA_T USBH_CDC_SetControlLineState(USBH_INFO_T* usbInfo, USBH_CDC_CONTROL_LINE_STATE_T* controlLine) +{ + USBH_STA_T usbStatus = USBH_OK; + + usbStatus = USBH_CDC_REQ_SetControlLineState(usbInfo, ((USBH_REQ_DIR_OUT << 7) | \ + (USBH_REQ_TYPE_CLASS << 5) | \ + (USBH_RECIPIENT_INTERFACE)), + controlLine); + + return usbStatus; +} + +/*! + * @brief USB host CDC read data status + * + * @param usbInfo: usb host information + * + * @retval USB host CDC data status + */ +USBH_CDC_DATA_STATE_T USBH_CDC_ReadDataStatus(USBH_INFO_T* usbInfo) +{ + USBH_CDC_INFO_T* usbHostCDC = (USBH_CDC_INFO_T*)usbInfo->activeClass->classData; + + return usbHostCDC->dataXferState; +} + +/*! + * @brief USB host CDC configure control line state + * + * @param usbInfo: usb host information + * + * @retval USB host operation status + */ +USBH_STA_T USBH_CDC_ConfigControlLineState(USBH_INFO_T* usbInfo) +{ + USBH_STA_T usbStatus = USBH_BUSY; + USBH_CDC_INFO_T* usbHostCDC = (USBH_CDC_INFO_T*)usbInfo->activeClass->classData; + + if (usbHostCDC->state == USBH_CDC_IDLE) + { + + usbHostCDC->controlLine->DATA_B.DTR = 0; + usbHostCDC->controlLine->DATA_B.RTS = 0; + + usbHostCDC->state = USBH_CDC_SET_CONTROL_LINE_STATE; + + usbStatus = USBH_OK; + } + + return usbStatus; +} + +/*! + * @brief USB host CDC read receive data size + * + * @param usbInfo: usb host information + * + * @retval USB host CDC receive data size + */ +uint16_t USBH_CDC_ReadRevDataSize(USBH_INFO_T* usbInfo) +{ + uint32_t revDataSize = 0; + USBH_CDC_INFO_T* usbHostCDC = (USBH_CDC_INFO_T*)usbInfo->activeClass->classData; + + if (usbInfo->hostState == USBH_HOST_CLASS) + { + revDataSize = USBH_ReadLastXferSizeCallback(usbInfo, usbHostCDC->dataXfer.inChNum); + } + + return revDataSize; +} + +/*! + * @brief USB host CDC send data + * + * @param usbInfo: usb host information + * + * @param buffer: buffer point to send data + * + * @param length: length of send data + * + * @retval USB host operation status + */ +USBH_STA_T USBH_CDC_SendData(USBH_INFO_T* usbInfo, uint8_t* buffer, uint32_t length) +{ + USBH_STA_T usbStatus = USBH_BUSY; + USBH_CDC_INFO_T* usbHostCDC = (USBH_CDC_INFO_T*)usbInfo->activeClass->classData; + + if ((usbHostCDC->state == USBH_CDC_TRANSFER_DATA_STATE) || \ + usbHostCDC->state == USBH_CDC_IDLE) + { + usbHostCDC->dataXfer.txdLength = length; + usbHostCDC->dataXfer.txBuffer = buffer; + + usbHostCDC->state = USBH_CDC_TRANSFER_DATA_STATE; + usbHostCDC->dataXferState = USBH_CDC_DATA_SEND; + + usbStatus = USBH_OK; + } + + return usbStatus; +} + +/*! + * @brief USB host CDC receive data + * + * @param usbInfo: usb host information + * + * @param buffer: buffer point to receive data + * + * @param length: length of receive data + * + * @retval USB host operation status + */ +USBH_STA_T USBH_CDC_ReceiveData(USBH_INFO_T* usbInfo, uint8_t* buffer, uint32_t length) +{ + USBH_STA_T usbStatus = USBH_BUSY; + USBH_CDC_INFO_T* usbHostCDC = (USBH_CDC_INFO_T*)usbInfo->activeClass->classData; + + if ((usbHostCDC->state == USBH_CDC_TRANSFER_DATA_STATE) || \ + usbHostCDC->state == USBH_CDC_IDLE) + { + usbHostCDC->dataXfer.rxdLength = length; + usbHostCDC->dataXfer.rxBuffer = buffer; + + usbHostCDC->state = USBH_CDC_TRANSFER_DATA_STATE; + usbHostCDC->dataXferState = USBH_CDC_DATA_RECEIVE; + + usbStatus = USBH_OK; + } + + return usbStatus; +} + +/*! + * @brief USB host CDC init handler + * + * @param usbInfo: usb host information + * + * @retval USB host operation status + */ +static USBH_STA_T USBH_CDC_InitHandler(USBH_INFO_T* usbInfo) +{ + USBH_STA_T usbStatus = USBH_OK; + USBH_CDC_INFO_T* usbHostCDC = (USBH_CDC_INFO_T*)usbInfo->activeClass->classData; + + /* Notify User */ + usbInfo->userCallback(usbInfo, USBH_USER_CLASS_LAUNCHED); + + usbHostCDC->state = USBH_CDC_IDLE; + + return usbStatus; +} + +/*! + * @brief USB host CDC idle handler + * + * @param usbInfo: usb host information + * + * @retval USB host operation status + */ +static USBH_STA_T USBH_CDC_IdleHandler(USBH_INFO_T* usbInfo) +{ + USBH_STA_T usbStatus = USBH_OK; + + return usbStatus; +} + +/*! + * @brief USB host CDC data idle handler + * + * @param usbInfo: usb host information + * + * @retval USB host operation status + */ +static USBH_STA_T USBH_CDC_DataIdleHandler(USBH_INFO_T* usbInfo) +{ + USBH_STA_T usbStatus = USBH_OK; + + return usbStatus; +} + +/*! + * @brief USB host CDC send data handler + * + * @param usbInfo: usb host information + * + * @retval USB host operation status + */ +static USBH_STA_T USBH_CDC_DataSendHandler(USBH_INFO_T* usbInfo) +{ + USBH_STA_T usbStatus = USBH_OK; + USBH_CDC_INFO_T* usbHostCDC = (USBH_CDC_INFO_T*)usbInfo->activeClass->classData; + + if (usbHostCDC->dataXfer.txdLength > usbHostCDC->dataXfer.outEpsize) + { + USBH_BulkSendDataReq(usbInfo, usbHostCDC->dataXfer.outChNum, \ + usbHostCDC->dataXfer.txBuffer, \ + usbHostCDC->dataXfer.outEpsize, ENABLE); + } + else + { + USBH_BulkSendDataReq(usbInfo, usbHostCDC->dataXfer.outChNum, \ + usbHostCDC->dataXfer.txBuffer, \ + usbHostCDC->dataXfer.txdLength, ENABLE); + } + + usbHostCDC->dataXferState = USBH_CDC_DATA_SEND_WAIT; + + return usbStatus; +} + +/*! + * @brief USB host CDC send data wait handler + * + * @param usbInfo: usb host information + * + * @retval USB host operation status + */ +static USBH_STA_T USBH_CDC_DataSendWaitHandler(USBH_INFO_T* usbInfo) +{ + USBH_STA_T usbStatus = USBH_OK; + uint8_t usbUrbStatus = USB_URB_IDLE; + USBH_CDC_INFO_T* usbHostCDC = (USBH_CDC_INFO_T*)usbInfo->activeClass->classData; + + /* Read USB URB status */ + usbUrbStatus = USBH_ReadUrbStatusCallback(usbInfo, usbHostCDC->dataXfer.outChNum); + + switch (usbUrbStatus) + { + case USB_URB_OK: + if (usbHostCDC->dataXfer.txdLength > usbHostCDC->dataXfer.outEpsize) + { + usbHostCDC->dataXfer.txdLength -= usbHostCDC->dataXfer.outEpsize; + usbHostCDC->dataXfer.txBuffer += usbHostCDC->dataXfer.outEpsize; + } + else + { + usbHostCDC->dataXfer.txdLength = 0; + } + + if (usbHostCDC->dataXfer.txdLength > 0) + { + usbHostCDC->dataXferState = USBH_CDC_DATA_SEND; + } + else + { + usbHostCDC->dataXferState = USBH_CDC_DATA_IDLE; + + /* Notify User */ + USBH_CDC_XferEndCallback(usbInfo); + } + break; + + case USB_URB_NOREADY: + usbHostCDC->dataXferState = USBH_CDC_DATA_SEND; + break; + + default: + break; + } + + return usbStatus; +} + +/*! + * @brief USB host CDC receive data handler + * + * @param usbInfo: usb host information + * + * @retval USB host operation status + */ +static USBH_STA_T USBH_CDC_DataRevHandler(USBH_INFO_T* usbInfo) +{ + USBH_STA_T usbStatus = USBH_OK; + USBH_CDC_INFO_T* usbHostCDC = (USBH_CDC_INFO_T*)usbInfo->activeClass->classData; + + USBH_BulkReceiveDataReq(usbInfo, usbHostCDC->dataXfer.inChNum, \ + usbHostCDC->dataXfer.rxBuffer, \ + usbHostCDC->dataXfer.inEpsize); + + usbHostCDC->dataXferState = USBH_CDC_DATA_RECEIVE_WAIT; + + return usbStatus; +} + +/*! + * @brief USB host CDC receive data wait handler + * + * @param usbInfo: usb host information + * + * @retval USB host operation status + */ +static USBH_STA_T USBH_CDC_DataRevWaitHandler(USBH_INFO_T* usbInfo) +{ + USBH_STA_T usbStatus = USBH_OK; + uint8_t usbUrbStatus = USB_URB_IDLE; + USBH_CDC_INFO_T* usbHostCDC = (USBH_CDC_INFO_T*)usbInfo->activeClass->classData; + uint32_t length; + + /* Read USB URB status */ + usbUrbStatus = USBH_ReadUrbStatusCallback(usbInfo, usbHostCDC->dataXfer.inChNum); + + switch (usbUrbStatus) + { + case USB_URB_OK: + length = USBH_ReadLastXferSizeCallback(usbInfo, usbHostCDC->dataXfer.inChNum); + + if ((length > usbHostCDC->dataXfer.inEpsize) && \ + (usbHostCDC->dataXfer.rxdLength - length > 0)) + { + usbHostCDC->dataXfer.rxBuffer += length; + usbHostCDC->dataXfer.rxdLength -= length; + + usbHostCDC->dataXferState = USBH_CDC_DATA_RECEIVE; + } + else + { + usbHostCDC->dataXferState = USBH_CDC_DATA_IDLE; + + /* Notify User */ + USBH_CDC_RevEndCallback(usbInfo); + } + break; + + default: + break; + } + + return usbStatus; +} + +/*! + * @brief USB host CDC data error handler + * + * @param usbInfo: usb host information + * + * @retval USB host operation status + */ +static USBH_STA_T USBH_CDC_DataErrorHandler(USBH_INFO_T* usbInfo) +{ + USBH_STA_T usbStatus = USBH_OK; + + return usbStatus; +} + +/*! + * @brief USB host CDC set line coding handler + * + * @param usbInfo: usb host information + * + * @retval USB host operation status + */ +static USBH_STA_T USBH_CDC_SetLineCodingHandler(USBH_INFO_T* usbInfo) +{ + USBH_STA_T usbStatus = USBH_OK; + uint8_t reqStatus = USBH_OK; + USBH_CDC_INFO_T* usbHostCDC = (USBH_CDC_INFO_T*)usbInfo->activeClass->classData; + + reqStatus = USBH_CDC_SetLineCoding(usbInfo, usbHostCDC->lineCoding); + switch (reqStatus) + { + case USBH_OK: + usbHostCDC->state = USBH_CDC_GET_LINE_CODING_STATE; + break; + + case USBH_BUSY: + break; + + default: + usbHostCDC->state = USBH_CDC_ERROR_STATE; + break; + } + + + return usbStatus; +} + +/*! + * @brief USB host CDC get line coding handler + * + * @param usbInfo: usb host information + * + * @retval USB host operation status + */ +static USBH_STA_T USBH_CDC_GetLineCodingHandler(USBH_INFO_T* usbInfo) +{ + USBH_STA_T usbStatus = USBH_OK; + uint8_t reqStatus = USBH_OK; + USBH_CDC_INFO_T* usbHostCDC = (USBH_CDC_INFO_T*)usbInfo->activeClass->classData; + uint8_t i; + uint8_t lineCodingStatus = USBH_OK; + + reqStatus = USBH_CDC_GetLineCoding(usbInfo, &usbHostCDC->userLineCoding); + switch (reqStatus) + { + case USBH_OK: + usbHostCDC->state = USBH_CDC_IDLE; + + for (i = 0; i < USBH_CDC_LINE_CODING_NUM; i++) + { + if (usbHostCDC->userLineCoding.data[i] != usbHostCDC->lineCoding->data[i]) + { + lineCodingStatus = USBH_FAIL; + } + } + + if (lineCodingStatus == USBH_OK) + { + USBH_CDC_LineCodingIsChangeCallback(usbInfo); + } + + break; + + case USBH_BUSY: + break; + + default: + usbHostCDC->state = USBH_CDC_ERROR_STATE; + break; + } + + return usbStatus; +} + +/*! + * @brief USB host CDC set control line state handler + * + * @param usbInfo: usb host information + * + * @retval USB host operation status + */ +static USBH_STA_T USBH_CDC_SetControlLineHandler(USBH_INFO_T* usbInfo) +{ + USBH_STA_T usbStatus = USBH_OK; + uint8_t reqStatus = USBH_OK; + USBH_CDC_INFO_T* usbHostCDC = (USBH_CDC_INFO_T*)usbInfo->activeClass->classData; + + reqStatus = USBH_CDC_SetControlLineState(usbInfo, usbHostCDC->controlLine); + + switch (reqStatus) + { + case USBH_OK: + usbHostCDC->state = USBH_CDC_IDLE; + break; + + default: + usbHostCDC->state = USBH_CDC_ERROR_STATE; + break; + } + + return usbStatus; +} + +/*! + * @brief USB host CDC transfer data state handler + * + * @param usbInfo: usb host information + * + * @retval USB host operation status + */ +static USBH_STA_T USBH_CDC_TransferDataHandler(USBH_INFO_T* usbInfo) +{ + USBH_STA_T usbStatus = USBH_OK; + USBH_CDC_INFO_T* usbHostCDC = (USBH_CDC_INFO_T*)usbInfo->activeClass->classData; + + usbStatus = USBH_CDC_DATA_Handler[usbHostCDC->dataXferState](usbInfo); + + return usbStatus; +} + +/*! + * @brief USB host CDC error state handler + * + * @param usbInfo: usb host information + * + * @retval USB host operation status + */ +static USBH_STA_T USBH_CDC_ErrorHandler(USBH_INFO_T* usbInfo) +{ + USBH_STA_T usbStatus = USBH_OK; + uint8_t reqStatus = USBH_OK; + USBH_CDC_INFO_T* usbHostCDC = (USBH_CDC_INFO_T*)usbInfo->activeClass->classData; + + reqStatus = USBH_ClearFeature(usbInfo, 0); + + switch (reqStatus) + { + case USBH_OK: + usbHostCDC->state = USBH_CDC_IDLE; + break; + + default: + break; + } + + + return usbStatus; +} + +/*! + * @brief USB host CDC configuration handler + * + * @param usbInfo: usb host information + * + * @retval USB host operation status + */ +static USBH_STA_T USBH_CDC_ClassInitHandler(USBH_INFO_T* usbInfo) +{ + USBH_STA_T usbStatus = USBH_OK; + + USBH_CDC_INFO_T* usbHostCDC; + + uint8_t itfNum; + uint8_t subClass; + uint8_t classInterface; + uint8_t protocolInterface; + + uint8_t epNum; + uint8_t epAddr; + uint8_t epDir; + + USBH_USR_Debug("USBH_CDC_ClassInitHandler"); + + /* Link class data */ + usbInfo->activeClass->classData = (USBH_CDC_INFO_T*)malloc(sizeof(USBH_CDC_INFO_T)); + usbHostCDC = (USBH_CDC_INFO_T*)usbInfo->activeClass->classData; + memset(usbHostCDC, 0, sizeof(USBH_CDC_INFO_T)); + + /* Configure communication endpoint */ + itfNum = USBH_ReadConfigurationItfNum(usbInfo); + + while (itfNum--) + { + classInterface = USBH_ReadInterfaceClass(usbInfo, itfNum); + if (classInterface != USBH_CLASS_CDCC) + { + usbStatus = USBH_ERR_NOT_SUP; + continue; + } + + subClass = USBH_ReadInterfaceSubClass(usbInfo, itfNum); + if (subClass != USBH_CDC_ACM_CODE) + { + usbStatus = USBH_FAIL; + continue; + } + + protocolInterface = USBH_ReadInterfaceProtocol(usbInfo, itfNum); + if (protocolInterface != USBH_CDC_AT_COMMAND_CODE) + { + usbStatus = USBH_FAIL; + continue; + } + + epNum = USBH_ReadInterfaceEpNum(usbInfo, itfNum); + + if (epNum > ENDPOINT_DESC_MAX_NUM) + { + epNum = ENDPOINT_DESC_MAX_NUM; + } + + while (epNum--) + { + /* Get endpoint and size */ + epAddr = USBH_ReadEndpointAddress(usbInfo, itfNum, epNum); + epDir = epAddr & 0x80; + + if (epDir) + { + usbHostCDC->comm.notifyEpAddr = USBH_ReadEndpointAddress(usbInfo, itfNum, epNum); + usbHostCDC->comm.notifyEpsize = USBH_ReadEndpointMPS(usbInfo, itfNum, epNum); + } + } + } + + /* Notify channels */ + usbHostCDC->comm.notifyChNum = USBH_CH_AllocChannel(usbInfo, usbHostCDC->comm.notifyEpAddr); + + /* Open the new Notify channels */ + USBH_OpenChannelCallback(usbInfo, usbHostCDC->comm.notifyChNum, + usbHostCDC->comm.notifyEpAddr, + usbInfo->devInfo.address, + usbInfo->devInfo.speed, + EP_TYPE_INTERRUPT, + usbHostCDC->comm.notifyEpsize); + + USBH_ConfigDataPidCallback(usbInfo, usbHostCDC->comm.notifyChNum, 0); + + /* Configure data endpoint */ + itfNum = USBH_ReadConfigurationItfNum(usbInfo); + + while (itfNum--) + { + classInterface = USBH_ReadInterfaceClass(usbInfo, itfNum); + if (classInterface != USBH_CLASS_CDCD) + { + usbStatus = USBH_ERR_NOT_SUP; + continue; + } + + epNum = USBH_ReadInterfaceEpNum(usbInfo, itfNum); + + if (epNum > ENDPOINT_DESC_MAX_NUM) + { + epNum = ENDPOINT_DESC_MAX_NUM; + } + + while (epNum--) + { + /* Get endpoint and size */ + epAddr = USBH_ReadEndpointAddress(usbInfo, itfNum, epNum); + epDir = epAddr & 0x80; + + if (epDir) + { + usbHostCDC->dataXfer.inEpAddr = USBH_ReadEndpointAddress(usbInfo, itfNum, epNum); + usbHostCDC->dataXfer.inEpsize = USBH_ReadEndpointMPS(usbInfo, itfNum, epNum); + } + else + { + usbHostCDC->dataXfer.outEpAddr = USBH_ReadEndpointAddress(usbInfo, itfNum, epNum); + usbHostCDC->dataXfer.outEpsize = USBH_ReadEndpointMPS(usbInfo, itfNum, epNum); + } + } + } + + /* Out channels */ + usbHostCDC->dataXfer.outChNum = USBH_CH_AllocChannel(usbInfo, usbHostCDC->dataXfer.outEpAddr); + + /* In channels */ + usbHostCDC->dataXfer.inChNum = USBH_CH_AllocChannel(usbInfo, usbHostCDC->dataXfer.inEpAddr); + + /* Open the new OUT channels */ + USBH_OpenChannelCallback(usbInfo, usbHostCDC->dataXfer.outChNum, + usbHostCDC->dataXfer.outEpAddr, + usbInfo->devInfo.address, + usbInfo->devInfo.speed, + EP_TYPE_BULK, + usbHostCDC->dataXfer.outEpsize); + + + /* Open the new IN channels */ + USBH_OpenChannelCallback(usbInfo, usbHostCDC->dataXfer.inChNum, + usbHostCDC->dataXfer.inEpAddr, + usbInfo->devInfo.address, + usbInfo->devInfo.speed, + EP_TYPE_BULK, + usbHostCDC->dataXfer.inEpsize); + + USBH_ConfigDataPidCallback(usbInfo, usbHostCDC->dataXfer.outChNum, 0); + + USBH_ConfigDataPidCallback(usbInfo, usbHostCDC->dataXfer.inChNum, 0); + + usbStatus = USBH_OK; + + usbHostCDC->state = USBH_CDC_INIT; + usbHostCDC->dataXferState = USBH_CDC_DATA_IDLE; + + return usbStatus; +} + +/*! + * @brief USB host CDC class reset handler + * + * @param usbInfo: usb host information + * + * @retval USB host operation status + */ +static USBH_STA_T USBH_CDC_ClassDeInitHandler(USBH_INFO_T* usbInfo) +{ + USBH_STA_T usbStatus = USBH_OK; + USBH_CDC_INFO_T* usbHostCDC = (USBH_CDC_INFO_T*)usbInfo->activeClass->classData; + + USBH_USR_Debug("USBH_CDC_ClassDeInitHandler"); + + if (usbHostCDC->comm.notifyChNum != 0) + { + USBH_CloseChannelCallback(usbInfo, usbHostCDC->comm.notifyChNum); + USBH_CH_FreeChannel(usbInfo, usbHostCDC->comm.notifyChNum); + usbHostCDC->comm.notifyChNum = 0; + } + + if (usbHostCDC->dataXfer.inChNum != 0) + { + USBH_CloseChannelCallback(usbInfo, usbHostCDC->dataXfer.inChNum); + USBH_CH_FreeChannel(usbInfo, usbHostCDC->dataXfer.inChNum); + usbHostCDC->dataXfer.inChNum = 0; + } + + if (usbHostCDC->dataXfer.outChNum != 0) + { + USBH_CloseChannelCallback(usbInfo, usbHostCDC->dataXfer.outChNum); + USBH_CH_FreeChannel(usbInfo, usbHostCDC->dataXfer.outChNum); + usbHostCDC->dataXfer.outChNum = 0; + } + + if (usbInfo->activeClass->classData != NULL) + { + free(usbInfo->activeClass->classData); + usbInfo->activeClass->classData = 0; + } + + return usbStatus; +} + +/*! + * @brief USB host CDC class reguest handler + * + * @param usbInfo: usb host information + * + * @retval USB host operation status + */ +static USBH_STA_T USBH_CDC_ClassReqHandler(USBH_INFO_T* usbInfo) +{ + USBH_STA_T usbStatus = USBH_BUSY; + uint8_t reqStatus = USBH_BUSY; + USBH_CDC_INFO_T* usbHostCDC = (USBH_CDC_INFO_T*)usbInfo->activeClass->classData; + + USBH_USR_Debug("USBH_CDC_ClassReqHandler"); + + reqStatus = USBH_CDC_GetLineCoding(usbInfo, &usbHostCDC->userLineCoding); + + switch (reqStatus) + { + case USBH_OK: + usbStatus = USBH_OK; + break; + + case USBH_ERR_NOT_SUP: + usbStatus = USBH_ERR_NOT_SUP; + USBH_USR_LOG("CTRL error: get device line coding configuration"); + break; + + default: + break; + } + + return usbStatus; +} + +/*! + * @brief USB host CDC SOF handler + * + * @param usbInfo: usb host information + * + * @retval USB host operation status + */ +static USBH_STA_T USBH_CDC_SOFHandler(USBH_INFO_T* usbInfo) +{ + USBH_STA_T usbStatus = USBH_OK; + + return usbStatus; +} + +/*! + * @brief USB host CDC handler + * + * @param usbInfo: usb host information + * + * @retval USB host operation status + */ +static USBH_STA_T USBH_CDC_CoreHandler(USBH_INFO_T* usbInfo) +{ + USBH_STA_T usbStatus = USBH_BUSY; + USBH_CDC_INFO_T* usbHostCDC = (USBH_CDC_INFO_T*)usbInfo->activeClass->classData; + + usbStatus = USBH_CDC_Handler[usbHostCDC->state](usbInfo); + + return usbStatus; +} + +/*! + * @brief USB host CDC send data finish callback + * + * @param usbInfo: usb host information + * + * @retval None + */ +__weak void USBH_CDC_XferEndCallback(USBH_INFO_T* usbInfo) +{ + /* callback interface */ +} + +/*! + * @brief USB host CDC receive data finish callback + * + * @param usbInfo: usb host information + * + * @retval None + */ +__weak void USBH_CDC_RevEndCallback(USBH_INFO_T* usbInfo) +{ + /* callback interface */ +} + +/*! + * @brief USB host CDC line coding status is change callback + * + * @param usbInfo: usb host information + * + * @retval None + */ +__weak void USBH_CDC_LineCodingIsChangeCallback(USBH_INFO_T* usbInfo) +{ + /* callback interface */ +} + +/**@} end of group USBH_CDC_Functions */ +/**@} end of group USBH_CDC_Class */ +/**@} end of group APM32_USB_Library */ diff --git a/lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Class/HID/Inc/usbh_hid.h b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Class/HID/Inc/usbh_hid.h new file mode 100644 index 0000000000..1af635031c --- /dev/null +++ b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Class/HID/Inc/usbh_hid.h @@ -0,0 +1,180 @@ +/*! + * @file usbh_hid.h + * + * @brief USB HID core function head file + * + * @version V1.0.0 + * + * @date 2023-01-16 + * + * @attention + * + * Copyright (C) 2023 Geehy Semiconductor + * + * You may not use this file except in compliance with the + * GEEHY COPYRIGHT NOTICE (GEEHY SOFTWARE PACKAGE LICENSE). + * + * The program is only for reference, which is distributed in the hope + * that it will be useful and instructional for customers to develop + * their software. Unless required by applicable law or agreed to in + * writing, the program is distributed on an "AS IS" BASIS, WITHOUT + * ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied. + * See the GEEHY SOFTWARE PACKAGE LICENSE for the governing permissions + * and limitations under the License. + */ + +/* Define to prevent recursive inclusion */ +#ifndef _USBH_HID_H_ +#define _USBH_HID_H_ + +/* Includes */ +#include "usbh_core.h" + +/** @addtogroup APM32_USB_Library + @{ + */ + +/** @addtogroup USBH_HID_Class + @{ + */ + +/** @defgroup USBH_HID_Macros Macros + @{ +*/ + +#define USBH_HID_CLASS_CODE 0x03 +#define USBH_HID_BOOT_CODE 0x01 +#define USBH_HID_MOUSE_BOOT_CODE 0x02 +#define USBH_HID_KEYBOARD_BOOT_CODE 0x01 + +#define USBH_HID_QUEUE_MAX_SIZE 10 +#define USBH_HID_POLL_MIN_NUM 10 + +/**@} end of group USBH_HID_Macros*/ + +/** @defgroup USBH_HID_Enumerates Enumerates + @{ + */ + +/** + * @brief USB HID state table + */ +typedef enum +{ + USBH_HID_INIT = 0, + USBH_HID_IDLE = 1, + USBH_HID_SYNC, + USBH_HID_IN_DATA, + USBH_HID_POLL, + USBH_HID_OUT_DATA, + USBH_HID_BUSY, + USBH_HID_ERR, +} USBH_HID_STATE_T; + +/** + * @brief USB HID request state table + */ +typedef enum +{ + USBH_HID_REQ_INIT, + USBH_HID_REQ_IDLE, + USBH_HID_REQ_GET_REP_DESC, + USBH_HID_REQ_GET_HID_DESC, + USBH_HID_REQ_SET_IDLE, + USBH_HID_REQ_SET_PROTOCOL, + USBH_HID_REQ_SET_REPORT, +} USBH_HID_REQ_STA_T; + +/** + * @brief USB HID report type + */ +typedef enum +{ + HID_INPUT_REPORT = 1, + HID_OUTPUT_REPORT, + HID_FEATURE_REPORT, +} USBH_HID_REPORT_T; + +/** + * @brief USB HID device class requests type + */ +typedef enum +{ + USBH_HID_GET_REPORT = 1, + USBH_HID_GET_IDLE, + USBH_HID_GET_PROTOCOL, + USBH_HID_SET_REPORT = 9, + USBH_HID_SET_IDLE, + USBH_HID_SET_PROTOCOL, +} USBH_HID_REQ_TYPE_T; + +/**@} end of group USBH_HID_Enumerates*/ + +/** @defgroup USBH_HID_Structures Structures + @{ + */ + +/** + * @brief USB HID descriptor + */ +typedef struct +{ + uint8_t bLength; + uint8_t bDescriptorType; + uint8_t bcdHID[2]; + uint8_t bCountryCode; + uint8_t bNumDescriptors; + uint8_t bReportDescriptorType; + uint8_t wDescriptorLength[2]; + +} USBH_HID_DESC_T; + +/* Host HID class state handler function */ +typedef USBH_STA_T(*USBH_HIDStateHandler_T)(USBH_INFO_T* usbInfo); + +/** + * @brief USB host HID class handler + */ +typedef struct +{ + USBH_STA_T(*InitHandler)(USBH_INFO_T* usbInfo); + USBH_STA_T(*DecodeHandler)(USBH_INFO_T* usbInfo); +} USBH_HID_CLASS_T; + +/** + * @brief HID information management + */ +typedef struct +{ + uint8_t* buffer; + USBH_HID_STATE_T state; + uint8_t classReqState; + uint8_t inChNum; + uint8_t outChNum; + uint8_t intOutEpAddr; + uint8_t intInEpAddr; + + uint8_t epAddr; + uint8_t epSize; + uint16_t pollInterval; + uint8_t dataFlag; + USBH_HID_DESC_T desc; + USBH_HID_CLASS_T* callback; + uint32_t timer; +} USBH_HID_INFO_T; + +extern USBH_CLASS_T USBH_HID_CLASS; + +/**@} end of group USBH_HID_Structures*/ + +/** @defgroup USBH_HID_Functions Functions + @{ + */ + +void USBH_HID_PollCallback(USBH_INFO_T* usbInfo); + +/**@} end of group USBH_HID_Functions */ +/**@} end of group USBH_HID_Class */ +/**@} end of group APM32_USB_Library */ + +#endif diff --git a/lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Class/HID/Inc/usbh_hid_keyboard.h b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Class/HID/Inc/usbh_hid_keyboard.h new file mode 100644 index 0000000000..5705864e08 --- /dev/null +++ b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Class/HID/Inc/usbh_hid_keyboard.h @@ -0,0 +1,342 @@ +/*! + * @file usbh_hid_keyboard.h + * + * @brief USB host HID keyboard function head file + * + * @version V1.0.0 + * + * @date 2023-01-16 + * + * @attention + * + * Copyright (C) 2023 Geehy Semiconductor + * + * You may not use this file except in compliance with the + * GEEHY COPYRIGHT NOTICE (GEEHY SOFTWARE PACKAGE LICENSE). + * + * The program is only for reference, which is distributed in the hope + * that it will be useful and instructional for customers to develop + * their software. Unless required by applicable law or agreed to in + * writing, the program is distributed on an "AS IS" BASIS, WITHOUT + * ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied. + * See the GEEHY SOFTWARE PACKAGE LICENSE for the governing permissions + * and limitations under the License. + */ + +/* Define to prevent recursive inclusion */ +#ifndef _USBH_HID_KEYBOARD_H_ +#define _USBH_HID_KEYBOARD_H_ + +/* Includes */ +#include "usbh_core.h" +#include "usbh_hid.h" + +/** @addtogroup APM32_USB_Library + @{ + */ + +/** @addtogroup USBH_HID_Class + @{ + */ + +/** @defgroup USBH_HID_Macros Macros + @{ +*/ + +#define USBH_HID_KEY_PRESSED_NUM_MAX 0x06 + +/**@} end of group USBH_HID_Macros*/ + +/** @defgroup USBH_HID_Enumerates Enumerates + @{ + */ + +/** + * @brief HID keyboard value + */ +typedef enum +{ + KEYBOARD_NONE, + KEYBOARD_ERROR_ROLL_OVER, + KEYBOARD_POST_FAIL, + KEYBOARD_ERROR_UNDEFINED, + KEYBOARD_A, + KEYBOARD_B, + KEYBOARD_C, + KEYBOARD_D, + KEYBOARD_E, + KEYBOARD_F, + KEYBOARD_G, + KEYBOARD_H, + KEYBOARD_I, + KEYBOARD_J, + KEYBOARD_K, + KEYBOARD_L, + KEYBOARD_M, + KEYBOARD_N, + KEYBOARD_O, + KEYBOARD_P, + KEYBOARD_Q, + KEYBOARD_R, + KEYBOARD_S, + KEYBOARD_T, + KEYBOARD_U, + KEYBOARD_V, + KEYBOARD_W, + KEYBOARD_X, + KEYBOARD_Y, + KEYBOARD_Z, + KEYBOARD_1_EXCLAMATION, + KEYBOARD_2_AT, + KEYBOARD_3_NUMBER_SIGN, + KEYBOARD_4_DOLLAR, + KEYBOARD_5_PERCENT, + KEYBOARD_6_CARET, + KEYBOARD_7_AMPERSAND, + KEYBOARD_8_ASTERISK, + KEYBOARD_9_OPARENTHESIS, + KEYBOARD_10_CPARENTHESIS, + KEYBOARD_ENTER, + KEYBOARD_ESCAPE, + KEYBOARD_BACKSPACE, + KEYBOARD_TAB, + KEYBOARD_SPACEBAR, + KEYBOARD_MINUS_UNDERSCORE, + KEYBOARD_EQUAL_PLUS, + KEYBOARD_OBRACKET_AND_OBRACE, + KEYBOARD_CBRACKET_AND_CBRACE, + KEYBOARD_BACKSLASH_VERTICAL_BAR, + KEYBOARD_NONUS_NUMBER_SIGN_TILDE, + KEYBOARD_SEMICOLON_COLON, + KEYBOARD_SINGLE_AND_DOUBLE_QUOTE, + KEYBOARD_GRAVE_ACCENT_AND_TILDE, + KEYBOARD_COMMA_AND_LESS, + KEYBOARD_DOT_GREATER, + KEYBOARD_SLASH_QUESTION, + KEYBOARD_CAPS_LOCK, + KEYBOARD_F1, + KEYBOARD_F2, + KEYBOARD_F3, + KEYBOARD_F4, + KEYBOARD_F5, + KEYBOARD_F6, + KEYBOARD_F7, + KEYBOARD_F8, + KEYBOARD_F9, + KEYBOARD_F10, + KEYBOARD_F11, + KEYBOARD_F12, + KEYBOARD_PRINTSCREEN, + KEYBOARD_SCROLL_LOCK, + KEYBOARD_PAUSE, + KEYBOARD_INSERT, + KEYBOARD_HOME, + KEYBOARD_PAGEUP, + KEYBOARD_DELETE, + KEYBOARD_END1, + KEYBOARD_PAGEDOWN, + KEYBOARD_RIGHTARROW, + KEYBOARD_LEFTARROW, + KEYBOARD_DOWNARROW, + KEYBOARD_UPARROW, + KEYBOARD_KEYBOARDPAD_NUM_LOCK_AND_CLEAR, + KEYBOARD_KEYBOARDPAD_SLASH, + KEYBOARD_KEYBOARDPAD_ASTERIKS, + KEYBOARD_KEYBOARDPAD_MINUS, + KEYBOARD_KEYBOARDPAD_PLUS, + KEYBOARD_KEYBOARDPAD_ENTER, + KEYBOARD_KEYBOARDPAD_1_END, + KEYBOARD_KEYBOARDPAD_2_DOWN_ARROW, + KEYBOARD_KEYBOARDPAD_3_PAGEDN, + KEYBOARD_KEYBOARDPAD_4_LEFT_ARROW, + KEYBOARD_KEYBOARDPAD_5, + KEYBOARD_KEYBOARDPAD_6_RIGHT_ARROW, + KEYBOARD_KEYBOARDPAD_7_HOME, + KEYBOARD_KEYBOARDPAD_8_UP_ARROW, + KEYBOARD_KEYBOARDPAD_9_PAGEUP, + KEYBOARD_KEYBOARDPAD_0_INSERT, + KEYBOARD_KEYBOARDPAD_DECIMAL_SEPARATOR_DELETE, + KEYBOARD_NONUS_BACK_SLASH_VERTICAL_BAR, + KEYBOARD_APPLICATION, + KEYBOARD_POWER, + KEYBOARD_KEYBOARDPAD_EQUAL, + KEYBOARD_F13, + KEYBOARD_F14, + KEYBOARD_F15, + KEYBOARD_F16, + KEYBOARD_F17, + KEYBOARD_F18, + KEYBOARD_F19, + KEYBOARD_F20, + KEYBOARD_F21, + KEYBOARD_F22, + KEYBOARD_F23, + KEYBOARD_F24, + KEYBOARD_EXECUTE, + KEYBOARD_HELP, + KEYBOARD_MENU, + KEYBOARD_SELECT, + KEYBOARD_STOP, + KEYBOARD_AGAIN, + KEYBOARD_UNDO, + KEYBOARD_CUT, + KEYBOARD_COPY, + KEYBOARD_PASTE, + KEYBOARD_FIND, + KEYBOARD_MUTE, + KEYBOARD_VOLUME_UP, + KEYBOARD_VOLUME_DOWN, + KEYBOARD_LOCKING_CAPS_LOCK, + KEYBOARD_LOCKING_NUM_LOCK, + KEYBOARD_LOCKING_SCROLL_LOCK, + KEYBOARD_KEYBOARDPAD_COMMA, + KEYBOARD_KEYBOARDPAD_EQUAL_SIGN, + KEYBOARD_INTERNATIONAL1, + KEYBOARD_INTERNATIONAL2, + KEYBOARD_INTERNATIONAL3, + KEYBOARD_INTERNATIONAL4, + KEYBOARD_INTERNATIONAL5, + KEYBOARD_INTERNATIONAL6, + KEYBOARD_INTERNATIONAL7, + KEYBOARD_INTERNATIONAL8, + KEYBOARD_INTERNATIONAL9, + KEYBOARD_LANG1, + KEYBOARD_LANG2, + KEYBOARD_LANG3, + KEYBOARD_LANG4, + KEYBOARD_LANG5, + KEYBOARD_LANG6, + KEYBOARD_LANG7, + KEYBOARD_LANG8, + KEYBOARD_LANG9, + KEYBOARD_ALTERNATE_ERASE, + KEYBOARD_SYSREQ, + KEYBOARD_CANCEL, + KEYBOARD_CLEAR, + KEYBOARD_PRIOR, + KEYBOARD_RETURN, + KEYBOARD_SEPARATOR, + KEYBOARD_OUT, + KEYBOARD_OPER, + KEYBOARD_CLEAR_AGAIN, + KEYBOARD_CRSEL, + KEYBOARD_EXSEL, + KEYBOARD_RESERVED1, + KEYBOARD_RESERVED2, + KEYBOARD_RESERVED3, + KEYBOARD_RESERVED4, + KEYBOARD_RESERVED5, + KEYBOARD_RESERVED6, + KEYBOARD_RESERVED7, + KEYBOARD_RESERVED8, + KEYBOARD_RESERVED9, + KEYBOARD_RESERVED10, + KEYBOARD_RESERVED11, + KEYBOARD_KEYBOARDPAD_00, + KEYBOARD_KEYBOARDPAD_000, + KEYBOARD_THOUSANDS_SEPARATOR, + KEYBOARD_DECIMAL_SEPARATOR, + KEYBOARD_CURRENCY_UNIT, + KEYBOARD_CURRENCY_SUB_UNIT, + KEYBOARD_KEYBOARDPAD_OPARENTHESIS, + KEYBOARD_KEYBOARDPAD_CPARENTHESIS, + KEYBOARD_KEYBOARDPAD_OBRACE, + KEYBOARD_KEYBOARDPAD_CBRACE, + KEYBOARD_KEYBOARDPAD_TAB, + KEYBOARD_KEYBOARDPAD_BACKSPACE, + KEYBOARD_KEYBOARDPAD_A, + KEYBOARD_KEYBOARDPAD_B, + KEYBOARD_KEYBOARDPAD_C, + KEYBOARD_KEYBOARDPAD_D, + KEYBOARD_KEYBOARDPAD_E, + KEYBOARD_KEYBOARDPAD_F, + KEYBOARD_KEYBOARDPAD_XOR, + KEYBOARD_KEYBOARDPAD_CARET, + KEYBOARD_KEYBOARDPAD_PERCENT, + KEYBOARD_KEYBOARDPAD_LESS, + KEYBOARD_KEYBOARDPAD_GREATER, + KEYBOARD_KEYBOARDPAD_AMPERSAND, + KEYBOARD_KEYBOARDPAD_LOGICAL_AND, + KEYBOARD_KEYBOARDPAD_VERTICAL_BAR, + KEYBOARD_KEYBOARDPAD_LOGIACL_OR, + KEYBOARD_KEYBOARDPAD_COLON, + KEYBOARD_KEYBOARDPAD_NUMBER_SIGN, + KEYBOARD_KEYBOARDPAD_SPACE, + KEYBOARD_KEYBOARDPAD_AT, + KEYBOARD_KEYBOARDPAD_EXCLAMATION_MARK, + KEYBOARD_KEYBOARDPAD_MEMORY_STORE, + KEYBOARD_KEYBOARDPAD_MEMORY_RECALL, + KEYBOARD_KEYBOARDPAD_MEMORY_CLEAR, + KEYBOARD_KEYBOARDPAD_MEMORY_ADD, + KEYBOARD_KEYBOARDPAD_MEMORY_SUBTRACT, + KEYBOARD_KEYBOARDPAD_MEMORY_MULTIPLY, + KEYBOARD_KEYBOARDPAD_MEMORY_DIVIDE, + KEYBOARD_KEYBOARDPAD_PLUSMINUS, + KEYBOARD_KEYBOARDPAD_CLEAR, + KEYBOARD_KEYBOARDPAD_CLEAR_ENTRY, + KEYBOARD_KEYBOARDPAD_BINARY, + KEYBOARD_KEYBOARDPAD_OCTAL, + KEYBOARD_KEYBOARDPAD_DECIMAL, + KEYBOARD_KEYBOARDPAD_HEXADECIMAL, + KEYBOARD_RESERVED12, + KEYBOARD_RESERVED13, + KEYBOARD_LEFTCONTROL, + KEYBOARD_LEFTSHIFT, + KEYBOARD_LEFTALT, + KEYBOARD_LEFT_GUI, + KEYBOARD_RIGHTCONTROL, + KEYBOARD_RIGHTSHIFT, + KEYBOARD_RIGHTALT, + KEYBOARD_RIGHT_GUI, +} USBH_HID_KEYBOARD_VALUE_T; + +/**@} end of group USBH_HID_Enumerates*/ + +/** @defgroup USBH_HID_Structures Structures + @{ + */ + +/** + * @brief HID keyboard report information + */ +typedef struct +{ + uint32_t data[2]; + uint32_t rxBuffer[2]; +} USBH_HID_KEYBOARD_REPORT_T; + +/** + * @brief HID keyboard information management + */ +typedef struct +{ + uint8_t ctrlLeft; + uint8_t shiftLeft; + uint8_t altLeft; + uint8_t winLeft; + + uint8_t ctrlRight; + uint8_t shiftRight; + uint8_t altRight; + uint8_t winRight; + uint8_t key[USBH_HID_KEY_PRESSED_NUM_MAX]; + USBH_HID_KEYBOARD_REPORT_T report; +} USBH_HID_KEYBOARD_INFO_T; + +extern USBH_HID_CLASS_T USBH_HID_KEYBOARD_Handler; + +/**@} end of group USBH_HID_Structures*/ + +/** @defgroup USBH_HID_Functions Functions + @{ + */ + +USBH_STA_T USBH_HID_KeyBoardInit(USBH_INFO_T* usbInfo); +USBH_STA_T USBH_HID_KeyboardDecode(USBH_INFO_T* usbInfo); +USBH_STA_T USBH_HID_KeyboardCallback(USBH_INFO_T* usbInfo); + +/**@} end of group USBH_HID_Functions */ +/**@} end of group USBH_HID_Class */ +/**@} end of group APM32_USB_Library */ + +#endif diff --git a/lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Class/HID/Inc/usbh_hid_mouse.h b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Class/HID/Inc/usbh_hid_mouse.h new file mode 100644 index 0000000000..4dce3f0ea0 --- /dev/null +++ b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Class/HID/Inc/usbh_hid_mouse.h @@ -0,0 +1,92 @@ +/*! + * @file usbh_hid_mouse.h + * + * @brief USB host HID mouse function head file + * + * @version V1.0.0 + * + * @date 2023-01-16 + * + * @attention + * + * Copyright (C) 2023 Geehy Semiconductor + * + * You may not use this file except in compliance with the + * GEEHY COPYRIGHT NOTICE (GEEHY SOFTWARE PACKAGE LICENSE). + * + * The program is only for reference, which is distributed in the hope + * that it will be useful and instructional for customers to develop + * their software. Unless required by applicable law or agreed to in + * writing, the program is distributed on an "AS IS" BASIS, WITHOUT + * ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied. + * See the GEEHY SOFTWARE PACKAGE LICENSE for the governing permissions + * and limitations under the License. + */ + +/* Define to prevent recursive inclusion */ +#ifndef _USBH_HID_MOUSE_H_ +#define _USBH_HID_MOUSE_H_ + +/* Includes */ +#include "usbh_core.h" +#include "usbh_hid.h" + +/** @addtogroup APM32_USB_Library + @{ + */ + +/** @addtogroup USBH_HID_Class + @{ + */ + +/** @defgroup USBH_HID_Macros Macros + @{ +*/ + +#define USBH_HID_MOUSE_BUTTON_MAX_NUM 3 + +/**@} end of group USBH_HID_Macros*/ + +/** @defgroup USBH_HID_Structures Structures + @{ + */ + +/** + * @brief HID mouse report information + */ +typedef struct +{ + uint32_t data[2]; + uint32_t rxBuffer[2]; +} USBH_HID_MOUSE_REPORT_T; + +/** + * @brief HID mouse information management + */ +typedef struct +{ + uint8_t x; + uint8_t y; + uint8_t z; + uint8_t button[USBH_HID_MOUSE_BUTTON_MAX_NUM]; + USBH_HID_MOUSE_REPORT_T report; +} USBH_HID_MOUSE_INFO_T; + +extern USBH_HID_MOUSE_INFO_T usbHostHidMouse; +extern USBH_HID_CLASS_T USBH_HID_MOUSE_Handler; + +/**@} end of group USBH_HID_Structures*/ + +/** @defgroup USBH_HID_Functions Functions + @{ + */ + +USBH_STA_T USBH_HID_MouseInit(USBH_INFO_T* usbInfo); +USBH_STA_T USBH_HID_MouseDecode(USBH_INFO_T* usbInfo); +USBH_STA_T USBH_HID_MouseCallback(USBH_INFO_T* usbInfo); + +/**@} end of group USBH_HID_Functions */ +/**@} end of group USBH_HID_Class */ +/**@} end of group APM32_USB_Library */ + +#endif diff --git a/lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Class/HID/Src/usbh_hid.c b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Class/HID/Src/usbh_hid.c new file mode 100644 index 0000000000..fb9f0284ba --- /dev/null +++ b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Class/HID/Src/usbh_hid.c @@ -0,0 +1,952 @@ +/*! + * @file usbh_hid.h + * + * @brief USB HID core function + * + * @version V1.0.0 + * + * @date 2023-01-16 + * + * @attention + * + * Copyright (C) 2023 Geehy Semiconductor + * + * You may not use this file except in compliance with the + * GEEHY COPYRIGHT NOTICE (GEEHY SOFTWARE PACKAGE LICENSE). + * + * The program is only for reference, which is distributed in the hope + * that it will be useful and instructional for customers to develop + * their software. Unless required by applicable law or agreed to in + * writing, the program is distributed on an "AS IS" BASIS, WITHOUT + * ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied. + * See the GEEHY SOFTWARE PACKAGE LICENSE for the governing permissions + * and limitations under the License. + */ + +/* Includes */ +#include "usbh_hid.h" +#include "usbh_hid_mouse.h" +#include "usbh_hid_keyboard.h" +#include "usbh_stdReq.h" +#include "usbh_dataXfer.h" +#include +#include +#include + +/** @addtogroup APM32_USB_Library + @{ + */ + +/** @addtogroup USBH_HID_Class + @{ + */ + +/** @defgroup USBH_HID_Functions Functions + @{ + */ + +static USBH_STA_T USBH_HID_ClassInitHandler(USBH_INFO_T* usbInfo); +static USBH_STA_T USBH_HID_ClassDeInitHandler(USBH_INFO_T* usbInfo); +static USBH_STA_T USBH_HID_ClassReqHandler(USBH_INFO_T* usbInfo); +static USBH_STA_T USBH_HID_SOFHandler(USBH_INFO_T* usbInfo); +static USBH_STA_T USBH_HID_CoreHandler(USBH_INFO_T* usbInfo); + +static USBH_STA_T USBH_HID_InitHandler(USBH_INFO_T* usbInfo); +static USBH_STA_T USBH_HID_IdleHandler(USBH_INFO_T* usbInfo); +static USBH_STA_T USBH_HID_SyncHandler(USBH_INFO_T* usbInfo); +static USBH_STA_T USBH_HID_InDataHandler(USBH_INFO_T* usbInfo); +static USBH_STA_T USBH_HID_PollingHandler(USBH_INFO_T* usbInfo); +static USBH_STA_T USBH_HID_OutDataHandler(USBH_INFO_T* usbInfo); +static USBH_STA_T USBH_HID_BusyHandler(USBH_INFO_T* usbInfo); +static USBH_STA_T USBH_HID_ErrorHandler(USBH_INFO_T* usbInfo); + +/**@} end of group USBH_HID_Functions */ + +/** @defgroup USBH_HID_Structures Structures + @{ + */ + +/* HID class handler */ +USBH_CLASS_T USBH_HID_CLASS = +{ + "Class HID", + USBH_CLASS_HID, + NULL, + USBH_HID_ClassInitHandler, + USBH_HID_ClassDeInitHandler, + USBH_HID_ClassReqHandler, + USBH_HID_CoreHandler, + USBH_HID_SOFHandler, +}; + +/* USB host HID state handler function */ +USBH_HIDStateHandler_T USBH_HID_Handler[] = +{ + USBH_HID_InitHandler, + USBH_HID_IdleHandler, + USBH_HID_SyncHandler, + USBH_HID_InDataHandler, + USBH_HID_PollingHandler, + USBH_HID_OutDataHandler, + USBH_HID_BusyHandler, + USBH_HID_ErrorHandler, +}; + +/**@} end of group USBH_HID_Structures*/ + +/** @defgroup USBH_HID_Functions Functions + @{ + */ + +/*! + * @brief Config HID get report descriptor request + * + * @param usbInfo : usb handler information + * + * @param reqType : Select request type + * + * @param reportType : type of report + * + * @param reportID : ID of report + * + * @param buffer : report buffer + * + * @param length : report length + * + * @retval usb host status + */ +static USBH_STA_T USBH_HID_REQ_GetRepDescriptor(USBH_INFO_T* usbInfo, uint8_t reqType, \ + uint8_t reportType, uint8_t reportID, \ + uint8_t* buffer, uint8_t length) +{ + USBH_STA_T usbStatus = USBH_OK; + + switch (usbInfo->xferState) + { + case USBH_XFER_START: + usbInfo->ctrl.reqData.DATA_FIELD.bmRequestType.REQ_TYPE_B.dir = ((reqType & 0x80) >> 7); + usbInfo->ctrl.reqData.DATA_FIELD.bmRequestType.REQ_TYPE_B.type = ((reqType & 0x60) >> 5); + usbInfo->ctrl.reqData.DATA_FIELD.bmRequestType.REQ_TYPE_B.recipient = (reqType & 0x1F); + + usbInfo->ctrl.reqData.DATA_FIELD.bRequest = USBH_HID_GET_REPORT; + + usbInfo->ctrl.reqData.DATA_FIELD.wValue[0] = reportID; + usbInfo->ctrl.reqData.DATA_FIELD.wValue[1] = reportType; + + usbInfo->ctrl.reqData.DATA_FIELD.wIndex[0] = 0; + usbInfo->ctrl.reqData.DATA_FIELD.wIndex[1] = 0; + + usbInfo->ctrl.reqData.DATA_FIELD.wLength[0] = length & 0xFF; + usbInfo->ctrl.reqData.DATA_FIELD.wLength[1] = length >> 8; + break; + + default: + break; + } + + usbStatus = USBH_REQ_CtrlXferHandler(usbInfo, buffer, length); + + return usbStatus; +} + +/*! + * @brief USB host HID set idle request + * + * @param usbInfo : usb handler information + * + * @param reqType : Select request type. + * + * @param reportID : traget report ID + * + * @param duration : duration for idle request + * + * @retval usb host status + */ +static USBH_STA_T USBH_HID_REQ_SetIdle(USBH_INFO_T* usbInfo, uint8_t reqType, \ + uint8_t reportID, uint8_t duration) +{ + USBH_STA_T usbStatus = USBH_OK; + + switch (usbInfo->xferState) + { + case USBH_XFER_START: + usbInfo->ctrl.reqData.DATA_FIELD.bmRequestType.REQ_TYPE_B.dir = ((reqType & 0x80) >> 7); + usbInfo->ctrl.reqData.DATA_FIELD.bmRequestType.REQ_TYPE_B.type = ((reqType & 0x60) >> 5); + usbInfo->ctrl.reqData.DATA_FIELD.bmRequestType.REQ_TYPE_B.recipient = (reqType & 0x1F); + + usbInfo->ctrl.reqData.DATA_FIELD.bRequest = USBH_HID_SET_IDLE; + + usbInfo->ctrl.reqData.DATA_FIELD.wValue[0] = reportID; + usbInfo->ctrl.reqData.DATA_FIELD.wValue[1] = duration; + + usbInfo->ctrl.reqData.DATA_FIELD.wIndex[0] = 0; + usbInfo->ctrl.reqData.DATA_FIELD.wIndex[1] = 0; + + usbInfo->ctrl.reqData.DATA_FIELD.wLength[0] = 0; + usbInfo->ctrl.reqData.DATA_FIELD.wLength[1] = 0; + break; + + default: + break; + } + + usbStatus = USBH_REQ_CtrlXferHandler(usbInfo, NULL, 0); + + return usbStatus; +} + +/*! + * @brief USB host HID set protocol request + * + * @param usbInfo : usb handler information + * + * @param reqType : Select request type. + * + * @param protocol : boot / report protocol + * + * @retval usb host status + */ +static USBH_STA_T USBH_HID_REQ_SetProtocol(USBH_INFO_T* usbInfo, uint8_t reqType, \ + uint8_t protocol) +{ + USBH_STA_T usbStatus = USBH_OK; + + switch (usbInfo->xferState) + { + case USBH_XFER_START: + usbInfo->ctrl.reqData.DATA_FIELD.bmRequestType.REQ_TYPE_B.dir = ((reqType & 0x80) >> 7); + usbInfo->ctrl.reqData.DATA_FIELD.bmRequestType.REQ_TYPE_B.type = ((reqType & 0x60) >> 5); + usbInfo->ctrl.reqData.DATA_FIELD.bmRequestType.REQ_TYPE_B.recipient = (reqType & 0x1F); + + usbInfo->ctrl.reqData.DATA_FIELD.bRequest = USBH_HID_SET_PROTOCOL; + + if (protocol) + { + usbInfo->ctrl.reqData.DATA_FIELD.wValue[0] = 0; + } + else + { + usbInfo->ctrl.reqData.DATA_FIELD.wValue[0] = 1; + } + + usbInfo->ctrl.reqData.DATA_FIELD.wValue[1] = 0; + + usbInfo->ctrl.reqData.DATA_FIELD.wIndex[0] = 0; + usbInfo->ctrl.reqData.DATA_FIELD.wIndex[1] = 0; + + usbInfo->ctrl.reqData.DATA_FIELD.wLength[0] = 0; + usbInfo->ctrl.reqData.DATA_FIELD.wLength[1] = 0; + break; + + default: + break; + } + + usbStatus = USBH_REQ_CtrlXferHandler(usbInfo, NULL, 0); + + return usbStatus; +} + +/*! + * @brief USB host get HID description + * + * @param usbInfo : usb handler information + * + * @param desLength : length of description + * + * @retval usb host status + */ +static USBH_STA_T USBH_HID_GetHIDDesc(USBH_INFO_T* usbInfo, uint16_t desLength) +{ + USBH_STA_T usbStatus = USBH_OK; + + usbStatus = USBH_REQ_GetDescriptor(usbInfo, ((USBH_REQ_DIR_IN << 7) | \ + (USBH_REQ_TYPE_STANDARD << 5) | \ + (USBH_RECIPIENT_INTERFACE)), \ + USBH_DESC_HID_REPORT, + usbInfo->devInfo.data, + desLength); + return usbStatus; +} + +/*! + * @brief USB host get HID report description + * + * @param usbInfo : usb handler information + * + * @param reportType : type of report + * + * @param reportID : ID of report + * + * @param buffer : report buffer + * + * @param length : report length + * + * @retval usb host status + */ +static USBH_STA_T USBH_HID_GetReportDesc(USBH_INFO_T* usbInfo, uint8_t reportType, \ + uint8_t reportID, uint8_t* buffer, uint8_t length) +{ + USBH_STA_T usbStatus = USBH_OK; + + usbStatus = USBH_HID_REQ_GetRepDescriptor(usbInfo, ((USBH_REQ_DIR_IN << 7) | \ + (USBH_REQ_TYPE_CLASS << 5) | \ + (USBH_RECIPIENT_INTERFACE)), \ + reportType, + reportID, + buffer, + length); + + return usbStatus; +} + +/*! + * @brief USB host set HID idle + * + * @param usbInfo : usb handler information + * + * @param reportID : traget report ID + * + * @param duration : duration for idle request + * + * @retval usb host status + */ +static USBH_STA_T USBH_HID_SetIdle(USBH_INFO_T* usbInfo, uint8_t reportID, uint8_t duration) +{ + USBH_STA_T usbStatus = USBH_OK; + + usbStatus = USBH_HID_REQ_SetIdle(usbInfo, ((USBH_REQ_DIR_OUT << 7) | \ + (USBH_REQ_TYPE_CLASS << 5) | \ + (USBH_RECIPIENT_INTERFACE)), + reportID, \ + duration); + + return usbStatus; +} + +/*! + * @brief USB host set HID protocol + * + * @param usbInfo : usb handler information + * + * @param protocol : boot / report protocol + * + * @retval usb host status + */ +static USBH_STA_T USBH_HID_SetProtocol(USBH_INFO_T* usbInfo, uint8_t protocol) +{ + USBH_STA_T usbStatus = USBH_OK; + + usbStatus = USBH_HID_REQ_SetProtocol(usbInfo, ((USBH_REQ_DIR_OUT << 7) | \ + (USBH_REQ_TYPE_CLASS << 5) | \ + (USBH_RECIPIENT_INTERFACE)), + protocol); + + return usbStatus; +} + +/*! + * @brief USB host HID init handler + * + * @param usbInfo: usb host information + * + * @retval USB host operation status + */ +static USBH_STA_T USBH_HID_InitHandler(USBH_INFO_T* usbInfo) +{ + USBH_STA_T usbStatus = USBH_OK; + + USBH_HID_INFO_T* usbHostHID = (USBH_HID_INFO_T*)usbInfo->activeClass->classData; + + usbHostHID->callback->InitHandler(usbInfo); + + /* Notify User */ + usbInfo->userCallback(usbInfo, USBH_USER_CLASS_LAUNCHED); + + usbHostHID->state = USBH_HID_IDLE; + + return usbStatus; +} + +/*! + * @brief USB host HID idle handler + * + * @param usbInfo: usb host information + * + * @retval USB host operation status + */ +static USBH_STA_T USBH_HID_IdleHandler(USBH_INFO_T* usbInfo) +{ + USBH_STA_T usbStatus = USBH_OK; + uint8_t reqStatus = USBH_BUSY; + + USBH_HID_INFO_T* usbHostHID = (USBH_HID_INFO_T*)usbInfo->activeClass->classData; + + USBH_USR_Debug("USBH_HID_IdleHandler"); + + reqStatus = USBH_HID_GetReportDesc(usbInfo, + HID_INPUT_REPORT, + 0, + usbHostHID->buffer, + usbHostHID->epSize); + + switch (reqStatus) + { + case USBH_OK: + usbHostHID->state = USBH_HID_SYNC; + break; + + case USBH_BUSY: + usbHostHID->state = USBH_HID_IDLE; + usbStatus = USBH_OK; + break; + + case USBH_ERR_NOT_SUP: + usbHostHID->state = USBH_HID_SYNC; + usbStatus = USBH_OK; + break; + + default: + usbHostHID->state = USBH_HID_ERR; + usbStatus = USBH_FAIL; + break; + } + + return usbStatus; +} + +/*! + * @brief USB host HID SYNC handler + * + * @param usbInfo: usb host information + * + * @retval USB host operation status + */ +static USBH_STA_T USBH_HID_SyncHandler(USBH_INFO_T* usbInfo) +{ + USBH_STA_T usbStatus = USBH_OK; + + USBH_HID_INFO_T* usbHostHID = (USBH_HID_INFO_T*)usbInfo->activeClass->classData; + + USBH_USR_Debug("USBH_HID_SyncHandler"); + + /* Sync with SOF */ + if (usbInfo->timer % 2) + { + usbHostHID->state = USBH_HID_IN_DATA; + } + + return usbStatus; +} + +/*! + * @brief USB host HID get data handler + * + * @param usbInfo: usb host information + * + * @retval USB host operation status + */ +static USBH_STA_T USBH_HID_InDataHandler(USBH_INFO_T* usbInfo) +{ + USBH_STA_T usbStatus = USBH_OK; + + USBH_HID_INFO_T* usbHostHID = (USBH_HID_INFO_T*)usbInfo->activeClass->classData; + + USBH_USR_Debug("USBH_HID_InDataHandler"); + + USBH_IntReceiveDataReq(usbInfo, usbHostHID->inChNum, usbHostHID->buffer, \ + usbHostHID->epSize); + + usbHostHID->state = USBH_HID_POLL; + usbHostHID->timer = usbInfo->timer; + usbHostHID->dataFlag = DISABLE; + + return usbStatus; +} + +/*! + * @brief USB host HID polling handler + * + * @param usbInfo: usb host information + * + * @retval USB host operation status + */ +static USBH_STA_T USBH_HID_PollingHandler(USBH_INFO_T* usbInfo) +{ + USBH_STA_T usbStatus = USBH_OK; + uint8_t usbUrbStatus; + uint8_t reqStatus = USBH_BUSY; + uint32_t xferSize; + + USBH_HID_INFO_T* usbHostHID = (USBH_HID_INFO_T*)usbInfo->activeClass->classData; + + USBH_USR_Debug("USBH_HID_PollingHandler"); + + usbUrbStatus = USBH_ReadUrbStatusCallback(usbInfo, usbHostHID->inChNum); + + switch (usbUrbStatus) + { + case USB_URB_OK: + xferSize = USBH_ReadLastXferSizeCallback(usbInfo, usbHostHID->inChNum); + + if ((xferSize != 0) && (usbHostHID->dataFlag == DISABLE)) + { + usbHostHID->dataFlag = ENABLE; + //USBH_HID_WriteFifo(&usbHostHID->fifo, usbHostHID->buffer, usbHostHID->epSize); + + /* HID event callback */ + USBH_HID_PollCallback(usbInfo); + } + break; + + case USB_URB_STALL: + reqStatus = USBH_ClearFeature(usbInfo, usbHostHID->epAddr); + + switch (reqStatus) + { + case USBH_OK: + usbHostHID->state = USBH_HID_IN_DATA; + break; + + default: + break; + } + break; + + default: + break; + } + + return usbStatus; +} + +/*! + * @brief USB host HID send data handler + * + * @param usbInfo: usb host information + * + * @retval USB host operation status + */ +static USBH_STA_T USBH_HID_OutDataHandler(USBH_INFO_T* usbInfo) +{ + USBH_STA_T usbStatus = USBH_OK; + + return usbStatus; +} + +/*! + * @brief USB host HID busy handler + * + * @param usbInfo: usb host information + * + * @retval USB host operation status + */ +static USBH_STA_T USBH_HID_BusyHandler(USBH_INFO_T* usbInfo) +{ + USBH_STA_T usbStatus = USBH_OK; + + USBH_USR_Debug("USBH_HID_BusyHandler"); + + return usbStatus; +} + +/*! + * @brief USB host HID error handler + * + * @param usbInfo: usb host information + * + * @retval USB host operation status + */ +static USBH_STA_T USBH_HID_ErrorHandler(USBH_INFO_T* usbInfo) +{ + USBH_STA_T usbStatus = USBH_OK; + + USBH_USR_Debug("USBH_HID_ErrorHandler"); + + return usbStatus; +} + +/*! + * @brief Parse HID descriptor + * + * @param hidDesc : HID descriptor + * + * @param buffer : source data of configuration descriptor + * + * @retval usb host status + */ +USBH_STA_T USBH_HidDescParse(USBH_HID_DESC_T* hidDesc, uint8_t* buffer) +{ + USBH_STA_T usbStatus = USBH_OK; + uint16_t totalLenTemp = 0; + uint8_t subLen = 0; + uint16_t parseIndex = 0; + + totalLenTemp = *(uint8_t*)(buffer + 2) | (*(uint8_t*)(buffer + 3) << 8); + totalLenTemp = ((totalLenTemp) < (CFG_DESC_MAX_LEN) ? (totalLenTemp) : (CFG_DESC_MAX_LEN)); + + if (totalLenTemp > STD_CFG_DESC_SIZE) + { + parseIndex = STD_CFG_DESC_SIZE; + + while (totalLenTemp > parseIndex) + { + subLen = buffer[parseIndex]; + + switch (buffer[parseIndex + 1]) + { + case USBH_DESC_HID: + hidDesc->bLength = buffer[parseIndex + 0]; + hidDesc->bDescriptorType = buffer[parseIndex + 1]; + hidDesc->bcdHID[0] = buffer[parseIndex + 2]; + hidDesc->bcdHID[1] = buffer[parseIndex + 3]; + hidDesc->bCountryCode = buffer[parseIndex + 4]; + hidDesc->bNumDescriptors = buffer[parseIndex + 5]; + hidDesc->bReportDescriptorType = buffer[parseIndex + 6]; + hidDesc->wDescriptorLength[0] = buffer[parseIndex + 7]; + hidDesc->wDescriptorLength[1] = buffer[parseIndex + 8]; + break; + + default: + break; + } + + parseIndex += subLen; + + /* To avoid some useless data left */ + if ((totalLenTemp - parseIndex) < STD_EP_DESC_SIZE) + { + break; + } + } + } + + return usbStatus; +} + +/*! + * @brief USB host HID configuration handler + * + * @param usbInfo: usb host information + * + * @retval USB host operation status + */ +static USBH_STA_T USBH_HID_ClassInitHandler(USBH_INFO_T* usbInfo) +{ + USBH_STA_T usbStatus = USBH_OK; + + USBH_HID_INFO_T* usbHostHID; + uint8_t itfNum; + uint8_t subClass; + uint8_t classInterface; + uint8_t protocolInterface; + uint16_t mps; + uint8_t epAddr; + uint8_t pollInterval; + uint8_t epNum; + uint8_t epDir; + + USBH_USR_Debug("USBH_HID_ClassInitHandler"); + + /* Link class data */ + usbInfo->activeClass->classData = (USBH_HID_INFO_T*)malloc(sizeof(USBH_HID_INFO_T)); + usbHostHID = (USBH_HID_INFO_T*)usbInfo->activeClass->classData; + memset(usbHostHID, 0, sizeof(USBH_HID_INFO_T)); + + itfNum = USBH_ReadConfigurationItfNum(usbInfo); + + while (itfNum--) + { + subClass = USBH_ReadInterfaceSubClass(usbInfo, itfNum); + + if (subClass != USBH_HID_BOOT_CODE) + { + USBH_USR_Debug("Interface is not valid"); + usbStatus = USBH_FAIL; + continue; + } + + classInterface = USBH_ReadInterfaceClass(usbInfo, itfNum); + if (classInterface != USBH_CLASS_HID) + { + USBH_USR_Debug("Class type is not support"); + usbStatus = USBH_ERR_NOT_SUP; + continue; + } + + protocolInterface = USBH_ReadInterfaceProtocol(usbInfo, itfNum); + /* Decode class protocol */ + switch (protocolInterface) + { + case USBH_HID_KEYBOARD_BOOT_CODE: + USBH_USR_LOG("Register keyboard class init"); + usbHostHID->callback = &USBH_HID_KEYBOARD_Handler; + usbStatus = USBH_OK; + break; + + case USBH_HID_MOUSE_BOOT_CODE: + USBH_USR_LOG("Register mouse class init"); + usbHostHID->callback = &USBH_HID_MOUSE_Handler; + usbStatus = USBH_OK; + break; + + default: + USBH_USR_LOG("Protocol is not support"); + usbStatus = USBH_FAIL; + break; + } + + epAddr = USBH_ReadEndpointAddress(usbInfo, itfNum, 0); + mps = USBH_ReadEndpointMPS(usbInfo, itfNum, 0); + pollInterval = USBH_ReadEndpointInterval(usbInfo, itfNum, 0); + + usbHostHID->epAddr = epAddr; + usbHostHID->epSize = mps; + usbHostHID->pollInterval = pollInterval; + usbHostHID->state = USBH_HID_INIT; + usbHostHID->classReqState = USBH_HID_REQ_INIT; + + if (usbHostHID->pollInterval < USBH_HID_POLL_MIN_NUM) + { + usbHostHID->pollInterval = USBH_HID_POLL_MIN_NUM; + } + + epNum = USBH_ReadInterfaceEpNum(usbInfo, itfNum); + + if (epNum > ENDPOINT_DESC_MAX_NUM) + { + epNum = ENDPOINT_DESC_MAX_NUM; + } + + while (epNum--) + { + /* Get endpoint and size */ + epDir = epAddr & 0x80; + + if (epDir) + { + usbHostHID->intInEpAddr = USBH_ReadEndpointAddress(usbInfo, itfNum, epNum); + usbHostHID->inChNum = USBH_CH_AllocChannel(usbInfo, usbHostHID->intInEpAddr); + + USBH_OpenChannelCallback(usbInfo, usbHostHID->inChNum, + usbHostHID->intInEpAddr, + usbInfo->devInfo.address, + usbInfo->devInfo.speed, + EP_TYPE_INTERRUPT, + usbHostHID->epSize); + + USBH_ConfigDataPidCallback(usbInfo, usbHostHID->inChNum, 0); + } + else + { + usbHostHID->intOutEpAddr = USBH_ReadEndpointAddress(usbInfo, itfNum, epNum); + usbHostHID->outChNum = USBH_CH_AllocChannel(usbInfo, usbHostHID->intOutEpAddr); + + USBH_OpenChannelCallback(usbInfo, usbHostHID->outChNum, + usbHostHID->intOutEpAddr, + usbInfo->devInfo.address, + usbInfo->devInfo.speed, + EP_TYPE_INTERRUPT, + usbHostHID->epSize); + + USBH_ConfigDataPidCallback(usbInfo, usbHostHID->outChNum, 0); + } + } + } + + return usbStatus; +} + +/*! + * @brief USB host HID class reset handler + * + * @param usbInfo: usb host information + * + * @retval USB host operation status + */ +static USBH_STA_T USBH_HID_ClassDeInitHandler(USBH_INFO_T* usbInfo) +{ + USBH_STA_T usbStatus = USBH_OK; + + USBH_HID_INFO_T* usbHostHID = (USBH_HID_INFO_T*)usbInfo->activeClass->classData; + + USBH_USR_Debug("USBH_HID_ClassDeInitHandler"); + + if (usbHostHID->inChNum != 0) + { + USBH_CloseChannelCallback(usbInfo, usbHostHID->inChNum); + USBH_CH_FreeChannel(usbInfo, usbHostHID->inChNum); + usbHostHID->inChNum = 0; + } + + if (usbHostHID->outChNum != 0) + { + USBH_CloseChannelCallback(usbInfo, usbHostHID->outChNum); + USBH_CH_FreeChannel(usbInfo, usbHostHID->outChNum); + usbHostHID->outChNum = 0; + } + + if (usbInfo->activeClass->classData != NULL) + { + free(usbInfo->activeClass->classData); + usbInfo->activeClass->classData = 0; + } + + return usbStatus; +} + +/*! + * @brief USB host HID class reguest handler + * + * @param usbInfo: usb host information + * + * @retval USB host operation status + */ +static USBH_STA_T USBH_HID_ClassReqHandler(USBH_INFO_T* usbInfo) +{ + USBH_STA_T usbStatus = USBH_BUSY; + uint8_t reqStatus = USBH_BUSY; + USBH_HID_INFO_T* usbHostHID = (USBH_HID_INFO_T*)usbInfo->activeClass->classData; + + uint16_t descLength; + + USBH_USR_Debug("USBH_HID_ClassReqHandler"); + + switch (usbHostHID->classReqState) + { + case USBH_HID_REQ_IDLE: + break; + + case USBH_HID_REQ_INIT: + case USBH_HID_REQ_GET_HID_DESC: + USBH_HidDescParse(&usbHostHID->desc, usbInfo->devInfo.desc.cfgDescBuf); + usbHostHID->classReqState = USBH_HID_REQ_GET_REP_DESC; + break; + + case USBH_HID_REQ_GET_REP_DESC: + descLength = usbHostHID->desc.wDescriptorLength[0] | usbHostHID->desc.wDescriptorLength[1] << 8; + reqStatus = USBH_HID_GetHIDDesc(usbInfo, descLength); + switch (reqStatus) + { + case USBH_OK: + usbHostHID->classReqState = USBH_HID_REQ_SET_IDLE; + break; + + case USBH_ERR_NOT_SUP: + USBH_USR_LOG("Class Req Error: Get report descriptor failed"); + usbStatus = USBH_FAIL; + break; + + default: + break; + } + break; + + case USBH_HID_REQ_SET_IDLE: + reqStatus = USBH_HID_SetIdle(usbInfo, 0, 0); + switch (reqStatus) + { + case USBH_OK: + usbHostHID->classReqState = USBH_HID_REQ_SET_PROTOCOL; + break; + + case USBH_ERR_NOT_SUP: + usbHostHID->classReqState = USBH_HID_REQ_SET_PROTOCOL; + break; + + default: + break; + } + break; + + case USBH_HID_REQ_SET_PROTOCOL: + reqStatus = USBH_HID_SetProtocol(usbInfo, 0); + switch (reqStatus) + { + case USBH_OK: + usbHostHID->classReqState = USBH_HID_REQ_IDLE; + usbStatus = USBH_OK; + break; + + case USBH_ERR_NOT_SUP: + USBH_USR_LOG("Class Req Error: Set protocol failed"); + usbStatus = USBH_FAIL; + break; + + default: + break; + } + break; + + default: + break; + } + + return usbStatus; +} + +/*! + * @brief USB host HID SOF handler + * + * @param usbInfo: usb host information + * + * @retval USB host operation status + */ +static USBH_STA_T USBH_HID_SOFHandler(USBH_INFO_T* usbInfo) +{ + USBH_STA_T usbStatus = USBH_OK; + USBH_HID_INFO_T* usbHostHID = (USBH_HID_INFO_T*)usbInfo->activeClass->classData; + uint32_t interval; + + USBH_USR_Debug("USBH_HID_SOFHandler"); + + if (usbHostHID->state == USBH_HID_POLL) + { + interval = usbInfo->timer - usbHostHID->timer; + + if (interval >= usbHostHID->pollInterval) + { + usbHostHID->state = USBH_HID_IN_DATA; + } + } + + return usbStatus; +} + +/*! + * @brief USB host HID handler + * + * @param usbInfo: usb host information + * + * @retval USB host operation status + */ +static USBH_STA_T USBH_HID_CoreHandler(USBH_INFO_T* usbInfo) +{ + USBH_STA_T usbStatus = USBH_BUSY; + USBH_HID_INFO_T* usbHostHID = (USBH_HID_INFO_T*)usbInfo->activeClass->classData; + + USBH_USR_Debug("USBH_HID_CoreHandler"); + + usbStatus = USBH_HID_Handler[usbHostHID->state](usbInfo); + + return usbStatus; +} + +/*! + * @brief USB host HID handler + * + * @param usbInfo: usb host information + * + * @retval USB host operation status + */ +__weak void USBH_HID_PollCallback(USBH_INFO_T* usbInfo) +{ + USBH_HID_INFO_T* usbHostHID = (USBH_HID_INFO_T*)usbInfo->activeClass->classData; + + /* callback interface */ + usbHostHID->callback->DecodeHandler(usbInfo); +} + +/**@} end of group USBH_HID_Functions */ +/**@} end of group USBH_HID_Class */ +/**@} end of group APM32_USB_Library */ diff --git a/lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Class/HID/Src/usbh_hid_keyboard.c b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Class/HID/Src/usbh_hid_keyboard.c new file mode 100644 index 0000000000..b67123dec2 --- /dev/null +++ b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Class/HID/Src/usbh_hid_keyboard.c @@ -0,0 +1,192 @@ +/*! + * @file usbh_hid_keyboard.c + * + * @brief USB host HID keyboard function + * + * @version V1.0.0 + * + * @date 2023-01-16 + * + * @attention + * + * Copyright (C) 2023 Geehy Semiconductor + * + * You may not use this file except in compliance with the + * GEEHY COPYRIGHT NOTICE (GEEHY SOFTWARE PACKAGE LICENSE). + * + * The program is only for reference, which is distributed in the hope + * that it will be useful and instructional for customers to develop + * their software. Unless required by applicable law or agreed to in + * writing, the program is distributed on an "AS IS" BASIS, WITHOUT + * ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied. + * See the GEEHY SOFTWARE PACKAGE LICENSE for the governing permissions + * and limitations under the License. + */ + +/* Includes */ +#include "usbh_hid_keyboard.h" + +/** @addtogroup APM32_USB_Library + @{ + */ + +/** @addtogroup USBH_HID_Class + @{ + */ + +/** @defgroup USBH_HID_Structures Structures + @{ + */ + +USBH_HID_KEYBOARD_INFO_T usbHostHidKeyboard; + +/* HID keyboard class handler */ +USBH_HID_CLASS_T USBH_HID_KEYBOARD_Handler = +{ + USBH_HID_KeyBoardInit, + USBH_HID_KeyboardDecode, +}; + +/**@} end of group USBH_HID_Structures*/ + +/** @defgroup USBH_HID_Functions Functions + @{ + */ + +/*! + * @brief USB host HID init keyboard + * + * @param usbInfo: usb host information + * + * @retval USB host operation status + */ +USBH_STA_T USBH_HID_KeyBoardInit(USBH_INFO_T* usbInfo) +{ + USBH_STA_T usbStatus = USBH_OK; + USBH_HID_INFO_T* usbHostHID = (USBH_HID_INFO_T*)usbInfo->activeClass->classData; + uint16_t i; + + usbHostHidKeyboard.ctrlLeft = 0; + usbHostHidKeyboard.altLeft = 0; + usbHostHidKeyboard.shiftLeft = 0; + usbHostHidKeyboard.winLeft = 0; + + usbHostHidKeyboard.ctrlRight = 0; + usbHostHidKeyboard.altRight = 0; + usbHostHidKeyboard.shiftRight = 0; + usbHostHidKeyboard.winRight = 0; + + for (i = 0; i < USBH_HID_KEY_PRESSED_NUM_MAX; i++) + { + usbHostHidKeyboard.key[i] = 0; + } + + for (i = 0; i < (sizeof(usbHostHidKeyboard.report.data) \ + / sizeof(usbHostHidKeyboard.report.data[0])); i++) + { + usbHostHidKeyboard.report.data[i] = 0; + usbHostHidKeyboard.report.rxBuffer[i] = 0; + } + + if (usbHostHID->epSize > sizeof(usbHostHidKeyboard.report.data)) + { + usbHostHID->epSize = (uint16_t)sizeof(usbHostHidKeyboard.report.data); + } + + /* Init buffer point */ + usbHostHID->buffer = (uint8_t*)(void*)usbHostHidKeyboard.report.data; + + return usbStatus; +} + +/*! + * @brief USB host HID decode keyboard + * + * @param usbInfo: usb host information + * + * @retval USB host operation status + */ +USBH_STA_T USBH_HID_KeyboardDecode(USBH_INFO_T* usbInfo) +{ + USBH_STA_T usbStatus = USBH_OK; + + uint8_t funKeyTemp; + uint8_t i; + + if ((usbHostHidKeyboard.report.data[1] == 0x01010101) && \ + (usbHostHidKeyboard.report.data[0] == 0x01010000)) + { + USBH_USR_LOG("Keyboard do not support this operation"); + } + else + { + for (i = 2; i < 2 + USBH_HID_KEY_PRESSED_NUM_MAX; i++) + { + funKeyTemp = *((uint8_t*)(void*)usbHostHidKeyboard.report.data + i); + if ((funKeyTemp == KEYBOARD_ERROR_ROLL_OVER) || \ + (funKeyTemp == KEYBOARD_POST_FAIL) || \ + (funKeyTemp == KEYBOARD_ERROR_UNDEFINED)) + { + return USBH_FAIL; + } + } + + funKeyTemp = *((uint8_t*)(void*)usbHostHidKeyboard.report.data + 0); + + usbHostHidKeyboard.ctrlLeft = (funKeyTemp & 0x01) > 0 ? 1 : 0; + usbHostHidKeyboard.shiftLeft = (funKeyTemp & 0x02) > 0 ? 1 : 0; + usbHostHidKeyboard.altLeft = (funKeyTemp & 0x04) > 0 ? 1 : 0; + usbHostHidKeyboard.winLeft = (funKeyTemp & 0x08) > 0 ? 1 : 0; + + usbHostHidKeyboard.ctrlRight = (funKeyTemp & 0x10) > 0 ? 1 : 0; + usbHostHidKeyboard.shiftRight = (funKeyTemp & 0x20) > 0 ? 1 : 0; + usbHostHidKeyboard.altRight = (funKeyTemp & 0x40) > 0 ? 1 : 0; + usbHostHidKeyboard.winRight = (funKeyTemp & 0x80) > 0 ? 1 : 0; + + for (i = 0; i < USBH_HID_KEY_PRESSED_NUM_MAX; i++) + { + usbHostHidKeyboard.key[i] = *((uint8_t*)(void*)usbHostHidKeyboard.report.data + i + 2); + } + + /* Process keyboard data */ + USBH_HID_KeyboardCallback(usbInfo); + } + + return usbStatus; +} + +/*! + * @brief USB host HID keyboard data process + * + * @param usbInfo: usb host information + * + * @retval USB host operation status + */ +__weak USBH_STA_T USBH_HID_KeyboardCallback(USBH_INFO_T* usbInfo) +{ + USBH_STA_T usbStatus = USBH_OK; + uint8_t i; + + USBH_USR_LOG("CTRL L:%02X", usbHostHidKeyboard.ctrlLeft); + USBH_USR_LOG("SHIFT L:%02X", usbHostHidKeyboard.shiftLeft); + USBH_USR_LOG("ALT L:%02X", usbHostHidKeyboard.altLeft); + USBH_USR_LOG("WIN L:%02X", usbHostHidKeyboard.winLeft); + + USBH_USR_LOG("CTRL R:%02X", usbHostHidKeyboard.ctrlRight); + USBH_USR_LOG("SHIFT R:%02X", usbHostHidKeyboard.shiftRight); + USBH_USR_LOG("ALT R:%02X", usbHostHidKeyboard.altRight); + USBH_USR_LOG("WIN R:%02X", usbHostHidKeyboard.winRight); + + for (i = 0; i < USBH_HID_KEY_PRESSED_NUM_MAX; i++) + { + USBH_USR_LOG("KEY[%d] :%02X", i, usbHostHidKeyboard.key[i]); + } + + USBH_USR_LOG(" "); + + return usbStatus; +} + +/**@} end of group USBH_HID_Functions */ +/**@} end of group USBH_HID_Class */ +/**@} end of group APM32_USB_Library */ diff --git a/lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Class/HID/Src/usbh_hid_mouse.c b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Class/HID/Src/usbh_hid_mouse.c new file mode 100644 index 0000000000..35ee596e68 --- /dev/null +++ b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Class/HID/Src/usbh_hid_mouse.c @@ -0,0 +1,154 @@ +/*! + * @file usbh_hid_mouse.c + * + * @brief USB host HID mouse function + * + * @version V1.0.0 + * + * @date 2023-01-16 + * + * @attention + * + * Copyright (C) 2023 Geehy Semiconductor + * + * You may not use this file except in compliance with the + * GEEHY COPYRIGHT NOTICE (GEEHY SOFTWARE PACKAGE LICENSE). + * + * The program is only for reference, which is distributed in the hope + * that it will be useful and instructional for customers to develop + * their software. Unless required by applicable law or agreed to in + * writing, the program is distributed on an "AS IS" BASIS, WITHOUT + * ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied. + * See the GEEHY SOFTWARE PACKAGE LICENSE for the governing permissions + * and limitations under the License. + */ + +/* Includes */ +#include "usbh_hid_mouse.h" + +/** @addtogroup APM32_USB_Library + @{ + */ + +/** @addtogroup USBH_HID_Class + @{ + */ + +/** @defgroup USBH_HID_Structures Structures + @{ + */ + +USBH_HID_MOUSE_INFO_T usbHostHidMouse; + +/* HID mouse class handler */ +USBH_HID_CLASS_T USBH_HID_MOUSE_Handler = +{ + USBH_HID_MouseInit, + USBH_HID_MouseDecode, +}; + +/**@} end of group USBH_HID_Structures*/ + +/** @defgroup USBH_HID_Functions Functions + @{ + */ + +/*! + * @brief USB host HID init mouse + * + * @param usbInfo: usb host information + * + * @retval USB host operation status + */ +USBH_STA_T USBH_HID_MouseInit(USBH_INFO_T* usbInfo) +{ + USBH_STA_T usbStatus = USBH_OK; + USBH_HID_INFO_T* usbHostHID = (USBH_HID_INFO_T*)usbInfo->activeClass->classData; + uint16_t i; + + usbHostHidMouse.x = 0; + usbHostHidMouse.y = 0; + + for (i = 0; i < USBH_HID_MOUSE_BUTTON_MAX_NUM; i++) + { + usbHostHidMouse.button[i] = 0; + } + + for (i = 0; i < (sizeof(usbHostHidMouse.report.data) \ + / sizeof(usbHostHidMouse.report.data[0])); i++) + { + usbHostHidMouse.report.data[i] = 0; + usbHostHidMouse.report.rxBuffer[i] = 0; + } + + if (usbHostHID->epSize > sizeof(usbHostHidMouse.report.data)) + { + usbHostHID->epSize = (uint16_t)sizeof(usbHostHidMouse.report.data); + } + + /* Init buffer point */ + usbHostHID->buffer = (uint8_t*)(void*)usbHostHidMouse.report.data; + + return usbStatus; +} + +/*! + * @brief USB host HID decode mouse + * + * @param usbInfo: usb host information + * + * @retval USB host operation status + */ +USBH_STA_T USBH_HID_MouseDecode(USBH_INFO_T* usbInfo) +{ + USBH_STA_T usbStatus = USBH_OK; + + uint8_t buttonTemp; + uint8_t coordinateX; + uint8_t coordinateY; + uint8_t coordinateZ; + + buttonTemp = *((uint8_t*)(void*)usbHostHidMouse.report.data + 0); + coordinateX = *((uint8_t*)(void*)usbHostHidMouse.report.data + 1); + coordinateY = *((uint8_t*)(void*)usbHostHidMouse.report.data + 2); + coordinateZ = *((uint8_t*)(void*)usbHostHidMouse.report.data + 3); + + usbHostHidMouse.button[0] = (buttonTemp & 0x01) > 0 ? 1 : 0; + usbHostHidMouse.button[1] = (buttonTemp & 0x02) > 0 ? 1 : 0; + usbHostHidMouse.button[2] = (buttonTemp & 0x04) > 0 ? 1 : 0; + + usbHostHidMouse.x = coordinateX; + usbHostHidMouse.y = coordinateY; + usbHostHidMouse.z = coordinateZ; + + /* Process mouse data */ + USBH_HID_MouseCallback(usbInfo); + + return usbStatus; +} + +/*! + * @brief USB host HID mouse data process + * + * @param usbInfo: usb host information + * + * @retval USB host operation status + */ +__weak USBH_STA_T USBH_HID_MouseCallback(USBH_INFO_T* usbInfo) +{ + USBH_STA_T usbStatus = USBH_OK; + + USBH_USR_LOG("x:%02X", usbHostHidMouse.x); + USBH_USR_LOG("y:%02X", usbHostHidMouse.y); + USBH_USR_LOG("z:%02X", usbHostHidMouse.z); + USBH_USR_LOG("b1:%02X", usbHostHidMouse.button[0]); + USBH_USR_LOG("b2:%02X", usbHostHidMouse.button[1]); + USBH_USR_LOG("b3:%02X", usbHostHidMouse.button[2]); + USBH_USR_LOG(" "); + + return usbStatus; +} + +/**@} end of group USBH_HID_Functions */ +/**@} end of group USBH_HID_Class */ +/**@} end of group APM32_USB_Library */ diff --git a/lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Class/MSC/Inc/usbh_msc.h b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Class/MSC/Inc/usbh_msc.h new file mode 100644 index 0000000000..df31b8f7eb --- /dev/null +++ b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Class/MSC/Inc/usbh_msc.h @@ -0,0 +1,167 @@ +/*! + * @file usbh_msc.h + * + * @brief usb host msc class handler header file + * + * @version V1.0.0 + * + * @date 2023-01-16 + * + * @attention + * + * Copyright (C) 2023 Geehy Semiconductor + * + * You may not use this file except in compliance with the + * GEEHY COPYRIGHT NOTICE (GEEHY SOFTWARE PACKAGE LICENSE). + * + * The program is only for reference, which is distributed in the hope + * that it will be useful and instructional for customers to develop + * their software. Unless required by applicable law or agreed to in + * writing, the program is distributed on an "AS IS" BASIS, WITHOUT + * ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied. + * See the GEEHY SOFTWARE PACKAGE LICENSE for the governing permissions + * and limitations under the License. + */ + +/* Define to prevent recursive inclusion */ +#ifndef _USBH_MSC_H_ +#define _USBH_MSC_H_ + +/* Includes */ +#include "usbh_core.h" +#include "usbh_msc_scsi.h" +#include "usbh_msc_bot.h" + +/** @addtogroup APM32_USB_Library + @{ + */ + +/** @addtogroup USBH_MSC_Class + @{ + */ + +/** @defgroup USBH_MSC_Macros Macros + @{ +*/ + +#define USBH_CLASS_GET_MAX_LUN 0xFE +#define USBH_CLASS_BOT_RESET 0xFF +#define USBH_SUPPORTED_LUN_MAX 0x02 +#define USBH_MSC_SCSI_CLASS_CODE 0x06 + +/**@} end of group USBH_MSC_Macros*/ + +/** @defgroup USBH_MSC_Enumerates Enumerates + @{ + */ + +/** + * @brief MSC state table + */ +typedef enum +{ + USBH_MSC_INIT = 0, + USBH_MSC_IDLE = 1, + USBH_MSC_INQUIRY, + USBH_MSC_TEST_UNIT_READY, + USBH_MSC_REQUEST_SENSE, + USBH_MSC_READ_CAPACITY, + USBH_MSC_UNRECOVERED_STATE, + + USBH_MSC_RW_READ, + USBH_MSC_RW_WRITE, + USBH_MSC_RW_REQIEST_SENSE, +} USBH_MSC_STATE_T; + +/** + * @brief MSC error state type + */ +typedef enum +{ + USBH_MSC_OK, + USBH_MSC_BUSY, + USBH_MSC_ERR, +} USBH_MSC_ERR_STATE_T; + +/** + * @brief MSC class request state table + */ +typedef enum +{ + USBH_MSC_REQ_GET_MAX_LUN, + USBH_MSC_REQ_BOT_RESET, + USBH_MSC_REQ_CTRL_ERROR +} USBH_MSC_REQ_STATE_T; + +/** + * @brief MSC protocol code + */ +typedef enum +{ + USBH_MSC_PROTOCOL_CBI_00 = 0x00, + USBH_MSC_PROTOCOL_CBI_01 = 0x01, + USBH_MSC_PROTOCOL_BBB = 0x50, + USBH_MSC_PROTOCOL_UAS = 0x62 +} USBH_MSC_PROTOCOL_CODE_T; + +/**@} end of group USBH_MSC_Enumerates*/ + +/** @defgroup USBH_MSC_Structures Structures + @{ + */ + +/** + * @brief MSC Storage info + */ +typedef struct +{ + USBH_SCSI_READ_CAPACITY_REQ_T capacity; + USBH_SCSI_INQUIRY_REQ_T inquiryReq; + USBH_SCSI_SENSE_REQ_T sense; + USBH_MSC_STATE_T state; + uint8_t changeState; + uint8_t preReadyState; + USBH_MSC_ERR_STATE_T errState; +} USBH_MSC_STORAGE_INFO_T; + +/* Host MSC class state handler function */ +typedef USBH_STA_T(*USBH_MscStateHandler_T)(USBH_INFO_T* usbInfo, uint8_t lun); + +/** + * @brief MSC information management + */ +typedef struct +{ + USBH_MSC_STATE_T state; + USBH_MSC_ERR_STATE_T errState; + USBH_MSC_REQ_STATE_T preClassReqState; + USBH_MSC_REQ_STATE_T classReqState; + uint8_t maxLun; + uint8_t curLun; + uint8_t opLun; + uint32_t timer; + USBH_MSC_STORAGE_INFO_T storage[USBH_SUPPORTED_LUN_MAX]; + USBH_BOT_INFO_T usbHostBOT; +} USBH_MSC_INFO_T; + +extern USBH_CLASS_T USBH_MSC_CLASS; + +/**@} end of group USBH_MSC_Structures*/ + +/** @defgroup USBH_MSC_Functions Functions + @{ + */ + +USBH_STA_T USBH_MSC_ReadDevInfo(USBH_INFO_T* usbInfo, uint8_t lun, USBH_MSC_STORAGE_INFO_T* device); +uint8_t USBH_MSC_DevStatus(USBH_INFO_T* usbInfo, uint8_t lun); +uint8_t USBH_MSC_ReadDevWP(USBH_INFO_T* usbInfo, uint8_t lun); +USBH_STA_T USBH_MSC_DevRead(USBH_INFO_T* usbInfo, uint8_t lun, uint32_t address, \ + uint8_t* buffer, uint16_t cnt); +USBH_STA_T USBH_MSC_DevWrite(USBH_INFO_T* usbInfo, uint8_t lun, uint32_t address, \ + uint8_t* buffer, uint16_t cnt); + +/**@} end of group USBH_MSC_Functions */ +/**@} end of group USBH_MSC_Class */ +/**@} end of group APM32_USB_Library */ + +#endif diff --git a/lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Class/MSC/Inc/usbh_msc_bot.h b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Class/MSC/Inc/usbh_msc_bot.h new file mode 100644 index 0000000000..bc72bdcca9 --- /dev/null +++ b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Class/MSC/Inc/usbh_msc_bot.h @@ -0,0 +1,203 @@ +/*! + * @file usbh_msc_bot.h + * + * @brief USB host MSC bot + * + * @version V1.0.0 + * + * @date 2023-01-16 + * + * @attention + * + * Copyright (C) 2023 Geehy Semiconductor + * + * You may not use this file except in compliance with the + * GEEHY COPYRIGHT NOTICE (GEEHY SOFTWARE PACKAGE LICENSE). + * + * The program is only for reference, which is distributed in the hope + * that it will be useful and instructional for customers to develop + * their software. Unless required by applicable law or agreed to in + * writing, the program is distributed on an "AS IS" BASIS, WITHOUT + * ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied. + * See the GEEHY SOFTWARE PACKAGE LICENSE for the governing permissions + * and limitations under the License. + */ + +/* Define to prevent recursive inclusion */ +#ifndef _USBH_MSC_BOT_H_ +#define _USBH_MSC_BOT_H_ + +/* Includes */ +#include "usbh_core.h" + +/** @addtogroup APM32_USB_Library + @{ + */ + +/** @addtogroup USBH_MSC_Class + @{ + */ + +/** @defgroup USBH_MSC_Macros Macros + @{ +*/ + +/* CBW parameter */ +#define USBH_MSC_BOT_CBW_SIGNATURE (uint32_t)(0x43425355) +#define USBH_MSC_BOT_CBW_TAG (uint32_t)(0x20304050) +#define USBH_MSC_BOT_CBW_LEN 31 +#define USBH_BOT_CBW_CB_LEN 16 +#define USBH_LEN_CBW 10 + +/* CSW parameter */ +#define USBH_MSC_BOT_CSW_SIGNATURE (uint32_t)(0x53425355) +#define USBH_MSC_BOT_CSW_LEN 13 +#define USBH_LEN_CSW_MAX 63 + +/**@} end of group USBH_MSC_Macros*/ + +/** @defgroup USBH_MSC_Enumerates Enumerates + @{ + */ + +/** + * @brief SCSI transmission state of BOT + */ +typedef enum +{ + USBH_BOT_SEND_CBW, + USBH_BOT_SEND_CBW_WAIT, + USBH_BOT_DATAIN, + USBH_BOT_DATAIN_WAIT, + USBH_BOT_DATAOUT, + USBH_BOT_DATAOUT_WAIT, + USBH_BOT_RECEIVE_CSW, + USBH_BOT_RECEIVE_CSW_WAIT, + USBH_BOT_ERROR_IN, + USBH_BOT_ERROR_OUT, + USBH_BOT_ERROR_UNRECOVERED, +} USBH_BOT_STATE_T; + +/** + * @brief CSW status + */ +typedef enum +{ + USBH_BOT_CSW_OK, + USBH_BOT_CSW_FAIL, + USBH_BOT_CSW_ERR, +} USBH_BOT_CSW_STA_T; + +/** + * @brief SCSI transmission command state of BOT + */ +typedef enum +{ + USBH_BOT_XFER_IDLE, + USBH_BOT_XFER_START, + USBH_BOT_XFER_WAITING, +} USBH_BOT_XFER_STA_T; + +/**@} end of group USBH_MSC_Enumerates*/ + +/** @defgroup USBH_MSC_Structures Structures + @{ + */ + +/** + * @brief CBW flag + */ +typedef union +{ + uint8_t CBW_Flag; + + struct + { + uint8_t reserved : 7; + uint8_t dir : 1; + } CBW_FLAG_B; + +} USBH_BOT_CBW_FLAG_T; + +/** + * @brief Command Block Wrapper + */ +typedef union +{ + struct + { + uint32_t dSignature; + uint32_t dTag; + uint32_t dDataXferLen; + USBH_BOT_CBW_FLAG_T bmFlags; + uint8_t bLUN; + uint8_t bCBLen; + uint8_t CB[16]; + } DATA_FIELD; + + uint8_t buffer[31]; +} USBH_BOT_CBW_T; + +/** + * @brief Command Status Wrapper + */ +typedef union +{ + struct + { + uint32_t dSignature; + uint32_t dTag; + uint32_t dDataResidue; + uint8_t bStatus; + } DATA_FIELD; + + uint8_t buffer[13]; +} USBH_BOT_CSW_T; + +/** + * @brief BOT transmission parameter + */ +typedef struct +{ + USBH_BOT_CBW_T CBW; + USBH_BOT_CSW_T CSW; +} USBH_BOT_CMDPACK_T; + +/* Host BOT state handler function */ +typedef USBH_STA_T(*USBH_BotStateHandler_T)(struct _USBH_INFO_T* usbInfo, uint8_t lun); + +/** + * @brief MSC BOT information + */ +typedef struct +{ + uint8_t* buffer; + uint32_t data[16]; + uint8_t inChNum; + uint8_t outChNum; + uint8_t bulkOutEpAddr; + uint8_t bulkInEpAddr; + uint16_t bulkInEpSize; + uint16_t bulkOutEpSize; + USBH_BOT_STATE_T state; + uint8_t xferState; + USBH_BOT_CMDPACK_T cmdPack; +} USBH_BOT_INFO_T; + +extern USBH_BotStateHandler_T USBH_MSC_BOT_Handler[]; + +/**@} end of group USBH_MSC_Structures*/ + +/** @defgroup USBH_MSC_Functions Functions + @{ + */ + +USBH_STA_T USBH_MSC_BOT_Init(USBH_INFO_T* usbInfo); +USBH_STA_T USBH_MSC_BOT_REQ_Reset(USBH_INFO_T* usbInfo); +USBH_STA_T USBH_MSC_BOT_REQ_GetMaxLunHandler(USBH_INFO_T* usbInfo, uint8_t* maxLun); + +/**@} end of group USBH_MSC_Functions */ +/**@} end of group USBH_MSC_Class */ +/**@} end of group APM32_USB_Library */ + +#endif diff --git a/lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Class/MSC/Inc/usbh_msc_scsi.h b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Class/MSC/Inc/usbh_msc_scsi.h new file mode 100644 index 0000000000..0f80c9cd8d --- /dev/null +++ b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Class/MSC/Inc/usbh_msc_scsi.h @@ -0,0 +1,191 @@ +/*! + * @file usbh_msc_scsi.h + * + * @brief USB host MSC scsi + * + * @version V1.0.0 + * + * @date 2023-01-16 + * + * @attention + * + * Copyright (C) 2023 Geehy Semiconductor + * + * You may not use this file except in compliance with the + * GEEHY COPYRIGHT NOTICE (GEEHY SOFTWARE PACKAGE LICENSE). + * + * The program is only for reference, which is distributed in the hope + * that it will be useful and instructional for customers to develop + * their software. Unless required by applicable law or agreed to in + * writing, the program is distributed on an "AS IS" BASIS, WITHOUT + * ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied. + * See the GEEHY SOFTWARE PACKAGE LICENSE for the governing permissions + * and limitations under the License. + */ + +/* Define to prevent recursive inclusion */ +#ifndef __USBH_MSC_SCSI_H_ +#define __USBH_MSC_SCSI_H_ + +/* Includes */ +#include "usbh_core.h" + +/** @addtogroup APM32_USB_Library + @{ + */ + +/** @addtogroup USBH_MSC_Class + @{ + */ + +/** @defgroup USBH_MSC_Macros Macros + @{ +*/ + +/* Length define of command */ +#define LEN_XFER_TEST_UNIT_READY 0 +#define LEN_XFER_READ_CAPACITY 8 +#define LEN_XFER_REQUEST_SENSE 14 +#define LEN_XFER_INQUIRY 36 + +/* SCSI Commands */ +#define USBH_SCSI_CMD_FORMAT_UNIT ((uint8_t)0x04) +#define USBH_SCSI_CMD_INQUIRY ((uint8_t)0x12) +#define USBH_SCSI_CMD_MODE_SELECT_6 ((uint8_t)0x15) +#define USBH_SCSI_CMD_MODE_SELECT_10 ((uint8_t)0x55) +#define USBH_SCSI_CMD_MODE_SENSE_6 ((uint8_t)0x1A) +#define USBH_SCSI_CMD_MODE_SENSE_10 ((uint8_t)0x5A) +#define USBH_SCSI_CMD_ALLOW_MEDIUM_REMOVAL ((uint8_t)0x1E) +#define USBH_SCSI_CMD_READ_6 ((uint8_t)0x08) +#define USBH_SCSI_CMD_READ_10 ((uint8_t)0x28) +#define USBH_SCSI_CMD_READ_12 ((uint8_t)0xA8) +#define USBH_SCSI_CMD_READ_16 ((uint8_t)0x88) + +#define USBH_SCSI_CMD_READ_CAPACITY ((uint8_t)0x25) +#define USBH_SCSI_CMD_READ_CAPACITY_16 ((uint8_t)0x9E) + +#define USBH_SCSI_CMD_REQUEST_SENSE ((uint8_t)0x03) +#define USBH_SCSI_CMD_START_STOP_UNIT ((uint8_t)0x1B) +#define USBH_SCSI_CMD_TEST_UNIT_READY ((uint8_t)0x00) +#define USBH_SCSI_CMD_WRITE6 ((uint8_t)0x0A) +#define USBH_SCSI_CMD_WRITE10 ((uint8_t)0x2A) +#define USBH_SCSI_CMD_WRITE12 ((uint8_t)0xAA) +#define USBH_SCSI_CMD_WRITE16 ((uint8_t)0x8A) + +#define USBH_SCSI_CMD_VERIFY_10 ((uint8_t)0x2F) +#define USBH_SCSI_CMD_VERIFY_12 ((uint8_t)0xAF) +#define USBH_SCSI_CMD_VERIFY_16 ((uint8_t)0x8F) + +#define USBH_SCSI_CMD_SEND_DIAGNOSTIC ((uint8_t)0x1D) +#define USBH_SCSI_CMD_READ_FORMAT_CAPACITIES ((uint8_t)0x23) + +/**@} end of group USBH_MSC_Macros*/ + +/** @defgroup USBH_MSC_Enumerates Enumerates + @{ + */ + +/** + * @brief SCSI sense ASC type + */ +typedef enum +{ + USBH_SCSI_ASC_NO_ADDITIONAL_SENSE_INFORMATION = 0x00, + USBH_SCSI_ASCQ_FORMAT_COMMAND_FAILED = 0x01, + USBH_SCSI_ASCQ_INITIALIZING_COMMAND_REQUIRED = 0x02, + USBH_SCSI_ASC_LOGICAL_UNIT_NOT_READY = 0x04, + USBH_SCSI_ASCQ_OPERATION_IN_PROGRESS = 0x07, + USBH_SCSI_ASC_INVALID_COMMAND_OPERATION_CODE = 0x20, + USBH_SCSI_ASC_INVALID_FIELD_IN_CDB = 0x24, + USBH_SCSI_ASC_WRITE_PROTECTED = 0x27, + USBH_SCSI_ASC_NOT_READY_TO_READY_CHANGE = 0x28, + USBH_SCSI_ASC_FORMAT_ERROR = 0x31, + USBH_SCSI_ASC_MEDIUM_NOT_PRESENT = 0x3A, +} USBH_SCSI_SENSE_ASC_T; + +/** + * @brief SCSI sense key type + */ +typedef enum +{ + USBH_SCSI_SENSE_KEY_NO_SENSE = 0x00, + USBH_SCSI_SENSE_KEY_RECOVERED_ERROR, + USBH_SCSI_SENSE_KEY_NOT_READY, + USBH_SCSI_SENSE_KEY_MEDIUM_ERROR, + USBH_SCSI_SENSE_KEY_HARDWARE_ERROR, + USBH_SCSI_SENSE_KEY_ILLEGAL_REQUEST, + USBH_SCSI_SENSE_KEY_UNIT_ATTENTION, + USBH_SCSI_SENSE_KEY_DATA_PROTECT, + USBH_SCSI_SENSE_KEY_BLANK_CHECK, + USBH_SCSI_SENSE_KEY_VENDOR_SPECIFIC, + USBH_SCSI_SENSE_KEY_COPY_ABORTED, + USBH_SCSI_SENSE_KEY_ABORTED_COMMAND, + USBH_SCSI_SENSE_KEY_VOLUME_OVERFLOW = 0x0D, + USBH_SCSI_SENSE_KEY_MISCOMPARE = 0x0E, +} USBH_SCSI_SENSE_KEY_T; + +/**@} end of group USBH_MSC_Enumerates*/ + +/** @defgroup USBH_MSC_Structures Structures + @{ + */ + +/** + * @brief SCSI inquiry response data type + */ +typedef struct +{ + uint8_t peripheral; + uint8_t devType; + uint8_t media; + uint8_t vendorID[9]; + uint8_t productID[17]; + uint8_t revID[5]; +} USBH_SCSI_INQUIRY_REQ_T; + +/** + * @brief SCSI read capacity response data type + */ +typedef struct +{ + uint32_t blockNum; + uint32_t blockSize; +} USBH_SCSI_READ_CAPACITY_REQ_T; + +/** + * @brief SCSI sense response data type + */ +typedef struct +{ + uint8_t key; + uint8_t asc; + uint8_t ascq; +} USBH_SCSI_SENSE_REQ_T; + +/**@} end of group USBH_MSC_Structures*/ + +/** @defgroup USBH_MSC_Functions Functions + @{ + */ + +USBH_STA_T USBH_MSC_SCSI_Inquiry(USBH_INFO_T* usbInfo, uint8_t lun, \ + USBH_SCSI_INQUIRY_REQ_T* inquiry); +USBH_STA_T USBH_MSC_SCSI_TestUnitReady(USBH_INFO_T* usbInfo, uint8_t lun); + +USBH_STA_T USBH_MSC_SCSI_ReadCapacity(USBH_INFO_T* usbInfo, uint8_t lun, \ + USBH_SCSI_READ_CAPACITY_REQ_T* capacity); + +USBH_STA_T USBH_MSC_SCSI_RequestSense(USBH_INFO_T* usbInfo, uint8_t lun, \ + USBH_SCSI_SENSE_REQ_T* sense); + +USBH_STA_T USBH_MSC_SCSI_Read(USBH_INFO_T* usbInfo, uint8_t lun, uint32_t address, \ + uint8_t* buffer, uint16_t cnt); + +USBH_STA_T USBH_MSC_SCSI_Write(USBH_INFO_T* usbInfo, uint8_t lun, uint32_t address, \ + uint8_t* buffer, uint16_t cnt); + +/**@} end of group USBH_MSC_Functions */ +/**@} end of group USBH_MSC_Class */ +/**@} end of group APM32_USB_Library */ + +#endif diff --git a/lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Class/MSC/Src/usbh_msc.c b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Class/MSC/Src/usbh_msc.c new file mode 100644 index 0000000000..6713b588b6 --- /dev/null +++ b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Class/MSC/Src/usbh_msc.c @@ -0,0 +1,1023 @@ +/*! + * @file usbh_msc.c + * + * @brief usb host msc class handler + * + * @version V1.0.0 + * + * @date 2023-01-16 + * + * @attention + * + * Copyright (C) 2023 Geehy Semiconductor + * + * You may not use this file except in compliance with the + * GEEHY COPYRIGHT NOTICE (GEEHY SOFTWARE PACKAGE LICENSE). + * + * The program is only for reference, which is distributed in the hope + * that it will be useful and instructional for customers to develop + * their software. Unless required by applicable law or agreed to in + * writing, the program is distributed on an "AS IS" BASIS, WITHOUT + * ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied. + * See the GEEHY SOFTWARE PACKAGE LICENSE for the governing permissions + * and limitations under the License. + */ + +/* Includes */ +#include "usbh_msc.h" +#include "usbh_msc_bot.h" +#include +#include +#include + +/** @addtogroup APM32_USB_Library + @{ + */ + +/** @addtogroup USBH_MSC_Class + @{ + */ + +/** @defgroup USBH_MSC_Functions Functions + @{ + */ + +static USBH_STA_T USBH_MSC_ClassInitHandler(USBH_INFO_T* usbInfo); +static USBH_STA_T USBH_MSC_ClassDeInitHandler(USBH_INFO_T* usbInfo); +static USBH_STA_T USBH_MSC_ClassReqHandler(USBH_INFO_T* usbInfo); +static USBH_STA_T USBH_MSC_CoreHandler(USBH_INFO_T* usbInfo); +static USBH_STA_T USBH_MSC_SOFHandler(USBH_INFO_T* usbInfo); + +static USBH_STA_T USBH_MSC_IdleHandler(USBH_INFO_T* usbInfo, uint8_t lun); +static USBH_STA_T USBH_MSC_InitHandler(USBH_INFO_T* usbInfo, uint8_t lun); +static USBH_STA_T USBH_MSC_InquiryHandler(USBH_INFO_T* usbInfo, uint8_t lun); +static USBH_STA_T USBH_MSC_TestUnitReadyHandler(USBH_INFO_T* usbInfo, uint8_t lun); +static USBH_STA_T USBH_MSC_RequestSenseHandler(USBH_INFO_T* usbInfo, uint8_t lun); +static USBH_STA_T USBH_MSC_ReadCapacityHandler(USBH_INFO_T* usbInfo, uint8_t lun); +static USBH_STA_T USBH_MSC_ErrorUnrecoveredHandler(USBH_INFO_T* usbInfo, uint8_t lun); + +static USBH_STA_T USBH_MSC_ReadHandler(USBH_INFO_T* usbInfo, uint8_t lun); +static USBH_STA_T USBH_MSC_WriteHandler(USBH_INFO_T* usbInfo, uint8_t lun); +static USBH_STA_T USBH_MSC_RWRequestSenseHandler(USBH_INFO_T* usbInfo, uint8_t lun); + +/**@} end of group USBH_MSC_Functions */ + +/** @defgroup USBH_MSC_Structures Structures + @{ + */ + +/* MSC class handler */ +USBH_CLASS_T USBH_MSC_CLASS = +{ + "Class MSC", + USBH_CLASS_MSC, + NULL, + USBH_MSC_ClassInitHandler, + USBH_MSC_ClassDeInitHandler, + USBH_MSC_ClassReqHandler, + USBH_MSC_CoreHandler, + USBH_MSC_SOFHandler, +}; + +/* USB host MSC state handler function */ +USBH_MscStateHandler_T USBH_MSC_Handler[] = +{ + USBH_MSC_InitHandler, + USBH_MSC_IdleHandler, + USBH_MSC_InquiryHandler, + USBH_MSC_TestUnitReadyHandler, + USBH_MSC_RequestSenseHandler, + USBH_MSC_ReadCapacityHandler, + USBH_MSC_ErrorUnrecoveredHandler, + USBH_MSC_ReadHandler, + USBH_MSC_WriteHandler, + USBH_MSC_RWRequestSenseHandler, +}; + +/**@} end of group USBH_MSC_Structures*/ + +/** @defgroup USBH_MSC_Functions Functions + @{ + */ + +/*! + * @brief USB host MSC logic unit init handler + * + * @param usbInfo: usb host information + * + * @param lun: logical unit number + * + * @retval USB host operation status + */ +static USBH_STA_T USBH_MSC_InitHandler(USBH_INFO_T* usbInfo, uint8_t lun) +{ + USBH_STA_T usbStatus = USBH_OK; + USBH_MSC_INFO_T* usbHostMSC = (USBH_MSC_INFO_T*)usbInfo->activeClass->classData; + + USBH_USR_Debug("USBH_MSC_InitHandler"); + + USBH_USR_Debug("Configure LUN:%d", usbHostMSC->curLun); + + usbHostMSC->timer = usbInfo->timer; + + usbHostMSC->storage[usbHostMSC->curLun].state = USBH_MSC_INQUIRY; + + return usbStatus; +} + +/*! + * @brief USB host MSC logic unit read handler + * + * @param usbInfo: usb host information + * + * @param lun: logical unit number + * + * @retval USB host operation status + */ +static USBH_STA_T USBH_MSC_ReadHandler(USBH_INFO_T* usbInfo, uint8_t lun) +{ + USBH_STA_T usbStatus = USBH_BUSY; + USBH_MSC_INFO_T* usbHostMSC = (USBH_MSC_INFO_T*)usbInfo->activeClass->classData; + uint8_t reqStatus; + + USBH_USR_Debug("USBH_MSC_ReadHandler"); + + reqStatus = USBH_MSC_SCSI_Read(usbInfo, lun, 0, NULL, 0); + + switch (reqStatus) + { + case USBH_OK: + usbHostMSC->storage[lun].state = USBH_MSC_IDLE; + usbStatus = USBH_OK; + break; + + case USBH_FAIL: + usbHostMSC->storage[lun].state = USBH_MSC_RW_REQIEST_SENSE; + break; + + case USBH_ERR_UNRECOVERED: + usbHostMSC->storage[lun].state = USBH_MSC_UNRECOVERED_STATE; + usbStatus = USBH_FAIL; + break; + + default: + break; + } + + return usbStatus; +} + +/*! + * @brief USB host MSC logic unit write handler + * + * @param usbInfo: usb host information + * + * @param lun: logical unit number + * + * @retval USB host operation status + */ +static USBH_STA_T USBH_MSC_WriteHandler(USBH_INFO_T* usbInfo, uint8_t lun) +{ + USBH_STA_T usbStatus = USBH_BUSY; + USBH_MSC_INFO_T* usbHostMSC = (USBH_MSC_INFO_T*)usbInfo->activeClass->classData; + uint8_t reqStatus; + + USBH_USR_Debug("USBH_MSC_WriteHandler"); + + reqStatus = USBH_MSC_SCSI_Write(usbInfo, lun, 0, NULL, 0); + + switch (reqStatus) + { + case USBH_OK: + usbHostMSC->storage[lun].state = USBH_MSC_IDLE; + usbStatus = USBH_OK; + break; + + case USBH_FAIL: + usbHostMSC->storage[lun].state = USBH_MSC_RW_REQIEST_SENSE; + break; + + case USBH_ERR_UNRECOVERED: + usbHostMSC->storage[lun].state = USBH_MSC_UNRECOVERED_STATE; + usbStatus = USBH_FAIL; + break; + + default: + break; + } + + return usbStatus; +} + +/*! + * @brief USB host MSC logic unit read and write request sense handler + * + * @param usbInfo: usb host information + * + * @param lun: logical unit number + * + * @retval USB host operation status + */ +static USBH_STA_T USBH_MSC_RWRequestSenseHandler(USBH_INFO_T* usbInfo, uint8_t lun) +{ + USBH_STA_T usbStatus = USBH_BUSY; + USBH_MSC_INFO_T* usbHostMSC = (USBH_MSC_INFO_T*)usbInfo->activeClass->classData; + uint8_t reqStatus; + + USBH_USR_Debug("USBH_MSC_RWRequestSenseHandler"); + + reqStatus = USBH_MSC_SCSI_RequestSense(usbInfo, lun, \ + &usbHostMSC->storage[lun].sense); + + switch (reqStatus) + { + case USBH_OK: + USBH_USR_LOG("Sense KEY : %x", usbHostMSC->storage[lun].sense.key); + USBH_USR_LOG("Sense ASC : %x", usbHostMSC->storage[lun].sense.asc); + USBH_USR_LOG("Sense ASCQ : %x", usbHostMSC->storage[lun].sense.ascq); + + usbHostMSC->storage[lun].state = USBH_MSC_IDLE; + usbHostMSC->storage[lun].errState = USBH_MSC_ERR; + usbStatus = USBH_FAIL; + break; + + case USBH_FAIL: + USBH_USR_LOG("MSC device is not ready"); + break; + + case USBH_ERR_UNRECOVERED: + usbHostMSC->storage[lun].state = USBH_MSC_UNRECOVERED_STATE; + usbStatus = USBH_FAIL; + break; + + default: + break; + } + + return usbStatus; +} + +/*! + * @brief USB host MSC logic unit idle handler + * + * @param usbInfo: usb host information + * + * @param lun: logical unit number + * + * @retval USB host operation status + */ +static USBH_STA_T USBH_MSC_IdleHandler(USBH_INFO_T* usbInfo, uint8_t lun) +{ + USBH_STA_T usbStatus = USBH_OK; + + return usbStatus; +} + +/*! + * @brief USB host MSC logic unit INQUIRY handler + * + * @param usbInfo: usb host information + * + * @param lun: logical unit number + * + * @retval USB host operation status + */ +static USBH_STA_T USBH_MSC_InquiryHandler(USBH_INFO_T* usbInfo, uint8_t lun) +{ + USBH_STA_T usbStatus = USBH_BUSY; + USBH_MSC_INFO_T* usbHostMSC = (USBH_MSC_INFO_T*)usbInfo->activeClass->classData; + uint8_t reqStatus; + + USBH_USR_Debug("USBH_MSC_InquiryHandler"); + + reqStatus = USBH_MSC_SCSI_Inquiry(usbInfo, lun, \ + &usbHostMSC->storage[lun].inquiryReq); + + switch (reqStatus) + { + case USBH_OK: + USBH_USR_LOG("Inquiry Revision :%s", usbHostMSC->storage[lun].inquiryReq.revID); + USBH_USR_LOG("Inquiry Product :%s", usbHostMSC->storage[lun].inquiryReq.productID); + USBH_USR_LOG("Inquiry Vendor :%s", usbHostMSC->storage[lun].inquiryReq.vendorID); + + usbHostMSC->storage[lun].state = USBH_MSC_TEST_UNIT_READY; + break; + + case USBH_FAIL: + usbHostMSC->storage[lun].state = USBH_MSC_REQUEST_SENSE; + break; + + case USBH_ERR_UNRECOVERED: + usbHostMSC->storage[lun].state = USBH_MSC_IDLE; + usbHostMSC->storage[lun].errState = USBH_MSC_ERR; + break; + + default: + break; + } + + return usbStatus; +} + +/*! + * @brief USB host MSC logic unit test unit ready handler + * + * @param usbInfo: usb host information + * + * @param lun: logical unit number + * + * @retval USB host operation status + */ +static USBH_STA_T USBH_MSC_TestUnitReadyHandler(USBH_INFO_T* usbInfo, uint8_t lun) +{ + USBH_STA_T usbStatus = USBH_BUSY; + USBH_MSC_INFO_T* usbHostMSC = (USBH_MSC_INFO_T*)usbInfo->activeClass->classData; + uint8_t reqStatus; + + USBH_USR_Debug("USBH_MSC_TestUnitReadyHandler"); + + reqStatus = USBH_MSC_SCSI_TestUnitReady(usbInfo, lun); + + switch (reqStatus) + { + case USBH_OK: + if (usbHostMSC->storage[lun].preReadyState == USBH_OK) + { + usbHostMSC->storage[lun].changeState = DISABLE; + } + else + { + usbHostMSC->storage[lun].changeState = ENABLE; + USBH_USR_LOG("MSC device is ready"); + } + + usbHostMSC->storage[lun].state = USBH_MSC_READ_CAPACITY; + usbHostMSC->storage[lun].preReadyState = USBH_OK; + usbHostMSC->storage[lun].errState = USBH_MSC_OK; + break; + + case USBH_FAIL: + if (usbHostMSC->storage[lun].preReadyState == USBH_FAIL) + { + usbHostMSC->storage[lun].changeState = DISABLE; + } + else + { + usbHostMSC->storage[lun].changeState = ENABLE; + USBH_USR_LOG("MSC device is not ready"); + } + + /* Media not ready, try to check again during 10s */ + usbHostMSC->storage[lun].state = USBH_MSC_REQUEST_SENSE; + usbHostMSC->storage[lun].preReadyState = USBH_FAIL; + usbHostMSC->storage[lun].errState = USBH_MSC_BUSY; + break; + + case USBH_ERR_UNRECOVERED: + usbHostMSC->storage[lun].state = USBH_MSC_IDLE; + usbHostMSC->storage[lun].errState = USBH_MSC_ERR; + break; + + default: + break; + } + + return usbStatus; +} + +/*! + * @brief USB host MSC logic unit read capacity handler + * + * @param usbInfo: usb host information + * + * @param lun: logical unit number + * + * @retval USB host operation status + */ +static USBH_STA_T USBH_MSC_ReadCapacityHandler(USBH_INFO_T* usbInfo, uint8_t lun) +{ + USBH_STA_T usbStatus = USBH_BUSY; + USBH_MSC_INFO_T* usbHostMSC = (USBH_MSC_INFO_T*)usbInfo->activeClass->classData; + uint8_t reqStatus; + + uint32_t blockNum; + uint32_t blockSize; + + USBH_USR_Debug("USBH_MSC_ReadCapacityHandler"); + reqStatus = USBH_MSC_SCSI_ReadCapacity(usbInfo, lun, \ + &usbHostMSC->storage[lun].capacity); + + switch (reqStatus) + { + case USBH_OK: + if (usbHostMSC->storage[lun].changeState == ENABLE) + { + blockNum = usbHostMSC->storage[lun].capacity.blockNum; + blockSize = usbHostMSC->storage[lun].capacity.blockSize; + + USBH_USR_LOG("MSC device capacity : %lu bytes", (uint32_t)(blockNum * blockSize)); + + USBH_USR_LOG("MSC device block number : %lu", blockNum); + + USBH_USR_LOG("MSC device block size : %lu", blockSize); + } + + usbHostMSC->storage[lun].state = USBH_MSC_IDLE; + usbHostMSC->storage[lun].errState = USBH_MSC_OK; + usbHostMSC->curLun++; + break; + + case USBH_FAIL: + usbHostMSC->storage[lun].state = USBH_MSC_REQUEST_SENSE; + break; + + case USBH_ERR_UNRECOVERED: + usbHostMSC->storage[lun].state = USBH_MSC_IDLE; + usbHostMSC->storage[lun].errState = USBH_MSC_ERR; + break; + + default: + break; + } + + return usbStatus; +} + +/*! + * @brief USB host MSC logic unit request sense handler + * + * @param usbInfo: usb host information + * + * @param lun: logical unit number + * + * @retval USB host operation status + */ +static USBH_STA_T USBH_MSC_RequestSenseHandler(USBH_INFO_T* usbInfo, uint8_t lun) +{ + USBH_STA_T usbStatus = USBH_BUSY; + USBH_MSC_INFO_T* usbHostMSC = (USBH_MSC_INFO_T*)usbInfo->activeClass->classData; + uint8_t reqStatus; + uint8_t senseKey; + + USBH_USR_Debug("USBH_MSC_RequestSenseHandler"); + + reqStatus = USBH_MSC_SCSI_RequestSense(usbInfo, lun, \ + &usbHostMSC->storage[lun].sense); + + switch (reqStatus) + { + case USBH_OK: + senseKey = usbHostMSC->storage[lun].sense.key; + + if ((senseKey == USBH_SCSI_SENSE_KEY_UNIT_ATTENTION) || (senseKey == USBH_SCSI_SENSE_KEY_NOT_READY)) + { + if ((usbInfo->timer - usbHostMSC->timer) < 0x2FFF) + { + /* timer is less than 10s and retry again */ + usbHostMSC->storage[lun].state = USBH_MSC_TEST_UNIT_READY; + break; + } + + USBH_USR_Debug("Sense KEY : %x", usbHostMSC->storage[lun].sense.key); + USBH_USR_Debug("Sense ASC : %x", usbHostMSC->storage[lun].sense.asc); + USBH_USR_Debug("Sense ASCQ : %x", usbHostMSC->storage[lun].sense.ascq); + + usbHostMSC->storage[lun].state = USBH_MSC_IDLE; + usbHostMSC->curLun++; + } + else + { + USBH_USR_LOG("Device sense key error. Please unplug the Device."); + usbHostMSC->storage[lun].state = USBH_MSC_IDLE; + usbHostMSC->storage[lun].errState = USBH_MSC_ERR; + } + break; + + case USBH_FAIL: + USBH_USR_LOG("MSC device is not ready"); + usbHostMSC->storage[lun].state = USBH_MSC_UNRECOVERED_STATE; + break; + + case USBH_ERR_UNRECOVERED: + usbHostMSC->storage[lun].state = USBH_MSC_IDLE; + usbHostMSC->storage[lun].errState = USBH_MSC_ERR; + break; + + default: + break; + } + + return usbStatus; +} + +/*! + * @brief USB host MSC logic unit unrecovered error handler + * + * @param usbInfo: usb host information + * + * @param lun: logical unit number + * + * @retval USB host operation status + */ +static USBH_STA_T USBH_MSC_ErrorUnrecoveredHandler(USBH_INFO_T* usbInfo, uint8_t lun) +{ + USBH_STA_T usbStatus = USBH_BUSY; + + USBH_MSC_INFO_T* usbHostMSC = (USBH_MSC_INFO_T*)usbInfo->activeClass->classData; + + USBH_USR_Debug("USBH_MSC_ErrorUnrecoveredHandler"); + + usbHostMSC->curLun++; + + return usbStatus; +} + +/*! + * @brief USB host MSC configuration handler + * + * @param usbInfo: usb host information + * + * @retval USB host operation status + */ +static USBH_STA_T USBH_MSC_ClassInitHandler(USBH_INFO_T* usbInfo) +{ + USBH_STA_T usbStatus = USBH_OK; + + USBH_MSC_INFO_T* usbHostMSC; + uint8_t itfNum, epNum; + uint8_t classInterface; + uint8_t subClass; + uint8_t protocolInterface; + uint8_t epAddr; + uint8_t epDir; + + USBH_USR_Debug("USBH_MSC_ClassInitHandler"); + + /* Link class data */ + usbInfo->activeClass->classData = (USBH_MSC_INFO_T*)malloc(sizeof(USBH_MSC_INFO_T)); + usbHostMSC = (USBH_MSC_INFO_T*)usbInfo->activeClass->classData; + memset(usbHostMSC, 0, sizeof(USBH_MSC_INFO_T)); + + USBH_USR_Debug("USBH_MSC_INFO_T size %d\r\n", sizeof(USBH_MSC_INFO_T)); + + if (usbHostMSC == NULL) + { + USBH_USR_LOG("usbHostMSC is NULL"); + return USBH_FAIL; + } + + itfNum = USBH_ReadConfigurationItfNum(usbInfo); + + while (itfNum--) + { + classInterface = USBH_ReadInterfaceClass(usbInfo, itfNum); + protocolInterface = USBH_ReadInterfaceProtocol(usbInfo, itfNum); + subClass = USBH_ReadInterfaceSubClass(usbInfo, itfNum); + + if (subClass != USBH_MSC_SCSI_CLASS_CODE) + { + usbStatus = USBH_ERR_NOT_SUP; + continue; + } + + if ((classInterface != USBH_CLASS_MSC) || (protocolInterface != USBH_MSC_PROTOCOL_BBB)) + { + usbStatus = USBH_ERR_NOT_SUP; + continue; + } + + epNum = USBH_ReadInterfaceEpNum(usbInfo, itfNum); + + while (epNum--) + { + /* Get endpoint and size */ + epAddr = USBH_ReadEndpointAddress(usbInfo, itfNum, epNum); + epDir = epAddr & 0x80; + + if (epDir) + { + usbHostMSC->usbHostBOT.bulkInEpAddr = USBH_ReadEndpointAddress(usbInfo, itfNum, epNum); + usbHostMSC->usbHostBOT.bulkInEpSize = USBH_ReadEndpointMPS(usbInfo, itfNum, epNum); + } + else + { + usbHostMSC->usbHostBOT.bulkOutEpAddr = USBH_ReadEndpointAddress(usbInfo, itfNum, epNum); + usbHostMSC->usbHostBOT.bulkOutEpSize = USBH_ReadEndpointMPS(usbInfo, itfNum, epNum); + } + } + } + + /* Init BOT */ + USBH_MSC_BOT_Init(usbInfo); + + usbHostMSC->state = USBH_MSC_INIT; + usbHostMSC->errState = USBH_MSC_OK; + usbHostMSC->classReqState = USBH_MSC_REQ_GET_MAX_LUN; + usbHostMSC->preClassReqState = usbHostMSC->classReqState; + + /* Out channels */ + usbHostMSC->usbHostBOT.outChNum = USBH_CH_AllocChannel(usbInfo, usbHostMSC->usbHostBOT.bulkOutEpAddr); + + /* In channels */ + usbHostMSC->usbHostBOT.inChNum = USBH_CH_AllocChannel(usbInfo, usbHostMSC->usbHostBOT.bulkInEpAddr); + + /* Open the new OUT channels */ + if ((usbHostMSC->usbHostBOT.bulkOutEpAddr == 0) || (usbHostMSC->usbHostBOT.bulkOutEpSize == 0)) + { + return USBH_ERR_NOT_SUP; + } + else + { + USBH_OpenChannelCallback(usbInfo, usbHostMSC->usbHostBOT.outChNum, + usbHostMSC->usbHostBOT.bulkOutEpAddr, + usbInfo->devInfo.address, + usbInfo->devInfo.speed, + EP_TYPE_BULK, + usbHostMSC->usbHostBOT.bulkOutEpSize); + } + + /* Open the new IN channels */ + if ((usbHostMSC->usbHostBOT.bulkInEpAddr == 0) || (usbHostMSC->usbHostBOT.bulkInEpSize == 0)) + { + return USBH_ERR_NOT_SUP; + } + else + { + USBH_OpenChannelCallback(usbInfo, usbHostMSC->usbHostBOT.inChNum, + usbHostMSC->usbHostBOT.bulkInEpAddr, + usbInfo->devInfo.address, + usbInfo->devInfo.speed, + EP_TYPE_BULK, + usbHostMSC->usbHostBOT.bulkInEpSize); + } + + USBH_ConfigDataPidCallback(usbInfo, usbHostMSC->usbHostBOT.inChNum, 0); + USBH_ConfigDataPidCallback(usbInfo, usbHostMSC->usbHostBOT.outChNum, 0); + + return usbStatus; +} + +/*! + * @brief USB host MSC class reset handler + * + * @param usbInfo: usb host information + * + * @retval USB host operation status + */ +static USBH_STA_T USBH_MSC_ClassDeInitHandler(USBH_INFO_T* usbInfo) +{ + USBH_STA_T usbStatus = USBH_OK; + USBH_MSC_INFO_T* usbHostMSC = (USBH_MSC_INFO_T*)usbInfo->activeClass->classData; + + if (usbHostMSC->usbHostBOT.inChNum != 0) + { + USBH_CloseChannelCallback(usbInfo, usbHostMSC->usbHostBOT.inChNum); + USBH_CH_FreeChannel(usbInfo, usbHostMSC->usbHostBOT.inChNum); + usbHostMSC->usbHostBOT.inChNum = 0; + } + + if (usbHostMSC->usbHostBOT.outChNum != 0) + { + USBH_CloseChannelCallback(usbInfo, usbHostMSC->usbHostBOT.outChNum); + USBH_CH_FreeChannel(usbInfo, usbHostMSC->usbHostBOT.outChNum); + usbHostMSC->usbHostBOT.outChNum = 0; + } + + if (usbInfo->activeClass->classData != NULL) + { + free(usbInfo->activeClass->classData); + usbInfo->activeClass->classData = 0; + } + + return usbStatus; +} + +/*! + * @brief USB host MSC class reguest handler + * + * @param usbInfo: usb host information + * + * @retval USB host operation status + */ +static USBH_STA_T USBH_MSC_ClassReqHandler(USBH_INFO_T* usbInfo) +{ + USBH_STA_T usbStatus = USBH_BUSY; + uint8_t reqStatus = USBH_BUSY; + USBH_MSC_INFO_T* usbHostMSC = (USBH_MSC_INFO_T*)usbInfo->activeClass->classData; + uint8_t i; + + USBH_USR_Debug("USBH_MSC_ClassReqHandler"); + + switch (usbHostMSC->classReqState) + { + case USBH_MSC_REQ_GET_MAX_LUN: + reqStatus = USBH_MSC_BOT_REQ_GetMaxLunHandler(usbInfo, &usbHostMSC->maxLun); + + switch (reqStatus) + { + case USBH_OK: + if (usbHostMSC->maxLun > USBH_SUPPORTED_LUN_MAX) + { + usbHostMSC->maxLun = USBH_SUPPORTED_LUN_MAX; + } + else + { + usbHostMSC->maxLun += 1; + } + + for (i = 0; i < usbHostMSC->maxLun; i++) + { + usbHostMSC->storage[i].changeState = DISABLE; + usbHostMSC->storage[i].preReadyState = USBH_FAIL; + } + + usbStatus = USBH_OK; + break; + + case USBH_ERR_NOT_SUP: + usbHostMSC->maxLun = 0; + usbStatus = USBH_OK; + break; + + default: + break; + } + break; + + + case USBH_MSC_REQ_CTRL_ERROR: + reqStatus = USBH_ClearFeature(usbInfo, 0); + + switch (reqStatus) + { + case USBH_OK: + usbHostMSC->classReqState = usbHostMSC->preClassReqState; + break; + + default: + break; + } + break; + + default : + break; + } + + return usbStatus; +} + +/*! + * @brief USB host MSC SOF handler + * + * @param usbInfo: usb host information + * + * @retval USB host operation status + */ +static USBH_STA_T USBH_MSC_SOFHandler(USBH_INFO_T* usbInfo) +{ + USBH_STA_T usbStatus = USBH_BUSY; + + return usbStatus; +} + +/*! + * @brief USB host MSC handler + * + * @param usbInfo: usb host information + * + * @retval USB host operation status + */ +static USBH_STA_T USBH_MSC_CoreHandler(USBH_INFO_T* usbInfo) +{ + USBH_STA_T usbStatus = USBH_BUSY; + USBH_MSC_INFO_T* usbHostMSC = (USBH_MSC_INFO_T*)usbInfo->activeClass->classData; + + if (usbHostMSC->state == USBH_MSC_INIT) + { + if (usbHostMSC->curLun >= usbHostMSC->maxLun) + { + usbHostMSC->curLun = 0; + usbHostMSC->state = USBH_MSC_IDLE; + + USBH_USR_Debug("%s is launched", usbInfo->hostClass[usbInfo->classNum]->className); + + /* Notify User */ + usbInfo->userCallback(usbInfo, USBH_USER_CLASS_LAUNCHED); + } + else + { + usbHostMSC->storage[usbHostMSC->curLun].errState = USBH_MSC_BUSY; + + /* MSC process */ + USBH_MSC_Handler[usbHostMSC->storage[usbHostMSC->curLun].state](usbInfo, usbHostMSC->curLun); + } + } + else if (usbHostMSC->state == USBH_MSC_IDLE) + { + usbStatus = USBH_MSC_Handler[usbHostMSC->state](usbInfo, usbHostMSC->curLun); + } + else + { + + } + + return usbStatus; +} + +/*! + * @brief USB host MSC read unit information + * + * @param usbInfo: usb host information + * + * @param lun: logical unit number + * + * @param device: device unit information + * + * @retval USB host operation status + */ +USBH_STA_T USBH_MSC_ReadDevInfo(USBH_INFO_T* usbInfo, uint8_t lun, USBH_MSC_STORAGE_INFO_T* device) +{ + USBH_STA_T usbStatus = USBH_FAIL; + USBH_MSC_INFO_T* usbHostMSC = (USBH_MSC_INFO_T*)usbInfo->activeClass->classData; + + if (usbInfo->hostState == USBH_HOST_CLASS) + { + memcpy(device, &usbHostMSC->storage[lun], sizeof(USBH_MSC_STORAGE_INFO_T)); + + usbStatus = USBH_OK; + } + + return usbStatus; +} + +/*! + * @brief USB host MSC read device ready status + * + * @param usbInfo: usb host information + * + * @param lun: logical unit number + * + * @retval Unit ready status + * @arg 0: not ready + * @arg 1: ready + */ +uint8_t USBH_MSC_DevStatus(USBH_INFO_T* usbInfo, uint8_t lun) +{ + uint8_t unitStatus = 0; + USBH_MSC_INFO_T* usbHostMSC = (USBH_MSC_INFO_T*)usbInfo->activeClass->classData; + + if (usbInfo->hostState == USBH_HOST_CLASS) + { + if (usbHostMSC->storage[lun].errState == USBH_MSC_OK) + { + unitStatus = 1; + } + } + + return unitStatus; +} + +/*! + * @brief USB host MSC read device WP status + * + * @param usbInfo: usb host information + * + * @param lun: logical unit number + * + * @retval WP status + * @arg DISABLE: not protect + * @arg 1: protect + */ +uint8_t USBH_MSC_ReadDevWP(USBH_INFO_T* usbInfo, uint8_t lun) +{ + uint8_t wpStatus = DISABLE; + USBH_MSC_INFO_T* usbHostMSC = (USBH_MSC_INFO_T*)usbInfo->activeClass->classData; + + if (usbInfo->hostState == USBH_HOST_CLASS) + { + if (usbHostMSC->storage[lun].sense.asc == USBH_SCSI_ASC_WRITE_PROTECTED) + { + wpStatus = ENABLE; + } + } + + return wpStatus; +} + +/*! + * @brief USB host MSC read unit information + * + * @param usbInfo: usb host information + * + * @param lun: logical unit number + * + * @param address: sector address + * + * @param buffer: buffer point to data + * + * @param cnt: count number of data + * + * @retval USB host operation status + */ +USBH_STA_T USBH_MSC_DevRead(USBH_INFO_T* usbInfo, uint8_t lun, uint32_t address, \ + uint8_t* buffer, uint16_t cnt) +{ + USBH_STA_T usbStatus = USBH_FAIL; + USBH_MSC_INFO_T* usbHostMSC = (USBH_MSC_INFO_T*)usbInfo->activeClass->classData; + + if ((usbInfo->devInfo.connectedStatus == DISABLE) || \ + (usbInfo->hostState != USBH_HOST_CLASS) || \ + (usbHostMSC->storage[lun].state != USBH_MSC_IDLE)) + { + return usbStatus; + } + + usbHostMSC->state = USBH_MSC_RW_READ; + usbHostMSC->storage[lun].state = USBH_MSC_RW_READ; + usbHostMSC->opLun = lun; + + USBH_MSC_SCSI_Read(usbInfo, lun, address, buffer, cnt); + + usbHostMSC->timer = usbInfo->timer; + + while (USBH_MSC_Handler[usbHostMSC->storage[lun].state](usbInfo, lun) == USBH_BUSY) + { + USBH_USR_Debug("read usbInfo->timer:%d", usbInfo->timer); + USBH_USR_Debug("read usbHostMSC->timer:%d", usbHostMSC->timer); + + if (((usbInfo->timer - usbHostMSC->timer) > (0x2FFF * cnt)) || \ + (usbInfo->devInfo.connectedStatus == DISABLE)) + { + usbHostMSC->state = USBH_MSC_IDLE; + return USBH_FAIL; + } + } + + usbHostMSC->state = USBH_MSC_IDLE; + usbStatus = USBH_OK; + + USBH_USR_Debug("USBH_MSC_DevRead end"); + + return usbStatus; +} + +/*! + * @brief USB host MSC write + * + * @param usbInfo: usb host information + * + * @param lun: logical unit number + * + * @param address: sector address + * + * @param buffer: buffer point to data + * + * @param cnt: count number of data + * + * @retval USB host operation status + */ +USBH_STA_T USBH_MSC_DevWrite(USBH_INFO_T* usbInfo, uint8_t lun, uint32_t address, \ + uint8_t* buffer, uint16_t cnt) +{ + USBH_STA_T usbStatus = USBH_FAIL; + USBH_MSC_INFO_T* usbHostMSC = (USBH_MSC_INFO_T*)usbInfo->activeClass->classData; + + if ((usbInfo->devInfo.connectedStatus == DISABLE) || \ + (usbInfo->hostState != USBH_HOST_CLASS) || \ + (usbHostMSC->storage[lun].state != USBH_MSC_IDLE)) + { + return usbStatus; + } + + usbHostMSC->state = USBH_MSC_RW_WRITE; + usbHostMSC->storage[lun].state = USBH_MSC_RW_WRITE; + usbHostMSC->opLun = lun; + + USBH_MSC_SCSI_Write(usbInfo, lun, address, buffer, cnt); + + usbHostMSC->timer = usbInfo->timer; + + while (USBH_MSC_Handler[usbHostMSC->storage[lun].state](usbInfo, lun) == USBH_BUSY) + { + USBH_USR_Debug("write usbInfo->timer:%d", usbInfo->timer); + USBH_USR_Debug("write usbHostMSC->timer:%d", usbHostMSC->timer); + + if (((usbInfo->timer - usbHostMSC->timer) > (0x2FFF * cnt)) || \ + (usbInfo->devInfo.connectedStatus == DISABLE)) + { + usbHostMSC->state = USBH_MSC_IDLE; + return USBH_FAIL; + } + } + + usbHostMSC->state = USBH_MSC_IDLE; + usbStatus = USBH_OK; + + USBH_USR_Debug("USBH_MSC_DevWrite end"); + + return usbStatus; +} + +/**@} end of group USBH_MSC_Functions */ +/**@} end of group USBH_MSC_Class */ +/**@} end of group APM32_USB_Library */ diff --git a/lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Class/MSC/Src/usbh_msc_bot.c b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Class/MSC/Src/usbh_msc_bot.c new file mode 100644 index 0000000000..2cd8d02ca2 --- /dev/null +++ b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Class/MSC/Src/usbh_msc_bot.c @@ -0,0 +1,672 @@ +/*! + * @file usbh_msc_bot.c + * + * @brief USB host MSC bot + * + * @version V1.0.0 + * + * @date 2023-01-16 + * + * @attention + * + * Copyright (C) 2023 Geehy Semiconductor + * + * You may not use this file except in compliance with the + * GEEHY COPYRIGHT NOTICE (GEEHY SOFTWARE PACKAGE LICENSE). + * + * The program is only for reference, which is distributed in the hope + * that it will be useful and instructional for customers to develop + * their software. Unless required by applicable law or agreed to in + * writing, the program is distributed on an "AS IS" BASIS, WITHOUT + * ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied. + * See the GEEHY SOFTWARE PACKAGE LICENSE for the governing permissions + * and limitations under the License. + */ + +/* Includes */ +#include "usbh_msc_bot.h" +#include "usbh_msc.h" +#include "usbh_dataXfer.h" + +/** @addtogroup APM32_USB_Library + @{ + */ + +/** @addtogroup USBH_MSC_Class + @{ + */ + +/** @defgroup USBH_MSC_Functions Functions + @{ + */ + +static USBH_STA_T USBH_MSC_BOT_SendCBWHandler(USBH_INFO_T* usbInfo, uint8_t lun); +static USBH_STA_T USBH_MSC_BOT_SendCBWWaitHandler(USBH_INFO_T* usbInfo, uint8_t lun); +static USBH_STA_T USBH_MSC_BOT_DataInHandler(USBH_INFO_T* usbInfo, uint8_t lun); +static USBH_STA_T USBH_MSC_BOT_DataInWaitHandler(USBH_INFO_T* usbInfo, uint8_t lun); +static USBH_STA_T USBH_MSC_BOT_DataOutHandler(USBH_INFO_T* usbInfo, uint8_t lun); +static USBH_STA_T USBH_MSC_BOT_DataOutWaitHandler(USBH_INFO_T* usbInfo, uint8_t lun); +static USBH_STA_T USBH_MSC_BOT_RevCSWHandler(USBH_INFO_T* usbInfo, uint8_t lun); +static USBH_STA_T USBH_MSC_BOT_RevCSWWaitHandler(USBH_INFO_T* usbInfo, uint8_t lun); +static USBH_STA_T USBH_MSC_BOT_ErrorInHandler(USBH_INFO_T* usbInfo, uint8_t lun); +static USBH_STA_T USBH_MSC_BOT_ErrorOutHandler(USBH_INFO_T* usbInfo, uint8_t lun); +static USBH_STA_T USBH_MSC_BOT_ErrorUnrecoveredHandler(USBH_INFO_T* usbInfo, uint8_t lun); + +/**@} end of group USBH_MSC_Functions */ + +/** @defgroup USBH_MSC_Structures Structures + @{ + */ + +/* USB host BOT state handler function */ +USBH_BotStateHandler_T USBH_MSC_BOT_Handler[] = +{ + USBH_MSC_BOT_SendCBWHandler, + USBH_MSC_BOT_SendCBWWaitHandler, + USBH_MSC_BOT_DataInHandler, + USBH_MSC_BOT_DataInWaitHandler, + USBH_MSC_BOT_DataOutHandler, + USBH_MSC_BOT_DataOutWaitHandler, + USBH_MSC_BOT_RevCSWHandler, + USBH_MSC_BOT_RevCSWWaitHandler, + USBH_MSC_BOT_ErrorInHandler, + USBH_MSC_BOT_ErrorOutHandler, + USBH_MSC_BOT_ErrorUnrecoveredHandler, +}; + +/**@} end of group USBH_MSC_Structures*/ + +/** @defgroup USBH_MSC_Functions Functions + @{ + */ + +/*! + * @brief USB host MSC BOT send CBW handler + * + * @param usbInfo : usb handler information + * + * @param lun : logical unit numer + * + * @retval CSW decode status + */ +static USBH_BOT_CSW_STA_T USBH_MSC_BOT_DecodeCSW(USBH_INFO_T* usbInfo) +{ + USBH_BOT_CSW_STA_T cswStatus = USBH_BOT_CSW_FAIL; + USBH_MSC_INFO_T* usbHostMSC = (USBH_MSC_INFO_T*)usbInfo->activeClass->classData; + uint32_t lastXferSize; + + lastXferSize = USBH_ReadLastXferSizeCallback(usbInfo, usbHostMSC->usbHostBOT.inChNum); + + /* CSW length is Correct */ + if (lastXferSize == USBH_MSC_BOT_CSW_LEN) + { + /* dSignature is equal to 0x53425355 */ + if (usbHostMSC->usbHostBOT.cmdPack.CSW.DATA_FIELD.dSignature == USBH_MSC_BOT_CSW_SIGNATURE) + { + /* dTag matches the dTag from the corresponding CBW */ + if (usbHostMSC->usbHostBOT.cmdPack.CSW.DATA_FIELD.dTag == usbHostMSC->usbHostBOT.cmdPack.CBW.DATA_FIELD.dTag) + { + switch (usbHostMSC->usbHostBOT.cmdPack.CSW.DATA_FIELD.bStatus) + { + case USBH_BOT_CSW_OK: + cswStatus = USBH_BOT_CSW_OK; + break; + + case USBH_BOT_CSW_FAIL: + cswStatus = USBH_BOT_CSW_FAIL; + break; + + case USBH_BOT_CSW_ERR: + cswStatus = USBH_BOT_CSW_ERR; + break; + } + } + } + else + { + cswStatus = USBH_BOT_CSW_ERR; + } + } + else + { + cswStatus = USBH_BOT_CSW_ERR; + } + + return cswStatus; +} + +/*! + * @brief USB host MSC BOT send CBW handler + * + * @param usbInfo : usb handler information + * + * @param lun : logical unit numer + * + * @retval USB host operation status + */ +static USBH_STA_T USBH_MSC_BOT_SendCBWHandler(USBH_INFO_T* usbInfo, uint8_t lun) +{ + USBH_STA_T usbStatus = USBH_BUSY; + USBH_MSC_INFO_T* usbHostMSC = (USBH_MSC_INFO_T*)usbInfo->activeClass->classData; + + usbHostMSC->usbHostBOT.cmdPack.CBW.DATA_FIELD.bLUN = lun; + + USBH_USR_Debug("USBH_MSC_BOT_SendCBWHandler"); + + USBH_BulkSendDataReq(usbInfo, usbHostMSC->usbHostBOT.outChNum, usbHostMSC->usbHostBOT.cmdPack.CBW.buffer, \ + USBH_MSC_BOT_CBW_LEN, ENABLE); + + usbHostMSC->usbHostBOT.state = USBH_BOT_SEND_CBW_WAIT; + + return usbStatus; +} + +/*! + * @brief USB host MSC BOT send CBW wait handler + * + * @param usbInfo : usb handler information + * + * @param lun : logical unit numer + * + * @retval USB host operation status + */ +static USBH_STA_T USBH_MSC_BOT_SendCBWWaitHandler(USBH_INFO_T* usbInfo, uint8_t lun) +{ + USBH_STA_T usbStatus = USBH_BUSY; + uint8_t usbUrbStatus = USB_URB_IDLE; + USBH_MSC_INFO_T* usbHostMSC = (USBH_MSC_INFO_T*)usbInfo->activeClass->classData; + + USBH_USR_Debug("USBH_MSC_BOT_SendCBWWaitHandler"); + + /* Read USB URB status */ + usbUrbStatus = USBH_ReadUrbStatusCallback(usbInfo, usbHostMSC->usbHostBOT.outChNum); + + switch (usbUrbStatus) + { + case USB_URB_OK: + if (usbHostMSC->usbHostBOT.cmdPack.CBW.DATA_FIELD.dDataXferLen == 0) + { + usbHostMSC->usbHostBOT.state = USBH_BOT_RECEIVE_CSW; + } + else + { + if (usbHostMSC->usbHostBOT.cmdPack.CBW.DATA_FIELD.bmFlags.CBW_FLAG_B.dir == USBH_REQ_DIR_IN) + { + usbHostMSC->usbHostBOT.state = USBH_BOT_DATAIN; + } + else + { + usbHostMSC->usbHostBOT.state = USBH_BOT_DATAOUT; + } + } + break; + + case USB_URB_NOREADY: + /* Resend CBW */ + usbHostMSC->usbHostBOT.state = USBH_BOT_SEND_CBW; + break; + + case USB_URB_STALL: + usbHostMSC->usbHostBOT.state = USBH_BOT_ERROR_OUT; + break; + + default: + break; + } + + return usbStatus; +} + +/*! + * @brief USB host MSC BOT data IN handler + * + * @param usbInfo : usb handler information + * + * @param lun : logical unit numer + * + * @retval USB host operation status + */ +static USBH_STA_T USBH_MSC_BOT_DataInHandler(USBH_INFO_T* usbInfo, uint8_t lun) +{ + USBH_STA_T usbStatus = USBH_BUSY; + USBH_MSC_INFO_T* usbHostMSC = (USBH_MSC_INFO_T*)usbInfo->activeClass->classData; + + USBH_USR_Debug("USBH_MSC_BOT_DataInHandler"); + USBH_BulkReceiveDataReq(usbInfo, usbHostMSC->usbHostBOT.inChNum, usbHostMSC->usbHostBOT.buffer, \ + usbHostMSC->usbHostBOT.bulkInEpSize); + + usbHostMSC->usbHostBOT.state = USBH_BOT_DATAIN_WAIT; + + return usbStatus; +} + +/*! + * @brief USB host MSC BOT data IN wait handler + * + * @param usbInfo : usb handler information + * + * @param lun : logical unit numer + * + * @retval USB host operation status + */ +static USBH_STA_T USBH_MSC_BOT_DataInWaitHandler(USBH_INFO_T* usbInfo, uint8_t lun) +{ + USBH_STA_T usbStatus = USBH_BUSY; + uint8_t usbUrbStatus = USB_URB_IDLE; + USBH_MSC_INFO_T* usbHostMSC = (USBH_MSC_INFO_T*)usbInfo->activeClass->classData; + + USBH_USR_Debug("USBH_MSC_BOT_DataInWaitHandler"); + + /* Read USB URB status */ + usbUrbStatus = USBH_ReadUrbStatusCallback(usbInfo, usbHostMSC->usbHostBOT.inChNum); + + switch (usbUrbStatus) + { + case USB_URB_OK: + if (usbHostMSC->usbHostBOT.cmdPack.CBW.DATA_FIELD.dDataXferLen <= usbHostMSC->usbHostBOT.bulkInEpSize) + { + usbHostMSC->usbHostBOT.cmdPack.CBW.DATA_FIELD.dDataXferLen = 0; + } + else + { + usbHostMSC->usbHostBOT.buffer += usbHostMSC->usbHostBOT.bulkInEpSize; + usbHostMSC->usbHostBOT.cmdPack.CBW.DATA_FIELD.dDataXferLen -= usbHostMSC->usbHostBOT.bulkInEpSize; + } + + if (usbHostMSC->usbHostBOT.cmdPack.CBW.DATA_FIELD.dDataXferLen > 0) + { + /* Receive the next bulk packet */ + USBH_BulkReceiveDataReq(usbInfo, usbHostMSC->usbHostBOT.inChNum, usbHostMSC->usbHostBOT.buffer, \ + usbHostMSC->usbHostBOT.bulkInEpSize); + } + else + { + usbHostMSC->usbHostBOT.state = USBH_BOT_RECEIVE_CSW; + } + break; + + case USB_URB_STALL: + usbHostMSC->usbHostBOT.state = USBH_BOT_ERROR_IN; + break; + + default: + break; + } + + return usbStatus; +} + +/*! + * @brief USB host MSC BOT data OUT handler + * + * @param usbInfo : usb handler information + * + * @param lun : logical unit numer + * + * @retval USB host operation status + */ +static USBH_STA_T USBH_MSC_BOT_DataOutHandler(USBH_INFO_T* usbInfo, uint8_t lun) +{ + USBH_STA_T usbStatus = USBH_BUSY; + USBH_MSC_INFO_T* usbHostMSC = (USBH_MSC_INFO_T*)usbInfo->activeClass->classData; + + USBH_USR_Debug("USBH_MSC_BOT_DataOutHandler"); + + USBH_BulkSendDataReq(usbInfo, usbHostMSC->usbHostBOT.outChNum, usbHostMSC->usbHostBOT.buffer, \ + usbHostMSC->usbHostBOT.bulkOutEpSize, ENABLE); + + usbHostMSC->usbHostBOT.state = USBH_BOT_DATAOUT_WAIT; + + return usbStatus; +} + +/*! + * @brief USB host MSC BOT data OUT wait handler + * + * @param usbInfo : usb handler information + * + * @param lun : logical unit numer + * + * @retval USB host operation status + */ +static USBH_STA_T USBH_MSC_BOT_DataOutWaitHandler(USBH_INFO_T* usbInfo, uint8_t lun) +{ + USBH_STA_T usbStatus = USBH_BUSY; + uint8_t usbUrbStatus = USB_URB_IDLE; + USBH_MSC_INFO_T* usbHostMSC = (USBH_MSC_INFO_T*)usbInfo->activeClass->classData; + + USBH_USR_Debug("USBH_MSC_BOT_DataOutWaitHandler"); + + /* Read USB URB status */ + usbUrbStatus = USBH_ReadUrbStatusCallback(usbInfo, usbHostMSC->usbHostBOT.outChNum); + + switch (usbUrbStatus) + { + case USB_URB_OK: + if (usbHostMSC->usbHostBOT.cmdPack.CBW.DATA_FIELD.dDataXferLen <= usbHostMSC->usbHostBOT.bulkOutEpSize) + { + usbHostMSC->usbHostBOT.cmdPack.CBW.DATA_FIELD.dDataXferLen = 0; + } + else + { + usbHostMSC->usbHostBOT.buffer += usbHostMSC->usbHostBOT.bulkOutEpSize; + usbHostMSC->usbHostBOT.cmdPack.CBW.DATA_FIELD.dDataXferLen -= usbHostMSC->usbHostBOT.bulkOutEpSize; + } + + if (usbHostMSC->usbHostBOT.cmdPack.CBW.DATA_FIELD.dDataXferLen > 0) + { + /* Send the next bulk packet */ + USBH_BulkSendDataReq(usbInfo, usbHostMSC->usbHostBOT.outChNum, usbHostMSC->usbHostBOT.buffer, \ + usbHostMSC->usbHostBOT.bulkOutEpSize, ENABLE); + } + else + { + usbHostMSC->usbHostBOT.state = USBH_BOT_RECEIVE_CSW; + } + break; + + case USB_URB_NOREADY: + usbHostMSC->usbHostBOT.state = USBH_BOT_DATAOUT; + break; + + case USB_URB_STALL: + usbHostMSC->usbHostBOT.state = USBH_BOT_ERROR_OUT; + break; + + default: + break; + } + + return usbStatus; +} + +/*! + * @brief USB host MSC BOT receive CSW handler + * + * @param usbInfo : usb handler information + * + * @param lun : logical unit numer + * + * @retval USB host operation status + */ +static USBH_STA_T USBH_MSC_BOT_RevCSWHandler(USBH_INFO_T* usbInfo, uint8_t lun) +{ + USBH_STA_T usbStatus = USBH_BUSY; + USBH_MSC_INFO_T* usbHostMSC = (USBH_MSC_INFO_T*)usbInfo->activeClass->classData; + + USBH_USR_Debug("USBH_MSC_BOT_RevCSWHandler"); + + USBH_BulkReceiveDataReq(usbInfo, usbHostMSC->usbHostBOT.inChNum, usbHostMSC->usbHostBOT.cmdPack.CSW.buffer, \ + USBH_MSC_BOT_CSW_LEN); + + usbHostMSC->usbHostBOT.state = USBH_BOT_RECEIVE_CSW_WAIT; + + return usbStatus; +} + +/*! + * @brief USB host MSC BOT reveive CSW wait handler + * + * @param usbInfo : usb handler information + * + * @param lun : logical unit numer + * + * @retval USB host operation status + */ +static USBH_STA_T USBH_MSC_BOT_RevCSWWaitHandler(USBH_INFO_T* usbInfo, uint8_t lun) +{ + USBH_STA_T usbStatus = USBH_BUSY; + uint8_t usbUrbStatus = USB_URB_IDLE; + USBH_MSC_INFO_T* usbHostMSC = (USBH_MSC_INFO_T*)usbInfo->activeClass->classData; + + USBH_BOT_CSW_STA_T cswStatus = USBH_BOT_CSW_FAIL; + + USBH_USR_Debug("USBH_MSC_BOT_RevCSWWaitHandler"); + + /* Read USB URB status */ + usbUrbStatus = USBH_ReadUrbStatusCallback(usbInfo, usbHostMSC->usbHostBOT.inChNum); + + switch (usbUrbStatus) + { + case USB_URB_OK: + usbHostMSC->usbHostBOT.state = USBH_BOT_SEND_CBW; + usbHostMSC->usbHostBOT.xferState = USBH_BOT_XFER_START; + cswStatus = USBH_MSC_BOT_DecodeCSW(usbInfo); + + if (cswStatus == USBH_BOT_CSW_OK) + { + usbStatus = USBH_OK; + } + else + { + usbStatus = USBH_FAIL; + } + break; + + case USB_URB_STALL: + usbHostMSC->usbHostBOT.state = USBH_BOT_ERROR_IN; + break; + + default: + break; + } + + return usbStatus; +} + +/*! + * @brief USB host MSC BOT IN error handler + * + * @param usbInfo : usb handler information + * + * @param lun : logical unit numer + * + * @retval USB host operation status + */ +static USBH_STA_T USBH_MSC_BOT_ErrorInHandler(USBH_INFO_T* usbInfo, uint8_t lun) +{ + USBH_STA_T usbStatus = USBH_BUSY; + uint8_t reqStatus = USBH_OK; + USBH_MSC_INFO_T* usbHostMSC = (USBH_MSC_INFO_T*)usbInfo->activeClass->classData; + + USBH_USR_Debug("USBH_MSC_BOT_ErrorInHandler"); + + reqStatus = USBH_ClearFeature(usbInfo, usbHostMSC->usbHostBOT.bulkInEpAddr); + + switch (reqStatus) + { + case USBH_OK: + usbHostMSC->usbHostBOT.state = USBH_BOT_RECEIVE_CSW; + break; + + case USBH_ERR_UNRECOVERED: + usbHostMSC->usbHostBOT.state = USBH_BOT_ERROR_UNRECOVERED; + break; + + default: + break; + } + + return usbStatus; +} + +/*! + * @brief USB host MSC BOT OUT error handler + * + * @param usbInfo : usb handler information + * + * @param lun : logical unit numer + * + * @retval USB host operation status + */ +static USBH_STA_T USBH_MSC_BOT_ErrorOutHandler(USBH_INFO_T* usbInfo, uint8_t lun) +{ + USBH_STA_T usbStatus = USBH_BUSY; + uint8_t reqStatus = USBH_OK; + USBH_MSC_INFO_T* usbHostMSC = (USBH_MSC_INFO_T*)usbInfo->activeClass->classData; + uint8_t toggle; + + USBH_USR_Debug("USBH_MSC_BOT_ErrorOutHandler"); + + reqStatus = USBH_ClearFeature(usbInfo, usbHostMSC->usbHostBOT.bulkOutEpAddr); + + switch (reqStatus) + { + case USBH_OK: + toggle = USBH_ReadToggleCallback(usbInfo, usbHostMSC->usbHostBOT.outChNum); + + USBH_ConfigToggleCallback(usbInfo, usbHostMSC->usbHostBOT.outChNum, 1 - toggle); + USBH_ConfigToggleCallback(usbInfo, usbHostMSC->usbHostBOT.inChNum, 0); + + usbHostMSC->usbHostBOT.state = USBH_BOT_ERROR_IN; + break; + + case USBH_ERR_UNRECOVERED: + usbHostMSC->usbHostBOT.state = USBH_BOT_ERROR_UNRECOVERED; + break; + + default: + break; + } + + return usbStatus; +} + +/*! + * @brief USB host MSC BOT unrecovered error handler + * + * @param usbInfo : usb handler information + * + * @param lun : logical unit numer + * + * @retval USB host operation status + */ +static USBH_STA_T USBH_MSC_BOT_ErrorUnrecoveredHandler(USBH_INFO_T* usbInfo, uint8_t lun) +{ + USBH_STA_T usbStatus = USBH_BUSY; + uint8_t reqStatus = USBH_OK; + USBH_MSC_INFO_T* usbHostMSC = (USBH_MSC_INFO_T*)usbInfo->activeClass->classData; + + USBH_USR_Debug("USBH_MSC_BOT_ErrorUnrecoveredHandler"); + + reqStatus = USBH_MSC_BOT_REQ_Reset(usbInfo); + + switch (reqStatus) + { + case USBH_OK: + usbHostMSC->usbHostBOT.state = USBH_BOT_SEND_CBW; + break; + + default: + break; + } + + return usbStatus; +} + +/*! + * @brief Init BOT of USB host MSC + * + * @param usbInfo : usb handler information + * + * @retval USB host operation status + */ +USBH_STA_T USBH_MSC_BOT_Init(USBH_INFO_T* usbInfo) +{ + USBH_STA_T usbStatus = USBH_OK; + USBH_MSC_INFO_T* usbHostMSC = (USBH_MSC_INFO_T*)usbInfo->activeClass->classData; + + usbHostMSC->usbHostBOT.cmdPack.CBW.DATA_FIELD.dSignature = USBH_MSC_BOT_CBW_SIGNATURE; + usbHostMSC->usbHostBOT.cmdPack.CBW.DATA_FIELD.dTag = USBH_MSC_BOT_CBW_TAG; + + usbHostMSC->usbHostBOT.xferState = USBH_BOT_XFER_START; + usbHostMSC->usbHostBOT.state = USBH_BOT_SEND_CBW; + + return usbStatus; +} + +/*! + * @brief Reset request of MSC BOT + * + * @param usbInfo : usb handler information + * + * @retval USB host operation status + */ +USBH_STA_T USBH_MSC_BOT_REQ_Reset(USBH_INFO_T* usbInfo) +{ + USBH_STA_T usbStatus = USBH_OK; + + /* Config Request */ + switch (usbInfo->xferState) + { + case USBH_XFER_START: + usbInfo->ctrl.reqData.DATA_FIELD.bmRequestType.REQ_TYPE_B.dir = USBH_REQ_DIR_OUT; + usbInfo->ctrl.reqData.DATA_FIELD.bmRequestType.REQ_TYPE_B.recipient = USBH_RECIPIENT_INTERFACE; + usbInfo->ctrl.reqData.DATA_FIELD.bmRequestType.REQ_TYPE_B.type = USBH_REQ_TYPE_CLASS; + + usbInfo->ctrl.reqData.DATA_FIELD.bRequest = USBH_CLASS_BOT_RESET; + + usbInfo->ctrl.reqData.DATA_FIELD.wValue[0] = 0x00; + usbInfo->ctrl.reqData.DATA_FIELD.wValue[1] = 0x00; + + usbInfo->ctrl.reqData.DATA_FIELD.wIndex[0] = 0x00; + usbInfo->ctrl.reqData.DATA_FIELD.wIndex[1] = 0x00; + + usbInfo->ctrl.reqData.DATA_FIELD.wLength[0] = 0x00; + usbInfo->ctrl.reqData.DATA_FIELD.wLength[1] = 0x00; + break; + + default: + break; + } + + usbStatus = USBH_REQ_CtrlXferHandler(usbInfo, NULL, 0); + + return usbStatus; +} + +/*! + * @brief Get the max lun of MSC BOT + * + * @param usbInfo : usb handler information + * + * @param maxLun: max of logic unit number + * + * @retval USB host operation status + */ +USBH_STA_T USBH_MSC_BOT_REQ_GetMaxLunHandler(USBH_INFO_T* usbInfo, uint8_t* maxLun) +{ + USBH_STA_T usbStatus = USBH_OK; + + /* Config Request */ + switch (usbInfo->xferState) + { + case USBH_XFER_START: + usbInfo->ctrl.reqData.DATA_FIELD.bmRequestType.REQ_TYPE_B.dir = USBH_REQ_DIR_IN; + usbInfo->ctrl.reqData.DATA_FIELD.bmRequestType.REQ_TYPE_B.recipient = USBH_RECIPIENT_INTERFACE; + usbInfo->ctrl.reqData.DATA_FIELD.bmRequestType.REQ_TYPE_B.type = USBH_REQ_TYPE_CLASS; + + usbInfo->ctrl.reqData.DATA_FIELD.bRequest = USBH_CLASS_GET_MAX_LUN; + + usbInfo->ctrl.reqData.DATA_FIELD.wValue[0] = 0x00; + usbInfo->ctrl.reqData.DATA_FIELD.wValue[1] = 0x00; + + usbInfo->ctrl.reqData.DATA_FIELD.wIndex[0] = 0x00; + usbInfo->ctrl.reqData.DATA_FIELD.wIndex[1] = 0x00; + + usbInfo->ctrl.reqData.DATA_FIELD.wLength[0] = 0x01; + usbInfo->ctrl.reqData.DATA_FIELD.wLength[1] = 0x00; + break; + + default: + break; + } + + usbStatus = USBH_REQ_CtrlXferHandler(usbInfo, maxLun, 1); + + return usbStatus; +} + +/**@} end of group USBH_MSC_Functions */ +/**@} end of group USBH_MSC_Class */ +/**@} end of group APM32_USB_Library */ diff --git a/lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Class/MSC/Src/usbh_msc_scsi.c b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Class/MSC/Src/usbh_msc_scsi.c new file mode 100644 index 0000000000..5388c378e7 --- /dev/null +++ b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Class/MSC/Src/usbh_msc_scsi.c @@ -0,0 +1,395 @@ +/*! + * @file usbh_msc_scsi.c + * + * @brief USB host MSC scsi + * + * @version V1.0.0 + * + * @date 2023-01-16 + * + * @attention + * + * Copyright (C) 2023 Geehy Semiconductor + * + * You may not use this file except in compliance with the + * GEEHY COPYRIGHT NOTICE (GEEHY SOFTWARE PACKAGE LICENSE). + * + * The program is only for reference, which is distributed in the hope + * that it will be useful and instructional for customers to develop + * their software. Unless required by applicable law or agreed to in + * writing, the program is distributed on an "AS IS" BASIS, WITHOUT + * ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied. + * See the GEEHY SOFTWARE PACKAGE LICENSE for the governing permissions + * and limitations under the License. + */ + +/* Includes */ +#include "usbh_msc_scsi.h" +#include "usbh_msc_bot.h" +#include "usbh_msc.h" +#include +#include +#include + +/** @addtogroup APM32_USB_Library + @{ + */ + +/** @addtogroup USBH_MSC_Class + @{ + */ + +/** @defgroup USBH_MSC_Functions Functions + @{ + */ + +/*! + * @brief USB host MSC SCSI INQUIRY handler + * + * @param usbInfo + * + * @param lun: logical unit number + * + * @param inquiry: inquiry response + * + * @retval USB host operation status + */ +USBH_STA_T USBH_MSC_SCSI_Inquiry(USBH_INFO_T* usbInfo, uint8_t lun, \ + USBH_SCSI_INQUIRY_REQ_T* inquiry) +{ + USBH_STA_T usbStatus = USBH_BUSY; + USBH_MSC_INFO_T* usbHostMSC = (USBH_MSC_INFO_T*)usbInfo->activeClass->classData; + + switch (usbHostMSC->usbHostBOT.xferState) + { + case USBH_BOT_XFER_START: + usbHostMSC->usbHostBOT.cmdPack.CBW.DATA_FIELD.dDataXferLen = LEN_XFER_INQUIRY; + usbHostMSC->usbHostBOT.cmdPack.CBW.DATA_FIELD.bmFlags.CBW_FLAG_B.dir = USBH_REQ_DIR_IN; + usbHostMSC->usbHostBOT.cmdPack.CBW.DATA_FIELD.bCBLen = USBH_LEN_CBW; + + memset(usbHostMSC->usbHostBOT.cmdPack.CBW.DATA_FIELD.CB, 0, USBH_BOT_CBW_CB_LEN); + + usbHostMSC->usbHostBOT.cmdPack.CBW.DATA_FIELD.CB[0] = USBH_SCSI_CMD_INQUIRY; + usbHostMSC->usbHostBOT.cmdPack.CBW.DATA_FIELD.CB[1] = (lun << 5); + usbHostMSC->usbHostBOT.cmdPack.CBW.DATA_FIELD.CB[2] = 0; + usbHostMSC->usbHostBOT.cmdPack.CBW.DATA_FIELD.CB[3] = 0; + usbHostMSC->usbHostBOT.cmdPack.CBW.DATA_FIELD.CB[4] = 36; + usbHostMSC->usbHostBOT.cmdPack.CBW.DATA_FIELD.CB[5] = 0; + + usbHostMSC->usbHostBOT.state = USBH_BOT_SEND_CBW; + usbHostMSC->usbHostBOT.xferState = USBH_BOT_XFER_WAITING; + + /* Init buffer point */ + usbHostMSC->usbHostBOT.buffer = (uint8_t*)(void*)usbHostMSC->usbHostBOT.data; + break; + + case USBH_BOT_XFER_WAITING: + usbStatus = USBH_MSC_BOT_Handler[usbHostMSC->usbHostBOT.state](usbInfo, lun); + + switch (usbStatus) + { + case USBH_OK: + memset(inquiry, 0, sizeof(USBH_SCSI_INQUIRY_REQ_T)); + + inquiry->devType = usbHostMSC->usbHostBOT.buffer[0] & 0x1F; + inquiry->peripheral = usbHostMSC->usbHostBOT.buffer[0] >> 5; + + if (((uint32_t) usbHostMSC->usbHostBOT.buffer[1] & 0x80) == 0x80) + { + inquiry->media = 1; + } + else + { + inquiry->media = 0; + } + + memcpy(inquiry->revID, &usbHostMSC->usbHostBOT.buffer[32], 4); + memcpy(inquiry->productID, &usbHostMSC->usbHostBOT.buffer[16], 16); + memcpy(inquiry->vendorID, &usbHostMSC->usbHostBOT.buffer[8], 8); + break; + + default: + break; + } + break; + } + + return usbStatus; +} + +/*! + * @brief USB host MSC SCSI TEST UNIT READY handler + * + * @param usbInfo + * + * @param lun: logical unit number + * + * @param inquiry: inquiry response + * + * @retval USB host operation status + */ +USBH_STA_T USBH_MSC_SCSI_TestUnitReady(USBH_INFO_T* usbInfo, uint8_t lun) +{ + USBH_STA_T usbStatus = USBH_BUSY; + USBH_MSC_INFO_T* usbHostMSC = (USBH_MSC_INFO_T*)usbInfo->activeClass->classData; + + switch (usbHostMSC->usbHostBOT.xferState) + { + case USBH_BOT_XFER_START: + usbStatus = USBH_BUSY; + + usbHostMSC->usbHostBOT.cmdPack.CBW.DATA_FIELD.dDataXferLen = LEN_XFER_TEST_UNIT_READY; + usbHostMSC->usbHostBOT.cmdPack.CBW.DATA_FIELD.bmFlags.CBW_FLAG_B.dir = USBH_REQ_DIR_OUT; + usbHostMSC->usbHostBOT.cmdPack.CBW.DATA_FIELD.bCBLen = USBH_LEN_CBW; + + memset(usbHostMSC->usbHostBOT.cmdPack.CBW.DATA_FIELD.CB, 0, USBH_BOT_CBW_CB_LEN); + + usbHostMSC->usbHostBOT.cmdPack.CBW.DATA_FIELD.CB[0] = USBH_SCSI_CMD_TEST_UNIT_READY; + + usbHostMSC->usbHostBOT.state = USBH_BOT_SEND_CBW; + usbHostMSC->usbHostBOT.xferState = USBH_BOT_XFER_WAITING; + break; + + case USBH_BOT_XFER_WAITING: + usbStatus = USBH_MSC_BOT_Handler[usbHostMSC->usbHostBOT.state](usbInfo, lun); + break; + } + + return usbStatus; +} + +/*! + * @brief USB host MSC SCSI READ CAPACITY handler + * + * @param usbInfo + * + * @param lun: logical unit number + * + * @param capacity: capacity response + * + * @retval USB host operation status + */ +USBH_STA_T USBH_MSC_SCSI_ReadCapacity(USBH_INFO_T* usbInfo, uint8_t lun, \ + USBH_SCSI_READ_CAPACITY_REQ_T* capacity) +{ + USBH_STA_T usbStatus = USBH_BUSY; + USBH_MSC_INFO_T* usbHostMSC = (USBH_MSC_INFO_T*)usbInfo->activeClass->classData; + + switch (usbHostMSC->usbHostBOT.xferState) + { + case USBH_BOT_XFER_START: + usbHostMSC->usbHostBOT.cmdPack.CBW.DATA_FIELD.dDataXferLen = LEN_XFER_READ_CAPACITY; + usbHostMSC->usbHostBOT.cmdPack.CBW.DATA_FIELD.bmFlags.CBW_FLAG_B.dir = USBH_REQ_DIR_IN; + usbHostMSC->usbHostBOT.cmdPack.CBW.DATA_FIELD.bCBLen = USBH_LEN_CBW; + + memset(usbHostMSC->usbHostBOT.cmdPack.CBW.DATA_FIELD.CB, 0, USBH_BOT_CBW_CB_LEN); + + usbHostMSC->usbHostBOT.cmdPack.CBW.DATA_FIELD.CB[0] = USBH_SCSI_CMD_READ_CAPACITY; + + usbHostMSC->usbHostBOT.state = USBH_BOT_SEND_CBW; + usbHostMSC->usbHostBOT.xferState = USBH_BOT_XFER_WAITING; + + /* Init buffer point */ + usbHostMSC->usbHostBOT.buffer = (uint8_t*)(void*)usbHostMSC->usbHostBOT.data; + break; + + case USBH_BOT_XFER_WAITING: + usbStatus = USBH_MSC_BOT_Handler[usbHostMSC->usbHostBOT.state](usbInfo, lun); + + switch (usbStatus) + { + case USBH_OK: + capacity->blockNum = usbHostMSC->usbHostBOT.buffer[3] | (usbHostMSC->usbHostBOT.buffer[2] << 8) | \ + (usbHostMSC->usbHostBOT.buffer[1] << 16) | (usbHostMSC->usbHostBOT.buffer[0] << 24); + + capacity->blockSize = usbHostMSC->usbHostBOT.buffer[7] | (usbHostMSC->usbHostBOT.buffer[6] << 8) | \ + (usbHostMSC->usbHostBOT.buffer[5] << 16) | (usbHostMSC->usbHostBOT.buffer[4] << 24); + break; + + default: + break; + } + break; + } + + return usbStatus; +} + +/*! + * @brief USB host MSC SCSI request sense handler + * + * @param usbInfo + * + * @param lun: logical unit number + * + * @param sense: sense response + * + * @retval USB host operation status + */ +USBH_STA_T USBH_MSC_SCSI_RequestSense(USBH_INFO_T* usbInfo, uint8_t lun, \ + USBH_SCSI_SENSE_REQ_T* sense) +{ + USBH_STA_T usbStatus = USBH_BUSY; + USBH_MSC_INFO_T* usbHostMSC = (USBH_MSC_INFO_T*)usbInfo->activeClass->classData; + + switch (usbHostMSC->usbHostBOT.xferState) + { + case USBH_BOT_XFER_START: + usbHostMSC->usbHostBOT.cmdPack.CBW.DATA_FIELD.dDataXferLen = LEN_XFER_REQUEST_SENSE; + usbHostMSC->usbHostBOT.cmdPack.CBW.DATA_FIELD.bmFlags.CBW_FLAG_B.dir = USBH_REQ_DIR_IN; + usbHostMSC->usbHostBOT.cmdPack.CBW.DATA_FIELD.bCBLen = USBH_LEN_CBW; + + memset(usbHostMSC->usbHostBOT.cmdPack.CBW.DATA_FIELD.CB, 0, USBH_BOT_CBW_CB_LEN); + + usbHostMSC->usbHostBOT.cmdPack.CBW.DATA_FIELD.CB[0] = USBH_SCSI_CMD_REQUEST_SENSE; + usbHostMSC->usbHostBOT.cmdPack.CBW.DATA_FIELD.CB[1] = (lun << 5); + usbHostMSC->usbHostBOT.cmdPack.CBW.DATA_FIELD.CB[2] = 0; + usbHostMSC->usbHostBOT.cmdPack.CBW.DATA_FIELD.CB[3] = 0; + usbHostMSC->usbHostBOT.cmdPack.CBW.DATA_FIELD.CB[4] = LEN_XFER_REQUEST_SENSE; + usbHostMSC->usbHostBOT.cmdPack.CBW.DATA_FIELD.CB[5] = 0; + + usbHostMSC->usbHostBOT.state = USBH_BOT_SEND_CBW; + usbHostMSC->usbHostBOT.xferState = USBH_BOT_XFER_WAITING; + + /* Init buffer point */ + usbHostMSC->usbHostBOT.buffer = (uint8_t*)(void*)usbHostMSC->usbHostBOT.data; + break; + + case USBH_BOT_XFER_WAITING: + usbStatus = USBH_MSC_BOT_Handler[usbHostMSC->usbHostBOT.state](usbInfo, lun); + + switch (usbStatus) + { + case USBH_OK: + sense->key = usbHostMSC->usbHostBOT.buffer[2] & 0x0F; + sense->asc = usbHostMSC->usbHostBOT.buffer[12]; + sense->ascq = usbHostMSC->usbHostBOT.buffer[13]; + break; + + default: + break; + } + break; + } + + return usbStatus; +} + +/*! + * @brief USB host MSC SCSI read10 handler + * + * @param usbInfo: usb host information + * + * @param lun: logical unit number + * + * @param address: sector address + * + * @param buffer: buffer point to data + * + * @param cnt: count number of data + * + * @retval USB host operation status + */ +USBH_STA_T USBH_MSC_SCSI_Read(USBH_INFO_T* usbInfo, uint8_t lun, uint32_t address, \ + uint8_t* buffer, uint16_t cnt) +{ + USBH_STA_T usbStatus = USBH_BUSY; + USBH_MSC_INFO_T* usbHostMSC = (USBH_MSC_INFO_T*)usbInfo->activeClass->classData; + + switch (usbHostMSC->usbHostBOT.xferState) + { + case USBH_BOT_XFER_START: + usbHostMSC->usbHostBOT.cmdPack.CBW.DATA_FIELD.dDataXferLen = cnt * usbHostMSC->storage[0].capacity.blockSize; + usbHostMSC->usbHostBOT.cmdPack.CBW.DATA_FIELD.bmFlags.CBW_FLAG_B.dir = USBH_REQ_DIR_IN; + usbHostMSC->usbHostBOT.cmdPack.CBW.DATA_FIELD.bCBLen = USBH_LEN_CBW; + + memset(usbHostMSC->usbHostBOT.cmdPack.CBW.DATA_FIELD.CB, 0, USBH_BOT_CBW_CB_LEN); + + usbHostMSC->usbHostBOT.cmdPack.CBW.DATA_FIELD.CB[0] = USBH_SCSI_CMD_READ_10; + + /* logical block address*/ + usbHostMSC->usbHostBOT.cmdPack.CBW.DATA_FIELD.CB[2] = (((uint8_t*)&address)[3]); + usbHostMSC->usbHostBOT.cmdPack.CBW.DATA_FIELD.CB[3] = (((uint8_t*)&address)[2]); + usbHostMSC->usbHostBOT.cmdPack.CBW.DATA_FIELD.CB[4] = (((uint8_t*)&address)[1]); + usbHostMSC->usbHostBOT.cmdPack.CBW.DATA_FIELD.CB[5] = (((uint8_t*)&address)[0]); + + /* Transfer length */ + usbHostMSC->usbHostBOT.cmdPack.CBW.DATA_FIELD.CB[7] = (((uint8_t*)&cnt)[1]); + usbHostMSC->usbHostBOT.cmdPack.CBW.DATA_FIELD.CB[8] = (((uint8_t*)&cnt)[0]); + + usbHostMSC->usbHostBOT.state = USBH_BOT_SEND_CBW; + usbHostMSC->usbHostBOT.xferState = USBH_BOT_XFER_WAITING; + + /* Init buffer point */ + usbHostMSC->usbHostBOT.buffer = buffer; + break; + + case USBH_BOT_XFER_WAITING: + usbStatus = USBH_MSC_BOT_Handler[usbHostMSC->usbHostBOT.state](usbInfo, lun); + break; + } + + return usbStatus; +} + +/*! + * @brief USB host MSC SCSI write10 handler + * + * @param usbInfo: usb host information + * + * @param lun: logical unit number + * + * @param address: sector address + * + * @param buffer: buffer point to data + * + * @param cnt: count number of data + * + * @retval USB host operation status + */ +USBH_STA_T USBH_MSC_SCSI_Write(USBH_INFO_T* usbInfo, uint8_t lun, uint32_t address, \ + uint8_t* buffer, uint16_t cnt) +{ + USBH_STA_T usbStatus = USBH_BUSY; + USBH_MSC_INFO_T* usbHostMSC = (USBH_MSC_INFO_T*)usbInfo->activeClass->classData; + + switch (usbHostMSC->usbHostBOT.xferState) + { + case USBH_BOT_XFER_START: + + usbHostMSC->usbHostBOT.cmdPack.CBW.DATA_FIELD.dDataXferLen = cnt * usbHostMSC->storage[0].capacity.blockSize; + usbHostMSC->usbHostBOT.cmdPack.CBW.DATA_FIELD.bmFlags.CBW_FLAG_B.dir = USBH_REQ_DIR_OUT; + usbHostMSC->usbHostBOT.cmdPack.CBW.DATA_FIELD.bCBLen = USBH_LEN_CBW; + + memset(usbHostMSC->usbHostBOT.cmdPack.CBW.DATA_FIELD.CB, 0, USBH_BOT_CBW_CB_LEN); + + usbHostMSC->usbHostBOT.cmdPack.CBW.DATA_FIELD.CB[0] = USBH_SCSI_CMD_WRITE10; + + /* logical block address*/ + usbHostMSC->usbHostBOT.cmdPack.CBW.DATA_FIELD.CB[2] = (((uint8_t*)&address)[3]); + usbHostMSC->usbHostBOT.cmdPack.CBW.DATA_FIELD.CB[3] = (((uint8_t*)&address)[2]); + usbHostMSC->usbHostBOT.cmdPack.CBW.DATA_FIELD.CB[4] = (((uint8_t*)&address)[1]); + usbHostMSC->usbHostBOT.cmdPack.CBW.DATA_FIELD.CB[5] = (((uint8_t*)&address)[0]); + + /* Transfer length */ + usbHostMSC->usbHostBOT.cmdPack.CBW.DATA_FIELD.CB[7] = (((uint8_t*)&cnt)[1]); + usbHostMSC->usbHostBOT.cmdPack.CBW.DATA_FIELD.CB[8] = (((uint8_t*)&cnt)[0]); + + usbHostMSC->usbHostBOT.state = USBH_BOT_SEND_CBW; + usbHostMSC->usbHostBOT.xferState = USBH_BOT_XFER_WAITING; + + /* Init buffer point */ + usbHostMSC->usbHostBOT.buffer = buffer; + break; + + case USBH_BOT_XFER_WAITING: + usbStatus = USBH_MSC_BOT_Handler[usbHostMSC->usbHostBOT.state](usbInfo, lun); + break; + } + + return usbStatus; +} + +/**@} end of group USBH_MSC_Functions */ +/**@} end of group USBH_MSC_Class */ +/**@} end of group APM32_USB_Library */ diff --git a/lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Core/Inc/usbh_channel.h b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Core/Inc/usbh_channel.h new file mode 100644 index 0000000000..830f8f060e --- /dev/null +++ b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Core/Inc/usbh_channel.h @@ -0,0 +1,53 @@ +/*! + * @file usbh_channel.h + * + * @brief USB host channel handler function + * + * @version V1.0.0 + * + * @date 2023-01-16 + * + * @attention + * + * Copyright (C) 2023 Geehy Semiconductor + * + * You may not use this file except in compliance with the + * GEEHY COPYRIGHT NOTICE (GEEHY SOFTWARE PACKAGE LICENSE). + * + * The program is only for reference, which is distributed in the hope + * that it will be useful and instructional for customers to develop + * their software. Unless required by applicable law or agreed to in + * writing, the program is distributed on an "AS IS" BASIS, WITHOUT + * ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied. + * See the GEEHY SOFTWARE PACKAGE LICENSE for the governing permissions + * and limitations under the License. + */ + +/* Define to prevent recursive inclusion */ +#ifndef _USBH_CHANNEL_H_ +#define _USBH_CHANNEL_H_ + +/* Includes */ +#include "usbh_config.h" + +/** @addtogroup APM32_USB_Library + @{ + */ + +/** @addtogroup USBH_Core + @{ + */ + +/** @defgroup USBH_Core_Functions Functions + @{ + */ + +void USBH_CH_Clear(USBH_INFO_T* usbInfo); +void USBH_CH_FreeChannel(USBH_INFO_T* usbInfo, uint8_t chNum); +uint8_t USBH_CH_AllocChannel(USBH_INFO_T* usbInfo, uint8_t epAddr); + +/**@} end of group USBH_Core_Functions */ +/**@} end of group USBH_Core */ +/**@} end of group APM32_USB_Library */ + +#endif diff --git a/lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Core/Inc/usbh_config.h b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Core/Inc/usbh_config.h new file mode 100644 index 0000000000..db0b4cab03 --- /dev/null +++ b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Core/Inc/usbh_config.h @@ -0,0 +1,491 @@ +/*! + * @file usbh_config.h + * + * @brief usb host config header file + * + * @version V1.0.1 + * + * @date 2023-03-27 + * + * @attention + * + * Copyright (C) 2023 Geehy Semiconductor + * + * You may not use this file except in compliance with the + * GEEHY COPYRIGHT NOTICE (GEEHY SOFTWARE PACKAGE LICENSE). + * + * The program is only for reference, which is distributed in the hope + * that it will be useful and instructional for customers to develop + * their software. Unless required by applicable law or agreed to in + * writing, the program is distributed on an "AS IS" BASIS, WITHOUT + * ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied. + * See the GEEHY SOFTWARE PACKAGE LICENSE for the governing permissions + * and limitations under the License. + */ + +/* Define to prevent recursive inclusion */ +#ifndef _USBH_CONFIG_H_ +#define _USBH_CONFIG_H_ + +/* Includes */ +#include "usbh_board.h" +#include + +/** @addtogroup APM32_USB_Library + @{ + */ + +/** @addtogroup USBH_Core + @{ + */ + +/** @defgroup USBH_Core_Macros Macros + @{ +*/ + +/*!< [31:16] APM32 USB Host Library main version V1.1.3*/ +#define __APM32_USB_HOST_VERSION_MAIN (0x01) /*!< [31:24] main version */ +#define __APM32_USB_HOST_VERSION_SUB1 (0x01) /*!< [23:16] sub1 version */ +#define __APM32_USB_HOST_VERSION_SUB2 (0x03) /*!< [15:8] sub2 version */ +#define __APM32_USB_HOST_VERSION_RC (0x00) /*!< [7:0] release candidate */ +#define __APM32_USB_HOST_VERSION ((__APM32_USB_HOST_VERSION_MAIN << 24)\ + |(__APM32_USB_HOST_VERSION_SUB1 << 16)\ + |(__APM32_USB_HOST_VERSION_SUB2 << 8 )\ + |(__APM32_USB_HOST_VERSION_RC)) + +#define USBH_EP0_PACKET_SIZE 0x40 +#define USBH_LANG_ID 0x0409 + +#define USB_REQ_DIR_OUT 0x00 +#define USB_REQ_DIR_IN 0x80 + +#define USBH_DEVICE_RESET_TIMEOUT 0x64 +#define USBH_DEVICE_DEFAULT_ADDRESS 0 +#define USBH_DEVICE_CONFIGURED_ADDRESS 1 + +#define STD_DEV_DESC_SIZE 18 +#define STD_CFG_DESC_SIZE 9 +#define STD_INTERFACE_DESC_SIZE 9 +#define STD_EP_DESC_SIZE 7 +#define STD_HID_DESC_SIZE 9 + +#define CFG_DESC_MAX_LEN 256 +#define STRING_DESC_MAX_LEN 0x200 + +#ifndef USBH_Delay +#define USBH_Delay DAL_Delay +#endif + +/**@} end of group USBH_Core_Macros*/ + +/** @defgroup USBH_Core_Enumerates Enumerates + @{ + */ + +/** + * @brief USB host speed type + */ +typedef enum +{ + USBH_SPEED_FS, + USBH_SPEED_HS, +} USBH_SPEED_T; + +/** + * @brief USB device speed + */ +typedef enum +{ + USBH_DEVICE_SPEED_HS, + USBH_DEVICE_SPEED_FS, + USBH_DEVICE_SPEED_LS +} USBH_DEVICE_SPEED_T; + +/** + * @brief USB host operation status + */ +typedef enum +{ + USBH_OK, + USBH_BUSY, + USBH_FAIL, + USBH_ERR_NOT_SUP, + USBH_ERR_UNRECOVERED, + USBH_ERR_SPEED_UNKOWN, +} USBH_STA_T; + +/** + * @brief USB host state machine + */ +typedef enum +{ + USBH_HOST_IDLE, + USBH_HOST_DEVICE_ATTACHED, + USBH_HOST_DEVICE_DISCONNECTED, + USBH_HOST_ENUMERATION, + USBH_HOST_CLASS_REQ, + USBH_HOST_USER_INPUT, + USBH_HOST_SET_CONFIGURATION, + USBH_HOST_SET_FEATURE, + USBH_HOST_CLASS_ACTIVE, + USBH_HOST_CLASS, + USBH_HOST_SUSPEND, + USBH_HOST_ABORT, +} USBH_HOST_STA_T; + +/** + * @brief USB host enumeration state + */ +typedef enum +{ + USBH_ENUM_IDLE, //!< enum idle + USBH_ENUM_GET_DEV_DESC, //!< Get device descriptor + USBH_ENUM_SET_ADDR, //!< Set address + USBH_ENUM_GET_CFG_DESC, //!< Get Configuration descriptor + USBH_ENUM_GET_FULL_CFG_DESC, //!< Get Full Configuration descriptor + USBH_ENUM_GET_MFC_STRING_DESC, //!< Get Manufacturer string + USBH_ENUM_GET_PRODUCT_STRING_DESC, //!< Get Product string + USBH_ENUM_GET_SERIALNUM_STRING_DESC, //!< Get serial number string +} USBH_ENUM_STA_T; + +/** + * @brief USB transfer state + */ +typedef enum +{ + USBH_XFER_START, + USBH_XFER_WAITING, + USBH_XFER_OK, +} USBH_XFER_STA_T; + +/** + * @brief USB Host control transfer state + */ +typedef enum +{ + USBH_CTRL_IDLE, + USBH_CTRL_SETUP, + USBH_CTRL_SETUP_WAIT, + USBH_CTRL_DATA_IN, + USBH_CTRL_DATA_IN_WAIT, + USBH_CTRL_DATA_OUT, + USBH_CTRL_DATA_OUT_WAIT, + USBH_CTRL_STA_IN, + USBH_CTRL_STA_IN_WAIT, + USBH_CTRL_STA_OUT, + USBH_CTRL_STA_OUT_WAIT, + USBH_CTRL_ERROR, + USBH_CTRL_STALL, + USBH_CTRL_OK +} USBH_CTRL_STATE_T; + +/** + * @brief USB device feature request type + */ +typedef enum +{ + USBH_FEATURE_SELECTOR_ENDPOINT_HALT, + USBH_FEATURE_REMOTE_WAKEUP, + USBH_FEATURE_TEST_MODE, +} USBH_REQ_FEATURE_T; + +/** + * @brief USB device request direction + */ +typedef enum +{ + USBH_REQ_DIR_OUT, + USBH_REQ_DIR_IN +} USBH_DEV_REQ_DIR_T; + +/** + * @brief USB device request type + */ +typedef enum +{ + USBH_REQ_TYPE_STANDARD = 0, + USBH_REQ_TYPE_CLASS, + USBH_REQ_TYPE_VENDOR, + USBH_REQ_TYPE_RESERVED +} USBH_DEV_REQ_TYPE_T; + +/** + * @brief USB device request recipient + */ +typedef enum +{ + USBH_RECIPIENT_DEVICE = 0, + USBH_RECIPIENT_INTERFACE, + USBH_RECIPIENT_ENDPOINT, + USBH_RECIPIENT_OTHER +} USBH_DEV_RECIPIENT_T; + +/** + * @brief USB standard device standard requests type + */ +typedef enum +{ + USBH_STD_GET_STATUS = 0, + USBH_STD_CLEAR_FEATURE = 1, + USBH_STD_SET_FEATURE = 3, + USBH_STD_SET_ADDRESS = 5, + USBH_STD_GET_DESCRIPTOR = 6, + USBH_STD_SET_DESCRIPTOR = 7, + USBH_STD_GET_CONFIGURATION = 8, + USBH_STD_SET_CONFIGURATION = 9, + USBH_STD_GET_INTERFACE = 10, + USBH_STD_SET_INTERFACE = 11, + USBH_STD_SYNCH_FRAME = 12 +} USBH_STD_REQ_TYPE_T; + +/** + * @brief USB descriptor types + */ +typedef enum +{ + USBH_DESC_DEVICE = 1, + USBH_DESC_CONFIGURATION = 2, + USBH_DESC_STRING = 3, + USBH_DESC_INTERFACE = 4, + USBH_DESC_ENDPOINT = 5, + USBH_DESC_DEVICE_QUALIFIER = 6, + USBH_DESC_OTHER_SPEED = 7, + USBH_DESC_INTERFACE_POWER = 8, + USBH_DESC_HID = 0x21, + USBH_DESC_HID_REPORT = 0x22, + USBH_DESC_HID_PHY = 0x23, +} USBH_DESC_TYPE_T; + +/** + * @brief USB Class type + */ +typedef enum +{ + USBH_CLASS_AUDIO = 0x01, //!< Audio + USBH_CLASS_CDCC = 0x02, //!< Communications and CDC Control + USBH_CLASS_HID = 0x03, //!< HID (Human Interface Device) + USBH_CLASS_PRINTER = 0x07, //!< Printer + USBH_CLASS_MSC = 0x08, //!< Mass Storage + USBH_CLASS_HUB = 0x09, //!< Hub + USBH_CLASS_CDCD = 0x0A, //!< CDC-Data + USBH_CLASS_SMARTCARD = 0x0B, //!< Smart Card + USBH_CLASS_VIDEO = 0x0E, //!< Video + USBH_CLASS_AVD = 0x10 //!< Audio/Video Devices +} USBH_CLASS_TYPE_T; + +/**@} end of group USBH_Core_Enumerates*/ + +/** @defgroup USBH_Core_Structures Structures + @{ + */ + +/** + * @brief USB request type + */ +typedef union +{ + uint8_t REQ_TYPE; + + struct + { + uint8_t recipient : 5; + uint8_t type : 2; + uint8_t dir : 1; + } REQ_TYPE_B; +} USBH_REQ_TYPE_T; + +/** + * @brief USB Host request data + */ +typedef struct +{ + union + { + uint8_t REQ_DATA[8]; + + struct + { + USBH_REQ_TYPE_T bmRequestType; + uint8_t bRequest; + uint8_t wValue[2]; + uint8_t wIndex[2]; + uint8_t wLength[2]; + } DATA_FIELD; + }; + +} USBH_REQ_DATA_T; + +/** + * @brief USB device descriptor + */ +typedef struct +{ + uint8_t bLength; //!< Descriptor length + uint8_t bDescriptorType; //!< Descriptor Type + uint8_t bcdUSB[2]; //!< BCD of the supported USB specification + uint8_t bDeviceClass; //!< USB device class + uint8_t bDeviceSubClass; //!< USB device subclass + uint8_t bDeviceProtocol; //!< USB device protocol + uint8_t bMaxPacketSize; //!< Max Packet Size + uint8_t idVendor[2]; //!< Vendor ID + uint8_t idProduct[2]; //!< Product ID + uint8_t bcdDevice[2]; //!< Device Release Number + uint8_t iManufacturer; //!< Index of Manufacturer String Descriptor + uint8_t iProduct; //!< Index of Product String Descriptor + uint8_t iSerialNumber; //!< Index of Serial Number String Descriptor + uint8_t bNumConfigurations; //!< Number of Possible Configurations +} USBH_DEV_DESC_T; + +/** + * @brief USB Endpoint descriptor + */ +typedef struct +{ + uint8_t bLength; //!< Descriptor length + uint8_t bDescriptorType; //!< Descriptor Type + uint8_t bEndpointAddress; //!< Indicates what endpoint this descriptor is describing + uint8_t bmAttributes; //!< Specifies the transfer type + uint8_t wMaxPacketSize[2]; //!< Maximum Packet Size this endpoint is capable of sending or receiving + uint8_t bInterval; //!< Polling interval in milliseconds for the endpoint +} USBH_EP_DESC_T; + +/** + * @brief USB Interface descriptor + */ +typedef struct +{ + uint8_t bLength; //!< Descriptor length + uint8_t bDescriptorType; //!< Descriptor Type + uint8_t bInterfaceNumber; //!< Interface Number + uint8_t bAlternateSetting; //!< Value used to select alternative setting + uint8_t bNumEndpoints; //!< Number of Endpoints used for this interface + uint8_t bInterfaceClass; //!< Class Code + uint8_t bInterfaceSubClass; //!< Sub class Code + uint8_t bInterfaceProtocol; //!< Protocol Code + uint8_t iInterface; //!< Index of String Descriptor of this interface +} USBH_ITF_DESC_T; + +/** + * @brief USB Configuration descriptor + */ +typedef struct +{ + uint8_t bLength; //!< Descriptor length + uint8_t bDescriptorType; //!< Descriptor Type + uint8_t wTotalLength[2]; //!< Total Length of Configuration Descriptor gather + uint8_t bNumInterfaces; //!< Total number of interfaces in the configuration + uint8_t bConfigurationValue; //!< Configuration index of the current configuration + uint8_t iConfiguration; //!< Index of a string descriptor describing the configuration + uint8_t bmAttributes; //!< Configuration attributes + uint8_t bMaxPower; //!< Maximum power consumption +} USBH_CFG_DESC_T; + +/** + * @brief USB Interface and Endpoint descriptor + */ +typedef struct +{ + USBH_ITF_DESC_T interfaceDesc; + USBH_EP_DESC_T endpointDesc[ENDPOINT_DESC_MAX_NUM]; +} USBH_INTERFACE_T; + +/** + * @brief USB Host Descriptor structure + */ +typedef struct +{ + USBH_DEV_DESC_T device; + USBH_CFG_DESC_T configuration; + USBH_INTERFACE_T interface[INTERFACE_DESC_MAX_NUM]; + uint8_t cfgDescBuf[CFG_DESC_MAX_LEN]; + uint8_t stringBuf[STRING_DESC_MAX_LEN]; +} USBH_DESC_T; + +/** + * @brief USB Host device information + */ +typedef struct +{ + uint8_t data[USBH_DATA_BUF_MAX_NUM]; + uint8_t address; + uint8_t speed; + __IO uint8_t connectedStatus; + __IO uint8_t disconnectedStatus; + __IO uint8_t reEnumStatus; + uint8_t portEnable; + uint8_t rstCnt; + uint8_t enumCnt; + USBH_DESC_T desc; +} USBH_DEV_INFO_T; + +/** + * @brief USB Control thansfer info + */ +typedef struct +{ + uint8_t state; + uint8_t errCnt; + uint8_t channelInNum; + uint8_t channelOutNum; + uint8_t channelSize; + uint8_t* buffer; + uint16_t length; + USBH_REQ_DATA_T reqData; +} USBH_CTRL_T; + +struct _USBH_INFO_T; + +/* Class callback function type define */ +typedef USBH_STA_T(*USBH_ClassCallback_T)(struct _USBH_INFO_T* usbInfo); + +/** + * @brief USB host class handler + */ +typedef struct +{ + const char* className; + uint8_t classCode; + void* classData; + USBH_ClassCallback_T classInitHandler; + USBH_ClassCallback_T classDeInitHandler; + USBH_ClassCallback_T classReqHandler; + USBH_ClassCallback_T classCoreHandler; + USBH_ClassCallback_T classSofHandler; +} USBH_CLASS_T; + +/* Host state handler function */ +typedef USBH_STA_T(*USBH_CoreHandler_T)(struct _USBH_INFO_T* usbInfo); + +/* Host enum state handler function */ +typedef USBH_STA_T(*USBH_EnumHandler_T)(struct _USBH_INFO_T* usbInfo); + +/* Host control transfer state handler function */ +typedef USBH_STA_T(*USBH_CtrlStateHandler_T)(struct _USBH_INFO_T* usbInfo); + +/** + * @brief USB host information + */ +typedef struct _USBH_INFO_T +{ + USBH_HOST_STA_T hostState; /*!< USB Host State Machine*/ + USBH_ENUM_STA_T hostEnumState; + USBH_SPEED_T hostSpeed; + USBH_DEV_INFO_T devInfo; + uint8_t xferState; + USBH_CTRL_T ctrl; /*!< Control Thansfer info management*/ + USBH_CLASS_T* hostClass[USBH_SUP_CLASS_MAX_NUM]; /*!< USB host class */ + USBH_CLASS_T* activeClass; + uint32_t classNum; + __IO uint32_t timer; + uint32_t timeout; + uint32_t xferChannel[USBH_CHANNEL_MAX_NUM]; /*!< Thansfer data management (The sixteenth bit is indicate free or not status)*/ + void (*userCallback)(struct _USBH_INFO_T* usbInfo, uint8_t userStatus); + void* dataPoint; +} USBH_INFO_T; + + +/**@} end of group USBH_Core_Structures*/ +/**@} end of group USBH_Core */ +/**@} end of group APM32_USB_Library */ + +#endif diff --git a/lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Core/Inc/usbh_core.h b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Core/Inc/usbh_core.h new file mode 100644 index 0000000000..21becd7e8b --- /dev/null +++ b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Core/Inc/usbh_core.h @@ -0,0 +1,104 @@ +/*! + * @file usbh_core.h + * + * @brief USB host core function + * + * @version V1.0.0 + * + * @date 2023-01-16 + * + * @attention + * + * Copyright (C) 2023 Geehy Semiconductor + * + * You may not use this file except in compliance with the + * GEEHY COPYRIGHT NOTICE (GEEHY SOFTWARE PACKAGE LICENSE). + * + * The program is only for reference, which is distributed in the hope + * that it will be useful and instructional for customers to develop + * their software. Unless required by applicable law or agreed to in + * writing, the program is distributed on an "AS IS" BASIS, WITHOUT + * ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied. + * See the GEEHY SOFTWARE PACKAGE LICENSE for the governing permissions + * and limitations under the License. + */ + +/* Define to prevent recursive inclusion */ +#ifndef _USBH_CORE_H_ +#define _USBH_CORE_H_ + +/* Includes */ +#include "usbh_config.h" +#include "usbh_channel.h" +#include "usbh_stdReq.h" + +/** @addtogroup APM32_USB_Library + @{ + */ + +/** @addtogroup USBH_Core + @{ + */ + +/** @defgroup USBH_Core_Enumerates Enumerates + @{ + */ + +/** + * @brief USB host user status + */ +typedef enum +{ + USBH_USER_CONNECTION = 1, + USBH_USER_DISCONNECTION, + USBH_USER_DETECTED_SPEED, + USBH_USER_ENUMERATION, + USBH_USER_CLASS_LAUNCHED, + USBH_USER_NOT_SUPPORT, + USBH_USER_ERROR, +} USBH_USER_STATUS; + +/**@} end of group USBH_Core_Enumerates*/ + +/** @defgroup USBH_Core_Functions Functions + @{ + */ + +USBH_STA_T USBH_Init(USBH_INFO_T* usbInfo, USBH_SPEED_T usbHostSpeed, USBH_CLASS_T* usbHostClass, + void (*userCallbackFunc)(struct _USBH_INFO_T*, uint8_t)); +USBH_STA_T USBH_DeInit(USBH_INFO_T* usbInfo); +USBH_STA_T USBH_RegisterClass(USBH_INFO_T* usbInfo, USBH_CLASS_T* usbHostClass); +USBH_STA_T USBH_PollingProcess(USBH_INFO_T* usbInfo); +USBH_STA_T USBH_Disconnect(USBH_INFO_T* usbInfo); +USBH_STA_T USBH_Connect(USBH_INFO_T* usbInfo); +USBH_STA_T USBH_PortEnable(USBH_INFO_T* usbInfo); +USBH_STA_T USBH_PortDisable(USBH_INFO_T* usbInfo); +void USBH_IncTimer(USBH_INFO_T* usbInfo); +void USBH_ConfigTimer(USBH_INFO_T* usbInfo, uint32_t tick); +void USBH_HardwareInit(USBH_INFO_T* usbInfo); +void USBH_HardwareReset(USBH_INFO_T* usbInfo); +void USBH_StopHostCallback(USBH_INFO_T* usbInfo); +void USBH_StartCallback(USBH_INFO_T* usbInfo); +void USBH_StopCallback(USBH_INFO_T* usbInfo); +void USBH_ResetCallback(USBH_INFO_T* usbInfo); +uint8_t USBH_ReadSpeedCallback(USBH_INFO_T* usbInfo); +void USBH_OpenChannelCallback(USBH_INFO_T* usbInfo, uint8_t channelNum, \ + uint8_t endPointNum, uint8_t devAddr, \ + uint8_t devSpeed, uint8_t epType, uint16_t packetMaxSize); + +void USBH_UrbSubmitCallback(USBH_INFO_T* usbInfo, uint8_t chNum, uint8_t dir, \ + uint8_t epType, uint8_t tokenType, uint8_t* buffer, \ + uint16_t length, uint8_t pingStatus); + +uint8_t USBH_ReadUrbStatusCallback(USBH_INFO_T* usbInfo, uint8_t channelNum); +void USBH_ConfigDataPidCallback(USBH_INFO_T* usbInfo, uint8_t channelNum, uint8_t dataPid); +void USBH_CloseChannelCallback(USBH_INFO_T* usbInfo, uint8_t channelNum); +uint32_t USBH_ReadLastXferSizeCallback(USBH_INFO_T* usbInfo, uint8_t channelNum); +uint8_t USBH_ReadToggleCallback(USBH_INFO_T* usbInfo, uint8_t channelNum); +void USBH_ConfigToggleCallback(USBH_INFO_T* usbInfo, uint8_t channelNum, uint8_t toggle); + +/**@} end of group USBH_Core_Functions */ +/**@} end of group USBH_Core */ +/**@} end of group APM32_USB_Library */ + +#endif diff --git a/lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Core/Inc/usbh_dataXfer.h b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Core/Inc/usbh_dataXfer.h new file mode 100644 index 0000000000..0044bd356f --- /dev/null +++ b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Core/Inc/usbh_dataXfer.h @@ -0,0 +1,76 @@ +/*! + * @file usbh_dataXfer.h + * + * @brief USB host input and output hander function head file + * + * @version V1.0.0 + * + * @date 2023-01-16 + * + * @attention + * + * Copyright (C) 2023 Geehy Semiconductor + * + * You may not use this file except in compliance with the + * GEEHY COPYRIGHT NOTICE (GEEHY SOFTWARE PACKAGE LICENSE). + * + * The program is only for reference, which is distributed in the hope + * that it will be useful and instructional for customers to develop + * their software. Unless required by applicable law or agreed to in + * writing, the program is distributed on an "AS IS" BASIS, WITHOUT + * ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied. + * See the GEEHY SOFTWARE PACKAGE LICENSE for the governing permissions + * and limitations under the License. + */ + +/* Define to prevent recursive inclusion */ +#ifndef _USBH_DATAXFER_H_ +#define _USBH_DATAXFER_H_ + +/* Includes */ +#include "usbh_config.h" + +/** @addtogroup APM32_USB_Library + @{ + */ + +/** @addtogroup USBH_Core + @{ + */ + +/** @defgroup USBH_Core_Structures Structures + @{ + */ + +extern USBH_CtrlStateHandler_T USBH_CtrlStateHandler[]; + +/**@} end of group USBH_Core_Structures*/ + +/** @defgroup USBH_Core_Functions Functions + @{ + */ + +USBH_STA_T USBH_BulkSendDataReq(USBH_INFO_T* usbInfo, uint8_t channelNum, \ + uint8_t* buffer, uint16_t length, \ + uint8_t pingStatus); + +USBH_STA_T USBH_BulkReceiveDataReq(USBH_INFO_T* usbInfo, uint8_t channelNum, \ + uint8_t* buffer, uint16_t length); + +USBH_STA_T USBH_IntSendDataReq(USBH_INFO_T* usbInfo, uint8_t channelNum, \ + uint8_t* buffer, uint8_t length); + +USBH_STA_T USBH_IntReceiveDataReq(USBH_INFO_T* usbInfo, uint8_t channelNum, \ + uint8_t* buffer, uint8_t length); + +USBH_STA_T USBH_IntSendDataReq(USBH_INFO_T* usbInfo, uint8_t channelNum, \ + uint8_t* buffer, uint8_t length); + +USBH_STA_T USBH_IsoReceiveDataReq(USBH_INFO_T* usbInfo, uint8_t channelNum, \ + uint8_t* buffer, uint8_t length); + +/**@} end of group USBH_Core_Functions */ +/**@} end of group USBH_Core */ +/**@} end of group APM32_USB_Library */ + +#endif diff --git a/lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Core/Inc/usbh_enum.h b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Core/Inc/usbh_enum.h new file mode 100644 index 0000000000..bb05686700 --- /dev/null +++ b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Core/Inc/usbh_enum.h @@ -0,0 +1,51 @@ +/*! + * @file usbh_enum.h + * + * @brief USB host enum hander function head file + * + * @version V1.0.0 + * + * @date 2023-01-16 + * + * @attention + * + * Copyright (C) 2023 Geehy Semiconductor + * + * You may not use this file except in compliance with the + * GEEHY COPYRIGHT NOTICE (GEEHY SOFTWARE PACKAGE LICENSE). + * + * The program is only for reference, which is distributed in the hope + * that it will be useful and instructional for customers to develop + * their software. Unless required by applicable law or agreed to in + * writing, the program is distributed on an "AS IS" BASIS, WITHOUT + * ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied. + * See the GEEHY SOFTWARE PACKAGE LICENSE for the governing permissions + * and limitations under the License. + */ + +/* Define to prevent recursive inclusion */ +#ifndef _USBH_ENUM_H_ +#define _USBH_ENUM_H_ + +/* Includes */ +#include "usbh_config.h" + +/** @addtogroup APM32_USB_Library + @{ + */ + +/** @addtogroup USBH_Core + @{ + */ + +/** @defgroup USBH_Core_Structures Structures + @{ + */ + +extern USBH_EnumHandler_T USBH_EnumHandler[]; + +/**@} end of group USBH_Core_Structures*/ +/**@} end of group USBH_Core */ +/**@} end of group APM32_USB_Library */ + +#endif diff --git a/lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Core/Inc/usbh_stdReq.h b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Core/Inc/usbh_stdReq.h new file mode 100644 index 0000000000..a7badeefd5 --- /dev/null +++ b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Core/Inc/usbh_stdReq.h @@ -0,0 +1,96 @@ +/*! + * @file usbh_stdReq.h + * + * @brief USB standard request process + * + * @version V1.0.0 + * + * @date 2023-01-16 + * + * @attention + * + * Copyright (C) 2023 Geehy Semiconductor + * + * You may not use this file except in compliance with the + * GEEHY COPYRIGHT NOTICE (GEEHY SOFTWARE PACKAGE LICENSE). + * + * The program is only for reference, which is distributed in the hope + * that it will be useful and instructional for customers to develop + * their software. Unless required by applicable law or agreed to in + * writing, the program is distributed on an "AS IS" BASIS, WITHOUT + * ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied. + * See the GEEHY SOFTWARE PACKAGE LICENSE for the governing permissions + * and limitations under the License. + */ + +/* Define to prevent recursive inclusion */ +#ifndef _USBH_STDREQ_H_ +#define _USBH_STDREQ_H_ + +/* Includes */ +#include "usbh_config.h" + +/** @addtogroup APM32_USB_Library + @{ + */ + +/** @addtogroup USBH_Core + @{ + */ + +/** @defgroup USBH_Core_Macros Macros + @{ +*/ + +#define USBH_SETUP_PACKET_SIZE 8 +#define USBH_ReadConfigurationItfNum(usbInfo) \ + usbInfo->devInfo.desc.configuration.bNumInterfaces + +#define USBH_ReadInterfaceClass(usbInfo, itfIndex) \ + usbInfo->devInfo.desc.interface[itfIndex].interfaceDesc.bInterfaceClass + +#define USBH_ReadInterfaceSubClass(usbInfo, itfIndex) \ + usbInfo->devInfo.desc.interface[itfIndex].interfaceDesc.bInterfaceSubClass + +#define USBH_ReadInterfaceProtocol(usbInfo, itfIndex) \ + usbInfo->devInfo.desc.interface[itfIndex].interfaceDesc.bInterfaceProtocol + +#define USBH_ReadInterfaceEpNum(usbInfo, itfIndex) \ + usbInfo->devInfo.desc.interface[itfIndex].interfaceDesc.bNumEndpoints + +#define USBH_ReadEndpointAddress(usbInfo, itfIndex, epIndex) \ + usbInfo->devInfo.desc.interface[itfIndex].endpointDesc[epIndex].bEndpointAddress + +#define USBH_ReadEndpointMPS(usbInfo, itfIndex, epIndex) \ + ((uint16_t)usbInfo->devInfo.desc.interface[itfIndex].endpointDesc[epIndex].wMaxPacketSize[0] | \ + (uint16_t)usbInfo->devInfo.desc.interface[itfIndex].endpointDesc[epIndex].wMaxPacketSize[1] << 8) + +#define USBH_ReadEndpointInterval(usbInfo, itfIndex, epIndex) \ + usbInfo->devInfo.desc.interface[itfIndex].endpointDesc[epIndex].bInterval + +/**@} end of group USBH_Core_Macros*/ + +/** @defgroup USBH_Core_Functions Functions + @{ + */ + +USBH_STA_T USBH_GetDevDesc(USBH_INFO_T* usbInfo, uint8_t desLength); +USBH_STA_T USBH_SetAddr(USBH_INFO_T* usbInfo, uint8_t address); +USBH_STA_T USBH_GetCfgDesc(USBH_INFO_T* usbInfo, uint16_t desLength); +USBH_STA_T USBH_GetStringDesc(USBH_INFO_T* usbInfo, uint8_t stringIndex, \ + uint8_t* buffer, uint16_t desLength); + +USBH_STA_T USBH_REQ_GetDescriptor(USBH_INFO_T* usbInfo, uint8_t reqType, \ + uint16_t desType, uint8_t* buffer, uint16_t length); + +USBH_STA_T USBH_SetConfiguration(USBH_INFO_T* usbInfo, uint16_t configuration); +USBH_STA_T USBH_SetFeature(USBH_INFO_T* usbInfo, uint8_t feature); +USBH_STA_T USBH_ClearFeature(USBH_INFO_T* usbInfo, uint8_t epNum); + +USBH_STA_T USBH_REQ_CtrlXferHandler(USBH_INFO_T* usbInfo, uint8_t* buffer, uint16_t length); + +/**@} end of group USBH_Core_Functions */ +/**@} end of group USBH_Core */ +/**@} end of group APM32_USB_Library */ + +#endif diff --git a/lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Core/Src/usbh_channel.c b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Core/Src/usbh_channel.c new file mode 100644 index 0000000000..9e001a982a --- /dev/null +++ b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Core/Src/usbh_channel.c @@ -0,0 +1,123 @@ +/*! + * @file usbh_core.c + * + * @brief USB host core function + * + * @version V1.0.0 + * + * @date 2023-01-16 + * + * @attention + * + * Copyright (C) 2023 Geehy Semiconductor + * + * You may not use this file except in compliance with the + * GEEHY COPYRIGHT NOTICE (GEEHY SOFTWARE PACKAGE LICENSE). + * + * The program is only for reference, which is distributed in the hope + * that it will be useful and instructional for customers to develop + * their software. Unless required by applicable law or agreed to in + * writing, the program is distributed on an "AS IS" BASIS, WITHOUT + * ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied. + * See the GEEHY SOFTWARE PACKAGE LICENSE for the governing permissions + * and limitations under the License. + */ + +/* Includes */ +#include "usbh_channel.h" +#include "usbh_core.h" + +/** @addtogroup APM32_USB_Library + @{ + */ + +/** @addtogroup USBH_Core + @{ + */ + +/** @defgroup USBH_Core_Functions Functions + @{ + */ + +/*! + * @brief Clear all of the pipe data buffer. + * + * @param usbInfo + * + * @retval None + */ +void USBH_CH_Clear(USBH_INFO_T* usbInfo) +{ + uint8_t i = 0; + + for (i = 0; i < USBH_CHANNEL_MAX_NUM; i++) + { + usbInfo->xferChannel[i] = 0; + } +} + +/*! + * @brief Get the free channel. + * + * @param usbInfo + * + * @retval None. + */ +uint16_t USBH_CH_ReadFreeChannel(USBH_INFO_T* usbInfo) +{ + uint8_t i; + + for (i = 0; i < USBH_CHANNEL_MAX_NUM; i++) + { + if ((usbInfo->xferChannel[i] & 0x8000) == 0) + { + return i; + } + } + + return 0xFFFF; +} + +/*! + * @brief Free the channel. + * + * @param usbInfo + * + * @param chNum : channel to be free. + * + * @retval None. + */ +void USBH_CH_FreeChannel(USBH_INFO_T* usbInfo, uint8_t chNum) +{ + if (chNum < USBH_CHANNEL_MAX_NUM) + { + usbInfo->xferChannel[chNum] &= 0x7FFF; + } +} + +/*! + * @brief Alloc a channel for a endpoint by address. + * + * @param usbInfo + * + * @param epAddr : endpoint address to be alloc channel. + * + * @retval channel number. + */ +uint8_t USBH_CH_AllocChannel(USBH_INFO_T* usbInfo, uint8_t epAddr) +{ + uint16_t channelNum; + + channelNum = USBH_CH_ReadFreeChannel(usbInfo); + + if (channelNum != 0xFFFF) + { + usbInfo->xferChannel[channelNum & 0x0F] = (uint32_t)(0x8000 | epAddr); + } + + return (uint8_t)channelNum; +} + +/**@} end of group USBH_Core_Functions */ +/**@} end of group USBH_Core */ +/**@} end of group APM32_USB_Library */ diff --git a/lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Core/Src/usbh_core.c b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Core/Src/usbh_core.c new file mode 100644 index 0000000000..a5ecf13ac1 --- /dev/null +++ b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Core/Src/usbh_core.c @@ -0,0 +1,1048 @@ +/*! + * @file usbh_core.c + * + * @brief USB host core function + * + * @version V1.0.0 + * + * @date 2023-01-16 + * + * @attention + * + * Copyright (C) 2023 Geehy Semiconductor + * + * You may not use this file except in compliance with the + * GEEHY COPYRIGHT NOTICE (GEEHY SOFTWARE PACKAGE LICENSE). + * + * The program is only for reference, which is distributed in the hope + * that it will be useful and instructional for customers to develop + * their software. Unless required by applicable law or agreed to in + * writing, the program is distributed on an "AS IS" BASIS, WITHOUT + * ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied. + * See the GEEHY SOFTWARE PACKAGE LICENSE for the governing permissions + * and limitations under the License. + */ + +/* Includes */ +#include "usbh_core.h" +#include "usbh_enum.h" + +/** @addtogroup APM32_USB_Library + @{ + */ + +/** @addtogroup USBH_Core + @{ + */ + +/** @defgroup USBH_Core_Functions Functions + @{ + */ + +static USBH_STA_T USBH_IdleHandler(USBH_INFO_T* usbInfo); +static USBH_STA_T USBH_DevAttachedHandler(USBH_INFO_T* usbInfo); +static USBH_STA_T USBH_DevDisconnectHandler(USBH_INFO_T* usbInfo); +static USBH_STA_T USBH_EnumerationHandler(USBH_INFO_T* usbInfo); +static USBH_STA_T USBH_ClassReqHandler(USBH_INFO_T* usbInfo); +static USBH_STA_T USBH_UserInputHandler(USBH_INFO_T* usbInfo); +static USBH_STA_T USBH_SetConfigHandler(USBH_INFO_T* usbInfo); +static USBH_STA_T USBH_SetFeatureHandler(USBH_INFO_T* usbInfo); +static USBH_STA_T USBH_ClassActiveHandler(USBH_INFO_T* usbInfo); +static USBH_STA_T USBH_ClassHandler(USBH_INFO_T* usbInfo); +static USBH_STA_T USBH_SuspendHandler(USBH_INFO_T* usbInfo); +static USBH_STA_T USBH_AbortHandler(USBH_INFO_T* usbInfo); +static void USBH_ClearDevData(USBH_INFO_T* usbInfo); + +/**@} end of group USBH_Core_Functions */ + +/** @defgroup USBH_Core_Structures Structures + @{ + */ + +/* USB host state handler function */ +USBH_CoreHandler_T USBH_CoreHandler[] = +{ + USBH_IdleHandler, /* !< Array number match with USBH_HOST_IDLE enumerate */ + USBH_DevAttachedHandler, + USBH_DevDisconnectHandler, /* !< Array number match with USBH_HOST_DEV_DISCONNECTED enumerate */ + USBH_EnumerationHandler, + USBH_ClassReqHandler, + USBH_UserInputHandler, + USBH_SetConfigHandler, + USBH_SetFeatureHandler, + USBH_ClassActiveHandler, + USBH_ClassHandler, + USBH_SuspendHandler, + USBH_AbortHandler, +}; + +/**@} end of group USBH_Core_Structures*/ + +/** @defgroup USBH_Core_Functions Functions + @{ + */ + +/*! + * @brief Host idle state handler + * + * @param usbInfo : usb handler information + * + * @retval usb host status + */ +static USBH_STA_T USBH_IdleHandler(USBH_INFO_T* usbInfo) +{ + USBH_STA_T usbStatus = USBH_OK; + + USBH_USR_Debug("USBH_IdleHandler"); + + if (usbInfo->devInfo.connectedStatus == ENABLE) + { + USBH_USR_Debug("USB device insert"); + + /* Wait for 200 ms */ + USBH_Delay(200); + + /* Reset usb host port */ + USBH_ResetCallback(usbInfo); + + usbInfo->devInfo.address = USBH_DEVICE_DEFAULT_ADDRESS; + /* Next USB host state */ + usbInfo->hostState = USBH_HOST_DEVICE_ATTACHED; + + usbInfo->timeout = 0; + } + + return usbStatus; +} + +/*! + * @brief Host Attached state handler + * + * @param usbInfo : usb handler information + * + * @retval usb host status + */ +static USBH_STA_T USBH_DevAttachedHandler(USBH_INFO_T* usbInfo) +{ + USBH_STA_T usbStatus = USBH_OK; + + USBH_USR_Debug("USBH_DevAttachedHandler"); + + if (usbInfo->devInfo.portEnable == ENABLE) + { + USBH_USR_LOG("USB Device Reset Completed"); + usbInfo->devInfo.rstCnt = 0; + + /* Notify user device is connected */ + usbInfo->userCallback(usbInfo, USBH_USER_CONNECTION); + + USBH_Delay(120); + + /* Get speed */ + usbInfo->devInfo.speed = USBH_ReadSpeedCallback(usbInfo); + + /* Notify user device speed is detected */ + usbInfo->userCallback(usbInfo, USBH_USER_DETECTED_SPEED); + + usbInfo->ctrl.channelOutNum = USBH_CH_AllocChannel(usbInfo, 0x00); + usbInfo->ctrl.channelInNum = USBH_CH_AllocChannel(usbInfo, 0x80); + + /* Open and config out channel */ + USBH_OpenChannelCallback(usbInfo, usbInfo->ctrl.channelOutNum, + 0x00, usbInfo->devInfo.address, + usbInfo->devInfo.speed, EP_TYPE_CONTROL, + usbInfo->ctrl.channelSize); + + /* Open and config in channel */ + USBH_OpenChannelCallback(usbInfo, usbInfo->ctrl.channelInNum, + 0x80, usbInfo->devInfo.address, + usbInfo->devInfo.speed, EP_TYPE_CONTROL, + usbInfo->ctrl.channelSize); + + /* Next USB host state */ + usbInfo->hostState = USBH_HOST_ENUMERATION; + } + else + { + if (usbInfo->timeout > USBH_DEVICE_RESET_TIMEOUT) + { + usbInfo->devInfo.rstCnt++; + if (usbInfo->devInfo.rstCnt > 5) + { + USBH_USR_LOG("USB Reset Failed. Please unplug the device and reset system"); + /* Next USB host state */ + usbInfo->hostState = USBH_HOST_ABORT; + } + else + { + /* Next USB host state */ + usbInfo->hostState = USBH_HOST_IDLE; + } + } + else + { + usbInfo->timeout++; + USBH_Delay(10); + } + } + + return usbStatus; +} + +/*! + * @brief Host device disconnect state handler + * + * @param usbInfo : usb handler information + * + * @retval usb host status + */ +static USBH_STA_T USBH_DevDisconnectHandler(USBH_INFO_T* usbInfo) +{ + USBH_STA_T usbStatus = USBH_OK; + + USBH_USR_Debug("USBH_DevDisconnectHandler"); + + usbInfo->devInfo.disconnectedStatus = DISABLE; + + /* De-init data and state machine */ + USBH_ClearDevData(usbInfo); + USBH_CH_Clear(usbInfo); + + usbInfo->hostState = USBH_HOST_IDLE; + usbInfo->hostEnumState = USBH_ENUM_IDLE; + usbInfo->xferState = USBH_XFER_START; + /* De-init control state */ + usbInfo->ctrl.state = USBH_CTRL_SETUP; + usbInfo->ctrl.channelSize = USBH_EP0_PACKET_SIZE; + usbInfo->ctrl.errCnt = 0; + usbInfo->timer = 0; + + /* Clear device all connection status */ + usbInfo->devInfo.address = USBH_DEVICE_DEFAULT_ADDRESS; + usbInfo->devInfo.speed = USBH_DEVICE_SPEED_FS; + usbInfo->devInfo.rstCnt = 0; + usbInfo->devInfo.enumCnt = 0; + + /* Re-init usb host for new enumeration */ + if (usbInfo->activeClass != NULL) + { + usbInfo->activeClass->classDeInitHandler(usbInfo); + usbInfo->activeClass = NULL; + } + + /* Notify user */ + usbInfo->userCallback(usbInfo, USBH_USER_DISCONNECTION); + + USBH_USR_Debug("USB device disconnected"); + + if (usbInfo->devInfo.reEnumStatus == ENABLE) + { + usbInfo->devInfo.reEnumStatus = DISABLE; + + USBH_StartCallback(usbInfo); + + /* Add re-enable VBUS interface */ + } + else + { + USBH_StartCallback(usbInfo); + } + + return usbStatus; +} + +/*! + * @brief Host enum state handler + * + * @param usbInfo : usb handler information + * + * @retval usb host status + */ +static USBH_STA_T USBH_EnumerationHandler(USBH_INFO_T* usbInfo) +{ + USBH_STA_T usbStatus = USBH_OK; + uint8_t usbEnumStatus; + + usbEnumStatus = USBH_EnumHandler[usbInfo->hostEnumState](usbInfo); + + if (usbEnumStatus == USBH_OK) + { + USBH_USR_Debug("USB device enumeration OK"); + + usbInfo->userCallback(usbInfo, USBH_USER_ENUMERATION); + + if (usbInfo->devInfo.desc.device.bNumConfigurations != 1) + { + usbInfo->hostState = USBH_HOST_USER_INPUT; + } + else + { + USBH_USR_LOG("USB device has only one configuration"); + usbInfo->hostState = USBH_HOST_SET_CONFIGURATION; + } + } + + return usbStatus; +} + +/*! + * @brief Through user input to go to class + * + * @param usbInfo : usb handler information + * + * @retval usb host status + */ +static USBH_STA_T USBH_UserInputHandler(USBH_INFO_T* usbInfo) +{ + USBH_STA_T usbStatus = USBH_OK; + + USBH_USR_Debug("USBH_UserInputHandler"); + + usbInfo->hostState = USBH_HOST_SET_CONFIGURATION; + + return usbStatus; +} + +/*! + * @brief Host set configuration handler + * + * @param usbInfo : usb handler information + * + * @retval usb host status + */ +static USBH_STA_T USBH_SetConfigHandler(USBH_INFO_T* usbInfo) +{ + USBH_STA_T usbStatus = USBH_OK; + uint8_t setCfgStatus; + + USBH_USR_Debug("USBH_SetConfigHandler"); + + setCfgStatus = USBH_SetConfiguration(usbInfo, \ + (uint16_t)usbInfo->devInfo.desc.configuration.bConfigurationValue); + + if (setCfgStatus == USBH_OK) + { + usbInfo->hostState = USBH_HOST_SET_FEATURE; + USBH_USR_LOG("Set to default configuration"); + } + + return usbStatus; +} + +/*! + * @brief Host set feature handler + * + * @param usbInfo : usb handler information + * + * @retval usb host status + */ +static USBH_STA_T USBH_SetFeatureHandler(USBH_INFO_T* usbInfo) +{ + USBH_STA_T usbStatus = USBH_OK; + uint8_t setFeatureStatus; + uint8_t remoteWakeupStatus; + + USBH_USR_Debug("USBH_SetFeatureHandler"); + + remoteWakeupStatus = usbInfo->devInfo.desc.configuration.bmAttributes & (1 << 5); + + if (remoteWakeupStatus) + { + setFeatureStatus = USBH_SetFeature(usbInfo, USBH_FEATURE_REMOTE_WAKEUP); + + switch (setFeatureStatus) + { + case USBH_OK: + USBH_USR_LOG("USB device set to remote wakeup"); + usbInfo->hostState = USBH_HOST_CLASS_ACTIVE; + break; + + case USBH_ERR_NOT_SUP: + USBH_USR_LOG("USB device is not support remote wakeup"); + usbInfo->hostState = USBH_HOST_CLASS_ACTIVE; + break; + + default: + break; + } + } + else + { + usbInfo->hostState = USBH_HOST_CLASS_ACTIVE; + } + + return usbStatus; +} + +/*! + * @brief Host class active handler + * + * @param usbInfo : usb handler information + * + * @retval usb host status + */ +static USBH_STA_T USBH_ClassActiveHandler(USBH_INFO_T* usbInfo) +{ + USBH_STA_T usbStatus = USBH_OK; + uint8_t classStatus; + uint8_t classInterface; + uint8_t classCode; + uint32_t i; + + USBH_USR_Debug("USBH_ClassActiveHandler"); + + /* multi class support */ + if (usbInfo->classNum != 0) + { + classInterface = USBH_ReadInterfaceClass(usbInfo, 0); + + usbInfo->activeClass = NULL; + + for (i = 0; i < USBH_SUP_CLASS_MAX_NUM; i++) + { + classCode = usbInfo->hostClass[i]->classCode; + + if (classCode == classInterface) + { + usbInfo->activeClass = usbInfo->hostClass[i]; + break; + } + } + + if (usbInfo->activeClass != NULL) + { + classStatus = usbInfo->activeClass->classInitHandler(usbInfo); + + switch (classStatus) + { + case USBH_OK: + /* Next state */ + usbInfo->hostState = USBH_HOST_CLASS_REQ; + break; + + default: + usbInfo->hostState = USBH_HOST_ABORT; + USBH_USR_LOG("Device not support to %s", usbInfo->activeClass->className); + usbInfo->userCallback(usbInfo,USBH_USER_NOT_SUPPORT); + break; + } + } + else + { + usbInfo->hostState = USBH_HOST_ABORT; + USBH_USR_LOG("USB host class is not register for this device"); + usbInfo->userCallback(usbInfo,USBH_USER_NOT_SUPPORT); + } + } + else + { + USBH_USR_LOG("USB host class is not register for this device"); + } + + return usbStatus; +} + +/*! + * @brief Host class request state handler + * + * @param usbInfo : usb handler information + * + * @retval usb host status + */ +static USBH_STA_T USBH_ClassReqHandler(USBH_INFO_T* usbInfo) +{ + USBH_STA_T usbStatus = USBH_OK; + uint8_t classStatus; + + if (usbInfo->activeClass != NULL) + { + classStatus = usbInfo->activeClass->classReqHandler(usbInfo); + + switch (classStatus) + { + case USBH_OK: + usbInfo->hostState = USBH_HOST_CLASS; + break; + + case USBH_FAIL: + usbInfo->hostState = USBH_HOST_ABORT; + USBH_USR_LOG("Device is not response. Please reseat device and reset system"); + break; + + default: + break; + } + + } + else + { + usbInfo->hostState = USBH_HOST_ABORT; + USBH_USR_LOG("USB host class driver is invalid"); + } + + return usbStatus; +} + +/*! + * @brief Host class handler + * + * @param usbInfo : usb handler information + * + * @retval usb host status + */ +static USBH_STA_T USBH_ClassHandler(USBH_INFO_T* usbInfo) +{ + USBH_STA_T usbStatus = USBH_OK; + + if (usbInfo->activeClass != NULL) + { + usbInfo->activeClass->classCoreHandler(usbInfo); + } + + return usbStatus; +} + +/*! + * @brief Host suspend state handler + * + * @param usbInfo : usb handler information + * + * @retval usb host status + */ +static USBH_STA_T USBH_SuspendHandler(USBH_INFO_T* usbInfo) +{ + USBH_STA_T usbStatus = USBH_OK; + + USBH_USR_Debug("USBH_SuspendHandler"); + + return usbStatus; +} + +/*! + * @brief Host abort state handler + * + * @param usbInfo : usb handler information + * + * @retval usb host status + */ +static USBH_STA_T USBH_AbortHandler(USBH_INFO_T* usbInfo) +{ + USBH_STA_T usbStatus = USBH_OK; + + USBH_USR_Debug("USBH_AbortHandler"); + + return usbStatus; +} + +/*! + * @brief Clear all of the device data buffer. + * + * @param usbInfo : usb handler information + * + * @retval None + */ +static void USBH_ClearDevData(USBH_INFO_T* usbInfo) +{ + uint32_t i = 0; + + for (i = 0; i < USBH_DATA_BUF_MAX_NUM; i++) + { + usbInfo->devInfo.data[i] = 0; + } +} + +/*! + * @brief USB host connection event + * + * @param usbInfo : usb handler information + * + * @retval None + */ +USBH_STA_T USBH_Connect(USBH_INFO_T* usbInfo) +{ + USBH_STA_T usbStatus = USBH_OK; + + usbInfo->devInfo.connectedStatus = ENABLE; + usbInfo->devInfo.reEnumStatus = DISABLE; + usbInfo->devInfo.disconnectedStatus = DISABLE; + + return usbStatus; +} + +/*! + * @brief USB host disconnection event + * + * @param usbInfo : usb handler information + * + * @retval None + */ +USBH_STA_T USBH_Disconnect(USBH_INFO_T* usbInfo) +{ + USBH_STA_T usbStatus = USBH_OK; + + usbInfo->devInfo.connectedStatus = DISABLE; + usbInfo->devInfo.portEnable = DISABLE; + usbInfo->devInfo.disconnectedStatus = ENABLE; + + /* USB OTG stop host callback */ + USBH_StopHostCallback(usbInfo); + + /* Free control channel */ + USBH_CH_FreeChannel(usbInfo, usbInfo->ctrl.channelInNum); + USBH_CH_FreeChannel(usbInfo, usbInfo->ctrl.channelOutNum); + + return usbStatus; +} + +/*! + * @brief USB host port enable event + * + * @param usbInfo : usb handler information + * + * @retval None + */ +USBH_STA_T USBH_PortEnable(USBH_INFO_T* usbInfo) +{ + USBH_STA_T usbStatus = USBH_OK; + + usbInfo->devInfo.portEnable = ENABLE; + + return usbStatus; +} + +/*! + * @brief USB host port disable event + * + * @param usbInfo : usb handler information + * + * @retval None + */ +USBH_STA_T USBH_PortDisable(USBH_INFO_T* usbInfo) +{ + USBH_STA_T usbStatus = USBH_OK; + + usbInfo->devInfo.portEnable = DISABLE; + + return usbStatus; +} + +/*! + * @brief USB host SOF handler + * + * @param usbInfo : usb handler information + * + * @retval None + */ +static void USBH_HandleSOF(USBH_INFO_T* usbInfo) +{ + if ((usbInfo->hostState == USBH_HOST_CLASS) && (usbInfo->activeClass != NULL)) + { + usbInfo->activeClass->classSofHandler(usbInfo); + } +} + +/*! + * @brief USB host configure timer + * + * @param usbInfo : usb handler information + * + * @param tick : time tick + * + * @retval None + */ +void USBH_ConfigTimer(USBH_INFO_T* usbInfo, uint32_t tick) +{ + usbInfo->timer = tick; +} + +/*! + * @brief USB host increase timer + * + * @param usbInfo : usb handler information + * + * @retval None + */ +void USBH_IncTimer(USBH_INFO_T* usbInfo) +{ + usbInfo->timer++; + USBH_HandleSOF(usbInfo); +} + +/*! + * @brief USB host core init + * + * @param usbInfo : usb handler information + * + * @param usbHostSpeed + * + * @param usbHostClass + * + * @param userCallback + * + * @retval usb host status + */ +USBH_STA_T USBH_Init(USBH_INFO_T* usbInfo, USBH_SPEED_T usbHostSpeed, USBH_CLASS_T* usbHostClass, + void (*userCallbackFunc)(struct _USBH_INFO_T*, uint8_t)) +{ + USBH_STA_T usbStatus = USBH_OK; + + /* Set USB host speed */ + usbInfo->hostSpeed = usbHostSpeed; + + /* De-init data and state machine */ + USBH_ClearDevData(usbInfo); + USBH_CH_Clear(usbInfo); + + usbInfo->hostState = USBH_HOST_IDLE; + usbInfo->hostEnumState = USBH_ENUM_IDLE; + usbInfo->xferState = USBH_XFER_START; + /* De-init control state */ + usbInfo->ctrl.state = USBH_CTRL_SETUP; + usbInfo->ctrl.channelSize = USBH_EP0_PACKET_SIZE; + usbInfo->ctrl.errCnt = 0; + + /* Clear device all connection status */ + usbInfo->devInfo.address = USBH_DEVICE_DEFAULT_ADDRESS; + usbInfo->devInfo.speed = USBH_DEVICE_SPEED_FS; + usbInfo->devInfo.portEnable = DISABLE; + usbInfo->devInfo.disconnectedStatus = DISABLE; + usbInfo->devInfo.connectedStatus = DISABLE; + usbInfo->devInfo.reEnumStatus = DISABLE; + usbInfo->devInfo.rstCnt = 0; + usbInfo->devInfo.enumCnt = 0; + usbInfo->timer = 0; + + /* Register user application */ + usbInfo->userCallback = userCallbackFunc; + + /* Register class function */ + if (usbInfo->classNum < USBH_SUP_CLASS_MAX_NUM) + { + usbInfo->hostClass[usbInfo->classNum++] = usbHostClass; + } + + /* Init USB hardware */ + USBH_HardwareInit(usbInfo); + + return usbStatus; +} + +/*! + * @brief USB device core de-init + * + * @param usbInfo : usb handler information + * + * @retval usb host status + */ +USBH_STA_T USBH_DeInit(USBH_INFO_T* usbInfo) +{ + USBH_STA_T usbStatus = USBH_OK; + + /* De-init data and state machine */ + USBH_ClearDevData(usbInfo); + USBH_CH_Clear(usbInfo); + + usbInfo->hostState = USBH_HOST_IDLE; + usbInfo->hostEnumState = USBH_ENUM_IDLE; + usbInfo->xferState = USBH_XFER_START; + /* De-init control state */ + usbInfo->ctrl.state = USBH_CTRL_SETUP; + usbInfo->ctrl.channelSize = USBH_EP0_PACKET_SIZE; + usbInfo->ctrl.errCnt = 0; + + /* Clear device all connection status */ + usbInfo->devInfo.address = USBH_DEVICE_DEFAULT_ADDRESS; + usbInfo->devInfo.speed = USBH_DEVICE_SPEED_FS; + usbInfo->devInfo.portEnable = DISABLE; + usbInfo->devInfo.disconnectedStatus = DISABLE; + usbInfo->devInfo.connectedStatus = DISABLE; + usbInfo->devInfo.reEnumStatus = DISABLE; + usbInfo->devInfo.rstCnt = 0; + usbInfo->devInfo.enumCnt = 0; + usbInfo->timer = 0; + + for(uint8_t i = 0; i < USBH_SUP_CLASS_MAX_NUM; i++) + { + if(usbInfo->hostClass[0] != NULL && usbInfo->activeClass != NULL && \ + usbInfo->activeClass->classData != NULL ) + { + usbInfo->hostClass[0]->classDeInitHandler(usbInfo); + } + } + + if(usbInfo->dataPoint != NULL) + { + USBH_StopHostCallback(usbInfo); + } + + USBH_HardwareReset(usbInfo); + + return usbStatus; +} + +/*! + * @brief Host register class + * + * @param usbInfo : usb handler information + * + * @param usbHostClass : host class + * + * @retval usb host status + */ +USBH_STA_T USBH_RegisterClass(USBH_INFO_T* usbInfo, USBH_CLASS_T* usbHostClass) +{ + USBH_STA_T usbStatus = USBH_OK; + + if (usbHostClass != NULL) + { + /* Register class function */ + if (usbInfo->classNum < USBH_SUP_CLASS_MAX_NUM) + { + usbInfo->hostClass[usbInfo->classNum++] = usbHostClass; + + usbStatus = USBH_OK; + } + else + { + usbStatus = USBH_FAIL; + } + } + else + { + usbStatus = USBH_FAIL; + } + + return usbStatus; +} + +/*! + * @brief Host state machine polling Process + * + * @param usbInfo : usb handler information + * + * @retval usb host status + */ +USBH_STA_T USBH_PollingProcess(USBH_INFO_T* usbInfo) +{ + USBH_STA_T usbStatus = USBH_OK; + + /* Device disconnect */ + if (usbInfo->devInfo.disconnectedStatus == ENABLE) + { + usbInfo->hostState = USBH_HOST_DEVICE_DISCONNECTED; + } + + usbStatus = USBH_CoreHandler[usbInfo->hostState](usbInfo); + + return usbStatus; +} + +/*! + * @brief USB stop host event callback function + * + * @param usbInfo : usb handler information + * + * @retval None + */ +__weak void USBH_StopHostCallback(USBH_INFO_T* usbInfo) +{ + /* callback interface */ +} + +/*! + * @brief USB host start event callback function + * + * @param usbInfo : usb handler information + * + * @retval None + */ +__weak void USBH_StartCallback(USBH_INFO_T* usbInfo) +{ + /* callback interface */ +} + +/*! + * @brief USB host stop event callback function + * + * @param usbInfo : usb handler information + * + * @retval None + */ +__weak void USBH_StopCallback(USBH_INFO_T* usbInfo) +{ + /* callback interface */ +} + +/*! + * @brief USB host reset event callback function + * + * @param usbInfo : usb handler information + * + * @retval None + */ +__weak void USBH_ResetCallback(USBH_INFO_T* usbInfo) +{ + /* callback interface */ +} + +/*! + * @brief USB host read speed event callback function + * + * @param usbInfo : usb handler information + * + * @retval speed + */ +__weak uint8_t USBH_ReadSpeedCallback(USBH_INFO_T* usbInfo) +{ + /* callback interface */ + return 0; +} + +/*! + * @brief USB host config the channel to transfer event callback function + * + * @param usbInfo : usb handler information + * + * @param channelNum : channel numer + * + * @param endPointNum : end point number + * + * @param devAddr : USB device address + * + * @param devSpeed : USB device speed + * + * @param epType : end point type + * + * @param packetMaxSize : max size of packet + * + * @retval None + */ +__weak void USBH_OpenChannelCallback(USBH_INFO_T* usbInfo, uint8_t channelNum, \ + uint8_t endPointNum, uint8_t devAddr, \ + uint8_t devSpeed, uint8_t epType, uint16_t packetMaxSize) +{ + /* callback interface */ +} + +/*! + * @brief USB submit URB event callback function + * + * @param usbInfo : usb handler information + * + * @param chNum : channel number + * + * @param dir : channel direction + * + * @param epType : endpoint type + * + * @param tokenType : tokenType + * + * @param buffer : URB data + * + * @param length : length of URB data + * + * @param pingStatus : ping status + * + * @retval None + */ +__weak void USBH_UrbSubmitCallback(USBH_INFO_T* usbInfo, uint8_t chNum, uint8_t dir, \ + uint8_t epType, uint8_t tokenType, uint8_t* buffer, \ + uint16_t length, uint8_t pingStatus) +{ + /* callback interface */ +} + +/*! + * @brief USB host read URB status event callback function + * + * @param usbInfo : usb handler information + * + * @param channelNum : channel number + * + * @retval URB status + */ +__weak uint8_t USBH_ReadUrbStatusCallback(USBH_INFO_T* usbInfo, uint8_t channelNum) +{ + /* callback interface */ + return 0; +} + +/*! + * @brief USB host configure data PID callback function + * + * @param usbInfo : usb handler information + * + * @param channelNum: channel number + * + * @param dataPid: data PID + * + * @retval None + */ +__weak void USBH_ConfigDataPidCallback(USBH_INFO_T* usbInfo, uint8_t channelNum, uint8_t dataPid) +{ + /* callback interface */ +} + +/*! + * @brief USB host close channel callback function + * + * @param usbInfo : usb handler information + * + * @param channelNum: channel number + * + * @retval None + */ +__weak void USBH_CloseChannelCallback(USBH_INFO_T* usbInfo, uint8_t channelNum) +{ + /* callback interface */ +} + +/*! + * @brief USB host read size of last xfer callback function + * + * @param usbInfo : usb handler information + * + * @param channelNum: channel number + * + * @retval xfer size + */ +__weak uint32_t USBH_ReadLastXferSizeCallback(USBH_INFO_T* usbInfo, uint8_t channelNum) +{ + /* callback interface */ + return 0; +} + +/*! + * @brief USB host configure current toggle of channel callback function + * + * @param usbInfo : usb handler information + * + * @param channelNum: channel number + * + * @param toggle: toggle + * + * @retval xfer size + */ +__weak void USBH_ConfigToggleCallback(USBH_INFO_T* usbInfo, uint8_t channelNum, uint8_t toggle) +{ + /* callback interface */ +} + +/*! + * @brief USB host read current toggle of channel callback function + * + * @param usbInfo : usb handler information + * + * @param channelNum: channel number + * + * @retval xfer size + */ +__weak uint8_t USBH_ReadToggleCallback(USBH_INFO_T* usbInfo, uint8_t channelNum) +{ + /* callback interface */ + return 0; +} + +/**@} end of group USBH_Core_Functions */ +/**@} end of group USBH_Core */ +/**@} end of group APM32_USB_Library */ diff --git a/lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Core/Src/usbh_dataXfer.c b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Core/Src/usbh_dataXfer.c new file mode 100644 index 0000000000..81831f108e --- /dev/null +++ b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Core/Src/usbh_dataXfer.c @@ -0,0 +1,808 @@ +/*! + * @file usbh_dataXfer.c + * + * @brief USB host input and output hander function + * + * @version V1.0.0 + * + * @date 2023-01-16 + * + * @attention + * + * Copyright (C) 2023 Geehy Semiconductor + * + * You may not use this file except in compliance with the + * GEEHY COPYRIGHT NOTICE (GEEHY SOFTWARE PACKAGE LICENSE). + * + * The program is only for reference, which is distributed in the hope + * that it will be useful and instructional for customers to develop + * their software. Unless required by applicable law or agreed to in + * writing, the program is distributed on an "AS IS" BASIS, WITHOUT + * ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied. + * See the GEEHY SOFTWARE PACKAGE LICENSE for the governing permissions + * and limitations under the License. + */ + +/* Includes */ +#include "usbh_dataXfer.h" +#include "usbh_core.h" +#include "usbh_stdReq.h" +#include "usbh_channel.h" + +/** @addtogroup APM32_USB_Library + @{ + */ + +/** @addtogroup USBH_Core + @{ + */ + +/** @defgroup USBH_Core_Functions Functions + @{ + */ + +static USBH_STA_T USBH_CtrlXferIdle(USBH_INFO_T* usbInfo); +static USBH_STA_T USBH_CtrlXferSetup(USBH_INFO_T* usbInfo); +static USBH_STA_T USBH_CtrlXferSetupWait(USBH_INFO_T* usbInfo); +static USBH_STA_T USBH_CtrlXferInData(USBH_INFO_T* usbInfo); +static USBH_STA_T USBH_CtrlXferInDataWait(USBH_INFO_T* usbInfo); +static USBH_STA_T USBH_CtrlXferOutData(USBH_INFO_T* usbInfo); +static USBH_STA_T USBH_CtrlXferOutDataWait(USBH_INFO_T* usbInfo); +static USBH_STA_T USBH_CtrlXferInSta(USBH_INFO_T* usbInfo); +static USBH_STA_T USBH_CtrlXferInStaWait(USBH_INFO_T* usbInfo); +static USBH_STA_T USBH_CtrlXferOutSta(USBH_INFO_T* usbInfo); +static USBH_STA_T USBH_CtrlXferOutStaWait(USBH_INFO_T* usbInfo); +static USBH_STA_T USBH_CtrlXferError(USBH_INFO_T* usbInfo); +static USBH_STA_T USBH_CtrlXferStall(USBH_INFO_T* usbInfo); +static USBH_STA_T USBH_CtrlXferOk(USBH_INFO_T* usbInfo); + +/**@} end of group USBH_Core_Functions */ + +/** @defgroup USBH_Core_Structures Structures + @{ + */ + +/* USB control transfer state handler function */ +USBH_CtrlStateHandler_T USBH_CtrlStateHandler[] = +{ + USBH_CtrlXferIdle, + USBH_CtrlXferSetup, + USBH_CtrlXferSetupWait, + USBH_CtrlXferInData, + USBH_CtrlXferInDataWait, + USBH_CtrlXferOutData, + USBH_CtrlXferOutDataWait, + USBH_CtrlXferInSta, + USBH_CtrlXferInStaWait, + USBH_CtrlXferOutSta, + USBH_CtrlXferOutStaWait, + USBH_CtrlXferError, + USBH_CtrlXferStall, + USBH_CtrlXferOk, +}; + +/**@} end of group USBH_Core_Structures*/ + +/** @defgroup USBH_Core_Functions Functions + @{ + */ + +/*! + * @brief Control transfer send data request + * + * @param usbInfo : usb handler information + * + * @param channelNum : channel number + * + * @param buffer : buffer to be receive data + * + * @param length : transfer length + * + * @param pingStatus : ping status + * + * @retval usb host status + */ +static USBH_STA_T USBH_CtrlSendDataReq(USBH_INFO_T* usbInfo, uint8_t channelNum, \ + uint8_t* buffer, uint16_t length, \ + uint8_t pingStatus) +{ + USBH_STA_T usbStatus = USBH_OK; + + if ((usbInfo->devInfo.speed != USBH_DEVICE_SPEED_HS) && (pingStatus == ENABLE)) + { + pingStatus = DISABLE; + } + + /* Callback USB URB submit */ + USBH_UrbSubmitCallback(usbInfo, channelNum, \ + EP_DIR_OUT, \ + EP_TYPE_CONTROL, \ + USBH_PID_DATA, \ + (uint8_t*)buffer, \ + length, \ + pingStatus); + + return usbStatus; +} + +/*! + * @brief Control transfer receive data request + * + * @param usbInfo : usb handler information + * + * @param channelNum : channel number + * + * @param buffer : buffer to be receive data + * + * @param length : transfer length + * + * @retval usb host status + */ +static USBH_STA_T USBH_CtrlReceiveDataReq(USBH_INFO_T* usbInfo, uint8_t channelNum, \ + uint8_t* buffer, uint16_t length) +{ + USBH_STA_T usbStatus = USBH_OK; + + /* Callback USB URB submit */ + USBH_UrbSubmitCallback(usbInfo, channelNum, \ + EP_DIR_IN, \ + EP_TYPE_CONTROL, \ + USBH_PID_DATA, \ + (uint8_t*)buffer, \ + length, \ + 0); + + return usbStatus; +} + +/*! + * @brief Start control setup transfer + * + * @param usbInfo : usb handler information + * + * @param channelNum : channel number + * + * @param buffer : buffer to be sent + * + * @retval usb host status + */ +static USBH_STA_T USBH_CtrlSetupReq(USBH_INFO_T* usbInfo, uint8_t channelNum, \ + USBH_REQ_DATA_T* buffer) +{ + USBH_STA_T usbStatus = USBH_OK; + + /* Callback USB URB submit */ + USBH_UrbSubmitCallback(usbInfo, channelNum, \ + EP_DIR_OUT, \ + EP_TYPE_CONTROL, \ + USBH_PID_SETUP, \ + (uint8_t*)buffer, \ + USBH_SETUP_PACKET_SIZE, \ + 0); + + return usbStatus; +} + +/*! + * @brief Handle control idle state + * + * @param usbInfo : usb handler information + * + * @retval usb host status + */ +static USBH_STA_T USBH_CtrlXferIdle(USBH_INFO_T* usbInfo) +{ + USBH_STA_T usbStatus = USBH_OK; + + usbInfo->ctrl.state = USBH_CTRL_IDLE; + + USBH_USR_Debug("USBH_CtrlXferIdle"); + + return usbStatus; +} + +/*! + * @brief Handle control setup transfer + * + * @param usbInfo : usb handler information + * + * @retval usb host status + */ +static USBH_STA_T USBH_CtrlXferSetup(USBH_INFO_T* usbInfo) +{ + USBH_STA_T usbStatus = USBH_BUSY; + + USBH_USR_Debug("USBH_CtrlXferSetup"); + + /* Sent setup packet */ + USBH_CtrlSetupReq(usbInfo, usbInfo->ctrl.channelOutNum, &usbInfo->ctrl.reqData); + + usbInfo->ctrl.state = USBH_CTRL_SETUP_WAIT; + + return usbStatus; +} + +/*! + * @brief Handle control setup wait URB status transfer + * + * @param usbInfo : usb handler information + * + * @retval usb host status + */ +static USBH_STA_T USBH_CtrlXferSetupWait(USBH_INFO_T* usbInfo) +{ + USBH_STA_T usbStatus = USBH_BUSY; + uint8_t usbUrbStatus = USB_URB_IDLE; + uint16_t reqLenghTemp; + uint8_t reqDirTemp; + //static uint32_t timeout = 0; + + USBH_USR_Debug("USBH_CtrlXferSetupWait"); + + /* Read USB URB status */ + usbUrbStatus = USBH_ReadUrbStatusCallback(usbInfo, usbInfo->ctrl.channelOutNum); + + switch (usbUrbStatus) + { + case USB_URB_OK: + //timeout = 0; + reqDirTemp = usbInfo->ctrl.reqData.DATA_FIELD.bmRequestType.REQ_TYPE_B.dir; + reqLenghTemp = usbInfo->ctrl.reqData.DATA_FIELD.wLength[1] << 8 | \ + usbInfo->ctrl.reqData.DATA_FIELD.wLength[0]; + + /* Goto DATA state */ + if (reqLenghTemp != 0) + { + if (reqDirTemp == USB_REQ_DIR_OUT) + { + usbInfo->ctrl.state = USBH_CTRL_DATA_OUT; + } + else + { + usbInfo->ctrl.state = USBH_CTRL_DATA_IN; + } + } + else + { + if (reqDirTemp == USB_REQ_DIR_OUT) + { + usbInfo->ctrl.state = USBH_CTRL_STA_IN; + } + else + { + usbInfo->ctrl.state = USBH_CTRL_STA_OUT; + } + } + break; + + case USB_URB_ERROR: + case USB_URB_NOREADY: + //timeout = 0; + usbInfo->ctrl.state = USBH_CTRL_ERROR; + break; + + default: + //timeout++; + break; + } + + /*if(timeout >= 500) + { + timeout = 0; + + usbInfo->ctrl.state = USBH_CTRL_ERROR; + }*/ + + return usbStatus; +} + +/*! + * @brief Handle control IN state + * + * @param usbInfo : usb handler information + * + * @retval usb host status + */ +static USBH_STA_T USBH_CtrlXferInData(USBH_INFO_T* usbInfo) +{ + USBH_STA_T usbStatus = USBH_BUSY; + + USBH_USR_Debug("USBH_CtrlXferInData"); + + USBH_CtrlReceiveDataReq(usbInfo, usbInfo->ctrl.channelInNum, \ + usbInfo->ctrl.buffer, usbInfo->ctrl.length); + + usbInfo->ctrl.state = USBH_CTRL_DATA_IN_WAIT; + + return usbStatus; +} + +/*! + * @brief Handle control IN wait URB status state + * + * @param usbInfo : usb handler information + * + * @retval usb host status + */ +static USBH_STA_T USBH_CtrlXferInDataWait(USBH_INFO_T* usbInfo) +{ + USBH_STA_T usbStatus = USBH_BUSY; + uint8_t usbUrbStatus = USB_URB_IDLE; + + USBH_USR_Debug("USBH_CtrlXferInDataWait"); + + /* Read USB URB status */ + usbUrbStatus = USBH_ReadUrbStatusCallback(usbInfo, usbInfo->ctrl.channelInNum); + + switch (usbUrbStatus) + { + case USB_URB_OK: + usbInfo->ctrl.state = USBH_CTRL_STA_OUT; + break; + + case USB_URB_STALL: + usbStatus = USBH_ERR_NOT_SUP; + break; + + case USB_URB_ERROR: + usbInfo->ctrl.state = USBH_CTRL_ERROR; + break; + + default: + break; + } + + return usbStatus; +} + +/*! + * @brief Handle control OUT state + * + * @param usbInfo : usb handler information + * + * @retval usb host status + */ +static USBH_STA_T USBH_CtrlXferOutData(USBH_INFO_T* usbInfo) +{ + USBH_STA_T usbStatus = USBH_BUSY; + + USBH_USR_Debug("USBH_CtrlXferOutData"); + + USBH_CtrlSendDataReq(usbInfo, usbInfo->ctrl.channelOutNum, \ + usbInfo->ctrl.buffer, usbInfo->ctrl.length, \ + ENABLE); + + usbInfo->ctrl.state = USBH_CTRL_DATA_OUT_WAIT; + + return usbStatus; +} + + +/*! + * @brief Handle control OUT wait URB status state + * + * @param usbInfo : usb handler information + * + * @retval usb host status + */ +static USBH_STA_T USBH_CtrlXferOutDataWait(USBH_INFO_T* usbInfo) +{ + USBH_STA_T usbStatus = USBH_BUSY; + uint8_t usbUrbStatus = USB_URB_IDLE; + + USBH_USR_Debug("USBH_CtrlXferOutDataWait"); + + /* Read USB URB status */ + usbUrbStatus = USBH_ReadUrbStatusCallback(usbInfo, usbInfo->ctrl.channelOutNum); + + switch (usbUrbStatus) + { + case USB_URB_OK: + usbInfo->ctrl.state = USBH_CTRL_STA_IN; + break; + + case USB_URB_STALL: + usbInfo->ctrl.state = USBH_CTRL_STALL; + usbStatus = USBH_ERR_NOT_SUP; + break; + + case USB_URB_NOREADY: + usbInfo->ctrl.state = USBH_CTRL_DATA_OUT; + break; + + case USB_URB_ERROR: + usbInfo->ctrl.state = USBH_CTRL_ERROR; + usbStatus = USBH_FAIL; + break; + + default: + break; + } + + return usbStatus; +} + +/*! + * @brief Handle control STATUS IN state + * + * @param usbInfo : usb handler information + * + * @retval usb host status + */ +static USBH_STA_T USBH_CtrlXferInSta(USBH_INFO_T* usbInfo) +{ + USBH_STA_T usbStatus = USBH_BUSY; + + USBH_USR_Debug("USBH_CtrlXferInSta"); + + /* Send 0 byte out packet */ + USBH_CtrlReceiveDataReq(usbInfo, usbInfo->ctrl.channelInNum, \ + NULL, 0); + + usbInfo->ctrl.state = USBH_CTRL_STA_IN_WAIT; + + return usbStatus; +} + +/*! + * @brief Handle control STATUS IN wait state + * + * @param usbInfo : usb handler information + * + * @retval usb host status + */ +static USBH_STA_T USBH_CtrlXferInStaWait(USBH_INFO_T* usbInfo) +{ + USBH_STA_T usbStatus = USBH_BUSY; + uint8_t usbUrbStatus = USB_URB_IDLE; + + USBH_USR_Debug("USBH_CtrlXferInStaWait"); + + /* Read USB URB status */ + usbUrbStatus = USBH_ReadUrbStatusCallback(usbInfo, usbInfo->ctrl.channelInNum); + + switch (usbUrbStatus) + { + case USB_URB_OK: + usbInfo->ctrl.state = USBH_CTRL_OK; + usbStatus = USBH_OK; + break; + + case USB_URB_STALL: + usbStatus = USBH_ERR_NOT_SUP; + break; + + case USB_URB_ERROR: + usbInfo->ctrl.state = USBH_CTRL_ERROR; + break; + + default: + break; + } + + return usbStatus; +} + +/*! + * @brief Handle control STATUS OUT state + * + * @param usbInfo : usb handler information + * + * @retval usb host status + */ +static USBH_STA_T USBH_CtrlXferOutSta(USBH_INFO_T* usbInfo) +{ + USBH_STA_T usbStatus = USBH_BUSY; + + USBH_USR_Debug("USBH_CtrlXferOutSta"); + + /* Send 0 byte out packet */ + USBH_CtrlSendDataReq(usbInfo, usbInfo->ctrl.channelOutNum, \ + NULL, 0, ENABLE); + + usbInfo->ctrl.state = USBH_CTRL_STA_OUT_WAIT; + + return usbStatus; +} + +/*! + * @brief Handle control STATUS OUT wait state + * + * @param usbInfo : usb handler information + * + * @retval usb host status + */ +static USBH_STA_T USBH_CtrlXferOutStaWait(USBH_INFO_T* usbInfo) +{ + USBH_STA_T usbStatus = USBH_BUSY; + uint8_t usbUrbStatus = USB_URB_IDLE; + + USBH_USR_Debug("USBH_CtrlXferOutStaWait"); + + /* Read USB URB status */ + usbUrbStatus = USBH_ReadUrbStatusCallback(usbInfo, usbInfo->ctrl.channelOutNum); + + switch (usbUrbStatus) + { + case USB_URB_OK: + usbInfo->ctrl.state = USBH_CTRL_OK; + usbStatus = USBH_OK; + break; + + case USB_URB_NOREADY: + usbInfo->ctrl.state = USBH_CTRL_STA_OUT; + break; + + case USB_URB_ERROR: + usbInfo->ctrl.state = USBH_CTRL_ERROR; + break; + + default: + break; + } + + return usbStatus; +} + +/*! + * @brief Handle control ERROR state + * + * @param usbInfo : usb handler information + * + * @retval usb host status + */ +static USBH_STA_T USBH_CtrlXferError(USBH_INFO_T* usbInfo) +{ + USBH_STA_T usbStatus = USBH_BUSY; + + USBH_USR_Debug("USBH_CtrlXferError"); + + usbInfo->ctrl.errCnt++; + + if (usbInfo->ctrl.errCnt > 2) + { + /* Notify user */ + usbInfo->userCallback(usbInfo, USBH_USER_ERROR); + usbInfo->ctrl.errCnt = 0; + USBH_USR_LOG("Control error: Device No Response"); + + USBH_CH_FreeChannel(usbInfo, usbInfo->ctrl.channelInNum); + USBH_CH_FreeChannel(usbInfo, usbInfo->ctrl.channelOutNum); + + usbInfo->hostState = USBH_HOST_IDLE; + usbStatus = USBH_FAIL; +// usbStatus = USBH_ERR_NOT_SUP; + } + else + { + /* Retry again */ + usbInfo->ctrl.state = USBH_CTRL_SETUP; + usbInfo->xferState = USBH_XFER_START; + } + + return usbStatus; +} + +/*! + * @brief Handle control STALL state + * + * @param usbInfo : usb handler information + * + * @retval usb host status + */ +static USBH_STA_T USBH_CtrlXferStall(USBH_INFO_T* usbInfo) +{ + USBH_STA_T usbStatus = USBH_ERR_NOT_SUP; + + USBH_USR_Debug("USBH_CtrlXferStall"); + + return usbStatus; +} + +/*! + * @brief Handle control OK state + * + * @param usbInfo : usb handler information + * + * @retval usb host status + */ +static USBH_STA_T USBH_CtrlXferOk(USBH_INFO_T* usbInfo) +{ + USBH_STA_T usbStatus = USBH_OK; + + USBH_USR_Debug("USBH_CtrlXferOk"); + + return usbStatus; +} + +/*! + * @brief Bulk transfer send data request + * + * @param usbInfo : usb handler information + * + * @param channelNum : channel number + * + * @param buffer : buffer to be receive data + * + * @param length : transfer length + * + * @param pingStatus : ping status + * + * @retval usb host status + */ +USBH_STA_T USBH_BulkSendDataReq(USBH_INFO_T* usbInfo, uint8_t channelNum, \ + uint8_t* buffer, uint16_t length, \ + uint8_t pingStatus) +{ + USBH_STA_T usbStatus = USBH_OK; + + if ((usbInfo->devInfo.speed != USBH_DEVICE_SPEED_HS) && (pingStatus == ENABLE)) + { + pingStatus = DISABLE; + } + + /* Callback USB URB submit */ + USBH_UrbSubmitCallback(usbInfo, channelNum, \ + EP_DIR_OUT, \ + EP_TYPE_BULK, \ + USBH_PID_DATA, \ + (uint8_t*)buffer, \ + length, \ + pingStatus); + + return usbStatus; +} + +/*! + * @brief Bulk transfer receive data request + * + * @param usbInfo : usb handler information + * + * @param channelNum : channel number + * + * @param buffer : buffer to be receive data + * + * @param length : transfer length + * + * @retval usb host status + */ +USBH_STA_T USBH_BulkReceiveDataReq(USBH_INFO_T* usbInfo, uint8_t channelNum, \ + uint8_t* buffer, uint16_t length) +{ + USBH_STA_T usbStatus = USBH_OK; + + /* Callback USB URB submit */ + USBH_UrbSubmitCallback(usbInfo, channelNum, \ + EP_DIR_IN, \ + EP_TYPE_BULK, \ + USBH_PID_DATA, \ + buffer, \ + length, \ + 0); + + return usbStatus; +} + +/*! + * @brief Interrupt transfer receive data request + * + * @param usbInfo : usb handler information + * + * @param channelNum : channel number + * + * @param buffer : buffer to be receive data + * + * @param length : transfer length + * + * @retval usb host status + */ +USBH_STA_T USBH_IntReceiveDataReq(USBH_INFO_T* usbInfo, uint8_t channelNum, \ + uint8_t* buffer, uint8_t length) +{ + USBH_STA_T usbStatus = USBH_OK; + + /* Callback USB URB submit */ + USBH_UrbSubmitCallback(usbInfo, channelNum, \ + EP_DIR_IN, \ + EP_TYPE_INTERRUPT, \ + USBH_PID_DATA, \ + buffer, \ + length, \ + 0); + + return usbStatus; +} + +/*! + * @brief Interrupt transfer send data request + * + * @param usbInfo : usb handler information + * + * @param channelNum : channel number + * + * @param buffer : buffer to be receive data + * + * @param length : transfer length + * + * @retval usb host status + */ +USBH_STA_T USBH_IntSendDataReq(USBH_INFO_T* usbInfo, uint8_t channelNum, \ + uint8_t* buffer, uint8_t length) +{ + USBH_STA_T usbStatus = USBH_OK; + + /* Callback USB URB submit */ + USBH_UrbSubmitCallback(usbInfo, channelNum, \ + EP_DIR_OUT, \ + EP_TYPE_INTERRUPT, \ + USBH_PID_DATA, \ + buffer, \ + length, \ + 0); + + return usbStatus; +} + +/*! + * @brief Isochronous transfer receive data request + * + * @param usbInfo : usb handler information + * + * @param channelNum : channel number + * + * @param buffer : buffer to be receive data + * + * @param length : transfer length + * + * @retval usb host status + */ +USBH_STA_T USBH_IsoReceiveDataReq(USBH_INFO_T* usbInfo, uint8_t channelNum, \ + uint8_t* buffer, uint8_t length) +{ + USBH_STA_T usbStatus = USBH_OK; + + /* Callback USB URB submit */ + USBH_UrbSubmitCallback(usbInfo, channelNum, \ + EP_DIR_IN, \ + EP_TYPE_ISO, \ + USBH_PID_DATA, \ + buffer, \ + length, \ + 0); + + return usbStatus; +} + +/*! + * @brief Isochronous transfer send data request + * + * @param usbInfo : usb handler information + * + * @param channelNum : channel number + * + * @param buffer : buffer to be receive data + * + * @param length : transfer length + * + * @retval usb host status + */ +USBH_STA_T USBH_IsoSendDataReq(USBH_INFO_T* usbInfo, uint8_t channelNum, \ + uint8_t* buffer, uint8_t length) +{ + USBH_STA_T usbStatus = USBH_OK; + + /* Callback USB URB submit */ + USBH_UrbSubmitCallback(usbInfo, channelNum, \ + EP_DIR_OUT, \ + EP_TYPE_ISO, \ + USBH_PID_DATA, \ + buffer, \ + length, \ + 0); + + return usbStatus; +} + +/**@} end of group USBH_Core_Functions */ +/**@} end of group USBH_Core */ +/**@} end of group APM32_USB_Library */ diff --git a/lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Core/Src/usbh_enum.c b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Core/Src/usbh_enum.c new file mode 100644 index 0000000000..d842b570e3 --- /dev/null +++ b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Core/Src/usbh_enum.c @@ -0,0 +1,495 @@ +/*! + * @file usbh_enum.c + * + * @brief USB host enum hander function + * + * @version V1.0.0 + * + * @date 2023-01-16 + * + * @attention + * + * Copyright (C) 2023 Geehy Semiconductor + * + * You may not use this file except in compliance with the + * GEEHY COPYRIGHT NOTICE (GEEHY SOFTWARE PACKAGE LICENSE). + * + * The program is only for reference, which is distributed in the hope + * that it will be useful and instructional for customers to develop + * their software. Unless required by applicable law or agreed to in + * writing, the program is distributed on an "AS IS" BASIS, WITHOUT + * ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied. + * See the GEEHY SOFTWARE PACKAGE LICENSE for the governing permissions + * and limitations under the License. + */ + +/* Includes */ +#include "usbh_enum.h" +#include "usbh_stdReq.h" +#include "usbh_core.h" +#include +#include + +/** @addtogroup APM32_USB_Library + @{ + */ + +/** @addtogroup USBH_Core + @{ + */ + +/** @defgroup USBH_Core_Functions Functions + @{ + */ + +static USBH_STA_T USBH_ENUM_IdleHandler(USBH_INFO_T* usbInfo); +static USBH_STA_T USBH_ENUM_GetDevDescHandler(USBH_INFO_T* usbInfo); +static USBH_STA_T USBH_ENUM_SetAddressHandler(USBH_INFO_T* usbInfo); +static USBH_STA_T USBH_ENUM_GetConfigurationDescHandler(USBH_INFO_T* usbInfo); +static USBH_STA_T USBH_ENUM_GetFullConfigurationDescHandler(USBH_INFO_T* usbInfo); +static USBH_STA_T USBH_ENUM_GetMFCStringHandler(USBH_INFO_T* usbInfo); +static USBH_STA_T USBH_ENUM_GetProductStringHandler(USBH_INFO_T* usbInfo); +static USBH_STA_T USBH_ENUM_GetSerialNumStringHandler(USBH_INFO_T* usbInfo); + +/**@} end of group USBH_Core_Functions */ + +/** @defgroup USBH_Core_Structures Structures + @{ + */ + +/* USB host enum state handler function */ +USBH_EnumHandler_T USBH_EnumHandler[] = +{ + USBH_ENUM_IdleHandler, + USBH_ENUM_GetDevDescHandler, + USBH_ENUM_SetAddressHandler, + USBH_ENUM_GetConfigurationDescHandler, + USBH_ENUM_GetFullConfigurationDescHandler, + USBH_ENUM_GetMFCStringHandler, + USBH_ENUM_GetProductStringHandler, + USBH_ENUM_GetSerialNumStringHandler, +}; + +/**@} end of group USBH_Core_Structures*/ + +/** @defgroup USBH_Core_Functions Functions + @{ + */ + +/*! + * @brief Handle enum idle stage and get 8 bytes device descriptor + * + * @param usbInfo : usb handler information + * + * @retval usb host status + */ +static USBH_STA_T USBH_ENUM_IdleHandler(USBH_INFO_T* usbInfo) +{ + USBH_STA_T usbEnumStatus = USBH_BUSY; + uint8_t usbStatus = USBH_BUSY; + + usbStatus = USBH_GetDevDesc(usbInfo, 0x08); + + switch (usbStatus) + { + case USBH_OK: + usbInfo->ctrl.channelSize = usbInfo->devInfo.desc.device.bMaxPacketSize; + + /* Open and config in channel */ + USBH_OpenChannelCallback(usbInfo, usbInfo->ctrl.channelInNum, + 0x80, usbInfo->devInfo.address, + usbInfo->devInfo.speed, EP_TYPE_CONTROL, + usbInfo->ctrl.channelSize); + + /* Open and config out channel */ + USBH_OpenChannelCallback(usbInfo, usbInfo->ctrl.channelOutNum, + 0x00, usbInfo->devInfo.address, + usbInfo->devInfo.speed, EP_TYPE_CONTROL, + usbInfo->ctrl.channelSize); + + usbInfo->hostEnumState = USBH_ENUM_GET_DEV_DESC; + break; + + case USBH_ERR_NOT_SUP: + USBH_USR_LOG("CTRL error: get device descriptor"); + usbInfo->devInfo.enumCnt++; + + if (usbInfo->devInfo.enumCnt <= 3) + { + /* Free control channel */ + USBH_CH_FreeChannel(usbInfo, usbInfo->ctrl.channelInNum); + USBH_CH_FreeChannel(usbInfo, usbInfo->ctrl.channelOutNum); + + /* Reset USB host state machine */ + usbInfo->hostState = USBH_HOST_IDLE; + } + else + { + USBH_USR_LOG("CTRL error: device no response, please unplug the device"); + usbInfo->hostState = USBH_HOST_ABORT; + } + break; + + default: + break; + } + + return usbEnumStatus; +} + +/*! + * @brief Handle enum get full bytes device descriptor stage + * + * @param usbInfo : usb handler information + * + * @retval usb host status + */ +static USBH_STA_T USBH_ENUM_GetDevDescHandler(USBH_INFO_T* usbInfo) +{ + USBH_STA_T usbEnumStatus = USBH_BUSY; + uint8_t usbStatus = USBH_BUSY; + + USBH_USR_Debug("USBH_ENUM_GetDevDescHandler"); + + usbStatus = USBH_GetDevDesc(usbInfo, STD_DEV_DESC_SIZE); + + switch (usbStatus) + { + case USBH_OK: + USBH_USR_LOG("PID: 0x%04X", usbInfo->devInfo.desc.device.idProduct[0] | \ + usbInfo->devInfo.desc.device.idProduct[1] << 8); + + USBH_USR_LOG("VID: 0x%04X", usbInfo->devInfo.desc.device.idVendor[0] | \ + usbInfo->devInfo.desc.device.idVendor[1] << 8); + USBH_USR_LOG("Endpoint 0 max packet size if %d", usbInfo->devInfo.desc.device.bMaxPacketSize); + + + usbInfo->hostEnumState = USBH_ENUM_SET_ADDR; + break; + + case USBH_ERR_NOT_SUP: + USBH_USR_LOG("CTRL error: get full device descriptor"); + usbInfo->devInfo.enumCnt++; + + if (usbInfo->devInfo.enumCnt <= 3) + { + /* Free control channel */ + USBH_CH_FreeChannel(usbInfo, usbInfo->ctrl.channelInNum); + USBH_CH_FreeChannel(usbInfo, usbInfo->ctrl.channelOutNum); + + /* Reset USB host state machine */ + usbInfo->hostState = USBH_HOST_IDLE; + usbInfo->hostEnumState = USBH_ENUM_IDLE; + } + else + { + USBH_USR_LOG("CTRL error: device no response, please unplug the device"); + usbInfo->hostState = USBH_HOST_ABORT; + } + break; + + default: + break; + } + + return usbEnumStatus; +} + +/*! + * @brief Handle enum set address stage + * + * @param usbInfo : usb handler information + * + * @retval usb host status + */ +static USBH_STA_T USBH_ENUM_SetAddressHandler(USBH_INFO_T* usbInfo) +{ + USBH_STA_T usbEnumStatus = USBH_BUSY; + uint8_t usbStatus = USBH_BUSY; + + USBH_USR_Debug("USBH_ENUM_SetAddressHandler"); + + usbStatus = USBH_SetAddr(usbInfo, USBH_DEVICE_CONFIGURED_ADDRESS); + + switch (usbStatus) + { + case USBH_OK: + /* Update device address */ + usbInfo->devInfo.address = USBH_DEVICE_CONFIGURED_ADDRESS; + USBH_USR_LOG("USB device address: %d", usbInfo->devInfo.address); + + USBH_Delay(5); + + /* Modify channels to new device address */ + /* Open and config out channel */ + USBH_OpenChannelCallback(usbInfo, usbInfo->ctrl.channelOutNum, + 0x00, usbInfo->devInfo.address, + usbInfo->devInfo.speed, EP_TYPE_CONTROL, + usbInfo->ctrl.channelSize); + + /* Open and config in channel */ + USBH_OpenChannelCallback(usbInfo, usbInfo->ctrl.channelInNum, + 0x80, usbInfo->devInfo.address, + usbInfo->devInfo.speed, EP_TYPE_CONTROL, + usbInfo->ctrl.channelSize); + + usbInfo->hostEnumState = USBH_ENUM_GET_CFG_DESC; + break; + + case USBH_ERR_NOT_SUP: + USBH_USR_LOG("CTRL error: set device address"); + USBH_USR_LOG("CTRL error: device no response, please unplug the device"); + usbInfo->hostState = USBH_HOST_ABORT; + usbInfo->hostEnumState = USBH_ENUM_IDLE; + break; + + default: + break; + } + + return usbEnumStatus; +} + +/*! + * @brief Handle enum get configuration descriptor stage + * + * @param usbInfo : usb handler information + * + * @retval usb host status + */ +static USBH_STA_T USBH_ENUM_GetConfigurationDescHandler(USBH_INFO_T* usbInfo) +{ + USBH_STA_T usbEnumStatus = USBH_BUSY; + uint8_t usbStatus = USBH_BUSY; + + USBH_USR_Debug("USBH_ENUM_GetConfigurationDescHandler"); + + usbStatus = USBH_GetCfgDesc(usbInfo, STD_CFG_DESC_SIZE); + + switch (usbStatus) + { + case USBH_OK: + usbInfo->hostEnumState = USBH_ENUM_GET_FULL_CFG_DESC; + break; + + case USBH_ERR_NOT_SUP: + USBH_USR_LOG("CTRL error: get configuration descriptor"); + + usbInfo->devInfo.enumCnt++; + + if (usbInfo->devInfo.enumCnt <= 3) + { + /* Free control channel */ + USBH_CH_FreeChannel(usbInfo, usbInfo->ctrl.channelInNum); + USBH_CH_FreeChannel(usbInfo, usbInfo->ctrl.channelOutNum); + + /* Reset USB host state machine */ + usbInfo->hostState = USBH_HOST_IDLE; + usbInfo->hostEnumState = USBH_ENUM_IDLE; + } + else + { + USBH_USR_LOG("CTRL error: device no response, please unplug the device"); + usbInfo->hostState = USBH_HOST_ABORT; + } + break; + + default: + break; + } + + return usbEnumStatus; +} + +/*! + * @brief Handle enum get full configuration descriptor stage + * + * @param usbInfo : usb handler information + * + * @retval usb host status + */ +static USBH_STA_T USBH_ENUM_GetFullConfigurationDescHandler(USBH_INFO_T* usbInfo) +{ + USBH_STA_T usbEnumStatus = USBH_BUSY; + uint8_t usbStatus = USBH_BUSY; + uint16_t cfgDescTotalTemp; + + USBH_USR_Debug("USBH_ENUM_GetFullConfigurationDescHandler"); + + cfgDescTotalTemp = usbInfo->devInfo.desc.configuration.wTotalLength[0] | \ + usbInfo->devInfo.desc.configuration.wTotalLength[1] << 8; + + usbStatus = USBH_GetCfgDesc(usbInfo, cfgDescTotalTemp); + + switch (usbStatus) + { + case USBH_OK: + usbInfo->hostEnumState = USBH_ENUM_GET_MFC_STRING_DESC; + break; + + case USBH_ERR_NOT_SUP: + USBH_USR_LOG("CTRL error: get full configuration descriptor"); + + usbInfo->devInfo.enumCnt++; + + if (usbInfo->devInfo.enumCnt <= 3) + { + /* Free control channel */ + USBH_CH_FreeChannel(usbInfo, usbInfo->ctrl.channelInNum); + USBH_CH_FreeChannel(usbInfo, usbInfo->ctrl.channelOutNum); + + /* Reset USB host state machine */ + usbInfo->hostState = USBH_HOST_IDLE; + usbInfo->hostEnumState = USBH_ENUM_IDLE; + } + else + { + USBH_USR_LOG("CTRL error: device no response, please unplug the device"); + usbInfo->hostState = USBH_HOST_ABORT; + } + break; + + default: + break; + } + + return usbEnumStatus; +} + +/*! + * @brief Handle enum get manufacturer string stage + * + * @param usbInfo : usb handler information + * + * @retval usb host status + */ +static USBH_STA_T USBH_ENUM_GetMFCStringHandler(USBH_INFO_T* usbInfo) +{ + USBH_STA_T usbEnumStatus = USBH_BUSY; + uint8_t usbStatus = USBH_BUSY; + + USBH_USR_Debug("USBH_ENUM_GetMFCStringHandler"); + + if (usbInfo->devInfo.desc.device.iManufacturer == 0) + { + USBH_USR_LOG("Manufacturer is N/A"); + + usbInfo->hostEnumState = USBH_ENUM_GET_PRODUCT_STRING_DESC; + } + else + { + usbStatus = USBH_GetStringDesc(usbInfo, usbInfo->devInfo.desc.device.iManufacturer, \ + usbInfo->devInfo.desc.stringBuf, 0xFF); + + switch (usbStatus) + { + case USBH_OK: + USBH_USR_LOG("Manufacturer: %s", (char*)usbInfo->devInfo.desc.stringBuf); + usbInfo->hostEnumState = USBH_ENUM_GET_PRODUCT_STRING_DESC; + break; + + case USBH_ERR_NOT_SUP: + USBH_USR_LOG("Manufacturer is N/A"); + usbInfo->hostEnumState = USBH_ENUM_GET_PRODUCT_STRING_DESC; + break; + + default: + break; + } + } + + return usbEnumStatus; +} + +/*! + * @brief Handle enum get product string stage + * + * @param usbInfo : usb handler information + * + * @retval usb host status + */ +static USBH_STA_T USBH_ENUM_GetProductStringHandler(USBH_INFO_T* usbInfo) +{ + USBH_STA_T usbEnumStatus = USBH_BUSY; + uint8_t usbStatus = USBH_BUSY; + + USBH_USR_Debug("USBH_ENUM_GetProductStringHandler"); + + if (usbInfo->devInfo.desc.device.iProduct == 0) + { + USBH_USR_LOG("Product is N/A"); + + usbInfo->hostEnumState = USBH_ENUM_GET_SERIALNUM_STRING_DESC; + } + else + { + usbStatus = USBH_GetStringDesc(usbInfo, usbInfo->devInfo.desc.device.iProduct, \ + usbInfo->devInfo.desc.stringBuf, 0xFF); + + switch (usbStatus) + { + case USBH_OK: + USBH_USR_LOG("Product: %s", (char*)usbInfo->devInfo.desc.stringBuf); + usbInfo->hostEnumState = USBH_ENUM_GET_SERIALNUM_STRING_DESC; + break; + + case USBH_ERR_NOT_SUP: + USBH_USR_LOG("Product is N/A"); + usbInfo->hostEnumState = USBH_ENUM_GET_SERIALNUM_STRING_DESC; + break; + + default: + break; + } + } + + return usbEnumStatus; +} + +/*! + * @brief Handle enum get serial number string stage + * + * @param usbInfo : usb handler information + * + * @retval usb host status + */ +static USBH_STA_T USBH_ENUM_GetSerialNumStringHandler(USBH_INFO_T* usbInfo) +{ + USBH_STA_T usbEnumStatus = USBH_BUSY; + uint8_t usbStatus = USBH_BUSY; + + USBH_USR_Debug("USBH_ENUM_GetSerialNumStringHandler"); + + if (usbInfo->devInfo.desc.device.iSerialNumber == 0) + { + USBH_USR_LOG("SerialNumber is N/A"); + usbEnumStatus = USBH_OK; + } + else + { + usbStatus = USBH_GetStringDesc(usbInfo, usbInfo->devInfo.desc.device.iSerialNumber, \ + usbInfo->devInfo.desc.stringBuf, 0xFF); + + switch (usbStatus) + { + case USBH_OK: + USBH_USR_LOG("SerialNumber: %s", (char*)usbInfo->devInfo.desc.stringBuf); + usbEnumStatus = USBH_OK; + break; + + case USBH_ERR_NOT_SUP: + USBH_USR_LOG("SerialNumber is N/A"); + usbEnumStatus = USBH_OK; + break; + + default: + break; + } + } + + return usbEnumStatus; +} + +/**@} end of group USBH_Core_Functions */ +/**@} end of group USBH_Core */ +/**@} end of group APM32_USB_Library */ diff --git a/lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Core/Src/usbh_stdReq.c b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Core/Src/usbh_stdReq.c new file mode 100644 index 0000000000..9226715be1 --- /dev/null +++ b/lib/main/APM32F4/Middlewares/APM32_USB_Library/Host/Core/Src/usbh_stdReq.c @@ -0,0 +1,723 @@ +/*! + * @file usbh_stdReq.c + * + * @brief USB standard request process + * + * @version V1.0.0 + * + * @date 2023-01-16 + * + * @attention + * + * Copyright (C) 2023 Geehy Semiconductor + * + * You may not use this file except in compliance with the + * GEEHY COPYRIGHT NOTICE (GEEHY SOFTWARE PACKAGE LICENSE). + * + * The program is only for reference, which is distributed in the hope + * that it will be useful and instructional for customers to develop + * their software. Unless required by applicable law or agreed to in + * writing, the program is distributed on an "AS IS" BASIS, WITHOUT + * ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied. + * See the GEEHY SOFTWARE PACKAGE LICENSE for the governing permissions + * and limitations under the License. + */ + +/* Includes */ +#include "usbh_stdReq.h" +#include "usbh_dataXfer.h" +#include "usbh_core.h" + +/** @addtogroup APM32_USB_Library + @{ + */ + +/** @addtogroup USBH_Core + @{ + */ + +/** @defgroup USBH_Core_Functions Functions + @{ + */ + +/*! + * @brief Parse string descriptor + * + * @param stringDesc : string descriptor + * + * @param buffer : source recevice data + * + * @param length : device descriptor length + * + * @retval usb host status + */ +USBH_STA_T USBH_StringDescParse(uint8_t* stringDesc, uint8_t* buffer, uint16_t length) +{ + USBH_STA_T usbStatus = USBH_OK; + + uint8_t descType; + uint16_t stringLen; + uint16_t i; + + descType = *(uint8_t*)(buffer + 1); + + if (descType == USBH_DESC_STRING) + { + stringLen = *(uint8_t*)(buffer + 0) - 2; + if (stringLen > length) + { + stringLen = length; + } + + buffer += 2; + + /* only copy UNICODE bsting */ + for (i = 0; i < stringLen; i += 2) + { + *stringDesc = buffer[i]; + stringDesc++; + } + } + + return usbStatus; +} + +/*! + * @brief Copy data from source buffer to destination buffer. + * + * @param desBuffer: point to destination buffer + * + * @param srcBuf : point to source buffer + * + * @param len: copy length + * + * @retval None + */ +static void USBH_CopyBuffer(uint8_t* desBuffer, uint8_t* srcBuf, uint32_t len) +{ + while (len--) + { + desBuffer[len] = srcBuf[len]; + } +} + +/*! + * @brief Parse configuration descriptor + * + * @param cfgDesc : configuration descriptor + * + * @param interface : interface of intDesc and epDesc + * + * @param buffer : source recevice data + * + * @param length : device descriptor length + * + * @retval usb host status + */ +USBH_STA_T USBH_CfgDescParse(USBH_CFG_DESC_T* cfgDesc, USBH_INTERFACE_T* interface, uint8_t* buffer, uint16_t length) +{ + USBH_STA_T usbStatus = USBH_OK; + uint16_t totalLenTemp = 0; + uint16_t parseIndex = 0; + uint8_t itfIndex = 0; + uint8_t epIndex = 0; + uint8_t subLen = 0; + + cfgDesc->bLength = *(uint8_t*)(buffer + 0); + cfgDesc->bDescriptorType = *(uint8_t*)(buffer + 1); + + totalLenTemp = *(uint8_t*)(buffer + 2) | (*(uint8_t*)(buffer + 3) << 8); + totalLenTemp = ((totalLenTemp) < (CFG_DESC_MAX_LEN) ? (totalLenTemp) : (CFG_DESC_MAX_LEN)); + + cfgDesc->wTotalLength[0] = totalLenTemp & 0xFF; + cfgDesc->wTotalLength[1] = (totalLenTemp >> 8) & 0xFF; + cfgDesc->bNumInterfaces = *(uint8_t*)(buffer + 4); + cfgDesc->bConfigurationValue = *(uint8_t*)(buffer + 5); + cfgDesc->iConfiguration = *(uint8_t*)(buffer + 6); + cfgDesc->bmAttributes = *(uint8_t*)(buffer + 7); + cfgDesc->bMaxPower = *(uint8_t*)(buffer + 8); + + if (cfgDesc->bLength != STD_CFG_DESC_SIZE) + { + cfgDesc->bLength = STD_CFG_DESC_SIZE; + } + + /* USB configuration descriptor lenght > STD_CFG_DESC_SIZE */ + if (length > STD_CFG_DESC_SIZE) + { + parseIndex = STD_CFG_DESC_SIZE; + + while (totalLenTemp > parseIndex) + { + /* Get descriptor length at first byte */ + subLen = buffer[parseIndex]; + + /* Check the descriptor Type at second byte */ + switch (buffer[parseIndex + 1]) + { + case USBH_DESC_INTERFACE: + if (itfIndex < INTERFACE_DESC_MAX_NUM) + { + /* Move data from parse Buffer to Interface descriptor */ + USBH_CopyBuffer((uint8_t*)&interface[itfIndex].interfaceDesc, + &buffer[parseIndex], + STD_INTERFACE_DESC_SIZE); + + itfIndex++; + epIndex = 0; + } + break; + + case USBH_DESC_ENDPOINT: + if ((itfIndex > 0) && (epIndex < ENDPOINT_DESC_MAX_NUM)) + { + /* Move data from parse Buffer to Endpoint descriptor */ + USBH_CopyBuffer((uint8_t*)&interface[itfIndex - 1].endpointDesc[epIndex], + &buffer[parseIndex], + STD_INTERFACE_DESC_SIZE); + + epIndex++; + } + break; + + default: + break; + } + + parseIndex += subLen; + + /* To avoid some useless data left */ + if ((totalLenTemp - parseIndex) < STD_EP_DESC_SIZE) + { + break; + } + } + } + + return usbStatus; +} + +/*! + * @brief Parse device descriptor + * + * @param devDesc : device descriptor + * + * @param buffer : source recevice data + * + * @param length : device descriptor length + * + * @retval usb host status + */ +USBH_STA_T USBH_DevDescParse(USBH_DEV_DESC_T* devDesc, uint8_t* buffer, uint16_t length) +{ + USBH_STA_T usbStatus = USBH_OK; + + devDesc->bLength = *(uint8_t*)(buffer + 0); + devDesc->bDescriptorType = *(uint8_t*)(buffer + 1); + devDesc->bcdUSB[0] = *(uint8_t*)(buffer + 2); + devDesc->bcdUSB[1] = *(uint8_t*)(buffer + 3); + devDesc->bDeviceClass = *(uint8_t*)(buffer + 4); + devDesc->bDeviceSubClass = *(uint8_t*)(buffer + 5); + devDesc->bDeviceProtocol = *(uint8_t*)(buffer + 6); + devDesc->bMaxPacketSize = *(uint8_t*)(buffer + 7); + + switch (devDesc->bMaxPacketSize) + { + case 8: + case 16: + case 32: + case 64: + devDesc->bMaxPacketSize = devDesc->bMaxPacketSize; + break; + + default: + devDesc->bMaxPacketSize = 64; + break; + } + + if (length > 8) + { + devDesc->idVendor[0] = *(uint8_t*)(buffer + 8); + devDesc->idVendor[1] = *(uint8_t*)(buffer + 9); + devDesc->idProduct[0] = *(uint8_t*)(buffer + 10); + devDesc->idProduct[1] = *(uint8_t*)(buffer + 11); + devDesc->bcdDevice[0] = *(uint8_t*)(buffer + 12); + devDesc->bcdDevice[1] = *(uint8_t*)(buffer + 13); + devDesc->iManufacturer = *(uint8_t*)(buffer + 14); + devDesc->iProduct = *(uint8_t*)(buffer + 15); + devDesc->iSerialNumber = *(uint8_t*)(buffer + 16); + devDesc->bNumConfigurations = *(uint8_t*)(buffer + 17); + } + + return usbStatus; +} + +/*! + * @brief Handle control setup transfer. + * + * @param usbInfo : usb handler information + * + * @param buffer : control transfer buffer + * + * @param length : length of response + * + * @retval usb host status + */ +USBH_STA_T USBH_REQ_CtrlXferHandler(USBH_INFO_T* usbInfo, uint8_t* buffer, uint16_t length) +{ + USBH_STA_T usbStatus = USBH_OK; + + switch (usbInfo->xferState) + { + case USBH_XFER_START: + USBH_USR_Debug("USBH_XFER_START"); + usbInfo->ctrl.buffer = buffer; + usbInfo->ctrl.length = length; + usbInfo->ctrl.state = USBH_CTRL_SETUP; + usbInfo->xferState = USBH_XFER_WAITING; + usbStatus = USBH_BUSY; + break; + + case USBH_XFER_WAITING: + USBH_USR_Debug("USBH_XFER_WAITING"); + usbStatus = USBH_CtrlStateHandler[usbInfo->ctrl.state](usbInfo); + + if ((usbStatus == USBH_OK) || (usbStatus == USBH_ERR_NOT_SUP)) + { + usbInfo->xferState = USBH_XFER_START; + usbInfo->ctrl.state = USBH_CTRL_IDLE; + } + else if (usbStatus == USBH_FAIL) + { + usbInfo->xferState = USBH_XFER_START; + } + else + { + + } + break; + } + + return usbStatus; +} + +/*! + * @brief USB host set device feature request + * + * @param usbInfo : usb handler information + * + * @param reqType : Select request type. + * + * @param feature : feature value + * + * @retval usb host status + */ +USBH_STA_T USBH_REQ_SetFeature(USBH_INFO_T* usbInfo, uint8_t reqType, \ + uint8_t feature) +{ + USBH_STA_T usbStatus = USBH_OK; + + switch (usbInfo->xferState) + { + case USBH_XFER_START: + usbInfo->ctrl.reqData.DATA_FIELD.bmRequestType.REQ_TYPE_B.dir = ((reqType & 0x80) >> 7); + usbInfo->ctrl.reqData.DATA_FIELD.bmRequestType.REQ_TYPE_B.type = ((reqType & 0x60) >> 5); + usbInfo->ctrl.reqData.DATA_FIELD.bmRequestType.REQ_TYPE_B.recipient = (reqType & 0x1F); + + usbInfo->ctrl.reqData.DATA_FIELD.bRequest = USBH_STD_SET_FEATURE; + + usbInfo->ctrl.reqData.DATA_FIELD.wValue[0] = feature; + usbInfo->ctrl.reqData.DATA_FIELD.wValue[1] = 0; + + usbInfo->ctrl.reqData.DATA_FIELD.wIndex[0] = 0; + usbInfo->ctrl.reqData.DATA_FIELD.wIndex[1] = 0; + + usbInfo->ctrl.reqData.DATA_FIELD.wLength[0] = 0; + usbInfo->ctrl.reqData.DATA_FIELD.wLength[1] = 0; + break; + + default: + break; + } + + usbStatus = USBH_REQ_CtrlXferHandler(usbInfo, NULL, 0); + + return usbStatus; +} + +/*! + * @brief USB host clear device feature request + * + * @param usbInfo : usb handler information + * + * @param reqType : Select request type. + * + * @param feature : feature value + * + * @retval usb host status + */ +USBH_STA_T USBH_REQ_ClearFeature(USBH_INFO_T* usbInfo, uint8_t reqType, \ + uint8_t epNum) +{ + USBH_STA_T usbStatus = USBH_OK; + + switch (usbInfo->xferState) + { + case USBH_XFER_START: + usbInfo->ctrl.reqData.DATA_FIELD.bmRequestType.REQ_TYPE_B.dir = ((reqType & 0x80) >> 7); + usbInfo->ctrl.reqData.DATA_FIELD.bmRequestType.REQ_TYPE_B.type = ((reqType & 0x60) >> 5); + usbInfo->ctrl.reqData.DATA_FIELD.bmRequestType.REQ_TYPE_B.recipient = (reqType & 0x1F); + + usbInfo->ctrl.reqData.DATA_FIELD.bRequest = USBH_STD_CLEAR_FEATURE; + + usbInfo->ctrl.reqData.DATA_FIELD.wValue[0] = USBH_FEATURE_SELECTOR_ENDPOINT_HALT; + usbInfo->ctrl.reqData.DATA_FIELD.wValue[1] = 0; + + usbInfo->ctrl.reqData.DATA_FIELD.wIndex[0] = epNum; + usbInfo->ctrl.reqData.DATA_FIELD.wIndex[1] = 0; + + usbInfo->ctrl.reqData.DATA_FIELD.wLength[0] = 0; + usbInfo->ctrl.reqData.DATA_FIELD.wLength[1] = 0; + break; + + default: + break; + } + + usbStatus = USBH_REQ_CtrlXferHandler(usbInfo, NULL, 0); + + return usbStatus; +} + +/*! + * @brief USB host set device configuration request + * + * @param usbInfo : usb handler information + * + * @param reqType : Select request type. + * + * @param configuration : configuration value + * + * @retval usb host status + */ +USBH_STA_T USBH_REQ_SetConfiguration(USBH_INFO_T* usbInfo, uint8_t reqType, \ + uint16_t configuration) +{ + USBH_STA_T usbStatus = USBH_OK; + + switch (usbInfo->xferState) + { + case USBH_XFER_START: + usbInfo->ctrl.reqData.DATA_FIELD.bmRequestType.REQ_TYPE_B.dir = ((reqType & 0x80) >> 7); + usbInfo->ctrl.reqData.DATA_FIELD.bmRequestType.REQ_TYPE_B.type = ((reqType & 0x60) >> 5); + usbInfo->ctrl.reqData.DATA_FIELD.bmRequestType.REQ_TYPE_B.recipient = (reqType & 0x1F); + + usbInfo->ctrl.reqData.DATA_FIELD.bRequest = USBH_STD_SET_CONFIGURATION; + + usbInfo->ctrl.reqData.DATA_FIELD.wValue[0] = configuration; + usbInfo->ctrl.reqData.DATA_FIELD.wValue[1] = 0; + + usbInfo->ctrl.reqData.DATA_FIELD.wIndex[0] = 0; + usbInfo->ctrl.reqData.DATA_FIELD.wIndex[1] = 0; + + usbInfo->ctrl.reqData.DATA_FIELD.wLength[0] = 0; + usbInfo->ctrl.reqData.DATA_FIELD.wLength[1] = 0; + break; + + default: + break; + } + + usbStatus = USBH_REQ_CtrlXferHandler(usbInfo, NULL, 0); + + return usbStatus; +} + +/*! + * @brief USB host set device address request + * + * @param usbInfo : usb handler information + * + * @param reqType : Select request type. + * + * @param addr : device address + * + * @retval usb host status + */ +USBH_STA_T USBH_REQ_SetAddr(USBH_INFO_T* usbInfo, uint8_t reqType, \ + uint8_t addr) +{ + USBH_STA_T usbStatus = USBH_OK; + + switch (usbInfo->xferState) + { + case USBH_XFER_START: + usbInfo->ctrl.reqData.DATA_FIELD.bmRequestType.REQ_TYPE_B.dir = ((reqType & 0x80) >> 7); + usbInfo->ctrl.reqData.DATA_FIELD.bmRequestType.REQ_TYPE_B.type = ((reqType & 0x60) >> 5); + usbInfo->ctrl.reqData.DATA_FIELD.bmRequestType.REQ_TYPE_B.recipient = (reqType & 0x1F); + + usbInfo->ctrl.reqData.DATA_FIELD.bRequest = USBH_STD_SET_ADDRESS; + + usbInfo->ctrl.reqData.DATA_FIELD.wValue[0] = addr; + usbInfo->ctrl.reqData.DATA_FIELD.wValue[1] = 0; + + usbInfo->ctrl.reqData.DATA_FIELD.wIndex[0] = 0; + usbInfo->ctrl.reqData.DATA_FIELD.wIndex[1] = 0; + + usbInfo->ctrl.reqData.DATA_FIELD.wLength[0] = 0; + usbInfo->ctrl.reqData.DATA_FIELD.wLength[1] = 0; + break; + + default: + break; + } + + usbStatus = USBH_REQ_CtrlXferHandler(usbInfo, NULL, 0); + + return usbStatus; +} + +/*! + * @brief Config standard get descriptor request + * + * @param usbInfo : usb handler information + * + * @param reqType : Select request type + * + * @param desType : Specifies descriptor type + * This value can be one of the following values: + * @arg USBH_DESC_DEVICE + * @arg USBH_DESC_CONFIGURATION + * @arg USBH_DESC_STRING + * @arg USBH_DESC_INTERFACE + * @arg USBH_DESC_ENDPOINT + * @arg USBH_DESC_DEVICE_QUALIFIER + * @arg USBH_DESC_OTHER_SPEED + * @arg USBH_INTERFACE_POWER + * + * @param buffer : buffer to store descriptor + * + * @param length : Specifies len of request + * + * @retval usb host status + */ +USBH_STA_T USBH_REQ_GetDescriptor(USBH_INFO_T* usbInfo, uint8_t reqType, \ + uint16_t desType, uint8_t* buffer, uint16_t length) +{ + USBH_STA_T usbStatus = USBH_OK; + + switch (usbInfo->xferState) + { + case USBH_XFER_START: + usbInfo->ctrl.reqData.DATA_FIELD.bmRequestType.REQ_TYPE_B.dir = ((reqType & 0x80) >> 7); + usbInfo->ctrl.reqData.DATA_FIELD.bmRequestType.REQ_TYPE_B.type = ((reqType & 0x60) >> 5); + usbInfo->ctrl.reqData.DATA_FIELD.bmRequestType.REQ_TYPE_B.recipient = (reqType & 0x1F); + + usbInfo->ctrl.reqData.DATA_FIELD.bRequest = USBH_STD_GET_DESCRIPTOR; + + usbInfo->ctrl.reqData.DATA_FIELD.wValue[0] = (desType >> 8) & 0xFF; + usbInfo->ctrl.reqData.DATA_FIELD.wValue[1] = desType & 0xFF; + + if ((desType & 0xFF) == USBH_DESC_STRING) + { + usbInfo->ctrl.reqData.DATA_FIELD.wIndex[0] = USBH_LANG_ID & 0xFF; + usbInfo->ctrl.reqData.DATA_FIELD.wIndex[1] = USBH_LANG_ID >> 8; + } + else + { + usbInfo->ctrl.reqData.DATA_FIELD.wIndex[0] = 0; + usbInfo->ctrl.reqData.DATA_FIELD.wIndex[1] = 0; + } + + usbInfo->ctrl.reqData.DATA_FIELD.wLength[0] = length & 0xFF; + usbInfo->ctrl.reqData.DATA_FIELD.wLength[1] = length >> 8; + break; + + default: + break; + } + + usbStatus = USBH_REQ_CtrlXferHandler(usbInfo, buffer, length); + + return usbStatus; +} + +/*! + * @brief USB host set feature + * + * @param usbInfo : usb handler information + * + * @param feature : value of feature + * + * @retval usb host status + */ +USBH_STA_T USBH_SetFeature(USBH_INFO_T* usbInfo, uint8_t feature) +{ + USBH_STA_T usbStatus = USBH_OK; + + usbStatus = USBH_REQ_SetFeature(usbInfo, ((USBH_REQ_DIR_OUT << 7) | \ + (USBH_REQ_TYPE_STANDARD << 5) | \ + (USBH_RECIPIENT_DEVICE)), + feature); + + return usbStatus; +} + +/*! + * @brief USB host clear feature + * + * @param usbInfo : usb handler information + * + * @param epNum : number of endpoint + * + * @retval usb host status + */ +USBH_STA_T USBH_ClearFeature(USBH_INFO_T* usbInfo, uint8_t epNum) +{ + USBH_STA_T usbStatus = USBH_OK; + + usbStatus = USBH_REQ_ClearFeature(usbInfo, ((USBH_REQ_DIR_OUT << 7) | \ + (USBH_REQ_TYPE_STANDARD << 5) | \ + (USBH_RECIPIENT_ENDPOINT)), + epNum); + + return usbStatus; +} + +/*! + * @brief USB host set configuration + * + * @param usbInfo : usb handler information + * + * @param configuration : value of configuration + * + * @retval usb host status + */ +USBH_STA_T USBH_SetConfiguration(USBH_INFO_T* usbInfo, uint16_t configuration) +{ + USBH_STA_T usbStatus = USBH_OK; + + usbStatus = USBH_REQ_SetConfiguration(usbInfo, ((USBH_REQ_DIR_OUT << 7) | \ + (USBH_REQ_TYPE_STANDARD << 5) | \ + (USBH_RECIPIENT_DEVICE)), + configuration); + + return usbStatus; +} + +/*! + * @brief USB host get configuration description + * + * @param usbInfo : usb handler information + * + * @param desLength : length of description + * + * @retval usb host status + */ +USBH_STA_T USBH_GetCfgDesc(USBH_INFO_T* usbInfo, uint16_t desLength) +{ + USBH_STA_T usbStatus = USBH_OK; + + usbStatus = USBH_REQ_GetDescriptor(usbInfo, ((USBH_REQ_DIR_IN << 7) | \ + (USBH_REQ_TYPE_STANDARD << 5) | \ + (USBH_RECIPIENT_DEVICE)), \ + USBH_DESC_CONFIGURATION, + usbInfo->devInfo.desc.cfgDescBuf, + desLength); + if (usbStatus == USBH_OK) + { + /* Store received data */ + USBH_CfgDescParse(&usbInfo->devInfo.desc.configuration, \ + usbInfo->devInfo.desc.interface, + usbInfo->devInfo.desc.cfgDescBuf, desLength); + } + + return usbStatus; +} + +/*! + * @brief USB host get string description + * + * @param usbInfo : usb handler information + * + * @param stringIndex : string index + * + * @param buffer : buffer to store descriptor + * + * @param desLength : length of description + * + * @retval usb host status + */ +USBH_STA_T USBH_GetStringDesc(USBH_INFO_T* usbInfo, uint8_t stringIndex, uint8_t* buffer, uint16_t desLength) +{ + USBH_STA_T usbStatus = USBH_OK; + + usbStatus = USBH_REQ_GetDescriptor(usbInfo, ((USBH_REQ_DIR_IN << 7) | \ + (USBH_REQ_TYPE_STANDARD << 5) | \ + (USBH_RECIPIENT_DEVICE)), \ + (USBH_DESC_STRING | stringIndex << 8), + usbInfo->devInfo.desc.stringBuf, + desLength); + + if (usbStatus == USBH_OK) + { + /* Store received data */ + USBH_StringDescParse(usbInfo->devInfo.desc.stringBuf, buffer, desLength); + } + + return usbStatus; +} + +/*! + * @brief USB host set device address + * + * @param usbInfo : usb handler information + * + * @param address : device address + * + * @retval usb host status + */ +USBH_STA_T USBH_SetAddr(USBH_INFO_T* usbInfo, uint8_t address) +{ + USBH_STA_T usbStatus = USBH_OK; + + usbStatus = USBH_REQ_SetAddr(usbInfo, ((USBH_REQ_DIR_OUT << 7) | \ + (USBH_REQ_TYPE_STANDARD << 5) | \ + (USBH_RECIPIENT_DEVICE)), + address); + + return usbStatus; +} + +/*! + * @brief USB host get device description + * + * @param usbInfo : usb handler information + * + * @param desLength : length of description + * + * @retval usb host status + */ +USBH_STA_T USBH_GetDevDesc(USBH_INFO_T* usbInfo, uint8_t desLength) +{ + USBH_STA_T usbStatus = USBH_OK; + + usbStatus = USBH_REQ_GetDescriptor(usbInfo, ((USBH_REQ_DIR_IN << 7) | \ + (USBH_REQ_TYPE_STANDARD << 5) | \ + (USBH_RECIPIENT_DEVICE)), \ + USBH_DESC_DEVICE, + usbInfo->devInfo.data, + desLength); + + if (usbStatus == USBH_OK) + { + /* Store received data */ + USBH_DevDescParse(&usbInfo->devInfo.desc.device, usbInfo->devInfo.data, desLength); + } + + return usbStatus; +} + +/**@} end of group USBH_Core_Functions */ +/**@} end of group USBH_Core */ +/**@} end of group APM32_USB_Library */